blob: 8236907ea773b799f1172599980b0569c1b236ba [file] [log] [blame]
Ted Kremenekf0413bf2008-07-02 00:03:09 +00001//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ted Kremenekf0413bf2008-07-02 00:03:09 +00006//
7//===----------------------------------------------------------------------===//
8//
9// "Meta" ASTConsumer for running different source analyses.
10//
11//===----------------------------------------------------------------------===//
12
Alexander Kornienko6de39492014-01-03 17:23:10 +000013#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000014#include "ModelInjector.h"
Artem Dergachevf0bb45f2019-09-11 20:54:27 +000015#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenekf0413bf2008-07-02 00:03:09 +000016#include "clang/AST/Decl.h"
Zhongxing Xu686b8452009-12-16 05:29:59 +000017#include "clang/AST/DeclCXX.h"
Ted Kremenekf0413bf2008-07-02 00:03:09 +000018#include "clang/AST/DeclObjC.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000019#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/Analyses/LiveVariables.h"
Daniel Dunbarb5f20252009-11-05 02:41:58 +000021#include "clang/Analysis/CFG.h"
Anna Zakseee91102012-03-08 23:16:38 +000022#include "clang/Analysis/CallGraph.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000023#include "clang/Analysis/CodeInjector.h"
Daniel Dunbarb5f20252009-11-05 02:41:58 +000024#include "clang/Basic/SourceManager.h"
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +000025#include "clang/CrossTU/CrossTranslationUnit.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbarb5f20252009-11-05 02:41:58 +000027#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
29#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
30#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/StaticAnalyzer/Core/CheckerManager.h"
32#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
35#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000036#include "llvm/ADT/PostOrderIterator.h"
Anna Zaksb0286542012-02-27 21:33:16 +000037#include "llvm/ADT/Statistic.h"
Rafael Espindola4168ee72013-06-26 06:13:06 +000038#include "llvm/Support/FileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/Path.h"
40#include "llvm/Support/Program.h"
41#include "llvm/Support/Timer.h"
42#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000043#include <memory>
Anna Zaksca70ed52012-03-13 19:32:13 +000044#include <queue>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000045#include <utility>
Anna Zaksca70ed52012-03-13 19:32:13 +000046
Ted Kremenekf0413bf2008-07-02 00:03:09 +000047using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000048using namespace ento;
Ted Kremenekf0413bf2008-07-02 00:03:09 +000049
Chandler Carruth10346662014-04-22 03:17:02 +000050#define DEBUG_TYPE "AnalysisConsumer"
51
Anna Zaks394d07e2012-03-09 21:14:01 +000052STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
Anna Zaks5d484782012-12-07 21:51:47 +000053STATISTIC(NumFunctionsAnalyzed,
Anna Zaksad3704c2012-12-17 20:08:54 +000054 "The # of functions and blocks analyzed (as top level "
55 "with inlining turned on).");
Anna Zakscc24e452012-04-03 02:05:47 +000056STATISTIC(NumBlocksInAnalyzedFunctions,
Anna Zaksad3704c2012-12-17 20:08:54 +000057 "The # of basic blocks in the analyzed functions.");
George Karpenkov2a639852018-02-09 23:37:47 +000058STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
59 "The # of visited basic blocks in the analyzed functions.");
Anna Zakscc24e452012-04-03 02:05:47 +000060STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
Anna Zaks40b87fc2012-07-05 20:44:02 +000061STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
Anna Zakseee91102012-03-08 23:16:38 +000062
Ted Kremenekb5351812009-02-17 04:27:41 +000063//===----------------------------------------------------------------------===//
David Blaikie0cc49432011-09-27 01:43:33 +000064// Special PathDiagnosticConsumers.
Ted Kremenek04ade6f2009-07-27 22:13:39 +000065//===----------------------------------------------------------------------===//
66
Balazs Keri32f220c2019-07-23 07:04:20 +000067void ento::createPlistHTMLDiagnosticConsumer(
68 AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
69 const std::string &prefix, const Preprocessor &PP,
70 const cross_tu::CrossTranslationUnitContext &CTU) {
Ted Kremenek3a081a02012-12-19 01:35:35 +000071 createHTMLDiagnosticConsumer(AnalyzerOpts, C,
Balazs Keri32f220c2019-07-23 07:04:20 +000072 llvm::sys::path::parent_path(prefix), PP, CTU);
73 createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP, CTU);
Ted Kremenek04ade6f2009-07-27 22:13:39 +000074}
75
Balazs Keri32f220c2019-07-23 07:04:20 +000076void ento::createTextPathDiagnosticConsumer(
77 AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
78 const std::string &Prefix, const clang::Preprocessor &PP,
79 const cross_tu::CrossTranslationUnitContext &CTU) {
Jordan Rose367843a2013-08-16 01:06:30 +000080 llvm_unreachable("'text' consumer should be enabled on ClangDiags");
81}
82
Ted Kremenek9bf9af92012-08-16 17:45:23 +000083namespace {
84class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
85 DiagnosticsEngine &Diag;
Artem Dergachev6cee4342019-09-06 20:55:29 +000086 bool IncludePath = false, ShouldEmitAsError = false, FixitsAsRemarks = false;
Keno Fischer6f48c072019-06-07 23:34:00 +000087
Ted Kremenek9bf9af92012-08-16 17:45:23 +000088public:
Jordan Rose367843a2013-08-16 01:06:30 +000089 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
Artem Dergachev6cee4342019-09-06 20:55:29 +000090 : Diag(Diag) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000091 ~ClangDiagPathDiagConsumer() override {}
Craig Topperfb6b25b2014-03-15 04:29:04 +000092 StringRef getName() const override { return "ClangDiags"; }
Jordan Rose367843a2013-08-16 01:06:30 +000093
Craig Topperfb6b25b2014-03-15 04:29:04 +000094 bool supportsLogicalOpControlFlow() const override { return true; }
95 bool supportsCrossFileDiagnostics() const override { return true; }
Jordan Rose367843a2013-08-16 01:06:30 +000096
Craig Topperfb6b25b2014-03-15 04:29:04 +000097 PathGenerationScheme getGenerationScheme() const override {
Jordan Rose367843a2013-08-16 01:06:30 +000098 return IncludePath ? Minimal : None;
99 }
100
Artem Dergachev6cee4342019-09-06 20:55:29 +0000101 void enablePaths() { IncludePath = true; }
Keno Fischer6f48c072019-06-07 23:34:00 +0000102 void enableWerror() { ShouldEmitAsError = true; }
Artem Dergachev6cee4342019-09-06 20:55:29 +0000103 void enableFixitsAsRemarks() { FixitsAsRemarks = true; }
Keno Fischer6f48c072019-06-07 23:34:00 +0000104
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000105 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000106 FilesMade *filesMade) override {
Keno Fischer6f48c072019-06-07 23:34:00 +0000107 unsigned WarnID =
108 ShouldEmitAsError
109 ? Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0")
110 : Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
Alp Toker5c494cb2013-12-23 17:59:59 +0000111 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
Artem Dergachev6cee4342019-09-06 20:55:29 +0000112 unsigned RemarkID = Diag.getCustomDiagID(DiagnosticsEngine::Remark, "%0");
Alp Toker5c494cb2013-12-23 17:59:59 +0000113
Artem Dergachev6cee4342019-09-06 20:55:29 +0000114 auto reportPiece =
115 [&](unsigned ID, SourceLocation Loc, StringRef String,
116 ArrayRef<SourceRange> Ranges, ArrayRef<FixItHint> Fixits) {
117 if (!FixitsAsRemarks) {
118 Diag.Report(Loc, ID) << String << Ranges << Fixits;
119 } else {
120 Diag.Report(Loc, ID) << String << Ranges;
121 for (const FixItHint &Hint : Fixits) {
122 SourceManager &SM = Diag.getSourceManager();
123 llvm::SmallString<128> Str;
124 llvm::raw_svector_ostream OS(Str);
125 // FIXME: Add support for InsertFromRange and
126 // BeforePreviousInsertion.
127 assert(!Hint.InsertFromRange.isValid() && "Not implemented yet!");
128 assert(!Hint.BeforePreviousInsertions && "Not implemented yet!");
129 OS << SM.getSpellingColumnNumber(Hint.RemoveRange.getBegin())
130 << "-" << SM.getSpellingColumnNumber(Hint.RemoveRange.getEnd())
131 << ": '" << Hint.CodeToInsert << "'";
132 Diag.Report(Loc, RemarkID) << OS.str();
133 }
134 }
135 };
136
137 for (std::vector<const PathDiagnostic *>::iterator I = Diags.begin(),
138 E = Diags.end();
139 I != E; ++I) {
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000140 const PathDiagnostic *PD = *I;
Artem Dergachev6cee4342019-09-06 20:55:29 +0000141 reportPiece(WarnID, PD->getLocation().asLocation(),
142 PD->getShortDescription(), PD->path.back()->getRanges(),
143 PD->path.back()->getFixits());
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000144
Artem Dergachevb1991c52016-10-07 19:25:10 +0000145 // First, add extra notes, even if paths should not be included.
146 for (const auto &Piece : PD->path) {
147 if (!isa<PathDiagnosticNotePiece>(Piece.get()))
148 continue;
149
Artem Dergachev6cee4342019-09-06 20:55:29 +0000150 reportPiece(NoteID, Piece->getLocation().asLocation(),
151 Piece->getString(), Piece->getRanges(), Piece->getFixits());
Artem Dergachevb1991c52016-10-07 19:25:10 +0000152 }
153
Jordan Rose367843a2013-08-16 01:06:30 +0000154 if (!IncludePath)
155 continue;
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000156
Artem Dergachevb1991c52016-10-07 19:25:10 +0000157 // Then, add the path notes if necessary.
Jordan Rose367843a2013-08-16 01:06:30 +0000158 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
Artem Dergachevb1991c52016-10-07 19:25:10 +0000159 for (const auto &Piece : FlatPath) {
160 if (isa<PathDiagnosticNotePiece>(Piece.get()))
161 continue;
162
Artem Dergachev6cee4342019-09-06 20:55:29 +0000163 reportPiece(NoteID, Piece->getLocation().asLocation(),
164 Piece->getString(), Piece->getRanges(), Piece->getFixits());
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000165 }
166 }
167 }
168};
169} // end anonymous namespace
170
Ted Kremenek04ade6f2009-07-27 22:13:39 +0000171//===----------------------------------------------------------------------===//
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000172// AnalysisConsumer declaration.
173//===----------------------------------------------------------------------===//
174
175namespace {
176
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000177class AnalysisConsumer : public AnalysisASTConsumer,
Richard Smith50668452015-11-24 03:55:01 +0000178 public RecursiveASTVisitor<AnalysisConsumer> {
Jordan Rosed8665b32012-10-10 17:55:40 +0000179 enum {
180 AM_None = 0,
181 AM_Syntax = 0x1,
182 AM_Path = 0x2
Anna Zaks14189512012-03-13 19:32:00 +0000183 };
Jordan Rosed8665b32012-10-10 17:55:40 +0000184 typedef unsigned AnalysisMode;
Anna Zaks14189512012-03-13 19:32:00 +0000185
186 /// Mode of the analyzes while recursively visiting Decls.
187 AnalysisMode RecVisitorMode;
188 /// Bug Reporter to use while recursively visiting Decls.
189 BugReporter *RecVisitorBR;
190
Alexander Kornienkod00ed8e2018-06-27 14:56:12 +0000191 std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
192
Zhongxing Xu685a1d82010-04-30 04:14:20 +0000193public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000194 ASTContext *Ctx;
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000195 const Preprocessor &PP;
196 const std::string OutDir;
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000197 AnalyzerOptionsRef Opts;
Jordy Rose59cce712011-08-16 21:24:21 +0000198 ArrayRef<std::string> Plugins;
Ted Kremenekeeccb302014-08-27 15:14:15 +0000199 CodeInjector *Injector;
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000200 cross_tu::CrossTranslationUnitContext CTU;
Zhongxing Xub9a45a42009-08-03 03:27:37 +0000201
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000202 /// Stores the declarations from the local translation unit.
Anna Zaks8e078522012-04-12 22:36:48 +0000203 /// Note, we pre-compute the local declarations at parse time as an
204 /// optimization to make sure we do not deserialize everything from disk.
205 /// The local declaration to all declarations ratio might be very small when
206 /// working with a PCH file.
207 SetOfDecls LocalTUDecls;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000208
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000209 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
210 PathDiagnosticConsumers PathConsumers;
Zhongxing Xub9a45a42009-08-03 03:27:37 +0000211
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000212 StoreManagerCreator CreateStoreMgr;
213 ConstraintManagerCreator CreateConstraintMgr;
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000214
Ahmed Charlesb8984322014-03-07 20:03:18 +0000215 std::unique_ptr<CheckerManager> checkerMgr;
216 std::unique_ptr<AnalysisManager> Mgr;
Zhongxing Xubcbe44f2009-08-03 03:13:46 +0000217
Anna Zaks9bd4be92012-03-05 20:53:59 +0000218 /// Time the analyzes time of each translation unit.
George Karpenkov5a755b32018-02-10 01:49:20 +0000219 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000220 std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
221 std::unique_ptr<llvm::Timer> ExprEngineTimer;
222 std::unique_ptr<llvm::Timer> BugReporterTimer;
Anna Zaks9bd4be92012-03-05 20:53:59 +0000223
Anna Zaks54fd4a02012-03-30 05:48:10 +0000224 /// The information about analyzed functions shared throughout the
225 /// translation unit.
226 FunctionSummariesTy FunctionSummaries;
227
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000228 AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000229 AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
Ted Kremenekeeccb302014-08-27 15:14:15 +0000230 CodeInjector *injector)
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000231 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
232 PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
233 Plugins(plugins), Injector(injector), CTU(CI) {
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000234 DigestAnalyzerOptions();
Kristof Umann549f9cd2018-11-30 20:44:00 +0000235 if (Opts->PrintStats || Opts->ShouldSerializeStats) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000236 AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
George Karpenkov5a755b32018-02-10 01:49:20 +0000237 "analyzer", "Analyzer timers");
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000238 SyntaxCheckTimer = std::make_unique<llvm::Timer>(
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000239 "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers);
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000240 ExprEngineTimer = std::make_unique<llvm::Timer>(
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000241 "exprengine", "Path exploration time", *AnalyzerTimers);
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000242 BugReporterTimer = std::make_unique<llvm::Timer>(
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000243 "bugreporter", "Path-sensitive report post-processing time",
244 *AnalyzerTimers);
George Karpenkov5a755b32018-02-10 01:49:20 +0000245 llvm::EnableStatistics(/* PrintOnExit= */ false);
Anna Zaks9bd4be92012-03-05 20:53:59 +0000246 }
247 }
248
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000249 ~AnalysisConsumer() override {
Matthias Braunabb6eea2016-09-26 18:53:34 +0000250 if (Opts->PrintStats) {
Matthias Braunabb6eea2016-09-26 18:53:34 +0000251 llvm::PrintStatistics();
252 }
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000253 }
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000254
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000255 void DigestAnalyzerOptions() {
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000256 if (Opts->AnalysisDiagOpt != PD_NONE) {
257 // Create the PathDiagnosticConsumer.
258 ClangDiagPathDiagConsumer *clangDiags =
259 new ClangDiagPathDiagConsumer(PP.getDiagnostics());
260 PathConsumers.push_back(clangDiags);
Ted Kremenek9bf9af92012-08-16 17:45:23 +0000261
Keno Fischer6f48c072019-06-07 23:34:00 +0000262 if (Opts->AnalyzerWerror)
263 clangDiags->enableWerror();
264
Artem Dergachev6cee4342019-09-06 20:55:29 +0000265 if (Opts->ShouldEmitFixItHintsAsRemarks)
266 clangDiags->enableFixitsAsRemarks();
267
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000268 if (Opts->AnalysisDiagOpt == PD_TEXT) {
269 clangDiags->enablePaths();
Jordan Rose367843a2013-08-16 01:06:30 +0000270
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000271 } else if (!OutDir.empty()) {
272 switch (Opts->AnalysisDiagOpt) {
273 default:
274#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
275 case PD_##NAME: \
Balazs Keri32f220c2019-07-23 07:04:20 +0000276 CREATEFN(*Opts.get(), PathConsumers, OutDir, PP, CTU); \
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000277 break;
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000278#include "clang/StaticAnalyzer/Core/Analyses.def"
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000279 }
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000280 }
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000281 }
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000282
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000283 // Create the analyzer component creators.
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000284 switch (Opts->AnalysisStoreOpt) {
Argyrios Kyrtzidis4ec3cf92011-02-14 18:13:17 +0000285 default:
David Blaikie83d382b2011-09-23 05:06:16 +0000286 llvm_unreachable("Unknown store manager.");
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000287#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
Argyrios Kyrtzidis4ec3cf92011-02-14 18:13:17 +0000288 case NAME##Model: CreateStoreMgr = CREATEFN; break;
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000289#include "clang/StaticAnalyzer/Core/Analyses.def"
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000290 }
Mike Stump11289f42009-09-09 15:08:12 +0000291
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000292 switch (Opts->AnalysisConstraintsOpt) {
Argyrios Kyrtzidis4ec3cf92011-02-14 18:13:17 +0000293 default:
Anna Zaks297176c2013-02-07 23:29:20 +0000294 llvm_unreachable("Unknown constraint manager.");
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000295#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
Argyrios Kyrtzidis4ec3cf92011-02-14 18:13:17 +0000296 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000297#include "clang/StaticAnalyzer/Core/Analyses.def"
Zhongxing Xu4b03d492009-07-30 09:11:52 +0000298 }
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000299 }
Ted Kremenek39df94b2010-02-14 19:08:51 +0000300
Anna Zakse9eb13a2013-02-02 00:30:02 +0000301 void DisplayFunction(const Decl *D, AnalysisMode Mode,
302 ExprEngine::InliningModes IMode) {
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000303 if (!Opts->AnalyzerDisplayProgress)
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000304 return;
Ted Kremenek39df94b2010-02-14 19:08:51 +0000305
Ted Kremenek68189912009-12-07 22:06:12 +0000306 SourceManager &SM = Mgr->getASTContext().getSourceManager();
307 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000308 if (Loc.isValid()) {
Anna Zaks14189512012-03-13 19:32:00 +0000309 llvm::errs() << "ANALYZE";
Jordan Rosed8665b32012-10-10 17:55:40 +0000310
311 if (Mode == AM_Syntax)
312 llvm::errs() << " (Syntax)";
Anna Zakse9eb13a2013-02-02 00:30:02 +0000313 else if (Mode == AM_Path) {
314 llvm::errs() << " (Path, ";
315 switch (IMode) {
Anna Zaksb13d21b2013-03-26 18:57:58 +0000316 case ExprEngine::Inline_Minimal:
317 llvm::errs() << " Inline_Minimal";
Anna Zakse9eb13a2013-02-02 00:30:02 +0000318 break;
Anna Zaksb13d21b2013-03-26 18:57:58 +0000319 case ExprEngine::Inline_Regular:
320 llvm::errs() << " Inline_Regular";
Anna Zakse9eb13a2013-02-02 00:30:02 +0000321 break;
322 }
323 llvm::errs() << ")";
324 }
Jordan Rosed8665b32012-10-10 17:55:40 +0000325 else
326 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
327
Artem Dergachev6a76a162016-08-08 16:01:02 +0000328 llvm::errs() << ": " << Loc.getFilename() << ' '
329 << getFunctionName(D) << '\n';
Ted Kremenek7043fba2010-10-22 22:08:29 +0000330 }
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000331 }
Mike Stump11289f42009-09-09 15:08:12 +0000332
Craig Topperfb6b25b2014-03-15 04:29:04 +0000333 void Initialize(ASTContext &Context) override {
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000334 Ctx = &Context;
George Karpenkov4ece68a2018-08-06 23:09:07 +0000335 checkerMgr = createCheckerManager(
336 *Ctx, *Opts, Plugins, CheckerRegistrationFns, PP.getDiagnostics());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000337
Dmitri Gribenko6b9d7c92019-08-21 08:48:24 +0000338 Mgr = std::make_unique<AnalysisManager>(*Ctx, PathConsumers, CreateStoreMgr,
339 CreateConstraintMgr,
340 checkerMgr.get(), *Opts, Injector);
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000341 }
Mike Stump11289f42009-09-09 15:08:12 +0000342
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000343 /// Store the top level decls in the set to be processed later on.
Anna Zaks8e078522012-04-12 22:36:48 +0000344 /// (Doing this pre-processing avoids deserialization of data from PCH.)
Craig Topperfb6b25b2014-03-15 04:29:04 +0000345 bool HandleTopLevelDecl(DeclGroupRef D) override;
346 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
Anna Zaks8e078522012-04-12 22:36:48 +0000347
Craig Topperfb6b25b2014-03-15 04:29:04 +0000348 void HandleTranslationUnit(ASTContext &C) override;
Ted Kremeneka1ec4f32011-01-20 17:09:48 +0000349
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000350 /// Determine which inlining mode should be used when this function is
Anna Zaksb13d21b2013-03-26 18:57:58 +0000351 /// analyzed. This allows to redefine the default inlining policies when
352 /// analyzing a given function.
Anna Zaks5d484782012-12-07 21:51:47 +0000353 ExprEngine::InliningModes
Anna Zaksd5478fd2014-08-29 20:01:38 +0000354 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
Anna Zaks5d484782012-12-07 21:51:47 +0000355
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000356 /// Build the call graph for all the top level decls of this TU and
Anna Zaks8e078522012-04-12 22:36:48 +0000357 /// use it to define the order in which the functions should be visited.
Jordan Rose85c8c812012-10-10 17:55:37 +0000358 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
Anna Zaks14189512012-03-13 19:32:00 +0000359
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000360 /// Run analyzes(syntax or path sensitive) on the given function.
Anna Zaks14189512012-03-13 19:32:00 +0000361 /// \param Mode - determines if we are requesting syntax only or path
362 /// sensitive only analysis.
363 /// \param VisitedCallees - The output parameter, which is populated with the
364 /// set of functions which should be considered analyzed after analyzing the
365 /// given root function.
Anna Zaks8e078522012-04-12 22:36:48 +0000366 void HandleCode(Decl *D, AnalysisMode Mode,
Anna Zaksb13d21b2013-03-26 18:57:58 +0000367 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
Craig Topper0dbb7832014-05-27 02:45:47 +0000368 SetOfConstDecls *VisitedCallees = nullptr);
Anna Zaks14189512012-03-13 19:32:00 +0000369
Anna Zaks5d484782012-12-07 21:51:47 +0000370 void RunPathSensitiveChecks(Decl *D,
371 ExprEngine::InliningModes IMode,
372 SetOfConstDecls *VisitedCallees);
Anna Zaks14189512012-03-13 19:32:00 +0000373
374 /// Visitors for the RecursiveASTVisitor.
Anna Zakse7e7c9e2012-05-11 23:15:18 +0000375 bool shouldWalkTypesOfTypeLocs() const { return false; }
Anna Zaks14189512012-03-13 19:32:00 +0000376
377 /// Handle callbacks for arbitrary Decls.
378 bool VisitDecl(Decl *D) {
Jordan Rosed8665b32012-10-10 17:55:40 +0000379 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000380 if (Mode & AM_Syntax) {
381 if (SyntaxCheckTimer)
382 SyntaxCheckTimer->startTimer();
Jordan Rosed8665b32012-10-10 17:55:40 +0000383 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000384 if (SyntaxCheckTimer)
385 SyntaxCheckTimer->stopTimer();
386 }
Anna Zaks14189512012-03-13 19:32:00 +0000387 return true;
388 }
389
Rafael Stahl850361f2019-04-23 11:04:41 +0000390 bool VisitVarDecl(VarDecl *VD) {
391 if (!Opts->IsNaiveCTUEnabled)
392 return true;
393
394 if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
395 if (!cross_tu::containsConst(VD, *Ctx))
396 return true;
397 } else {
398 // Cannot be initialized in another TU.
399 return true;
400 }
401
402 if (VD->getAnyInitializer())
403 return true;
404
405 llvm::Expected<const VarDecl *> CTUDeclOrError =
Keno Fischer6f48c072019-06-07 23:34:00 +0000406 CTU.getCrossTUDefinition(VD, Opts->CTUDir, Opts->CTUIndexName,
Rafael Stahl850361f2019-04-23 11:04:41 +0000407 Opts->DisplayCTUProgress);
408
409 if (!CTUDeclOrError) {
410 handleAllErrors(CTUDeclOrError.takeError(),
411 [&](const cross_tu::IndexError &IE) {
412 CTU.emitCrossTUDiagnostics(IE);
413 });
414 }
415
416 return true;
417 }
418
Anna Zaks14189512012-03-13 19:32:00 +0000419 bool VisitFunctionDecl(FunctionDecl *FD) {
420 IdentifierInfo *II = FD->getIdentifier();
421 if (II && II->getName().startswith("__inline"))
422 return true;
423
424 // We skip function template definitions, as their semantics is
425 // only determined when they are instantiated.
426 if (FD->isThisDeclarationADefinition() &&
427 !FD->isDependentContext()) {
Anna Zaks5d484782012-12-07 21:51:47 +0000428 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Anna Zaks14189512012-03-13 19:32:00 +0000429 HandleCode(FD, RecVisitorMode);
430 }
431 return true;
432 }
433
434 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
Anna Zaks5d484782012-12-07 21:51:47 +0000435 if (MD->isThisDeclarationADefinition()) {
436 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Anna Zaks14189512012-03-13 19:32:00 +0000437 HandleCode(MD, RecVisitorMode);
Anna Zaks5d484782012-12-07 21:51:47 +0000438 }
Anna Zaks14189512012-03-13 19:32:00 +0000439 return true;
440 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000441
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000442 bool VisitBlockDecl(BlockDecl *BD) {
443 if (BD->hasBody()) {
444 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
Devin Coughlin6e644ab2015-11-18 22:46:52 +0000445 // Since we skip function template definitions, we should skip blocks
446 // declared in those functions as well.
447 if (!BD->isDependentContext()) {
448 HandleCode(BD, RecVisitorMode);
449 }
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000450 }
451 return true;
452 }
Anna Zaks8e078522012-04-12 22:36:48 +0000453
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000454 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
Alexander Kornienko7a712ce2014-02-03 18:37:50 +0000455 PathConsumers.push_back(Consumer);
456 }
457
Alexander Kornienkod00ed8e2018-06-27 14:56:12 +0000458 void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
459 CheckerRegistrationFns.push_back(std::move(Fn));
460 }
461
Anna Zaks8e078522012-04-12 22:36:48 +0000462private:
463 void storeTopLevelDecls(DeclGroupRef DG);
Artem Dergachev6a76a162016-08-08 16:01:02 +0000464 std::string getFunctionName(const Decl *D);
Anna Zaks8e078522012-04-12 22:36:48 +0000465
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000466 /// Check if we should skip (not analyze) the given function.
Jordan Rosed8665b32012-10-10 17:55:40 +0000467 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000468 void runAnalysisOnTranslationUnit(ASTContext &C);
Anna Zaks8e078522012-04-12 22:36:48 +0000469
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000470 /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
471 void reportAnalyzerProgress(StringRef S);
Ted Kremenek55d59bf2009-11-11 06:28:42 +0000472};
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000473} // end anonymous namespace
474
Anna Zaks14189512012-03-13 19:32:00 +0000475
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000476//===----------------------------------------------------------------------===//
477// AnalysisConsumer implementation.
478//===----------------------------------------------------------------------===//
Anna Zaks8e078522012-04-12 22:36:48 +0000479bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
480 storeTopLevelDecls(DG);
481 return true;
482}
483
484void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
485 storeTopLevelDecls(DG);
486}
487
488void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
489 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
490
491 // Skip ObjCMethodDecl, wait for the objc container to avoid
492 // analyzing twice.
493 if (isa<ObjCMethodDecl>(*I))
494 continue;
495
Ted Kremenek2964aac2012-04-27 04:54:28 +0000496 LocalTUDecls.push_back(*I);
Anna Zaks8e078522012-04-12 22:36:48 +0000497 }
498}
499
Anna Zaks5f2af812012-12-14 19:08:17 +0000500static bool shouldSkipFunction(const Decl *D,
Alexander Kornienkofe659982014-04-23 16:39:41 +0000501 const SetOfConstDecls &Visited,
502 const SetOfConstDecls &VisitedAsTopLevel) {
Anna Zaks5f2af812012-12-14 19:08:17 +0000503 if (VisitedAsTopLevel.count(D))
Anna Zaks5d484782012-12-07 21:51:47 +0000504 return true;
505
506 // We want to re-analyse the functions as top level in the following cases:
Anna Zaksa8017ec2012-08-30 23:42:02 +0000507 // - The 'init' methods should be reanalyzed because
508 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
Anna Zaks5d484782012-12-07 21:51:47 +0000509 // 'nil' and unless we analyze the 'init' functions as top level, we will
510 // not catch errors within defensive code.
Anna Zaksa8017ec2012-08-30 23:42:02 +0000511 // - We want to reanalyze all ObjC methods as top level to report Retain
512 // Count naming convention errors more aggressively.
Anna Zaks5f2af812012-12-14 19:08:17 +0000513 if (isa<ObjCMethodDecl>(D))
Anna Zaksa8017ec2012-08-30 23:42:02 +0000514 return false;
Devin Coughlinf57f90d2016-07-21 23:42:31 +0000515 // We also want to reanalyze all C++ copy and move assignment operators to
516 // separately check the two cases where 'this' aliases with the parameter and
517 // where it may not. (cplusplus.SelfAssignmentChecker)
518 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
519 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
520 return false;
521 }
Anna Zaksa8017ec2012-08-30 23:42:02 +0000522
523 // Otherwise, if we visited the function before, do not reanalyze it.
Anna Zaks5f2af812012-12-14 19:08:17 +0000524 return Visited.count(D);
Anna Zaksa8017ec2012-08-30 23:42:02 +0000525}
526
Anna Zaks5d484782012-12-07 21:51:47 +0000527ExprEngine::InliningModes
Anna Zaks5f2af812012-12-14 19:08:17 +0000528AnalysisConsumer::getInliningModeForFunction(const Decl *D,
Alexander Kornienkofe659982014-04-23 16:39:41 +0000529 const SetOfConstDecls &Visited) {
Anna Zaks5d484782012-12-07 21:51:47 +0000530 // We want to reanalyze all ObjC methods as top level to report Retain
Anna Zaksb13d21b2013-03-26 18:57:58 +0000531 // Count naming convention errors more aggressively. But we should tune down
Anna Zaks5d484782012-12-07 21:51:47 +0000532 // inlining when reanalyzing an already inlined function.
Devin Coughlinf57f90d2016-07-21 23:42:31 +0000533 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
Anna Zaks5f2af812012-12-14 19:08:17 +0000534 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
Anna Zaks5d484782012-12-07 21:51:47 +0000535 if (ObjCM->getMethodFamily() != OMF_init)
Anna Zaksb13d21b2013-03-26 18:57:58 +0000536 return ExprEngine::Inline_Minimal;
Anna Zaks5d484782012-12-07 21:51:47 +0000537 }
538
Anna Zaksb13d21b2013-03-26 18:57:58 +0000539 return ExprEngine::Inline_Regular;
Anna Zaks5d484782012-12-07 21:51:47 +0000540}
541
Jordan Rose85c8c812012-10-10 17:55:37 +0000542void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
Anna Zaks1ee76c12012-12-21 17:27:01 +0000543 // Build the Call Graph by adding all the top level declarations to the graph.
Anna Zaks2774f992012-05-31 18:07:55 +0000544 // Note: CallGraph can trigger deserialization of more items from a pch
545 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
546 // We rely on random access to add the initially processed Decls to CG.
Anna Zaks1ee76c12012-12-21 17:27:01 +0000547 CallGraph CG;
Anna Zaks2774f992012-05-31 18:07:55 +0000548 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
Anna Zaks34d89b72012-05-30 23:14:48 +0000549 CG.addToCallGraph(LocalTUDecls[i]);
550 }
Anna Zakseee91102012-03-08 23:16:38 +0000551
Anna Zaks1ee76c12012-12-21 17:27:01 +0000552 // Walk over all of the call graph nodes in topological order, so that we
553 // analyze parents before the children. Skip the functions inlined into
554 // the previously processed functions. Use external Visited set to identify
555 // inlined functions. The topological order allows the "do not reanalyze
556 // previously inlined function" performance heuristic to be triggered more
557 // often.
Anna Zaks5f2af812012-12-14 19:08:17 +0000558 SetOfConstDecls Visited;
559 SetOfConstDecls VisitedAsTopLevel;
Anna Zaks1ee76c12012-12-21 17:27:01 +0000560 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
561 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
562 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
563 NumFunctionTopLevel++;
Anna Zaksca70ed52012-03-13 19:32:13 +0000564
Anna Zaks1ee76c12012-12-21 17:27:01 +0000565 CallGraphNode *N = *I;
Anna Zaks5f2af812012-12-14 19:08:17 +0000566 Decl *D = N->getDecl();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000567
Anna Zaks1ee76c12012-12-21 17:27:01 +0000568 // Skip the abstract root node.
569 if (!D)
570 continue;
Anna Zaks5f2af812012-12-14 19:08:17 +0000571
Anna Zaksca70ed52012-03-13 19:32:13 +0000572 // Skip the functions which have been processed already or previously
573 // inlined.
Anna Zaks5f2af812012-12-14 19:08:17 +0000574 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
Anna Zaksca70ed52012-03-13 19:32:13 +0000575 continue;
576
577 // Analyze the function.
Anna Zaks8e078522012-04-12 22:36:48 +0000578 SetOfConstDecls VisitedCallees;
Anna Zaks5d484782012-12-07 21:51:47 +0000579
Anna Zaks5f2af812012-12-14 19:08:17 +0000580 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
Craig Topper0dbb7832014-05-27 02:45:47 +0000581 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
Anna Zaksca70ed52012-03-13 19:32:13 +0000582
583 // Add the visited callees to the global visited set.
Yury Gribov054873b2016-01-11 09:38:48 +0000584 for (const Decl *Callee : VisitedCallees)
585 // Decls from CallGraph are already canonical. But Decls coming from
586 // CallExprs may be not. We should canonicalize them manually.
587 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
588 : Callee->getCanonicalDecl());
Anna Zaks5f2af812012-12-14 19:08:17 +0000589 VisitedAsTopLevel.insert(D);
Anna Zakseee91102012-03-08 23:16:38 +0000590 }
Ted Kremenek60120fb2011-08-27 21:28:09 +0000591}
592
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000593static bool isBisonFile(ASTContext &C) {
594 const SourceManager &SM = C.getSourceManager();
595 FileID FID = SM.getMainFileID();
596 StringRef Buffer = SM.getBuffer(FID)->getBuffer();
597 if (Buffer.startswith("/* A Bison parser, made by"))
598 return true;
599 return false;
600}
601
602void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
603 BugReporter BR(*Mgr);
604 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000605 if (SyntaxCheckTimer)
606 SyntaxCheckTimer->startTimer();
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000607 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000608 if (SyntaxCheckTimer)
609 SyntaxCheckTimer->stopTimer();
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000610
611 // Run the AST-only checks using the order in which functions are defined.
612 // If inlining is not turned on, use the simplest function order for path
613 // sensitive analyzes as well.
614 RecVisitorMode = AM_Syntax;
615 if (!Mgr->shouldInlineCall())
616 RecVisitorMode |= AM_Path;
617 RecVisitorBR = &BR;
618
619 // Process all the top level declarations.
620 //
621 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
622 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
623 // random access. By doing so, we automatically compensate for iterators
624 // possibly being invalidated, although this is a bit slower.
625 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
626 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
627 TraverseDecl(LocalTUDecls[i]);
628 }
629
630 if (Mgr->shouldInlineCall())
631 HandleDeclsCallGraph(LocalTUDeclsSize);
632
633 // After all decls handled, run checkers on the entire TranslationUnit.
634 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
635
Artem Dergachev3fdc4272019-08-20 21:41:20 +0000636 BR.FlushReports();
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000637 RecVisitorBR = nullptr;
638}
639
640void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
641 if (Opts->AnalyzerDisplayProgress)
642 llvm::errs() << S;
643}
644
Ted Kremeneka1ec4f32011-01-20 17:09:48 +0000645void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000646
Anna Zaks14189512012-03-13 19:32:00 +0000647 // Don't run the actions if an error has occurred with parsing the file.
648 DiagnosticsEngine &Diags = PP.getDiagnostics();
649 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
650 return;
651
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000652 if (isBisonFile(C)) {
653 reportAnalyzerProgress("Skipping bison-generated file\n");
Kristof Umann72649422019-09-12 19:09:24 +0000654 } else if (Opts->DisableAllCheckers) {
Anna Zaks9bd4be92012-03-05 20:53:59 +0000655
George Karpenkov1d3e49e2018-02-26 22:14:16 +0000656 // Don't analyze if the user explicitly asked for no checks to be performed
657 // on this file.
658 reportAnalyzerProgress("All checks are disabled using a supplied option\n");
659 } else {
660 // Otherwise, just run the analysis.
661 runAnalysisOnTranslationUnit(C);
Anna Zaks17f57b02012-01-07 16:49:46 +0000662 }
Ted Kremeneke69ab052011-05-05 03:41:17 +0000663
Anna Zaks8382e452012-04-05 02:10:21 +0000664 // Count how many basic blocks we have not covered.
665 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
George Karpenkov2a639852018-02-09 23:37:47 +0000666 NumVisitedBlocksInAnalyzedFunctions =
667 FunctionSummaries.getTotalNumVisitedBasicBlocks();
Anna Zaks8382e452012-04-05 02:10:21 +0000668 if (NumBlocksInAnalyzedFunctions > 0)
669 PercentReachableBlocks =
670 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
671 NumBlocksInAnalyzedFunctions;
672
George Karpenkov5a755b32018-02-10 01:49:20 +0000673 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
674 // FIXME: This should be replaced with something that doesn't rely on
675 // side-effects in PathDiagnosticConsumer's destructor. This is required when
676 // used with option -disable-free.
677 Mgr.reset();
Ted Kremenek0e7d2522008-07-03 04:29:21 +0000678}
679
Artem Dergachev6a76a162016-08-08 16:01:02 +0000680std::string AnalysisConsumer::getFunctionName(const Decl *D) {
681 std::string Str;
682 llvm::raw_string_ostream OS(Str);
683
684 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
685 OS << FD->getQualifiedNameAsString();
686
687 // In C++, there are overloads.
688 if (Ctx->getLangOpts().CPlusPlus) {
689 OS << '(';
690 for (const auto &P : FD->parameters()) {
691 if (P != *FD->param_begin())
692 OS << ", ";
693 OS << P->getType().getAsString();
694 }
695 OS << ')';
696 }
697
698 } else if (isa<BlockDecl>(D)) {
699 PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
700
701 if (Loc.isValid()) {
702 OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
703 << ')';
704 }
705
706 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
707
708 // FIXME: copy-pasted from CGDebugInfo.cpp.
709 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
710 const DeclContext *DC = OMD->getDeclContext();
711 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
712 OS << OID->getName();
713 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
714 OS << OID->getName();
715 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
716 if (OC->IsClassExtension()) {
717 OS << OC->getClassInterface()->getName();
718 } else {
719 OS << OC->getIdentifier()->getNameStart() << '('
720 << OC->getIdentifier()->getNameStart() << ')';
721 }
722 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +0000723 OS << OCD->getClassInterface()->getName() << '('
724 << OCD->getName() << ')';
Artem Dergachev6a76a162016-08-08 16:01:02 +0000725 } else if (isa<ObjCProtocolDecl>(DC)) {
726 // We can extract the type of the class from the self pointer.
727 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
728 QualType ClassTy =
729 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
730 ClassTy.print(OS, PrintingPolicy(LangOptions()));
731 }
732 }
733 OS << ' ' << OMD->getSelector().getAsString() << ']';
734
Anna Zakseee91102012-03-08 23:16:38 +0000735 }
Artem Dergachev6a76a162016-08-08 16:01:02 +0000736
737 return OS.str();
Anna Zakseee91102012-03-08 23:16:38 +0000738}
739
Jordan Rosed8665b32012-10-10 17:55:40 +0000740AnalysisConsumer::AnalysisMode
741AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
Ted Kremenek40ea0ea2012-08-31 04:36:05 +0000742 if (!Opts->AnalyzeSpecificFunction.empty() &&
743 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
Jordan Rosed8665b32012-10-10 17:55:40 +0000744 return AM_None;
Mike Stump11289f42009-09-09 15:08:12 +0000745
Jordan Rosed8665b32012-10-10 17:55:40 +0000746 // Unless -analyze-all is specified, treat decls differently depending on
747 // where they came from:
748 // - Main source file: run both path-sensitive and non-path-sensitive checks.
749 // - Header files: run non-path-sensitive checks only.
750 // - System headers: don't run any checks.
Ted Kremenek4c721bf2010-06-15 00:55:40 +0000751 SourceManager &SM = Ctx->getSourceManager();
Aaron Ballman65693872015-08-20 21:27:35 +0000752 const Stmt *Body = D->getBody();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000753 SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
Anna Zaks3849dea2015-06-26 17:42:58 +0000754 SL = SM.getExpansionLoc(SL);
755
Artem Dergachev516837f2018-04-25 21:51:26 +0000756 if (!Opts->AnalyzeAll && !Mgr->isInCodeFile(SL)) {
Jordan Rosed8665b32012-10-10 17:55:40 +0000757 if (SL.isInvalid() || SM.isInSystemHeader(SL))
758 return AM_None;
759 return Mode & ~AM_Path;
760 }
Anna Zaksaa19abe2012-03-13 19:31:54 +0000761
Jordan Rosed8665b32012-10-10 17:55:40 +0000762 return Mode;
Anna Zaksaa19abe2012-03-13 19:31:54 +0000763}
764
Anna Zaks14189512012-03-13 19:32:00 +0000765void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
Anna Zaks5d484782012-12-07 21:51:47 +0000766 ExprEngine::InliningModes IMode,
Anna Zaks8e078522012-04-12 22:36:48 +0000767 SetOfConstDecls *VisitedCallees) {
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000768 if (!D->hasBody())
769 return;
Jordan Rosed8665b32012-10-10 17:55:40 +0000770 Mode = getModeForDecl(D, Mode);
771 if (Mode == AM_None)
Mike Stump11289f42009-09-09 15:08:12 +0000772 return;
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000773
Alexander Shaposhnikova1fead22016-09-23 20:49:01 +0000774 // Clear the AnalysisManager of old AnalysisDeclContexts.
775 Mgr->ClearContexts();
776 // Ignore autosynthesized code.
777 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
778 return;
779
Anna Zakse9eb13a2013-02-02 00:30:02 +0000780 DisplayFunction(D, Mode, IMode);
Anna Zaks40b87fc2012-07-05 20:44:02 +0000781 CFG *DeclCFG = Mgr->getCFG(D);
Craig Topper704b4fb2017-05-18 01:11:52 +0000782 if (DeclCFG)
783 MaxCFGSize.updateMax(DeclCFG->size());
Anna Zaks40b87fc2012-07-05 20:44:02 +0000784
Argyrios Kyrtzidis24ffc082011-02-17 21:39:24 +0000785 BugReporter BR(*Mgr);
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000786
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000787 if (Mode & AM_Syntax) {
788 if (SyntaxCheckTimer)
789 SyntaxCheckTimer->startTimer();
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000790 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000791 if (SyntaxCheckTimer)
792 SyntaxCheckTimer->stopTimer();
793 }
Artem Dergachev3fdc4272019-08-20 21:41:20 +0000794
795 BR.FlushReports();
796
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000797 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
798 RunPathSensitiveChecks(D, IMode, VisitedCallees);
Anna Zaksb13d21b2013-03-26 18:57:58 +0000799 if (IMode != ExprEngine::Inline_Minimal)
Anna Zaks5c32dfc2012-12-21 01:19:15 +0000800 NumFunctionsAnalyzed++;
801 }
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000802}
803
804//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6a1c7602011-02-28 19:49:17 +0000805// Path-sensitive checking.
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000806//===----------------------------------------------------------------------===//
807
George Karpenkovc82d4572018-09-28 18:49:41 +0000808void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
809 ExprEngine::InliningModes IMode,
810 SetOfConstDecls *VisitedCallees) {
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000811 // Construct the analysis engine. First check if the CFG is valid.
Ted Kremenek1e7f9882009-09-18 22:29:35 +0000812 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
Anna Zaks394d07e2012-03-09 21:14:01 +0000813 if (!Mgr->getCFG(D))
Ted Kremenek39df94b2010-02-14 19:08:51 +0000814 return;
Anna Zaks394d07e2012-03-09 21:14:01 +0000815
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000816 // See if the LiveVariables analysis scales.
817 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
818 return;
819
George Karpenkovc82d4572018-09-28 18:49:41 +0000820 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
Ted Kremenek39df94b2010-02-14 19:08:51 +0000821
Ted Kremenek8e631a02008-07-02 00:44:58 +0000822 // Execute the worklist algorithm.
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000823 if (ExprEngineTimer)
824 ExprEngineTimer->startTimer();
Jordy Rose4f8198e2012-04-28 01:58:08 +0000825 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
Kristof Umann549f9cd2018-11-30 20:44:00 +0000826 Mgr->options.MaxNodesPerTopLevelFunction);
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000827 if (ExprEngineTimer)
828 ExprEngineTimer->stopTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000829
George Karpenkovc704f4f2018-09-28 18:49:21 +0000830 if (!Mgr->options.DumpExplodedGraphTo.empty())
831 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
832
Ted Kremenek71ac8322008-07-02 16:49:11 +0000833 // Visualize the exploded graph.
Ted Kremenekb8f8b352012-08-30 19:26:53 +0000834 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
Ted Kremenek8756c4a2012-08-30 19:26:43 +0000835 Eng.ViewGraph(Mgr->options.TrimGraph);
Mike Stump11289f42009-09-09 15:08:12 +0000836
Ted Kremenek39df18f2009-03-11 01:42:29 +0000837 // Display warnings.
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000838 if (BugReporterTimer)
839 BugReporterTimer->startTimer();
Ted Kremenek39df18f2009-03-11 01:42:29 +0000840 Eng.getBugReporter().FlushReports();
Artem Dergachevc48be7f2019-06-25 02:16:47 +0000841 if (BugReporterTimer)
842 BugReporterTimer->stopTimer();
Ted Kremenekbecec2c2008-07-02 16:35:50 +0000843}
844
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000845//===----------------------------------------------------------------------===//
846// AnalysisConsumer creation.
847//===----------------------------------------------------------------------===//
848
David Blaikie6beb6aa2014-08-10 19:56:51 +0000849std::unique_ptr<AnalysisASTConsumer>
Ted Kremenekeeccb302014-08-27 15:14:15 +0000850ento::CreateAnalysisConsumer(CompilerInstance &CI) {
Jordy Rose59cce712011-08-16 21:24:21 +0000851 // Disable the effects of '-Werror' when using the AnalysisConsumer.
Ted Kremenekeeccb302014-08-27 15:14:15 +0000852 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
Ted Kremenekb5351812009-02-17 04:27:41 +0000853
Ted Kremenekeeccb302014-08-27 15:14:15 +0000854 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
855 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
856
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000857 return std::make_unique<AnalysisConsumer>(
Ilya Biryukov8b9b3bd2018-03-01 14:54:16 +0000858 CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
Ted Kremenekeeccb302014-08-27 15:14:15 +0000859 CI.getFrontendOpts().Plugins,
860 hasModelPath ? new ModelInjector(CI) : nullptr);
Ted Kremenekf0413bf2008-07-02 00:03:09 +0000861}