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"
30 using namespace llvmc;
34 const std::string* LanguageMap::GetLanguage(const sys::Path& File) const {
35 StringRef suf = File.getSuffix();
36 LanguageMap::const_iterator Lang =
37 this->find(suf.empty() ? "*empty*" : suf);
38 if (Lang == this->end()) {
39 PrintError("File '" + File.str() + "' has unknown suffix '"
49 /// ChooseEdge - Return the edge with the maximum weight.
51 const Edge* ChooseEdge(const C& EdgesContainer,
52 const InputLanguagesSet& InLangs,
53 const std::string& NodeName = "root") {
54 const Edge* MaxEdge = 0;
55 unsigned MaxWeight = 0;
56 bool SingleMax = true;
58 for (typename C::const_iterator B = EdgesContainer.begin(),
59 E = EdgesContainer.end(); B != E; ++B) {
60 const Edge* e = B->getPtr();
61 unsigned EW = e->Weight(InLangs);
66 } else if (EW == MaxWeight) {
72 PrintError("Node " + NodeName + ": multiple maximal outward edges found!"
73 " Most probably a specification error.");
77 PrintError("Node " + NodeName + ": no maximal outward edge found!"
78 " Most probably a specification error.");
86 void Node::AddEdge(Edge* Edg) {
87 // If there already was an edge between two nodes, modify it instead
88 // of adding a new edge.
89 const std::string& ToolName = Edg->ToolName();
90 for (container_type::iterator B = OutEdges.begin(), E = OutEdges.end();
92 if ((*B)->ToolName() == ToolName) {
93 llvm::IntrusiveRefCntPtr<Edge>(Edg).swap(*B);
97 OutEdges.push_back(llvm::IntrusiveRefCntPtr<Edge>(Edg));
100 CompilationGraph::CompilationGraph() {
101 NodesMap["root"] = Node(this);
104 Node* CompilationGraph::getNode(const std::string& ToolName) {
105 nodes_map_type::iterator I = NodesMap.find(ToolName);
106 if (I == NodesMap.end()) {
107 PrintError("Node " + ToolName + " is not in the graph");
113 const Node* CompilationGraph::getNode(const std::string& ToolName) const {
114 nodes_map_type::const_iterator I = NodesMap.find(ToolName);
115 if (I == NodesMap.end()) {
116 PrintError("Node " + ToolName + " is not in the graph!");
122 // Find the tools list corresponding to the given language name.
123 const CompilationGraph::tools_vector_type*
124 CompilationGraph::getToolsVector(const std::string& LangName) const
126 tools_map_type::const_iterator I = ToolsMap.find(LangName);
127 if (I == ToolsMap.end()) {
128 PrintError("No tool corresponding to the language " + LangName + " found");
134 void CompilationGraph::insertNode(Tool* V) {
135 if (NodesMap.count(V->Name()) == 0)
136 NodesMap[V->Name()] = Node(this, V);
139 int CompilationGraph::insertEdge(const std::string& A, Edge* Edg) {
140 Node* B = getNode(Edg->ToolName());
145 const char** InLangs = B->ToolPtr->InputLanguages();
146 for (;*InLangs; ++InLangs)
147 ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr<Edge>(Edg));
148 NodesMap["root"].AddEdge(Edg);
151 Node* N = getNode(A);
157 // Increase the inward edge counter.
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 int CompilationGraph::PassThroughGraph (const sys::Path& InFile,
166 const Node* StartNode,
167 const InputLanguagesSet& InLangs,
168 const sys::Path& TempDir,
169 const LanguageMap& LangMap) const {
170 sys::Path In = InFile;
171 const Node* CurNode = StartNode;
174 Tool* CurTool = CurNode->ToolPtr.getPtr();
176 if (CurTool->IsJoin()) {
177 JoinTool& JT = static_cast<JoinTool&>(*CurTool);
178 JT.AddToJoinList(In);
183 if (int ret = CurTool->GenerateAction(CurAction, In, CurNode->HasChildren(),
184 TempDir, InLangs, LangMap)) {
188 if (int ret = CurAction.Execute())
191 if (CurAction.StopCompilation())
194 const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name());
198 CurNode = getNode(Edg->ToolName());
202 In = CurAction.OutFile();
208 // Find the head of the toolchain corresponding to the given file.
209 // Also, insert an input language into InLangs.
210 const Node* CompilationGraph::
211 FindToolChain(const sys::Path& In, const std::string* ForceLanguage,
212 InputLanguagesSet& InLangs, const LanguageMap& LangMap) const {
214 // Determine the input language.
215 const std::string* InLang = LangMap.GetLanguage(In);
218 const std::string& InLanguage = (ForceLanguage ? *ForceLanguage : *InLang);
220 // Add the current input language to the input language set.
221 InLangs.insert(InLanguage);
223 // Find the toolchain for the input language.
224 const tools_vector_type* pTV = getToolsVector(InLanguage);
228 const tools_vector_type& TV = *pTV;
230 PrintError("No toolchain corresponding to language "
231 + InLanguage + " found");
235 const Edge* Edg = ChooseEdge(TV, InLangs);
239 return getNode(Edg->ToolName());
242 // Helper function used by Build().
243 // Traverses initial portions of the toolchains (up to the first Join node).
244 // This function is also responsible for handling the -x option.
245 int CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
246 const sys::Path& TempDir,
247 const LanguageMap& LangMap) {
248 // This is related to -x option handling.
249 cl::list<std::string>::const_iterator xIter = Languages.begin(),
250 xBegin = xIter, xEnd = Languages.end();
252 const std::string* xLanguage = 0;
253 unsigned xPos = 0, xPosNext = 0, filePos = 0;
257 xPos = Languages.getPosition(xIter - xBegin);
258 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
259 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
260 : Languages.getPosition(xNext - xBegin);
261 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
264 // For each input file:
265 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
266 CB = B, E = InputFilenames.end(); B != E; ++B) {
267 sys::Path In = sys::Path(*B);
269 // Code for handling the -x option.
270 // Output: std::string* xLanguage (can be NULL).
272 filePos = InputFilenames.getPosition(B - CB);
274 if (xPos < filePos) {
275 if (filePos < xPosNext) {
276 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
278 else { // filePos >= xPosNext
279 // Skip xIters while filePos > xPosNext
280 while (filePos > xPosNext) {
284 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
286 xPosNext = std::numeric_limits<unsigned>::max();
288 xPosNext = Languages.getPosition(xNext - xBegin);
289 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
295 // Find the toolchain corresponding to this file.
296 const Node* N = FindToolChain(In, xLanguage, InLangs, LangMap);
299 // Pass file through the chain starting at head.
300 if (int ret = PassThroughGraph(In, N, InLangs, TempDir, LangMap))
307 // Sort the nodes in topological order.
308 int CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
309 std::queue<const Node*> Q;
311 Node* Root = getNode("root");
318 const Node* A = Q.front();
321 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
323 Node* B = getNode((*EB)->ToolName());
328 if (B->HasNoInEdges())
337 bool NotJoinNode(const Node* N) {
338 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
342 // Call TopologicalSort and filter the resulting list to include
344 int CompilationGraph::
345 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
346 std::vector<const Node*> TopSorted;
347 if (int ret = TopologicalSort(TopSorted))
349 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
350 std::back_inserter(Out), NotJoinNode);
355 int CompilationGraph::Build (const sys::Path& TempDir,
356 const LanguageMap& LangMap) {
357 InputLanguagesSet InLangs;
359 // Traverse initial parts of the toolchains and fill in InLangs.
360 if (int ret = BuildInitial(InLangs, TempDir, LangMap))
363 std::vector<const Node*> JTV;
364 if (int ret = TopologicalSortFilterJoinNodes(JTV))
367 // For all join nodes in topological order:
368 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
371 const Node* CurNode = *B;
372 JoinTool* JT = &static_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
374 // Are there any files in the join list?
375 if (JT->JoinListEmpty() && !(JT->WorksOnEmpty() && InputFilenames.empty()))
379 if (int ret = JT->GenerateAction(CurAction, CurNode->HasChildren(),
380 TempDir, InLangs, LangMap)) {
384 if (int ret = CurAction.Execute())
387 if (CurAction.StopCompilation())
390 const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name());
394 const Node* NextNode = getNode(Edg->ToolName());
398 if (int ret = PassThroughGraph(sys::Path(CurAction.OutFile()), NextNode,
399 InLangs, TempDir, LangMap)) {
407 int CompilationGraph::CheckLanguageNames() const {
410 // Check that names for output and input languages on all edges do match.
411 for (const_nodes_iterator B = this->NodesMap.begin(),
412 E = this->NodesMap.end(); B != E; ++B) {
414 const Node & N1 = B->second;
416 for (Node::const_iterator EB = N1.EdgesBegin(), EE = N1.EdgesEnd();
418 const Node* N2 = this->getNode((*EB)->ToolName());
424 errs() << "Error: there is an edge from '" << N1.ToolPtr->Name()
425 << "' back to the root!\n\n";
429 const char* OutLang = N1.ToolPtr->OutputLanguage();
430 const char** InLangs = N2->ToolPtr->InputLanguages();
432 for (;*InLangs; ++InLangs) {
433 if (std::strcmp(OutLang, *InLangs) == 0) {
441 errs() << "Error: Output->input language mismatch in the edge '"
442 << N1.ToolPtr->Name() << "' -> '" << N2->ToolPtr->Name()
444 << "Expected one of { ";
446 InLangs = N2->ToolPtr->InputLanguages();
447 for (;*InLangs; ++InLangs) {
448 errs() << '\'' << *InLangs << (*(InLangs+1) ? "', " : "'");
451 errs() << " }, but got '" << OutLang << "'!\n\n";
461 int CompilationGraph::CheckMultipleDefaultEdges() const {
463 InputLanguagesSet Dummy;
465 // For all nodes, just iterate over the outgoing edges and check if there is
466 // more than one edge with maximum weight.
467 for (const_nodes_iterator B = this->NodesMap.begin(),
468 E = this->NodesMap.end(); B != E; ++B) {
469 const Node& N = B->second;
470 unsigned MaxWeight = 0;
472 // Ignore the root node.
476 for (Node::const_iterator EB = N.EdgesBegin(), EE = N.EdgesEnd();
478 unsigned EdgeWeight = (*EB)->Weight(Dummy);
479 if (EdgeWeight > MaxWeight) {
480 MaxWeight = EdgeWeight;
482 else if (EdgeWeight == MaxWeight) {
484 errs() << "Error: there are multiple maximal edges stemming from the '"
485 << N.ToolPtr->Name() << "' node!\n\n";
494 int CompilationGraph::CheckCycles() {
495 unsigned deleted = 0;
498 Node* Root = getNode("root");
504 // Try to delete all nodes that have no ingoing edges, starting from the
505 // root. If there are any nodes left after this operation, then we have a
506 // cycle. This relies on '--check-graph' not performing the topological sort.
512 for (Node::iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
514 Node* B = getNode((*EB)->ToolName());
519 if (B->HasNoInEdges())
524 if (deleted != NodesMap.size()) {
525 errs() << "Error: there are cycles in the compilation graph!\n"
526 << "Try inspecting the diagram produced by "
527 << "'llvmc --view-graph'.\n\n";
534 int CompilationGraph::Check () {
535 // We try to catch as many errors as we can in one go.
539 // Check that output/input language names match.
540 ret = this->CheckLanguageNames();
545 // Check for multiple default edges.
546 ret = this->CheckMultipleDefaultEdges();
552 ret = this->CheckCycles();
560 // Code related to graph visualization.
564 struct DOTGraphTraits<llvmc::CompilationGraph*>
565 : public DefaultDOTGraphTraits
567 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
569 template<typename GraphType>
570 static std::string getNodeLabel(const Node* N, const GraphType&)
573 if (N->ToolPtr->IsJoin())
574 return N->Name() + "\n (join" +
575 (N->HasChildren() ? ")"
576 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
583 template<typename EdgeIter>
584 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
586 return N->ToolPtr->OutputLanguage();
589 const char** InLangs = I->ToolPtr->InputLanguages();
592 for (; *InLangs; ++InLangs) {
593 if (*(InLangs + 1)) {
609 int CompilationGraph::writeGraph(const std::string& OutputFilename) {
610 std::string ErrorInfo;
611 raw_fd_ostream O(OutputFilename.c_str(), ErrorInfo);
613 if (ErrorInfo.empty()) {
614 errs() << "Writing '"<< OutputFilename << "' file...";
615 llvm::WriteGraph(O, this);
619 PrintError("Error opening file '" + OutputFilename + "' for writing!");
626 void CompilationGraph::viewGraph() {
627 llvm::ViewGraph(this, "compilation-graph");