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