Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
Line
Count
Source (jump to first uncovered line)
1
//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines ExprEngine's support for C expressions.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ExprCXX.h"
14
#include "clang/AST/DeclCXX.h"
15
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
16
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17
18
using namespace clang;
19
using namespace ento;
20
using llvm::APSInt;
21
22
/// Optionally conjure and return a symbol for offset when processing
23
/// an expression \p Expression.
24
/// If \p Other is a location, conjure a symbol for \p Symbol
25
/// (offset) if it is unknown so that memory arithmetic always
26
/// results in an ElementRegion.
27
/// \p Count The number of times the current basic block was visited.
28
static SVal conjureOffsetSymbolOnLocation(
29
    SVal Symbol, SVal Other, Expr* Expression, SValBuilder &svalBuilder,
30
25.5k
    unsigned Count, const LocationContext *LCtx) {
31
25.5k
  QualType Ty = Expression->getType();
32
25.5k
  if (Other.getAs<Loc>() &&
33
10.1k
      Ty->isIntegralOrEnumerationType() &&
34
9.99k
      Symbol.isUnknown()) {
35
0
    return svalBuilder.conjureSymbolVal(Expression, LCtx, Ty, Count);
36
0
  }
37
25.5k
  return Symbol;
38
25.5k
}
39
40
void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
41
                                     ExplodedNode *Pred,
42
72.7k
                                     ExplodedNodeSet &Dst) {
43
44
72.7k
  Expr *LHS = B->getLHS()->IgnoreParens();
45
72.7k
  Expr *RHS = B->getRHS()->IgnoreParens();
46
47
  // FIXME: Prechecks eventually go in ::Visit().
48
72.7k
  ExplodedNodeSet CheckedSet;
49
72.7k
  ExplodedNodeSet Tmp2;
50
72.7k
  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
51
52
  // With both the LHS and RHS evaluated, process the operation itself.
53
72.7k
  for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
54
145k
         it != ei; 
++it72.5k
) {
55
56
72.5k
    ProgramStateRef state = (*it)->getState();
57
72.5k
    const LocationContext *LCtx = (*it)->getLocationContext();
58
72.5k
    SVal LeftV = state->getSVal(LHS, LCtx);
59
72.5k
    SVal RightV = state->getSVal(RHS, LCtx);
60
61
72.5k
    BinaryOperator::Opcode Op = B->getOpcode();
62
63
72.5k
    if (Op == BO_Assign) {
64
      // EXPERIMENTAL: "Conjured" symbols.
65
      // FIXME: Handle structs.
66
20.8k
      if (RightV.isUnknown()) {
67
2.96k
        unsigned Count = currBldrCtx->blockCount();
68
2.96k
        RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
69
2.96k
                                              Count);
70
2.96k
      }
71
      // Simulate the effects of a "store":  bind the value of the RHS
72
      // to the L-Value represented by the LHS.
73
14.8k
      SVal ExprVal = B->isGLValue() ? LeftV : 
RightV6.00k
;
74
20.8k
      evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
75
20.8k
                LeftV, RightV);
76
20.8k
      continue;
77
20.8k
    }
78
79
51.6k
    if (!B->isAssignmentOp()) {
80
50.6k
      StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
81
82
50.6k
      if (B->isAdditiveOp()) {
83
        // TODO: This can be removed after we enable history tracking with
84
        // SymSymExpr.
85
12.7k
        unsigned Count = currBldrCtx->blockCount();
86
12.7k
        RightV = conjureOffsetSymbolOnLocation(
87
12.7k
            RightV, LeftV, RHS, svalBuilder, Count, LCtx);
88
12.7k
        LeftV = conjureOffsetSymbolOnLocation(
89
12.7k
            LeftV, RightV, LHS, svalBuilder, Count, LCtx);
90
12.7k
      }
91
92
      // Although we don't yet model pointers-to-members, we do need to make
93
      // sure that the members of temporaries have a valid 'this' pointer for
94
      // other checks.
95
50.6k
      if (B->getOpcode() == BO_PtrMemD)
96
20
        state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
97
98
      // Process non-assignments except commas or short-circuited
99
      // logical expressions (LAnd and LOr).
100
50.6k
      SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
101
50.6k
      if (!Result.isUnknown()) {
102
49.8k
        state = state->BindExpr(B, LCtx, Result);
103
829
      } else {
104
        // If we cannot evaluate the operation escape the operands.
105
829
        state = escapeValues(state, LeftV, PSK_EscapeOther);
106
829
        state = escapeValues(state, RightV, PSK_EscapeOther);
107
829
      }
108
109
50.6k
      Bldr.generateNode(B, *it, state);
110
50.6k
      continue;
111
50.6k
    }
112
113
1.01k
    assert (B->isCompoundAssignmentOp());
114
115
1.01k
    switch (Op) {
116
0
      default:
117
0
        llvm_unreachable("Invalid opcode for compound assignment.");
118
32
      case BO_MulAssign: Op = BO_Mul; break;
119
29
      case BO_DivAssign: Op = BO_Div; break;
120
12
      case BO_RemAssign: Op = BO_Rem; break;
121
471
      case BO_AddAssign: Op = BO_Add; break;
122
189
      case BO_SubAssign: Op = BO_Sub; break;
123
20
      case BO_ShlAssign: Op = BO_Shl; break;
124
8
      case BO_ShrAssign: Op = BO_Shr; break;
125
171
      case BO_AndAssign: Op = BO_And; break;
126
66
      case BO_XorAssign: Op = BO_Xor; break;
127
20
      case BO_OrAssign:  Op = BO_Or;  break;
128
1.01k
    }
129
130
    // Perform a load (the LHS).  This performs the checks for
131
    // null dereferences, and so on.
132
1.01k
    ExplodedNodeSet Tmp;
133
1.01k
    SVal location = LeftV;
134
1.01k
    evalLoad(Tmp, B, LHS, *it, state, location);
135
136
2.03k
    for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
137
1.01k
         ++I) {
138
139
1.01k
      state = (*I)->getState();
140
1.01k
      const LocationContext *LCtx = (*I)->getLocationContext();
141
1.01k
      SVal V = state->getSVal(LHS, LCtx);
142
143
      // Get the computation type.
144
1.01k
      QualType CTy =
145
1.01k
        cast<CompoundAssignOperator>(B)->getComputationResultType();
146
1.01k
      CTy = getContext().getCanonicalType(CTy);
147
148
1.01k
      QualType CLHSTy =
149
1.01k
        cast<CompoundAssignOperator>(B)->getComputationLHSType();
150
1.01k
      CLHSTy = getContext().getCanonicalType(CLHSTy);
151
152
1.01k
      QualType LTy = getContext().getCanonicalType(LHS->getType());
153
154
      // Promote LHS.
155
1.01k
      V = svalBuilder.evalCast(V, CLHSTy, LTy);
156
157
      // Compute the result of the operation.
158
1.01k
      SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
159
1.01k
                                         B->getType(), CTy);
160
161
      // EXPERIMENTAL: "Conjured" symbols.
162
      // FIXME: Handle structs.
163
164
1.01k
      SVal LHSVal;
165
166
1.01k
      if (Result.isUnknown()) {
167
        // The symbolic value is actually for the type of the left-hand side
168
        // expression, not the computation type, as this is the value the
169
        // LValue on the LHS will bind to.
170
179
        LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
171
179
                                              currBldrCtx->blockCount());
172
        // However, we need to convert the symbol to the computation type.
173
179
        Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
174
179
      }
175
837
      else {
176
        // The left-hand side may bind to a different value then the
177
        // computation type.
178
837
        LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
179
837
      }
180
181
      // In C++, assignment and compound assignment operators return an
182
      // lvalue.
183
1.01k
      if (B->isGLValue())
184
260
        state = state->BindExpr(B, LCtx, location);
185
756
      else
186
756
        state = state->BindExpr(B, LCtx, Result);
187
188
1.01k
      evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
189
1.01k
    }
190
1.01k
  }
191
192
  // FIXME: postvisits eventually go in ::Visit()
193
72.7k
  getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
194
72.7k
}
195
196
void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
197
380
                                ExplodedNodeSet &Dst) {
198
199
380
  CanQualType T = getContext().getCanonicalType(BE->getType());
200
201
380
  const BlockDecl *BD = BE->getBlockDecl();
202
  // Get the value of the block itself.
203
380
  SVal V = svalBuilder.getBlockPointer(BD, T,
204
380
                                       Pred->getLocationContext(),
205
380
                                       currBldrCtx->blockCount());
206
207
380
  ProgramStateRef State = Pred->getState();
208
209
  // If we created a new MemRegion for the block, we should explicitly bind
210
  // the captured variables.
211
380
  if (const BlockDataRegion *BDR =
212
380
      dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
213
214
380
    BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
215
380
                                              E = BDR->referenced_vars_end();
216
217
380
    auto CI = BD->capture_begin();
218
380
    auto CE = BD->capture_end();
219
697
    for (; I != E; 
++I317
) {
220
317
      const VarRegion *capturedR = I.getCapturedRegion();
221
317
      const TypedValueRegion *originalR = I.getOriginalRegion();
222
223
      // If the capture had a copy expression, use the result of evaluating
224
      // that expression, otherwise use the original value.
225
      // We rely on the invariant that the block declaration's capture variables
226
      // are a prefix of the BlockDataRegion's referenced vars (which may include
227
      // referenced globals, etc.) to enable fast lookup of the capture for a
228
      // given referenced var.
229
317
      const Expr *copyExpr = nullptr;
230
317
      if (CI != CE) {
231
277
        assert(CI->getVariable() == capturedR->getDecl());
232
277
        copyExpr = CI->getCopyExpr();
233
277
        CI++;
234
277
      }
235
236
317
      if (capturedR != originalR) {
237
205
        SVal originalV;
238
205
        const LocationContext *LCtx = Pred->getLocationContext();
239
205
        if (copyExpr) {
240
10
          originalV = State->getSVal(copyExpr, LCtx);
241
195
        } else {
242
195
          originalV = State->getSVal(loc::MemRegionVal(originalR));
243
195
        }
244
205
        State = State->bindLoc(loc::MemRegionVal(capturedR), originalV, LCtx);
245
205
      }
246
317
    }
247
380
  }
248
249
380
  ExplodedNodeSet Tmp;
250
380
  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
251
380
  Bldr.generateNode(BE, Pred,
252
380
                    State->BindExpr(BE, Pred->getLocationContext(), V),
253
380
                    nullptr, ProgramPoint::PostLValueKind);
254
255
  // FIXME: Move all post/pre visits to ::Visit().
256
380
  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
257
380
}
258
259
ProgramStateRef ExprEngine::handleLValueBitCast(
260
    ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx,
261
    QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr,
262
46.5k
    ExplodedNode* Pred) {
263
46.5k
  if (T->isLValueReferenceType()) {
264
6
    assert(!CastE->getType()->isLValueReferenceType());
265
6
    ExTy = getContext().getLValueReferenceType(ExTy);
266
46.5k
  } else if (T->isRValueReferenceType()) {
267
1
    assert(!CastE->getType()->isRValueReferenceType());
268
1
    ExTy = getContext().getRValueReferenceType(ExTy);
269
1
  }
270
  // Delegate to SValBuilder to process.
271
46.5k
  SVal OrigV = state->getSVal(Ex, LCtx);
272
46.5k
  SVal V = svalBuilder.evalCast(OrigV, T, ExTy);
273
  // Negate the result if we're treating the boolean as a signed i1
274
46.5k
  if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
275
0
    V = evalMinus(V);
276
46.5k
  state = state->BindExpr(CastE, LCtx, V);
277
46.5k
  if (V.isUnknown() && 
!OrigV.isUnknown()879
) {
278
242
    state = escapeValues(state, OrigV, PSK_EscapeOther);
279
242
  }
280
46.5k
  Bldr.generateNode(CastE, Pred, state);
281
282
46.5k
  return state;
283
46.5k
}
284
285
ProgramStateRef ExprEngine::handleLVectorSplat(
286
    ProgramStateRef state, const LocationContext* LCtx, const CastExpr* CastE,
287
0
    StmtNodeBuilder &Bldr, ExplodedNode* Pred) {
288
  // Recover some path sensitivity by conjuring a new value.
289
0
  QualType resultType = CastE->getType();
290
0
  if (CastE->isGLValue())
291
0
    resultType = getContext().getPointerType(resultType);
292
0
  SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
293
0
                                             resultType,
294
0
                                             currBldrCtx->blockCount());
295
0
  state = state->BindExpr(CastE, LCtx, result);
296
0
  Bldr.generateNode(CastE, Pred, state);
297
298
0
  return state;
299
0
}
300
301
void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
302
319k
                           ExplodedNode *Pred, ExplodedNodeSet &Dst) {
303
304
319k
  ExplodedNodeSet dstPreStmt;
305
319k
  getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
306
307
319k
  if (CastE->getCastKind() == CK_LValueToRValue) {
308
138k
    for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
309
277k
         I!=E; 
++I138k
) {
310
138k
      ExplodedNode *subExprNode = *I;
311
138k
      ProgramStateRef state = subExprNode->getState();
312
138k
      const LocationContext *LCtx = subExprNode->getLocationContext();
313
138k
      evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
314
138k
    }
315
138k
    return;
316
138k
  }
317
318
  // All other casts.
319
181k
  QualType T = CastE->getType();
320
181k
  QualType ExTy = Ex->getType();
321
322
181k
  if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
323
18.0k
    T = ExCast->getTypeAsWritten();
324
325
181k
  StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
326
181k
  for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
327
362k
       I != E; 
++I181k
) {
328
329
181k
    Pred = *I;
330
181k
    ProgramStateRef state = Pred->getState();
331
181k
    const LocationContext *LCtx = Pred->getLocationContext();
332
333
181k
    switch (CastE->getCastKind()) {
334
0
      case CK_LValueToRValue:
335
0
        llvm_unreachable("LValueToRValue casts handled earlier.");
336
838
      case CK_ToVoid:
337
838
        continue;
338
        // The analyzer doesn't do anything special with these casts,
339
        // since it understands retain/release semantics already.
340
96.7k
      case CK_ARCProduceObject:
341
96.7k
      case CK_ARCConsumeObject:
342
96.7k
      case CK_ARCReclaimReturnedObject:
343
96.7k
      case CK_ARCExtendBlockObject: // Fall-through.
344
96.7k
      case CK_CopyAndAutoreleaseBlockObject:
345
        // The analyser can ignore atomic casts for now, although some future
346
        // checkers may want to make certain that you're not modifying the same
347
        // value through atomic and nonatomic pointers.
348
96.7k
      case CK_AtomicToNonAtomic:
349
96.7k
      case CK_NonAtomicToAtomic:
350
        // True no-ops.
351
96.7k
      case CK_NoOp:
352
96.7k
      case CK_ConstructorConversion:
353
96.7k
      case CK_UserDefinedConversion:
354
96.7k
      case CK_FunctionToPointerDecay:
355
96.7k
      case CK_BuiltinFnToFnPtr: {
356
        // Copy the SVal of Ex to CastE.
357
96.7k
        ProgramStateRef state = Pred->getState();
358
96.7k
        const LocationContext *LCtx = Pred->getLocationContext();
359
96.7k
        SVal V = state->getSVal(Ex, LCtx);
360
96.7k
        state = state->BindExpr(CastE, LCtx, V);
361
96.7k
        Bldr.generateNode(CastE, Pred, state);
362
96.7k
        continue;
363
96.7k
      }
364
898
      case CK_MemberPointerToBoolean:
365
898
      case CK_PointerToBoolean: {
366
898
        SVal V = state->getSVal(Ex, LCtx);
367
898
        auto PTMSV = V.getAs<nonloc::PointerToMember>();
368
898
        if (PTMSV)
369
20
          V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy);
370
898
        if (V.isUndef() || PTMSV) {
371
20
          state = state->BindExpr(CastE, LCtx, V);
372
20
          Bldr.generateNode(CastE, Pred, state);
373
20
          continue;
374
20
        }
375
        // Explicitly proceed with default handler for this case cascade.
376
878
        state =
377
878
            handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
378
878
        continue;
379
878
      }
380
20.3k
      case CK_Dependent:
381
20.3k
      case CK_ArrayToPointerDecay:
382
20.3k
      case CK_BitCast:
383
20.3k
      case CK_LValueToRValueBitCast:
384
20.3k
      case CK_AddressSpaceConversion:
385
20.3k
      case CK_BooleanToSignedIntegral:
386
20.3k
      case CK_IntegralToPointer:
387
20.3k
      case CK_PointerToIntegral: {
388
20.3k
        SVal V = state->getSVal(Ex, LCtx);
389
20.3k
        if (V.getAs<nonloc::PointerToMember>()) {
390
0
          state = state->BindExpr(CastE, LCtx, UnknownVal());
391
0
          Bldr.generateNode(CastE, Pred, state);
392
0
          continue;
393
0
        }
394
        // Explicitly proceed with default handler for this case cascade.
395
20.3k
        state =
396
20.3k
            handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
397
20.3k
        continue;
398
20.3k
      }
399
25.3k
      case CK_IntegralToBoolean:
400
25.3k
      case CK_IntegralToFloating:
401
25.3k
      case CK_FloatingToIntegral:
402
25.3k
      case CK_FloatingToBoolean:
403
25.3k
      case CK_FloatingCast:
404
25.3k
      case CK_FloatingRealToComplex:
405
25.3k
      case CK_FloatingComplexToReal:
406
25.3k
      case CK_FloatingComplexToBoolean:
407
25.3k
      case CK_FloatingComplexCast:
408
25.3k
      case CK_FloatingComplexToIntegralComplex:
409
25.3k
      case CK_IntegralRealToComplex:
410
25.3k
      case CK_IntegralComplexToReal:
411
25.3k
      case CK_IntegralComplexToBoolean:
412
25.3k
      case CK_IntegralComplexCast:
413
25.3k
      case CK_IntegralComplexToFloatingComplex:
414
25.3k
      case CK_CPointerToObjCPointerCast:
415
25.3k
      case CK_BlockPointerToObjCPointerCast:
416
25.3k
      case CK_AnyPointerToBlockPointerCast:
417
25.3k
      case CK_ObjCObjectLValueCast:
418
25.3k
      case CK_ZeroToOCLOpaqueType:
419
25.3k
      case CK_IntToOCLSampler:
420
25.3k
      case CK_LValueBitCast:
421
25.3k
      case CK_FixedPointCast:
422
25.3k
      case CK_FixedPointToBoolean:
423
25.3k
      case CK_FixedPointToIntegral:
424
25.3k
      case CK_IntegralToFixedPoint: {
425
25.3k
        state =
426
25.3k
            handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
427
25.3k
        continue;
428
25.3k
      }
429
32.4k
      case CK_IntegralCast: {
430
        // Delegate to SValBuilder to process.
431
32.4k
        SVal V = state->getSVal(Ex, LCtx);
432
32.4k
        V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
433
32.4k
        state = state->BindExpr(CastE, LCtx, V);
434
32.4k
        Bldr.generateNode(CastE, Pred, state);
435
32.4k
        continue;
436
25.3k
      }
437
833
      case CK_DerivedToBase:
438
833
      case CK_UncheckedDerivedToBase: {
439
        // For DerivedToBase cast, delegate to the store manager.
440
833
        SVal val = state->getSVal(Ex, LCtx);
441
833
        val = getStoreManager().evalDerivedToBase(val, CastE);
442
833
        state = state->BindExpr(CastE, LCtx, val);
443
833
        Bldr.generateNode(CastE, Pred, state);
444
833
        continue;
445
833
      }
446
      // Handle C++ dyn_cast.
447
38
      case CK_Dynamic: {
448
38
        SVal val = state->getSVal(Ex, LCtx);
449
450
        // Compute the type of the result.
451
38
        QualType resultType = CastE->getType();
452
38
        if (CastE->isGLValue())
453
3
          resultType = getContext().getPointerType(resultType);
454
455
38
        bool Failed = false;
456
457
        // Check if the value being cast evaluates to 0.
458
38
        if (val.isZeroConstant())
459
2
          Failed = true;
460
        // Else, evaluate the cast.
461
36
        else
462
36
          val = getStoreManager().attemptDownCast(val, T, Failed);
463
464
38
        if (Failed) {
465
8
          if (T->isReferenceType()) {
466
            // A bad_cast exception is thrown if input value is a reference.
467
            // Currently, we model this, by generating a sink.
468
1
            Bldr.generateSink(CastE, Pred, state);
469
1
            continue;
470
7
          } else {
471
            // If the cast fails on a pointer, bind to 0.
472
7
            state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
473
7
          }
474
30
        } else {
475
          // If we don't know if the cast succeeded, conjure a new symbol.
476
30
          if (val.isUnknown()) {
477
0
            DefinedOrUnknownSVal NewSym =
478
0
              svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
479
0
                                           currBldrCtx->blockCount());
480
0
            state = state->BindExpr(CastE, LCtx, NewSym);
481
0
          } else
482
            // Else, bind to the derived region value.
483
30
            state = state->BindExpr(CastE, LCtx, val);
484
30
        }
485
37
        Bldr.generateNode(CastE, Pred, state);
486
37
        continue;
487
38
      }
488
80
      case CK_BaseToDerived: {
489
80
        SVal val = state->getSVal(Ex, LCtx);
490
80
        QualType resultType = CastE->getType();
491
80
        if (CastE->isGLValue())
492
0
          resultType = getContext().getPointerType(resultType);
493
494
80
        bool Failed = false;
495
496
80
        if (!val.isConstant()) {
497
72
          val = getStoreManager().attemptDownCast(val, T, Failed);
498
72
        }
499
500
        // Failed to cast or the result is unknown, fall back to conservative.
501
80
        if (Failed || 
val.isUnknown()76
) {
502
4
          val =
503
4
            svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
504
4
                                         currBldrCtx->blockCount());
505
4
        }
506
80
        state = state->BindExpr(CastE, LCtx, val);
507
80
        Bldr.generateNode(CastE, Pred, state);
508
80
        continue;
509
38
      }
510
3.41k
      case CK_NullToPointer: {
511
3.41k
        SVal V = svalBuilder.makeNull();
512
3.41k
        state = state->BindExpr(CastE, LCtx, V);
513
3.41k
        Bldr.generateNode(CastE, Pred, state);
514
3.41k
        continue;
515
38
      }
516
5
      case CK_NullToMemberPointer: {
517
5
        SVal V = svalBuilder.getMemberPointer(nullptr);
518
5
        state = state->BindExpr(CastE, LCtx, V);
519
5
        Bldr.generateNode(CastE, Pred, state);
520
5
        continue;
521
38
      }
522
24
      case CK_DerivedToBaseMemberPointer:
523
24
      case CK_BaseToDerivedMemberPointer:
524
24
      case CK_ReinterpretMemberPointer: {
525
24
        SVal V = state->getSVal(Ex, LCtx);
526
24
        if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
527
24
          SVal CastedPTMSV = svalBuilder.makePointerToMember(
528
24
              getBasicVals().accumCXXBase(
529
24
                  llvm::make_range<CastExpr::path_const_iterator>(
530
24
                      CastE->path_begin(), CastE->path_end()), *PTMSV));
531
24
          state = state->BindExpr(CastE, LCtx, CastedPTMSV);
532
24
          Bldr.generateNode(CastE, Pred, state);
533
24
          continue;
534
24
        }
535
        // Explicitly proceed with default handler for this case cascade.
536
0
        state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
537
0
        continue;
538
0
      }
539
      // Various C++ casts that are not handled yet.
540
0
      case CK_ToUnion:
541
0
      case CK_VectorSplat: {
542
0
        state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
543
0
        continue;
544
0
      }
545
181k
    }
546
181k
  }
547
181k
}
548
549
void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
550
                                          ExplodedNode *Pred,
551
65
                                          ExplodedNodeSet &Dst) {
552
65
  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
553
554
65
  ProgramStateRef State = Pred->getState();
555
65
  const LocationContext *LCtx = Pred->getLocationContext();
556
557
65
  const Expr *Init = CL->getInitializer();
558
65
  SVal V = State->getSVal(CL->getInitializer(), LCtx);
559
560
65
  if (isa<CXXConstructExpr>(Init) || 
isa<CXXStdInitializerListExpr>(Init)59
) {
561
    // No work needed. Just pass the value up to this expression.
562
55
  } else {
563
55
    assert(isa<InitListExpr>(Init));
564
55
    Loc CLLoc = State->getLValue(CL, LCtx);
565
55
    State = State->bindLoc(CLLoc, V, LCtx);
566
567
55
    if (CL->isGLValue())
568
36
      V = CLLoc;
569
55
  }
570
571
65
  B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
572
65
}
573
574
void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
575
31.2k
                               ExplodedNodeSet &Dst) {
576
31.2k
  if (isa<TypedefNameDecl>(*DS->decl_begin())) {
577
    // C99 6.7.7 "Any array size expressions associated with variable length
578
    // array declarators are evaluated each time the declaration of the typedef
579
    // name is reached in the order of execution."
580
    // The checkers should know about typedef to be able to handle VLA size
581
    // expressions.
582
5
    ExplodedNodeSet DstPre;
583
5
    getCheckerManager().runCheckersForPreStmt(DstPre, Pred, DS, *this);
584
5
    getCheckerManager().runCheckersForPostStmt(Dst, DstPre, DS, *this);
585
5
    return;
586
5
  }
587
588
  // Assumption: The CFG has one DeclStmt per Decl.
589
31.2k
  const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
590
591
31.2k
  if (!VD) {
592
    //TODO:AZ: remove explicit insertion after refactoring is done.
593
0
    Dst.insert(Pred);
594
0
    return;
595
0
  }
596
597
  // FIXME: all pre/post visits should eventually be handled by ::Visit().
598
31.2k
  ExplodedNodeSet dstPreVisit;
599
31.2k
  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
600
601
31.2k
  ExplodedNodeSet dstEvaluated;
602
31.2k
  StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
603
31.2k
  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
604
62.5k
       I!=E; 
++I31.2k
) {
605
31.2k
    ExplodedNode *N = *I;
606
31.2k
    ProgramStateRef state = N->getState();
607
31.2k
    const LocationContext *LC = N->getLocationContext();
608
609
    // Decls without InitExpr are not initialized explicitly.
610
31.2k
    if (const Expr *InitEx = VD->getInit()) {
611
612
      // Note in the state that the initialization has occurred.
613
28.3k
      ExplodedNode *UpdatedN = N;
614
28.3k
      SVal InitVal = state->getSVal(InitEx, LC);
615
616
28.3k
      assert(DS->isSingleDecl());
617
28.3k
      if (getObjectUnderConstruction(state, DS, LC)) {
618
7.35k
        state = finishObjectConstruction(state, DS, LC);
619
        // We constructed the object directly in the variable.
620
        // No need to bind anything.
621
7.35k
        B.generateNode(DS, UpdatedN, state);
622
21.0k
      } else {
623
        // Recover some path-sensitivity if a scalar value evaluated to
624
        // UnknownVal.
625
21.0k
        if (InitVal.isUnknown()) {
626
5.17k
          QualType Ty = InitEx->getType();
627
5.17k
          if (InitEx->isGLValue()) {
628
0
            Ty = getContext().getPointerType(Ty);
629
0
          }
630
631
5.17k
          InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
632
5.17k
                                                 currBldrCtx->blockCount());
633
5.17k
        }
634
635
636
21.0k
        B.takeNodes(UpdatedN);
637
21.0k
        ExplodedNodeSet Dst2;
638
21.0k
        evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
639
21.0k
        B.addNodes(Dst2);
640
21.0k
      }
641
28.3k
    }
642
2.89k
    else {
643
2.89k
      B.generateNode(DS, N, state);
644
2.89k
    }
645
31.2k
  }
646
647
31.2k
  getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
648
31.2k
}
649
650
void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
651
1.18k
                                  ExplodedNodeSet &Dst) {
652
  // This method acts upon CFG elements for logical operators && and ||
653
  // and attaches the value (true or false) to them as expressions.
654
  // It doesn't produce any state splits.
655
  // If we made it that far, we're past the point when we modeled the short
656
  // circuit. It means that we should have precise knowledge about whether
657
  // we've short-circuited. If we did, we already know the value we need to
658
  // bind. If we didn't, the value of the RHS (casted to the boolean type)
659
  // is the answer.
660
  // Currently this method tries to figure out whether we've short-circuited
661
  // by looking at the ExplodedGraph. This method is imperfect because there
662
  // could inevitably have been merges that would have resulted in multiple
663
  // potential path traversal histories. We bail out when we fail.
664
  // Due to this ambiguity, a more reliable solution would have been to
665
  // track the short circuit operation history path-sensitively until
666
  // we evaluate the respective logical operator.
667
1.18k
  assert(B->getOpcode() == BO_LAnd ||
668
1.18k
         B->getOpcode() == BO_LOr);
669
670
1.18k
  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
671
1.18k
  ProgramStateRef state = Pred->getState();
672
673
1.18k
  if (B->getType()->isVectorType()) {
674
    // FIXME: We do not model vector arithmetic yet. When adding support for
675
    // that, note that the CFG-based reasoning below does not apply, because
676
    // logical operators on vectors are not short-circuit. Currently they are
677
    // modeled as short-circuit in Clang CFG but this is incorrect.
678
    // Do not set the value for the expression. It'd be UnknownVal by default.
679
2
    Bldr.generateNode(B, Pred, state);
680
2
    return;
681
2
  }
682
683
1.18k
  ExplodedNode *N = Pred;
684
2.39k
  while (!N->getLocation().getAs<BlockEntrance>()) {
685
1.20k
    ProgramPoint P = N->getLocation();
686
1.20k
    assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
687
1.20k
    (void) P;
688
1.20k
    if (N->pred_size() != 1) {
689
      // We failed to track back where we came from.
690
0
      Bldr.generateNode(B, Pred, state);
691
0
      return;
692
0
    }
693
1.20k
    N = *N->pred_begin();
694
1.20k
  }
695
696
1.18k
  if (N->pred_size() != 1) {
697
    // We failed to track back where we came from.
698
6
    Bldr.generateNode(B, Pred, state);
699
6
    return;
700
6
  }
701
702
1.17k
  N = *N->pred_begin();
703
1.17k
  BlockEdge BE = N->getLocation().castAs<BlockEdge>();
704
1.17k
  SVal X;
705
706
  // Determine the value of the expression by introspecting how we
707
  // got this location in the CFG.  This requires looking at the previous
708
  // block we were in and what kind of control-flow transfer was involved.
709
1.17k
  const CFGBlock *SrcBlock = BE.getSrc();
710
  // The only terminator (if there is one) that makes sense is a logical op.
711
1.17k
  CFGTerminator T = SrcBlock->getTerminator();
712
1.17k
  if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
713
498
    (void) Term;
714
498
    assert(Term->isLogicalOp());
715
498
    assert(SrcBlock->succ_size() == 2);
716
    // Did we take the true or false branch?
717
405
    unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 
193
: 0;
718
498
    X = svalBuilder.makeIntVal(constant, B->getType());
719
498
  }
720
680
  else {
721
    // If there is no terminator, by construction the last statement
722
    // in SrcBlock is the value of the enclosing expression.
723
    // However, we still need to constrain that value to be 0 or 1.
724
680
    assert(!SrcBlock->empty());
725
680
    CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
726
680
    const Expr *RHS = cast<Expr>(Elem.getStmt());
727
680
    SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
728
729
680
    if (RHSVal.isUndef()) {
730
1
      X = RHSVal;
731
679
    } else {
732
      // We evaluate "RHSVal != 0" expression which result in 0 if the value is
733
      // known to be false, 1 if the value is known to be true and a new symbol
734
      // when the assumption is unknown.
735
679
      nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType()));
736
679
      X = evalBinOp(N->getState(), BO_NE,
737
679
                    svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()),
738
679
                    Zero, B->getType());
739
679
    }
740
680
  }
741
1.17k
  Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
742
1.17k
}
743
744
void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
745
                                   ExplodedNode *Pred,
746
1.18k
                                   ExplodedNodeSet &Dst) {
747
1.18k
  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
748
749
1.18k
  ProgramStateRef state = Pred->getState();
750
1.18k
  const LocationContext *LCtx = Pred->getLocationContext();
751
1.18k
  QualType T = getContext().getCanonicalType(IE->getType());
752
1.18k
  unsigned NumInitElements = IE->getNumInits();
753
754
1.18k
  if (!IE->isGLValue() && 
!IE->isTransparent()1.18k
&&
755
1.15k
      (T->isArrayType() || 
T->isRecordType()632
||
T->isVectorType()68
||
756
1.10k
       
T->isAnyComplexType()62
)) {
757
1.10k
    llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
758
759
    // Handle base case where the initializer has no elements.
760
    // e.g: static int* myArray[] = {};
761
1.10k
    if (NumInitElements == 0) {
762
168
      SVal V = svalBuilder.makeCompoundVal(T, vals);
763
168
      B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
764
168
      return;
765
168
    }
766
767
934
    for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
768
3.06k
         ei = IE->rend(); it != ei; 
++it2.13k
) {
769
2.13k
      SVal V = state->getSVal(cast<Expr>(*it), LCtx);
770
2.13k
      vals = getBasicVals().prependSVal(V, vals);
771
2.13k
    }
772
773
934
    B.generateNode(IE, Pred,
774
934
                   state->BindExpr(IE, LCtx,
775
934
                                   svalBuilder.makeCompoundVal(T, vals)));
776
934
    return;
777
934
  }
778
779
  // Handle scalars: int{5} and int{} and GLvalues.
780
  // Note, if the InitListExpr is a GLvalue, it means that there is an address
781
  // representing it, so it must have a single init element.
782
86
  assert(NumInitElements <= 1);
783
784
86
  SVal V;
785
86
  if (NumInitElements == 0)
786
57
    V = getSValBuilder().makeZeroVal(T);
787
29
  else
788
29
    V = state->getSVal(IE->getInit(0), LCtx);
789
790
86
  B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
791
86
}
792
793
void ExprEngine::VisitGuardedExpr(const Expr *Ex,
794
                                  const Expr *L,
795
                                  const Expr *R,
796
                                  ExplodedNode *Pred,
797
904
                                  ExplodedNodeSet &Dst) {
798
904
  assert(L && R);
799
800
904
  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
801
904
  ProgramStateRef state = Pred->getState();
802
904
  const LocationContext *LCtx = Pred->getLocationContext();
803
904
  const CFGBlock *SrcBlock = nullptr;
804
805
  // Find the predecessor block.
806
904
  ProgramStateRef SrcState = state;
807
2.71k
  for (const ExplodedNode *N = Pred ; N ; 
N = *N->pred_begin()1.81k
) {
808
2.71k
    ProgramPoint PP = N->getLocation();
809
2.71k
    if (PP.getAs<PreStmtPurgeDeadSymbols>() || 
PP.getAs<BlockEntrance>()1.80k
) {
810
      // If the state N has multiple predecessors P, it means that successors
811
      // of P are all equivalent.
812
      // In turn, that means that all nodes at P are equivalent in terms
813
      // of observable behavior at N, and we can follow any of them.
814
      // FIXME: a more robust solution which does not walk up the tree.
815
1.81k
      continue;
816
1.81k
    }
817
904
    SrcBlock = PP.castAs<BlockEdge>().getSrc();
818
904
    SrcState = N->getState();
819
904
    break;
820
904
  }
821
822
904
  assert(SrcBlock && "missing function entry");
823
824
  // Find the last expression in the predecessor block.  That is the
825
  // expression that is used for the value of the ternary expression.
826
904
  bool hasValue = false;
827
904
  SVal V;
828
829
904
  for (CFGElement CE : llvm::reverse(*SrcBlock)) {
830
904
    if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
831
904
      const Expr *ValEx = cast<Expr>(CS->getStmt());
832
904
      ValEx = ValEx->IgnoreParens();
833
834
      // For GNU extension '?:' operator, the left hand side will be an
835
      // OpaqueValueExpr, so get the underlying expression.
836
904
      if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
837
21
        L = OpaqueEx->getSourceExpr();
838
839
      // If the last expression in the predecessor block matches true or false
840
      // subexpression, get its the value.
841
904
      if (ValEx == L->IgnoreParens() || 
ValEx == R->IgnoreParens()273
) {
842
902
        hasValue = true;
843
902
        V = SrcState->getSVal(ValEx, LCtx);
844
902
      }
845
904
      break;
846
904
    }
847
904
  }
848
849
904
  if (!hasValue)
850
2
    V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
851
2
                                     currBldrCtx->blockCount());
852
853
  // Generate a new node with the binding from the appropriate path.
854
904
  B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
855
904
}
856
857
void ExprEngine::
858
VisitOffsetOfExpr(const OffsetOfExpr *OOE,
859
21
                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
860
21
  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
861
21
  Expr::EvalResult Result;
862
21
  if (OOE->EvaluateAsInt(Result, getContext())) {
863
21
    APSInt IV = Result.Val.getInt();
864
21
    assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
865
21
    assert(OOE->getType()->castAs<BuiltinType>()->isInteger());
866
21
    assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
867
21
    SVal X = svalBuilder.makeIntVal(IV);
868
21
    B.generateNode(OOE, Pred,
869
21
                   Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
870
21
                                              X));
871
21
  }
872
  // FIXME: Handle the case where __builtin_offsetof is not a constant.
873
21
}
874
875
876
void ExprEngine::
877
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
878
                              ExplodedNode *Pred,
879
958
                              ExplodedNodeSet &Dst) {
880
  // FIXME: Prechecks eventually go in ::Visit().
881
958
  ExplodedNodeSet CheckedSet;
882
958
  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
883
884
958
  ExplodedNodeSet EvalSet;
885
958
  StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
886
887
958
  QualType T = Ex->getTypeOfArgument();
888
889
958
  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
890
1.91k
       I != E; 
++I956
) {
891
956
    if (Ex->getKind() == UETT_SizeOf) {
892
953
      if (!T->isIncompleteType() && 
!T->isConstantSizeType()949
) {
893
11
        assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
894
895
        // FIXME: Add support for VLA type arguments and VLA expressions.
896
        // When that happens, we should probably refactor VLASizeChecker's code.
897
11
        continue;
898
942
      } else if (T->getAs<ObjCObjectType>()) {
899
        // Some code tries to take the sizeof an ObjCObjectType, relying that
900
        // the compiler has laid out its representation.  Just report Unknown
901
        // for these.
902
0
        continue;
903
0
      }
904
945
    }
905
906
945
    APSInt Value = Ex->EvaluateKnownConstInt(getContext());
907
945
    CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
908
909
945
    ProgramStateRef state = (*I)->getState();
910
945
    state = state->BindExpr(Ex, (*I)->getLocationContext(),
911
945
                            svalBuilder.makeIntVal(amt.getQuantity(),
912
945
                                                   Ex->getType()));
913
945
    Bldr.generateNode(Ex, *I, state);
914
945
  }
915
916
958
  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
917
958
}
918
919
void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
920
                                   const UnaryOperator *U,
921
16.9k
                                   StmtNodeBuilder &Bldr) {
922
  // FIXME: We can probably just have some magic in Environment::getSVal()
923
  // that propagates values, instead of creating a new node here.
924
  //
925
  // Unary "+" is a no-op, similar to a parentheses.  We still have places
926
  // where it may be a block-level expression, so we need to
927
  // generate an extra node that just propagates the value of the
928
  // subexpression.
929
16.9k
  const Expr *Ex = U->getSubExpr()->IgnoreParens();
930
16.9k
  ProgramStateRef state = (*I)->getState();
931
16.9k
  const LocationContext *LCtx = (*I)->getLocationContext();
932
16.9k
  Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
933
16.9k
                                           state->getSVal(Ex, LCtx)));
934
16.9k
}
935
936
void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
937
28.3k
                                    ExplodedNodeSet &Dst) {
938
  // FIXME: Prechecks eventually go in ::Visit().
939
28.3k
  ExplodedNodeSet CheckedSet;
940
28.3k
  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
941
942
28.3k
  ExplodedNodeSet EvalSet;
943
28.3k
  StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
944
945
28.3k
  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
946
56.6k
       I != E; 
++I28.3k
) {
947
28.3k
    switch (U->getOpcode()) {
948
7.82k
    default: {
949
7.82k
      Bldr.takeNodes(*I);
950
7.82k
      ExplodedNodeSet Tmp;
951
7.82k
      VisitIncrementDecrementOperator(U, *I, Tmp);
952
7.82k
      Bldr.addNodes(Tmp);
953
7.82k
      break;
954
0
    }
955
14
    case UO_Real: {
956
14
      const Expr *Ex = U->getSubExpr()->IgnoreParens();
957
958
      // FIXME: We don't have complex SValues yet.
959
14
      if (Ex->getType()->isAnyComplexType()) {
960
        // Just report "Unknown."
961
10
        break;
962
10
      }
963
964
      // For all other types, UO_Real is an identity operation.
965
4
      assert (U->getType() == Ex->getType());
966
4
      ProgramStateRef state = (*I)->getState();
967
4
      const LocationContext *LCtx = (*I)->getLocationContext();
968
4
      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
969
4
                                               state->getSVal(Ex, LCtx)));
970
4
      break;
971
4
    }
972
973
11
    case UO_Imag: {
974
11
      const Expr *Ex = U->getSubExpr()->IgnoreParens();
975
      // FIXME: We don't have complex SValues yet.
976
11
      if (Ex->getType()->isAnyComplexType()) {
977
        // Just report "Unknown."
978
8
        break;
979
8
      }
980
      // For all other types, UO_Imag returns 0.
981
3
      ProgramStateRef state = (*I)->getState();
982
3
      const LocationContext *LCtx = (*I)->getLocationContext();
983
3
      SVal X = svalBuilder.makeZeroVal(Ex->getType());
984
3
      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
985
3
      break;
986
3
    }
987
988
3.62k
    case UO_AddrOf: {
989
      // Process pointer-to-member address operation.
990
3.62k
      const Expr *Ex = U->getSubExpr()->IgnoreParens();
991
3.62k
      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
992
2.88k
        const ValueDecl *VD = DRE->getDecl();
993
994
2.88k
        if (isa<CXXMethodDecl>(VD) || 
isa<FieldDecl>(VD)2.85k
||
995
2.83k
            isa<IndirectFieldDecl>(VD)) {
996
58
          ProgramStateRef State = (*I)->getState();
997
58
          const LocationContext *LCtx = (*I)->getLocationContext();
998
58
          SVal SV = svalBuilder.getMemberPointer(cast<NamedDecl>(VD));
999
58
          Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
1000
58
          break;
1001
58
        }
1002
3.57k
      }
1003
      // Explicitly proceed with default handler for this case cascade.
1004
3.57k
      handleUOExtension(I, U, Bldr);
1005
3.57k
      break;
1006
3.57k
    }
1007
0
    case UO_Plus:
1008
0
      assert(!U->isGLValue());
1009
0
      LLVM_FALLTHROUGH;
1010
13.4k
    case UO_Deref:
1011
13.4k
    case UO_Extension: {
1012
13.4k
      handleUOExtension(I, U, Bldr);
1013
13.4k
      break;
1014
13.4k
    }
1015
1016
3.43k
    case UO_LNot:
1017
3.43k
    case UO_Minus:
1018
3.43k
    case UO_Not: {
1019
3.43k
      assert (!U->isGLValue());
1020
3.43k
      const Expr *Ex = U->getSubExpr()->IgnoreParens();
1021
3.43k
      ProgramStateRef state = (*I)->getState();
1022
3.43k
      const LocationContext *LCtx = (*I)->getLocationContext();
1023
1024
      // Get the value of the subexpression.
1025
3.43k
      SVal V = state->getSVal(Ex, LCtx);
1026
1027
3.43k
      if (V.isUnknownOrUndef()) {
1028
10
        Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
1029
10
        break;
1030
10
      }
1031
1032
3.42k
      switch (U->getOpcode()) {
1033
0
        default:
1034
0
          llvm_unreachable("Invalid Opcode.");
1035
1.00k
        case UO_Not:
1036
          // FIXME: Do we need to handle promotions?
1037
1.00k
          state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
1038
1.00k
          break;
1039
1.31k
        case UO_Minus:
1040
          // FIXME: Do we need to handle promotions?
1041
1.31k
          state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
1042
1.31k
          break;
1043
1.11k
        case UO_LNot:
1044
          // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
1045
          //
1046
          //  Note: technically we do "E == 0", but this is the same in the
1047
          //    transfer functions as "0 == E".
1048
1.11k
          SVal Result;
1049
1.11k
          if (Optional<Loc> LV = V.getAs<Loc>()) {
1050
281
            Loc X = svalBuilder.makeNullWithType(Ex->getType());
1051
281
            Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
1052
829
          } else if (Ex->getType()->isFloatingType()) {
1053
            // FIXME: handle floating point types.
1054
1
            Result = UnknownVal();
1055
828
          } else {
1056
828
            nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
1057
828
            Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
1058
828
                               U->getType());
1059
828
          }
1060
1061
1.11k
          state = state->BindExpr(U, LCtx, Result);
1062
1.11k
          break;
1063
3.42k
      }
1064
3.42k
      Bldr.generateNode(U, *I, state);
1065
3.42k
      break;
1066
3.42k
    }
1067
28.3k
    }
1068
28.3k
  }
1069
1070
28.3k
  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
1071
28.3k
}
1072
1073
void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
1074
                                                 ExplodedNode *Pred,
1075
7.82k
                                                 ExplodedNodeSet &Dst) {
1076
  // Handle ++ and -- (both pre- and post-increment).
1077
7.82k
  assert (U->isIncrementDecrementOp());
1078
7.82k
  const Expr *Ex = U->getSubExpr()->IgnoreParens();
1079
1080
7.82k
  const LocationContext *LCtx = Pred->getLocationContext();
1081
7.82k
  ProgramStateRef state = Pred->getState();
1082
7.82k
  SVal loc = state->getSVal(Ex, LCtx);
1083
1084
  // Perform a load.
1085
7.82k
  ExplodedNodeSet Tmp;
1086
7.82k
  evalLoad(Tmp, U, Ex, Pred, state, loc);
1087
1088
7.82k
  ExplodedNodeSet Dst2;
1089
7.82k
  StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
1090
15.6k
  for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;
++I7.81k
) {
1091
1092
7.81k
    state = (*I)->getState();
1093
7.81k
    assert(LCtx == (*I)->getLocationContext());
1094
7.81k
    SVal V2_untested = state->getSVal(Ex, LCtx);
1095
1096
    // Propagate unknown and undefined values.
1097
7.81k
    if (V2_untested.isUnknownOrUndef()) {
1098
292
      state = state->BindExpr(U, LCtx, V2_untested);
1099
1100
      // Perform the store, so that the uninitialized value detection happens.
1101
292
      Bldr.takeNodes(*I);
1102
292
      ExplodedNodeSet Dst3;
1103
292
      evalStore(Dst3, U, Ex, *I, state, loc, V2_untested);
1104
292
      Bldr.addNodes(Dst3);
1105
1106
292
      continue;
1107
292
    }
1108
7.52k
    DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
1109
1110
    // Handle all other values.
1111
7.12k
    BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : 
BO_Sub398
;
1112
1113
    // If the UnaryOperator has non-location type, use its type to create the
1114
    // constant value. If the UnaryOperator has location type, create the
1115
    // constant with int type and pointer width.
1116
7.52k
    SVal RHS;
1117
7.52k
    SVal Result;
1118
1119
7.52k
    if (U->getType()->isAnyPointerType())
1120
831
      RHS = svalBuilder.makeArrayIndex(1);
1121
6.69k
    else if (U->getType()->isIntegralOrEnumerationType())
1122
6.69k
      RHS = svalBuilder.makeIntVal(1, U->getType());
1123
1
    else
1124
1
      RHS = UnknownVal();
1125
1126
    // The use of an operand of type bool with the ++ operators is deprecated
1127
    // but valid until C++17. And if the operand of the ++ operator is of type
1128
    // bool, it is set to true until C++17. Note that for '_Bool', it is also
1129
    // set to true when it encounters ++ operator.
1130
7.52k
    if (U->getType()->isBooleanType() && 
U->isIncrementOp()70
)
1131
52
      Result = svalBuilder.makeTruthVal(true, U->getType());
1132
7.47k
    else
1133
7.47k
      Result = evalBinOp(state, Op, V2, RHS, U->getType());
1134
1135
    // Conjure a new symbol if necessary to recover precision.
1136
7.52k
    if (Result.isUnknown()){
1137
3
      DefinedOrUnknownSVal SymVal =
1138
3
        svalBuilder.conjureSymbolVal(nullptr, U, LCtx,
1139
3
                                     currBldrCtx->blockCount());
1140
3
      Result = SymVal;
1141
1142
      // If the value is a location, ++/-- should always preserve
1143
      // non-nullness.  Check if the original value was non-null, and if so
1144
      // propagate that constraint.
1145
3
      if (Loc::isLocType(U->getType())) {
1146
0
        DefinedOrUnknownSVal Constraint =
1147
0
        svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
1148
1149
0
        if (!state->assume(Constraint, true)) {
1150
          // It isn't feasible for the original value to be null.
1151
          // Propagate this constraint.
1152
0
          Constraint = svalBuilder.evalEQ(state, SymVal,
1153
0
                                       svalBuilder.makeZeroVal(U->getType()));
1154
1155
0
          state = state->assume(Constraint, false);
1156
0
          assert(state);
1157
0
        }
1158
0
      }
1159
3
    }
1160
1161
    // Since the lvalue-to-rvalue conversion is explicit in the AST,
1162
    // we bind an l-value if the operator is prefix and an lvalue (in C++).
1163
7.52k
    if (U->isGLValue())
1164
1.32k
      state = state->BindExpr(U, LCtx, loc);
1165
6.20k
    else
1166
6.20k
      state = state->BindExpr(U, LCtx, U->isPostfix() ? 
V25.67k
:
Result530
);
1167
1168
    // Perform the store.
1169
7.52k
    Bldr.takeNodes(*I);
1170
7.52k
    ExplodedNodeSet Dst3;
1171
7.52k
    evalStore(Dst3, U, Ex, *I, state, loc, Result);
1172
7.52k
    Bldr.addNodes(Dst3);
1173
7.52k
  }
1174
7.82k
  Dst.insert(Dst2);
1175
7.82k
}