ExprEngineC.cpp revision c07cad8364e7fb0e8cb0d5181edb7db718271b65
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/AST/ExprCXX.h"
15#include "clang/StaticAnalyzer/Core/CheckerManager.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17
18using namespace clang;
19using namespace ento;
20using llvm::APSInt;
21
22void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
23                                     ExplodedNode *Pred,
24                                     ExplodedNodeSet &Dst) {
25
26  Expr *LHS = B->getLHS()->IgnoreParens();
27  Expr *RHS = B->getRHS()->IgnoreParens();
28
29  // FIXME: Prechecks eventually go in ::Visit().
30  ExplodedNodeSet CheckedSet;
31  ExplodedNodeSet Tmp2;
32  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
33
34  // With both the LHS and RHS evaluated, process the operation itself.
35  for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
36         it != ei; ++it) {
37
38    ProgramStateRef state = (*it)->getState();
39    const LocationContext *LCtx = (*it)->getLocationContext();
40    SVal LeftV = state->getSVal(LHS, LCtx);
41    SVal RightV = state->getSVal(RHS, LCtx);
42
43    BinaryOperator::Opcode Op = B->getOpcode();
44
45    if (Op == BO_Assign) {
46      // EXPERIMENTAL: "Conjured" symbols.
47      // FIXME: Handle structs.
48      if (RightV.isUnknown()) {
49        unsigned Count = currBldrCtx->blockCount();
50        RightV = svalBuilder.conjureSymbolVal(0, B->getRHS(), LCtx, Count);
51      }
52      // Simulate the effects of a "store":  bind the value of the RHS
53      // to the L-Value represented by the LHS.
54      SVal ExprVal = B->isGLValue() ? LeftV : RightV;
55      evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
56                LeftV, RightV);
57      continue;
58    }
59
60    if (!B->isAssignmentOp()) {
61      StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
62
63      if (B->isAdditiveOp()) {
64        // If one of the operands is a location, conjure a symbol for the other
65        // one (offset) if it's unknown so that memory arithmetic always
66        // results in an ElementRegion.
67        // TODO: This can be removed after we enable history tracking with
68        // SymSymExpr.
69        unsigned Count = currBldrCtx->blockCount();
70        if (LeftV.getAs<Loc>() &&
71            RHS->getType()->isIntegralOrEnumerationType() &&
72            RightV.isUnknown()) {
73          RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
74                                                Count);
75        }
76        if (RightV.getAs<Loc>() &&
77            LHS->getType()->isIntegralOrEnumerationType() &&
78            LeftV.isUnknown()) {
79          LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(),
80                                               Count);
81        }
82      }
83
84      // Process non-assignments except commas or short-circuited
85      // logical expressions (LAnd and LOr).
86      SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
87      if (Result.isUnknown()) {
88        Bldr.generateNode(B, *it, state);
89        continue;
90      }
91
92      state = state->BindExpr(B, LCtx, Result);
93      Bldr.generateNode(B, *it, state);
94      continue;
95    }
96
97    assert (B->isCompoundAssignmentOp());
98
99    switch (Op) {
100      default:
101        llvm_unreachable("Invalid opcode for compound assignment.");
102      case BO_MulAssign: Op = BO_Mul; break;
103      case BO_DivAssign: Op = BO_Div; break;
104      case BO_RemAssign: Op = BO_Rem; break;
105      case BO_AddAssign: Op = BO_Add; break;
106      case BO_SubAssign: Op = BO_Sub; break;
107      case BO_ShlAssign: Op = BO_Shl; break;
108      case BO_ShrAssign: Op = BO_Shr; break;
109      case BO_AndAssign: Op = BO_And; break;
110      case BO_XorAssign: Op = BO_Xor; break;
111      case BO_OrAssign:  Op = BO_Or;  break;
112    }
113
114    // Perform a load (the LHS).  This performs the checks for
115    // null dereferences, and so on.
116    ExplodedNodeSet Tmp;
117    SVal location = LeftV;
118    evalLoad(Tmp, B, LHS, *it, state, location);
119
120    for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
121         ++I) {
122
123      state = (*I)->getState();
124      const LocationContext *LCtx = (*I)->getLocationContext();
125      SVal V = state->getSVal(LHS, LCtx);
126
127      // Get the computation type.
128      QualType CTy =
129        cast<CompoundAssignOperator>(B)->getComputationResultType();
130      CTy = getContext().getCanonicalType(CTy);
131
132      QualType CLHSTy =
133        cast<CompoundAssignOperator>(B)->getComputationLHSType();
134      CLHSTy = getContext().getCanonicalType(CLHSTy);
135
136      QualType LTy = getContext().getCanonicalType(LHS->getType());
137
138      // Promote LHS.
139      V = svalBuilder.evalCast(V, CLHSTy, LTy);
140
141      // Compute the result of the operation.
142      SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
143                                         B->getType(), CTy);
144
145      // EXPERIMENTAL: "Conjured" symbols.
146      // FIXME: Handle structs.
147
148      SVal LHSVal;
149
150      if (Result.isUnknown()) {
151        // The symbolic value is actually for the type of the left-hand side
152        // expression, not the computation type, as this is the value the
153        // LValue on the LHS will bind to.
154        LHSVal = svalBuilder.conjureSymbolVal(0, B->getRHS(), LCtx, LTy,
155                                              currBldrCtx->blockCount());
156        // However, we need to convert the symbol to the computation type.
157        Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
158      }
159      else {
160        // The left-hand side may bind to a different value then the
161        // computation type.
162        LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
163      }
164
165      // In C++, assignment and compound assignment operators return an
166      // lvalue.
167      if (B->isGLValue())
168        state = state->BindExpr(B, LCtx, location);
169      else
170        state = state->BindExpr(B, LCtx, Result);
171
172      evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
173    }
174  }
175
176  // FIXME: postvisits eventually go in ::Visit()
177  getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
178}
179
180void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
181                                ExplodedNodeSet &Dst) {
182
183  CanQualType T = getContext().getCanonicalType(BE->getType());
184
185  // Get the value of the block itself.
186  SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
187                                       Pred->getLocationContext());
188
189  ProgramStateRef State = Pred->getState();
190
191  // If we created a new MemRegion for the block, we should explicitly bind
192  // the captured variables.
193  if (const BlockDataRegion *BDR =
194      dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
195
196    BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
197                                              E = BDR->referenced_vars_end();
198
199    for (; I != E; ++I) {
200      const MemRegion *capturedR = I.getCapturedRegion();
201      const MemRegion *originalR = I.getOriginalRegion();
202      if (capturedR != originalR) {
203        SVal originalV = State->getSVal(loc::MemRegionVal(originalR));
204        State = State->bindLoc(loc::MemRegionVal(capturedR), originalV);
205      }
206    }
207  }
208
209  ExplodedNodeSet Tmp;
210  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
211  Bldr.generateNode(BE, Pred,
212                    State->BindExpr(BE, Pred->getLocationContext(), V),
213                    0, ProgramPoint::PostLValueKind);
214
215  // FIXME: Move all post/pre visits to ::Visit().
216  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
217}
218
219void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
220                           ExplodedNode *Pred, ExplodedNodeSet &Dst) {
221
222  ExplodedNodeSet dstPreStmt;
223  getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
224
225  if (CastE->getCastKind() == CK_LValueToRValue) {
226    for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
227         I!=E; ++I) {
228      ExplodedNode *subExprNode = *I;
229      ProgramStateRef state = subExprNode->getState();
230      const LocationContext *LCtx = subExprNode->getLocationContext();
231      evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
232    }
233    return;
234  }
235
236  // All other casts.
237  QualType T = CastE->getType();
238  QualType ExTy = Ex->getType();
239
240  if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
241    T = ExCast->getTypeAsWritten();
242
243  StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
244  for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
245       I != E; ++I) {
246
247    Pred = *I;
248    ProgramStateRef state = Pred->getState();
249    const LocationContext *LCtx = Pred->getLocationContext();
250
251    switch (CastE->getCastKind()) {
252      case CK_LValueToRValue:
253        llvm_unreachable("LValueToRValue casts handled earlier.");
254      case CK_ToVoid:
255        continue;
256        // The analyzer doesn't do anything special with these casts,
257        // since it understands retain/release semantics already.
258      case CK_ARCProduceObject:
259      case CK_ARCConsumeObject:
260      case CK_ARCReclaimReturnedObject:
261      case CK_ARCExtendBlockObject: // Fall-through.
262      case CK_CopyAndAutoreleaseBlockObject:
263        // The analyser can ignore atomic casts for now, although some future
264        // checkers may want to make certain that you're not modifying the same
265        // value through atomic and nonatomic pointers.
266      case CK_AtomicToNonAtomic:
267      case CK_NonAtomicToAtomic:
268        // True no-ops.
269      case CK_NoOp:
270      case CK_ConstructorConversion:
271      case CK_UserDefinedConversion:
272      case CK_FunctionToPointerDecay:
273      case CK_BuiltinFnToFnPtr: {
274        // Copy the SVal of Ex to CastE.
275        ProgramStateRef state = Pred->getState();
276        const LocationContext *LCtx = Pred->getLocationContext();
277        SVal V = state->getSVal(Ex, LCtx);
278        state = state->BindExpr(CastE, LCtx, V);
279        Bldr.generateNode(CastE, Pred, state);
280        continue;
281      }
282      case CK_MemberPointerToBoolean:
283        // FIXME: For now, member pointers are represented by void *.
284        // FALLTHROUGH
285      case CK_Dependent:
286      case CK_ArrayToPointerDecay:
287      case CK_BitCast:
288      case CK_IntegralCast:
289      case CK_NullToPointer:
290      case CK_IntegralToPointer:
291      case CK_PointerToIntegral:
292      case CK_PointerToBoolean:
293      case CK_IntegralToBoolean:
294      case CK_IntegralToFloating:
295      case CK_FloatingToIntegral:
296      case CK_FloatingToBoolean:
297      case CK_FloatingCast:
298      case CK_FloatingRealToComplex:
299      case CK_FloatingComplexToReal:
300      case CK_FloatingComplexToBoolean:
301      case CK_FloatingComplexCast:
302      case CK_FloatingComplexToIntegralComplex:
303      case CK_IntegralRealToComplex:
304      case CK_IntegralComplexToReal:
305      case CK_IntegralComplexToBoolean:
306      case CK_IntegralComplexCast:
307      case CK_IntegralComplexToFloatingComplex:
308      case CK_CPointerToObjCPointerCast:
309      case CK_BlockPointerToObjCPointerCast:
310      case CK_AnyPointerToBlockPointerCast:
311      case CK_ObjCObjectLValueCast:
312      case CK_ZeroToOCLEvent:
313      case CK_LValueBitCast: {
314        // Delegate to SValBuilder to process.
315        SVal V = state->getSVal(Ex, LCtx);
316        V = svalBuilder.evalCast(V, T, ExTy);
317        state = state->BindExpr(CastE, LCtx, V);
318        Bldr.generateNode(CastE, Pred, state);
319        continue;
320      }
321      case CK_DerivedToBase:
322      case CK_UncheckedDerivedToBase: {
323        // For DerivedToBase cast, delegate to the store manager.
324        SVal val = state->getSVal(Ex, LCtx);
325        val = getStoreManager().evalDerivedToBase(val, CastE);
326        state = state->BindExpr(CastE, LCtx, val);
327        Bldr.generateNode(CastE, Pred, state);
328        continue;
329      }
330      // Handle C++ dyn_cast.
331      case CK_Dynamic: {
332        SVal val = state->getSVal(Ex, LCtx);
333
334        // Compute the type of the result.
335        QualType resultType = CastE->getType();
336        if (CastE->isGLValue())
337          resultType = getContext().getPointerType(resultType);
338
339        bool Failed = false;
340
341        // Check if the value being cast evaluates to 0.
342        if (val.isZeroConstant())
343          Failed = true;
344        // Else, evaluate the cast.
345        else
346          val = getStoreManager().evalDynamicCast(val, T, Failed);
347
348        if (Failed) {
349          if (T->isReferenceType()) {
350            // A bad_cast exception is thrown if input value is a reference.
351            // Currently, we model this, by generating a sink.
352            Bldr.generateSink(CastE, Pred, state);
353            continue;
354          } else {
355            // If the cast fails on a pointer, bind to 0.
356            state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
357          }
358        } else {
359          // If we don't know if the cast succeeded, conjure a new symbol.
360          if (val.isUnknown()) {
361            DefinedOrUnknownSVal NewSym =
362              svalBuilder.conjureSymbolVal(0, CastE, LCtx, resultType,
363                                           currBldrCtx->blockCount());
364            state = state->BindExpr(CastE, LCtx, NewSym);
365          } else
366            // Else, bind to the derived region value.
367            state = state->BindExpr(CastE, LCtx, val);
368        }
369        Bldr.generateNode(CastE, Pred, state);
370        continue;
371      }
372      case CK_NullToMemberPointer: {
373        // FIXME: For now, member pointers are represented by void *.
374        SVal V = svalBuilder.makeNull();
375        state = state->BindExpr(CastE, LCtx, V);
376        Bldr.generateNode(CastE, Pred, state);
377        continue;
378      }
379      // Various C++ casts that are not handled yet.
380      case CK_ToUnion:
381      case CK_BaseToDerived:
382      case CK_BaseToDerivedMemberPointer:
383      case CK_DerivedToBaseMemberPointer:
384      case CK_ReinterpretMemberPointer:
385      case CK_VectorSplat: {
386        // Recover some path-sensitivty by conjuring a new value.
387        QualType resultType = CastE->getType();
388        if (CastE->isGLValue())
389          resultType = getContext().getPointerType(resultType);
390        SVal result = svalBuilder.conjureSymbolVal(0, CastE, LCtx,
391                                                   resultType,
392                                                   currBldrCtx->blockCount());
393        state = state->BindExpr(CastE, LCtx, result);
394        Bldr.generateNode(CastE, Pred, state);
395        continue;
396      }
397    }
398  }
399}
400
401void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
402                                          ExplodedNode *Pred,
403                                          ExplodedNodeSet &Dst) {
404  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
405
406  ProgramStateRef State = Pred->getState();
407  const LocationContext *LCtx = Pred->getLocationContext();
408
409  const Expr *Init = CL->getInitializer();
410  SVal V = State->getSVal(CL->getInitializer(), LCtx);
411
412  if (isa<CXXConstructExpr>(Init)) {
413    // No work needed. Just pass the value up to this expression.
414  } else {
415    assert(isa<InitListExpr>(Init));
416    Loc CLLoc = State->getLValue(CL, LCtx);
417    State = State->bindLoc(CLLoc, V);
418
419    // Compound literal expressions are a GNU extension in C++.
420    // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues,
421    // and like temporary objects created by the functional notation T()
422    // CLs are destroyed at the end of the containing full-expression.
423    // HOWEVER, an rvalue of array type is not something the analyzer can
424    // reason about, since we expect all regions to be wrapped in Locs.
425    // So we treat array CLs as lvalues as well, knowing that they will decay
426    // to pointers as soon as they are used.
427    if (CL->isGLValue() || CL->getType()->isArrayType())
428      V = CLLoc;
429  }
430
431  B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
432}
433
434void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
435                               ExplodedNodeSet &Dst) {
436  // Assumption: The CFG has one DeclStmt per Decl.
437  const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
438
439  if (!VD) {
440    //TODO:AZ: remove explicit insertion after refactoring is done.
441    Dst.insert(Pred);
442    return;
443  }
444
445  // FIXME: all pre/post visits should eventually be handled by ::Visit().
446  ExplodedNodeSet dstPreVisit;
447  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
448
449  ExplodedNodeSet dstEvaluated;
450  StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
451  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
452       I!=E; ++I) {
453    ExplodedNode *N = *I;
454    ProgramStateRef state = N->getState();
455    const LocationContext *LC = N->getLocationContext();
456
457    // Decls without InitExpr are not initialized explicitly.
458    if (const Expr *InitEx = VD->getInit()) {
459
460      // Note in the state that the initialization has occurred.
461      ExplodedNode *UpdatedN = N;
462      SVal InitVal = state->getSVal(InitEx, LC);
463
464      if (isa<CXXConstructExpr>(InitEx->IgnoreImplicit())) {
465        // We constructed the object directly in the variable.
466        // No need to bind anything.
467        B.generateNode(DS, UpdatedN, state);
468      } else {
469        // We bound the temp obj region to the CXXConstructExpr. Now recover
470        // the lazy compound value when the variable is not a reference.
471        if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
472            !VD->getType()->isReferenceType()) {
473          if (Optional<loc::MemRegionVal> M =
474                  InitVal.getAs<loc::MemRegionVal>()) {
475            InitVal = state->getSVal(M->getRegion());
476            assert(InitVal.getAs<nonloc::LazyCompoundVal>());
477          }
478        }
479
480        // Recover some path-sensitivity if a scalar value evaluated to
481        // UnknownVal.
482        if (InitVal.isUnknown()) {
483          QualType Ty = InitEx->getType();
484          if (InitEx->isGLValue()) {
485            Ty = getContext().getPointerType(Ty);
486          }
487
488          InitVal = svalBuilder.conjureSymbolVal(0, InitEx, LC, Ty,
489                                                 currBldrCtx->blockCount());
490        }
491
492
493        B.takeNodes(UpdatedN);
494        ExplodedNodeSet Dst2;
495        evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
496        B.addNodes(Dst2);
497      }
498    }
499    else {
500      B.generateNode(DS, N, state);
501    }
502  }
503
504  getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
505}
506
507static ProgramStateRef evaluateLogicalExpression(const Expr *E,
508                                                 const LocationContext *LC,
509                                                 ProgramStateRef State) {
510  SVal X = State->getSVal(E, LC);
511  if (! X.isUnknown())
512    return State;
513
514  const BinaryOperator *B = dyn_cast<BinaryOperator>(E->IgnoreParens());
515  if (!B || (B->getOpcode() != BO_LAnd && B->getOpcode() != BO_LOr))
516    return State;
517
518  State = evaluateLogicalExpression(B->getLHS(), LC, State);
519  X = State->getSVal(B->getLHS(), LC);
520  QualType XType = B->getLHS()->getType();
521
522  assert(X.isConstant());
523  if (!X.isZeroConstant() == (B->getOpcode() == BO_LAnd)) {
524    // LHS not sufficient, we need to check RHS as well
525    State = evaluateLogicalExpression(B->getRHS(), LC, State);
526    X = State->getSVal(B->getRHS(), LC);
527    XType = B->getRHS()->getType();
528  }
529
530  SValBuilder &SVB = State->getStateManager().getSValBuilder();
531  return State->BindExpr(E, LC, SVB.evalCast(X, B->getType(), XType));
532}
533
534void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
535                                  ExplodedNodeSet &Dst) {
536  assert(B->getOpcode() == BO_LAnd ||
537         B->getOpcode() == BO_LOr);
538
539  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
540  ProgramStateRef state = Pred->getState();
541
542  state = evaluateLogicalExpression(B, Pred->getLocationContext(), state);
543  SVal X = state->getSVal(B, Pred->getLocationContext());
544
545  if (!X.isUndef()) {
546    DefinedOrUnknownSVal DefinedRHS = X.castAs<DefinedOrUnknownSVal>();
547    ProgramStateRef StTrue, StFalse;
548    llvm::tie(StTrue, StFalse) = state->assume(DefinedRHS);
549    if (StTrue) {
550      if (!StFalse) {
551        // The value is known to be true.
552        X = getSValBuilder().makeIntVal(1, B->getType());
553      } // else The truth value of X is unknown, just leave it as it is.
554    } else {
555      // The value is known to be false.
556      assert(StFalse && "Infeasible path!");
557      X = getSValBuilder().makeIntVal(0, B->getType());
558    }
559  }
560
561  Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
562}
563
564void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
565                                   ExplodedNode *Pred,
566                                   ExplodedNodeSet &Dst) {
567  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
568
569  ProgramStateRef state = Pred->getState();
570  const LocationContext *LCtx = Pred->getLocationContext();
571  QualType T = getContext().getCanonicalType(IE->getType());
572  unsigned NumInitElements = IE->getNumInits();
573
574  if (!IE->isGLValue() &&
575      (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
576       T->isAnyComplexType())) {
577    llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
578
579    // Handle base case where the initializer has no elements.
580    // e.g: static int* myArray[] = {};
581    if (NumInitElements == 0) {
582      SVal V = svalBuilder.makeCompoundVal(T, vals);
583      B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
584      return;
585    }
586
587    for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
588         ei = IE->rend(); it != ei; ++it) {
589      SVal V = state->getSVal(cast<Expr>(*it), LCtx);
590      vals = getBasicVals().consVals(V, vals);
591    }
592
593    B.generateNode(IE, Pred,
594                   state->BindExpr(IE, LCtx,
595                                   svalBuilder.makeCompoundVal(T, vals)));
596    return;
597  }
598
599  // Handle scalars: int{5} and int{} and GLvalues.
600  // Note, if the InitListExpr is a GLvalue, it means that there is an address
601  // representing it, so it must have a single init element.
602  assert(NumInitElements <= 1);
603
604  SVal V;
605  if (NumInitElements == 0)
606    V = getSValBuilder().makeZeroVal(T);
607  else
608    V = state->getSVal(IE->getInit(0), LCtx);
609
610  B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
611}
612
613void ExprEngine::VisitGuardedExpr(const Expr *Ex,
614                                  const Expr *L,
615                                  const Expr *R,
616                                  ExplodedNode *Pred,
617                                  ExplodedNodeSet &Dst) {
618  assert(L && R);
619
620  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
621  ProgramStateRef state = Pred->getState();
622  const LocationContext *LCtx = Pred->getLocationContext();
623  const CFGBlock *SrcBlock = 0;
624
625  // Find the predecessor block.
626  ProgramStateRef SrcState = state;
627  for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
628    ProgramPoint PP = N->getLocation();
629    if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
630      assert(N->pred_size() == 1);
631      continue;
632    }
633    SrcBlock = PP.castAs<BlockEdge>().getSrc();
634    SrcState = N->getState();
635    break;
636  }
637
638  assert(SrcBlock && "missing function entry");
639
640  // Find the last expression in the predecessor block.  That is the
641  // expression that is used for the value of the ternary expression.
642  bool hasValue = false;
643  SVal V;
644
645  for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(),
646                                        E = SrcBlock->rend(); I != E; ++I) {
647    CFGElement CE = *I;
648    if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
649      const Expr *ValEx = cast<Expr>(CS->getStmt());
650      ValEx = ValEx->IgnoreParens();
651
652      // For GNU extension '?:' operator, the left hand side will be an
653      // OpaqueValueExpr, so get the underlying expression.
654      if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
655        L = OpaqueEx->getSourceExpr();
656
657      // If the last expression in the predecessor block matches true or false
658      // subexpression, get its the value.
659      if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
660        hasValue = true;
661        V = SrcState->getSVal(ValEx, LCtx);
662      }
663      break;
664    }
665  }
666
667  if (!hasValue)
668    V = svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount());
669
670  // Generate a new node with the binding from the appropriate path.
671  B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
672}
673
674void ExprEngine::
675VisitOffsetOfExpr(const OffsetOfExpr *OOE,
676                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
677  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
678  APSInt IV;
679  if (OOE->EvaluateAsInt(IV, getContext())) {
680    assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
681    assert(OOE->getType()->isBuiltinType());
682    assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
683    assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
684    SVal X = svalBuilder.makeIntVal(IV);
685    B.generateNode(OOE, Pred,
686                   Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
687                                              X));
688  }
689  // FIXME: Handle the case where __builtin_offsetof is not a constant.
690}
691
692
693void ExprEngine::
694VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
695                              ExplodedNode *Pred,
696                              ExplodedNodeSet &Dst) {
697  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
698
699  QualType T = Ex->getTypeOfArgument();
700
701  if (Ex->getKind() == UETT_SizeOf) {
702    if (!T->isIncompleteType() && !T->isConstantSizeType()) {
703      assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
704
705      // FIXME: Add support for VLA type arguments and VLA expressions.
706      // When that happens, we should probably refactor VLASizeChecker's code.
707      return;
708    }
709    else if (T->getAs<ObjCObjectType>()) {
710      // Some code tries to take the sizeof an ObjCObjectType, relying that
711      // the compiler has laid out its representation.  Just report Unknown
712      // for these.
713      return;
714    }
715  }
716
717  APSInt Value = Ex->EvaluateKnownConstInt(getContext());
718  CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
719
720  ProgramStateRef state = Pred->getState();
721  state = state->BindExpr(Ex, Pred->getLocationContext(),
722                          svalBuilder.makeIntVal(amt.getQuantity(),
723                                                     Ex->getType()));
724  Bldr.generateNode(Ex, Pred, state);
725}
726
727void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
728                                    ExplodedNode *Pred,
729                                    ExplodedNodeSet &Dst) {
730  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
731  switch (U->getOpcode()) {
732    default: {
733      Bldr.takeNodes(Pred);
734      ExplodedNodeSet Tmp;
735      VisitIncrementDecrementOperator(U, Pred, Tmp);
736      Bldr.addNodes(Tmp);
737    }
738      break;
739    case UO_Real: {
740      const Expr *Ex = U->getSubExpr()->IgnoreParens();
741
742      // FIXME: We don't have complex SValues yet.
743      if (Ex->getType()->isAnyComplexType()) {
744        // Just report "Unknown."
745        break;
746      }
747
748      // For all other types, UO_Real is an identity operation.
749      assert (U->getType() == Ex->getType());
750      ProgramStateRef state = Pred->getState();
751      const LocationContext *LCtx = Pred->getLocationContext();
752      Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx,
753                                                 state->getSVal(Ex, LCtx)));
754      break;
755    }
756
757    case UO_Imag: {
758      const Expr *Ex = U->getSubExpr()->IgnoreParens();
759      // FIXME: We don't have complex SValues yet.
760      if (Ex->getType()->isAnyComplexType()) {
761        // Just report "Unknown."
762        break;
763      }
764      // For all other types, UO_Imag returns 0.
765      ProgramStateRef state = Pred->getState();
766      const LocationContext *LCtx = Pred->getLocationContext();
767      SVal X = svalBuilder.makeZeroVal(Ex->getType());
768      Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, X));
769      break;
770    }
771
772    case UO_Plus:
773      assert(!U->isGLValue());
774      // FALL-THROUGH.
775    case UO_Deref:
776    case UO_AddrOf:
777    case UO_Extension: {
778      // FIXME: We can probably just have some magic in Environment::getSVal()
779      // that propagates values, instead of creating a new node here.
780      //
781      // Unary "+" is a no-op, similar to a parentheses.  We still have places
782      // where it may be a block-level expression, so we need to
783      // generate an extra node that just propagates the value of the
784      // subexpression.
785      const Expr *Ex = U->getSubExpr()->IgnoreParens();
786      ProgramStateRef state = Pred->getState();
787      const LocationContext *LCtx = Pred->getLocationContext();
788      Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx,
789                                                 state->getSVal(Ex, LCtx)));
790      break;
791    }
792
793    case UO_LNot:
794    case UO_Minus:
795    case UO_Not: {
796      assert (!U->isGLValue());
797      const Expr *Ex = U->getSubExpr()->IgnoreParens();
798      ProgramStateRef state = Pred->getState();
799      const LocationContext *LCtx = Pred->getLocationContext();
800
801      // Get the value of the subexpression.
802      SVal V = state->getSVal(Ex, LCtx);
803
804      if (V.isUnknownOrUndef()) {
805        Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, V));
806        break;
807      }
808
809      switch (U->getOpcode()) {
810        default:
811          llvm_unreachable("Invalid Opcode.");
812        case UO_Not:
813          // FIXME: Do we need to handle promotions?
814          state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
815          break;
816        case UO_Minus:
817          // FIXME: Do we need to handle promotions?
818          state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
819          break;
820        case UO_LNot:
821          // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
822          //
823          //  Note: technically we do "E == 0", but this is the same in the
824          //    transfer functions as "0 == E".
825          SVal Result;
826          if (Optional<Loc> LV = V.getAs<Loc>()) {
827            Loc X = svalBuilder.makeNull();
828            Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
829          }
830          else if (Ex->getType()->isFloatingType()) {
831            // FIXME: handle floating point types.
832            Result = UnknownVal();
833          } else {
834            nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
835            Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
836                               U->getType());
837          }
838
839          state = state->BindExpr(U, LCtx, Result);
840          break;
841      }
842      Bldr.generateNode(U, Pred, state);
843      break;
844    }
845  }
846
847}
848
849void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
850                                                 ExplodedNode *Pred,
851                                                 ExplodedNodeSet &Dst) {
852  // Handle ++ and -- (both pre- and post-increment).
853  assert (U->isIncrementDecrementOp());
854  const Expr *Ex = U->getSubExpr()->IgnoreParens();
855
856  const LocationContext *LCtx = Pred->getLocationContext();
857  ProgramStateRef state = Pred->getState();
858  SVal loc = state->getSVal(Ex, LCtx);
859
860  // Perform a load.
861  ExplodedNodeSet Tmp;
862  evalLoad(Tmp, U, Ex, Pred, state, loc);
863
864  ExplodedNodeSet Dst2;
865  StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
866  for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
867
868    state = (*I)->getState();
869    assert(LCtx == (*I)->getLocationContext());
870    SVal V2_untested = state->getSVal(Ex, LCtx);
871
872    // Propagate unknown and undefined values.
873    if (V2_untested.isUnknownOrUndef()) {
874      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
875      continue;
876    }
877    DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
878
879    // Handle all other values.
880    BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
881
882    // If the UnaryOperator has non-location type, use its type to create the
883    // constant value. If the UnaryOperator has location type, create the
884    // constant with int type and pointer width.
885    SVal RHS;
886
887    if (U->getType()->isAnyPointerType())
888      RHS = svalBuilder.makeArrayIndex(1);
889    else if (U->getType()->isIntegralOrEnumerationType())
890      RHS = svalBuilder.makeIntVal(1, U->getType());
891    else
892      RHS = UnknownVal();
893
894    SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
895
896    // Conjure a new symbol if necessary to recover precision.
897    if (Result.isUnknown()){
898      DefinedOrUnknownSVal SymVal =
899        svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount());
900      Result = SymVal;
901
902      // If the value is a location, ++/-- should always preserve
903      // non-nullness.  Check if the original value was non-null, and if so
904      // propagate that constraint.
905      if (Loc::isLocType(U->getType())) {
906        DefinedOrUnknownSVal Constraint =
907        svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
908
909        if (!state->assume(Constraint, true)) {
910          // It isn't feasible for the original value to be null.
911          // Propagate this constraint.
912          Constraint = svalBuilder.evalEQ(state, SymVal,
913                                       svalBuilder.makeZeroVal(U->getType()));
914
915
916          state = state->assume(Constraint, false);
917          assert(state);
918        }
919      }
920    }
921
922    // Since the lvalue-to-rvalue conversion is explicit in the AST,
923    // we bind an l-value if the operator is prefix and an lvalue (in C++).
924    if (U->isGLValue())
925      state = state->BindExpr(U, LCtx, loc);
926    else
927      state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
928
929    // Perform the store.
930    Bldr.takeNodes(*I);
931    ExplodedNodeSet Dst3;
932    evalStore(Dst3, U, U, *I, state, loc, Result);
933    Bldr.addNodes(Dst3);
934  }
935  Dst.insert(Dst2);
936}
937