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