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