AnalysisConsumer.cpp 28 KB

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