1 //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines a set of BugReporter "visitors" which can be used to
11 //  enhance the diagnostics reported for a bug.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/Stmt.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Analysis/AnalysisDeclContext.h"
26 #include "clang/Analysis/CFG.h"
27 #include "clang/Analysis/CFGStmtMap.h"
28 #include "clang/Analysis/ProgramPoint.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/SourceLocation.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Lex/Lexer.h"
34 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
35 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
36 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
37 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
38 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
39 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
40 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
41 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/None.h"
49 #include "llvm/ADT/Optional.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallString.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/ADT/StringRef.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <cassert>
60 #include <deque>
61 #include <memory>
62 #include <string>
63 #include <utility>
64 
65 using namespace clang;
66 using namespace ento;
67 
68 //===----------------------------------------------------------------------===//
69 // Utility functions.
70 //===----------------------------------------------------------------------===//
71 
72 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
73   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
74     return DRE->getDecl()->getType()->isReferenceType();
75   return false;
76 }
77 
78 static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
79   if (B->isAdditiveOp() && B->getType()->isPointerType()) {
80     if (B->getLHS()->getType()->isPointerType()) {
81       return B->getLHS();
82     } else if (B->getRHS()->getType()->isPointerType()) {
83       return B->getRHS();
84     }
85   }
86   return nullptr;
87 }
88 
89 /// Given that expression S represents a pointer that would be dereferenced,
90 /// try to find a sub-expression from which the pointer came from.
91 /// This is used for tracking down origins of a null or undefined value:
92 /// "this is null because that is null because that is null" etc.
93 /// We wipe away field and element offsets because they merely add offsets.
94 /// We also wipe away all casts except lvalue-to-rvalue casts, because the
95 /// latter represent an actual pointer dereference; however, we remove
96 /// the final lvalue-to-rvalue cast before returning from this function
97 /// because it demonstrates more clearly from where the pointer rvalue was
98 /// loaded. Examples:
99 ///   x->y.z      ==>  x (lvalue)
100 ///   foo()->y.z  ==>  foo() (rvalue)
101 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
102   const auto *E = dyn_cast<Expr>(S);
103   if (!E)
104     return nullptr;
105 
106   while (true) {
107     if (const auto *CE = dyn_cast<CastExpr>(E)) {
108       if (CE->getCastKind() == CK_LValueToRValue) {
109         // This cast represents the load we're looking for.
110         break;
111       }
112       E = CE->getSubExpr();
113     } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
114       // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
115       if (const Expr *Inner = peelOffPointerArithmetic(B)) {
116         E = Inner;
117       } else {
118         // Probably more arithmetic can be pattern-matched here,
119         // but for now give up.
120         break;
121       }
122     } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
123       if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
124           (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
125         // Operators '*' and '&' don't actually mean anything.
126         // We look at casts instead.
127         E = U->getSubExpr();
128       } else {
129         // Probably more arithmetic can be pattern-matched here,
130         // but for now give up.
131         break;
132       }
133     }
134     // Pattern match for a few useful cases: a[0], p->f, *p etc.
135     else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
136       E = ME->getBase();
137     } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
138       E = IvarRef->getBase();
139     } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
140       E = AE->getBase();
141     } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
142       E = PE->getSubExpr();
143     } else {
144       // Other arbitrary stuff.
145       break;
146     }
147   }
148 
149   // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
150   // deeper into the sub-expression. This way we return the lvalue from which
151   // our pointer rvalue was loaded.
152   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
153     if (CE->getCastKind() == CK_LValueToRValue)
154       E = CE->getSubExpr();
155 
156   return E;
157 }
158 
159 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
160   const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
161   if (const auto *BE = dyn_cast<BinaryOperator>(S))
162     return BE->getRHS();
163   return nullptr;
164 }
165 
166 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
167   const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
168   if (const auto *RS = dyn_cast<ReturnStmt>(S))
169     return RS->getRetValue();
170   return nullptr;
171 }
172 
173 //===----------------------------------------------------------------------===//
174 // Definitions for bug reporter visitors.
175 //===----------------------------------------------------------------------===//
176 
177 std::unique_ptr<PathDiagnosticPiece>
178 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
179                                const ExplodedNode *EndPathNode, BugReport &BR) {
180   return nullptr;
181 }
182 
183 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
184     BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
185   PathDiagnosticLocation L =
186     PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
187 
188   const auto &Ranges = BR.getRanges();
189 
190   // Only add the statement itself as a range if we didn't specify any
191   // special ranges for this report.
192   auto P = llvm::make_unique<PathDiagnosticEventPiece>(
193       L, BR.getDescription(), Ranges.begin() == Ranges.end());
194   for (SourceRange Range : Ranges)
195     P->addRange(Range);
196 
197   return std::move(P);
198 }
199 
200 /// \return name of the macro inside the location \p Loc.
201 static StringRef getMacroName(SourceLocation Loc,
202     BugReporterContext &BRC) {
203   return Lexer::getImmediateMacroName(
204       Loc,
205       BRC.getSourceManager(),
206       BRC.getASTContext().getLangOpts());
207 }
208 
209 /// \return Whether given spelling location corresponds to an expansion
210 /// of a function-like macro.
211 static bool isFunctionMacroExpansion(SourceLocation Loc,
212                                 const SourceManager &SM) {
213   if (!Loc.isMacroID())
214     return false;
215   while (SM.isMacroArgExpansion(Loc))
216     Loc = SM.getImmediateExpansionRange(Loc).getBegin();
217   std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
218   SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
219   const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
220   return EInfo.isFunctionMacroExpansion();
221 }
222 
223 namespace {
224 
225 /// Put a diagnostic on return statement of all inlined functions
226 /// for which  the region of interest \p RegionOfInterest was passed into,
227 /// but not written inside, and it has caused an undefined read or a null
228 /// pointer dereference outside.
229 class NoStoreFuncVisitor final
230     : public BugReporterVisitorImpl<NoStoreFuncVisitor> {
231   const SubRegion *RegionOfInterest;
232   static constexpr const char *DiagnosticsMsg =
233       "Returning without writing to '";
234 
235   /// Frames writing into \c RegionOfInterest.
236   /// This visitor generates a note only if a function does not write into
237   /// a region of interest. This information is not immediately available
238   /// by looking at the node associated with the exit from the function
239   /// (usually the return statement). To avoid recomputing the same information
240   /// many times (going up the path for each node and checking whether the
241   /// region was written into) we instead lazily compute the
242   /// stack frames along the path which write into the region of interest.
243   llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
244   llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
245 
246 public:
247   NoStoreFuncVisitor(const SubRegion *R) : RegionOfInterest(R) {}
248 
249   void Profile(llvm::FoldingSetNodeID &ID) const override {
250     static int Tag = 0;
251     ID.AddPointer(&Tag);
252   }
253 
254   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
255                                                  const ExplodedNode *PrevN,
256                                                  BugReporterContext &BRC,
257                                                  BugReport &BR) override {
258 
259     const LocationContext *Ctx = N->getLocationContext();
260     const StackFrameContext *SCtx = Ctx->getCurrentStackFrame();
261     ProgramStateRef State = N->getState();
262     auto CallExitLoc = N->getLocationAs<CallExitBegin>();
263 
264     // No diagnostic if region was modified inside the frame.
265     if (!CallExitLoc)
266       return nullptr;
267 
268     CallEventRef<> Call =
269         BRC.getStateManager().getCallEventManager().getCaller(SCtx, State);
270 
271     const PrintingPolicy &PP = BRC.getASTContext().getPrintingPolicy();
272     const SourceManager &SM = BRC.getSourceManager();
273     if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
274       const MemRegion *ThisRegion = CCall->getCXXThisVal().getAsRegion();
275       if (RegionOfInterest->isSubRegionOf(ThisRegion)
276           && !CCall->getDecl()->isImplicit()
277           && !isRegionOfInterestModifiedInFrame(N))
278         return notModifiedInConstructorDiagnostics(Ctx, SM, PP, *CallExitLoc,
279                                                    CCall, ThisRegion);
280     }
281 
282     ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
283     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
284       const ParmVarDecl *PVD = parameters[I];
285       SVal S = Call->getArgSVal(I);
286       unsigned IndirectionLevel = 1;
287       QualType T = PVD->getType();
288       while (const MemRegion *R = S.getAsRegion()) {
289         if (RegionOfInterest->isSubRegionOf(R)
290             && !isPointerToConst(PVD->getType())) {
291 
292           if (isRegionOfInterestModifiedInFrame(N))
293             return nullptr;
294 
295           return notModifiedDiagnostics(
296               Ctx, SM, PP, *CallExitLoc, Call, PVD, R, IndirectionLevel);
297         }
298         QualType PT = T->getPointeeType();
299         if (PT.isNull() || PT->isVoidType()) break;
300         S = State->getSVal(R, PT);
301         T = PT;
302         IndirectionLevel++;
303       }
304     }
305 
306     return nullptr;
307   }
308 
309 private:
310   /// Check and lazily calculate whether the region of interest is
311   /// modified in the stack frame to which \p N belongs.
312   /// The calculation is cached in FramesModifyingRegion.
313   bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
314     const LocationContext *Ctx = N->getLocationContext();
315     const StackFrameContext *SCtx = Ctx->getCurrentStackFrame();
316     if (!FramesModifyingCalculated.count(SCtx))
317       findModifyingFrames(N);
318     return FramesModifyingRegion.count(SCtx);
319   }
320 
321 
322   /// Write to \c FramesModifyingRegion all stack frames along
323   /// the path in the current stack frame which modify \c RegionOfInterest.
324   void findModifyingFrames(const ExplodedNode *N) {
325     assert(N->getLocationAs<CallExitBegin>());
326     ProgramStateRef LastReturnState = N->getState();
327     SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
328     const LocationContext *Ctx = N->getLocationContext();
329     const StackFrameContext *OriginalSCtx = Ctx->getCurrentStackFrame();
330 
331     do {
332       ProgramStateRef State = N->getState();
333       auto CallExitLoc = N->getLocationAs<CallExitBegin>();
334       if (CallExitLoc) {
335         LastReturnState = State;
336         ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
337       }
338 
339       FramesModifyingCalculated.insert(
340         N->getLocationContext()->getCurrentStackFrame());
341 
342       if (wasRegionOfInterestModifiedAt(N, LastReturnState, ValueAtReturn)) {
343         const StackFrameContext *SCtx =
344             N->getLocationContext()->getCurrentStackFrame();
345         while (!SCtx->inTopFrame()) {
346           auto p = FramesModifyingRegion.insert(SCtx);
347           if (!p.second)
348             break; // Frame and all its parents already inserted.
349           SCtx = SCtx->getParent()->getCurrentStackFrame();
350         }
351       }
352 
353       // Stop calculation at the call to the current function.
354       if (auto CE = N->getLocationAs<CallEnter>())
355         if (CE->getCalleeContext() == OriginalSCtx)
356           break;
357 
358       N = N->getFirstPred();
359     } while (N);
360   }
361 
362   /// \return Whether \c RegionOfInterest was modified at \p N,
363   /// where \p ReturnState is a state associated with the return
364   /// from the current frame.
365   bool wasRegionOfInterestModifiedAt(const ExplodedNode *N,
366                                      ProgramStateRef ReturnState,
367                                      SVal ValueAtReturn) {
368     if (!N->getLocationAs<PostStore>()
369         && !N->getLocationAs<PostInitializer>()
370         && !N->getLocationAs<PostStmt>())
371       return false;
372 
373     // Writing into region of interest.
374     if (auto PS = N->getLocationAs<PostStmt>())
375       if (auto *BO = PS->getStmtAs<BinaryOperator>())
376         if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
377                                         N->getSVal(BO->getLHS()).getAsRegion()))
378           return true;
379 
380     // SVal after the state is possibly different.
381     SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
382     if (!ReturnState->areEqual(ValueAtN, ValueAtReturn).isConstrainedTrue() &&
383         (!ValueAtN.isUndef() || !ValueAtReturn.isUndef()))
384       return true;
385 
386     return false;
387   }
388 
389   /// Get parameters associated with runtime definition in order
390   /// to get the correct parameter name.
391   ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
392     // Use runtime definition, if available.
393     RuntimeDefinition RD = Call->getRuntimeDefinition();
394     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
395       return FD->parameters();
396 
397     return Call->parameters();
398   }
399 
400   /// \return whether \p Ty points to a const type, or is a const reference.
401   bool isPointerToConst(QualType Ty) {
402     return !Ty->getPointeeType().isNull() &&
403            Ty->getPointeeType().getCanonicalType().isConstQualified();
404   }
405 
406   std::shared_ptr<PathDiagnosticPiece> notModifiedInConstructorDiagnostics(
407       const LocationContext *Ctx,
408       const SourceManager &SM,
409       const PrintingPolicy &PP,
410       CallExitBegin &CallExitLoc,
411       const CXXConstructorCall *Call,
412       const MemRegion *ArgRegion) {
413     SmallString<256> sbuf;
414     llvm::raw_svector_ostream os(sbuf);
415     os << DiagnosticsMsg;
416     bool out = prettyPrintRegionName(
417         "this", "->", /*IsReference=*/true,
418         /*IndirectionLevel=*/1, ArgRegion, os, PP);
419 
420     // Return nothing if we have failed to pretty-print.
421     if (!out)
422       return nullptr;
423 
424     os << "'";
425     PathDiagnosticLocation L =
426         getPathDiagnosticLocation(nullptr, SM, Ctx, Call);
427     return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
428   }
429 
430   /// \p IndirectionLevel How many times \c ArgRegion has to be dereferenced
431   /// before we get to the super region of \c RegionOfInterest
432   std::shared_ptr<PathDiagnosticPiece>
433   notModifiedDiagnostics(const LocationContext *Ctx,
434                          const SourceManager &SM,
435                          const PrintingPolicy &PP,
436                          CallExitBegin &CallExitLoc,
437                          CallEventRef<> Call,
438                          const ParmVarDecl *PVD,
439                          const MemRegion *ArgRegion,
440                          unsigned IndirectionLevel) {
441     PathDiagnosticLocation L = getPathDiagnosticLocation(
442         CallExitLoc.getReturnStmt(), SM, Ctx, Call);
443     SmallString<256> sbuf;
444     llvm::raw_svector_ostream os(sbuf);
445     os << DiagnosticsMsg;
446     bool IsReference = PVD->getType()->isReferenceType();
447     const char *Sep = IsReference && IndirectionLevel == 1 ? "." : "->";
448     bool Success = prettyPrintRegionName(
449         PVD->getQualifiedNameAsString().c_str(),
450         Sep, IsReference, IndirectionLevel, ArgRegion, os, PP);
451 
452     // Print the parameter name if the pretty-printing has failed.
453     if (!Success)
454       PVD->printQualifiedName(os);
455     os << "'";
456     return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
457   }
458 
459   /// \return a path diagnostic location for the optionally
460   /// present return statement \p RS.
461   PathDiagnosticLocation getPathDiagnosticLocation(const ReturnStmt *RS,
462                                                    const SourceManager &SM,
463                                                    const LocationContext *Ctx,
464                                                    CallEventRef<> Call) {
465     if (RS)
466       return PathDiagnosticLocation::createBegin(RS, SM, Ctx);
467     return PathDiagnosticLocation(
468         Call->getRuntimeDefinition().getDecl()->getSourceRange().getEnd(), SM);
469   }
470 
471   /// Pretty-print region \p ArgRegion starting from parent to \p os.
472   /// \return whether printing has succeeded
473   bool prettyPrintRegionName(const char *TopRegionName,
474                              const char *Sep,
475                              bool IsReference,
476                              int IndirectionLevel,
477                              const MemRegion *ArgRegion,
478                              llvm::raw_svector_ostream &os,
479                              const PrintingPolicy &PP) {
480     SmallVector<const MemRegion *, 5> Subregions;
481     const MemRegion *R = RegionOfInterest;
482     while (R != ArgRegion) {
483       if (!(isa<FieldRegion>(R) || isa<CXXBaseObjectRegion>(R)))
484         return false; // Pattern-matching failed.
485       Subregions.push_back(R);
486       R = cast<SubRegion>(R)->getSuperRegion();
487     }
488     bool IndirectReference = !Subregions.empty();
489 
490     if (IndirectReference)
491       IndirectionLevel--; // Due to "->" symbol.
492 
493     if (IsReference)
494       IndirectionLevel--; // Due to reference semantics.
495 
496     bool ShouldSurround = IndirectReference && IndirectionLevel > 0;
497 
498     if (ShouldSurround)
499       os << "(";
500     for (int i = 0; i < IndirectionLevel; i++)
501       os << "*";
502     os << TopRegionName;
503     if (ShouldSurround)
504       os << ")";
505 
506     for (auto I = Subregions.rbegin(), E = Subregions.rend(); I != E; ++I) {
507       if (const auto *FR = dyn_cast<FieldRegion>(*I)) {
508         os << Sep;
509         FR->getDecl()->getDeclName().print(os, PP);
510         Sep = ".";
511       } else if (isa<CXXBaseObjectRegion>(*I)) {
512         continue; // Just keep going up to the base region.
513       } else {
514         llvm_unreachable("Previous check has missed an unexpected region");
515       }
516     }
517     return true;
518   }
519 };
520 
521 class MacroNullReturnSuppressionVisitor final
522     : public BugReporterVisitorImpl<MacroNullReturnSuppressionVisitor> {
523   const SubRegion *RegionOfInterest;
524 
525 public:
526   MacroNullReturnSuppressionVisitor(const SubRegion *R) : RegionOfInterest(R) {}
527 
528   static void *getTag() {
529     static int Tag = 0;
530     return static_cast<void *>(&Tag);
531   }
532 
533   void Profile(llvm::FoldingSetNodeID &ID) const override {
534     ID.AddPointer(getTag());
535   }
536 
537   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
538                                                  const ExplodedNode *PrevN,
539                                                  BugReporterContext &BRC,
540                                                  BugReport &BR) override {
541     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
542     if (!BugPoint)
543       return nullptr;
544 
545     const SourceManager &SMgr = BRC.getSourceManager();
546     if (auto Loc = matchAssignment(N, BRC)) {
547       if (isFunctionMacroExpansion(*Loc, SMgr)) {
548         std::string MacroName = getMacroName(*Loc, BRC);
549         SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
550         if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
551           BR.markInvalid(getTag(), MacroName.c_str());
552       }
553     }
554     return nullptr;
555   }
556 
557   static void addMacroVisitorIfNecessary(
558         const ExplodedNode *N, const MemRegion *R,
559         bool EnableNullFPSuppression, BugReport &BR,
560         const SVal V) {
561     AnalyzerOptions &Options = N->getState()->getStateManager()
562         .getOwningEngine()->getAnalysisManager().options;
563     if (EnableNullFPSuppression && Options.shouldSuppressNullReturnPaths()
564           && V.getAs<Loc>())
565       BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
566               R->getAs<SubRegion>()));
567   }
568 
569 private:
570   /// \return Source location of right hand side of an assignment
571   /// into \c RegionOfInterest, empty optional if none found.
572   Optional<SourceLocation> matchAssignment(const ExplodedNode *N,
573                                            BugReporterContext &BRC) {
574     const Stmt *S = PathDiagnosticLocation::getStmt(N);
575     ProgramStateRef State = N->getState();
576     auto *LCtx = N->getLocationContext();
577     if (!S)
578       return None;
579 
580     if (const auto *DS = dyn_cast<DeclStmt>(S)) {
581       if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
582         if (const Expr *RHS = VD->getInit())
583           if (RegionOfInterest->isSubRegionOf(
584                   State->getLValue(VD, LCtx).getAsRegion()))
585             return RHS->getLocStart();
586     } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
587       const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
588       const Expr *RHS = BO->getRHS();
589       if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
590         return RHS->getLocStart();
591       }
592     }
593     return None;
594   }
595 };
596 
597 /// Emits an extra note at the return statement of an interesting stack frame.
598 ///
599 /// The returned value is marked as an interesting value, and if it's null,
600 /// adds a visitor to track where it became null.
601 ///
602 /// This visitor is intended to be used when another visitor discovers that an
603 /// interesting value comes from an inlined function call.
604 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
605   const StackFrameContext *StackFrame;
606   enum {
607     Initial,
608     MaybeUnsuppress,
609     Satisfied
610   } Mode = Initial;
611 
612   bool EnableNullFPSuppression;
613 
614 public:
615   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
616       : StackFrame(Frame), EnableNullFPSuppression(Suppressed) {}
617 
618   static void *getTag() {
619     static int Tag = 0;
620     return static_cast<void *>(&Tag);
621   }
622 
623   void Profile(llvm::FoldingSetNodeID &ID) const override {
624     ID.AddPointer(ReturnVisitor::getTag());
625     ID.AddPointer(StackFrame);
626     ID.AddBoolean(EnableNullFPSuppression);
627   }
628 
629   /// Adds a ReturnVisitor if the given statement represents a call that was
630   /// inlined.
631   ///
632   /// This will search back through the ExplodedGraph, starting from the given
633   /// node, looking for when the given statement was processed. If it turns out
634   /// the statement is a call that was inlined, we add the visitor to the
635   /// bug report, so it can print a note later.
636   static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
637                                     BugReport &BR,
638                                     bool InEnableNullFPSuppression) {
639     if (!CallEvent::isCallStmt(S))
640       return;
641 
642     // First, find when we processed the statement.
643     do {
644       if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
645         if (CEE->getCalleeContext()->getCallSite() == S)
646           break;
647       if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
648         if (SP->getStmt() == S)
649           break;
650 
651       Node = Node->getFirstPred();
652     } while (Node);
653 
654     // Next, step over any post-statement checks.
655     while (Node && Node->getLocation().getAs<PostStmt>())
656       Node = Node->getFirstPred();
657     if (!Node)
658       return;
659 
660     // Finally, see if we inlined the call.
661     Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
662     if (!CEE)
663       return;
664 
665     const StackFrameContext *CalleeContext = CEE->getCalleeContext();
666     if (CalleeContext->getCallSite() != S)
667       return;
668 
669     // Check the return value.
670     ProgramStateRef State = Node->getState();
671     SVal RetVal = Node->getSVal(S);
672 
673     // Handle cases where a reference is returned and then immediately used.
674     if (cast<Expr>(S)->isGLValue())
675       if (Optional<Loc> LValue = RetVal.getAs<Loc>())
676         RetVal = State->getSVal(*LValue);
677 
678     // See if the return value is NULL. If so, suppress the report.
679     SubEngine *Eng = State->getStateManager().getOwningEngine();
680     assert(Eng && "Cannot file a bug report without an owning engine");
681     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
682 
683     bool EnableNullFPSuppression = false;
684     if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
685       if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
686         EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
687 
688     BR.markInteresting(CalleeContext);
689     BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
690                                                    EnableNullFPSuppression));
691   }
692 
693   /// Returns true if any counter-suppression heuristics are enabled for
694   /// ReturnVisitor.
695   static bool hasCounterSuppression(AnalyzerOptions &Options) {
696     return Options.shouldAvoidSuppressingNullArgumentPaths();
697   }
698 
699   std::shared_ptr<PathDiagnosticPiece>
700   visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
701                    BugReporterContext &BRC, BugReport &BR) {
702     // Only print a message at the interesting return statement.
703     if (N->getLocationContext() != StackFrame)
704       return nullptr;
705 
706     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
707     if (!SP)
708       return nullptr;
709 
710     const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
711     if (!Ret)
712       return nullptr;
713 
714     // Okay, we're at the right return statement, but do we have the return
715     // value available?
716     ProgramStateRef State = N->getState();
717     SVal V = State->getSVal(Ret, StackFrame);
718     if (V.isUnknownOrUndef())
719       return nullptr;
720 
721     // Don't print any more notes after this one.
722     Mode = Satisfied;
723 
724     const Expr *RetE = Ret->getRetValue();
725     assert(RetE && "Tracking a return value for a void function");
726 
727     // Handle cases where a reference is returned and then immediately used.
728     Optional<Loc> LValue;
729     if (RetE->isGLValue()) {
730       if ((LValue = V.getAs<Loc>())) {
731         SVal RValue = State->getRawSVal(*LValue, RetE->getType());
732         if (RValue.getAs<DefinedSVal>())
733           V = RValue;
734       }
735     }
736 
737     // Ignore aggregate rvalues.
738     if (V.getAs<nonloc::LazyCompoundVal>() ||
739         V.getAs<nonloc::CompoundVal>())
740       return nullptr;
741 
742     RetE = RetE->IgnoreParenCasts();
743 
744     // If we can't prove the return value is 0, just mark it interesting, and
745     // make sure to track it into any further inner functions.
746     if (!State->isNull(V).isConstrainedTrue()) {
747       BR.markInteresting(V);
748       ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
749                                            EnableNullFPSuppression);
750       return nullptr;
751     }
752 
753     // If we're returning 0, we should track where that 0 came from.
754     bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
755                                        EnableNullFPSuppression);
756 
757     // Build an appropriate message based on the return value.
758     SmallString<64> Msg;
759     llvm::raw_svector_ostream Out(Msg);
760 
761     if (V.getAs<Loc>()) {
762       // If we have counter-suppression enabled, make sure we keep visiting
763       // future nodes. We want to emit a path note as well, in case
764       // the report is resurrected as valid later on.
765       ExprEngine &Eng = BRC.getBugReporter().getEngine();
766       AnalyzerOptions &Options = Eng.getAnalysisManager().options;
767       if (EnableNullFPSuppression && hasCounterSuppression(Options))
768         Mode = MaybeUnsuppress;
769 
770       if (RetE->getType()->isObjCObjectPointerType())
771         Out << "Returning nil";
772       else
773         Out << "Returning null pointer";
774     } else {
775       Out << "Returning zero";
776     }
777 
778     if (LValue) {
779       if (const MemRegion *MR = LValue->getAsRegion()) {
780         if (MR->canPrintPretty()) {
781           Out << " (reference to ";
782           MR->printPretty(Out);
783           Out << ")";
784         }
785       }
786     } else {
787       // FIXME: We should have a more generalized location printing mechanism.
788       if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
789         if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
790           Out << " (loaded from '" << *DD << "')";
791     }
792 
793     PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
794     if (!L.isValid() || !L.asLocation().isValid())
795       return nullptr;
796 
797     return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
798   }
799 
800   std::shared_ptr<PathDiagnosticPiece>
801   visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
802                            BugReporterContext &BRC, BugReport &BR) {
803 #ifndef NDEBUG
804     ExprEngine &Eng = BRC.getBugReporter().getEngine();
805     AnalyzerOptions &Options = Eng.getAnalysisManager().options;
806     assert(hasCounterSuppression(Options));
807 #endif
808 
809     // Are we at the entry node for this call?
810     Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
811     if (!CE)
812       return nullptr;
813 
814     if (CE->getCalleeContext() != StackFrame)
815       return nullptr;
816 
817     Mode = Satisfied;
818 
819     // Don't automatically suppress a report if one of the arguments is
820     // known to be a null pointer. Instead, start tracking /that/ null
821     // value back to its origin.
822     ProgramStateManager &StateMgr = BRC.getStateManager();
823     CallEventManager &CallMgr = StateMgr.getCallEventManager();
824 
825     ProgramStateRef State = N->getState();
826     CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
827     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
828       Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
829       if (!ArgV)
830         continue;
831 
832       const Expr *ArgE = Call->getArgExpr(I);
833       if (!ArgE)
834         continue;
835 
836       // Is it possible for this argument to be non-null?
837       if (!State->isNull(*ArgV).isConstrainedTrue())
838         continue;
839 
840       if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
841                                              EnableNullFPSuppression))
842         BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
843 
844       // If we /can't/ track the null pointer, we should err on the side of
845       // false negatives, and continue towards marking this report invalid.
846       // (We will still look at the other arguments, though.)
847     }
848 
849     return nullptr;
850   }
851 
852   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
853                                                  const ExplodedNode *PrevN,
854                                                  BugReporterContext &BRC,
855                                                  BugReport &BR) override {
856     switch (Mode) {
857     case Initial:
858       return visitNodeInitial(N, PrevN, BRC, BR);
859     case MaybeUnsuppress:
860       return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
861     case Satisfied:
862       return nullptr;
863     }
864 
865     llvm_unreachable("Invalid visit mode!");
866   }
867 
868   std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
869                                                   const ExplodedNode *N,
870                                                   BugReport &BR) override {
871     if (EnableNullFPSuppression)
872       BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
873     return nullptr;
874   }
875 };
876 
877 } // namespace
878 
879 void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
880   static int tag = 0;
881   ID.AddPointer(&tag);
882   ID.AddPointer(R);
883   ID.Add(V);
884   ID.AddBoolean(EnableNullFPSuppression);
885 }
886 
887 /// Returns true if \p N represents the DeclStmt declaring and initializing
888 /// \p VR.
889 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
890   Optional<PostStmt> P = N->getLocationAs<PostStmt>();
891   if (!P)
892     return false;
893 
894   const DeclStmt *DS = P->getStmtAs<DeclStmt>();
895   if (!DS)
896     return false;
897 
898   if (DS->getSingleDecl() != VR->getDecl())
899     return false;
900 
901   const MemSpaceRegion *VarSpace = VR->getMemorySpace();
902   const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
903   if (!FrameSpace) {
904     // If we ever directly evaluate global DeclStmts, this assertion will be
905     // invalid, but this still seems preferable to silently accepting an
906     // initialization that may be for a path-sensitive variable.
907     assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
908     return true;
909   }
910 
911   assert(VR->getDecl()->hasLocalStorage());
912   const LocationContext *LCtx = N->getLocationContext();
913   return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
914 }
915 
916 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
917 static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
918                               const MemRegion *R, SVal V, const DeclStmt *DS) {
919   if (R->canPrintPretty()) {
920     R->printPretty(os);
921     os << " ";
922   }
923 
924   if (V.getAs<loc::ConcreteInt>()) {
925     bool b = false;
926     if (R->isBoundable()) {
927       if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
928         if (TR->getValueType()->isObjCObjectPointerType()) {
929           os << action << "nil";
930           b = true;
931         }
932       }
933     }
934     if (!b)
935       os << action << "a null pointer value";
936 
937   } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
938     os << action << CVal->getValue();
939   } else if (DS) {
940     if (V.isUndef()) {
941       if (isa<VarRegion>(R)) {
942         const auto *VD = cast<VarDecl>(DS->getSingleDecl());
943         if (VD->getInit()) {
944           os << (R->canPrintPretty() ? "initialized" : "Initializing")
945             << " to a garbage value";
946         } else {
947           os << (R->canPrintPretty() ? "declared" : "Declaring")
948             << " without an initial value";
949         }
950       }
951     } else {
952       os << (R->canPrintPretty() ? "initialized" : "Initialized")
953         << " here";
954     }
955   }
956 }
957 
958 /// Display diagnostics for passing bad region as a parameter.
959 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
960     const VarRegion *VR,
961     SVal V) {
962   const auto *Param = cast<ParmVarDecl>(VR->getDecl());
963 
964   os << "Passing ";
965 
966   if (V.getAs<loc::ConcreteInt>()) {
967     if (Param->getType()->isObjCObjectPointerType())
968       os << "nil object reference";
969     else
970       os << "null pointer value";
971   } else if (V.isUndef()) {
972     os << "uninitialized value";
973   } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
974     os << "the value " << CI->getValue();
975   } else {
976     os << "value";
977   }
978 
979   // Printed parameter indexes are 1-based, not 0-based.
980   unsigned Idx = Param->getFunctionScopeIndex() + 1;
981   os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
982   if (VR->canPrintPretty()) {
983     os << " ";
984     VR->printPretty(os);
985   }
986 }
987 
988 /// Show default diagnostics for storing bad region.
989 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
990     const MemRegion *R,
991     SVal V) {
992   if (V.getAs<loc::ConcreteInt>()) {
993     bool b = false;
994     if (R->isBoundable()) {
995       if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
996         if (TR->getValueType()->isObjCObjectPointerType()) {
997           os << "nil object reference stored";
998           b = true;
999         }
1000       }
1001     }
1002     if (!b) {
1003       if (R->canPrintPretty())
1004         os << "Null pointer value stored";
1005       else
1006         os << "Storing null pointer value";
1007     }
1008 
1009   } else if (V.isUndef()) {
1010     if (R->canPrintPretty())
1011       os << "Uninitialized value stored";
1012     else
1013       os << "Storing uninitialized value";
1014 
1015   } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1016     if (R->canPrintPretty())
1017       os << "The value " << CV->getValue() << " is assigned";
1018     else
1019       os << "Assigning " << CV->getValue();
1020 
1021   } else {
1022     if (R->canPrintPretty())
1023       os << "Value assigned";
1024     else
1025       os << "Assigning value";
1026   }
1027 
1028   if (R->canPrintPretty()) {
1029     os << " to ";
1030     R->printPretty(os);
1031   }
1032 }
1033 
1034 std::shared_ptr<PathDiagnosticPiece>
1035 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1036                                   const ExplodedNode *Pred,
1037                                   BugReporterContext &BRC, BugReport &BR) {
1038   if (Satisfied)
1039     return nullptr;
1040 
1041   const ExplodedNode *StoreSite = nullptr;
1042   const Expr *InitE = nullptr;
1043   bool IsParam = false;
1044 
1045   // First see if we reached the declaration of the region.
1046   if (const auto *VR = dyn_cast<VarRegion>(R)) {
1047     if (isInitializationOfVar(Pred, VR)) {
1048       StoreSite = Pred;
1049       InitE = VR->getDecl()->getInit();
1050     }
1051   }
1052 
1053   // If this is a post initializer expression, initializing the region, we
1054   // should track the initializer expression.
1055   if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1056     const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1057     if (FieldReg && FieldReg == R) {
1058       StoreSite = Pred;
1059       InitE = PIP->getInitializer()->getInit();
1060     }
1061   }
1062 
1063   // Otherwise, see if this is the store site:
1064   // (1) Succ has this binding and Pred does not, i.e. this is
1065   //     where the binding first occurred.
1066   // (2) Succ has this binding and is a PostStore node for this region, i.e.
1067   //     the same binding was re-assigned here.
1068   if (!StoreSite) {
1069     if (Succ->getState()->getSVal(R) != V)
1070       return nullptr;
1071 
1072     if (Pred->getState()->getSVal(R) == V) {
1073       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1074       if (!PS || PS->getLocationValue() != R)
1075         return nullptr;
1076     }
1077 
1078     StoreSite = Succ;
1079 
1080     // If this is an assignment expression, we can track the value
1081     // being assigned.
1082     if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1083       if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1084         if (BO->isAssignmentOp())
1085           InitE = BO->getRHS();
1086 
1087     // If this is a call entry, the variable should be a parameter.
1088     // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1089     // 'this' should never be NULL, but this visitor isn't just for NULL and
1090     // UndefinedVal.)
1091     if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1092       if (const auto *VR = dyn_cast<VarRegion>(R)) {
1093         const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1094 
1095         ProgramStateManager &StateMgr = BRC.getStateManager();
1096         CallEventManager &CallMgr = StateMgr.getCallEventManager();
1097 
1098         CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1099                                                 Succ->getState());
1100         InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1101         IsParam = true;
1102       }
1103     }
1104 
1105     // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1106     // is wrapped inside of it.
1107     if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1108       InitE = TmpR->getExpr();
1109   }
1110 
1111   if (!StoreSite)
1112     return nullptr;
1113   Satisfied = true;
1114 
1115   // If we have an expression that provided the value, try to track where it
1116   // came from.
1117   if (InitE) {
1118     if (V.isUndef() ||
1119         V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1120       if (!IsParam)
1121         InitE = InitE->IgnoreParenCasts();
1122       bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
1123                                          EnableNullFPSuppression);
1124     } else {
1125       ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
1126                                            BR, EnableNullFPSuppression);
1127     }
1128   }
1129 
1130   // Okay, we've found the binding. Emit an appropriate message.
1131   SmallString<256> sbuf;
1132   llvm::raw_svector_ostream os(sbuf);
1133 
1134   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1135     const Stmt *S = PS->getStmt();
1136     const char *action = nullptr;
1137     const auto *DS = dyn_cast<DeclStmt>(S);
1138     const auto *VR = dyn_cast<VarRegion>(R);
1139 
1140     if (DS) {
1141       action = R->canPrintPretty() ? "initialized to " :
1142                                      "Initializing to ";
1143     } else if (isa<BlockExpr>(S)) {
1144       action = R->canPrintPretty() ? "captured by block as " :
1145                                      "Captured by block as ";
1146       if (VR) {
1147         // See if we can get the BlockVarRegion.
1148         ProgramStateRef State = StoreSite->getState();
1149         SVal V = StoreSite->getSVal(S);
1150         if (const auto *BDR =
1151               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1152           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1153             if (Optional<KnownSVal> KV =
1154                 State->getSVal(OriginalR).getAs<KnownSVal>())
1155               BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1156                   *KV, OriginalR, EnableNullFPSuppression));
1157           }
1158         }
1159       }
1160     }
1161     if (action)
1162       showBRDiagnostics(action, os, R, V, DS);
1163 
1164   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
1165     if (const auto *VR = dyn_cast<VarRegion>(R))
1166       showBRParamDiagnostics(os, VR, V);
1167   }
1168 
1169   if (os.str().empty())
1170     showBRDefaultDiagnostics(os, R, V);
1171 
1172   // Construct a new PathDiagnosticPiece.
1173   ProgramPoint P = StoreSite->getLocation();
1174   PathDiagnosticLocation L;
1175   if (P.getAs<CallEnter>() && InitE)
1176     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1177                                P.getLocationContext());
1178 
1179   if (!L.isValid() || !L.asLocation().isValid())
1180     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1181 
1182   if (!L.isValid() || !L.asLocation().isValid())
1183     return nullptr;
1184 
1185   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1186 }
1187 
1188 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1189   static int tag = 0;
1190   ID.AddPointer(&tag);
1191   ID.AddBoolean(Assumption);
1192   ID.Add(Constraint);
1193 }
1194 
1195 /// Return the tag associated with this visitor.  This tag will be used
1196 /// to make all PathDiagnosticPieces created by this visitor.
1197 const char *TrackConstraintBRVisitor::getTag() {
1198   return "TrackConstraintBRVisitor";
1199 }
1200 
1201 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1202   if (IsZeroCheck)
1203     return N->getState()->isNull(Constraint).isUnderconstrained();
1204   return (bool)N->getState()->assume(Constraint, !Assumption);
1205 }
1206 
1207 std::shared_ptr<PathDiagnosticPiece>
1208 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
1209                                     const ExplodedNode *PrevN,
1210                                     BugReporterContext &BRC, BugReport &BR) {
1211   if (IsSatisfied)
1212     return nullptr;
1213 
1214   // Start tracking after we see the first state in which the value is
1215   // constrained.
1216   if (!IsTrackingTurnedOn)
1217     if (!isUnderconstrained(N))
1218       IsTrackingTurnedOn = true;
1219   if (!IsTrackingTurnedOn)
1220     return nullptr;
1221 
1222   // Check if in the previous state it was feasible for this constraint
1223   // to *not* be true.
1224   if (isUnderconstrained(PrevN)) {
1225     IsSatisfied = true;
1226 
1227     // As a sanity check, make sure that the negation of the constraint
1228     // was infeasible in the current state.  If it is feasible, we somehow
1229     // missed the transition point.
1230     assert(!isUnderconstrained(N));
1231 
1232     // We found the transition point for the constraint.  We now need to
1233     // pretty-print the constraint. (work-in-progress)
1234     SmallString<64> sbuf;
1235     llvm::raw_svector_ostream os(sbuf);
1236 
1237     if (Constraint.getAs<Loc>()) {
1238       os << "Assuming pointer value is ";
1239       os << (Assumption ? "non-null" : "null");
1240     }
1241 
1242     if (os.str().empty())
1243       return nullptr;
1244 
1245     // Construct a new PathDiagnosticPiece.
1246     ProgramPoint P = N->getLocation();
1247     PathDiagnosticLocation L =
1248       PathDiagnosticLocation::create(P, BRC.getSourceManager());
1249     if (!L.isValid())
1250       return nullptr;
1251 
1252     auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1253     X->setTag(getTag());
1254     return std::move(X);
1255   }
1256 
1257   return nullptr;
1258 }
1259 
1260 SuppressInlineDefensiveChecksVisitor::
1261 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1262     : V(Value) {
1263   // Check if the visitor is disabled.
1264   SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
1265   assert(Eng && "Cannot file a bug report without an owning engine");
1266   AnalyzerOptions &Options = Eng->getAnalysisManager().options;
1267   if (!Options.shouldSuppressInlinedDefensiveChecks())
1268     IsSatisfied = true;
1269 
1270   assert(N->getState()->isNull(V).isConstrainedTrue() &&
1271          "The visitor only tracks the cases where V is constrained to 0");
1272 }
1273 
1274 void SuppressInlineDefensiveChecksVisitor::Profile(
1275     llvm::FoldingSetNodeID &ID) const {
1276   static int id = 0;
1277   ID.AddPointer(&id);
1278   ID.Add(V);
1279 }
1280 
1281 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1282   return "IDCVisitor";
1283 }
1284 
1285 std::shared_ptr<PathDiagnosticPiece>
1286 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1287                                                 const ExplodedNode *Pred,
1288                                                 BugReporterContext &BRC,
1289                                                 BugReport &BR) {
1290   if (IsSatisfied)
1291     return nullptr;
1292 
1293   // Start tracking after we see the first state in which the value is null.
1294   if (!IsTrackingTurnedOn)
1295     if (Succ->getState()->isNull(V).isConstrainedTrue())
1296       IsTrackingTurnedOn = true;
1297   if (!IsTrackingTurnedOn)
1298     return nullptr;
1299 
1300   // Check if in the previous state it was feasible for this value
1301   // to *not* be null.
1302   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
1303     IsSatisfied = true;
1304 
1305     assert(Succ->getState()->isNull(V).isConstrainedTrue());
1306 
1307     // Check if this is inlined defensive checks.
1308     const LocationContext *CurLC =Succ->getLocationContext();
1309     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1310     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
1311       BR.markInvalid("Suppress IDC", CurLC);
1312       return nullptr;
1313     }
1314 
1315     // Treat defensive checks in function-like macros as if they were an inlined
1316     // defensive check. If the bug location is not in a macro and the
1317     // terminator for the current location is in a macro then suppress the
1318     // warning.
1319     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1320 
1321     if (!BugPoint)
1322       return nullptr;
1323 
1324     ProgramPoint CurPoint = Succ->getLocation();
1325     const Stmt *CurTerminatorStmt = nullptr;
1326     if (auto BE = CurPoint.getAs<BlockEdge>()) {
1327       CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1328     } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1329       const Stmt *CurStmt = SP->getStmt();
1330       if (!CurStmt->getLocStart().isMacroID())
1331         return nullptr;
1332 
1333       CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1334       CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
1335     } else {
1336       return nullptr;
1337     }
1338 
1339     if (!CurTerminatorStmt)
1340       return nullptr;
1341 
1342     SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
1343     if (TerminatorLoc.isMacroID()) {
1344       SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
1345 
1346       // Suppress reports unless we are in that same macro.
1347       if (!BugLoc.isMacroID() ||
1348           getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1349         BR.markInvalid("Suppress Macro IDC", CurLC);
1350       }
1351       return nullptr;
1352     }
1353   }
1354   return nullptr;
1355 }
1356 
1357 static const MemRegion *getLocationRegionIfReference(const Expr *E,
1358                                                      const ExplodedNode *N) {
1359   if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1360     if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1361       if (!VD->getType()->isReferenceType())
1362         return nullptr;
1363       ProgramStateManager &StateMgr = N->getState()->getStateManager();
1364       MemRegionManager &MRMgr = StateMgr.getRegionManager();
1365       return MRMgr.getVarRegion(VD, N->getLocationContext());
1366     }
1367   }
1368 
1369   // FIXME: This does not handle other kinds of null references,
1370   // for example, references from FieldRegions:
1371   //   struct Wrapper { int &ref; };
1372   //   Wrapper w = { *(int *)0 };
1373   //   w.ref = 1;
1374 
1375   return nullptr;
1376 }
1377 
1378 static const Expr *peelOffOuterExpr(const Expr *Ex,
1379                                     const ExplodedNode *N) {
1380   Ex = Ex->IgnoreParenCasts();
1381   if (const auto *EWC = dyn_cast<ExprWithCleanups>(Ex))
1382     return peelOffOuterExpr(EWC->getSubExpr(), N);
1383   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1384     return peelOffOuterExpr(OVE->getSourceExpr(), N);
1385   if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1386     const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1387     if (PropRef && PropRef->isMessagingGetter()) {
1388       const Expr *GetterMessageSend =
1389           POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1390       assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1391       return peelOffOuterExpr(GetterMessageSend, N);
1392     }
1393   }
1394 
1395   // Peel off the ternary operator.
1396   if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1397     // Find a node where the branching occurred and find out which branch
1398     // we took (true/false) by looking at the ExplodedGraph.
1399     const ExplodedNode *NI = N;
1400     do {
1401       ProgramPoint ProgPoint = NI->getLocation();
1402       if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1403         const CFGBlock *srcBlk = BE->getSrc();
1404         if (const Stmt *term = srcBlk->getTerminator()) {
1405           if (term == CO) {
1406             bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1407             if (TookTrueBranch)
1408               return peelOffOuterExpr(CO->getTrueExpr(), N);
1409             else
1410               return peelOffOuterExpr(CO->getFalseExpr(), N);
1411           }
1412         }
1413       }
1414       NI = NI->getFirstPred();
1415     } while (NI);
1416   }
1417 
1418   if (auto *BO = dyn_cast<BinaryOperator>(Ex))
1419     if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1420       return peelOffOuterExpr(SubEx, N);
1421 
1422   return Ex;
1423 }
1424 
1425 /// Walk through nodes until we get one that matches the statement exactly.
1426 /// Alternately, if we hit a known lvalue for the statement, we know we've
1427 /// gone too far (though we can likely track the lvalue better anyway).
1428 static const ExplodedNode* findNodeForStatement(const ExplodedNode *N,
1429                                                 const Stmt *S,
1430                                                 const Expr *Inner) {
1431   do {
1432     const ProgramPoint &pp = N->getLocation();
1433     if (auto ps = pp.getAs<StmtPoint>()) {
1434       if (ps->getStmt() == S || ps->getStmt() == Inner)
1435         break;
1436     } else if (auto CEE = pp.getAs<CallExitEnd>()) {
1437       if (CEE->getCalleeContext()->getCallSite() == S ||
1438           CEE->getCalleeContext()->getCallSite() == Inner)
1439         break;
1440     }
1441     N = N->getFirstPred();
1442   } while (N);
1443   return N;
1444 }
1445 
1446 /// Find the ExplodedNode where the lvalue (the value of 'Ex')
1447 /// was computed.
1448 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1449     const Expr *Inner) {
1450   while (N) {
1451     if (auto P = N->getLocation().getAs<PostStmt>()) {
1452       if (P->getStmt() == Inner)
1453         break;
1454     }
1455     N = N->getFirstPred();
1456   }
1457   assert(N && "Unable to find the lvalue node.");
1458   return N;
1459 }
1460 
1461 /// Performing operator `&' on an lvalue expression is essentially a no-op.
1462 /// Then, if we are taking addresses of fields or elements, these are also
1463 /// unlikely to matter.
1464 static const Expr* peelOfOuterAddrOf(const Expr* Ex) {
1465   Ex = Ex->IgnoreParenCasts();
1466 
1467   // FIXME: There's a hack in our Store implementation that always computes
1468   // field offsets around null pointers as if they are always equal to 0.
1469   // The idea here is to report accesses to fields as null dereferences
1470   // even though the pointer value that's being dereferenced is actually
1471   // the offset of the field rather than exactly 0.
1472   // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1473   // This code interacts heavily with this hack; otherwise the value
1474   // would not be null at all for most fields, so we'd be unable to track it.
1475   if (const auto *Op = dyn_cast<UnaryOperator>(Ex))
1476     if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue())
1477       if (const Expr *DerefEx = bugreporter::getDerefExpr(Op->getSubExpr()))
1478         return DerefEx;
1479   return Ex;
1480 }
1481 
1482 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
1483                                         const Stmt *S,
1484                                         BugReport &report, bool IsArg,
1485                                         bool EnableNullFPSuppression) {
1486   if (!S || !N)
1487     return false;
1488 
1489   if (const auto *Ex = dyn_cast<Expr>(S))
1490     S = peelOffOuterExpr(Ex, N);
1491 
1492   const Expr *Inner = nullptr;
1493   if (const auto *Ex = dyn_cast<Expr>(S)) {
1494     Ex = peelOfOuterAddrOf(Ex);
1495     Ex = Ex->IgnoreParenCasts();
1496 
1497     if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex)
1498           || CallEvent::isCallStmt(Ex)))
1499       Inner = Ex;
1500   }
1501 
1502   if (IsArg && !Inner) {
1503     assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
1504   } else {
1505     N = findNodeForStatement(N, S, Inner);
1506     if (!N)
1507       return false;
1508   }
1509 
1510   ProgramStateRef state = N->getState();
1511 
1512   // The message send could be nil due to the receiver being nil.
1513   // At this point in the path, the receiver should be live since we are at the
1514   // message send expr. If it is nil, start tracking it.
1515   if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
1516     trackNullOrUndefValue(N, Receiver, report, /* IsArg=*/ false,
1517         EnableNullFPSuppression);
1518 
1519   // See if the expression we're interested refers to a variable.
1520   // If so, we can track both its contents and constraints on its value.
1521   if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
1522     const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
1523     ProgramStateRef LVState = LVNode->getState();
1524     SVal LVal = LVNode->getSVal(Inner);
1525 
1526     const MemRegion *RR = getLocationRegionIfReference(Inner, N);
1527     bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1528 
1529     // If this is a C++ reference to a null pointer, we are tracking the
1530     // pointer. In addition, we should find the store at which the reference
1531     // got initialized.
1532     if (RR && !LVIsNull) {
1533       if (auto KV = LVal.getAs<KnownSVal>())
1534         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1535               *KV, RR, EnableNullFPSuppression));
1536     }
1537 
1538     // In case of C++ references, we want to differentiate between a null
1539     // reference and reference to null pointer.
1540     // If the LVal is null, check if we are dealing with null reference.
1541     // For those, we want to track the location of the reference.
1542     const MemRegion *R = (RR && LVIsNull) ? RR :
1543         LVNode->getSVal(Inner).getAsRegion();
1544 
1545     if (R) {
1546       // Mark both the variable region and its contents as interesting.
1547       SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1548       report.addVisitor(
1549           llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
1550 
1551       MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1552           N, R, EnableNullFPSuppression, report, V);
1553 
1554       report.markInteresting(R);
1555       report.markInteresting(V);
1556       report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1557 
1558       // If the contents are symbolic, find out when they became null.
1559       if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1560         report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1561               V.castAs<DefinedSVal>(), false));
1562 
1563       // Add visitor, which will suppress inline defensive checks.
1564       if (auto DV = V.getAs<DefinedSVal>()) {
1565         if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1566             EnableNullFPSuppression) {
1567           report.addVisitor(
1568               llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1569                 LVNode));
1570         }
1571       }
1572 
1573       if (auto KV = V.getAs<KnownSVal>())
1574         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1575               *KV, R, EnableNullFPSuppression));
1576       return true;
1577     }
1578   }
1579 
1580   // If the expression is not an "lvalue expression", we can still
1581   // track the constraints on its contents.
1582   SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1583 
1584   // If the value came from an inlined function call, we should at least make
1585   // sure that function isn't pruned in our output.
1586   if (const auto *E = dyn_cast<Expr>(S))
1587     S = E->IgnoreParenCasts();
1588 
1589   ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1590 
1591   // Uncomment this to find cases where we aren't properly getting the
1592   // base value that was dereferenced.
1593   // assert(!V.isUnknownOrUndef());
1594   // Is it a symbolic value?
1595   if (auto L = V.getAs<loc::MemRegionVal>()) {
1596     report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1597 
1598     // At this point we are dealing with the region's LValue.
1599     // However, if the rvalue is a symbolic region, we should track it as well.
1600     // Try to use the correct type when looking up the value.
1601     SVal RVal;
1602     if (const auto *E = dyn_cast<Expr>(S))
1603       RVal = state->getRawSVal(L.getValue(), E->getType());
1604     else
1605       RVal = state->getSVal(L->getRegion());
1606 
1607     if (auto KV = RVal.getAs<KnownSVal>())
1608       report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1609             *KV, L->getRegion(), EnableNullFPSuppression));
1610 
1611     const MemRegion *RegionRVal = RVal.getAsRegion();
1612     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1613       report.markInteresting(RegionRVal);
1614       report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1615             loc::MemRegionVal(RegionRVal), false));
1616     }
1617   }
1618   return true;
1619 }
1620 
1621 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1622                                                  const ExplodedNode *N) {
1623   const auto *ME = dyn_cast<ObjCMessageExpr>(S);
1624   if (!ME)
1625     return nullptr;
1626   if (const Expr *Receiver = ME->getInstanceReceiver()) {
1627     ProgramStateRef state = N->getState();
1628     SVal V = N->getSVal(Receiver);
1629     if (state->isNull(V).isConstrainedTrue())
1630       return Receiver;
1631   }
1632   return nullptr;
1633 }
1634 
1635 std::shared_ptr<PathDiagnosticPiece>
1636 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1637                                 const ExplodedNode *PrevN,
1638                                 BugReporterContext &BRC, BugReport &BR) {
1639   Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1640   if (!P)
1641     return nullptr;
1642 
1643   const Stmt *S = P->getStmt();
1644   const Expr *Receiver = getNilReceiver(S, N);
1645   if (!Receiver)
1646     return nullptr;
1647 
1648   llvm::SmallString<256> Buf;
1649   llvm::raw_svector_ostream OS(Buf);
1650 
1651   if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1652     OS << "'";
1653     ME->getSelector().print(OS);
1654     OS << "' not called";
1655   }
1656   else {
1657     OS << "No method is called";
1658   }
1659   OS << " because the receiver is nil";
1660 
1661   // The receiver was nil, and hence the method was skipped.
1662   // Register a BugReporterVisitor to issue a message telling us how
1663   // the receiver was null.
1664   bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1665                                      /*EnableNullFPSuppression*/ false);
1666   // Issue a message saying that the method was skipped.
1667   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1668                                      N->getLocationContext());
1669   return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1670 }
1671 
1672 // Registers every VarDecl inside a Stmt with a last store visitor.
1673 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1674                                                 const Stmt *S,
1675                                                 bool EnableNullFPSuppression) {
1676   const ExplodedNode *N = BR.getErrorNode();
1677   std::deque<const Stmt *> WorkList;
1678   WorkList.push_back(S);
1679 
1680   while (!WorkList.empty()) {
1681     const Stmt *Head = WorkList.front();
1682     WorkList.pop_front();
1683 
1684     ProgramStateManager &StateMgr = N->getState()->getStateManager();
1685 
1686     if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
1687       if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1688         const VarRegion *R =
1689         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1690 
1691         // What did we load?
1692         SVal V = N->getSVal(S);
1693 
1694         if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1695           // Register a new visitor with the BugReport.
1696           BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1697               V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1698         }
1699       }
1700     }
1701 
1702     for (const Stmt *SubStmt : Head->children())
1703       WorkList.push_back(SubStmt);
1704   }
1705 }
1706 
1707 //===----------------------------------------------------------------------===//
1708 // Visitor that tries to report interesting diagnostics from conditions.
1709 //===----------------------------------------------------------------------===//
1710 
1711 /// Return the tag associated with this visitor.  This tag will be used
1712 /// to make all PathDiagnosticPieces created by this visitor.
1713 const char *ConditionBRVisitor::getTag() {
1714   return "ConditionBRVisitor";
1715 }
1716 
1717 std::shared_ptr<PathDiagnosticPiece>
1718 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
1719                               BugReporterContext &BRC, BugReport &BR) {
1720   auto piece = VisitNodeImpl(N, Prev, BRC, BR);
1721   if (piece) {
1722     piece->setTag(getTag());
1723     if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1724       ev->setPrunable(true, /* override */ false);
1725   }
1726   return piece;
1727 }
1728 
1729 std::shared_ptr<PathDiagnosticPiece>
1730 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1731                                   const ExplodedNode *Prev,
1732                                   BugReporterContext &BRC, BugReport &BR) {
1733   ProgramPoint progPoint = N->getLocation();
1734   ProgramStateRef CurrentState = N->getState();
1735   ProgramStateRef PrevState = Prev->getState();
1736 
1737   // Compare the GDMs of the state, because that is where constraints
1738   // are managed.  Note that ensure that we only look at nodes that
1739   // were generated by the analyzer engine proper, not checkers.
1740   if (CurrentState->getGDM().getRoot() ==
1741       PrevState->getGDM().getRoot())
1742     return nullptr;
1743 
1744   // If an assumption was made on a branch, it should be caught
1745   // here by looking at the state transition.
1746   if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1747     const CFGBlock *srcBlk = BE->getSrc();
1748     if (const Stmt *term = srcBlk->getTerminator())
1749       return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1750     return nullptr;
1751   }
1752 
1753   if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1754     // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1755     // violation.
1756     const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1757       cast<GRBugReporter>(BRC.getBugReporter()).
1758         getEngine().geteagerlyAssumeBinOpBifurcationTags();
1759 
1760     const ProgramPointTag *tag = PS->getTag();
1761     if (tag == tags.first)
1762       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1763                            BRC, BR, N);
1764     if (tag == tags.second)
1765       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1766                            BRC, BR, N);
1767 
1768     return nullptr;
1769   }
1770 
1771   return nullptr;
1772 }
1773 
1774 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1775     const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1776     const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1777   const Expr *Cond = nullptr;
1778 
1779   // In the code below, Term is a CFG terminator and Cond is a branch condition
1780   // expression upon which the decision is made on this terminator.
1781   //
1782   // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1783   // and "x == 0" is the respective condition.
1784   //
1785   // Another example: in "if (x && y)", we've got two terminators and two
1786   // conditions due to short-circuit nature of operator "&&":
1787   // 1. The "if (x && y)" statement is a terminator,
1788   //    and "y" is the respective condition.
1789   // 2. Also "x && ..." is another terminator,
1790   //    and "x" is its condition.
1791 
1792   switch (Term->getStmtClass()) {
1793   // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1794   // more tricky because there are more than two branches to account for.
1795   default:
1796     return nullptr;
1797   case Stmt::IfStmtClass:
1798     Cond = cast<IfStmt>(Term)->getCond();
1799     break;
1800   case Stmt::ConditionalOperatorClass:
1801     Cond = cast<ConditionalOperator>(Term)->getCond();
1802     break;
1803   case Stmt::BinaryOperatorClass:
1804     // When we encounter a logical operator (&& or ||) as a CFG terminator,
1805     // then the condition is actually its LHS; otherwise, we'd encounter
1806     // the parent, such as if-statement, as a terminator.
1807     const auto *BO = cast<BinaryOperator>(Term);
1808     assert(BO->isLogicalOp() &&
1809            "CFG terminator is not a short-circuit operator!");
1810     Cond = BO->getLHS();
1811     break;
1812   }
1813 
1814   // However, when we encounter a logical operator as a branch condition,
1815   // then the condition is actually its RHS, because LHS would be
1816   // the condition for the logical operator terminator.
1817   while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1818     if (!InnerBO->isLogicalOp())
1819       break;
1820     Cond = InnerBO->getRHS()->IgnoreParens();
1821   }
1822 
1823   assert(Cond);
1824   assert(srcBlk->succ_size() == 2);
1825   const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1826   return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1827 }
1828 
1829 std::shared_ptr<PathDiagnosticPiece>
1830 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1831                                   BugReporterContext &BRC, BugReport &R,
1832                                   const ExplodedNode *N) {
1833   // These will be modified in code below, but we need to preserve the original
1834   //  values in case we want to throw the generic message.
1835   const Expr *CondTmp = Cond;
1836   bool tookTrueTmp = tookTrue;
1837 
1838   while (true) {
1839     CondTmp = CondTmp->IgnoreParenCasts();
1840     switch (CondTmp->getStmtClass()) {
1841       default:
1842         break;
1843       case Stmt::BinaryOperatorClass:
1844         if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1845                                    tookTrueTmp, BRC, R, N))
1846           return P;
1847         break;
1848       case Stmt::DeclRefExprClass:
1849         if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1850                                    tookTrueTmp, BRC, R, N))
1851           return P;
1852         break;
1853       case Stmt::UnaryOperatorClass: {
1854         const auto *UO = cast<UnaryOperator>(CondTmp);
1855         if (UO->getOpcode() == UO_LNot) {
1856           tookTrueTmp = !tookTrueTmp;
1857           CondTmp = UO->getSubExpr();
1858           continue;
1859         }
1860         break;
1861       }
1862     }
1863     break;
1864   }
1865 
1866   // Condition too complex to explain? Just say something so that the user
1867   // knew we've made some path decision at this point.
1868   const LocationContext *LCtx = N->getLocationContext();
1869   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1870   if (!Loc.isValid() || !Loc.asLocation().isValid())
1871     return nullptr;
1872 
1873   return std::make_shared<PathDiagnosticEventPiece>(
1874       Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1875 }
1876 
1877 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1878                                       const Expr *ParentEx,
1879                                       raw_ostream &Out,
1880                                       BugReporterContext &BRC,
1881                                       BugReport &report,
1882                                       const ExplodedNode *N,
1883                                       Optional<bool> &prunable) {
1884   const Expr *OriginalExpr = Ex;
1885   Ex = Ex->IgnoreParenCasts();
1886 
1887   // Use heuristics to determine if Ex is a macro expending to a literal and
1888   // if so, use the macro's name.
1889   SourceLocation LocStart = Ex->getLocStart();
1890   SourceLocation LocEnd = Ex->getLocEnd();
1891   if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1892       (isa<GNUNullExpr>(Ex) ||
1893        isa<ObjCBoolLiteralExpr>(Ex) ||
1894        isa<CXXBoolLiteralExpr>(Ex) ||
1895        isa<IntegerLiteral>(Ex) ||
1896        isa<FloatingLiteral>(Ex))) {
1897     StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1898       BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1899     StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1900       BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1901     bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1902 
1903     bool partOfParentMacro = false;
1904     if (ParentEx->getLocStart().isMacroID()) {
1905       StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1906         ParentEx->getLocStart(), BRC.getSourceManager(),
1907         BRC.getASTContext().getLangOpts());
1908       partOfParentMacro = PName.equals(StartName);
1909     }
1910 
1911     if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1912       // Get the location of the macro name as written by the caller.
1913       SourceLocation Loc = LocStart;
1914       while (LocStart.isMacroID()) {
1915         Loc = LocStart;
1916         LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1917       }
1918       StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1919         Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1920 
1921       // Return the macro name.
1922       Out << MacroName;
1923       return false;
1924     }
1925   }
1926 
1927   if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
1928     const bool quotes = isa<VarDecl>(DR->getDecl());
1929     if (quotes) {
1930       Out << '\'';
1931       const LocationContext *LCtx = N->getLocationContext();
1932       const ProgramState *state = N->getState().get();
1933       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1934                                                 LCtx).getAsRegion()) {
1935         if (report.isInteresting(R))
1936           prunable = false;
1937         else {
1938           const ProgramState *state = N->getState().get();
1939           SVal V = state->getSVal(R);
1940           if (report.isInteresting(V))
1941             prunable = false;
1942         }
1943       }
1944     }
1945     Out << DR->getDecl()->getDeclName().getAsString();
1946     if (quotes)
1947       Out << '\'';
1948     return quotes;
1949   }
1950 
1951   if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
1952     QualType OriginalTy = OriginalExpr->getType();
1953     if (OriginalTy->isPointerType()) {
1954       if (IL->getValue() == 0) {
1955         Out << "null";
1956         return false;
1957       }
1958     }
1959     else if (OriginalTy->isObjCObjectPointerType()) {
1960       if (IL->getValue() == 0) {
1961         Out << "nil";
1962         return false;
1963       }
1964     }
1965 
1966     Out << IL->getValue();
1967     return false;
1968   }
1969 
1970   return false;
1971 }
1972 
1973 std::shared_ptr<PathDiagnosticPiece>
1974 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
1975                                   const bool tookTrue, BugReporterContext &BRC,
1976                                   BugReport &R, const ExplodedNode *N) {
1977   bool shouldInvert = false;
1978   Optional<bool> shouldPrune;
1979 
1980   SmallString<128> LhsString, RhsString;
1981   {
1982     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1983     const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
1984                                        BRC, R, N, shouldPrune);
1985     const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
1986                                        BRC, R, N, shouldPrune);
1987 
1988     shouldInvert = !isVarLHS && isVarRHS;
1989   }
1990 
1991   BinaryOperator::Opcode Op = BExpr->getOpcode();
1992 
1993   if (BinaryOperator::isAssignmentOp(Op)) {
1994     // For assignment operators, all that we care about is that the LHS
1995     // evaluates to "true" or "false".
1996     return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1997                                   BRC, R, N);
1998   }
1999 
2000   // For non-assignment operations, we require that we can understand
2001   // both the LHS and RHS.
2002   if (LhsString.empty() || RhsString.empty() ||
2003       !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
2004     return nullptr;
2005 
2006   // Should we invert the strings if the LHS is not a variable name?
2007   SmallString<256> buf;
2008   llvm::raw_svector_ostream Out(buf);
2009   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
2010 
2011   // Do we need to invert the opcode?
2012   if (shouldInvert)
2013     switch (Op) {
2014       default: break;
2015       case BO_LT: Op = BO_GT; break;
2016       case BO_GT: Op = BO_LT; break;
2017       case BO_LE: Op = BO_GE; break;
2018       case BO_GE: Op = BO_LE; break;
2019     }
2020 
2021   if (!tookTrue)
2022     switch (Op) {
2023       case BO_EQ: Op = BO_NE; break;
2024       case BO_NE: Op = BO_EQ; break;
2025       case BO_LT: Op = BO_GE; break;
2026       case BO_GT: Op = BO_LE; break;
2027       case BO_LE: Op = BO_GT; break;
2028       case BO_GE: Op = BO_LT; break;
2029       default:
2030         return nullptr;
2031     }
2032 
2033   switch (Op) {
2034     case BO_EQ:
2035       Out << "equal to ";
2036       break;
2037     case BO_NE:
2038       Out << "not equal to ";
2039       break;
2040     default:
2041       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2042       break;
2043   }
2044 
2045   Out << (shouldInvert ? LhsString : RhsString);
2046   const LocationContext *LCtx = N->getLocationContext();
2047   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2048   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2049   if (shouldPrune.hasValue())
2050     event->setPrunable(shouldPrune.getValue());
2051   return event;
2052 }
2053 
2054 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
2055     StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
2056     BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
2057   // FIXME: If there's already a constraint tracker for this variable,
2058   // we shouldn't emit anything here (c.f. the double note in
2059   // test/Analysis/inlining/path-notes.c)
2060   SmallString<256> buf;
2061   llvm::raw_svector_ostream Out(buf);
2062   Out << "Assuming " << LhsString << " is ";
2063 
2064   QualType Ty = CondVarExpr->getType();
2065 
2066   if (Ty->isPointerType())
2067     Out << (tookTrue ? "not null" : "null");
2068   else if (Ty->isObjCObjectPointerType())
2069     Out << (tookTrue ? "not nil" : "nil");
2070   else if (Ty->isBooleanType())
2071     Out << (tookTrue ? "true" : "false");
2072   else if (Ty->isIntegralOrEnumerationType())
2073     Out << (tookTrue ? "non-zero" : "zero");
2074   else
2075     return nullptr;
2076 
2077   const LocationContext *LCtx = N->getLocationContext();
2078   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2079   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2080 
2081   if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
2082     if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2083       const ProgramState *state = N->getState().get();
2084       if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2085         if (report.isInteresting(R))
2086           event->setPrunable(false);
2087       }
2088     }
2089   }
2090 
2091   return event;
2092 }
2093 
2094 std::shared_ptr<PathDiagnosticPiece>
2095 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
2096                                   const bool tookTrue, BugReporterContext &BRC,
2097                                   BugReport &report, const ExplodedNode *N) {
2098   const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
2099   if (!VD)
2100     return nullptr;
2101 
2102   SmallString<256> Buf;
2103   llvm::raw_svector_ostream Out(Buf);
2104 
2105   Out << "Assuming '" << VD->getDeclName() << "' is ";
2106 
2107   QualType VDTy = VD->getType();
2108 
2109   if (VDTy->isPointerType())
2110     Out << (tookTrue ? "non-null" : "null");
2111   else if (VDTy->isObjCObjectPointerType())
2112     Out << (tookTrue ? "non-nil" : "nil");
2113   else if (VDTy->isScalarType())
2114     Out << (tookTrue ? "not equal to 0" : "0");
2115   else
2116     return nullptr;
2117 
2118   const LocationContext *LCtx = N->getLocationContext();
2119   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2120   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2121 
2122   const ProgramState *state = N->getState().get();
2123   if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2124     if (report.isInteresting(R))
2125       event->setPrunable(false);
2126     else {
2127       SVal V = state->getSVal(R);
2128       if (report.isInteresting(V))
2129         event->setPrunable(false);
2130     }
2131   }
2132   return std::move(event);
2133 }
2134 
2135 const char *const ConditionBRVisitor::GenericTrueMessage =
2136     "Assuming the condition is true";
2137 const char *const ConditionBRVisitor::GenericFalseMessage =
2138     "Assuming the condition is false";
2139 
2140 bool ConditionBRVisitor::isPieceMessageGeneric(
2141     const PathDiagnosticPiece *Piece) {
2142   return Piece->getString() == GenericTrueMessage ||
2143          Piece->getString() == GenericFalseMessage;
2144 }
2145 
2146 std::unique_ptr<PathDiagnosticPiece>
2147 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
2148                                                     const ExplodedNode *N,
2149                                                     BugReport &BR) {
2150   // Here we suppress false positives coming from system headers. This list is
2151   // based on known issues.
2152   ExprEngine &Eng = BRC.getBugReporter().getEngine();
2153   AnalyzerOptions &Options = Eng.getAnalysisManager().options;
2154   const Decl *D = N->getLocationContext()->getDecl();
2155 
2156   if (AnalysisDeclContext::isInStdNamespace(D)) {
2157     // Skip reports within the 'std' namespace. Although these can sometimes be
2158     // the user's fault, we currently don't report them very well, and
2159     // Note that this will not help for any other data structure libraries, like
2160     // TR1, Boost, or llvm/ADT.
2161     if (Options.shouldSuppressFromCXXStandardLibrary()) {
2162       BR.markInvalid(getTag(), nullptr);
2163       return nullptr;
2164     } else {
2165       // If the complete 'std' suppression is not enabled, suppress reports
2166       // from the 'std' namespace that are known to produce false positives.
2167 
2168       // The analyzer issues a false use-after-free when std::list::pop_front
2169       // or std::list::pop_back are called multiple times because we cannot
2170       // reason about the internal invariants of the data structure.
2171       if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2172         const CXXRecordDecl *CD = MD->getParent();
2173         if (CD->getName() == "list") {
2174           BR.markInvalid(getTag(), nullptr);
2175           return nullptr;
2176         }
2177       }
2178 
2179       // The analyzer issues a false positive when the constructor of
2180       // std::__independent_bits_engine from algorithms is used.
2181       if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2182         const CXXRecordDecl *CD = MD->getParent();
2183         if (CD->getName() == "__independent_bits_engine") {
2184           BR.markInvalid(getTag(), nullptr);
2185           return nullptr;
2186         }
2187       }
2188 
2189       for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
2190            LCtx = LCtx->getParent()) {
2191         const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2192         if (!MD)
2193           continue;
2194 
2195         const CXXRecordDecl *CD = MD->getParent();
2196         // The analyzer issues a false positive on
2197         //   std::basic_string<uint8_t> v; v.push_back(1);
2198         // and
2199         //   std::u16string s; s += u'a';
2200         // because we cannot reason about the internal invariants of the
2201         // data structure.
2202         if (CD->getName() == "basic_string") {
2203           BR.markInvalid(getTag(), nullptr);
2204           return nullptr;
2205         }
2206 
2207         // The analyzer issues a false positive on
2208         //    std::shared_ptr<int> p(new int(1)); p = nullptr;
2209         // because it does not reason properly about temporary destructors.
2210         if (CD->getName() == "shared_ptr") {
2211           BR.markInvalid(getTag(), nullptr);
2212           return nullptr;
2213         }
2214       }
2215     }
2216   }
2217 
2218   // Skip reports within the sys/queue.h macros as we do not have the ability to
2219   // reason about data structure shapes.
2220   SourceManager &SM = BRC.getSourceManager();
2221   FullSourceLoc Loc = BR.getLocation(SM).asLocation();
2222   while (Loc.isMacroID()) {
2223     Loc = Loc.getSpellingLoc();
2224     if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2225       BR.markInvalid(getTag(), nullptr);
2226       return nullptr;
2227     }
2228   }
2229 
2230   return nullptr;
2231 }
2232 
2233 std::shared_ptr<PathDiagnosticPiece>
2234 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
2235                                  const ExplodedNode *PrevN,
2236                                  BugReporterContext &BRC, BugReport &BR) {
2237   ProgramStateRef State = N->getState();
2238   ProgramPoint ProgLoc = N->getLocation();
2239 
2240   // We are only interested in visiting CallEnter nodes.
2241   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2242   if (!CEnter)
2243     return nullptr;
2244 
2245   // Check if one of the arguments is the region the visitor is tracking.
2246   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2247   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2248   unsigned Idx = 0;
2249   ArrayRef<ParmVarDecl *> parms = Call->parameters();
2250 
2251   for (const auto ParamDecl : parms) {
2252     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2253     ++Idx;
2254 
2255     // Are we tracking the argument or its subregion?
2256     if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
2257       continue;
2258 
2259     // Check the function parameter type.
2260     assert(ParamDecl && "Formal parameter has no decl?");
2261     QualType T = ParamDecl->getType();
2262 
2263     if (!(T->isAnyPointerType() || T->isReferenceType())) {
2264       // Function can only change the value passed in by address.
2265       continue;
2266     }
2267 
2268     // If it is a const pointer value, the function does not intend to
2269     // change the value.
2270     if (T->getPointeeType().isConstQualified())
2271       continue;
2272 
2273     // Mark the call site (LocationContext) as interesting if the value of the
2274     // argument is undefined or '0'/'NULL'.
2275     SVal BoundVal = State->getSVal(R);
2276     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
2277       BR.markInteresting(CEnter->getCalleeContext());
2278       return nullptr;
2279     }
2280   }
2281   return nullptr;
2282 }
2283 
2284 std::shared_ptr<PathDiagnosticPiece>
2285 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
2286                                       const ExplodedNode *Pred,
2287                                       BugReporterContext &BRC, BugReport &BR) {
2288   if (Satisfied)
2289     return nullptr;
2290 
2291   const auto Edge = Succ->getLocation().getAs<BlockEdge>();
2292   if (!Edge.hasValue())
2293     return nullptr;
2294 
2295   auto Tag = Edge->getTag();
2296   if (!Tag)
2297     return nullptr;
2298 
2299   if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
2300     return nullptr;
2301 
2302   Satisfied = true;
2303 
2304   const auto *Met =
2305       dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
2306   assert(Met && "Not a C++ method.");
2307   assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
2308          "Not a copy/move assignment operator.");
2309 
2310   const auto *LCtx = Edge->getLocationContext();
2311 
2312   const auto &State = Succ->getState();
2313   auto &SVB = State->getStateManager().getSValBuilder();
2314 
2315   const auto Param =
2316       State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
2317   const auto This =
2318       State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame()));
2319 
2320   auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
2321 
2322   if (!L.isValid() || !L.asLocation().isValid())
2323     return nullptr;
2324 
2325   SmallString<256> Buf;
2326   llvm::raw_svector_ostream Out(Buf);
2327 
2328   Out << "Assuming " << Met->getParamDecl(0)->getName() <<
2329     ((Param == This) ? " == " : " != ") << "*this";
2330 
2331   auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
2332   Piece->addRange(Met->getSourceRange());
2333 
2334   return std::move(Piece);
2335 }
2336 
2337 std::shared_ptr<PathDiagnosticPiece>
2338 TaintBugVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN,
2339                            BugReporterContext &BRC, BugReport &BR) {
2340 
2341   // Find the ExplodedNode where the taint was first introduced
2342   if (!N->getState()->isTainted(V) || PrevN->getState()->isTainted(V))
2343     return nullptr;
2344 
2345   const Stmt *S = PathDiagnosticLocation::getStmt(N);
2346   if (!S)
2347     return nullptr;
2348 
2349   const LocationContext *NCtx = N->getLocationContext();
2350   PathDiagnosticLocation L =
2351       PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);
2352   if (!L.isValid() || !L.asLocation().isValid())
2353     return nullptr;
2354 
2355   return std::make_shared<PathDiagnosticEventPiece>(L, "Taint originated here");
2356 }
2357