Be a bit more efficient when processing the active and inactive
[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 "Support/CommandLine.h"
21 #include "Support/GraphWriter.h"
22 #include "Support/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->getReturnNodes().empty())
47     M = G->getReturnNodes().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   for (unsigned i = 0, e = N->getGlobals().size(); i != e; ++i) {
78     WriteAsOperand(OS, N->getGlobals()[i], false, true, M);
79     OS << "\n";
80   }
81
82   return OS.str();
83 }
84
85 namespace llvm {
86 template<>
87 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
88   static std::string getGraphName(const DSGraph *G) {
89     switch (G->getReturnNodes().size()) {
90     case 0: return G->getFunctionNames();
91     case 1: return "Function " + G->getFunctionNames();
92     default: return "Functions: " + G->getFunctionNames();
93     }
94   }
95
96   static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
97     return getCaption(Node, Graph);
98   }
99
100   static std::string getNodeAttributes(const DSNode *N) {
101     return "shape=Mrecord";
102   }
103
104   static bool edgeTargetsEdgeSource(const void *Node,
105                                     DSNode::const_iterator I) {
106     unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
107     return (O >> DS::PointerShift) != 0;
108   }
109
110   static DSNode::const_iterator getEdgeTarget(const DSNode *Node,
111                                               DSNode::const_iterator I) {
112     unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
113     unsigned LinkNo = O >> DS::PointerShift;
114     const DSNode *N = *I;
115     DSNode::const_iterator R = N->begin();
116     for (; LinkNo; --LinkNo)
117       ++R;
118     return R;
119   }
120
121   
122   /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
123   /// and the return node.
124   ///
125   static void addCustomGraphFeatures(const DSGraph *G,
126                                      GraphWriter<const DSGraph*> &GW) {
127     Module *CurMod = 0;
128     if (!G->getReturnNodes().empty())
129       CurMod = G->getReturnNodes().begin()->first->getParent();
130     else {
131       // If there is a global in the graph, we can use it to find the module.
132       const DSScalarMap &SM = G->getScalarMap();
133       if (SM.global_begin() != SM.global_end())
134         CurMod = (*SM.global_begin())->getParent();
135     }
136
137
138     // Add scalar nodes to the graph...
139     const DSGraph::ScalarMapTy &VM = G->getScalarMap();
140     for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)
141       if (!isa<GlobalValue>(I->first)) {
142         std::stringstream OS;
143         WriteAsOperand(OS, I->first, false, true, CurMod);
144         GW.emitSimpleNode(I->first, "", OS.str());
145         
146         // Add edge from return node to real destination
147         int EdgeDest = I->second.getOffset() >> DS::PointerShift;
148         if (EdgeDest == 0) EdgeDest = -1;
149         GW.emitEdge(I->first, -1, I->second.getNode(),
150                     EdgeDest, "arrowtail=tee,color=gray63");
151       }
152
153
154     // Output the returned value pointer...
155     const DSGraph::ReturnNodesTy &RetNodes = G->getReturnNodes();
156     for (DSGraph::ReturnNodesTy::const_iterator I = RetNodes.begin(),
157            E = RetNodes.end(); I != E; ++I)
158       if (I->second.getNode()) {
159         std::string Label;
160         if (RetNodes.size() == 1)
161           Label = "returning";
162         else
163           Label = I->first->getName() + " ret node";
164         // Output the return node...
165         GW.emitSimpleNode((void*)I->first, "plaintext=circle", Label);
166
167         // Add edge from return node to real destination
168         int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;
169         if (RetEdgeDest == 0) RetEdgeDest = -1;
170         GW.emitEdge((void*)I->first, -1, I->second.getNode(),
171                     RetEdgeDest, "arrowtail=tee,color=gray63");
172       }
173
174     // Output all of the call nodes...
175     const std::vector<DSCallSite> &FCs =
176       G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
177       : G->getFunctionCalls();
178     for (unsigned i = 0, e = FCs.size(); i != e; ++i) {
179       const DSCallSite &Call = FCs[i];
180       std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
181       EdgeSourceCaptions[0] = "r";
182       if (Call.isDirectCall())
183         EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
184       else
185         EdgeSourceCaptions[1] = "f";
186
187       GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
188                         &EdgeSourceCaptions);
189
190       if (DSNode *N = Call.getRetVal().getNode()) {
191         int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
192         if (EdgeDest == 0) EdgeDest = -1;
193         GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
194       }
195
196       // Print out the callee...
197       if (Call.isIndirectCall()) {
198         DSNode *N = Call.getCalleeNode();
199         assert(N && "Null call site callee node!");
200         GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
201       }
202
203       for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
204         if (DSNode *N = Call.getPtrArg(j).getNode()) {
205           int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
206           if (EdgeDest == 0) EdgeDest = -1;
207           GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
208         }
209     }
210   }
211 };
212 }   // end namespace llvm
213
214 void DSNode::print(std::ostream &O, const DSGraph *G) const {
215   GraphWriter<const DSGraph *> W(O, G);
216   W.writeNode(this);
217 }
218
219 void DSGraph::print(std::ostream &O) const {
220   WriteGraph(O, this, "DataStructures");
221 }
222
223 void DSGraph::writeGraphToFile(std::ostream &O,
224                                const std::string &GraphName) const {
225   std::string Filename = GraphName + ".dot";
226   O << "Writing '" << Filename << "'...";
227   std::ofstream F(Filename.c_str());
228   
229   if (F.good()) {
230     print(F);
231     unsigned NumCalls = shouldPrintAuxCalls() ?
232       getAuxFunctionCalls().size() : getFunctionCalls().size();
233     O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
234   } else {
235     O << "  error opening file for writing!\n";
236   }
237 }
238
239 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
240 /// then cleanup.  For use from the debugger.
241 ///
242 void DSGraph::viewGraph() const {
243   std::ofstream F("/tmp/tempgraph.dot");
244   if (!F.good()) {
245     std::cerr << "Error opening '/tmp/tempgraph.dot' for temporary graph!\n";
246     return;
247   }
248   print(F);
249   F.close();
250   if (system("dot -Tps -Gsize=10,7.5 -Grotate=90 /tmp/tempgraph.dot > /tmp/tempgraph.ps"))
251     std::cerr << "Error running dot: 'dot' not in path?\n";
252   system("gv /tmp/tempgraph.ps");
253   system("rm /tmp/tempgraph.dot /tmp/tempgraph.ps");
254 }
255
256
257 template <typename Collection>
258 static void printCollection(const Collection &C, std::ostream &O,
259                             const Module *M, const std::string &Prefix) {
260   if (M == 0) {
261     O << "Null Module pointer, cannot continue!\n";
262     return;
263   }
264
265   unsigned TotalNumNodes = 0, TotalCallNodes = 0;
266   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
267     if (C.hasGraph(*I)) {
268       DSGraph &Gr = C.getDSGraph((Function&)*I);
269       TotalNumNodes += Gr.getGraphSize();
270       unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
271         Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
272
273       TotalCallNodes += NumCalls;
274       if (I->getName() == "main" || !OnlyPrintMain)
275         Gr.writeGraphToFile(O, Prefix+I->getName());
276       else {
277         O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
278           << Gr.getGraphSize() << "+" << NumCalls << "]\n";
279       }
280
281       unsigned GraphSize = Gr.getGraphSize();
282       if (MaxGraphSize < GraphSize) MaxGraphSize = GraphSize;
283
284       for (DSGraph::node_iterator NI = Gr.node_begin(), E = Gr.node_end();
285            NI != E; ++NI)
286         if ((*NI)->isNodeCompletelyFolded())
287           ++NumFoldedNodes;
288     }
289
290   DSGraph &GG = C.getGlobalsGraph();
291   TotalNumNodes  += GG.getGraphSize();
292   TotalCallNodes += GG.getFunctionCalls().size();
293   if (!OnlyPrintMain) {
294     GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
295   } else {
296     O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
297       << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
298   }
299
300   O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes 
301     << "] nodes total" << std::endl;
302 }
303
304
305 // print - Print out the analysis results...
306 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
307   if (DontPrintAnything) return;
308   printCollection(*this, O, M, "ds.");
309 }
310
311 void BUDataStructures::print(std::ostream &O, const Module *M) const {
312   if (DontPrintAnything) return;
313   printCollection(*this, O, M, "bu.");
314 }
315
316 void TDDataStructures::print(std::ostream &O, const Module *M) const {
317   if (DontPrintAnything) return;
318   printCollection(*this, O, M, "td.");
319 }
320
321 void CompleteBUDataStructures::print(std::ostream &O, const Module *M) const {
322   if (DontPrintAnything) return;
323   printCollection(*this, O, M, "cbu.");
324 }
325
326