AnalysisConsumer.cpp revision 243830
1218887Sdim//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===// 2218887Sdim// 3218887Sdim// The LLVM Compiler Infrastructure 4218887Sdim// 5218887Sdim// This file is distributed under the University of Illinois Open Source 6218887Sdim// License. See LICENSE.TXT for details. 7218887Sdim// 8218887Sdim//===----------------------------------------------------------------------===// 9218887Sdim// 10218887Sdim// "Meta" ASTConsumer for running different source analyses. 11218887Sdim// 12218887Sdim//===----------------------------------------------------------------------===// 13218887Sdim 14234353Sdim#define DEBUG_TYPE "AnalysisConsumer" 15234353Sdim 16218887Sdim#include "AnalysisConsumer.h" 17218887Sdim#include "clang/AST/ASTConsumer.h" 18218887Sdim#include "clang/AST/Decl.h" 19218887Sdim#include "clang/AST/DeclCXX.h" 20218887Sdim#include "clang/AST/DeclObjC.h" 21218887Sdim#include "clang/AST/ParentMap.h" 22234353Sdim#include "clang/AST/RecursiveASTVisitor.h" 23218887Sdim#include "clang/Analysis/CFG.h" 24234353Sdim#include "clang/Analysis/CallGraph.h" 25239462Sdim#include "clang/Analysis/Analyses/LiveVariables.h" 26218887Sdim#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h" 27218887Sdim#include "clang/StaticAnalyzer/Core/CheckerManager.h" 28218887Sdim#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 29218887Sdim#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 30218887Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 31218887Sdim#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 32218887Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 33226633Sdim#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 34218887Sdim 35218887Sdim#include "clang/Basic/FileManager.h" 36218887Sdim#include "clang/Basic/SourceManager.h" 37243830Sdim#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 38218887Sdim#include "clang/Lex/Preprocessor.h" 39218887Sdim#include "llvm/Support/raw_ostream.h" 40218887Sdim#include "llvm/Support/Path.h" 41218887Sdim#include "llvm/Support/Program.h" 42234353Sdim#include "llvm/Support/Timer.h" 43234353Sdim#include "llvm/ADT/DepthFirstIterator.h" 44218887Sdim#include "llvm/ADT/OwningPtr.h" 45234353Sdim#include "llvm/ADT/SmallPtrSet.h" 46234353Sdim#include "llvm/ADT/Statistic.h" 47218887Sdim 48234353Sdim#include <queue> 49234353Sdim 50218887Sdimusing namespace clang; 51218887Sdimusing namespace ento; 52234353Sdimusing llvm::SmallPtrSet; 53218887Sdim 54218887Sdimstatic ExplodedNode::Auditor* CreateUbiViz(); 55218887Sdim 56234353SdimSTATISTIC(NumFunctionTopLevel, "The # of functions at top level."); 57234353SdimSTATISTIC(NumFunctionsAnalyzed, "The # of functions analysed (as top level)."); 58234353SdimSTATISTIC(NumBlocksInAnalyzedFunctions, 59234353Sdim "The # of basic blocks in the analyzed functions."); 60234353SdimSTATISTIC(PercentReachableBlocks, "The % of reachable basic blocks."); 61239462SdimSTATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function."); 62234353Sdim 63218887Sdim//===----------------------------------------------------------------------===// 64226633Sdim// Special PathDiagnosticConsumers. 65218887Sdim//===----------------------------------------------------------------------===// 66218887Sdim 67239462Sdimstatic void createPlistHTMLDiagnosticConsumer(PathDiagnosticConsumers &C, 68239462Sdim const std::string &prefix, 69239462Sdim const Preprocessor &PP) { 70239462Sdim createHTMLDiagnosticConsumer(C, llvm::sys::path::parent_path(prefix), PP); 71239462Sdim createPlistDiagnosticConsumer(C, prefix, PP); 72218887Sdim} 73218887Sdim 74239462Sdimnamespace { 75239462Sdimclass ClangDiagPathDiagConsumer : public PathDiagnosticConsumer { 76239462Sdim DiagnosticsEngine &Diag; 77239462Sdimpublic: 78239462Sdim ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag) : Diag(Diag) {} 79239462Sdim virtual ~ClangDiagPathDiagConsumer() {} 80239462Sdim virtual StringRef getName() const { return "ClangDiags"; } 81239462Sdim virtual PathGenerationScheme getGenerationScheme() const { return None; } 82239462Sdim 83239462Sdim void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, 84239462Sdim FilesMade *filesMade) { 85239462Sdim for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(), 86239462Sdim E = Diags.end(); I != E; ++I) { 87239462Sdim const PathDiagnostic *PD = *I; 88243830Sdim StringRef desc = PD->getShortDescription(); 89239462Sdim SmallString<512> TmpStr; 90239462Sdim llvm::raw_svector_ostream Out(TmpStr); 91239462Sdim for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) { 92239462Sdim if (*I == '%') 93239462Sdim Out << "%%"; 94239462Sdim else 95239462Sdim Out << *I; 96239462Sdim } 97239462Sdim Out.flush(); 98239462Sdim unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning, 99239462Sdim TmpStr); 100239462Sdim SourceLocation L = PD->getLocation().asLocation(); 101239462Sdim DiagnosticBuilder diagBuilder = Diag.Report(L, ErrorDiag); 102239462Sdim 103239462Sdim // Get the ranges from the last point in the path. 104239462Sdim ArrayRef<SourceRange> Ranges = PD->path.back()->getRanges(); 105239462Sdim 106239462Sdim for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), 107239462Sdim E = Ranges.end(); I != E; ++I) { 108239462Sdim diagBuilder << *I; 109239462Sdim } 110239462Sdim } 111239462Sdim } 112239462Sdim}; 113239462Sdim} // end anonymous namespace 114239462Sdim 115218887Sdim//===----------------------------------------------------------------------===// 116218887Sdim// AnalysisConsumer declaration. 117218887Sdim//===----------------------------------------------------------------------===// 118218887Sdim 119218887Sdimnamespace { 120218887Sdim 121234353Sdimclass AnalysisConsumer : public ASTConsumer, 122234353Sdim public RecursiveASTVisitor<AnalysisConsumer> { 123243830Sdim enum { 124243830Sdim AM_None = 0, 125243830Sdim AM_Syntax = 0x1, 126243830Sdim AM_Path = 0x2 127234353Sdim }; 128243830Sdim typedef unsigned AnalysisMode; 129234353Sdim 130234353Sdim /// Mode of the analyzes while recursively visiting Decls. 131234353Sdim AnalysisMode RecVisitorMode; 132234353Sdim /// Bug Reporter to use while recursively visiting Decls. 133234353Sdim BugReporter *RecVisitorBR; 134234353Sdim 135218887Sdimpublic: 136226633Sdim ASTContext *Ctx; 137218887Sdim const Preprocessor &PP; 138218887Sdim const std::string OutDir; 139243830Sdim AnalyzerOptionsRef Opts; 140226633Sdim ArrayRef<std::string> Plugins; 141218887Sdim 142234353Sdim /// \brief Stores the declarations from the local translation unit. 143234353Sdim /// Note, we pre-compute the local declarations at parse time as an 144234353Sdim /// optimization to make sure we do not deserialize everything from disk. 145234353Sdim /// The local declaration to all declarations ratio might be very small when 146234353Sdim /// working with a PCH file. 147234353Sdim SetOfDecls LocalTUDecls; 148239462Sdim 149239462Sdim // Set of PathDiagnosticConsumers. Owned by AnalysisManager. 150239462Sdim PathDiagnosticConsumers PathConsumers; 151234353Sdim 152218887Sdim StoreManagerCreator CreateStoreMgr; 153218887Sdim ConstraintManagerCreator CreateConstraintMgr; 154218887Sdim 155234353Sdim OwningPtr<CheckerManager> checkerMgr; 156234353Sdim OwningPtr<AnalysisManager> Mgr; 157218887Sdim 158234353Sdim /// Time the analyzes time of each translation unit. 159234353Sdim static llvm::Timer* TUTotalTimer; 160234353Sdim 161234353Sdim /// The information about analyzed functions shared throughout the 162234353Sdim /// translation unit. 163234353Sdim FunctionSummariesTy FunctionSummaries; 164234353Sdim 165218887Sdim AnalysisConsumer(const Preprocessor& pp, 166218887Sdim const std::string& outdir, 167243830Sdim AnalyzerOptionsRef opts, 168226633Sdim ArrayRef<std::string> plugins) 169243830Sdim : RecVisitorMode(0), RecVisitorBR(0), 170239462Sdim Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins) { 171218887Sdim DigestAnalyzerOptions(); 172243830Sdim if (Opts->PrintStats) { 173234353Sdim llvm::EnableStatistics(); 174234353Sdim TUTotalTimer = new llvm::Timer("Analyzer Total Time"); 175234353Sdim } 176218887Sdim } 177218887Sdim 178234353Sdim ~AnalysisConsumer() { 179243830Sdim if (Opts->PrintStats) 180234353Sdim delete TUTotalTimer; 181234353Sdim } 182234353Sdim 183218887Sdim void DigestAnalyzerOptions() { 184226633Sdim // Create the PathDiagnosticConsumer. 185239462Sdim PathConsumers.push_back(new ClangDiagPathDiagConsumer(PP.getDiagnostics())); 186239462Sdim 187218887Sdim if (!OutDir.empty()) { 188243830Sdim switch (Opts->AnalysisDiagOpt) { 189218887Sdim default: 190218887Sdim#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \ 191239462Sdim case PD_##NAME: CREATEFN(PathConsumers, OutDir, PP); break; 192243830Sdim#include "clang/StaticAnalyzer/Core/Analyses.def" 193218887Sdim } 194243830Sdim } else if (Opts->AnalysisDiagOpt == PD_TEXT) { 195218887Sdim // Create the text client even without a specified output file since 196218887Sdim // it just uses diagnostic notes. 197239462Sdim createTextPathDiagnosticConsumer(PathConsumers, "", PP); 198218887Sdim } 199218887Sdim 200218887Sdim // Create the analyzer component creators. 201243830Sdim switch (Opts->AnalysisStoreOpt) { 202218887Sdim default: 203226633Sdim llvm_unreachable("Unknown store manager."); 204218887Sdim#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ 205218887Sdim case NAME##Model: CreateStoreMgr = CREATEFN; break; 206243830Sdim#include "clang/StaticAnalyzer/Core/Analyses.def" 207218887Sdim } 208218887Sdim 209243830Sdim switch (Opts->AnalysisConstraintsOpt) { 210218887Sdim default: 211226633Sdim llvm_unreachable("Unknown store manager."); 212218887Sdim#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ 213218887Sdim case NAME##Model: CreateConstraintMgr = CREATEFN; break; 214243830Sdim#include "clang/StaticAnalyzer/Core/Analyses.def" 215218887Sdim } 216218887Sdim } 217218887Sdim 218234353Sdim void DisplayFunction(const Decl *D, AnalysisMode Mode) { 219243830Sdim if (!Opts->AnalyzerDisplayProgress) 220218887Sdim return; 221218887Sdim 222218887Sdim SourceManager &SM = Mgr->getASTContext().getSourceManager(); 223218887Sdim PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 224218887Sdim if (Loc.isValid()) { 225234353Sdim llvm::errs() << "ANALYZE"; 226243830Sdim 227243830Sdim if (Mode == AM_Syntax) 228243830Sdim llvm::errs() << " (Syntax)"; 229243830Sdim else if (Mode == AM_Path) 230243830Sdim llvm::errs() << " (Path)"; 231243830Sdim else 232243830Sdim assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!"); 233243830Sdim 234234353Sdim llvm::errs() << ": " << Loc.getFilename(); 235218887Sdim if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { 236218887Sdim const NamedDecl *ND = cast<NamedDecl>(D); 237226633Sdim llvm::errs() << ' ' << *ND << '\n'; 238218887Sdim } 239218887Sdim else if (isa<BlockDecl>(D)) { 240218887Sdim llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:" 241218887Sdim << Loc.getColumn() << '\n'; 242218887Sdim } 243218887Sdim else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 244218887Sdim Selector S = MD->getSelector(); 245218887Sdim llvm::errs() << ' ' << S.getAsString(); 246218887Sdim } 247218887Sdim } 248218887Sdim } 249218887Sdim 250218887Sdim virtual void Initialize(ASTContext &Context) { 251218887Sdim Ctx = &Context; 252243830Sdim checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins, 253226633Sdim PP.getDiagnostics())); 254239462Sdim Mgr.reset(new AnalysisManager(*Ctx, 255239462Sdim PP.getDiagnostics(), 256239462Sdim PP.getLangOpts(), 257239462Sdim PathConsumers, 258239462Sdim CreateStoreMgr, 259239462Sdim CreateConstraintMgr, 260218887Sdim checkerMgr.get(), 261243830Sdim *Opts)); 262218887Sdim } 263218887Sdim 264234353Sdim /// \brief Store the top level decls in the set to be processed later on. 265234353Sdim /// (Doing this pre-processing avoids deserialization of data from PCH.) 266234353Sdim virtual bool HandleTopLevelDecl(DeclGroupRef D); 267234353Sdim virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D); 268234353Sdim 269218887Sdim virtual void HandleTranslationUnit(ASTContext &C); 270218887Sdim 271234353Sdim /// \brief Build the call graph for all the top level decls of this TU and 272234353Sdim /// use it to define the order in which the functions should be visited. 273243830Sdim void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize); 274234353Sdim 275234353Sdim /// \brief Run analyzes(syntax or path sensitive) on the given function. 276234353Sdim /// \param Mode - determines if we are requesting syntax only or path 277234353Sdim /// sensitive only analysis. 278234353Sdim /// \param VisitedCallees - The output parameter, which is populated with the 279234353Sdim /// set of functions which should be considered analyzed after analyzing the 280234353Sdim /// given root function. 281234353Sdim void HandleCode(Decl *D, AnalysisMode Mode, 282234353Sdim SetOfConstDecls *VisitedCallees = 0); 283234353Sdim 284234353Sdim void RunPathSensitiveChecks(Decl *D, SetOfConstDecls *VisitedCallees); 285234353Sdim void ActionExprEngine(Decl *D, bool ObjCGCEnabled, 286234353Sdim SetOfConstDecls *VisitedCallees); 287234353Sdim 288234353Sdim /// Visitors for the RecursiveASTVisitor. 289239462Sdim bool shouldWalkTypesOfTypeLocs() const { return false; } 290234353Sdim 291234353Sdim /// Handle callbacks for arbitrary Decls. 292234353Sdim bool VisitDecl(Decl *D) { 293243830Sdim AnalysisMode Mode = getModeForDecl(D, RecVisitorMode); 294243830Sdim if (Mode & AM_Syntax) 295243830Sdim checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR); 296234353Sdim return true; 297234353Sdim } 298234353Sdim 299234353Sdim bool VisitFunctionDecl(FunctionDecl *FD) { 300234353Sdim IdentifierInfo *II = FD->getIdentifier(); 301234353Sdim if (II && II->getName().startswith("__inline")) 302234353Sdim return true; 303234353Sdim 304234353Sdim // We skip function template definitions, as their semantics is 305234353Sdim // only determined when they are instantiated. 306234353Sdim if (FD->isThisDeclarationADefinition() && 307234353Sdim !FD->isDependentContext()) { 308234353Sdim HandleCode(FD, RecVisitorMode); 309234353Sdim } 310234353Sdim return true; 311234353Sdim } 312234353Sdim 313234353Sdim bool VisitObjCMethodDecl(ObjCMethodDecl *MD) { 314234353Sdim if (MD->isThisDeclarationADefinition()) 315234353Sdim HandleCode(MD, RecVisitorMode); 316234353Sdim return true; 317234353Sdim } 318234353Sdim 319234353Sdimprivate: 320234353Sdim void storeTopLevelDecls(DeclGroupRef DG); 321234353Sdim 322234353Sdim /// \brief Check if we should skip (not analyze) the given function. 323243830Sdim AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode); 324234353Sdim 325218887Sdim}; 326218887Sdim} // end anonymous namespace 327218887Sdim 328234353Sdim 329218887Sdim//===----------------------------------------------------------------------===// 330218887Sdim// AnalysisConsumer implementation. 331218887Sdim//===----------------------------------------------------------------------===// 332234353Sdimllvm::Timer* AnalysisConsumer::TUTotalTimer = 0; 333218887Sdim 334234353Sdimbool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) { 335234353Sdim storeTopLevelDecls(DG); 336234353Sdim return true; 337234353Sdim} 338234353Sdim 339234353Sdimvoid AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 340234353Sdim storeTopLevelDecls(DG); 341234353Sdim} 342234353Sdim 343234353Sdimvoid AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) { 344234353Sdim for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { 345234353Sdim 346234353Sdim // Skip ObjCMethodDecl, wait for the objc container to avoid 347234353Sdim // analyzing twice. 348234353Sdim if (isa<ObjCMethodDecl>(*I)) 349234353Sdim continue; 350234353Sdim 351239462Sdim LocalTUDecls.push_back(*I); 352226633Sdim } 353226633Sdim} 354226633Sdim 355243830Sdimstatic bool shouldSkipFunction(CallGraphNode *N, 356243830Sdim SmallPtrSet<CallGraphNode*,24> Visited) { 357243830Sdim // We want to re-analyse the functions as top level in several cases: 358243830Sdim // - The 'init' methods should be reanalyzed because 359243830Sdim // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns 360243830Sdim // 'nil' and unless we analyze the 'init' functions as top level, we will not 361243830Sdim // catch errors within defensive code. 362243830Sdim // - We want to reanalyze all ObjC methods as top level to report Retain 363243830Sdim // Count naming convention errors more aggressively. 364243830Sdim if (isa<ObjCMethodDecl>(N->getDecl())) 365243830Sdim return false; 366243830Sdim 367243830Sdim // Otherwise, if we visited the function before, do not reanalyze it. 368243830Sdim return Visited.count(N); 369243830Sdim} 370243830Sdim 371243830Sdimvoid AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) { 372234353Sdim // Otherwise, use the Callgraph to derive the order. 373234353Sdim // Build the Call Graph. 374234353Sdim CallGraph CG; 375239462Sdim 376234353Sdim // Add all the top level declarations to the graph. 377239462Sdim // Note: CallGraph can trigger deserialization of more items from a pch 378239462Sdim // (though HandleInterestingDecl); triggering additions to LocalTUDecls. 379239462Sdim // We rely on random access to add the initially processed Decls to CG. 380239462Sdim for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 381239462Sdim CG.addToCallGraph(LocalTUDecls[i]); 382239462Sdim } 383234353Sdim 384234353Sdim // Find the top level nodes - children of root + the unreachable (parentless) 385234353Sdim // nodes. 386234353Sdim llvm::SmallVector<CallGraphNode*, 24> TopLevelFunctions; 387234353Sdim for (CallGraph::nodes_iterator TI = CG.parentless_begin(), 388234353Sdim TE = CG.parentless_end(); TI != TE; ++TI) { 389234353Sdim TopLevelFunctions.push_back(*TI); 390234353Sdim NumFunctionTopLevel++; 391226633Sdim } 392234353Sdim CallGraphNode *Entry = CG.getRoot(); 393234353Sdim for (CallGraphNode::iterator I = Entry->begin(), 394234353Sdim E = Entry->end(); I != E; ++I) { 395234353Sdim TopLevelFunctions.push_back(*I); 396234353Sdim NumFunctionTopLevel++; 397234353Sdim } 398218887Sdim 399234353Sdim // Make sure the nodes are sorted in order reverse of their definition in the 400234353Sdim // translation unit. This step is very important for performance. It ensures 401234353Sdim // that we analyze the root functions before the externally available 402234353Sdim // subroutines. 403239462Sdim std::deque<CallGraphNode*> BFSQueue; 404234353Sdim for (llvm::SmallVector<CallGraphNode*, 24>::reverse_iterator 405234353Sdim TI = TopLevelFunctions.rbegin(), TE = TopLevelFunctions.rend(); 406234353Sdim TI != TE; ++TI) 407239462Sdim BFSQueue.push_back(*TI); 408234353Sdim 409234353Sdim // BFS over all of the functions, while skipping the ones inlined into 410234353Sdim // the previously processed functions. Use external Visited set, which is 411234353Sdim // also modified when we inline a function. 412234353Sdim SmallPtrSet<CallGraphNode*,24> Visited; 413234353Sdim while(!BFSQueue.empty()) { 414234353Sdim CallGraphNode *N = BFSQueue.front(); 415239462Sdim BFSQueue.pop_front(); 416234353Sdim 417239462Sdim // Push the children into the queue. 418239462Sdim for (CallGraphNode::const_iterator CI = N->begin(), 419239462Sdim CE = N->end(); CI != CE; ++CI) { 420243830Sdim if (!shouldSkipFunction(*CI, Visited)) 421239462Sdim BFSQueue.push_back(*CI); 422239462Sdim } 423239462Sdim 424234353Sdim // Skip the functions which have been processed already or previously 425234353Sdim // inlined. 426243830Sdim if (shouldSkipFunction(N, Visited)) 427234353Sdim continue; 428234353Sdim 429234353Sdim // Analyze the function. 430234353Sdim SetOfConstDecls VisitedCallees; 431234353Sdim Decl *D = N->getDecl(); 432234353Sdim assert(D); 433243830Sdim HandleCode(D, AM_Path, 434243830Sdim (Mgr->options.InliningMode == All ? 0 : &VisitedCallees)); 435234353Sdim 436234353Sdim // Add the visited callees to the global visited set. 437239462Sdim for (SetOfConstDecls::iterator I = VisitedCallees.begin(), 438239462Sdim E = VisitedCallees.end(); I != E; ++I) { 439234353Sdim CallGraphNode *VN = CG.getNode(*I); 440234353Sdim if (VN) 441234353Sdim Visited.insert(VN); 442226633Sdim } 443234353Sdim Visited.insert(N); 444226633Sdim } 445218887Sdim} 446218887Sdim 447218887Sdimvoid AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 448234353Sdim // Don't run the actions if an error has occurred with parsing the file. 449234353Sdim DiagnosticsEngine &Diags = PP.getDiagnostics(); 450234353Sdim if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 451234353Sdim return; 452218887Sdim 453234353Sdim { 454234353Sdim if (TUTotalTimer) TUTotalTimer->startTimer(); 455223017Sdim 456234353Sdim // Introduce a scope to destroy BR before Mgr. 457234353Sdim BugReporter BR(*Mgr); 458234353Sdim TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 459234353Sdim checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 460234353Sdim 461234353Sdim // Run the AST-only checks using the order in which functions are defined. 462234353Sdim // If inlining is not turned on, use the simplest function order for path 463234353Sdim // sensitive analyzes as well. 464243830Sdim RecVisitorMode = AM_Syntax; 465243830Sdim if (!Mgr->shouldInlineCall()) 466243830Sdim RecVisitorMode |= AM_Path; 467234353Sdim RecVisitorBR = &BR; 468234353Sdim 469234353Sdim // Process all the top level declarations. 470239462Sdim // 471239462Sdim // Note: TraverseDecl may modify LocalTUDecls, but only by appending more 472239462Sdim // entries. Thus we don't use an iterator, but rely on LocalTUDecls 473239462Sdim // random access. By doing so, we automatically compensate for iterators 474239462Sdim // possibly being invalidated, although this is a bit slower. 475239462Sdim const unsigned LocalTUDeclsSize = LocalTUDecls.size(); 476239462Sdim for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 477239462Sdim TraverseDecl(LocalTUDecls[i]); 478239462Sdim } 479234353Sdim 480234353Sdim if (Mgr->shouldInlineCall()) 481243830Sdim HandleDeclsCallGraph(LocalTUDeclsSize); 482234353Sdim 483234353Sdim // After all decls handled, run checkers on the entire TranslationUnit. 484234353Sdim checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 485234353Sdim 486234353Sdim RecVisitorBR = 0; 487234353Sdim } 488234353Sdim 489226633Sdim // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 490218887Sdim // FIXME: This should be replaced with something that doesn't rely on 491226633Sdim // side-effects in PathDiagnosticConsumer's destructor. This is required when 492218887Sdim // used with option -disable-free. 493218887Sdim Mgr.reset(NULL); 494234353Sdim 495234353Sdim if (TUTotalTimer) TUTotalTimer->stopTimer(); 496234353Sdim 497234353Sdim // Count how many basic blocks we have not covered. 498234353Sdim NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks(); 499234353Sdim if (NumBlocksInAnalyzedFunctions > 0) 500234353Sdim PercentReachableBlocks = 501234353Sdim (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) / 502234353Sdim NumBlocksInAnalyzedFunctions; 503234353Sdim 504218887Sdim} 505218887Sdim 506226633Sdimstatic void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) { 507218887Sdim if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) 508218887Sdim WL.push_back(BD); 509218887Sdim 510218887Sdim for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 511218887Sdim I!=E; ++I) 512218887Sdim if (DeclContext *DC = dyn_cast<DeclContext>(*I)) 513218887Sdim FindBlocks(DC, WL); 514218887Sdim} 515218887Sdim 516234353Sdimstatic std::string getFunctionName(const Decl *D) { 517234353Sdim if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) { 518234353Sdim return ID->getSelector().getAsString(); 519234353Sdim } 520234353Sdim if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) { 521234353Sdim IdentifierInfo *II = ND->getIdentifier(); 522234353Sdim if (II) 523234353Sdim return II->getName(); 524234353Sdim } 525234353Sdim return ""; 526234353Sdim} 527218887Sdim 528243830SdimAnalysisConsumer::AnalysisMode 529243830SdimAnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) { 530243830Sdim if (!Opts->AnalyzeSpecificFunction.empty() && 531243830Sdim getFunctionName(D) != Opts->AnalyzeSpecificFunction) 532243830Sdim return AM_None; 533221345Sdim 534243830Sdim // Unless -analyze-all is specified, treat decls differently depending on 535243830Sdim // where they came from: 536243830Sdim // - Main source file: run both path-sensitive and non-path-sensitive checks. 537243830Sdim // - Header files: run non-path-sensitive checks only. 538243830Sdim // - System headers: don't run any checks. 539218887Sdim SourceManager &SM = Ctx->getSourceManager(); 540226633Sdim SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 541243830Sdim if (!Opts->AnalyzeAll && !SM.isFromMainFile(SL)) { 542243830Sdim if (SL.isInvalid() || SM.isInSystemHeader(SL)) 543243830Sdim return AM_None; 544243830Sdim return Mode & ~AM_Path; 545243830Sdim } 546234353Sdim 547243830Sdim return Mode; 548234353Sdim} 549234353Sdim 550234353Sdimvoid AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode, 551234353Sdim SetOfConstDecls *VisitedCallees) { 552243830Sdim Mode = getModeForDecl(D, Mode); 553243830Sdim if (Mode == AM_None) 554218887Sdim return; 555218887Sdim 556234353Sdim DisplayFunction(D, Mode); 557239462Sdim CFG *DeclCFG = Mgr->getCFG(D); 558239462Sdim if (DeclCFG) { 559239462Sdim unsigned CFGSize = DeclCFG->size(); 560239462Sdim MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize; 561239462Sdim } 562234353Sdim 563239462Sdim 564234353Sdim // Clear the AnalysisManager of old AnalysisDeclContexts. 565218887Sdim Mgr->ClearContexts(); 566218887Sdim 567218887Sdim // Dispatch on the actions. 568226633Sdim SmallVector<Decl*, 10> WL; 569218887Sdim WL.push_back(D); 570218887Sdim 571243830Sdim if (D->hasBody() && Opts->AnalyzeNestedBlocks) 572218887Sdim FindBlocks(cast<DeclContext>(D), WL); 573218887Sdim 574218887Sdim BugReporter BR(*Mgr); 575226633Sdim for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end(); 576218887Sdim WI != WE; ++WI) 577221345Sdim if ((*WI)->hasBody()) { 578243830Sdim if (Mode & AM_Syntax) 579234353Sdim checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR); 580243830Sdim if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) { 581234353Sdim RunPathSensitiveChecks(*WI, VisitedCallees); 582234353Sdim NumFunctionsAnalyzed++; 583234353Sdim } 584221345Sdim } 585218887Sdim} 586218887Sdim 587218887Sdim//===----------------------------------------------------------------------===// 588221345Sdim// Path-sensitive checking. 589218887Sdim//===----------------------------------------------------------------------===// 590218887Sdim 591234353Sdimvoid AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled, 592234353Sdim SetOfConstDecls *VisitedCallees) { 593226633Sdim // Construct the analysis engine. First check if the CFG is valid. 594218887Sdim // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 595234353Sdim if (!Mgr->getCFG(D)) 596218887Sdim return; 597218887Sdim 598239462Sdim // See if the LiveVariables analysis scales. 599239462Sdim if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>()) 600239462Sdim return; 601239462Sdim 602234353Sdim ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries); 603234353Sdim 604218887Sdim // Set the graph auditor. 605234353Sdim OwningPtr<ExplodedNode::Auditor> Auditor; 606243830Sdim if (Mgr->options.visualizeExplodedGraphWithUbiGraph) { 607218887Sdim Auditor.reset(CreateUbiViz()); 608218887Sdim ExplodedNode::SetAuditor(Auditor.get()); 609218887Sdim } 610218887Sdim 611218887Sdim // Execute the worklist algorithm. 612239462Sdim Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D), 613243830Sdim Mgr->options.MaxNodes); 614218887Sdim 615218887Sdim // Release the auditor (if any) so that it doesn't monitor the graph 616218887Sdim // created BugReporter. 617218887Sdim ExplodedNode::SetAuditor(0); 618218887Sdim 619218887Sdim // Visualize the exploded graph. 620243830Sdim if (Mgr->options.visualizeExplodedGraphWithGraphViz) 621243830Sdim Eng.ViewGraph(Mgr->options.TrimGraph); 622218887Sdim 623218887Sdim // Display warnings. 624218887Sdim Eng.getBugReporter().FlushReports(); 625218887Sdim} 626218887Sdim 627234353Sdimvoid AnalysisConsumer::RunPathSensitiveChecks(Decl *D, 628234353Sdim SetOfConstDecls *Visited) { 629218887Sdim 630234353Sdim switch (Mgr->getLangOpts().getGC()) { 631226633Sdim case LangOptions::NonGC: 632234353Sdim ActionExprEngine(D, false, Visited); 633226633Sdim break; 634226633Sdim 635226633Sdim case LangOptions::GCOnly: 636234353Sdim ActionExprEngine(D, true, Visited); 637226633Sdim break; 638226633Sdim 639226633Sdim case LangOptions::HybridGC: 640234353Sdim ActionExprEngine(D, false, Visited); 641234353Sdim ActionExprEngine(D, true, Visited); 642226633Sdim break; 643226633Sdim } 644218887Sdim} 645218887Sdim 646218887Sdim//===----------------------------------------------------------------------===// 647218887Sdim// AnalysisConsumer creation. 648218887Sdim//===----------------------------------------------------------------------===// 649218887Sdim 650218887SdimASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 651226633Sdim const std::string& outDir, 652243830Sdim AnalyzerOptionsRef opts, 653226633Sdim ArrayRef<std::string> plugins) { 654226633Sdim // Disable the effects of '-Werror' when using the AnalysisConsumer. 655218887Sdim pp.getDiagnostics().setWarningsAsErrors(false); 656218887Sdim 657226633Sdim return new AnalysisConsumer(pp, outDir, opts, plugins); 658218887Sdim} 659218887Sdim 660218887Sdim//===----------------------------------------------------------------------===// 661218887Sdim// Ubigraph Visualization. FIXME: Move to separate file. 662218887Sdim//===----------------------------------------------------------------------===// 663218887Sdim 664218887Sdimnamespace { 665218887Sdim 666218887Sdimclass UbigraphViz : public ExplodedNode::Auditor { 667234353Sdim OwningPtr<raw_ostream> Out; 668218887Sdim llvm::sys::Path Dir, Filename; 669218887Sdim unsigned Cntr; 670218887Sdim 671218887Sdim typedef llvm::DenseMap<void*,unsigned> VMap; 672218887Sdim VMap M; 673218887Sdim 674218887Sdimpublic: 675226633Sdim UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 676218887Sdim llvm::sys::Path& filename); 677218887Sdim 678218887Sdim ~UbigraphViz(); 679218887Sdim 680226633Sdim virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst); 681218887Sdim}; 682218887Sdim 683218887Sdim} // end anonymous namespace 684218887Sdim 685218887Sdimstatic ExplodedNode::Auditor* CreateUbiViz() { 686218887Sdim std::string ErrMsg; 687218887Sdim 688218887Sdim llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); 689218887Sdim if (!ErrMsg.empty()) 690218887Sdim return 0; 691218887Sdim 692218887Sdim llvm::sys::Path Filename = Dir; 693218887Sdim Filename.appendComponent("llvm_ubi"); 694218887Sdim Filename.makeUnique(true,&ErrMsg); 695218887Sdim 696218887Sdim if (!ErrMsg.empty()) 697218887Sdim return 0; 698218887Sdim 699218887Sdim llvm::errs() << "Writing '" << Filename.str() << "'.\n"; 700218887Sdim 701234353Sdim OwningPtr<llvm::raw_fd_ostream> Stream; 702218887Sdim Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); 703218887Sdim 704218887Sdim if (!ErrMsg.empty()) 705218887Sdim return 0; 706218887Sdim 707218887Sdim return new UbigraphViz(Stream.take(), Dir, Filename); 708218887Sdim} 709218887Sdim 710226633Sdimvoid UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 711218887Sdim 712218887Sdim assert (Src != Dst && "Self-edges are not allowed."); 713218887Sdim 714218887Sdim // Lookup the Src. If it is a new node, it's a root. 715218887Sdim VMap::iterator SrcI= M.find(Src); 716218887Sdim unsigned SrcID; 717218887Sdim 718218887Sdim if (SrcI == M.end()) { 719218887Sdim M[Src] = SrcID = Cntr++; 720218887Sdim *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 721218887Sdim } 722218887Sdim else 723218887Sdim SrcID = SrcI->second; 724218887Sdim 725218887Sdim // Lookup the Dst. 726218887Sdim VMap::iterator DstI= M.find(Dst); 727218887Sdim unsigned DstID; 728218887Sdim 729218887Sdim if (DstI == M.end()) { 730218887Sdim M[Dst] = DstID = Cntr++; 731218887Sdim *Out << "('vertex', " << DstID << ")\n"; 732218887Sdim } 733218887Sdim else { 734218887Sdim // We have hit DstID before. Change its style to reflect a cache hit. 735218887Sdim DstID = DstI->second; 736218887Sdim *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 737218887Sdim } 738218887Sdim 739218887Sdim // Add the edge. 740218887Sdim *Out << "('edge', " << SrcID << ", " << DstID 741218887Sdim << ", ('arrow','true'), ('oriented', 'true'))\n"; 742218887Sdim} 743218887Sdim 744226633SdimUbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 745218887Sdim llvm::sys::Path& filename) 746218887Sdim : Out(out), Dir(dir), Filename(filename), Cntr(0) { 747218887Sdim 748218887Sdim *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 749218887Sdim *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 750218887Sdim " ('size', '1.5'))\n"; 751218887Sdim} 752218887Sdim 753218887SdimUbigraphViz::~UbigraphViz() { 754218887Sdim Out.reset(0); 755218887Sdim llvm::errs() << "Running 'ubiviz' program... "; 756218887Sdim std::string ErrMsg; 757218887Sdim llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); 758218887Sdim std::vector<const char*> args; 759218887Sdim args.push_back(Ubiviz.c_str()); 760218887Sdim args.push_back(Filename.c_str()); 761218887Sdim args.push_back(0); 762218887Sdim 763218887Sdim if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { 764218887Sdim llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 765218887Sdim } 766218887Sdim 767218887Sdim // Delete the directory. 768218887Sdim Dir.eraseFromDisk(true); 769218887Sdim} 770