AnalysisConsumer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // "Meta" ASTConsumer for running different source analyses.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/AnalysisConsumer.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/ParentMap.h"
  19. #include "clang/Analysis/Analyses/LiveVariables.h"
  20. #include "clang/Analysis/Analyses/UninitializedValues.h"
  21. #include "clang/Analysis/CFG.h"
  22. #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
  23. #include "clang/StaticAnalyzer/ManagerRegistry.h"
  24. #include "clang/StaticAnalyzer/BugReporter/PathDiagnostic.h"
  25. #include "clang/StaticAnalyzer/PathSensitive/AnalysisManager.h"
  26. #include "clang/StaticAnalyzer/BugReporter/BugReporter.h"
  27. #include "clang/StaticAnalyzer/PathSensitive/ExprEngine.h"
  28. #include "clang/StaticAnalyzer/PathSensitive/TransferFuncs.h"
  29. #include "clang/StaticAnalyzer/PathDiagnosticClients.h"
  30. // FIXME: Restructure checker registration.
  31. #include "ExprEngineExperimentalChecks.h"
  32. #include "InternalChecks.h"
  33. #include "clang/Basic/FileManager.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Frontend/AnalyzerOptions.h"
  36. #include "clang/Lex/Preprocessor.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Support/Path.h"
  39. #include "llvm/Support/Program.h"
  40. #include "llvm/ADT/OwningPtr.h"
  41. using namespace clang;
  42. using namespace ento;
  43. static ExplodedNode::Auditor* CreateUbiViz();
  44. //===----------------------------------------------------------------------===//
  45. // Special PathDiagnosticClients.
  46. //===----------------------------------------------------------------------===//
  47. static PathDiagnosticClient*
  48. createPlistHTMLDiagnosticClient(const std::string& prefix,
  49. const Preprocessor &PP) {
  50. PathDiagnosticClient *PD =
  51. createHTMLDiagnosticClient(llvm::sys::path::parent_path(prefix), PP);
  52. return createPlistDiagnosticClient(prefix, PP, PD);
  53. }
  54. //===----------------------------------------------------------------------===//
  55. // AnalysisConsumer declaration.
  56. //===----------------------------------------------------------------------===//
  57. namespace {
  58. class AnalysisConsumer : public ASTConsumer {
  59. public:
  60. typedef void (*CodeAction)(AnalysisConsumer &C, AnalysisManager &M, Decl *D);
  61. typedef void (*TUAction)(AnalysisConsumer &C, AnalysisManager &M,
  62. TranslationUnitDecl &TU);
  63. private:
  64. typedef std::vector<CodeAction> Actions;
  65. typedef std::vector<TUAction> TUActions;
  66. Actions FunctionActions;
  67. Actions ObjCMethodActions;
  68. Actions ObjCImplementationActions;
  69. Actions CXXMethodActions;
  70. TUActions TranslationUnitActions; // Remove this.
  71. public:
  72. ASTContext* Ctx;
  73. const Preprocessor &PP;
  74. const std::string OutDir;
  75. AnalyzerOptions Opts;
  76. // PD is owned by AnalysisManager.
  77. PathDiagnosticClient *PD;
  78. StoreManagerCreator CreateStoreMgr;
  79. ConstraintManagerCreator CreateConstraintMgr;
  80. llvm::OwningPtr<AnalysisManager> Mgr;
  81. AnalysisConsumer(const Preprocessor& pp,
  82. const std::string& outdir,
  83. const AnalyzerOptions& opts)
  84. : Ctx(0), PP(pp), OutDir(outdir),
  85. Opts(opts), PD(0) {
  86. DigestAnalyzerOptions();
  87. }
  88. void DigestAnalyzerOptions() {
  89. // Create the PathDiagnosticClient.
  90. if (!OutDir.empty()) {
  91. switch (Opts.AnalysisDiagOpt) {
  92. default:
  93. #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
  94. case PD_##NAME: PD = CREATEFN(OutDir, PP); break;
  95. #include "clang/Frontend/Analyses.def"
  96. }
  97. } else if (Opts.AnalysisDiagOpt == PD_TEXT) {
  98. // Create the text client even without a specified output file since
  99. // it just uses diagnostic notes.
  100. PD = createTextPathDiagnosticClient("", PP);
  101. }
  102. // Create the analyzer component creators.
  103. if (ManagerRegistry::StoreMgrCreator != 0) {
  104. CreateStoreMgr = ManagerRegistry::StoreMgrCreator;
  105. }
  106. else {
  107. switch (Opts.AnalysisStoreOpt) {
  108. default:
  109. assert(0 && "Unknown store manager.");
  110. #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
  111. case NAME##Model: CreateStoreMgr = CREATEFN; break;
  112. #include "clang/Frontend/Analyses.def"
  113. }
  114. }
  115. if (ManagerRegistry::ConstraintMgrCreator != 0)
  116. CreateConstraintMgr = ManagerRegistry::ConstraintMgrCreator;
  117. else {
  118. switch (Opts.AnalysisConstraintsOpt) {
  119. default:
  120. assert(0 && "Unknown store manager.");
  121. #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
  122. case NAME##Model: CreateConstraintMgr = CREATEFN; break;
  123. #include "clang/Frontend/Analyses.def"
  124. }
  125. }
  126. }
  127. void DisplayFunction(const Decl *D) {
  128. if (!Opts.AnalyzerDisplayProgress)
  129. return;
  130. SourceManager &SM = Mgr->getASTContext().getSourceManager();
  131. PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
  132. if (Loc.isValid()) {
  133. llvm::errs() << "ANALYZE: " << Loc.getFilename();
  134. if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
  135. const NamedDecl *ND = cast<NamedDecl>(D);
  136. llvm::errs() << ' ' << ND << '\n';
  137. }
  138. else if (isa<BlockDecl>(D)) {
  139. llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
  140. << Loc.getColumn() << '\n';
  141. }
  142. else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  143. Selector S = MD->getSelector();
  144. llvm::errs() << ' ' << S.getAsString();
  145. }
  146. }
  147. }
  148. void addCodeAction(CodeAction action) {
  149. FunctionActions.push_back(action);
  150. ObjCMethodActions.push_back(action);
  151. CXXMethodActions.push_back(action);
  152. }
  153. void addTranslationUnitAction(TUAction action) {
  154. TranslationUnitActions.push_back(action);
  155. }
  156. void addObjCImplementationAction(CodeAction action) {
  157. ObjCImplementationActions.push_back(action);
  158. }
  159. virtual void Initialize(ASTContext &Context) {
  160. Ctx = &Context;
  161. Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(),
  162. PP.getLangOptions(), PD,
  163. CreateStoreMgr, CreateConstraintMgr,
  164. /* Indexer */ 0,
  165. Opts.MaxNodes, Opts.MaxLoop,
  166. Opts.VisualizeEGDot, Opts.VisualizeEGUbi,
  167. Opts.PurgeDead, Opts.EagerlyAssume,
  168. Opts.TrimGraph, Opts.InlineCall,
  169. Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors,
  170. Opts.CFGAddInitializers));
  171. }
  172. virtual void HandleTranslationUnit(ASTContext &C);
  173. void HandleDeclContext(ASTContext &C, DeclContext *dc);
  174. void HandleCode(Decl *D, Actions& actions);
  175. };
  176. } // end anonymous namespace
  177. //===----------------------------------------------------------------------===//
  178. // AnalysisConsumer implementation.
  179. //===----------------------------------------------------------------------===//
  180. void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
  181. for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
  182. I != E; ++I) {
  183. Decl *D = *I;
  184. switch (D->getKind()) {
  185. case Decl::Namespace: {
  186. HandleDeclContext(C, cast<NamespaceDecl>(D));
  187. break;
  188. }
  189. case Decl::CXXConstructor:
  190. case Decl::CXXDestructor:
  191. case Decl::CXXConversion:
  192. case Decl::CXXMethod:
  193. case Decl::Function: {
  194. FunctionDecl* FD = cast<FunctionDecl>(D);
  195. // We skip function template definitions, as their semantics is
  196. // only determined when they are instantiated.
  197. if (FD->isThisDeclarationADefinition() &&
  198. !FD->isDependentContext()) {
  199. if (!Opts.AnalyzeSpecificFunction.empty() &&
  200. FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
  201. break;
  202. DisplayFunction(FD);
  203. HandleCode(FD, FunctionActions);
  204. }
  205. break;
  206. }
  207. case Decl::ObjCImplementation: {
  208. ObjCImplementationDecl* ID = cast<ObjCImplementationDecl>(*I);
  209. HandleCode(ID, ObjCImplementationActions);
  210. for (ObjCImplementationDecl::method_iterator MI = ID->meth_begin(),
  211. ME = ID->meth_end(); MI != ME; ++MI) {
  212. if ((*MI)->isThisDeclarationADefinition()) {
  213. if (!Opts.AnalyzeSpecificFunction.empty() &&
  214. Opts.AnalyzeSpecificFunction != (*MI)->getSelector().getAsString())
  215. break;
  216. DisplayFunction(*MI);
  217. HandleCode(*MI, ObjCMethodActions);
  218. }
  219. }
  220. break;
  221. }
  222. default:
  223. break;
  224. }
  225. }
  226. }
  227. void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
  228. TranslationUnitDecl *TU = C.getTranslationUnitDecl();
  229. HandleDeclContext(C, TU);
  230. for (TUActions::iterator I = TranslationUnitActions.begin(),
  231. E = TranslationUnitActions.end(); I != E; ++I) {
  232. (*I)(*this, *Mgr, *TU);
  233. }
  234. // Explicitly destroy the PathDiagnosticClient. This will flush its output.
  235. // FIXME: This should be replaced with something that doesn't rely on
  236. // side-effects in PathDiagnosticClient's destructor. This is required when
  237. // used with option -disable-free.
  238. Mgr.reset(NULL);
  239. }
  240. static void FindBlocks(DeclContext *D, llvm::SmallVectorImpl<Decl*> &WL) {
  241. if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
  242. WL.push_back(BD);
  243. for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
  244. I!=E; ++I)
  245. if (DeclContext *DC = dyn_cast<DeclContext>(*I))
  246. FindBlocks(DC, WL);
  247. }
  248. void AnalysisConsumer::HandleCode(Decl *D, Actions& actions) {
  249. // Don't run the actions if an error has occured with parsing the file.
  250. Diagnostic &Diags = PP.getDiagnostics();
  251. if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
  252. return;
  253. // Don't run the actions on declarations in header files unless
  254. // otherwise specified.
  255. SourceManager &SM = Ctx->getSourceManager();
  256. SourceLocation SL = SM.getInstantiationLoc(D->getLocation());
  257. if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
  258. return;
  259. // Clear the AnalysisManager of old AnalysisContexts.
  260. Mgr->ClearContexts();
  261. // Dispatch on the actions.
  262. llvm::SmallVector<Decl*, 10> WL;
  263. WL.push_back(D);
  264. if (D->hasBody() && Opts.AnalyzeNestedBlocks)
  265. FindBlocks(cast<DeclContext>(D), WL);
  266. for (Actions::iterator I = actions.begin(), E = actions.end(); I != E; ++I)
  267. for (llvm::SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
  268. WI != WE; ++WI)
  269. (*I)(*this, *Mgr, *WI);
  270. }
  271. //===----------------------------------------------------------------------===//
  272. // Analyses
  273. //===----------------------------------------------------------------------===//
  274. static void ActionWarnDeadStores(AnalysisConsumer &C, AnalysisManager& mgr,
  275. Decl *D) {
  276. if (LiveVariables *L = mgr.getLiveVariables(D)) {
  277. BugReporter BR(mgr);
  278. CheckDeadStores(*mgr.getCFG(D), *L, mgr.getParentMap(D), BR);
  279. }
  280. }
  281. static void ActionWarnUninitVals(AnalysisConsumer &C, AnalysisManager& mgr,
  282. Decl *D) {
  283. if (CFG* c = mgr.getCFG(D)) {
  284. CheckUninitializedValues(*c, mgr.getASTContext(), mgr.getDiagnostic());
  285. }
  286. }
  287. static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr,
  288. Decl *D,
  289. TransferFuncs* tf) {
  290. llvm::OwningPtr<TransferFuncs> TF(tf);
  291. // Construct the analysis engine. We first query for the LiveVariables
  292. // information to see if the CFG is valid.
  293. // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
  294. if (!mgr.getLiveVariables(D))
  295. return;
  296. ExprEngine Eng(mgr, TF.take());
  297. if (C.Opts.EnableExperimentalInternalChecks)
  298. RegisterExperimentalInternalChecks(Eng);
  299. RegisterAppleChecks(Eng, *D);
  300. if (C.Opts.EnableExperimentalChecks)
  301. RegisterExperimentalChecks(Eng);
  302. if (C.Opts.ObjCSelfInitCheck && isa<ObjCMethodDecl>(D))
  303. registerObjCSelfInitChecker(Eng);
  304. // Enable idempotent operation checking if it was explicitly turned on, or if
  305. // we are running experimental checks (i.e. everything)
  306. if (C.Opts.IdempotentOps || C.Opts.EnableExperimentalChecks
  307. || C.Opts.EnableExperimentalInternalChecks)
  308. RegisterIdempotentOperationChecker(Eng);
  309. if (C.Opts.BufferOverflows)
  310. RegisterArrayBoundCheckerV2(Eng);
  311. // Enable AnalyzerStatsChecker if it was given as an argument
  312. if (C.Opts.AnalyzerStats)
  313. RegisterAnalyzerStatsChecker(Eng);
  314. // Set the graph auditor.
  315. llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
  316. if (mgr.shouldVisualizeUbigraph()) {
  317. Auditor.reset(CreateUbiViz());
  318. ExplodedNode::SetAuditor(Auditor.get());
  319. }
  320. // Execute the worklist algorithm.
  321. Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
  322. // Release the auditor (if any) so that it doesn't monitor the graph
  323. // created BugReporter.
  324. ExplodedNode::SetAuditor(0);
  325. // Visualize the exploded graph.
  326. if (mgr.shouldVisualizeGraphviz())
  327. Eng.ViewGraph(mgr.shouldTrimGraph());
  328. // Display warnings.
  329. Eng.getBugReporter().FlushReports();
  330. }
  331. static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr,
  332. Decl *D, bool GCEnabled) {
  333. TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(),
  334. GCEnabled,
  335. mgr.getLangOptions());
  336. ActionExprEngine(C, mgr, D, TF);
  337. }
  338. static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
  339. Decl *D) {
  340. switch (mgr.getLangOptions().getGCMode()) {
  341. default:
  342. assert (false && "Invalid GC mode.");
  343. case LangOptions::NonGC:
  344. ActionObjCMemCheckerAux(C, mgr, D, false);
  345. break;
  346. case LangOptions::GCOnly:
  347. ActionObjCMemCheckerAux(C, mgr, D, true);
  348. break;
  349. case LangOptions::HybridGC:
  350. ActionObjCMemCheckerAux(C, mgr, D, false);
  351. ActionObjCMemCheckerAux(C, mgr, D, true);
  352. break;
  353. }
  354. }
  355. static void ActionDisplayLiveVariables(AnalysisConsumer &C,
  356. AnalysisManager& mgr, Decl *D) {
  357. if (LiveVariables* L = mgr.getLiveVariables(D)) {
  358. L->dumpBlockLiveness(mgr.getSourceManager());
  359. }
  360. }
  361. static void ActionCFGDump(AnalysisConsumer &C, AnalysisManager& mgr, Decl *D) {
  362. if (CFG *cfg = mgr.getCFG(D)) {
  363. cfg->dump(mgr.getLangOptions());
  364. }
  365. }
  366. static void ActionCFGView(AnalysisConsumer &C, AnalysisManager& mgr, Decl *D) {
  367. if (CFG *cfg = mgr.getCFG(D)) {
  368. cfg->viewCFG(mgr.getLangOptions());
  369. }
  370. }
  371. static void ActionSecuritySyntacticChecks(AnalysisConsumer &C,
  372. AnalysisManager &mgr, Decl *D) {
  373. BugReporter BR(mgr);
  374. CheckSecuritySyntaxOnly(D, BR);
  375. }
  376. static void ActionLLVMConventionChecker(AnalysisConsumer &C,
  377. AnalysisManager &mgr,
  378. TranslationUnitDecl &TU) {
  379. BugReporter BR(mgr);
  380. CheckLLVMConventions(TU, BR);
  381. }
  382. static void ActionWarnObjCDealloc(AnalysisConsumer &C, AnalysisManager& mgr,
  383. Decl *D) {
  384. if (mgr.getLangOptions().getGCMode() == LangOptions::GCOnly)
  385. return;
  386. BugReporter BR(mgr);
  387. CheckObjCDealloc(cast<ObjCImplementationDecl>(D), mgr.getLangOptions(), BR);
  388. }
  389. static void ActionWarnObjCUnusedIvars(AnalysisConsumer &C, AnalysisManager& mgr,
  390. Decl *D) {
  391. BugReporter BR(mgr);
  392. CheckObjCUnusedIvar(cast<ObjCImplementationDecl>(D), BR);
  393. }
  394. static void ActionWarnObjCMethSigs(AnalysisConsumer &C, AnalysisManager& mgr,
  395. Decl *D) {
  396. BugReporter BR(mgr);
  397. CheckObjCInstMethSignature(cast<ObjCImplementationDecl>(D), BR);
  398. }
  399. static void ActionWarnSizeofPointer(AnalysisConsumer &C, AnalysisManager &mgr,
  400. Decl *D) {
  401. BugReporter BR(mgr);
  402. CheckSizeofPointer(D, BR);
  403. }
  404. //===----------------------------------------------------------------------===//
  405. // AnalysisConsumer creation.
  406. //===----------------------------------------------------------------------===//
  407. ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
  408. const std::string& OutDir,
  409. const AnalyzerOptions& Opts) {
  410. llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts));
  411. for (unsigned i = 0; i < Opts.AnalysisList.size(); ++i)
  412. switch (Opts.AnalysisList[i]) {
  413. #define ANALYSIS(NAME, CMD, DESC, SCOPE)\
  414. case NAME:\
  415. C->add ## SCOPE ## Action(&Action ## NAME);\
  416. break;
  417. #include "clang/Frontend/Analyses.def"
  418. default: break;
  419. }
  420. // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
  421. pp.getDiagnostics().setWarningsAsErrors(false);
  422. return C.take();
  423. }
  424. //===----------------------------------------------------------------------===//
  425. // Ubigraph Visualization. FIXME: Move to separate file.
  426. //===----------------------------------------------------------------------===//
  427. namespace {
  428. class UbigraphViz : public ExplodedNode::Auditor {
  429. llvm::OwningPtr<llvm::raw_ostream> Out;
  430. llvm::sys::Path Dir, Filename;
  431. unsigned Cntr;
  432. typedef llvm::DenseMap<void*,unsigned> VMap;
  433. VMap M;
  434. public:
  435. UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
  436. llvm::sys::Path& filename);
  437. ~UbigraphViz();
  438. virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst);
  439. };
  440. } // end anonymous namespace
  441. static ExplodedNode::Auditor* CreateUbiViz() {
  442. std::string ErrMsg;
  443. llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
  444. if (!ErrMsg.empty())
  445. return 0;
  446. llvm::sys::Path Filename = Dir;
  447. Filename.appendComponent("llvm_ubi");
  448. Filename.makeUnique(true,&ErrMsg);
  449. if (!ErrMsg.empty())
  450. return 0;
  451. llvm::errs() << "Writing '" << Filename.str() << "'.\n";
  452. llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
  453. Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
  454. if (!ErrMsg.empty())
  455. return 0;
  456. return new UbigraphViz(Stream.take(), Dir, Filename);
  457. }
  458. void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) {
  459. assert (Src != Dst && "Self-edges are not allowed.");
  460. // Lookup the Src. If it is a new node, it's a root.
  461. VMap::iterator SrcI= M.find(Src);
  462. unsigned SrcID;
  463. if (SrcI == M.end()) {
  464. M[Src] = SrcID = Cntr++;
  465. *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
  466. }
  467. else
  468. SrcID = SrcI->second;
  469. // Lookup the Dst.
  470. VMap::iterator DstI= M.find(Dst);
  471. unsigned DstID;
  472. if (DstI == M.end()) {
  473. M[Dst] = DstID = Cntr++;
  474. *Out << "('vertex', " << DstID << ")\n";
  475. }
  476. else {
  477. // We have hit DstID before. Change its style to reflect a cache hit.
  478. DstID = DstI->second;
  479. *Out << "('change_vertex_style', " << DstID << ", 1)\n";
  480. }
  481. // Add the edge.
  482. *Out << "('edge', " << SrcID << ", " << DstID
  483. << ", ('arrow','true'), ('oriented', 'true'))\n";
  484. }
  485. UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
  486. llvm::sys::Path& filename)
  487. : Out(out), Dir(dir), Filename(filename), Cntr(0) {
  488. *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
  489. *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
  490. " ('size', '1.5'))\n";
  491. }
  492. UbigraphViz::~UbigraphViz() {
  493. Out.reset(0);
  494. llvm::errs() << "Running 'ubiviz' program... ";
  495. std::string ErrMsg;
  496. llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
  497. std::vector<const char*> args;
  498. args.push_back(Ubiviz.c_str());
  499. args.push_back(Filename.c_str());
  500. args.push_back(0);
  501. if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
  502. llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
  503. }
  504. // Delete the directory.
  505. Dir.eraseFromDisk(true);
  506. }