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