clang  3.7.0
AnalysisConsumer.cpp
Go to the documentation of this file.
1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
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 // "Meta" ASTConsumer for running different source analyses.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "ModelInjector.h"
16 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ParentMap.h"
23 #include "clang/Analysis/CFG.h"
29 #include "clang/Lex/Preprocessor.h"
39 #include "llvm/ADT/DepthFirstIterator.h"
40 #include "llvm/ADT/PostOrderIterator.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Program.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <memory>
49 #include <queue>
50 
51 using namespace clang;
52 using namespace ento;
53 using llvm::SmallPtrSet;
54 
55 #define DEBUG_TYPE "AnalysisConsumer"
56 
57 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz();
58 
59 STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
60 STATISTIC(NumFunctionsAnalyzed,
61  "The # of functions and blocks analyzed (as top level "
62  "with inlining turned on).");
63 STATISTIC(NumBlocksInAnalyzedFunctions,
64  "The # of basic blocks in the analyzed functions.");
65 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
66 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
67 
68 //===----------------------------------------------------------------------===//
69 // Special PathDiagnosticConsumers.
70 //===----------------------------------------------------------------------===//
71 
72 void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
74  const std::string &prefix,
75  const Preprocessor &PP) {
76  createHTMLDiagnosticConsumer(AnalyzerOpts, C,
77  llvm::sys::path::parent_path(prefix), PP);
78  createPlistDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
79 }
80 
81 void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
83  const std::string &Prefix,
84  const clang::Preprocessor &PP) {
85  llvm_unreachable("'text' consumer should be enabled on ClangDiags");
86 }
87 
88 namespace {
89 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
91  bool IncludePath;
92 public:
93  ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
94  : Diag(Diag), IncludePath(false) {}
95  ~ClangDiagPathDiagConsumer() override {}
96  StringRef getName() const override { return "ClangDiags"; }
97 
98  bool supportsLogicalOpControlFlow() const override { return true; }
99  bool supportsCrossFileDiagnostics() const override { return true; }
100 
101  PathGenerationScheme getGenerationScheme() const override {
102  return IncludePath ? Minimal : None;
103  }
104 
105  void enablePaths() {
106  IncludePath = true;
107  }
108 
109  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
110  FilesMade *filesMade) override {
111  unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
112  unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
113 
114  for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
115  E = Diags.end(); I != E; ++I) {
116  const PathDiagnostic *PD = *I;
117  SourceLocation WarnLoc = PD->getLocation().asLocation();
118  Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
119  << PD->path.back()->getRanges();
120 
121  if (!IncludePath)
122  continue;
123 
124  PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
125  for (PathPieces::const_iterator PI = FlatPath.begin(),
126  PE = FlatPath.end();
127  PI != PE; ++PI) {
128  SourceLocation NoteLoc = (*PI)->getLocation().asLocation();
129  Diag.Report(NoteLoc, NoteID) << (*PI)->getString()
130  << (*PI)->getRanges();
131  }
132  }
133  }
134 };
135 } // end anonymous namespace
136 
137 //===----------------------------------------------------------------------===//
138 // AnalysisConsumer declaration.
139 //===----------------------------------------------------------------------===//
140 
141 namespace {
142 
143 class AnalysisConsumer : public AnalysisASTConsumer,
144  public DataRecursiveASTVisitor<AnalysisConsumer> {
145  enum {
146  AM_None = 0,
147  AM_Syntax = 0x1,
148  AM_Path = 0x2
149  };
150  typedef unsigned AnalysisMode;
151 
152  /// Mode of the analyzes while recursively visiting Decls.
153  AnalysisMode RecVisitorMode;
154  /// Bug Reporter to use while recursively visiting Decls.
155  BugReporter *RecVisitorBR;
156 
157 public:
158  ASTContext *Ctx;
159  const Preprocessor &PP;
160  const std::string OutDir;
161  AnalyzerOptionsRef Opts;
162  ArrayRef<std::string> Plugins;
163  CodeInjector *Injector;
164 
165  /// \brief Stores the declarations from the local translation unit.
166  /// Note, we pre-compute the local declarations at parse time as an
167  /// optimization to make sure we do not deserialize everything from disk.
168  /// The local declaration to all declarations ratio might be very small when
169  /// working with a PCH file.
170  SetOfDecls LocalTUDecls;
171 
172  // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
173  PathDiagnosticConsumers PathConsumers;
174 
175  StoreManagerCreator CreateStoreMgr;
176  ConstraintManagerCreator CreateConstraintMgr;
177 
178  std::unique_ptr<CheckerManager> checkerMgr;
179  std::unique_ptr<AnalysisManager> Mgr;
180 
181  /// Time the analyzes time of each translation unit.
182  static llvm::Timer* TUTotalTimer;
183 
184  /// The information about analyzed functions shared throughout the
185  /// translation unit.
186  FunctionSummariesTy FunctionSummaries;
187 
188  AnalysisConsumer(const Preprocessor& pp,
189  const std::string& outdir,
190  AnalyzerOptionsRef opts,
191  ArrayRef<std::string> plugins,
192  CodeInjector *injector)
193  : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr), PP(pp),
194  OutDir(outdir), Opts(opts), Plugins(plugins), Injector(injector) {
195  DigestAnalyzerOptions();
196  if (Opts->PrintStats) {
197  llvm::EnableStatistics();
198  TUTotalTimer = new llvm::Timer("Analyzer Total Time");
199  }
200  }
201 
202  ~AnalysisConsumer() override {
203  if (Opts->PrintStats)
204  delete TUTotalTimer;
205  }
206 
207  void DigestAnalyzerOptions() {
208  if (Opts->AnalysisDiagOpt != PD_NONE) {
209  // Create the PathDiagnosticConsumer.
210  ClangDiagPathDiagConsumer *clangDiags =
211  new ClangDiagPathDiagConsumer(PP.getDiagnostics());
212  PathConsumers.push_back(clangDiags);
213 
214  if (Opts->AnalysisDiagOpt == PD_TEXT) {
215  clangDiags->enablePaths();
216 
217  } else if (!OutDir.empty()) {
218  switch (Opts->AnalysisDiagOpt) {
219  default:
220 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
221  case PD_##NAME: \
222  CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \
223  break;
224 #include "clang/StaticAnalyzer/Core/Analyses.def"
225  }
226  }
227  }
228 
229  // Create the analyzer component creators.
230  switch (Opts->AnalysisStoreOpt) {
231  default:
232  llvm_unreachable("Unknown store manager.");
233 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
234  case NAME##Model: CreateStoreMgr = CREATEFN; break;
235 #include "clang/StaticAnalyzer/Core/Analyses.def"
236  }
237 
238  switch (Opts->AnalysisConstraintsOpt) {
239  default:
240  llvm_unreachable("Unknown constraint manager.");
241 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
242  case NAME##Model: CreateConstraintMgr = CREATEFN; break;
243 #include "clang/StaticAnalyzer/Core/Analyses.def"
244  }
245  }
246 
247  void DisplayFunction(const Decl *D, AnalysisMode Mode,
249  if (!Opts->AnalyzerDisplayProgress)
250  return;
251 
252  SourceManager &SM = Mgr->getASTContext().getSourceManager();
254  if (Loc.isValid()) {
255  llvm::errs() << "ANALYZE";
256 
257  if (Mode == AM_Syntax)
258  llvm::errs() << " (Syntax)";
259  else if (Mode == AM_Path) {
260  llvm::errs() << " (Path, ";
261  switch (IMode) {
263  llvm::errs() << " Inline_Minimal";
264  break;
266  llvm::errs() << " Inline_Regular";
267  break;
268  }
269  llvm::errs() << ")";
270  }
271  else
272  assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
273 
274  llvm::errs() << ": " << Loc.getFilename();
275  if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
276  const NamedDecl *ND = cast<NamedDecl>(D);
277  llvm::errs() << ' ' << *ND << '\n';
278  }
279  else if (isa<BlockDecl>(D)) {
280  llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
281  << Loc.getColumn() << '\n';
282  }
283  else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
284  Selector S = MD->getSelector();
285  llvm::errs() << ' ' << S.getAsString();
286  }
287  }
288  }
289 
290  void Initialize(ASTContext &Context) override {
291  Ctx = &Context;
292  checkerMgr = createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
293  PP.getDiagnostics());
294 
295  Mgr = llvm::make_unique<AnalysisManager>(
296  *Ctx, PP.getDiagnostics(), PP.getLangOpts(), PathConsumers,
297  CreateStoreMgr, CreateConstraintMgr, checkerMgr.get(), *Opts, Injector);
298  }
299 
300  /// \brief Store the top level decls in the set to be processed later on.
301  /// (Doing this pre-processing avoids deserialization of data from PCH.)
302  bool HandleTopLevelDecl(DeclGroupRef D) override;
303  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
304 
305  void HandleTranslationUnit(ASTContext &C) override;
306 
307  /// \brief Determine which inlining mode should be used when this function is
308  /// analyzed. This allows to redefine the default inlining policies when
309  /// analyzing a given function.
311  getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
312 
313  /// \brief Build the call graph for all the top level decls of this TU and
314  /// use it to define the order in which the functions should be visited.
315  void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
316 
317  /// \brief Run analyzes(syntax or path sensitive) on the given function.
318  /// \param Mode - determines if we are requesting syntax only or path
319  /// sensitive only analysis.
320  /// \param VisitedCallees - The output parameter, which is populated with the
321  /// set of functions which should be considered analyzed after analyzing the
322  /// given root function.
323  void HandleCode(Decl *D, AnalysisMode Mode,
325  SetOfConstDecls *VisitedCallees = nullptr);
326 
327  void RunPathSensitiveChecks(Decl *D,
329  SetOfConstDecls *VisitedCallees);
330  void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
332  SetOfConstDecls *VisitedCallees);
333 
334  /// Visitors for the RecursiveASTVisitor.
335  bool shouldWalkTypesOfTypeLocs() const { return false; }
336 
337  /// Handle callbacks for arbitrary Decls.
338  bool VisitDecl(Decl *D) {
339  AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
340  if (Mode & AM_Syntax)
341  checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
342  return true;
343  }
344 
345  bool VisitFunctionDecl(FunctionDecl *FD) {
346  IdentifierInfo *II = FD->getIdentifier();
347  if (II && II->getName().startswith("__inline"))
348  return true;
349 
350  // We skip function template definitions, as their semantics is
351  // only determined when they are instantiated.
352  if (FD->isThisDeclarationADefinition() &&
353  !FD->isDependentContext()) {
354  assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
355  HandleCode(FD, RecVisitorMode);
356  }
357  return true;
358  }
359 
360  bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
361  if (MD->isThisDeclarationADefinition()) {
362  assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
363  HandleCode(MD, RecVisitorMode);
364  }
365  return true;
366  }
367 
368  bool VisitBlockDecl(BlockDecl *BD) {
369  if (BD->hasBody()) {
370  assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
371  HandleCode(BD, RecVisitorMode);
372  }
373  return true;
374  }
375 
376  void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
377  PathConsumers.push_back(Consumer);
378  }
379 
380 private:
381  void storeTopLevelDecls(DeclGroupRef DG);
382 
383  /// \brief Check if we should skip (not analyze) the given function.
384  AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
385 
386 };
387 } // end anonymous namespace
388 
389 
390 //===----------------------------------------------------------------------===//
391 // AnalysisConsumer implementation.
392 //===----------------------------------------------------------------------===//
393 llvm::Timer* AnalysisConsumer::TUTotalTimer = nullptr;
394 
395 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
396  storeTopLevelDecls(DG);
397  return true;
398 }
399 
400 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
401  storeTopLevelDecls(DG);
402 }
403 
404 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
405  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
406 
407  // Skip ObjCMethodDecl, wait for the objc container to avoid
408  // analyzing twice.
409  if (isa<ObjCMethodDecl>(*I))
410  continue;
411 
412  LocalTUDecls.push_back(*I);
413  }
414 }
415 
416 static bool shouldSkipFunction(const Decl *D,
417  const SetOfConstDecls &Visited,
418  const SetOfConstDecls &VisitedAsTopLevel) {
419  if (VisitedAsTopLevel.count(D))
420  return true;
421 
422  // We want to re-analyse the functions as top level in the following cases:
423  // - The 'init' methods should be reanalyzed because
424  // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
425  // 'nil' and unless we analyze the 'init' functions as top level, we will
426  // not catch errors within defensive code.
427  // - We want to reanalyze all ObjC methods as top level to report Retain
428  // Count naming convention errors more aggressively.
429  if (isa<ObjCMethodDecl>(D))
430  return false;
431 
432  // Otherwise, if we visited the function before, do not reanalyze it.
433  return Visited.count(D);
434 }
435 
437 AnalysisConsumer::getInliningModeForFunction(const Decl *D,
438  const SetOfConstDecls &Visited) {
439  // We want to reanalyze all ObjC methods as top level to report Retain
440  // Count naming convention errors more aggressively. But we should tune down
441  // inlining when reanalyzing an already inlined function.
442  if (Visited.count(D)) {
443  assert(isa<ObjCMethodDecl>(D) &&
444  "We are only reanalyzing ObjCMethods.");
445  const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
446  if (ObjCM->getMethodFamily() != OMF_init)
448  }
449 
451 }
452 
453 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
454  // Build the Call Graph by adding all the top level declarations to the graph.
455  // Note: CallGraph can trigger deserialization of more items from a pch
456  // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
457  // We rely on random access to add the initially processed Decls to CG.
458  CallGraph CG;
459  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
460  CG.addToCallGraph(LocalTUDecls[i]);
461  }
462 
463  // Walk over all of the call graph nodes in topological order, so that we
464  // analyze parents before the children. Skip the functions inlined into
465  // the previously processed functions. Use external Visited set to identify
466  // inlined functions. The topological order allows the "do not reanalyze
467  // previously inlined function" performance heuristic to be triggered more
468  // often.
469  SetOfConstDecls Visited;
470  SetOfConstDecls VisitedAsTopLevel;
471  llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
472  for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
473  I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
474  NumFunctionTopLevel++;
475 
476  CallGraphNode *N = *I;
477  Decl *D = N->getDecl();
478 
479  // Skip the abstract root node.
480  if (!D)
481  continue;
482 
483  // Skip the functions which have been processed already or previously
484  // inlined.
485  if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
486  continue;
487 
488  // Analyze the function.
489  SetOfConstDecls VisitedCallees;
490 
491  HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
492  (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
493 
494  // Add the visited callees to the global visited set.
495  for (SetOfConstDecls::iterator I = VisitedCallees.begin(),
496  E = VisitedCallees.end(); I != E; ++I) {
497  Visited.insert(*I);
498  }
499  VisitedAsTopLevel.insert(D);
500  }
501 }
502 
503 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
504  // Don't run the actions if an error has occurred with parsing the file.
505  DiagnosticsEngine &Diags = PP.getDiagnostics();
506  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
507  return;
508 
509  // Don't analyze if the user explicitly asked for no checks to be performed
510  // on this file.
511  if (Opts->DisableAllChecks)
512  return;
513 
514  {
515  if (TUTotalTimer) TUTotalTimer->startTimer();
516 
517  // Introduce a scope to destroy BR before Mgr.
518  BugReporter BR(*Mgr);
520  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
521 
522  // Run the AST-only checks using the order in which functions are defined.
523  // If inlining is not turned on, use the simplest function order for path
524  // sensitive analyzes as well.
525  RecVisitorMode = AM_Syntax;
526  if (!Mgr->shouldInlineCall())
527  RecVisitorMode |= AM_Path;
528  RecVisitorBR = &BR;
529 
530  // Process all the top level declarations.
531  //
532  // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
533  // entries. Thus we don't use an iterator, but rely on LocalTUDecls
534  // random access. By doing so, we automatically compensate for iterators
535  // possibly being invalidated, although this is a bit slower.
536  const unsigned LocalTUDeclsSize = LocalTUDecls.size();
537  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
538  TraverseDecl(LocalTUDecls[i]);
539  }
540 
541  if (Mgr->shouldInlineCall())
542  HandleDeclsCallGraph(LocalTUDeclsSize);
543 
544  // After all decls handled, run checkers on the entire TranslationUnit.
545  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
546 
547  RecVisitorBR = nullptr;
548  }
549 
550  // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
551  // FIXME: This should be replaced with something that doesn't rely on
552  // side-effects in PathDiagnosticConsumer's destructor. This is required when
553  // used with option -disable-free.
554  Mgr.reset();
555 
556  if (TUTotalTimer) TUTotalTimer->stopTimer();
557 
558  // Count how many basic blocks we have not covered.
559  NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
560  if (NumBlocksInAnalyzedFunctions > 0)
561  PercentReachableBlocks =
562  (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
563  NumBlocksInAnalyzedFunctions;
564 
565 }
566 
567 static std::string getFunctionName(const Decl *D) {
568  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
569  return ID->getSelector().getAsString();
570  }
571  if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
572  IdentifierInfo *II = ND->getIdentifier();
573  if (II)
574  return II->getName();
575  }
576  return "";
577 }
578 
579 AnalysisConsumer::AnalysisMode
580 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
581  if (!Opts->AnalyzeSpecificFunction.empty() &&
582  getFunctionName(D) != Opts->AnalyzeSpecificFunction)
583  return AM_None;
584 
585  // Unless -analyze-all is specified, treat decls differently depending on
586  // where they came from:
587  // - Main source file: run both path-sensitive and non-path-sensitive checks.
588  // - Header files: run non-path-sensitive checks only.
589  // - System headers: don't run any checks.
590  SourceManager &SM = Ctx->getSourceManager();
591  SourceLocation SL = D->hasBody() ? D->getBody()->getLocStart()
592  : D->getLocation();
593  SL = SM.getExpansionLoc(SL);
594 
595  if (!Opts->AnalyzeAll && !SM.isWrittenInMainFile(SL)) {
596  if (SL.isInvalid() || SM.isInSystemHeader(SL))
597  return AM_None;
598  return Mode & ~AM_Path;
599  }
600 
601  return Mode;
602 }
603 
604 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
606  SetOfConstDecls *VisitedCallees) {
607  if (!D->hasBody())
608  return;
609  Mode = getModeForDecl(D, Mode);
610  if (Mode == AM_None)
611  return;
612 
613  DisplayFunction(D, Mode, IMode);
614  CFG *DeclCFG = Mgr->getCFG(D);
615  if (DeclCFG) {
616  unsigned CFGSize = DeclCFG->size();
617  MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
618  }
619 
620  // Clear the AnalysisManager of old AnalysisDeclContexts.
621  Mgr->ClearContexts();
622  BugReporter BR(*Mgr);
623 
624  if (Mode & AM_Syntax)
625  checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
626  if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
627  RunPathSensitiveChecks(D, IMode, VisitedCallees);
628  if (IMode != ExprEngine::Inline_Minimal)
629  NumFunctionsAnalyzed++;
630  }
631 }
632 
633 //===----------------------------------------------------------------------===//
634 // Path-sensitive checking.
635 //===----------------------------------------------------------------------===//
636 
637 void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
639  SetOfConstDecls *VisitedCallees) {
640  // Construct the analysis engine. First check if the CFG is valid.
641  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
642  if (!Mgr->getCFG(D))
643  return;
644 
645  // See if the LiveVariables analysis scales.
646  if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
647  return;
648 
649  ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
650 
651  // Set the graph auditor.
652  std::unique_ptr<ExplodedNode::Auditor> Auditor;
653  if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
654  Auditor = CreateUbiViz();
655  ExplodedNode::SetAuditor(Auditor.get());
656  }
657 
658  // Execute the worklist algorithm.
659  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
660  Mgr->options.getMaxNodesPerTopLevelFunction());
661 
662  // Release the auditor (if any) so that it doesn't monitor the graph
663  // created BugReporter.
664  ExplodedNode::SetAuditor(nullptr);
665 
666  // Visualize the exploded graph.
667  if (Mgr->options.visualizeExplodedGraphWithGraphViz)
668  Eng.ViewGraph(Mgr->options.TrimGraph);
669 
670  // Display warnings.
671  Eng.getBugReporter().FlushReports();
672 }
673 
674 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
676  SetOfConstDecls *Visited) {
677 
678  switch (Mgr->getLangOpts().getGC()) {
679  case LangOptions::NonGC:
680  ActionExprEngine(D, false, IMode, Visited);
681  break;
682 
683  case LangOptions::GCOnly:
684  ActionExprEngine(D, true, IMode, Visited);
685  break;
686 
688  ActionExprEngine(D, false, IMode, Visited);
689  ActionExprEngine(D, true, IMode, Visited);
690  break;
691  }
692 }
693 
694 //===----------------------------------------------------------------------===//
695 // AnalysisConsumer creation.
696 //===----------------------------------------------------------------------===//
697 
698 std::unique_ptr<AnalysisASTConsumer>
700  // Disable the effects of '-Werror' when using the AnalysisConsumer.
702 
703  AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
704  bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
705 
706  return llvm::make_unique<AnalysisConsumer>(
707  CI.getPreprocessor(), CI.getFrontendOpts().OutputFile, analyzerOpts,
709  hasModelPath ? new ModelInjector(CI) : nullptr);
710 }
711 
712 //===----------------------------------------------------------------------===//
713 // Ubigraph Visualization. FIXME: Move to separate file.
714 //===----------------------------------------------------------------------===//
715 
716 namespace {
717 
718 class UbigraphViz : public ExplodedNode::Auditor {
719  std::unique_ptr<raw_ostream> Out;
720  std::string Filename;
721  unsigned Cntr;
722 
723  typedef llvm::DenseMap<void*,unsigned> VMap;
724  VMap M;
725 
726 public:
727  UbigraphViz(std::unique_ptr<raw_ostream> Out, StringRef Filename);
728 
729  ~UbigraphViz() override;
730 
731  void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) override;
732 };
733 
734 } // end anonymous namespace
735 
736 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz() {
738  int FD;
739  llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P);
740  llvm::errs() << "Writing '" << P << "'.\n";
741 
742  auto Stream = llvm::make_unique<llvm::raw_fd_ostream>(FD, true);
743 
744  return llvm::make_unique<UbigraphViz>(std::move(Stream), P);
745 }
746 
747 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
748 
749  assert (Src != Dst && "Self-edges are not allowed.");
750 
751  // Lookup the Src. If it is a new node, it's a root.
752  VMap::iterator SrcI= M.find(Src);
753  unsigned SrcID;
754 
755  if (SrcI == M.end()) {
756  M[Src] = SrcID = Cntr++;
757  *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
758  }
759  else
760  SrcID = SrcI->second;
761 
762  // Lookup the Dst.
763  VMap::iterator DstI= M.find(Dst);
764  unsigned DstID;
765 
766  if (DstI == M.end()) {
767  M[Dst] = DstID = Cntr++;
768  *Out << "('vertex', " << DstID << ")\n";
769  }
770  else {
771  // We have hit DstID before. Change its style to reflect a cache hit.
772  DstID = DstI->second;
773  *Out << "('change_vertex_style', " << DstID << ", 1)\n";
774  }
775 
776  // Add the edge.
777  *Out << "('edge', " << SrcID << ", " << DstID
778  << ", ('arrow','true'), ('oriented', 'true'))\n";
779 }
780 
781 UbigraphViz::UbigraphViz(std::unique_ptr<raw_ostream> Out, StringRef Filename)
782  : Out(std::move(Out)), Filename(Filename), Cntr(0) {
783 
784  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
785  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
786  " ('size', '1.5'))\n";
787 }
788 
789 UbigraphViz::~UbigraphViz() {
790  Out.reset();
791  llvm::errs() << "Running 'ubiviz' program... ";
792  std::string ErrMsg;
793  std::string Ubiviz;
794  if (auto Path = llvm::sys::findProgramByName("ubiviz"))
795  Ubiviz = *Path;
796  std::vector<const char*> args;
797  args.push_back(Ubiviz.c_str());
798  args.push_back(Filename.c_str());
799  args.push_back(nullptr);
800 
801  if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0], nullptr, nullptr, 0, 0,
802  &ErrMsg)) {
803  llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
804  }
805 
806  // Delete the file.
807  llvm::sys::fs::remove(Filename);
808 }
The AST-based call graph.
Definition: CallGraph.h:34
std::string OutputFile
The output file, if any.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Smart pointer class that efficiently represents Objective-C method names.
unsigned getColumn() const
Return the presumed column number of this location.
bool isValid() const
Defines the clang::FileManager interface and associated types.
IdentifierInfo * getIdentifier() const
Definition: Decl.h:163
STATISTIC(NumFunctionTopLevel,"The # of functions at top level.")
Defines the SourceManager interface.
Decl * getDecl() const
Definition: CallGraph.h:163
iterator end()
Definition: DeclGroup.h:109
PathPieces flatten(bool ShouldFlattenMacros) const
bool hasErrorOccurred() const
Definition: Diagnostic.h:573
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:851
PathDiagnosticLocation getLocation() const
std::unique_ptr< ConstraintManager >(* ConstraintManagerCreator)(ProgramStateManager &, SubEngine *)
Definition: ProgramState.h:42
FullSourceLoc asLocation() const
Follow the default settings for inlining callees.
Definition: ExprEngine.h:53
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
std::deque< Decl * > SetOfDecls
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:679
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
Definition: DeclObjC.h:497
FrontendOptions & getFrontendOpts()
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:856
unsigned size() const
Definition: CFG.h:937
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
iterator begin()
Definition: DeclGroup.h:103
unsigned getLine() const
Return the presumed line number of this location.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
bool isInvalid() const
AnalyzerOptionsRef getAnalyzerOpts()
AnnotatingParser & P
ASTContext * Context
static bool shouldSkipFunction(const Decl *D, const SetOfConstDecls &Visited, const SetOfConstDecls &VisitedAsTopLevel)
ID
Defines the set of possible language-specific address spaces.
Definition: AddressSpaces.h:27
SourceManager & SM
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition: ExprEngine.h:51
std::vector< std::string > Plugins
The list of plugins to load.
StringRef getName() const
Return the actual identifier string.
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:580
StringRef getShortDescription() const
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:812
Defines the clang::Preprocessor interface.
bool isWrittenInMainFile(SourceLocation Loc) const
Returns true if the spelling location for the given location is in the main file buffer.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
This file defines the clang::ento::ModelInjector class which implements the clang::CodeInjector inter...
Represents an unpacked "presumed" location which can be presented to the user.
#define false
Definition: stdbool.h:33
const char * getFilename() const
Return the presumed filename of this location.
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
std::vector< PathDiagnosticConsumer * > PathDiagnosticConsumers
virtual Stmt * getBody() const
Definition: DeclBase.h:840
std::string getAsString() const
Derive the full selector name (e.g. "foo:bar:") and return it as an std::string.
Do minimal inlining of callees.
Definition: ExprEngine.h:55
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:676
static std::string getFunctionName(const Decl *D)
CodeInjector is an interface which is responsible for injecting AST of function definitions that may ...
Definition: CodeInjector.h:36
bool isThisDeclarationADefinition() const
Definition: Decl.h:1766
std::unique_ptr< AnalysisASTConsumer > CreateAnalysisConsumer(CompilerInstance &CI)
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
Definition: Diagnostic.h:451
static std::unique_ptr< ExplodedNode::Auditor > CreateUbiViz()
static void SetAuditor(Auditor *A)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
void addToCallGraph(Decl *D)
Populate the call graph with the functions in the given declaration.
Definition: CallGraph.h:53
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:78
SourceLocation getLocation() const
Definition: DeclBase.h:372
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:846
std::unique_ptr< CheckerManager > createCheckerManager(AnalyzerOptions &opts, const LangOptions &langOpts, ArrayRef< std::string > plugins, DiagnosticsEngine &diags)
This class handles loading and caching of source files into memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:96
std::unique_ptr< StoreManager >(* StoreManagerCreator)(ProgramStateManager &)
Definition: ProgramState.h:44
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.