Change from llvm::SmallSet<std::string> to llvm::StringMap<char>.
[oota-llvm.git] / tools / llvmc2 / CompilationGraph.cpp
1 //===--- CompilationGraph.cpp - The LLVM Compiler Driver --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Compilation graph - implementation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CompilationGraph.h"
15
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/DOTGraphTraits.h"
19 #include "llvm/Support/GraphWriter.h"
20
21 #include <algorithm>
22 #include <iterator>
23 #include <limits>
24 #include <queue>
25 #include <stdexcept>
26
27 using namespace llvm;
28 using namespace llvmc;
29
30 extern cl::list<std::string> InputFilenames;
31 extern cl::opt<std::string> OutputFilename;
32 extern cl::list<std::string> Languages;
33
34 namespace {
35
36   // Return the edge with the maximum weight.
37   template <class C>
38   const Edge* ChooseEdge(const C& EdgesContainer,
39                          const InputLanguagesSet& InLangs,
40                          const std::string& NodeName = "root") {
41     const Edge* MaxEdge = 0;
42     unsigned MaxWeight = 0;
43     bool SingleMax = true;
44
45     for (typename C::const_iterator B = EdgesContainer.begin(),
46            E = EdgesContainer.end(); B != E; ++B) {
47       const Edge* E = B->getPtr();
48       unsigned EW = E->Weight(InLangs);
49       if (EW > MaxWeight) {
50         MaxEdge = E;
51         MaxWeight = EW;
52         SingleMax = true;
53       } else if (EW == MaxWeight) {
54         SingleMax = false;
55       }
56     }
57
58     if (!SingleMax)
59       throw std::runtime_error("Node " + NodeName +
60                                ": multiple maximal outward edges found!"
61                                " Most probably a specification error.");
62     if (!MaxEdge)
63       throw std::runtime_error("Node " + NodeName +
64                                ": no maximal outward edge found!"
65                                " Most probably a specification error.");
66     return MaxEdge;
67   }
68
69 }
70
71 CompilationGraph::CompilationGraph() {
72   NodesMap["root"] = Node(this);
73 }
74
75 Node& CompilationGraph::getNode(const std::string& ToolName) {
76   nodes_map_type::iterator I = NodesMap.find(ToolName);
77   if (I == NodesMap.end())
78     throw std::runtime_error("Node " + ToolName + " is not in the graph");
79   return I->second;
80 }
81
82 const Node& CompilationGraph::getNode(const std::string& ToolName) const {
83   nodes_map_type::const_iterator I = NodesMap.find(ToolName);
84   if (I == NodesMap.end())
85     throw std::runtime_error("Node " + ToolName + " is not in the graph!");
86   return I->second;
87 }
88
89 // Find the language name corresponding to the given file.
90 const std::string& CompilationGraph::getLanguage(const sys::Path& File) const {
91   LanguageMap::const_iterator Lang = ExtsToLangs.find(File.getSuffix());
92   if (Lang == ExtsToLangs.end())
93     throw std::runtime_error("Unknown suffix: " + File.getSuffix() + '!');
94   return Lang->second;
95 }
96
97 // Find the tools list corresponding to the given language name.
98 const CompilationGraph::tools_vector_type&
99 CompilationGraph::getToolsVector(const std::string& LangName) const
100 {
101   tools_map_type::const_iterator I = ToolsMap.find(LangName);
102   if (I == ToolsMap.end())
103     throw std::runtime_error("No tool corresponding to the language "
104                              + LangName + "found!");
105   return I->second;
106 }
107
108 void CompilationGraph::insertNode(Tool* V) {
109   if (NodesMap.count(V->Name()) == 0) {
110     Node N;
111     N.OwningGraph = this;
112     N.ToolPtr = V;
113     NodesMap[V->Name()] = N;
114   }
115 }
116
117 void CompilationGraph::insertEdge(const std::string& A, Edge* E) {
118   Node& B = getNode(E->ToolName());
119   if (A == "root") {
120     const std::string& InputLanguage = B.ToolPtr->InputLanguage();
121     ToolsMap[InputLanguage].push_back(IntrusiveRefCntPtr<Edge>(E));
122     NodesMap["root"].AddEdge(E);
123   }
124   else {
125     Node& N = getNode(A);
126     N.AddEdge(E);
127   }
128   // Increase the inward edge counter.
129   B.IncrInEdges();
130 }
131
132 namespace {
133   sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName,
134                          const std::string& Suffix) {
135     sys::Path Out = TempDir;
136     Out.appendComponent(BaseName);
137     Out.appendSuffix(Suffix);
138     Out.makeUnique(true, NULL);
139     return Out;
140   }
141 }
142
143 // Pass input file through the chain until we bump into a Join node or
144 // a node that says that it is the last.
145 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
146                                          const Node* StartNode,
147                                          const InputLanguagesSet& InLangs,
148                                          const sys::Path& TempDir) const {
149   bool Last = false;
150   sys::Path In = InFile;
151   const Node* CurNode = StartNode;
152
153   while(!Last) {
154     sys::Path Out;
155     Tool* CurTool = CurNode->ToolPtr.getPtr();
156
157     if (CurTool->IsJoin()) {
158       JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
159       JT.AddToJoinList(In);
160       break;
161     }
162
163     // Since toolchains do not have to end with a Join node, we should
164     // check if this Node is the last.
165     if (!CurNode->HasChildren() || CurTool->IsLast()) {
166       if (!OutputFilename.empty()) {
167         Out.set(OutputFilename);
168       }
169       else {
170         Out.set(In.getBasename());
171         Out.appendSuffix(CurTool->OutputSuffix());
172       }
173       Last = true;
174     }
175     else {
176       Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
177     }
178
179     if (CurTool->GenerateAction(In, Out).Execute() != 0)
180       throw std::runtime_error("Tool returned error code!");
181
182     if (Last)
183       return;
184
185     CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
186                                   InLangs,
187                                   CurNode->Name())->ToolName());
188     In = Out; Out.clear();
189   }
190 }
191
192 // Find the head of the toolchain corresponding to the given file.
193 // Also, insert an input language into InLangs.
194 const Node* CompilationGraph::
195 FindToolChain(const sys::Path& In, const std::string* forceLanguage,
196               InputLanguagesSet& InLangs) const {
197
198   // Determine the input language.
199   const std::string& InLanguage =
200     forceLanguage ? *forceLanguage : getLanguage(In);
201
202   // Add the current input language to the input language set.
203   InLangs.insert(InLanguage);
204
205   // Find the toolchain for the input language.
206   const tools_vector_type& TV = getToolsVector(InLanguage);
207   if (TV.empty())
208     throw std::runtime_error("No toolchain corresponding to language"
209                              + InLanguage + " found!");
210   return &getNode(ChooseEdge(TV, InLangs)->ToolName());
211 }
212
213 // Helper function used by Build().
214 // Traverses initial portions of the toolchains (up to the first Join node).
215 // This function is also responsible for handling the -x option.
216 void CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
217                                      const sys::Path& TempDir) {
218   // This is related to -x option handling.
219   cl::list<std::string>::const_iterator xIter = Languages.begin(),
220     xBegin = xIter, xEnd = Languages.end();
221   bool xEmpty = true;
222   const std::string* xLanguage = 0;
223   unsigned xPos = 0, xPosNext = 0, filePos = 0;
224
225   if (xIter != xEnd) {
226     xEmpty = false;
227     xPos = Languages.getPosition(xIter - xBegin);
228     cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
229     xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
230       : Languages.getPosition(xNext - xBegin);
231     xLanguage = (*xIter == "none") ? 0 : &(*xIter);
232   }
233
234   // For each input file:
235   for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
236          CB = B, E = InputFilenames.end(); B != E; ++B) {
237     sys::Path In = sys::Path(*B);
238
239     // Code for handling the -x option.
240     // Output: std::string* xLanguage (can be NULL).
241     if (!xEmpty) {
242       filePos = InputFilenames.getPosition(B - CB);
243
244       if (xPos < filePos) {
245         if (filePos < xPosNext) {
246           xLanguage = (*xIter == "none") ? 0 : &(*xIter);
247         }
248         else { // filePos >= xPosNext
249           // Skip xIters while filePos > xPosNext
250           while (filePos > xPosNext) {
251             ++xIter;
252             xPos = xPosNext;
253
254             cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
255             if (xNext == xEnd)
256               xPosNext = std::numeric_limits<unsigned>::max();
257             else
258               xPosNext = Languages.getPosition(xNext - xBegin);
259             xLanguage = (*xIter == "none") ? 0 : &(*xIter);
260           }
261         }
262       }
263     }
264
265     // Find the toolchain corresponding to this file.
266     const Node* N = FindToolChain(In, xLanguage, InLangs);
267     // Pass file through the chain starting at head.
268     PassThroughGraph(In, N, InLangs, TempDir);
269   }
270 }
271
272 // Sort the nodes in topological order.
273 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
274   std::queue<const Node*> Q;
275   Q.push(&getNode("root"));
276
277   while (!Q.empty()) {
278     const Node* A = Q.front();
279     Q.pop();
280     Out.push_back(A);
281     for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
282          EB != EE; ++EB) {
283       Node* B = &getNode((*EB)->ToolName());
284       B->DecrInEdges();
285       if (B->HasNoInEdges())
286         Q.push(B);
287     }
288   }
289 }
290
291 namespace {
292   bool NotJoinNode(const Node* N) {
293     return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
294   }
295 }
296
297 // Call TopologicalSort and filter the resulting list to include
298 // only Join nodes.
299 void CompilationGraph::
300 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
301   std::vector<const Node*> TopSorted;
302   TopologicalSort(TopSorted);
303   std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
304                       std::back_inserter(Out), NotJoinNode);
305 }
306
307 // Build the targets. Command-line options are accessed through global
308 // variables.
309 int CompilationGraph::Build (const sys::Path& TempDir) {
310
311   InputLanguagesSet InLangs;
312
313   // Traverse initial parts of the toolchains and fill in InLangs.
314   BuildInitial(InLangs, TempDir);
315
316   std::vector<const Node*> JTV;
317   TopologicalSortFilterJoinNodes(JTV);
318
319   // For all join nodes in topological order:
320   for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
321        B != E; ++B) {
322
323     sys::Path Out;
324     const Node* CurNode = *B;
325     JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
326     bool IsLast = false;
327
328     // Are there any files in the join list?
329     if (JT->JoinListEmpty())
330       continue;
331
332     // Is this the last tool in the toolchain?
333     // NOTE: we can process several toolchains in parallel.
334     if (!CurNode->HasChildren() || JT->IsLast()) {
335       if (OutputFilename.empty()) {
336         Out.set("a");
337         Out.appendSuffix(JT->OutputSuffix());
338       }
339       else
340         Out.set(OutputFilename);
341       IsLast = true;
342     }
343     else {
344       Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
345     }
346
347     if (JT->GenerateAction(Out).Execute() != 0)
348       throw std::runtime_error("Tool returned error code!");
349
350     if (!IsLast) {
351       const Node* NextNode =
352         &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
353                             CurNode->Name())->ToolName());
354       PassThroughGraph(Out, NextNode, InLangs, TempDir);
355     }
356   }
357
358   return 0;
359 }
360
361 // Code related to graph visualization.
362
363 namespace llvm {
364   template <>
365   struct DOTGraphTraits<llvmc::CompilationGraph*>
366     : public DefaultDOTGraphTraits
367   {
368
369     template<typename GraphType>
370     static std::string getNodeLabel(const Node* N, const GraphType&)
371     {
372       if (N->ToolPtr)
373         if (N->ToolPtr->IsJoin())
374           return N->Name() + "\n (join" +
375             (N->HasChildren() ? ")"
376              : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
377         else
378           return N->Name();
379       else
380         return "root";
381     }
382
383     template<typename EdgeIter>
384     static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
385       if (N->ToolPtr)
386         return N->ToolPtr->OutputLanguage();
387       else
388         return I->ToolPtr->InputLanguage();
389     }
390   };
391
392 }
393
394 void CompilationGraph::writeGraph() {
395   std::ofstream O("CompilationGraph.dot");
396
397   if (O.good()) {
398     llvm::WriteGraph(this, "compilation-graph");
399     O.close();
400   }
401   else {
402     throw std::runtime_error("");
403   }
404 }
405
406 void CompilationGraph::viewGraph() {
407   llvm::ViewGraph(this, "compilation-graph");
408 }