ConstantFold.cpp revision 92f6feaf792469130eec7196854ff01215955964
1//===- ConstantFolding.cpp - LLVM constant folder -------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements folding of constants for LLVM.  This implements the
11// (internal) ConstantFolding.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// template-based folder for simple primitive constants like ConstantInt, and
16// the special case hackery that we use to symbolically evaluate expressions
17// that use ConstantExprs.
18//
19//===----------------------------------------------------------------------===//
20
21#include "ConstantFold.h"
22#include "llvm/Constants.h"
23#include "llvm/Instructions.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Function.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/GetElementPtrTypeIterator.h"
29#include "llvm/Support/ManagedStatic.h"
30#include "llvm/Support/MathExtras.h"
31#include <limits>
32using namespace llvm;
33
34//===----------------------------------------------------------------------===//
35//                ConstantFold*Instruction Implementations
36//===----------------------------------------------------------------------===//
37
38/// CastConstantVector - Convert the specified ConstantVector node to the
39/// specified vector type.  At this point, we know that the elements of the
40/// input packed constant are all simple integer or FP values.
41static Constant *CastConstantVector(ConstantVector *CP,
42                                    const VectorType *DstTy) {
43  unsigned SrcNumElts = CP->getType()->getNumElements();
44  unsigned DstNumElts = DstTy->getNumElements();
45  const Type *SrcEltTy = CP->getType()->getElementType();
46  const Type *DstEltTy = DstTy->getElementType();
47
48  // If both vectors have the same number of elements (thus, the elements
49  // are the same size), perform the conversion now.
50  if (SrcNumElts == DstNumElts) {
51    std::vector<Constant*> Result;
52
53    // If the src and dest elements are both integers, or both floats, we can
54    // just BitCast each element because the elements are the same size.
55    if ((SrcEltTy->isInteger() && DstEltTy->isInteger()) ||
56        (SrcEltTy->isFloatingPoint() && DstEltTy->isFloatingPoint())) {
57      for (unsigned i = 0; i != SrcNumElts; ++i)
58        Result.push_back(
59          ConstantExpr::getBitCast(CP->getOperand(i), DstEltTy));
60      return ConstantVector::get(Result);
61    }
62
63    // If this is an int-to-fp cast ..
64    if (SrcEltTy->isInteger()) {
65      // Ensure that it is int-to-fp cast
66      assert(DstEltTy->isFloatingPoint());
67      if (DstEltTy->getTypeID() == Type::DoubleTyID) {
68        for (unsigned i = 0; i != SrcNumElts; ++i) {
69          double V =
70            BitsToDouble(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
71          Result.push_back(ConstantFP::get(Type::DoubleTy, V));
72        }
73        return ConstantVector::get(Result);
74      }
75      assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
76      for (unsigned i = 0; i != SrcNumElts; ++i) {
77        float V =
78        BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
79        Result.push_back(ConstantFP::get(Type::FloatTy, V));
80      }
81      return ConstantVector::get(Result);
82    }
83
84    // Otherwise, this is an fp-to-int cast.
85    assert(SrcEltTy->isFloatingPoint() && DstEltTy->isInteger());
86
87    if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
88      for (unsigned i = 0; i != SrcNumElts; ++i) {
89        uint64_t V =
90          DoubleToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
91        Constant *C = ConstantInt::get(Type::Int64Ty, V);
92        Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
93      }
94      return ConstantVector::get(Result);
95    }
96
97    assert(SrcEltTy->getTypeID() == Type::FloatTyID);
98    for (unsigned i = 0; i != SrcNumElts; ++i) {
99      uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
100      Constant *C = ConstantInt::get(Type::Int32Ty, V);
101      Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
102    }
103    return ConstantVector::get(Result);
104  }
105
106  // Otherwise, this is a cast that changes element count and size.  Handle
107  // casts which shrink the elements here.
108
109  // FIXME: We need to know endianness to do this!
110
111  return 0;
112}
113
114/// This function determines which opcode to use to fold two constant cast
115/// expressions together. It uses CastInst::isEliminableCastPair to determine
116/// the opcode. Consequently its just a wrapper around that function.
117/// @Determine if it is valid to fold a cast of a cast
118static unsigned
119foldConstantCastPair(
120  unsigned opc,          ///< opcode of the second cast constant expression
121  const ConstantExpr*Op, ///< the first cast constant expression
122  const Type *DstTy      ///< desintation type of the first cast
123) {
124  assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
125  assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
126  assert(CastInst::isCast(opc) && "Invalid cast opcode");
127
128  // The the types and opcodes for the two Cast constant expressions
129  const Type *SrcTy = Op->getOperand(0)->getType();
130  const Type *MidTy = Op->getType();
131  Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
132  Instruction::CastOps secondOp = Instruction::CastOps(opc);
133
134  // Let CastInst::isEliminableCastPair do the heavy lifting.
135  return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
136                                        Type::Int64Ty);
137}
138
139Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
140                                            const Type *DestTy) {
141  const Type *SrcTy = V->getType();
142
143  if (isa<UndefValue>(V))
144    return UndefValue::get(DestTy);
145
146  // If the cast operand is a constant expression, there's a few things we can
147  // do to try to simplify it.
148  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
149    if (CE->isCast()) {
150      // Try hard to fold cast of cast because they are often eliminable.
151      if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
152        return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
153    } else if (CE->getOpcode() == Instruction::GetElementPtr) {
154      // If all of the indexes in the GEP are null values, there is no pointer
155      // adjustment going on.  We might as well cast the source pointer.
156      bool isAllNull = true;
157      for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
158        if (!CE->getOperand(i)->isNullValue()) {
159          isAllNull = false;
160          break;
161        }
162      if (isAllNull)
163        // This is casting one pointer type to another, always BitCast
164        return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
165    }
166  }
167
168  // We actually have to do a cast now. Perform the cast according to the
169  // opcode specified.
170  switch (opc) {
171  case Instruction::FPTrunc:
172  case Instruction::FPExt:
173    if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
174      return ConstantFP::get(DestTy, FPC->getValue());
175    return 0; // Can't fold.
176  case Instruction::FPToUI:
177    if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
178      return ConstantInt::get(DestTy,(uint64_t) FPC->getValue());
179    return 0; // Can't fold.
180  case Instruction::FPToSI:
181    if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
182      return ConstantInt::get(DestTy,(int64_t) FPC->getValue());
183    return 0; // Can't fold.
184  case Instruction::IntToPtr:   //always treated as unsigned
185    if (V->isNullValue())       // Is it an integral null value?
186      return ConstantPointerNull::get(cast<PointerType>(DestTy));
187    return 0;                   // Other pointer types cannot be casted
188  case Instruction::PtrToInt:   // always treated as unsigned
189    if (V->isNullValue())       // is it a null pointer value?
190      return ConstantInt::get(DestTy, 0);
191    return 0;                   // Other pointer types cannot be casted
192  case Instruction::UIToFP:
193    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
194      return ConstantFP::get(DestTy, double(CI->getZExtValue()));
195    return 0;
196  case Instruction::SIToFP:
197    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
198      return ConstantFP::get(DestTy, double(CI->getSExtValue()));
199    return 0;
200  case Instruction::ZExt:
201    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
202      return ConstantInt::get(DestTy, CI->getZExtValue());
203    return 0;
204  case Instruction::SExt:
205    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
206      return ConstantInt::get(DestTy, CI->getSExtValue());
207    return 0;
208  case Instruction::Trunc:
209    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) // Can't trunc a bool
210      return ConstantInt::get(DestTy, CI->getZExtValue());
211    return 0;
212  case Instruction::BitCast:
213    if (SrcTy == DestTy)
214      return (Constant*)V; // no-op cast
215
216    // Check to see if we are casting a pointer to an aggregate to a pointer to
217    // the first element.  If so, return the appropriate GEP instruction.
218    if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
219      if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
220        SmallVector<Value*, 8> IdxList;
221        IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
222        const Type *ElTy = PTy->getElementType();
223        while (ElTy != DPTy->getElementType()) {
224          if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
225            if (STy->getNumElements() == 0) break;
226            ElTy = STy->getElementType(0);
227            IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
228          } else if (const SequentialType *STy =
229                     dyn_cast<SequentialType>(ElTy)) {
230            if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
231            ElTy = STy->getElementType();
232            IdxList.push_back(IdxList[0]);
233          } else {
234            break;
235          }
236        }
237
238        if (ElTy == DPTy->getElementType())
239          return ConstantExpr::getGetElementPtr(
240              const_cast<Constant*>(V), &IdxList[0], IdxList.size());
241      }
242
243    // Handle casts from one packed constant to another.  We know that the src
244    // and dest type have the same size (otherwise its an illegal cast).
245    if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
246      if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
247        assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
248               "Not cast between same sized vectors!");
249        // First, check for null and undef
250        if (isa<ConstantAggregateZero>(V))
251          return Constant::getNullValue(DestTy);
252        if (isa<UndefValue>(V))
253          return UndefValue::get(DestTy);
254
255        if (const ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
256          // This is a cast from a ConstantVector of one type to a
257          // ConstantVector of another type.  Check to see if all elements of
258          // the input are simple.
259          bool AllSimpleConstants = true;
260          for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
261            if (!isa<ConstantInt>(CP->getOperand(i)) &&
262                !isa<ConstantFP>(CP->getOperand(i))) {
263              AllSimpleConstants = false;
264              break;
265            }
266          }
267
268          // If all of the elements are simple constants, we can fold this.
269          if (AllSimpleConstants)
270            return CastConstantVector(const_cast<ConstantVector*>(CP), DestPTy);
271        }
272      }
273    }
274
275    // Finally, implement bitcast folding now.   The code below doesn't handle
276    // bitcast right.
277    if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
278      return ConstantPointerNull::get(cast<PointerType>(DestTy));
279
280    // Handle integral constant input.
281    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
282      // Integral -> Integral, must be changing sign.
283      if (DestTy->isInteger())
284        return ConstantInt::get(DestTy, CI->getZExtValue());
285
286      if (DestTy->isFloatingPoint()) {
287        if (DestTy == Type::FloatTy)
288          return ConstantFP::get(DestTy, BitsToFloat(CI->getZExtValue()));
289        assert(DestTy == Type::DoubleTy && "Unknown FP type!");
290        return ConstantFP::get(DestTy, BitsToDouble(CI->getZExtValue()));
291      }
292      // Otherwise, can't fold this (packed?)
293      return 0;
294    }
295
296    // Handle ConstantFP input.
297    if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
298      // FP -> Integral.
299      if (DestTy == Type::Int32Ty) {
300        return ConstantInt::get(DestTy, FloatToBits(FP->getValue()));
301      } else {
302        assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
303        return ConstantInt::get(DestTy, DoubleToBits(FP->getValue()));
304      }
305    }
306    return 0;
307  default:
308    assert(!"Invalid CE CastInst opcode");
309    break;
310  }
311
312  assert(0 && "Failed to cast constant expression");
313  return 0;
314}
315
316Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
317                                              const Constant *V1,
318                                              const Constant *V2) {
319  if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
320    return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
321
322  if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
323  if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
324  if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
325  if (V1 == V2) return const_cast<Constant*>(V1);
326  return 0;
327}
328
329Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
330                                                      const Constant *Idx) {
331  if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
332    return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
333  if (Val->isNullValue())  // ee(zero, x) -> zero
334    return Constant::getNullValue(
335                          cast<VectorType>(Val->getType())->getElementType());
336
337  if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
338    if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
339      return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
340    } else if (isa<UndefValue>(Idx)) {
341      // ee({w,x,y,z}, undef) -> w (an arbitrary value).
342      return const_cast<Constant*>(CVal->getOperand(0));
343    }
344  }
345  return 0;
346}
347
348Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
349                                                     const Constant *Elt,
350                                                     const Constant *Idx) {
351  const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
352  if (!CIdx) return 0;
353  uint64_t idxVal = CIdx->getZExtValue();
354  if (isa<UndefValue>(Val)) {
355    // Insertion of scalar constant into packed undef
356    // Optimize away insertion of undef
357    if (isa<UndefValue>(Elt))
358      return const_cast<Constant*>(Val);
359    // Otherwise break the aggregate undef into multiple undefs and do
360    // the insertion
361    unsigned numOps =
362      cast<VectorType>(Val->getType())->getNumElements();
363    std::vector<Constant*> Ops;
364    Ops.reserve(numOps);
365    for (unsigned i = 0; i < numOps; ++i) {
366      const Constant *Op =
367        (i == idxVal) ? Elt : UndefValue::get(Elt->getType());
368      Ops.push_back(const_cast<Constant*>(Op));
369    }
370    return ConstantVector::get(Ops);
371  }
372  if (isa<ConstantAggregateZero>(Val)) {
373    // Insertion of scalar constant into packed aggregate zero
374    // Optimize away insertion of zero
375    if (Elt->isNullValue())
376      return const_cast<Constant*>(Val);
377    // Otherwise break the aggregate zero into multiple zeros and do
378    // the insertion
379    unsigned numOps =
380      cast<VectorType>(Val->getType())->getNumElements();
381    std::vector<Constant*> Ops;
382    Ops.reserve(numOps);
383    for (unsigned i = 0; i < numOps; ++i) {
384      const Constant *Op =
385        (i == idxVal) ? Elt : Constant::getNullValue(Elt->getType());
386      Ops.push_back(const_cast<Constant*>(Op));
387    }
388    return ConstantVector::get(Ops);
389  }
390  if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
391    // Insertion of scalar constant into packed constant
392    std::vector<Constant*> Ops;
393    Ops.reserve(CVal->getNumOperands());
394    for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
395      const Constant *Op =
396        (i == idxVal) ? Elt : cast<Constant>(CVal->getOperand(i));
397      Ops.push_back(const_cast<Constant*>(Op));
398    }
399    return ConstantVector::get(Ops);
400  }
401  return 0;
402}
403
404Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
405                                                     const Constant *V2,
406                                                     const Constant *Mask) {
407  // TODO:
408  return 0;
409}
410
411/// EvalVectorOp - Given two packed constants and a function pointer, apply the
412/// function pointer to each element pair, producing a new ConstantVector
413/// constant.
414static Constant *EvalVectorOp(const ConstantVector *V1,
415                              const ConstantVector *V2,
416                              Constant *(*FP)(Constant*, Constant*)) {
417  std::vector<Constant*> Res;
418  for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
419    Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
420                     const_cast<Constant*>(V2->getOperand(i))));
421  return ConstantVector::get(Res);
422}
423
424Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
425                                              const Constant *C1,
426                                              const Constant *C2) {
427  // Handle UndefValue up front
428  if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
429    switch (Opcode) {
430    case Instruction::Add:
431    case Instruction::Sub:
432    case Instruction::Xor:
433      return UndefValue::get(C1->getType());
434    case Instruction::Mul:
435    case Instruction::And:
436      return Constant::getNullValue(C1->getType());
437    case Instruction::UDiv:
438    case Instruction::SDiv:
439    case Instruction::FDiv:
440    case Instruction::URem:
441    case Instruction::SRem:
442    case Instruction::FRem:
443      if (!isa<UndefValue>(C2))                    // undef / X -> 0
444        return Constant::getNullValue(C1->getType());
445      return const_cast<Constant*>(C2);            // X / undef -> undef
446    case Instruction::Or:                          // X | undef -> -1
447      if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
448        return ConstantVector::getAllOnesValue(PTy);
449      return ConstantInt::getAllOnesValue(C1->getType());
450    case Instruction::LShr:
451      if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
452        return const_cast<Constant*>(C1);           // undef lshr undef -> undef
453      return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
454                                                    // undef lshr X -> 0
455    case Instruction::AShr:
456      if (!isa<UndefValue>(C2))
457        return const_cast<Constant*>(C1);           // undef ashr X --> undef
458      else if (isa<UndefValue>(C1))
459        return const_cast<Constant*>(C1);           // undef ashr undef -> undef
460      else
461        return const_cast<Constant*>(C1);           // X ashr undef --> X
462    case Instruction::Shl:
463      // undef << X -> 0   or   X << undef -> 0
464      return Constant::getNullValue(C1->getType());
465    }
466  }
467
468  if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
469    if (isa<ConstantExpr>(C2)) {
470      // There are many possible foldings we could do here.  We should probably
471      // at least fold add of a pointer with an integer into the appropriate
472      // getelementptr.  This will improve alias analysis a bit.
473    } else {
474      // Just implement a couple of simple identities.
475      switch (Opcode) {
476      case Instruction::Add:
477        if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X + 0 == X
478        break;
479      case Instruction::Sub:
480        if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X - 0 == X
481        break;
482      case Instruction::Mul:
483        if (C2->isNullValue()) return const_cast<Constant*>(C2);  // X * 0 == 0
484        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
485          if (CI->getZExtValue() == 1)
486            return const_cast<Constant*>(C1);                     // X * 1 == X
487        break;
488      case Instruction::UDiv:
489      case Instruction::SDiv:
490        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
491          if (CI->getZExtValue() == 1)
492            return const_cast<Constant*>(C1);                     // X / 1 == X
493        break;
494      case Instruction::URem:
495      case Instruction::SRem:
496        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
497          if (CI->getZExtValue() == 1)
498            return Constant::getNullValue(CI->getType());         // X % 1 == 0
499        break;
500      case Instruction::And:
501        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
502          if (CI->isAllOnesValue())
503            return const_cast<Constant*>(C1);                     // X & -1 == X
504        if (C2->isNullValue()) return const_cast<Constant*>(C2);  // X & 0 == 0
505        if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
506          GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
507
508          // Functions are at least 4-byte aligned.  If and'ing the address of a
509          // function with a constant < 4, fold it to zero.
510          if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
511            if (CI->getZExtValue() < 4 && isa<Function>(CPR))
512              return Constant::getNullValue(CI->getType());
513        }
514        break;
515      case Instruction::Or:
516        if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X | 0 == X
517        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
518          if (CI->isAllOnesValue())
519            return const_cast<Constant*>(C2);  // X | -1 == -1
520        break;
521      case Instruction::Xor:
522        if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X ^ 0 == X
523        break;
524      }
525    }
526  } else if (isa<ConstantExpr>(C2)) {
527    // If C2 is a constant expr and C1 isn't, flop them around and fold the
528    // other way if possible.
529    switch (Opcode) {
530    case Instruction::Add:
531    case Instruction::Mul:
532    case Instruction::And:
533    case Instruction::Or:
534    case Instruction::Xor:
535      // No change of opcode required.
536      return ConstantFoldBinaryInstruction(Opcode, C2, C1);
537
538    case Instruction::Shl:
539    case Instruction::LShr:
540    case Instruction::AShr:
541    case Instruction::Sub:
542    case Instruction::SDiv:
543    case Instruction::UDiv:
544    case Instruction::FDiv:
545    case Instruction::URem:
546    case Instruction::SRem:
547    case Instruction::FRem:
548    default:  // These instructions cannot be flopped around.
549      return 0;
550    }
551  }
552
553  // At this point we know neither constant is an UndefValue nor a ConstantExpr
554  // so look at directly computing the value.
555  if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
556    if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
557      uint64_t C1Val = CI1->getZExtValue();
558      uint64_t C2Val = CI2->getZExtValue();
559      switch (Opcode) {
560      default:
561        break;
562      case Instruction::Add:
563        return ConstantInt::get(C1->getType(), C1Val + C2Val);
564      case Instruction::Sub:
565        return ConstantInt::get(C1->getType(), C1Val - C2Val);
566      case Instruction::Mul:
567        return ConstantInt::get(C1->getType(), C1Val * C2Val);
568      case Instruction::UDiv:
569        if (CI2->isNullValue())                  // X / 0 -> can't fold
570          return 0;
571        return ConstantInt::get(C1->getType(), C1Val / C2Val);
572      case Instruction::SDiv:
573        if (CI2->isNullValue()) return 0;        // X / 0 -> can't fold
574        if (CI2->isAllOnesValue() &&
575            (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
576              (CI1->getSExtValue() == INT64_MIN)) ||
577             (CI1->getSExtValue() == -CI1->getSExtValue() &&
578              CI1->getSExtValue())))
579          return 0;                              // MIN_INT / -1 -> overflow
580        return ConstantInt::get(C1->getType(),
581                                CI1->getSExtValue() / CI2->getSExtValue());
582      case Instruction::URem:
583        if (C2->isNullValue()) return 0;         // X / 0 -> can't fold
584        return ConstantInt::get(C1->getType(), C1Val % C2Val);
585      case Instruction::SRem:
586        if (CI2->isNullValue()) return 0;        // X % 0 -> can't fold
587        if (CI2->isAllOnesValue() &&
588            (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
589              (CI1->getSExtValue() == INT64_MIN)) ||
590             (CI1->getSExtValue() == -CI1->getSExtValue())))
591          return 0;                              // MIN_INT % -1 -> overflow
592        return ConstantInt::get(C1->getType(),
593                                CI1->getSExtValue() % CI2->getSExtValue());
594      case Instruction::And:
595        return ConstantInt::get(C1->getType(), C1Val & C2Val);
596      case Instruction::Or:
597        return ConstantInt::get(C1->getType(), C1Val | C2Val);
598      case Instruction::Xor:
599        return ConstantInt::get(C1->getType(), C1Val ^ C2Val);
600      case Instruction::Shl:
601        return ConstantInt::get(C1->getType(), C1Val << C2Val);
602      case Instruction::LShr:
603        return ConstantInt::get(C1->getType(), C1Val >> C2Val);
604      case Instruction::AShr:
605        return ConstantInt::get(C1->getType(),
606                                CI1->getSExtValue() >> C2Val);
607      }
608    }
609  } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
610    if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
611      double C1Val = CFP1->getValue();
612      double C2Val = CFP2->getValue();
613      switch (Opcode) {
614      default:
615        break;
616      case Instruction::Add:
617        return ConstantFP::get(CFP1->getType(), C1Val + C2Val);
618      case Instruction::Sub:
619        return ConstantFP::get(CFP1->getType(), C1Val - C2Val);
620      case Instruction::Mul:
621        return ConstantFP::get(CFP1->getType(), C1Val * C2Val);
622      case Instruction::FDiv:
623        if (CFP2->isExactlyValue(0.0))
624          return ConstantFP::get(CFP1->getType(),
625                                 std::numeric_limits<double>::infinity());
626        if (CFP2->isExactlyValue(-0.0))
627          return ConstantFP::get(CFP1->getType(),
628                                 -std::numeric_limits<double>::infinity());
629        return ConstantFP::get(CFP1->getType(), C1Val / C2Val);
630      case Instruction::FRem:
631        if (CFP2->isNullValue())
632          return 0;
633        return ConstantFP::get(CFP1->getType(), std::fmod(C1Val, C2Val));
634      }
635    }
636  } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
637    if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
638      switch (Opcode) {
639        default:
640          break;
641        case Instruction::Add:
642          return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
643        case Instruction::Sub:
644          return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
645        case Instruction::Mul:
646          return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
647        case Instruction::UDiv:
648          return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
649        case Instruction::SDiv:
650          return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
651        case Instruction::FDiv:
652          return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
653        case Instruction::URem:
654          return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
655        case Instruction::SRem:
656          return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
657        case Instruction::FRem:
658          return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
659        case Instruction::And:
660          return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
661        case Instruction::Or:
662          return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
663        case Instruction::Xor:
664          return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
665      }
666    }
667  }
668
669  // We don't know how to fold this
670  return 0;
671}
672
673/// isZeroSizedType - This type is zero sized if its an array or structure of
674/// zero sized types.  The only leaf zero sized type is an empty structure.
675static bool isMaybeZeroSizedType(const Type *Ty) {
676  if (isa<OpaqueType>(Ty)) return true;  // Can't say.
677  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
678
679    // If all of elements have zero size, this does too.
680    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
681      if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
682    return true;
683
684  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
685    return isMaybeZeroSizedType(ATy->getElementType());
686  }
687  return false;
688}
689
690/// IdxCompare - Compare the two constants as though they were getelementptr
691/// indices.  This allows coersion of the types to be the same thing.
692///
693/// If the two constants are the "same" (after coersion), return 0.  If the
694/// first is less than the second, return -1, if the second is less than the
695/// first, return 1.  If the constants are not integral, return -2.
696///
697static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
698  if (C1 == C2) return 0;
699
700  // Ok, we found a different index.  If they are not ConstantInt, we can't do
701  // anything with them.
702  if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
703    return -2; // don't know!
704
705  // Ok, we have two differing integer indices.  Sign extend them to be the same
706  // type.  Long is always big enough, so we use it.
707  if (C1->getType() != Type::Int64Ty)
708    C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
709
710  if (C2->getType() != Type::Int64Ty)
711    C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
712
713  if (C1 == C2) return 0;  // They are equal
714
715  // If the type being indexed over is really just a zero sized type, there is
716  // no pointer difference being made here.
717  if (isMaybeZeroSizedType(ElTy))
718    return -2; // dunno.
719
720  // If they are really different, now that they are the same type, then we
721  // found a difference!
722  if (cast<ConstantInt>(C1)->getSExtValue() <
723      cast<ConstantInt>(C2)->getSExtValue())
724    return -1;
725  else
726    return 1;
727}
728
729/// evaluateFCmpRelation - This function determines if there is anything we can
730/// decide about the two constants provided.  This doesn't need to handle simple
731/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
732/// If we can determine that the two constants have a particular relation to
733/// each other, we should return the corresponding FCmpInst predicate,
734/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
735/// ConstantFoldCompareInstruction.
736///
737/// To simplify this code we canonicalize the relation so that the first
738/// operand is always the most "complex" of the two.  We consider ConstantFP
739/// to be the simplest, and ConstantExprs to be the most complex.
740static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
741                                                const Constant *V2) {
742  assert(V1->getType() == V2->getType() &&
743         "Cannot compare values of different types!");
744  // Handle degenerate case quickly
745  if (V1 == V2) return FCmpInst::FCMP_OEQ;
746
747  if (!isa<ConstantExpr>(V1)) {
748    if (!isa<ConstantExpr>(V2)) {
749      // We distilled thisUse the standard constant folder for a few cases
750      ConstantInt *R = 0;
751      Constant *C1 = const_cast<Constant*>(V1);
752      Constant *C2 = const_cast<Constant*>(V2);
753      R = dyn_cast<ConstantInt>(
754                             ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
755      if (R && R->getZExtValue())
756        return FCmpInst::FCMP_OEQ;
757      R = dyn_cast<ConstantInt>(
758                             ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
759      if (R && R->getZExtValue())
760        return FCmpInst::FCMP_OLT;
761      R = dyn_cast<ConstantInt>(
762                             ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
763      if (R && R->getZExtValue())
764        return FCmpInst::FCMP_OGT;
765
766      // Nothing more we can do
767      return FCmpInst::BAD_FCMP_PREDICATE;
768    }
769
770    // If the first operand is simple and second is ConstantExpr, swap operands.
771    FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
772    if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
773      return FCmpInst::getSwappedPredicate(SwappedRelation);
774  } else {
775    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
776    // constantexpr or a simple constant.
777    const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
778    switch (CE1->getOpcode()) {
779    case Instruction::FPTrunc:
780    case Instruction::FPExt:
781    case Instruction::UIToFP:
782    case Instruction::SIToFP:
783      // We might be able to do something with these but we don't right now.
784      break;
785    default:
786      break;
787    }
788  }
789  // There are MANY other foldings that we could perform here.  They will
790  // probably be added on demand, as they seem needed.
791  return FCmpInst::BAD_FCMP_PREDICATE;
792}
793
794/// evaluateICmpRelation - This function determines if there is anything we can
795/// decide about the two constants provided.  This doesn't need to handle simple
796/// things like integer comparisons, but should instead handle ConstantExprs
797/// and GlobalValues.  If we can determine that the two constants have a
798/// particular relation to each other, we should return the corresponding ICmp
799/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
800///
801/// To simplify this code we canonicalize the relation so that the first
802/// operand is always the most "complex" of the two.  We consider simple
803/// constants (like ConstantInt) to be the simplest, followed by
804/// GlobalValues, followed by ConstantExpr's (the most complex).
805///
806static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
807                                                const Constant *V2,
808                                                bool isSigned) {
809  assert(V1->getType() == V2->getType() &&
810         "Cannot compare different types of values!");
811  if (V1 == V2) return ICmpInst::ICMP_EQ;
812
813  if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
814    if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
815      // We distilled this down to a simple case, use the standard constant
816      // folder.
817      ConstantInt *R = 0;
818      Constant *C1 = const_cast<Constant*>(V1);
819      Constant *C2 = const_cast<Constant*>(V2);
820      ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
821      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
822      if (R && R->getZExtValue())
823        return pred;
824      pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
825      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
826      if (R && R->getZExtValue())
827        return pred;
828      pred = isSigned ?  ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
829      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
830      if (R && R->getZExtValue())
831        return pred;
832
833      // If we couldn't figure it out, bail.
834      return ICmpInst::BAD_ICMP_PREDICATE;
835    }
836
837    // If the first operand is simple, swap operands.
838    ICmpInst::Predicate SwappedRelation =
839      evaluateICmpRelation(V2, V1, isSigned);
840    if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
841      return ICmpInst::getSwappedPredicate(SwappedRelation);
842
843  } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
844    if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
845      ICmpInst::Predicate SwappedRelation =
846        evaluateICmpRelation(V2, V1, isSigned);
847      if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
848        return ICmpInst::getSwappedPredicate(SwappedRelation);
849      else
850        return ICmpInst::BAD_ICMP_PREDICATE;
851    }
852
853    // Now we know that the RHS is a GlobalValue or simple constant,
854    // which (since the types must match) means that it's a ConstantPointerNull.
855    if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
856      if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
857        return ICmpInst::ICMP_NE;
858    } else {
859      // GlobalVals can never be null.
860      assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
861      if (!CPR1->hasExternalWeakLinkage())
862        return ICmpInst::ICMP_NE;
863    }
864  } else {
865    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
866    // constantexpr, a CPR, or a simple constant.
867    const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
868    const Constant *CE1Op0 = CE1->getOperand(0);
869
870    switch (CE1->getOpcode()) {
871    case Instruction::Trunc:
872    case Instruction::FPTrunc:
873    case Instruction::FPExt:
874    case Instruction::FPToUI:
875    case Instruction::FPToSI:
876      break; // We can't evaluate floating point casts or truncations.
877
878    case Instruction::UIToFP:
879    case Instruction::SIToFP:
880    case Instruction::IntToPtr:
881    case Instruction::BitCast:
882    case Instruction::ZExt:
883    case Instruction::SExt:
884    case Instruction::PtrToInt:
885      // If the cast is not actually changing bits, and the second operand is a
886      // null pointer, do the comparison with the pre-casted value.
887      if (V2->isNullValue() &&
888          (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
889        bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
890          (CE1->getOpcode() == Instruction::SExt ? true :
891           (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
892        return evaluateICmpRelation(
893            CE1Op0, Constant::getNullValue(CE1Op0->getType()), sgnd);
894      }
895
896      // If the dest type is a pointer type, and the RHS is a constantexpr cast
897      // from the same type as the src of the LHS, evaluate the inputs.  This is
898      // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
899      // which happens a lot in compilers with tagged integers.
900      if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
901        if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
902            CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
903            CE1->getOperand(0)->getType()->isInteger()) {
904          bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
905            (CE1->getOpcode() == Instruction::SExt ? true :
906             (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
907          return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
908              sgnd);
909        }
910      break;
911
912    case Instruction::GetElementPtr:
913      // Ok, since this is a getelementptr, we know that the constant has a
914      // pointer type.  Check the various cases.
915      if (isa<ConstantPointerNull>(V2)) {
916        // If we are comparing a GEP to a null pointer, check to see if the base
917        // of the GEP equals the null pointer.
918        if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
919          if (GV->hasExternalWeakLinkage())
920            // Weak linkage GVals could be zero or not. We're comparing that
921            // to null pointer so its greater-or-equal
922            return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
923          else
924            // If its not weak linkage, the GVal must have a non-zero address
925            // so the result is greater-than
926            return isSigned ? ICmpInst::ICMP_SGT :  ICmpInst::ICMP_UGT;
927        } else if (isa<ConstantPointerNull>(CE1Op0)) {
928          // If we are indexing from a null pointer, check to see if we have any
929          // non-zero indices.
930          for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
931            if (!CE1->getOperand(i)->isNullValue())
932              // Offsetting from null, must not be equal.
933              return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
934          // Only zero indexes from null, must still be zero.
935          return ICmpInst::ICMP_EQ;
936        }
937        // Otherwise, we can't really say if the first operand is null or not.
938      } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
939        if (isa<ConstantPointerNull>(CE1Op0)) {
940          if (CPR2->hasExternalWeakLinkage())
941            // Weak linkage GVals could be zero or not. We're comparing it to
942            // a null pointer, so its less-or-equal
943            return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
944          else
945            // If its not weak linkage, the GVal must have a non-zero address
946            // so the result is less-than
947            return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
948        } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
949          if (CPR1 == CPR2) {
950            // If this is a getelementptr of the same global, then it must be
951            // different.  Because the types must match, the getelementptr could
952            // only have at most one index, and because we fold getelementptr's
953            // with a single zero index, it must be nonzero.
954            assert(CE1->getNumOperands() == 2 &&
955                   !CE1->getOperand(1)->isNullValue() &&
956                   "Suprising getelementptr!");
957            return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
958          } else {
959            // If they are different globals, we don't know what the value is,
960            // but they can't be equal.
961            return ICmpInst::ICMP_NE;
962          }
963        }
964      } else {
965        const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
966        const Constant *CE2Op0 = CE2->getOperand(0);
967
968        // There are MANY other foldings that we could perform here.  They will
969        // probably be added on demand, as they seem needed.
970        switch (CE2->getOpcode()) {
971        default: break;
972        case Instruction::GetElementPtr:
973          // By far the most common case to handle is when the base pointers are
974          // obviously to the same or different globals.
975          if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
976            if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
977              return ICmpInst::ICMP_NE;
978            // Ok, we know that both getelementptr instructions are based on the
979            // same global.  From this, we can precisely determine the relative
980            // ordering of the resultant pointers.
981            unsigned i = 1;
982
983            // Compare all of the operands the GEP's have in common.
984            gep_type_iterator GTI = gep_type_begin(CE1);
985            for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
986                 ++i, ++GTI)
987              switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
988                                 GTI.getIndexedType())) {
989              case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
990              case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
991              case -2: return ICmpInst::BAD_ICMP_PREDICATE;
992              }
993
994            // Ok, we ran out of things they have in common.  If any leftovers
995            // are non-zero then we have a difference, otherwise we are equal.
996            for (; i < CE1->getNumOperands(); ++i)
997              if (!CE1->getOperand(i)->isNullValue())
998                if (isa<ConstantInt>(CE1->getOperand(i)))
999                  return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1000                else
1001                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1002
1003            for (; i < CE2->getNumOperands(); ++i)
1004              if (!CE2->getOperand(i)->isNullValue())
1005                if (isa<ConstantInt>(CE2->getOperand(i)))
1006                  return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1007                else
1008                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1009            return ICmpInst::ICMP_EQ;
1010          }
1011        }
1012      }
1013    default:
1014      break;
1015    }
1016  }
1017
1018  return ICmpInst::BAD_ICMP_PREDICATE;
1019}
1020
1021Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1022                                               const Constant *C1,
1023                                               const Constant *C2) {
1024
1025  // Handle some degenerate cases first
1026  if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1027    return UndefValue::get(Type::Int1Ty);
1028
1029  // icmp eq/ne(null,GV) -> false/true
1030  if (C1->isNullValue()) {
1031    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1032      if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1033        if (pred == ICmpInst::ICMP_EQ)
1034          return ConstantInt::getFalse();
1035        else if (pred == ICmpInst::ICMP_NE)
1036          return ConstantInt::getTrue();
1037  // icmp eq/ne(GV,null) -> false/true
1038  } else if (C2->isNullValue()) {
1039    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1040      if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1041        if (pred == ICmpInst::ICMP_EQ)
1042          return ConstantInt::getFalse();
1043        else if (pred == ICmpInst::ICMP_NE)
1044          return ConstantInt::getTrue();
1045  }
1046
1047  if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1048    if (ICmpInst::isSignedPredicate(ICmpInst::Predicate(pred))) {
1049      int64_t V1 = cast<ConstantInt>(C1)->getSExtValue();
1050      int64_t V2 = cast<ConstantInt>(C2)->getSExtValue();
1051      switch (pred) {
1052      default: assert(0 && "Invalid ICmp Predicate"); return 0;
1053      case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1 <  V2);
1054      case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1 >  V2);
1055      case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1 <= V2);
1056      case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1 >= V2);
1057      }
1058    } else {
1059      uint64_t V1 = cast<ConstantInt>(C1)->getZExtValue();
1060      uint64_t V2 = cast<ConstantInt>(C2)->getZExtValue();
1061      switch (pred) {
1062      default: assert(0 && "Invalid ICmp Predicate"); return 0;
1063      case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1064      case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1065      case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1 <  V2);
1066      case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1 >  V2);
1067      case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1 <= V2);
1068      case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1 >= V2);
1069      }
1070    }
1071  } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1072    double C1Val = cast<ConstantFP>(C1)->getValue();
1073    double C2Val = cast<ConstantFP>(C2)->getValue();
1074    switch (pred) {
1075    default: assert(0 && "Invalid FCmp Predicate"); return 0;
1076    case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1077    case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue();
1078    case FCmpInst::FCMP_UNO:
1079      return ConstantInt::get(Type::Int1Ty, C1Val != C1Val || C2Val != C2Val);
1080    case FCmpInst::FCMP_ORD:
1081      return ConstantInt::get(Type::Int1Ty, C1Val == C1Val && C2Val == C2Val);
1082    case FCmpInst::FCMP_UEQ:
1083      if (C1Val != C1Val || C2Val != C2Val)
1084        return ConstantInt::getTrue();
1085      /* FALL THROUGH */
1086    case FCmpInst::FCMP_OEQ:
1087      return ConstantInt::get(Type::Int1Ty, C1Val == C2Val);
1088    case FCmpInst::FCMP_UNE:
1089      if (C1Val != C1Val || C2Val != C2Val)
1090        return ConstantInt::getTrue();
1091      /* FALL THROUGH */
1092    case FCmpInst::FCMP_ONE:
1093      return ConstantInt::get(Type::Int1Ty, C1Val != C2Val);
1094    case FCmpInst::FCMP_ULT:
1095      if (C1Val != C1Val || C2Val != C2Val)
1096        return ConstantInt::getTrue();
1097      /* FALL THROUGH */
1098    case FCmpInst::FCMP_OLT:
1099      return ConstantInt::get(Type::Int1Ty, C1Val < C2Val);
1100    case FCmpInst::FCMP_UGT:
1101      if (C1Val != C1Val || C2Val != C2Val)
1102        return ConstantInt::getTrue();
1103      /* FALL THROUGH */
1104    case FCmpInst::FCMP_OGT:
1105      return ConstantInt::get(Type::Int1Ty, C1Val > C2Val);
1106    case FCmpInst::FCMP_ULE:
1107      if (C1Val != C1Val || C2Val != C2Val)
1108        return ConstantInt::getTrue();
1109      /* FALL THROUGH */
1110    case FCmpInst::FCMP_OLE:
1111      return ConstantInt::get(Type::Int1Ty, C1Val <= C2Val);
1112    case FCmpInst::FCMP_UGE:
1113      if (C1Val != C1Val || C2Val != C2Val)
1114        return ConstantInt::getTrue();
1115      /* FALL THROUGH */
1116    case FCmpInst::FCMP_OGE:
1117      return ConstantInt::get(Type::Int1Ty, C1Val >= C2Val);
1118    }
1119  } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1120    if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1121      if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1122        for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1123          Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1124              const_cast<Constant*>(CP1->getOperand(i)),
1125              const_cast<Constant*>(CP2->getOperand(i)));
1126          if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1127            return CB;
1128        }
1129        // Otherwise, could not decide from any element pairs.
1130        return 0;
1131      } else if (pred == ICmpInst::ICMP_EQ) {
1132        for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1133          Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1134              const_cast<Constant*>(CP1->getOperand(i)),
1135              const_cast<Constant*>(CP2->getOperand(i)));
1136          if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1137            return CB;
1138        }
1139        // Otherwise, could not decide from any element pairs.
1140        return 0;
1141      }
1142    }
1143  }
1144
1145  if (C1->getType()->isFloatingPoint()) {
1146    switch (evaluateFCmpRelation(C1, C2)) {
1147    default: assert(0 && "Unknown relation!");
1148    case FCmpInst::FCMP_UNO:
1149    case FCmpInst::FCMP_ORD:
1150    case FCmpInst::FCMP_UEQ:
1151    case FCmpInst::FCMP_UNE:
1152    case FCmpInst::FCMP_ULT:
1153    case FCmpInst::FCMP_UGT:
1154    case FCmpInst::FCMP_ULE:
1155    case FCmpInst::FCMP_UGE:
1156    case FCmpInst::FCMP_TRUE:
1157    case FCmpInst::FCMP_FALSE:
1158    case FCmpInst::BAD_FCMP_PREDICATE:
1159      break; // Couldn't determine anything about these constants.
1160    case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1161      return ConstantInt::get(Type::Int1Ty,
1162          pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1163          pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1164          pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1165    case FCmpInst::FCMP_OLT: // We know that C1 < C2
1166      return ConstantInt::get(Type::Int1Ty,
1167          pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1168          pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1169          pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1170    case FCmpInst::FCMP_OGT: // We know that C1 > C2
1171      return ConstantInt::get(Type::Int1Ty,
1172          pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1173          pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1174          pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1175    case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1176      // We can only partially decide this relation.
1177      if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1178        return ConstantInt::getFalse();
1179      if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1180        return ConstantInt::getTrue();
1181      break;
1182    case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1183      // We can only partially decide this relation.
1184      if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1185        return ConstantInt::getFalse();
1186      if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1187        return ConstantInt::getTrue();
1188      break;
1189    case ICmpInst::ICMP_NE: // We know that C1 != C2
1190      // We can only partially decide this relation.
1191      if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1192        return ConstantInt::getFalse();
1193      if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1194        return ConstantInt::getTrue();
1195      break;
1196    }
1197  } else {
1198    // Evaluate the relation between the two constants, per the predicate.
1199    switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1200    default: assert(0 && "Unknown relational!");
1201    case ICmpInst::BAD_ICMP_PREDICATE:
1202      break;  // Couldn't determine anything about these constants.
1203    case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1204      // If we know the constants are equal, we can decide the result of this
1205      // computation precisely.
1206      return ConstantInt::get(Type::Int1Ty,
1207                              pred == ICmpInst::ICMP_EQ  ||
1208                              pred == ICmpInst::ICMP_ULE ||
1209                              pred == ICmpInst::ICMP_SLE ||
1210                              pred == ICmpInst::ICMP_UGE ||
1211                              pred == ICmpInst::ICMP_SGE);
1212    case ICmpInst::ICMP_ULT:
1213      // If we know that C1 < C2, we can decide the result of this computation
1214      // precisely.
1215      return ConstantInt::get(Type::Int1Ty,
1216                              pred == ICmpInst::ICMP_ULT ||
1217                              pred == ICmpInst::ICMP_NE  ||
1218                              pred == ICmpInst::ICMP_ULE);
1219    case ICmpInst::ICMP_SLT:
1220      // If we know that C1 < C2, we can decide the result of this computation
1221      // precisely.
1222      return ConstantInt::get(Type::Int1Ty,
1223                              pred == ICmpInst::ICMP_SLT ||
1224                              pred == ICmpInst::ICMP_NE  ||
1225                              pred == ICmpInst::ICMP_SLE);
1226    case ICmpInst::ICMP_UGT:
1227      // If we know that C1 > C2, we can decide the result of this computation
1228      // precisely.
1229      return ConstantInt::get(Type::Int1Ty,
1230                              pred == ICmpInst::ICMP_UGT ||
1231                              pred == ICmpInst::ICMP_NE  ||
1232                              pred == ICmpInst::ICMP_UGE);
1233    case ICmpInst::ICMP_SGT:
1234      // If we know that C1 > C2, we can decide the result of this computation
1235      // precisely.
1236      return ConstantInt::get(Type::Int1Ty,
1237                              pred == ICmpInst::ICMP_SGT ||
1238                              pred == ICmpInst::ICMP_NE  ||
1239                              pred == ICmpInst::ICMP_SGE);
1240    case ICmpInst::ICMP_ULE:
1241      // If we know that C1 <= C2, we can only partially decide this relation.
1242      if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1243      if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1244      break;
1245    case ICmpInst::ICMP_SLE:
1246      // If we know that C1 <= C2, we can only partially decide this relation.
1247      if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1248      if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1249      break;
1250
1251    case ICmpInst::ICMP_UGE:
1252      // If we know that C1 >= C2, we can only partially decide this relation.
1253      if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1254      if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1255      break;
1256    case ICmpInst::ICMP_SGE:
1257      // If we know that C1 >= C2, we can only partially decide this relation.
1258      if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1259      if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1260      break;
1261
1262    case ICmpInst::ICMP_NE:
1263      // If we know that C1 != C2, we can only partially decide this relation.
1264      if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1265      if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1266      break;
1267    }
1268
1269    if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1270      // If C2 is a constant expr and C1 isn't, flop them around and fold the
1271      // other way if possible.
1272      switch (pred) {
1273      case ICmpInst::ICMP_EQ:
1274      case ICmpInst::ICMP_NE:
1275        // No change of predicate required.
1276        return ConstantFoldCompareInstruction(pred, C2, C1);
1277
1278      case ICmpInst::ICMP_ULT:
1279      case ICmpInst::ICMP_SLT:
1280      case ICmpInst::ICMP_UGT:
1281      case ICmpInst::ICMP_SGT:
1282      case ICmpInst::ICMP_ULE:
1283      case ICmpInst::ICMP_SLE:
1284      case ICmpInst::ICMP_UGE:
1285      case ICmpInst::ICMP_SGE:
1286        // Change the predicate as necessary to swap the operands.
1287        pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1288        return ConstantFoldCompareInstruction(pred, C2, C1);
1289
1290      default:  // These predicates cannot be flopped around.
1291        break;
1292      }
1293    }
1294  }
1295  return 0;
1296}
1297
1298Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1299                                          Constant* const *Idxs,
1300                                          unsigned NumIdx) {
1301  if (NumIdx == 0 ||
1302      (NumIdx == 1 && Idxs[0]->isNullValue()))
1303    return const_cast<Constant*>(C);
1304
1305  if (isa<UndefValue>(C)) {
1306    const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1307                                                       (Value**)Idxs, NumIdx,
1308                                                       true);
1309    assert(Ty != 0 && "Invalid indices for GEP!");
1310    return UndefValue::get(PointerType::get(Ty));
1311  }
1312
1313  Constant *Idx0 = Idxs[0];
1314  if (C->isNullValue()) {
1315    bool isNull = true;
1316    for (unsigned i = 0, e = NumIdx; i != e; ++i)
1317      if (!Idxs[i]->isNullValue()) {
1318        isNull = false;
1319        break;
1320      }
1321    if (isNull) {
1322      const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1323                                                         (Value**)Idxs, NumIdx,
1324                                                         true);
1325      assert(Ty != 0 && "Invalid indices for GEP!");
1326      return ConstantPointerNull::get(PointerType::get(Ty));
1327    }
1328  }
1329
1330  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1331    // Combine Indices - If the source pointer to this getelementptr instruction
1332    // is a getelementptr instruction, combine the indices of the two
1333    // getelementptr instructions into a single instruction.
1334    //
1335    if (CE->getOpcode() == Instruction::GetElementPtr) {
1336      const Type *LastTy = 0;
1337      for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1338           I != E; ++I)
1339        LastTy = *I;
1340
1341      if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1342        SmallVector<Value*, 16> NewIndices;
1343        NewIndices.reserve(NumIdx + CE->getNumOperands());
1344        for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1345          NewIndices.push_back(CE->getOperand(i));
1346
1347        // Add the last index of the source with the first index of the new GEP.
1348        // Make sure to handle the case when they are actually different types.
1349        Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1350        // Otherwise it must be an array.
1351        if (!Idx0->isNullValue()) {
1352          const Type *IdxTy = Combined->getType();
1353          if (IdxTy != Idx0->getType()) {
1354            Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1355            Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1356                                                          Type::Int64Ty);
1357            Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1358          } else {
1359            Combined =
1360              ConstantExpr::get(Instruction::Add, Idx0, Combined);
1361          }
1362        }
1363
1364        NewIndices.push_back(Combined);
1365        NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1366        return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1367                                              NewIndices.size());
1368      }
1369    }
1370
1371    // Implement folding of:
1372    //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1373    //                        long 0, long 0)
1374    // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1375    //
1376    if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue())
1377      if (const PointerType *SPT =
1378          dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1379        if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1380          if (const ArrayType *CAT =
1381        dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1382            if (CAT->getElementType() == SAT->getElementType())
1383              return ConstantExpr::getGetElementPtr(
1384                      (Constant*)CE->getOperand(0), Idxs, NumIdx);
1385  }
1386  return 0;
1387}
1388
1389