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