310413b9f0a5a4b41d0b2740c0897d831278e850
[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 std::string& NodeName = "root") {
40     const Edge* MaxEdge = 0;
41     unsigned MaxWeight = 0;
42     bool SingleMax = true;
43
44     for (typename C::const_iterator B = EdgesContainer.begin(),
45            E = EdgesContainer.end(); B != E; ++B) {
46       const Edge* E = B->getPtr();
47       unsigned EW = E->Weight();
48       if (EW > MaxWeight) {
49         MaxEdge = E;
50         MaxWeight = EW;
51         SingleMax = true;
52       }
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 const std::string& CompilationGraph::getLanguage(const sys::Path& File) const {
90   LanguageMap::const_iterator Lang = ExtsToLangs.find(File.getSuffix());
91   if (Lang == ExtsToLangs.end())
92     throw std::runtime_error("Unknown suffix: " + File.getSuffix() + '!');
93   return Lang->second;
94 }
95
96 const CompilationGraph::tools_vector_type&
97 CompilationGraph::getToolsVector(const std::string& LangName) const
98 {
99   tools_map_type::const_iterator I = ToolsMap.find(LangName);
100   if (I == ToolsMap.end())
101     throw std::runtime_error("No tool corresponding to the language "
102                              + LangName + "found!");
103   return I->second;
104 }
105
106 void CompilationGraph::insertNode(Tool* V) {
107   if (NodesMap.count(V->Name()) == 0) {
108     Node N;
109     N.OwningGraph = this;
110     N.ToolPtr = V;
111     NodesMap[V->Name()] = N;
112   }
113 }
114
115 void CompilationGraph::insertEdge(const std::string& A, Edge* E) {
116   Node& B = getNode(E->ToolName());
117   if (A == "root") {
118     const std::string& InputLanguage = B.ToolPtr->InputLanguage();
119     ToolsMap[InputLanguage].push_back(IntrusiveRefCntPtr<Edge>(E));
120     NodesMap["root"].AddEdge(E);
121   }
122   else {
123     Node& N = getNode(A);
124     N.AddEdge(E);
125   }
126   // Increase the inward edge counter.
127   B.IncrInEdges();
128 }
129
130 namespace {
131   sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName,
132                          const std::string& Suffix) {
133     sys::Path Out = TempDir;
134     Out.appendComponent(BaseName);
135     Out.appendSuffix(Suffix);
136     Out.makeUnique(true, NULL);
137     return Out;
138   }
139 }
140
141 // Pass input file through the chain until we bump into a Join node or
142 // a node that says that it is the last.
143 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
144                                          const Node* StartNode,
145                                          const sys::Path& TempDir) const {
146   bool Last = false;
147   sys::Path In = InFile;
148   const Node* CurNode = StartNode;
149
150   while(!Last) {
151     sys::Path Out;
152     Tool* CurTool = CurNode->ToolPtr.getPtr();
153
154     if (CurTool->IsJoin()) {
155       JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
156       JT.AddToJoinList(In);
157       break;
158     }
159
160     // Since toolchains do not have to end with a Join node, we should
161     // check if this Node is the last.
162     if (!CurNode->HasChildren() || CurTool->IsLast()) {
163       if (!OutputFilename.empty()) {
164         Out.set(OutputFilename);
165       }
166       else {
167         Out.set(In.getBasename());
168         Out.appendSuffix(CurTool->OutputSuffix());
169       }
170       Last = true;
171     }
172     else {
173       Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
174     }
175
176     if (CurTool->GenerateAction(In, Out).Execute() != 0)
177       throw std::runtime_error("Tool returned error code!");
178
179     if (Last)
180       return;
181
182     CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
183                                   CurNode->Name())->ToolName());
184     In = Out; Out.clear();
185   }
186 }
187
188 // Sort the nodes in topological order.
189 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
190   std::queue<const Node*> Q;
191   Q.push(&getNode("root"));
192
193   while (!Q.empty()) {
194     const Node* A = Q.front();
195     Q.pop();
196     Out.push_back(A);
197     for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
198          EB != EE; ++EB) {
199       Node* B = &getNode((*EB)->ToolName());
200       B->DecrInEdges();
201       if (B->HasNoInEdges())
202         Q.push(B);
203     }
204   }
205 }
206
207 namespace {
208   bool NotJoinNode(const Node* N) {
209     return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
210   }
211 }
212
213 // Call TopologicalSort and filter the resulting list to include
214 // only Join nodes.
215 void CompilationGraph::
216 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
217   std::vector<const Node*> TopSorted;
218   TopologicalSort(TopSorted);
219   std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
220                       std::back_inserter(Out), NotJoinNode);
221 }
222
223 // Find head of the toolchain corresponding to the given file.
224 const Node* CompilationGraph::
225 FindToolChain(const sys::Path& In, const std::string* forceLanguage) const {
226   const std::string& InLanguage =
227     forceLanguage ? *forceLanguage : getLanguage(In);
228   const tools_vector_type& TV = getToolsVector(InLanguage);
229   if (TV.empty())
230     throw std::runtime_error("No toolchain corresponding to language"
231                              + InLanguage + " found!");
232   return &getNode(ChooseEdge(TV)->ToolName());
233 }
234
235 // Build the targets. Command-line options are passed through
236 // temporary variables.
237 int CompilationGraph::Build (const sys::Path& TempDir) {
238
239   // This is related to -x option handling.
240   cl::list<std::string>::const_iterator xIter = Languages.begin(),
241     xBegin = xIter, xEnd = Languages.end();
242   bool xEmpty = true;
243   const std::string* xLanguage = 0;
244   unsigned xPos = 0, xPosNext = 0, filePos = 0;
245
246   if (xIter != xEnd) {
247     xEmpty = false;
248     xPos = Languages.getPosition(xIter - xBegin);
249     cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
250     xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
251       : Languages.getPosition(xNext - xBegin);
252     xLanguage = (*xIter == "none") ? 0 : &(*xIter);
253   }
254
255   // For each input file:
256   for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
257          CB = B, E = InputFilenames.end(); B != E; ++B) {
258     sys::Path In = sys::Path(*B);
259
260     // Code for handling the -x option.
261     // Output: std::string* xLanguage (can be NULL).
262     if (!xEmpty) {
263       filePos = InputFilenames.getPosition(B - CB);
264
265       if (xPos < filePos) {
266         if (filePos < xPosNext) {
267           xLanguage = (*xIter == "none") ? 0 : &(*xIter);
268         }
269         else { // filePos >= xPosNext
270           // Skip xIters while filePos > xPosNext
271           while (filePos > xPosNext) {
272             ++xIter;
273             xPos = xPosNext;
274
275             cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
276             if (xNext == xEnd)
277               xPosNext = std::numeric_limits<unsigned>::max();
278             else
279               xPosNext = Languages.getPosition(xNext - xBegin);
280             xLanguage = (*xIter == "none") ? 0 : &(*xIter);
281           }
282         }
283       }
284     }
285
286     // Find the toolchain corresponding to this file.
287     const Node* N = FindToolChain(In, xLanguage);
288     // Pass file through the chain starting at head.
289     PassThroughGraph(In, N, TempDir);
290   }
291
292   std::vector<const Node*> JTV;
293   TopologicalSortFilterJoinNodes(JTV);
294
295   // For all join nodes in topological order:
296   for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
297        B != E; ++B) {
298
299     sys::Path Out;
300     const Node* CurNode = *B;
301     JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
302     bool IsLast = false;
303
304     // Are there any files to be joined?
305     if (JT->JoinListEmpty())
306       continue;
307
308     // Is this the last tool in the chain?
309     // NOTE: we can process several chains in parallel.
310     if (!CurNode->HasChildren() || JT->IsLast()) {
311       if (OutputFilename.empty()) {
312         Out.set("a");
313         Out.appendSuffix(JT->OutputSuffix());
314       }
315       else
316         Out.set(OutputFilename);
317       IsLast = true;
318     }
319     else {
320       Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
321     }
322
323     if (JT->GenerateAction(Out).Execute() != 0)
324       throw std::runtime_error("Tool returned error code!");
325
326     if (!IsLast) {
327       const Node* NextNode = &getNode(ChooseEdge(CurNode->OutEdges,
328                                                  CurNode->Name())->ToolName());
329       PassThroughGraph(Out, NextNode, TempDir);
330     }
331   }
332
333   return 0;
334 }
335
336 // Code related to graph visualization.
337
338 namespace llvm {
339   template <>
340   struct DOTGraphTraits<llvmc::CompilationGraph*>
341     : public DefaultDOTGraphTraits
342   {
343
344     template<typename GraphType>
345     static std::string getNodeLabel(const Node* N, const GraphType&)
346     {
347       if (N->ToolPtr)
348         if (N->ToolPtr->IsJoin())
349           return N->Name() + "\n (join" +
350             (N->HasChildren() ? ")"
351              : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
352         else
353           return N->Name();
354       else
355         return "root";
356     }
357
358     template<typename EdgeIter>
359     static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
360       if (N->ToolPtr)
361         return N->ToolPtr->OutputLanguage();
362       else
363         return I->ToolPtr->InputLanguage();
364     }
365   };
366
367 }
368
369 void CompilationGraph::writeGraph() {
370   std::ofstream O("CompilationGraph.dot");
371
372   if (O.good()) {
373     llvm::WriteGraph(this, "compilation-graph");
374     O.close();
375   }
376   else {
377     throw std::runtime_error("");
378   }
379 }
380
381 void CompilationGraph::viewGraph() {
382   llvm::ViewGraph(this, "compilation-graph");
383 }