Make error messages more useful than jsut an abort
[oota-llvm.git] / lib / Analysis / DataStructure / Printer.cpp
1 //===- Printer.cpp - Code for printing data structure graphs nicely -------===//
2 //
3 // This file implements the 'dot' graph printer.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Analysis/DataStructure.h"
8 #include "llvm/Analysis/DSGraph.h"
9 #include "llvm/Analysis/DSGraphTraits.h"
10 #include "llvm/Module.h"
11 #include "llvm/Assembly/Writer.h"
12 #include "Support/CommandLine.h"
13 #include "Support/GraphWriter.h"
14 #include "Support/Statistic.h"
15 #include <fstream>
16 #include <sstream>
17
18 // OnlyPrintMain - The DataStructure printer exposes this option to allow
19 // printing of only the graph for "main".
20 //
21 namespace {
22   cl::opt<bool> OnlyPrintMain("only-print-main-ds", cl::ReallyHidden);
23   Statistic<> MaxGraphSize   ("dsnode", "Maximum graph size");
24   Statistic<> NumFoldedNodes ("dsnode", "Number of folded nodes (in final graph)");
25 }
26
27
28 void DSNode::dump() const { print(std::cerr, 0); }
29
30 static std::string getCaption(const DSNode *N, const DSGraph *G) {
31   std::stringstream OS;
32   Module *M = G && G->hasFunction() ? G->getFunction().getParent() : 0;
33
34   if (N->isNodeCompletelyFolded())
35     OS << "FOLDED";
36   else {
37     WriteTypeSymbolic(OS, N->getType(), M);
38     if (N->isArray())
39       OS << " array";
40   }
41   if (N->NodeType) {
42     OS << ": ";
43     if (N->NodeType & DSNode::AllocaNode ) OS << "S";
44     if (N->NodeType & DSNode::HeapNode   ) OS << "H";
45     if (N->NodeType & DSNode::GlobalNode ) OS << "G";
46     if (N->NodeType & DSNode::UnknownNode) OS << "U";
47     if (N->NodeType & DSNode::Incomplete ) OS << "I";
48     if (N->NodeType & DSNode::Modified   ) OS << "M";
49     if (N->NodeType & DSNode::Read       ) OS << "R";
50     if (N->NodeType & DSNode::DEAD       ) OS << "<dead>";
51     OS << "\n";
52   }
53
54   for (unsigned i = 0, e = N->getGlobals().size(); i != e; ++i) {
55     WriteAsOperand(OS, N->getGlobals()[i], false, true, M);
56     OS << "\n";
57   }
58
59   return OS.str();
60 }
61
62 template<>
63 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
64   static std::string getGraphName(const DSGraph *G) {
65     if (G->hasFunction())
66       return "Function " + G->getFunction().getName();
67     else
68       return "Global graph";
69   }
70
71   static const char *getGraphProperties(const DSGraph *G) {
72     return "\tsize=\"10,7.5\";\n"
73            "\trotate=\"90\";\n";
74   }
75
76   static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
77     return getCaption(Node, Graph);
78   }
79
80   static std::string getNodeAttributes(const DSNode *N) {
81     return "shape=Mrecord";//fontname=Courier";
82   }
83   
84   /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
85   /// and the return node.
86   ///
87   static void addCustomGraphFeatures(const DSGraph *G,
88                                      GraphWriter<const DSGraph*> &GW) {
89     Module *CurMod = G->hasFunction() ? G->getFunction().getParent() : 0;
90
91     // Add scalar nodes to the graph...
92     const hash_map<Value*, DSNodeHandle> &VM = G->getScalarMap();
93     for (hash_map<Value*, DSNodeHandle>::const_iterator I = VM.begin();
94          I != VM.end(); ++I)
95       if (!isa<GlobalValue>(I->first)) {
96         std::stringstream OS;
97         WriteAsOperand(OS, I->first, false, true, CurMod);
98         GW.emitSimpleNode(I->first, "", OS.str());
99         
100         // Add edge from return node to real destination
101         int EdgeDest = I->second.getOffset() >> DS::PointerShift;
102         if (EdgeDest == 0) EdgeDest = -1;
103         GW.emitEdge(I->first, -1, I->second.getNode(),
104                     EdgeDest, "arrowtail=tee,color=gray63");
105       }
106
107
108     // Output the returned value pointer...
109     if (G->getRetNode().getNode() != 0) {
110       // Output the return node...
111       GW.emitSimpleNode((void*)1, "plaintext=circle", "returning");
112
113       // Add edge from return node to real destination
114       int RetEdgeDest = G->getRetNode().getOffset() >> DS::PointerShift;;
115       if (RetEdgeDest == 0) RetEdgeDest = -1;
116       GW.emitEdge((void*)1, -1, G->getRetNode().getNode(),
117                   RetEdgeDest, "arrowtail=tee,color=gray63");
118     }
119
120     // Output all of the call nodes...
121     const std::vector<DSCallSite> &FCs =
122       G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
123       : G->getFunctionCalls();
124     for (unsigned i = 0, e = FCs.size(); i != e; ++i) {
125       const DSCallSite &Call = FCs[i];
126       std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
127       EdgeSourceCaptions[0] = "r";
128       if (Call.isDirectCall())
129         EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
130       else
131         EdgeSourceCaptions[1] = "f";
132
133       GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
134                         &EdgeSourceCaptions);
135
136       if (DSNode *N = Call.getRetVal().getNode()) {
137         int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
138         if (EdgeDest == 0) EdgeDest = -1;
139         GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
140       }
141
142       // Print out the callee...
143       if (Call.isIndirectCall()) {
144         DSNode *N = Call.getCalleeNode();
145         assert(N && "Null call site callee node!");
146         GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
147       }
148
149       for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
150         if (DSNode *N = Call.getPtrArg(j).getNode()) {
151           int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
152           if (EdgeDest == 0) EdgeDest = -1;
153           GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
154         }
155     }
156   }
157 };
158
159 void DSNode::print(std::ostream &O, const DSGraph *G) const {
160   GraphWriter<const DSGraph *> W(O, G);
161   W.writeNode(this);
162 }
163
164 void DSGraph::print(std::ostream &O) const {
165   WriteGraph(O, this, "DataStructures");
166 }
167
168 void DSGraph::writeGraphToFile(std::ostream &O,
169                                const std::string &GraphName) const {
170   std::string Filename = GraphName + ".dot";
171   O << "Writing '" << Filename << "'...";
172   std::ofstream F(Filename.c_str());
173   
174   if (F.good()) {
175     print(F);
176     unsigned NumCalls = shouldPrintAuxCalls() ?
177       getAuxFunctionCalls().size() : getFunctionCalls().size();
178     O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
179   } else {
180     O << "  error opening file for writing!\n";
181   }
182 }
183
184 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
185 /// then cleanup.  For use from the debugger.
186 ///
187 void DSGraph::viewGraph() const {
188   std::ofstream F("/tmp/tempgraph.dot");
189   if (!F.good()) {
190     std::cerr << "Error opening '/tmp/tempgraph.dot' for temporary graph!\n";
191     return;
192   }
193   print(F);
194   F.close();
195   if (system("dot -Tps /tmp/tempgraph.dot > /tmp/tempgraph.ps"))
196     std::cerr << "Error running dot: 'dot' not in path?\n";
197   system("gv /tmp/tempgraph.ps");
198   system("rm /tmp/tempgraph.dot /tmp/tempgraph.ps");
199 }
200
201
202 template <typename Collection>
203 static void printCollection(const Collection &C, std::ostream &O,
204                             const Module *M, const std::string &Prefix) {
205   if (M == 0) {
206     O << "Null Module pointer, cannot continue!\n";
207     return;
208   }
209
210   unsigned TotalNumNodes = 0, TotalCallNodes = 0;
211   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
212     if (C.hasGraph(*I)) {
213       DSGraph &Gr = C.getDSGraph((Function&)*I);
214       TotalNumNodes += Gr.getGraphSize();
215       unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
216         Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
217
218       TotalCallNodes += NumCalls;
219       if (I->getName() == "main" || !OnlyPrintMain)
220         Gr.writeGraphToFile(O, Prefix+I->getName());
221       else {
222         O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
223           << Gr.getGraphSize() << "+" << NumCalls << "]\n";
224       }
225
226       if (MaxGraphSize < Gr.getNodes().size())
227         MaxGraphSize = Gr.getNodes().size();
228       for (unsigned i = 0, e = Gr.getNodes().size(); i != e; ++i)
229         if (Gr.getNodes()[i]->isNodeCompletelyFolded())
230           ++NumFoldedNodes;
231     }
232
233   DSGraph &GG = C.getGlobalsGraph();
234   TotalNumNodes  += GG.getGraphSize();
235   TotalCallNodes += GG.getFunctionCalls().size();
236   if (!OnlyPrintMain) {
237     GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
238   } else {
239     O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
240       << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
241   }
242
243   O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes 
244     << "] nodes total" << std::endl;
245 }
246
247
248 // print - Print out the analysis results...
249 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
250   printCollection(*this, O, M, "ds.");
251 }
252
253 void BUDataStructures::print(std::ostream &O, const Module *M) const {
254   printCollection(*this, O, M, "bu.");
255 }
256
257 void TDDataStructures::print(std::ostream &O, const Module *M) const {
258   printCollection(*this, O, M, "td.");
259 }