10b57cec5SDimitry Andric //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // "Meta" ASTConsumer for running different source analyses.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
140b57cec5SDimitry Andric #include "ModelInjector.h"
150b57cec5SDimitry Andric #include "clang/AST/Decl.h"
160b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
170b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
180b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
190b57cec5SDimitry Andric #include "clang/Analysis/Analyses/LiveVariables.h"
200b57cec5SDimitry Andric #include "clang/Analysis/CFG.h"
210b57cec5SDimitry Andric #include "clang/Analysis/CallGraph.h"
220b57cec5SDimitry Andric #include "clang/Analysis/CodeInjector.h"
23fe6060f1SDimitry Andric #include "clang/Analysis/MacroExpansionContext.h"
245ffd83dbSDimitry Andric #include "clang/Analysis/PathDiagnostic.h"
250b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
260b57cec5SDimitry Andric #include "clang/CrossTU/CrossTranslationUnit.h"
270b57cec5SDimitry Andric #include "clang/Frontend/CompilerInstance.h"
280b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h"
295ffd83dbSDimitry Andric #include "clang/Rewrite/Core/Rewriter.h"
300b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
310b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
320b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
330b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
340b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
350b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
360b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
370eae32dcSDimitry Andric #include "llvm/ADT/ScopeExit.h"
380b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
390b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
400b57cec5SDimitry Andric #include "llvm/Support/Path.h"
410b57cec5SDimitry Andric #include "llvm/Support/Program.h"
420b57cec5SDimitry Andric #include "llvm/Support/Timer.h"
430b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
440b57cec5SDimitry Andric #include <memory>
450b57cec5SDimitry Andric #include <queue>
460b57cec5SDimitry Andric #include <utility>
470b57cec5SDimitry Andric
480b57cec5SDimitry Andric using namespace clang;
490b57cec5SDimitry Andric using namespace ento;
500b57cec5SDimitry Andric
510b57cec5SDimitry Andric #define DEBUG_TYPE "AnalysisConsumer"
520b57cec5SDimitry Andric
530b57cec5SDimitry Andric STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
540b57cec5SDimitry Andric STATISTIC(NumFunctionsAnalyzed,
550b57cec5SDimitry Andric "The # of functions and blocks analyzed (as top level "
560b57cec5SDimitry Andric "with inlining turned on).");
570b57cec5SDimitry Andric STATISTIC(NumBlocksInAnalyzedFunctions,
580b57cec5SDimitry Andric "The # of basic blocks in the analyzed functions.");
590b57cec5SDimitry Andric STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
600b57cec5SDimitry Andric "The # of visited basic blocks in the analyzed functions.");
610b57cec5SDimitry Andric STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
620b57cec5SDimitry Andric STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
630b57cec5SDimitry Andric
640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
650b57cec5SDimitry Andric // AnalysisConsumer declaration.
660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
670b57cec5SDimitry Andric
680b57cec5SDimitry Andric namespace {
690b57cec5SDimitry Andric
700b57cec5SDimitry Andric class AnalysisConsumer : public AnalysisASTConsumer,
710b57cec5SDimitry Andric public RecursiveASTVisitor<AnalysisConsumer> {
720b57cec5SDimitry Andric enum {
730b57cec5SDimitry Andric AM_None = 0,
740b57cec5SDimitry Andric AM_Syntax = 0x1,
750b57cec5SDimitry Andric AM_Path = 0x2
760b57cec5SDimitry Andric };
770b57cec5SDimitry Andric typedef unsigned AnalysisMode;
780b57cec5SDimitry Andric
790b57cec5SDimitry Andric /// Mode of the analyzes while recursively visiting Decls.
800b57cec5SDimitry Andric AnalysisMode RecVisitorMode;
810b57cec5SDimitry Andric /// Bug Reporter to use while recursively visiting Decls.
820b57cec5SDimitry Andric BugReporter *RecVisitorBR;
830b57cec5SDimitry Andric
840b57cec5SDimitry Andric std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
850b57cec5SDimitry Andric
860b57cec5SDimitry Andric public:
870b57cec5SDimitry Andric ASTContext *Ctx;
885ffd83dbSDimitry Andric Preprocessor &PP;
890b57cec5SDimitry Andric const std::string OutDir;
905f757f3fSDimitry Andric AnalyzerOptions &Opts;
910b57cec5SDimitry Andric ArrayRef<std::string> Plugins;
920b57cec5SDimitry Andric CodeInjector *Injector;
930b57cec5SDimitry Andric cross_tu::CrossTranslationUnitContext CTU;
940b57cec5SDimitry Andric
950b57cec5SDimitry Andric /// Stores the declarations from the local translation unit.
960b57cec5SDimitry Andric /// Note, we pre-compute the local declarations at parse time as an
970b57cec5SDimitry Andric /// optimization to make sure we do not deserialize everything from disk.
980b57cec5SDimitry Andric /// The local declaration to all declarations ratio might be very small when
990b57cec5SDimitry Andric /// working with a PCH file.
1000b57cec5SDimitry Andric SetOfDecls LocalTUDecls;
1010b57cec5SDimitry Andric
102fe6060f1SDimitry Andric MacroExpansionContext MacroExpansions;
103fe6060f1SDimitry Andric
1040b57cec5SDimitry Andric // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
1050b57cec5SDimitry Andric PathDiagnosticConsumers PathConsumers;
1060b57cec5SDimitry Andric
1070b57cec5SDimitry Andric StoreManagerCreator CreateStoreMgr;
1080b57cec5SDimitry Andric ConstraintManagerCreator CreateConstraintMgr;
1090b57cec5SDimitry Andric
1100b57cec5SDimitry Andric std::unique_ptr<CheckerManager> checkerMgr;
1110b57cec5SDimitry Andric std::unique_ptr<AnalysisManager> Mgr;
1120b57cec5SDimitry Andric
1130b57cec5SDimitry Andric /// Time the analyzes time of each translation unit.
1140b57cec5SDimitry Andric std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
1150b57cec5SDimitry Andric std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
1160b57cec5SDimitry Andric std::unique_ptr<llvm::Timer> ExprEngineTimer;
1170b57cec5SDimitry Andric std::unique_ptr<llvm::Timer> BugReporterTimer;
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric /// The information about analyzed functions shared throughout the
1200b57cec5SDimitry Andric /// translation unit.
1210b57cec5SDimitry Andric FunctionSummariesTy FunctionSummaries;
1220b57cec5SDimitry Andric
AnalysisConsumer(CompilerInstance & CI,const std::string & outdir,AnalyzerOptions & opts,ArrayRef<std::string> plugins,CodeInjector * injector)1230b57cec5SDimitry Andric AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
1245f757f3fSDimitry Andric AnalyzerOptions &opts, ArrayRef<std::string> plugins,
1250b57cec5SDimitry Andric CodeInjector *injector)
1260b57cec5SDimitry Andric : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
1275f757f3fSDimitry Andric PP(CI.getPreprocessor()), OutDir(outdir), Opts(opts),
128fe6060f1SDimitry Andric Plugins(plugins), Injector(injector), CTU(CI),
129fe6060f1SDimitry Andric MacroExpansions(CI.getLangOpts()) {
1300b57cec5SDimitry Andric DigestAnalyzerOptions();
1315f757f3fSDimitry Andric if (Opts.AnalyzerDisplayProgress || Opts.PrintStats ||
1325f757f3fSDimitry Andric Opts.ShouldSerializeStats) {
133a7dea167SDimitry Andric AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
1340b57cec5SDimitry Andric "analyzer", "Analyzer timers");
135a7dea167SDimitry Andric SyntaxCheckTimer = std::make_unique<llvm::Timer>(
1360b57cec5SDimitry Andric "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers);
137a7dea167SDimitry Andric ExprEngineTimer = std::make_unique<llvm::Timer>(
1380b57cec5SDimitry Andric "exprengine", "Path exploration time", *AnalyzerTimers);
139a7dea167SDimitry Andric BugReporterTimer = std::make_unique<llvm::Timer>(
1400b57cec5SDimitry Andric "bugreporter", "Path-sensitive report post-processing time",
1410b57cec5SDimitry Andric *AnalyzerTimers);
142fe6060f1SDimitry Andric }
143fe6060f1SDimitry Andric
1445f757f3fSDimitry Andric if (Opts.PrintStats || Opts.ShouldSerializeStats) {
14504eeddc0SDimitry Andric llvm::EnableStatistics(/* DoPrintOnExit= */ false);
1460b57cec5SDimitry Andric }
147fe6060f1SDimitry Andric
1485f757f3fSDimitry Andric if (Opts.ShouldDisplayMacroExpansions)
149fe6060f1SDimitry Andric MacroExpansions.registerForPreprocessor(PP);
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric
~AnalysisConsumer()1520b57cec5SDimitry Andric ~AnalysisConsumer() override {
1535f757f3fSDimitry Andric if (Opts.PrintStats) {
1540b57cec5SDimitry Andric llvm::PrintStatistics();
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric }
1570b57cec5SDimitry Andric
DigestAnalyzerOptions()1580b57cec5SDimitry Andric void DigestAnalyzerOptions() {
1595f757f3fSDimitry Andric switch (Opts.AnalysisDiagOpt) {
1605ffd83dbSDimitry Andric case PD_NONE:
1615ffd83dbSDimitry Andric break;
1620b57cec5SDimitry Andric #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
1630b57cec5SDimitry Andric case PD_##NAME: \
1645f757f3fSDimitry Andric CREATEFN(Opts.getDiagOpts(), PathConsumers, OutDir, PP, CTU, \
165fe6060f1SDimitry Andric MacroExpansions); \
1660b57cec5SDimitry Andric break;
1670b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
1685ffd83dbSDimitry Andric default:
1695ffd83dbSDimitry Andric llvm_unreachable("Unknown analyzer output type!");
1700b57cec5SDimitry Andric }
1710b57cec5SDimitry Andric
1720b57cec5SDimitry Andric // Create the analyzer component creators.
17381ad6265SDimitry Andric CreateStoreMgr = &CreateRegionStoreManager;
1740b57cec5SDimitry Andric
1755f757f3fSDimitry Andric switch (Opts.AnalysisConstraintsOpt) {
1760b57cec5SDimitry Andric default:
1770b57cec5SDimitry Andric llvm_unreachable("Unknown constraint manager.");
1780b57cec5SDimitry Andric #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
1790b57cec5SDimitry Andric case NAME##Model: CreateConstraintMgr = CREATEFN; break;
1800b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Analyses.def"
1810b57cec5SDimitry Andric }
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric
DisplayTime(llvm::TimeRecord & Time)184fe6060f1SDimitry Andric void DisplayTime(llvm::TimeRecord &Time) {
1855f757f3fSDimitry Andric if (!Opts.AnalyzerDisplayProgress) {
186fe6060f1SDimitry Andric return;
187fe6060f1SDimitry Andric }
188fe6060f1SDimitry Andric llvm::errs() << " : " << llvm::format("%1.1f", Time.getWallTime() * 1000)
189fe6060f1SDimitry Andric << " ms\n";
190fe6060f1SDimitry Andric }
191fe6060f1SDimitry Andric
DisplayFunction(const Decl * D,AnalysisMode Mode,ExprEngine::InliningModes IMode)1920b57cec5SDimitry Andric void DisplayFunction(const Decl *D, AnalysisMode Mode,
1930b57cec5SDimitry Andric ExprEngine::InliningModes IMode) {
1945f757f3fSDimitry Andric if (!Opts.AnalyzerDisplayProgress)
1950b57cec5SDimitry Andric return;
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric SourceManager &SM = Mgr->getASTContext().getSourceManager();
1980b57cec5SDimitry Andric PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
1990b57cec5SDimitry Andric if (Loc.isValid()) {
2000b57cec5SDimitry Andric llvm::errs() << "ANALYZE";
2010b57cec5SDimitry Andric
2020b57cec5SDimitry Andric if (Mode == AM_Syntax)
2030b57cec5SDimitry Andric llvm::errs() << " (Syntax)";
2040b57cec5SDimitry Andric else if (Mode == AM_Path) {
2050b57cec5SDimitry Andric llvm::errs() << " (Path, ";
2060b57cec5SDimitry Andric switch (IMode) {
2070b57cec5SDimitry Andric case ExprEngine::Inline_Minimal:
2080b57cec5SDimitry Andric llvm::errs() << " Inline_Minimal";
2090b57cec5SDimitry Andric break;
2100b57cec5SDimitry Andric case ExprEngine::Inline_Regular:
2110b57cec5SDimitry Andric llvm::errs() << " Inline_Regular";
2120b57cec5SDimitry Andric break;
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric llvm::errs() << ")";
2155ffd83dbSDimitry Andric } else
2160b57cec5SDimitry Andric assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
2170b57cec5SDimitry Andric
218fe6060f1SDimitry Andric llvm::errs() << ": " << Loc.getFilename() << ' '
219fe6060f1SDimitry Andric << AnalysisDeclContext::getFunctionName(D);
2200b57cec5SDimitry Andric }
2210b57cec5SDimitry Andric }
2220b57cec5SDimitry Andric
Initialize(ASTContext & Context)2230b57cec5SDimitry Andric void Initialize(ASTContext &Context) override {
2240b57cec5SDimitry Andric Ctx = &Context;
2255f757f3fSDimitry Andric checkerMgr = std::make_unique<CheckerManager>(*Ctx, Opts, PP, Plugins,
2265ffd83dbSDimitry Andric CheckerRegistrationFns);
2270b57cec5SDimitry Andric
2285ffd83dbSDimitry Andric Mgr = std::make_unique<AnalysisManager>(*Ctx, PP, PathConsumers,
2295ffd83dbSDimitry Andric CreateStoreMgr, CreateConstraintMgr,
2305f757f3fSDimitry Andric checkerMgr.get(), Opts, Injector);
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric
2330b57cec5SDimitry Andric /// Store the top level decls in the set to be processed later on.
2340b57cec5SDimitry Andric /// (Doing this pre-processing avoids deserialization of data from PCH.)
2350b57cec5SDimitry Andric bool HandleTopLevelDecl(DeclGroupRef D) override;
2360b57cec5SDimitry Andric void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
2370b57cec5SDimitry Andric
2380b57cec5SDimitry Andric void HandleTranslationUnit(ASTContext &C) override;
2390b57cec5SDimitry Andric
2400b57cec5SDimitry Andric /// Determine which inlining mode should be used when this function is
2410b57cec5SDimitry Andric /// analyzed. This allows to redefine the default inlining policies when
2420b57cec5SDimitry Andric /// analyzing a given function.
2430b57cec5SDimitry Andric ExprEngine::InliningModes
2440b57cec5SDimitry Andric getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
2450b57cec5SDimitry Andric
2460b57cec5SDimitry Andric /// Build the call graph for all the top level decls of this TU and
2470b57cec5SDimitry Andric /// use it to define the order in which the functions should be visited.
2480b57cec5SDimitry Andric void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
2490b57cec5SDimitry Andric
2500b57cec5SDimitry Andric /// Run analyzes(syntax or path sensitive) on the given function.
2510b57cec5SDimitry Andric /// \param Mode - determines if we are requesting syntax only or path
2520b57cec5SDimitry Andric /// sensitive only analysis.
2530b57cec5SDimitry Andric /// \param VisitedCallees - The output parameter, which is populated with the
2540b57cec5SDimitry Andric /// set of functions which should be considered analyzed after analyzing the
2550b57cec5SDimitry Andric /// given root function.
2560b57cec5SDimitry Andric void HandleCode(Decl *D, AnalysisMode Mode,
2570b57cec5SDimitry Andric ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
2580b57cec5SDimitry Andric SetOfConstDecls *VisitedCallees = nullptr);
2590b57cec5SDimitry Andric
2600b57cec5SDimitry Andric void RunPathSensitiveChecks(Decl *D,
2610b57cec5SDimitry Andric ExprEngine::InliningModes IMode,
2620b57cec5SDimitry Andric SetOfConstDecls *VisitedCallees);
2630b57cec5SDimitry Andric
2640b57cec5SDimitry Andric /// Visitors for the RecursiveASTVisitor.
shouldWalkTypesOfTypeLocs() const2650b57cec5SDimitry Andric bool shouldWalkTypesOfTypeLocs() const { return false; }
2660b57cec5SDimitry Andric
2670b57cec5SDimitry Andric /// Handle callbacks for arbitrary Decls.
VisitDecl(Decl * D)2680b57cec5SDimitry Andric bool VisitDecl(Decl *D) {
2690b57cec5SDimitry Andric AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
2700b57cec5SDimitry Andric if (Mode & AM_Syntax) {
2710b57cec5SDimitry Andric if (SyntaxCheckTimer)
2720b57cec5SDimitry Andric SyntaxCheckTimer->startTimer();
2730b57cec5SDimitry Andric checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
2740b57cec5SDimitry Andric if (SyntaxCheckTimer)
2750b57cec5SDimitry Andric SyntaxCheckTimer->stopTimer();
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric return true;
2780b57cec5SDimitry Andric }
2790b57cec5SDimitry Andric
VisitVarDecl(VarDecl * VD)2800b57cec5SDimitry Andric bool VisitVarDecl(VarDecl *VD) {
2815f757f3fSDimitry Andric if (!Opts.IsNaiveCTUEnabled)
2820b57cec5SDimitry Andric return true;
2830b57cec5SDimitry Andric
2840b57cec5SDimitry Andric if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
28581ad6265SDimitry Andric if (!cross_tu::shouldImport(VD, *Ctx))
2860b57cec5SDimitry Andric return true;
2870b57cec5SDimitry Andric } else {
2880b57cec5SDimitry Andric // Cannot be initialized in another TU.
2890b57cec5SDimitry Andric return true;
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric
2920b57cec5SDimitry Andric if (VD->getAnyInitializer())
2930b57cec5SDimitry Andric return true;
2940b57cec5SDimitry Andric
2950b57cec5SDimitry Andric llvm::Expected<const VarDecl *> CTUDeclOrError =
2965f757f3fSDimitry Andric CTU.getCrossTUDefinition(VD, Opts.CTUDir, Opts.CTUIndexName,
2975f757f3fSDimitry Andric Opts.DisplayCTUProgress);
2980b57cec5SDimitry Andric
2990b57cec5SDimitry Andric if (!CTUDeclOrError) {
3000b57cec5SDimitry Andric handleAllErrors(CTUDeclOrError.takeError(),
3010b57cec5SDimitry Andric [&](const cross_tu::IndexError &IE) {
3020b57cec5SDimitry Andric CTU.emitCrossTUDiagnostics(IE);
3030b57cec5SDimitry Andric });
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric
3060b57cec5SDimitry Andric return true;
3070b57cec5SDimitry Andric }
3080b57cec5SDimitry Andric
VisitFunctionDecl(FunctionDecl * FD)3090b57cec5SDimitry Andric bool VisitFunctionDecl(FunctionDecl *FD) {
3100b57cec5SDimitry Andric IdentifierInfo *II = FD->getIdentifier();
3115f757f3fSDimitry Andric if (II && II->getName().starts_with("__inline"))
3120b57cec5SDimitry Andric return true;
3130b57cec5SDimitry Andric
3140b57cec5SDimitry Andric // We skip function template definitions, as their semantics is
3150b57cec5SDimitry Andric // only determined when they are instantiated.
3160b57cec5SDimitry Andric if (FD->isThisDeclarationADefinition() &&
3170b57cec5SDimitry Andric !FD->isDependentContext()) {
3180b57cec5SDimitry Andric assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
3190b57cec5SDimitry Andric HandleCode(FD, RecVisitorMode);
3200b57cec5SDimitry Andric }
3210b57cec5SDimitry Andric return true;
3220b57cec5SDimitry Andric }
3230b57cec5SDimitry Andric
VisitObjCMethodDecl(ObjCMethodDecl * MD)3240b57cec5SDimitry Andric bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
3250b57cec5SDimitry Andric if (MD->isThisDeclarationADefinition()) {
3260b57cec5SDimitry Andric assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
3270b57cec5SDimitry Andric HandleCode(MD, RecVisitorMode);
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric return true;
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric
VisitBlockDecl(BlockDecl * BD)3320b57cec5SDimitry Andric bool VisitBlockDecl(BlockDecl *BD) {
3330b57cec5SDimitry Andric if (BD->hasBody()) {
3340b57cec5SDimitry Andric assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
3350b57cec5SDimitry Andric // Since we skip function template definitions, we should skip blocks
3360b57cec5SDimitry Andric // declared in those functions as well.
3370b57cec5SDimitry Andric if (!BD->isDependentContext()) {
3380b57cec5SDimitry Andric HandleCode(BD, RecVisitorMode);
3390b57cec5SDimitry Andric }
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric return true;
3420b57cec5SDimitry Andric }
3430b57cec5SDimitry Andric
AddDiagnosticConsumer(PathDiagnosticConsumer * Consumer)3440b57cec5SDimitry Andric void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
3450b57cec5SDimitry Andric PathConsumers.push_back(Consumer);
3460b57cec5SDimitry Andric }
3470b57cec5SDimitry Andric
AddCheckerRegistrationFn(std::function<void (CheckerRegistry &)> Fn)3480b57cec5SDimitry Andric void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
3490b57cec5SDimitry Andric CheckerRegistrationFns.push_back(std::move(Fn));
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric
3520b57cec5SDimitry Andric private:
3530b57cec5SDimitry Andric void storeTopLevelDecls(DeclGroupRef DG);
3540b57cec5SDimitry Andric
3550b57cec5SDimitry Andric /// Check if we should skip (not analyze) the given function.
3560b57cec5SDimitry Andric AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
3570b57cec5SDimitry Andric void runAnalysisOnTranslationUnit(ASTContext &C);
3580b57cec5SDimitry Andric
3595f757f3fSDimitry Andric /// Print \p S to stderr if \c Opts.AnalyzerDisplayProgress is set.
3600b57cec5SDimitry Andric void reportAnalyzerProgress(StringRef S);
3615ffd83dbSDimitry Andric }; // namespace
3620b57cec5SDimitry Andric } // end anonymous namespace
3630b57cec5SDimitry Andric
3640b57cec5SDimitry Andric
3650b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3660b57cec5SDimitry Andric // AnalysisConsumer implementation.
3670b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
HandleTopLevelDecl(DeclGroupRef DG)3680b57cec5SDimitry Andric bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
3690b57cec5SDimitry Andric storeTopLevelDecls(DG);
3700b57cec5SDimitry Andric return true;
3710b57cec5SDimitry Andric }
3720b57cec5SDimitry Andric
HandleTopLevelDeclInObjCContainer(DeclGroupRef DG)3730b57cec5SDimitry Andric void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
3740b57cec5SDimitry Andric storeTopLevelDecls(DG);
3750b57cec5SDimitry Andric }
3760b57cec5SDimitry Andric
storeTopLevelDecls(DeclGroupRef DG)3770b57cec5SDimitry Andric void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
37881ad6265SDimitry Andric for (auto &I : DG) {
3790b57cec5SDimitry Andric
3800b57cec5SDimitry Andric // Skip ObjCMethodDecl, wait for the objc container to avoid
3810b57cec5SDimitry Andric // analyzing twice.
38281ad6265SDimitry Andric if (isa<ObjCMethodDecl>(I))
3830b57cec5SDimitry Andric continue;
3840b57cec5SDimitry Andric
38581ad6265SDimitry Andric LocalTUDecls.push_back(I);
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric }
3880b57cec5SDimitry Andric
shouldSkipFunction(const Decl * D,const SetOfConstDecls & Visited,const SetOfConstDecls & VisitedAsTopLevel)3890b57cec5SDimitry Andric static bool shouldSkipFunction(const Decl *D,
3900b57cec5SDimitry Andric const SetOfConstDecls &Visited,
3910b57cec5SDimitry Andric const SetOfConstDecls &VisitedAsTopLevel) {
3920b57cec5SDimitry Andric if (VisitedAsTopLevel.count(D))
3930b57cec5SDimitry Andric return true;
3940b57cec5SDimitry Andric
3955ffd83dbSDimitry Andric // Skip analysis of inheriting constructors as top-level functions. These
3965ffd83dbSDimitry Andric // constructors don't even have a body written down in the code, so even if
3975ffd83dbSDimitry Andric // we find a bug, we won't be able to display it.
3985ffd83dbSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
3995ffd83dbSDimitry Andric if (CD->isInheritingConstructor())
4005ffd83dbSDimitry Andric return true;
4015ffd83dbSDimitry Andric
4020b57cec5SDimitry Andric // We want to re-analyse the functions as top level in the following cases:
4030b57cec5SDimitry Andric // - The 'init' methods should be reanalyzed because
4040b57cec5SDimitry Andric // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
4050b57cec5SDimitry Andric // 'nil' and unless we analyze the 'init' functions as top level, we will
4060b57cec5SDimitry Andric // not catch errors within defensive code.
4070b57cec5SDimitry Andric // - We want to reanalyze all ObjC methods as top level to report Retain
4080b57cec5SDimitry Andric // Count naming convention errors more aggressively.
4090b57cec5SDimitry Andric if (isa<ObjCMethodDecl>(D))
4100b57cec5SDimitry Andric return false;
4110b57cec5SDimitry Andric // We also want to reanalyze all C++ copy and move assignment operators to
4120b57cec5SDimitry Andric // separately check the two cases where 'this' aliases with the parameter and
4130b57cec5SDimitry Andric // where it may not. (cplusplus.SelfAssignmentChecker)
4140b57cec5SDimitry Andric if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
4150b57cec5SDimitry Andric if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
4160b57cec5SDimitry Andric return false;
4170b57cec5SDimitry Andric }
4180b57cec5SDimitry Andric
4190b57cec5SDimitry Andric // Otherwise, if we visited the function before, do not reanalyze it.
4200b57cec5SDimitry Andric return Visited.count(D);
4210b57cec5SDimitry Andric }
4220b57cec5SDimitry Andric
4230b57cec5SDimitry Andric ExprEngine::InliningModes
getInliningModeForFunction(const Decl * D,const SetOfConstDecls & Visited)4240b57cec5SDimitry Andric AnalysisConsumer::getInliningModeForFunction(const Decl *D,
4250b57cec5SDimitry Andric const SetOfConstDecls &Visited) {
4260b57cec5SDimitry Andric // We want to reanalyze all ObjC methods as top level to report Retain
4270b57cec5SDimitry Andric // Count naming convention errors more aggressively. But we should tune down
4280b57cec5SDimitry Andric // inlining when reanalyzing an already inlined function.
4290b57cec5SDimitry Andric if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
4300b57cec5SDimitry Andric const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
4310b57cec5SDimitry Andric if (ObjCM->getMethodFamily() != OMF_init)
4320b57cec5SDimitry Andric return ExprEngine::Inline_Minimal;
4330b57cec5SDimitry Andric }
4340b57cec5SDimitry Andric
4350b57cec5SDimitry Andric return ExprEngine::Inline_Regular;
4360b57cec5SDimitry Andric }
4370b57cec5SDimitry Andric
HandleDeclsCallGraph(const unsigned LocalTUDeclsSize)4380b57cec5SDimitry Andric void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
4390b57cec5SDimitry Andric // Build the Call Graph by adding all the top level declarations to the graph.
4400b57cec5SDimitry Andric // Note: CallGraph can trigger deserialization of more items from a pch
4410b57cec5SDimitry Andric // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
4420b57cec5SDimitry Andric // We rely on random access to add the initially processed Decls to CG.
4430b57cec5SDimitry Andric CallGraph CG;
4440b57cec5SDimitry Andric for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
4450b57cec5SDimitry Andric CG.addToCallGraph(LocalTUDecls[i]);
4460b57cec5SDimitry Andric }
4470b57cec5SDimitry Andric
4480b57cec5SDimitry Andric // Walk over all of the call graph nodes in topological order, so that we
4490b57cec5SDimitry Andric // analyze parents before the children. Skip the functions inlined into
4500b57cec5SDimitry Andric // the previously processed functions. Use external Visited set to identify
4510b57cec5SDimitry Andric // inlined functions. The topological order allows the "do not reanalyze
4520b57cec5SDimitry Andric // previously inlined function" performance heuristic to be triggered more
4530b57cec5SDimitry Andric // often.
4540b57cec5SDimitry Andric SetOfConstDecls Visited;
4550b57cec5SDimitry Andric SetOfConstDecls VisitedAsTopLevel;
4560b57cec5SDimitry Andric llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
45781ad6265SDimitry Andric for (auto &N : RPOT) {
4580b57cec5SDimitry Andric NumFunctionTopLevel++;
4590b57cec5SDimitry Andric
4600b57cec5SDimitry Andric Decl *D = N->getDecl();
4610b57cec5SDimitry Andric
4620b57cec5SDimitry Andric // Skip the abstract root node.
4630b57cec5SDimitry Andric if (!D)
4640b57cec5SDimitry Andric continue;
4650b57cec5SDimitry Andric
4660b57cec5SDimitry Andric // Skip the functions which have been processed already or previously
4670b57cec5SDimitry Andric // inlined.
4680b57cec5SDimitry Andric if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
4690b57cec5SDimitry Andric continue;
4700b57cec5SDimitry Andric
47181ad6265SDimitry Andric // The CallGraph might have declarations as callees. However, during CTU
47281ad6265SDimitry Andric // the declaration might form a declaration chain with the newly imported
47381ad6265SDimitry Andric // definition from another TU. In this case we don't want to analyze the
47481ad6265SDimitry Andric // function definition as toplevel.
47581ad6265SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
47681ad6265SDimitry Andric // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
47781ad6265SDimitry Andric // that has the body.
47881ad6265SDimitry Andric FD->hasBody(FD);
47981ad6265SDimitry Andric if (CTU.isImportedAsNew(FD))
48081ad6265SDimitry Andric continue;
48181ad6265SDimitry Andric }
48281ad6265SDimitry Andric
4830b57cec5SDimitry Andric // Analyze the function.
4840b57cec5SDimitry Andric SetOfConstDecls VisitedCallees;
4850b57cec5SDimitry Andric
4860b57cec5SDimitry Andric HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
4870b57cec5SDimitry Andric (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
4880b57cec5SDimitry Andric
4890b57cec5SDimitry Andric // Add the visited callees to the global visited set.
4900b57cec5SDimitry Andric for (const Decl *Callee : VisitedCallees)
4910b57cec5SDimitry Andric // Decls from CallGraph are already canonical. But Decls coming from
4920b57cec5SDimitry Andric // CallExprs may be not. We should canonicalize them manually.
4930b57cec5SDimitry Andric Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
4940b57cec5SDimitry Andric : Callee->getCanonicalDecl());
4950b57cec5SDimitry Andric VisitedAsTopLevel.insert(D);
4960b57cec5SDimitry Andric }
4970b57cec5SDimitry Andric }
4980b57cec5SDimitry Andric
fileContainsString(StringRef Substring,ASTContext & C)4990eae32dcSDimitry Andric static bool fileContainsString(StringRef Substring, ASTContext &C) {
5000b57cec5SDimitry Andric const SourceManager &SM = C.getSourceManager();
5010b57cec5SDimitry Andric FileID FID = SM.getMainFileID();
502e8d8bef9SDimitry Andric StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();
5030eae32dcSDimitry Andric return Buffer.contains(Substring);
5040b57cec5SDimitry Andric }
5050b57cec5SDimitry Andric
reportAnalyzerFunctionMisuse(const AnalyzerOptions & Opts,const ASTContext & Ctx)50681ad6265SDimitry Andric static void reportAnalyzerFunctionMisuse(const AnalyzerOptions &Opts,
50781ad6265SDimitry Andric const ASTContext &Ctx) {
50881ad6265SDimitry Andric llvm::errs() << "Every top-level function was skipped.\n";
50981ad6265SDimitry Andric
51081ad6265SDimitry Andric if (!Opts.AnalyzerDisplayProgress)
51181ad6265SDimitry Andric llvm::errs() << "Pass the -analyzer-display-progress for tracking which "
51281ad6265SDimitry Andric "functions are analyzed.\n";
51381ad6265SDimitry Andric
51481ad6265SDimitry Andric bool HasBrackets =
51581ad6265SDimitry Andric Opts.AnalyzeSpecificFunction.find("(") != std::string::npos;
51681ad6265SDimitry Andric
51781ad6265SDimitry Andric if (Ctx.getLangOpts().CPlusPlus && !HasBrackets) {
51881ad6265SDimitry Andric llvm::errs()
51981ad6265SDimitry Andric << "For analyzing C++ code you need to pass the function parameter "
52081ad6265SDimitry Andric "list: -analyze-function=\"foobar(int, _Bool)\"\n";
52181ad6265SDimitry Andric } else if (!Ctx.getLangOpts().CPlusPlus && HasBrackets) {
52281ad6265SDimitry Andric llvm::errs() << "For analyzing C code you shouldn't pass the function "
52381ad6265SDimitry Andric "parameter list, only the name of the function: "
52481ad6265SDimitry Andric "-analyze-function=foobar\n";
52581ad6265SDimitry Andric }
52681ad6265SDimitry Andric }
52781ad6265SDimitry Andric
runAnalysisOnTranslationUnit(ASTContext & C)5280b57cec5SDimitry Andric void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
5290b57cec5SDimitry Andric BugReporter BR(*Mgr);
530*0fca6ea1SDimitry Andric const TranslationUnitDecl *TU = C.getTranslationUnitDecl();
531*0fca6ea1SDimitry Andric BR.setAnalysisEntryPoint(TU);
5320b57cec5SDimitry Andric if (SyntaxCheckTimer)
5330b57cec5SDimitry Andric SyntaxCheckTimer->startTimer();
5340b57cec5SDimitry Andric checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
5350b57cec5SDimitry Andric if (SyntaxCheckTimer)
5360b57cec5SDimitry Andric SyntaxCheckTimer->stopTimer();
5370b57cec5SDimitry Andric
5380b57cec5SDimitry Andric // Run the AST-only checks using the order in which functions are defined.
5390b57cec5SDimitry Andric // If inlining is not turned on, use the simplest function order for path
5400b57cec5SDimitry Andric // sensitive analyzes as well.
5410b57cec5SDimitry Andric RecVisitorMode = AM_Syntax;
5420b57cec5SDimitry Andric if (!Mgr->shouldInlineCall())
5430b57cec5SDimitry Andric RecVisitorMode |= AM_Path;
5440b57cec5SDimitry Andric RecVisitorBR = &BR;
5450b57cec5SDimitry Andric
5460b57cec5SDimitry Andric // Process all the top level declarations.
5470b57cec5SDimitry Andric //
5480b57cec5SDimitry Andric // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
5490b57cec5SDimitry Andric // entries. Thus we don't use an iterator, but rely on LocalTUDecls
5500b57cec5SDimitry Andric // random access. By doing so, we automatically compensate for iterators
5510b57cec5SDimitry Andric // possibly being invalidated, although this is a bit slower.
5520b57cec5SDimitry Andric const unsigned LocalTUDeclsSize = LocalTUDecls.size();
5530b57cec5SDimitry Andric for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
5540b57cec5SDimitry Andric TraverseDecl(LocalTUDecls[i]);
5550b57cec5SDimitry Andric }
5560b57cec5SDimitry Andric
5570b57cec5SDimitry Andric if (Mgr->shouldInlineCall())
5580b57cec5SDimitry Andric HandleDeclsCallGraph(LocalTUDeclsSize);
5590b57cec5SDimitry Andric
5600b57cec5SDimitry Andric // After all decls handled, run checkers on the entire TranslationUnit.
5610b57cec5SDimitry Andric checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
5620b57cec5SDimitry Andric
563a7dea167SDimitry Andric BR.FlushReports();
5640b57cec5SDimitry Andric RecVisitorBR = nullptr;
56581ad6265SDimitry Andric
56681ad6265SDimitry Andric // If the user wanted to analyze a specific function and the number of basic
56781ad6265SDimitry Andric // blocks analyzed is zero, than the user might not specified the function
56881ad6265SDimitry Andric // name correctly.
56981ad6265SDimitry Andric // FIXME: The user might have analyzed the requested function in Syntax mode,
57081ad6265SDimitry Andric // but we are unaware of that.
5715f757f3fSDimitry Andric if (!Opts.AnalyzeSpecificFunction.empty() && NumFunctionsAnalyzed == 0)
5725f757f3fSDimitry Andric reportAnalyzerFunctionMisuse(Opts, *Ctx);
5730b57cec5SDimitry Andric }
5740b57cec5SDimitry Andric
reportAnalyzerProgress(StringRef S)5750b57cec5SDimitry Andric void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
5765f757f3fSDimitry Andric if (Opts.AnalyzerDisplayProgress)
5770b57cec5SDimitry Andric llvm::errs() << S;
5780b57cec5SDimitry Andric }
5790b57cec5SDimitry Andric
HandleTranslationUnit(ASTContext & C)5800b57cec5SDimitry Andric void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
5810b57cec5SDimitry Andric // Don't run the actions if an error has occurred with parsing the file.
5820b57cec5SDimitry Andric DiagnosticsEngine &Diags = PP.getDiagnostics();
5830b57cec5SDimitry Andric if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
5840b57cec5SDimitry Andric return;
5850b57cec5SDimitry Andric
5860eae32dcSDimitry Andric // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
5870eae32dcSDimitry Andric // FIXME: This should be replaced with something that doesn't rely on
5880eae32dcSDimitry Andric // side-effects in PathDiagnosticConsumer's destructor. This is required when
5890eae32dcSDimitry Andric // used with option -disable-free.
5900eae32dcSDimitry Andric const auto DiagFlusherScopeExit =
5910eae32dcSDimitry Andric llvm::make_scope_exit([this] { Mgr.reset(); });
5920eae32dcSDimitry Andric
5935f757f3fSDimitry Andric if (Opts.ShouldIgnoreBisonGeneratedFiles &&
5940eae32dcSDimitry Andric fileContainsString("/* A Bison parser, made by", C)) {
5950b57cec5SDimitry Andric reportAnalyzerProgress("Skipping bison-generated file\n");
5960eae32dcSDimitry Andric return;
5970eae32dcSDimitry Andric }
5980eae32dcSDimitry Andric
5995f757f3fSDimitry Andric if (Opts.ShouldIgnoreFlexGeneratedFiles &&
6000eae32dcSDimitry Andric fileContainsString("/* A lexical scanner generated by flex", C)) {
6010eae32dcSDimitry Andric reportAnalyzerProgress("Skipping flex-generated file\n");
6020eae32dcSDimitry Andric return;
6030eae32dcSDimitry Andric }
6040b57cec5SDimitry Andric
6050b57cec5SDimitry Andric // Don't analyze if the user explicitly asked for no checks to be performed
6060b57cec5SDimitry Andric // on this file.
6075f757f3fSDimitry Andric if (Opts.DisableAllCheckers) {
6080b57cec5SDimitry Andric reportAnalyzerProgress("All checks are disabled using a supplied option\n");
6090eae32dcSDimitry Andric return;
6100eae32dcSDimitry Andric }
6110eae32dcSDimitry Andric
6120b57cec5SDimitry Andric // Otherwise, just run the analysis.
6130b57cec5SDimitry Andric runAnalysisOnTranslationUnit(C);
6140b57cec5SDimitry Andric
6150b57cec5SDimitry Andric // Count how many basic blocks we have not covered.
6160b57cec5SDimitry Andric NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
6170b57cec5SDimitry Andric NumVisitedBlocksInAnalyzedFunctions =
6180b57cec5SDimitry Andric FunctionSummaries.getTotalNumVisitedBasicBlocks();
6190b57cec5SDimitry Andric if (NumBlocksInAnalyzedFunctions > 0)
6200b57cec5SDimitry Andric PercentReachableBlocks =
6210b57cec5SDimitry Andric (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
6220b57cec5SDimitry Andric NumBlocksInAnalyzedFunctions;
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric
6250b57cec5SDimitry Andric AnalysisConsumer::AnalysisMode
getModeForDecl(Decl * D,AnalysisMode Mode)6260b57cec5SDimitry Andric AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
6275f757f3fSDimitry Andric if (!Opts.AnalyzeSpecificFunction.empty() &&
6285f757f3fSDimitry Andric AnalysisDeclContext::getFunctionName(D) != Opts.AnalyzeSpecificFunction)
6290b57cec5SDimitry Andric return AM_None;
6300b57cec5SDimitry Andric
6310b57cec5SDimitry Andric // Unless -analyze-all is specified, treat decls differently depending on
6320b57cec5SDimitry Andric // where they came from:
6330b57cec5SDimitry Andric // - Main source file: run both path-sensitive and non-path-sensitive checks.
6340b57cec5SDimitry Andric // - Header files: run non-path-sensitive checks only.
6350b57cec5SDimitry Andric // - System headers: don't run any checks.
6365f757f3fSDimitry Andric if (Opts.AnalyzeAll)
6374824e7fdSDimitry Andric return Mode;
6384824e7fdSDimitry Andric
6394824e7fdSDimitry Andric const SourceManager &SM = Ctx->getSourceManager();
6404824e7fdSDimitry Andric
6414824e7fdSDimitry Andric const SourceLocation Loc = [&SM](Decl *D) -> SourceLocation {
6420b57cec5SDimitry Andric const Stmt *Body = D->getBody();
6430b57cec5SDimitry Andric SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
6444824e7fdSDimitry Andric return SM.getExpansionLoc(SL);
6454824e7fdSDimitry Andric }(D);
6460b57cec5SDimitry Andric
6474824e7fdSDimitry Andric // Ignore system headers.
6484824e7fdSDimitry Andric if (Loc.isInvalid() || SM.isInSystemHeader(Loc))
6490b57cec5SDimitry Andric return AM_None;
6504824e7fdSDimitry Andric
6514824e7fdSDimitry Andric // Disable path sensitive analysis in user-headers.
6524824e7fdSDimitry Andric if (!Mgr->isInCodeFile(Loc))
6530b57cec5SDimitry Andric return Mode & ~AM_Path;
6540b57cec5SDimitry Andric
6550b57cec5SDimitry Andric return Mode;
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric
HandleCode(Decl * D,AnalysisMode Mode,ExprEngine::InliningModes IMode,SetOfConstDecls * VisitedCallees)6580b57cec5SDimitry Andric void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
6590b57cec5SDimitry Andric ExprEngine::InliningModes IMode,
6600b57cec5SDimitry Andric SetOfConstDecls *VisitedCallees) {
6610b57cec5SDimitry Andric if (!D->hasBody())
6620b57cec5SDimitry Andric return;
6630b57cec5SDimitry Andric Mode = getModeForDecl(D, Mode);
6640b57cec5SDimitry Andric if (Mode == AM_None)
6650b57cec5SDimitry Andric return;
6660b57cec5SDimitry Andric
6670b57cec5SDimitry Andric // Clear the AnalysisManager of old AnalysisDeclContexts.
6680b57cec5SDimitry Andric Mgr->ClearContexts();
6690b57cec5SDimitry Andric // Ignore autosynthesized code.
6700b57cec5SDimitry Andric if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
6710b57cec5SDimitry Andric return;
6720b57cec5SDimitry Andric
6730b57cec5SDimitry Andric CFG *DeclCFG = Mgr->getCFG(D);
6740b57cec5SDimitry Andric if (DeclCFG)
6750b57cec5SDimitry Andric MaxCFGSize.updateMax(DeclCFG->size());
6760b57cec5SDimitry Andric
677fe6060f1SDimitry Andric DisplayFunction(D, Mode, IMode);
6780b57cec5SDimitry Andric BugReporter BR(*Mgr);
679*0fca6ea1SDimitry Andric BR.setAnalysisEntryPoint(D);
6800b57cec5SDimitry Andric
6810b57cec5SDimitry Andric if (Mode & AM_Syntax) {
682fe6060f1SDimitry Andric llvm::TimeRecord CheckerStartTime;
683fe6060f1SDimitry Andric if (SyntaxCheckTimer) {
684fe6060f1SDimitry Andric CheckerStartTime = SyntaxCheckTimer->getTotalTime();
6850b57cec5SDimitry Andric SyntaxCheckTimer->startTimer();
686fe6060f1SDimitry Andric }
6870b57cec5SDimitry Andric checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
688fe6060f1SDimitry Andric if (SyntaxCheckTimer) {
6890b57cec5SDimitry Andric SyntaxCheckTimer->stopTimer();
690fe6060f1SDimitry Andric llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime();
691fe6060f1SDimitry Andric CheckerEndTime -= CheckerStartTime;
692fe6060f1SDimitry Andric DisplayTime(CheckerEndTime);
693fe6060f1SDimitry Andric }
6940b57cec5SDimitry Andric }
695a7dea167SDimitry Andric
696a7dea167SDimitry Andric BR.FlushReports();
697a7dea167SDimitry Andric
6980b57cec5SDimitry Andric if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
6990b57cec5SDimitry Andric RunPathSensitiveChecks(D, IMode, VisitedCallees);
7000b57cec5SDimitry Andric if (IMode != ExprEngine::Inline_Minimal)
7010b57cec5SDimitry Andric NumFunctionsAnalyzed++;
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric }
7040b57cec5SDimitry Andric
7050b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7060b57cec5SDimitry Andric // Path-sensitive checking.
7070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7080b57cec5SDimitry Andric
RunPathSensitiveChecks(Decl * D,ExprEngine::InliningModes IMode,SetOfConstDecls * VisitedCallees)7090b57cec5SDimitry Andric void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
7100b57cec5SDimitry Andric ExprEngine::InliningModes IMode,
7110b57cec5SDimitry Andric SetOfConstDecls *VisitedCallees) {
7120b57cec5SDimitry Andric // Construct the analysis engine. First check if the CFG is valid.
7130b57cec5SDimitry Andric // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
7140b57cec5SDimitry Andric if (!Mgr->getCFG(D))
7150b57cec5SDimitry Andric return;
7160b57cec5SDimitry Andric
7170b57cec5SDimitry Andric // See if the LiveVariables analysis scales.
7180b57cec5SDimitry Andric if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
7190b57cec5SDimitry Andric return;
7200b57cec5SDimitry Andric
7210b57cec5SDimitry Andric ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
7220b57cec5SDimitry Andric
7230b57cec5SDimitry Andric // Execute the worklist algorithm.
724fe6060f1SDimitry Andric llvm::TimeRecord ExprEngineStartTime;
725fe6060f1SDimitry Andric if (ExprEngineTimer) {
726fe6060f1SDimitry Andric ExprEngineStartTime = ExprEngineTimer->getTotalTime();
7270b57cec5SDimitry Andric ExprEngineTimer->startTimer();
728fe6060f1SDimitry Andric }
7290b57cec5SDimitry Andric Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
7300b57cec5SDimitry Andric Mgr->options.MaxNodesPerTopLevelFunction);
731fe6060f1SDimitry Andric if (ExprEngineTimer) {
7320b57cec5SDimitry Andric ExprEngineTimer->stopTimer();
733fe6060f1SDimitry Andric llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime();
734fe6060f1SDimitry Andric ExprEngineEndTime -= ExprEngineStartTime;
735fe6060f1SDimitry Andric DisplayTime(ExprEngineEndTime);
736fe6060f1SDimitry Andric }
7370b57cec5SDimitry Andric
7380b57cec5SDimitry Andric if (!Mgr->options.DumpExplodedGraphTo.empty())
7390b57cec5SDimitry Andric Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
7400b57cec5SDimitry Andric
7410b57cec5SDimitry Andric // Visualize the exploded graph.
7420b57cec5SDimitry Andric if (Mgr->options.visualizeExplodedGraphWithGraphViz)
7430b57cec5SDimitry Andric Eng.ViewGraph(Mgr->options.TrimGraph);
7440b57cec5SDimitry Andric
7450b57cec5SDimitry Andric // Display warnings.
7460b57cec5SDimitry Andric if (BugReporterTimer)
7470b57cec5SDimitry Andric BugReporterTimer->startTimer();
7480b57cec5SDimitry Andric Eng.getBugReporter().FlushReports();
7490b57cec5SDimitry Andric if (BugReporterTimer)
7500b57cec5SDimitry Andric BugReporterTimer->stopTimer();
7510b57cec5SDimitry Andric }
7520b57cec5SDimitry Andric
7530b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7540b57cec5SDimitry Andric // AnalysisConsumer creation.
7550b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7560b57cec5SDimitry Andric
7570b57cec5SDimitry Andric std::unique_ptr<AnalysisASTConsumer>
CreateAnalysisConsumer(CompilerInstance & CI)7580b57cec5SDimitry Andric ento::CreateAnalysisConsumer(CompilerInstance &CI) {
7590b57cec5SDimitry Andric // Disable the effects of '-Werror' when using the AnalysisConsumer.
7600b57cec5SDimitry Andric CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
7610b57cec5SDimitry Andric
7625f757f3fSDimitry Andric AnalyzerOptions &analyzerOpts = CI.getAnalyzerOpts();
7635f757f3fSDimitry Andric bool hasModelPath = analyzerOpts.Config.count("model-path") > 0;
7640b57cec5SDimitry Andric
765a7dea167SDimitry Andric return std::make_unique<AnalysisConsumer>(
7660b57cec5SDimitry Andric CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
7670b57cec5SDimitry Andric CI.getFrontendOpts().Plugins,
7680b57cec5SDimitry Andric hasModelPath ? new ModelInjector(CI) : nullptr);
7690b57cec5SDimitry Andric }
770