GraphPrinters.cpp revision 21c62da287237d39d0d95004881ea4baae3be6da
1//===- GraphPrinters.cpp - DOT printers for various graph types -----------===//
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// This file defines several printers for various different types of graphs used
11// by the LLVM infrastructure.  It uses the generic graph interface to convert
12// the graph into a .dot graph.  These graphs can then be processed with the
13// "dot" tool to convert them to postscript or some other suitable format.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Support/GraphWriter.h"
18#include "llvm/Pass.h"
19#include "llvm/Value.h"
20#include "llvm/Analysis/CallGraph.h"
21#include <iostream>
22#include <fstream>
23using namespace llvm;
24
25template<typename GraphType>
26static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
27                             const GraphType &GT) {
28  std::string Filename = GraphName + ".dot";
29  O << "Writing '" << Filename << "'...";
30  std::ofstream F(Filename.c_str());
31
32  if (F.good())
33    WriteGraph(F, GT);
34  else
35    O << "  error opening file for writing!";
36  O << "\n";
37}
38
39
40//===----------------------------------------------------------------------===//
41//                              Call Graph Printer
42//===----------------------------------------------------------------------===//
43
44namespace llvm {
45  template<>
46  struct DOTGraphTraits<CallGraph*> : public DefaultDOTGraphTraits {
47    static std::string getGraphName(CallGraph *F) {
48      return "Call Graph";
49    }
50
51    static std::string getNodeLabel(CallGraphNode *Node, CallGraph *Graph) {
52      if (Node->getFunction())
53        return ((Value*)Node->getFunction())->getName();
54      else
55        return "Indirect call node";
56    }
57  };
58}
59
60
61namespace {
62  struct CallGraphPrinter : public ModulePass {
63    static char ID; // Pass ID, replacement for typeid
64    CallGraphPrinter() : ModulePass((intptr_t)&ID) {}
65
66    virtual bool runOnModule(Module &M) {
67      WriteGraphToFile(std::cerr, "callgraph", &getAnalysis<CallGraph>());
68      return false;
69    }
70
71    void print(std::ostream &OS) const {}
72    void print(std::ostream &OS, const llvm::Module*) const {}
73
74    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75      AU.addRequired<CallGraph>();
76      AU.setPreservesAll();
77    }
78  };
79
80  char CallGraphPrinter::ID = 0;
81  RegisterPass<CallGraphPrinter> P2("print-callgraph",
82                                    "Print Call Graph to 'dot' file");
83}
84