SimpleSValBuilder.cpp revision 14d20b1dff6370f76279fcfb0fd780e2e5eb57bb
1// SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
16
17using namespace clang;
18using namespace ento;
19
20namespace {
21class SimpleSValBuilder : public SValBuilder {
22protected:
23  virtual SVal dispatchCast(SVal val, QualType castTy);
24  virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy);
25  virtual SVal evalCastFromLoc(Loc val, QualType castTy);
26
27public:
28  SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
29                    ProgramStateManager &stateMgr)
30                    : SValBuilder(alloc, context, stateMgr) {}
31  virtual ~SimpleSValBuilder() {}
32
33  virtual SVal evalMinus(NonLoc val);
34  virtual SVal evalComplement(NonLoc val);
35  virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
36                           NonLoc lhs, NonLoc rhs, QualType resultTy);
37  virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
38                           Loc lhs, Loc rhs, QualType resultTy);
39  virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
40                           Loc lhs, NonLoc rhs, QualType resultTy);
41
42  /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
43  ///  (integer) value, that value is returned. Otherwise, returns NULL.
44  virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V);
45
46  SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
47                     const llvm::APSInt &RHS, QualType resultTy);
48};
49} // end anonymous namespace
50
51SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
52                                           ASTContext &context,
53                                           ProgramStateManager &stateMgr) {
54  return new SimpleSValBuilder(alloc, context, stateMgr);
55}
56
57//===----------------------------------------------------------------------===//
58// Transfer function for Casts.
59//===----------------------------------------------------------------------===//
60
61SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
62  assert(isa<Loc>(&Val) || isa<NonLoc>(&Val));
63  return isa<Loc>(Val) ? evalCastFromLoc(cast<Loc>(Val), CastTy)
64                       : evalCastFromNonLoc(cast<NonLoc>(Val), CastTy);
65}
66
67SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
68
69  bool isLocType = Loc::isLocType(castTy);
70
71  if (nonloc::LocAsInteger *LI = dyn_cast<nonloc::LocAsInteger>(&val)) {
72    if (isLocType)
73      return LI->getLoc();
74
75    // FIXME: Correctly support promotions/truncations.
76    unsigned castSize = Context.getTypeSize(castTy);
77    if (castSize == LI->getNumBits())
78      return val;
79    return makeLocAsInteger(LI->getLoc(), castSize);
80  }
81
82  if (const SymExpr *se = val.getAsSymbolicExpression()) {
83    QualType T = Context.getCanonicalType(se->getType(Context));
84    // If types are the same or both are integers, ignore the cast.
85    // FIXME: Remove this hack when we support symbolic truncation/extension.
86    // HACK: If both castTy and T are integers, ignore the cast.  This is
87    // not a permanent solution.  Eventually we want to precisely handle
88    // extension/truncation of symbolic integers.  This prevents us from losing
89    // precision when we assign 'x = y' and 'y' is symbolic and x and y are
90    // different integer types.
91   if (haveSameType(T, castTy))
92      return val;
93
94    if (!isLocType)
95      return makeNonLoc(se, T, castTy);
96    return UnknownVal();
97  }
98
99  // If value is a non integer constant, produce unknown.
100  if (!isa<nonloc::ConcreteInt>(val))
101    return UnknownVal();
102
103  // Only handle casts from integers to integers - if val is an integer constant
104  // being cast to a non integer type, produce unknown.
105  if (!isLocType && !castTy->isIntegerType())
106    return UnknownVal();
107
108  llvm::APSInt i = cast<nonloc::ConcreteInt>(val).getValue();
109  i.setIsUnsigned(castTy->isUnsignedIntegerOrEnumerationType() ||
110                  Loc::isLocType(castTy));
111  i = i.extOrTrunc(Context.getTypeSize(castTy));
112
113  if (isLocType)
114    return makeIntLocVal(i);
115  else
116    return makeIntVal(i);
117}
118
119SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
120
121  // Casts from pointers -> pointers, just return the lval.
122  //
123  // Casts from pointers -> references, just return the lval.  These
124  //   can be introduced by the frontend for corner cases, e.g
125  //   casting from va_list* to __builtin_va_list&.
126  //
127  if (Loc::isLocType(castTy) || castTy->isReferenceType())
128    return val;
129
130  // FIXME: Handle transparent unions where a value can be "transparently"
131  //  lifted into a union type.
132  if (castTy->isUnionType())
133    return UnknownVal();
134
135  if (castTy->isIntegerType()) {
136    unsigned BitWidth = Context.getTypeSize(castTy);
137
138    if (!isa<loc::ConcreteInt>(val))
139      return makeLocAsInteger(val, BitWidth);
140
141    llvm::APSInt i = cast<loc::ConcreteInt>(val).getValue();
142    i.setIsUnsigned(castTy->isUnsignedIntegerOrEnumerationType() ||
143                    Loc::isLocType(castTy));
144    i = i.extOrTrunc(BitWidth);
145    return makeIntVal(i);
146  }
147
148  // All other cases: return 'UnknownVal'.  This includes casting pointers
149  // to floats, which is probably badness it itself, but this is a good
150  // intermediate solution until we do something better.
151  return UnknownVal();
152}
153
154//===----------------------------------------------------------------------===//
155// Transfer function for unary operators.
156//===----------------------------------------------------------------------===//
157
158SVal SimpleSValBuilder::evalMinus(NonLoc val) {
159  switch (val.getSubKind()) {
160  case nonloc::ConcreteIntKind:
161    return cast<nonloc::ConcreteInt>(val).evalMinus(*this);
162  default:
163    return UnknownVal();
164  }
165}
166
167SVal SimpleSValBuilder::evalComplement(NonLoc X) {
168  switch (X.getSubKind()) {
169  case nonloc::ConcreteIntKind:
170    return cast<nonloc::ConcreteInt>(X).evalComplement(*this);
171  default:
172    return UnknownVal();
173  }
174}
175
176//===----------------------------------------------------------------------===//
177// Transfer function for binary operators.
178//===----------------------------------------------------------------------===//
179
180static BinaryOperator::Opcode NegateComparison(BinaryOperator::Opcode op) {
181  switch (op) {
182  default:
183    llvm_unreachable("Invalid opcode.");
184  case BO_LT: return BO_GE;
185  case BO_GT: return BO_LE;
186  case BO_LE: return BO_GT;
187  case BO_GE: return BO_LT;
188  case BO_EQ: return BO_NE;
189  case BO_NE: return BO_EQ;
190  }
191}
192
193static BinaryOperator::Opcode ReverseComparison(BinaryOperator::Opcode op) {
194  switch (op) {
195  default:
196    llvm_unreachable("Invalid opcode.");
197  case BO_LT: return BO_GT;
198  case BO_GT: return BO_LT;
199  case BO_LE: return BO_GE;
200  case BO_GE: return BO_LE;
201  case BO_EQ:
202  case BO_NE:
203    return op;
204  }
205}
206
207SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
208                                    BinaryOperator::Opcode op,
209                                    const llvm::APSInt &RHS,
210                                    QualType resultTy) {
211  bool isIdempotent = false;
212
213  // Check for a few special cases with known reductions first.
214  switch (op) {
215  default:
216    // We can't reduce this case; just treat it normally.
217    break;
218  case BO_Mul:
219    // a*0 and a*1
220    if (RHS == 0)
221      return makeIntVal(0, resultTy);
222    else if (RHS == 1)
223      isIdempotent = true;
224    break;
225  case BO_Div:
226    // a/0 and a/1
227    if (RHS == 0)
228      // This is also handled elsewhere.
229      return UndefinedVal();
230    else if (RHS == 1)
231      isIdempotent = true;
232    break;
233  case BO_Rem:
234    // a%0 and a%1
235    if (RHS == 0)
236      // This is also handled elsewhere.
237      return UndefinedVal();
238    else if (RHS == 1)
239      return makeIntVal(0, resultTy);
240    break;
241  case BO_Add:
242  case BO_Sub:
243  case BO_Shl:
244  case BO_Shr:
245  case BO_Xor:
246    // a+0, a-0, a<<0, a>>0, a^0
247    if (RHS == 0)
248      isIdempotent = true;
249    break;
250  case BO_And:
251    // a&0 and a&(~0)
252    if (RHS == 0)
253      return makeIntVal(0, resultTy);
254    else if (RHS.isAllOnesValue())
255      isIdempotent = true;
256    break;
257  case BO_Or:
258    // a|0 and a|(~0)
259    if (RHS == 0)
260      isIdempotent = true;
261    else if (RHS.isAllOnesValue()) {
262      const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
263      return nonloc::ConcreteInt(Result);
264    }
265    break;
266  }
267
268  // Idempotent ops (like a*1) can still change the type of an expression.
269  // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
270  // dirty work.
271  if (isIdempotent)
272      return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
273
274  // If we reach this point, the expression cannot be simplified.
275  // Make a SymbolVal for the entire expression.
276  return makeNonLoc(LHS, op, RHS, resultTy);
277}
278
279SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
280                                  BinaryOperator::Opcode op,
281                                  NonLoc lhs, NonLoc rhs,
282                                  QualType resultTy)  {
283  NonLoc InputLHS = lhs;
284  NonLoc InputRHS = rhs;
285
286  // Handle trivial case where left-side and right-side are the same.
287  if (lhs == rhs)
288    switch (op) {
289      default:
290        break;
291      case BO_EQ:
292      case BO_LE:
293      case BO_GE:
294        return makeTruthVal(true, resultTy);
295      case BO_LT:
296      case BO_GT:
297      case BO_NE:
298        return makeTruthVal(false, resultTy);
299      case BO_Xor:
300      case BO_Sub:
301        return makeIntVal(0, resultTy);
302      case BO_Or:
303      case BO_And:
304        return evalCastFromNonLoc(lhs, resultTy);
305    }
306
307  while (1) {
308    switch (lhs.getSubKind()) {
309    default:
310      return makeSymExprValNN(state, op, lhs, rhs, resultTy);
311    case nonloc::LocAsIntegerKind: {
312      Loc lhsL = cast<nonloc::LocAsInteger>(lhs).getLoc();
313      switch (rhs.getSubKind()) {
314        case nonloc::LocAsIntegerKind:
315          return evalBinOpLL(state, op, lhsL,
316                             cast<nonloc::LocAsInteger>(rhs).getLoc(),
317                             resultTy);
318        case nonloc::ConcreteIntKind: {
319          // Transform the integer into a location and compare.
320          llvm::APSInt i = cast<nonloc::ConcreteInt>(rhs).getValue();
321          i.setIsUnsigned(true);
322          i = i.extOrTrunc(Context.getTypeSize(Context.VoidPtrTy));
323          return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
324        }
325        default:
326          switch (op) {
327            case BO_EQ:
328              return makeTruthVal(false, resultTy);
329            case BO_NE:
330              return makeTruthVal(true, resultTy);
331            default:
332              // This case also handles pointer arithmetic.
333              return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
334          }
335      }
336    }
337    case nonloc::ConcreteIntKind: {
338      const nonloc::ConcreteInt& lhsInt = cast<nonloc::ConcreteInt>(lhs);
339
340      // Is the RHS a symbol we can simplify?
341      // FIXME: This was mostly copy/pasted from the LHS-is-a-symbol case.
342      if (const nonloc::SymbolVal *srhs = dyn_cast<nonloc::SymbolVal>(&rhs)) {
343        SymbolRef RSym = srhs->getSymbol();
344        if (RSym->getType(Context)->isIntegerType()) {
345          if (const llvm::APSInt *Constant = state->getSymVal(RSym)) {
346            // The symbol evaluates to a constant.
347            const llvm::APSInt *rhs_I;
348            if (BinaryOperator::isComparisonOp(op))
349              rhs_I = &BasicVals.Convert(lhsInt.getValue(), *Constant);
350            else
351              rhs_I = &BasicVals.Convert(resultTy, *Constant);
352
353            rhs = nonloc::ConcreteInt(*rhs_I);
354          }
355        }
356      }
357
358      if (isa<nonloc::ConcreteInt>(rhs)) {
359        return lhsInt.evalBinOp(*this, op, cast<nonloc::ConcreteInt>(rhs));
360      } else {
361        const llvm::APSInt& lhsValue = lhsInt.getValue();
362
363        // Swap the left and right sides and flip the operator if doing so
364        // allows us to better reason about the expression (this is a form
365        // of expression canonicalization).
366        // While we're at it, catch some special cases for non-commutative ops.
367        NonLoc tmp = rhs;
368        rhs = lhs;
369        lhs = tmp;
370
371        switch (op) {
372          case BO_LT:
373          case BO_GT:
374          case BO_LE:
375          case BO_GE:
376            op = ReverseComparison(op);
377            continue;
378          case BO_EQ:
379          case BO_NE:
380          case BO_Add:
381          case BO_Mul:
382          case BO_And:
383          case BO_Xor:
384          case BO_Or:
385            continue;
386          case BO_Shr:
387            if (lhsValue.isAllOnesValue() && lhsValue.isSigned())
388              // At this point lhs and rhs have been swapped.
389              return rhs;
390            // FALL-THROUGH
391          case BO_Shl:
392            if (lhsValue == 0)
393              // At this point lhs and rhs have been swapped.
394              return rhs;
395            return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
396          default:
397            return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
398        }
399      }
400    }
401    case nonloc::SymbolValKind: {
402      nonloc::SymbolVal *selhs = cast<nonloc::SymbolVal>(&lhs);
403
404      // LHS is a symbolic expression.
405      if (selhs->isExpression()) {
406
407        // Only handle LHS of the form "$sym op constant", at least for now.
408        const SymIntExpr *symIntExpr =
409            dyn_cast<SymIntExpr>(selhs->getSymbol());
410
411        if (!symIntExpr)
412          return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
413
414        // Is this a logical not? (!x is represented as x == 0.)
415        if (op == BO_EQ && rhs.isZeroConstant()) {
416          // We know how to negate certain expressions. Simplify them here.
417
418          BinaryOperator::Opcode opc = symIntExpr->getOpcode();
419          switch (opc) {
420          default:
421            // We don't know how to negate this operation.
422            // Just handle it as if it were a normal comparison to 0.
423            break;
424          case BO_LAnd:
425          case BO_LOr:
426            llvm_unreachable("Logical operators handled by branching logic.");
427          case BO_Assign:
428          case BO_MulAssign:
429          case BO_DivAssign:
430          case BO_RemAssign:
431          case BO_AddAssign:
432          case BO_SubAssign:
433          case BO_ShlAssign:
434          case BO_ShrAssign:
435          case BO_AndAssign:
436          case BO_XorAssign:
437          case BO_OrAssign:
438          case BO_Comma:
439            llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
440          case BO_PtrMemD:
441          case BO_PtrMemI:
442            llvm_unreachable("Pointer arithmetic not handled here.");
443          case BO_LT:
444          case BO_GT:
445          case BO_LE:
446          case BO_GE:
447          case BO_EQ:
448          case BO_NE:
449            // Negate the comparison and make a value.
450            opc = NegateComparison(opc);
451            assert(symIntExpr->getType(Context) == resultTy);
452            return makeNonLoc(symIntExpr->getLHS(), opc,
453                symIntExpr->getRHS(), resultTy);
454          }
455        }
456
457        // For now, only handle expressions whose RHS is a constant.
458        const nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs);
459        if (!rhsInt)
460          return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
461
462        // If both the LHS and the current expression are additive,
463        // fold their constants.
464        if (BinaryOperator::isAdditiveOp(op)) {
465          BinaryOperator::Opcode lop = symIntExpr->getOpcode();
466          if (BinaryOperator::isAdditiveOp(lop)) {
467            // resultTy may not be the best type to convert to, but it's
468            // probably the best choice in expressions with mixed type
469            // (such as x+1U+2LL). The rules for implicit conversions should
470            // choose a reasonable type to preserve the expression, and will
471            // at least match how the value is going to be used.
472            const llvm::APSInt &first =
473                BasicVals.Convert(resultTy, symIntExpr->getRHS());
474            const llvm::APSInt &second =
475                BasicVals.Convert(resultTy, rhsInt->getValue());
476            const llvm::APSInt *newRHS;
477            if (lop == op)
478              newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
479            else
480              newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
481            return MakeSymIntVal(symIntExpr->getLHS(), lop, *newRHS, resultTy);
482          }
483        }
484
485        // Otherwise, make a SymbolVal out of the expression.
486        return MakeSymIntVal(symIntExpr, op, rhsInt->getValue(), resultTy);
487
488      // LHS is a simple symbol (not a symbolic expression).
489      } else {
490        nonloc::SymbolVal *slhs = cast<nonloc::SymbolVal>(&lhs);
491        SymbolRef Sym = slhs->getSymbol();
492        QualType lhsType = Sym->getType(Context);
493
494        // The conversion type is usually the result type, but not in the case
495        // of relational expressions.
496        QualType conversionType = resultTy;
497        if (BinaryOperator::isComparisonOp(op))
498          conversionType = lhsType;
499
500        // Does the symbol simplify to a constant?  If so, "fold" the constant
501        // by setting 'lhs' to a ConcreteInt and try again.
502        if (lhsType->isIntegerType())
503          if (const llvm::APSInt *Constant = state->getSymVal(Sym)) {
504            // The symbol evaluates to a constant. If necessary, promote the
505            // folded constant (LHS) to the result type.
506            const llvm::APSInt &lhs_I = BasicVals.Convert(conversionType,
507                *Constant);
508            lhs = nonloc::ConcreteInt(lhs_I);
509
510            // Also promote the RHS (if necessary).
511
512            // For shifts, it is not necessary to promote the RHS.
513            if (BinaryOperator::isShiftOp(op))
514              continue;
515
516            // Other operators: do an implicit conversion.  This shouldn't be
517            // necessary once we support truncation/extension of symbolic values.
518            if (nonloc::ConcreteInt *rhs_I = dyn_cast<nonloc::ConcreteInt>(&rhs)){
519              rhs = nonloc::ConcreteInt(BasicVals.Convert(conversionType,
520                  rhs_I->getValue()));
521            }
522
523            continue;
524          }
525
526        // Is the RHS a symbol we can simplify?
527        if (const nonloc::SymbolVal *srhs = dyn_cast<nonloc::SymbolVal>(&rhs)) {
528          SymbolRef RSym = srhs->getSymbol();
529          if (RSym->getType(Context)->isIntegerType()) {
530            if (const llvm::APSInt *Constant = state->getSymVal(RSym)) {
531              // The symbol evaluates to a constant.
532              const llvm::APSInt &rhs_I = BasicVals.Convert(conversionType,
533                  *Constant);
534              rhs = nonloc::ConcreteInt(rhs_I);
535            }
536          }
537        }
538
539        if (isa<nonloc::ConcreteInt>(rhs)) {
540          return MakeSymIntVal(slhs->getSymbol(), op,
541              cast<nonloc::ConcreteInt>(rhs).getValue(),
542              resultTy);
543        }
544
545        return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
546      }
547    }
548    }
549  }
550}
551
552// FIXME: all this logic will change if/when we have MemRegion::getLocation().
553SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
554                                  BinaryOperator::Opcode op,
555                                  Loc lhs, Loc rhs,
556                                  QualType resultTy) {
557  // Only comparisons and subtractions are valid operations on two pointers.
558  // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
559  // However, if a pointer is casted to an integer, evalBinOpNN may end up
560  // calling this function with another operation (PR7527). We don't attempt to
561  // model this for now, but it could be useful, particularly when the
562  // "location" is actually an integer value that's been passed through a void*.
563  if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
564    return UnknownVal();
565
566  // Special cases for when both sides are identical.
567  if (lhs == rhs) {
568    switch (op) {
569    default:
570      llvm_unreachable("Unimplemented operation for two identical values");
571    case BO_Sub:
572      return makeZeroVal(resultTy);
573    case BO_EQ:
574    case BO_LE:
575    case BO_GE:
576      return makeTruthVal(true, resultTy);
577    case BO_NE:
578    case BO_LT:
579    case BO_GT:
580      return makeTruthVal(false, resultTy);
581    }
582  }
583
584  switch (lhs.getSubKind()) {
585  default:
586    llvm_unreachable("Ordering not implemented for this Loc.");
587
588  case loc::GotoLabelKind:
589    // The only thing we know about labels is that they're non-null.
590    if (rhs.isZeroConstant()) {
591      switch (op) {
592      default:
593        break;
594      case BO_Sub:
595        return evalCastFromLoc(lhs, resultTy);
596      case BO_EQ:
597      case BO_LE:
598      case BO_LT:
599        return makeTruthVal(false, resultTy);
600      case BO_NE:
601      case BO_GT:
602      case BO_GE:
603        return makeTruthVal(true, resultTy);
604      }
605    }
606    // There may be two labels for the same location, and a function region may
607    // have the same address as a label at the start of the function (depending
608    // on the ABI).
609    // FIXME: we can probably do a comparison against other MemRegions, though.
610    // FIXME: is there a way to tell if two labels refer to the same location?
611    return UnknownVal();
612
613  case loc::ConcreteIntKind: {
614    // If one of the operands is a symbol and the other is a constant,
615    // build an expression for use by the constraint manager.
616    if (SymbolRef rSym = rhs.getAsLocSymbol()) {
617      // We can only build expressions with symbols on the left,
618      // so we need a reversible operator.
619      if (!BinaryOperator::isComparisonOp(op))
620        return UnknownVal();
621
622      const llvm::APSInt &lVal = cast<loc::ConcreteInt>(lhs).getValue();
623      return makeNonLoc(rSym, ReverseComparison(op), lVal, resultTy);
624    }
625
626    // If both operands are constants, just perform the operation.
627    if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
628      SVal ResultVal = cast<loc::ConcreteInt>(lhs).evalBinOp(BasicVals, op,
629                                                             *rInt);
630      if (Loc *Result = dyn_cast<Loc>(&ResultVal))
631        return evalCastFromLoc(*Result, resultTy);
632      else
633        return UnknownVal();
634    }
635
636    // Special case comparisons against NULL.
637    // This must come after the test if the RHS is a symbol, which is used to
638    // build constraints. The address of any non-symbolic region is guaranteed
639    // to be non-NULL, as is any label.
640    assert(isa<loc::MemRegionVal>(rhs) || isa<loc::GotoLabel>(rhs));
641    if (lhs.isZeroConstant()) {
642      switch (op) {
643      default:
644        break;
645      case BO_EQ:
646      case BO_GT:
647      case BO_GE:
648        return makeTruthVal(false, resultTy);
649      case BO_NE:
650      case BO_LT:
651      case BO_LE:
652        return makeTruthVal(true, resultTy);
653      }
654    }
655
656    // Comparing an arbitrary integer to a region or label address is
657    // completely unknowable.
658    return UnknownVal();
659  }
660  case loc::MemRegionKind: {
661    if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
662      // If one of the operands is a symbol and the other is a constant,
663      // build an expression for use by the constraint manager.
664      if (SymbolRef lSym = lhs.getAsLocSymbol())
665        return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
666
667      // Special case comparisons to NULL.
668      // This must come after the test if the LHS is a symbol, which is used to
669      // build constraints. The address of any non-symbolic region is guaranteed
670      // to be non-NULL.
671      if (rInt->isZeroConstant()) {
672        switch (op) {
673        default:
674          break;
675        case BO_Sub:
676          return evalCastFromLoc(lhs, resultTy);
677        case BO_EQ:
678        case BO_LT:
679        case BO_LE:
680          return makeTruthVal(false, resultTy);
681        case BO_NE:
682        case BO_GT:
683        case BO_GE:
684          return makeTruthVal(true, resultTy);
685        }
686      }
687
688      // Comparing a region to an arbitrary integer is completely unknowable.
689      return UnknownVal();
690    }
691
692    // Get both values as regions, if possible.
693    const MemRegion *LeftMR = lhs.getAsRegion();
694    assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
695
696    const MemRegion *RightMR = rhs.getAsRegion();
697    if (!RightMR)
698      // The RHS is probably a label, which in theory could address a region.
699      // FIXME: we can probably make a more useful statement about non-code
700      // regions, though.
701      return UnknownVal();
702
703    // If both values wrap regions, see if they're from different base regions.
704    const MemRegion *LeftBase = LeftMR->getBaseRegion();
705    const MemRegion *RightBase = RightMR->getBaseRegion();
706    if (LeftBase != RightBase &&
707        !isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) {
708      switch (op) {
709      default:
710        return UnknownVal();
711      case BO_EQ:
712        return makeTruthVal(false, resultTy);
713      case BO_NE:
714        return makeTruthVal(true, resultTy);
715      }
716    }
717
718    // The two regions are from the same base region. See if they're both a
719    // type of region we know how to compare.
720    const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
721    const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
722
723    // Heuristic: assume that no symbolic region (whose memory space is
724    // unknown) is on the stack.
725    // FIXME: we should be able to be more precise once we can do better
726    // aliasing constraints for symbolic regions, but this is a reasonable,
727    // albeit unsound, assumption that holds most of the time.
728    if (isa<StackSpaceRegion>(LeftMS) ^ isa<StackSpaceRegion>(RightMS)) {
729      switch (op) {
730        default:
731          break;
732        case BO_EQ:
733          return makeTruthVal(false, resultTy);
734        case BO_NE:
735          return makeTruthVal(true, resultTy);
736      }
737    }
738
739    // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
740    // ElementRegion path and the FieldRegion path below should be unified.
741    if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) {
742      // First see if the right region is also an ElementRegion.
743      const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
744      if (!RightER)
745        return UnknownVal();
746
747      // Next, see if the two ERs have the same super-region and matching types.
748      // FIXME: This should do something useful even if the types don't match,
749      // though if both indexes are constant the RegionRawOffset path will
750      // give the correct answer.
751      if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
752          LeftER->getElementType() == RightER->getElementType()) {
753        // Get the left index and cast it to the correct type.
754        // If the index is unknown or undefined, bail out here.
755        SVal LeftIndexVal = LeftER->getIndex();
756        NonLoc *LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
757        if (!LeftIndex)
758          return UnknownVal();
759        LeftIndexVal = evalCastFromNonLoc(*LeftIndex, resultTy);
760        LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
761        if (!LeftIndex)
762          return UnknownVal();
763
764        // Do the same for the right index.
765        SVal RightIndexVal = RightER->getIndex();
766        NonLoc *RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
767        if (!RightIndex)
768          return UnknownVal();
769        RightIndexVal = evalCastFromNonLoc(*RightIndex, resultTy);
770        RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
771        if (!RightIndex)
772          return UnknownVal();
773
774        // Actually perform the operation.
775        // evalBinOpNN expects the two indexes to already be the right type.
776        return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
777      }
778
779      // If the element indexes aren't comparable, see if the raw offsets are.
780      RegionRawOffset LeftOffset = LeftER->getAsArrayOffset();
781      RegionRawOffset RightOffset = RightER->getAsArrayOffset();
782
783      if (LeftOffset.getRegion() != NULL &&
784          LeftOffset.getRegion() == RightOffset.getRegion()) {
785        CharUnits left = LeftOffset.getOffset();
786        CharUnits right = RightOffset.getOffset();
787
788        switch (op) {
789        default:
790          return UnknownVal();
791        case BO_LT:
792          return makeTruthVal(left < right, resultTy);
793        case BO_GT:
794          return makeTruthVal(left > right, resultTy);
795        case BO_LE:
796          return makeTruthVal(left <= right, resultTy);
797        case BO_GE:
798          return makeTruthVal(left >= right, resultTy);
799        case BO_EQ:
800          return makeTruthVal(left == right, resultTy);
801        case BO_NE:
802          return makeTruthVal(left != right, resultTy);
803        }
804      }
805
806      // If we get here, we have no way of comparing the ElementRegions.
807      return UnknownVal();
808    }
809
810    // See if both regions are fields of the same structure.
811    // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars.
812    if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) {
813      // Only comparisons are meaningful here!
814      if (!BinaryOperator::isComparisonOp(op))
815        return UnknownVal();
816
817      // First see if the right region is also a FieldRegion.
818      const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
819      if (!RightFR)
820        return UnknownVal();
821
822      // Next, see if the two FRs have the same super-region.
823      // FIXME: This doesn't handle casts yet, and simply stripping the casts
824      // doesn't help.
825      if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
826        return UnknownVal();
827
828      const FieldDecl *LeftFD = LeftFR->getDecl();
829      const FieldDecl *RightFD = RightFR->getDecl();
830      const RecordDecl *RD = LeftFD->getParent();
831
832      // Make sure the two FRs are from the same kind of record. Just in case!
833      // FIXME: This is probably where inheritance would be a problem.
834      if (RD != RightFD->getParent())
835        return UnknownVal();
836
837      // We know for sure that the two fields are not the same, since that
838      // would have given us the same SVal.
839      if (op == BO_EQ)
840        return makeTruthVal(false, resultTy);
841      if (op == BO_NE)
842        return makeTruthVal(true, resultTy);
843
844      // Iterate through the fields and see which one comes first.
845      // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
846      // members and the units in which bit-fields reside have addresses that
847      // increase in the order in which they are declared."
848      bool leftFirst = (op == BO_LT || op == BO_LE);
849      for (RecordDecl::field_iterator I = RD->field_begin(),
850           E = RD->field_end(); I!=E; ++I) {
851        if (&*I == LeftFD)
852          return makeTruthVal(leftFirst, resultTy);
853        if (&*I == RightFD)
854          return makeTruthVal(!leftFirst, resultTy);
855      }
856
857      llvm_unreachable("Fields not found in parent record's definition");
858    }
859
860    // If we get here, we have no way of comparing the regions.
861    return UnknownVal();
862  }
863  }
864}
865
866SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
867                                  BinaryOperator::Opcode op,
868                                  Loc lhs, NonLoc rhs, QualType resultTy) {
869
870  // Special case: rhs is a zero constant.
871  if (rhs.isZeroConstant())
872    return lhs;
873
874  // Special case: 'rhs' is an integer that has the same width as a pointer and
875  // we are using the integer location in a comparison.  Normally this cannot be
876  // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32
877  // can generate comparisons that trigger this code.
878  // FIXME: Are all locations guaranteed to have pointer width?
879  if (BinaryOperator::isComparisonOp(op)) {
880    if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
881      const llvm::APSInt *x = &rhsInt->getValue();
882      ASTContext &ctx = Context;
883      if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
884        // Convert the signedness of the integer (if necessary).
885        if (x->isSigned())
886          x = &getBasicValueFactory().getValue(*x, true);
887
888        return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy);
889      }
890    }
891  }
892
893  // We are dealing with pointer arithmetic.
894
895  // Handle pointer arithmetic on constant values.
896  if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
897    if (loc::ConcreteInt *lhsInt = dyn_cast<loc::ConcreteInt>(&lhs)) {
898      const llvm::APSInt &leftI = lhsInt->getValue();
899      assert(leftI.isUnsigned());
900      llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
901
902      // Convert the bitwidth of rightI.  This should deal with overflow
903      // since we are dealing with concrete values.
904      rightI = rightI.extOrTrunc(leftI.getBitWidth());
905
906      // Offset the increment by the pointer size.
907      llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
908      rightI *= Multiplicand;
909
910      // Compute the adjusted pointer.
911      switch (op) {
912        case BO_Add:
913          rightI = leftI + rightI;
914          break;
915        case BO_Sub:
916          rightI = leftI - rightI;
917          break;
918        default:
919          llvm_unreachable("Invalid pointer arithmetic operation");
920      }
921      return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
922    }
923  }
924
925  // Handle cases where 'lhs' is a region.
926  if (const MemRegion *region = lhs.getAsRegion()) {
927    rhs = cast<NonLoc>(convertToArrayIndex(rhs));
928    SVal index = UnknownVal();
929    const MemRegion *superR = 0;
930    QualType elementType;
931
932    if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
933      assert(op == BO_Add || op == BO_Sub);
934      index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
935                          getArrayIndexType());
936      superR = elemReg->getSuperRegion();
937      elementType = elemReg->getElementType();
938    }
939    else if (isa<SubRegion>(region)) {
940      superR = region;
941      index = rhs;
942      if (const PointerType *PT = resultTy->getAs<PointerType>()) {
943        elementType = PT->getPointeeType();
944      }
945      else {
946        const ObjCObjectPointerType *OT =
947          resultTy->getAs<ObjCObjectPointerType>();
948        elementType = OT->getPointeeType();
949      }
950    }
951
952    if (NonLoc *indexV = dyn_cast<NonLoc>(&index)) {
953      return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
954                                                       superR, getContext()));
955    }
956  }
957  return UnknownVal();
958}
959
960const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
961                                                   SVal V) {
962  if (V.isUnknownOrUndef())
963    return NULL;
964
965  if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
966    return &X->getValue();
967
968  if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
969    return &X->getValue();
970
971  if (SymbolRef Sym = V.getAsSymbol())
972    return state->getSymVal(Sym);
973
974  // FIXME: Add support for SymExprs.
975  return NULL;
976}
977