Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- BugReporterVisitors.cpp - Helpers for reporting 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 a set of BugReporter "visitors" which can be used to
10
//  enhance the diagnostics reported for a bug.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/Decl.h"
17
#include "clang/AST/DeclBase.h"
18
#include "clang/AST/DeclCXX.h"
19
#include "clang/AST/Expr.h"
20
#include "clang/AST/ExprCXX.h"
21
#include "clang/AST/ExprObjC.h"
22
#include "clang/AST/Stmt.h"
23
#include "clang/AST/Type.h"
24
#include "clang/ASTMatchers/ASTMatchFinder.h"
25
#include "clang/Analysis/Analyses/Dominators.h"
26
#include "clang/Analysis/AnalysisDeclContext.h"
27
#include "clang/Analysis/CFG.h"
28
#include "clang/Analysis/CFGStmtMap.h"
29
#include "clang/Analysis/PathDiagnostic.h"
30
#include "clang/Analysis/ProgramPoint.h"
31
#include "clang/Basic/IdentifierTable.h"
32
#include "clang/Basic/LLVM.h"
33
#include "clang/Basic/SourceLocation.h"
34
#include "clang/Basic/SourceManager.h"
35
#include "clang/Lex/Lexer.h"
36
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
37
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
38
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
39
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
40
#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
41
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
42
#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
43
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
44
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
45
#include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
46
#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
47
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
48
#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
49
#include "llvm/ADT/ArrayRef.h"
50
#include "llvm/ADT/None.h"
51
#include "llvm/ADT/Optional.h"
52
#include "llvm/ADT/STLExtras.h"
53
#include "llvm/ADT/SmallPtrSet.h"
54
#include "llvm/ADT/SmallString.h"
55
#include "llvm/ADT/SmallVector.h"
56
#include "llvm/ADT/StringExtras.h"
57
#include "llvm/ADT/StringRef.h"
58
#include "llvm/Support/Casting.h"
59
#include "llvm/Support/ErrorHandling.h"
60
#include "llvm/Support/raw_ostream.h"
61
#include <cassert>
62
#include <deque>
63
#include <memory>
64
#include <string>
65
#include <utility>
66
67
using namespace clang;
68
using namespace ento;
69
70
//===----------------------------------------------------------------------===//
71
// Utility functions.
72
//===----------------------------------------------------------------------===//
73
74
373
static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
75
373
  if (B->isAdditiveOp() && 
B->getType()->isPointerType()67
) {
76
23
    if (B->getLHS()->getType()->isPointerType()) {
77
22
      return B->getLHS();
78
22
    } else 
if (1
B->getRHS()->getType()->isPointerType()1
) {
79
1
      return B->getRHS();
80
1
    }
81
350
  }
82
350
  return nullptr;
83
350
}
84
85
/// Given that expression S represents a pointer that would be dereferenced,
86
/// try to find a sub-expression from which the pointer came from.
87
/// This is used for tracking down origins of a null or undefined value:
88
/// "this is null because that is null because that is null" etc.
89
/// We wipe away field and element offsets because they merely add offsets.
90
/// We also wipe away all casts except lvalue-to-rvalue casts, because the
91
/// latter represent an actual pointer dereference; however, we remove
92
/// the final lvalue-to-rvalue cast before returning from this function
93
/// because it demonstrates more clearly from where the pointer rvalue was
94
/// loaded. Examples:
95
///   x->y.z      ==>  x (lvalue)
96
///   foo()->y.z  ==>  foo() (rvalue)
97
900
const Expr *bugreporter::getDerefExpr(const Stmt *S) {
98
900
  const auto *E = dyn_cast<Expr>(S);
99
900
  if (!E)
100
0
    return nullptr;
101
900
102
1.95k
  
while (900
true) {
103
1.95k
    if (const auto *CE = dyn_cast<CastExpr>(E)) {
104
887
      if (CE->getCastKind() == CK_LValueToRValue) {
105
784
        // This cast represents the load we're looking for.
106
784
        break;
107
784
      }
108
103
      E = CE->getSubExpr();
109
1.06k
    } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
110
14
      // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
111
14
      if (const Expr *Inner = peelOffPointerArithmetic(B)) {
112
12
        E = Inner;
113
12
      } else {
114
2
        // Probably more arithmetic can be pattern-matched here,
115
2
        // but for now give up.
116
2
        break;
117
2
      }
118
1.05k
    } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
119
813
      if (U->getOpcode() == UO_Deref || 
U->getOpcode() == UO_AddrOf8
||
120
813
          
(4
U->isIncrementDecrementOp()4
&&
U->getType()->isPointerType()4
)) {
121
813
        // Operators '*' and '&' don't actually mean anything.
122
813
        // We look at casts instead.
123
813
        E = U->getSubExpr();
124
813
      } else {
125
0
        // Probably more arithmetic can be pattern-matched here,
126
0
        // but for now give up.
127
0
        break;
128
0
      }
129
240
    }
130
240
    // Pattern match for a few useful cases: a[0], p->f, *p etc.
131
240
    else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
132
34
      E = ME->getBase();
133
206
    } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
134
16
      E = IvarRef->getBase();
135
190
    } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
136
32
      E = AE->getBase();
137
158
    } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
138
43
      E = PE->getSubExpr();
139
115
    } else if (const auto *FE = dyn_cast<FullExpr>(E)) {
140
1
      E = FE->getSubExpr();
141
114
    } else {
142
114
      // Other arbitrary stuff.
143
114
      break;
144
114
    }
145
1.95k
  }
146
900
147
900
  // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
148
900
  // deeper into the sub-expression. This way we return the lvalue from which
149
900
  // our pointer rvalue was loaded.
150
900
  if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
151
784
    if (CE->getCastKind() == CK_LValueToRValue)
152
784
      E = CE->getSubExpr();
153
900
154
900
  return E;
155
900
}
156
157
/// Comparing internal representations of symbolic values (via
158
/// SVal::operator==()) is a valid way to check if the value was updated,
159
/// unless it's a LazyCompoundVal that may have a different internal
160
/// representation every time it is loaded from the state. In this function we
161
/// do an approximate comparison for lazy compound values, checking that they
162
/// are the immediate snapshots of the tracked region's bindings within the
163
/// node's respective states but not really checking that these snapshots
164
/// actually contain the same set of bindings.
165
static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
166
53.9k
                             const ExplodedNode *RightNode, SVal RightVal) {
167
53.9k
  if (LeftVal == RightVal)
168
53.4k
    return true;
169
525
170
525
  const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>();
171
525
  if (!LLCV)
172
504
    return false;
173
21
174
21
  const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>();
175
21
  if (!RLCV)
176
0
    return false;
177
21
178
21
  return LLCV->getRegion() == RLCV->getRegion() &&
179
21
    LLCV->getStore() == LeftNode->getState()->getStore() &&
180
21
    RLCV->getStore() == RightNode->getState()->getStore();
181
21
}
182
183
static Optional<SVal> getSValForVar(const Expr *CondVarExpr,
184
1.74k
                                    const ExplodedNode *N) {
185
1.74k
  ProgramStateRef State = N->getState();
186
1.74k
  const LocationContext *LCtx = N->getLocationContext();
187
1.74k
188
1.74k
  assert(CondVarExpr);
189
1.74k
  CondVarExpr = CondVarExpr->IgnoreImpCasts();
190
1.74k
191
1.74k
  // The declaration of the value may rely on a pointer so take its l-value.
192
1.74k
  // FIXME: As seen in VisitCommonDeclRefExpr, sometimes DeclRefExpr may
193
1.74k
  // evaluate to a FieldRegion when it refers to a declaration of a lambda
194
1.74k
  // capture variable. We most likely need to duplicate that logic here.
195
1.74k
  if (const auto *DRE = dyn_cast<DeclRefExpr>(CondVarExpr))
196
1.35k
    if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
197
1.35k
      return State->getSVal(State->getLValue(VD, LCtx));
198
383
199
383
  if (const auto *ME = dyn_cast<MemberExpr>(CondVarExpr))
200
253
    if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
201
253
      if (auto FieldL = State->getSVal(ME, LCtx).getAs<Loc>())
202
253
        return State->getRawSVal(*FieldL, FD->getType());
203
130
204
130
  return None;
205
130
}
206
207
static Optional<const llvm::APSInt *>
208
372
getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N) {
209
372
210
372
  if (Optional<SVal> V = getSValForVar(CondVarExpr, N))
211
372
    if (auto CI = V->getAs<nonloc::ConcreteInt>())
212
145
      return &CI->getValue();
213
227
  return None;
214
227
}
215
216
static bool isVarAnInterestingCondition(const Expr *CondVarExpr,
217
                                        const ExplodedNode *N,
218
4.21k
                                        const PathSensitiveBugReport *B) {
219
4.21k
  // Even if this condition is marked as interesting, it isn't *that*
220
4.21k
  // interesting if it didn't happen in a nested stackframe, the user could just
221
4.21k
  // follow the arrows.
222
4.21k
  if (!B->getErrorNode()->getStackFrame()->isParentOf(N->getStackFrame()))
223
3.71k
    return false;
224
507
225
507
  if (Optional<SVal> V = getSValForVar(CondVarExpr, N))
226
377
    if (Optional<bugreporter::TrackingKind> K = B->getInterestingnessKind(*V))
227
79
      return *K == bugreporter::TrackingKind::Condition;
228
428
229
428
  return false;
230
428
}
231
232
static bool isInterestingExpr(const Expr *E, const ExplodedNode *N,
233
861
                              const PathSensitiveBugReport *B) {
234
861
  if (Optional<SVal> V = getSValForVar(E, N))
235
861
    return B->getInterestingnessKind(*V).hasValue();
236
0
  return false;
237
0
}
238
239
/// \return name of the macro inside the location \p Loc.
240
static StringRef getMacroName(SourceLocation Loc,
241
33
    BugReporterContext &BRC) {
242
33
  return Lexer::getImmediateMacroName(
243
33
      Loc,
244
33
      BRC.getSourceManager(),
245
33
      BRC.getASTContext().getLangOpts());
246
33
}
247
248
/// \return Whether given spelling location corresponds to an expansion
249
/// of a function-like macro.
250
static bool isFunctionMacroExpansion(SourceLocation Loc,
251
830
                                const SourceManager &SM) {
252
830
  if (!Loc.isMacroID())
253
650
    return false;
254
180
  while (SM.isMacroArgExpansion(Loc))
255
0
    Loc = SM.getImmediateExpansionRange(Loc).getBegin();
256
180
  std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
257
180
  SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
258
180
  const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
259
180
  return EInfo.isFunctionMacroExpansion();
260
180
}
261
262
/// \return Whether \c RegionOfInterest was modified at \p N,
263
/// where \p ValueAfter is \c RegionOfInterest's value at the end of the
264
/// stack frame.
265
static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest,
266
                                          const ExplodedNode *N,
267
36.1k
                                          SVal ValueAfter) {
268
36.1k
  ProgramStateRef State = N->getState();
269
36.1k
  ProgramStateManager &Mgr = N->getState()->getStateManager();
270
36.1k
271
36.1k
  if (!N->getLocationAs<PostStore>() && 
!N->getLocationAs<PostInitializer>()35.0k
&&
272
36.1k
      
!N->getLocationAs<PostStmt>()34.9k
)
273
14.7k
    return false;
274
21.4k
275
21.4k
  // Writing into region of interest.
276
21.4k
  if (auto PS = N->getLocationAs<PostStmt>())
277
21.3k
    if (auto *BO = PS->getStmtAs<BinaryOperator>())
278
1.89k
      if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
279
1.46k
                                      N->getSVal(BO->getLHS()).getAsRegion()))
280
392
        return true;
281
21.0k
282
21.0k
  // SVal after the state is possibly different.
283
21.0k
  SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
284
21.0k
  if (!Mgr.getSValBuilder()
285
21.0k
           .areEqual(State, ValueAtN, ValueAfter)
286
21.0k
           .isConstrainedTrue() &&
287
21.0k
      
(6.45k
!ValueAtN.isUndef()6.45k
||
!ValueAfter.isUndef()5.63k
))
288
1.88k
    return true;
289
19.1k
290
19.1k
  return false;
291
19.1k
}
292
293
//===----------------------------------------------------------------------===//
294
// Implementation of BugReporterVisitor.
295
//===----------------------------------------------------------------------===//
296
297
PathDiagnosticPieceRef BugReporterVisitor::getEndPath(BugReporterContext &,
298
                                                      const ExplodedNode *,
299
61.3k
                                                      PathSensitiveBugReport &) {
300
61.3k
  return nullptr;
301
61.3k
}
302
303
void BugReporterVisitor::finalizeVisitor(BugReporterContext &,
304
                                         const ExplodedNode *,
305
50.2k
                                         PathSensitiveBugReport &) {}
306
307
PathDiagnosticPieceRef
308
BugReporterVisitor::getDefaultEndPath(const BugReporterContext &BRC,
309
                                      const ExplodedNode *EndPathNode,
310
1.39k
                                      const PathSensitiveBugReport &BR) {
311
1.39k
  PathDiagnosticLocation L = BR.getLocation();
312
1.39k
  const auto &Ranges = BR.getRanges();
313
1.39k
314
1.39k
  // Only add the statement itself as a range if we didn't specify any
315
1.39k
  // special ranges for this report.
316
1.39k
  auto P = std::make_shared<PathDiagnosticEventPiece>(
317
1.39k
      L, BR.getDescription(), Ranges.begin() == Ranges.end());
318
1.39k
  for (SourceRange Range : Ranges)
319
1.33k
    P->addRange(Range);
320
1.39k
321
1.39k
  return P;
322
1.39k
}
323
324
//===----------------------------------------------------------------------===//
325
// Implementation of NoStoreFuncVisitor.
326
//===----------------------------------------------------------------------===//
327
328
namespace {
329
330
/// Put a diagnostic on return statement of all inlined functions
331
/// for which  the region of interest \p RegionOfInterest was passed into,
332
/// but not written inside, and it has caused an undefined read or a null
333
/// pointer dereference outside.
334
class NoStoreFuncVisitor final : public BugReporterVisitor {
335
  const SubRegion *RegionOfInterest;
336
  MemRegionManager &MmrMgr;
337
  const SourceManager &SM;
338
  const PrintingPolicy &PP;
339
  bugreporter::TrackingKind TKind;
340
341
  /// Recursion limit for dereferencing fields when looking for the
342
  /// region of interest.
343
  /// The limit of two indicates that we will dereference fields only once.
344
  static const unsigned DEREFERENCE_LIMIT = 2;
345
346
  /// Frames writing into \c RegionOfInterest.
347
  /// This visitor generates a note only if a function does not write into
348
  /// a region of interest. This information is not immediately available
349
  /// by looking at the node associated with the exit from the function
350
  /// (usually the return statement). To avoid recomputing the same information
351
  /// many times (going up the path for each node and checking whether the
352
  /// region was written into) we instead lazily compute the
353
  /// stack frames along the path which write into the region of interest.
354
  llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
355
  llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
356
357
  using RegionVector = SmallVector<const MemRegion *, 5>;
358
359
public:
360
  NoStoreFuncVisitor(const SubRegion *R, bugreporter::TrackingKind TKind)
361
      : RegionOfInterest(R), MmrMgr(R->getMemRegionManager()),
362
        SM(MmrMgr.getContext().getSourceManager()),
363
2.31k
        PP(MmrMgr.getContext().getPrintingPolicy()), TKind(TKind) {}
364
365
2.31k
  void Profile(llvm::FoldingSetNodeID &ID) const override {
366
2.31k
    static int Tag = 0;
367
2.31k
    ID.AddPointer(&Tag);
368
2.31k
    ID.AddPointer(RegionOfInterest);
369
2.31k
  }
370
371
1
  void *getTag() const {
372
1
    static int Tag = 0;
373
1
    return static_cast<void *>(&Tag);
374
1
  }
375
376
  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
377
                                   BugReporterContext &BR,
378
                                   PathSensitiveBugReport &R) override;
379
380
private:
381
  /// Attempts to find the region of interest in a given record decl,
382
  /// by either following the base classes or fields.
383
  /// Dereferences fields up to a given recursion limit.
384
  /// Note that \p Vec is passed by value, leading to quadratic copying cost,
385
  /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
386
  /// \return A chain fields leading to the region of interest or None.
387
  const Optional<RegionVector>
388
  findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
389
                               const MemRegion *R, const RegionVector &Vec = {},
390
                               int depth = 0);
391
392
  /// Check and lazily calculate whether the region of interest is
393
  /// modified in the stack frame to which \p N belongs.
394
  /// The calculation is cached in FramesModifyingRegion.
395
1.08k
  bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
396
1.08k
    const LocationContext *Ctx = N->getLocationContext();
397
1.08k
    const StackFrameContext *SCtx = Ctx->getStackFrame();
398
1.08k
    if (!FramesModifyingCalculated.count(SCtx))
399
945
      findModifyingFrames(N);
400
1.08k
    return FramesModifyingRegion.count(SCtx);
401
1.08k
  }
402
403
  /// Write to \c FramesModifyingRegion all stack frames along
404
  /// the path in the current stack frame which modify \c RegionOfInterest.
405
  void findModifyingFrames(const ExplodedNode *N);
406
407
  /// Consume the information on the no-store stack frame in order to
408
  /// either emit a note or suppress the report enirely.
409
  /// \return Diagnostics piece for region not modified in the current function,
410
  /// if it decides to emit one.
411
  PathDiagnosticPieceRef
412
  maybeEmitNote(PathSensitiveBugReport &R, const CallEvent &Call,
413
                const ExplodedNode *N, const RegionVector &FieldChain,
414
                const MemRegion *MatchedRegion, StringRef FirstElement,
415
                bool FirstIsReferenceType, unsigned IndirectionLevel);
416
417
  /// Pretty-print region \p MatchedRegion to \p os.
418
  /// \return Whether printing succeeded.
419
  bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType,
420
                             const MemRegion *MatchedRegion,
421
                             const RegionVector &FieldChain,
422
                             int IndirectionLevel,
423
                             llvm::raw_svector_ostream &os);
424
425
  /// Print first item in the chain, return new separator.
426
  static StringRef prettyPrintFirstElement(StringRef FirstElement,
427
                                           bool MoreItemsExpected,
428
                                           int IndirectionLevel,
429
                                           llvm::raw_svector_ostream &os);
430
};
431
432
} // end of anonymous namespace
433
434
/// \return Whether the method declaration \p Parent
435
/// syntactically has a binary operation writing into the ivar \p Ivar.
436
static bool potentiallyWritesIntoIvar(const Decl *Parent,
437
9
                                      const ObjCIvarDecl *Ivar) {
438
9
  using namespace ast_matchers;
439
9
  const char *IvarBind = "Ivar";
440
9
  if (!Parent || !Parent->hasBody())
441
0
    return false;
442
9
  StatementMatcher WriteIntoIvarM = binaryOperator(
443
9
      hasOperatorName("="),
444
9
      hasLHS(ignoringParenImpCasts(
445
9
          objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
446
9
  StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
447
9
  auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
448
9
  for (BoundNodes &Match : Matches) {
449
2
    auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
450
2
    if (IvarRef->isFreeIvar())
451
1
      return true;
452
1
453
1
    const Expr *Base = IvarRef->getBase();
454
1
    if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
455
1
      Base = ICE->getSubExpr();
456
1
457
1
    if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
458
1
      if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
459
1
        if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
460
1
          return true;
461
0
462
0
    return false;
463
0
  }
464
9
  
return false7
;
465
9
}
466
467
/// Get parameters associated with runtime definition in order
468
/// to get the correct parameter name.
469
769
static ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
470
769
  // Use runtime definition, if available.
471
769
  RuntimeDefinition RD = Call->getRuntimeDefinition();
472
769
  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
473
659
    return FD->parameters();
474
110
  if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl()))
475
107
    return MD->parameters();
476
3
477
3
  return Call->parameters();
478
3
}
479
480
/// \return whether \p Ty points to a const type, or is a const reference.
481
44
static bool isPointerToConst(QualType Ty) {
482
44
  return !Ty->getPointeeType().isNull() &&
483
44
         Ty->getPointeeType().getCanonicalType().isConstQualified();
484
44
}
485
486
/// Attempts to find the region of interest in a given CXX decl,
487
/// by either following the base classes or fields.
488
/// Dereferences fields up to a given recursion limit.
489
/// Note that \p Vec is passed by value, leading to quadratic copying cost,
490
/// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
491
/// \return A chain fields leading to the region of interest or None.
492
const Optional<NoStoreFuncVisitor::RegionVector>
493
NoStoreFuncVisitor::findRegionOfInterestInRecord(
494
    const RecordDecl *RD, ProgramStateRef State, const MemRegion *R,
495
    const NoStoreFuncVisitor::RegionVector &Vec /* = {} */,
496
63
    int depth /* = 0 */) {
497
63
498
63
  if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
499
5
    return None;
500
58
501
58
  if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
502
57
    if (!RDX->hasDefinition())
503
0
      return None;
504
58
505
58
  // Recursively examine the base classes.
506
58
  // Note that following base classes does not increase the recursion depth.
507
58
  if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
508
57
    for (const auto &II : RDX->bases())
509
1
      if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
510
1
        if (Optional<RegionVector> Out =
511
1
                findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
512
1
          return Out;
513
58
514
60
  
for (const FieldDecl *I : RD->fields())57
{
515
60
    QualType FT = I->getType();
516
60
    const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
517
60
    const SVal V = State->getSVal(FR);
518
60
    const MemRegion *VR = V.getAsRegion();
519
60
520
60
    RegionVector VecF = Vec;
521
60
    VecF.push_back(FR);
522
60
523
60
    if (RegionOfInterest == VR)
524
10
      return VecF;
525
50
526
50
    if (const RecordDecl *RRD = FT->getAsRecordDecl())
527
13
      if (auto Out =
528
1
              findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
529
1
        return Out;
530
49
531
49
    QualType PT = FT->getPointeeType();
532
49
    if (PT.isNull() || 
PT->isVoidType()8
||
!VR8
)
533
41
      continue;
534
8
535
8
    if (const RecordDecl *RRD = PT->getAsRecordDecl())
536
4
      if (Optional<RegionVector> Out =
537
3
              findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
538
3
        return Out;
539
8
  }
540
57
541
57
  
return None43
;
542
57
}
543
544
PathDiagnosticPieceRef
545
NoStoreFuncVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BR,
546
98.3k
                              PathSensitiveBugReport &R) {
547
98.3k
548
98.3k
  const LocationContext *Ctx = N->getLocationContext();
549
98.3k
  const StackFrameContext *SCtx = Ctx->getStackFrame();
550
98.3k
  ProgramStateRef State = N->getState();
551
98.3k
  auto CallExitLoc = N->getLocationAs<CallExitBegin>();
552
98.3k
553
98.3k
  // No diagnostic if region was modified inside the frame.
554
98.3k
  if (!CallExitLoc || 
isRegionOfInterestModifiedInFrame(N)1.08k
)
555
97.3k
    return nullptr;
556
916
557
916
  CallEventRef<> Call =
558
916
      BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
559
916
560
916
  // Region of interest corresponds to an IVar, exiting a method
561
916
  // which could have written into that IVar, but did not.
562
916
  if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
563
109
    if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
564
10
      const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion();
565
10
      if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
566
10
          potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
567
9
                                    IvarR->getDecl()))
568
2
        return maybeEmitNote(R, *Call, N, {}, SelfRegion, "self",
569
2
                             /*FirstIsReferenceType=*/false, 1);
570
914
    }
571
109
  }
572
914
573
914
  if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
574
145
    const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
575
145
    if (RegionOfInterest->isSubRegionOf(ThisR) &&
576
145
        
!CCall->getDecl()->isImplicit()50
)
577
27
      return maybeEmitNote(R, *Call, N, {}, ThisR, "this",
578
27
                           /*FirstIsReferenceType=*/false, 1);
579
118
580
118
    // Do not generate diagnostics for not modified parameters in
581
118
    // constructors.
582
118
    return nullptr;
583
118
  }
584
769
585
769
  ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
586
1.17k
  for (unsigned I = 0; I < Call->getNumArgs() && 
I < parameters.size()463
;
++I410
) {
587
462
    const ParmVarDecl *PVD = parameters[I];
588
462
    SVal V = Call->getArgSVal(I);
589
462
    bool ParamIsReferenceType = PVD->getType()->isReferenceType();
590
462
    std::string ParamName = PVD->getNameAsString();
591
462
592
462
    int IndirectionLevel = 1;
593
462
    QualType T = PVD->getType();
594
565
    while (const MemRegion *MR = V.getAsRegion()) {
595
229
      if (RegionOfInterest->isSubRegionOf(MR) && 
!isPointerToConst(T)44
)
596
42
        return maybeEmitNote(R, *Call, N, {}, MR, ParamName,
597
42
                             ParamIsReferenceType, IndirectionLevel);
598
187
599
187
      QualType PT = T->getPointeeType();
600
187
      if (PT.isNull() || 
PT->isVoidType()181
)
601
74
        break;
602
113
603
113
      if (const RecordDecl *RD = PT->getAsRecordDecl())
604
45
        if (Optional<RegionVector> P =
605
10
                findRegionOfInterestInRecord(RD, State, MR))
606
10
          return maybeEmitNote(R, *Call, N, *P, RegionOfInterest, ParamName,
607
10
                               ParamIsReferenceType, IndirectionLevel);
608
103
609
103
      V = State->getSVal(MR, PT);
610
103
      T = PT;
611
103
      IndirectionLevel++;
612
103
    }
613
462
  }
614
769
615
769
  
return nullptr717
;
616
769
}
617
618
945
void NoStoreFuncVisitor::findModifyingFrames(const ExplodedNode *N) {
619
945
  assert(N->getLocationAs<CallExitBegin>());
620
945
  ProgramStateRef LastReturnState = N->getState();
621
945
  SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
622
945
  const LocationContext *Ctx = N->getLocationContext();
623
945
  const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
624
945
625
22.8k
  do {
626
22.8k
    ProgramStateRef State = N->getState();
627
22.8k
    auto CallExitLoc = N->getLocationAs<CallExitBegin>();
628
22.8k
    if (CallExitLoc) {
629
1.08k
      LastReturnState = State;
630
1.08k
      ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
631
1.08k
    }
632
22.8k
633
22.8k
    FramesModifyingCalculated.insert(N->getLocationContext()->getStackFrame());
634
22.8k
635
22.8k
    if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
636
1.50k
      const StackFrameContext *SCtx = N->getStackFrame();
637
1.68k
      while (!SCtx->inTopFrame()) {
638
1.53k
        auto p = FramesModifyingRegion.insert(SCtx);
639
1.53k
        if (!p.second)
640
1.35k
          break; // Frame and all its parents already inserted.
641
181
        SCtx = SCtx->getParent()->getStackFrame();
642
181
      }
643
1.50k
    }
644
22.8k
645
22.8k
    // Stop calculation at the call to the current function.
646
22.8k
    if (auto CE = N->getLocationAs<CallEnter>())
647
1.08k
      if (CE->getCalleeContext() == OriginalSCtx)
648
945
        break;
649
21.8k
650
21.8k
    N = N->getFirstPred();
651
21.8k
  } while (N);
652
945
}
653
654
static llvm::StringLiteral WillBeUsedForACondition =
655
    ", which participates in a condition later";
656
657
PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNote(
658
    PathSensitiveBugReport &R, const CallEvent &Call, const ExplodedNode *N,
659
    const RegionVector &FieldChain, const MemRegion *MatchedRegion,
660
    StringRef FirstElement, bool FirstIsReferenceType,
661
81
    unsigned IndirectionLevel) {
662
81
  // Optimistically suppress uninitialized value bugs that result
663
81
  // from system headers having a chance to initialize the value
664
81
  // but failing to do so. It's too unlikely a system header's fault.
665
81
  // It's much more likely a situation in which the function has a failure
666
81
  // mode that the user decided not to check. If we want to hunt such
667
81
  // omitted checks, we should provide an explicit function-specific note
668
81
  // describing the precondition under which the function isn't supposed to
669
81
  // initialize its out-parameter, and additionally check that such
670
81
  // precondition can actually be fulfilled on the current path.
671
81
  if (Call.isInSystemHeader()) {
672
5
    // We make an exception for system header functions that have no branches.
673
5
    // Such functions unconditionally fail to initialize the variable.
674
5
    // If they call other functions that have more paths within them,
675
5
    // this suppression would still apply when we visit these inner functions.
676
5
    // One common example of a standard function that doesn't ever initialize
677
5
    // its out parameter is operator placement new; it's up to the follow-up
678
5
    // constructor (if any) to initialize the memory.
679
5
    if (!N->getStackFrame()->getCFG()->isLinear())
680
1
      R.markInvalid(getTag(), nullptr);
681
5
    return nullptr;
682
5
  }
683
76
684
76
  PathDiagnosticLocation L =
685
76
      PathDiagnosticLocation::create(N->getLocation(), SM);
686
76
687
76
  // For now this shouldn't trigger, but once it does (as we add more
688
76
  // functions to the body farm), we'll need to decide if these reports
689
76
  // are worth suppressing as well.
690
76
  if (!L.hasValidLocation())
691
0
    return nullptr;
692
76
693
76
  SmallString<256> sbuf;
694
76
  llvm::raw_svector_ostream os(sbuf);
695
76
  os << "Returning without writing to '";
696
76
697
76
  // Do not generate the note if failed to pretty-print.
698
76
  if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType, MatchedRegion,
699
76
                             FieldChain, IndirectionLevel, os))
700
1
    return nullptr;
701
75
702
75
  os << "'";
703
75
  if (TKind == bugreporter::TrackingKind::Condition)
704
0
    os << WillBeUsedForACondition;
705
75
  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
706
75
}
707
708
bool NoStoreFuncVisitor::prettyPrintRegionName(StringRef FirstElement,
709
                                               bool FirstIsReferenceType,
710
                                               const MemRegion *MatchedRegion,
711
                                               const RegionVector &FieldChain,
712
                                               int IndirectionLevel,
713
76
                                               llvm::raw_svector_ostream &os) {
714
76
715
76
  if (FirstIsReferenceType)
716
21
    IndirectionLevel--;
717
76
718
76
  RegionVector RegionSequence;
719
76
720
76
  // Add the regions in the reverse order, then reverse the resulting array.
721
76
  assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
722
76
  const MemRegion *R = RegionOfInterest;
723
135
  while (R != MatchedRegion) {
724
59
    RegionSequence.push_back(R);
725
59
    R = cast<SubRegion>(R)->getSuperRegion();
726
59
  }
727
76
  std::reverse(RegionSequence.begin(), RegionSequence.end());
728
76
  RegionSequence.append(FieldChain.begin(), FieldChain.end());
729
76
730
76
  StringRef Sep;
731
76
  for (const MemRegion *R : RegionSequence) {
732
72
733
72
    // Just keep going up to the base region.
734
72
    // Element regions may appear due to casts.
735
72
    if (isa<CXXBaseObjectRegion>(R) || 
isa<CXXTempObjectRegion>(R)67
)
736
5
      continue;
737
67
738
67
    if (Sep.empty())
739
58
      Sep = prettyPrintFirstElement(FirstElement,
740
58
                                    /*MoreItemsExpected=*/true,
741
58
                                    IndirectionLevel, os);
742
67
743
67
    os << Sep;
744
67
745
67
    // Can only reasonably pretty-print DeclRegions.
746
67
    if (!isa<DeclRegion>(R))
747
1
      return false;
748
66
749
66
    const auto *DR = cast<DeclRegion>(R);
750
66
    Sep = DR->getValueType()->isAnyPointerType() ? 
"->"9
:
"."57
;
751
66
    DR->getDecl()->getDeclName().print(os, PP);
752
66
  }
753
76
754
76
  
if (75
Sep.empty()75
)
755
18
    prettyPrintFirstElement(FirstElement,
756
18
                            /*MoreItemsExpected=*/false, IndirectionLevel, os);
757
75
  return true;
758
76
}
759
760
StringRef NoStoreFuncVisitor::prettyPrintFirstElement(
761
    StringRef FirstElement, bool MoreItemsExpected, int IndirectionLevel,
762
76
    llvm::raw_svector_ostream &os) {
763
76
  StringRef Out = ".";
764
76
765
76
  if (IndirectionLevel > 0 && 
MoreItemsExpected56
) {
766
41
    IndirectionLevel--;
767
41
    Out = "->";
768
41
  }
769
76
770
76
  if (IndirectionLevel > 0 && 
MoreItemsExpected16
)
771
1
    os << "(";
772
76
773
93
  for (int i = 0; i < IndirectionLevel; 
i++17
)
774
17
    os << "*";
775
76
  os << FirstElement;
776
76
777
76
  if (IndirectionLevel > 0 && 
MoreItemsExpected16
)
778
1
    os << ")";
779
76
780
76
  return Out;
781
76
}
782
783
//===----------------------------------------------------------------------===//
784
// Implementation of MacroNullReturnSuppressionVisitor.
785
//===----------------------------------------------------------------------===//
786
787
namespace {
788
789
/// Suppress null-pointer-dereference bugs where dereferenced null was returned
790
/// the macro.
791
class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
792
  const SubRegion *RegionOfInterest;
793
  const SVal ValueAtDereference;
794
795
  // Do not invalidate the reports where the value was modified
796
  // after it got assigned to from the macro.
797
  bool WasModified = false;
798
799
public:
800
  MacroNullReturnSuppressionVisitor(const SubRegion *R, const SVal V)
801
1.06k
      : RegionOfInterest(R), ValueAtDereference(V) {}
802
803
  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
804
                                   BugReporterContext &BRC,
805
38.6k
                                   PathSensitiveBugReport &BR) override {
806
38.6k
    if (WasModified)
807
25.1k
      return nullptr;
808
13.5k
809
13.5k
    auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
810
13.5k
    if (!BugPoint)
811
152
      return nullptr;
812
13.3k
813
13.3k
    const SourceManager &SMgr = BRC.getSourceManager();
814
13.3k
    if (auto Loc = matchAssignment(N)) {
815
830
      if (isFunctionMacroExpansion(*Loc, SMgr)) {
816
8
        std::string MacroName = std::string(getMacroName(*Loc, BRC));
817
8
        SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
818
8
        if (!BugLoc.isMacroID() || 
getMacroName(BugLoc, BRC) != MacroName3
)
819
5
          BR.markInvalid(getTag(), MacroName.c_str());
820
8
      }
821
830
    }
822
13.3k
823
13.3k
    if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
824
778
      WasModified = true;
825
13.3k
826
13.3k
    return nullptr;
827
13.3k
  }
828
829
  static void addMacroVisitorIfNecessary(
830
        const ExplodedNode *N, const MemRegion *R,
831
        bool EnableNullFPSuppression, PathSensitiveBugReport &BR,
832
2.31k
        const SVal V) {
833
2.31k
    AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
834
2.31k
    if (EnableNullFPSuppression &&
835
2.31k
        
Options.ShouldSuppressNullReturnPaths1.81k
&&
V.getAs<Loc>()1.69k
)
836
1.06k
      BR.addVisitor(std::make_unique<MacroNullReturnSuppressionVisitor>(
837
1.06k
              R->getAs<SubRegion>(), V));
838
2.31k
  }
839
840
1.07k
  void* getTag() const {
841
1.07k
    static int Tag = 0;
842
1.07k
    return static_cast<void *>(&Tag);
843
1.07k
  }
844
845
1.06k
  void Profile(llvm::FoldingSetNodeID &ID) const override {
846
1.06k
    ID.AddPointer(getTag());
847
1.06k
  }
848
849
private:
850
  /// \return Source location of right hand side of an assignment
851
  /// into \c RegionOfInterest, empty optional if none found.
852
13.3k
  Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
853
13.3k
    const Stmt *S = N->getStmtForDiagnostics();
854
13.3k
    ProgramStateRef State = N->getState();
855
13.3k
    auto *LCtx = N->getLocationContext();
856
13.3k
    if (!S)
857
1.03k
      return None;
858
12.3k
859
12.3k
    if (const auto *DS = dyn_cast<DeclStmt>(S)) {
860
1.11k
      if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
861
1.11k
        if (const Expr *RHS = VD->getInit())
862
1.07k
          if (RegionOfInterest->isSubRegionOf(
863
1.07k
                  State->getLValue(VD, LCtx).getAsRegion()))
864
760
            return RHS->getBeginLoc();
865
11.2k
    } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
866
990
      const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
867
990
      const Expr *RHS = BO->getRHS();
868
990
      if (BO->isAssignmentOp() && 
RegionOfInterest->isSubRegionOf(R)762
) {
869
70
        return RHS->getBeginLoc();
870
70
      }
871
11.4k
    }
872
11.4k
    return None;
873
11.4k
  }
874
};
875
876
} // end of anonymous namespace
877
878
namespace {
879
880
/// Emits an extra note at the return statement of an interesting stack frame.
881
///
882
/// The returned value is marked as an interesting value, and if it's null,
883
/// adds a visitor to track where it became null.
884
///
885
/// This visitor is intended to be used when another visitor discovers that an
886
/// interesting value comes from an inlined function call.
887
class ReturnVisitor : public BugReporterVisitor {
888
  const StackFrameContext *CalleeSFC;
889
  enum {
890
    Initial,
891
    MaybeUnsuppress,
892
    Satisfied
893
  } Mode = Initial;
894
895
  bool EnableNullFPSuppression;
896
  bool ShouldInvalidate = true;
897
  AnalyzerOptions& Options;
898
  bugreporter::TrackingKind TKind;
899
900
public:
901
  ReturnVisitor(const StackFrameContext *Frame, bool Suppressed,
902
                AnalyzerOptions &Options, bugreporter::TrackingKind TKind)
903
      : CalleeSFC(Frame), EnableNullFPSuppression(Suppressed),
904
303
        Options(Options), TKind(TKind) {}
905
906
410
  static void *getTag() {
907
410
    static int Tag = 0;
908
410
    return static_cast<void *>(&Tag);
909
410
  }
910
911
303
  void Profile(llvm::FoldingSetNodeID &ID) const override {
912
303
    ID.AddPointer(ReturnVisitor::getTag());
913
303
    ID.AddPointer(CalleeSFC);
914
303
    ID.AddBoolean(EnableNullFPSuppression);
915
303
  }
916
917
  /// Adds a ReturnVisitor if the given statement represents a call that was
918
  /// inlined.
919
  ///
920
  /// This will search back through the ExplodedGraph, starting from the given
921
  /// node, looking for when the given statement was processed. If it turns out
922
  /// the statement is a call that was inlined, we add the visitor to the
923
  /// bug report, so it can print a note later.
924
  static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
925
                                    PathSensitiveBugReport &BR,
926
                                    bool InEnableNullFPSuppression,
927
2.19k
                                    bugreporter::TrackingKind TKind) {
928
2.19k
    if (!CallEvent::isCallStmt(S))
929
1.58k
      return;
930
611
931
611
    // First, find when we processed the statement.
932
611
    // If we work with a 'CXXNewExpr' that is going to be purged away before
933
611
    // its call take place. We would catch that purge in the last condition
934
611
    // as a 'StmtPoint' so we have to bypass it.
935
611
    const bool BypassCXXNewExprEval = isa<CXXNewExpr>(S);
936
611
937
611
    // This is moving forward when we enter into another context.
938
611
    const StackFrameContext *CurrentSFC = Node->getStackFrame();
939
611
940
926
    do {
941
926
      // If that is satisfied we found our statement as an inlined call.
942
926
      if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
943
307
        if (CEE->getCalleeContext()->getCallSite() == S)
944
303
          break;
945
623
946
623
      // Try to move forward to the end of the call-chain.
947
623
      Node = Node->getFirstPred();
948
623
      if (!Node)
949
7
        break;
950
616
951
616
      const StackFrameContext *PredSFC = Node->getStackFrame();
952
616
953
616
      // If that is satisfied we found our statement.
954
616
      // FIXME: This code currently bypasses the call site for the
955
616
      //        conservatively evaluated allocator.
956
616
      if (!BypassCXXNewExprEval)
957
541
        if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
958
481
          // See if we do not enter into another context.
959
481
          if (SP->getStmt() == S && 
CurrentSFC == PredSFC301
)
960
301
            break;
961
315
962
315
      CurrentSFC = PredSFC;
963
315
    } while (Node->getStackFrame() == CurrentSFC);
964
611
965
611
    // Next, step over any post-statement checks.
966
628
    while (Node && 
Node->getLocation().getAs<PostStmt>()621
)
967
17
      Node = Node->getFirstPred();
968
611
    if (!Node)
969
7
      return;
970
604
971
604
    // Finally, see if we inlined the call.
972
604
    Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
973
604
    if (!CEE)
974
301
      return;
975
303
976
303
    const StackFrameContext *CalleeContext = CEE->getCalleeContext();
977
303
    if (CalleeContext->getCallSite() != S)
978
0
      return;
979
303
980
303
    // Check the return value.
981
303
    ProgramStateRef State = Node->getState();
982
303
    SVal RetVal = Node->getSVal(S);
983
303
984
303
    // Handle cases where a reference is returned and then immediately used.
985
303
    if (cast<Expr>(S)->isGLValue())
986
16
      if (Optional<Loc> LValue = RetVal.getAs<Loc>())
987
16
        RetVal = State->getSVal(*LValue);
988
303
989
303
    // See if the return value is NULL. If so, suppress the report.
990
303
    AnalyzerOptions &Options = State->getAnalysisManager().options;
991
303
992
303
    bool EnableNullFPSuppression = false;
993
303
    if (InEnableNullFPSuppression &&
994
303
        
Options.ShouldSuppressNullReturnPaths225
)
995
159
      if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
996
116
        EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
997
303
998
303
    BR.addVisitor(std::make_unique<ReturnVisitor>(CalleeContext,
999
303
                                                   EnableNullFPSuppression,
1000
303
                                                   Options, TKind));
1001
303
  }
1002
1003
  PathDiagnosticPieceRef visitNodeInitial(const ExplodedNode *N,
1004
                                          BugReporterContext &BRC,
1005
2.03k
                                          PathSensitiveBugReport &BR) {
1006
2.03k
    // Only print a message at the interesting return statement.
1007
2.03k
    if (N->getLocationContext() != CalleeSFC)
1008
1.41k
      return nullptr;
1009
618
1010
618
    Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
1011
618
    if (!SP)
1012
10
      return nullptr;
1013
608
1014
608
    const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
1015
608
    if (!Ret)
1016
279
      return nullptr;
1017
329
1018
329
    // Okay, we're at the right return statement, but do we have the return
1019
329
    // value available?
1020
329
    ProgramStateRef State = N->getState();
1021
329
    SVal V = State->getSVal(Ret, CalleeSFC);
1022
329
    if (V.isUnknownOrUndef())
1023
29
      return nullptr;
1024
300
1025
300
    // Don't print any more notes after this one.
1026
300
    Mode = Satisfied;
1027
300
1028
300
    const Expr *RetE = Ret->getRetValue();
1029
300
    assert(RetE && "Tracking a return value for a void function");
1030
300
1031
300
    // Handle cases where a reference is returned and then immediately used.
1032
300
    Optional<Loc> LValue;
1033
300
    if (RetE->isGLValue()) {
1034
16
      if ((LValue = V.getAs<Loc>())) {
1035
16
        SVal RValue = State->getRawSVal(*LValue, RetE->getType());
1036
16
        if (RValue.getAs<DefinedSVal>())
1037
14
          V = RValue;
1038
16
      }
1039
16
    }
1040
300
1041
300
    // Ignore aggregate rvalues.
1042
300
    if (V.getAs<nonloc::LazyCompoundVal>() ||
1043
300
        
V.getAs<nonloc::CompoundVal>()298
)
1044
2
      return nullptr;
1045
298
1046
298
    RetE = RetE->IgnoreParenCasts();
1047
298
1048
298
    // Let's track the return value.
1049
298
    bugreporter::trackExpressionValue(
1050
298
        N, RetE, BR, TKind, EnableNullFPSuppression);
1051
298
1052
298
    // Build an appropriate message based on the return value.
1053
298
    SmallString<64> Msg;
1054
298
    llvm::raw_svector_ostream Out(Msg);
1055
298
1056
298
    bool WouldEventBeMeaningless = false;
1057
298
1058
298
    if (State->isNull(V).isConstrainedTrue()) {
1059
254
      if (V.getAs<Loc>()) {
1060
209
1061
209
        // If we have counter-suppression enabled, make sure we keep visiting
1062
209
        // future nodes. We want to emit a path note as well, in case
1063
209
        // the report is resurrected as valid later on.
1064
209
        if (EnableNullFPSuppression &&
1065
209
            
Options.ShouldAvoidSuppressingNullArgumentPaths112
)
1066
31
          Mode = MaybeUnsuppress;
1067
209
1068
209
        if (RetE->getType()->isObjCObjectPointerType()) {
1069
5
          Out << "Returning nil";
1070
204
        } else {
1071
204
          Out << "Returning null pointer";
1072
204
        }
1073
209
      } else {
1074
45
        Out << "Returning zero";
1075
45
      }
1076
254
1077
254
    } else {
1078
44
      if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1079
5
        Out << "Returning the value " << CI->getValue();
1080
39
      } else {
1081
39
        // There is nothing interesting about returning a value, when it is
1082
39
        // plain value without any constraints, and the function is guaranteed
1083
39
        // to return that every time. We could use CFG::isLinear() here, but
1084
39
        // constexpr branches are obvious to the compiler, not necesserily to
1085
39
        // the programmer.
1086
39
        if (N->getCFG().size() == 3)
1087
33
          WouldEventBeMeaningless = true;
1088
39
1089
39
        if (V.getAs<Loc>())
1090
29
          Out << "Returning pointer";
1091
10
        else
1092
10
          Out << "Returning value";
1093
39
      }
1094
44
    }
1095
298
1096
298
    if (LValue) {
1097
16
      if (const MemRegion *MR = LValue->getAsRegion()) {
1098
16
        if (MR->canPrintPretty()) {
1099
10
          Out << " (reference to ";
1100
10
          MR->printPretty(Out);
1101
10
          Out << ")";
1102
10
        }
1103
16
      }
1104
282
    } else {
1105
282
      // FIXME: We should have a more generalized location printing mechanism.
1106
282
      if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
1107
30
        if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
1108
30
          Out << " (loaded from '" << *DD << "')";
1109
282
    }
1110
298
1111
298
    PathDiagnosticLocation L(Ret, BRC.getSourceManager(), CalleeSFC);
1112
298
    if (!L.isValid() || !L.asLocation().isValid())
1113
23
      return nullptr;
1114
275
1115
275
    if (TKind == bugreporter::TrackingKind::Condition)
1116
35
      Out << WillBeUsedForACondition;
1117
275
1118
275
    auto EventPiece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1119
275
1120
275
    // If we determined that the note is meaningless, make it prunable, and
1121
275
    // don't mark the stackframe interesting.
1122
275
    if (WouldEventBeMeaningless)
1123
19
      EventPiece->setPrunable(true);
1124
256
    else
1125
256
      BR.markInteresting(CalleeSFC);
1126
275
1127
275
    return EventPiece;
1128
275
  }
1129
1130
  PathDiagnosticPieceRef visitNodeMaybeUnsuppress(const ExplodedNode *N,
1131
                                                  BugReporterContext &BRC,
1132
465
                                                  PathSensitiveBugReport &BR) {
1133
465
    assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
1134
465
1135
465
    // Are we at the entry node for this call?
1136
465
    Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
1137
465
    if (!CE)
1138
433
      return nullptr;
1139
32
1140
32
    if (CE->getCalleeContext() != CalleeSFC)
1141
1
      return nullptr;
1142
31
1143
31
    Mode = Satisfied;
1144
31
1145
31
    // Don't automatically suppress a report if one of the arguments is
1146
31
    // known to be a null pointer. Instead, start tracking /that/ null
1147
31
    // value back to its origin.
1148
31
    ProgramStateManager &StateMgr = BRC.getStateManager();
1149
31
    CallEventManager &CallMgr = StateMgr.getCallEventManager();
1150
31
1151
31
    ProgramStateRef State = N->getState();
1152
31
    CallEventRef<> Call = CallMgr.getCaller(CalleeSFC, State);
1153
43
    for (unsigned I = 0, E = Call->getNumArgs(); I != E; 
++I12
) {
1154
12
      Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
1155
12
      if (!ArgV)
1156
2
        continue;
1157
10
1158
10
      const Expr *ArgE = Call->getArgExpr(I);
1159
10
      if (!ArgE)
1160
0
        continue;
1161
10
1162
10
      // Is it possible for this argument to be non-null?
1163
10
      if (!State->isNull(*ArgV).isConstrainedTrue())
1164
6
        continue;
1165
4
1166
4
      if (trackExpressionValue(N, ArgE, BR, TKind, EnableNullFPSuppression))
1167
4
        ShouldInvalidate = false;
1168
4
1169
4
      // If we /can't/ track the null pointer, we should err on the side of
1170
4
      // false negatives, and continue towards marking this report invalid.
1171
4
      // (We will still look at the other arguments, though.)
1172
4
    }
1173
31
1174
31
    return nullptr;
1175
31
  }
1176
1177
  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1178
                                   BugReporterContext &BRC,
1179
21.8k
                                   PathSensitiveBugReport &BR) override {
1180
21.8k
    switch (Mode) {
1181
2.03k
    case Initial:
1182
2.03k
      return visitNodeInitial(N, BRC, BR);
1183
465
    case MaybeUnsuppress:
1184
465
      return visitNodeMaybeUnsuppress(N, BRC, BR);
1185
19.3k
    case Satisfied:
1186
19.3k
      return nullptr;
1187
0
    }
1188
0
1189
0
    llvm_unreachable("Invalid visit mode!");
1190
0
  }
1191
1192
  void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
1193
302
                       PathSensitiveBugReport &BR) override {
1194
302
    if (EnableNullFPSuppression && 
ShouldInvalidate111
)
1195
107
      BR.markInvalid(ReturnVisitor::getTag(), CalleeSFC);
1196
302
  }
1197
};
1198
1199
} // end of anonymous namespace
1200
1201
//===----------------------------------------------------------------------===//
1202
// Implementation of FindLastStoreBRVisitor.
1203
//===----------------------------------------------------------------------===//
1204
1205
2.47k
void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1206
2.47k
  static int tag = 0;
1207
2.47k
  ID.AddPointer(&tag);
1208
2.47k
  ID.AddPointer(R);
1209
2.47k
  ID.Add(V);
1210
2.47k
  ID.AddInteger(static_cast<int>(TKind));
1211
2.47k
  ID.AddBoolean(EnableNullFPSuppression);
1212
2.47k
}
1213
1214
/// Returns true if \p N represents the DeclStmt declaring and initializing
1215
/// \p VR.
1216
48.5k
static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
1217
48.5k
  Optional<PostStmt> P = N->getLocationAs<PostStmt>();
1218
48.5k
  if (!P)
1219
17.5k
    return false;
1220
31.0k
1221
31.0k
  const DeclStmt *DS = P->getStmtAs<DeclStmt>();
1222
31.0k
  if (!DS)
1223
29.1k
    return false;
1224
1.96k
1225
1.96k
  if (DS->getSingleDecl() != VR->getDecl())
1226
769
    return false;
1227
1.19k
1228
1.19k
  const MemSpaceRegion *VarSpace = VR->getMemorySpace();
1229
1.19k
  const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
1230
1.19k
  if (!FrameSpace) {
1231
4
    // If we ever directly evaluate global DeclStmts, this assertion will be
1232
4
    // invalid, but this still seems preferable to silently accepting an
1233
4
    // initialization that may be for a path-sensitive variable.
1234
4
    assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
1235
4
    return true;
1236
4
  }
1237
1.19k
1238
1.19k
  assert(VR->getDecl()->hasLocalStorage());
1239
1.19k
  const LocationContext *LCtx = N->getLocationContext();
1240
1.19k
  return FrameSpace->getStackFrame() == LCtx->getStackFrame();
1241
1.19k
}
1242
1243
/// Show diagnostics for initializing or declaring a region \p R with a bad value.
1244
static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
1245
1.14k
                              const MemRegion *R, SVal V, const DeclStmt *DS) {
1246
1.14k
  if (R->canPrintPretty()) {
1247
1.14k
    R->printPretty(os);
1248
1.14k
    os << " ";
1249
1.14k
  }
1250
1.14k
1251
1.14k
  if (V.getAs<loc::ConcreteInt>()) {
1252
579
    bool b = false;
1253
579
    if (R->isBoundable()) {
1254
579
      if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1255
579
        if (TR->getValueType()->isObjCObjectPointerType()) {
1256
70
          os << action << "nil";
1257
70
          b = true;
1258
70
        }
1259
579
      }
1260
579
    }
1261
579
    if (!b)
1262
509
      os << action << "a null pointer value";
1263
579
1264
579
  } else 
if (auto 570
CVal570
= V.getAs<nonloc::ConcreteInt>()) {
1265
57
    os << action << CVal->getValue();
1266
513
  } else if (DS) {
1267
513
    if (V.isUndef()) {
1268
424
      if (isa<VarRegion>(R)) {
1269
424
        const auto *VD = cast<VarDecl>(DS->getSingleDecl());
1270
424
        if (VD->getInit()) {
1271
0
          os << (R->canPrintPretty() ? "initialized" : "Initializing")
1272
0
            << " to a garbage value";
1273
424
        } else {
1274
424
          os << (R->canPrintPretty() ? "declared" : 
"Declaring"0
)
1275
424
            << " without an initial value";
1276
424
        }
1277
424
      }
1278
424
    } else {
1279
89
      os << (R->canPrintPretty() ? "initialized" : 
"Initialized"0
)
1280
89
        << " here";
1281
89
    }
1282
513
  }
1283
1.14k
}
1284
1285
/// Display diagnostics for passing bad region as a parameter.
1286
static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
1287
    const VarRegion *VR,
1288
113
    SVal V) {
1289
113
  const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1290
113
1291
113
  os << "Passing ";
1292
113
1293
113
  if (V.getAs<loc::ConcreteInt>()) {
1294
80
    if (Param->getType()->isObjCObjectPointerType())
1295
5
      os << "nil object reference";
1296
75
    else
1297
75
      os << "null pointer value";
1298
80
  } else 
if (33
V.isUndef()33
) {
1299
0
    os << "uninitialized value";
1300
33
  } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1301
14
    os << "the value " << CI->getValue();
1302
19
  } else {
1303
19
    os << "value";
1304
19
  }
1305
113
1306
113
  // Printed parameter indexes are 1-based, not 0-based.
1307
113
  unsigned Idx = Param->getFunctionScopeIndex() + 1;
1308
113
  os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1309
113
  if (VR->canPrintPretty()) {
1310
113
    os << " ";
1311
113
    VR->printPretty(os);
1312
113
  }
1313
113
}
1314
1315
/// Show default diagnostics for storing bad region.
1316
static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &os,
1317
335
                                     const MemRegion *R, SVal V) {
1318
335
  if (V.getAs<loc::ConcreteInt>()) {
1319
223
    bool b = false;
1320
223
    if (R->isBoundable()) {
1321
223
      if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1322
206
        if (TR->getValueType()->isObjCObjectPointerType()) {
1323
21
          os << "nil object reference stored";
1324
21
          b = true;
1325
21
        }
1326
206
      }
1327
223
    }
1328
223
    if (!b) {
1329
202
      if (R->canPrintPretty())
1330
178
        os << "Null pointer value stored";
1331
24
      else
1332
24
        os << "Storing null pointer value";
1333
202
    }
1334
223
1335
223
  } else 
if (112
V.isUndef()112
) {
1336
8
    if (R->canPrintPretty())
1337
4
      os << "Uninitialized value stored";
1338
4
    else
1339
4
      os << "Storing uninitialized value";
1340
8
1341
104
  } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1342
38
    if (R->canPrintPretty())
1343
32
      os << "The value " << CV->getValue() << " is assigned";
1344
6
    else
1345
6
      os << "Assigning " << CV->getValue();
1346
38
1347
66
  } else {
1348
66
    if (R->canPrintPretty())
1349
66
      os << "Value assigned";
1350
0
    else
1351
0
      os << "Assigning value";
1352
66
  }
1353
335
1354
335
  if (R->canPrintPretty()) {
1355
301
    os << " to ";
1356
301
    R->printPretty(os);
1357
301
  }
1358
335
}
1359
1360
PathDiagnosticPieceRef
1361
FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1362
                                  BugReporterContext &BRC,
1363
105k
                                  PathSensitiveBugReport &BR) {
1364
105k
  if (Satisfied)
1365
48.0k
    return nullptr;
1366
57.1k
1367
57.1k
  const ExplodedNode *StoreSite = nullptr;
1368
57.1k
  const ExplodedNode *Pred = Succ->getFirstPred();
1369
57.1k
  const Expr *InitE = nullptr;
1370
57.1k
  bool IsParam = false;
1371
57.1k
1372
57.1k
  // First see if we reached the declaration of the region.
1373
57.1k
  if (const auto *VR = dyn_cast<VarRegion>(R)) {
1374
48.5k
    if (isInitializationOfVar(Pred, VR)) {
1375
1.19k
      StoreSite = Pred;
1376
1.19k
      InitE = VR->getDecl()->getInit();
1377
1.19k
    }
1378
48.5k
  }
1379
57.1k
1380
57.1k
  // If this is a post initializer expression, initializing the region, we
1381
57.1k
  // should track the initializer expression.
1382
57.1k
  if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1383
99
    const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1384
99
    if (FieldReg == R) {
1385
6
      StoreSite = Pred;
1386
6
      InitE = PIP->getInitializer()->getInit();
1387
6
    }
1388
99
  }
1389
57.1k
1390
57.1k
  // Otherwise, see if this is the store site:
1391
57.1k
  // (1) Succ has this binding and Pred does not, i.e. this is
1392
57.1k
  //     where the binding first occurred.
1393
57.1k
  // (2) Succ has this binding and is a PostStore node for this region, i.e.
1394
57.1k
  //     the same binding was re-assigned here.
1395
57.1k
  if (!StoreSite) {
1396
55.9k
    if (Succ->getState()->getSVal(R) != V)
1397
1.93k
      return nullptr;
1398
53.9k
1399
53.9k
    if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
1400
53.4k
      Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1401
53.4k
      if (!PS || 
PS->getLocationValue() != R885
)
1402
53.4k
        return nullptr;
1403
550
    }
1404
550
1405
550
    StoreSite = Succ;
1406
550
1407
550
    // If this is an assignment expression, we can track the value
1408
550
    // being assigned.
1409
550
    if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1410
369
      if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1411
323
        if (BO->isAssignmentOp())
1412
323
          InitE = BO->getRHS();
1413
550
1414
550
    // If this is a call entry, the variable should be a parameter.
1415
550
    // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1416
550
    // 'this' should never be NULL, but this visitor isn't just for NULL and
1417
550
    // UndefinedVal.)
1418
550
    if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1419
174
      if (const auto *VR = dyn_cast<VarRegion>(R)) {
1420
174
1421
174
        if (const auto *Param = dyn_cast<ParmVarDecl>(VR->getDecl())) {
1422
154
          ProgramStateManager &StateMgr = BRC.getStateManager();
1423
154
          CallEventManager &CallMgr = StateMgr.getCallEventManager();
1424
154
1425
154
          CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1426
154
                                                  Succ->getState());
1427
154
          InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1428
154
        } else {
1429
20
          // Handle Objective-C 'self'.
1430
20
          assert(isa<ImplicitParamDecl>(VR->getDecl()));
1431
20
          InitE = cast<ObjCMessageExpr>(CE->getCalleeContext()->getCallSite())
1432
20
                      ->getInstanceReceiver()->IgnoreParenCasts();
1433
20
        }
1434
174
        IsParam = true;
1435
174
      }
1436
174
    }
1437
550
1438
550
    // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1439
550
    // is wrapped inside of it.
1440
550
    if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1441
7
      InitE = TmpR->getExpr();
1442
550
  }
1443
57.1k
1444
57.1k
  
if (1.74k
!StoreSite1.74k
)
1445
0
    return nullptr;
1446
1.74k
1447
1.74k
  Satisfied = true;
1448
1.74k
1449
1.74k
  // If we have an expression that provided the value, try to track where it
1450
1.74k
  // came from.
1451
1.74k
  if (InitE) {
1452
1.24k
    if (!IsParam)
1453
1.07k
      InitE = InitE->IgnoreParenCasts();
1454
1.24k
1455
1.24k
    bugreporter::trackExpressionValue(
1456
1.24k
        StoreSite, InitE, BR, TKind, EnableNullFPSuppression);
1457
1.24k
  }
1458
1.74k
1459
1.74k
  if (TKind == TrackingKind::Condition &&
1460
1.74k
      
!OriginSFC->isParentOf(StoreSite->getStackFrame())176
)
1461
151
    return nullptr;
1462
1.59k
1463
1.59k
  // Okay, we've found the binding. Emit an appropriate message.
1464
1.59k
  SmallString<256> sbuf;
1465
1.59k
  llvm::raw_svector_ostream os(sbuf);
1466
1.59k
1467
1.59k
  if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1468
1.47k
    const Stmt *S = PS->getStmt();
1469
1.47k
    const char *action = nullptr;
1470
1.47k
    const auto *DS = dyn_cast<DeclStmt>(S);
1471
1.47k
    const auto *VR = dyn_cast<VarRegion>(R);
1472
1.47k
1473
1.47k
    if (DS) {
1474
1.14k
      action = R->canPrintPretty() ? 
"initialized to "1.14k
:
1475
1.14k
                                     
"Initializing to "1
;
1476
1.14k
    } else 
if (326
isa<BlockExpr>(S)326
) {
1477
4
      action = R->canPrintPretty() ? "captured by block as " :
1478
4
                                     
"Captured by block as "0
;
1479
4
      if (VR) {
1480
4
        // See if we can get the BlockVarRegion.
1481
4
        ProgramStateRef State = StoreSite->getState();
1482
4
        SVal V = StoreSite->getSVal(S);
1483
4
        if (const auto *BDR =
1484
4
              dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1485
4
          if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1486
4
            if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>())
1487
4
              BR.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
1488
4
                  *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC));
1489
4
          }
1490
4
        }
1491
4
      }
1492
4
    }
1493
1.47k
    if (action)
1494
1.14k
      showBRDiagnostics(action, os, R, V, DS);
1495
1.47k
1496
1.47k
  } else 
if (126
StoreSite->getLocation().getAs<CallEnter>()126
) {
1497
113
    if (const auto *VR = dyn_cast<VarRegion>(R))
1498
113
      showBRParamDiagnostics(os, VR, V);
1499
113
  }
1500
1.59k
1501
1.59k
  if (os.str().empty())
1502
335
    showBRDefaultDiagnostics(os, R, V);
1503
1.59k
1504
1.59k
  if (TKind == bugreporter::TrackingKind::Condition)
1505
25
    os << WillBeUsedForACondition;
1506
1.59k
1507
1.59k
  // Construct a new PathDiagnosticPiece.
1508
1.59k
  ProgramPoint P = StoreSite->getLocation();
1509
1.59k
  PathDiagnosticLocation L;
1510
1.59k
  if (P.getAs<CallEnter>() && 
InitE113
)
1511
113
    L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1512
113
                               P.getLocationContext());
1513
1.59k
1514
1.59k
  if (!L.isValid() || 
!L.asLocation().isValid()113
)
1515
1.48k
    L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1516
1.59k
1517
1.59k
  if (!L.isValid() || !L.asLocation().isValid())
1518
1
    return nullptr;
1519
1.59k
1520
1.59k
  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1521
1.59k
}
1522
1523
//===----------------------------------------------------------------------===//
1524
// Implementation of TrackConstraintBRVisitor.
1525
//===----------------------------------------------------------------------===//
1526
1527
310
void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1528
310
  static int tag = 0;
1529
310
  ID.AddPointer(&tag);
1530
310
  ID.AddBoolean(Assumption);
1531
310
  ID.Add(Constraint);
1532
310
}
1533
1534
/// Return the tag associated with this visitor.  This tag will be used
1535
/// to make all PathDiagnosticPieces created by this visitor.
1536
1.31k
const char *TrackConstraintBRVisitor::getTag() {
1537
1.31k
  return "TrackConstraintBRVisitor";
1538
1.31k
}
1539
1540
7.09k
bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1541
7.09k
  if (IsZeroCheck)
1542
7.07k
    return N->getState()->isNull(Constraint).isUnderconstrained();
1543
24
  return (bool)N->getState()->assume(Constraint, !Assumption);
1544
24
}
1545
1546
PathDiagnosticPieceRef TrackConstraintBRVisitor::VisitNode(
1547
9.16k
    const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &) {
1548
9.16k
  const ExplodedNode *PrevN = N->getFirstPred();
1549
9.16k
  if (IsSatisfied)
1550
2.65k
    return nullptr;
1551
6.50k
1552
6.50k
  // Start tracking after we see the first state in which the value is
1553
6.50k
  // constrained.
1554
6.50k
  if (!IsTrackingTurnedOn)
1555
998
    if (!isUnderconstrained(N))
1556
295
      IsTrackingTurnedOn = true;
1557
6.50k
  if (!IsTrackingTurnedOn)
1558
703
    return nullptr;
1559
5.80k
1560
5.80k
  // Check if in the previous state it was feasible for this constraint
1561
5.80k
  // to *not* be true.
1562
5.80k
  if (isUnderconstrained(PrevN)) {
1563
295
    IsSatisfied = true;
1564
295
1565
295
    // As a sanity check, make sure that the negation of the constraint
1566
295
    // was infeasible in the current state.  If it is feasible, we somehow
1567
295
    // missed the transition point.
1568
295
    assert(!isUnderconstrained(N));
1569
295
1570
295
    // We found the transition point for the constraint.  We now need to
1571
295
    // pretty-print the constraint. (work-in-progress)
1572
295
    SmallString<64> sbuf;
1573
295
    llvm::raw_svector_ostream os(sbuf);
1574
295
1575
295
    if (Constraint.getAs<Loc>()) {
1576
293
      os << "Assuming pointer value is ";
1577
293
      os << (Assumption ? 
"non-null"0
: "null");
1578
293
    }
1579
295
1580
295
    if (os.str().empty())
1581
2
      return nullptr;
1582
293
1583
293
    // Construct a new PathDiagnosticPiece.
1584
293
    ProgramPoint P = N->getLocation();
1585
293
    PathDiagnosticLocation L =
1586
293
      PathDiagnosticLocation::create(P, BRC.getSourceManager());
1587
293
    if (!L.isValid())
1588
0
      return nullptr;
1589
293
1590
293
    auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1591
293
    X->setTag(getTag());
1592
293
    return std::move(X);
1593
293
  }
1594
5.51k
1595
5.51k
  return nullptr;
1596
5.51k
}
1597
1598
//===----------------------------------------------------------------------===//
1599
// Implementation of SuppressInlineDefensiveChecksVisitor.
1600
//===----------------------------------------------------------------------===//
1601
1602
SuppressInlineDefensiveChecksVisitor::
1603
SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1604
399
    : V(Value) {
1605
399
  // Check if the visitor is disabled.
1606
399
  AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1607
399
  if (!Options.ShouldSuppressInlinedDefensiveChecks)
1608
0
    IsSatisfied = true;
1609
399
}
1610
1611
void SuppressInlineDefensiveChecksVisitor::Profile(
1612
399
    llvm::FoldingSetNodeID &ID) const {
1613
399
  static int id = 0;
1614
399
  ID.AddPointer(&id);
1615
399
  ID.Add(V);
1616
399
}
1617
1618
0
const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1619
0
  return "IDCVisitor";
1620
0
}
1621
1622
PathDiagnosticPieceRef
1623
SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1624
                                                BugReporterContext &BRC,
1625
17.7k
                                                PathSensitiveBugReport &BR) {
1626
17.7k
  const ExplodedNode *Pred = Succ->getFirstPred();
1627
17.7k
  if (IsSatisfied)
1628
2.43k
    return nullptr;
1629
15.2k
1630
15.2k
  // Start tracking after we see the first state in which the value is null.
1631
15.2k
  if (!IsTrackingTurnedOn)
1632
9.98k
    if (Succ->getState()->isNull(V).isConstrainedTrue())
1633
287
      IsTrackingTurnedOn = true;
1634
15.2k
  if (!IsTrackingTurnedOn)
1635
9.70k
    return nullptr;
1636
5.58k
1637
5.58k
  // Check if in the previous state it was feasible for this value
1638
5.58k
  // to *not* be null.
1639
5.58k
  if (!Pred->getState()->isNull(V).isConstrainedTrue() &&
1640
5.58k
      
Succ->getState()->isNull(V).isConstrainedTrue()287
) {
1641
287
    IsSatisfied = true;
1642
287
1643
287
    // Check if this is inlined defensive checks.
1644
287
    const LocationContext *CurLC = Succ->getLocationContext();
1645
287
    const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1646
287
    if (CurLC != ReportLC && 
!CurLC->isParentOf(ReportLC)55
) {
1647
50
      BR.markInvalid("Suppress IDC", CurLC);
1648
50
      return nullptr;
1649
50
    }
1650
237
1651
237
    // Treat defensive checks in function-like macros as if they were an inlined
1652
237
    // defensive check. If the bug location is not in a macro and the
1653
237
    // terminator for the current location is in a macro then suppress the
1654
237
    // warning.
1655
237
    auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1656
237
1657
237
    if (!BugPoint)
1658
0
      return nullptr;
1659
237
1660
237
    ProgramPoint CurPoint = Succ->getLocation();
1661
237
    const Stmt *CurTerminatorStmt = nullptr;
1662
237
    if (auto BE = CurPoint.getAs<BlockEdge>()) {
1663
146
      CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1664
146
    } else 
if (auto 91
SP91
= CurPoint.getAs<StmtPoint>()) {
1665
91
      const Stmt *CurStmt = SP->getStmt();
1666
91
      if (!CurStmt->getBeginLoc().isMacroID())
1667
52
        return nullptr;
1668
39
1669
39
      CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1670
39
      CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt();
1671
39
    } else {
1672
0
      return nullptr;
1673
0
    }
1674
185
1675
185
    if (!CurTerminatorStmt)
1676
2
      return nullptr;
1677
183
1678
183
    SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
1679
183
    if (TerminatorLoc.isMacroID()) {
1680
38
      SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
1681
38
1682
38
      // Suppress reports unless we are in that same macro.
1683
38
      if (!BugLoc.isMacroID() ||
1684
38
          
getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)11
) {
1685
30
        BR.markInvalid("Suppress Macro IDC", CurLC);
1686
30
      }
1687
38
      return nullptr;
1688
38
    }
1689
5.44k
  }
1690
5.44k
  return nullptr;
1691
5.44k
}
1692
1693
//===----------------------------------------------------------------------===//
1694
// TrackControlDependencyCondBRVisitor.
1695
//===----------------------------------------------------------------------===//
1696
1697
namespace {
1698
/// Tracks the expressions that are a control dependency of the node that was
1699
/// supplied to the constructor.
1700
/// For example:
1701
///
1702
///   cond = 1;
1703
///   if (cond)
1704
///     10 / 0;
1705
///
1706
/// An error is emitted at line 3. This visitor realizes that the branch
1707
/// on line 2 is a control dependency of line 3, and tracks it's condition via
1708
/// trackExpressionValue().
1709
class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor {
1710
  const ExplodedNode *Origin;
1711
  ControlDependencyCalculator ControlDeps;
1712
  llvm::SmallSet<const CFGBlock *, 32> VisitedBlocks;
1713
1714
public:
1715
  TrackControlDependencyCondBRVisitor(const ExplodedNode *O)
1716
4.43k
  : Origin(O), ControlDeps(&O->getCFG()) {}
1717
1718
4.43k
  void Profile(llvm::FoldingSetNodeID &ID) const override {
1719
4.43k
    static int x = 0;
1720
4.43k
    ID.AddPointer(&x);
1721
4.43k
  }
1722
1723
  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1724
                                   BugReporterContext &BRC,
1725
                                   PathSensitiveBugReport &BR) override;
1726
};
1727
} // end of anonymous namespace
1728
1729
static std::shared_ptr<PathDiagnosticEventPiece>
1730
constructDebugPieceForTrackedCondition(const Expr *Cond,
1731
                                       const ExplodedNode *N,
1732
824
                                       BugReporterContext &BRC) {
1733
824
1734
824
  if (BRC.getAnalyzerOptions().AnalysisDiagOpt == PD_NONE ||
1735
824
      !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
1736
786
    return nullptr;
1737
38
1738
38
  std::string ConditionText = std::string(Lexer::getSourceText(
1739
38
      CharSourceRange::getTokenRange(Cond->getSourceRange()),
1740
38
      BRC.getSourceManager(), BRC.getASTContext().getLangOpts()));
1741
38
1742
38
  return std::make_shared<PathDiagnosticEventPiece>(
1743
38
      PathDiagnosticLocation::createBegin(
1744
38
          Cond, BRC.getSourceManager(), N->getLocationContext()),
1745
38
          (Twine() + "Tracking condition '" + ConditionText + "'").str());
1746
38
}
1747
1748
8.93k
static bool isAssertlikeBlock(const CFGBlock *B, ASTContext &Context) {
1749
8.93k
  if (B->succ_size() != 2)
1750
4.98k
    return false;
1751
3.95k
1752
3.95k
  const CFGBlock *Then = B->succ_begin()->getReachableBlock();
1753
3.95k
  const CFGBlock *Else = (B->succ_begin() + 1)->getReachableBlock();
1754
3.95k
1755
3.95k
  if (!Then || 
!Else3.89k
)
1756
606
    return false;
1757
3.34k
1758
3.34k
  if (Then->isInevitablySinking() != Else->isInevitablySinking())
1759
50
    return true;
1760
3.29k
1761
3.29k
  // For the following condition the following CFG would be built:
1762
3.29k
  //
1763
3.29k
  //                          ------------->
1764
3.29k
  //                         /              \
1765
3.29k
  //                       [B1] -> [B2] -> [B3] -> [sink]
1766
3.29k
  // assert(A && B || C);            \       \
1767
3.29k
  //                                  -----------> [go on with the execution]
1768
3.29k
  //
1769
3.29k
  // It so happens that CFGBlock::getTerminatorCondition returns 'A' for block
1770
3.29k
  // B1, 'A && B' for B2, and 'A && B || C' for B3. Let's check whether we
1771
3.29k
  // reached the end of the condition!
1772
3.29k
  if (const Stmt *ElseCond = Else->getTerminatorCondition())
1773
833
    if (const auto *BinOp = dyn_cast<BinaryOperator>(ElseCond))
1774
232
      if (BinOp->isLogicalOp())
1775
137
        return isAssertlikeBlock(Else, Context);
1776
3.15k
1777
3.15k
  return false;
1778
3.15k
}
1779
1780
PathDiagnosticPieceRef
1781
TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
1782
                                               BugReporterContext &BRC,
1783
188k
                                               PathSensitiveBugReport &BR) {
1784
188k
  // We can only reason about control dependencies within the same stack frame.
1785
188k
  if (Origin->getStackFrame() != N->getStackFrame())
1786
57.1k
    return nullptr;
1787
131k
1788
131k
  CFGBlock *NB = const_cast<CFGBlock *>(N->getCFGBlock());
1789
131k
1790
131k
  // Skip if we already inspected this block.
1791
131k
  if (!VisitedBlocks.insert(NB).second)
1792
120k
    return nullptr;
1793
10.3k
1794
10.3k
  CFGBlock *OriginB = const_cast<CFGBlock *>(Origin->getCFGBlock());
1795
10.3k
1796
10.3k
  // TODO: Cache CFGBlocks for each ExplodedNode.
1797
10.3k
  if (!OriginB || !NB)
1798
1.52k
    return nullptr;
1799
8.79k
1800
8.79k
  if (isAssertlikeBlock(NB, BRC.getASTContext()))
1801
50
    return nullptr;
1802
8.74k
1803
8.74k
  if (ControlDeps.isControlDependent(OriginB, NB)) {
1804
1.56k
    // We don't really want to explain for range loops. Evidence suggests that
1805
1.56k
    // the only thing that leads to is the addition of calls to operator!=.
1806
1.56k
    if (llvm::isa_and_nonnull<CXXForRangeStmt>(NB->getTerminatorStmt()))
1807
16
      return nullptr;
1808
1.54k
1809
1.54k
    if (const Expr *Condition = NB->getLastCondition()) {
1810
1.28k
      // Keeping track of the already tracked conditions on a visitor level
1811
1.28k
      // isn't sufficient, because a new visitor is created for each tracked
1812
1.28k
      // expression, hence the BugReport level set.
1813
1.28k
      if (BR.addTrackedCondition(N)) {
1814
824
        bugreporter::trackExpressionValue(
1815
824
            N, Condition, BR, bugreporter::TrackingKind::Condition,
1816
824
            /*EnableNullFPSuppression=*/false);
1817
824
        return constructDebugPieceForTrackedCondition(Condition, N, BRC);
1818
824
      }
1819
7.90k
    }
1820
1.54k
  }
1821
7.90k
1822
7.90k
  return nullptr;
1823
7.90k
}
1824
1825
//===----------------------------------------------------------------------===//
1826
// Implementation of trackExpressionValue.
1827
//===----------------------------------------------------------------------===//
1828
1829
static const MemRegion *getLocationRegionIfReference(const Expr *E,
1830
2.31k
                                                     const ExplodedNode *N) {
1831
2.31k
  if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1832
2.19k
    if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1833
2.19k
      if (!VD->getType()->isReferenceType())
1834
2.15k
        return nullptr;
1835
40
      ProgramStateManager &StateMgr = N->getState()->getStateManager();
1836
40
      MemRegionManager &MRMgr = StateMgr.getRegionManager();
1837
40
      return MRMgr.getVarRegion(VD, N->getLocationContext());
1838
40
    }
1839
2.19k
  }
1840
125
1841
125
  // FIXME: This does not handle other kinds of null references,
1842
125
  // for example, references from FieldRegions:
1843
125
  //   struct Wrapper { int &ref; };
1844
125
  //   Wrapper w = { *(int *)0 };
1845
125
  //   w.ref = 1;
1846
125
1847
125
  return nullptr;
1848
125
}
1849
1850
/// \return A subexpression of {@code Ex} which represents the
1851
/// expression-of-interest.
1852
static const Expr *peelOffOuterExpr(const Expr *Ex,
1853
4.83k
                                    const ExplodedNode *N) {
1854
4.83k
  Ex = Ex->IgnoreParenCasts();
1855
4.83k
  if (const auto *FE = dyn_cast<FullExpr>(Ex))
1856
0
    return peelOffOuterExpr(FE->getSubExpr(), N);
1857
4.83k
  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1858
29
    return peelOffOuterExpr(OVE->getSourceExpr(), N);
1859
4.80k
  if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1860
43
    const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1861
43
    if (PropRef && PropRef->isMessagingGetter()) {
1862
43
      const Expr *GetterMessageSend =
1863
43
          POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1864
43
      assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1865
43
      return peelOffOuterExpr(GetterMessageSend, N);
1866
43
    }
1867
4.75k
  }
1868
4.75k
1869
4.75k
  // Peel off the ternary operator.
1870
4.75k
  if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1871
48
    // Find a node where the branching occurred and find out which branch
1872
48
    // we took (true/false) by looking at the ExplodedGraph.
1873
48
    const ExplodedNode *NI = N;
1874
1.16k
    do {
1875
1.16k
      ProgramPoint ProgPoint = NI->getLocation();
1876
1.16k
      if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1877
191
        const CFGBlock *srcBlk = BE->getSrc();
1878
191
        if (const Stmt *term = srcBlk->getTerminatorStmt()) {
1879
61
          if (term == CO) {
1880
47
            bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1881
47
            if (TookTrueBranch)
1882
25
              return peelOffOuterExpr(CO->getTrueExpr(), N);
1883
22
            else
1884
22
              return peelOffOuterExpr(CO->getFalseExpr(), N);
1885
1.11k
          }
1886
61
        }
1887
191
      }
1888
1.11k
      NI = NI->getFirstPred();
1889
1.11k
    } while (NI);
1890
48
  }
1891
4.75k
1892
4.75k
  
if (auto *4.71k
BO4.71k
= dyn_cast<BinaryOperator>(Ex))
1893
359
    if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1894
11
      return peelOffOuterExpr(SubEx, N);
1895
4.70k
1896
4.70k
  if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
1897
174
    if (UO->getOpcode() == UO_LNot)
1898
103
      return peelOffOuterExpr(UO->getSubExpr(), N);
1899
71
1900
71
    // FIXME: There's a hack in our Store implementation that always computes
1901
71
    // field offsets around null pointers as if they are always equal to 0.
1902
71
    // The idea here is to report accesses to fields as null dereferences
1903
71
    // even though the pointer value that's being dereferenced is actually
1904
71
    // the offset of the field rather than exactly 0.
1905
71
    // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1906
71
    // This code interacts heavily with this hack; otherwise the value
1907
71
    // would not be null at all for most fields, so we'd be unable to track it.
1908
71
    if (UO->getOpcode() == UO_AddrOf && 
UO->getSubExpr()->isLValue()31
)
1909
31
      if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
1910
31
        return peelOffOuterExpr(DerefEx, N);
1911
4.56k
  }
1912
4.56k
1913
4.56k
  return Ex;
1914
4.56k
}
1915
1916
/// Find the ExplodedNode where the lvalue (the value of 'Ex')
1917
/// was computed.
1918
static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1919
4.56k
                                                 const Expr *Inner) {
1920
45.5k
  while (N) {
1921
45.4k
    if (N->getStmtForDiagnostics() == Inner)
1922
4.50k
      return N;
1923
40.9k
    N = N->getFirstPred();
1924
40.9k
  }
1925
4.56k
  
return N63
;
1926
4.56k
}
1927
1928
bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
1929
                                       const Expr *E,
1930
                                       PathSensitiveBugReport &report,
1931
                                       bugreporter::TrackingKind TKind,
1932
4.56k
                                       bool EnableNullFPSuppression) {
1933
4.56k
1934
4.56k
  if (!E || !InputNode)
1935
0
    return false;
1936
4.56k
1937
4.56k
  const Expr *Inner = peelOffOuterExpr(E, InputNode);
1938
4.56k
  const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner);
1939
4.56k
  if (!LVNode)
1940
63
    return false;
1941
4.50k
1942
4.50k
  ProgramStateRef LVState = LVNode->getState();
1943
4.50k
  const StackFrameContext *SFC = LVNode->getStackFrame();
1944
4.50k
1945
4.50k
  // We only track expressions if we believe that they are important. Chances
1946
4.50k
  // are good that control dependencies to the tracking point are also improtant
1947
4.50k
  // because of this, let's explain why we believe control reached this point.
1948
4.50k
  // TODO: Shouldn't we track control dependencies of every bug location, rather
1949
4.50k
  // than only tracked expressions?
1950
4.50k
  if (LVState->getAnalysisManager().getAnalyzerOptions().ShouldTrackConditions)
1951
4.43k
    report.addVisitor(std::make_unique<TrackControlDependencyCondBRVisitor>(
1952
4.43k
          InputNode));
1953
4.50k
1954
4.50k
  // The message send could be nil due to the receiver being nil.
1955
4.50k
  // At this point in the path, the receiver should be live since we are at the
1956
4.50k
  // message send expr. If it is nil, start tracking it.
1957
4.50k
  if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
1958
41
    trackExpressionValue(
1959
41
        LVNode, Receiver, report, TKind, EnableNullFPSuppression);
1960
4.50k
1961
4.50k
  // Track the index if this is an array subscript.
1962
4.50k
  if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner))
1963
25
    trackExpressionValue(
1964
25
        LVNode, Arr->getIdx(), report, TKind, /*EnableNullFPSuppression*/false);
1965
4.50k
1966
4.50k
  // See if the expression we're interested refers to a variable.
1967
4.50k
  // If so, we can track both its contents and constraints on its value.
1968
4.50k
  if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
1969
2.31k
    SVal LVal = LVNode->getSVal(Inner);
1970
2.31k
1971
2.31k
    const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
1972
2.31k
    bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1973
2.31k
1974
2.31k
    // If this is a C++ reference to a null pointer, we are tracking the
1975
2.31k
    // pointer. In addition, we should find the store at which the reference
1976
2.31k
    // got initialized.
1977
2.31k
    if (RR && 
!LVIsNull40
)
1978
33
      if (auto KV = LVal.getAs<KnownSVal>())
1979
33
        report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
1980
33
            *KV, RR, EnableNullFPSuppression, TKind, SFC));
1981
2.31k
1982
2.31k
    // In case of C++ references, we want to differentiate between a null
1983
2.31k
    // reference and reference to null pointer.
1984
2.31k
    // If the LVal is null, check if we are dealing with null reference.
1985
2.31k
    // For those, we want to track the location of the reference.
1986
2.31k
    const MemRegion *R = (RR && 
LVIsNull40
) ?
RR7
:
1987
2.31k
        
LVNode->getSVal(Inner).getAsRegion()2.30k
;
1988
2.31k
1989
2.31k
    if (R) {
1990
2.31k
1991
2.31k
      // Mark both the variable region and its contents as interesting.
1992
2.31k
      SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1993
2.31k
      report.addVisitor(
1994
2.31k
          std::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R), TKind));
1995
2.31k
1996
2.31k
      MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1997
2.31k
          LVNode, R, EnableNullFPSuppression, report, V);
1998
2.31k
1999
2.31k
      report.markInteresting(V, TKind);
2000
2.31k
      report.addVisitor(std::make_unique<UndefOrNullArgVisitor>(R));
2001
2.31k
2002
2.31k
      // If the contents are symbolic and null, find out when they became null.
2003
2.31k
      if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true))
2004
513
        if (LVState->isNull(V).isConstrainedTrue())
2005
289
          report.addVisitor(std::make_unique<TrackConstraintBRVisitor>(
2006
289
              V.castAs<DefinedSVal>(), false));
2007
2.31k
2008
2.31k
      // Add visitor, which will suppress inline defensive checks.
2009
2.31k
      if (auto DV = V.getAs<DefinedSVal>())
2010
1.82k
        if (!DV->isZeroConstant() && 
EnableNullFPSuppression799
) {
2011
399
          // Note that LVNode may be too late (i.e., too far from the InputNode)
2012
399
          // because the lvalue may have been computed before the inlined call
2013
399
          // was evaluated. InputNode may as well be too early here, because
2014
399
          // the symbol is already dead; this, however, is fine because we can
2015
399
          // still find the node in which it collapsed to null previously.
2016
399
          report.addVisitor(
2017
399
              std::make_unique<SuppressInlineDefensiveChecksVisitor>(
2018
399
                  *DV, InputNode));
2019
399
        }
2020
2.31k
2021
2.31k
      if (auto KV = V.getAs<KnownSVal>())
2022
2.31k
        report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
2023
2.31k
            *KV, R, EnableNullFPSuppression, TKind, SFC));
2024
2.31k
      return true;
2025
2.31k
    }
2026
2.19k
  }
2027
2.19k
2028
2.19k
  // If the expression is not an "lvalue expression", we can still
2029
2.19k
  // track the constraints on its contents.
2030
2.19k
  SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
2031
2.19k
2032
2.19k
  ReturnVisitor::addVisitorIfNecessary(
2033
2.19k
    LVNode, Inner, report, EnableNullFPSuppression, TKind);
2034
2.19k
2035
2.19k
  // Is it a symbolic value?
2036
2.19k
  if (auto L = V.getAs<loc::MemRegionVal>()) {
2037
157
    // FIXME: this is a hack for fixing a later crash when attempting to
2038
157
    // dereference a void* pointer.
2039
157
    // We should not try to dereference pointers at all when we don't care
2040
157
    // what is written inside the pointer.
2041
157
    bool CanDereference = true;
2042
157
    if (const auto *SR = L->getRegionAs<SymbolicRegion>()) {
2043
95
      if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
2044
8
        CanDereference = false;
2045
95
    } else 
if (62
L->getRegionAs<AllocaRegion>()62
)
2046
1
      CanDereference = false;
2047
157
2048
157
    // At this point we are dealing with the region's LValue.
2049
157
    // However, if the rvalue is a symbolic region, we should track it as well.
2050
157
    // Try to use the correct type when looking up the value.
2051
157
    SVal RVal;
2052
157
    if (ExplodedGraph::isInterestingLValueExpr(Inner))
2053
0
      RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
2054
157
    else if (CanDereference)
2055
148
      RVal = LVState->getSVal(L->getRegion());
2056
157
2057
157
    if (CanDereference) {
2058
148
      report.addVisitor(
2059
148
          std::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
2060
148
2061
148
      if (auto KV = RVal.getAs<KnownSVal>())
2062
123
        report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
2063
123
            *KV, L->getRegion(), EnableNullFPSuppression, TKind, SFC));
2064
148
    }
2065
157
2066
157
    const MemRegion *RegionRVal = RVal.getAsRegion();
2067
157
    if (RegionRVal && 
isa<SymbolicRegion>(RegionRVal)21
) {
2068
21
      report.markInteresting(RegionRVal, TKind);
2069
21
      report.addVisitor(std::make_unique<TrackConstraintBRVisitor>(
2070
21
            loc::MemRegionVal(RegionRVal), /*assumption=*/false));
2071
21
    }
2072
157
  }
2073
2.19k
  return true;
2074
2.19k
}
2075
2076
//===----------------------------------------------------------------------===//
2077
// Implementation of NulReceiverBRVisitor.
2078
//===----------------------------------------------------------------------===//
2079
2080
const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
2081
29.7k
                                                 const ExplodedNode *N) {
2082
29.7k
  const auto *ME = dyn_cast<ObjCMessageExpr>(S);
2083
29.7k
  if (!ME)
2084
29.4k
    return nullptr;
2085
262
  if (const Expr *Receiver = ME->getInstanceReceiver()) {
2086
194
    ProgramStateRef state = N->getState();
2087
194
    SVal V = N->getSVal(Receiver);
2088
194
    if (state->isNull(V).isConstrainedTrue())
2089
89
      return Receiver;
2090
173
  }
2091
173
  return nullptr;
2092
173
}
2093
2094
PathDiagnosticPieceRef
2095
NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
2096
1.26M
                                PathSensitiveBugReport &BR) {
2097
1.26M
  Optional<PreStmt> P = N->getLocationAs<PreStmt>();
2098
1.26M
  if (!P)
2099
1.24M
    return nullptr;
2100
25.2k
2101
25.2k
  const Stmt *S = P->getStmt();
2102
25.2k
  const Expr *Receiver = getNilReceiver(S, N);
2103
25.2k
  if (!Receiver)
2104
25.1k
    return nullptr;
2105
48
2106
48
  llvm::SmallString<256> Buf;
2107
48
  llvm::raw_svector_ostream OS(Buf);
2108
48
2109
48
  if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
2110
48
    OS << "'";
2111
48
    ME->getSelector().print(OS);
2112
48
    OS << "' not called";
2113
48
  }
2114
0
  else {
2115
0
    OS << "No method is called";
2116
0
  }
2117
48
  OS << " because the receiver is nil";
2118
48
2119
48
  // The receiver was nil, and hence the method was skipped.
2120
48
  // Register a BugReporterVisitor to issue a message telling us how
2121
48
  // the receiver was null.
2122
48
  bugreporter::trackExpressionValue(
2123
48
      N, Receiver, BR, bugreporter::TrackingKind::Thorough,
2124
48
      /*EnableNullFPSuppression*/ false);
2125
48
  // Issue a message saying that the method was skipped.
2126
48
  PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
2127
48
                                     N->getLocationContext());
2128
48
  return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
2129
48
}
2130
2131
//===----------------------------------------------------------------------===//
2132
// Visitor that tries to report interesting diagnostics from conditions.
2133
//===----------------------------------------------------------------------===//
2134
2135
/// Return the tag associated with this visitor.  This tag will be used
2136
/// to make all PathDiagnosticPieces created by this visitor.
2137
5.86k
const char *ConditionBRVisitor::getTag() { return "ConditionBRVisitor"; }
2138
2139
PathDiagnosticPieceRef
2140
ConditionBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
2141
1.26M
                              PathSensitiveBugReport &BR) {
2142
1.26M
  auto piece = VisitNodeImpl(N, BRC, BR);
2143
1.26M
  if (piece) {
2144
4.84k
    piece->setTag(getTag());
2145
4.84k
    if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
2146
3.92k
      ev->setPrunable(true, /* override */ false);
2147
4.84k
  }
2148
1.26M
  return piece;
2149
1.26M
}
2150
2151
PathDiagnosticPieceRef
2152
ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
2153
                                  BugReporterContext &BRC,
2154
1.26M
                                  PathSensitiveBugReport &BR) {
2155
1.26M
  ProgramPoint ProgPoint = N->getLocation();
2156
1.26M
  const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
2157
1.26M
      ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
2158
1.26M
2159
1.26M
  // If an assumption was made on a branch, it should be caught
2160
1.26M
  // here by looking at the state transition.
2161
1.26M
  if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
2162
59.6k
    const CFGBlock *SrcBlock = BE->getSrc();
2163
59.6k
    if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
2164
7.68k
      // If the tag of the previous node is 'Eagerly Assume...' the current
2165
7.68k
      // 'BlockEdge' has the same constraint information. We do not want to
2166
7.68k
      // report the value as it is just an assumption on the predecessor node
2167
7.68k
      // which will be caught in the next VisitNode() iteration as a 'PostStmt'.
2168
7.68k
      const ProgramPointTag *PreviousNodeTag =
2169
7.68k
          N->getFirstPred()->getLocation().getTag();
2170
7.68k
      if (PreviousNodeTag == Tags.first || 
PreviousNodeTag == Tags.second7.28k
)
2171
783
        return nullptr;
2172
6.90k
2173
6.90k
      return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
2174
6.90k
    }
2175
51.9k
    return nullptr;
2176
51.9k
  }
2177
1.20M
2178
1.20M
  if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
2179
850k
    const ProgramPointTag *CurrentNodeTag = PS->getTag();
2180
850k
    if (CurrentNodeTag != Tags.first && 
CurrentNodeTag != Tags.second849k
)
2181
848k
      return nullptr;
2182
1.66k
2183
1.66k
    bool TookTrue = CurrentNodeTag == Tags.first;
2184
1.66k
    return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
2185
1.66k
  }
2186
357k
2187
357k
  return nullptr;
2188
357k
}
2189
2190
PathDiagnosticPieceRef ConditionBRVisitor::VisitTerminator(
2191
    const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
2192
    const CFGBlock *dstBlk, PathSensitiveBugReport &R,
2193
6.90k
    BugReporterContext &BRC) {
2194
6.90k
  const Expr *Cond = nullptr;
2195
6.90k
2196
6.90k
  // In the code below, Term is a CFG terminator and Cond is a branch condition
2197
6.90k
  // expression upon which the decision is made on this terminator.
2198
6.90k
  //
2199
6.90k
  // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
2200
6.90k
  // and "x == 0" is the respective condition.
2201
6.90k
  //
2202
6.90k
  // Another example: in "if (x && y)", we've got two terminators and two
2203
6.90k
  // conditions due to short-circuit nature of operator "&&":
2204
6.90k
  // 1. The "if (x && y)" statement is a terminator,
2205
6.90k
  //    and "y" is the respective condition.
2206
6.90k
  // 2. Also "x && ..." is another terminator,
2207
6.90k
  //    and "x" is its condition.
2208
6.90k
2209
6.90k
  switch (Term->getStmtClass()) {
2210
0
  // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
2211
0
  // more tricky because there are more than two branches to account for.
2212
2.38k
  default:
2213
2.38k
    return nullptr;
2214
2.81k
  case Stmt::IfStmtClass:
2215
2.81k
    Cond = cast<IfStmt>(Term)->getCond();
2216
2.81k
    break;
2217
1.08k
  case Stmt::ConditionalOperatorClass:
2218
1.08k
    Cond = cast<ConditionalOperator>(Term)->getCond();
2219
1.08k
    break;
2220
624
  case Stmt::BinaryOperatorClass:
2221
624
    // When we encounter a logical operator (&& or ||) as a CFG terminator,
2222
624
    // then the condition is actually its LHS; otherwise, we'd encounter
2223
624
    // the parent, such as if-statement, as a terminator.
2224
624
    const auto *BO = cast<BinaryOperator>(Term);
2225
624
    assert(BO->isLogicalOp() &&
2226
624
           "CFG terminator is not a short-circuit operator!");
2227
624
    Cond = BO->getLHS();
2228
624
    break;
2229
4.52k
  }
2230
4.52k
2231
4.52k
  Cond = Cond->IgnoreParens();
2232
4.52k
2233
4.52k
  // However, when we encounter a logical operator as a branch condition,
2234
4.52k
  // then the condition is actually its RHS, because LHS would be
2235
4.52k
  // the condition for the logical operator terminator.
2236
4.65k
  while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
2237
2.16k
    if (!InnerBO->isLogicalOp())
2238
2.03k
      break;
2239
134
    Cond = InnerBO->getRHS()->IgnoreParens();
2240
134
  }
2241
4.52k
2242
4.52k
  assert(Cond);
2243
4.52k
  assert(srcBlk->succ_size() == 2);
2244
4.52k
  const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
2245
4.52k
  return VisitTrueTest(Cond, BRC, R, N, TookTrue);
2246
4.52k
}
2247
2248
PathDiagnosticPieceRef
2249
ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC,
2250
                                  PathSensitiveBugReport &R,
2251
6.18k
                                  const ExplodedNode *N, bool TookTrue) {
2252
6.18k
  ProgramStateRef CurrentState = N->getState();
2253
6.18k
  ProgramStateRef PrevState = N->getFirstPred()->getState();
2254
6.18k
  const LocationContext *LCtx = N->getLocationContext();
2255
6.18k
2256
6.18k
  // If the constraint information is changed between the current and the
2257
6.18k
  // previous program state we assuming the newly seen constraint information.
2258
6.18k
  // If we cannot evaluate the condition (and the constraints are the same)
2259
6.18k
  // the analyzer has no information about the value and just assuming it.
2260
6.18k
  bool IsAssuming =
2261
6.18k
      !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
2262
6.18k
      
CurrentState->getSVal(Cond, LCtx).isUnknownOrUndef()2.30k
;
2263
6.18k
2264
6.18k
  // These will be modified in code below, but we need to preserve the original
2265
6.18k
  //  values in case we want to throw the generic message.
2266
6.18k
  const Expr *CondTmp = Cond;
2267
6.18k
  bool TookTrueTmp = TookTrue;
2268
6.18k
2269
6.52k
  while (true) {
2270
6.52k
    CondTmp = CondTmp->IgnoreParenCasts();
2271
6.52k
    switch (CondTmp->getStmtClass()) {
2272
904
      default:
2273
904
        break;
2274
3.85k
      case Stmt::BinaryOperatorClass:
2275
3.85k
        if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
2276
1.43k
                                   BRC, R, N, TookTrueTmp, IsAssuming))
2277
1.43k
          return P;
2278
2.42k
        break;
2279
2.42k
      case Stmt::DeclRefExprClass:
2280
1.25k
        if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
2281
1.24k
                                   BRC, R, N, TookTrueTmp, IsAssuming))
2282
1.24k
          return P;
2283
10
        break;
2284
152
      case Stmt::MemberExprClass:
2285
152
        if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
2286
111
                                   BRC, R, N, TookTrueTmp, IsAssuming))
2287
111
          return P;
2288
41
        break;
2289
355
      case Stmt::UnaryOperatorClass: {
2290
355
        const auto *UO = cast<UnaryOperator>(CondTmp);
2291
355
        if (UO->getOpcode() == UO_LNot) {
2292
344
          TookTrueTmp = !TookTrueTmp;
2293
344
          CondTmp = UO->getSubExpr();
2294
344
          continue;
2295
344
        }
2296
11
        break;
2297
11
      }
2298
3.38k
    }
2299
3.38k
    break;
2300
3.38k
  }
2301
6.18k
2302
6.18k
  // Condition too complex to explain? Just say something so that the user
2303
6.18k
  // knew we've made some path decision at this point.
2304
6.18k
  // If it is too complex and we know the evaluation of the condition do not
2305
6.18k
  // repeat the note from 'BugReporter.cpp'
2306
6.18k
  
if (3.38k
!IsAssuming3.38k
)
2307
1.33k
    return nullptr;
2308
2.05k
2309
2.05k
  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2310
2.05k
  if (!Loc.isValid() || !Loc.asLocation().isValid())
2311
4
    return nullptr;
2312
2.05k
2313
2.05k
  return std::make_shared<PathDiagnosticEventPiece>(
2314
2.05k
      Loc, TookTrue ? 
GenericTrueMessage1.52k
:
GenericFalseMessage527
);
2315
2.05k
}
2316
2317
bool ConditionBRVisitor::patternMatch(const Expr *Ex,
2318
                                      const Expr *ParentEx,
2319
                                      raw_ostream &Out,
2320
                                      BugReporterContext &BRC,
2321
                                      PathSensitiveBugReport &report,
2322
                                      const ExplodedNode *N,
2323
                                      Optional<bool> &prunable,
2324
7.71k
                                      bool IsSameFieldName) {
2325
7.71k
  const Expr *OriginalExpr = Ex;
2326
7.71k
  Ex = Ex->IgnoreParenCasts();
2327
7.71k
2328
7.71k
  if (isa<GNUNullExpr>(Ex) || 
isa<ObjCBoolLiteralExpr>(Ex)7.71k
||
2329
7.71k
      
isa<CXXBoolLiteralExpr>(Ex)7.71k
||
isa<IntegerLiteral>(Ex)7.45k
||
2330
7.71k
      
isa<FloatingLiteral>(Ex)5.80k
) {
2331
1.92k
    // Use heuristics to determine if the expression is a macro
2332
1.92k
    // expanding to a literal and if so, use the macro's name.
2333
1.92k
    SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
2334
1.92k
    SourceLocation EndLoc = OriginalExpr->getEndLoc();
2335
1.92k
    if (BeginLoc.isMacroID() && 
EndLoc.isMacroID()89
) {
2336
89
      const SourceManager &SM = BRC.getSourceManager();
2337
89
      const LangOptions &LO = BRC.getASTContext().getLangOpts();
2338
89
      if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
2339
89
          
Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)14
) {
2340
14
        CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
2341
14
        Out << Lexer::getSourceText(R, SM, LO);
2342
14
        return false;
2343
14
      }
2344
7.70k
    }
2345
1.92k
  }
2346
7.70k
2347
7.70k
  if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
2348
2.37k
    const bool quotes = isa<VarDecl>(DR->getDecl());
2349
2.37k
    if (quotes) {
2350
2.36k
      Out << '\'';
2351
2.36k
      const LocationContext *LCtx = N->getLocationContext();
2352
2.36k
      const ProgramState *state = N->getState().get();
2353
2.36k
      if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
2354
2.36k
                                                LCtx).getAsRegion()) {
2355
2.36k
        if (report.isInteresting(R))
2356
0
          prunable = false;
2357
2.36k
        else {
2358
2.36k
          const ProgramState *state = N->getState().get();
2359
2.36k
          SVal V = state->getSVal(R);
2360
2.36k
          if (report.isInteresting(V))
2361
103
            prunable = false;
2362
2.36k
        }
2363
2.36k
      }
2364
2.36k
    }
2365
2.37k
    Out << DR->getDecl()->getDeclName().getAsString();
2366
2.37k
    if (quotes)
2367
2.36k
      Out << '\'';
2368
2.37k
    return quotes;
2369
2.37k
  }
2370
5.32k
2371
5.32k
  if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2372
1.64k
    QualType OriginalTy = OriginalExpr->getType();
2373
1.64k
    if (OriginalTy->isPointerType()) {
2374
126
      if (IL->getValue() == 0) {
2375
126
        Out << "null";
2376
126
        return false;
2377
126
      }
2378
1.51k
    }
2379
1.51k
    else if (OriginalTy->isObjCObjectPointerType()) {
2380
4
      if (IL->getValue() == 0) {
2381
4
        Out << "nil";
2382
4
        return false;
2383
4
      }
2384
1.51k
    }
2385
1.51k
2386
1.51k
    Out << IL->getValue();
2387
1.51k
    return false;
2388
1.51k
  }
2389
3.68k
2390
3.68k
  if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
2391
283
    if (!IsSameFieldName)
2392
267
      Out << "field '" << ME->getMemberDecl()->getName() << '\'';
2393
16
    else
2394
16
      Out << '\''
2395
16
          << Lexer::getSourceText(
2396
16
                 CharSourceRange::getTokenRange(Ex->getSourceRange()),
2397
16
                 BRC.getSourceManager(), BRC.getASTContext().getLangOpts(), 0)
2398
16
          << '\'';
2399
283
  }
2400
3.68k
2401
3.68k
  return false;
2402
3.68k
}
2403
2404
PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
2405
    const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
2406
    PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue,
2407
3.85k
    bool IsAssuming) {
2408
3.85k
  bool shouldInvert = false;
2409
3.85k
  Optional<bool> shouldPrune;
2410
3.85k
2411
3.85k
  // Check if the field name of the MemberExprs is ambiguous. Example:
2412
3.85k
  // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'.
2413
3.85k
  bool IsSameFieldName = false;
2414
3.85k
  const auto *LhsME = dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts());
2415
3.85k
  const auto *RhsME = dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts());
2416
3.85k
2417
3.85k
  if (LhsME && 
RhsME275
)
2418
8
    IsSameFieldName =
2419
8
        LhsME->getMemberDecl()->getName() == RhsME->getMemberDecl()->getName();
2420
3.85k
2421
3.85k
  SmallString<128> LhsString, RhsString;
2422
3.85k
  {
2423
3.85k
    llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
2424
3.85k
    const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
2425
3.85k
                                       N, shouldPrune, IsSameFieldName);
2426
3.85k
    const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
2427
3.85k
                                       N, shouldPrune, IsSameFieldName);
2428
3.85k
2429
3.85k
    shouldInvert = !isVarLHS && 
isVarRHS1.66k
;
2430
3.85k
  }
2431
3.85k
2432
3.85k
  BinaryOperator::Opcode Op = BExpr->getOpcode();
2433
3.85k
2434
3.85k
  if (BinaryOperator::isAssignmentOp(Op)) {
2435
10
    // For assignment operators, all that we care about is that the LHS
2436
10
    // evaluates to "true" or "false".
2437
10
    return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
2438
10
                                  TookTrue);
2439
10
  }
2440
3.84k
2441
3.84k
  // For non-assignment operations, we require that we can understand
2442
3.84k
  // both the LHS and RHS.
2443
3.84k
  if (LhsString.empty() || 
RhsString.empty()2.47k
||
2444
3.84k
      
!BinaryOperator::isComparisonOp(Op)1.44k
||
Op == BO_Cmp1.42k
)
2445
2.42k
    return nullptr;
2446
1.42k
2447
1.42k
  // Should we invert the strings if the LHS is not a variable name?
2448
1.42k
  SmallString<256> buf;
2449
1.42k
  llvm::raw_svector_ostream Out(buf);
2450
1.42k
  Out << (IsAssuming ? 
"Assuming "1.01k
:
""409
)
2451
1.42k
      << (shouldInvert ? 
RhsString9
:
LhsString1.41k
) << " is ";
2452
1.42k
2453
1.42k
  // Do we need to invert the opcode?
2454
1.42k
  if (shouldInvert)
2455
9
    switch (Op) {
2456
9
      default: break;
2457
0
      case BO_LT: Op = BO_GT; break;
2458
0
      case BO_GT: Op = BO_LT; break;
2459
0
      case BO_LE: Op = BO_GE; break;
2460
0
      case BO_GE: Op = BO_LE; break;
2461
1.42k
    }
2462
1.42k
2463
1.42k
  if (!TookTrue)
2464
876
    switch (Op) {
2465
332
      case BO_EQ: Op = BO_NE; break;
2466
342
      case BO_NE: Op = BO_EQ; break;
2467
75
      case BO_LT: Op = BO_GE; break;
2468
90
      case BO_GT: Op = BO_LE; break;
2469
12
      case BO_LE: Op = BO_GT; break;
2470
25
      case BO_GE: Op = BO_LT; break;
2471
0
      default:
2472
0
        return nullptr;
2473
1.42k
    }
2474
1.42k
2475
1.42k
  switch (Op) {
2476
651
    case BO_EQ:
2477
651
      Out << "equal to ";
2478
651
      break;
2479
390
    case BO_NE:
2480
390
      Out << "not equal to ";
2481
390
      break;
2482
385
    default:
2483
385
      Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2484
385
      break;
2485
1.42k
  }
2486
1.42k
2487
1.42k
  Out << (shouldInvert ? 
LhsString9
:
RhsString1.41k
);
2488
1.42k
  const LocationContext *LCtx = N->getLocationContext();
2489
1.42k
  const SourceManager &SM = BRC.getSourceManager();
2490
1.42k
2491
1.42k
  if (isVarAnInterestingCondition(BExpr->getLHS(), N, &R) ||
2492
1.42k
      
isVarAnInterestingCondition(BExpr->getRHS(), N, &R)1.42k
)
2493
4
    Out << WillBeUsedForACondition;
2494
1.42k
2495
1.42k
  // Convert 'field ...' to 'Field ...' if it is a MemberExpr.
2496
1.42k
  std::string Message = std::string(Out.str());
2497
1.42k
  Message[0] = toupper(Message[0]);
2498
1.42k
2499
1.42k
  // If we know the value create a pop-up note to the value part of 'BExpr'.
2500
1.42k
  if (!IsAssuming) {
2501
409
    PathDiagnosticLocation Loc;
2502
409
    if (!shouldInvert) {
2503
403
      if (LhsME && 
LhsME->getMemberLoc().isValid()77
)
2504
77
        Loc = PathDiagnosticLocation(LhsME->getMemberLoc(), SM);
2505
326
      else
2506
326
        Loc = PathDiagnosticLocation(BExpr->getLHS(), SM, LCtx);
2507
403
    } else {
2508
6
      if (RhsME && 
RhsME->getMemberLoc().isValid()0
)
2509
0
        Loc = PathDiagnosticLocation(RhsME->getMemberLoc(), SM);
2510
6
      else
2511
6
        Loc = PathDiagnosticLocation(BExpr->getRHS(), SM, LCtx);
2512
6
    }
2513
409
2514
409
    return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
2515
409
  }
2516
1.01k
2517
1.01k
  PathDiagnosticLocation Loc(Cond, SM, LCtx);
2518
1.01k
  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
2519
1.01k
  if (shouldPrune.hasValue())
2520
86
    event->setPrunable(shouldPrune.getValue());
2521
1.01k
  return event;
2522
1.01k
}
2523
2524
PathDiagnosticPieceRef ConditionBRVisitor::VisitConditionVariable(
2525
    StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
2526
10
    PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue) {
2527
10
  // FIXME: If there's already a constraint tracker for this variable,
2528
10
  // we shouldn't emit anything here (c.f. the double note in
2529
10
  // test/Analysis/inlining/path-notes.c)
2530
10
  SmallString<256> buf;
2531
10
  llvm::raw_svector_ostream Out(buf);
2532
10
  Out << "Assuming " << LhsString << " is ";
2533
10
2534
10
  if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true))
2535
0
    return nullptr;
2536
10
2537
10
  const LocationContext *LCtx = N->getLocationContext();
2538
10
  PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2539
10
2540
10
  if (isVarAnInterestingCondition(CondVarExpr, N, &report))
2541
2
    Out << WillBeUsedForACondition;
2542
10
2543
10
  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2544
10
2545
10
  if (isInterestingExpr(CondVarExpr, N, &report))
2546
4
    event->setPrunable(false);
2547
10
2548
10
  return event;
2549
10
}
2550
2551
PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
2552
    const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
2553
    PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
2554
1.25k
    bool IsAssuming) {
2555
1.25k
  const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
2556
1.25k
  if (!VD)
2557
4
    return nullptr;
2558
1.25k
2559
1.25k
  SmallString<256> Buf;
2560
1.25k
  llvm::raw_svector_ostream Out(Buf);
2561
1.25k
2562
1.25k
  Out << (IsAssuming ? 
"Assuming '"816
:
"'"438
) << VD->getDeclName() << "' is ";
2563
1.25k
2564
1.25k
  if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
2565
6
    return nullptr;
2566
1.24k
2567
1.24k
  const LocationContext *LCtx = N->getLocationContext();
2568
1.24k
2569
1.24k
  if (isVarAnInterestingCondition(DRE, N, &report))
2570
15
    Out << WillBeUsedForACondition;
2571
1.24k
2572
1.24k
  // If we know the value create a pop-up note to the 'DRE'.
2573
1.24k
  if (!IsAssuming) {
2574
438
    PathDiagnosticLocation Loc(DRE, BRC.getSourceManager(), LCtx);
2575
438
    return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
2576
438
  }
2577
810
2578
810
  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2579
810
  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2580
810
2581
810
  if (isInterestingExpr(DRE, N, &report))
2582
321
    event->setPrunable(false);
2583
810
2584
810
  return std::move(event);
2585
810
}
2586
2587
PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
2588
    const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
2589
    PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
2590
152
    bool IsAssuming) {
2591
152
  SmallString<256> Buf;
2592
152
  llvm::raw_svector_ostream Out(Buf);
2593
152
2594
152
  Out << (IsAssuming ? 
"Assuming field '"41
:
"Field '"111
)
2595
152
      << ME->getMemberDecl()->getName() << "' is ";
2596
152
2597
152
  if (!printValue(ME, Out, N, TookTrue, IsAssuming))
2598
0
    return nullptr;
2599
152
2600
152
  const LocationContext *LCtx = N->getLocationContext();
2601
152
  PathDiagnosticLocation Loc;
2602
152
2603
152
  // If we know the value create a pop-up note to the member of the MemberExpr.
2604
152
  if (!IsAssuming && 
ME->getMemberLoc().isValid()111
)
2605
70
    Loc = PathDiagnosticLocation(ME->getMemberLoc(), BRC.getSourceManager());
2606
82
  else
2607
82
    Loc = PathDiagnosticLocation(Cond, BRC.getSourceManager(), LCtx);
2608
152
2609
152
  if (!Loc.isValid() || !Loc.asLocation().isValid())
2610
41
    return nullptr;
2611
111
2612
111
  if (isVarAnInterestingCondition(ME, N, &report))
2613
2
    Out << WillBeUsedForACondition;
2614
111
2615
111
  // If we know the value create a pop-up note.
2616
111
  if (!IsAssuming)
2617
70
    return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
2618
41
2619
41
  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2620
41
  if (isInterestingExpr(ME, N, &report))
2621
8
    event->setPrunable(false);
2622
41
  return event;
2623
41
}
2624
2625
bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
2626
                                    const ExplodedNode *N, bool TookTrue,
2627
1.41k
                                    bool IsAssuming) {
2628
1.41k
  QualType Ty = CondVarExpr->getType();
2629
1.41k
2630
1.41k
  if (Ty->isPointerType()) {
2631
501
    Out << (TookTrue ? 
"non-null"133
:
"null"368
);
2632
501
    return true;
2633
501
  }
2634
915
2635
915
  if (Ty->isObjCObjectPointerType()) {
2636
81
    Out << (TookTrue ? 
"non-nil"39
:
"nil"42
);
2637
81
    return true;
2638
81
  }
2639
834
2640
834
  if (!Ty->isIntegralOrEnumerationType())
2641
6
    return false;
2642
828
2643
828
  Optional<const llvm::APSInt *> IntValue;
2644
828
  if (!IsAssuming)
2645
372
    IntValue = getConcreteIntegerValue(CondVarExpr, N);
2646
828
2647
828
  if (IsAssuming || 
!IntValue.hasValue()372
) {
2648
683
    if (Ty->isBooleanType())
2649
78
      Out << (TookTrue ? 
"true"48
:
"false"30
);
2650
605
    else
2651
605
      Out << (TookTrue ? 
"not equal to 0"348
:
"0"257
);
2652
683
  } else {
2653
145
    if (Ty->isBooleanType())
2654
18
      Out << (IntValue.getValue()->getBoolValue() ? 
"true"7
:
"false"11
);
2655
127
    else
2656
127
      Out << *IntValue.getValue();
2657
145
  }
2658
828
2659
828
  return true;
2660
828
}
2661
2662
constexpr llvm::StringLiteral ConditionBRVisitor::GenericTrueMessage;
2663
constexpr llvm::StringLiteral ConditionBRVisitor::GenericFalseMessage;
2664
2665
bool ConditionBRVisitor::isPieceMessageGeneric(
2666
107
    const PathDiagnosticPiece *Piece) {
2667
107
  return Piece->getString() == GenericTrueMessage ||
2668
107
         
Piece->getString() == GenericFalseMessage104
;
2669
107
}
2670
2671
//===----------------------------------------------------------------------===//
2672
// Implementation of LikelyFalsePositiveSuppressionBRVisitor.
2673
//===----------------------------------------------------------------------===//
2674
2675
void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
2676
    BugReporterContext &BRC, const ExplodedNode *N,
2677
12.0k
    PathSensitiveBugReport &BR) {
2678
12.0k
  // Here we suppress false positives coming from system headers. This list is
2679
12.0k
  // based on known issues.
2680
12.0k
  const AnalyzerOptions &Options = BRC.getAnalyzerOptions();
2681
12.0k
  const Decl *D = N->getLocationContext()->getDecl();
2682
12.0k
2683
12.0k
  if (AnalysisDeclContext::isInStdNamespace(D)) {
2684
15
    // Skip reports within the 'std' namespace. Although these can sometimes be
2685
15
    // the user's fault, we currently don't report them very well, and
2686
15
    // Note that this will not help for any other data structure libraries, like
2687
15
    // TR1, Boost, or llvm/ADT.
2688
15
    if (Options.ShouldSuppressFromCXXStandardLibrary) {
2689
14
      BR.markInvalid(getTag(), nullptr);
2690
14
      return;
2691
14
    } else {
2692
1
      // If the complete 'std' suppression is not enabled, suppress reports
2693
1
      // from the 'std' namespace that are known to produce false positives.
2694
1
2695
1
      // The analyzer issues a false use-after-free when std::list::pop_front
2696
1
      // or std::list::pop_back are called multiple times because we cannot
2697
1
      // reason about the internal invariants of the data structure.
2698
1
      if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2699
0
        const CXXRecordDecl *CD = MD->getParent();
2700
0
        if (CD->getName() == "list") {
2701
0
          BR.markInvalid(getTag(), nullptr);
2702
0
          return;
2703
0
        }
2704
1
      }
2705
1
2706
1
      // The analyzer issues a false positive when the constructor of
2707
1
      // std::__independent_bits_engine from algorithms is used.
2708
1
      if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2709
0
        const CXXRecordDecl *CD = MD->getParent();
2710
0
        if (CD->getName() == "__independent_bits_engine") {
2711
0
          BR.markInvalid(getTag(), nullptr);
2712
0
          return;
2713
0
        }
2714
1
      }
2715
1
2716
4
      
for (const LocationContext *LCtx = N->getLocationContext(); 1
LCtx;
2717
3
           LCtx = LCtx->getParent()) {
2718
3
        const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2719
3
        if (!MD)
2720
3
          continue;
2721
0
2722
0
        const CXXRecordDecl *CD = MD->getParent();
2723
0
        // The analyzer issues a false positive on
2724
0
        //   std::basic_string<uint8_t> v; v.push_back(1);
2725
0
        // and
2726
0
        //   std::u16string s; s += u'a';
2727
0
        // because we cannot reason about the internal invariants of the
2728
0
        // data structure.
2729
0
        if (CD->getName() == "basic_string") {
2730
0
          BR.markInvalid(getTag(), nullptr);
2731
0
          return;
2732
0
        }
2733
0
2734
0
        // The analyzer issues a false positive on
2735
0
        //    std::shared_ptr<int> p(new int(1)); p = nullptr;
2736
0
        // because it does not reason properly about temporary destructors.
2737
0
        if (CD->getName() == "shared_ptr") {
2738
0
          BR.markInvalid(getTag(), nullptr);
2739
0
          return;
2740
0
        }
2741
0
      }
2742
1
    }
2743
15
  }
2744
12.0k
2745
12.0k
  // Skip reports within the sys/queue.h macros as we do not have the ability to
2746
12.0k
  // reason about data structure shapes.
2747
12.0k
  const SourceManager &SM = BRC.getSourceManager();
2748
11.9k
  FullSourceLoc Loc = BR.getLocation().asLocation();
2749
12.3k
  while (Loc.isMacroID()) {
2750
403
    Loc = Loc.getSpellingLoc();
2751
403
    if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2752
2
      BR.markInvalid(getTag(), nullptr);
2753
2
      return;
2754
2
    }
2755
403
  }
2756
11.9k
}
2757
2758
//===----------------------------------------------------------------------===//
2759
// Implementation of UndefOrNullArgVisitor.
2760
//===----------------------------------------------------------------------===//
2761
2762
PathDiagnosticPieceRef
2763
UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
2764
104k
                                 PathSensitiveBugReport &BR) {
2765
104k
  ProgramStateRef State = N->getState();
2766
104k
  ProgramPoint ProgLoc = N->getLocation();
2767
104k
2768
104k
  // We are only interested in visiting CallEnter nodes.
2769
104k
  Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2770
104k
  if (!CEnter)
2771
103k
    return nullptr;
2772
1.49k
2773
1.49k
  // Check if one of the arguments is the region the visitor is tracking.
2774
1.49k
  CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2775
1.49k
  CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2776
1.49k
  unsigned Idx = 0;
2777
1.49k
  ArrayRef<ParmVarDecl *> parms = Call->parameters();
2778
1.49k
2779
1.49k
  for (const auto ParamDecl : parms) {
2780
978
    const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2781
978
    ++Idx;
2782
978
2783
978
    // Are we tracking the argument or its subregion?
2784
978
    if ( !ArgReg || 
!R->isSubRegionOf(ArgReg->StripCasts())431
)
2785
820
      continue;
2786
158
2787
158
    // Check the function parameter type.
2788
158
    assert(ParamDecl && "Formal parameter has no decl?");
2789
158
    QualType T = ParamDecl->getType();
2790
158
2791
158
    if (!(T->isAnyPointerType() || 
T->isReferenceType()72
)) {
2792
8
      // Function can only change the value passed in by address.
2793
8
      continue;
2794
8
    }
2795
150
2796
150
    // If it is a const pointer value, the function does not intend to
2797
150
    // change the value.
2798
150
    if (T->getPointeeType().isConstQualified())
2799
21
      continue;
2800
129
2801
129
    // Mark the call site (LocationContext) as interesting if the value of the
2802
129
    // argument is undefined or '0'/'NULL'.
2803
129
    SVal BoundVal = State->getSVal(R);
2804
129
    if (BoundVal.isUndef() || 
BoundVal.isZeroConstant()28
) {
2805
110
      BR.markInteresting(CEnter->getCalleeContext());
2806
110
      return nullptr;
2807
110
    }
2808
129
  }
2809
1.49k
  
return nullptr1.38k
;
2810
1.49k
}
2811
2812
//===----------------------------------------------------------------------===//
2813
// Implementation of FalsePositiveRefutationBRVisitor.
2814
//===----------------------------------------------------------------------===//
2815
2816
FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
2817
0
    : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
2818
2819
void FalsePositiveRefutationBRVisitor::finalizeVisitor(
2820
    BugReporterContext &BRC, const ExplodedNode *EndPathNode,
2821
0
    PathSensitiveBugReport &BR) {
2822
0
  // Collect new constraints
2823
0
  VisitNode(EndPathNode, BRC, BR);
2824
0
2825
0
  // Create a refutation manager
2826
0
  llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver();
2827
0
  ASTContext &Ctx = BRC.getASTContext();
2828
0
2829
0
  // Add constraints to the solver
2830
0
  for (const auto &I : Constraints) {
2831
0
    const SymbolRef Sym = I.first;
2832
0
    auto RangeIt = I.second.begin();
2833
0
2834
0
    llvm::SMTExprRef Constraints = SMTConv::getRangeExpr(
2835
0
        RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
2836
0
        /*InRange=*/true);
2837
0
    while ((++RangeIt) != I.second.end()) {
2838
0
      Constraints = RefutationSolver->mkOr(
2839
0
          Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
2840
0
                                             RangeIt->From(), RangeIt->To(),
2841
0
                                             /*InRange=*/true));
2842
0
    }
2843
0
2844
0
    RefutationSolver->addConstraint(Constraints);
2845
0
  }
2846
0
2847
0
  // And check for satisfiability
2848
0
  Optional<bool> isSat = RefutationSolver->check();
2849
0
  if (!isSat.hasValue())
2850
0
    return;
2851
0
2852
0
  if (!isSat.getValue())
2853
0
    BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
2854
0
}
2855
2856
PathDiagnosticPieceRef FalsePositiveRefutationBRVisitor::VisitNode(
2857
0
    const ExplodedNode *N, BugReporterContext &, PathSensitiveBugReport &) {
2858
0
  // Collect new constraints
2859
0
  const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
2860
0
  ConstraintRangeTy::Factory &CF =
2861
0
      N->getState()->get_context<ConstraintRange>();
2862
0
2863
0
  // Add constraints if we don't have them yet
2864
0
  for (auto const &C : NewCs) {
2865
0
    const SymbolRef &Sym = C.first;
2866
0
    if (!Constraints.contains(Sym)) {
2867
0
      Constraints = CF.add(Constraints, Sym, C.second);
2868
0
    }
2869
0
  }
2870
0
2871
0
  return nullptr;
2872
0
}
2873
2874
void FalsePositiveRefutationBRVisitor::Profile(
2875
0
    llvm::FoldingSetNodeID &ID) const {
2876
0
  static int Tag = 0;
2877
0
  ID.AddPointer(&Tag);
2878
0
}
2879
2880
//===----------------------------------------------------------------------===//
2881
// Implementation of TagVisitor.
2882
//===----------------------------------------------------------------------===//
2883
2884
int NoteTag::Kind = 0;
2885
2886
12.1k
void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
2887
12.1k
  static int Tag = 0;
2888
12.1k
  ID.AddPointer(&Tag);
2889
12.1k
}
2890
2891
PathDiagnosticPieceRef TagVisitor::VisitNode(const ExplodedNode *N,
2892
                                             BugReporterContext &BRC,
2893
1.26M
                                             PathSensitiveBugReport &R) {
2894
1.26M
  ProgramPoint PP = N->getLocation();
2895
1.26M
  const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
2896
1.26M
  if (!T)
2897
1.26M
    return nullptr;
2898
185
2899
185
  if (Optional<std::string> Msg = T->generateMessage(BRC, R)) {
2900
183
    PathDiagnosticLocation Loc =
2901
183
        PathDiagnosticLocation::create(PP, BRC.getSourceManager());
2902
183
    auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
2903
183
    Piece->setPrunable(T->isPrunable());
2904
183
    return Piece;
2905
183
  }
2906
2
2907
2
  return nullptr;
2908
2
}