Updated VS build system. Patch provided by Cedric Venet:
[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;
143
144     // Make sure we don't end up with path names like '/file.o' if the
145     // TempDir is empty.
146     if (TempDir.empty()) {
147       Out.set(BaseName);
148     }
149     else {
150       Out = TempDir;
151       Out.appendComponent(BaseName);
152     }
153     Out.appendSuffix(Suffix);
154     // NOTE: makeUnique always *creates* a unique temporary file,
155     // which is good, since there will be no races. However, some
156     // tools do not like it when the output file already exists, so
157     // they have to be placated with -f or something like that.
158     Out.makeUnique(true, NULL);
159     return Out;
160   }
161 }
162
163 // Pass input file through the chain until we bump into a Join node or
164 // a node that says that it is the last.
165 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
166                                          const Node* StartNode,
167                                          const InputLanguagesSet& InLangs,
168                                          const sys::Path& TempDir) const {
169   bool Last = false;
170   sys::Path In = InFile;
171   const Node* CurNode = StartNode;
172
173   while(!Last) {
174     sys::Path Out;
175     Tool* CurTool = CurNode->ToolPtr.getPtr();
176
177     if (CurTool->IsJoin()) {
178       JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
179       JT.AddToJoinList(In);
180       break;
181     }
182
183     // Since toolchains do not have to end with a Join node, we should
184     // check if this Node is the last.
185     if (!CurNode->HasChildren() || CurTool->IsLast()) {
186       if (!OutputFilename.empty()) {
187         Out.set(OutputFilename);
188       }
189       else {
190         Out.set(In.getBasename());
191         Out.appendSuffix(CurTool->OutputSuffix());
192       }
193       Last = true;
194     }
195     else {
196       Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
197     }
198
199     if (int ret = CurTool->GenerateAction(In, Out, InLangs).Execute())
200       throw error_code(ret);
201
202     if (Last)
203       return;
204
205     CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
206                                   InLangs,
207                                   CurNode->Name())->ToolName());
208     In = Out; Out.clear();
209   }
210 }
211
212 // Find the head of the toolchain corresponding to the given file.
213 // Also, insert an input language into InLangs.
214 const Node* CompilationGraph::
215 FindToolChain(const sys::Path& In, const std::string* forceLanguage,
216               InputLanguagesSet& InLangs) const {
217
218   // Determine the input language.
219   const std::string& InLanguage =
220     forceLanguage ? *forceLanguage : GetLanguage(In);
221
222   // Add the current input language to the input language set.
223   InLangs.insert(InLanguage);
224
225   // Find the toolchain for the input language.
226   const tools_vector_type& TV = getToolsVector(InLanguage);
227   if (TV.empty())
228     throw std::runtime_error("No toolchain corresponding to language "
229                              + InLanguage + " found");
230   return &getNode(ChooseEdge(TV, InLangs)->ToolName());
231 }
232
233 // Helper function used by Build().
234 // Traverses initial portions of the toolchains (up to the first Join node).
235 // This function is also responsible for handling the -x option.
236 void CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
237                                      const sys::Path& TempDir) {
238   // This is related to -x option handling.
239   cl::list<std::string>::const_iterator xIter = Languages.begin(),
240     xBegin = xIter, xEnd = Languages.end();
241   bool xEmpty = true;
242   const std::string* xLanguage = 0;
243   unsigned xPos = 0, xPosNext = 0, filePos = 0;
244
245   if (xIter != xEnd) {
246     xEmpty = false;
247     xPos = Languages.getPosition(xIter - xBegin);
248     cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
249     xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
250       : Languages.getPosition(xNext - xBegin);
251     xLanguage = (*xIter == "none") ? 0 : &(*xIter);
252   }
253
254   // For each input file:
255   for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
256          CB = B, E = InputFilenames.end(); B != E; ++B) {
257     sys::Path In = sys::Path(*B);
258
259     // Code for handling the -x option.
260     // Output: std::string* xLanguage (can be NULL).
261     if (!xEmpty) {
262       filePos = InputFilenames.getPosition(B - CB);
263
264       if (xPos < filePos) {
265         if (filePos < xPosNext) {
266           xLanguage = (*xIter == "none") ? 0 : &(*xIter);
267         }
268         else { // filePos >= xPosNext
269           // Skip xIters while filePos > xPosNext
270           while (filePos > xPosNext) {
271             ++xIter;
272             xPos = xPosNext;
273
274             cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
275             if (xNext == xEnd)
276               xPosNext = std::numeric_limits<unsigned>::max();
277             else
278               xPosNext = Languages.getPosition(xNext - xBegin);
279             xLanguage = (*xIter == "none") ? 0 : &(*xIter);
280           }
281         }
282       }
283     }
284
285     // Find the toolchain corresponding to this file.
286     const Node* N = FindToolChain(In, xLanguage, InLangs);
287     // Pass file through the chain starting at head.
288     PassThroughGraph(In, N, InLangs, TempDir);
289   }
290 }
291
292 // Sort the nodes in topological order.
293 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
294   std::queue<const Node*> Q;
295   Q.push(&getNode("root"));
296
297   while (!Q.empty()) {
298     const Node* A = Q.front();
299     Q.pop();
300     Out.push_back(A);
301     for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
302          EB != EE; ++EB) {
303       Node* B = &getNode((*EB)->ToolName());
304       B->DecrInEdges();
305       if (B->HasNoInEdges())
306         Q.push(B);
307     }
308   }
309 }
310
311 namespace {
312   bool NotJoinNode(const Node* N) {
313     return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
314   }
315 }
316
317 // Call TopologicalSort and filter the resulting list to include
318 // only Join nodes.
319 void CompilationGraph::
320 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
321   std::vector<const Node*> TopSorted;
322   TopologicalSort(TopSorted);
323   std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
324                       std::back_inserter(Out), NotJoinNode);
325 }
326
327 int CompilationGraph::Build (const sys::Path& TempDir) {
328
329   InputLanguagesSet InLangs;
330
331   // Traverse initial parts of the toolchains and fill in InLangs.
332   BuildInitial(InLangs, TempDir);
333
334   std::vector<const Node*> JTV;
335   TopologicalSortFilterJoinNodes(JTV);
336
337   // For all join nodes in topological order:
338   for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
339        B != E; ++B) {
340
341     sys::Path Out;
342     const Node* CurNode = *B;
343     JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
344     bool IsLast = false;
345
346     // Are there any files in the join list?
347     if (JT->JoinListEmpty())
348       continue;
349
350     // Is this the last tool in the toolchain?
351     // NOTE: we can process several toolchains in parallel.
352     if (!CurNode->HasChildren() || JT->IsLast()) {
353       if (OutputFilename.empty()) {
354         Out.set("a");
355         Out.appendSuffix(JT->OutputSuffix());
356       }
357       else
358         Out.set(OutputFilename);
359       IsLast = true;
360     }
361     else {
362       Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
363     }
364
365     if (int ret = JT->GenerateAction(Out, InLangs).Execute())
366       throw error_code(ret);
367
368     if (!IsLast) {
369       const Node* NextNode =
370         &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
371                             CurNode->Name())->ToolName());
372       PassThroughGraph(Out, NextNode, InLangs, TempDir);
373     }
374   }
375
376   return 0;
377 }
378
379 // Code related to graph visualization.
380
381 namespace llvm {
382   template <>
383   struct DOTGraphTraits<llvmc::CompilationGraph*>
384     : public DefaultDOTGraphTraits
385   {
386
387     template<typename GraphType>
388     static std::string getNodeLabel(const Node* N, const GraphType&)
389     {
390       if (N->ToolPtr)
391         if (N->ToolPtr->IsJoin())
392           return N->Name() + "\n (join" +
393             (N->HasChildren() ? ")"
394              : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
395         else
396           return N->Name();
397       else
398         return "root";
399     }
400
401     template<typename EdgeIter>
402     static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
403       if (N->ToolPtr) {
404         return N->ToolPtr->OutputLanguage();
405       }
406       else {
407         const char** InLangs = I->ToolPtr->InputLanguages();
408         std::string ret;
409
410         for (; *InLangs; ++InLangs) {
411           if (*(InLangs + 1)) {
412             ret += *InLangs;
413             ret +=  ", ";
414           }
415           else {
416             ret += *InLangs;
417           }
418         }
419
420         return ret;
421       }
422     }
423   };
424
425 }
426
427 void CompilationGraph::writeGraph() {
428   std::ofstream O("compilation-graph.dot");
429
430   if (O.good()) {
431     llvm::WriteGraph(this, "compilation-graph");
432     O.close();
433   }
434   else {
435     throw std::runtime_error("Error opening file 'compilation-graph.dot'"
436                              " for writing!");
437   }
438 }
439
440 void CompilationGraph::viewGraph() {
441   llvm::ViewGraph(this, "compilation-graph");
442 }