ExprEngineC.cpp revision 084842d334fca296279262c2534f6aa31b1dfdbb
1//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- 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 ExprEngine's support for C expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/CheckerManager.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
16
17using namespace clang;
18using namespace ento;
19using llvm::APSInt;
20
21void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
22                                     ExplodedNode *Pred,
23                                     ExplodedNodeSet &Dst) {
24
25  Expr *LHS = B->getLHS()->IgnoreParens();
26  Expr *RHS = B->getRHS()->IgnoreParens();
27
28  // FIXME: Prechecks eventually go in ::Visit().
29  ExplodedNodeSet CheckedSet;
30  ExplodedNodeSet Tmp2;
31  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
32
33  // With both the LHS and RHS evaluated, process the operation itself.
34  for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
35         it != ei; ++it) {
36
37    const ProgramState *state = (*it)->getState();
38    SVal LeftV = state->getSVal(LHS);
39    SVal RightV = state->getSVal(RHS);
40
41    BinaryOperator::Opcode Op = B->getOpcode();
42
43    if (Op == BO_Assign) {
44      // EXPERIMENTAL: "Conjured" symbols.
45      // FIXME: Handle structs.
46      if (RightV.isUnknown()) {
47        unsigned Count = currentBuilderContext->getCurrentBlockCount();
48        RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count);
49      }
50      // Simulate the effects of a "store":  bind the value of the RHS
51      // to the L-Value represented by the LHS.
52      SVal ExprVal = B->isLValue() ? LeftV : RightV;
53      evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, ExprVal), LeftV, RightV);
54      continue;
55    }
56
57    if (!B->isAssignmentOp()) {
58      StmtNodeBuilder Bldr(*it, Tmp2, *currentBuilderContext);
59      // Process non-assignments except commas or short-circuited
60      // logical expressions (LAnd and LOr).
61      SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
62      if (Result.isUnknown()) {
63        Bldr.generateNode(B, *it, state);
64        continue;
65      }
66
67      state = state->BindExpr(B, Result);
68      Bldr.generateNode(B, *it, state);
69      continue;
70    }
71
72    assert (B->isCompoundAssignmentOp());
73
74    switch (Op) {
75      default:
76        llvm_unreachable("Invalid opcode for compound assignment.");
77      case BO_MulAssign: Op = BO_Mul; break;
78      case BO_DivAssign: Op = BO_Div; break;
79      case BO_RemAssign: Op = BO_Rem; break;
80      case BO_AddAssign: Op = BO_Add; break;
81      case BO_SubAssign: Op = BO_Sub; break;
82      case BO_ShlAssign: Op = BO_Shl; break;
83      case BO_ShrAssign: Op = BO_Shr; break;
84      case BO_AndAssign: Op = BO_And; break;
85      case BO_XorAssign: Op = BO_Xor; break;
86      case BO_OrAssign:  Op = BO_Or;  break;
87    }
88
89    // Perform a load (the LHS).  This performs the checks for
90    // null dereferences, and so on.
91    ExplodedNodeSet Tmp;
92    SVal location = LeftV;
93    evalLoad(Tmp, LHS, *it, state, location);
94
95    for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
96         ++I) {
97
98      state = (*I)->getState();
99      SVal V = state->getSVal(LHS);
100
101      // Get the computation type.
102      QualType CTy =
103        cast<CompoundAssignOperator>(B)->getComputationResultType();
104      CTy = getContext().getCanonicalType(CTy);
105
106      QualType CLHSTy =
107        cast<CompoundAssignOperator>(B)->getComputationLHSType();
108      CLHSTy = getContext().getCanonicalType(CLHSTy);
109
110      QualType LTy = getContext().getCanonicalType(LHS->getType());
111
112      // Promote LHS.
113      V = svalBuilder.evalCast(V, CLHSTy, LTy);
114
115      // Compute the result of the operation.
116      SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
117                                         B->getType(), CTy);
118
119      // EXPERIMENTAL: "Conjured" symbols.
120      // FIXME: Handle structs.
121
122      SVal LHSVal;
123
124      if (Result.isUnknown()) {
125
126        unsigned Count = currentBuilderContext->getCurrentBlockCount();
127
128        // The symbolic value is actually for the type of the left-hand side
129        // expression, not the computation type, as this is the value the
130        // LValue on the LHS will bind to.
131        LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy,
132                                                  Count);
133
134        // However, we need to convert the symbol to the computation type.
135        Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
136      }
137      else {
138        // The left-hand side may bind to a different value then the
139        // computation type.
140        LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
141      }
142
143      // In C++, assignment and compound assignment operators return an
144      // lvalue.
145      if (B->isLValue())
146        state = state->BindExpr(B, location);
147      else
148        state = state->BindExpr(B, Result);
149
150      evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
151    }
152  }
153
154  // FIXME: postvisits eventually go in ::Visit()
155  getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
156}
157
158void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
159                                ExplodedNodeSet &Dst) {
160
161  CanQualType T = getContext().getCanonicalType(BE->getType());
162  SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
163                                       Pred->getLocationContext());
164
165  ExplodedNodeSet Tmp;
166  StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
167  Bldr.generateNode(BE, Pred, Pred->getState()->BindExpr(BE, V), false, 0,
168                    ProgramPoint::PostLValueKind);
169
170  // FIXME: Move all post/pre visits to ::Visit().
171  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
172}
173
174void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
175                           ExplodedNode *Pred, ExplodedNodeSet &Dst) {
176
177  ExplodedNodeSet dstPreStmt;
178  getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
179
180  if (CastE->getCastKind() == CK_LValueToRValue) {
181    for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
182         I!=E; ++I) {
183      ExplodedNode *subExprNode = *I;
184      const ProgramState *state = subExprNode->getState();
185      evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex));
186    }
187    return;
188  }
189
190  // All other casts.
191  QualType T = CastE->getType();
192  QualType ExTy = Ex->getType();
193
194  if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
195    T = ExCast->getTypeAsWritten();
196
197  StmtNodeBuilder Bldr(dstPreStmt, Dst, *currentBuilderContext);
198  for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
199       I != E; ++I) {
200
201    Pred = *I;
202
203    switch (CastE->getCastKind()) {
204      case CK_LValueToRValue:
205        llvm_unreachable("LValueToRValue casts handled earlier.");
206      case CK_ToVoid:
207        continue;
208        // The analyzer doesn't do anything special with these casts,
209        // since it understands retain/release semantics already.
210      case CK_ARCProduceObject:
211      case CK_ARCConsumeObject:
212      case CK_ARCReclaimReturnedObject:
213      case CK_ARCExtendBlockObject: // Fall-through.
214        // True no-ops.
215      case CK_NoOp:
216      case CK_FunctionToPointerDecay: {
217        // Copy the SVal of Ex to CastE.
218        const ProgramState *state = Pred->getState();
219        SVal V = state->getSVal(Ex);
220        state = state->BindExpr(CastE, V);
221        Bldr.generateNode(CastE, Pred, state);
222        continue;
223      }
224      case CK_Dependent:
225      case CK_ArrayToPointerDecay:
226      case CK_BitCast:
227      case CK_LValueBitCast:
228      case CK_IntegralCast:
229      case CK_NullToPointer:
230      case CK_IntegralToPointer:
231      case CK_PointerToIntegral:
232      case CK_PointerToBoolean:
233      case CK_IntegralToBoolean:
234      case CK_IntegralToFloating:
235      case CK_FloatingToIntegral:
236      case CK_FloatingToBoolean:
237      case CK_FloatingCast:
238      case CK_FloatingRealToComplex:
239      case CK_FloatingComplexToReal:
240      case CK_FloatingComplexToBoolean:
241      case CK_FloatingComplexCast:
242      case CK_FloatingComplexToIntegralComplex:
243      case CK_IntegralRealToComplex:
244      case CK_IntegralComplexToReal:
245      case CK_IntegralComplexToBoolean:
246      case CK_IntegralComplexCast:
247      case CK_IntegralComplexToFloatingComplex:
248      case CK_CPointerToObjCPointerCast:
249      case CK_BlockPointerToObjCPointerCast:
250      case CK_AnyPointerToBlockPointerCast:
251      case CK_ObjCObjectLValueCast: {
252        // Delegate to SValBuilder to process.
253        const ProgramState *state = Pred->getState();
254        SVal V = state->getSVal(Ex);
255        V = svalBuilder.evalCast(V, T, ExTy);
256        state = state->BindExpr(CastE, V);
257        Bldr.generateNode(CastE, Pred, state);
258        continue;
259      }
260      case CK_DerivedToBase:
261      case CK_UncheckedDerivedToBase: {
262        // For DerivedToBase cast, delegate to the store manager.
263        const ProgramState *state = Pred->getState();
264        SVal val = state->getSVal(Ex);
265        val = getStoreManager().evalDerivedToBase(val, T);
266        state = state->BindExpr(CastE, val);
267        Bldr.generateNode(CastE, Pred, state);
268        continue;
269      }
270        // Various C++ casts that are not handled yet.
271      case CK_Dynamic:
272      case CK_ToUnion:
273      case CK_BaseToDerived:
274      case CK_NullToMemberPointer:
275      case CK_BaseToDerivedMemberPointer:
276      case CK_DerivedToBaseMemberPointer:
277      case CK_UserDefinedConversion:
278      case CK_ConstructorConversion:
279      case CK_VectorSplat:
280      case CK_MemberPointerToBoolean: {
281        // Recover some path-sensitivty by conjuring a new value.
282        QualType resultType = CastE->getType();
283        if (CastE->isLValue())
284          resultType = getContext().getPointerType(resultType);
285
286        SVal result =
287        svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType,
288                               currentBuilderContext->getCurrentBlockCount());
289
290        const ProgramState *state = Pred->getState()->BindExpr(CastE, result);
291        Bldr.generateNode(CastE, Pred, state);
292        continue;
293      }
294    }
295  }
296}
297
298void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
299                                          ExplodedNode *Pred,
300                                          ExplodedNodeSet &Dst) {
301  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
302
303  const InitListExpr *ILE
304    = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
305
306  const ProgramState *state = Pred->getState();
307  SVal ILV = state->getSVal(ILE);
308  const LocationContext *LC = Pred->getLocationContext();
309  state = state->bindCompoundLiteral(CL, LC, ILV);
310
311  if (CL->isLValue())
312    B.generateNode(CL, Pred, state->BindExpr(CL, state->getLValue(CL, LC)));
313  else
314    B.generateNode(CL, Pred, state->BindExpr(CL, ILV));
315}
316
317void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
318                               ExplodedNodeSet &Dst) {
319
320  // FIXME: static variables may have an initializer, but the second
321  //  time a function is called those values may not be current.
322  //  This may need to be reflected in the CFG.
323
324  // Assumption: The CFG has one DeclStmt per Decl.
325  const Decl *D = *DS->decl_begin();
326
327  if (!D || !isa<VarDecl>(D)) {
328    //TODO:AZ: remove explicit insertion after refactoring is done.
329    Dst.insert(Pred);
330    return;
331  }
332
333  // FIXME: all pre/post visits should eventually be handled by ::Visit().
334  ExplodedNodeSet dstPreVisit;
335  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
336
337  StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
338  const VarDecl *VD = dyn_cast<VarDecl>(D);
339  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
340       I!=E; ++I) {
341    ExplodedNode *N = *I;
342    const ProgramState *state = N->getState();
343
344    // Decls without InitExpr are not initialized explicitly.
345    const LocationContext *LC = N->getLocationContext();
346
347    if (const Expr *InitEx = VD->getInit()) {
348      SVal InitVal = state->getSVal(InitEx);
349
350      // We bound the temp obj region to the CXXConstructExpr. Now recover
351      // the lazy compound value when the variable is not a reference.
352      if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() &&
353          !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){
354        InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion());
355        assert(isa<nonloc::LazyCompoundVal>(InitVal));
356      }
357
358      // Recover some path-sensitivity if a scalar value evaluated to
359      // UnknownVal.
360      if (InitVal.isUnknown()) {
361        InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx,
362                                 currentBuilderContext->getCurrentBlockCount());
363      }
364      B.takeNodes(N);
365      ExplodedNodeSet Dst2;
366      evalBind(Dst2, DS, N, state->getLValue(VD, LC), InitVal, true);
367      B.addNodes(Dst2);
368    }
369    else {
370      B.generateNode(DS, N,state->bindDeclWithNoInit(state->getRegion(VD, LC)));
371    }
372  }
373}
374
375void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
376                                  ExplodedNodeSet &Dst) {
377  assert(B->getOpcode() == BO_LAnd ||
378         B->getOpcode() == BO_LOr);
379
380  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
381  const ProgramState *state = Pred->getState();
382  SVal X = state->getSVal(B);
383  assert(X.isUndef());
384
385  const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData();
386  assert(Ex);
387
388  if (Ex == B->getRHS()) {
389    X = state->getSVal(Ex);
390
391    // Handle undefined values.
392    if (X.isUndef()) {
393      Bldr.generateNode(B, Pred, state->BindExpr(B, X));
394      return;
395    }
396
397    DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X);
398
399    // We took the RHS.  Because the value of the '&&' or '||' expression must
400    // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0
401    // or 1.  Alternatively, we could take a lazy approach, and calculate this
402    // value later when necessary.  We don't have the machinery in place for
403    // this right now, and since most logical expressions are used for branches,
404    // the payoff is not likely to be large.  Instead, we do eager evaluation.
405    if (const ProgramState *newState = state->assume(XD, true))
406      Bldr.generateNode(B, Pred,
407               newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType())));
408
409    if (const ProgramState *newState = state->assume(XD, false))
410      Bldr.generateNode(B, Pred,
411               newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType())));
412  }
413  else {
414    // We took the LHS expression.  Depending on whether we are '&&' or
415    // '||' we know what the value of the expression is via properties of
416    // the short-circuiting.
417    X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U,
418                               B->getType());
419    Bldr.generateNode(B, Pred, state->BindExpr(B, X));
420  }
421}
422
423void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
424                                   ExplodedNode *Pred,
425                                   ExplodedNodeSet &Dst) {
426  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
427
428  const ProgramState *state = Pred->getState();
429  QualType T = getContext().getCanonicalType(IE->getType());
430  unsigned NumInitElements = IE->getNumInits();
431
432  if (T->isArrayType() || T->isRecordType() || T->isVectorType()) {
433    llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
434
435    // Handle base case where the initializer has no elements.
436    // e.g: static int* myArray[] = {};
437    if (NumInitElements == 0) {
438      SVal V = svalBuilder.makeCompoundVal(T, vals);
439      B.generateNode(IE, Pred, state->BindExpr(IE, V));
440      return;
441    }
442
443    for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
444         ei = IE->rend(); it != ei; ++it) {
445      vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it)), vals);
446    }
447
448    B.generateNode(IE, Pred,
449                   state->BindExpr(IE, svalBuilder.makeCompoundVal(T, vals)));
450    return;
451  }
452
453  if (Loc::isLocType(T) || T->isIntegerType()) {
454    assert(IE->getNumInits() == 1);
455    const Expr *initEx = IE->getInit(0);
456    B.generateNode(IE, Pred, state->BindExpr(IE, state->getSVal(initEx)));
457    return;
458  }
459
460  llvm_unreachable("unprocessed InitListExpr type");
461}
462
463void ExprEngine::VisitGuardedExpr(const Expr *Ex,
464                                  const Expr *L,
465                                  const Expr *R,
466                                  ExplodedNode *Pred,
467                                  ExplodedNodeSet &Dst) {
468  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
469
470  const ProgramState *state = Pred->getState();
471  SVal X = state->getSVal(Ex);
472  assert (X.isUndef());
473  const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData();
474  assert(SE);
475  X = state->getSVal(SE);
476
477  // Make sure that we invalidate the previous binding.
478  B.generateNode(Ex, Pred, state->BindExpr(Ex, X, true));
479}
480
481void ExprEngine::
482VisitOffsetOfExpr(const OffsetOfExpr *OOE,
483                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
484  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
485  Expr::EvalResult Res;
486  if (OOE->EvaluateAsRValue(Res, getContext()) && Res.Val.isInt()) {
487    const APSInt &IV = Res.Val.getInt();
488    assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
489    assert(OOE->getType()->isIntegerType());
490    assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType());
491    SVal X = svalBuilder.makeIntVal(IV);
492    B.generateNode(OOE, Pred, Pred->getState()->BindExpr(OOE, X));
493  }
494  // FIXME: Handle the case where __builtin_offsetof is not a constant.
495}
496
497
498void ExprEngine::
499VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
500                              ExplodedNode *Pred,
501                              ExplodedNodeSet &Dst) {
502  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
503
504  QualType T = Ex->getTypeOfArgument();
505
506  if (Ex->getKind() == UETT_SizeOf) {
507    if (!T->isIncompleteType() && !T->isConstantSizeType()) {
508      assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
509
510      // FIXME: Add support for VLA type arguments and VLA expressions.
511      // When that happens, we should probably refactor VLASizeChecker's code.
512      return;
513    }
514    else if (T->getAs<ObjCObjectType>()) {
515      // Some code tries to take the sizeof an ObjCObjectType, relying that
516      // the compiler has laid out its representation.  Just report Unknown
517      // for these.
518      return;
519    }
520  }
521
522  Expr::EvalResult Result;
523  Ex->EvaluateAsRValue(Result, getContext());
524  CharUnits amt = CharUnits::fromQuantity(Result.Val.getInt().getZExtValue());
525
526  const ProgramState *state = Pred->getState();
527  state = state->BindExpr(Ex, svalBuilder.makeIntVal(amt.getQuantity(),
528                                                     Ex->getType()));
529  Bldr.generateNode(Ex, Pred, state);
530}
531
532void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
533                                    ExplodedNode *Pred,
534                                    ExplodedNodeSet &Dst) {
535  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
536  switch (U->getOpcode()) {
537    default: {
538      Bldr.takeNodes(Pred);
539      ExplodedNodeSet Tmp;
540      VisitIncrementDecrementOperator(U, Pred, Tmp);
541      Bldr.addNodes(Tmp);
542    }
543      break;
544    case UO_Real: {
545      const Expr *Ex = U->getSubExpr()->IgnoreParens();
546      ExplodedNodeSet Tmp;
547      Visit(Ex, Pred, Tmp);
548
549      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
550
551        // FIXME: We don't have complex SValues yet.
552        if (Ex->getType()->isAnyComplexType()) {
553          // Just report "Unknown."
554          continue;
555        }
556
557        // For all other types, UO_Real is an identity operation.
558        assert (U->getType() == Ex->getType());
559        const ProgramState *state = (*I)->getState();
560        Bldr.generateNode(U, *I, state->BindExpr(U, state->getSVal(Ex)));
561      }
562
563      break;
564    }
565
566    case UO_Imag: {
567
568      const Expr *Ex = U->getSubExpr()->IgnoreParens();
569      ExplodedNodeSet Tmp;
570      Visit(Ex, Pred, Tmp);
571
572      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
573        // FIXME: We don't have complex SValues yet.
574        if (Ex->getType()->isAnyComplexType()) {
575          // Just report "Unknown."
576          continue;
577        }
578
579        // For all other types, UO_Imag returns 0.
580        const ProgramState *state = (*I)->getState();
581        SVal X = svalBuilder.makeZeroVal(Ex->getType());
582        Bldr.generateNode(U, *I, state->BindExpr(U, X));
583      }
584
585      break;
586    }
587
588    case UO_Plus:
589      assert(!U->isLValue());
590      // FALL-THROUGH.
591    case UO_Deref:
592    case UO_AddrOf:
593    case UO_Extension: {
594
595      // Unary "+" is a no-op, similar to a parentheses.  We still have places
596      // where it may be a block-level expression, so we need to
597      // generate an extra node that just propagates the value of the
598      // subexpression.
599
600      const Expr *Ex = U->getSubExpr()->IgnoreParens();
601      ExplodedNodeSet Tmp;
602      Visit(Ex, Pred, Tmp);
603
604      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
605        const ProgramState *state = (*I)->getState();
606        Bldr.generateNode(U, *I, state->BindExpr(U, state->getSVal(Ex)));
607      }
608
609      break;
610    }
611
612    case UO_LNot:
613    case UO_Minus:
614    case UO_Not: {
615      assert (!U->isLValue());
616      const Expr *Ex = U->getSubExpr()->IgnoreParens();
617      ExplodedNodeSet Tmp;
618      Visit(Ex, Pred, Tmp);
619
620      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
621        const ProgramState *state = (*I)->getState();
622
623        // Get the value of the subexpression.
624        SVal V = state->getSVal(Ex);
625
626        if (V.isUnknownOrUndef()) {
627          Bldr.generateNode(U, *I, state->BindExpr(U, V));
628          continue;
629        }
630
631        switch (U->getOpcode()) {
632          default:
633            llvm_unreachable("Invalid Opcode.");
634
635          case UO_Not:
636            // FIXME: Do we need to handle promotions?
637            state = state->BindExpr(U, evalComplement(cast<NonLoc>(V)));
638            break;
639
640          case UO_Minus:
641            // FIXME: Do we need to handle promotions?
642            state = state->BindExpr(U, evalMinus(cast<NonLoc>(V)));
643            break;
644
645          case UO_LNot:
646
647            // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
648            //
649            //  Note: technically we do "E == 0", but this is the same in the
650            //    transfer functions as "0 == E".
651            SVal Result;
652
653            if (isa<Loc>(V)) {
654              Loc X = svalBuilder.makeNull();
655              Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X,
656                                 U->getType());
657            }
658            else {
659              nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
660              Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
661                                 U->getType());
662            }
663
664            state = state->BindExpr(U, Result);
665
666            break;
667        }
668        Bldr.generateNode(U, *I, state);
669      }
670      break;
671    }
672  }
673
674}
675
676void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
677                                                 ExplodedNode *Pred,
678                                                 ExplodedNodeSet &Dst) {
679  // Handle ++ and -- (both pre- and post-increment).
680  assert (U->isIncrementDecrementOp());
681  ExplodedNodeSet Tmp;
682  const Expr *Ex = U->getSubExpr()->IgnoreParens();
683  Visit(Ex, Pred, Tmp);
684
685  for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
686
687    const ProgramState *state = (*I)->getState();
688    SVal loc = state->getSVal(Ex);
689
690    // Perform a load.
691    ExplodedNodeSet Tmp2;
692    evalLoad(Tmp2, Ex, *I, state, loc);
693
694    ExplodedNodeSet Dst2;
695    StmtNodeBuilder Bldr(Tmp2, Dst2, *currentBuilderContext);
696    for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) {
697
698      state = (*I2)->getState();
699      SVal V2_untested = state->getSVal(Ex);
700
701      // Propagate unknown and undefined values.
702      if (V2_untested.isUnknownOrUndef()) {
703        Bldr.generateNode(U, *I2, state->BindExpr(U, V2_untested));
704        continue;
705      }
706      DefinedSVal V2 = cast<DefinedSVal>(V2_untested);
707
708      // Handle all other values.
709      BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add
710      : BO_Sub;
711
712      // If the UnaryOperator has non-location type, use its type to create the
713      // constant value. If the UnaryOperator has location type, create the
714      // constant with int type and pointer width.
715      SVal RHS;
716
717      if (U->getType()->isAnyPointerType())
718        RHS = svalBuilder.makeArrayIndex(1);
719      else
720        RHS = svalBuilder.makeIntVal(1, U->getType());
721
722      SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
723
724      // Conjure a new symbol if necessary to recover precision.
725      if (Result.isUnknown()){
726        DefinedOrUnknownSVal SymVal =
727        svalBuilder.getConjuredSymbolVal(NULL, Ex,
728                                 currentBuilderContext->getCurrentBlockCount());
729        Result = SymVal;
730
731        // If the value is a location, ++/-- should always preserve
732        // non-nullness.  Check if the original value was non-null, and if so
733        // propagate that constraint.
734        if (Loc::isLocType(U->getType())) {
735          DefinedOrUnknownSVal Constraint =
736          svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
737
738          if (!state->assume(Constraint, true)) {
739            // It isn't feasible for the original value to be null.
740            // Propagate this constraint.
741            Constraint = svalBuilder.evalEQ(state, SymVal,
742                                         svalBuilder.makeZeroVal(U->getType()));
743
744
745            state = state->assume(Constraint, false);
746            assert(state);
747          }
748        }
749      }
750
751      // Since the lvalue-to-rvalue conversion is explicit in the AST,
752      // we bind an l-value if the operator is prefix and an lvalue (in C++).
753      if (U->isLValue())
754        state = state->BindExpr(U, loc);
755      else
756        state = state->BindExpr(U, U->isPostfix() ? V2 : Result);
757
758      // Perform the store.
759      Bldr.takeNodes(*I2);
760      ExplodedNodeSet Dst4;
761      evalStore(Dst4, NULL, U, *I2, state, loc, Result);
762      Bldr.addNodes(Dst4);
763    }
764    Dst.insert(Dst2);
765  }
766}
767