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