Coverage Report

Created: 2021-04-13 08:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- CoreEngine.cpp - Path-Sensitive Dataflow Engine --------------------===//
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 a generic engine for intraprocedural, path-sensitive,
10
//  dataflow analysis via graph reachability engine.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
15
#include "clang/AST/Expr.h"
16
#include "clang/AST/ExprCXX.h"
17
#include "clang/AST/Stmt.h"
18
#include "clang/AST/StmtCXX.h"
19
#include "clang/Analysis/AnalysisDeclContext.h"
20
#include "clang/Analysis/CFG.h"
21
#include "clang/Analysis/ProgramPoint.h"
22
#include "clang/Basic/LLVM.h"
23
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
24
#include "clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h"
25
#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
26
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
27
#include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h"
28
#include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
29
#include "llvm/ADT/Optional.h"
30
#include "llvm/ADT/STLExtras.h"
31
#include "llvm/ADT/Statistic.h"
32
#include "llvm/Support/Casting.h"
33
#include "llvm/Support/ErrorHandling.h"
34
#include <algorithm>
35
#include <cassert>
36
#include <memory>
37
#include <utility>
38
39
using namespace clang;
40
using namespace ento;
41
42
#define DEBUG_TYPE "CoreEngine"
43
44
STATISTIC(NumSteps,
45
            "The # of steps executed.");
46
STATISTIC(NumReachedMaxSteps,
47
            "The # of times we reached the max number of steps.");
48
STATISTIC(NumPathsExplored,
49
            "The # of paths explored by the analyzer.");
50
51
//===----------------------------------------------------------------------===//
52
// Core analysis engine.
53
//===----------------------------------------------------------------------===//
54
55
13.8k
static std::unique_ptr<WorkList> generateWorkList(AnalyzerOptions &Opts) {
56
13.8k
  switch (Opts.getExplorationStrategy()) {
57
311
    case ExplorationStrategyKind::DFS:
58
311
      return WorkList::makeDFS();
59
0
    case ExplorationStrategyKind::BFS:
60
0
      return WorkList::makeBFS();
61
0
    case ExplorationStrategyKind::BFSBlockDFSContents:
62
0
      return WorkList::makeBFSBlockDFSContents();
63
4
    case ExplorationStrategyKind::UnexploredFirst:
64
4
      return WorkList::makeUnexploredFirst();
65
13.5k
    case ExplorationStrategyKind::UnexploredFirstQueue:
66
13.5k
      return WorkList::makeUnexploredFirstPriorityQueue();
67
0
    case ExplorationStrategyKind::UnexploredFirstLocationQueue:
68
0
      return WorkList::makeUnexploredFirstPriorityLocationQueue();
69
13.8k
  }
70
13.8k
  
llvm_unreachable0
("Unknown AnalyzerOptions::ExplorationStrategyKind");
71
13.8k
}
72
73
CoreEngine::CoreEngine(ExprEngine &exprengine, FunctionSummariesTy *FS,
74
                       AnalyzerOptions &Opts)
75
    : ExprEng(exprengine), WList(generateWorkList(Opts)),
76
13.8k
      BCounterFactory(G.getAllocator()), FunctionSummaries(FS) {}
77
78
/// ExecuteWorkList - Run the worklist algorithm for a maximum number of steps.
79
bool CoreEngine::ExecuteWorkList(const LocationContext *L, unsigned Steps,
80
13.8k
                                   ProgramStateRef InitState) {
81
13.8k
  if (G.num_roots() == 0) { // Initialize the analysis by constructing
82
    // the root if none exists.
83
84
13.8k
    const CFGBlock *Entry = &(L->getCFG()->getEntry());
85
86
13.8k
    assert(Entry->empty() && "Entry block must be empty.");
87
88
0
    assert(Entry->succ_size() == 1 && "Entry block must have 1 successor.");
89
90
    // Mark the entry block as visited.
91
0
    FunctionSummaries->markVisitedBasicBlock(Entry->getBlockID(),
92
13.8k
                                             L->getDecl(),
93
13.8k
                                             L->getCFG()->getNumBlockIDs());
94
95
    // Get the solitary successor.
96
13.8k
    const CFGBlock *Succ = *(Entry->succ_begin());
97
98
    // Construct an edge representing the
99
    // starting location in the function.
100
13.8k
    BlockEdge StartLoc(Entry, Succ, L);
101
102
    // Set the current block counter to being empty.
103
13.8k
    WList->setBlockCounter(BCounterFactory.GetEmptyCounter());
104
105
13.8k
    if (!InitState)
106
13.8k
      InitState = ExprEng.getInitialState(L);
107
108
13.8k
    bool IsNew;
109
13.8k
    ExplodedNode *Node = G.getNode(StartLoc, InitState, false, &IsNew);
110
13.8k
    assert(IsNew);
111
0
    G.addRoot(Node);
112
113
13.8k
    NodeBuilderContext BuilderCtx(*this, StartLoc.getDst(), Node);
114
13.8k
    ExplodedNodeSet DstBegin;
115
13.8k
    ExprEng.processBeginOfFunction(BuilderCtx, Node, DstBegin, StartLoc);
116
117
13.8k
    enqueue(DstBegin);
118
13.8k
  }
119
120
  // Check if we have a steps limit
121
0
  bool UnlimitedSteps = Steps == 0;
122
  // Cap our pre-reservation in the event that the user specifies
123
  // a very large number of maximum steps.
124
13.8k
  const unsigned PreReservationCap = 4000000;
125
13.8k
  if(!UnlimitedSteps)
126
13.8k
    G.reserve(std::min(Steps,PreReservationCap));
127
128
1.40M
  while (WList->hasWork()) {
129
1.38M
    if (!UnlimitedSteps) {
130
1.38M
      if (Steps == 0) {
131
9
        NumReachedMaxSteps++;
132
9
        break;
133
9
      }
134
1.38M
      --Steps;
135
1.38M
    }
136
137
1.38M
    NumSteps++;
138
139
1.38M
    const WorkListUnit& WU = WList->dequeue();
140
141
    // Set the current block counter.
142
1.38M
    WList->setBlockCounter(WU.getBlockCounter());
143
144
    // Retrieve the node.
145
1.38M
    ExplodedNode *Node = WU.getNode();
146
147
1.38M
    dispatchWorkItem(Node, Node->getLocation(), WU);
148
1.38M
  }
149
13.8k
  ExprEng.processEndWorklist();
150
13.8k
  return WList->hasWork();
151
13.8k
}
152
153
void CoreEngine::dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
154
1.38M
                                  const WorkListUnit& WU) {
155
  // Dispatch on the location type.
156
1.38M
  switch (Loc.getKind()) {
157
202k
    case ProgramPoint::BlockEdgeKind:
158
202k
      HandleBlockEdge(Loc.castAs<BlockEdge>(), Pred);
159
202k
      break;
160
161
124k
    case ProgramPoint::BlockEntranceKind:
162
124k
      HandleBlockEntrance(Loc.castAs<BlockEntrance>(), Pred);
163
124k
      break;
164
165
0
    case ProgramPoint::BlockExitKind:
166
0
      assert(false && "BlockExit location never occur in forward analysis.");
167
0
      break;
168
169
34.1k
    case ProgramPoint::CallEnterKind:
170
34.1k
      HandleCallEnter(Loc.castAs<CallEnter>(), Pred);
171
34.1k
      break;
172
173
41.8k
    case ProgramPoint::CallExitBeginKind:
174
41.8k
      ExprEng.processCallExit(Pred);
175
41.8k
      break;
176
177
36
    case ProgramPoint::EpsilonKind: {
178
36
      assert(Pred->hasSinglePred() &&
179
36
             "Assume epsilon has exactly one predecessor by construction");
180
0
      ExplodedNode *PNode = Pred->getFirstPred();
181
36
      dispatchWorkItem(Pred, PNode->getLocation(), WU);
182
36
      break;
183
0
    }
184
986k
    default:
185
986k
      assert(Loc.getAs<PostStmt>() ||
186
986k
             Loc.getAs<PostInitializer>() ||
187
986k
             Loc.getAs<PostImplicitCall>() ||
188
986k
             Loc.getAs<CallExitEnd>() ||
189
986k
             Loc.getAs<LoopExit>() ||
190
986k
             Loc.getAs<PostAllocatorCall>());
191
0
      HandlePostStmt(WU.getBlock(), WU.getIndex(), Pred);
192
986k
      break;
193
1.38M
  }
194
1.38M
}
195
196
bool CoreEngine::ExecuteWorkListWithInitialState(const LocationContext *L,
197
                                                 unsigned Steps,
198
                                                 ProgramStateRef InitState,
199
0
                                                 ExplodedNodeSet &Dst) {
200
0
  bool DidNotFinish = ExecuteWorkList(L, Steps, InitState);
201
0
  for (ExplodedGraph::eop_iterator I = G.eop_begin(), E = G.eop_end(); I != E;
202
0
       ++I) {
203
0
    Dst.Add(*I);
204
0
  }
205
0
  return DidNotFinish;
206
0
}
207
208
202k
void CoreEngine::HandleBlockEdge(const BlockEdge &L, ExplodedNode *Pred) {
209
202k
  const CFGBlock *Blk = L.getDst();
210
202k
  NodeBuilderContext BuilderCtx(*this, Blk, Pred);
211
212
  // Mark this block as visited.
213
202k
  const LocationContext *LC = Pred->getLocationContext();
214
202k
  FunctionSummaries->markVisitedBasicBlock(Blk->getBlockID(),
215
202k
                                           LC->getDecl(),
216
202k
                                           LC->getCFG()->getNumBlockIDs());
217
218
  // Display a prunable path note to the user if it's a virtual bases branch
219
  // and we're taking the path that skips virtual base constructors.
220
202k
  if (L.getSrc()->getTerminator().isVirtualBaseBranch() &&
221
202k
      
L.getDst() == *L.getSrc()->succ_begin()155
) {
222
71
    ProgramPoint P = L.withTag(getNoteTags().makeNoteTag(
223
110
        [](BugReporterContext &, PathSensitiveBugReport &) -> std::string {
224
          // TODO: Just call out the name of the most derived class
225
          // when we know it.
226
110
          return "Virtual base initialization skipped because "
227
110
                 "it has already been handled by the most derived class";
228
110
        }, /*IsPrunable=*/true));
229
    // Perform the transition.
230
71
    ExplodedNodeSet Dst;
231
71
    NodeBuilder Bldr(Pred, Dst, BuilderCtx);
232
71
    Pred = Bldr.generateNode(P, Pred->getState(), Pred);
233
71
    if (!Pred)
234
0
      return;
235
71
  }
236
237
  // Check if we are entering the EXIT block.
238
202k
  if (Blk == &(L.getLocationContext()->getCFG()->getExit())) {
239
63.7k
    assert(L.getLocationContext()->getCFG()->getExit().empty() &&
240
63.7k
           "EXIT block cannot contain Stmts.");
241
242
    // Get return statement..
243
0
    const ReturnStmt *RS = nullptr;
244
63.7k
    if (!L.getSrc()->empty()) {
245
59.3k
      CFGElement LastElement = L.getSrc()->back();
246
59.3k
      if (Optional<CFGStmt> LastStmt = LastElement.getAs<CFGStmt>()) {
247
53.0k
        RS = dyn_cast<ReturnStmt>(LastStmt->getStmt());
248
53.0k
      } else 
if (Optional<CFGAutomaticObjDtor> 6.32k
AutoDtor6.32k
=
249
6.32k
                 LastElement.getAs<CFGAutomaticObjDtor>()) {
250
266
        RS = dyn_cast<ReturnStmt>(AutoDtor->getTriggerStmt());
251
266
      }
252
59.3k
    }
253
254
    // Process the final state transition.
255
63.7k
    ExprEng.processEndOfFunction(BuilderCtx, Pred, RS);
256
257
    // This path is done. Don't enqueue any more nodes.
258
63.7k
    return;
259
63.7k
  }
260
261
  // Call into the ExprEngine to process entering the CFGBlock.
262
139k
  ExplodedNodeSet dstNodes;
263
139k
  BlockEntrance BE(Blk, Pred->getLocationContext());
264
139k
  NodeBuilderWithSinks nodeBuilder(Pred, dstNodes, BuilderCtx, BE);
265
139k
  ExprEng.processCFGBlockEntrance(L, nodeBuilder, Pred);
266
267
  // Auto-generate a node.
268
139k
  if (!nodeBuilder.hasGeneratedNodes()) {
269
137k
    nodeBuilder.generateNode(Pred->State, Pred);
270
137k
  }
271
272
  // Enqueue nodes onto the worklist.
273
139k
  enqueue(dstNodes);
274
139k
}
275
276
void CoreEngine::HandleBlockEntrance(const BlockEntrance &L,
277
124k
                                       ExplodedNode *Pred) {
278
  // Increment the block counter.
279
124k
  const LocationContext *LC = Pred->getLocationContext();
280
124k
  unsigned BlockId = L.getBlock()->getBlockID();
281
124k
  BlockCounter Counter = WList->getBlockCounter();
282
124k
  Counter = BCounterFactory.IncrementCount(Counter, LC->getStackFrame(),
283
124k
                                           BlockId);
284
124k
  WList->setBlockCounter(Counter);
285
286
  // Process the entrance of the block.
287
124k
  if (Optional<CFGElement> E = L.getFirstElement()) {
288
111k
    NodeBuilderContext Ctx(*this, L.getBlock(), Pred);
289
111k
    ExprEng.processCFGElement(*E, Pred, 0, &Ctx);
290
111k
  }
291
13.1k
  else
292
13.1k
    HandleBlockExit(L.getBlock(), Pred);
293
124k
}
294
295
127k
void CoreEngine::HandleBlockExit(const CFGBlock * B, ExplodedNode *Pred) {
296
127k
  if (const Stmt *Term = B->getTerminatorStmt()) {
297
44.8k
    switch (Term->getStmtClass()) {
298
0
      default:
299
0
        llvm_unreachable("Analysis for this terminator not implemented.");
300
301
603
      case Stmt::CXXBindTemporaryExprClass:
302
603
        HandleCleanupTemporaryBranch(
303
603
            cast<CXXBindTemporaryExpr>(Term), B, Pred);
304
603
        return;
305
306
      // Model static initializers.
307
203
      case Stmt::DeclStmtClass:
308
203
        HandleStaticInit(cast<DeclStmt>(Term), B, Pred);
309
203
        return;
310
311
11.3k
      case Stmt::BinaryOperatorClass: // '&&' and '||'
312
11.3k
        HandleBranch(cast<BinaryOperator>(Term)->getLHS(), Term, B, Pred);
313
11.3k
        return;
314
315
25
      case Stmt::BinaryConditionalOperatorClass:
316
831
      case Stmt::ConditionalOperatorClass:
317
831
        HandleBranch(cast<AbstractConditionalOperator>(Term)->getCond(),
318
831
                     Term, B, Pred);
319
831
        return;
320
321
        // FIXME: Use constant-folding in CFG construction to simplify this
322
        // case.
323
324
0
      case Stmt::ChooseExprClass:
325
0
        HandleBranch(cast<ChooseExpr>(Term)->getCond(), Term, B, Pred);
326
0
        return;
327
328
0
      case Stmt::CXXTryStmtClass:
329
        // Generate a node for each of the successors.
330
        // Our logic for EH analysis can certainly be improved.
331
0
        for (CFGBlock::const_succ_iterator it = B->succ_begin(),
332
0
             et = B->succ_end(); it != et; ++it) {
333
0
          if (const CFGBlock *succ = *it) {
334
0
            generateNode(BlockEdge(B, succ, Pred->getLocationContext()),
335
0
                         Pred->State, Pred);
336
0
          }
337
0
        }
338
0
        return;
339
340
261
      case Stmt::DoStmtClass:
341
261
        HandleBranch(cast<DoStmt>(Term)->getCond(), Term, B, Pred);
342
261
        return;
343
344
187
      case Stmt::CXXForRangeStmtClass:
345
187
        HandleBranch(cast<CXXForRangeStmt>(Term)->getCond(), Term, B, Pred);
346
187
        return;
347
348
4.61k
      case Stmt::ForStmtClass:
349
4.61k
        HandleBranch(cast<ForStmt>(Term)->getCond(), Term, B, Pred);
350
4.61k
        return;
351
352
19
      case Stmt::ContinueStmtClass:
353
382
      case Stmt::BreakStmtClass:
354
393
      case Stmt::GotoStmtClass:
355
393
        break;
356
357
15.6k
      case Stmt::IfStmtClass:
358
15.6k
        HandleBranch(cast<IfStmt>(Term)->getCond(), Term, B, Pred);
359
15.6k
        return;
360
361
8
      case Stmt::IndirectGotoStmtClass: {
362
        // Only 1 successor: the indirect goto dispatch block.
363
8
        assert(B->succ_size() == 1);
364
365
0
        IndirectGotoNodeBuilder
366
8
           builder(Pred, B, cast<IndirectGotoStmt>(Term)->getTarget(),
367
8
                   *(B->succ_begin()), this);
368
369
8
        ExprEng.processIndirectGoto(builder);
370
8
        return;
371
382
      }
372
373
448
      case Stmt::ObjCForCollectionStmtClass:
374
        // In the case of ObjCForCollectionStmt, it appears twice in a CFG:
375
        //
376
        //  (1) inside a basic block, which represents the binding of the
377
        //      'element' variable to a value.
378
        //  (2) in a terminator, which represents the branch.
379
        //
380
        // For (1), ExprEngine will bind a value (i.e., 0 or 1) indicating
381
        // whether or not collection contains any more elements.  We cannot
382
        // just test to see if the element is nil because a container can
383
        // contain nil elements.
384
448
        HandleBranch(Term, Term, B, Pred);
385
448
        return;
386
387
245
      case Stmt::SwitchStmtClass: {
388
245
        SwitchNodeBuilder builder(Pred, B, cast<SwitchStmt>(Term)->getCond(),
389
245
                                    this);
390
391
245
        ExprEng.processSwitch(builder);
392
245
        return;
393
382
      }
394
395
9.96k
      case Stmt::WhileStmtClass:
396
9.96k
        HandleBranch(cast<WhileStmt>(Term)->getCond(), Term, B, Pred);
397
9.96k
        return;
398
399
1
      case Stmt::GCCAsmStmtClass:
400
1
        assert(cast<GCCAsmStmt>(Term)->isAsmGoto() && "Encountered GCCAsmStmt without labels");
401
        // TODO: Handle jumping to labels
402
0
        return;
403
44.8k
    }
404
44.8k
  }
405
406
83.2k
  if (B->getTerminator().isVirtualBaseBranch()) {
407
155
    HandleVirtualBaseBranch(B, Pred);
408
155
    return;
409
155
  }
410
411
83.0k
  assert(B->succ_size() == 1 &&
412
83.0k
         "Blocks with no terminator should have at most 1 successor.");
413
414
0
  generateNode(BlockEdge(B, *(B->succ_begin()), Pred->getLocationContext()),
415
83.0k
               Pred->State, Pred);
416
83.0k
}
417
418
34.1k
void CoreEngine::HandleCallEnter(const CallEnter &CE, ExplodedNode *Pred) {
419
34.1k
  NodeBuilderContext BuilderCtx(*this, CE.getEntry(), Pred);
420
34.1k
  ExprEng.processCallEnter(BuilderCtx, CE, Pred);
421
34.1k
}
422
423
void CoreEngine::HandleBranch(const Stmt *Cond, const Stmt *Term,
424
43.3k
                                const CFGBlock * B, ExplodedNode *Pred) {
425
43.3k
  assert(B->succ_size() == 2);
426
0
  NodeBuilderContext Ctx(*this, B, Pred);
427
43.3k
  ExplodedNodeSet Dst;
428
43.3k
  ExprEng.processBranch(Cond, Ctx, Pred, Dst, *(B->succ_begin()),
429
43.3k
                       *(B->succ_begin() + 1));
430
  // Enqueue the new frontier onto the worklist.
431
43.3k
  enqueue(Dst);
432
43.3k
}
433
434
void CoreEngine::HandleCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
435
                                              const CFGBlock *B,
436
603
                                              ExplodedNode *Pred) {
437
603
  assert(B->succ_size() == 2);
438
0
  NodeBuilderContext Ctx(*this, B, Pred);
439
603
  ExplodedNodeSet Dst;
440
603
  ExprEng.processCleanupTemporaryBranch(BTE, Ctx, Pred, Dst, *(B->succ_begin()),
441
603
                                       *(B->succ_begin() + 1));
442
  // Enqueue the new frontier onto the worklist.
443
603
  enqueue(Dst);
444
603
}
445
446
void CoreEngine::HandleStaticInit(const DeclStmt *DS, const CFGBlock *B,
447
203
                                  ExplodedNode *Pred) {
448
203
  assert(B->succ_size() == 2);
449
0
  NodeBuilderContext Ctx(*this, B, Pred);
450
203
  ExplodedNodeSet Dst;
451
203
  ExprEng.processStaticInitializer(DS, Ctx, Pred, Dst,
452
203
                                  *(B->succ_begin()), *(B->succ_begin()+1));
453
  // Enqueue the new frontier onto the worklist.
454
203
  enqueue(Dst);
455
203
}
456
457
void CoreEngine::HandlePostStmt(const CFGBlock *B, unsigned StmtIdx,
458
986k
                                ExplodedNode *Pred) {
459
986k
  assert(B);
460
0
  assert(!B->empty());
461
462
986k
  if (StmtIdx == B->size())
463
114k
    HandleBlockExit(B, Pred);
464
872k
  else {
465
872k
    NodeBuilderContext Ctx(*this, B, Pred);
466
872k
    ExprEng.processCFGElement((*B)[StmtIdx], Pred, StmtIdx, &Ctx);
467
872k
  }
468
986k
}
469
470
void CoreEngine::HandleVirtualBaseBranch(const CFGBlock *B,
471
155
                                         ExplodedNode *Pred) {
472
155
  const LocationContext *LCtx = Pred->getLocationContext();
473
155
  if (const auto *CallerCtor = dyn_cast_or_null<CXXConstructExpr>(
474
155
          LCtx->getStackFrame()->getCallSite())) {
475
133
    switch (CallerCtor->getConstructionKind()) {
476
60
    case CXXConstructExpr::CK_NonVirtualBase:
477
71
    case CXXConstructExpr::CK_VirtualBase: {
478
71
      BlockEdge Loc(B, *B->succ_begin(), LCtx);
479
71
      HandleBlockEdge(Loc, Pred);
480
71
      return;
481
60
    }
482
62
    default:
483
62
      break;
484
133
    }
485
133
  }
486
487
  // We either don't see a parent stack frame because we're in the top frame,
488
  // or the parent stack frame doesn't initialize our virtual bases.
489
84
  BlockEdge Loc(B, *(B->succ_begin() + 1), LCtx);
490
84
  HandleBlockEdge(Loc, Pred);
491
84
}
492
493
/// generateNode - Utility method to generate nodes, hook up successors,
494
///  and add nodes to the worklist.
495
void CoreEngine::generateNode(const ProgramPoint &Loc,
496
                              ProgramStateRef State,
497
83.0k
                              ExplodedNode *Pred) {
498
83.0k
  bool IsNew;
499
83.0k
  ExplodedNode *Node = G.getNode(Loc, State, false, &IsNew);
500
501
83.0k
  if (Pred)
502
83.0k
    Node->addPredecessor(Pred, G); // Link 'Node' with its predecessor.
503
0
  else {
504
0
    assert(IsNew);
505
0
    G.addRoot(Node); // 'Node' has no predecessor.  Make it a root.
506
0
  }
507
508
  // Only add 'Node' to the worklist if it was freshly generated.
509
83.0k
  if (IsNew) 
WList->enqueue(Node)83.0k
;
510
83.0k
}
511
512
void CoreEngine::enqueueStmtNode(ExplodedNode *N,
513
946k
                                 const CFGBlock *Block, unsigned Idx) {
514
946k
  assert(Block);
515
0
  assert(!N->isSink());
516
517
  // Check if this node entered a callee.
518
946k
  if (N->getLocation().getAs<CallEnter>()) {
519
    // Still use the index of the CallExpr. It's needed to create the callee
520
    // StackFrameContext.
521
0
    WList->enqueue(N, Block, Idx);
522
0
    return;
523
0
  }
524
525
  // Do not create extra nodes. Move to the next CFG element.
526
946k
  if (N->getLocation().getAs<PostInitializer>() ||
527
946k
      
N->getLocation().getAs<PostImplicitCall>()935k
||
528
946k
      
N->getLocation().getAs<LoopExit>()934k
) {
529
13.1k
    WList->enqueue(N, Block, Idx+1);
530
13.1k
    return;
531
13.1k
  }
532
533
933k
  if (N->getLocation().getAs<EpsilonPoint>()) {
534
36
    WList->enqueue(N, Block, Idx);
535
36
    return;
536
36
  }
537
538
933k
  if ((*Block)[Idx].getKind() == CFGElement::NewAllocator) {
539
657
    WList->enqueue(N, Block, Idx+1);
540
657
    return;
541
657
  }
542
543
  // At this point, we know we're processing a normal statement.
544
933k
  CFGStmt CS = (*Block)[Idx].castAs<CFGStmt>();
545
933k
  PostStmt Loc(CS.getStmt(), N->getLocationContext());
546
547
933k
  if (Loc == N->getLocation().withTag(nullptr)) {
548
    // Note: 'N' should be a fresh node because otherwise it shouldn't be
549
    // a member of Deferred.
550
384k
    WList->enqueue(N, Block, Idx+1);
551
384k
    return;
552
384k
  }
553
554
548k
  bool IsNew;
555
548k
  ExplodedNode *Succ = G.getNode(Loc, N->getState(), false, &IsNew);
556
548k
  Succ->addPredecessor(N, G);
557
558
548k
  if (IsNew)
559
548k
    WList->enqueue(Succ, Block, Idx+1);
560
548k
}
561
562
ExplodedNode *CoreEngine::generateCallExitBeginNode(ExplodedNode *N,
563
41.8k
                                                    const ReturnStmt *RS) {
564
  // Create a CallExitBegin node and enqueue it.
565
41.8k
  const auto *LocCtx = cast<StackFrameContext>(N->getLocationContext());
566
567
  // Use the callee location context.
568
41.8k
  CallExitBegin Loc(LocCtx, RS);
569
570
41.8k
  bool isNew;
571
41.8k
  ExplodedNode *Node = G.getNode(Loc, N->getState(), false, &isNew);
572
41.8k
  Node->addPredecessor(N, G);
573
41.8k
  return isNew ? Node : 
nullptr0
;
574
41.8k
}
575
576
231k
void CoreEngine::enqueue(ExplodedNodeSet &Set) {
577
231k
  for (const auto I : Set)
578
256k
    WList->enqueue(I);
579
231k
}
580
581
void CoreEngine::enqueue(ExplodedNodeSet &Set,
582
983k
                         const CFGBlock *Block, unsigned Idx) {
583
983k
  for (const auto I : Set)
584
946k
    enqueueStmtNode(I, Block, Idx);
585
983k
}
586
587
63.7k
void CoreEngine::enqueueEndOfFunction(ExplodedNodeSet &Set, const ReturnStmt *RS) {
588
63.7k
  for (auto I : Set) {
589
    // If we are in an inlined call, generate CallExitBegin node.
590
62.6k
    if (I->getLocationContext()->getParent()) {
591
41.8k
      I = generateCallExitBeginNode(I, RS);
592
41.8k
      if (I)
593
41.8k
        WList->enqueue(I);
594
41.8k
    } else {
595
      // TODO: We should run remove dead bindings here.
596
20.8k
      G.addEndOfPath(I);
597
20.8k
      NumPathsExplored++;
598
20.8k
    }
599
62.6k
  }
600
63.7k
}
601
602
0
void NodeBuilder::anchor() {}
603
604
ExplodedNode* NodeBuilder::generateNodeImpl(const ProgramPoint &Loc,
605
                                            ProgramStateRef State,
606
                                            ExplodedNode *FromN,
607
1.63M
                                            bool MarkAsSink) {
608
1.63M
  HasGeneratedNodes = true;
609
1.63M
  bool IsNew;
610
1.63M
  ExplodedNode *N = C.Eng.G.getNode(Loc, State, MarkAsSink, &IsNew);
611
1.63M
  N->addPredecessor(FromN, C.Eng.G);
612
1.63M
  Frontier.erase(FromN);
613
614
1.63M
  if (!IsNew)
615
5.99k
    return nullptr;
616
617
1.62M
  if (!MarkAsSink)
618
1.62M
    Frontier.Add(N);
619
620
1.62M
  return N;
621
1.63M
}
622
623
0
void NodeBuilderWithSinks::anchor() {}
624
625
2.65M
StmtNodeBuilder::~StmtNodeBuilder() {
626
2.65M
  if (EnclosingBldr)
627
0
    for (const auto I : Frontier)
628
0
      EnclosingBldr->addNodes(I);
629
2.65M
}
630
631
0
void BranchNodeBuilder::anchor() {}
632
633
ExplodedNode *BranchNodeBuilder::generateNode(ProgramStateRef State,
634
                                              bool branch,
635
71.0k
                                              ExplodedNode *NodePred) {
636
  // If the branch has been marked infeasible we should not generate a node.
637
71.0k
  if (!isFeasible(branch))
638
0
    return nullptr;
639
640
71.0k
  ProgramPoint Loc = BlockEdge(C.Block, branch ? 
DstT37.2k
:
DstF33.7k
,
641
71.0k
                               NodePred->getLocationContext());
642
71.0k
  ExplodedNode *Succ = generateNodeImpl(Loc, State, NodePred);
643
71.0k
  return Succ;
644
71.0k
}
645
646
ExplodedNode*
647
IndirectGotoNodeBuilder::generateNode(const iterator &I,
648
                                      ProgramStateRef St,
649
8
                                      bool IsSink) {
650
8
  bool IsNew;
651
8
  ExplodedNode *Succ =
652
8
      Eng.G.getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()),
653
8
                    St, IsSink, &IsNew);
654
8
  Succ->addPredecessor(Pred, Eng.G);
655
656
8
  if (!IsNew)
657
0
    return nullptr;
658
659
8
  if (!IsSink)
660
8
    Eng.WList->enqueue(Succ);
661
662
8
  return Succ;
663
8
}
664
665
ExplodedNode*
666
SwitchNodeBuilder::generateCaseStmtNode(const iterator &I,
667
410
                                        ProgramStateRef St) {
668
410
  bool IsNew;
669
410
  ExplodedNode *Succ =
670
410
      Eng.G.getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()),
671
410
                    St, false, &IsNew);
672
410
  Succ->addPredecessor(Pred, Eng.G);
673
410
  if (!IsNew)
674
0
    return nullptr;
675
676
410
  Eng.WList->enqueue(Succ);
677
410
  return Succ;
678
410
}
679
680
ExplodedNode*
681
SwitchNodeBuilder::generateDefaultCaseNode(ProgramStateRef St,
682
153
                                           bool IsSink) {
683
  // Get the block for the default case.
684
153
  assert(Src->succ_rbegin() != Src->succ_rend());
685
0
  CFGBlock *DefaultBlock = *Src->succ_rbegin();
686
687
  // Sanity check for default blocks that are unreachable and not caught
688
  // by earlier stages.
689
153
  if (!DefaultBlock)
690
0
    return nullptr;
691
692
153
  bool IsNew;
693
153
  ExplodedNode *Succ =
694
153
      Eng.G.getNode(BlockEdge(Src, DefaultBlock, Pred->getLocationContext()),
695
153
                    St, IsSink, &IsNew);
696
153
  Succ->addPredecessor(Pred, Eng.G);
697
698
153
  if (!IsNew)
699
0
    return nullptr;
700
701
153
  if (!IsSink)
702
153
    Eng.WList->enqueue(Succ);
703
704
153
  return Succ;
705
153
}