1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // "Meta" ASTConsumer for running different source analyses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
15 #include "ModelInjector.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/Analysis/Analyses/LiveVariables.h"
21 #include "clang/Analysis/CFG.h"
22 #include "clang/Analysis/CallGraph.h"
23 #include "clang/Analysis/CodeInjector.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/CrossTU/CrossTranslationUnit.h"
26 #include "clang/Frontend/CompilerInstance.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
29 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
30 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
31 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
32 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
33 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
35 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
36 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
37 #include "llvm/ADT/PostOrderIterator.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Program.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/raw_ostream.h"
48 using namespace clang;
51 #define DEBUG_TYPE "AnalysisConsumer"
53 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz();
55 STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
56 STATISTIC(NumFunctionsAnalyzed,
57 "The # of functions and blocks analyzed (as top level "
58 "with inlining turned on).");
59 STATISTIC(NumBlocksInAnalyzedFunctions,
60 "The # of basic blocks in the analyzed functions.");
61 STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
62 "The # of visited basic blocks in the analyzed functions.");
63 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
64 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
66 //===----------------------------------------------------------------------===//
67 // Special PathDiagnosticConsumers.
68 //===----------------------------------------------------------------------===//
70 void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
71 PathDiagnosticConsumers &C,
72 const std::string &prefix,
73 const Preprocessor &PP) {
74 createHTMLDiagnosticConsumer(AnalyzerOpts, C,
75 llvm::sys::path::parent_path(prefix), PP);
76 createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
79 void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
80 PathDiagnosticConsumers &C,
81 const std::string &Prefix,
82 const clang::Preprocessor &PP) {
83 llvm_unreachable("'text' consumer should be enabled on ClangDiags");
87 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
88 DiagnosticsEngine &Diag;
91 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
92 : Diag(Diag), IncludePath(false) {}
93 ~ClangDiagPathDiagConsumer() override {}
94 StringRef getName() const override { return "ClangDiags"; }
96 bool supportsLogicalOpControlFlow() const override { return true; }
97 bool supportsCrossFileDiagnostics() const override { return true; }
99 PathGenerationScheme getGenerationScheme() const override {
100 return IncludePath ? Minimal : None;
107 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
108 FilesMade *filesMade) override {
109 unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
110 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
112 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
113 E = Diags.end(); I != E; ++I) {
114 const PathDiagnostic *PD = *I;
115 SourceLocation WarnLoc = PD->getLocation().asLocation();
116 Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
117 << PD->path.back()->getRanges();
119 // First, add extra notes, even if paths should not be included.
120 for (const auto &Piece : PD->path) {
121 if (!isa<PathDiagnosticNotePiece>(Piece.get()))
124 SourceLocation NoteLoc = Piece->getLocation().asLocation();
125 Diag.Report(NoteLoc, NoteID) << Piece->getString()
126 << Piece->getRanges();
132 // Then, add the path notes if necessary.
133 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
134 for (const auto &Piece : FlatPath) {
135 if (isa<PathDiagnosticNotePiece>(Piece.get()))
138 SourceLocation NoteLoc = Piece->getLocation().asLocation();
139 Diag.Report(NoteLoc, NoteID) << Piece->getString()
140 << Piece->getRanges();
145 } // end anonymous namespace
147 //===----------------------------------------------------------------------===//
148 // AnalysisConsumer declaration.
149 //===----------------------------------------------------------------------===//
153 class AnalysisConsumer : public AnalysisASTConsumer,
154 public RecursiveASTVisitor<AnalysisConsumer> {
160 typedef unsigned AnalysisMode;
162 /// Mode of the analyzes while recursively visiting Decls.
163 AnalysisMode RecVisitorMode;
164 /// Bug Reporter to use while recursively visiting Decls.
165 BugReporter *RecVisitorBR;
167 std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
171 const Preprocessor &PP;
172 const std::string OutDir;
173 AnalyzerOptionsRef Opts;
174 ArrayRef<std::string> Plugins;
175 CodeInjector *Injector;
176 cross_tu::CrossTranslationUnitContext CTU;
178 /// Stores the declarations from the local translation unit.
179 /// Note, we pre-compute the local declarations at parse time as an
180 /// optimization to make sure we do not deserialize everything from disk.
181 /// The local declaration to all declarations ratio might be very small when
182 /// working with a PCH file.
183 SetOfDecls LocalTUDecls;
185 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
186 PathDiagnosticConsumers PathConsumers;
188 StoreManagerCreator CreateStoreMgr;
189 ConstraintManagerCreator CreateConstraintMgr;
191 std::unique_ptr<CheckerManager> checkerMgr;
192 std::unique_ptr<AnalysisManager> Mgr;
194 /// Time the analyzes time of each translation unit.
195 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
196 std::unique_ptr<llvm::Timer> TUTotalTimer;
198 /// The information about analyzed functions shared throughout the
199 /// translation unit.
200 FunctionSummariesTy FunctionSummaries;
202 AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
203 AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
204 CodeInjector *injector)
205 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
206 PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
207 Plugins(plugins), Injector(injector), CTU(CI) {
208 DigestAnalyzerOptions();
209 if (Opts->PrintStats || Opts->shouldSerializeStats()) {
210 AnalyzerTimers = llvm::make_unique<llvm::TimerGroup>(
211 "analyzer", "Analyzer timers");
212 TUTotalTimer = llvm::make_unique<llvm::Timer>(
213 "time", "Analyzer total time", *AnalyzerTimers);
214 llvm::EnableStatistics(/* PrintOnExit= */ false);
218 ~AnalysisConsumer() override {
219 if (Opts->PrintStats) {
220 llvm::PrintStatistics();
224 void DigestAnalyzerOptions() {
225 if (Opts->AnalysisDiagOpt != PD_NONE) {
226 // Create the PathDiagnosticConsumer.
227 ClangDiagPathDiagConsumer *clangDiags =
228 new ClangDiagPathDiagConsumer(PP.getDiagnostics());
229 PathConsumers.push_back(clangDiags);
231 if (Opts->AnalysisDiagOpt == PD_TEXT) {
232 clangDiags->enablePaths();
234 } else if (!OutDir.empty()) {
235 switch (Opts->AnalysisDiagOpt) {
237 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
239 CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \
241 #include "clang/StaticAnalyzer/Core/Analyses.def"
246 // Create the analyzer component creators.
247 switch (Opts->AnalysisStoreOpt) {
249 llvm_unreachable("Unknown store manager.");
250 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
251 case NAME##Model: CreateStoreMgr = CREATEFN; break;
252 #include "clang/StaticAnalyzer/Core/Analyses.def"
255 switch (Opts->AnalysisConstraintsOpt) {
257 llvm_unreachable("Unknown constraint manager.");
258 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
259 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
260 #include "clang/StaticAnalyzer/Core/Analyses.def"
264 void DisplayFunction(const Decl *D, AnalysisMode Mode,
265 ExprEngine::InliningModes IMode) {
266 if (!Opts->AnalyzerDisplayProgress)
269 SourceManager &SM = Mgr->getASTContext().getSourceManager();
270 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
272 llvm::errs() << "ANALYZE";
274 if (Mode == AM_Syntax)
275 llvm::errs() << " (Syntax)";
276 else if (Mode == AM_Path) {
277 llvm::errs() << " (Path, ";
279 case ExprEngine::Inline_Minimal:
280 llvm::errs() << " Inline_Minimal";
282 case ExprEngine::Inline_Regular:
283 llvm::errs() << " Inline_Regular";
289 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
291 llvm::errs() << ": " << Loc.getFilename() << ' '
292 << getFunctionName(D) << '\n';
296 void Initialize(ASTContext &Context) override {
299 createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
300 CheckerRegistrationFns, PP.getDiagnostics());
302 Mgr = llvm::make_unique<AnalysisManager>(
303 *Ctx, PP.getDiagnostics(), PP.getLangOpts(), PathConsumers,
304 CreateStoreMgr, CreateConstraintMgr, checkerMgr.get(), *Opts, Injector);
307 /// Store the top level decls in the set to be processed later on.
308 /// (Doing this pre-processing avoids deserialization of data from PCH.)
309 bool HandleTopLevelDecl(DeclGroupRef D) override;
310 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
312 void HandleTranslationUnit(ASTContext &C) override;
314 /// Determine which inlining mode should be used when this function is
315 /// analyzed. This allows to redefine the default inlining policies when
316 /// analyzing a given function.
317 ExprEngine::InliningModes
318 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
320 /// Build the call graph for all the top level decls of this TU and
321 /// use it to define the order in which the functions should be visited.
322 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
324 /// Run analyzes(syntax or path sensitive) on the given function.
325 /// \param Mode - determines if we are requesting syntax only or path
326 /// sensitive only analysis.
327 /// \param VisitedCallees - The output parameter, which is populated with the
328 /// set of functions which should be considered analyzed after analyzing the
329 /// given root function.
330 void HandleCode(Decl *D, AnalysisMode Mode,
331 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
332 SetOfConstDecls *VisitedCallees = nullptr);
334 void RunPathSensitiveChecks(Decl *D,
335 ExprEngine::InliningModes IMode,
336 SetOfConstDecls *VisitedCallees);
337 void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
338 ExprEngine::InliningModes IMode,
339 SetOfConstDecls *VisitedCallees);
341 /// Visitors for the RecursiveASTVisitor.
342 bool shouldWalkTypesOfTypeLocs() const { return false; }
344 /// Handle callbacks for arbitrary Decls.
345 bool VisitDecl(Decl *D) {
346 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
347 if (Mode & AM_Syntax)
348 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
352 bool VisitFunctionDecl(FunctionDecl *FD) {
353 IdentifierInfo *II = FD->getIdentifier();
354 if (II && II->getName().startswith("__inline"))
357 // We skip function template definitions, as their semantics is
358 // only determined when they are instantiated.
359 if (FD->isThisDeclarationADefinition() &&
360 !FD->isDependentContext()) {
361 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
362 HandleCode(FD, RecVisitorMode);
367 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
368 if (MD->isThisDeclarationADefinition()) {
369 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
370 HandleCode(MD, RecVisitorMode);
375 bool VisitBlockDecl(BlockDecl *BD) {
377 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
378 // Since we skip function template definitions, we should skip blocks
379 // declared in those functions as well.
380 if (!BD->isDependentContext()) {
381 HandleCode(BD, RecVisitorMode);
387 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
388 PathConsumers.push_back(Consumer);
391 void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
392 CheckerRegistrationFns.push_back(std::move(Fn));
396 void storeTopLevelDecls(DeclGroupRef DG);
397 std::string getFunctionName(const Decl *D);
399 /// Check if we should skip (not analyze) the given function.
400 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
401 void runAnalysisOnTranslationUnit(ASTContext &C);
403 /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
404 void reportAnalyzerProgress(StringRef S);
406 } // end anonymous namespace
409 //===----------------------------------------------------------------------===//
410 // AnalysisConsumer implementation.
411 //===----------------------------------------------------------------------===//
412 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
413 storeTopLevelDecls(DG);
417 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
418 storeTopLevelDecls(DG);
421 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
422 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
424 // Skip ObjCMethodDecl, wait for the objc container to avoid
426 if (isa<ObjCMethodDecl>(*I))
429 LocalTUDecls.push_back(*I);
433 static bool shouldSkipFunction(const Decl *D,
434 const SetOfConstDecls &Visited,
435 const SetOfConstDecls &VisitedAsTopLevel) {
436 if (VisitedAsTopLevel.count(D))
439 // We want to re-analyse the functions as top level in the following cases:
440 // - The 'init' methods should be reanalyzed because
441 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
442 // 'nil' and unless we analyze the 'init' functions as top level, we will
443 // not catch errors within defensive code.
444 // - We want to reanalyze all ObjC methods as top level to report Retain
445 // Count naming convention errors more aggressively.
446 if (isa<ObjCMethodDecl>(D))
448 // We also want to reanalyze all C++ copy and move assignment operators to
449 // separately check the two cases where 'this' aliases with the parameter and
450 // where it may not. (cplusplus.SelfAssignmentChecker)
451 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
452 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
456 // Otherwise, if we visited the function before, do not reanalyze it.
457 return Visited.count(D);
460 ExprEngine::InliningModes
461 AnalysisConsumer::getInliningModeForFunction(const Decl *D,
462 const SetOfConstDecls &Visited) {
463 // We want to reanalyze all ObjC methods as top level to report Retain
464 // Count naming convention errors more aggressively. But we should tune down
465 // inlining when reanalyzing an already inlined function.
466 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
467 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
468 if (ObjCM->getMethodFamily() != OMF_init)
469 return ExprEngine::Inline_Minimal;
472 return ExprEngine::Inline_Regular;
475 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
476 // Build the Call Graph by adding all the top level declarations to the graph.
477 // Note: CallGraph can trigger deserialization of more items from a pch
478 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
479 // We rely on random access to add the initially processed Decls to CG.
481 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
482 CG.addToCallGraph(LocalTUDecls[i]);
485 // Walk over all of the call graph nodes in topological order, so that we
486 // analyze parents before the children. Skip the functions inlined into
487 // the previously processed functions. Use external Visited set to identify
488 // inlined functions. The topological order allows the "do not reanalyze
489 // previously inlined function" performance heuristic to be triggered more
491 SetOfConstDecls Visited;
492 SetOfConstDecls VisitedAsTopLevel;
493 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
494 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
495 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
496 NumFunctionTopLevel++;
498 CallGraphNode *N = *I;
499 Decl *D = N->getDecl();
501 // Skip the abstract root node.
505 // Skip the functions which have been processed already or previously
507 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
510 // Analyze the function.
511 SetOfConstDecls VisitedCallees;
513 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
514 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
516 // Add the visited callees to the global visited set.
517 for (const Decl *Callee : VisitedCallees)
518 // Decls from CallGraph are already canonical. But Decls coming from
519 // CallExprs may be not. We should canonicalize them manually.
520 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
521 : Callee->getCanonicalDecl());
522 VisitedAsTopLevel.insert(D);
526 static bool isBisonFile(ASTContext &C) {
527 const SourceManager &SM = C.getSourceManager();
528 FileID FID = SM.getMainFileID();
529 StringRef Buffer = SM.getBuffer(FID)->getBuffer();
530 if (Buffer.startswith("/* A Bison parser, made by"))
535 void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
536 BugReporter BR(*Mgr);
537 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
538 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
540 // Run the AST-only checks using the order in which functions are defined.
541 // If inlining is not turned on, use the simplest function order for path
542 // sensitive analyzes as well.
543 RecVisitorMode = AM_Syntax;
544 if (!Mgr->shouldInlineCall())
545 RecVisitorMode |= AM_Path;
548 // Process all the top level declarations.
550 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
551 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
552 // random access. By doing so, we automatically compensate for iterators
553 // possibly being invalidated, although this is a bit slower.
554 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
555 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
556 TraverseDecl(LocalTUDecls[i]);
559 if (Mgr->shouldInlineCall())
560 HandleDeclsCallGraph(LocalTUDeclsSize);
562 // After all decls handled, run checkers on the entire TranslationUnit.
563 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
565 RecVisitorBR = nullptr;
568 void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
569 if (Opts->AnalyzerDisplayProgress)
573 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
575 // Don't run the actions if an error has occurred with parsing the file.
576 DiagnosticsEngine &Diags = PP.getDiagnostics();
577 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
580 if (TUTotalTimer) TUTotalTimer->startTimer();
582 if (isBisonFile(C)) {
583 reportAnalyzerProgress("Skipping bison-generated file\n");
584 } else if (Opts->DisableAllChecks) {
586 // Don't analyze if the user explicitly asked for no checks to be performed
588 reportAnalyzerProgress("All checks are disabled using a supplied option\n");
590 // Otherwise, just run the analysis.
591 runAnalysisOnTranslationUnit(C);
594 if (TUTotalTimer) TUTotalTimer->stopTimer();
596 // Count how many basic blocks we have not covered.
597 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
598 NumVisitedBlocksInAnalyzedFunctions =
599 FunctionSummaries.getTotalNumVisitedBasicBlocks();
600 if (NumBlocksInAnalyzedFunctions > 0)
601 PercentReachableBlocks =
602 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
603 NumBlocksInAnalyzedFunctions;
605 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
606 // FIXME: This should be replaced with something that doesn't rely on
607 // side-effects in PathDiagnosticConsumer's destructor. This is required when
608 // used with option -disable-free.
612 std::string AnalysisConsumer::getFunctionName(const Decl *D) {
614 llvm::raw_string_ostream OS(Str);
616 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
617 OS << FD->getQualifiedNameAsString();
619 // In C++, there are overloads.
620 if (Ctx->getLangOpts().CPlusPlus) {
622 for (const auto &P : FD->parameters()) {
623 if (P != *FD->param_begin())
625 OS << P->getType().getAsString();
630 } else if (isa<BlockDecl>(D)) {
631 PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
634 OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
638 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
640 // FIXME: copy-pasted from CGDebugInfo.cpp.
641 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
642 const DeclContext *DC = OMD->getDeclContext();
643 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
644 OS << OID->getName();
645 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
646 OS << OID->getName();
647 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
648 if (OC->IsClassExtension()) {
649 OS << OC->getClassInterface()->getName();
651 OS << OC->getIdentifier()->getNameStart() << '('
652 << OC->getIdentifier()->getNameStart() << ')';
654 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
655 OS << OCD->getClassInterface()->getName() << '('
656 << OCD->getName() << ')';
657 } else if (isa<ObjCProtocolDecl>(DC)) {
658 // We can extract the type of the class from the self pointer.
659 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
661 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
662 ClassTy.print(OS, PrintingPolicy(LangOptions()));
665 OS << ' ' << OMD->getSelector().getAsString() << ']';
672 AnalysisConsumer::AnalysisMode
673 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
674 if (!Opts->AnalyzeSpecificFunction.empty() &&
675 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
678 // Unless -analyze-all is specified, treat decls differently depending on
679 // where they came from:
680 // - Main source file: run both path-sensitive and non-path-sensitive checks.
681 // - Header files: run non-path-sensitive checks only.
682 // - System headers: don't run any checks.
683 SourceManager &SM = Ctx->getSourceManager();
684 const Stmt *Body = D->getBody();
685 SourceLocation SL = Body ? Body->getLocStart() : D->getLocation();
686 SL = SM.getExpansionLoc(SL);
688 if (!Opts->AnalyzeAll && !Mgr->isInCodeFile(SL)) {
689 if (SL.isInvalid() || SM.isInSystemHeader(SL))
691 return Mode & ~AM_Path;
697 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
698 ExprEngine::InliningModes IMode,
699 SetOfConstDecls *VisitedCallees) {
702 Mode = getModeForDecl(D, Mode);
706 // Clear the AnalysisManager of old AnalysisDeclContexts.
707 Mgr->ClearContexts();
708 // Ignore autosynthesized code.
709 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
712 DisplayFunction(D, Mode, IMode);
713 CFG *DeclCFG = Mgr->getCFG(D);
715 MaxCFGSize.updateMax(DeclCFG->size());
717 BugReporter BR(*Mgr);
719 if (Mode & AM_Syntax)
720 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
721 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
722 RunPathSensitiveChecks(D, IMode, VisitedCallees);
723 if (IMode != ExprEngine::Inline_Minimal)
724 NumFunctionsAnalyzed++;
728 //===----------------------------------------------------------------------===//
729 // Path-sensitive checking.
730 //===----------------------------------------------------------------------===//
732 void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
733 ExprEngine::InliningModes IMode,
734 SetOfConstDecls *VisitedCallees) {
735 // Construct the analysis engine. First check if the CFG is valid.
736 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
740 // See if the LiveVariables analysis scales.
741 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
744 ExprEngine Eng(CTU, *Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,
747 // Set the graph auditor.
748 std::unique_ptr<ExplodedNode::Auditor> Auditor;
749 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
750 Auditor = CreateUbiViz();
751 ExplodedNode::SetAuditor(Auditor.get());
754 // Execute the worklist algorithm.
755 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
756 Mgr->options.getMaxNodesPerTopLevelFunction());
758 // Release the auditor (if any) so that it doesn't monitor the graph
759 // created BugReporter.
760 ExplodedNode::SetAuditor(nullptr);
762 // Visualize the exploded graph.
763 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
764 Eng.ViewGraph(Mgr->options.TrimGraph);
767 Eng.getBugReporter().FlushReports();
770 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
771 ExprEngine::InliningModes IMode,
772 SetOfConstDecls *Visited) {
774 switch (Mgr->getLangOpts().getGC()) {
775 case LangOptions::NonGC:
776 ActionExprEngine(D, false, IMode, Visited);
779 case LangOptions::GCOnly:
780 ActionExprEngine(D, true, IMode, Visited);
783 case LangOptions::HybridGC:
784 ActionExprEngine(D, false, IMode, Visited);
785 ActionExprEngine(D, true, IMode, Visited);
790 //===----------------------------------------------------------------------===//
791 // AnalysisConsumer creation.
792 //===----------------------------------------------------------------------===//
794 std::unique_ptr<AnalysisASTConsumer>
795 ento::CreateAnalysisConsumer(CompilerInstance &CI) {
796 // Disable the effects of '-Werror' when using the AnalysisConsumer.
797 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
799 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
800 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
802 return llvm::make_unique<AnalysisConsumer>(
803 CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
804 CI.getFrontendOpts().Plugins,
805 hasModelPath ? new ModelInjector(CI) : nullptr);
808 //===----------------------------------------------------------------------===//
809 // Ubigraph Visualization. FIXME: Move to separate file.
810 //===----------------------------------------------------------------------===//
814 class UbigraphViz : public ExplodedNode::Auditor {
815 std::unique_ptr<raw_ostream> Out;
816 std::string Filename;
819 typedef llvm::DenseMap<void*,unsigned> VMap;
823 UbigraphViz(std::unique_ptr<raw_ostream> Out, StringRef Filename);
825 ~UbigraphViz() override;
827 void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) override;
830 } // end anonymous namespace
832 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz() {
835 llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P);
836 llvm::errs() << "Writing '" << P << "'.\n";
838 auto Stream = llvm::make_unique<llvm::raw_fd_ostream>(FD, true);
840 return llvm::make_unique<UbigraphViz>(std::move(Stream), P);
843 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
845 assert (Src != Dst && "Self-edges are not allowed.");
847 // Lookup the Src. If it is a new node, it's a root.
848 VMap::iterator SrcI= M.find(Src);
851 if (SrcI == M.end()) {
852 M[Src] = SrcID = Cntr++;
853 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
856 SrcID = SrcI->second;
859 VMap::iterator DstI= M.find(Dst);
862 if (DstI == M.end()) {
863 M[Dst] = DstID = Cntr++;
864 *Out << "('vertex', " << DstID << ")\n";
867 // We have hit DstID before. Change its style to reflect a cache hit.
868 DstID = DstI->second;
869 *Out << "('change_vertex_style', " << DstID << ", 1)\n";
873 *Out << "('edge', " << SrcID << ", " << DstID
874 << ", ('arrow','true'), ('oriented', 'true'))\n";
877 UbigraphViz::UbigraphViz(std::unique_ptr<raw_ostream> OutStream,
879 : Out(std::move(OutStream)), Filename(Filename), Cntr(0) {
881 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
882 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
883 " ('size', '1.5'))\n";
886 UbigraphViz::~UbigraphViz() {
888 llvm::errs() << "Running 'ubiviz' program... ";
891 if (auto Path = llvm::sys::findProgramByName("ubiviz"))
893 std::array<StringRef, 2> Args{{Ubiviz, Filename}};
895 if (llvm::sys::ExecuteAndWait(Ubiviz, Args, llvm::None, {}, 0, 0, &ErrMsg)) {
896 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
900 llvm::sys::fs::remove(Filename);