1 //===- GraphPrinters.cpp - DOT printers for various graph types -----------===//
3 // This file defines several printers for various different types of graphs used
4 // by the LLVM infrastructure. It uses the generic graph interface to convert
5 // the graph into a .dot graph. These graphs can then be processed with the
6 // "dot" tool to convert them to postscript or some other suitable format.
8 //===----------------------------------------------------------------------===//
10 #include "Support/GraphWriter.h"
11 #include "llvm/Pass.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/Support/CFG.h"
18 struct DOTGraphTraits<Function*> : public DefaultDOTGraphTraits {
19 static std::string getGraphName(Function *F) {
20 return "CFG for '" + F->getName() + "' function";
23 static std::string getNodeLabel(BasicBlock *Node, Function *Graph) {
24 std::ostringstream Out;
26 std::string OutStr = Out.str();
27 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
29 // Process string output to make it nicer...
30 for (unsigned i = 0; i != OutStr.length(); ++i)
31 if (OutStr[i] == '\n') { // Left justify
33 OutStr.insert(OutStr.begin()+i+1, 'l');
34 } else if (OutStr[i] == ';') { // Delete comments!
35 unsigned Idx = OutStr.find('\n', i+1); // Find end of line
36 OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
43 static std::string getNodeAttributes(BasicBlock *N) {
44 return "fontname=Courier";
47 static std::string getEdgeSourceLabel(BasicBlock *Node, succ_iterator I) {
48 // Label source of conditional branches with "T" or "F"
49 if (BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
50 if (BI->isConditional())
51 return (I == succ_begin(Node)) ? "T" : "F";
56 template<typename GraphType>
57 static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
58 const GraphType >) {
59 std::string Filename = GraphName + ".dot";
60 O << "Writing '" << Filename << "'...";
61 std::ofstream F(Filename.c_str());
66 O << " error opening file for writing!";
72 struct CFGPrinter : public FunctionPass {
74 virtual bool runOnFunction(Function &Func) {
75 WriteGraphToFile(std::cerr, "cfg."+Func.getName(), &Func);
79 void print(std::ostream &OS) const {}
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 RegisterAnalysis<CFGPrinter> P1("print-cfg",
87 "Print CFG of function to 'dot' file");