1//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// "Meta" ASTConsumer for running different source analyses.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
14#include "ModelInjector.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/RecursiveASTVisitor.h"
19#include "clang/Analysis/Analyses/LiveVariables.h"
20#include "clang/Analysis/CFG.h"
21#include "clang/Analysis/CallGraph.h"
22#include "clang/Analysis/CodeInjector.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/CrossTU/CrossTranslationUnit.h"
25#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Lex/Preprocessor.h"
27#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
28#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
29#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
30#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
31#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"
36#include "llvm/ADT/PostOrderIterator.h"
37#include "llvm/ADT/Statistic.h"
38#include "llvm/Support/FileSystem.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/Program.h"
41#include "llvm/Support/Timer.h"
42#include "llvm/Support/raw_ostream.h"
43#include <memory>
44#include <queue>
45#include <utility>
46
47using namespace clang;
48using namespace ento;
49
50#define DEBUG_TYPE "AnalysisConsumer"
51
52STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
53STATISTIC(NumFunctionsAnalyzed,
54 "The # of functions and blocks analyzed (as top level "
55 "with inlining turned on).");
56STATISTIC(NumBlocksInAnalyzedFunctions,
57 "The # of basic blocks in the analyzed functions.");
58STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
59 "The # of visited basic blocks in the analyzed functions.");
60STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
61STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
62
63//===----------------------------------------------------------------------===//
64// Special PathDiagnosticConsumers.
65//===----------------------------------------------------------------------===//
66
67void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
68 PathDiagnosticConsumers &C,
69 const std::string &prefix,
70 const Preprocessor &PP) {
71 createHTMLDiagnosticConsumer(AnalyzerOpts, C,
72 llvm::sys::path::parent_path(prefix), PP);
73 createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
74}
75
76void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
77 PathDiagnosticConsumers &C,
78 const std::string &Prefix,
79 const clang::Preprocessor &PP) {
80 llvm_unreachable("'text' consumer should be enabled on ClangDiags");
81}
82
83namespace {
84class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
85 DiagnosticsEngine &Diag;
86 bool IncludePath;
87public:
88 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
89 : Diag(Diag), IncludePath(false) {}
90 ~ClangDiagPathDiagConsumer() override {}
91 StringRef getName() const override { return "ClangDiags"; }
92
93 bool supportsLogicalOpControlFlow() const override { return true; }
94 bool supportsCrossFileDiagnostics() const override { return true; }
95
96 PathGenerationScheme getGenerationScheme() const override {
97 return IncludePath ? Minimal : None;
98 }
99
100 void enablePaths() {
101 IncludePath = true;
102 }
103
104 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
105 FilesMade *filesMade) override {
106 unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
107 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
108
109 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
110 E = Diags.end(); I != E; ++I) {
111 const PathDiagnostic *PD = *I;
112 SourceLocation WarnLoc = PD->getLocation().asLocation();
113 Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
114 << PD->path.back()->getRanges();
115
116 // First, add extra notes, even if paths should not be included.
117 for (const auto &Piece : PD->path) {
118 if (!isa<PathDiagnosticNotePiece>(Piece.get()))
119 continue;
120
121 SourceLocation NoteLoc = Piece->getLocation().asLocation();
122 Diag.Report(NoteLoc, NoteID) << Piece->getString()
123 << Piece->getRanges();
124 }
125
126 if (!IncludePath)
127 continue;
128
129 // Then, add the path notes if necessary.
130 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
131 for (const auto &Piece : FlatPath) {
132 if (isa<PathDiagnosticNotePiece>(Piece.get()))
133 continue;
134
135 SourceLocation NoteLoc = Piece->getLocation().asLocation();
136 Diag.Report(NoteLoc, NoteID) << Piece->getString()
137 << Piece->getRanges();
138 }
139 }
140 }
141};
142} // end anonymous namespace
143
144//===----------------------------------------------------------------------===//
145// AnalysisConsumer declaration.
146//===----------------------------------------------------------------------===//
147
148namespace {
149
150class AnalysisConsumer : public AnalysisASTConsumer,
151 public RecursiveASTVisitor<AnalysisConsumer> {
152 enum {
153 AM_None = 0,
154 AM_Syntax = 0x1,
155 AM_Path = 0x2
156 };
157 typedef unsigned AnalysisMode;
158
159 /// Mode of the analyzes while recursively visiting Decls.
160 AnalysisMode RecVisitorMode;
161 /// Bug Reporter to use while recursively visiting Decls.
162 BugReporter *RecVisitorBR;
163
164 std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
165
166public:
167 ASTContext *Ctx;
168 const Preprocessor &PP;
169 const std::string OutDir;
170 AnalyzerOptionsRef Opts;
171 ArrayRef<std::string> Plugins;
172 CodeInjector *Injector;
173 cross_tu::CrossTranslationUnitContext CTU;
174
175 /// Stores the declarations from the local translation unit.
176 /// Note, we pre-compute the local declarations at parse time as an
177 /// optimization to make sure we do not deserialize everything from disk.
178 /// The local declaration to all declarations ratio might be very small when
179 /// working with a PCH file.
180 SetOfDecls LocalTUDecls;
181
182 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
183 PathDiagnosticConsumers PathConsumers;
184
185 StoreManagerCreator CreateStoreMgr;
186 ConstraintManagerCreator CreateConstraintMgr;
187
188 std::unique_ptr<CheckerManager> checkerMgr;
189 std::unique_ptr<AnalysisManager> Mgr;
190
191 /// Time the analyzes time of each translation unit.
192 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
193 std::unique_ptr<llvm::Timer> TUTotalTimer;
194
195 /// The information about analyzed functions shared throughout the
196 /// translation unit.
197 FunctionSummariesTy FunctionSummaries;
198
199 AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
200 AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
201 CodeInjector *injector)
202 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
203 PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
204 Plugins(plugins), Injector(injector), CTU(CI) {
205 DigestAnalyzerOptions();
206 if (Opts->PrintStats || Opts->ShouldSerializeStats) {
207 AnalyzerTimers = llvm::make_unique<llvm::TimerGroup>(
208 "analyzer", "Analyzer timers");
209 TUTotalTimer = llvm::make_unique<llvm::Timer>(
210 "time", "Analyzer total time", *AnalyzerTimers);
211 llvm::EnableStatistics(/* PrintOnExit= */ false);
212 }
213 }
214
215 ~AnalysisConsumer() override {
216 if (Opts->PrintStats) {
217 llvm::PrintStatistics();
218 }
219 }
220
221 void DigestAnalyzerOptions() {
222 if (Opts->AnalysisDiagOpt != PD_NONE) {
223 // Create the PathDiagnosticConsumer.
224 ClangDiagPathDiagConsumer *clangDiags =
225 new ClangDiagPathDiagConsumer(PP.getDiagnostics());
226 PathConsumers.push_back(clangDiags);
227
228 if (Opts->AnalysisDiagOpt == PD_TEXT) {
229 clangDiags->enablePaths();
230
231 } else if (!OutDir.empty()) {
232 switch (Opts->AnalysisDiagOpt) {
233 default:
234#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
235 case PD_##NAME: \
236 CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \
237 break;
238#include "clang/StaticAnalyzer/Core/Analyses.def"
239 }
240 }
241 }
242
243 // Create the analyzer component creators.
244 switch (Opts->AnalysisStoreOpt) {
245 default:
246 llvm_unreachable("Unknown store manager.");
247#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
248 case NAME##Model: CreateStoreMgr = CREATEFN; break;
249#include "clang/StaticAnalyzer/Core/Analyses.def"
250 }
251
252 switch (Opts->AnalysisConstraintsOpt) {
253 default:
254 llvm_unreachable("Unknown constraint manager.");
255#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
256 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
257#include "clang/StaticAnalyzer/Core/Analyses.def"
258 }
259 }
260
261 void DisplayFunction(const Decl *D, AnalysisMode Mode,
262 ExprEngine::InliningModes IMode) {
263 if (!Opts->AnalyzerDisplayProgress)
264 return;
265
266 SourceManager &SM = Mgr->getASTContext().getSourceManager();
267 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
268 if (Loc.isValid()) {
269 llvm::errs() << "ANALYZE";
270
271 if (Mode == AM_Syntax)
272 llvm::errs() << " (Syntax)";
273 else if (Mode == AM_Path) {
274 llvm::errs() << " (Path, ";
275 switch (IMode) {
276 case ExprEngine::Inline_Minimal:
277 llvm::errs() << " Inline_Minimal";
278 break;
279 case ExprEngine::Inline_Regular:
280 llvm::errs() << " Inline_Regular";
281 break;
282 }
283 llvm::errs() << ")";
284 }
285 else
286 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
287
288 llvm::errs() << ": " << Loc.getFilename() << ' '
289 << getFunctionName(D) << '\n';
290 }
291 }
292
293 void Initialize(ASTContext &Context) override {
294 Ctx = &Context;
295 checkerMgr = createCheckerManager(
296 *Ctx, *Opts, Plugins, CheckerRegistrationFns, PP.getDiagnostics());
297
298 Mgr = llvm::make_unique<AnalysisManager>(
299 *Ctx, PP.getDiagnostics(), PathConsumers, CreateStoreMgr,
300 CreateConstraintMgr, checkerMgr.get(), *Opts, Injector);
301 }
302
303 /// Store the top level decls in the set to be processed later on.
304 /// (Doing this pre-processing avoids deserialization of data from PCH.)
305 bool HandleTopLevelDecl(DeclGroupRef D) override;
306 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
307
308 void HandleTranslationUnit(ASTContext &C) override;
309
310 /// Determine which inlining mode should be used when this function is
311 /// analyzed. This allows to redefine the default inlining policies when
312 /// analyzing a given function.
313 ExprEngine::InliningModes
314 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
315
316 /// Build the call graph for all the top level decls of this TU and
317 /// use it to define the order in which the functions should be visited.
318 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
319
320 /// Run analyzes(syntax or path sensitive) on the given function.
321 /// \param Mode - determines if we are requesting syntax only or path
322 /// sensitive only analysis.
323 /// \param VisitedCallees - The output parameter, which is populated with the
324 /// set of functions which should be considered analyzed after analyzing the
325 /// given root function.
326 void HandleCode(Decl *D, AnalysisMode Mode,
327 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
328 SetOfConstDecls *VisitedCallees = nullptr);
329
330 void RunPathSensitiveChecks(Decl *D,
331 ExprEngine::InliningModes IMode,
332 SetOfConstDecls *VisitedCallees);
333
334 /// Visitors for the RecursiveASTVisitor.
335 bool shouldWalkTypesOfTypeLocs() const { return false; }
336
337 /// Handle callbacks for arbitrary Decls.
338 bool VisitDecl(Decl *D) {
339 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
340 if (Mode & AM_Syntax)
341 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
342 return true;
343 }
344
345 bool VisitFunctionDecl(FunctionDecl *FD) {
346 IdentifierInfo *II = FD->getIdentifier();
347 if (II && II->getName().startswith("__inline"))
348 return true;
349
350 // We skip function template definitions, as their semantics is
351 // only determined when they are instantiated.
352 if (FD->isThisDeclarationADefinition() &&
353 !FD->isDependentContext()) {
354 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
355 HandleCode(FD, RecVisitorMode);
356 }
357 return true;
358 }
359
360 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
361 if (MD->isThisDeclarationADefinition()) {
362 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
363 HandleCode(MD, RecVisitorMode);
364 }
365 return true;
366 }
367
368 bool VisitBlockDecl(BlockDecl *BD) {
369 if (BD->hasBody()) {
370 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
371 // Since we skip function template definitions, we should skip blocks
372 // declared in those functions as well.
373 if (!BD->isDependentContext()) {
374 HandleCode(BD, RecVisitorMode);
375 }
376 }
377 return true;
378 }
379
380 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
381 PathConsumers.push_back(Consumer);
382 }
383
384 void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
385 CheckerRegistrationFns.push_back(std::move(Fn));
386 }
387
388private:
389 void storeTopLevelDecls(DeclGroupRef DG);
390 std::string getFunctionName(const Decl *D);
391
392 /// Check if we should skip (not analyze) the given function.
393 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
394 void runAnalysisOnTranslationUnit(ASTContext &C);
395
396 /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
397 void reportAnalyzerProgress(StringRef S);
398};
399} // end anonymous namespace
400
401
402//===----------------------------------------------------------------------===//
403// AnalysisConsumer implementation.
404//===----------------------------------------------------------------------===//
405bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
406 storeTopLevelDecls(DG);
407 return true;
408}
409
410void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
411 storeTopLevelDecls(DG);
412}
413
414void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
415 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
416
417 // Skip ObjCMethodDecl, wait for the objc container to avoid
418 // analyzing twice.
419 if (isa<ObjCMethodDecl>(*I))
420 continue;
421
422 LocalTUDecls.push_back(*I);
423 }
424}
425
426static bool shouldSkipFunction(const Decl *D,
427 const SetOfConstDecls &Visited,
428 const SetOfConstDecls &VisitedAsTopLevel) {
429 if (VisitedAsTopLevel.count(D))
430 return true;
431
432 // We want to re-analyse the functions as top level in the following cases:
433 // - The 'init' methods should be reanalyzed because
434 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
435 // 'nil' and unless we analyze the 'init' functions as top level, we will
436 // not catch errors within defensive code.
437 // - We want to reanalyze all ObjC methods as top level to report Retain
438 // Count naming convention errors more aggressively.
439 if (isa<ObjCMethodDecl>(D))
440 return false;
441 // We also want to reanalyze all C++ copy and move assignment operators to
442 // separately check the two cases where 'this' aliases with the parameter and
443 // where it may not. (cplusplus.SelfAssignmentChecker)
444 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
445 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
446 return false;
447 }
448
449 // Otherwise, if we visited the function before, do not reanalyze it.
450 return Visited.count(D);
451}
452
453ExprEngine::InliningModes
454AnalysisConsumer::getInliningModeForFunction(const Decl *D,
455 const SetOfConstDecls &Visited) {
456 // We want to reanalyze all ObjC methods as top level to report Retain
457 // Count naming convention errors more aggressively. But we should tune down
458 // inlining when reanalyzing an already inlined function.
459 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
460 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
461 if (ObjCM->getMethodFamily() != OMF_init)
462 return ExprEngine::Inline_Minimal;
463 }
464
465 return ExprEngine::Inline_Regular;
466}
467
468void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
469 // Build the Call Graph by adding all the top level declarations to the graph.
470 // Note: CallGraph can trigger deserialization of more items from a pch
471 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
472 // We rely on random access to add the initially processed Decls to CG.
473 CallGraph CG;
474 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
475 CG.addToCallGraph(LocalTUDecls[i]);
476 }
477
478 // Walk over all of the call graph nodes in topological order, so that we
479 // analyze parents before the children. Skip the functions inlined into
480 // the previously processed functions. Use external Visited set to identify
481 // inlined functions. The topological order allows the "do not reanalyze
482 // previously inlined function" performance heuristic to be triggered more
483 // often.
484 SetOfConstDecls Visited;
485 SetOfConstDecls VisitedAsTopLevel;
486 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
487 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
488 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
489 NumFunctionTopLevel++;
490
491 CallGraphNode *N = *I;
492 Decl *D = N->getDecl();
493
494 // Skip the abstract root node.
495 if (!D)
496 continue;
497
498 // Skip the functions which have been processed already or previously
499 // inlined.
500 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
501 continue;
502
503 // Analyze the function.
504 SetOfConstDecls VisitedCallees;
505
506 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
507 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
508
509 // Add the visited callees to the global visited set.
510 for (const Decl *Callee : VisitedCallees)
511 // Decls from CallGraph are already canonical. But Decls coming from
512 // CallExprs may be not. We should canonicalize them manually.
513 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
514 : Callee->getCanonicalDecl());
515 VisitedAsTopLevel.insert(D);
516 }
517}
518
519static bool isBisonFile(ASTContext &C) {
520 const SourceManager &SM = C.getSourceManager();
521 FileID FID = SM.getMainFileID();
522 StringRef Buffer = SM.getBuffer(FID)->getBuffer();
523 if (Buffer.startswith("/* A Bison parser, made by"))
524 return true;
525 return false;
526}
527
528void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
529 BugReporter BR(*Mgr);
530 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
531 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
532
533 // Run the AST-only checks using the order in which functions are defined.
534 // If inlining is not turned on, use the simplest function order for path
535 // sensitive analyzes as well.
536 RecVisitorMode = AM_Syntax;
537 if (!Mgr->shouldInlineCall())
538 RecVisitorMode |= AM_Path;
539 RecVisitorBR = &BR;
540
541 // Process all the top level declarations.
542 //
543 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
544 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
545 // random access. By doing so, we automatically compensate for iterators
546 // possibly being invalidated, although this is a bit slower.
547 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
548 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
549 TraverseDecl(LocalTUDecls[i]);
550 }
551
552 if (Mgr->shouldInlineCall())
553 HandleDeclsCallGraph(LocalTUDeclsSize);
554
555 // After all decls handled, run checkers on the entire TranslationUnit.
556 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
557
558 RecVisitorBR = nullptr;
559}
560
561void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
562 if (Opts->AnalyzerDisplayProgress)
563 llvm::errs() << S;
564}
565
566void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
567
568 // Don't run the actions if an error has occurred with parsing the file.
569 DiagnosticsEngine &Diags = PP.getDiagnostics();
570 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
571 return;
572
573 if (TUTotalTimer) TUTotalTimer->startTimer();
574
575 if (isBisonFile(C)) {
576 reportAnalyzerProgress("Skipping bison-generated file\n");
577 } else if (Opts->DisableAllChecks) {
578
579 // Don't analyze if the user explicitly asked for no checks to be performed
580 // on this file.
581 reportAnalyzerProgress("All checks are disabled using a supplied option\n");
582 } else {
583 // Otherwise, just run the analysis.
584 runAnalysisOnTranslationUnit(C);
585 }
586
587 if (TUTotalTimer) TUTotalTimer->stopTimer();
588
589 // Count how many basic blocks we have not covered.
590 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
591 NumVisitedBlocksInAnalyzedFunctions =
592 FunctionSummaries.getTotalNumVisitedBasicBlocks();
593 if (NumBlocksInAnalyzedFunctions > 0)
594 PercentReachableBlocks =
595 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
596 NumBlocksInAnalyzedFunctions;
597
598 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
599 // FIXME: This should be replaced with something that doesn't rely on
600 // side-effects in PathDiagnosticConsumer's destructor. This is required when
601 // used with option -disable-free.
602 Mgr.reset();
603}
604
605std::string AnalysisConsumer::getFunctionName(const Decl *D) {
606 std::string Str;
607 llvm::raw_string_ostream OS(Str);
608
609 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
610 OS << FD->getQualifiedNameAsString();
611
612 // In C++, there are overloads.
613 if (Ctx->getLangOpts().CPlusPlus) {
614 OS << '(';
615 for (const auto &P : FD->parameters()) {
616 if (P != *FD->param_begin())
617 OS << ", ";
618 OS << P->getType().getAsString();
619 }
620 OS << ')';
621 }
622
623 } else if (isa<BlockDecl>(D)) {
624 PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
625
626 if (Loc.isValid()) {
627 OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
628 << ')';
629 }
630
631 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
632
633 // FIXME: copy-pasted from CGDebugInfo.cpp.
634 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
635 const DeclContext *DC = OMD->getDeclContext();
636 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
637 OS << OID->getName();
638 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
639 OS << OID->getName();
640 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
641 if (OC->IsClassExtension()) {
642 OS << OC->getClassInterface()->getName();
643 } else {
644 OS << OC->getIdentifier()->getNameStart() << '('
645 << OC->getIdentifier()->getNameStart() << ')';
646 }
647 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
648 OS << OCD->getClassInterface()->getName() << '('
649 << OCD->getName() << ')';
650 } else if (isa<ObjCProtocolDecl>(DC)) {
651 // We can extract the type of the class from the self pointer.
652 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
653 QualType ClassTy =
654 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
655 ClassTy.print(OS, PrintingPolicy(LangOptions()));
656 }
657 }
658 OS << ' ' << OMD->getSelector().getAsString() << ']';
659
660 }
661
662 return OS.str();
663}
664
665AnalysisConsumer::AnalysisMode
666AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
667 if (!Opts->AnalyzeSpecificFunction.empty() &&
668 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
669 return AM_None;
670
671 // Unless -analyze-all is specified, treat decls differently depending on
672 // where they came from:
673 // - Main source file: run both path-sensitive and non-path-sensitive checks.
674 // - Header files: run non-path-sensitive checks only.
675 // - System headers: don't run any checks.
676 SourceManager &SM = Ctx->getSourceManager();
677 const Stmt *Body = D->getBody();
678 SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
679 SL = SM.getExpansionLoc(SL);
680
681 if (!Opts->AnalyzeAll && !Mgr->isInCodeFile(SL)) {
682 if (SL.isInvalid() || SM.isInSystemHeader(SL))
683 return AM_None;
684 return Mode & ~AM_Path;
685 }
686
687 return Mode;
688}
689
690void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
691 ExprEngine::InliningModes IMode,
692 SetOfConstDecls *VisitedCallees) {
693 if (!D->hasBody())
694 return;
695 Mode = getModeForDecl(D, Mode);
696 if (Mode == AM_None)
697 return;
698
699 // Clear the AnalysisManager of old AnalysisDeclContexts.
700 Mgr->ClearContexts();
701 // Ignore autosynthesized code.
702 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
703 return;
704
705 DisplayFunction(D, Mode, IMode);
706 CFG *DeclCFG = Mgr->getCFG(D);
707 if (DeclCFG)
708 MaxCFGSize.updateMax(DeclCFG->size());
709
710 BugReporter BR(*Mgr);
711
712 if (Mode & AM_Syntax)
713 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
714 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
715 RunPathSensitiveChecks(D, IMode, VisitedCallees);
716 if (IMode != ExprEngine::Inline_Minimal)
717 NumFunctionsAnalyzed++;
718 }
719}
720
721//===----------------------------------------------------------------------===//
722// Path-sensitive checking.
723//===----------------------------------------------------------------------===//
724
725void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
726 ExprEngine::InliningModes IMode,
727 SetOfConstDecls *VisitedCallees) {
728 // Construct the analysis engine. First check if the CFG is valid.
729 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
730 if (!Mgr->getCFG(D))
731 return;
732
733 // See if the LiveVariables analysis scales.
734 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
735 return;
736
737 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
738
739 // Execute the worklist algorithm.
740 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
741 Mgr->options.MaxNodesPerTopLevelFunction);
742
743 if (!Mgr->options.DumpExplodedGraphTo.empty())
744 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
745
746 // Visualize the exploded graph.
747 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
748 Eng.ViewGraph(Mgr->options.TrimGraph);
749
750 // Display warnings.
751 Eng.getBugReporter().FlushReports();
752}
753
754//===----------------------------------------------------------------------===//
755// AnalysisConsumer creation.
756//===----------------------------------------------------------------------===//
757
758std::unique_ptr<AnalysisASTConsumer>
759ento::CreateAnalysisConsumer(CompilerInstance &CI) {
760 // Disable the effects of '-Werror' when using the AnalysisConsumer.
761 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
762
763 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
764 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
765
766 return llvm::make_unique<AnalysisConsumer>(
767 CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
768 CI.getFrontendOpts().Plugins,
769 hasModelPath ? new ModelInjector(CI) : nullptr);
770}
771