AnalysisConsumer.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
  13. #include "ModelInjector.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/RecursiveASTVisitor.h"
  18. #include "clang/Analysis/Analyses/LiveVariables.h"
  19. #include "clang/Analysis/CFG.h"
  20. #include "clang/Analysis/CallGraph.h"
  21. #include "clang/Analysis/CodeInjector.h"
  22. #include "clang/Analysis/MacroExpansionContext.h"
  23. #include "clang/Analysis/PathDiagnostic.h"
  24. #include "clang/Basic/SourceManager.h"
  25. #include "clang/CrossTU/CrossTranslationUnit.h"
  26. #include "clang/Frontend/CompilerInstance.h"
  27. #include "clang/Lex/Preprocessor.h"
  28. #include "clang/Rewrite/Core/Rewriter.h"
  29. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  30. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.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 "llvm/ADT/PostOrderIterator.h"
  36. #include "llvm/ADT/ScopeExit.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. using namespace clang;
  47. using namespace ento;
  48. #define DEBUG_TYPE "AnalysisConsumer"
  49. STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
  50. STATISTIC(NumFunctionsAnalyzed,
  51. "The # of functions and blocks analyzed (as top level "
  52. "with inlining turned on).");
  53. STATISTIC(NumBlocksInAnalyzedFunctions,
  54. "The # of basic blocks in the analyzed functions.");
  55. STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
  56. "The # of visited basic blocks in the analyzed functions.");
  57. STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
  58. STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
  59. //===----------------------------------------------------------------------===//
  60. // AnalysisConsumer declaration.
  61. //===----------------------------------------------------------------------===//
  62. namespace {
  63. class AnalysisConsumer : public AnalysisASTConsumer,
  64. public RecursiveASTVisitor<AnalysisConsumer> {
  65. enum {
  66. AM_None = 0,
  67. AM_Syntax = 0x1,
  68. AM_Path = 0x2
  69. };
  70. typedef unsigned AnalysisMode;
  71. /// Mode of the analyzes while recursively visiting Decls.
  72. AnalysisMode RecVisitorMode;
  73. /// Bug Reporter to use while recursively visiting Decls.
  74. BugReporter *RecVisitorBR;
  75. std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
  76. public:
  77. ASTContext *Ctx;
  78. Preprocessor &PP;
  79. const std::string OutDir;
  80. AnalyzerOptionsRef Opts;
  81. ArrayRef<std::string> Plugins;
  82. CodeInjector *Injector;
  83. cross_tu::CrossTranslationUnitContext CTU;
  84. /// Stores the declarations from the local translation unit.
  85. /// Note, we pre-compute the local declarations at parse time as an
  86. /// optimization to make sure we do not deserialize everything from disk.
  87. /// The local declaration to all declarations ratio might be very small when
  88. /// working with a PCH file.
  89. SetOfDecls LocalTUDecls;
  90. MacroExpansionContext MacroExpansions;
  91. // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
  92. PathDiagnosticConsumers PathConsumers;
  93. StoreManagerCreator CreateStoreMgr;
  94. ConstraintManagerCreator CreateConstraintMgr;
  95. std::unique_ptr<CheckerManager> checkerMgr;
  96. std::unique_ptr<AnalysisManager> Mgr;
  97. /// Time the analyzes time of each translation unit.
  98. std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
  99. std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
  100. std::unique_ptr<llvm::Timer> ExprEngineTimer;
  101. std::unique_ptr<llvm::Timer> BugReporterTimer;
  102. /// The information about analyzed functions shared throughout the
  103. /// translation unit.
  104. FunctionSummariesTy FunctionSummaries;
  105. AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
  106. AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
  107. CodeInjector *injector)
  108. : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
  109. PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
  110. Plugins(plugins), Injector(injector), CTU(CI),
  111. MacroExpansions(CI.getLangOpts()) {
  112. DigestAnalyzerOptions();
  113. if (Opts->AnalyzerDisplayProgress || Opts->PrintStats ||
  114. Opts->ShouldSerializeStats) {
  115. AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
  116. "analyzer", "Analyzer timers");
  117. SyntaxCheckTimer = std::make_unique<llvm::Timer>(
  118. "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers);
  119. ExprEngineTimer = std::make_unique<llvm::Timer>(
  120. "exprengine", "Path exploration time", *AnalyzerTimers);
  121. BugReporterTimer = std::make_unique<llvm::Timer>(
  122. "bugreporter", "Path-sensitive report post-processing time",
  123. *AnalyzerTimers);
  124. }
  125. if (Opts->PrintStats || Opts->ShouldSerializeStats) {
  126. llvm::EnableStatistics(/* DoPrintOnExit= */ false);
  127. }
  128. if (Opts->ShouldDisplayMacroExpansions)
  129. MacroExpansions.registerForPreprocessor(PP);
  130. }
  131. ~AnalysisConsumer() override {
  132. if (Opts->PrintStats) {
  133. llvm::PrintStatistics();
  134. }
  135. }
  136. void DigestAnalyzerOptions() {
  137. switch (Opts->AnalysisDiagOpt) {
  138. case PD_NONE:
  139. break;
  140. #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
  141. case PD_##NAME: \
  142. CREATEFN(Opts->getDiagOpts(), PathConsumers, OutDir, PP, CTU, \
  143. MacroExpansions); \
  144. break;
  145. #include "clang/StaticAnalyzer/Core/Analyses.def"
  146. default:
  147. llvm_unreachable("Unknown analyzer output type!");
  148. }
  149. // Create the analyzer component creators.
  150. CreateStoreMgr = &CreateRegionStoreManager;
  151. switch (Opts->AnalysisConstraintsOpt) {
  152. default:
  153. llvm_unreachable("Unknown constraint manager.");
  154. #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
  155. case NAME##Model: CreateConstraintMgr = CREATEFN; break;
  156. #include "clang/StaticAnalyzer/Core/Analyses.def"
  157. }
  158. }
  159. void DisplayTime(llvm::TimeRecord &Time) {
  160. if (!Opts->AnalyzerDisplayProgress) {
  161. return;
  162. }
  163. llvm::errs() << " : " << llvm::format("%1.1f", Time.getWallTime() * 1000)
  164. << " ms\n";
  165. }
  166. void DisplayFunction(const Decl *D, AnalysisMode Mode,
  167. ExprEngine::InliningModes IMode) {
  168. if (!Opts->AnalyzerDisplayProgress)
  169. return;
  170. SourceManager &SM = Mgr->getASTContext().getSourceManager();
  171. PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
  172. if (Loc.isValid()) {
  173. llvm::errs() << "ANALYZE";
  174. if (Mode == AM_Syntax)
  175. llvm::errs() << " (Syntax)";
  176. else if (Mode == AM_Path) {
  177. llvm::errs() << " (Path, ";
  178. switch (IMode) {
  179. case ExprEngine::Inline_Minimal:
  180. llvm::errs() << " Inline_Minimal";
  181. break;
  182. case ExprEngine::Inline_Regular:
  183. llvm::errs() << " Inline_Regular";
  184. break;
  185. }
  186. llvm::errs() << ")";
  187. } else
  188. assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
  189. llvm::errs() << ": " << Loc.getFilename() << ' '
  190. << AnalysisDeclContext::getFunctionName(D);
  191. }
  192. }
  193. void Initialize(ASTContext &Context) override {
  194. Ctx = &Context;
  195. checkerMgr = std::make_unique<CheckerManager>(*Ctx, *Opts, PP, Plugins,
  196. CheckerRegistrationFns);
  197. Mgr = std::make_unique<AnalysisManager>(*Ctx, PP, PathConsumers,
  198. CreateStoreMgr, CreateConstraintMgr,
  199. checkerMgr.get(), *Opts, Injector);
  200. }
  201. /// Store the top level decls in the set to be processed later on.
  202. /// (Doing this pre-processing avoids deserialization of data from PCH.)
  203. bool HandleTopLevelDecl(DeclGroupRef D) override;
  204. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
  205. void HandleTranslationUnit(ASTContext &C) override;
  206. /// Determine which inlining mode should be used when this function is
  207. /// analyzed. This allows to redefine the default inlining policies when
  208. /// analyzing a given function.
  209. ExprEngine::InliningModes
  210. getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
  211. /// Build the call graph for all the top level decls of this TU and
  212. /// use it to define the order in which the functions should be visited.
  213. void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
  214. /// Run analyzes(syntax or path sensitive) on the given function.
  215. /// \param Mode - determines if we are requesting syntax only or path
  216. /// sensitive only analysis.
  217. /// \param VisitedCallees - The output parameter, which is populated with the
  218. /// set of functions which should be considered analyzed after analyzing the
  219. /// given root function.
  220. void HandleCode(Decl *D, AnalysisMode Mode,
  221. ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
  222. SetOfConstDecls *VisitedCallees = nullptr);
  223. void RunPathSensitiveChecks(Decl *D,
  224. ExprEngine::InliningModes IMode,
  225. SetOfConstDecls *VisitedCallees);
  226. /// Visitors for the RecursiveASTVisitor.
  227. bool shouldWalkTypesOfTypeLocs() const { return false; }
  228. /// Handle callbacks for arbitrary Decls.
  229. bool VisitDecl(Decl *D) {
  230. AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
  231. if (Mode & AM_Syntax) {
  232. if (SyntaxCheckTimer)
  233. SyntaxCheckTimer->startTimer();
  234. checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
  235. if (SyntaxCheckTimer)
  236. SyntaxCheckTimer->stopTimer();
  237. }
  238. return true;
  239. }
  240. bool VisitVarDecl(VarDecl *VD) {
  241. if (!Opts->IsNaiveCTUEnabled)
  242. return true;
  243. if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
  244. if (!cross_tu::shouldImport(VD, *Ctx))
  245. return true;
  246. } else {
  247. // Cannot be initialized in another TU.
  248. return true;
  249. }
  250. if (VD->getAnyInitializer())
  251. return true;
  252. llvm::Expected<const VarDecl *> CTUDeclOrError =
  253. CTU.getCrossTUDefinition(VD, Opts->CTUDir, Opts->CTUIndexName,
  254. Opts->DisplayCTUProgress);
  255. if (!CTUDeclOrError) {
  256. handleAllErrors(CTUDeclOrError.takeError(),
  257. [&](const cross_tu::IndexError &IE) {
  258. CTU.emitCrossTUDiagnostics(IE);
  259. });
  260. }
  261. return true;
  262. }
  263. bool VisitFunctionDecl(FunctionDecl *FD) {
  264. IdentifierInfo *II = FD->getIdentifier();
  265. if (II && II->getName().startswith("__inline"))
  266. return true;
  267. // We skip function template definitions, as their semantics is
  268. // only determined when they are instantiated.
  269. if (FD->isThisDeclarationADefinition() &&
  270. !FD->isDependentContext()) {
  271. assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
  272. HandleCode(FD, RecVisitorMode);
  273. }
  274. return true;
  275. }
  276. bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
  277. if (MD->isThisDeclarationADefinition()) {
  278. assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
  279. HandleCode(MD, RecVisitorMode);
  280. }
  281. return true;
  282. }
  283. bool VisitBlockDecl(BlockDecl *BD) {
  284. if (BD->hasBody()) {
  285. assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
  286. // Since we skip function template definitions, we should skip blocks
  287. // declared in those functions as well.
  288. if (!BD->isDependentContext()) {
  289. HandleCode(BD, RecVisitorMode);
  290. }
  291. }
  292. return true;
  293. }
  294. void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
  295. PathConsumers.push_back(Consumer);
  296. }
  297. void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
  298. CheckerRegistrationFns.push_back(std::move(Fn));
  299. }
  300. private:
  301. void storeTopLevelDecls(DeclGroupRef DG);
  302. /// Check if we should skip (not analyze) the given function.
  303. AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
  304. void runAnalysisOnTranslationUnit(ASTContext &C);
  305. /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
  306. void reportAnalyzerProgress(StringRef S);
  307. }; // namespace
  308. } // end anonymous namespace
  309. //===----------------------------------------------------------------------===//
  310. // AnalysisConsumer implementation.
  311. //===----------------------------------------------------------------------===//
  312. bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
  313. storeTopLevelDecls(DG);
  314. return true;
  315. }
  316. void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
  317. storeTopLevelDecls(DG);
  318. }
  319. void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
  320. for (auto &I : DG) {
  321. // Skip ObjCMethodDecl, wait for the objc container to avoid
  322. // analyzing twice.
  323. if (isa<ObjCMethodDecl>(I))
  324. continue;
  325. LocalTUDecls.push_back(I);
  326. }
  327. }
  328. static bool shouldSkipFunction(const Decl *D,
  329. const SetOfConstDecls &Visited,
  330. const SetOfConstDecls &VisitedAsTopLevel) {
  331. if (VisitedAsTopLevel.count(D))
  332. return true;
  333. // Skip analysis of inheriting constructors as top-level functions. These
  334. // constructors don't even have a body written down in the code, so even if
  335. // we find a bug, we won't be able to display it.
  336. if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  337. if (CD->isInheritingConstructor())
  338. return true;
  339. // We want to re-analyse the functions as top level in the following cases:
  340. // - The 'init' methods should be reanalyzed because
  341. // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
  342. // 'nil' and unless we analyze the 'init' functions as top level, we will
  343. // not catch errors within defensive code.
  344. // - We want to reanalyze all ObjC methods as top level to report Retain
  345. // Count naming convention errors more aggressively.
  346. if (isa<ObjCMethodDecl>(D))
  347. return false;
  348. // We also want to reanalyze all C++ copy and move assignment operators to
  349. // separately check the two cases where 'this' aliases with the parameter and
  350. // where it may not. (cplusplus.SelfAssignmentChecker)
  351. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  352. if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
  353. return false;
  354. }
  355. // Otherwise, if we visited the function before, do not reanalyze it.
  356. return Visited.count(D);
  357. }
  358. ExprEngine::InliningModes
  359. AnalysisConsumer::getInliningModeForFunction(const Decl *D,
  360. const SetOfConstDecls &Visited) {
  361. // We want to reanalyze all ObjC methods as top level to report Retain
  362. // Count naming convention errors more aggressively. But we should tune down
  363. // inlining when reanalyzing an already inlined function.
  364. if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
  365. const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
  366. if (ObjCM->getMethodFamily() != OMF_init)
  367. return ExprEngine::Inline_Minimal;
  368. }
  369. return ExprEngine::Inline_Regular;
  370. }
  371. void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
  372. // Build the Call Graph by adding all the top level declarations to the graph.
  373. // Note: CallGraph can trigger deserialization of more items from a pch
  374. // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
  375. // We rely on random access to add the initially processed Decls to CG.
  376. CallGraph CG;
  377. for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
  378. CG.addToCallGraph(LocalTUDecls[i]);
  379. }
  380. // Walk over all of the call graph nodes in topological order, so that we
  381. // analyze parents before the children. Skip the functions inlined into
  382. // the previously processed functions. Use external Visited set to identify
  383. // inlined functions. The topological order allows the "do not reanalyze
  384. // previously inlined function" performance heuristic to be triggered more
  385. // often.
  386. SetOfConstDecls Visited;
  387. SetOfConstDecls VisitedAsTopLevel;
  388. llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
  389. for (auto &N : RPOT) {
  390. NumFunctionTopLevel++;
  391. Decl *D = N->getDecl();
  392. // Skip the abstract root node.
  393. if (!D)
  394. continue;
  395. // Skip the functions which have been processed already or previously
  396. // inlined.
  397. if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
  398. continue;
  399. // The CallGraph might have declarations as callees. However, during CTU
  400. // the declaration might form a declaration chain with the newly imported
  401. // definition from another TU. In this case we don't want to analyze the
  402. // function definition as toplevel.
  403. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  404. // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
  405. // that has the body.
  406. FD->hasBody(FD);
  407. if (CTU.isImportedAsNew(FD))
  408. continue;
  409. }
  410. // Analyze the function.
  411. SetOfConstDecls VisitedCallees;
  412. HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
  413. (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
  414. // Add the visited callees to the global visited set.
  415. for (const Decl *Callee : VisitedCallees)
  416. // Decls from CallGraph are already canonical. But Decls coming from
  417. // CallExprs may be not. We should canonicalize them manually.
  418. Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
  419. : Callee->getCanonicalDecl());
  420. VisitedAsTopLevel.insert(D);
  421. }
  422. }
  423. static bool fileContainsString(StringRef Substring, ASTContext &C) {
  424. const SourceManager &SM = C.getSourceManager();
  425. FileID FID = SM.getMainFileID();
  426. StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();
  427. return Buffer.contains(Substring);
  428. }
  429. static void reportAnalyzerFunctionMisuse(const AnalyzerOptions &Opts,
  430. const ASTContext &Ctx) {
  431. llvm::errs() << "Every top-level function was skipped.\n";
  432. if (!Opts.AnalyzerDisplayProgress)
  433. llvm::errs() << "Pass the -analyzer-display-progress for tracking which "
  434. "functions are analyzed.\n";
  435. bool HasBrackets =
  436. Opts.AnalyzeSpecificFunction.find("(") != std::string::npos;
  437. if (Ctx.getLangOpts().CPlusPlus && !HasBrackets) {
  438. llvm::errs()
  439. << "For analyzing C++ code you need to pass the function parameter "
  440. "list: -analyze-function=\"foobar(int, _Bool)\"\n";
  441. } else if (!Ctx.getLangOpts().CPlusPlus && HasBrackets) {
  442. llvm::errs() << "For analyzing C code you shouldn't pass the function "
  443. "parameter list, only the name of the function: "
  444. "-analyze-function=foobar\n";
  445. }
  446. }
  447. void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
  448. BugReporter BR(*Mgr);
  449. TranslationUnitDecl *TU = C.getTranslationUnitDecl();
  450. if (SyntaxCheckTimer)
  451. SyntaxCheckTimer->startTimer();
  452. checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
  453. if (SyntaxCheckTimer)
  454. SyntaxCheckTimer->stopTimer();
  455. // Run the AST-only checks using the order in which functions are defined.
  456. // If inlining is not turned on, use the simplest function order for path
  457. // sensitive analyzes as well.
  458. RecVisitorMode = AM_Syntax;
  459. if (!Mgr->shouldInlineCall())
  460. RecVisitorMode |= AM_Path;
  461. RecVisitorBR = &BR;
  462. // Process all the top level declarations.
  463. //
  464. // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
  465. // entries. Thus we don't use an iterator, but rely on LocalTUDecls
  466. // random access. By doing so, we automatically compensate for iterators
  467. // possibly being invalidated, although this is a bit slower.
  468. const unsigned LocalTUDeclsSize = LocalTUDecls.size();
  469. for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
  470. TraverseDecl(LocalTUDecls[i]);
  471. }
  472. if (Mgr->shouldInlineCall())
  473. HandleDeclsCallGraph(LocalTUDeclsSize);
  474. // After all decls handled, run checkers on the entire TranslationUnit.
  475. checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
  476. BR.FlushReports();
  477. RecVisitorBR = nullptr;
  478. // If the user wanted to analyze a specific function and the number of basic
  479. // blocks analyzed is zero, than the user might not specified the function
  480. // name correctly.
  481. // FIXME: The user might have analyzed the requested function in Syntax mode,
  482. // but we are unaware of that.
  483. if (!Opts->AnalyzeSpecificFunction.empty() && NumFunctionsAnalyzed == 0)
  484. reportAnalyzerFunctionMisuse(*Opts, *Ctx);
  485. }
  486. void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
  487. if (Opts->AnalyzerDisplayProgress)
  488. llvm::errs() << S;
  489. }
  490. void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
  491. // Don't run the actions if an error has occurred with parsing the file.
  492. DiagnosticsEngine &Diags = PP.getDiagnostics();
  493. if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
  494. return;
  495. // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
  496. // FIXME: This should be replaced with something that doesn't rely on
  497. // side-effects in PathDiagnosticConsumer's destructor. This is required when
  498. // used with option -disable-free.
  499. const auto DiagFlusherScopeExit =
  500. llvm::make_scope_exit([this] { Mgr.reset(); });
  501. if (Opts->ShouldIgnoreBisonGeneratedFiles &&
  502. fileContainsString("/* A Bison parser, made by", C)) {
  503. reportAnalyzerProgress("Skipping bison-generated file\n");
  504. return;
  505. }
  506. if (Opts->ShouldIgnoreFlexGeneratedFiles &&
  507. fileContainsString("/* A lexical scanner generated by flex", C)) {
  508. reportAnalyzerProgress("Skipping flex-generated file\n");
  509. return;
  510. }
  511. // Don't analyze if the user explicitly asked for no checks to be performed
  512. // on this file.
  513. if (Opts->DisableAllCheckers) {
  514. reportAnalyzerProgress("All checks are disabled using a supplied option\n");
  515. return;
  516. }
  517. // Otherwise, just run the analysis.
  518. runAnalysisOnTranslationUnit(C);
  519. // Count how many basic blocks we have not covered.
  520. NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
  521. NumVisitedBlocksInAnalyzedFunctions =
  522. FunctionSummaries.getTotalNumVisitedBasicBlocks();
  523. if (NumBlocksInAnalyzedFunctions > 0)
  524. PercentReachableBlocks =
  525. (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
  526. NumBlocksInAnalyzedFunctions;
  527. }
  528. AnalysisConsumer::AnalysisMode
  529. AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
  530. if (!Opts->AnalyzeSpecificFunction.empty() &&
  531. AnalysisDeclContext::getFunctionName(D) != Opts->AnalyzeSpecificFunction)
  532. return AM_None;
  533. // Unless -analyze-all is specified, treat decls differently depending on
  534. // where they came from:
  535. // - Main source file: run both path-sensitive and non-path-sensitive checks.
  536. // - Header files: run non-path-sensitive checks only.
  537. // - System headers: don't run any checks.
  538. if (Opts->AnalyzeAll)
  539. return Mode;
  540. const SourceManager &SM = Ctx->getSourceManager();
  541. const SourceLocation Loc = [&SM](Decl *D) -> SourceLocation {
  542. const Stmt *Body = D->getBody();
  543. SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
  544. return SM.getExpansionLoc(SL);
  545. }(D);
  546. // Ignore system headers.
  547. if (Loc.isInvalid() || SM.isInSystemHeader(Loc))
  548. return AM_None;
  549. // Disable path sensitive analysis in user-headers.
  550. if (!Mgr->isInCodeFile(Loc))
  551. return Mode & ~AM_Path;
  552. return Mode;
  553. }
  554. void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
  555. ExprEngine::InliningModes IMode,
  556. SetOfConstDecls *VisitedCallees) {
  557. if (!D->hasBody())
  558. return;
  559. Mode = getModeForDecl(D, Mode);
  560. if (Mode == AM_None)
  561. return;
  562. // Clear the AnalysisManager of old AnalysisDeclContexts.
  563. Mgr->ClearContexts();
  564. // Ignore autosynthesized code.
  565. if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
  566. return;
  567. CFG *DeclCFG = Mgr->getCFG(D);
  568. if (DeclCFG)
  569. MaxCFGSize.updateMax(DeclCFG->size());
  570. DisplayFunction(D, Mode, IMode);
  571. BugReporter BR(*Mgr);
  572. if (Mode & AM_Syntax) {
  573. llvm::TimeRecord CheckerStartTime;
  574. if (SyntaxCheckTimer) {
  575. CheckerStartTime = SyntaxCheckTimer->getTotalTime();
  576. SyntaxCheckTimer->startTimer();
  577. }
  578. checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
  579. if (SyntaxCheckTimer) {
  580. SyntaxCheckTimer->stopTimer();
  581. llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime();
  582. CheckerEndTime -= CheckerStartTime;
  583. DisplayTime(CheckerEndTime);
  584. }
  585. }
  586. BR.FlushReports();
  587. if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
  588. RunPathSensitiveChecks(D, IMode, VisitedCallees);
  589. if (IMode != ExprEngine::Inline_Minimal)
  590. NumFunctionsAnalyzed++;
  591. }
  592. }
  593. //===----------------------------------------------------------------------===//
  594. // Path-sensitive checking.
  595. //===----------------------------------------------------------------------===//
  596. void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
  597. ExprEngine::InliningModes IMode,
  598. SetOfConstDecls *VisitedCallees) {
  599. // Construct the analysis engine. First check if the CFG is valid.
  600. // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
  601. if (!Mgr->getCFG(D))
  602. return;
  603. // See if the LiveVariables analysis scales.
  604. if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
  605. return;
  606. ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
  607. // Execute the worklist algorithm.
  608. llvm::TimeRecord ExprEngineStartTime;
  609. if (ExprEngineTimer) {
  610. ExprEngineStartTime = ExprEngineTimer->getTotalTime();
  611. ExprEngineTimer->startTimer();
  612. }
  613. Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
  614. Mgr->options.MaxNodesPerTopLevelFunction);
  615. if (ExprEngineTimer) {
  616. ExprEngineTimer->stopTimer();
  617. llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime();
  618. ExprEngineEndTime -= ExprEngineStartTime;
  619. DisplayTime(ExprEngineEndTime);
  620. }
  621. if (!Mgr->options.DumpExplodedGraphTo.empty())
  622. Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
  623. // Visualize the exploded graph.
  624. if (Mgr->options.visualizeExplodedGraphWithGraphViz)
  625. Eng.ViewGraph(Mgr->options.TrimGraph);
  626. // Display warnings.
  627. if (BugReporterTimer)
  628. BugReporterTimer->startTimer();
  629. Eng.getBugReporter().FlushReports();
  630. if (BugReporterTimer)
  631. BugReporterTimer->stopTimer();
  632. }
  633. //===----------------------------------------------------------------------===//
  634. // AnalysisConsumer creation.
  635. //===----------------------------------------------------------------------===//
  636. std::unique_ptr<AnalysisASTConsumer>
  637. ento::CreateAnalysisConsumer(CompilerInstance &CI) {
  638. // Disable the effects of '-Werror' when using the AnalysisConsumer.
  639. CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
  640. AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
  641. bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
  642. return std::make_unique<AnalysisConsumer>(
  643. CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
  644. CI.getFrontendOpts().Plugins,
  645. hasModelPath ? new ModelInjector(CI) : nullptr);
  646. }