1 //===--- CompilationGraph.cpp - The LLVM Compiler Driver --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Compilation graph - implementation.
12 //===----------------------------------------------------------------------===//
14 #include "CompilationGraph.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/DOTGraphTraits.h"
19 #include "llvm/Support/GraphWriter.h"
28 using namespace llvmc;
30 extern cl::list<std::string> InputFilenames;
31 extern cl::opt<std::string> OutputFilename;
32 extern cl::list<std::string> Languages;
36 // Return the edge with the maximum weight.
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;
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();
53 else if (EW == MaxWeight) {
59 throw std::runtime_error("Node " + NodeName +
60 ": multiple maximal outward edges found!"
61 " Most probably a specification error.");
63 throw std::runtime_error("Node " + NodeName +
64 ": no maximal outward edge found!"
65 " Most probably a specification error.");
71 CompilationGraph::CompilationGraph() {
72 NodesMap["root"] = Node(this);
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");
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!");
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() + '!');
96 const CompilationGraph::tools_vector_type&
97 CompilationGraph::getToolsVector(const std::string& LangName) const
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!");
106 void CompilationGraph::insertNode(Tool* V) {
107 if (NodesMap.count(V->Name()) == 0) {
109 N.OwningGraph = this;
111 NodesMap[V->Name()] = N;
115 void CompilationGraph::insertEdge(const std::string& A, Edge* E) {
116 Node& B = getNode(E->ToolName());
118 const std::string& InputLanguage = B.ToolPtr->InputLanguage();
119 ToolsMap[InputLanguage].push_back(IntrusiveRefCntPtr<Edge>(E));
120 NodesMap["root"].AddEdge(E);
123 Node& N = getNode(A);
126 // Increase the inward edge counter.
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);
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 {
147 sys::Path In = InFile;
148 const Node* CurNode = StartNode;
152 Tool* CurTool = CurNode->ToolPtr.getPtr();
154 if (CurTool->IsJoin()) {
155 JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
156 JT.AddToJoinList(In);
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);
167 Out.set(In.getBasename());
168 Out.appendSuffix(CurTool->OutputSuffix());
173 Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
176 if (CurTool->GenerateAction(In, Out).Execute() != 0)
177 throw std::runtime_error("Tool returned error code!");
182 CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
183 CurNode->Name())->ToolName());
184 In = Out; Out.clear();
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"));
194 const Node* A = Q.front();
197 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
199 Node* B = &getNode((*EB)->ToolName());
201 if (B->HasNoInEdges())
208 bool NotJoinNode(const Node* N) {
209 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
213 // Call TopologicalSort and filter the resulting list to include
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);
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);
230 throw std::runtime_error("No toolchain corresponding to language"
231 + InLanguage + " found!");
232 return &getNode(ChooseEdge(TV)->ToolName());
235 // Build the targets. Command-line options are passed through
236 // temporary variables.
237 int CompilationGraph::Build (const sys::Path& TempDir) {
239 // This is related to -x option handling.
240 cl::list<std::string>::const_iterator xIter = Languages.begin(),
241 xBegin = xIter, xEnd = Languages.end();
243 const std::string* xLanguage = 0;
244 unsigned xPos = 0, xPosNext = 0, filePos = 0;
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);
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);
260 // Code for handling the -x option.
261 // Output: std::string* xLanguage (can be NULL).
263 filePos = InputFilenames.getPosition(B - CB);
265 if (xPos < filePos) {
266 if (filePos < xPosNext) {
267 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
269 else { // filePos >= xPosNext
270 // Skip xIters while filePos > xPosNext
271 while (filePos > xPosNext) {
275 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
277 xPosNext = std::numeric_limits<unsigned>::max();
279 xPosNext = Languages.getPosition(xNext - xBegin);
280 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
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);
292 std::vector<const Node*> JTV;
293 TopologicalSortFilterJoinNodes(JTV);
295 // For all join nodes in topological order:
296 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
300 const Node* CurNode = *B;
301 JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
304 // Are there any files to be joined?
305 if (JT->JoinListEmpty())
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()) {
313 Out.appendSuffix(JT->OutputSuffix());
316 Out.set(OutputFilename);
320 Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
323 if (JT->GenerateAction(Out).Execute() != 0)
324 throw std::runtime_error("Tool returned error code!");
327 const Node* NextNode = &getNode(ChooseEdge(CurNode->OutEdges,
328 CurNode->Name())->ToolName());
329 PassThroughGraph(Out, NextNode, TempDir);
336 // Code related to graph visualization.
340 struct DOTGraphTraits<llvmc::CompilationGraph*>
341 : public DefaultDOTGraphTraits
344 template<typename GraphType>
345 static std::string getNodeLabel(const Node* N, const GraphType&)
348 if (N->ToolPtr->IsJoin())
349 return N->Name() + "\n (join" +
350 (N->HasChildren() ? ")"
351 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
358 template<typename EdgeIter>
359 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
361 return N->ToolPtr->OutputLanguage();
363 return I->ToolPtr->InputLanguage();
369 void CompilationGraph::writeGraph() {
370 std::ofstream O("CompilationGraph.dot");
373 llvm::WriteGraph(this, "compilation-graph");
377 throw std::runtime_error("");
381 void CompilationGraph::viewGraph() {
382 llvm::ViewGraph(this, "compilation-graph");