d149c0fbfd2a95af0c1958e4501e89ad0f84914b
[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   /// ChooseEdge - 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 int CompilationGraph::Build (const sys::Path& TempDir) {
308
309   InputLanguagesSet InLangs;
310
311   // Traverse initial parts of the toolchains and fill in InLangs.
312   BuildInitial(InLangs, TempDir);
313
314   std::vector<const Node*> JTV;
315   TopologicalSortFilterJoinNodes(JTV);
316
317   // For all join nodes in topological order:
318   for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
319        B != E; ++B) {
320
321     sys::Path Out;
322     const Node* CurNode = *B;
323     JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
324     bool IsLast = false;
325
326     // Are there any files in the join list?
327     if (JT->JoinListEmpty())
328       continue;
329
330     // Is this the last tool in the toolchain?
331     // NOTE: we can process several toolchains in parallel.
332     if (!CurNode->HasChildren() || JT->IsLast()) {
333       if (OutputFilename.empty()) {
334         Out.set("a");
335         Out.appendSuffix(JT->OutputSuffix());
336       }
337       else
338         Out.set(OutputFilename);
339       IsLast = true;
340     }
341     else {
342       Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
343     }
344
345     if (JT->GenerateAction(Out).Execute() != 0)
346       throw std::runtime_error("Tool returned error code!");
347
348     if (!IsLast) {
349       const Node* NextNode =
350         &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
351                             CurNode->Name())->ToolName());
352       PassThroughGraph(Out, NextNode, InLangs, TempDir);
353     }
354   }
355
356   return 0;
357 }
358
359 // Code related to graph visualization.
360
361 namespace llvm {
362   template <>
363   struct DOTGraphTraits<llvmc::CompilationGraph*>
364     : public DefaultDOTGraphTraits
365   {
366
367     template<typename GraphType>
368     static std::string getNodeLabel(const Node* N, const GraphType&)
369     {
370       if (N->ToolPtr)
371         if (N->ToolPtr->IsJoin())
372           return N->Name() + "\n (join" +
373             (N->HasChildren() ? ")"
374              : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
375         else
376           return N->Name();
377       else
378         return "root";
379     }
380
381     template<typename EdgeIter>
382     static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
383       if (N->ToolPtr)
384         return N->ToolPtr->OutputLanguage();
385       else
386         return I->ToolPtr->InputLanguage();
387     }
388   };
389
390 }
391
392 void CompilationGraph::writeGraph() {
393   std::ofstream O("CompilationGraph.dot");
394
395   if (O.good()) {
396     llvm::WriteGraph(this, "compilation-graph");
397     O.close();
398   }
399   else {
400     throw std::runtime_error("");
401   }
402 }
403
404 void CompilationGraph::viewGraph() {
405   llvm::ViewGraph(this, "compilation-graph");
406 }