AnalysisConsumer.cpp 28 KB

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