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 InputLanguagesSet& InLangs,
40 const std::string& NodeName = "root") {
41 const Edge* MaxEdge = 0;
42 unsigned MaxWeight = 0;
43 bool SingleMax = true;
45 for (typename C::const_iterator B = EdgesContainer.begin(),
46 E = EdgesContainer.end(); B != E; ++B) {
47 const Edge* E = B->getPtr();
48 unsigned EW = E->Weight(InLangs);
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 // Find the language name corresponding to the given file.
90 const std::string& CompilationGraph::getLanguage(const sys::Path& File) const {
91 LanguageMap::const_iterator Lang = ExtsToLangs.find(File.getSuffix());
92 if (Lang == ExtsToLangs.end())
93 throw std::runtime_error("Unknown suffix: " + File.getSuffix() + '!');
97 // Find the tools list corresponding to the given language name.
98 const CompilationGraph::tools_vector_type&
99 CompilationGraph::getToolsVector(const std::string& LangName) const
101 tools_map_type::const_iterator I = ToolsMap.find(LangName);
102 if (I == ToolsMap.end())
103 throw std::runtime_error("No tool corresponding to the language "
104 + LangName + "found!");
108 void CompilationGraph::insertNode(Tool* V) {
109 if (NodesMap.count(V->Name()) == 0) {
111 N.OwningGraph = this;
113 NodesMap[V->Name()] = N;
117 void CompilationGraph::insertEdge(const std::string& A, Edge* E) {
118 Node& B = getNode(E->ToolName());
120 const std::string& InputLanguage = B.ToolPtr->InputLanguage();
121 ToolsMap[InputLanguage].push_back(IntrusiveRefCntPtr<Edge>(E));
122 NodesMap["root"].AddEdge(E);
125 Node& N = getNode(A);
128 // Increase the inward edge counter.
133 sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName,
134 const std::string& Suffix) {
135 sys::Path Out = TempDir;
136 Out.appendComponent(BaseName);
137 Out.appendSuffix(Suffix);
138 Out.makeUnique(true, NULL);
143 // Pass input file through the chain until we bump into a Join node or
144 // a node that says that it is the last.
145 void CompilationGraph::PassThroughGraph (const sys::Path& InFile,
146 const Node* StartNode,
147 const InputLanguagesSet& InLangs,
148 const sys::Path& TempDir) const {
150 sys::Path In = InFile;
151 const Node* CurNode = StartNode;
155 Tool* CurTool = CurNode->ToolPtr.getPtr();
157 if (CurTool->IsJoin()) {
158 JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
159 JT.AddToJoinList(In);
163 // Since toolchains do not have to end with a Join node, we should
164 // check if this Node is the last.
165 if (!CurNode->HasChildren() || CurTool->IsLast()) {
166 if (!OutputFilename.empty()) {
167 Out.set(OutputFilename);
170 Out.set(In.getBasename());
171 Out.appendSuffix(CurTool->OutputSuffix());
176 Out = MakeTempFile(TempDir, In.getBasename(), CurTool->OutputSuffix());
179 if (CurTool->GenerateAction(In, Out).Execute() != 0)
180 throw std::runtime_error("Tool returned error code!");
185 CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
187 CurNode->Name())->ToolName());
188 In = Out; Out.clear();
192 // Find the head of the toolchain corresponding to the given file.
193 // Also, insert an input language into InLangs.
194 const Node* CompilationGraph::
195 FindToolChain(const sys::Path& In, const std::string* forceLanguage,
196 InputLanguagesSet& InLangs) const {
198 // Determine the input language.
199 const std::string& InLanguage =
200 forceLanguage ? *forceLanguage : getLanguage(In);
202 // Add the current input language to the input language set.
203 InLangs.insert(InLanguage);
205 // Find the toolchain for the input language.
206 const tools_vector_type& TV = getToolsVector(InLanguage);
208 throw std::runtime_error("No toolchain corresponding to language"
209 + InLanguage + " found!");
210 return &getNode(ChooseEdge(TV, InLangs)->ToolName());
213 // Helper function used by Build().
214 // Traverses initial portions of the toolchains (up to the first Join node).
215 // This function is also responsible for handling the -x option.
216 void CompilationGraph::BuildInitial (InputLanguagesSet& InLangs,
217 const sys::Path& TempDir) {
218 // This is related to -x option handling.
219 cl::list<std::string>::const_iterator xIter = Languages.begin(),
220 xBegin = xIter, xEnd = Languages.end();
222 const std::string* xLanguage = 0;
223 unsigned xPos = 0, xPosNext = 0, filePos = 0;
227 xPos = Languages.getPosition(xIter - xBegin);
228 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
229 xPosNext = (xNext == xEnd) ? std::numeric_limits<unsigned>::max()
230 : Languages.getPosition(xNext - xBegin);
231 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
234 // For each input file:
235 for (cl::list<std::string>::const_iterator B = InputFilenames.begin(),
236 CB = B, E = InputFilenames.end(); B != E; ++B) {
237 sys::Path In = sys::Path(*B);
239 // Code for handling the -x option.
240 // Output: std::string* xLanguage (can be NULL).
242 filePos = InputFilenames.getPosition(B - CB);
244 if (xPos < filePos) {
245 if (filePos < xPosNext) {
246 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
248 else { // filePos >= xPosNext
249 // Skip xIters while filePos > xPosNext
250 while (filePos > xPosNext) {
254 cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
256 xPosNext = std::numeric_limits<unsigned>::max();
258 xPosNext = Languages.getPosition(xNext - xBegin);
259 xLanguage = (*xIter == "none") ? 0 : &(*xIter);
265 // Find the toolchain corresponding to this file.
266 const Node* N = FindToolChain(In, xLanguage, InLangs);
267 // Pass file through the chain starting at head.
268 PassThroughGraph(In, N, InLangs, TempDir);
272 // Sort the nodes in topological order.
273 void CompilationGraph::TopologicalSort(std::vector<const Node*>& Out) {
274 std::queue<const Node*> Q;
275 Q.push(&getNode("root"));
278 const Node* A = Q.front();
281 for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
283 Node* B = &getNode((*EB)->ToolName());
285 if (B->HasNoInEdges())
292 bool NotJoinNode(const Node* N) {
293 return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
297 // Call TopologicalSort and filter the resulting list to include
299 void CompilationGraph::
300 TopologicalSortFilterJoinNodes(std::vector<const Node*>& Out) {
301 std::vector<const Node*> TopSorted;
302 TopologicalSort(TopSorted);
303 std::remove_copy_if(TopSorted.begin(), TopSorted.end(),
304 std::back_inserter(Out), NotJoinNode);
307 // Build the targets. Command-line options are accessed through global
309 int CompilationGraph::Build (const sys::Path& TempDir) {
311 InputLanguagesSet InLangs;
313 // Traverse initial parts of the toolchains and fill in InLangs.
314 BuildInitial(InLangs, TempDir);
316 std::vector<const Node*> JTV;
317 TopologicalSortFilterJoinNodes(JTV);
319 // For all join nodes in topological order:
320 for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
324 const Node* CurNode = *B;
325 JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
328 // Are there any files in the join list?
329 if (JT->JoinListEmpty())
332 // Is this the last tool in the toolchain?
333 // NOTE: we can process several toolchains in parallel.
334 if (!CurNode->HasChildren() || JT->IsLast()) {
335 if (OutputFilename.empty()) {
337 Out.appendSuffix(JT->OutputSuffix());
340 Out.set(OutputFilename);
344 Out = MakeTempFile(TempDir, "tmp", JT->OutputSuffix());
347 if (JT->GenerateAction(Out).Execute() != 0)
348 throw std::runtime_error("Tool returned error code!");
351 const Node* NextNode =
352 &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
353 CurNode->Name())->ToolName());
354 PassThroughGraph(Out, NextNode, InLangs, TempDir);
361 // Code related to graph visualization.
365 struct DOTGraphTraits<llvmc::CompilationGraph*>
366 : public DefaultDOTGraphTraits
369 template<typename GraphType>
370 static std::string getNodeLabel(const Node* N, const GraphType&)
373 if (N->ToolPtr->IsJoin())
374 return N->Name() + "\n (join" +
375 (N->HasChildren() ? ")"
376 : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
383 template<typename EdgeIter>
384 static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
386 return N->ToolPtr->OutputLanguage();
388 return I->ToolPtr->InputLanguage();
394 void CompilationGraph::writeGraph() {
395 std::ofstream O("CompilationGraph.dot");
398 llvm::WriteGraph(this, "compilation-graph");
402 throw std::runtime_error("");
406 void CompilationGraph::viewGraph() {
407 llvm::ViewGraph(this, "compilation-graph");