ExprEngineC.cpp revision 321369
1226586Sdim//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
2226586Sdim//
3226586Sdim//                     The LLVM Compiler Infrastructure
4226586Sdim//
5226586Sdim// This file is distributed under the University of Illinois Open Source
6226586Sdim// License. See LICENSE.TXT for details.
7226586Sdim//
8226586Sdim//===----------------------------------------------------------------------===//
9226586Sdim//
10226586Sdim//  This file defines ExprEngine's support for C expressions.
11226586Sdim//
12226586Sdim//===----------------------------------------------------------------------===//
13226586Sdim
14249423Sdim#include "clang/AST/ExprCXX.h"
15314564Sdim#include "clang/AST/DeclCXX.h"
16226586Sdim#include "clang/StaticAnalyzer/Core/CheckerManager.h"
17226586Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18226586Sdim
19226586Sdimusing namespace clang;
20226586Sdimusing namespace ento;
21226586Sdimusing llvm::APSInt;
22226586Sdim
23226586Sdimvoid ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
24226586Sdim                                     ExplodedNode *Pred,
25226586Sdim                                     ExplodedNodeSet &Dst) {
26226586Sdim
27226586Sdim  Expr *LHS = B->getLHS()->IgnoreParens();
28226586Sdim  Expr *RHS = B->getRHS()->IgnoreParens();
29296417Sdim
30226586Sdim  // FIXME: Prechecks eventually go in ::Visit().
31226586Sdim  ExplodedNodeSet CheckedSet;
32226586Sdim  ExplodedNodeSet Tmp2;
33226586Sdim  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
34296417Sdim
35288943Sdim  // With both the LHS and RHS evaluated, process the operation itself.
36226586Sdim  for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
37226586Sdim         it != ei; ++it) {
38296417Sdim
39234353Sdim    ProgramStateRef state = (*it)->getState();
40234353Sdim    const LocationContext *LCtx = (*it)->getLocationContext();
41234353Sdim    SVal LeftV = state->getSVal(LHS, LCtx);
42234353Sdim    SVal RightV = state->getSVal(RHS, LCtx);
43296417Sdim
44226586Sdim    BinaryOperator::Opcode Op = B->getOpcode();
45296417Sdim
46226586Sdim    if (Op == BO_Assign) {
47226586Sdim      // EXPERIMENTAL: "Conjured" symbols.
48226586Sdim      // FIXME: Handle structs.
49234353Sdim      if (RightV.isUnknown()) {
50243830Sdim        unsigned Count = currBldrCtx->blockCount();
51276479Sdim        RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
52276479Sdim                                              Count);
53226586Sdim      }
54226586Sdim      // Simulate the effects of a "store":  bind the value of the RHS
55226586Sdim      // to the L-Value represented by the LHS.
56239462Sdim      SVal ExprVal = B->isGLValue() ? LeftV : RightV;
57234353Sdim      evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
58234353Sdim                LeftV, RightV);
59226586Sdim      continue;
60226586Sdim    }
61296417Sdim
62226586Sdim    if (!B->isAssignmentOp()) {
63243830Sdim      StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
64239462Sdim
65239462Sdim      if (B->isAdditiveOp()) {
66239462Sdim        // If one of the operands is a location, conjure a symbol for the other
67239462Sdim        // one (offset) if it's unknown so that memory arithmetic always
68239462Sdim        // results in an ElementRegion.
69239462Sdim        // TODO: This can be removed after we enable history tracking with
70239462Sdim        // SymSymExpr.
71243830Sdim        unsigned Count = currBldrCtx->blockCount();
72249423Sdim        if (LeftV.getAs<Loc>() &&
73251662Sdim            RHS->getType()->isIntegralOrEnumerationType() &&
74251662Sdim            RightV.isUnknown()) {
75243830Sdim          RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
76243830Sdim                                                Count);
77239462Sdim        }
78249423Sdim        if (RightV.getAs<Loc>() &&
79251662Sdim            LHS->getType()->isIntegralOrEnumerationType() &&
80251662Sdim            LeftV.isUnknown()) {
81243830Sdim          LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(),
82243830Sdim                                               Count);
83239462Sdim        }
84239462Sdim      }
85239462Sdim
86276479Sdim      // Although we don't yet model pointers-to-members, we do need to make
87276479Sdim      // sure that the members of temporaries have a valid 'this' pointer for
88276479Sdim      // other checks.
89276479Sdim      if (B->getOpcode() == BO_PtrMemD)
90276479Sdim        state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
91276479Sdim
92226586Sdim      // Process non-assignments except commas or short-circuited
93226586Sdim      // logical expressions (LAnd and LOr).
94296417Sdim      SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
95226586Sdim      if (Result.isUnknown()) {
96234353Sdim        Bldr.generateNode(B, *it, state);
97226586Sdim        continue;
98296417Sdim      }
99226586Sdim
100296417Sdim      state = state->BindExpr(B, LCtx, Result);
101234353Sdim      Bldr.generateNode(B, *it, state);
102226586Sdim      continue;
103226586Sdim    }
104296417Sdim
105226586Sdim    assert (B->isCompoundAssignmentOp());
106296417Sdim
107226586Sdim    switch (Op) {
108226586Sdim      default:
109226586Sdim        llvm_unreachable("Invalid opcode for compound assignment.");
110226586Sdim      case BO_MulAssign: Op = BO_Mul; break;
111226586Sdim      case BO_DivAssign: Op = BO_Div; break;
112226586Sdim      case BO_RemAssign: Op = BO_Rem; break;
113226586Sdim      case BO_AddAssign: Op = BO_Add; break;
114226586Sdim      case BO_SubAssign: Op = BO_Sub; break;
115226586Sdim      case BO_ShlAssign: Op = BO_Shl; break;
116226586Sdim      case BO_ShrAssign: Op = BO_Shr; break;
117226586Sdim      case BO_AndAssign: Op = BO_And; break;
118226586Sdim      case BO_XorAssign: Op = BO_Xor; break;
119226586Sdim      case BO_OrAssign:  Op = BO_Or;  break;
120226586Sdim    }
121296417Sdim
122226586Sdim    // Perform a load (the LHS).  This performs the checks for
123226586Sdim    // null dereferences, and so on.
124226586Sdim    ExplodedNodeSet Tmp;
125226586Sdim    SVal location = LeftV;
126234353Sdim    evalLoad(Tmp, B, LHS, *it, state, location);
127296417Sdim
128226586Sdim    for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
129226586Sdim         ++I) {
130226586Sdim
131226586Sdim      state = (*I)->getState();
132234353Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
133234353Sdim      SVal V = state->getSVal(LHS, LCtx);
134296417Sdim
135226586Sdim      // Get the computation type.
136226586Sdim      QualType CTy =
137226586Sdim        cast<CompoundAssignOperator>(B)->getComputationResultType();
138226586Sdim      CTy = getContext().getCanonicalType(CTy);
139296417Sdim
140226586Sdim      QualType CLHSTy =
141226586Sdim        cast<CompoundAssignOperator>(B)->getComputationLHSType();
142226586Sdim      CLHSTy = getContext().getCanonicalType(CLHSTy);
143296417Sdim
144226586Sdim      QualType LTy = getContext().getCanonicalType(LHS->getType());
145296417Sdim
146226586Sdim      // Promote LHS.
147226586Sdim      V = svalBuilder.evalCast(V, CLHSTy, LTy);
148296417Sdim
149226586Sdim      // Compute the result of the operation.
150226586Sdim      SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
151226586Sdim                                         B->getType(), CTy);
152296417Sdim
153226586Sdim      // EXPERIMENTAL: "Conjured" symbols.
154226586Sdim      // FIXME: Handle structs.
155296417Sdim
156226586Sdim      SVal LHSVal;
157296417Sdim
158234353Sdim      if (Result.isUnknown()) {
159226586Sdim        // The symbolic value is actually for the type of the left-hand side
160226586Sdim        // expression, not the computation type, as this is the value the
161226586Sdim        // LValue on the LHS will bind to.
162276479Sdim        LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
163243830Sdim                                              currBldrCtx->blockCount());
164226586Sdim        // However, we need to convert the symbol to the computation type.
165226586Sdim        Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
166226586Sdim      }
167226586Sdim      else {
168226586Sdim        // The left-hand side may bind to a different value then the
169226586Sdim        // computation type.
170226586Sdim        LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
171226586Sdim      }
172296417Sdim
173296417Sdim      // In C++, assignment and compound assignment operators return an
174226586Sdim      // lvalue.
175239462Sdim      if (B->isGLValue())
176234353Sdim        state = state->BindExpr(B, LCtx, location);
177226586Sdim      else
178234353Sdim        state = state->BindExpr(B, LCtx, Result);
179296417Sdim
180226586Sdim      evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
181226586Sdim    }
182226586Sdim  }
183296417Sdim
184226586Sdim  // FIXME: postvisits eventually go in ::Visit()
185226586Sdim  getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
186226586Sdim}
187226586Sdim
188226586Sdimvoid ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
189226586Sdim                                ExplodedNodeSet &Dst) {
190296417Sdim
191226586Sdim  CanQualType T = getContext().getCanonicalType(BE->getType());
192239462Sdim
193296417Sdim  const BlockDecl *BD = BE->getBlockDecl();
194239462Sdim  // Get the value of the block itself.
195296417Sdim  SVal V = svalBuilder.getBlockPointer(BD, T,
196261991Sdim                                       Pred->getLocationContext(),
197261991Sdim                                       currBldrCtx->blockCount());
198296417Sdim
199239462Sdim  ProgramStateRef State = Pred->getState();
200296417Sdim
201239462Sdim  // If we created a new MemRegion for the block, we should explicitly bind
202239462Sdim  // the captured variables.
203239462Sdim  if (const BlockDataRegion *BDR =
204239462Sdim      dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
205296417Sdim
206239462Sdim    BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
207239462Sdim                                              E = BDR->referenced_vars_end();
208296417Sdim
209296417Sdim    auto CI = BD->capture_begin();
210296417Sdim    auto CE = BD->capture_end();
211239462Sdim    for (; I != E; ++I) {
212296417Sdim      const VarRegion *capturedR = I.getCapturedRegion();
213296417Sdim      const VarRegion *originalR = I.getOriginalRegion();
214296417Sdim
215296417Sdim      // If the capture had a copy expression, use the result of evaluating
216296417Sdim      // that expression, otherwise use the original value.
217296417Sdim      // We rely on the invariant that the block declaration's capture variables
218296417Sdim      // are a prefix of the BlockDataRegion's referenced vars (which may include
219296417Sdim      // referenced globals, etc.) to enable fast lookup of the capture for a
220296417Sdim      // given referenced var.
221296417Sdim      const Expr *copyExpr = nullptr;
222296417Sdim      if (CI != CE) {
223296417Sdim        assert(CI->getVariable() == capturedR->getDecl());
224296417Sdim        copyExpr = CI->getCopyExpr();
225296417Sdim        CI++;
226296417Sdim      }
227296417Sdim
228239462Sdim      if (capturedR != originalR) {
229296417Sdim        SVal originalV;
230321369Sdim        const LocationContext *LCtx = Pred->getLocationContext();
231296417Sdim        if (copyExpr) {
232321369Sdim          originalV = State->getSVal(copyExpr, LCtx);
233296417Sdim        } else {
234296417Sdim          originalV = State->getSVal(loc::MemRegionVal(originalR));
235296417Sdim        }
236321369Sdim        State = State->bindLoc(loc::MemRegionVal(capturedR), originalV, LCtx);
237239462Sdim      }
238239462Sdim    }
239239462Sdim  }
240296417Sdim
241226586Sdim  ExplodedNodeSet Tmp;
242243830Sdim  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
243234353Sdim  Bldr.generateNode(BE, Pred,
244239462Sdim                    State->BindExpr(BE, Pred->getLocationContext(), V),
245276479Sdim                    nullptr, ProgramPoint::PostLValueKind);
246276479Sdim
247226586Sdim  // FIXME: Move all post/pre visits to ::Visit().
248226586Sdim  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
249226586Sdim}
250226586Sdim
251314564SdimProgramStateRef ExprEngine::handleLValueBitCast(
252314564Sdim    ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx,
253314564Sdim    QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr,
254314564Sdim    ExplodedNode* Pred) {
255314564Sdim  // Delegate to SValBuilder to process.
256314564Sdim  SVal V = state->getSVal(Ex, LCtx);
257314564Sdim  V = svalBuilder.evalCast(V, T, ExTy);
258314564Sdim  // Negate the result if we're treating the boolean as a signed i1
259314564Sdim  if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
260314564Sdim    V = evalMinus(V);
261314564Sdim  state = state->BindExpr(CastE, LCtx, V);
262314564Sdim  Bldr.generateNode(CastE, Pred, state);
263314564Sdim
264314564Sdim  return state;
265314564Sdim}
266314564Sdim
267314564SdimProgramStateRef ExprEngine::handleLVectorSplat(
268314564Sdim    ProgramStateRef state, const LocationContext* LCtx, const CastExpr* CastE,
269314564Sdim    StmtNodeBuilder &Bldr, ExplodedNode* Pred) {
270314564Sdim  // Recover some path sensitivity by conjuring a new value.
271314564Sdim  QualType resultType = CastE->getType();
272314564Sdim  if (CastE->isGLValue())
273314564Sdim    resultType = getContext().getPointerType(resultType);
274314564Sdim  SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
275314564Sdim                                             resultType,
276314564Sdim                                             currBldrCtx->blockCount());
277314564Sdim  state = state->BindExpr(CastE, LCtx, result);
278314564Sdim  Bldr.generateNode(CastE, Pred, state);
279314564Sdim
280314564Sdim  return state;
281314564Sdim}
282314564Sdim
283296417Sdimvoid ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
284226586Sdim                           ExplodedNode *Pred, ExplodedNodeSet &Dst) {
285296417Sdim
286226586Sdim  ExplodedNodeSet dstPreStmt;
287226586Sdim  getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
288296417Sdim
289234353Sdim  if (CastE->getCastKind() == CK_LValueToRValue) {
290226586Sdim    for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
291226586Sdim         I!=E; ++I) {
292226586Sdim      ExplodedNode *subExprNode = *I;
293234353Sdim      ProgramStateRef state = subExprNode->getState();
294234353Sdim      const LocationContext *LCtx = subExprNode->getLocationContext();
295234353Sdim      evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
296226586Sdim    }
297226586Sdim    return;
298226586Sdim  }
299296417Sdim
300296417Sdim  // All other casts.
301226586Sdim  QualType T = CastE->getType();
302226586Sdim  QualType ExTy = Ex->getType();
303296417Sdim
304226586Sdim  if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
305226586Sdim    T = ExCast->getTypeAsWritten();
306296417Sdim
307243830Sdim  StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
308226586Sdim  for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
309226586Sdim       I != E; ++I) {
310296417Sdim
311226586Sdim    Pred = *I;
312243830Sdim    ProgramStateRef state = Pred->getState();
313243830Sdim    const LocationContext *LCtx = Pred->getLocationContext();
314243830Sdim
315226586Sdim    switch (CastE->getCastKind()) {
316226586Sdim      case CK_LValueToRValue:
317226586Sdim        llvm_unreachable("LValueToRValue casts handled earlier.");
318226586Sdim      case CK_ToVoid:
319226586Sdim        continue;
320226586Sdim        // The analyzer doesn't do anything special with these casts,
321226586Sdim        // since it understands retain/release semantics already.
322226586Sdim      case CK_ARCProduceObject:
323226586Sdim      case CK_ARCConsumeObject:
324226586Sdim      case CK_ARCReclaimReturnedObject:
325226586Sdim      case CK_ARCExtendBlockObject: // Fall-through.
326234353Sdim      case CK_CopyAndAutoreleaseBlockObject:
327234353Sdim        // The analyser can ignore atomic casts for now, although some future
328234353Sdim        // checkers may want to make certain that you're not modifying the same
329234353Sdim        // value through atomic and nonatomic pointers.
330234353Sdim      case CK_AtomicToNonAtomic:
331234353Sdim      case CK_NonAtomicToAtomic:
332226586Sdim        // True no-ops.
333226586Sdim      case CK_NoOp:
334243830Sdim      case CK_ConstructorConversion:
335243830Sdim      case CK_UserDefinedConversion:
336243830Sdim      case CK_FunctionToPointerDecay:
337243830Sdim      case CK_BuiltinFnToFnPtr: {
338226586Sdim        // Copy the SVal of Ex to CastE.
339234353Sdim        ProgramStateRef state = Pred->getState();
340234353Sdim        const LocationContext *LCtx = Pred->getLocationContext();
341234353Sdim        SVal V = state->getSVal(Ex, LCtx);
342234353Sdim        state = state->BindExpr(CastE, LCtx, V);
343234353Sdim        Bldr.generateNode(CastE, Pred, state);
344226586Sdim        continue;
345226586Sdim      }
346243830Sdim      case CK_MemberPointerToBoolean:
347314564Sdim      case CK_PointerToBoolean: {
348314564Sdim        SVal V = state->getSVal(Ex, LCtx);
349314564Sdim        auto PTMSV = V.getAs<nonloc::PointerToMember>();
350314564Sdim        if (PTMSV)
351314564Sdim          V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy);
352314564Sdim        if (V.isUndef() || PTMSV) {
353314564Sdim          state = state->BindExpr(CastE, LCtx, V);
354314564Sdim          Bldr.generateNode(CastE, Pred, state);
355314564Sdim          continue;
356314564Sdim        }
357314564Sdim        // Explicitly proceed with default handler for this case cascade.
358314564Sdim        state =
359314564Sdim            handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
360314564Sdim        continue;
361314564Sdim      }
362226586Sdim      case CK_Dependent:
363226586Sdim      case CK_ArrayToPointerDecay:
364226586Sdim      case CK_BitCast:
365276479Sdim      case CK_AddressSpaceConversion:
366296417Sdim      case CK_BooleanToSignedIntegral:
367226586Sdim      case CK_NullToPointer:
368226586Sdim      case CK_IntegralToPointer:
369314564Sdim      case CK_PointerToIntegral: {
370314564Sdim        SVal V = state->getSVal(Ex, LCtx);
371314564Sdim        if (V.getAs<nonloc::PointerToMember>()) {
372314564Sdim          state = state->BindExpr(CastE, LCtx, UnknownVal());
373314564Sdim          Bldr.generateNode(CastE, Pred, state);
374314564Sdim          continue;
375314564Sdim        }
376314564Sdim        // Explicitly proceed with default handler for this case cascade.
377314564Sdim        state =
378314564Sdim            handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
379314564Sdim        continue;
380314564Sdim      }
381226586Sdim      case CK_IntegralToBoolean:
382226586Sdim      case CK_IntegralToFloating:
383226586Sdim      case CK_FloatingToIntegral:
384226586Sdim      case CK_FloatingToBoolean:
385226586Sdim      case CK_FloatingCast:
386226586Sdim      case CK_FloatingRealToComplex:
387226586Sdim      case CK_FloatingComplexToReal:
388226586Sdim      case CK_FloatingComplexToBoolean:
389226586Sdim      case CK_FloatingComplexCast:
390226586Sdim      case CK_FloatingComplexToIntegralComplex:
391226586Sdim      case CK_IntegralRealToComplex:
392226586Sdim      case CK_IntegralComplexToReal:
393226586Sdim      case CK_IntegralComplexToBoolean:
394226586Sdim      case CK_IntegralComplexCast:
395226586Sdim      case CK_IntegralComplexToFloatingComplex:
396226586Sdim      case CK_CPointerToObjCPointerCast:
397226586Sdim      case CK_BlockPointerToObjCPointerCast:
398296417Sdim      case CK_AnyPointerToBlockPointerCast:
399296417Sdim      case CK_ObjCObjectLValueCast:
400261991Sdim      case CK_ZeroToOCLEvent:
401314564Sdim      case CK_ZeroToOCLQueue:
402314564Sdim      case CK_IntToOCLSampler:
403261991Sdim      case CK_LValueBitCast: {
404314564Sdim        state =
405314564Sdim            handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
406226586Sdim        continue;
407226586Sdim      }
408296417Sdim      case CK_IntegralCast: {
409296417Sdim        // Delegate to SValBuilder to process.
410296417Sdim        SVal V = state->getSVal(Ex, LCtx);
411296417Sdim        V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
412296417Sdim        state = state->BindExpr(CastE, LCtx, V);
413296417Sdim        Bldr.generateNode(CastE, Pred, state);
414296417Sdim        continue;
415296417Sdim      }
416226586Sdim      case CK_DerivedToBase:
417226586Sdim      case CK_UncheckedDerivedToBase: {
418226586Sdim        // For DerivedToBase cast, delegate to the store manager.
419234353Sdim        SVal val = state->getSVal(Ex, LCtx);
420239462Sdim        val = getStoreManager().evalDerivedToBase(val, CastE);
421234353Sdim        state = state->BindExpr(CastE, LCtx, val);
422234353Sdim        Bldr.generateNode(CastE, Pred, state);
423226586Sdim        continue;
424226586Sdim      }
425234353Sdim      // Handle C++ dyn_cast.
426234353Sdim      case CK_Dynamic: {
427234353Sdim        SVal val = state->getSVal(Ex, LCtx);
428234353Sdim
429234353Sdim        // Compute the type of the result.
430234353Sdim        QualType resultType = CastE->getType();
431239462Sdim        if (CastE->isGLValue())
432234353Sdim          resultType = getContext().getPointerType(resultType);
433234353Sdim
434234353Sdim        bool Failed = false;
435234353Sdim
436234353Sdim        // Check if the value being cast evaluates to 0.
437234353Sdim        if (val.isZeroConstant())
438234353Sdim          Failed = true;
439234353Sdim        // Else, evaluate the cast.
440234353Sdim        else
441314564Sdim          val = getStoreManager().attemptDownCast(val, T, Failed);
442234353Sdim
443234353Sdim        if (Failed) {
444234353Sdim          if (T->isReferenceType()) {
445234353Sdim            // A bad_cast exception is thrown if input value is a reference.
446234353Sdim            // Currently, we model this, by generating a sink.
447243830Sdim            Bldr.generateSink(CastE, Pred, state);
448234353Sdim            continue;
449234353Sdim          } else {
450234353Sdim            // If the cast fails on a pointer, bind to 0.
451234353Sdim            state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
452234353Sdim          }
453234353Sdim        } else {
454234353Sdim          // If we don't know if the cast succeeded, conjure a new symbol.
455234353Sdim          if (val.isUnknown()) {
456243830Sdim            DefinedOrUnknownSVal NewSym =
457276479Sdim              svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
458243830Sdim                                           currBldrCtx->blockCount());
459234353Sdim            state = state->BindExpr(CastE, LCtx, NewSym);
460296417Sdim          } else
461234353Sdim            // Else, bind to the derived region value.
462234353Sdim            state = state->BindExpr(CastE, LCtx, val);
463234353Sdim        }
464234353Sdim        Bldr.generateNode(CastE, Pred, state);
465234353Sdim        continue;
466234353Sdim      }
467314564Sdim      case CK_BaseToDerived: {
468314564Sdim        SVal val = state->getSVal(Ex, LCtx);
469314564Sdim        QualType resultType = CastE->getType();
470314564Sdim        if (CastE->isGLValue())
471314564Sdim          resultType = getContext().getPointerType(resultType);
472314564Sdim
473314564Sdim        bool Failed = false;
474314564Sdim
475314564Sdim        if (!val.isConstant()) {
476314564Sdim          val = getStoreManager().attemptDownCast(val, T, Failed);
477314564Sdim        }
478314564Sdim
479314564Sdim        // Failed to cast or the result is unknown, fall back to conservative.
480314564Sdim        if (Failed || val.isUnknown()) {
481314564Sdim          val =
482314564Sdim            svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
483314564Sdim                                         currBldrCtx->blockCount());
484314564Sdim        }
485314564Sdim        state = state->BindExpr(CastE, LCtx, val);
486314564Sdim        Bldr.generateNode(CastE, Pred, state);
487314564Sdim        continue;
488314564Sdim      }
489243830Sdim      case CK_NullToMemberPointer: {
490314564Sdim        SVal V = svalBuilder.getMemberPointer(nullptr);
491243830Sdim        state = state->BindExpr(CastE, LCtx, V);
492243830Sdim        Bldr.generateNode(CastE, Pred, state);
493243830Sdim        continue;
494243830Sdim      }
495314564Sdim      case CK_DerivedToBaseMemberPointer:
496314564Sdim      case CK_BaseToDerivedMemberPointer:
497314564Sdim      case CK_ReinterpretMemberPointer: {
498314564Sdim        SVal V = state->getSVal(Ex, LCtx);
499314564Sdim        if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
500314564Sdim          SVal CastedPTMSV = svalBuilder.makePointerToMember(
501314564Sdim              getBasicVals().accumCXXBase(
502314564Sdim                  llvm::make_range<CastExpr::path_const_iterator>(
503314564Sdim                      CastE->path_begin(), CastE->path_end()), *PTMSV));
504314564Sdim          state = state->BindExpr(CastE, LCtx, CastedPTMSV);
505314564Sdim          Bldr.generateNode(CastE, Pred, state);
506314564Sdim          continue;
507314564Sdim        }
508314564Sdim        // Explicitly proceed with default handler for this case cascade.
509314564Sdim        state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
510314564Sdim        continue;
511314564Sdim      }
512234353Sdim      // Various C++ casts that are not handled yet.
513226586Sdim      case CK_ToUnion:
514261991Sdim      case CK_VectorSplat: {
515314564Sdim        state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
516226586Sdim        continue;
517226586Sdim      }
518226586Sdim    }
519226586Sdim  }
520226586Sdim}
521226586Sdim
522226586Sdimvoid ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
523226586Sdim                                          ExplodedNode *Pred,
524226586Sdim                                          ExplodedNodeSet &Dst) {
525243830Sdim  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
526234353Sdim
527251662Sdim  ProgramStateRef State = Pred->getState();
528251662Sdim  const LocationContext *LCtx = Pred->getLocationContext();
529251662Sdim
530251662Sdim  const Expr *Init = CL->getInitializer();
531251662Sdim  SVal V = State->getSVal(CL->getInitializer(), LCtx);
532296417Sdim
533251662Sdim  if (isa<CXXConstructExpr>(Init)) {
534251662Sdim    // No work needed. Just pass the value up to this expression.
535251662Sdim  } else {
536251662Sdim    assert(isa<InitListExpr>(Init));
537251662Sdim    Loc CLLoc = State->getLValue(CL, LCtx);
538321369Sdim    State = State->bindLoc(CLLoc, V, LCtx);
539239462Sdim
540314564Sdim    if (CL->isGLValue())
541251662Sdim      V = CLLoc;
542251662Sdim  }
543251662Sdim
544251662Sdim  B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
545226586Sdim}
546226586Sdim
547226586Sdimvoid ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
548226586Sdim                               ExplodedNodeSet &Dst) {
549226586Sdim  // Assumption: The CFG has one DeclStmt per Decl.
550249423Sdim  const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
551249423Sdim
552249423Sdim  if (!VD) {
553234353Sdim    //TODO:AZ: remove explicit insertion after refactoring is done.
554234353Sdim    Dst.insert(Pred);
555226586Sdim    return;
556234353Sdim  }
557296417Sdim
558226586Sdim  // FIXME: all pre/post visits should eventually be handled by ::Visit().
559226586Sdim  ExplodedNodeSet dstPreVisit;
560226586Sdim  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
561296417Sdim
562261991Sdim  ExplodedNodeSet dstEvaluated;
563261991Sdim  StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
564226586Sdim  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
565226586Sdim       I!=E; ++I) {
566226586Sdim    ExplodedNode *N = *I;
567234353Sdim    ProgramStateRef state = N->getState();
568249423Sdim    const LocationContext *LC = N->getLocationContext();
569249423Sdim
570226586Sdim    // Decls without InitExpr are not initialized explicitly.
571226586Sdim    if (const Expr *InitEx = VD->getInit()) {
572249423Sdim
573249423Sdim      // Note in the state that the initialization has occurred.
574249423Sdim      ExplodedNode *UpdatedN = N;
575239462Sdim      SVal InitVal = state->getSVal(InitEx, LC);
576234353Sdim
577296417Sdim      assert(DS->isSingleDecl());
578296417Sdim      if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
579296417Sdim        assert(InitEx->IgnoreImplicit() == CtorExpr);
580296417Sdim        (void)CtorExpr;
581239462Sdim        // We constructed the object directly in the variable.
582239462Sdim        // No need to bind anything.
583249423Sdim        B.generateNode(DS, UpdatedN, state);
584239462Sdim      } else {
585239462Sdim        // We bound the temp obj region to the CXXConstructExpr. Now recover
586239462Sdim        // the lazy compound value when the variable is not a reference.
587249423Sdim        if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
588249423Sdim            !VD->getType()->isReferenceType()) {
589249423Sdim          if (Optional<loc::MemRegionVal> M =
590249423Sdim                  InitVal.getAs<loc::MemRegionVal>()) {
591249423Sdim            InitVal = state->getSVal(M->getRegion());
592249423Sdim            assert(InitVal.getAs<nonloc::LazyCompoundVal>());
593249423Sdim          }
594239462Sdim        }
595296417Sdim
596239462Sdim        // Recover some path-sensitivity if a scalar value evaluated to
597239462Sdim        // UnknownVal.
598239462Sdim        if (InitVal.isUnknown()) {
599239462Sdim          QualType Ty = InitEx->getType();
600239462Sdim          if (InitEx->isGLValue()) {
601239462Sdim            Ty = getContext().getPointerType(Ty);
602239462Sdim          }
603239462Sdim
604276479Sdim          InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
605243830Sdim                                                 currBldrCtx->blockCount());
606239462Sdim        }
607249423Sdim
608249423Sdim
609249423Sdim        B.takeNodes(UpdatedN);
610239462Sdim        ExplodedNodeSet Dst2;
611249423Sdim        evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
612239462Sdim        B.addNodes(Dst2);
613226586Sdim      }
614226586Sdim    }
615226586Sdim    else {
616243830Sdim      B.generateNode(DS, N, state);
617226586Sdim    }
618226586Sdim  }
619261991Sdim
620261991Sdim  getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
621226586Sdim}
622226586Sdim
623226586Sdimvoid ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
624226586Sdim                                  ExplodedNodeSet &Dst) {
625226586Sdim  assert(B->getOpcode() == BO_LAnd ||
626226586Sdim         B->getOpcode() == BO_LOr);
627234353Sdim
628243830Sdim  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
629234353Sdim  ProgramStateRef state = Pred->getState();
630239462Sdim
631239462Sdim  ExplodedNode *N = Pred;
632249423Sdim  while (!N->getLocation().getAs<BlockEntrance>()) {
633239462Sdim    ProgramPoint P = N->getLocation();
634249423Sdim    assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
635239462Sdim    (void) P;
636239462Sdim    assert(N->pred_size() == 1);
637239462Sdim    N = *N->pred_begin();
638226586Sdim  }
639239462Sdim  assert(N->pred_size() == 1);
640239462Sdim  N = *N->pred_begin();
641249423Sdim  BlockEdge BE = N->getLocation().castAs<BlockEdge>();
642239462Sdim  SVal X;
643239462Sdim
644239462Sdim  // Determine the value of the expression by introspecting how we
645239462Sdim  // got this location in the CFG.  This requires looking at the previous
646239462Sdim  // block we were in and what kind of control-flow transfer was involved.
647239462Sdim  const CFGBlock *SrcBlock = BE.getSrc();
648239462Sdim  // The only terminator (if there is one) that makes sense is a logical op.
649239462Sdim  CFGTerminator T = SrcBlock->getTerminator();
650239462Sdim  if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
651239462Sdim    (void) Term;
652239462Sdim    assert(Term->isLogicalOp());
653239462Sdim    assert(SrcBlock->succ_size() == 2);
654239462Sdim    // Did we take the true or false branch?
655239462Sdim    unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
656239462Sdim    X = svalBuilder.makeIntVal(constant, B->getType());
657239462Sdim  }
658226586Sdim  else {
659239462Sdim    // If there is no terminator, by construction the last statement
660239462Sdim    // in SrcBlock is the value of the enclosing expression.
661243830Sdim    // However, we still need to constrain that value to be 0 or 1.
662239462Sdim    assert(!SrcBlock->empty());
663249423Sdim    CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
664243830Sdim    const Expr *RHS = cast<Expr>(Elem.getStmt());
665243830Sdim    SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
666243830Sdim
667249423Sdim    if (RHSVal.isUndef()) {
668249423Sdim      X = RHSVal;
669249423Sdim    } else {
670314564Sdim      // We evaluate "RHSVal != 0" expression which result in 0 if the value is
671314564Sdim      // known to be false, 1 if the value is known to be true and a new symbol
672314564Sdim      // when the assumption is unknown.
673314564Sdim      nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType()));
674314564Sdim      X = evalBinOp(N->getState(), BO_NE,
675314564Sdim                    svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()),
676314564Sdim                    Zero, B->getType());
677243830Sdim    }
678226586Sdim  }
679239462Sdim  Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
680226586Sdim}
681226586Sdim
682226586Sdimvoid ExprEngine::VisitInitListExpr(const InitListExpr *IE,
683226586Sdim                                   ExplodedNode *Pred,
684226586Sdim                                   ExplodedNodeSet &Dst) {
685243830Sdim  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
686226586Sdim
687234353Sdim  ProgramStateRef state = Pred->getState();
688234353Sdim  const LocationContext *LCtx = Pred->getLocationContext();
689226586Sdim  QualType T = getContext().getCanonicalType(IE->getType());
690226586Sdim  unsigned NumInitElements = IE->getNumInits();
691261991Sdim
692261991Sdim  if (!IE->isGLValue() &&
693261991Sdim      (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
694261991Sdim       T->isAnyComplexType())) {
695226586Sdim    llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
696296417Sdim
697226586Sdim    // Handle base case where the initializer has no elements.
698226586Sdim    // e.g: static int* myArray[] = {};
699226586Sdim    if (NumInitElements == 0) {
700226586Sdim      SVal V = svalBuilder.makeCompoundVal(T, vals);
701234353Sdim      B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
702226586Sdim      return;
703226586Sdim    }
704296417Sdim
705226586Sdim    for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
706226586Sdim         ei = IE->rend(); it != ei; ++it) {
707249423Sdim      SVal V = state->getSVal(cast<Expr>(*it), LCtx);
708314564Sdim      vals = getBasicVals().prependSVal(V, vals);
709226586Sdim    }
710296417Sdim
711234353Sdim    B.generateNode(IE, Pred,
712234353Sdim                   state->BindExpr(IE, LCtx,
713234353Sdim                                   svalBuilder.makeCompoundVal(T, vals)));
714226586Sdim    return;
715226586Sdim  }
716239462Sdim
717261991Sdim  // Handle scalars: int{5} and int{} and GLvalues.
718261991Sdim  // Note, if the InitListExpr is a GLvalue, it means that there is an address
719261991Sdim  // representing it, so it must have a single init element.
720239462Sdim  assert(NumInitElements <= 1);
721239462Sdim
722239462Sdim  SVal V;
723239462Sdim  if (NumInitElements == 0)
724239462Sdim    V = getSValBuilder().makeZeroVal(T);
725239462Sdim  else
726239462Sdim    V = state->getSVal(IE->getInit(0), LCtx);
727239462Sdim
728239462Sdim  B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
729226586Sdim}
730226586Sdim
731226586Sdimvoid ExprEngine::VisitGuardedExpr(const Expr *Ex,
732296417Sdim                                  const Expr *L,
733226586Sdim                                  const Expr *R,
734226586Sdim                                  ExplodedNode *Pred,
735226586Sdim                                  ExplodedNodeSet &Dst) {
736251662Sdim  assert(L && R);
737251662Sdim
738243830Sdim  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
739234353Sdim  ProgramStateRef state = Pred->getState();
740234353Sdim  const LocationContext *LCtx = Pred->getLocationContext();
741276479Sdim  const CFGBlock *SrcBlock = nullptr;
742239462Sdim
743251662Sdim  // Find the predecessor block.
744251662Sdim  ProgramStateRef SrcState = state;
745239462Sdim  for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
746239462Sdim    ProgramPoint PP = N->getLocation();
747249423Sdim    if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
748239462Sdim      assert(N->pred_size() == 1);
749239462Sdim      continue;
750239462Sdim    }
751249423Sdim    SrcBlock = PP.castAs<BlockEdge>().getSrc();
752251662Sdim    SrcState = N->getState();
753239462Sdim    break;
754239462Sdim  }
755239462Sdim
756249423Sdim  assert(SrcBlock && "missing function entry");
757249423Sdim
758239462Sdim  // Find the last expression in the predecessor block.  That is the
759239462Sdim  // expression that is used for the value of the ternary expression.
760239462Sdim  bool hasValue = false;
761239462Sdim  SVal V;
762239462Sdim
763296417Sdim  for (CFGElement CE : llvm::reverse(*SrcBlock)) {
764249423Sdim    if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
765239462Sdim      const Expr *ValEx = cast<Expr>(CS->getStmt());
766251662Sdim      ValEx = ValEx->IgnoreParens();
767251662Sdim
768251662Sdim      // For GNU extension '?:' operator, the left hand side will be an
769251662Sdim      // OpaqueValueExpr, so get the underlying expression.
770251662Sdim      if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
771251662Sdim        L = OpaqueEx->getSourceExpr();
772251662Sdim
773251662Sdim      // If the last expression in the predecessor block matches true or false
774251662Sdim      // subexpression, get its the value.
775251662Sdim      if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
776251662Sdim        hasValue = true;
777251662Sdim        V = SrcState->getSVal(ValEx, LCtx);
778251662Sdim      }
779239462Sdim      break;
780239462Sdim    }
781239462Sdim  }
782239462Sdim
783251662Sdim  if (!hasValue)
784276479Sdim    V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
785276479Sdim                                     currBldrCtx->blockCount());
786239462Sdim
787239462Sdim  // Generate a new node with the binding from the appropriate path.
788239462Sdim  B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
789226586Sdim}
790226586Sdim
791226586Sdimvoid ExprEngine::
792296417SdimVisitOffsetOfExpr(const OffsetOfExpr *OOE,
793226586Sdim                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
794243830Sdim  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
795234353Sdim  APSInt IV;
796234353Sdim  if (OOE->EvaluateAsInt(IV, getContext())) {
797226586Sdim    assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
798251662Sdim    assert(OOE->getType()->isBuiltinType());
799251662Sdim    assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
800251662Sdim    assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
801226586Sdim    SVal X = svalBuilder.makeIntVal(IV);
802234353Sdim    B.generateNode(OOE, Pred,
803234353Sdim                   Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
804234353Sdim                                              X));
805226586Sdim  }
806226586Sdim  // FIXME: Handle the case where __builtin_offsetof is not a constant.
807226586Sdim}
808226586Sdim
809226586Sdim
810226586Sdimvoid ExprEngine::
811226586SdimVisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
812226586Sdim                              ExplodedNode *Pred,
813226586Sdim                              ExplodedNodeSet &Dst) {
814276479Sdim  // FIXME: Prechecks eventually go in ::Visit().
815276479Sdim  ExplodedNodeSet CheckedSet;
816276479Sdim  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
817226586Sdim
818276479Sdim  ExplodedNodeSet EvalSet;
819276479Sdim  StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
820276479Sdim
821226586Sdim  QualType T = Ex->getTypeOfArgument();
822276479Sdim
823276479Sdim  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
824276479Sdim       I != E; ++I) {
825276479Sdim    if (Ex->getKind() == UETT_SizeOf) {
826276479Sdim      if (!T->isIncompleteType() && !T->isConstantSizeType()) {
827276479Sdim        assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
828296417Sdim
829276479Sdim        // FIXME: Add support for VLA type arguments and VLA expressions.
830276479Sdim        // When that happens, we should probably refactor VLASizeChecker's code.
831276479Sdim        continue;
832276479Sdim      } else if (T->getAs<ObjCObjectType>()) {
833276479Sdim        // Some code tries to take the sizeof an ObjCObjectType, relying that
834276479Sdim        // the compiler has laid out its representation.  Just report Unknown
835276479Sdim        // for these.
836276479Sdim        continue;
837276479Sdim      }
838226586Sdim    }
839296417Sdim
840276479Sdim    APSInt Value = Ex->EvaluateKnownConstInt(getContext());
841276479Sdim    CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
842296417Sdim
843276479Sdim    ProgramStateRef state = (*I)->getState();
844276479Sdim    state = state->BindExpr(Ex, (*I)->getLocationContext(),
845276479Sdim                            svalBuilder.makeIntVal(amt.getQuantity(),
846276479Sdim                                                   Ex->getType()));
847276479Sdim    Bldr.generateNode(Ex, *I, state);
848226586Sdim  }
849276479Sdim
850276479Sdim  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
851226586Sdim}
852226586Sdim
853314564Sdimvoid ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
854314564Sdim                                   const UnaryOperator *U,
855314564Sdim                                   StmtNodeBuilder &Bldr) {
856314564Sdim  // FIXME: We can probably just have some magic in Environment::getSVal()
857314564Sdim  // that propagates values, instead of creating a new node here.
858314564Sdim  //
859314564Sdim  // Unary "+" is a no-op, similar to a parentheses.  We still have places
860314564Sdim  // where it may be a block-level expression, so we need to
861314564Sdim  // generate an extra node that just propagates the value of the
862314564Sdim  // subexpression.
863314564Sdim  const Expr *Ex = U->getSubExpr()->IgnoreParens();
864314564Sdim  ProgramStateRef state = (*I)->getState();
865314564Sdim  const LocationContext *LCtx = (*I)->getLocationContext();
866314564Sdim  Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
867314564Sdim                                           state->getSVal(Ex, LCtx)));
868314564Sdim}
869314564Sdim
870314564Sdimvoid ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
871234353Sdim                                    ExplodedNodeSet &Dst) {
872261991Sdim  // FIXME: Prechecks eventually go in ::Visit().
873261991Sdim  ExplodedNodeSet CheckedSet;
874261991Sdim  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
875261991Sdim
876261991Sdim  ExplodedNodeSet EvalSet;
877261991Sdim  StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
878261991Sdim
879261991Sdim  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
880261991Sdim       I != E; ++I) {
881261991Sdim    switch (U->getOpcode()) {
882234353Sdim    default: {
883261991Sdim      Bldr.takeNodes(*I);
884234353Sdim      ExplodedNodeSet Tmp;
885261991Sdim      VisitIncrementDecrementOperator(U, *I, Tmp);
886234353Sdim      Bldr.addNodes(Tmp);
887261991Sdim      break;
888234353Sdim    }
889226586Sdim    case UO_Real: {
890226586Sdim      const Expr *Ex = U->getSubExpr()->IgnoreParens();
891296417Sdim
892234353Sdim      // FIXME: We don't have complex SValues yet.
893234353Sdim      if (Ex->getType()->isAnyComplexType()) {
894234353Sdim        // Just report "Unknown."
895234353Sdim        break;
896234353Sdim      }
897296417Sdim
898234353Sdim      // For all other types, UO_Real is an identity operation.
899234353Sdim      assert (U->getType() == Ex->getType());
900261991Sdim      ProgramStateRef state = (*I)->getState();
901261991Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
902261991Sdim      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
903261991Sdim                                               state->getSVal(Ex, LCtx)));
904234353Sdim      break;
905226586Sdim    }
906296417Sdim
907296417Sdim    case UO_Imag: {
908226586Sdim      const Expr *Ex = U->getSubExpr()->IgnoreParens();
909234353Sdim      // FIXME: We don't have complex SValues yet.
910234353Sdim      if (Ex->getType()->isAnyComplexType()) {
911234353Sdim        // Just report "Unknown."
912234353Sdim        break;
913226586Sdim      }
914234353Sdim      // For all other types, UO_Imag returns 0.
915261991Sdim      ProgramStateRef state = (*I)->getState();
916261991Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
917234353Sdim      SVal X = svalBuilder.makeZeroVal(Ex->getType());
918261991Sdim      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
919234353Sdim      break;
920226586Sdim    }
921296417Sdim
922314564Sdim    case UO_AddrOf: {
923314564Sdim      // Process pointer-to-member address operation.
924314564Sdim      const Expr *Ex = U->getSubExpr()->IgnoreParens();
925314564Sdim      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
926314564Sdim        const ValueDecl *VD = DRE->getDecl();
927314564Sdim
928314564Sdim        if (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD)) {
929314564Sdim          ProgramStateRef State = (*I)->getState();
930314564Sdim          const LocationContext *LCtx = (*I)->getLocationContext();
931314564Sdim          SVal SV = svalBuilder.getMemberPointer(cast<DeclaratorDecl>(VD));
932314564Sdim          Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
933314564Sdim          break;
934314564Sdim        }
935314564Sdim      }
936314564Sdim      // Explicitly proceed with default handler for this case cascade.
937314564Sdim      handleUOExtension(I, U, Bldr);
938314564Sdim      break;
939314564Sdim    }
940226586Sdim    case UO_Plus:
941239462Sdim      assert(!U->isGLValue());
942226586Sdim      // FALL-THROUGH.
943226586Sdim    case UO_Deref:
944226586Sdim    case UO_Extension: {
945314564Sdim      handleUOExtension(I, U, Bldr);
946234353Sdim      break;
947226586Sdim    }
948296417Sdim
949226586Sdim    case UO_LNot:
950226586Sdim    case UO_Minus:
951226586Sdim    case UO_Not: {
952239462Sdim      assert (!U->isGLValue());
953226586Sdim      const Expr *Ex = U->getSubExpr()->IgnoreParens();
954261991Sdim      ProgramStateRef state = (*I)->getState();
955261991Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
956296417Sdim
957234353Sdim      // Get the value of the subexpression.
958234353Sdim      SVal V = state->getSVal(Ex, LCtx);
959296417Sdim
960234353Sdim      if (V.isUnknownOrUndef()) {
961261991Sdim        Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
962234353Sdim        break;
963234353Sdim      }
964296417Sdim
965234353Sdim      switch (U->getOpcode()) {
966234353Sdim        default:
967234353Sdim          llvm_unreachable("Invalid Opcode.");
968234353Sdim        case UO_Not:
969234353Sdim          // FIXME: Do we need to handle promotions?
970249423Sdim          state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
971234353Sdim          break;
972234353Sdim        case UO_Minus:
973234353Sdim          // FIXME: Do we need to handle promotions?
974249423Sdim          state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
975234353Sdim          break;
976234353Sdim        case UO_LNot:
977234353Sdim          // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
978234353Sdim          //
979234353Sdim          //  Note: technically we do "E == 0", but this is the same in the
980234353Sdim          //    transfer functions as "0 == E".
981296417Sdim          SVal Result;
982249423Sdim          if (Optional<Loc> LV = V.getAs<Loc>()) {
983321369Sdim            Loc X = svalBuilder.makeNullWithType(Ex->getType());
984249423Sdim            Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
985321369Sdim          } else if (Ex->getType()->isFloatingType()) {
986249423Sdim            // FIXME: handle floating point types.
987249423Sdim            Result = UnknownVal();
988249423Sdim          } else {
989234353Sdim            nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
990249423Sdim            Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
991234353Sdim                               U->getType());
992234353Sdim          }
993296417Sdim
994296417Sdim          state = state->BindExpr(U, LCtx, Result);
995234353Sdim          break;
996226586Sdim      }
997261991Sdim      Bldr.generateNode(U, *I, state);
998234353Sdim      break;
999226586Sdim    }
1000261991Sdim    }
1001226586Sdim  }
1002234353Sdim
1003261991Sdim  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
1004234353Sdim}
1005234353Sdim
1006234353Sdimvoid ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
1007234353Sdim                                                 ExplodedNode *Pred,
1008234353Sdim                                                 ExplodedNodeSet &Dst) {
1009226586Sdim  // Handle ++ and -- (both pre- and post-increment).
1010226586Sdim  assert (U->isIncrementDecrementOp());
1011226586Sdim  const Expr *Ex = U->getSubExpr()->IgnoreParens();
1012296417Sdim
1013234353Sdim  const LocationContext *LCtx = Pred->getLocationContext();
1014234353Sdim  ProgramStateRef state = Pred->getState();
1015234353Sdim  SVal loc = state->getSVal(Ex, LCtx);
1016296417Sdim
1017234353Sdim  // Perform a load.
1018234353Sdim  ExplodedNodeSet Tmp;
1019234353Sdim  evalLoad(Tmp, U, Ex, Pred, state, loc);
1020296417Sdim
1021234353Sdim  ExplodedNodeSet Dst2;
1022243830Sdim  StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
1023234353Sdim  for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
1024296417Sdim
1025234353Sdim    state = (*I)->getState();
1026234353Sdim    assert(LCtx == (*I)->getLocationContext());
1027234353Sdim    SVal V2_untested = state->getSVal(Ex, LCtx);
1028296417Sdim
1029234353Sdim    // Propagate unknown and undefined values.
1030234353Sdim    if (V2_untested.isUnknownOrUndef()) {
1031234353Sdim      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
1032234353Sdim      continue;
1033234353Sdim    }
1034249423Sdim    DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
1035296417Sdim
1036234353Sdim    // Handle all other values.
1037234353Sdim    BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
1038296417Sdim
1039234353Sdim    // If the UnaryOperator has non-location type, use its type to create the
1040234353Sdim    // constant value. If the UnaryOperator has location type, create the
1041234353Sdim    // constant with int type and pointer width.
1042234353Sdim    SVal RHS;
1043296417Sdim
1044234353Sdim    if (U->getType()->isAnyPointerType())
1045234353Sdim      RHS = svalBuilder.makeArrayIndex(1);
1046243830Sdim    else if (U->getType()->isIntegralOrEnumerationType())
1047243830Sdim      RHS = svalBuilder.makeIntVal(1, U->getType());
1048234353Sdim    else
1049243830Sdim      RHS = UnknownVal();
1050296417Sdim
1051234353Sdim    SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
1052296417Sdim
1053234353Sdim    // Conjure a new symbol if necessary to recover precision.
1054234353Sdim    if (Result.isUnknown()){
1055234353Sdim      DefinedOrUnknownSVal SymVal =
1056321369Sdim        svalBuilder.conjureSymbolVal(nullptr, U, LCtx,
1057276479Sdim                                     currBldrCtx->blockCount());
1058234353Sdim      Result = SymVal;
1059296417Sdim
1060234353Sdim      // If the value is a location, ++/-- should always preserve
1061234353Sdim      // non-nullness.  Check if the original value was non-null, and if so
1062234353Sdim      // propagate that constraint.
1063234353Sdim      if (Loc::isLocType(U->getType())) {
1064234353Sdim        DefinedOrUnknownSVal Constraint =
1065234353Sdim        svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
1066296417Sdim
1067234353Sdim        if (!state->assume(Constraint, true)) {
1068234353Sdim          // It isn't feasible for the original value to be null.
1069234353Sdim          // Propagate this constraint.
1070234353Sdim          Constraint = svalBuilder.evalEQ(state, SymVal,
1071234353Sdim                                       svalBuilder.makeZeroVal(U->getType()));
1072296417Sdim
1073296417Sdim
1074234353Sdim          state = state->assume(Constraint, false);
1075234353Sdim          assert(state);
1076226586Sdim        }
1077226586Sdim      }
1078226586Sdim    }
1079296417Sdim
1080234353Sdim    // Since the lvalue-to-rvalue conversion is explicit in the AST,
1081234353Sdim    // we bind an l-value if the operator is prefix and an lvalue (in C++).
1082239462Sdim    if (U->isGLValue())
1083234353Sdim      state = state->BindExpr(U, LCtx, loc);
1084234353Sdim    else
1085234353Sdim      state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
1086296417Sdim
1087234353Sdim    // Perform the store.
1088234353Sdim    Bldr.takeNodes(*I);
1089234353Sdim    ExplodedNodeSet Dst3;
1090234353Sdim    evalStore(Dst3, U, U, *I, state, loc, Result);
1091234353Sdim    Bldr.addNodes(Dst3);
1092226586Sdim  }
1093234353Sdim  Dst.insert(Dst2);
1094226586Sdim}
1095