Coverage Report

Created: 2023-09-30 09:22

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- BugReporter.cpp - Generate PathDiagnostics for bugs ----------------===//
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 BugReporter, a utility class for generating
10
//  PathDiagnostics.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
15
#include "clang/AST/Decl.h"
16
#include "clang/AST/DeclBase.h"
17
#include "clang/AST/DeclObjC.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/ExprCXX.h"
20
#include "clang/AST/ParentMap.h"
21
#include "clang/AST/Stmt.h"
22
#include "clang/AST/StmtCXX.h"
23
#include "clang/AST/StmtObjC.h"
24
#include "clang/Analysis/AnalysisDeclContext.h"
25
#include "clang/Analysis/CFG.h"
26
#include "clang/Analysis/CFGStmtMap.h"
27
#include "clang/Analysis/PathDiagnostic.h"
28
#include "clang/Analysis/ProgramPoint.h"
29
#include "clang/Basic/LLVM.h"
30
#include "clang/Basic/SourceLocation.h"
31
#include "clang/Basic/SourceManager.h"
32
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
33
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
34
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
35
#include "clang/StaticAnalyzer/Core/Checker.h"
36
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
37
#include "clang/StaticAnalyzer/Core/CheckerRegistryData.h"
38
#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
39
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
40
#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
41
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
42
#include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
43
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
44
#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
45
#include "llvm/ADT/ArrayRef.h"
46
#include "llvm/ADT/DenseMap.h"
47
#include "llvm/ADT/DenseSet.h"
48
#include "llvm/ADT/FoldingSet.h"
49
#include "llvm/ADT/STLExtras.h"
50
#include "llvm/ADT/SmallPtrSet.h"
51
#include "llvm/ADT/SmallString.h"
52
#include "llvm/ADT/SmallVector.h"
53
#include "llvm/ADT/Statistic.h"
54
#include "llvm/ADT/StringExtras.h"
55
#include "llvm/ADT/StringRef.h"
56
#include "llvm/ADT/iterator_range.h"
57
#include "llvm/Support/Casting.h"
58
#include "llvm/Support/Compiler.h"
59
#include "llvm/Support/ErrorHandling.h"
60
#include "llvm/Support/MemoryBuffer.h"
61
#include "llvm/Support/raw_ostream.h"
62
#include <algorithm>
63
#include <cassert>
64
#include <cstddef>
65
#include <iterator>
66
#include <memory>
67
#include <optional>
68
#include <queue>
69
#include <string>
70
#include <tuple>
71
#include <utility>
72
#include <vector>
73
74
using namespace clang;
75
using namespace ento;
76
using namespace llvm;
77
78
#define DEBUG_TYPE "BugReporter"
79
80
STATISTIC(MaxBugClassSize,
81
          "The maximum number of bug reports in the same equivalence class");
82
STATISTIC(MaxValidBugClassSize,
83
          "The maximum number of bug reports in the same equivalence class "
84
          "where at least one report is valid (not suppressed)");
85
86
104k
BugReporterVisitor::~BugReporterVisitor() = default;
87
88
0
void BugReporterContext::anchor() {}
89
90
//===----------------------------------------------------------------------===//
91
// PathDiagnosticBuilder and its associated routines and helper objects.
92
//===----------------------------------------------------------------------===//
93
94
namespace {
95
96
/// A (CallPiece, node assiciated with its CallEnter) pair.
97
using CallWithEntry =
98
    std::pair<PathDiagnosticCallPiece *, const ExplodedNode *>;
99
using CallWithEntryStack = SmallVector<CallWithEntry, 6>;
100
101
/// Map from each node to the diagnostic pieces visitors emit for them.
102
using VisitorsDiagnosticsTy =
103
    llvm::DenseMap<const ExplodedNode *, std::vector<PathDiagnosticPieceRef>>;
104
105
/// A map from PathDiagnosticPiece to the LocationContext of the inlined
106
/// function call it represents.
107
using LocationContextMap =
108
    llvm::DenseMap<const PathPieces *, const LocationContext *>;
109
110
/// A helper class that contains everything needed to construct a
111
/// PathDiagnostic object. It does no much more then providing convenient
112
/// getters and some well placed asserts for extra security.
113
class PathDiagnosticConstruct {
114
  /// The consumer we're constructing the bug report for.
115
  const PathDiagnosticConsumer *Consumer;
116
  /// Our current position in the bug path, which is owned by
117
  /// PathDiagnosticBuilder.
118
  const ExplodedNode *CurrentNode;
119
  /// A mapping from parts of the bug path (for example, a function call, which
120
  /// would span backwards from a CallExit to a CallEnter with the nodes in
121
  /// between them) with the location contexts it is associated with.
122
  LocationContextMap LCM;
123
  const SourceManager &SM;
124
125
public:
126
  /// We keep stack of calls to functions as we're ascending the bug path.
127
  /// TODO: PathDiagnostic has a stack doing the same thing, shouldn't we use
128
  /// that instead?
129
  CallWithEntryStack CallStack;
130
  /// The bug report we're constructing. For ease of use, this field is kept
131
  /// public, though some "shortcut" getters are provided for commonly used
132
  /// methods of PathDiagnostic.
133
  std::unique_ptr<PathDiagnostic> PD;
134
135
public:
136
  PathDiagnosticConstruct(const PathDiagnosticConsumer *PDC,
137
                          const ExplodedNode *ErrorNode,
138
                          const PathSensitiveBugReport *R);
139
140
  /// \returns the location context associated with the current position in the
141
  /// bug path.
142
270k
  const LocationContext *getCurrLocationContext() const {
143
270k
    assert(CurrentNode && "Already reached the root!");
144
270k
    return CurrentNode->getLocationContext();
145
270k
  }
146
147
  /// Same as getCurrLocationContext (they should always return the same
148
  /// location context), but works after reaching the root of the bug path as
149
  /// well.
150
226k
  const LocationContext *getLocationContextForActivePath() const {
151
226k
    return LCM.find(&PD->getActivePath())->getSecond();
152
226k
  }
153
154
475k
  const ExplodedNode *getCurrentNode() const { return CurrentNode; }
155
156
  /// Steps the current node to its predecessor.
157
  /// \returns whether we reached the root of the bug path.
158
235k
  bool ascendToPrevNode() {
159
235k
    CurrentNode = CurrentNode->getFirstPred();
160
235k
    return static_cast<bool>(CurrentNode);
161
235k
  }
162
163
2.14k
  const ParentMap &getParentMap() const {
164
2.14k
    return getCurrLocationContext()->getParentMap();
165
2.14k
  }
166
167
24.2k
  const SourceManager &getSourceManager() const { return SM; }
168
169
0
  const Stmt *getParent(const Stmt *S) const {
170
0
    return getParentMap().getParent(S);
171
0
  }
172
173
7.43k
  void updateLocCtxMap(const PathPieces *Path, const LocationContext *LC) {
174
7.43k
    assert(Path && LC);
175
7.43k
    LCM[Path] = LC;
176
7.43k
  }
177
178
9.96k
  const LocationContext *getLocationContextFor(const PathPieces *Path) const {
179
9.96k
    assert(LCM.count(Path) &&
180
9.96k
           "Failed to find the context associated with these pieces!");
181
9.96k
    return LCM.find(Path)->getSecond();
182
9.96k
  }
183
184
7.43k
  bool isInLocCtxMap(const PathPieces *Path) const { return LCM.count(Path); }
185
186
46.0k
  PathPieces &getActivePath() { return PD->getActivePath(); }
187
13.8k
  PathPieces &getMutablePieces() { return PD->getMutablePieces(); }
188
189
161k
  bool shouldAddPathEdges() const { return Consumer->shouldAddPathEdges(); }
190
18.5k
  bool shouldAddControlNotes() const {
191
18.5k
    return Consumer->shouldAddControlNotes();
192
18.5k
  }
193
0
  bool shouldGenerateDiagnostics() const {
194
0
    return Consumer->shouldGenerateDiagnostics();
195
0
  }
196
86
  bool supportsLogicalOpControlFlow() const {
197
86
    return Consumer->supportsLogicalOpControlFlow();
198
86
  }
199
};
200
201
/// Contains every contextual information needed for constructing a
202
/// PathDiagnostic object for a given bug report. This class and its fields are
203
/// immutable, and passes a BugReportConstruct object around during the
204
/// construction.
205
class PathDiagnosticBuilder : public BugReporterContext {
206
  /// A linear path from the error node to the root.
207
  std::unique_ptr<const ExplodedGraph> BugPath;
208
  /// The bug report we're describing. Visitors create their diagnostics with
209
  /// them being the last entities being able to modify it (for example,
210
  /// changing interestingness here would cause inconsistencies as to how this
211
  /// file and visitors construct diagnostics), hence its const.
212
  const PathSensitiveBugReport *R;
213
  /// The leaf of the bug path. This isn't the same as the bug reports error
214
  /// node, which refers to the *original* graph, not the bug path.
215
  const ExplodedNode *const ErrorNode;
216
  /// The diagnostic pieces visitors emitted, which is expected to be collected
217
  /// by the time this builder is constructed.
218
  std::unique_ptr<const VisitorsDiagnosticsTy> VisitorsDiagnostics;
219
220
public:
221
  /// Find a non-invalidated report for a given equivalence class,  and returns
222
  /// a PathDiagnosticBuilder able to construct bug reports for different
223
  /// consumers. Returns std::nullopt if no valid report is found.
224
  static std::optional<PathDiagnosticBuilder>
225
  findValidReport(ArrayRef<PathSensitiveBugReport *> &bugReports,
226
                  PathSensitiveBugReporter &Reporter);
227
228
  PathDiagnosticBuilder(
229
      BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
230
      PathSensitiveBugReport *r, const ExplodedNode *ErrorNode,
231
      std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics);
232
233
  /// This function is responsible for generating diagnostic pieces that are
234
  /// *not* provided by bug report visitors.
235
  /// These diagnostics may differ depending on the consumer's settings,
236
  /// and are therefore constructed separately for each consumer.
237
  ///
238
  /// There are two path diagnostics generation modes: with adding edges (used
239
  /// for plists) and without  (used for HTML and text). When edges are added,
240
  /// the path is modified to insert artificially generated edges.
241
  /// Otherwise, more detailed diagnostics is emitted for block edges,
242
  /// explaining the transitions in words.
243
  std::unique_ptr<PathDiagnostic>
244
  generate(const PathDiagnosticConsumer *PDC) const;
245
246
private:
247
  void updateStackPiecesWithMessage(PathDiagnosticPieceRef P,
248
                                    const CallWithEntryStack &CallStack) const;
249
  void generatePathDiagnosticsForNode(PathDiagnosticConstruct &C,
250
                                      PathDiagnosticLocation &PrevLoc) const;
251
252
  void generateMinimalDiagForBlockEdge(PathDiagnosticConstruct &C,
253
                                       BlockEdge BE) const;
254
255
  PathDiagnosticPieceRef
256
  generateDiagForGotoOP(const PathDiagnosticConstruct &C, const Stmt *S,
257
                        PathDiagnosticLocation &Start) const;
258
259
  PathDiagnosticPieceRef
260
  generateDiagForSwitchOP(const PathDiagnosticConstruct &C, const CFGBlock *Dst,
261
                          PathDiagnosticLocation &Start) const;
262
263
  PathDiagnosticPieceRef
264
  generateDiagForBinaryOP(const PathDiagnosticConstruct &C, const Stmt *T,
265
                          const CFGBlock *Src, const CFGBlock *DstC) const;
266
267
  PathDiagnosticLocation
268
  ExecutionContinues(const PathDiagnosticConstruct &C) const;
269
270
  PathDiagnosticLocation
271
  ExecutionContinues(llvm::raw_string_ostream &os,
272
                     const PathDiagnosticConstruct &C) const;
273
274
1.85k
  const PathSensitiveBugReport *getBugReport() const { return R; }
275
};
276
277
} // namespace
278
279
//===----------------------------------------------------------------------===//
280
// Base implementation of stack hint generators.
281
//===----------------------------------------------------------------------===//
282
283
626
StackHintGenerator::~StackHintGenerator() = default;
284
285
21
std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
286
21
  if (!N)
287
0
    return getMessageForSymbolNotFound();
288
289
21
  ProgramPoint P = N->getLocation();
290
21
  CallExitEnd CExit = P.castAs<CallExitEnd>();
291
292
  // FIXME: Use CallEvent to abstract this over all calls.
293
21
  const Stmt *CallSite = CExit.getCalleeContext()->getCallSite();
294
21
  const auto *CE = dyn_cast_or_null<CallExpr>(CallSite);
295
21
  if (!CE)
296
1
    return {};
297
298
  // Check if one of the parameters are set to the interesting symbol.
299
20
  for (auto [Idx, ArgExpr] : llvm::enumerate(CE->arguments())) {
300
11
    SVal SV = N->getSVal(ArgExpr);
301
302
    // Check if the variable corresponding to the symbol is passed by value.
303
11
    SymbolRef AS = SV.getAsLocSymbol();
304
11
    if (AS == Sym) {
305
4
      return getMessageForArg(ArgExpr, Idx);
306
4
    }
307
308
    // Check if the parameter is a pointer to the symbol.
309
7
    if (std::optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) {
310
      // Do not attempt to dereference void*.
311
5
      if (ArgExpr->getType()->isVoidPointerType())
312
0
        continue;
313
5
      SVal PSV = N->getState()->getSVal(Reg->getRegion());
314
5
      SymbolRef AS = PSV.getAsLocSymbol();
315
5
      if (AS == Sym) {
316
2
        return getMessageForArg(ArgExpr, Idx);
317
2
      }
318
5
    }
319
7
  }
320
321
  // Check if we are returning the interesting symbol.
322
14
  SVal SV = N->getSVal(CE);
323
14
  SymbolRef RetSym = SV.getAsLocSymbol();
324
14
  if (RetSym == Sym) {
325
9
    return getMessageForReturn(CE);
326
9
  }
327
328
5
  return getMessageForSymbolNotFound();
329
14
}
330
331
std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
332
5
                                                          unsigned ArgIndex) {
333
  // Printed parameters start at 1, not 0.
334
5
  ++ArgIndex;
335
336
5
  return (llvm::Twine(Msg) + " via " + std::to_string(ArgIndex) +
337
5
          llvm::getOrdinalSuffix(ArgIndex) + " parameter").str();
338
5
}
339
340
//===----------------------------------------------------------------------===//
341
// Diagnostic cleanup.
342
//===----------------------------------------------------------------------===//
343
344
static PathDiagnosticEventPiece *
345
eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
346
1.57k
                            PathDiagnosticEventPiece *Y) {
347
  // Prefer diagnostics that come from ConditionBRVisitor over
348
  // those that came from TrackConstraintBRVisitor,
349
  // unless the one from ConditionBRVisitor is
350
  // its generic fallback diagnostic.
351
1.57k
  const void *tagPreferred = ConditionBRVisitor::getTag();
352
1.57k
  const void *tagLesser = TrackConstraintBRVisitor::getTag();
353
354
1.57k
  if (X->getLocation() != Y->getLocation())
355
1.39k
    return nullptr;
356
357
176
  if (X->getTag() == tagPreferred && 
Y->getTag() == tagLesser117
)
358
97
    return ConditionBRVisitor::isPieceMessageGeneric(X) ? 
Y5
:
X92
;
359
360
79
  if (Y->getTag() == tagPreferred && 
X->getTag() == tagLesser17
)
361
15
    return ConditionBRVisitor::isPieceMessageGeneric(Y) ? 
X2
:
Y13
;
362
363
64
  return nullptr;
364
79
}
365
366
/// An optimization pass over PathPieces that removes redundant diagnostics
367
/// generated by both ConditionBRVisitor and TrackConstraintBRVisitor.  Both
368
/// BugReporterVisitors use different methods to generate diagnostics, with
369
/// one capable of emitting diagnostics in some cases but not in others.  This
370
/// can lead to redundant diagnostic pieces at the same point in a path.
371
2.69k
static void removeRedundantMsgs(PathPieces &path) {
372
2.69k
  unsigned N = path.size();
373
2.69k
  if (N < 2)
374
451
    return;
375
  // NOTE: this loop intentionally is not using an iterator.  Instead, we
376
  // are streaming the path and modifying it in place.  This is done by
377
  // grabbing the front, processing it, and if we decide to keep it append
378
  // it to the end of the path.  The entire path is processed in this way.
379
11.7k
  
for (unsigned i = 0; 2.24k
i < N;
++i9.54k
) {
380
9.54k
    auto piece = std::move(path.front());
381
9.54k
    path.pop_front();
382
383
9.54k
    switch (piece->getKind()) {
384
407
      case PathDiagnosticPiece::Call:
385
407
        removeRedundantMsgs(cast<PathDiagnosticCallPiece>(*piece).path);
386
407
        break;
387
0
      case PathDiagnosticPiece::Macro:
388
0
        removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(*piece).subPieces);
389
0
        break;
390
5.30k
      case PathDiagnosticPiece::Event: {
391
5.30k
        if (i == N-1)
392
2.06k
          break;
393
394
3.23k
        if (auto *nextEvent =
395
3.23k
            dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
396
1.57k
          auto *event = cast<PathDiagnosticEventPiece>(piece.get());
397
          // Check to see if we should keep one of the two pieces.  If we
398
          // come up with a preference, record which piece to keep, and consume
399
          // another piece from the path.
400
1.57k
          if (auto *pieceToKeep =
401
1.57k
                  eventsDescribeSameCondition(event, nextEvent)) {
402
112
            piece = std::move(pieceToKeep == event ? 
piece94
:
path.front()18
);
403
112
            path.pop_front();
404
112
            ++i;
405
112
          }
406
1.57k
        }
407
3.23k
        break;
408
5.30k
      }
409
3.59k
      case PathDiagnosticPiece::ControlFlow:
410
3.59k
      case PathDiagnosticPiece::Note:
411
3.83k
      case PathDiagnosticPiece::PopUp:
412
3.83k
        break;
413
9.54k
    }
414
9.54k
    path.push_back(std::move(piece));
415
9.54k
  }
416
2.24k
}
417
418
/// Recursively scan through a path and prune out calls and macros pieces
419
/// that aren't needed.  Return true if afterwards the path contains
420
/// "interesting stuff" which means it shouldn't be pruned from the parent path.
421
static bool removeUnneededCalls(const PathDiagnosticConstruct &C,
422
                                PathPieces &pieces,
423
                                const PathSensitiveBugReport *R,
424
9.53k
                                bool IsInteresting = false) {
425
9.53k
  bool containsSomethingInteresting = IsInteresting;
426
9.53k
  const unsigned N = pieces.size();
427
428
38.3k
  for (unsigned i = 0 ; i < N ; 
++i28.7k
) {
429
    // Remove the front piece from the path.  If it is still something we
430
    // want to keep once we are done, we will push it back on the end.
431
28.7k
    auto piece = std::move(pieces.front());
432
28.7k
    pieces.pop_front();
433
434
28.7k
    switch (piece->getKind()) {
435
7.24k
      case PathDiagnosticPiece::Call: {
436
7.24k
        auto &call = cast<PathDiagnosticCallPiece>(*piece);
437
        // Check if the location context is interesting.
438
7.24k
        if (!removeUnneededCalls(
439
7.24k
                C, call.path, R,
440
7.24k
                R->isInteresting(C.getLocationContextFor(&call.path))))
441
6.77k
          continue;
442
443
474
        containsSomethingInteresting = true;
444
474
        break;
445
7.24k
      }
446
0
      case PathDiagnosticPiece::Macro: {
447
0
        auto &macro = cast<PathDiagnosticMacroPiece>(*piece);
448
0
        if (!removeUnneededCalls(C, macro.subPieces, R, IsInteresting))
449
0
          continue;
450
0
        containsSomethingInteresting = true;
451
0
        break;
452
0
      }
453
5.94k
      case PathDiagnosticPiece::Event: {
454
5.94k
        auto &event = cast<PathDiagnosticEventPiece>(*piece);
455
456
        // We never throw away an event, but we do throw it away wholesale
457
        // as part of a path if we throw the entire path away.
458
5.94k
        containsSomethingInteresting |= !event.isPrunable();
459
5.94k
        break;
460
0
      }
461
15.3k
      case PathDiagnosticPiece::ControlFlow:
462
15.3k
      case PathDiagnosticPiece::Note:
463
15.5k
      case PathDiagnosticPiece::PopUp:
464
15.5k
        break;
465
28.7k
    }
466
467
22.0k
    pieces.push_back(std::move(piece));
468
22.0k
  }
469
470
9.53k
  return containsSomethingInteresting;
471
9.53k
}
472
473
/// Same logic as above to remove extra pieces.
474
4
static void removePopUpNotes(PathPieces &Path) {
475
34
  for (unsigned int i = 0; i < Path.size(); 
++i30
) {
476
30
    auto Piece = std::move(Path.front());
477
30
    Path.pop_front();
478
30
    if (!isa<PathDiagnosticPopUpPiece>(*Piece))
479
28
      Path.push_back(std::move(Piece));
480
30
  }
481
4
}
482
483
/// Returns true if the given decl has been implicitly given a body, either by
484
/// the analyzer or by the compiler proper.
485
543
static bool hasImplicitBody(const Decl *D) {
486
543
  assert(D);
487
543
  return D->isImplicit() || 
!D->hasBody()519
;
488
543
}
489
490
/// Recursively scan through a path and make sure that all call pieces have
491
/// valid locations.
492
static void
493
adjustCallLocations(PathPieces &Pieces,
494
2.76k
                    PathDiagnosticLocation *LastCallLocation = nullptr) {
495
21.4k
  for (const auto &I : Pieces) {
496
21.4k
    auto *Call = dyn_cast<PathDiagnosticCallPiece>(I.get());
497
498
21.4k
    if (!Call)
499
20.9k
      continue;
500
501
479
    if (LastCallLocation) {
502
64
      bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
503
64
      if (CallerIsImplicit || 
!Call->callEnter.asLocation().isValid()44
)
504
26
        Call->callEnter = *LastCallLocation;
505
64
      if (CallerIsImplicit || 
!Call->callReturn.asLocation().isValid()44
)
506
46
        Call->callReturn = *LastCallLocation;
507
64
    }
508
509
    // Recursively clean out the subclass.  Keep this call around if
510
    // it contains any informative diagnostics.
511
479
    PathDiagnosticLocation *ThisCallLocation;
512
479
    if (Call->callEnterWithin.asLocation().isValid() &&
513
479
        !hasImplicitBody(Call->getCallee()))
514
453
      ThisCallLocation = &Call->callEnterWithin;
515
26
    else
516
26
      ThisCallLocation = &Call->callEnter;
517
518
479
    assert(ThisCallLocation && "Outermost call has an invalid location");
519
479
    adjustCallLocations(Call->path, ThisCallLocation);
520
479
  }
521
2.76k
}
522
523
/// Remove edges in and out of C++ default initializer expressions. These are
524
/// for fields that have in-class initializers, as opposed to being initialized
525
/// explicitly in a constructor or braced list.
526
2.76k
static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
527
12.9k
  for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
528
10.1k
    if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
529
479
      removeEdgesToDefaultInitializers(C->path);
530
531
10.1k
    if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
532
0
      removeEdgesToDefaultInitializers(M->subPieces);
533
534
10.1k
    if (auto *CF = dyn_cast<PathDiagnosticControlFlowPiece>(I->get())) {
535
3.66k
      const Stmt *Start = CF->getStartLocation().asStmt();
536
3.66k
      const Stmt *End = CF->getEndLocation().asStmt();
537
3.66k
      if (isa_and_nonnull<CXXDefaultInitExpr>(Start)) {
538
0
        I = Pieces.erase(I);
539
0
        continue;
540
3.66k
      } else if (isa_and_nonnull<CXXDefaultInitExpr>(End)) {
541
1
        PathPieces::iterator Next = std::next(I);
542
1
        if (Next != E) {
543
1
          if (auto *NextCF =
544
1
                  dyn_cast<PathDiagnosticControlFlowPiece>(Next->get())) {
545
1
            NextCF->setStartLocation(CF->getStartLocation());
546
1
          }
547
1
        }
548
1
        I = Pieces.erase(I);
549
1
        continue;
550
1
      }
551
3.66k
    }
552
553
10.1k
    I++;
554
10.1k
  }
555
2.76k
}
556
557
/// Remove all pieces with invalid locations as these cannot be serialized.
558
/// We might have pieces with invalid locations as a result of inlining Body
559
/// Farm generated functions.
560
2.76k
static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
561
24.2k
  for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
562
21.4k
    if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
563
479
      removePiecesWithInvalidLocations(C->path);
564
565
21.4k
    if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
566
0
      removePiecesWithInvalidLocations(M->subPieces);
567
568
21.4k
    if (!(*I)->getLocation().isValid() ||
569
21.4k
        !(*I)->getLocation().asLocation().isValid()) {
570
11
      I = Pieces.erase(I);
571
11
      continue;
572
11
    }
573
21.4k
    I++;
574
21.4k
  }
575
2.76k
}
576
577
PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
578
1.12k
    const PathDiagnosticConstruct &C) const {
579
1.12k
  if (const Stmt *S = C.getCurrentNode()->getNextStmtForDiagnostics())
580
1.12k
    return PathDiagnosticLocation(S, getSourceManager(),
581
1.12k
                                  C.getCurrLocationContext());
582
583
0
  return PathDiagnosticLocation::createDeclEnd(C.getCurrLocationContext(),
584
0
                                               getSourceManager());
585
1.12k
}
586
587
PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
588
79
    llvm::raw_string_ostream &os, const PathDiagnosticConstruct &C) const {
589
  // Slow, but probably doesn't matter.
590
79
  if (os.str().empty())
591
6
    os << ' ';
592
593
79
  const PathDiagnosticLocation &Loc = ExecutionContinues(C);
594
595
79
  if (Loc.asStmt())
596
13
    os << "Execution continues on line "
597
13
       << getSourceManager().getExpansionLineNumber(Loc.asLocation())
598
13
       << '.';
599
66
  else {
600
66
    os << "Execution jumps to the end of the ";
601
66
    const Decl *D = C.getCurrLocationContext()->getDecl();
602
66
    if (isa<ObjCMethodDecl>(D))
603
0
      os << "method";
604
66
    else if (isa<FunctionDecl>(D))
605
66
      os << "function";
606
0
    else {
607
0
      assert(isa<BlockDecl>(D));
608
0
      os << "anonymous block";
609
0
    }
610
66
    os << '.';
611
66
  }
612
613
79
  return Loc;
614
79
}
615
616
15.6k
static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
617
15.6k
  if (isa<Expr>(S) && 
PM.isConsumedExpr(cast<Expr>(S))9.25k
)
618
5.99k
    return PM.getParentIgnoreParens(S);
619
620
9.68k
  const Stmt *Parent = PM.getParentIgnoreParens(S);
621
9.68k
  if (!Parent)
622
64
    return nullptr;
623
624
9.62k
  switch (Parent->getStmtClass()) {
625
57
  case Stmt::ForStmtClass:
626
57
  case Stmt::DoStmtClass:
627
59
  case Stmt::WhileStmtClass:
628
85
  case Stmt::ObjCForCollectionStmtClass:
629
139
  case Stmt::CXXForRangeStmtClass:
630
139
    return Parent;
631
9.48k
  default:
632
9.48k
    break;
633
9.62k
  }
634
635
9.48k
  return nullptr;
636
9.62k
}
637
638
static PathDiagnosticLocation
639
getEnclosingStmtLocation(const Stmt *S, const LocationContext *LC,
640
10.1k
                         bool allowNestedContexts = false) {
641
10.1k
  if (!S)
642
367
    return {};
643
644
9.80k
  const SourceManager &SMgr = LC->getDecl()->getASTContext().getSourceManager();
645
646
15.6k
  while (const Stmt *Parent = getEnclosingParent(S, LC->getParentMap())) {
647
6.13k
    switch (Parent->getStmtClass()) {
648
718
      case Stmt::BinaryOperatorClass: {
649
718
        const auto *B = cast<BinaryOperator>(Parent);
650
718
        if (B->isLogicalOp())
651
88
          return PathDiagnosticLocation(allowNestedContexts ? B : 
S0
, SMgr, LC);
652
630
        break;
653
718
      }
654
630
      case Stmt::CompoundStmtClass:
655
0
      case Stmt::StmtExprClass:
656
0
        return PathDiagnosticLocation(S, SMgr, LC);
657
0
      case Stmt::ChooseExprClass:
658
        // Similar to '?' if we are referring to condition, just have the edge
659
        // point to the entire choose expression.
660
0
        if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
661
0
          return PathDiagnosticLocation(Parent, SMgr, LC);
662
0
        else
663
0
          return PathDiagnosticLocation(S, SMgr, LC);
664
4
      case Stmt::BinaryConditionalOperatorClass:
665
88
      case Stmt::ConditionalOperatorClass:
666
        // For '?', if we are referring to condition, just have the edge point
667
        // to the entire '?' expression.
668
88
        if (allowNestedContexts ||
669
88
            
cast<AbstractConditionalOperator>(Parent)->getCond() == S32
)
670
57
          return PathDiagnosticLocation(Parent, SMgr, LC);
671
31
        else
672
31
          return PathDiagnosticLocation(S, SMgr, LC);
673
54
      case Stmt::CXXForRangeStmtClass:
674
54
        if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
675
0
          return PathDiagnosticLocation(S, SMgr, LC);
676
54
        break;
677
54
      case Stmt::DoStmtClass:
678
29
          return PathDiagnosticLocation(S, SMgr, LC);
679
165
      case Stmt::ForStmtClass:
680
165
        if (cast<ForStmt>(Parent)->getBody() == S)
681
52
          return PathDiagnosticLocation(S, SMgr, LC);
682
113
        break;
683
1.19k
      case Stmt::IfStmtClass:
684
1.19k
        if (cast<IfStmt>(Parent)->getCond() != S)
685
0
          return PathDiagnosticLocation(S, SMgr, LC);
686
1.19k
        break;
687
1.19k
      case Stmt::ObjCForCollectionStmtClass:
688
26
        if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
689
2
          return PathDiagnosticLocation(S, SMgr, LC);
690
24
        break;
691
42
      case Stmt::WhileStmtClass:
692
42
        if (cast<WhileStmt>(Parent)->getCond() != S)
693
2
          return PathDiagnosticLocation(S, SMgr, LC);
694
40
        break;
695
3.82k
      default:
696
3.82k
        break;
697
6.13k
    }
698
699
5.87k
    S = Parent;
700
5.87k
  }
701
702
9.54k
  assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
703
704
9.54k
  return PathDiagnosticLocation(S, SMgr, LC);
705
9.54k
}
706
707
//===----------------------------------------------------------------------===//
708
// "Minimal" path diagnostic generation algorithm.
709
//===----------------------------------------------------------------------===//
710
711
/// If the piece contains a special message, add it to all the call pieces on
712
/// the active stack. For example, my_malloc allocated memory, so MallocChecker
713
/// will construct an event at the call to malloc(), and add a stack hint that
714
/// an allocated memory was returned. We'll use this hint to construct a message
715
/// when returning from the call to my_malloc
716
///
717
///   void *my_malloc() { return malloc(sizeof(int)); }
718
///   void fishy() {
719
///     void *ptr = my_malloc(); // returned allocated memory
720
///   } // leak
721
void PathDiagnosticBuilder::updateStackPiecesWithMessage(
722
3.80k
    PathDiagnosticPieceRef P, const CallWithEntryStack &CallStack) const {
723
3.80k
  if (R->hasCallStackHint(P))
724
119
    for (const auto &I : CallStack) {
725
21
      PathDiagnosticCallPiece *CP = I.first;
726
21
      const ExplodedNode *N = I.second;
727
21
      std::string stackMsg = R->getCallStackMessage(P, N);
728
729
      // The last message on the path to final bug is the most important
730
      // one. Since we traverse the path backwards, do not add the message
731
      // if one has been previously added.
732
21
      if (!CP->hasCallStackMessage())
733
19
        CP->setCallStackMessage(stackMsg);
734
21
    }
735
3.80k
}
736
737
static void CompactMacroExpandedPieces(PathPieces &path,
738
                                       const SourceManager& SM);
739
740
PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForSwitchOP(
741
    const PathDiagnosticConstruct &C, const CFGBlock *Dst,
742
15
    PathDiagnosticLocation &Start) const {
743
744
15
  const SourceManager &SM = getSourceManager();
745
  // Figure out what case arm we took.
746
15
  std::string sbuf;
747
15
  llvm::raw_string_ostream os(sbuf);
748
15
  PathDiagnosticLocation End;
749
750
15
  if (const Stmt *S = Dst->getLabel()) {
751
15
    End = PathDiagnosticLocation(S, SM, C.getCurrLocationContext());
752
753
15
    switch (S->getStmtClass()) {
754
0
    default:
755
0
      os << "No cases match in the switch statement. "
756
0
        "Control jumps to line "
757
0
        << End.asLocation().getExpansionLineNumber();
758
0
      break;
759
2
    case Stmt::DefaultStmtClass:
760
2
      os << "Control jumps to the 'default' case at line "
761
2
        << End.asLocation().getExpansionLineNumber();
762
2
      break;
763
764
13
    case Stmt::CaseStmtClass: {
765
13
      os << "Control jumps to 'case ";
766
13
      const auto *Case = cast<CaseStmt>(S);
767
13
      const Expr *LHS = Case->getLHS()->IgnoreParenImpCasts();
768
769
      // Determine if it is an enum.
770
13
      bool GetRawInt = true;
771
772
13
      if (const auto *DR = dyn_cast<DeclRefExpr>(LHS)) {
773
        // FIXME: Maybe this should be an assertion.  Are there cases
774
        // were it is not an EnumConstantDecl?
775
1
        const auto *D = dyn_cast<EnumConstantDecl>(DR->getDecl());
776
777
1
        if (D) {
778
1
          GetRawInt = false;
779
1
          os << *D;
780
1
        }
781
1
      }
782
783
13
      if (GetRawInt)
784
12
        os << LHS->EvaluateKnownConstInt(getASTContext());
785
786
13
      os << ":'  at line " << End.asLocation().getExpansionLineNumber();
787
13
      break;
788
0
    }
789
15
    }
790
15
  } else {
791
0
    os << "'Default' branch taken. ";
792
0
    End = ExecutionContinues(os, C);
793
0
  }
794
15
  return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
795
15
                                                       os.str());
796
15
}
797
798
PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForGotoOP(
799
    const PathDiagnosticConstruct &C, const Stmt *S,
800
1
    PathDiagnosticLocation &Start) const {
801
1
  std::string sbuf;
802
1
  llvm::raw_string_ostream os(sbuf);
803
1
  const PathDiagnosticLocation &End =
804
1
      getEnclosingStmtLocation(S, C.getCurrLocationContext());
805
1
  os << "Control jumps to line " << End.asLocation().getExpansionLineNumber();
806
1
  return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str());
807
1
}
808
809
PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForBinaryOP(
810
    const PathDiagnosticConstruct &C, const Stmt *T, const CFGBlock *Src,
811
86
    const CFGBlock *Dst) const {
812
813
86
  const SourceManager &SM = getSourceManager();
814
815
86
  const auto *B = cast<BinaryOperator>(T);
816
86
  std::string sbuf;
817
86
  llvm::raw_string_ostream os(sbuf);
818
86
  os << "Left side of '";
819
86
  PathDiagnosticLocation Start, End;
820
821
86
  if (B->getOpcode() == BO_LAnd) {
822
62
    os << "&&"
823
62
      << "' is ";
824
825
62
    if (*(Src->succ_begin() + 1) == Dst) {
826
36
      os << "false";
827
36
      End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
828
36
      Start =
829
36
        PathDiagnosticLocation::createOperatorLoc(B, SM);
830
36
    } else {
831
26
      os << "true";
832
26
      Start =
833
26
          PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
834
26
      End = ExecutionContinues(C);
835
26
    }
836
62
  } else {
837
24
    assert(B->getOpcode() == BO_LOr);
838
24
    os << "||"
839
24
      << "' is ";
840
841
24
    if (*(Src->succ_begin() + 1) == Dst) {
842
11
      os << "false";
843
11
      Start =
844
11
          PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
845
11
      End = ExecutionContinues(C);
846
13
    } else {
847
13
      os << "true";
848
13
      End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
849
13
      Start =
850
13
        PathDiagnosticLocation::createOperatorLoc(B, SM);
851
13
    }
852
24
  }
853
86
  return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
854
86
                                                         os.str());
855
86
}
856
857
void PathDiagnosticBuilder::generateMinimalDiagForBlockEdge(
858
16.7k
    PathDiagnosticConstruct &C, BlockEdge BE) const {
859
16.7k
  const SourceManager &SM = getSourceManager();
860
16.7k
  const LocationContext *LC = C.getCurrLocationContext();
861
16.7k
  const CFGBlock *Src = BE.getSrc();
862
16.7k
  const CFGBlock *Dst = BE.getDst();
863
16.7k
  const Stmt *T = Src->getTerminatorStmt();
864
16.7k
  if (!T)
865
15.5k
    return;
866
867
1.22k
  auto Start = PathDiagnosticLocation::createBegin(T, SM, LC);
868
1.22k
  switch (T->getStmtClass()) {
869
30
  default:
870
30
    break;
871
872
30
  case Stmt::GotoStmtClass:
873
1
  case Stmt::IndirectGotoStmtClass: {
874
1
    if (const Stmt *S = C.getCurrentNode()->getNextStmtForDiagnostics())
875
1
      C.getActivePath().push_front(generateDiagForGotoOP(C, S, Start));
876
1
    break;
877
1
  }
878
879
15
  case Stmt::SwitchStmtClass: {
880
15
    C.getActivePath().push_front(generateDiagForSwitchOP(C, Dst, Start));
881
15
    break;
882
1
  }
883
884
6
  case Stmt::BreakStmtClass:
885
6
  case Stmt::ContinueStmtClass: {
886
6
    std::string sbuf;
887
6
    llvm::raw_string_ostream os(sbuf);
888
6
    PathDiagnosticLocation End = ExecutionContinues(os, C);
889
6
    C.getActivePath().push_front(
890
6
        std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
891
6
    break;
892
6
  }
893
894
  // Determine control-flow for ternary '?'.
895
2
  case Stmt::BinaryConditionalOperatorClass:
896
31
  case Stmt::ConditionalOperatorClass: {
897
31
    std::string sbuf;
898
31
    llvm::raw_string_ostream os(sbuf);
899
31
    os << "'?' condition is ";
900
901
31
    if (*(Src->succ_begin() + 1) == Dst)
902
15
      os << "false";
903
16
    else
904
16
      os << "true";
905
906
31
    PathDiagnosticLocation End = ExecutionContinues(C);
907
908
31
    if (const Stmt *S = End.asStmt())
909
31
      End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
910
911
31
    C.getActivePath().push_front(
912
31
        std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
913
31
    break;
914
2
  }
915
916
  // Determine control-flow for short-circuited '&&' and '||'.
917
86
  case Stmt::BinaryOperatorClass: {
918
86
    if (!C.supportsLogicalOpControlFlow())
919
0
      break;
920
921
86
    C.getActivePath().push_front(generateDiagForBinaryOP(C, T, Src, Dst));
922
86
    break;
923
86
  }
924
925
13
  case Stmt::DoStmtClass:
926
13
    if (*(Src->succ_begin()) == Dst) {
927
1
      std::string sbuf;
928
1
      llvm::raw_string_ostream os(sbuf);
929
930
1
      os << "Loop condition is true. ";
931
1
      PathDiagnosticLocation End = ExecutionContinues(os, C);
932
933
1
      if (const Stmt *S = End.asStmt())
934
1
        End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
935
936
1
      C.getActivePath().push_front(
937
1
          std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
938
1
                                                           os.str()));
939
12
    } else {
940
12
      PathDiagnosticLocation End = ExecutionContinues(C);
941
942
12
      if (const Stmt *S = End.asStmt())
943
12
        End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
944
945
12
      C.getActivePath().push_front(
946
12
          std::make_shared<PathDiagnosticControlFlowPiece>(
947
12
              Start, End, "Loop condition is false.  Exiting loop"));
948
12
    }
949
13
    break;
950
951
8
  case Stmt::WhileStmtClass:
952
181
  case Stmt::ForStmtClass:
953
181
    if (*(Src->succ_begin() + 1) == Dst) {
954
72
      std::string sbuf;
955
72
      llvm::raw_string_ostream os(sbuf);
956
957
72
      os << "Loop condition is false. ";
958
72
      PathDiagnosticLocation End = ExecutionContinues(os, C);
959
72
      if (const Stmt *S = End.asStmt())
960
12
        End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
961
962
72
      C.getActivePath().push_front(
963
72
          std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
964
72
                                                           os.str()));
965
109
    } else {
966
109
      PathDiagnosticLocation End = ExecutionContinues(C);
967
109
      if (const Stmt *S = End.asStmt())
968
109
        End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
969
970
109
      C.getActivePath().push_front(
971
109
          std::make_shared<PathDiagnosticControlFlowPiece>(
972
109
              Start, End, "Loop condition is true.  Entering loop body"));
973
109
    }
974
975
181
    break;
976
977
861
  case Stmt::IfStmtClass: {
978
861
    PathDiagnosticLocation End = ExecutionContinues(C);
979
980
861
    if (const Stmt *S = End.asStmt())
981
806
      End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
982
983
861
    if (*(Src->succ_begin() + 1) == Dst)
984
480
      C.getActivePath().push_front(
985
480
          std::make_shared<PathDiagnosticControlFlowPiece>(
986
480
              Start, End, "Taking false branch"));
987
381
    else
988
381
      C.getActivePath().push_front(
989
381
          std::make_shared<PathDiagnosticControlFlowPiece>(
990
381
              Start, End, "Taking true branch"));
991
992
861
    break;
993
8
  }
994
1.22k
  }
995
1.22k
}
996
997
//===----------------------------------------------------------------------===//
998
// Functions for determining if a loop was executed 0 times.
999
//===----------------------------------------------------------------------===//
1000
1001
497
static bool isLoop(const Stmt *Term) {
1002
497
  switch (Term->getStmtClass()) {
1003
46
    case Stmt::ForStmtClass:
1004
62
    case Stmt::WhileStmtClass:
1005
70
    case Stmt::ObjCForCollectionStmtClass:
1006
96
    case Stmt::CXXForRangeStmtClass:
1007
96
      return true;
1008
401
    default:
1009
      // Note that we intentionally do not include do..while here.
1010
401
      return false;
1011
497
  }
1012
497
}
1013
1014
96
static bool isJumpToFalseBranch(const BlockEdge *BE) {
1015
96
  const CFGBlock *Src = BE->getSrc();
1016
96
  assert(Src->succ_size() == 2);
1017
96
  return (*(Src->succ_begin()+1) == BE->getDst());
1018
96
}
1019
1020
static bool isContainedByStmt(const ParentMap &PM, const Stmt *S,
1021
1.04k
                              const Stmt *SubS) {
1022
2.80k
  while (SubS) {
1023
2.58k
    if (SubS == S)
1024
823
      return true;
1025
1.76k
    SubS = PM.getParent(SubS);
1026
1.76k
  }
1027
223
  return false;
1028
1.04k
}
1029
1030
static const Stmt *getStmtBeforeCond(const ParentMap &PM, const Stmt *Term,
1031
96
                                     const ExplodedNode *N) {
1032
1.17k
  while (N) {
1033
1.17k
    std::optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
1034
1.17k
    if (SP) {
1035
883
      const Stmt *S = SP->getStmt();
1036
883
      if (!isContainedByStmt(PM, Term, S))
1037
88
        return S;
1038
883
    }
1039
1.08k
    N = N->getFirstPred();
1040
1.08k
  }
1041
8
  return nullptr;
1042
96
}
1043
1044
96
static bool isInLoopBody(const ParentMap &PM, const Stmt *S, const Stmt *Term) {
1045
96
  const Stmt *LoopBody = nullptr;
1046
96
  switch (Term->getStmtClass()) {
1047
26
    case Stmt::CXXForRangeStmtClass: {
1048
26
      const auto *FR = cast<CXXForRangeStmt>(Term);
1049
26
      if (isContainedByStmt(PM, FR->getInc(), S))
1050
11
        return true;
1051
15
      if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
1052
0
        return true;
1053
15
      LoopBody = FR->getBody();
1054
15
      break;
1055
15
    }
1056
46
    case Stmt::ForStmtClass: {
1057
46
      const auto *FS = cast<ForStmt>(Term);
1058
46
      if (isContainedByStmt(PM, FS->getInc(), S))
1059
9
        return true;
1060
37
      LoopBody = FS->getBody();
1061
37
      break;
1062
46
    }
1063
8
    case Stmt::ObjCForCollectionStmtClass: {
1064
8
      const auto *FC = cast<ObjCForCollectionStmt>(Term);
1065
8
      LoopBody = FC->getBody();
1066
8
      break;
1067
46
    }
1068
16
    case Stmt::WhileStmtClass:
1069
16
      LoopBody = cast<WhileStmt>(Term)->getBody();
1070
16
      break;
1071
0
    default:
1072
0
      return false;
1073
96
  }
1074
76
  return isContainedByStmt(PM, LoopBody, S);
1075
96
}
1076
1077
/// Adds a sanitized control-flow diagnostic edge to a path.
1078
static void addEdgeToPath(PathPieces &path,
1079
                          PathDiagnosticLocation &PrevLoc,
1080
25.8k
                          PathDiagnosticLocation NewLoc) {
1081
25.8k
  if (!NewLoc.isValid())
1082
0
    return;
1083
1084
25.8k
  SourceLocation NewLocL = NewLoc.asLocation();
1085
25.8k
  if (NewLocL.isInvalid())
1086
1.23k
    return;
1087
1088
24.6k
  if (!PrevLoc.isValid() || 
!PrevLoc.asLocation().isValid()24.4k
) {
1089
253
    PrevLoc = NewLoc;
1090
253
    return;
1091
253
  }
1092
1093
  // Ignore self-edges, which occur when there are multiple nodes at the same
1094
  // statement.
1095
24.4k
  if (NewLoc.asStmt() && 
NewLoc.asStmt() == PrevLoc.asStmt()23.3k
)
1096
10.2k
    return;
1097
1098
14.1k
  path.push_front(
1099
14.1k
      std::make_shared<PathDiagnosticControlFlowPiece>(NewLoc, PrevLoc));
1100
14.1k
  PrevLoc = NewLoc;
1101
14.1k
}
1102
1103
/// A customized wrapper for CFGBlock::getTerminatorCondition()
1104
/// which returns the element for ObjCForCollectionStmts.
1105
96
static const Stmt *getTerminatorCondition(const CFGBlock *B) {
1106
96
  const Stmt *S = B->getTerminatorCondition();
1107
96
  if (const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(S))
1108
8
    return FS->getElement();
1109
88
  return S;
1110
96
}
1111
1112
constexpr llvm::StringLiteral StrEnteringLoop = "Entering loop body";
1113
constexpr llvm::StringLiteral StrLoopBodyZero = "Loop body executed 0 times";
1114
constexpr llvm::StringLiteral StrLoopRangeEmpty =
1115
    "Loop body skipped when range is empty";
1116
constexpr llvm::StringLiteral StrLoopCollectionEmpty =
1117
    "Loop body skipped when collection is empty";
1118
1119
static std::unique_ptr<FilesToLineNumsMap>
1120
findExecutedLines(const SourceManager &SM, const ExplodedNode *N);
1121
1122
void PathDiagnosticBuilder::generatePathDiagnosticsForNode(
1123
233k
    PathDiagnosticConstruct &C, PathDiagnosticLocation &PrevLoc) const {
1124
233k
  ProgramPoint P = C.getCurrentNode()->getLocation();
1125
233k
  const SourceManager &SM = getSourceManager();
1126
1127
  // Have we encountered an entrance to a call?  It may be
1128
  // the case that we have not encountered a matching
1129
  // call exit before this point.  This means that the path
1130
  // terminated within the call itself.
1131
233k
  if (auto CE = P.getAs<CallEnter>()) {
1132
1133
7.25k
    if (C.shouldAddPathEdges()) {
1134
      // Add an edge to the start of the function.
1135
361
      const StackFrameContext *CalleeLC = CE->getCalleeContext();
1136
361
      const Decl *D = CalleeLC->getDecl();
1137
      // Add the edge only when the callee has body. We jump to the beginning
1138
      // of the *declaration*, however we expect it to be followed by the
1139
      // body. This isn't the case for autosynthesized property accessors in
1140
      // Objective-C. No need for a similar extra check for CallExit points
1141
      // because the exit edge comes from a statement (i.e. return),
1142
      // not from declaration.
1143
361
      if (D->hasBody())
1144
349
        addEdgeToPath(C.getActivePath(), PrevLoc,
1145
349
                      PathDiagnosticLocation::createBegin(D, SM));
1146
361
    }
1147
1148
    // Did we visit an entire call?
1149
7.25k
    bool VisitedEntireCall = C.PD->isWithinCall();
1150
7.25k
    C.PD->popActivePath();
1151
1152
7.25k
    PathDiagnosticCallPiece *Call;
1153
7.25k
    if (VisitedEntireCall) {
1154
7.06k
      Call = cast<PathDiagnosticCallPiece>(C.getActivePath().front().get());
1155
7.06k
    } else {
1156
      // The path terminated within a nested location context, create a new
1157
      // call piece to encapsulate the rest of the path pieces.
1158
184
      const Decl *Caller = CE->getLocationContext()->getDecl();
1159
184
      Call = PathDiagnosticCallPiece::construct(C.getActivePath(), Caller);
1160
184
      assert(C.getActivePath().size() == 1 &&
1161
184
             C.getActivePath().front().get() == Call);
1162
1163
      // Since we just transferred the path over to the call piece, reset the
1164
      // mapping of the active path to the current location context.
1165
184
      assert(C.isInLocCtxMap(&C.getActivePath()) &&
1166
184
             "When we ascend to a previously unvisited call, the active path's "
1167
184
             "address shouldn't change, but rather should be compacted into "
1168
184
             "a single CallEvent!");
1169
184
      C.updateLocCtxMap(&C.getActivePath(), C.getCurrLocationContext());
1170
1171
      // Record the location context mapping for the path within the call.
1172
184
      assert(!C.isInLocCtxMap(&Call->path) &&
1173
184
             "When we ascend to a previously unvisited call, this must be the "
1174
184
             "first time we encounter the caller context!");
1175
184
      C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
1176
184
    }
1177
7.25k
    Call->setCallee(*CE, SM);
1178
1179
    // Update the previous location in the active path.
1180
7.25k
    PrevLoc = Call->getLocation();
1181
1182
7.25k
    if (!C.CallStack.empty()) {
1183
7.06k
      assert(C.CallStack.back().first == Call);
1184
7.06k
      C.CallStack.pop_back();
1185
7.06k
    }
1186
7.25k
    return;
1187
7.25k
  }
1188
1189
226k
  assert(C.getCurrLocationContext() == C.getLocationContextForActivePath() &&
1190
226k
         "The current position in the bug path is out of sync with the "
1191
226k
         "location context associated with the active path!");
1192
1193
  // Have we encountered an exit from a function call?
1194
226k
  if (std::optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1195
1196
    // We are descending into a call (backwards).  Construct
1197
    // a new call piece to contain the path pieces for that call.
1198
7.06k
    auto Call = PathDiagnosticCallPiece::construct(*CE, SM);
1199
    // Record the mapping from call piece to LocationContext.
1200
7.06k
    assert(!C.isInLocCtxMap(&Call->path) &&
1201
7.06k
           "We just entered a call, this must've been the first time we "
1202
7.06k
           "encounter its context!");
1203
7.06k
    C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
1204
1205
7.06k
    if (C.shouldAddPathEdges()) {
1206
      // Add the edge to the return site.
1207
256
      addEdgeToPath(C.getActivePath(), PrevLoc, Call->callReturn);
1208
256
      PrevLoc.invalidate();
1209
256
    }
1210
1211
7.06k
    auto *P = Call.get();
1212
7.06k
    C.getActivePath().push_front(std::move(Call));
1213
1214
    // Make the contents of the call the active path for now.
1215
7.06k
    C.PD->pushActivePath(&P->path);
1216
7.06k
    C.CallStack.push_back(CallWithEntry(P, C.getCurrentNode()));
1217
7.06k
    return;
1218
7.06k
  }
1219
1220
219k
  if (auto PS = P.getAs<PostStmt>()) {
1221
129k
    if (!C.shouldAddPathEdges())
1222
105k
      return;
1223
1224
    // Add an edge.  If this is an ObjCForCollectionStmt do
1225
    // not add an edge here as it appears in the CFG both
1226
    // as a terminator and as a terminator condition.
1227
23.2k
    if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
1228
23.2k
      PathDiagnosticLocation L =
1229
23.2k
          PathDiagnosticLocation(PS->getStmt(), SM, C.getCurrLocationContext());
1230
23.2k
      addEdgeToPath(C.getActivePath(), PrevLoc, L);
1231
23.2k
    }
1232
1233
90.0k
  } else if (auto BE = P.getAs<BlockEdge>()) {
1234
1235
18.4k
    if (C.shouldAddControlNotes()) {
1236
16.7k
      generateMinimalDiagForBlockEdge(C, *BE);
1237
16.7k
    }
1238
1239
18.4k
    if (!C.shouldAddPathEdges()) {
1240
16.2k
      return;
1241
16.2k
    }
1242
1243
    // Are we jumping to the head of a loop?  Add a special diagnostic.
1244
2.14k
    if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1245
30
      PathDiagnosticLocation L(Loop, SM, C.getCurrLocationContext());
1246
30
      const Stmt *Body = nullptr;
1247
1248
30
      if (const auto *FS = dyn_cast<ForStmt>(Loop))
1249
13
        Body = FS->getBody();
1250
17
      else if (const auto *WS = dyn_cast<WhileStmt>(Loop))
1251
4
        Body = WS->getBody();
1252
13
      else if (const auto *OFS = dyn_cast<ObjCForCollectionStmt>(Loop)) {
1253
0
        Body = OFS->getBody();
1254
13
      } else if (const auto *FRS = dyn_cast<CXXForRangeStmt>(Loop)) {
1255
11
        Body = FRS->getBody();
1256
11
      }
1257
      // do-while statements are explicitly excluded here
1258
1259
30
      auto p = std::make_shared<PathDiagnosticEventPiece>(
1260
30
          L, "Looping back to the head of the loop");
1261
30
      p->setPrunable(true);
1262
1263
30
      addEdgeToPath(C.getActivePath(), PrevLoc, p->getLocation());
1264
      // We might've added a very similar control node already
1265
30
      if (!C.shouldAddControlNotes()) {
1266
27
        C.getActivePath().push_front(std::move(p));
1267
27
      }
1268
1269
30
      if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
1270
25
        addEdgeToPath(C.getActivePath(), PrevLoc,
1271
25
                      PathDiagnosticLocation::createEndBrace(CS, SM));
1272
25
      }
1273
30
    }
1274
1275
2.14k
    const CFGBlock *BSrc = BE->getSrc();
1276
2.14k
    const ParentMap &PM = C.getParentMap();
1277
1278
2.14k
    if (const Stmt *Term = BSrc->getTerminatorStmt()) {
1279
      // Are we jumping past the loop body without ever executing the
1280
      // loop (because the condition was false)?
1281
497
      if (isLoop(Term)) {
1282
96
        const Stmt *TermCond = getTerminatorCondition(BSrc);
1283
96
        bool IsInLoopBody = isInLoopBody(
1284
96
            PM, getStmtBeforeCond(PM, TermCond, C.getCurrentNode()), Term);
1285
1286
96
        StringRef str;
1287
1288
96
        if (isJumpToFalseBranch(&*BE)) {
1289
45
          if (!IsInLoopBody) {
1290
34
            if (isa<ObjCForCollectionStmt>(Term)) {
1291
6
              str = StrLoopCollectionEmpty;
1292
28
            } else if (isa<CXXForRangeStmt>(Term)) {
1293
6
              str = StrLoopRangeEmpty;
1294
22
            } else {
1295
22
              str = StrLoopBodyZero;
1296
22
            }
1297
34
          }
1298
51
        } else {
1299
51
          str = StrEnteringLoop;
1300
51
        }
1301
1302
96
        if (!str.empty()) {
1303
85
          PathDiagnosticLocation L(TermCond ? 
TermCond80
:
Term5
, SM,
1304
85
                                   C.getCurrLocationContext());
1305
85
          auto PE = std::make_shared<PathDiagnosticEventPiece>(L, str);
1306
85
          PE->setPrunable(true);
1307
85
          addEdgeToPath(C.getActivePath(), PrevLoc, PE->getLocation());
1308
1309
          // We might've added a very similar control node already
1310
85
          if (!C.shouldAddControlNotes()) {
1311
81
            C.getActivePath().push_front(std::move(PE));
1312
81
          }
1313
85
        }
1314
401
      } else if (isa<BreakStmt, ContinueStmt, GotoStmt>(Term)) {
1315
9
        PathDiagnosticLocation L(Term, SM, C.getCurrLocationContext());
1316
9
        addEdgeToPath(C.getActivePath(), PrevLoc, L);
1317
9
      }
1318
497
    }
1319
2.14k
  }
1320
219k
}
1321
1322
static std::unique_ptr<PathDiagnostic>
1323
1.03k
generateDiagnosticForBasicReport(const BasicBugReport *R) {
1324
1.03k
  const BugType &BT = R->getBugType();
1325
1.03k
  return std::make_unique<PathDiagnostic>(
1326
1.03k
      BT.getCheckerName(), R->getDeclWithIssue(), BT.getDescription(),
1327
1.03k
      R->getDescription(), R->getShortDescription(/*UseFallback=*/false),
1328
1.03k
      BT.getCategory(), R->getUniqueingLocation(), R->getUniqueingDecl(),
1329
1.03k
      std::make_unique<FilesToLineNumsMap>());
1330
1.03k
}
1331
1332
static std::unique_ptr<PathDiagnostic>
1333
generateEmptyDiagnosticForReport(const PathSensitiveBugReport *R,
1334
40.8k
                                 const SourceManager &SM) {
1335
40.8k
  const BugType &BT = R->getBugType();
1336
40.8k
  return std::make_unique<PathDiagnostic>(
1337
40.8k
      BT.getCheckerName(), R->getDeclWithIssue(), BT.getDescription(),
1338
40.8k
      R->getDescription(), R->getShortDescription(/*UseFallback=*/false),
1339
40.8k
      BT.getCategory(), R->getUniqueingLocation(), R->getUniqueingDecl(),
1340
40.8k
      findExecutedLines(SM, R->getErrorNode()));
1341
40.8k
}
1342
1343
64.3k
static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
1344
64.3k
  if (!S)
1345
6.10k
    return nullptr;
1346
1347
59.1k
  
while (58.2k
true) {
1348
59.1k
    S = PM.getParentIgnoreParens(S);
1349
1350
59.1k
    if (!S)
1351
46
      break;
1352
1353
59.0k
    if (isa<FullExpr, CXXBindTemporaryExpr, SubstNonTypeTemplateParmExpr>(S))
1354
831
      continue;
1355
1356
58.2k
    break;
1357
59.0k
  }
1358
1359
58.2k
  return S;
1360
64.3k
}
1361
1362
15.2k
static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
1363
15.2k
  switch (S->getStmtClass()) {
1364
1.94k
    case Stmt::BinaryOperatorClass: {
1365
1.94k
      const auto *BO = cast<BinaryOperator>(S);
1366
1.94k
      if (!BO->isLogicalOp())
1367
1.89k
        return false;
1368
48
      return BO->getLHS() == Cond || 
BO->getRHS() == Cond26
;
1369
1.94k
    }
1370
410
    case Stmt::IfStmtClass:
1371
410
      return cast<IfStmt>(S)->getCond() == Cond;
1372
86
    case Stmt::ForStmtClass:
1373
86
      return cast<ForStmt>(S)->getCond() == Cond;
1374
35
    case Stmt::WhileStmtClass:
1375
35
      return cast<WhileStmt>(S)->getCond() == Cond;
1376
27
    case Stmt::DoStmtClass:
1377
27
      return cast<DoStmt>(S)->getCond() == Cond;
1378
0
    case Stmt::ChooseExprClass:
1379
0
      return cast<ChooseExpr>(S)->getCond() == Cond;
1380
0
    case Stmt::IndirectGotoStmtClass:
1381
0
      return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
1382
30
    case Stmt::SwitchStmtClass:
1383
30
      return cast<SwitchStmt>(S)->getCond() == Cond;
1384
3
    case Stmt::BinaryConditionalOperatorClass:
1385
3
      return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
1386
19
    case Stmt::ConditionalOperatorClass: {
1387
19
      const auto *CO = cast<ConditionalOperator>(S);
1388
19
      return CO->getCond() == Cond ||
1389
19
             
CO->getLHS() == Cond17
||
1390
19
             
CO->getRHS() == Cond13
;
1391
1.94k
    }
1392
31
    case Stmt::ObjCForCollectionStmtClass:
1393
31
      return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
1394
47
    case Stmt::CXXForRangeStmtClass: {
1395
47
      const auto *FRS = cast<CXXForRangeStmt>(S);
1396
47
      return FRS->getCond() == Cond || 
FRS->getRangeInit() == Cond29
;
1397
1.94k
    }
1398
12.6k
    default:
1399
12.6k
      return false;
1400
15.2k
  }
1401
15.2k
}
1402
1403
13.0k
static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
1404
13.0k
  if (const auto *FS = dyn_cast<ForStmt>(FL))
1405
46
    return FS->getInc() == S || 
FS->getInit() == S37
;
1406
13.0k
  if (const auto *FRS = dyn_cast<CXXForRangeStmt>(FL))
1407
80
    return FRS->getInc() == S || 
FRS->getRangeStmt() == S69
||
1408
80
           
FRS->getLoopVarStmt()54
||
FRS->getRangeInit() == S0
;
1409
12.9k
  return false;
1410
13.0k
}
1411
1412
using OptimizedCallsSet = llvm::DenseSet<const PathDiagnosticCallPiece *>;
1413
1414
/// Adds synthetic edges from top-level statements to their subexpressions.
1415
///
1416
/// This avoids a "swoosh" effect, where an edge from a top-level statement A
1417
/// points to a sub-expression B.1 that's not at the start of B. In these cases,
1418
/// we'd like to see an edge from A to B, then another one from B to B.1.
1419
931
static void addContextEdges(PathPieces &pieces, const LocationContext *LC) {
1420
931
  const ParentMap &PM = LC->getParentMap();
1421
931
  PathPieces::iterator Prev = pieces.end();
1422
7.26k
  for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
1423
6.33k
       Prev = I, ++I) {
1424
6.33k
    auto *Piece = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1425
1426
6.33k
    if (!Piece)
1427
2.15k
      continue;
1428
1429
4.18k
    PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
1430
4.18k
    SmallVector<PathDiagnosticLocation, 4> SrcContexts;
1431
1432
4.18k
    PathDiagnosticLocation NextSrcContext = SrcLoc;
1433
4.18k
    const Stmt *InnerStmt = nullptr;
1434
8.37k
    while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
1435
4.18k
      SrcContexts.push_back(NextSrcContext);
1436
4.18k
      InnerStmt = NextSrcContext.asStmt();
1437
4.18k
      NextSrcContext = getEnclosingStmtLocation(InnerStmt, LC,
1438
4.18k
                                                /*allowNested=*/true);
1439
4.18k
    }
1440
1441
    // Repeatedly split the edge as necessary.
1442
    // This is important for nested logical expressions (||, &&, ?:) where we
1443
    // want to show all the levels of context.
1444
5.01k
    while (true) {
1445
5.01k
      const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
1446
1447
      // We are looking at an edge. Is the destination within a larger
1448
      // expression?
1449
5.01k
      PathDiagnosticLocation DstContext =
1450
5.01k
          getEnclosingStmtLocation(Dst, LC, /*allowNested=*/true);
1451
5.01k
      if (!DstContext.isValid() || 
DstContext.asStmt() == Dst4.64k
)
1452
3.11k
        break;
1453
1454
      // If the source is in the same context, we're already good.
1455
1.90k
      if (llvm::is_contained(SrcContexts, DstContext))
1456
982
        break;
1457
1458
      // Update the subexpression node to point to the context edge.
1459
918
      Piece->setStartLocation(DstContext);
1460
1461
      // Try to extend the previous edge if it's at the same level as the source
1462
      // context.
1463
918
      if (Prev != E) {
1464
537
        auto *PrevPiece = dyn_cast<PathDiagnosticControlFlowPiece>(Prev->get());
1465
1466
537
        if (PrevPiece) {
1467
326
          if (const Stmt *PrevSrc =
1468
326
                  PrevPiece->getStartLocation().getStmtOrNull()) {
1469
240
            const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
1470
240
            if (PrevSrcParent ==
1471
240
                getStmtParent(DstContext.getStmtOrNull(), PM)) {
1472
88
              PrevPiece->setEndLocation(DstContext);
1473
88
              break;
1474
88
            }
1475
240
          }
1476
326
        }
1477
537
      }
1478
1479
      // Otherwise, split the current edge into a context edge and a
1480
      // subexpression edge. Note that the context statement may itself have
1481
      // context.
1482
830
      auto P =
1483
830
          std::make_shared<PathDiagnosticControlFlowPiece>(SrcLoc, DstContext);
1484
830
      Piece = P.get();
1485
830
      I = pieces.insert(I, std::move(P));
1486
830
    }
1487
4.18k
  }
1488
931
}
1489
1490
/// Move edges from a branch condition to a branch target
1491
///        when the condition is simple.
1492
///
1493
/// This restructures some of the work of addContextEdges.  That function
1494
/// creates edges this may destroy, but they work together to create a more
1495
/// aesthetically set of edges around branches.  After the call to
1496
/// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
1497
/// the branch to the branch condition, and (3) an edge from the branch
1498
/// condition to the branch target.  We keep (1), but may wish to remove (2)
1499
/// and move the source of (3) to the branch if the branch condition is simple.
1500
931
static void simplifySimpleBranches(PathPieces &pieces) {
1501
6.51k
  for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; 
++I5.58k
) {
1502
5.60k
    const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1503
1504
5.60k
    if (!PieceI)
1505
2.09k
      continue;
1506
1507
3.51k
    const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1508
3.51k
    const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1509
1510
3.51k
    if (!s1Start || 
!s1End2.53k
)
1511
1.34k
      continue;
1512
1513
2.17k
    PathPieces::iterator NextI = I; ++NextI;
1514
2.17k
    if (NextI == E)
1515
23
      break;
1516
1517
2.14k
    PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
1518
1519
2.21k
    while (true) {
1520
2.21k
      if (NextI == E)
1521
0
        break;
1522
1523
2.21k
      const auto *EV = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1524
2.21k
      if (EV) {
1525
1.06k
        StringRef S = EV->getString();
1526
1.06k
        if (S == StrEnteringLoop || 
S == StrLoopBodyZero1.02k
||
1527
1.06k
            
S == StrLoopCollectionEmpty1.01k
||
S == StrLoopRangeEmpty1.01k
) {
1528
62
          ++NextI;
1529
62
          continue;
1530
62
        }
1531
1.00k
        break;
1532
1.06k
      }
1533
1534
1.14k
      PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1535
1.14k
      break;
1536
2.21k
    }
1537
1538
2.14k
    if (!PieceNextI)
1539
1.12k
      continue;
1540
1541
1.02k
    const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1542
1.02k
    const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1543
1544
1.02k
    if (!s2Start || 
!s2End984
||
s1End != s2Start787
)
1545
236
      continue;
1546
1547
    // We only perform this transformation for specific branch kinds.
1548
    // We don't want to do this for do..while, for example.
1549
787
    if (!isa<ForStmt, WhileStmt, IfStmt, ObjCForCollectionStmt,
1550
787
             CXXForRangeStmt>(s1Start))
1551
615
      continue;
1552
1553
    // Is s1End the branch condition?
1554
172
    if (!isConditionForTerminator(s1Start, s1End))
1555
57
      continue;
1556
1557
    // Perform the hoisting by eliminating (2) and changing the start
1558
    // location of (3).
1559
115
    PieceNextI->setStartLocation(PieceI->getStartLocation());
1560
115
    I = pieces.erase(I);
1561
115
  }
1562
931
}
1563
1564
/// Returns the number of bytes in the given (character-based) SourceRange.
1565
///
1566
/// If the locations in the range are not on the same line, returns
1567
/// std::nullopt.
1568
///
1569
/// Note that this does not do a precise user-visible character or column count.
1570
static std::optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
1571
3.13k
                                                   SourceRange Range) {
1572
3.13k
  SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
1573
3.13k
                             SM.getExpansionRange(Range.getEnd()).getEnd());
1574
1575
3.13k
  FileID FID = SM.getFileID(ExpansionRange.getBegin());
1576
3.13k
  if (FID != SM.getFileID(ExpansionRange.getEnd()))
1577
0
    return std::nullopt;
1578
1579
3.13k
  std::optional<MemoryBufferRef> Buffer = SM.getBufferOrNone(FID);
1580
3.13k
  if (!Buffer)
1581
0
    return std::nullopt;
1582
1583
3.13k
  unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
1584
3.13k
  unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
1585
3.13k
  StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
1586
1587
  // We're searching the raw bytes of the buffer here, which might include
1588
  // escaped newlines and such. That's okay; we're trying to decide whether the
1589
  // SourceRange is covering a large or small amount of space in the user's
1590
  // editor.
1591
3.13k
  if (Snippet.find_first_of("\r\n") != StringRef::npos)
1592
1.28k
    return std::nullopt;
1593
1594
  // This isn't Unicode-aware, but it doesn't need to be.
1595
1.84k
  return Snippet.size();
1596
3.13k
}
1597
1598
/// \sa getLengthOnSingleLine(SourceManager, SourceRange)
1599
static std::optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
1600
625
                                                   const Stmt *S) {
1601
625
  return getLengthOnSingleLine(SM, S->getSourceRange());
1602
625
}
1603
1604
/// Eliminate two-edge cycles created by addContextEdges().
1605
///
1606
/// Once all the context edges are in place, there are plenty of cases where
1607
/// there's a single edge from a top-level statement to a subexpression,
1608
/// followed by a single path note, and then a reverse edge to get back out to
1609
/// the top level. If the statement is simple enough, the subexpression edges
1610
/// just add noise and make it harder to understand what's going on.
1611
///
1612
/// This function only removes edges in pairs, because removing only one edge
1613
/// might leave other edges dangling.
1614
///
1615
/// This will not remove edges in more complicated situations:
1616
/// - if there is more than one "hop" leading to or from a subexpression.
1617
/// - if there is an inlined call between the edges instead of a single event.
1618
/// - if the whole statement is large enough that having subexpression arrows
1619
///   might be helpful.
1620
931
static void removeContextCycles(PathPieces &Path, const SourceManager &SM) {
1621
5.13k
  for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
1622
    // Pattern match the current piece and its successor.
1623
4.97k
    const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1624
1625
4.97k
    if (!PieceI) {
1626
1.09k
      ++I;
1627
1.09k
      continue;
1628
1.09k
    }
1629
1630
3.87k
    const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1631
3.87k
    const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1632
1633
3.87k
    PathPieces::iterator NextI = I; ++NextI;
1634
3.87k
    if (NextI == E)
1635
26
      break;
1636
1637
3.85k
    const auto *PieceNextI =
1638
3.85k
        dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1639
1640
3.85k
    if (!PieceNextI) {
1641
1.99k
      if (isa<PathDiagnosticEventPiece>(NextI->get())) {
1642
1.79k
        ++NextI;
1643
1.79k
        if (NextI == E)
1644
750
          break;
1645
1.04k
        PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1646
1.04k
      }
1647
1648
1.24k
      if (!PieceNextI) {
1649
275
        ++I;
1650
275
        continue;
1651
275
      }
1652
1.24k
    }
1653
1654
2.82k
    const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1655
2.82k
    const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1656
1657
2.82k
    if (s1Start && 
s2Start1.93k
&&
s1Start == s2End1.86k
&&
s2Start == s1End320
) {
1658
320
      const size_t MAX_SHORT_LINE_LENGTH = 80;
1659
320
      std::optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
1660
320
      if (s1Length && 
*s1Length <= MAX_SHORT_LINE_LENGTH306
) {
1661
305
        std::optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
1662
305
        if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
1663
305
          Path.erase(I);
1664
305
          I = Path.erase(NextI);
1665
305
          continue;
1666
305
        }
1667
305
      }
1668
320
    }
1669
1670
2.52k
    ++I;
1671
2.52k
  }
1672
931
}
1673
1674
/// Return true if X is contained by Y.
1675
3.18k
static bool lexicalContains(const ParentMap &PM, const Stmt *X, const Stmt *Y) {
1676
11.1k
  while (X) {
1677
8.45k
    if (X == Y)
1678
530
      return true;
1679
7.92k
    X = PM.getParent(X);
1680
7.92k
  }
1681
2.65k
  return false;
1682
3.18k
}
1683
1684
// Remove short edges on the same line less than 3 columns in difference.
1685
static void removePunyEdges(PathPieces &path, const SourceManager &SM,
1686
931
                            const ParentMap &PM) {
1687
931
  bool erased = false;
1688
1689
6.54k
  for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
1690
5.60k
       erased ? 
I102
:
++I5.50k
) {
1691
5.60k
    erased = false;
1692
1693
5.60k
    const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1694
1695
5.60k
    if (!PieceI)
1696
2.15k
      continue;
1697
1698
3.45k
    const Stmt *start = PieceI->getStartLocation().getStmtOrNull();
1699
3.45k
    const Stmt *end   = PieceI->getEndLocation().getStmtOrNull();
1700
1701
3.45k
    if (!start || 
!end2.47k
)
1702
1.34k
      continue;
1703
1704
2.11k
    const Stmt *endParent = PM.getParent(end);
1705
2.11k
    if (!endParent)
1706
2
      continue;
1707
1708
2.11k
    if (isConditionForTerminator(end, endParent))
1709
0
      continue;
1710
1711
2.11k
    SourceLocation FirstLoc = start->getBeginLoc();
1712
2.11k
    SourceLocation SecondLoc = end->getBeginLoc();
1713
1714
2.11k
    if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
1715
97
      continue;
1716
2.01k
    if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
1717
136
      std::swap(SecondLoc, FirstLoc);
1718
1719
2.01k
    SourceRange EdgeRange(FirstLoc, SecondLoc);
1720
2.01k
    std::optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
1721
1722
    // If the statements are on different lines, continue.
1723
2.01k
    if (!ByteWidth)
1724
1.27k
      continue;
1725
1726
746
    const size_t MAX_PUNY_EDGE_LENGTH = 2;
1727
746
    if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
1728
      // FIXME: There are enough /bytes/ between the endpoints of the edge, but
1729
      // there might not be enough /columns/. A proper user-visible column count
1730
      // is probably too expensive, though.
1731
102
      I = path.erase(I);
1732
102
      erased = true;
1733
102
      continue;
1734
102
    }
1735
746
  }
1736
931
}
1737
1738
931
static void removeIdenticalEvents(PathPieces &path) {
1739
5.64k
  for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; 
++I4.71k
) {
1740
5.50k
    const auto *PieceI = dyn_cast<PathDiagnosticEventPiece>(I->get());
1741
1742
5.50k
    if (!PieceI)
1743
3.59k
      continue;
1744
1745
1.90k
    PathPieces::iterator NextI = I; ++NextI;
1746
1.90k
    if (NextI == E)
1747
792
      return;
1748
1749
1.11k
    const auto *PieceNextI = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1750
1751
1.11k
    if (!PieceNextI)
1752
957
      continue;
1753
1754
    // Erase the second piece if it has the same exact message text.
1755
160
    if (PieceI->getString() == PieceNextI->getString()) {
1756
1
      path.erase(NextI);
1757
1
    }
1758
160
  }
1759
931
}
1760
1761
static bool optimizeEdges(const PathDiagnosticConstruct &C, PathPieces &path,
1762
1.99k
                          OptimizedCallsSet &OCS) {
1763
1.99k
  bool hasChanges = false;
1764
1.99k
  const LocationContext *LC = C.getLocationContextFor(&path);
1765
1.99k
  assert(LC);
1766
1.99k
  const ParentMap &PM = LC->getParentMap();
1767
1.99k
  const SourceManager &SM = C.getSourceManager();
1768
1769
24.8k
  for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
1770
    // Optimize subpaths.
1771
22.9k
    if (auto *CallI = dyn_cast<PathDiagnosticCallPiece>(I->get())) {
1772
      // Record the fact that a call has been optimized so we only do the
1773
      // effort once.
1774
411
      if (!OCS.count(CallI)) {
1775
378
        while (optimizeEdges(C, CallI->path, OCS)) {
1776
179
        }
1777
199
        OCS.insert(CallI);
1778
199
      }
1779
411
      ++I;
1780
411
      continue;
1781
411
    }
1782
1783
    // Pattern match the current piece and its successor.
1784
22.5k
    auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1785
1786
22.5k
    if (!PieceI) {
1787
4.25k
      ++I;
1788
4.25k
      continue;
1789
4.25k
    }
1790
1791
18.2k
    const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1792
18.2k
    const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1793
18.2k
    const Stmt *level1 = getStmtParent(s1Start, PM);
1794
18.2k
    const Stmt *level2 = getStmtParent(s1End, PM);
1795
1796
18.2k
    PathPieces::iterator NextI = I; ++NextI;
1797
18.2k
    if (NextI == E)
1798
78
      break;
1799
1800
18.1k
    const auto *PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1801
1802
18.1k
    if (!PieceNextI) {
1803
4.47k
      ++I;
1804
4.47k
      continue;
1805
4.47k
    }
1806
1807
13.7k
    const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1808
13.7k
    const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1809
13.7k
    const Stmt *level3 = getStmtParent(s2Start, PM);
1810
13.7k
    const Stmt *level4 = getStmtParent(s2End, PM);
1811
1812
    // Rule I.
1813
    //
1814
    // If we have two consecutive control edges whose end/begin locations
1815
    // are at the same level (e.g. statements or top-level expressions within
1816
    // a compound statement, or siblings share a single ancestor expression),
1817
    // then merge them if they have no interesting intermediate event.
1818
    //
1819
    // For example:
1820
    //
1821
    // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
1822
    // parent is '1'.  Here 'x.y.z' represents the hierarchy of statements.
1823
    //
1824
    // NOTE: this will be limited later in cases where we add barriers
1825
    // to prevent this optimization.
1826
13.7k
    if (level1 && 
level1 == level210.3k
&&
level1 == level31.48k
&&
level1 == level41.48k
) {
1827
384
      PieceI->setEndLocation(PieceNextI->getEndLocation());
1828
384
      path.erase(NextI);
1829
384
      hasChanges = true;
1830
384
      continue;
1831
384
    }
1832
1833
    // Rule II.
1834
    //
1835
    // Eliminate edges between subexpressions and parent expressions
1836
    // when the subexpression is consumed.
1837
    //
1838
    // NOTE: this will be limited later in cases where we add barriers
1839
    // to prevent this optimization.
1840
13.3k
    if (s1End && 
s1End == s2Start13.2k
&&
level213.1k
) {
1841
13.0k
      bool removeEdge = false;
1842
      // Remove edges into the increment or initialization of a
1843
      // loop that have no interleaving event.  This means that
1844
      // they aren't interesting.
1845
13.0k
      if (isIncrementOrInitInForLoop(s1End, level2))
1846
114
        removeEdge = true;
1847
      // Next only consider edges that are not anchored on
1848
      // the condition of a terminator.  This are intermediate edges
1849
      // that we might want to trim.
1850
12.9k
      else if (!isConditionForTerminator(level2, s1End)) {
1851
        // Trim edges on expressions that are consumed by
1852
        // the parent expression.
1853
12.7k
        if (isa<Expr>(s1End) && 
PM.isConsumedExpr(cast<Expr>(s1End))11.2k
) {
1854
9.87k
          removeEdge = true;
1855
9.87k
        }
1856
        // Trim edges where a lexical containment doesn't exist.
1857
        // For example:
1858
        //
1859
        //  X -> Y -> Z
1860
        //
1861
        // If 'Z' lexically contains Y (it is an ancestor) and
1862
        // 'X' does not lexically contain Y (it is a descendant OR
1863
        // it has no lexical relationship at all) then trim.
1864
        //
1865
        // This can eliminate edges where we dive into a subexpression
1866
        // and then pop back out, etc.
1867
2.88k
        else if (s1Start && 
s2End2.10k
&&
1868
2.88k
                 
lexicalContains(PM, s2Start, s2End)1.59k
&&
1869
2.88k
                 
!lexicalContains(PM, s1End, s1Start)35
) {
1870
35
          removeEdge = true;
1871
35
        }
1872
        // Trim edges from a subexpression back to the top level if the
1873
        // subexpression is on a different line.
1874
        //
1875
        // A.1 -> A -> B
1876
        // becomes
1877
        // A.1 -> B
1878
        //
1879
        // These edges just look ugly and don't usually add anything.
1880
2.85k
        else if (s1Start && 
s2End2.06k
&&
1881
2.85k
                 
lexicalContains(PM, s1Start, s1End)1.55k
) {
1882
495
          SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
1883
495
                                PieceI->getStartLocation().asLocation());
1884
495
          if (!getLengthOnSingleLine(SM, EdgeRange))
1885
3
            removeEdge = true;
1886
495
        }
1887
12.7k
      }
1888
1889
13.0k
      if (removeEdge) {
1890
10.0k
        PieceI->setEndLocation(PieceNextI->getEndLocation());
1891
10.0k
        path.erase(NextI);
1892
10.0k
        hasChanges = true;
1893
10.0k
        continue;
1894
10.0k
      }
1895
13.0k
    }
1896
1897
    // Optimize edges for ObjC fast-enumeration loops.
1898
    //
1899
    // (X -> collection) -> (collection -> element)
1900
    //
1901
    // becomes:
1902
    //
1903
    // (X -> element)
1904
3.28k
    if (s1End == s2Start) {
1905
3.13k
      const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(level3);
1906
3.13k
      if (FS && 
FS->getCollection()->IgnoreParens() == s2Start2
&&
1907
3.13k
          
s2End == FS->getElement()0
) {
1908
0
        PieceI->setEndLocation(PieceNextI->getEndLocation());
1909
0
        path.erase(NextI);
1910
0
        hasChanges = true;
1911
0
        continue;
1912
0
      }
1913
3.13k
    }
1914
1915
    // No changes at this index?  Move to the next one.
1916
3.28k
    ++I;
1917
3.28k
  }
1918
1919
1.99k
  if (!hasChanges) {
1920
    // Adjust edges into subexpressions to make them more uniform
1921
    // and aesthetically pleasing.
1922
931
    addContextEdges(path, LC);
1923
    // Remove "cyclical" edges that include one or more context edges.
1924
931
    removeContextCycles(path, SM);
1925
    // Hoist edges originating from branch conditions to branches
1926
    // for simple branches.
1927
931
    simplifySimpleBranches(path);
1928
    // Remove any puny edges left over after primary optimization pass.
1929
931
    removePunyEdges(path, SM, PM);
1930
    // Remove identical events.
1931
931
    removeIdenticalEvents(path);
1932
931
  }
1933
1934
1.99k
  return hasChanges;
1935
1.99k
}
1936
1937
/// Drop the very first edge in a path, which should be a function entry edge.
1938
///
1939
/// If the first edge is not a function entry edge (say, because the first
1940
/// statement had an invalid source location), this function does nothing.
1941
// FIXME: We should just generate invalid edges anyway and have the optimizer
1942
// deal with them.
1943
static void dropFunctionEntryEdge(const PathDiagnosticConstruct &C,
1944
732
                                  PathPieces &Path) {
1945
732
  const auto *FirstEdge =
1946
732
      dyn_cast<PathDiagnosticControlFlowPiece>(Path.front().get());
1947
732
  if (!FirstEdge)
1948
1
    return;
1949
1950
731
  const Decl *D = C.getLocationContextFor(&Path)->getDecl();
1951
731
  PathDiagnosticLocation EntryLoc =
1952
731
      PathDiagnosticLocation::createBegin(D, C.getSourceManager());
1953
731
  if (FirstEdge->getStartLocation() != EntryLoc)
1954
0
    return;
1955
1956
731
  Path.pop_front();
1957
731
}
1958
1959
/// Populate executes lines with lines containing at least one diagnostics.
1960
22.6k
static void updateExecutedLinesWithDiagnosticPieces(PathDiagnostic &PD) {
1961
1962
22.6k
  PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
1963
22.6k
  FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
1964
1965
30.9k
  for (const auto &P : path) {
1966
30.9k
    FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
1967
30.9k
    FileID FID = Loc.getFileID();
1968
30.9k
    unsigned LineNo = Loc.getLineNumber();
1969
30.9k
    assert(FID.isValid());
1970
30.9k
    ExecutedLines[FID].insert(LineNo);
1971
30.9k
  }
1972
22.6k
}
1973
1974
PathDiagnosticConstruct::PathDiagnosticConstruct(
1975
    const PathDiagnosticConsumer *PDC, const ExplodedNode *ErrorNode,
1976
    const PathSensitiveBugReport *R)
1977
21.5k
    : Consumer(PDC), CurrentNode(ErrorNode),
1978
21.5k
      SM(CurrentNode->getCodeDecl().getASTContext().getSourceManager()),
1979
21.5k
      PD(generateEmptyDiagnosticForReport(R, getSourceManager())) {
1980
21.5k
  LCM[&PD->getActivePath()] = ErrorNode->getLocationContext();
1981
21.5k
}
1982
1983
PathDiagnosticBuilder::PathDiagnosticBuilder(
1984
    BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
1985
    PathSensitiveBugReport *r, const ExplodedNode *ErrorNode,
1986
    std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics)
1987
20.8k
    : BugReporterContext(BRC), BugPath(std::move(BugPath)), R(r),
1988
20.8k
      ErrorNode(ErrorNode),
1989
20.8k
      VisitorsDiagnostics(std::move(VisitorsDiagnostics)) {}
1990
1991
std::unique_ptr<PathDiagnostic>
1992
21.5k
PathDiagnosticBuilder::generate(const PathDiagnosticConsumer *PDC) const {
1993
21.5k
  PathDiagnosticConstruct Construct(PDC, ErrorNode, R);
1994
1995
21.5k
  const SourceManager &SM = getSourceManager();
1996
21.5k
  const AnalyzerOptions &Opts = getAnalyzerOptions();
1997
1998
21.5k
  if (!PDC->shouldGenerateDiagnostics())
1999
19.2k
    return generateEmptyDiagnosticForReport(R, getSourceManager());
2000
2001
  // Construct the final (warning) event for the bug report.
2002
2.29k
  auto EndNotes = VisitorsDiagnostics->find(ErrorNode);
2003
2.29k
  PathDiagnosticPieceRef LastPiece;
2004
2.29k
  if (EndNotes != VisitorsDiagnostics->end()) {
2005
433
    assert(!EndNotes->second.empty());
2006
433
    LastPiece = EndNotes->second[0];
2007
1.85k
  } else {
2008
1.85k
    LastPiece = BugReporterVisitor::getDefaultEndPath(*this, ErrorNode,
2009
1.85k
                                                      *getBugReport());
2010
1.85k
  }
2011
2.29k
  Construct.PD->setEndOfPath(LastPiece);
2012
2013
2.29k
  PathDiagnosticLocation PrevLoc = Construct.PD->getLocation();
2014
  // From the error node to the root, ascend the bug path and construct the bug
2015
  // report.
2016
235k
  while (Construct.ascendToPrevNode()) {
2017
233k
    generatePathDiagnosticsForNode(Construct, PrevLoc);
2018
2019
233k
    auto VisitorNotes = VisitorsDiagnostics->find(Construct.getCurrentNode());
2020
233k
    if (VisitorNotes == VisitorsDiagnostics->end())
2021
229k
      continue;
2022
2023
    // This is a workaround due to inability to put shared PathDiagnosticPiece
2024
    // into a FoldingSet.
2025
3.65k
    std::set<llvm::FoldingSetNodeID> DeduplicationSet;
2026
2027
    // Add pieces from custom visitors.
2028
3.83k
    for (const PathDiagnosticPieceRef &Note : VisitorNotes->second) {
2029
3.83k
      llvm::FoldingSetNodeID ID;
2030
3.83k
      Note->Profile(ID);
2031
3.83k
      if (!DeduplicationSet.insert(ID).second)
2032
32
        continue;
2033
2034
3.80k
      if (PDC->shouldAddPathEdges())
2035
1.12k
        addEdgeToPath(Construct.getActivePath(), PrevLoc, Note->getLocation());
2036
3.80k
      updateStackPiecesWithMessage(Note, Construct.CallStack);
2037
3.80k
      Construct.getActivePath().push_front(Note);
2038
3.80k
    }
2039
3.65k
  }
2040
2041
2.29k
  if (PDC->shouldAddPathEdges()) {
2042
    // Add an edge to the start of the function.
2043
    // We'll prune it out later, but it helps make diagnostics more uniform.
2044
732
    const StackFrameContext *CalleeLC =
2045
732
        Construct.getLocationContextForActivePath()->getStackFrame();
2046
732
    const Decl *D = CalleeLC->getDecl();
2047
732
    addEdgeToPath(Construct.getActivePath(), PrevLoc,
2048
732
                  PathDiagnosticLocation::createBegin(D, SM));
2049
732
  }
2050
2051
2052
  // Finally, prune the diagnostic path of uninteresting stuff.
2053
2.29k
  if (!Construct.PD->path.empty()) {
2054
2.29k
    if (R->shouldPrunePath() && 
Opts.ShouldPrunePaths2.28k
) {
2055
2.28k
      bool stillHasNotes =
2056
2.28k
          removeUnneededCalls(Construct, Construct.getMutablePieces(), R);
2057
2.28k
      assert(stillHasNotes);
2058
2.28k
      (void)stillHasNotes;
2059
2.28k
    }
2060
2061
    // Remove pop-up notes if needed.
2062
2.29k
    if (!Opts.ShouldAddPopUpNotes)
2063
4
      removePopUpNotes(Construct.getMutablePieces());
2064
2065
    // Redirect all call pieces to have valid locations.
2066
2.29k
    adjustCallLocations(Construct.getMutablePieces());
2067
2.29k
    removePiecesWithInvalidLocations(Construct.getMutablePieces());
2068
2069
2.29k
    if (PDC->shouldAddPathEdges()) {
2070
2071
      // Reduce the number of edges from a very conservative set
2072
      // to an aesthetically pleasing subset that conveys the
2073
      // necessary information.
2074
732
      OptimizedCallsSet OCS;
2075
1.61k
      while (optimizeEdges(Construct, Construct.getMutablePieces(), OCS)) {
2076
880
      }
2077
2078
      // Drop the very first function-entry edge. It's not really necessary
2079
      // for top-level functions.
2080
732
      dropFunctionEntryEdge(Construct, Construct.getMutablePieces());
2081
732
    }
2082
2083
    // Remove messages that are basically the same, and edges that may not
2084
    // make sense.
2085
    // We have to do this after edge optimization in the Extensive mode.
2086
2.29k
    removeRedundantMsgs(Construct.getMutablePieces());
2087
2.29k
    removeEdgesToDefaultInitializers(Construct.getMutablePieces());
2088
2.29k
  }
2089
2090
2.29k
  if (Opts.ShouldDisplayMacroExpansions)
2091
42
    CompactMacroExpandedPieces(Construct.getMutablePieces(), SM);
2092
2093
2.29k
  return std::move(Construct.PD);
2094
2.29k
}
2095
2096
//===----------------------------------------------------------------------===//
2097
// Methods for BugType and subclasses.
2098
//===----------------------------------------------------------------------===//
2099
2100
0
void BugType::anchor() {}
2101
2102
//===----------------------------------------------------------------------===//
2103
// Methods for BugReport and subclasses.
2104
//===----------------------------------------------------------------------===//
2105
2106
LLVM_ATTRIBUTE_USED static bool
2107
23.0k
isDependency(const CheckerRegistryData &Registry, StringRef CheckerName) {
2108
1.40M
  for (const std::pair<StringRef, StringRef> &Pair : Registry.Dependencies) {
2109
1.40M
    if (Pair.second == CheckerName)
2110
0
      return true;
2111
1.40M
  }
2112
23.0k
  return false;
2113
23.0k
}
2114
2115
LLVM_ATTRIBUTE_USED static bool isHidden(const CheckerRegistryData &Registry,
2116
6.62k
                                         StringRef CheckerName) {
2117
597k
  for (const CheckerInfo &Checker : Registry.Checkers) {
2118
597k
    if (Checker.FullName == CheckerName)
2119
6.62k
      return Checker.IsHidden;
2120
597k
  }
2121
0
  llvm_unreachable(
2122
0
      "Checker name not found in CheckerRegistry -- did you retrieve it "
2123
0
      "correctly from CheckerManager::getCurrentCheckerName?");
2124
0
}
2125
2126
PathSensitiveBugReport::PathSensitiveBugReport(
2127
    const BugType &bt, StringRef shortDesc, StringRef desc,
2128
    const ExplodedNode *errorNode, PathDiagnosticLocation LocationToUnique,
2129
    const Decl *DeclToUnique)
2130
23.0k
    : BugReport(Kind::PathSensitive, bt, shortDesc, desc), ErrorNode(errorNode),
2131
23.0k
      ErrorNodeRange(getStmt() ? 
getStmt()->getSourceRange()22.9k
:
SourceRange()174
),
2132
23.0k
      UniqueingLocation(LocationToUnique), UniqueingDecl(DeclToUnique) {
2133
23.0k
  assert(!isDependency(ErrorNode->getState()
2134
23.0k
                           ->getAnalysisManager()
2135
23.0k
                           .getCheckerManager()
2136
23.0k
                           ->getCheckerRegistryData(),
2137
23.0k
                       bt.getCheckerName()) &&
2138
23.0k
         "Some checkers depend on this one! We don't allow dependency "
2139
23.0k
         "checkers to emit warnings, because checkers should depend on "
2140
23.0k
         "*modeling*, not *diagnostics*.");
2141
2142
23.0k
  assert(
2143
23.0k
      (bt.getCheckerName().startswith("debug") ||
2144
23.0k
       !isHidden(ErrorNode->getState()
2145
23.0k
                     ->getAnalysisManager()
2146
23.0k
                     .getCheckerManager()
2147
23.0k
                     ->getCheckerRegistryData(),
2148
23.0k
                 bt.getCheckerName())) &&
2149
23.0k
          "Hidden checkers musn't emit diagnostics as they are by definition "
2150
23.0k
          "non-user facing!");
2151
23.0k
}
2152
2153
void PathSensitiveBugReport::addVisitor(
2154
104k
    std::unique_ptr<BugReporterVisitor> visitor) {
2155
104k
  if (!visitor)
2156
0
    return;
2157
2158
104k
  llvm::FoldingSetNodeID ID;
2159
104k
  visitor->Profile(ID);
2160
2161
104k
  void *InsertPos = nullptr;
2162
104k
  if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
2163
0
    return;
2164
0
  }
2165
2166
104k
  Callbacks.push_back(std::move(visitor));
2167
104k
}
2168
2169
3.41M
void PathSensitiveBugReport::clearVisitors() {
2170
3.41M
  Callbacks.clear();
2171
3.41M
}
2172
2173
40.8k
const Decl *PathSensitiveBugReport::getDeclWithIssue() const {
2174
40.8k
  const ExplodedNode *N = getErrorNode();
2175
40.8k
  if (!N)
2176
0
    return nullptr;
2177
2178
40.8k
  const LocationContext *LC = N->getLocationContext();
2179
40.8k
  return LC->getStackFrame()->getDecl();
2180
40.8k
}
2181
2182
1.10k
void BasicBugReport::Profile(llvm::FoldingSetNodeID& hash) const {
2183
1.10k
  hash.AddInteger(static_cast<int>(getKind()));
2184
1.10k
  hash.AddPointer(&BT);
2185
1.10k
  hash.AddString(Description);
2186
1.10k
  assert(Location.isValid());
2187
1.10k
  Location.Profile(hash);
2188
2189
1.10k
  for (SourceRange range : Ranges) {
2190
981
    if (!range.isValid())
2191
1
      continue;
2192
980
    hash.Add(range.getBegin());
2193
980
    hash.Add(range.getEnd());
2194
980
  }
2195
1.10k
}
2196
2197
31.7k
void PathSensitiveBugReport::Profile(llvm::FoldingSetNodeID &hash) const {
2198
31.7k
  hash.AddInteger(static_cast<int>(getKind()));
2199
31.7k
  hash.AddPointer(&BT);
2200
31.7k
  hash.AddString(Description);
2201
31.7k
  PathDiagnosticLocation UL = getUniqueingLocation();
2202
31.7k
  if (UL.isValid()) {
2203
1.26k
    UL.Profile(hash);
2204
30.5k
  } else {
2205
    // TODO: The statement may be null if the report was emitted before any
2206
    // statements were executed. In particular, some checkers by design
2207
    // occasionally emit their reports in empty functions (that have no
2208
    // statements in their body). Do we profile correctly in this case?
2209
30.5k
    hash.AddPointer(ErrorNode->getCurrentOrPreviousStmtForDiagnostics());
2210
30.5k
  }
2211
2212
31.7k
  for (SourceRange range : Ranges) {
2213
4.31k
    if (!range.isValid())
2214
4
      continue;
2215
4.31k
    hash.Add(range.getBegin());
2216
4.31k
    hash.Add(range.getEnd());
2217
4.31k
  }
2218
31.7k
}
2219
2220
template <class T>
2221
static void insertToInterestingnessMap(
2222
    llvm::DenseMap<T, bugreporter::TrackingKind> &InterestingnessMap, T Val,
2223
8.28k
    bugreporter::TrackingKind TKind) {
2224
8.28k
  auto Result = InterestingnessMap.insert({Val, TKind});
2225
2226
8.28k
  if (Result.second)
2227
6.92k
    return;
2228
2229
  // Even if this symbol/region was already marked as interesting as a
2230
  // condition, if we later mark it as interesting again but with
2231
  // thorough tracking, overwrite it. Entities marked with thorough
2232
  // interestiness are the most important (or most interesting, if you will),
2233
  // and we wouldn't like to downplay their importance.
2234
2235
1.36k
  switch (TKind) {
2236
740
    case bugreporter::TrackingKind::Thorough:
2237
740
      Result.first->getSecond() = bugreporter::TrackingKind::Thorough;
2238
740
      return;
2239
629
    case bugreporter::TrackingKind::Condition:
2240
629
      return;
2241
1.36k
    }
2242
2243
0
    llvm_unreachable(
2244
0
        "BugReport::markInteresting currently can only handle 2 different "
2245
0
        "tracking kinds! Please define what tracking kind should this entitiy"
2246
0
        "have, if it was already marked as interesting with a different kind!");
2247
0
}
BugReporter.cpp:void insertToInterestingnessMap<clang::ento::SymExpr const*>(llvm::DenseMap<clang::ento::SymExpr const*, clang::ento::bugreporter::TrackingKind, llvm::DenseMapInfo<clang::ento::SymExpr const*, void>, llvm::detail::DenseMapPair<clang::ento::SymExpr const*, clang::ento::bugreporter::TrackingKind> >&, clang::ento::SymExpr const*, clang::ento::bugreporter::TrackingKind)
Line
Count
Source
2223
6.08k
    bugreporter::TrackingKind TKind) {
2224
6.08k
  auto Result = InterestingnessMap.insert({Val, TKind});
2225
2226
6.08k
  if (Result.second)
2227
4.97k
    return;
2228
2229
  // Even if this symbol/region was already marked as interesting as a
2230
  // condition, if we later mark it as interesting again but with
2231
  // thorough tracking, overwrite it. Entities marked with thorough
2232
  // interestiness are the most important (or most interesting, if you will),
2233
  // and we wouldn't like to downplay their importance.
2234
2235
1.10k
  switch (TKind) {
2236
675
    case bugreporter::TrackingKind::Thorough:
2237
675
      Result.first->getSecond() = bugreporter::TrackingKind::Thorough;
2238
675
      return;
2239
434
    case bugreporter::TrackingKind::Condition:
2240
434
      return;
2241
1.10k
    }
2242
2243
0
    llvm_unreachable(
2244
0
        "BugReport::markInteresting currently can only handle 2 different "
2245
0
        "tracking kinds! Please define what tracking kind should this entitiy"
2246
0
        "have, if it was already marked as interesting with a different kind!");
2247
0
}
BugReporter.cpp:void insertToInterestingnessMap<clang::ento::MemRegion const*>(llvm::DenseMap<clang::ento::MemRegion const*, clang::ento::bugreporter::TrackingKind, llvm::DenseMapInfo<clang::ento::MemRegion const*, void>, llvm::detail::DenseMapPair<clang::ento::MemRegion const*, clang::ento::bugreporter::TrackingKind> >&, clang::ento::MemRegion const*, clang::ento::bugreporter::TrackingKind)
Line
Count
Source
2223
2.20k
    bugreporter::TrackingKind TKind) {
2224
2.20k
  auto Result = InterestingnessMap.insert({Val, TKind});
2225
2226
2.20k
  if (Result.second)
2227
1.94k
    return;
2228
2229
  // Even if this symbol/region was already marked as interesting as a
2230
  // condition, if we later mark it as interesting again but with
2231
  // thorough tracking, overwrite it. Entities marked with thorough
2232
  // interestiness are the most important (or most interesting, if you will),
2233
  // and we wouldn't like to downplay their importance.
2234
2235
260
  switch (TKind) {
2236
65
    case bugreporter::TrackingKind::Thorough:
2237
65
      Result.first->getSecond() = bugreporter::TrackingKind::Thorough;
2238
65
      return;
2239
195
    case bugreporter::TrackingKind::Condition:
2240
195
      return;
2241
260
    }
2242
2243
0
    llvm_unreachable(
2244
0
        "BugReport::markInteresting currently can only handle 2 different "
2245
0
        "tracking kinds! Please define what tracking kind should this entitiy"
2246
0
        "have, if it was already marked as interesting with a different kind!");
2247
0
}
2248
2249
void PathSensitiveBugReport::markInteresting(SymbolRef sym,
2250
8.44k
                                             bugreporter::TrackingKind TKind) {
2251
8.44k
  if (!sym)
2252
2.35k
    return;
2253
2254
6.08k
  insertToInterestingnessMap(InterestingSymbols, sym, TKind);
2255
2256
  // FIXME: No tests exist for this code and it is questionable:
2257
  // How to handle multiple metadata for the same region?
2258
6.08k
  if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
2259
0
    markInteresting(meta->getRegion(), TKind);
2260
6.08k
}
2261
2262
37
void PathSensitiveBugReport::markNotInteresting(SymbolRef sym) {
2263
37
  if (!sym)
2264
0
    return;
2265
37
  InterestingSymbols.erase(sym);
2266
2267
  // The metadata part of markInteresting is not reversed here.
2268
  // Just making the same region not interesting is incorrect
2269
  // in specific cases.
2270
37
  if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
2271
0
    markNotInteresting(meta->getRegion());
2272
37
}
2273
2274
void PathSensitiveBugReport::markInteresting(const MemRegion *R,
2275
6.21k
                                             bugreporter::TrackingKind TKind) {
2276
6.21k
  if (!R)
2277
4.01k
    return;
2278
2279
2.20k
  R = R->getBaseRegion();
2280
2.20k
  insertToInterestingnessMap(InterestingRegions, R, TKind);
2281
2282
2.20k
  if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2283
1.64k
    markInteresting(SR->getSymbol(), TKind);
2284
2.20k
}
2285
2286
80
void PathSensitiveBugReport::markNotInteresting(const MemRegion *R) {
2287
80
  if (!R)
2288
0
    return;
2289
2290
80
  R = R->getBaseRegion();
2291
80
  InterestingRegions.erase(R);
2292
2293
80
  if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2294
29
    markNotInteresting(SR->getSymbol());
2295
80
}
2296
2297
void PathSensitiveBugReport::markInteresting(SVal V,
2298
4.85k
                                             bugreporter::TrackingKind TKind) {
2299
4.85k
  markInteresting(V.getAsRegion(), TKind);
2300
4.85k
  markInteresting(V.getAsSymbol(), TKind);
2301
4.85k
}
2302
2303
1.20k
void PathSensitiveBugReport::markInteresting(const LocationContext *LC) {
2304
1.20k
  if (!LC)
2305
431
    return;
2306
775
  InterestingLocationContexts.insert(LC);
2307
775
}
2308
2309
std::optional<bugreporter::TrackingKind>
2310
10.9k
PathSensitiveBugReport::getInterestingnessKind(SVal V) const {
2311
10.9k
  auto RKind = getInterestingnessKind(V.getAsRegion());
2312
10.9k
  auto SKind = getInterestingnessKind(V.getAsSymbol());
2313
10.9k
  if (!RKind)
2314
10.4k
    return SKind;
2315
453
  if (!SKind)
2316
4
    return RKind;
2317
2318
  // If either is marked with throrough tracking, return that, we wouldn't like
2319
  // to downplay a note's importance by 'only' mentioning it as a condition.
2320
449
  switch(*RKind) {
2321
424
    case bugreporter::TrackingKind::Thorough:
2322
424
      return RKind;
2323
25
    case bugreporter::TrackingKind::Condition:
2324
25
      return SKind;
2325
449
  }
2326
2327
0
  llvm_unreachable(
2328
0
      "BugReport::getInterestingnessKind currently can only handle 2 different "
2329
0
      "tracking kinds! Please define what tracking kind should we return here "
2330
0
      "when the kind of getAsRegion() and getAsSymbol() is different!");
2331
0
  return std::nullopt;
2332
449
}
2333
2334
std::optional<bugreporter::TrackingKind>
2335
17.2k
PathSensitiveBugReport::getInterestingnessKind(SymbolRef sym) const {
2336
17.2k
  if (!sym)
2337
621
    return std::nullopt;
2338
  // We don't currently consider metadata symbols to be interesting
2339
  // even if we know their region is interesting. Is that correct behavior?
2340
16.6k
  auto It = InterestingSymbols.find(sym);
2341
16.6k
  if (It == InterestingSymbols.end())
2342
14.8k
    return std::nullopt;
2343
1.83k
  return It->getSecond();
2344
16.6k
}
2345
2346
std::optional<bugreporter::TrackingKind>
2347
20.1k
PathSensitiveBugReport::getInterestingnessKind(const MemRegion *R) const {
2348
20.1k
  if (!R)
2349
9.26k
    return std::nullopt;
2350
2351
10.8k
  R = R->getBaseRegion();
2352
10.8k
  auto It = InterestingRegions.find(R);
2353
10.8k
  if (It != InterestingRegions.end())
2354
750
    return It->getSecond();
2355
2356
10.1k
  if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2357
1.66k
    return getInterestingnessKind(SR->getSymbol());
2358
8.45k
  return std::nullopt;
2359
10.1k
}
2360
2361
9.45k
bool PathSensitiveBugReport::isInteresting(SVal V) const {
2362
9.45k
  return getInterestingnessKind(V).has_value();
2363
9.45k
}
2364
2365
4.65k
bool PathSensitiveBugReport::isInteresting(SymbolRef sym) const {
2366
4.65k
  return getInterestingnessKind(sym).has_value();
2367
4.65k
}
2368
2369
9.23k
bool PathSensitiveBugReport::isInteresting(const MemRegion *R) const {
2370
9.23k
  return getInterestingnessKind(R).has_value();
2371
9.23k
}
2372
2373
9.37k
bool PathSensitiveBugReport::isInteresting(const LocationContext *LC)  const {
2374
9.37k
  if (!LC)
2375
0
    return false;
2376
9.37k
  return InterestingLocationContexts.count(LC);
2377
9.37k
}
2378
2379
63.1k
const Stmt *PathSensitiveBugReport::getStmt() const {
2380
63.1k
  if (!ErrorNode)
2381
0
    return nullptr;
2382
2383
63.1k
  ProgramPoint ProgP = ErrorNode->getLocation();
2384
63.1k
  const Stmt *S = nullptr;
2385
2386
63.1k
  if (std::optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
2387
0
    CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
2388
0
    if (BE->getBlock() == &Exit)
2389
0
      S = ErrorNode->getPreviousStmtForDiagnostics();
2390
0
  }
2391
63.1k
  if (!S)
2392
63.1k
    S = ErrorNode->getStmtForDiagnostics();
2393
2394
63.1k
  return S;
2395
63.1k
}
2396
2397
ArrayRef<SourceRange>
2398
20.9k
PathSensitiveBugReport::getRanges() const {
2399
  // If no custom ranges, add the range of the statement corresponding to
2400
  // the error node.
2401
20.9k
  if (Ranges.empty() && 
isa_and_nonnull<Expr>(getStmt())17.0k
)
2402
16.5k
      return ErrorNodeRange;
2403
2404
4.36k
  return Ranges;
2405
20.9k
}
2406
2407
PathDiagnosticLocation
2408
64.8k
PathSensitiveBugReport::getLocation() const {
2409
64.8k
  assert(ErrorNode && "Cannot create a location with a null node.");
2410
64.8k
  const Stmt *S = ErrorNode->getStmtForDiagnostics();
2411
64.8k
    ProgramPoint P = ErrorNode->getLocation();
2412
64.8k
  const LocationContext *LC = P.getLocationContext();
2413
64.8k
  SourceManager &SM =
2414
64.8k
      ErrorNode->getState()->getStateManager().getContext().getSourceManager();
2415
2416
64.8k
  if (!S) {
2417
    // If this is an implicit call, return the implicit call point location.
2418
501
      if (std::optional<PreImplicitCall> PIE = P.getAs<PreImplicitCall>())
2419
24
      return PathDiagnosticLocation(PIE->getLocation(), SM);
2420
477
    if (auto FE = P.getAs<FunctionExitPoint>()) {
2421
477
      if (const ReturnStmt *RS = FE->getStmt())
2422
0
        return PathDiagnosticLocation::createBegin(RS, SM, LC);
2423
477
    }
2424
477
    S = ErrorNode->getNextStmtForDiagnostics();
2425
477
  }
2426
2427
64.8k
  if (S) {
2428
    // For member expressions, return the location of the '.' or '->'.
2429
64.6k
    if (const auto *ME = dyn_cast<MemberExpr>(S))
2430
16
      return PathDiagnosticLocation::createMemberLoc(ME, SM);
2431
2432
    // For binary operators, return the location of the operator.
2433
64.5k
    if (const auto *B = dyn_cast<BinaryOperator>(S))
2434
3.95k
      return PathDiagnosticLocation::createOperatorLoc(B, SM);
2435
2436
60.6k
    if (P.getAs<PostStmtPurgeDeadSymbols>())
2437
804
      return PathDiagnosticLocation::createEnd(S, SM, LC);
2438
2439
59.8k
    if (S->getBeginLoc().isValid())
2440
59.8k
      return PathDiagnosticLocation(S, SM, LC);
2441
2442
2
    return PathDiagnosticLocation(
2443
2
        PathDiagnosticLocation::getValidSourceLocation(S, LC), SM);
2444
59.8k
  }
2445
2446
192
  return PathDiagnosticLocation::createDeclEnd(ErrorNode->getLocationContext(),
2447
192
                                               SM);
2448
64.8k
}
2449
2450
//===----------------------------------------------------------------------===//
2451
// Methods for BugReporter and subclasses.
2452
//===----------------------------------------------------------------------===//
2453
2454
21.0k
const ExplodedGraph &PathSensitiveBugReporter::getGraph() const {
2455
21.0k
  return Eng.getGraph();
2456
21.0k
}
2457
2458
43.4k
ProgramStateManager &PathSensitiveBugReporter::getStateManager() const {
2459
43.4k
  return Eng.getStateManager();
2460
43.4k
}
2461
2462
55.8k
BugReporter::BugReporter(BugReporterData &d) : D(d) {}
2463
55.8k
BugReporter::~BugReporter() {
2464
  // Make sure reports are flushed.
2465
55.8k
  assert(StrBugTypes.empty() &&
2466
55.8k
         "Destroying BugReporter before diagnostics are emitted!");
2467
2468
  // Free the bug reports we are tracking.
2469
55.8k
  for (const auto I : EQClassesVector)
2470
22.0k
    delete I;
2471
55.8k
}
2472
2473
55.8k
void BugReporter::FlushReports() {
2474
  // We need to flush reports in deterministic order to ensure the order
2475
  // of the reports is consistent between runs.
2476
55.8k
  for (const auto EQ : EQClassesVector)
2477
22.0k
    FlushReport(*EQ);
2478
2479
  // BugReporter owns and deletes only BugTypes created implicitly through
2480
  // EmitBasicReport.
2481
  // FIXME: There are leaks from checkers that assume that the BugTypes they
2482
  // create will be destroyed by the BugReporter.
2483
55.8k
  StrBugTypes.clear();
2484
55.8k
}
2485
2486
//===----------------------------------------------------------------------===//
2487
// PathDiagnostics generation.
2488
//===----------------------------------------------------------------------===//
2489
2490
namespace {
2491
2492
/// A wrapper around an ExplodedGraph that contains a single path from the root
2493
/// to the error node.
2494
class BugPathInfo {
2495
public:
2496
  std::unique_ptr<ExplodedGraph> BugPath;
2497
  PathSensitiveBugReport *Report;
2498
  const ExplodedNode *ErrorNode;
2499
};
2500
2501
/// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
2502
/// conveniently retrieve bug paths from a single error node to the root.
2503
class BugPathGetter {
2504
  std::unique_ptr<ExplodedGraph> TrimmedGraph;
2505
2506
  using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
2507
2508
  /// Assign each node with its distance from the root.
2509
  PriorityMapTy PriorityMap;
2510
2511
  /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
2512
  /// we need to pair it to the error node of the constructed trimmed graph.
2513
  using ReportNewNodePair =
2514
      std::pair<PathSensitiveBugReport *, const ExplodedNode *>;
2515
  SmallVector<ReportNewNodePair, 32> ReportNodes;
2516
2517
  BugPathInfo CurrentBugPath;
2518
2519
  /// A helper class for sorting ExplodedNodes by priority.
2520
  template <bool Descending>
2521
  class PriorityCompare {
2522
    const PriorityMapTy &PriorityMap;
2523
2524
  public:
2525
3.44M
    PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
BugReporter.cpp:(anonymous namespace)::BugPathGetter::PriorityCompare<true>::PriorityCompare(llvm::DenseMap<clang::ento::ExplodedNode const*, unsigned int, llvm::DenseMapInfo<clang::ento::ExplodedNode const*, void>, llvm::detail::DenseMapPair<clang::ento::ExplodedNode const*, unsigned int> > const&)
Line
Count
Source
2525
21.0k
    PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
BugReporter.cpp:(anonymous namespace)::BugPathGetter::PriorityCompare<false>::PriorityCompare(llvm::DenseMap<clang::ento::ExplodedNode const*, unsigned int, llvm::DenseMapInfo<clang::ento::ExplodedNode const*, void>, llvm::detail::DenseMapPair<clang::ento::ExplodedNode const*, unsigned int> > const&)
Line
Count
Source
2525
3.41M
    PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
2526
2527
8.75k
    bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2528
8.75k
      PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2529
8.75k
      PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2530
8.75k
      PriorityMapTy::const_iterator E = PriorityMap.end();
2531
2532
8.75k
      if (LI == E)
2533
376
        return Descending;
2534
8.38k
      if (RI == E)
2535
41
        return !Descending;
2536
2537
8.34k
      return Descending ? 
LI->second > RI->second7.13k
2538
8.34k
                        : 
LI->second < RI->second1.21k
;
2539
8.38k
    }
BugReporter.cpp:(anonymous namespace)::BugPathGetter::PriorityCompare<true>::operator()(clang::ento::ExplodedNode const*, clang::ento::ExplodedNode const*) const
Line
Count
Source
2527
7.13k
    bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2528
7.13k
      PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2529
7.13k
      PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2530
7.13k
      PriorityMapTy::const_iterator E = PriorityMap.end();
2531
2532
7.13k
      if (LI == E)
2533
0
        return Descending;
2534
7.13k
      if (RI == E)
2535
0
        return !Descending;
2536
2537
7.13k
      return Descending ? LI->second > RI->second
2538
7.13k
                        : 
LI->second < RI->second0
;
2539
7.13k
    }
BugReporter.cpp:(anonymous namespace)::BugPathGetter::PriorityCompare<false>::operator()(clang::ento::ExplodedNode const*, clang::ento::ExplodedNode const*) const
Line
Count
Source
2527
1.62k
    bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2528
1.62k
      PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2529
1.62k
      PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2530
1.62k
      PriorityMapTy::const_iterator E = PriorityMap.end();
2531
2532
1.62k
      if (LI == E)
2533
376
        return Descending;
2534
1.25k
      if (RI == E)
2535
41
        return !Descending;
2536
2537
1.21k
      return Descending ? 
LI->second > RI->second0
2538
1.21k
                        : LI->second < RI->second;
2539
1.25k
    }
2540
2541
    bool operator()(const ReportNewNodePair &LHS,
2542
7.13k
                    const ReportNewNodePair &RHS) const {
2543
7.13k
      return (*this)(LHS.second, RHS.second);
2544
7.13k
    }
2545
  };
2546
2547
public:
2548
  BugPathGetter(const ExplodedGraph *OriginalGraph,
2549
                ArrayRef<PathSensitiveBugReport *> &bugReports);
2550
2551
  BugPathInfo *getNextBugPath();
2552
};
2553
2554
} // namespace
2555
2556
BugPathGetter::BugPathGetter(const ExplodedGraph *OriginalGraph,
2557
21.0k
                             ArrayRef<PathSensitiveBugReport *> &bugReports) {
2558
21.0k
  SmallVector<const ExplodedNode *, 32> Nodes;
2559
23.0k
  for (const auto I : bugReports) {
2560
23.0k
    assert(I->isValid() &&
2561
23.0k
           "We only allow BugReporterVisitors and BugReporter itself to "
2562
23.0k
           "invalidate reports!");
2563
23.0k
    Nodes.emplace_back(I->getErrorNode());
2564
23.0k
  }
2565
2566
  // The trimmed graph is created in the body of the constructor to ensure
2567
  // that the DenseMaps have been initialized already.
2568
21.0k
  InterExplodedGraphMap ForwardMap;
2569
21.0k
  TrimmedGraph = OriginalGraph->trim(Nodes, &ForwardMap);
2570
2571
  // Find the (first) error node in the trimmed graph.  We just need to consult
2572
  // the node map which maps from nodes in the original graph to nodes
2573
  // in the new graph.
2574
21.0k
  llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
2575
2576
23.0k
  for (PathSensitiveBugReport *Report : bugReports) {
2577
23.0k
    const ExplodedNode *NewNode = ForwardMap.lookup(Report->getErrorNode());
2578
23.0k
    assert(NewNode &&
2579
23.0k
           "Failed to construct a trimmed graph that contains this error "
2580
23.0k
           "node!");
2581
23.0k
    ReportNodes.emplace_back(Report, NewNode);
2582
23.0k
    RemainingNodes.insert(NewNode);
2583
23.0k
  }
2584
2585
21.0k
  assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
2586
2587
  // Perform a forward BFS to find all the shortest paths.
2588
21.0k
  std::queue<const ExplodedNode *> WS;
2589
2590
21.0k
  assert(TrimmedGraph->num_roots() == 1);
2591
21.0k
  WS.push(*TrimmedGraph->roots_begin());
2592
21.0k
  unsigned Priority = 0;
2593
2594
3.99M
  while (!WS.empty()) {
2595
3.99M
    const ExplodedNode *Node = WS.front();
2596
3.99M
    WS.pop();
2597
2598
3.99M
    PriorityMapTy::iterator PriorityEntry;
2599
3.99M
    bool IsNew;
2600
3.99M
    std::tie(PriorityEntry, IsNew) = PriorityMap.insert({Node, Priority});
2601
3.99M
    ++Priority;
2602
2603
3.99M
    if (!IsNew) {
2604
6.31k
      assert(PriorityEntry->second <= Priority);
2605
6.31k
      continue;
2606
6.31k
    }
2607
2608
3.98M
    if (RemainingNodes.erase(Node))
2609
23.0k
      if (RemainingNodes.empty())
2610
21.0k
        break;
2611
2612
3.96M
    for (const ExplodedNode *Succ : Node->succs())
2613
3.97M
      WS.push(Succ);
2614
3.96M
  }
2615
2616
  // Sort the error paths from longest to shortest.
2617
21.0k
  llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
2618
21.0k
}
2619
2620
21.2k
BugPathInfo *BugPathGetter::getNextBugPath() {
2621
21.2k
  if (ReportNodes.empty())
2622
195
    return nullptr;
2623
2624
21.0k
  const ExplodedNode *OrigN;
2625
21.0k
  std::tie(CurrentBugPath.Report, OrigN) = ReportNodes.pop_back_val();
2626
21.0k
  assert(PriorityMap.contains(OrigN) && "error node not accessible from root");
2627
2628
  // Create a new graph with a single path. This is the graph that will be
2629
  // returned to the caller.
2630
21.0k
  auto GNew = std::make_unique<ExplodedGraph>();
2631
2632
  // Now walk from the error node up the BFS path, always taking the
2633
  // predeccessor with the lowest number.
2634
21.0k
  ExplodedNode *Succ = nullptr;
2635
3.44M
  while (true) {
2636
    // Create the equivalent node in the new graph with the same state
2637
    // and location.
2638
3.44M
    ExplodedNode *NewN = GNew->createUncachedNode(
2639
3.44M
        OrigN->getLocation(), OrigN->getState(),
2640
3.44M
        OrigN->getID(), OrigN->isSink());
2641
2642
    // Link up the new node with the previous node.
2643
3.44M
    if (Succ)
2644
3.41M
      Succ->addPredecessor(NewN, *GNew);
2645
21.0k
    else
2646
21.0k
      CurrentBugPath.ErrorNode = NewN;
2647
2648
3.44M
    Succ = NewN;
2649
2650
    // Are we at the final node?
2651
3.44M
    if (OrigN->pred_empty()) {
2652
21.0k
      GNew->addRoot(NewN);
2653
21.0k
      break;
2654
21.0k
    }
2655
2656
    // Find the next predeccessor node.  We choose the node that is marked
2657
    // with the lowest BFS number.
2658
3.41M
    OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2659
3.41M
                              PriorityCompare<false>(PriorityMap));
2660
3.41M
  }
2661
2662
21.0k
  CurrentBugPath.BugPath = std::move(GNew);
2663
2664
21.0k
  return &CurrentBugPath;
2665
21.0k
}
2666
2667
/// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
2668
/// object and collapses PathDiagosticPieces that are expanded by macros.
2669
static void CompactMacroExpandedPieces(PathPieces &path,
2670
61
                                       const SourceManager& SM) {
2671
61
  using MacroStackTy = std::vector<
2672
61
      std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
2673
2674
61
  using PiecesTy = std::vector<PathDiagnosticPieceRef>;
2675
2676
61
  MacroStackTy MacroStack;
2677
61
  PiecesTy Pieces;
2678
2679
61
  for (PathPieces::const_iterator I = path.begin(), E = path.end();
2680
305
       I != E; 
++I244
) {
2681
244
    const auto &piece = *I;
2682
2683
    // Recursively compact calls.
2684
244
    if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
2685
19
      CompactMacroExpandedPieces(call->path, SM);
2686
19
    }
2687
2688
    // Get the location of the PathDiagnosticPiece.
2689
244
    const FullSourceLoc Loc = piece->getLocation().asLocation();
2690
2691
    // Determine the instantiation location, which is the location we group
2692
    // related PathDiagnosticPieces.
2693
244
    SourceLocation InstantiationLoc = Loc.isMacroID() ?
2694
94
                                      SM.getExpansionLoc(Loc) :
2695
244
                                      
SourceLocation()150
;
2696
2697
244
    if (Loc.isFileID()) {
2698
150
      MacroStack.clear();
2699
150
      Pieces.push_back(piece);
2700
150
      continue;
2701
150
    }
2702
2703
94
    assert(Loc.isMacroID());
2704
2705
    // Is the PathDiagnosticPiece within the same macro group?
2706
94
    if (!MacroStack.empty() && 
InstantiationLoc == MacroStack.back().second49
) {
2707
48
      MacroStack.back().first->subPieces.push_back(piece);
2708
48
      continue;
2709
48
    }
2710
2711
    // We aren't in the same group.  Are we descending into a new macro
2712
    // or are part of an old one?
2713
46
    std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
2714
2715
46
    SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
2716
0
                                          SM.getExpansionLoc(Loc) :
2717
46
                                          SourceLocation();
2718
2719
    // Walk the entire macro stack.
2720
47
    while (!MacroStack.empty()) {
2721
1
      if (InstantiationLoc == MacroStack.back().second) {
2722
0
        MacroGroup = MacroStack.back().first;
2723
0
        break;
2724
0
      }
2725
2726
1
      if (ParentInstantiationLoc == MacroStack.back().second) {
2727
0
        MacroGroup = MacroStack.back().first;
2728
0
        break;
2729
0
      }
2730
2731
1
      MacroStack.pop_back();
2732
1
    }
2733
2734
46
    if (!MacroGroup || 
ParentInstantiationLoc == MacroStack.back().second0
) {
2735
      // Create a new macro group and add it to the stack.
2736
46
      auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
2737
46
          PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2738
2739
46
      if (MacroGroup)
2740
0
        MacroGroup->subPieces.push_back(NewGroup);
2741
46
      else {
2742
46
        assert(InstantiationLoc.isFileID());
2743
46
        Pieces.push_back(NewGroup);
2744
46
      }
2745
2746
46
      MacroGroup = NewGroup;
2747
46
      MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2748
46
    }
2749
2750
    // Finally, add the PathDiagnosticPiece to the group.
2751
46
    MacroGroup->subPieces.push_back(piece);
2752
46
  }
2753
2754
  // Now take the pieces and construct a new PathDiagnostic.
2755
61
  path.clear();
2756
2757
61
  path.insert(path.end(), Pieces.begin(), Pieces.end());
2758
61
}
2759
2760
/// Generate notes from all visitors.
2761
/// Notes associated with @c ErrorNode are generated using
2762
/// @c getEndPath, and the rest are generated with @c VisitNode.
2763
static std::unique_ptr<VisitorsDiagnosticsTy>
2764
generateVisitorsDiagnostics(PathSensitiveBugReport *R,
2765
                            const ExplodedNode *ErrorNode,
2766
21.0k
                            BugReporterContext &BRC) {
2767
21.0k
  std::unique_ptr<VisitorsDiagnosticsTy> Notes =
2768
21.0k
      std::make_unique<VisitorsDiagnosticsTy>();
2769
21.0k
  PathSensitiveBugReport::VisitorList visitors;
2770
2771
  // Run visitors on all nodes starting from the node *before* the last one.
2772
  // The last node is reserved for notes generated with @c getEndPath.
2773
21.0k
  const ExplodedNode *NextNode = ErrorNode->getFirstPred();
2774
3.41M
  while (NextNode) {
2775
2776
    // At each iteration, move all visitors from report to visitor list. This is
2777
    // important, because the Profile() functions of the visitors make sure that
2778
    // a visitor isn't added multiple times for the same node, but it's fine
2779
    // to add the a visitor with Profile() for different nodes (e.g. tracking
2780
    // a region at different points of the symbolic execution).
2781
3.41M
    for (std::unique_ptr<BugReporterVisitor> &Visitor : R->visitors())
2782
103k
      visitors.push_back(std::move(Visitor));
2783
2784
3.41M
    R->clearVisitors();
2785
2786
3.41M
    const ExplodedNode *Pred = NextNode->getFirstPred();
2787
3.41M
    if (!Pred) {
2788
20.9k
      PathDiagnosticPieceRef LastPiece;
2789
102k
      for (auto &V : visitors) {
2790
102k
        V->finalizeVisitor(BRC, ErrorNode, *R);
2791
2792
102k
        if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
2793
849
          assert(!LastPiece &&
2794
849
                 "There can only be one final piece in a diagnostic.");
2795
849
          assert(Piece->getKind() == PathDiagnosticPiece::Kind::Event &&
2796
849
                 "The final piece must contain a message!");
2797
849
          LastPiece = std::move(Piece);
2798
849
          (*Notes)[ErrorNode].push_back(LastPiece);
2799
849
        }
2800
102k
      }
2801
20.9k
      break;
2802
20.9k
    }
2803
2804
14.5M
    
for (auto &V : visitors)3.39M
{
2805
14.5M
      auto P = V->VisitNode(NextNode, BRC, *R);
2806
14.5M
      if (P)
2807
16.9k
        (*Notes)[NextNode].push_back(std::move(P));
2808
14.5M
    }
2809
2810
3.39M
    if (!R->isValid())
2811
92
      break;
2812
2813
3.39M
    NextNode = Pred;
2814
3.39M
  }
2815
2816
21.0k
  return Notes;
2817
21.0k
}
2818
2819
std::optional<PathDiagnosticBuilder> PathDiagnosticBuilder::findValidReport(
2820
    ArrayRef<PathSensitiveBugReport *> &bugReports,
2821
21.0k
    PathSensitiveBugReporter &Reporter) {
2822
2823
21.0k
  BugPathGetter BugGraph(&Reporter.getGraph(), bugReports);
2824
2825
21.2k
  while (BugPathInfo *BugPath = BugGraph.getNextBugPath()) {
2826
    // Find the BugReport with the original location.
2827
21.0k
    PathSensitiveBugReport *R = BugPath->Report;
2828
21.0k
    assert(R && "No original report found for sliced graph.");
2829
21.0k
    assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
2830
21.0k
    const ExplodedNode *ErrorNode = BugPath->ErrorNode;
2831
2832
    // Register refutation visitors first, if they mark the bug invalid no
2833
    // further analysis is required
2834
21.0k
    R->addVisitor<LikelyFalsePositiveSuppressionBRVisitor>();
2835
2836
    // Register additional node visitors.
2837
21.0k
    R->addVisitor<NilReceiverBRVisitor>();
2838
21.0k
    R->addVisitor<ConditionBRVisitor>();
2839
21.0k
    R->addVisitor<TagVisitor>();
2840
2841
21.0k
    BugReporterContext BRC(Reporter);
2842
2843
    // Run all visitors on a given graph, once.
2844
21.0k
    std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
2845
21.0k
        generateVisitorsDiagnostics(R, ErrorNode, BRC);
2846
2847
21.0k
    if (R->isValid()) {
2848
20.8k
      if (Reporter.getAnalyzerOptions().ShouldCrosscheckWithZ3) {
2849
        // If crosscheck is enabled, remove all visitors, add the refutation
2850
        // visitor and check again
2851
0
        R->clearVisitors();
2852
0
        R->addVisitor<FalsePositiveRefutationBRVisitor>();
2853
2854
        // We don't overwrite the notes inserted by other visitors because the
2855
        // refutation manager does not add any new note to the path
2856
0
        generateVisitorsDiagnostics(R, BugPath->ErrorNode, BRC);
2857
0
      }
2858
2859
      // Check if the bug is still valid
2860
20.8k
      if (R->isValid())
2861
20.8k
        return PathDiagnosticBuilder(
2862
20.8k
            std::move(BRC), std::move(BugPath->BugPath), BugPath->Report,
2863
20.8k
            BugPath->ErrorNode, std::move(visitorNotes));
2864
20.8k
    }
2865
21.0k
  }
2866
2867
195
  return {};
2868
21.0k
}
2869
2870
std::unique_ptr<DiagnosticForConsumerMapTy>
2871
PathSensitiveBugReporter::generatePathDiagnostics(
2872
    ArrayRef<PathDiagnosticConsumer *> consumers,
2873
21.0k
    ArrayRef<PathSensitiveBugReport *> &bugReports) {
2874
21.0k
  assert(!bugReports.empty());
2875
2876
21.0k
  auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
2877
2878
21.0k
  std::optional<PathDiagnosticBuilder> PDB =
2879
21.0k
      PathDiagnosticBuilder::findValidReport(bugReports, *this);
2880
2881
21.0k
  if (PDB) {
2882
21.5k
    for (PathDiagnosticConsumer *PC : consumers) {
2883
21.5k
      if (std::unique_ptr<PathDiagnostic> PD = PDB->generate(PC)) {
2884
21.5k
        (*Out)[PC] = std::move(PD);
2885
21.5k
      }
2886
21.5k
    }
2887
20.8k
  }
2888
2889
21.0k
  return Out;
2890
21.0k
}
2891
2892
24.1k
void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
2893
24.1k
  bool ValidSourceLoc = R->getLocation().isValid();
2894
24.1k
  assert(ValidSourceLoc);
2895
  // If we mess up in a release build, we'd still prefer to just drop the bug
2896
  // instead of trying to go on.
2897
24.1k
  if (!ValidSourceLoc)
2898
0
    return;
2899
2900
  // Compute the bug report's hash to determine its equivalence class.
2901
24.1k
  llvm::FoldingSetNodeID ID;
2902
24.1k
  R->Profile(ID);
2903
2904
  // Lookup the equivance class.  If there isn't one, create it.
2905
24.1k
  void *InsertPos;
2906
24.1k
  BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
2907
2908
24.1k
  if (!EQ) {
2909
22.0k
    EQ = new BugReportEquivClass(std::move(R));
2910
22.0k
    EQClasses.InsertNode(EQ, InsertPos);
2911
22.0k
    EQClassesVector.push_back(EQ);
2912
22.0k
  } else
2913
2.05k
    EQ->AddReport(std::move(R));
2914
24.1k
}
2915
2916
23.1k
void PathSensitiveBugReporter::emitReport(std::unique_ptr<BugReport> R) {
2917
23.1k
  if (auto PR = dyn_cast<PathSensitiveBugReport>(R.get()))
2918
23.0k
    if (const ExplodedNode *E = PR->getErrorNode()) {
2919
      // An error node must either be a sink or have a tag, otherwise
2920
      // it could get reclaimed before the path diagnostic is created.
2921
23.0k
      assert((E->isSink() || E->getLocation().getTag()) &&
2922
23.0k
             "Error node must either be a sink or have a tag");
2923
2924
23.0k
      const AnalysisDeclContext *DeclCtx =
2925
23.0k
          E->getLocationContext()->getAnalysisDeclContext();
2926
      // The source of autosynthesized body can be handcrafted AST or a model
2927
      // file. The locations from handcrafted ASTs have no valid source
2928
      // locations and have to be discarded. Locations from model files should
2929
      // be preserved for processing and reporting.
2930
23.0k
      if (DeclCtx->isBodyAutosynthesized() &&
2931
23.0k
          
!DeclCtx->isBodyAutosynthesizedFromModelFile()3
)
2932
3
        return;
2933
23.0k
    }
2934
2935
23.1k
  BugReporter::emitReport(std::move(R));
2936
23.1k
}
2937
2938
//===----------------------------------------------------------------------===//
2939
// Emitting reports in equivalence classes.
2940
//===----------------------------------------------------------------------===//
2941
2942
namespace {
2943
2944
struct FRIEC_WLItem {
2945
  const ExplodedNode *N;
2946
  ExplodedNode::const_succ_iterator I, E;
2947
2948
  FRIEC_WLItem(const ExplodedNode *n)
2949
18.1k
      : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2950
};
2951
2952
} // namespace
2953
2954
BugReport *PathSensitiveBugReporter::findReportInEquivalenceClass(
2955
21.0k
    BugReportEquivClass &EQ, SmallVectorImpl<BugReport *> &bugReports) {
2956
  // If we don't need to suppress any of the nodes because they are
2957
  // post-dominated by a sink, simply add all the nodes in the equivalence class
2958
  // to 'Nodes'.  Any of the reports will serve as a "representative" report.
2959
21.0k
  assert(EQ.getReports().size() > 0);
2960
21.0k
  const BugType& BT = EQ.getReports()[0]->getBugType();
2961
21.0k
  if (!BT.isSuppressOnSink()) {
2962
20.2k
    BugReport *R = EQ.getReports()[0].get();
2963
22.2k
    for (auto &J : EQ.getReports()) {
2964
22.2k
      if (auto *PR = dyn_cast<PathSensitiveBugReport>(J.get())) {
2965
22.2k
        R = PR;
2966
22.2k
        bugReports.push_back(PR);
2967
22.2k
      }
2968
22.2k
    }
2969
20.2k
    return R;
2970
20.2k
  }
2971
2972
  // For bug reports that should be suppressed when all paths are post-dominated
2973
  // by a sink node, iterate through the reports in the equivalence class
2974
  // until we find one that isn't post-dominated (if one exists).  We use a
2975
  // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
2976
  // this as a recursive function, but we don't want to risk blowing out the
2977
  // stack for very long paths.
2978
790
  BugReport *exampleReport = nullptr;
2979
2980
848
  for (const auto &I: EQ.getReports()) {
2981
848
    auto *R = dyn_cast<PathSensitiveBugReport>(I.get());
2982
848
    if (!R)
2983
0
      continue;
2984
2985
848
    const ExplodedNode *errorNode = R->getErrorNode();
2986
848
    if (errorNode->isSink()) {
2987
0
      llvm_unreachable(
2988
0
           "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2989
0
    }
2990
    // No successors?  By definition this nodes isn't post-dominated by a sink.
2991
848
    if (errorNode->succ_empty()) {
2992
11
      bugReports.push_back(R);
2993
11
      if (!exampleReport)
2994
11
        exampleReport = R;
2995
11
      continue;
2996
11
    }
2997
2998
    // See if we are in a no-return CFG block. If so, treat this similarly
2999
    // to being post-dominated by a sink. This works better when the analysis
3000
    // is incomplete and we have never reached the no-return function call(s)
3001
    // that we'd inevitably bump into on this path.
3002
837
    if (const CFGBlock *ErrorB = errorNode->getCFGBlock())
3003
502
      if (ErrorB->isInevitablySinking())
3004
23
        continue;
3005
3006
    // At this point we know that 'N' is not a sink and it has at least one
3007
    // successor.  Use a DFS worklist to find a non-sink end-of-path node.
3008
814
    using WLItem = FRIEC_WLItem;
3009
814
    using DFSWorkList = SmallVector<WLItem, 10>;
3010
3011
814
    llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
3012
3013
814
    DFSWorkList WL;
3014
814
    WL.push_back(errorNode);
3015
814
    Visited[errorNode] = 1;
3016
3017
20.9k
    while (!WL.empty()) {
3018
20.1k
      WLItem &WI = WL.back();
3019
20.1k
      assert(!WI.N->succ_empty());
3020
3021
22.1k
      
for (; 20.1k
WI.I != WI.E;
++WI.I2.02k
) {
3022
20.1k
        const ExplodedNode *Succ = *WI.I;
3023
        // End-of-path node?
3024
20.1k
        if (Succ->succ_empty()) {
3025
          // If we found an end-of-path node that is not a sink.
3026
832
          if (!Succ->isSink()) {
3027
781
            bugReports.push_back(R);
3028
781
            if (!exampleReport)
3029
736
              exampleReport = R;
3030
781
            WL.clear();
3031
781
            break;
3032
781
          }
3033
          // Found a sink?  Continue on to the next successor.
3034
51
          continue;
3035
832
        }
3036
        // Mark the successor as visited.  If it hasn't been explored,
3037
        // enqueue it to the DFS worklist.
3038
19.3k
        unsigned &mark = Visited[Succ];
3039
19.3k
        if (!mark) {
3040
17.3k
          mark = 1;
3041
17.3k
          WL.push_back(Succ);
3042
17.3k
          break;
3043
17.3k
        }
3044
19.3k
      }
3045
3046
      // The worklist may have been cleared at this point.  First
3047
      // check if it is empty before checking the last item.
3048
20.1k
      if (!WL.empty() && 
&WL.back() == &WI19.3k
)
3049
1.99k
        WL.pop_back();
3050
20.1k
    }
3051
814
  }
3052
3053
  // ExampleReport will be NULL if all the nodes in the equivalence class
3054
  // were post-dominated by sinks.
3055
790
  return exampleReport;
3056
790
}
3057
3058
22.0k
void BugReporter::FlushReport(BugReportEquivClass& EQ) {
3059
22.0k
  SmallVector<BugReport*, 10> bugReports;
3060
22.0k
  BugReport *report = findReportInEquivalenceClass(EQ, bugReports);
3061
22.0k
  if (!report)
3062
43
    return;
3063
3064
  // See whether we need to silence the checker/package.
3065
22.0k
  for (const std::string &CheckerOrPackage :
3066
22.0k
       getAnalyzerOptions().SilencedCheckersAndPackages) {
3067
20
    if (report->getBugType().getCheckerName().startswith(
3068
20
            CheckerOrPackage))
3069
14
      return;
3070
20
  }
3071
3072
22.0k
  ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
3073
22.0k
  std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
3074
22.0k
      generateDiagnosticForConsumerMap(report, Consumers, bugReports);
3075
3076
22.6k
  for (auto &P : *Diagnostics) {
3077
22.6k
    PathDiagnosticConsumer *Consumer = P.first;
3078
22.6k
    std::unique_ptr<PathDiagnostic> &PD = P.second;
3079
3080
    // If the path is empty, generate a single step path with the location
3081
    // of the issue.
3082
22.6k
    if (PD->path.empty()) {
3083
20.3k
      PathDiagnosticLocation L = report->getLocation();
3084
20.3k
      auto piece = std::make_unique<PathDiagnosticEventPiece>(
3085
20.3k
        L, report->getDescription());
3086
20.3k
      for (SourceRange Range : report->getRanges())
3087
19.6k
        piece->addRange(Range);
3088
20.3k
      PD->setEndOfPath(std::move(piece));
3089
20.3k
    }
3090
3091
22.6k
    PathPieces &Pieces = PD->getMutablePieces();
3092
22.6k
    if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
3093
      // For path diagnostic consumers that don't support extra notes,
3094
      // we may optionally convert those to path notes.
3095
2
      for (const auto &I : llvm::reverse(report->getNotes())) {
3096
2
        PathDiagnosticNotePiece *Piece = I.get();
3097
2
        auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
3098
2
          Piece->getLocation(), Piece->getString());
3099
2
        for (const auto &R: Piece->getRanges())
3100
2
          ConvertedPiece->addRange(R);
3101
3102
2
        Pieces.push_front(std::move(ConvertedPiece));
3103
2
      }
3104
22.6k
    } else {
3105
22.6k
      for (const auto &I : llvm::reverse(report->getNotes()))
3106
188
        Pieces.push_front(I);
3107
22.6k
    }
3108
3109
22.6k
    for (const auto &I : report->getFixits())
3110
13
      Pieces.back()->addFixit(I);
3111
3112
22.6k
    updateExecutedLinesWithDiagnosticPieces(*PD);
3113
22.6k
    Consumer->HandlePathDiagnostic(std::move(PD));
3114
22.6k
  }
3115
22.0k
}
3116
3117
/// Insert all lines participating in the function signature \p Signature
3118
/// into \p ExecutedLines.
3119
static void populateExecutedLinesWithFunctionSignature(
3120
    const Decl *Signature, const SourceManager &SM,
3121
103k
    FilesToLineNumsMap &ExecutedLines) {
3122
103k
  SourceRange SignatureSourceRange;
3123
103k
  const Stmt* Body = Signature->getBody();
3124
103k
  if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
3125
101k
    SignatureSourceRange = FD->getSourceRange();
3126
101k
  } else 
if (const auto 2.22k
OD2.22k
= dyn_cast<ObjCMethodDecl>(Signature)) {
3127
2.07k
    SignatureSourceRange = OD->getSourceRange();
3128
2.07k
  } else {
3129
149
    return;
3130
149
  }
3131
103k
  SourceLocation Start = SignatureSourceRange.getBegin();
3132
103k
  SourceLocation End = Body ? 
Body->getSourceRange().getBegin()99.8k
3133
103k
    : 
SignatureSourceRange.getEnd()3.91k
;
3134
103k
  if (!Start.isValid() || !End.isValid())
3135
0
    return;
3136
103k
  unsigned StartLine = SM.getExpansionLineNumber(Start);
3137
103k
  unsigned EndLine = SM.getExpansionLineNumber(End);
3138
3139
103k
  FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
3140
220k
  for (unsigned Line = StartLine; Line <= EndLine; 
Line++116k
)
3141
116k
    ExecutedLines[FID].insert(Line);
3142
103k
}
3143
3144
static void populateExecutedLinesWithStmt(
3145
    const Stmt *S, const SourceManager &SM,
3146
6.31M
    FilesToLineNumsMap &ExecutedLines) {
3147
6.31M
  SourceLocation Loc = S->getSourceRange().getBegin();
3148
6.31M
  if (!Loc.isValid())
3149
7.16k
    return;
3150
6.30M
  SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
3151
6.30M
  FileID FID = SM.getFileID(ExpansionLoc);
3152
6.30M
  unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
3153
6.30M
  ExecutedLines[FID].insert(LineNo);
3154
6.30M
}
3155
3156
/// \return all executed lines including function signatures on the path
3157
/// starting from \p N.
3158
static std::unique_ptr<FilesToLineNumsMap>
3159
40.8k
findExecutedLines(const SourceManager &SM, const ExplodedNode *N) {
3160
40.8k
  auto ExecutedLines = std::make_unique<FilesToLineNumsMap>();
3161
3162
6.73M
  while (N) {
3163
6.69M
    if (N->getFirstPred() == nullptr) {
3164
      // First node: show signature of the entrance point.
3165
40.8k
      const Decl *D = N->getLocationContext()->getDecl();
3166
40.8k
      populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
3167
6.65M
    } else if (auto CE = N->getLocationAs<CallEnter>()) {
3168
      // Inlined function: show signature.
3169
63.0k
      const Decl* D = CE->getCalleeContext()->getDecl();
3170
63.0k
      populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
3171
6.59M
    } else if (const Stmt *S = N->getStmtForDiagnostics()) {
3172
6.27M
      populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
3173
3174
      // Show extra context for some parent kinds.
3175
6.27M
      const Stmt *P = N->getParentMap().getParent(S);
3176
3177
      // The path exploration can die before the node with the associated
3178
      // return statement is generated, but we do want to show the whole
3179
      // return.
3180
6.27M
      if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
3181
35.5k
        populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
3182
35.5k
        P = N->getParentMap().getParent(RS);
3183
35.5k
      }
3184
3185
6.27M
      if (isa_and_nonnull<SwitchCase, LabelStmt>(P))
3186
3.55k
        populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
3187
6.27M
    }
3188
3189
6.69M
    N = N->getFirstPred();
3190
6.69M
  }
3191
40.8k
  return ExecutedLines;
3192
40.8k
}
3193
3194
std::unique_ptr<DiagnosticForConsumerMapTy>
3195
BugReporter::generateDiagnosticForConsumerMap(
3196
    BugReport *exampleReport, ArrayRef<PathDiagnosticConsumer *> consumers,
3197
1.01k
    ArrayRef<BugReport *> bugReports) {
3198
1.01k
  auto *basicReport = cast<BasicBugReport>(exampleReport);
3199
1.01k
  auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
3200
1.01k
  for (auto *Consumer : consumers)
3201
1.03k
    (*Out)[Consumer] = generateDiagnosticForBasicReport(basicReport);
3202
1.01k
  return Out;
3203
1.01k
}
3204
3205
static PathDiagnosticCallPiece *
3206
getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece *CP,
3207
9
                                const SourceManager &SMgr) {
3208
9
  SourceLocation CallLoc = CP->callEnter.asLocation();
3209
3210
  // If the call is within a macro, don't do anything (for now).
3211
9
  if (CallLoc.isMacroID())
3212
3
    return nullptr;
3213
3214
6
  assert(AnalysisManager::isInCodeFile(CallLoc, SMgr) &&
3215
6
         "The call piece should not be in a header file.");
3216
3217
  // Check if CP represents a path through a function outside of the main file.
3218
6
  if (!AnalysisManager::isInCodeFile(CP->callEnterWithin.asLocation(), SMgr))
3219
2
    return CP;
3220
3221
4
  const PathPieces &Path = CP->path;
3222
4
  if (Path.empty())
3223
0
    return nullptr;
3224
3225
  // Check if the last piece in the callee path is a call to a function outside
3226
  // of the main file.
3227
4
  if (auto *CPInner = dyn_cast<PathDiagnosticCallPiece>(Path.back().get()))
3228
2
    return getFirstStackedCallToHeaderFile(CPInner, SMgr);
3229
3230
  // Otherwise, the last piece is in the main file.
3231
2
  return nullptr;
3232
4
}
3233
3234
14
static void resetDiagnosticLocationToMainFile(PathDiagnostic &PD) {
3235
14
  if (PD.path.empty())
3236
7
    return;
3237
3238
7
  PathDiagnosticPiece *LastP = PD.path.back().get();
3239
7
  assert(LastP);
3240
7
  const SourceManager &SMgr = LastP->getLocation().getManager();
3241
3242
  // We only need to check if the report ends inside headers, if the last piece
3243
  // is a call piece.
3244
7
  if (auto *CP = dyn_cast<PathDiagnosticCallPiece>(LastP)) {
3245
7
    CP = getFirstStackedCallToHeaderFile(CP, SMgr);
3246
7
    if (CP) {
3247
      // Mark the piece.
3248
2
       CP->setAsLastInMainSourceFile();
3249
3250
      // Update the path diagnostic message.
3251
2
      const auto *ND = dyn_cast<NamedDecl>(CP->getCallee());
3252
2
      if (ND) {
3253
2
        SmallString<200> buf;
3254
2
        llvm::raw_svector_ostream os(buf);
3255
2
        os << " (within a call to '" << ND->getDeclName() << "')";
3256
2
        PD.appendToDesc(os.str());
3257
2
      }
3258
3259
      // Reset the report containing declaration and location.
3260
2
      PD.setDeclWithIssue(CP->getCaller());
3261
2
      PD.setLocation(CP->getLocation());
3262
3263
2
      return;
3264
2
    }
3265
7
  }
3266
7
}
3267
3268
3269
3270
std::unique_ptr<DiagnosticForConsumerMapTy>
3271
PathSensitiveBugReporter::generateDiagnosticForConsumerMap(
3272
    BugReport *exampleReport, ArrayRef<PathDiagnosticConsumer *> consumers,
3273
21.0k
    ArrayRef<BugReport *> bugReports) {
3274
21.0k
  std::vector<BasicBugReport *> BasicBugReports;
3275
21.0k
  std::vector<PathSensitiveBugReport *> PathSensitiveBugReports;
3276
21.0k
  if (isa<BasicBugReport>(exampleReport))
3277
24
    return BugReporter::generateDiagnosticForConsumerMap(exampleReport,
3278
24
                                                         consumers, bugReports);
3279
3280
  // Generate the full path sensitive diagnostic, using the generation scheme
3281
  // specified by the PathDiagnosticConsumer. Note that we have to generate
3282
  // path diagnostics even for consumers which do not support paths, because
3283
  // the BugReporterVisitors may mark this bug as a false positive.
3284
21.0k
  assert(!bugReports.empty());
3285
21.0k
  MaxBugClassSize.updateMax(bugReports.size());
3286
3287
  // Avoid copying the whole array because there may be a lot of reports.
3288
21.0k
  ArrayRef<PathSensitiveBugReport *> convertedArrayOfReports(
3289
21.0k
      reinterpret_cast<PathSensitiveBugReport *const *>(&*bugReports.begin()),
3290
21.0k
      reinterpret_cast<PathSensitiveBugReport *const *>(&*bugReports.end()));
3291
21.0k
  std::unique_ptr<DiagnosticForConsumerMapTy> Out = generatePathDiagnostics(
3292
21.0k
      consumers, convertedArrayOfReports);
3293
3294
21.0k
  if (Out->empty())
3295
195
    return Out;
3296
3297
20.8k
  MaxValidBugClassSize.updateMax(bugReports.size());
3298
3299
  // Examine the report and see if the last piece is in a header. Reset the
3300
  // report location to the last piece in the main source file.
3301
20.8k
  const AnalyzerOptions &Opts = getAnalyzerOptions();
3302
20.8k
  for (auto const &P : *Out)
3303
21.5k
    if (Opts.ShouldReportIssuesInMainSourceFile && 
!Opts.AnalyzeAll14
)
3304
14
      resetDiagnosticLocationToMainFile(*P.second);
3305
3306
20.8k
  return Out;
3307
21.0k
}
3308
3309
void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3310
                                  const CheckerBase *Checker, StringRef Name,
3311
                                  StringRef Category, StringRef Str,
3312
                                  PathDiagnosticLocation Loc,
3313
                                  ArrayRef<SourceRange> Ranges,
3314
585
                                  ArrayRef<FixItHint> Fixits) {
3315
585
  EmitBasicReport(DeclWithIssue, Checker->getCheckerName(), Name, Category, Str,
3316
585
                  Loc, Ranges, Fixits);
3317
585
}
3318
3319
void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3320
                                  CheckerNameRef CheckName,
3321
                                  StringRef name, StringRef category,
3322
                                  StringRef str, PathDiagnosticLocation Loc,
3323
                                  ArrayRef<SourceRange> Ranges,
3324
908
                                  ArrayRef<FixItHint> Fixits) {
3325
  // 'BT' is owned by BugReporter.
3326
908
  BugType *BT = getBugTypeForName(CheckName, name, category);
3327
908
  auto R = std::make_unique<BasicBugReport>(*BT, str, Loc);
3328
908
  R->setDeclWithIssue(DeclWithIssue);
3329
908
  for (const auto &SR : Ranges)
3330
819
    R->addRange(SR);
3331
908
  for (const auto &FH : Fixits)
3332
10
    R->addFixItHint(FH);
3333
908
  emitReport(std::move(R));
3334
908
}
3335
3336
BugType *BugReporter::getBugTypeForName(CheckerNameRef CheckName,
3337
908
                                        StringRef name, StringRef category) {
3338
908
  SmallString<136> fullDesc;
3339
908
  llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
3340
908
                                      << ":" << category;
3341
908
  std::unique_ptr<BugType> &BT = StrBugTypes[fullDesc];
3342
908
  if (!BT)
3343
564
    BT = std::make_unique<BugType>(CheckName, name, category);
3344
908
  return BT.get();
3345
908
}