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