1 // BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- C++ -*--//
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 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/Analysis/CFGStmtMap.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 
28 using namespace clang;
29 using namespace ento;
30 
31 using llvm::FoldingSetNodeID;
32 
33 //===----------------------------------------------------------------------===//
34 // Utility functions.
35 //===----------------------------------------------------------------------===//
36 
37 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
38   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
39     return DRE->getDecl()->getType()->isReferenceType();
40   }
41   return false;
42 }
43 
44 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
45   // Pattern match for a few useful cases:
46   //   a[0], p->f, *p
47   const Expr *E = dyn_cast<Expr>(S);
48   if (!E)
49     return nullptr;
50   E = E->IgnoreParenCasts();
51 
52   while (true) {
53     if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
54       assert(B->isAssignmentOp());
55       E = B->getLHS()->IgnoreParenCasts();
56       continue;
57     }
58     else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
59       if (U->getOpcode() == UO_Deref)
60         return U->getSubExpr()->IgnoreParenCasts();
61     }
62     else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
63       if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
64         return ME->getBase()->IgnoreParenCasts();
65       } else {
66         // If we have a member expr with a dot, the base must have been
67         // dereferenced.
68         return getDerefExpr(ME->getBase());
69       }
70     }
71     else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
72       return IvarRef->getBase()->IgnoreParenCasts();
73     }
74     else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
75       return AE->getBase();
76     }
77     else if (isDeclRefExprToReference(E)) {
78       return E;
79     }
80     break;
81   }
82 
83   return nullptr;
84 }
85 
86 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
87   const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
88   if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
89     return BE->getRHS();
90   return nullptr;
91 }
92 
93 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
94   const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
95   if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
96     return RS->getRetValue();
97   return nullptr;
98 }
99 
100 //===----------------------------------------------------------------------===//
101 // Definitions for bug reporter visitors.
102 //===----------------------------------------------------------------------===//
103 
104 std::unique_ptr<PathDiagnosticPiece>
105 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
106                                const ExplodedNode *EndPathNode, BugReport &BR) {
107   return nullptr;
108 }
109 
110 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
111     BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
112   PathDiagnosticLocation L =
113     PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
114 
115   const auto &Ranges = BR.getRanges();
116 
117   // Only add the statement itself as a range if we didn't specify any
118   // special ranges for this report.
119   auto P = llvm::make_unique<PathDiagnosticEventPiece>(
120       L, BR.getDescription(), Ranges.begin() == Ranges.end());
121   for (SourceRange Range : Ranges)
122     P->addRange(Range);
123 
124   return std::move(P);
125 }
126 
127 
128 namespace {
129 /// Emits an extra note at the return statement of an interesting stack frame.
130 ///
131 /// The returned value is marked as an interesting value, and if it's null,
132 /// adds a visitor to track where it became null.
133 ///
134 /// This visitor is intended to be used when another visitor discovers that an
135 /// interesting value comes from an inlined function call.
136 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
137   const StackFrameContext *StackFrame;
138   enum {
139     Initial,
140     MaybeUnsuppress,
141     Satisfied
142   } Mode;
143 
144   bool EnableNullFPSuppression;
145 
146 public:
147   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
148     : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
149 
150   static void *getTag() {
151     static int Tag = 0;
152     return static_cast<void *>(&Tag);
153   }
154 
155   void Profile(llvm::FoldingSetNodeID &ID) const override {
156     ID.AddPointer(ReturnVisitor::getTag());
157     ID.AddPointer(StackFrame);
158     ID.AddBoolean(EnableNullFPSuppression);
159   }
160 
161   /// Adds a ReturnVisitor if the given statement represents a call that was
162   /// inlined.
163   ///
164   /// This will search back through the ExplodedGraph, starting from the given
165   /// node, looking for when the given statement was processed. If it turns out
166   /// the statement is a call that was inlined, we add the visitor to the
167   /// bug report, so it can print a note later.
168   static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
169                                     BugReport &BR,
170                                     bool InEnableNullFPSuppression) {
171     if (!CallEvent::isCallStmt(S))
172       return;
173 
174     // First, find when we processed the statement.
175     do {
176       if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
177         if (CEE->getCalleeContext()->getCallSite() == S)
178           break;
179       if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
180         if (SP->getStmt() == S)
181           break;
182 
183       Node = Node->getFirstPred();
184     } while (Node);
185 
186     // Next, step over any post-statement checks.
187     while (Node && Node->getLocation().getAs<PostStmt>())
188       Node = Node->getFirstPred();
189     if (!Node)
190       return;
191 
192     // Finally, see if we inlined the call.
193     Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
194     if (!CEE)
195       return;
196 
197     const StackFrameContext *CalleeContext = CEE->getCalleeContext();
198     if (CalleeContext->getCallSite() != S)
199       return;
200 
201     // Check the return value.
202     ProgramStateRef State = Node->getState();
203     SVal RetVal = State->getSVal(S, Node->getLocationContext());
204 
205     // Handle cases where a reference is returned and then immediately used.
206     if (cast<Expr>(S)->isGLValue())
207       if (Optional<Loc> LValue = RetVal.getAs<Loc>())
208         RetVal = State->getSVal(*LValue);
209 
210     // See if the return value is NULL. If so, suppress the report.
211     SubEngine *Eng = State->getStateManager().getOwningEngine();
212     assert(Eng && "Cannot file a bug report without an owning engine");
213     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
214 
215     bool EnableNullFPSuppression = false;
216     if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
217       if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
218         EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
219 
220     BR.markInteresting(CalleeContext);
221     BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
222                                                    EnableNullFPSuppression));
223   }
224 
225   /// Returns true if any counter-suppression heuristics are enabled for
226   /// ReturnVisitor.
227   static bool hasCounterSuppression(AnalyzerOptions &Options) {
228     return Options.shouldAvoidSuppressingNullArgumentPaths();
229   }
230 
231   PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
232                                         const ExplodedNode *PrevN,
233                                         BugReporterContext &BRC,
234                                         BugReport &BR) {
235     // Only print a message at the interesting return statement.
236     if (N->getLocationContext() != StackFrame)
237       return nullptr;
238 
239     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
240     if (!SP)
241       return nullptr;
242 
243     const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
244     if (!Ret)
245       return nullptr;
246 
247     // Okay, we're at the right return statement, but do we have the return
248     // value available?
249     ProgramStateRef State = N->getState();
250     SVal V = State->getSVal(Ret, StackFrame);
251     if (V.isUnknownOrUndef())
252       return nullptr;
253 
254     // Don't print any more notes after this one.
255     Mode = Satisfied;
256 
257     const Expr *RetE = Ret->getRetValue();
258     assert(RetE && "Tracking a return value for a void function");
259 
260     // Handle cases where a reference is returned and then immediately used.
261     Optional<Loc> LValue;
262     if (RetE->isGLValue()) {
263       if ((LValue = V.getAs<Loc>())) {
264         SVal RValue = State->getRawSVal(*LValue, RetE->getType());
265         if (RValue.getAs<DefinedSVal>())
266           V = RValue;
267       }
268     }
269 
270     // Ignore aggregate rvalues.
271     if (V.getAs<nonloc::LazyCompoundVal>() ||
272         V.getAs<nonloc::CompoundVal>())
273       return nullptr;
274 
275     RetE = RetE->IgnoreParenCasts();
276 
277     // If we can't prove the return value is 0, just mark it interesting, and
278     // make sure to track it into any further inner functions.
279     if (!State->isNull(V).isConstrainedTrue()) {
280       BR.markInteresting(V);
281       ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
282                                            EnableNullFPSuppression);
283       return nullptr;
284     }
285 
286     // If we're returning 0, we should track where that 0 came from.
287     bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
288                                        EnableNullFPSuppression);
289 
290     // Build an appropriate message based on the return value.
291     SmallString<64> Msg;
292     llvm::raw_svector_ostream Out(Msg);
293 
294     if (V.getAs<Loc>()) {
295       // If we have counter-suppression enabled, make sure we keep visiting
296       // future nodes. We want to emit a path note as well, in case
297       // the report is resurrected as valid later on.
298       ExprEngine &Eng = BRC.getBugReporter().getEngine();
299       AnalyzerOptions &Options = Eng.getAnalysisManager().options;
300       if (EnableNullFPSuppression && hasCounterSuppression(Options))
301         Mode = MaybeUnsuppress;
302 
303       if (RetE->getType()->isObjCObjectPointerType())
304         Out << "Returning nil";
305       else
306         Out << "Returning null pointer";
307     } else {
308       Out << "Returning zero";
309     }
310 
311     if (LValue) {
312       if (const MemRegion *MR = LValue->getAsRegion()) {
313         if (MR->canPrintPretty()) {
314           Out << " (reference to ";
315           MR->printPretty(Out);
316           Out << ")";
317         }
318       }
319     } else {
320       // FIXME: We should have a more generalized location printing mechanism.
321       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
322         if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
323           Out << " (loaded from '" << *DD << "')";
324     }
325 
326     PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
327     return new PathDiagnosticEventPiece(L, Out.str());
328   }
329 
330   PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
331                                                 const ExplodedNode *PrevN,
332                                                 BugReporterContext &BRC,
333                                                 BugReport &BR) {
334 #ifndef NDEBUG
335     ExprEngine &Eng = BRC.getBugReporter().getEngine();
336     AnalyzerOptions &Options = Eng.getAnalysisManager().options;
337     assert(hasCounterSuppression(Options));
338 #endif
339 
340     // Are we at the entry node for this call?
341     Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
342     if (!CE)
343       return nullptr;
344 
345     if (CE->getCalleeContext() != StackFrame)
346       return nullptr;
347 
348     Mode = Satisfied;
349 
350     // Don't automatically suppress a report if one of the arguments is
351     // known to be a null pointer. Instead, start tracking /that/ null
352     // value back to its origin.
353     ProgramStateManager &StateMgr = BRC.getStateManager();
354     CallEventManager &CallMgr = StateMgr.getCallEventManager();
355 
356     ProgramStateRef State = N->getState();
357     CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
358     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
359       Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
360       if (!ArgV)
361         continue;
362 
363       const Expr *ArgE = Call->getArgExpr(I);
364       if (!ArgE)
365         continue;
366 
367       // Is it possible for this argument to be non-null?
368       if (!State->isNull(*ArgV).isConstrainedTrue())
369         continue;
370 
371       if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
372                                              EnableNullFPSuppression))
373         BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
374 
375       // If we /can't/ track the null pointer, we should err on the side of
376       // false negatives, and continue towards marking this report invalid.
377       // (We will still look at the other arguments, though.)
378     }
379 
380     return nullptr;
381   }
382 
383   PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
384                                  const ExplodedNode *PrevN,
385                                  BugReporterContext &BRC,
386                                  BugReport &BR) override {
387     switch (Mode) {
388     case Initial:
389       return visitNodeInitial(N, PrevN, BRC, BR);
390     case MaybeUnsuppress:
391       return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
392     case Satisfied:
393       return nullptr;
394     }
395 
396     llvm_unreachable("Invalid visit mode!");
397   }
398 
399   std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
400                                                   const ExplodedNode *N,
401                                                   BugReport &BR) override {
402     if (EnableNullFPSuppression)
403       BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
404     return nullptr;
405   }
406 };
407 } // end anonymous namespace
408 
409 
410 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
411   static int tag = 0;
412   ID.AddPointer(&tag);
413   ID.AddPointer(R);
414   ID.Add(V);
415   ID.AddBoolean(EnableNullFPSuppression);
416 }
417 
418 /// Returns true if \p N represents the DeclStmt declaring and initializing
419 /// \p VR.
420 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
421   Optional<PostStmt> P = N->getLocationAs<PostStmt>();
422   if (!P)
423     return false;
424 
425   const DeclStmt *DS = P->getStmtAs<DeclStmt>();
426   if (!DS)
427     return false;
428 
429   if (DS->getSingleDecl() != VR->getDecl())
430     return false;
431 
432   const MemSpaceRegion *VarSpace = VR->getMemorySpace();
433   const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
434   if (!FrameSpace) {
435     // If we ever directly evaluate global DeclStmts, this assertion will be
436     // invalid, but this still seems preferable to silently accepting an
437     // initialization that may be for a path-sensitive variable.
438     assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
439     return true;
440   }
441 
442   assert(VR->getDecl()->hasLocalStorage());
443   const LocationContext *LCtx = N->getLocationContext();
444   return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
445 }
446 
447 PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
448                                                        const ExplodedNode *Pred,
449                                                        BugReporterContext &BRC,
450                                                        BugReport &BR) {
451 
452   if (Satisfied)
453     return nullptr;
454 
455   const ExplodedNode *StoreSite = nullptr;
456   const Expr *InitE = nullptr;
457   bool IsParam = false;
458 
459   // First see if we reached the declaration of the region.
460   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
461     if (isInitializationOfVar(Pred, VR)) {
462       StoreSite = Pred;
463       InitE = VR->getDecl()->getInit();
464     }
465   }
466 
467   // If this is a post initializer expression, initializing the region, we
468   // should track the initializer expression.
469   if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
470     const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
471     if (FieldReg && FieldReg == R) {
472       StoreSite = Pred;
473       InitE = PIP->getInitializer()->getInit();
474     }
475   }
476 
477   // Otherwise, see if this is the store site:
478   // (1) Succ has this binding and Pred does not, i.e. this is
479   //     where the binding first occurred.
480   // (2) Succ has this binding and is a PostStore node for this region, i.e.
481   //     the same binding was re-assigned here.
482   if (!StoreSite) {
483     if (Succ->getState()->getSVal(R) != V)
484       return nullptr;
485 
486     if (Pred->getState()->getSVal(R) == V) {
487       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
488       if (!PS || PS->getLocationValue() != R)
489         return nullptr;
490     }
491 
492     StoreSite = Succ;
493 
494     // If this is an assignment expression, we can track the value
495     // being assigned.
496     if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
497       if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
498         if (BO->isAssignmentOp())
499           InitE = BO->getRHS();
500 
501     // If this is a call entry, the variable should be a parameter.
502     // FIXME: Handle CXXThisRegion as well. (This is not a priority because
503     // 'this' should never be NULL, but this visitor isn't just for NULL and
504     // UndefinedVal.)
505     if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
506       if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
507         const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
508 
509         ProgramStateManager &StateMgr = BRC.getStateManager();
510         CallEventManager &CallMgr = StateMgr.getCallEventManager();
511 
512         CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
513                                                 Succ->getState());
514         InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
515         IsParam = true;
516       }
517     }
518 
519     // If this is a CXXTempObjectRegion, the Expr responsible for its creation
520     // is wrapped inside of it.
521     if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
522       InitE = TmpR->getExpr();
523   }
524 
525   if (!StoreSite)
526     return nullptr;
527   Satisfied = true;
528 
529   // If we have an expression that provided the value, try to track where it
530   // came from.
531   if (InitE) {
532     if (V.isUndef() ||
533         V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
534       if (!IsParam)
535         InitE = InitE->IgnoreParenCasts();
536       bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
537                                          EnableNullFPSuppression);
538     } else {
539       ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
540                                            BR, EnableNullFPSuppression);
541     }
542   }
543 
544   // Okay, we've found the binding. Emit an appropriate message.
545   SmallString<256> sbuf;
546   llvm::raw_svector_ostream os(sbuf);
547 
548   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
549     const Stmt *S = PS->getStmt();
550     const char *action = nullptr;
551     const DeclStmt *DS = dyn_cast<DeclStmt>(S);
552     const VarRegion *VR = dyn_cast<VarRegion>(R);
553 
554     if (DS) {
555       action = R->canPrintPretty() ? "initialized to " :
556                                      "Initializing to ";
557     } else if (isa<BlockExpr>(S)) {
558       action = R->canPrintPretty() ? "captured by block as " :
559                                      "Captured by block as ";
560       if (VR) {
561         // See if we can get the BlockVarRegion.
562         ProgramStateRef State = StoreSite->getState();
563         SVal V = State->getSVal(S, PS->getLocationContext());
564         if (const BlockDataRegion *BDR =
565               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
566           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
567             if (Optional<KnownSVal> KV =
568                 State->getSVal(OriginalR).getAs<KnownSVal>())
569               BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
570                   *KV, OriginalR, EnableNullFPSuppression));
571           }
572         }
573       }
574     }
575 
576     if (action) {
577       if (R->canPrintPretty()) {
578         R->printPretty(os);
579         os << " ";
580       }
581 
582       if (V.getAs<loc::ConcreteInt>()) {
583         bool b = false;
584         if (R->isBoundable()) {
585           if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
586             if (TR->getValueType()->isObjCObjectPointerType()) {
587               os << action << "nil";
588               b = true;
589             }
590           }
591         }
592 
593         if (!b)
594           os << action << "a null pointer value";
595       } else if (Optional<nonloc::ConcreteInt> CVal =
596                      V.getAs<nonloc::ConcreteInt>()) {
597         os << action << CVal->getValue();
598       }
599       else if (DS) {
600         if (V.isUndef()) {
601           if (isa<VarRegion>(R)) {
602             const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
603             if (VD->getInit()) {
604               os << (R->canPrintPretty() ? "initialized" : "Initializing")
605                  << " to a garbage value";
606             } else {
607               os << (R->canPrintPretty() ? "declared" : "Declaring")
608                  << " without an initial value";
609             }
610           }
611         }
612         else {
613           os << (R->canPrintPretty() ? "initialized" : "Initialized")
614              << " here";
615         }
616       }
617     }
618   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
619     if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
620       const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
621 
622       os << "Passing ";
623 
624       if (V.getAs<loc::ConcreteInt>()) {
625         if (Param->getType()->isObjCObjectPointerType())
626           os << "nil object reference";
627         else
628           os << "null pointer value";
629       } else if (V.isUndef()) {
630         os << "uninitialized value";
631       } else if (Optional<nonloc::ConcreteInt> CI =
632                      V.getAs<nonloc::ConcreteInt>()) {
633         os << "the value " << CI->getValue();
634       } else {
635         os << "value";
636       }
637 
638       // Printed parameter indexes are 1-based, not 0-based.
639       unsigned Idx = Param->getFunctionScopeIndex() + 1;
640       os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
641       if (R->canPrintPretty()) {
642         os << " ";
643         R->printPretty(os);
644       }
645     }
646   }
647 
648   if (os.str().empty()) {
649     if (V.getAs<loc::ConcreteInt>()) {
650       bool b = false;
651       if (R->isBoundable()) {
652         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
653           if (TR->getValueType()->isObjCObjectPointerType()) {
654             os << "nil object reference stored";
655             b = true;
656           }
657         }
658       }
659       if (!b) {
660         if (R->canPrintPretty())
661           os << "Null pointer value stored";
662         else
663           os << "Storing null pointer value";
664       }
665 
666     } else if (V.isUndef()) {
667       if (R->canPrintPretty())
668         os << "Uninitialized value stored";
669       else
670         os << "Storing uninitialized value";
671 
672     } else if (Optional<nonloc::ConcreteInt> CV =
673                    V.getAs<nonloc::ConcreteInt>()) {
674       if (R->canPrintPretty())
675         os << "The value " << CV->getValue() << " is assigned";
676       else
677         os << "Assigning " << CV->getValue();
678 
679     } else {
680       if (R->canPrintPretty())
681         os << "Value assigned";
682       else
683         os << "Assigning value";
684     }
685 
686     if (R->canPrintPretty()) {
687       os << " to ";
688       R->printPretty(os);
689     }
690   }
691 
692   // Construct a new PathDiagnosticPiece.
693   ProgramPoint P = StoreSite->getLocation();
694   PathDiagnosticLocation L;
695   if (P.getAs<CallEnter>() && InitE)
696     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
697                                P.getLocationContext());
698 
699   if (!L.isValid() || !L.asLocation().isValid())
700     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
701 
702   if (!L.isValid() || !L.asLocation().isValid())
703     return nullptr;
704 
705   return new PathDiagnosticEventPiece(L, os.str());
706 }
707 
708 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
709   static int tag = 0;
710   ID.AddPointer(&tag);
711   ID.AddBoolean(Assumption);
712   ID.Add(Constraint);
713 }
714 
715 /// Return the tag associated with this visitor.  This tag will be used
716 /// to make all PathDiagnosticPieces created by this visitor.
717 const char *TrackConstraintBRVisitor::getTag() {
718   return "TrackConstraintBRVisitor";
719 }
720 
721 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
722   if (IsZeroCheck)
723     return N->getState()->isNull(Constraint).isUnderconstrained();
724   return (bool)N->getState()->assume(Constraint, !Assumption);
725 }
726 
727 PathDiagnosticPiece *
728 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
729                                     const ExplodedNode *PrevN,
730                                     BugReporterContext &BRC,
731                                     BugReport &BR) {
732   if (IsSatisfied)
733     return nullptr;
734 
735   // Start tracking after we see the first state in which the value is
736   // constrained.
737   if (!IsTrackingTurnedOn)
738     if (!isUnderconstrained(N))
739       IsTrackingTurnedOn = true;
740   if (!IsTrackingTurnedOn)
741     return nullptr;
742 
743   // Check if in the previous state it was feasible for this constraint
744   // to *not* be true.
745   if (isUnderconstrained(PrevN)) {
746 
747     IsSatisfied = true;
748 
749     // As a sanity check, make sure that the negation of the constraint
750     // was infeasible in the current state.  If it is feasible, we somehow
751     // missed the transition point.
752     assert(!isUnderconstrained(N));
753 
754     // We found the transition point for the constraint.  We now need to
755     // pretty-print the constraint. (work-in-progress)
756     SmallString<64> sbuf;
757     llvm::raw_svector_ostream os(sbuf);
758 
759     if (Constraint.getAs<Loc>()) {
760       os << "Assuming pointer value is ";
761       os << (Assumption ? "non-null" : "null");
762     }
763 
764     if (os.str().empty())
765       return nullptr;
766 
767     // Construct a new PathDiagnosticPiece.
768     ProgramPoint P = N->getLocation();
769     PathDiagnosticLocation L =
770       PathDiagnosticLocation::create(P, BRC.getSourceManager());
771     if (!L.isValid())
772       return nullptr;
773 
774     PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
775     X->setTag(getTag());
776     return X;
777   }
778 
779   return nullptr;
780 }
781 
782 SuppressInlineDefensiveChecksVisitor::
783 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
784   : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
785 
786     // Check if the visitor is disabled.
787     SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
788     assert(Eng && "Cannot file a bug report without an owning engine");
789     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
790     if (!Options.shouldSuppressInlinedDefensiveChecks())
791       IsSatisfied = true;
792 
793     assert(N->getState()->isNull(V).isConstrainedTrue() &&
794            "The visitor only tracks the cases where V is constrained to 0");
795 }
796 
797 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
798   static int id = 0;
799   ID.AddPointer(&id);
800   ID.Add(V);
801 }
802 
803 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
804   return "IDCVisitor";
805 }
806 
807 PathDiagnosticPiece *
808 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
809                                                 const ExplodedNode *Pred,
810                                                 BugReporterContext &BRC,
811                                                 BugReport &BR) {
812   if (IsSatisfied)
813     return nullptr;
814 
815   // Start tracking after we see the first state in which the value is null.
816   if (!IsTrackingTurnedOn)
817     if (Succ->getState()->isNull(V).isConstrainedTrue())
818       IsTrackingTurnedOn = true;
819   if (!IsTrackingTurnedOn)
820     return nullptr;
821 
822   // Check if in the previous state it was feasible for this value
823   // to *not* be null.
824   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
825     IsSatisfied = true;
826 
827     assert(Succ->getState()->isNull(V).isConstrainedTrue());
828 
829     // Check if this is inlined defensive checks.
830     const LocationContext *CurLC =Succ->getLocationContext();
831     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
832     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
833       BR.markInvalid("Suppress IDC", CurLC);
834       return nullptr;
835     }
836 
837     // Treat defensive checks in function-like macros as if they were an inlined
838     // defensive check. If the bug location is not in a macro and the
839     // terminator for the current location is in a macro then suppress the
840     // warning.
841     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
842 
843     if (!BugPoint)
844       return nullptr;
845 
846     SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
847     if (BugLoc.isMacroID())
848       return nullptr;
849 
850     ProgramPoint CurPoint = Succ->getLocation();
851     const Stmt *CurTerminatorStmt = nullptr;
852     if (auto BE = CurPoint.getAs<BlockEdge>()) {
853       CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
854     } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
855       const Stmt *CurStmt = SP->getStmt();
856       if (!CurStmt->getLocStart().isMacroID())
857         return nullptr;
858 
859       CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
860       CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
861     } else {
862       return nullptr;
863     }
864 
865     if (!CurTerminatorStmt)
866       return nullptr;
867 
868     SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
869     if (TerminatorLoc.isMacroID()) {
870       const SourceManager &SMgr = BRC.getSourceManager();
871       std::pair<FileID, unsigned> TLInfo = SMgr.getDecomposedLoc(TerminatorLoc);
872       SrcMgr::SLocEntry SE = SMgr.getSLocEntry(TLInfo.first);
873       const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
874       if (EInfo.isFunctionMacroExpansion()) {
875         BR.markInvalid("Suppress Macro IDC", CurLC);
876         return nullptr;
877       }
878     }
879   }
880   return nullptr;
881 }
882 
883 static const MemRegion *getLocationRegionIfReference(const Expr *E,
884                                                      const ExplodedNode *N) {
885   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
886     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
887       if (!VD->getType()->isReferenceType())
888         return nullptr;
889       ProgramStateManager &StateMgr = N->getState()->getStateManager();
890       MemRegionManager &MRMgr = StateMgr.getRegionManager();
891       return MRMgr.getVarRegion(VD, N->getLocationContext());
892     }
893   }
894 
895   // FIXME: This does not handle other kinds of null references,
896   // for example, references from FieldRegions:
897   //   struct Wrapper { int &ref; };
898   //   Wrapper w = { *(int *)0 };
899   //   w.ref = 1;
900 
901   return nullptr;
902 }
903 
904 static const Expr *peelOffOuterExpr(const Expr *Ex,
905                                     const ExplodedNode *N) {
906   Ex = Ex->IgnoreParenCasts();
907   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
908     return peelOffOuterExpr(EWC->getSubExpr(), N);
909   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
910     return peelOffOuterExpr(OVE->getSourceExpr(), N);
911 
912   // Peel off the ternary operator.
913   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
914     // Find a node where the branching occurred and find out which branch
915     // we took (true/false) by looking at the ExplodedGraph.
916     const ExplodedNode *NI = N;
917     do {
918       ProgramPoint ProgPoint = NI->getLocation();
919       if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
920         const CFGBlock *srcBlk = BE->getSrc();
921         if (const Stmt *term = srcBlk->getTerminator()) {
922           if (term == CO) {
923             bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
924             if (TookTrueBranch)
925               return peelOffOuterExpr(CO->getTrueExpr(), N);
926             else
927               return peelOffOuterExpr(CO->getFalseExpr(), N);
928           }
929         }
930       }
931       NI = NI->getFirstPred();
932     } while (NI);
933   }
934   return Ex;
935 }
936 
937 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
938                                         const Stmt *S,
939                                         BugReport &report, bool IsArg,
940                                         bool EnableNullFPSuppression) {
941   if (!S || !N)
942     return false;
943 
944   if (const Expr *Ex = dyn_cast<Expr>(S)) {
945     Ex = Ex->IgnoreParenCasts();
946     const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
947     if (Ex != PeeledEx)
948       S = PeeledEx;
949   }
950 
951   const Expr *Inner = nullptr;
952   if (const Expr *Ex = dyn_cast<Expr>(S)) {
953     Ex = Ex->IgnoreParenCasts();
954     if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
955       Inner = Ex;
956   }
957 
958   if (IsArg && !Inner) {
959     assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
960   } else {
961     // Walk through nodes until we get one that matches the statement exactly.
962     // Alternately, if we hit a known lvalue for the statement, we know we've
963     // gone too far (though we can likely track the lvalue better anyway).
964     do {
965       const ProgramPoint &pp = N->getLocation();
966       if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
967         if (ps->getStmt() == S || ps->getStmt() == Inner)
968           break;
969       } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
970         if (CEE->getCalleeContext()->getCallSite() == S ||
971             CEE->getCalleeContext()->getCallSite() == Inner)
972           break;
973       }
974       N = N->getFirstPred();
975     } while (N);
976 
977     if (!N)
978       return false;
979   }
980 
981   ProgramStateRef state = N->getState();
982 
983   // The message send could be nil due to the receiver being nil.
984   // At this point in the path, the receiver should be live since we are at the
985   // message send expr. If it is nil, start tracking it.
986   if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
987     trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
988 
989 
990   // See if the expression we're interested refers to a variable.
991   // If so, we can track both its contents and constraints on its value.
992   if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
993     const MemRegion *R = nullptr;
994 
995     // Find the ExplodedNode where the lvalue (the value of 'Ex')
996     // was computed.  We need this for getting the location value.
997     const ExplodedNode *LVNode = N;
998     while (LVNode) {
999       if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
1000         if (P->getStmt() == Inner)
1001           break;
1002       }
1003       LVNode = LVNode->getFirstPred();
1004     }
1005     assert(LVNode && "Unable to find the lvalue node.");
1006     ProgramStateRef LVState = LVNode->getState();
1007     SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
1008 
1009     if (LVState->isNull(LVal).isConstrainedTrue()) {
1010       // In case of C++ references, we want to differentiate between a null
1011       // reference and reference to null pointer.
1012       // If the LVal is null, check if we are dealing with null reference.
1013       // For those, we want to track the location of the reference.
1014       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
1015         R = RR;
1016     } else {
1017       R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
1018 
1019       // If this is a C++ reference to a null pointer, we are tracking the
1020       // pointer. In additon, we should find the store at which the reference
1021       // got initialized.
1022       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
1023         if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
1024           report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1025               *KV, RR, EnableNullFPSuppression));
1026       }
1027     }
1028 
1029     if (R) {
1030       // Mark both the variable region and its contents as interesting.
1031       SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1032 
1033       report.markInteresting(R);
1034       report.markInteresting(V);
1035       report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1036 
1037       // If the contents are symbolic, find out when they became null.
1038       if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1039         report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1040             V.castAs<DefinedSVal>(), false));
1041 
1042       // Add visitor, which will suppress inline defensive checks.
1043       if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
1044         if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1045             EnableNullFPSuppression) {
1046           report.addVisitor(
1047               llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1048                                                                       LVNode));
1049         }
1050       }
1051 
1052       if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1053         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1054             *KV, R, EnableNullFPSuppression));
1055       return true;
1056     }
1057   }
1058 
1059   // If the expression is not an "lvalue expression", we can still
1060   // track the constraints on its contents.
1061   SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1062 
1063   // If the value came from an inlined function call, we should at least make
1064   // sure that function isn't pruned in our output.
1065   if (const Expr *E = dyn_cast<Expr>(S))
1066     S = E->IgnoreParenCasts();
1067 
1068   ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1069 
1070   // Uncomment this to find cases where we aren't properly getting the
1071   // base value that was dereferenced.
1072   // assert(!V.isUnknownOrUndef());
1073   // Is it a symbolic value?
1074   if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1075     // At this point we are dealing with the region's LValue.
1076     // However, if the rvalue is a symbolic region, we should track it as well.
1077     // Try to use the correct type when looking up the value.
1078     SVal RVal;
1079     if (const Expr *E = dyn_cast<Expr>(S))
1080       RVal = state->getRawSVal(L.getValue(), E->getType());
1081     else
1082       RVal = state->getSVal(L->getRegion());
1083 
1084     const MemRegion *RegionRVal = RVal.getAsRegion();
1085     report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1086 
1087     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1088       report.markInteresting(RegionRVal);
1089       report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1090           loc::MemRegionVal(RegionRVal), false));
1091     }
1092   }
1093 
1094   return true;
1095 }
1096 
1097 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1098                                                  const ExplodedNode *N) {
1099   const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1100   if (!ME)
1101     return nullptr;
1102   if (const Expr *Receiver = ME->getInstanceReceiver()) {
1103     ProgramStateRef state = N->getState();
1104     SVal V = state->getSVal(Receiver, N->getLocationContext());
1105     if (state->isNull(V).isConstrainedTrue())
1106       return Receiver;
1107   }
1108   return nullptr;
1109 }
1110 
1111 PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1112                                                      const ExplodedNode *PrevN,
1113                                                      BugReporterContext &BRC,
1114                                                      BugReport &BR) {
1115   Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1116   if (!P)
1117     return nullptr;
1118 
1119   const Stmt *S = P->getStmt();
1120   const Expr *Receiver = getNilReceiver(S, N);
1121   if (!Receiver)
1122     return nullptr;
1123 
1124   llvm::SmallString<256> Buf;
1125   llvm::raw_svector_ostream OS(Buf);
1126 
1127   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1128     OS << "'";
1129     ME->getSelector().print(OS);
1130     OS << "' not called";
1131   }
1132   else {
1133     OS << "No method is called";
1134   }
1135   OS << " because the receiver is nil";
1136 
1137   // The receiver was nil, and hence the method was skipped.
1138   // Register a BugReporterVisitor to issue a message telling us how
1139   // the receiver was null.
1140   bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1141                                      /*EnableNullFPSuppression*/ false);
1142   // Issue a message saying that the method was skipped.
1143   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1144                                      N->getLocationContext());
1145   return new PathDiagnosticEventPiece(L, OS.str());
1146 }
1147 
1148 // Registers every VarDecl inside a Stmt with a last store visitor.
1149 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1150                                                 const Stmt *S,
1151                                                 bool EnableNullFPSuppression) {
1152   const ExplodedNode *N = BR.getErrorNode();
1153   std::deque<const Stmt *> WorkList;
1154   WorkList.push_back(S);
1155 
1156   while (!WorkList.empty()) {
1157     const Stmt *Head = WorkList.front();
1158     WorkList.pop_front();
1159 
1160     ProgramStateRef state = N->getState();
1161     ProgramStateManager &StateMgr = state->getStateManager();
1162 
1163     if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1164       if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1165         const VarRegion *R =
1166         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1167 
1168         // What did we load?
1169         SVal V = state->getSVal(S, N->getLocationContext());
1170 
1171         if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1172           // Register a new visitor with the BugReport.
1173           BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1174               V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1175         }
1176       }
1177     }
1178 
1179     for (const Stmt *SubStmt : Head->children())
1180       WorkList.push_back(SubStmt);
1181   }
1182 }
1183 
1184 //===----------------------------------------------------------------------===//
1185 // Visitor that tries to report interesting diagnostics from conditions.
1186 //===----------------------------------------------------------------------===//
1187 
1188 /// Return the tag associated with this visitor.  This tag will be used
1189 /// to make all PathDiagnosticPieces created by this visitor.
1190 const char *ConditionBRVisitor::getTag() {
1191   return "ConditionBRVisitor";
1192 }
1193 
1194 PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1195                                                    const ExplodedNode *Prev,
1196                                                    BugReporterContext &BRC,
1197                                                    BugReport &BR) {
1198   PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
1199   if (piece) {
1200     piece->setTag(getTag());
1201     if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
1202       ev->setPrunable(true, /* override */ false);
1203   }
1204   return piece;
1205 }
1206 
1207 PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1208                                                        const ExplodedNode *Prev,
1209                                                        BugReporterContext &BRC,
1210                                                        BugReport &BR) {
1211 
1212   ProgramPoint progPoint = N->getLocation();
1213   ProgramStateRef CurrentState = N->getState();
1214   ProgramStateRef PrevState = Prev->getState();
1215 
1216   // Compare the GDMs of the state, because that is where constraints
1217   // are managed.  Note that ensure that we only look at nodes that
1218   // were generated by the analyzer engine proper, not checkers.
1219   if (CurrentState->getGDM().getRoot() ==
1220       PrevState->getGDM().getRoot())
1221     return nullptr;
1222 
1223   // If an assumption was made on a branch, it should be caught
1224   // here by looking at the state transition.
1225   if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1226     const CFGBlock *srcBlk = BE->getSrc();
1227     if (const Stmt *term = srcBlk->getTerminator())
1228       return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1229     return nullptr;
1230   }
1231 
1232   if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1233     // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1234     // violation.
1235     const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1236       cast<GRBugReporter>(BRC.getBugReporter()).
1237         getEngine().geteagerlyAssumeBinOpBifurcationTags();
1238 
1239     const ProgramPointTag *tag = PS->getTag();
1240     if (tag == tags.first)
1241       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1242                            BRC, BR, N);
1243     if (tag == tags.second)
1244       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1245                            BRC, BR, N);
1246 
1247     return nullptr;
1248   }
1249 
1250   return nullptr;
1251 }
1252 
1253 PathDiagnosticPiece *
1254 ConditionBRVisitor::VisitTerminator(const Stmt *Term,
1255                                     const ExplodedNode *N,
1256                                     const CFGBlock *srcBlk,
1257                                     const CFGBlock *dstBlk,
1258                                     BugReport &R,
1259                                     BugReporterContext &BRC) {
1260   const Expr *Cond = nullptr;
1261 
1262   switch (Term->getStmtClass()) {
1263   default:
1264     return nullptr;
1265   case Stmt::IfStmtClass:
1266     Cond = cast<IfStmt>(Term)->getCond();
1267     break;
1268   case Stmt::ConditionalOperatorClass:
1269     Cond = cast<ConditionalOperator>(Term)->getCond();
1270     break;
1271   }
1272 
1273   assert(Cond);
1274   assert(srcBlk->succ_size() == 2);
1275   const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1276   return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1277 }
1278 
1279 PathDiagnosticPiece *
1280 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1281                                   bool tookTrue,
1282                                   BugReporterContext &BRC,
1283                                   BugReport &R,
1284                                   const ExplodedNode *N) {
1285 
1286   const Expr *Ex = Cond;
1287 
1288   while (true) {
1289     Ex = Ex->IgnoreParenCasts();
1290     switch (Ex->getStmtClass()) {
1291       default:
1292         return nullptr;
1293       case Stmt::BinaryOperatorClass:
1294         return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
1295                              R, N);
1296       case Stmt::DeclRefExprClass:
1297         return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
1298                              R, N);
1299       case Stmt::UnaryOperatorClass: {
1300         const UnaryOperator *UO = cast<UnaryOperator>(Ex);
1301         if (UO->getOpcode() == UO_LNot) {
1302           tookTrue = !tookTrue;
1303           Ex = UO->getSubExpr();
1304           continue;
1305         }
1306         return nullptr;
1307       }
1308     }
1309   }
1310 }
1311 
1312 bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
1313                                       BugReporterContext &BRC,
1314                                       BugReport &report,
1315                                       const ExplodedNode *N,
1316                                       Optional<bool> &prunable) {
1317   const Expr *OriginalExpr = Ex;
1318   Ex = Ex->IgnoreParenCasts();
1319 
1320   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1321     const bool quotes = isa<VarDecl>(DR->getDecl());
1322     if (quotes) {
1323       Out << '\'';
1324       const LocationContext *LCtx = N->getLocationContext();
1325       const ProgramState *state = N->getState().get();
1326       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1327                                                 LCtx).getAsRegion()) {
1328         if (report.isInteresting(R))
1329           prunable = false;
1330         else {
1331           const ProgramState *state = N->getState().get();
1332           SVal V = state->getSVal(R);
1333           if (report.isInteresting(V))
1334             prunable = false;
1335         }
1336       }
1337     }
1338     Out << DR->getDecl()->getDeclName().getAsString();
1339     if (quotes)
1340       Out << '\'';
1341     return quotes;
1342   }
1343 
1344   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1345     QualType OriginalTy = OriginalExpr->getType();
1346     if (OriginalTy->isPointerType()) {
1347       if (IL->getValue() == 0) {
1348         Out << "null";
1349         return false;
1350       }
1351     }
1352     else if (OriginalTy->isObjCObjectPointerType()) {
1353       if (IL->getValue() == 0) {
1354         Out << "nil";
1355         return false;
1356       }
1357     }
1358 
1359     Out << IL->getValue();
1360     return false;
1361   }
1362 
1363   return false;
1364 }
1365 
1366 PathDiagnosticPiece *
1367 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1368                                   const BinaryOperator *BExpr,
1369                                   const bool tookTrue,
1370                                   BugReporterContext &BRC,
1371                                   BugReport &R,
1372                                   const ExplodedNode *N) {
1373 
1374   bool shouldInvert = false;
1375   Optional<bool> shouldPrune;
1376 
1377   SmallString<128> LhsString, RhsString;
1378   {
1379     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1380     const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1381                                        shouldPrune);
1382     const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1383                                        shouldPrune);
1384 
1385     shouldInvert = !isVarLHS && isVarRHS;
1386   }
1387 
1388   BinaryOperator::Opcode Op = BExpr->getOpcode();
1389 
1390   if (BinaryOperator::isAssignmentOp(Op)) {
1391     // For assignment operators, all that we care about is that the LHS
1392     // evaluates to "true" or "false".
1393     return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1394                                   BRC, R, N);
1395   }
1396 
1397   // For non-assignment operations, we require that we can understand
1398   // both the LHS and RHS.
1399   if (LhsString.empty() || RhsString.empty() ||
1400       !BinaryOperator::isComparisonOp(Op))
1401     return nullptr;
1402 
1403   // Should we invert the strings if the LHS is not a variable name?
1404   SmallString<256> buf;
1405   llvm::raw_svector_ostream Out(buf);
1406   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1407 
1408   // Do we need to invert the opcode?
1409   if (shouldInvert)
1410     switch (Op) {
1411       default: break;
1412       case BO_LT: Op = BO_GT; break;
1413       case BO_GT: Op = BO_LT; break;
1414       case BO_LE: Op = BO_GE; break;
1415       case BO_GE: Op = BO_LE; break;
1416     }
1417 
1418   if (!tookTrue)
1419     switch (Op) {
1420       case BO_EQ: Op = BO_NE; break;
1421       case BO_NE: Op = BO_EQ; break;
1422       case BO_LT: Op = BO_GE; break;
1423       case BO_GT: Op = BO_LE; break;
1424       case BO_LE: Op = BO_GT; break;
1425       case BO_GE: Op = BO_LT; break;
1426       default:
1427         return nullptr;
1428     }
1429 
1430   switch (Op) {
1431     case BO_EQ:
1432       Out << "equal to ";
1433       break;
1434     case BO_NE:
1435       Out << "not equal to ";
1436       break;
1437     default:
1438       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1439       break;
1440   }
1441 
1442   Out << (shouldInvert ? LhsString : RhsString);
1443   const LocationContext *LCtx = N->getLocationContext();
1444   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1445   PathDiagnosticEventPiece *event =
1446     new PathDiagnosticEventPiece(Loc, Out.str());
1447   if (shouldPrune.hasValue())
1448     event->setPrunable(shouldPrune.getValue());
1449   return event;
1450 }
1451 
1452 PathDiagnosticPiece *
1453 ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1454                                            const Expr *CondVarExpr,
1455                                            const bool tookTrue,
1456                                            BugReporterContext &BRC,
1457                                            BugReport &report,
1458                                            const ExplodedNode *N) {
1459   // FIXME: If there's already a constraint tracker for this variable,
1460   // we shouldn't emit anything here (c.f. the double note in
1461   // test/Analysis/inlining/path-notes.c)
1462   SmallString<256> buf;
1463   llvm::raw_svector_ostream Out(buf);
1464   Out << "Assuming " << LhsString << " is ";
1465 
1466   QualType Ty = CondVarExpr->getType();
1467 
1468   if (Ty->isPointerType())
1469     Out << (tookTrue ? "not null" : "null");
1470   else if (Ty->isObjCObjectPointerType())
1471     Out << (tookTrue ? "not nil" : "nil");
1472   else if (Ty->isBooleanType())
1473     Out << (tookTrue ? "true" : "false");
1474   else if (Ty->isIntegralOrEnumerationType())
1475     Out << (tookTrue ? "non-zero" : "zero");
1476   else
1477     return nullptr;
1478 
1479   const LocationContext *LCtx = N->getLocationContext();
1480   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1481   PathDiagnosticEventPiece *event =
1482     new PathDiagnosticEventPiece(Loc, Out.str());
1483 
1484   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1485     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1486       const ProgramState *state = N->getState().get();
1487       if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1488         if (report.isInteresting(R))
1489           event->setPrunable(false);
1490       }
1491     }
1492   }
1493 
1494   return event;
1495 }
1496 
1497 PathDiagnosticPiece *
1498 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1499                                   const DeclRefExpr *DR,
1500                                   const bool tookTrue,
1501                                   BugReporterContext &BRC,
1502                                   BugReport &report,
1503                                   const ExplodedNode *N) {
1504 
1505   const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1506   if (!VD)
1507     return nullptr;
1508 
1509   SmallString<256> Buf;
1510   llvm::raw_svector_ostream Out(Buf);
1511 
1512   Out << "Assuming '" << VD->getDeclName() << "' is ";
1513 
1514   QualType VDTy = VD->getType();
1515 
1516   if (VDTy->isPointerType())
1517     Out << (tookTrue ? "non-null" : "null");
1518   else if (VDTy->isObjCObjectPointerType())
1519     Out << (tookTrue ? "non-nil" : "nil");
1520   else if (VDTy->isScalarType())
1521     Out << (tookTrue ? "not equal to 0" : "0");
1522   else
1523     return nullptr;
1524 
1525   const LocationContext *LCtx = N->getLocationContext();
1526   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1527   PathDiagnosticEventPiece *event =
1528     new PathDiagnosticEventPiece(Loc, Out.str());
1529 
1530   const ProgramState *state = N->getState().get();
1531   if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1532     if (report.isInteresting(R))
1533       event->setPrunable(false);
1534     else {
1535       SVal V = state->getSVal(R);
1536       if (report.isInteresting(V))
1537         event->setPrunable(false);
1538     }
1539   }
1540   return event;
1541 }
1542 
1543 std::unique_ptr<PathDiagnosticPiece>
1544 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1545                                                     const ExplodedNode *N,
1546                                                     BugReport &BR) {
1547   // Here we suppress false positives coming from system headers. This list is
1548   // based on known issues.
1549   ExprEngine &Eng = BRC.getBugReporter().getEngine();
1550   AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1551   const Decl *D = N->getLocationContext()->getDecl();
1552 
1553   if (AnalysisDeclContext::isInStdNamespace(D)) {
1554     // Skip reports within the 'std' namespace. Although these can sometimes be
1555     // the user's fault, we currently don't report them very well, and
1556     // Note that this will not help for any other data structure libraries, like
1557     // TR1, Boost, or llvm/ADT.
1558     if (Options.shouldSuppressFromCXXStandardLibrary()) {
1559       BR.markInvalid(getTag(), nullptr);
1560       return nullptr;
1561 
1562     } else {
1563       // If the complete 'std' suppression is not enabled, suppress reports
1564       // from the 'std' namespace that are known to produce false positives.
1565 
1566       // The analyzer issues a false use-after-free when std::list::pop_front
1567       // or std::list::pop_back are called multiple times because we cannot
1568       // reason about the internal invariants of the datastructure.
1569       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1570         const CXXRecordDecl *CD = MD->getParent();
1571         if (CD->getName() == "list") {
1572           BR.markInvalid(getTag(), nullptr);
1573           return nullptr;
1574         }
1575       }
1576 
1577       // The analyzer issues a false positive when the constructor of
1578       // std::__independent_bits_engine from algorithms is used.
1579       if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) {
1580         const CXXRecordDecl *CD = MD->getParent();
1581         if (CD->getName() == "__independent_bits_engine") {
1582           BR.markInvalid(getTag(), nullptr);
1583           return nullptr;
1584         }
1585       }
1586 
1587       // The analyzer issues a false positive on
1588       //   std::basic_string<uint8_t> v; v.push_back(1);
1589       // and
1590       //   std::u16string s; s += u'a';
1591       // because we cannot reason about the internal invariants of the
1592       // datastructure.
1593       for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
1594            LCtx = LCtx->getParent()) {
1595         const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
1596         if (!MD)
1597           continue;
1598 
1599         const CXXRecordDecl *CD = MD->getParent();
1600         if (CD->getName() == "basic_string") {
1601           BR.markInvalid(getTag(), nullptr);
1602           return nullptr;
1603         }
1604       }
1605     }
1606   }
1607 
1608   // Skip reports within the sys/queue.h macros as we do not have the ability to
1609   // reason about data structure shapes.
1610   SourceManager &SM = BRC.getSourceManager();
1611   FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1612   while (Loc.isMacroID()) {
1613     Loc = Loc.getSpellingLoc();
1614     if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1615       BR.markInvalid(getTag(), nullptr);
1616       return nullptr;
1617     }
1618   }
1619 
1620   return nullptr;
1621 }
1622 
1623 PathDiagnosticPiece *
1624 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1625                                   const ExplodedNode *PrevN,
1626                                   BugReporterContext &BRC,
1627                                   BugReport &BR) {
1628 
1629   ProgramStateRef State = N->getState();
1630   ProgramPoint ProgLoc = N->getLocation();
1631 
1632   // We are only interested in visiting CallEnter nodes.
1633   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1634   if (!CEnter)
1635     return nullptr;
1636 
1637   // Check if one of the arguments is the region the visitor is tracking.
1638   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1639   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1640   unsigned Idx = 0;
1641   ArrayRef<ParmVarDecl*> parms = Call->parameters();
1642 
1643   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1644                               I != E; ++I, ++Idx) {
1645     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1646 
1647     // Are we tracking the argument or its subregion?
1648     if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1649       continue;
1650 
1651     // Check the function parameter type.
1652     const ParmVarDecl *ParamDecl = *I;
1653     assert(ParamDecl && "Formal parameter has no decl?");
1654     QualType T = ParamDecl->getType();
1655 
1656     if (!(T->isAnyPointerType() || T->isReferenceType())) {
1657       // Function can only change the value passed in by address.
1658       continue;
1659     }
1660 
1661     // If it is a const pointer value, the function does not intend to
1662     // change the value.
1663     if (T->getPointeeType().isConstQualified())
1664       continue;
1665 
1666     // Mark the call site (LocationContext) as interesting if the value of the
1667     // argument is undefined or '0'/'NULL'.
1668     SVal BoundVal = State->getSVal(R);
1669     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1670       BR.markInteresting(CEnter->getCalleeContext());
1671       return nullptr;
1672     }
1673   }
1674   return nullptr;
1675 }
1676