ConstantFold.cpp revision ac9dcb94dde5f166ee29372385c0e3b695227ab4
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 "ConstantFolding.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          return 0;                              // MIN_INT / -1 -> overflow
579        return ConstantInt::get(C1->getType(),
580                                CI1->getSExtValue() / CI2->getSExtValue());
581      case Instruction::URem:
582        if (C2->isNullValue()) return 0;         // X / 0 -> can't fold
583        return ConstantInt::get(C1->getType(), C1Val % C2Val);
584      case Instruction::SRem:
585        if (CI2->isNullValue()) return 0;        // X % 0 -> can't fold
586        if (CI2->isAllOnesValue() &&
587            (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
588              (CI1->getSExtValue() == INT64_MIN)) ||
589             (CI1->getSExtValue() == -CI1->getSExtValue())))
590          return 0;                              // MIN_INT % -1 -> overflow
591        return ConstantInt::get(C1->getType(),
592                                CI1->getSExtValue() % CI2->getSExtValue());
593      case Instruction::And:
594        return ConstantInt::get(C1->getType(), C1Val & C2Val);
595      case Instruction::Or:
596        return ConstantInt::get(C1->getType(), C1Val | C2Val);
597      case Instruction::Xor:
598        return ConstantInt::get(C1->getType(), C1Val ^ C2Val);
599      case Instruction::Shl:
600        return ConstantInt::get(C1->getType(), C1Val << C2Val);
601      case Instruction::LShr:
602        return ConstantInt::get(C1->getType(), C1Val >> C2Val);
603      case Instruction::AShr:
604        return ConstantInt::get(C1->getType(),
605                                CI1->getSExtValue() >> C2Val);
606      }
607    }
608  } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
609    if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
610      double C1Val = CFP1->getValue();
611      double C2Val = CFP2->getValue();
612      switch (Opcode) {
613      default:
614        break;
615      case Instruction::Add:
616        return ConstantFP::get(CFP1->getType(), C1Val + C2Val);
617      case Instruction::Sub:
618        return ConstantFP::get(CFP1->getType(), C1Val - C2Val);
619      case Instruction::Mul:
620        return ConstantFP::get(CFP1->getType(), C1Val * C2Val);
621      case Instruction::FDiv:
622        if (CFP2->isExactlyValue(0.0))
623          return ConstantFP::get(CFP1->getType(),
624                                 std::numeric_limits<double>::infinity());
625        if (CFP2->isExactlyValue(-0.0))
626          return ConstantFP::get(CFP1->getType(),
627                                 -std::numeric_limits<double>::infinity());
628        return ConstantFP::get(CFP1->getType(), C1Val / C2Val);
629      case Instruction::FRem:
630        if (CFP2->isNullValue())
631          return 0;
632        return ConstantFP::get(CFP1->getType(), std::fmod(C1Val, C2Val));
633      }
634    }
635  } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
636    if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
637      switch (Opcode) {
638        default:
639          break;
640        case Instruction::Add:
641          return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
642        case Instruction::Sub:
643          return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
644        case Instruction::Mul:
645          return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
646        case Instruction::UDiv:
647          return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
648        case Instruction::SDiv:
649          return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
650        case Instruction::FDiv:
651          return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
652        case Instruction::URem:
653          return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
654        case Instruction::SRem:
655          return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
656        case Instruction::FRem:
657          return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
658        case Instruction::And:
659          return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
660        case Instruction::Or:
661          return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
662        case Instruction::Xor:
663          return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
664      }
665    }
666  }
667
668  // We don't know how to fold this
669  return 0;
670}
671
672/// isZeroSizedType - This type is zero sized if its an array or structure of
673/// zero sized types.  The only leaf zero sized type is an empty structure.
674static bool isMaybeZeroSizedType(const Type *Ty) {
675  if (isa<OpaqueType>(Ty)) return true;  // Can't say.
676  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
677
678    // If all of elements have zero size, this does too.
679    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
680      if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
681    return true;
682
683  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
684    return isMaybeZeroSizedType(ATy->getElementType());
685  }
686  return false;
687}
688
689/// IdxCompare - Compare the two constants as though they were getelementptr
690/// indices.  This allows coersion of the types to be the same thing.
691///
692/// If the two constants are the "same" (after coersion), return 0.  If the
693/// first is less than the second, return -1, if the second is less than the
694/// first, return 1.  If the constants are not integral, return -2.
695///
696static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
697  if (C1 == C2) return 0;
698
699  // Ok, we found a different index.  If they are not ConstantInt, we can't do
700  // anything with them.
701  if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
702    return -2; // don't know!
703
704  // Ok, we have two differing integer indices.  Sign extend them to be the same
705  // type.  Long is always big enough, so we use it.
706  if (C1->getType() != Type::Int64Ty)
707    C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
708
709  if (C2->getType() != Type::Int64Ty)
710    C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
711
712  if (C1 == C2) return 0;  // They are equal
713
714  // If the type being indexed over is really just a zero sized type, there is
715  // no pointer difference being made here.
716  if (isMaybeZeroSizedType(ElTy))
717    return -2; // dunno.
718
719  // If they are really different, now that they are the same type, then we
720  // found a difference!
721  if (cast<ConstantInt>(C1)->getSExtValue() <
722      cast<ConstantInt>(C2)->getSExtValue())
723    return -1;
724  else
725    return 1;
726}
727
728/// evaluateFCmpRelation - This function determines if there is anything we can
729/// decide about the two constants provided.  This doesn't need to handle simple
730/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
731/// If we can determine that the two constants have a particular relation to
732/// each other, we should return the corresponding FCmpInst predicate,
733/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
734/// ConstantFoldCompareInstruction.
735///
736/// To simplify this code we canonicalize the relation so that the first
737/// operand is always the most "complex" of the two.  We consider ConstantFP
738/// to be the simplest, and ConstantExprs to be the most complex.
739static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
740                                                const Constant *V2) {
741  assert(V1->getType() == V2->getType() &&
742         "Cannot compare values of different types!");
743  // Handle degenerate case quickly
744  if (V1 == V2) return FCmpInst::FCMP_OEQ;
745
746  if (!isa<ConstantExpr>(V1)) {
747    if (!isa<ConstantExpr>(V2)) {
748      // We distilled thisUse the standard constant folder for a few cases
749      ConstantInt *R = 0;
750      Constant *C1 = const_cast<Constant*>(V1);
751      Constant *C2 = const_cast<Constant*>(V2);
752      R = dyn_cast<ConstantInt>(
753                             ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
754      if (R && R->getZExtValue())
755        return FCmpInst::FCMP_OEQ;
756      R = dyn_cast<ConstantInt>(
757                             ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
758      if (R && R->getZExtValue())
759        return FCmpInst::FCMP_OLT;
760      R = dyn_cast<ConstantInt>(
761                             ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
762      if (R && R->getZExtValue())
763        return FCmpInst::FCMP_OGT;
764
765      // Nothing more we can do
766      return FCmpInst::BAD_FCMP_PREDICATE;
767    }
768
769    // If the first operand is simple and second is ConstantExpr, swap operands.
770    FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
771    if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
772      return FCmpInst::getSwappedPredicate(SwappedRelation);
773  } else {
774    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
775    // constantexpr or a simple constant.
776    const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
777    switch (CE1->getOpcode()) {
778    case Instruction::FPTrunc:
779    case Instruction::FPExt:
780    case Instruction::UIToFP:
781    case Instruction::SIToFP:
782      // We might be able to do something with these but we don't right now.
783      break;
784    default:
785      break;
786    }
787  }
788  // There are MANY other foldings that we could perform here.  They will
789  // probably be added on demand, as they seem needed.
790  return FCmpInst::BAD_FCMP_PREDICATE;
791}
792
793/// evaluateICmpRelation - This function determines if there is anything we can
794/// decide about the two constants provided.  This doesn't need to handle simple
795/// things like integer comparisons, but should instead handle ConstantExprs
796/// and GlobalValues.  If we can determine that the two constants have a
797/// particular relation to each other, we should return the corresponding ICmp
798/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
799///
800/// To simplify this code we canonicalize the relation so that the first
801/// operand is always the most "complex" of the two.  We consider simple
802/// constants (like ConstantInt) to be the simplest, followed by
803/// GlobalValues, followed by ConstantExpr's (the most complex).
804///
805static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
806                                                const Constant *V2,
807                                                bool isSigned) {
808  assert(V1->getType() == V2->getType() &&
809         "Cannot compare different types of values!");
810  if (V1 == V2) return ICmpInst::ICMP_EQ;
811
812  if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
813    if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
814      // We distilled this down to a simple case, use the standard constant
815      // folder.
816      ConstantInt *R = 0;
817      Constant *C1 = const_cast<Constant*>(V1);
818      Constant *C2 = const_cast<Constant*>(V2);
819      ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
820      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
821      if (R && R->getZExtValue())
822        return pred;
823      pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
824      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
825      if (R && R->getZExtValue())
826        return pred;
827      pred = isSigned ?  ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
828      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
829      if (R && R->getZExtValue())
830        return pred;
831
832      // If we couldn't figure it out, bail.
833      return ICmpInst::BAD_ICMP_PREDICATE;
834    }
835
836    // If the first operand is simple, swap operands.
837    ICmpInst::Predicate SwappedRelation =
838      evaluateICmpRelation(V2, V1, isSigned);
839    if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
840      return ICmpInst::getSwappedPredicate(SwappedRelation);
841
842  } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
843    if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
844      ICmpInst::Predicate SwappedRelation =
845        evaluateICmpRelation(V2, V1, isSigned);
846      if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
847        return ICmpInst::getSwappedPredicate(SwappedRelation);
848      else
849        return ICmpInst::BAD_ICMP_PREDICATE;
850    }
851
852    // Now we know that the RHS is a GlobalValue or simple constant,
853    // which (since the types must match) means that it's a ConstantPointerNull.
854    if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
855      if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
856        return ICmpInst::ICMP_NE;
857    } else {
858      // GlobalVals can never be null.
859      assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
860      if (!CPR1->hasExternalWeakLinkage())
861        return ICmpInst::ICMP_NE;
862    }
863  } else {
864    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
865    // constantexpr, a CPR, or a simple constant.
866    const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
867    const Constant *CE1Op0 = CE1->getOperand(0);
868
869    switch (CE1->getOpcode()) {
870    case Instruction::Trunc:
871    case Instruction::FPTrunc:
872    case Instruction::FPExt:
873    case Instruction::FPToUI:
874    case Instruction::FPToSI:
875      break; // We can't evaluate floating point casts or truncations.
876
877    case Instruction::UIToFP:
878    case Instruction::SIToFP:
879    case Instruction::IntToPtr:
880    case Instruction::BitCast:
881    case Instruction::ZExt:
882    case Instruction::SExt:
883    case Instruction::PtrToInt:
884      // If the cast is not actually changing bits, and the second operand is a
885      // null pointer, do the comparison with the pre-casted value.
886      if (V2->isNullValue() &&
887          (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
888        bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
889          (CE1->getOpcode() == Instruction::SExt ? true :
890           (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
891        return evaluateICmpRelation(
892            CE1Op0, Constant::getNullValue(CE1Op0->getType()), sgnd);
893      }
894
895      // If the dest type is a pointer type, and the RHS is a constantexpr cast
896      // from the same type as the src of the LHS, evaluate the inputs.  This is
897      // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
898      // which happens a lot in compilers with tagged integers.
899      if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
900        if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
901            CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
902            CE1->getOperand(0)->getType()->isInteger()) {
903          bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
904            (CE1->getOpcode() == Instruction::SExt ? true :
905             (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
906          return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
907              sgnd);
908        }
909      break;
910
911    case Instruction::GetElementPtr:
912      // Ok, since this is a getelementptr, we know that the constant has a
913      // pointer type.  Check the various cases.
914      if (isa<ConstantPointerNull>(V2)) {
915        // If we are comparing a GEP to a null pointer, check to see if the base
916        // of the GEP equals the null pointer.
917        if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
918          if (GV->hasExternalWeakLinkage())
919            // Weak linkage GVals could be zero or not. We're comparing that
920            // to null pointer so its greater-or-equal
921            return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
922          else
923            // If its not weak linkage, the GVal must have a non-zero address
924            // so the result is greater-than
925            return isSigned ? ICmpInst::ICMP_SGT :  ICmpInst::ICMP_UGT;
926        } else if (isa<ConstantPointerNull>(CE1Op0)) {
927          // If we are indexing from a null pointer, check to see if we have any
928          // non-zero indices.
929          for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
930            if (!CE1->getOperand(i)->isNullValue())
931              // Offsetting from null, must not be equal.
932              return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
933          // Only zero indexes from null, must still be zero.
934          return ICmpInst::ICMP_EQ;
935        }
936        // Otherwise, we can't really say if the first operand is null or not.
937      } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
938        if (isa<ConstantPointerNull>(CE1Op0)) {
939          if (CPR2->hasExternalWeakLinkage())
940            // Weak linkage GVals could be zero or not. We're comparing it to
941            // a null pointer, so its less-or-equal
942            return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
943          else
944            // If its not weak linkage, the GVal must have a non-zero address
945            // so the result is less-than
946            return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
947        } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
948          if (CPR1 == CPR2) {
949            // If this is a getelementptr of the same global, then it must be
950            // different.  Because the types must match, the getelementptr could
951            // only have at most one index, and because we fold getelementptr's
952            // with a single zero index, it must be nonzero.
953            assert(CE1->getNumOperands() == 2 &&
954                   !CE1->getOperand(1)->isNullValue() &&
955                   "Suprising getelementptr!");
956            return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
957          } else {
958            // If they are different globals, we don't know what the value is,
959            // but they can't be equal.
960            return ICmpInst::ICMP_NE;
961          }
962        }
963      } else {
964        const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
965        const Constant *CE2Op0 = CE2->getOperand(0);
966
967        // There are MANY other foldings that we could perform here.  They will
968        // probably be added on demand, as they seem needed.
969        switch (CE2->getOpcode()) {
970        default: break;
971        case Instruction::GetElementPtr:
972          // By far the most common case to handle is when the base pointers are
973          // obviously to the same or different globals.
974          if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
975            if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
976              return ICmpInst::ICMP_NE;
977            // Ok, we know that both getelementptr instructions are based on the
978            // same global.  From this, we can precisely determine the relative
979            // ordering of the resultant pointers.
980            unsigned i = 1;
981
982            // Compare all of the operands the GEP's have in common.
983            gep_type_iterator GTI = gep_type_begin(CE1);
984            for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
985                 ++i, ++GTI)
986              switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
987                                 GTI.getIndexedType())) {
988              case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
989              case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
990              case -2: return ICmpInst::BAD_ICMP_PREDICATE;
991              }
992
993            // Ok, we ran out of things they have in common.  If any leftovers
994            // are non-zero then we have a difference, otherwise we are equal.
995            for (; i < CE1->getNumOperands(); ++i)
996              if (!CE1->getOperand(i)->isNullValue())
997                if (isa<ConstantInt>(CE1->getOperand(i)))
998                  return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
999                else
1000                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1001
1002            for (; i < CE2->getNumOperands(); ++i)
1003              if (!CE2->getOperand(i)->isNullValue())
1004                if (isa<ConstantInt>(CE2->getOperand(i)))
1005                  return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1006                else
1007                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1008            return ICmpInst::ICMP_EQ;
1009          }
1010        }
1011      }
1012    default:
1013      break;
1014    }
1015  }
1016
1017  return ICmpInst::BAD_ICMP_PREDICATE;
1018}
1019
1020Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1021                                               const Constant *C1,
1022                                               const Constant *C2) {
1023
1024  // Handle some degenerate cases first
1025  if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1026    return UndefValue::get(Type::Int1Ty);
1027
1028  // icmp eq/ne(null,GV) -> false/true
1029  if (C1->isNullValue()) {
1030    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1031      if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1032        if (pred == ICmpInst::ICMP_EQ)
1033          return ConstantInt::getFalse();
1034        else if (pred == ICmpInst::ICMP_NE)
1035          return ConstantInt::getTrue();
1036  // icmp eq/ne(GV,null) -> false/true
1037  } else if (C2->isNullValue()) {
1038    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1039      if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1040        if (pred == ICmpInst::ICMP_EQ)
1041          return ConstantInt::getFalse();
1042        else if (pred == ICmpInst::ICMP_NE)
1043          return ConstantInt::getTrue();
1044  }
1045
1046  if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1047    if (ICmpInst::isSignedPredicate(ICmpInst::Predicate(pred))) {
1048      int64_t V1 = cast<ConstantInt>(C1)->getSExtValue();
1049      int64_t V2 = cast<ConstantInt>(C2)->getSExtValue();
1050      switch (pred) {
1051      default: assert(0 && "Invalid ICmp Predicate"); return 0;
1052      case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1 <  V2);
1053      case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1 >  V2);
1054      case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1 <= V2);
1055      case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1 >= V2);
1056      }
1057    } else {
1058      uint64_t V1 = cast<ConstantInt>(C1)->getZExtValue();
1059      uint64_t V2 = cast<ConstantInt>(C2)->getZExtValue();
1060      switch (pred) {
1061      default: assert(0 && "Invalid ICmp Predicate"); return 0;
1062      case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1063      case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1064      case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1 <  V2);
1065      case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1 >  V2);
1066      case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1 <= V2);
1067      case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1 >= V2);
1068      }
1069    }
1070  } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1071    double C1Val = cast<ConstantFP>(C1)->getValue();
1072    double C2Val = cast<ConstantFP>(C2)->getValue();
1073    switch (pred) {
1074    default: assert(0 && "Invalid FCmp Predicate"); return 0;
1075    case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1076    case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue();
1077    case FCmpInst::FCMP_UNO:
1078      return ConstantInt::get(Type::Int1Ty, C1Val != C1Val || C2Val != C2Val);
1079    case FCmpInst::FCMP_ORD:
1080      return ConstantInt::get(Type::Int1Ty, C1Val == C1Val && C2Val == C2Val);
1081    case FCmpInst::FCMP_UEQ:
1082      if (C1Val != C1Val || C2Val != C2Val)
1083        return ConstantInt::getTrue();
1084      /* FALL THROUGH */
1085    case FCmpInst::FCMP_OEQ:
1086      return ConstantInt::get(Type::Int1Ty, C1Val == C2Val);
1087    case FCmpInst::FCMP_UNE:
1088      if (C1Val != C1Val || C2Val != C2Val)
1089        return ConstantInt::getTrue();
1090      /* FALL THROUGH */
1091    case FCmpInst::FCMP_ONE:
1092      return ConstantInt::get(Type::Int1Ty, C1Val != C2Val);
1093    case FCmpInst::FCMP_ULT:
1094      if (C1Val != C1Val || C2Val != C2Val)
1095        return ConstantInt::getTrue();
1096      /* FALL THROUGH */
1097    case FCmpInst::FCMP_OLT:
1098      return ConstantInt::get(Type::Int1Ty, C1Val < C2Val);
1099    case FCmpInst::FCMP_UGT:
1100      if (C1Val != C1Val || C2Val != C2Val)
1101        return ConstantInt::getTrue();
1102      /* FALL THROUGH */
1103    case FCmpInst::FCMP_OGT:
1104      return ConstantInt::get(Type::Int1Ty, C1Val > C2Val);
1105    case FCmpInst::FCMP_ULE:
1106      if (C1Val != C1Val || C2Val != C2Val)
1107        return ConstantInt::getTrue();
1108      /* FALL THROUGH */
1109    case FCmpInst::FCMP_OLE:
1110      return ConstantInt::get(Type::Int1Ty, C1Val <= C2Val);
1111    case FCmpInst::FCMP_UGE:
1112      if (C1Val != C1Val || C2Val != C2Val)
1113        return ConstantInt::getTrue();
1114      /* FALL THROUGH */
1115    case FCmpInst::FCMP_OGE:
1116      return ConstantInt::get(Type::Int1Ty, C1Val >= C2Val);
1117    }
1118  } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1119    if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1120      if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1121        for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1122          Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1123              const_cast<Constant*>(CP1->getOperand(i)),
1124              const_cast<Constant*>(CP2->getOperand(i)));
1125          if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1126            return CB;
1127        }
1128        // Otherwise, could not decide from any element pairs.
1129        return 0;
1130      } else if (pred == ICmpInst::ICMP_EQ) {
1131        for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1132          Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1133              const_cast<Constant*>(CP1->getOperand(i)),
1134              const_cast<Constant*>(CP2->getOperand(i)));
1135          if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1136            return CB;
1137        }
1138        // Otherwise, could not decide from any element pairs.
1139        return 0;
1140      }
1141    }
1142  }
1143
1144  if (C1->getType()->isFloatingPoint()) {
1145    switch (evaluateFCmpRelation(C1, C2)) {
1146    default: assert(0 && "Unknown relation!");
1147    case FCmpInst::FCMP_UNO:
1148    case FCmpInst::FCMP_ORD:
1149    case FCmpInst::FCMP_UEQ:
1150    case FCmpInst::FCMP_UNE:
1151    case FCmpInst::FCMP_ULT:
1152    case FCmpInst::FCMP_UGT:
1153    case FCmpInst::FCMP_ULE:
1154    case FCmpInst::FCMP_UGE:
1155    case FCmpInst::FCMP_TRUE:
1156    case FCmpInst::FCMP_FALSE:
1157    case FCmpInst::BAD_FCMP_PREDICATE:
1158      break; // Couldn't determine anything about these constants.
1159    case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1160      return ConstantInt::get(Type::Int1Ty,
1161          pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1162          pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1163          pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1164    case FCmpInst::FCMP_OLT: // We know that C1 < C2
1165      return ConstantInt::get(Type::Int1Ty,
1166          pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1167          pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1168          pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1169    case FCmpInst::FCMP_OGT: // We know that C1 > C2
1170      return ConstantInt::get(Type::Int1Ty,
1171          pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1172          pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1173          pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1174    case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1175      // We can only partially decide this relation.
1176      if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1177        return ConstantInt::getFalse();
1178      if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1179        return ConstantInt::getTrue();
1180      break;
1181    case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1182      // We can only partially decide this relation.
1183      if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1184        return ConstantInt::getFalse();
1185      if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1186        return ConstantInt::getTrue();
1187      break;
1188    case ICmpInst::ICMP_NE: // We know that C1 != C2
1189      // We can only partially decide this relation.
1190      if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1191        return ConstantInt::getFalse();
1192      if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1193        return ConstantInt::getTrue();
1194      break;
1195    }
1196  } else {
1197    // Evaluate the relation between the two constants, per the predicate.
1198    switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1199    default: assert(0 && "Unknown relational!");
1200    case ICmpInst::BAD_ICMP_PREDICATE:
1201      break;  // Couldn't determine anything about these constants.
1202    case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1203      // If we know the constants are equal, we can decide the result of this
1204      // computation precisely.
1205      return ConstantInt::get(Type::Int1Ty,
1206                              pred == ICmpInst::ICMP_EQ  ||
1207                              pred == ICmpInst::ICMP_ULE ||
1208                              pred == ICmpInst::ICMP_SLE ||
1209                              pred == ICmpInst::ICMP_UGE ||
1210                              pred == ICmpInst::ICMP_SGE);
1211    case ICmpInst::ICMP_ULT:
1212      // If we know that C1 < C2, we can decide the result of this computation
1213      // precisely.
1214      return ConstantInt::get(Type::Int1Ty,
1215                              pred == ICmpInst::ICMP_ULT ||
1216                              pred == ICmpInst::ICMP_NE  ||
1217                              pred == ICmpInst::ICMP_ULE);
1218    case ICmpInst::ICMP_SLT:
1219      // If we know that C1 < C2, we can decide the result of this computation
1220      // precisely.
1221      return ConstantInt::get(Type::Int1Ty,
1222                              pred == ICmpInst::ICMP_SLT ||
1223                              pred == ICmpInst::ICMP_NE  ||
1224                              pred == ICmpInst::ICMP_SLE);
1225    case ICmpInst::ICMP_UGT:
1226      // If we know that C1 > C2, we can decide the result of this computation
1227      // precisely.
1228      return ConstantInt::get(Type::Int1Ty,
1229                              pred == ICmpInst::ICMP_UGT ||
1230                              pred == ICmpInst::ICMP_NE  ||
1231                              pred == ICmpInst::ICMP_UGE);
1232    case ICmpInst::ICMP_SGT:
1233      // If we know that C1 > C2, we can decide the result of this computation
1234      // precisely.
1235      return ConstantInt::get(Type::Int1Ty,
1236                              pred == ICmpInst::ICMP_SGT ||
1237                              pred == ICmpInst::ICMP_NE  ||
1238                              pred == ICmpInst::ICMP_SGE);
1239    case ICmpInst::ICMP_ULE:
1240      // If we know that C1 <= C2, we can only partially decide this relation.
1241      if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1242      if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1243      break;
1244    case ICmpInst::ICMP_SLE:
1245      // If we know that C1 <= C2, we can only partially decide this relation.
1246      if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1247      if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1248      break;
1249
1250    case ICmpInst::ICMP_UGE:
1251      // If we know that C1 >= C2, we can only partially decide this relation.
1252      if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1253      if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1254      break;
1255    case ICmpInst::ICMP_SGE:
1256      // If we know that C1 >= C2, we can only partially decide this relation.
1257      if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1258      if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1259      break;
1260
1261    case ICmpInst::ICMP_NE:
1262      // If we know that C1 != C2, we can only partially decide this relation.
1263      if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1264      if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1265      break;
1266    }
1267
1268    if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1269      // If C2 is a constant expr and C1 isn't, flop them around and fold the
1270      // other way if possible.
1271      switch (pred) {
1272      case ICmpInst::ICMP_EQ:
1273      case ICmpInst::ICMP_NE:
1274        // No change of predicate required.
1275        return ConstantFoldCompareInstruction(pred, C2, C1);
1276
1277      case ICmpInst::ICMP_ULT:
1278      case ICmpInst::ICMP_SLT:
1279      case ICmpInst::ICMP_UGT:
1280      case ICmpInst::ICMP_SGT:
1281      case ICmpInst::ICMP_ULE:
1282      case ICmpInst::ICMP_SLE:
1283      case ICmpInst::ICMP_UGE:
1284      case ICmpInst::ICMP_SGE:
1285        // Change the predicate as necessary to swap the operands.
1286        pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1287        return ConstantFoldCompareInstruction(pred, C2, C1);
1288
1289      default:  // These predicates cannot be flopped around.
1290        break;
1291      }
1292    }
1293  }
1294  return 0;
1295}
1296
1297Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1298                                          Constant* const *Idxs,
1299                                          unsigned NumIdx) {
1300  if (NumIdx == 0 ||
1301      (NumIdx == 1 && Idxs[0]->isNullValue()))
1302    return const_cast<Constant*>(C);
1303
1304  if (isa<UndefValue>(C)) {
1305    const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1306                                                       (Value**)Idxs, NumIdx,
1307                                                       true);
1308    assert(Ty != 0 && "Invalid indices for GEP!");
1309    return UndefValue::get(PointerType::get(Ty));
1310  }
1311
1312  Constant *Idx0 = Idxs[0];
1313  if (C->isNullValue()) {
1314    bool isNull = true;
1315    for (unsigned i = 0, e = NumIdx; i != e; ++i)
1316      if (!Idxs[i]->isNullValue()) {
1317        isNull = false;
1318        break;
1319      }
1320    if (isNull) {
1321      const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1322                                                         (Value**)Idxs, NumIdx,
1323                                                         true);
1324      assert(Ty != 0 && "Invalid indices for GEP!");
1325      return ConstantPointerNull::get(PointerType::get(Ty));
1326    }
1327  }
1328
1329  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1330    // Combine Indices - If the source pointer to this getelementptr instruction
1331    // is a getelementptr instruction, combine the indices of the two
1332    // getelementptr instructions into a single instruction.
1333    //
1334    if (CE->getOpcode() == Instruction::GetElementPtr) {
1335      const Type *LastTy = 0;
1336      for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1337           I != E; ++I)
1338        LastTy = *I;
1339
1340      if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1341        SmallVector<Value*, 16> NewIndices;
1342        NewIndices.reserve(NumIdx + CE->getNumOperands());
1343        for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1344          NewIndices.push_back(CE->getOperand(i));
1345
1346        // Add the last index of the source with the first index of the new GEP.
1347        // Make sure to handle the case when they are actually different types.
1348        Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1349        // Otherwise it must be an array.
1350        if (!Idx0->isNullValue()) {
1351          const Type *IdxTy = Combined->getType();
1352          if (IdxTy != Idx0->getType()) {
1353            Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1354            Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1355                                                          Type::Int64Ty);
1356            Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1357          } else {
1358            Combined =
1359              ConstantExpr::get(Instruction::Add, Idx0, Combined);
1360          }
1361        }
1362
1363        NewIndices.push_back(Combined);
1364        NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1365        return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1366                                              NewIndices.size());
1367      }
1368    }
1369
1370    // Implement folding of:
1371    //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1372    //                        long 0, long 0)
1373    // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1374    //
1375    if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue())
1376      if (const PointerType *SPT =
1377          dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1378        if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1379          if (const ArrayType *CAT =
1380        dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1381            if (CAT->getElementType() == SAT->getElementType())
1382              return ConstantExpr::getGetElementPtr(
1383                      (Constant*)CE->getOperand(0), Idxs, NumIdx);
1384  }
1385  return 0;
1386}
1387
1388