friendlier error message
[oota-llvm.git] / lib / Analysis / DataStructure / Printer.cpp
1 //===- Printer.cpp - Code for printing data structure graphs nicely -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the 'dot' graph printer.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/DataStructure/DataStructure.h"
15 #include "llvm/Analysis/DataStructure/DSGraph.h"
16 #include "llvm/Analysis/DataStructure/DSGraphTraits.h"
17 #include "llvm/Module.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/GraphWriter.h"
22 #include "llvm/ADT/Statistic.h"
23 #include <fstream>
24 #include <sstream>
25 using namespace llvm;
26
27 // OnlyPrintMain - The DataStructure printer exposes this option to allow
28 // printing of only the graph for "main".
29 //
30 namespace {
31   cl::opt<bool> OnlyPrintMain("only-print-main-ds", cl::ReallyHidden);
32   cl::opt<bool> DontPrintAnything("dont-print-ds", cl::ReallyHidden);
33   Statistic<> MaxGraphSize   ("dsa", "Maximum graph size");
34   Statistic<> NumFoldedNodes ("dsa", "Number of folded nodes (in final graph)");
35 }
36
37 void DSNode::dump() const { print(std::cerr, 0); }
38
39 static std::string getCaption(const DSNode *N, const DSGraph *G) {
40   std::stringstream OS;
41   Module *M = 0;
42
43   if (!G) G = N->getParentGraph();
44
45   // Get the module from ONE of the functions in the graph it is available.
46   if (G && G->retnodes_begin() != G->retnodes_end())
47     M = G->retnodes_begin()->first->getParent();
48   if (M == 0 && G) {
49     // If there is a global in the graph, we can use it to find the module.
50     const DSScalarMap &SM = G->getScalarMap();
51     if (SM.global_begin() != SM.global_end())
52       M = (*SM.global_begin())->getParent();
53   }
54
55   if (N->isNodeCompletelyFolded())
56     OS << "COLLAPSED";
57   else {
58     WriteTypeSymbolic(OS, N->getType(), M);
59     if (N->isArray())
60       OS << " array";
61   }
62   if (unsigned NodeType = N->getNodeFlags()) {
63     OS << ": ";
64     if (NodeType & DSNode::AllocaNode ) OS << "S";
65     if (NodeType & DSNode::HeapNode   ) OS << "H";
66     if (NodeType & DSNode::GlobalNode ) OS << "G";
67     if (NodeType & DSNode::UnknownNode) OS << "U";
68     if (NodeType & DSNode::Incomplete ) OS << "I";
69     if (NodeType & DSNode::Modified   ) OS << "M";
70     if (NodeType & DSNode::Read       ) OS << "R";
71 #ifndef NDEBUG
72     if (NodeType & DSNode::DEAD       ) OS << "<dead>";
73 #endif
74     OS << "\n";
75   }
76
77   EquivalenceClasses<GlobalValue*> *GlobalECs = 0;
78   if (G) GlobalECs = &G->getGlobalECs();
79
80   for (unsigned i = 0, e = N->getGlobalsList().size(); i != e; ++i) {
81     WriteAsOperand(OS, N->getGlobalsList()[i], false, true, M);
82
83     // Figure out how many globals are equivalent to this one.
84     if (GlobalECs) {
85       EquivalenceClasses<GlobalValue*>::iterator I =
86         GlobalECs->findValue(N->getGlobalsList()[i]);
87       if (I != GlobalECs->end()) {
88         unsigned NumMembers =
89           std::distance(GlobalECs->member_begin(I), GlobalECs->member_end());
90         if (NumMembers != 1) OS << " + " << (NumMembers-1) << " EC";
91       }
92     }
93     OS << "\n";
94   }
95
96   return OS.str();
97 }
98
99 namespace llvm {
100 template<>
101 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
102   static std::string getGraphName(const DSGraph *G) {
103     switch (G->getReturnNodes().size()) {
104     case 0: return G->getFunctionNames();
105     case 1: return "Function " + G->getFunctionNames();
106     default: return "Functions: " + G->getFunctionNames();
107     }
108   }
109
110   static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
111     return getCaption(Node, Graph);
112   }
113
114   static std::string getNodeAttributes(const DSNode *N) {
115     return "shape=Mrecord";
116   }
117
118   static bool edgeTargetsEdgeSource(const void *Node,
119                                     DSNode::const_iterator I) {
120     unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
121     return (O >> DS::PointerShift) != 0;
122   }
123
124   static DSNode::const_iterator getEdgeTarget(const DSNode *Node,
125                                               DSNode::const_iterator I) {
126     unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
127     unsigned LinkNo = O >> DS::PointerShift;
128     const DSNode *N = *I;
129     DSNode::const_iterator R = N->begin();
130     for (; LinkNo; --LinkNo)
131       ++R;
132     return R;
133   }
134
135
136   /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
137   /// and the return node.
138   ///
139   static void addCustomGraphFeatures(const DSGraph *G,
140                                      GraphWriter<const DSGraph*> &GW) {
141     Module *CurMod = 0;
142     if (G->retnodes_begin() != G->retnodes_end())
143       CurMod = G->retnodes_begin()->first->getParent();
144     else {
145       // If there is a global in the graph, we can use it to find the module.
146       const DSScalarMap &SM = G->getScalarMap();
147       if (SM.global_begin() != SM.global_end())
148         CurMod = (*SM.global_begin())->getParent();
149     }
150
151
152     // Add scalar nodes to the graph...
153     const DSGraph::ScalarMapTy &VM = G->getScalarMap();
154     for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)
155       if (!isa<GlobalValue>(I->first)) {
156         std::stringstream OS;
157         WriteAsOperand(OS, I->first, false, true, CurMod);
158         GW.emitSimpleNode(I->first, "", OS.str());
159
160         // Add edge from return node to real destination
161         DSNode *DestNode = I->second.getNode();
162         int EdgeDest = I->second.getOffset() >> DS::PointerShift;
163         if (EdgeDest == 0) EdgeDest = -1;
164         GW.emitEdge(I->first, -1, DestNode,
165                     EdgeDest, "arrowtail=tee,color=gray63");
166       }
167
168
169     // Output the returned value pointer...
170     for (DSGraph::retnodes_iterator I = G->retnodes_begin(),
171            E = G->retnodes_end(); I != E; ++I)
172       if (I->second.getNode()) {
173         std::string Label;
174         if (G->getReturnNodes().size() == 1)
175           Label = "returning";
176         else
177           Label = I->first->getName() + " ret node";
178         // Output the return node...
179         GW.emitSimpleNode((void*)I->first, "plaintext=circle", Label);
180
181         // Add edge from return node to real destination
182         DSNode *RetNode = I->second.getNode();
183         int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;
184         if (RetEdgeDest == 0) RetEdgeDest = -1;
185         GW.emitEdge((void*)I->first, -1, RetNode,
186                     RetEdgeDest, "arrowtail=tee,color=gray63");
187       }
188
189     // Output all of the call nodes...
190     const std::list<DSCallSite> &FCs =
191       G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
192       : G->getFunctionCalls();
193     for (std::list<DSCallSite>::const_iterator I = FCs.begin(), E = FCs.end();
194          I != E; ++I) {
195       const DSCallSite &Call = *I;
196       std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
197       EdgeSourceCaptions[0] = "r";
198       if (Call.isDirectCall())
199         EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
200       else
201         EdgeSourceCaptions[1] = "f";
202
203       GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
204                         &EdgeSourceCaptions);
205
206       if (DSNode *N = Call.getRetVal().getNode()) {
207         int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
208         if (EdgeDest == 0) EdgeDest = -1;
209         GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
210       }
211
212       // Print out the callee...
213       if (Call.isIndirectCall()) {
214         DSNode *N = Call.getCalleeNode();
215         assert(N && "Null call site callee node!");
216         GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
217       }
218
219       for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
220         if (DSNode *N = Call.getPtrArg(j).getNode()) {
221           int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
222           if (EdgeDest == 0) EdgeDest = -1;
223           GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
224         }
225     }
226   }
227 };
228 }   // end namespace llvm
229
230 void DSNode::print(std::ostream &O, const DSGraph *G) const {
231   GraphWriter<const DSGraph *> W(O, G);
232   W.writeNode(this);
233 }
234
235 void DSGraph::print(std::ostream &O) const {
236   WriteGraph(O, this, "DataStructures");
237 }
238
239 void DSGraph::writeGraphToFile(std::ostream &O,
240                                const std::string &GraphName) const {
241   std::string Filename = GraphName + ".dot";
242   O << "Writing '" << Filename << "'...";
243   std::ofstream F(Filename.c_str());
244
245   if (F.good()) {
246     print(F);
247     unsigned NumCalls = shouldPrintAuxCalls() ?
248       getAuxFunctionCalls().size() : getFunctionCalls().size();
249     O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
250   } else {
251     O << "  error opening file for writing!\n";
252   }
253 }
254
255 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
256 /// then cleanup.  For use from the debugger.
257 ///
258 void DSGraph::viewGraph() const {
259   std::ofstream F("/tmp/tempgraph.dot");
260   if (!F.good()) {
261     std::cerr << "Error opening '/tmp/tempgraph.dot' for temporary graph!\n";
262     return;
263   }
264   print(F);
265   F.close();
266   if (system("dot -Tps -Gsize=10,7.5 -Grotate=90 /tmp/tempgraph.dot > /tmp/tempgraph.ps"))
267     std::cerr << "Error running dot: 'dot' not in path?\n";
268   system("gv /tmp/tempgraph.ps");
269   system("rm /tmp/tempgraph.dot /tmp/tempgraph.ps");
270 }
271
272
273 template <typename Collection>
274 static void printCollection(const Collection &C, std::ostream &O,
275                             const Module *M, const std::string &Prefix) {
276   if (M == 0) {
277     O << "Null Module pointer, cannot continue!\n";
278     return;
279   }
280
281   unsigned TotalNumNodes = 0, TotalCallNodes = 0;
282   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
283     if (C.hasGraph(*I)) {
284       DSGraph &Gr = C.getDSGraph((Function&)*I);
285       unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
286         Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
287       bool IsDuplicateGraph = false;
288
289       if (I->getName() == "main" || !OnlyPrintMain) {
290         Function *SCCFn = Gr.retnodes_begin()->first;
291         if (&*I == SCCFn) {
292           Gr.writeGraphToFile(O, Prefix+I->getName());
293         } else {
294           IsDuplicateGraph = true; // Don't double count node/call nodes.
295           O << "Didn't write '" << Prefix+I->getName()
296             << ".dot' - Graph already emitted to '" << Prefix+SCCFn->getName()
297             << "\n";
298         }
299       } else {
300         Function *SCCFn = Gr.retnodes_begin()->first;
301         if (&*I == SCCFn) {
302           O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
303             << Gr.getGraphSize() << "+" << NumCalls << "]\n";
304         } else {
305           IsDuplicateGraph = true; // Don't double count node/call nodes.
306         }
307       }
308
309       if (!IsDuplicateGraph) {
310         unsigned GraphSize = Gr.getGraphSize();
311         if (MaxGraphSize < GraphSize) MaxGraphSize = GraphSize;
312
313         TotalNumNodes += Gr.getGraphSize();
314         TotalCallNodes += NumCalls;
315         for (DSGraph::node_iterator NI = Gr.node_begin(), E = Gr.node_end();
316              NI != E; ++NI)
317           if (NI->isNodeCompletelyFolded())
318             ++NumFoldedNodes;
319       }
320     }
321
322   DSGraph &GG = C.getGlobalsGraph();
323   TotalNumNodes  += GG.getGraphSize();
324   TotalCallNodes += GG.getFunctionCalls().size();
325   if (!OnlyPrintMain) {
326     GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
327   } else {
328     O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
329       << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
330   }
331
332   O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes
333     << "] nodes total" << std::endl;
334 }
335
336
337 // print - Print out the analysis results...
338 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
339   if (DontPrintAnything) return;
340   printCollection(*this, O, M, "ds.");
341 }
342
343 void BUDataStructures::print(std::ostream &O, const Module *M) const {
344   if (DontPrintAnything) return;
345   printCollection(*this, O, M, "bu.");
346 }
347
348 void TDDataStructures::print(std::ostream &O, const Module *M) const {
349   if (DontPrintAnything) return;
350   printCollection(*this, O, M, "td.");
351 }
352
353 void CompleteBUDataStructures::print(std::ostream &O, const Module *M) const {
354   if (DontPrintAnything) return;
355   printCollection(*this, O, M, "cbu.");
356 }
357
358
359 void EquivClassGraphs::print(std::ostream &O, const Module *M) const {
360   if (DontPrintAnything) return;
361   printCollection(*this, O, M, "eq.");
362 }
363