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. Returns 0 on error.
51 const Edge* ChooseEdge(const C& EdgesContainer,
52 const InputLanguagesSet& InLangs,
53 const std::string& NodeName = "root") {
54 const Edge* MaxEdge = 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 int EW = e->Weight(InLangs);
63 // (error) invocation in TableGen -> we don't need to print an error
71 } else if (EW == MaxWeight) {
77 PrintError("Node " + NodeName + ": multiple maximal outward edges found!"
78 " Most probably a specification error.");
82 PrintError("Node " + NodeName + ": no maximal outward edge found!"
83 " Most probably a specification error.");
91 void Node::AddEdge(Edge* Edg) {
92 // If there already was an edge between two nodes, modify it instead
93 // of adding a new edge.
94 const std::string& ToolName = Edg->ToolName();
95 for (container_type::iterator B = OutEdges.begin(), E = OutEdges.end();
97 if ((*B)->ToolName() == ToolName) {
98 llvm::IntrusiveRefCntPtr<Edge>(Edg).swap(*B);
102 OutEdges.push_back(llvm::IntrusiveRefCntPtr<Edge>(Edg));
105 CompilationGraph::CompilationGraph() {
106 NodesMap["root"] = Node(this);
109 Node* CompilationGraph::getNode(const std::string& ToolName) {
110 nodes_map_type::iterator I = NodesMap.find(ToolName);
111 if (I == NodesMap.end()) {
112 PrintError("Node " + ToolName + " is not in the graph");
118 const Node* CompilationGraph::getNode(const std::string& ToolName) const {
119 nodes_map_type::const_iterator I = NodesMap.find(ToolName);
120 if (I == NodesMap.end()) {
121 PrintError("Node " + ToolName + " is not in the graph!");
127 // Find the tools list corresponding to the given language name.
128 const CompilationGraph::tools_vector_type*
129 CompilationGraph::getToolsVector(const std::string& LangName) const
131 tools_map_type::const_iterator I = ToolsMap.find(LangName);
132 if (I == ToolsMap.end()) {
133 PrintError("No tool corresponding to the language " + LangName + " found");
139 void CompilationGraph::insertNode(Tool* V) {
140 if (NodesMap.count(V->Name()) == 0)
141 NodesMap[V->Name()] = Node(this, V);
144 int CompilationGraph::insertEdge(const std::string& A, Edge* Edg) {
145 Node* B = getNode(Edg->ToolName());
150 const char** InLangs = B->ToolPtr->InputLanguages();
151 for (;*InLangs; ++InLangs)
152 ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr<Edge>(Edg));
153 NodesMap["root"].AddEdge(Edg);
156 Node* N = getNode(A);
162 // Increase the inward edge counter.
168 // Pass input file through the chain until we bump into a Join node or
169 // a node that says that it is the last.
170 int CompilationGraph::PassThroughGraph (const sys::Path& InFile,
171 const Node* StartNode,
172 const InputLanguagesSet& InLangs,
173 const sys::Path& TempDir,
174 const LanguageMap& LangMap) const {
175 sys::Path In = InFile;
176 const Node* CurNode = StartNode;
179 Tool* CurTool = CurNode->ToolPtr.getPtr();
181 if (CurTool->IsJoin()) {
182 JoinTool& JT = static_cast<JoinTool&>(*CurTool);
183 JT.AddToJoinList(In);
188 if (int ret = CurTool->GenerateAction(CurAction, In, CurNode->HasChildren(),
189 TempDir, InLangs, LangMap)) {
193 if (int ret = CurAction.Execute())
196 if (CurAction.StopCompilation())
199 const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name());
203 CurNode = getNode(Edg->ToolName());
207 In = CurAction.OutFile();
213 // Find the head of the toolchain corresponding to the given file.
214 // Also, insert an input language into InLangs.
215 const Node* CompilationGraph::
216 FindToolChain(const sys::Path& In, const std::string* ForceLanguage,
217 InputLanguagesSet& InLangs, const LanguageMap& LangMap) const {
219 // Determine the input language.
220 const std::string* InLang = LangMap.GetLanguage(In);
223 const std::string& InLanguage = (ForceLanguage ? *ForceLanguage : *InLang);
225 // Add the current input language to the input language set.
226 InLangs.insert(InLanguage);
228 // Find the toolchain for the input language.
229 const tools_vector_type* pTV = getToolsVector(InLanguage);
233 const tools_vector_type& TV = *pTV;
235 PrintError("No toolchain corresponding to language "
236 + InLanguage + " found");
240 const Edge* Edg = ChooseEdge(TV, InLangs);
244 return getNode(Edg->ToolName());
247 // Helper function used by Build().
248 // Traverses initial portions of the toolchains (up to the first Join node).
249 // This function is also responsible for handling the -x option.
250 int CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
251 const sys::Path& TempDir,
252 const LanguageMap& LangMap) {
253 // This is related to -x option handling.
254 cl::list<std::string>::const_iterator xIter = Languages.begin(),
255 xBegin = xIter, xEnd = Languages.end();
257 const std::string* xLanguage = 0;
258 unsigned xPos = 0, xPosNext = 0, filePos = 0;
262 xPos = Languages.getPosition(xIter - xBegin);
263 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
264 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
265 : Languages.getPosition(xNext - xBegin);
266 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
269 // For each input file:
270 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
271 CB = B, E = InputFilenames.end(); B != E; ++B) {
272 sys::Path In = sys::Path(*B);
274 // Code for handling the -x option.
275 // Output: std::string* xLanguage (can be NULL).
277 filePos = InputFilenames.getPosition(B - CB);
279 if (xPos < filePos) {
280 if (filePos < xPosNext) {
281 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
283 else { // filePos >= xPosNext
284 // Skip xIters while filePos > xPosNext
285 while (filePos > xPosNext) {
289 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
291 xPosNext = std::numeric_limits<unsigned>::max();
293 xPosNext = Languages.getPosition(xNext - xBegin);
294 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
300 // Find the toolchain corresponding to this file.
301 const Node* N = FindToolChain(In, xLanguage, InLangs, LangMap);
304 // Pass file through the chain starting at head.
305 if (int ret = PassThroughGraph(In, N, InLangs, TempDir, LangMap))
312 // Sort the nodes in topological order.
313 int CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
314 std::queue<const Node*> Q;
316 Node* Root = getNode("root");
323 const Node* A = Q.front();
326 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
328 Node* B = getNode((*EB)->ToolName());
333 if (B->HasNoInEdges())
342 bool NotJoinNode(const Node* N) {
343 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
347 // Call TopologicalSort and filter the resulting list to include
349 int CompilationGraph::
350 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
351 std::vector<const Node*> TopSorted;
352 if (int ret = TopologicalSort(TopSorted))
354 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
355 std::back_inserter(Out), NotJoinNode);
360 int CompilationGraph::Build (const sys::Path& TempDir,
361 const LanguageMap& LangMap) {
362 InputLanguagesSet InLangs;
363 bool WasSomeActionGenerated = !InputFilenames.empty();
365 // Traverse initial parts of the toolchains and fill in InLangs.
366 if (int ret = BuildInitial(InLangs, TempDir, LangMap))
369 std::vector<const Node*> JTV;
370 if (int ret = TopologicalSortFilterJoinNodes(JTV))
373 // For all join nodes in topological order:
374 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
377 const Node* CurNode = *B;
378 JoinTool* JT = &static_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
380 // Are there any files in the join list?
381 if (JT->JoinListEmpty() && !(JT->WorksOnEmpty() && InputFilenames.empty()))
384 WasSomeActionGenerated = true;
386 if (int ret = JT->GenerateAction(CurAction, CurNode->HasChildren(),
387 TempDir, InLangs, LangMap)) {
391 if (int ret = CurAction.Execute())
394 if (CurAction.StopCompilation())
397 const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name());
401 const Node* NextNode = getNode(Edg->ToolName());
405 if (int ret = PassThroughGraph(sys::Path(CurAction.OutFile()), NextNode,
406 InLangs, TempDir, LangMap)) {
411 if (!WasSomeActionGenerated) {
412 PrintError("no input files");
419 int CompilationGraph::CheckLanguageNames() const {
422 // Check that names for output and input languages on all edges do match.
423 for (const_nodes_iterator B = this->NodesMap.begin(),
424 E = this->NodesMap.end(); B != E; ++B) {
426 const Node & N1 = B->second;
428 for (Node::const_iterator EB = N1.EdgesBegin(), EE = N1.EdgesEnd();
430 const Node* N2 = this->getNode((*EB)->ToolName());
436 errs() << "Error: there is an edge from '" << N1.ToolPtr->Name()
437 << "' back to the root!\n\n";
441 const char* OutLang = N1.ToolPtr->OutputLanguage();
442 const char** InLangs = N2->ToolPtr->InputLanguages();
444 for (;*InLangs; ++InLangs) {
445 if (std::strcmp(OutLang, *InLangs) == 0) {
453 errs() << "Error: Output->input language mismatch in the edge '"
454 << N1.ToolPtr->Name() << "' -> '" << N2->ToolPtr->Name()
456 << "Expected one of { ";
458 InLangs = N2->ToolPtr->InputLanguages();
459 for (;*InLangs; ++InLangs) {
460 errs() << '\'' << *InLangs << (*(InLangs+1) ? "', " : "'");
463 errs() << " }, but got '" << OutLang << "'!\n\n";
473 int CompilationGraph::CheckMultipleDefaultEdges() const {
475 InputLanguagesSet Dummy;
477 // For all nodes, just iterate over the outgoing edges and check if there is
478 // more than one edge with maximum weight.
479 for (const_nodes_iterator B = this->NodesMap.begin(),
480 E = this->NodesMap.end(); B != E; ++B) {
481 const Node& N = B->second;
484 // Ignore the root node.
488 for (Node::const_iterator EB = N.EdgesBegin(), EE = N.EdgesEnd();
490 int EdgeWeight = (*EB)->Weight(Dummy);
491 if (EdgeWeight > MaxWeight) {
492 MaxWeight = EdgeWeight;
494 else if (EdgeWeight == MaxWeight) {
496 errs() << "Error: there are multiple maximal edges stemming from the '"
497 << N.ToolPtr->Name() << "' node!\n\n";
506 int CompilationGraph::CheckCycles() {
507 unsigned deleted = 0;
510 Node* Root = getNode("root");
516 // Try to delete all nodes that have no ingoing edges, starting from the
517 // root. If there are any nodes left after this operation, then we have a
518 // cycle. This relies on '--check-graph' not performing the topological sort.
524 for (Node::iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
526 Node* B = getNode((*EB)->ToolName());
531 if (B->HasNoInEdges())
536 if (deleted != NodesMap.size()) {
537 errs() << "Error: there are cycles in the compilation graph!\n"
538 << "Try inspecting the diagram produced by "
539 << "'llvmc --view-graph'.\n\n";
546 int CompilationGraph::Check () {
547 // We try to catch as many errors as we can in one go.
551 // Check that output/input language names match.
552 ret = this->CheckLanguageNames();
557 // Check for multiple default edges.
558 ret = this->CheckMultipleDefaultEdges();
564 ret = this->CheckCycles();
572 // Code related to graph visualization.
576 struct DOTGraphTraits<llvmc::CompilationGraph*>
577 : public DefaultDOTGraphTraits
579 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
581 template<typename GraphType>
582 static std::string getNodeLabel(const Node* N, const GraphType&)
585 if (N->ToolPtr->IsJoin())
586 return N->Name() + "\n (join" +
587 (N->HasChildren() ? ")"
588 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
595 template<typename EdgeIter>
596 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
598 return N->ToolPtr->OutputLanguage();
601 const char** InLangs = I->ToolPtr->InputLanguages();
604 for (; *InLangs; ++InLangs) {
605 if (*(InLangs + 1)) {
621 int CompilationGraph::writeGraph(const std::string& OutputFilename) {
622 std::string ErrorInfo;
623 raw_fd_ostream O(OutputFilename.c_str(), ErrorInfo);
625 if (ErrorInfo.empty()) {
626 errs() << "Writing '"<< OutputFilename << "' file...";
627 llvm::WriteGraph(O, this);
631 PrintError("Error opening file '" + OutputFilename + "' for writing!");
638 void CompilationGraph::viewGraph() {
639 llvm::ViewGraph(this, "compilation-graph");