Better error message.
[oota-llvm.git] / lib / CompilerDriver / CompilationGraph.cpp
1 //===--- CompilationGraph.cpp - The LLVM Compiler Driver --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Compilation graph - implementation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CompilerDriver/BuiltinOptions.h"
15 #include "llvm/CompilerDriver/CompilationGraph.h"
16 #include "llvm/CompilerDriver/Error.h"
17
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"
22
23 #include <algorithm>
24 #include <cstring>
25 #include <iterator>
26 #include <limits>
27 #include <queue>
28 #include <stdexcept>
29
30 using namespace llvm;
31 using namespace llvmc;
32
33 namespace llvmc {
34
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() + '\'');
41     return Lang->second;
42   }
43 }
44
45 namespace {
46
47   /// ChooseEdge - Return the edge with the maximum weight.
48   template <class C>
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;
55
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);
60       if (EW > MaxWeight) {
61         MaxEdge = e;
62         MaxWeight = EW;
63         SingleMax = true;
64       } else if (EW == MaxWeight) {
65         SingleMax = false;
66       }
67     }
68
69     if (!SingleMax)
70       throw std::runtime_error("Node " + NodeName +
71                                ": multiple maximal outward edges found!"
72                                " Most probably a specification error.");
73     if (!MaxEdge)
74       throw std::runtime_error("Node " + NodeName +
75                                ": no maximal outward edge found!"
76                                " Most probably a specification error.");
77     return MaxEdge;
78   }
79
80 }
81
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();
87        B != E; ++B) {
88     if ((*B)->ToolName() == ToolName) {
89       llvm::IntrusiveRefCntPtr<Edge>(Edg).swap(*B);
90       return;
91     }
92   }
93   OutEdges.push_back(llvm::IntrusiveRefCntPtr<Edge>(Edg));
94 }
95
96 CompilationGraph::CompilationGraph() {
97   NodesMap["root"] = Node(this);
98 }
99
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");
104   return I->second;
105 }
106
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!");
111   return I->second;
112 }
113
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
117 {
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");
122   return I->second;
123 }
124
125 void CompilationGraph::insertNode(Tool* V) {
126   if (NodesMap.count(V->Name()) == 0)
127     NodesMap[V->Name()] = Node(this, V);
128 }
129
130 void CompilationGraph::insertEdge(const std::string& A, Edge* Edg) {
131   Node& B = getNode(Edg->ToolName());
132   if (A == "root") {
133     const char** InLangs = B.ToolPtr->InputLanguages();
134     for (;*InLangs; ++InLangs)
135       ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr<Edge>(Edg));
136     NodesMap["root"].AddEdge(Edg);
137   }
138   else {
139     Node& N = getNode(A);
140     N.AddEdge(Edg);
141   }
142   // Increase the inward edge counter.
143   B.IncrInEdges();
144 }
145
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;
155
156   while(true) {
157     Tool* CurTool = CurNode->ToolPtr.getPtr();
158
159     if (CurTool->IsJoin()) {
160       JoinTool& JT = dynamic_cast<JoinTool&>(*CurTool);
161       JT.AddToJoinList(In);
162       break;
163     }
164
165     Action CurAction = CurTool->GenerateAction(In, CurNode->HasChildren(),
166                                                TempDir, InLangs, LangMap);
167
168     if (int ret = CurAction.Execute())
169       throw error_code(ret);
170
171     if (CurAction.StopCompilation())
172       return;
173
174     CurNode = &getNode(ChooseEdge(CurNode->OutEdges,
175                                   InLangs,
176                                   CurNode->Name())->ToolName());
177     In = CurAction.OutFile();
178   }
179 }
180
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 {
186
187   // Determine the input language.
188   const std::string& InLanguage =
189     ForceLanguage ? *ForceLanguage : LangMap.GetLanguage(In);
190
191   // Add the current input language to the input language set.
192   InLangs.insert(InLanguage);
193
194   // Find the toolchain for the input language.
195   const tools_vector_type& TV = getToolsVector(InLanguage);
196   if (TV.empty())
197     throw std::runtime_error("No toolchain corresponding to language "
198                              + InLanguage + " found");
199   return &getNode(ChooseEdge(TV, InLangs)->ToolName());
200 }
201
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();
211   bool xEmpty = true;
212   const std::string* xLanguage = 0;
213   unsigned xPos = 0, xPosNext = 0, filePos = 0;
214
215   if (xIter != xEnd) {
216     xEmpty = false;
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);
222   }
223
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);
228
229     // Code for handling the -x option.
230     // Output: std::string* xLanguage (can be NULL).
231     if (!xEmpty) {
232       filePos = InputFilenames.getPosition(B - CB);
233
234       if (xPos < filePos) {
235         if (filePos < xPosNext) {
236           xLanguage = (*xIter == "none") ? 0 : &(*xIter);
237         }
238         else { // filePos >= xPosNext
239           // Skip xIters while filePos > xPosNext
240           while (filePos > xPosNext) {
241             ++xIter;
242             xPos = xPosNext;
243
244             cl::list<std::string>::const_iterator xNext = llvm::next(xIter);
245             if (xNext == xEnd)
246               xPosNext = std::numeric_limits<unsigned>::max();
247             else
248               xPosNext = Languages.getPosition(xNext - xBegin);
249             xLanguage = (*xIter == "none") ? 0 : &(*xIter);
250           }
251         }
252       }
253     }
254
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);
259   }
260 }
261
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"));
266
267   while (!Q.empty()) {
268     const Node* A = Q.front();
269     Q.pop();
270     Out.push_back(A);
271     for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
272          EB != EE; ++EB) {
273       Node* B = &getNode((*EB)->ToolName());
274       B->DecrInEdges();
275       if (B->HasNoInEdges())
276         Q.push(B);
277     }
278   }
279 }
280
281 namespace {
282   bool NotJoinNode(const Node* N) {
283     return N->ToolPtr ? !N->ToolPtr->IsJoin() : true;
284   }
285 }
286
287 // Call TopologicalSort and filter the resulting list to include
288 // only Join nodes.
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);
295 }
296
297 int CompilationGraph::Build (const sys::Path& TempDir,
298                              const LanguageMap& LangMap) {
299
300   InputLanguagesSet InLangs;
301
302   // Traverse initial parts of the toolchains and fill in InLangs.
303   BuildInitial(InLangs, TempDir, LangMap);
304
305   std::vector<const Node*> JTV;
306   TopologicalSortFilterJoinNodes(JTV);
307
308   // For all join nodes in topological order:
309   for (std::vector<const Node*>::iterator B = JTV.begin(), E = JTV.end();
310        B != E; ++B) {
311
312     const Node* CurNode = *B;
313     JoinTool* JT = &dynamic_cast<JoinTool&>(*CurNode->ToolPtr.getPtr());
314
315     // Are there any files in the join list?
316     if (JT->JoinListEmpty())
317       continue;
318
319     Action CurAction = JT->GenerateAction(CurNode->HasChildren(),
320                                           TempDir, InLangs, LangMap);
321
322     if (int ret = CurAction.Execute())
323       throw error_code(ret);
324
325     if (CurAction.StopCompilation())
326       return 0;
327
328     const Node* NextNode = &getNode(ChooseEdge(CurNode->OutEdges, InLangs,
329                                                CurNode->Name())->ToolName());
330     PassThroughGraph(sys::Path(CurAction.OutFile()), NextNode,
331                      InLangs, TempDir, LangMap);
332   }
333
334   return 0;
335 }
336
337 int CompilationGraph::CheckLanguageNames() const {
338   int ret = 0;
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) {
342
343     const Node & N1 = B->second;
344     if (N1.ToolPtr) {
345       for (Node::const_iterator EB = N1.EdgesBegin(), EE = N1.EdgesEnd();
346            EB != EE; ++EB) {
347         const Node& N2 = this->getNode((*EB)->ToolName());
348
349         if (!N2.ToolPtr) {
350           ++ret;
351           errs() << "Error: there is an edge from '" << N1.ToolPtr->Name()
352                  << "' back to the root!\n\n";
353           continue;
354         }
355
356         const char* OutLang = N1.ToolPtr->OutputLanguage();
357         const char** InLangs = N2.ToolPtr->InputLanguages();
358         bool eq = false;
359         for (;*InLangs; ++InLangs) {
360           if (std::strcmp(OutLang, *InLangs) == 0) {
361             eq = true;
362             break;
363           }
364         }
365
366         if (!eq) {
367           ++ret;
368           errs() << "Error: Output->input language mismatch in the edge '"
369                  << N1.ToolPtr->Name() << "' -> '" << N2.ToolPtr->Name()
370                  << "'!\n"
371                  << "Expected one of { ";
372
373           InLangs = N2.ToolPtr->InputLanguages();
374           for (;*InLangs; ++InLangs) {
375             errs() << '\'' << *InLangs << (*(InLangs+1) ? "', " : "'");
376           }
377
378           errs() << " }, but got '" << OutLang << "'!\n\n";
379         }
380
381       }
382     }
383   }
384
385   return ret;
386 }
387
388 int CompilationGraph::CheckMultipleDefaultEdges() const {
389   int ret = 0;
390   InputLanguagesSet Dummy;
391
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;
398
399     // Ignore the root node.
400     if (!N.ToolPtr)
401       continue;
402
403     for (Node::const_iterator EB = N.EdgesBegin(), EE = N.EdgesEnd();
404          EB != EE; ++EB) {
405       unsigned EdgeWeight = (*EB)->Weight(Dummy);
406       if (EdgeWeight > MaxWeight) {
407         MaxWeight = EdgeWeight;
408       }
409       else if (EdgeWeight == MaxWeight) {
410         ++ret;
411         errs() << "Error: there are multiple maximal edges stemming from the '"
412                << N.ToolPtr->Name() << "' node!\n\n";
413         break;
414       }
415     }
416   }
417
418   return ret;
419 }
420
421 int CompilationGraph::CheckCycles() {
422   unsigned deleted = 0;
423   std::queue<Node*> Q;
424   Q.push(&getNode("root"));
425
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.
429   while (!Q.empty()) {
430     Node* A = Q.front();
431     Q.pop();
432     ++deleted;
433
434     for (Node::iterator EB = A->EdgesBegin(), EE = A->EdgesEnd();
435          EB != EE; ++EB) {
436       Node* B = &getNode((*EB)->ToolName());
437       B->DecrInEdges();
438       if (B->HasNoInEdges())
439         Q.push(B);
440     }
441   }
442
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";
447     return 1;
448   }
449
450   return 0;
451 }
452
453 int CompilationGraph::Check () {
454   // We try to catch as many errors as we can in one go.
455   int ret = 0;
456
457   // Check that output/input language names match.
458   ret += this->CheckLanguageNames();
459
460   // Check for multiple default edges.
461   ret += this->CheckMultipleDefaultEdges();
462
463   // Check for cycles.
464   ret += this->CheckCycles();
465
466   return ret;
467 }
468
469 // Code related to graph visualization.
470
471 namespace llvm {
472   template <>
473   struct DOTGraphTraits<llvmc::CompilationGraph*>
474     : public DefaultDOTGraphTraits
475   {
476     DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
477
478     template<typename GraphType>
479     static std::string getNodeLabel(const Node* N, const GraphType&)
480     {
481       if (N->ToolPtr)
482         if (N->ToolPtr->IsJoin())
483           return N->Name() + "\n (join" +
484             (N->HasChildren() ? ")"
485              : std::string(": ") + N->ToolPtr->OutputLanguage() + ')');
486         else
487           return N->Name();
488       else
489         return "root";
490     }
491
492     template<typename EdgeIter>
493     static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) {
494       if (N->ToolPtr) {
495         return N->ToolPtr->OutputLanguage();
496       }
497       else {
498         const char** InLangs = I->ToolPtr->InputLanguages();
499         std::string ret;
500
501         for (; *InLangs; ++InLangs) {
502           if (*(InLangs + 1)) {
503             ret += *InLangs;
504             ret +=  ", ";
505           }
506           else {
507             ret += *InLangs;
508           }
509         }
510
511         return ret;
512       }
513     }
514   };
515
516 }
517
518 void CompilationGraph::writeGraph(const std::string& OutputFilename) {
519   std::string ErrorInfo;
520   raw_fd_ostream O(OutputFilename.c_str(), ErrorInfo);
521
522   if (ErrorInfo.empty()) {
523     errs() << "Writing '"<< OutputFilename << "' file...";
524     llvm::WriteGraph(O, this);
525     errs() << "done.\n";
526   }
527   else {
528     throw std::runtime_error("Error opening file '" + OutputFilename
529                              + "' for writing!");
530   }
531 }
532
533 void CompilationGraph::viewGraph() {
534   llvm::ViewGraph(this, "compilation-graph");
535 }