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 "llvm/CompilerDriver/BuiltinOptions.h"
15 #include "llvm/CompilerDriver/CompilationGraph.h"
16 #include "llvm/CompilerDriver/Error.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/DOTGraphTraits.h"
20 #include "llvm/Support/GraphWriter.h"
21 #include "llvm/Support/raw_ostream.h"
31 using namespace llvmc;
35 const std::string& LanguageMap::GetLanguage(const sys::Path& File) const {
36 StringRef suf = File.getSuffix();
37 LanguageMap::const_iterator Lang = this->find(suf);
38 if (Lang == this->end())
39 throw std::runtime_error("File '" + File.str() +
40 "' has unknown suffix '" + suf.str() + '\'');
47 /// ChooseEdge - Return the edge with the maximum weight.
49 const Edge* ChooseEdge(const C& EdgesContainer,
50 const InputLanguagesSet& InLangs,
51 const std::string& NodeName = "root") {
52 const Edge* MaxEdge = 0;
53 unsigned MaxWeight = 0;
54 bool SingleMax = true;
56 for (typename C::const_iterator B = EdgesContainer.begin(),
57 E = EdgesContainer.end(); B != E; ++B) {
58 const Edge* e = B->getPtr();
59 unsigned EW = e->Weight(InLangs);
64 } else if (EW == MaxWeight) {
70 throw std::runtime_error("Node " + NodeName +
71 ": multiple maximal outward edges found!"
72 " Most probably a specification error.");
74 throw std::runtime_error("Node " + NodeName +
75 ": no maximal outward edge found!"
76 " Most probably a specification error.");
82 void Node::AddEdge(Edge* Edg) {
83 // If there already was an edge between two nodes, modify it instead
84 // of adding a new edge.
85 const std::string& ToolName = Edg->ToolName();
86 for (container_type::iterator B = OutEdges.begin(), E = OutEdges.end();
88 if ((*B)->ToolName() == ToolName) {
89 llvm::IntrusiveRefCntPtr<Edge>(Edg).swap(*B);
93 OutEdges.push_back(llvm::IntrusiveRefCntPtr<Edge>(Edg));
96 CompilationGraph::CompilationGraph() {
97 NodesMap["root"] = Node(this);
100 Node& CompilationGraph::getNode(const std::string& ToolName) {
101 nodes_map_type::iterator I = NodesMap.find(ToolName);
102 if (I == NodesMap.end())
103 throw std::runtime_error("Node " + ToolName + " is not in the graph");
107 const Node& CompilationGraph::getNode(const std::string& ToolName) const {
108 nodes_map_type::const_iterator I = NodesMap.find(ToolName);
109 if (I == NodesMap.end())
110 throw std::runtime_error("Node " + ToolName + " is not in the graph!");
114 // Find the tools list corresponding to the given language name.
115 const CompilationGraph::tools_vector_type&
116 CompilationGraph::getToolsVector(const std::string& LangName) const
118 tools_map_type::const_iterator I = ToolsMap.find(LangName);
119 if (I == ToolsMap.end())
120 throw std::runtime_error("No tool corresponding to the language "
121 + LangName + " found");
125 void CompilationGraph::insertNode(Tool* V) {
126 if (NodesMap.count(V->Name()) == 0)
127 NodesMap[V->Name()] = Node(this, V);
130 void CompilationGraph::insertEdge(const std::string& A, Edge* Edg) {
131 Node& B = getNode(Edg->ToolName());
133 const char** InLangs = B.ToolPtr->InputLanguages();
134 for (;*InLangs; ++InLangs)
135 ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr<Edge>(Edg));
136 NodesMap["root"].AddEdge(Edg);
139 Node& N = getNode(A);
142 // Increase the inward edge counter.
146 // Pass input file through the chain until we bump into a Join node or
147 // a node that says that it is the last.
148 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
149 const Node* StartNode,
150 const InputLanguagesSet& InLangs,
151 const sys::Path& TempDir,
152 const LanguageMap& LangMap) const {
153 sys::Path In = InFile;
154 const Node* CurNode = StartNode;
157 Tool* CurTool = CurNode->ToolPtr.getPtr();
159 if (CurTool->IsJoin()) {
160 JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
161 JT.AddToJoinList(In);
165 Action CurAction = CurTool->GenerateAction(In, CurNode->HasChildren(),
166 TempDir, InLangs, LangMap);
168 if (int ret = CurAction.Execute())
169 throw error_code(ret);
171 if (CurAction.StopCompilation())
174 CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
176 CurNode->Name())->ToolName());
177 In = CurAction.OutFile();
181 // Find the head of the toolchain corresponding to the given file.
182 // Also, insert an input language into InLangs.
183 const Node* CompilationGraph::
184 FindToolChain(const sys::Path& In, const std::string* ForceLanguage,
185 InputLanguagesSet& InLangs, const LanguageMap& LangMap) const {
187 // Determine the input language.
188 const std::string& InLanguage =
189 ForceLanguage ? *ForceLanguage : LangMap.GetLanguage(In);
191 // Add the current input language to the input language set.
192 InLangs.insert(InLanguage);
194 // Find the toolchain for the input language.
195 const tools_vector_type& TV = getToolsVector(InLanguage);
197 throw std::runtime_error("No toolchain corresponding to language "
198 + InLanguage + " found");
199 return &getNode(ChooseEdge(TV, InLangs)->ToolName());
202 // Helper function used by Build().
203 // Traverses initial portions of the toolchains (up to the first Join node).
204 // This function is also responsible for handling the -x option.
205 void CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
206 const sys::Path& TempDir,
207 const LanguageMap& LangMap) {
208 // This is related to -x option handling.
209 cl::list<std::string>::const_iterator xIter = Languages.begin(),
210 xBegin = xIter, xEnd = Languages.end();
212 const std::string* xLanguage = 0;
213 unsigned xPos = 0, xPosNext = 0, filePos = 0;
217 xPos = Languages.getPosition(xIter - xBegin);
218 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
219 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
220 : Languages.getPosition(xNext - xBegin);
221 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
224 // For each input file:
225 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
226 CB = B, E = InputFilenames.end(); B != E; ++B) {
227 sys::Path In = sys::Path(*B);
229 // Code for handling the -x option.
230 // Output: std::string* xLanguage (can be NULL).
232 filePos = InputFilenames.getPosition(B - CB);
234 if (xPos < filePos) {
235 if (filePos < xPosNext) {
236 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
238 else { // filePos >= xPosNext
239 // Skip xIters while filePos > xPosNext
240 while (filePos > xPosNext) {
244 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
246 xPosNext = std::numeric_limits<unsigned>::max();
248 xPosNext = Languages.getPosition(xNext - xBegin);
249 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
255 // Find the toolchain corresponding to this file.
256 const Node* N = FindToolChain(In, xLanguage, InLangs, LangMap);
257 // Pass file through the chain starting at head.
258 PassThroughGraph(In, N, InLangs, TempDir, LangMap);
262 // Sort the nodes in topological order.
263 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
264 std::queue<const Node*> Q;
265 Q.push(&getNode("root"));
268 const Node* A = Q.front();
271 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
273 Node* B = &getNode((*EB)->ToolName());
275 if (B->HasNoInEdges())
282 bool NotJoinNode(const Node* N) {
283 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
287 // Call TopologicalSort and filter the resulting list to include
289 void CompilationGraph::
290 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
291 std::vector<const Node*> TopSorted;
292 TopologicalSort(TopSorted);
293 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
294 std::back_inserter(Out), NotJoinNode);
297 int CompilationGraph::Build (const sys::Path& TempDir,
298 const LanguageMap& LangMap) {
300 InputLanguagesSet InLangs;
302 // Traverse initial parts of the toolchains and fill in InLangs.
303 BuildInitial(InLangs, TempDir, LangMap);
305 std::vector<const Node*> JTV;
306 TopologicalSortFilterJoinNodes(JTV);
308 // For all join nodes in topological order:
309 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
312 const Node* CurNode = *B;
313 JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
315 // Are there any files in the join list?
316 if (JT->JoinListEmpty())
319 Action CurAction = JT->GenerateAction(CurNode->HasChildren(),
320 TempDir, InLangs, LangMap);
322 if (int ret = CurAction.Execute())
323 throw error_code(ret);
325 if (CurAction.StopCompilation())
328 const Node* NextNode = &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
329 CurNode->Name())->ToolName());
330 PassThroughGraph(sys::Path(CurAction.OutFile()), NextNode,
331 InLangs, TempDir, LangMap);
337 int CompilationGraph::CheckLanguageNames() const {
339 // Check that names for output and input languages on all edges do match.
340 for (const_nodes_iterator B = this->NodesMap.begin(),
341 E = this->NodesMap.end(); B != E; ++B) {
343 const Node & N1 = B->second;
345 for (Node::const_iterator EB = N1.EdgesBegin(), EE = N1.EdgesEnd();
347 const Node& N2 = this->getNode((*EB)->ToolName());
351 errs() << "Error: there is an edge from '" << N1.ToolPtr->Name()
352 << "' back to the root!\n\n";
356 const char* OutLang = N1.ToolPtr->OutputLanguage();
357 const char** InLangs = N2.ToolPtr->InputLanguages();
359 for (;*InLangs; ++InLangs) {
360 if (std::strcmp(OutLang, *InLangs) == 0) {
368 errs() << "Error: Output->input language mismatch in the edge '"
369 << N1.ToolPtr->Name() << "' -> '" << N2.ToolPtr->Name()
371 << "Expected one of { ";
373 InLangs = N2.ToolPtr->InputLanguages();
374 for (;*InLangs; ++InLangs) {
375 errs() << '\'' << *InLangs << (*(InLangs+1) ? "', " : "'");
378 errs() << " }, but got '" << OutLang << "'!\n\n";
388 int CompilationGraph::CheckMultipleDefaultEdges() const {
390 InputLanguagesSet Dummy;
392 // For all nodes, just iterate over the outgoing edges and check if there is
393 // more than one edge with maximum weight.
394 for (const_nodes_iterator B = this->NodesMap.begin(),
395 E = this->NodesMap.end(); B != E; ++B) {
396 const Node& N = B->second;
397 unsigned MaxWeight = 0;
399 // Ignore the root node.
403 for (Node::const_iterator EB = N.EdgesBegin(), EE = N.EdgesEnd();
405 unsigned EdgeWeight = (*EB)->Weight(Dummy);
406 if (EdgeWeight > MaxWeight) {
407 MaxWeight = EdgeWeight;
409 else if (EdgeWeight == MaxWeight) {
411 errs() << "Error: there are multiple maximal edges stemming from the '"
412 << N.ToolPtr->Name() << "' node!\n\n";
421 int CompilationGraph::CheckCycles() {
422 unsigned deleted = 0;
424 Q.push(&getNode("root"));
426 // Try to delete all nodes that have no ingoing edges, starting from the
427 // root. If there are any nodes left after this operation, then we have a
428 // cycle. This relies on '--check-graph' not performing the topological sort.
434 for (Node::iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
436 Node* B = &getNode((*EB)->ToolName());
438 if (B->HasNoInEdges())
443 if (deleted != NodesMap.size()) {
444 errs() << "Error: there are cycles in the compilation graph!\n"
445 << "Try inspecting the diagram produced by "
446 << "'llvmc --view-graph'.\n\n";
453 int CompilationGraph::Check () {
454 // We try to catch as many errors as we can in one go.
457 // Check that output/input language names match.
458 ret += this->CheckLanguageNames();
460 // Check for multiple default edges.
461 ret += this->CheckMultipleDefaultEdges();
464 ret += this->CheckCycles();
469 // Code related to graph visualization.
473 struct DOTGraphTraits<llvmc::CompilationGraph*>
474 : public DefaultDOTGraphTraits
476 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
478 template<typename GraphType>
479 static std::string getNodeLabel(const Node* N, const GraphType&)
482 if (N->ToolPtr->IsJoin())
483 return N->Name() + "\n (join" +
484 (N->HasChildren() ? ")"
485 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
492 template<typename EdgeIter>
493 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
495 return N->ToolPtr->OutputLanguage();
498 const char** InLangs = I->ToolPtr->InputLanguages();
501 for (; *InLangs; ++InLangs) {
502 if (*(InLangs + 1)) {
518 void CompilationGraph::writeGraph(const std::string& OutputFilename) {
519 std::string ErrorInfo;
520 raw_fd_ostream O(OutputFilename.c_str(), ErrorInfo);
522 if (ErrorInfo.empty()) {
523 errs() << "Writing '"<< OutputFilename << "' file...";
524 llvm::WriteGraph(O, this);
528 throw std::runtime_error("Error opening file '" + OutputFilename
533 void CompilationGraph::viewGraph() {
534 llvm::ViewGraph(this, "compilation-graph");