Make 'extern' an option property.
[oota-llvm.git] / utils / TableGen / LLVMCConfigurationEmitter.cpp
1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- 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 // This tablegen backend is responsible for emitting LLVMC configuration code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLVMCConfigurationEmitter.h"
15 #include "Record.h"
16
17 #include "llvm/ADT/IntrusiveRefCntPtr.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/Support/Streams.h"
23
24 #include <algorithm>
25 #include <cassert>
26 #include <functional>
27 #include <stdexcept>
28 #include <string>
29 #include <typeinfo>
30
31 using namespace llvm;
32
33 namespace {
34
35 //===----------------------------------------------------------------------===//
36 /// Typedefs
37
38 typedef std::vector<Record*> RecordVector;
39 typedef std::vector<std::string> StrVector;
40
41 //===----------------------------------------------------------------------===//
42 /// Constants
43
44 // Indentation strings.
45 const char * Indent1 = "    ";
46 const char * Indent2 = "        ";
47 const char * Indent3 = "            ";
48
49 // Default help string.
50 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51
52 // Name for the "sink" option.
53 const char * SinkOptionName = "AutoGeneratedSinkOption";
54
55 //===----------------------------------------------------------------------===//
56 /// Helper functions
57
58 /// Id - An 'identity' function object.
59 struct Id {
60   template<typename T>
61   void operator()(const T&) const {
62   }
63 };
64
65 int InitPtrToInt(const Init* ptr) {
66   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
67   return val.getValue();
68 }
69
70 const std::string& InitPtrToString(const Init* ptr) {
71   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
72   return val.getValue();
73 }
74
75 const ListInit& InitPtrToList(const Init* ptr) {
76   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
77   return val;
78 }
79
80 const DagInit& InitPtrToDag(const Init* ptr) {
81   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
82   return val;
83 }
84
85 // checkNumberOfArguments - Ensure that the number of args in d is
86 // less than or equal to min_arguments, otherwise throw an exception.
87 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
88   if (!d || d->getNumArgs() < min_arguments)
89     throw "Property " + d->getOperator()->getAsString()
90       + " has too few arguments!";
91 }
92
93 // isDagEmpty - is this DAG marked with an empty marker?
94 bool isDagEmpty (const DagInit* d) {
95   return d->getOperator()->getAsString() == "empty";
96 }
97
98 // EscapeVariableName - Escape commas and other symbols not allowed
99 // in the C++ variable names. Makes it possible to use options named
100 // like "Wa," (useful for prefix options).
101 std::string EscapeVariableName(const std::string& Var) {
102   std::string ret;
103   for (unsigned i = 0; i != Var.size(); ++i) {
104     char cur_char = Var[i];
105     if (cur_char == ',') {
106       ret += "_comma_";
107     }
108     else if (cur_char == '+') {
109       ret += "_plus_";
110     }
111     else if (cur_char == '-') {
112       ret += "_dash_";
113     }
114     else {
115       ret.push_back(cur_char);
116     }
117   }
118   return ret;
119 }
120
121 //===----------------------------------------------------------------------===//
122 /// Back-end specific code
123
124
125 /// OptionType - One of six different option types. See the
126 /// documentation for detailed description of differences.
127 /// Extern* options are those that are defined in some other plugin.
128 namespace OptionType {
129   enum OptionType { Alias, Switch, Parameter, ParameterList,
130                     Prefix, PrefixList};
131
132 bool IsList (OptionType t) {
133   return (t == ParameterList || t == PrefixList);
134 }
135
136 bool IsSwitch (OptionType t) {
137   return (t == Switch);
138 }
139
140 bool IsParameter (OptionType t) {
141   return (t == Parameter || t == Prefix);
142 }
143
144 }
145
146 OptionType::OptionType stringToOptionType(const std::string& T) {
147   if (T == "alias_option")
148     return OptionType::Alias;
149   else if (T == "switch_option")
150     return OptionType::Switch;
151   else if (T == "parameter_option")
152     return OptionType::Parameter;
153   else if (T == "parameter_list_option")
154     return OptionType::ParameterList;
155   else if (T == "prefix_option")
156     return OptionType::Prefix;
157   else if (T == "prefix_list_option")
158     return OptionType::PrefixList;
159   else
160     throw "Unknown option type: " + T + '!';
161 }
162
163 namespace OptionDescriptionFlags {
164   enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
165                                 ReallyHidden = 0x4, Extern = 0x8 };
166 }
167
168 /// OptionDescription - Represents data contained in a single
169 /// OptionList entry.
170 struct OptionDescription {
171   OptionType::OptionType Type;
172   std::string Name;
173   unsigned Flags;
174   std::string Help;
175
176   OptionDescription(OptionType::OptionType t = OptionType::Switch,
177                     const std::string& n = "",
178                     const std::string& h = DefaultHelpString)
179     : Type(t), Name(n), Flags(0x0), Help(h)
180   {}
181
182   /// GenTypeDeclaration - Returns the C++ variable type of this
183   /// option.
184   const char* GenTypeDeclaration() const;
185
186   /// GenVariableName - Returns the variable name used in the
187   /// generated C++ code.
188   std::string GenVariableName() const;
189
190   /// Merge - Merge two option descriptions.
191   void Merge (const OptionDescription& other);
192
193   // Misc convenient getters/setters.
194
195   bool isAlias() const;
196
197   bool isExtern() const;
198   void setExtern();
199
200   bool isRequired() const;
201   void setRequired();
202
203   bool isHidden() const;
204   void setHidden();
205
206   bool isReallyHidden() const;
207   void setReallyHidden();
208 };
209
210 void OptionDescription::Merge (const OptionDescription& other)
211 {
212   if (other.Type != Type)
213     throw "Conflicting definitions for the option " + Name + "!";
214
215   if (Help == other.Help || Help == DefaultHelpString)
216     Help = other.Help;
217   else if (other.Help != DefaultHelpString) {
218     llvm::cerr << "Warning: several different help strings"
219       " defined for option " + Name + "\n";
220   }
221
222   Flags |= other.Flags;
223 }
224
225 bool OptionDescription::isAlias() const {
226   return Type == OptionType::Alias;
227 }
228
229 bool OptionDescription::isExtern() const {
230   return Flags & OptionDescriptionFlags::Extern;
231 }
232 void OptionDescription::setExtern() {
233   Flags |= OptionDescriptionFlags::Extern;
234 }
235
236 bool OptionDescription::isRequired() const {
237   return Flags & OptionDescriptionFlags::Required;
238 }
239 void OptionDescription::setRequired() {
240   Flags |= OptionDescriptionFlags::Required;
241 }
242
243 bool OptionDescription::isHidden() const {
244   return Flags & OptionDescriptionFlags::Hidden;
245 }
246 void OptionDescription::setHidden() {
247   Flags |= OptionDescriptionFlags::Hidden;
248 }
249
250 bool OptionDescription::isReallyHidden() const {
251   return Flags & OptionDescriptionFlags::ReallyHidden;
252 }
253 void OptionDescription::setReallyHidden() {
254   Flags |= OptionDescriptionFlags::ReallyHidden;
255 }
256
257 const char* OptionDescription::GenTypeDeclaration() const {
258   switch (Type) {
259   case OptionType::Alias:
260     return "cl::alias";
261   case OptionType::PrefixList:
262   case OptionType::ParameterList:
263     return "cl::list<std::string>";
264   case OptionType::Switch:
265     return "cl::opt<bool>";
266   case OptionType::Parameter:
267   case OptionType::Prefix:
268   default:
269     return "cl::opt<std::string>";
270   }
271 }
272
273 std::string OptionDescription::GenVariableName() const {
274   const std::string& EscapedName = EscapeVariableName(Name);
275   switch (Type) {
276   case OptionType::Alias:
277     return "AutoGeneratedAlias_" + EscapedName;
278   case OptionType::PrefixList:
279   case OptionType::ParameterList:
280     return "AutoGeneratedList_" + EscapedName;
281   case OptionType::Switch:
282     return "AutoGeneratedSwitch_" + EscapedName;
283   case OptionType::Prefix:
284   case OptionType::Parameter:
285   default:
286     return "AutoGeneratedParameter_" + EscapedName;
287   }
288 }
289
290 /// OptionDescriptions - An OptionDescription array plus some helper
291 /// functions.
292 class OptionDescriptions {
293   typedef StringMap<OptionDescription> container_type;
294
295   /// Descriptions - A list of OptionDescriptions.
296   container_type Descriptions;
297
298 public:
299   /// FindOption - exception-throwing wrapper for find().
300   const OptionDescription& FindOption(const std::string& OptName) const;
301
302   /// insertDescription - Insert new OptionDescription into
303   /// OptionDescriptions list
304   void InsertDescription (const OptionDescription& o);
305
306   // Support for STL-style iteration
307   typedef container_type::const_iterator const_iterator;
308   const_iterator begin() const { return Descriptions.begin(); }
309   const_iterator end() const { return Descriptions.end(); }
310 };
311
312 const OptionDescription&
313 OptionDescriptions::FindOption(const std::string& OptName) const
314 {
315   const_iterator I = Descriptions.find(OptName);
316   if (I != Descriptions.end())
317     return I->second;
318   else
319     throw OptName + ": no such option!";
320 }
321
322 void OptionDescriptions::InsertDescription (const OptionDescription& o)
323 {
324   container_type::iterator I = Descriptions.find(o.Name);
325   if (I != Descriptions.end()) {
326     OptionDescription& D = I->second;
327     D.Merge(o);
328   }
329   else {
330     Descriptions[o.Name] = o;
331   }
332 }
333
334 /// HandlerTable - A base class for function objects implemented as
335 /// 'tables of handlers'.
336 template <class T>
337 class HandlerTable {
338 protected:
339   // Implementation details.
340
341   /// Handler -
342   typedef void (T::* Handler) (const DagInit*);
343   /// HandlerMap - A map from property names to property handlers
344   typedef StringMap<Handler> HandlerMap;
345
346   static HandlerMap Handlers_;
347   static bool staticMembersInitialized_;
348
349   T* childPtr;
350 public:
351
352   HandlerTable(T* cp) : childPtr(cp)
353   {}
354
355   /// operator() - Just forwards to the corresponding property
356   /// handler.
357   void operator() (Init* i) {
358     const DagInit& property = InitPtrToDag(i);
359     const std::string& property_name = property.getOperator()->getAsString();
360     typename HandlerMap::iterator method = Handlers_.find(property_name);
361
362     if (method != Handlers_.end()) {
363       Handler h = method->second;
364       (childPtr->*h)(&property);
365     }
366     else {
367       throw "No handler found for property " + property_name + "!";
368     }
369   }
370
371   void AddHandler(const char* Property, Handler Handl) {
372     Handlers_[Property] = Handl;
373   }
374 };
375
376 template <class T> typename HandlerTable<T>::HandlerMap
377 HandlerTable<T>::Handlers_;
378 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
379
380
381 /// CollectOptionProperties - Function object for iterating over an
382 /// option property list.
383 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
384 private:
385
386   /// optDescs_ - OptionDescriptions table. This is where the
387   /// information is stored.
388   OptionDescription& optDesc_;
389
390 public:
391
392   explicit CollectOptionProperties(OptionDescription& OD)
393     : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
394   {
395     if (!staticMembersInitialized_) {
396       AddHandler("extern", &CollectOptionProperties::onExtern);
397       AddHandler("help", &CollectOptionProperties::onHelp);
398       AddHandler("hidden", &CollectOptionProperties::onHidden);
399       AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
400       AddHandler("required", &CollectOptionProperties::onRequired);
401
402       staticMembersInitialized_ = true;
403     }
404   }
405
406 private:
407
408   /// Option property handlers --
409   /// Methods that handle option properties such as (help) or (hidden).
410
411   void onExtern (const DagInit* d) {
412     checkNumberOfArguments(d, 0);
413     optDesc_.setExtern();
414   }
415
416   void onHelp (const DagInit* d) {
417     checkNumberOfArguments(d, 1);
418     optDesc_.Help = InitPtrToString(d->getArg(0));
419   }
420
421   void onHidden (const DagInit* d) {
422     checkNumberOfArguments(d, 0);
423     optDesc_.setHidden();
424   }
425
426   void onReallyHidden (const DagInit* d) {
427     checkNumberOfArguments(d, 0);
428     optDesc_.setReallyHidden();
429   }
430
431   void onRequired (const DagInit* d) {
432     checkNumberOfArguments(d, 0);
433     optDesc_.setRequired();
434   }
435
436 };
437
438 /// AddOption - A function object that is applied to every option
439 /// description. Used by CollectOptionDescriptions.
440 class AddOption {
441 private:
442   OptionDescriptions& OptDescs_;
443
444 public:
445   explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
446   {}
447
448   void operator()(const Init* i) {
449     const DagInit& d = InitPtrToDag(i);
450     checkNumberOfArguments(&d, 1);
451
452     const OptionType::OptionType Type =
453       stringToOptionType(d.getOperator()->getAsString());
454     const std::string& Name = InitPtrToString(d.getArg(0));
455
456     OptionDescription OD(Type, Name);
457
458     if (!OD.isExtern())
459       checkNumberOfArguments(&d, 2);
460
461     if (OD.isAlias()) {
462       // Aliases store the aliased option name in the 'Help' field.
463       OD.Help = InitPtrToString(d.getArg(1));
464     }
465     else if (!OD.isExtern()) {
466       processOptionProperties(&d, OD);
467     }
468     OptDescs_.InsertDescription(OD);
469   }
470
471 private:
472   /// processOptionProperties - Go through the list of option
473   /// properties and call a corresponding handler for each.
474   static void processOptionProperties (const DagInit* d, OptionDescription& o) {
475     checkNumberOfArguments(d, 2);
476     DagInit::const_arg_iterator B = d->arg_begin();
477     // Skip the first argument: it's always the option name.
478     ++B;
479     std::for_each(B, d->arg_end(), CollectOptionProperties(o));
480   }
481
482 };
483
484 /// CollectOptionDescriptions - Collects option properties from all
485 /// OptionLists.
486 void CollectOptionDescriptions (RecordVector::const_iterator B,
487                                 RecordVector::const_iterator E,
488                                 OptionDescriptions& OptDescs)
489 {
490   // For every OptionList:
491   for (; B!=E; ++B) {
492     RecordVector::value_type T = *B;
493     // Throws an exception if the value does not exist.
494     ListInit* PropList = T->getValueAsListInit("options");
495
496     // For every option description in this list:
497     // collect the information and
498     std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
499   }
500 }
501
502 // Tool information record
503
504 namespace ToolFlags {
505   enum ToolFlags { Join = 0x1, Sink = 0x2 };
506 }
507
508 struct ToolDescription : public RefCountedBase<ToolDescription> {
509   std::string Name;
510   Init* CmdLine;
511   Init* Actions;
512   StrVector InLanguage;
513   std::string OutLanguage;
514   std::string OutputSuffix;
515   unsigned Flags;
516
517   // Various boolean properties
518   void setSink()      { Flags |= ToolFlags::Sink; }
519   bool isSink() const { return Flags & ToolFlags::Sink; }
520   void setJoin()      { Flags |= ToolFlags::Join; }
521   bool isJoin() const { return Flags & ToolFlags::Join; }
522
523   // Default ctor here is needed because StringMap can only store
524   // DefaultConstructible objects
525   ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
526   ToolDescription (const std::string& n)
527   : Name(n), CmdLine(0), Actions(0), Flags(0)
528   {}
529 };
530
531 /// ToolDescriptions - A list of Tool information records.
532 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
533
534
535 /// CollectToolProperties - Function object for iterating over a list of
536 /// tool property records.
537 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
538 private:
539
540   /// toolDesc_ - Properties of the current Tool. This is where the
541   /// information is stored.
542   ToolDescription& toolDesc_;
543
544 public:
545
546   explicit CollectToolProperties (ToolDescription& d)
547     : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
548   {
549     if (!staticMembersInitialized_) {
550
551       AddHandler("actions", &CollectToolProperties::onActions);
552       AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
553       AddHandler("in_language", &CollectToolProperties::onInLanguage);
554       AddHandler("join", &CollectToolProperties::onJoin);
555       AddHandler("out_language", &CollectToolProperties::onOutLanguage);
556       AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
557       AddHandler("sink", &CollectToolProperties::onSink);
558
559       staticMembersInitialized_ = true;
560     }
561   }
562
563 private:
564
565   /// Property handlers --
566   /// Functions that extract information about tool properties from
567   /// DAG representation.
568
569   void onActions (const DagInit* d) {
570     checkNumberOfArguments(d, 1);
571     Init* Case = d->getArg(0);
572     if (typeid(*Case) != typeid(DagInit) ||
573         static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
574       throw
575         std::string("The argument to (actions) should be a 'case' construct!");
576     toolDesc_.Actions = Case;
577   }
578
579   void onCmdLine (const DagInit* d) {
580     checkNumberOfArguments(d, 1);
581     toolDesc_.CmdLine = d->getArg(0);
582   }
583
584   void onInLanguage (const DagInit* d) {
585     checkNumberOfArguments(d, 1);
586     Init* arg = d->getArg(0);
587
588     // Find out the argument's type.
589     if (typeid(*arg) == typeid(StringInit)) {
590       // It's a string.
591       toolDesc_.InLanguage.push_back(InitPtrToString(arg));
592     }
593     else {
594       // It's a list.
595       const ListInit& lst = InitPtrToList(arg);
596       StrVector& out = toolDesc_.InLanguage;
597
598       // Copy strings to the output vector.
599       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
600            B != E; ++B) {
601         out.push_back(InitPtrToString(*B));
602       }
603
604       // Remove duplicates.
605       std::sort(out.begin(), out.end());
606       StrVector::iterator newE = std::unique(out.begin(), out.end());
607       out.erase(newE, out.end());
608     }
609   }
610
611   void onJoin (const DagInit* d) {
612     checkNumberOfArguments(d, 0);
613     toolDesc_.setJoin();
614   }
615
616   void onOutLanguage (const DagInit* d) {
617     checkNumberOfArguments(d, 1);
618     toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
619   }
620
621   void onOutputSuffix (const DagInit* d) {
622     checkNumberOfArguments(d, 1);
623     toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
624   }
625
626   void onSink (const DagInit* d) {
627     checkNumberOfArguments(d, 0);
628     toolDesc_.setSink();
629   }
630
631 };
632
633
634 /// CollectToolDescriptions - Gather information about tool properties
635 /// from the parsed TableGen data (basically a wrapper for the
636 /// CollectToolProperties function object).
637 void CollectToolDescriptions (RecordVector::const_iterator B,
638                               RecordVector::const_iterator E,
639                               ToolDescriptions& ToolDescs)
640 {
641   // Iterate over a properties list of every Tool definition
642   for (;B!=E;++B) {
643     const Record* T = *B;
644     // Throws an exception if the value does not exist.
645     ListInit* PropList = T->getValueAsListInit("properties");
646
647     IntrusiveRefCntPtr<ToolDescription>
648       ToolDesc(new ToolDescription(T->getName()));
649
650     std::for_each(PropList->begin(), PropList->end(),
651                   CollectToolProperties(*ToolDesc));
652     ToolDescs.push_back(ToolDesc);
653   }
654 }
655
656 /// FillInEdgeVector - Merge all compilation graph definitions into
657 /// one single edge list.
658 void FillInEdgeVector(RecordVector::const_iterator B,
659                       RecordVector::const_iterator E, RecordVector& Out) {
660   for (; B != E; ++B) {
661     const ListInit* edges = (*B)->getValueAsListInit("edges");
662
663     for (unsigned i = 0; i < edges->size(); ++i)
664       Out.push_back(edges->getElementAsRecord(i));
665   }
666 }
667
668 /// CalculatePriority - Calculate the priority of this plugin.
669 int CalculatePriority(RecordVector::const_iterator B,
670                       RecordVector::const_iterator E) {
671   int total = 0;
672   for (; B!=E; ++B) {
673     total += static_cast<int>((*B)->getValueAsInt("priority"));
674   }
675   return total;
676 }
677
678 /// NotInGraph - Helper function object for FilterNotInGraph.
679 struct NotInGraph {
680 private:
681   const llvm::StringSet<>& ToolsInGraph_;
682
683 public:
684   NotInGraph(const llvm::StringSet<>& ToolsInGraph)
685   : ToolsInGraph_(ToolsInGraph)
686   {}
687
688   bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
689     return (ToolsInGraph_.count(x->Name) == 0);
690   }
691 };
692
693 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
694 /// mentioned in the compilation graph definition.
695 void FilterNotInGraph (const RecordVector& EdgeVector,
696                        ToolDescriptions& ToolDescs) {
697
698   // List all tools mentioned in the graph.
699   llvm::StringSet<> ToolsInGraph;
700
701   for (RecordVector::const_iterator B = EdgeVector.begin(),
702          E = EdgeVector.end(); B != E; ++B) {
703
704     const Record* Edge = *B;
705     const std::string& NodeA = Edge->getValueAsString("a");
706     const std::string& NodeB = Edge->getValueAsString("b");
707
708     if (NodeA != "root")
709       ToolsInGraph.insert(NodeA);
710     ToolsInGraph.insert(NodeB);
711   }
712
713   // Filter ToolPropertiesList.
714   ToolDescriptions::iterator new_end =
715     std::remove_if(ToolDescs.begin(), ToolDescs.end(),
716                    NotInGraph(ToolsInGraph));
717   ToolDescs.erase(new_end, ToolDescs.end());
718 }
719
720 /// FillInToolToLang - Fills in two tables that map tool names to
721 /// (input, output) languages.  Helper function used by TypecheckGraph().
722 void FillInToolToLang (const ToolDescriptions& ToolDescs,
723                        StringMap<StringSet<> >& ToolToInLang,
724                        StringMap<std::string>& ToolToOutLang) {
725   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
726          E = ToolDescs.end(); B != E; ++B) {
727     const ToolDescription& D = *(*B);
728     for (StrVector::const_iterator B = D.InLanguage.begin(),
729            E = D.InLanguage.end(); B != E; ++B)
730       ToolToInLang[D.Name].insert(*B);
731     ToolToOutLang[D.Name] = D.OutLanguage;
732   }
733 }
734
735 /// TypecheckGraph - Check that names for output and input languages
736 /// on all edges do match. This doesn't do much when the information
737 /// about the whole graph is not available (i.e. when compiling most
738 /// plugins).
739 void TypecheckGraph (const RecordVector& EdgeVector,
740                      const ToolDescriptions& ToolDescs) {
741   StringMap<StringSet<> > ToolToInLang;
742   StringMap<std::string> ToolToOutLang;
743
744   FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
745   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
746   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
747
748   for (RecordVector::const_iterator B = EdgeVector.begin(),
749          E = EdgeVector.end(); B != E; ++B) {
750     const Record* Edge = *B;
751     const std::string& NodeA = Edge->getValueAsString("a");
752     const std::string& NodeB = Edge->getValueAsString("b");
753     StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
754     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
755
756     if (NodeA != "root") {
757       if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
758         throw "Edge " + NodeA + "->" + NodeB
759           + ": output->input language mismatch";
760     }
761
762     if (NodeB == "root")
763       throw std::string("Edges back to the root are not allowed!");
764   }
765 }
766
767 /// WalkCase - Walks the 'case' expression DAG and invokes
768 /// TestCallback on every test, and StatementCallback on every
769 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
770 /// combinators.
771 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
772 template <typename F1, typename F2>
773 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
774   const DagInit& d = InitPtrToDag(Case);
775   bool even = false;
776   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
777        B != E; ++B) {
778     Init* arg = *B;
779     if (even && dynamic_cast<DagInit*>(arg)
780         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
781       WalkCase(arg, TestCallback, StatementCallback);
782     else if (!even)
783       TestCallback(arg);
784     else
785       StatementCallback(arg);
786     even = !even;
787   }
788 }
789
790 /// ExtractOptionNames - A helper function object used by
791 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
792 class ExtractOptionNames {
793   llvm::StringSet<>& OptionNames_;
794
795   void processDag(const Init* Statement) {
796     const DagInit& Stmt = InitPtrToDag(Statement);
797     const std::string& ActionName = Stmt.getOperator()->getAsString();
798     if (ActionName == "forward" || ActionName == "forward_as" ||
799         ActionName == "unpack_values" || ActionName == "switch_on" ||
800         ActionName == "parameter_equals" || ActionName == "element_in_list" ||
801         ActionName == "not_empty") {
802       checkNumberOfArguments(&Stmt, 1);
803       const std::string& Name = InitPtrToString(Stmt.getArg(0));
804       OptionNames_.insert(Name);
805     }
806     else if (ActionName == "and" || ActionName == "or") {
807       for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
808         this->processDag(Stmt.getArg(i));
809       }
810     }
811   }
812
813 public:
814   ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
815   {}
816
817   void operator()(const Init* Statement) {
818     if (typeid(*Statement) == typeid(ListInit)) {
819       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
820       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
821            B != E; ++B)
822         this->processDag(*B);
823     }
824     else {
825       this->processDag(Statement);
826     }
827   }
828 };
829
830 /// CheckForSuperfluousOptions - Check that there are no side
831 /// effect-free options (specified only in the OptionList). Otherwise,
832 /// output a warning.
833 void CheckForSuperfluousOptions (const RecordVector& Edges,
834                                  const ToolDescriptions& ToolDescs,
835                                  const OptionDescriptions& OptDescs) {
836   llvm::StringSet<> nonSuperfluousOptions;
837
838   // Add all options mentioned in the ToolDesc.Actions to the set of
839   // non-superfluous options.
840   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
841          E = ToolDescs.end(); B != E; ++B) {
842     const ToolDescription& TD = *(*B);
843     ExtractOptionNames Callback(nonSuperfluousOptions);
844     if (TD.Actions)
845       WalkCase(TD.Actions, Callback, Callback);
846   }
847
848   // Add all options mentioned in the 'case' clauses of the
849   // OptionalEdges of the compilation graph to the set of
850   // non-superfluous options.
851   for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
852        B != E; ++B) {
853     const Record* Edge = *B;
854     DagInit* Weight = Edge->getValueAsDag("weight");
855
856     if (!isDagEmpty(Weight))
857       WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
858   }
859
860   // Check that all options in OptDescs belong to the set of
861   // non-superfluous options.
862   for (OptionDescriptions::const_iterator B = OptDescs.begin(),
863          E = OptDescs.end(); B != E; ++B) {
864     const OptionDescription& Val = B->second;
865     if (!nonSuperfluousOptions.count(Val.Name)
866         && Val.Type != OptionType::Alias)
867       llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
868         "Probable cause: this option is specified only in the OptionList.\n";
869   }
870 }
871
872 /// EmitCaseTest1Arg - Helper function used by
873 /// EmitCaseConstructHandler.
874 bool EmitCaseTest1Arg(const std::string& TestName,
875                       const DagInit& d,
876                       const OptionDescriptions& OptDescs,
877                       std::ostream& O) {
878   checkNumberOfArguments(&d, 1);
879   const std::string& OptName = InitPtrToString(d.getArg(0));
880   if (TestName == "switch_on") {
881     const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
882     if (!OptionType::IsSwitch(OptDesc.Type))
883       throw OptName + ": incorrect option type - should be a switch!";
884     O << OptDesc.GenVariableName();
885     return true;
886   } else if (TestName == "input_languages_contain") {
887     O << "InLangs.count(\"" << OptName << "\") != 0";
888     return true;
889   } else if (TestName == "in_language") {
890     // This works only for single-argument Tool::GenerateAction. Join
891     // tools can process several files in different languages simultaneously.
892
893     // TODO: make this work with Edge::Weight (if possible).
894     O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
895     return true;
896   } else if (TestName == "not_empty") {
897     if (OptName == "o") {
898       O << "!OutputFilename.empty()";
899       return true;
900     }
901     else {
902       const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
903       if (OptionType::IsSwitch(OptDesc.Type))
904         throw OptName
905           + ": incorrect option type - should be a list or parameter!";
906       O << '!' << OptDesc.GenVariableName() << ".empty()";
907       return true;
908     }
909   }
910
911   return false;
912 }
913
914 /// EmitCaseTest2Args - Helper function used by
915 /// EmitCaseConstructHandler.
916 bool EmitCaseTest2Args(const std::string& TestName,
917                        const DagInit& d,
918                        const char* IndentLevel,
919                        const OptionDescriptions& OptDescs,
920                        std::ostream& O) {
921   checkNumberOfArguments(&d, 2);
922   const std::string& OptName = InitPtrToString(d.getArg(0));
923   const std::string& OptArg = InitPtrToString(d.getArg(1));
924   const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
925
926   if (TestName == "parameter_equals") {
927     if (!OptionType::IsParameter(OptDesc.Type))
928       throw OptName + ": incorrect option type - should be a parameter!";
929     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
930     return true;
931   }
932   else if (TestName == "element_in_list") {
933     if (!OptionType::IsList(OptDesc.Type))
934       throw OptName + ": incorrect option type - should be a list!";
935     const std::string& VarName = OptDesc.GenVariableName();
936     O << "std::find(" << VarName << ".begin(),\n"
937       << IndentLevel << Indent1 << VarName << ".end(), \""
938       << OptArg << "\") != " << VarName << ".end()";
939     return true;
940   }
941
942   return false;
943 }
944
945 // Forward declaration.
946 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
947 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
948                   const OptionDescriptions& OptDescs,
949                   std::ostream& O);
950
951 /// EmitLogicalOperationTest - Helper function used by
952 /// EmitCaseConstructHandler.
953 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
954                               const char* IndentLevel,
955                               const OptionDescriptions& OptDescs,
956                               std::ostream& O) {
957   O << '(';
958   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
959     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
960     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
961     if (j != NumArgs - 1)
962       O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
963     else
964       O << ')';
965   }
966 }
967
968 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
969 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
970                   const OptionDescriptions& OptDescs,
971                   std::ostream& O) {
972   const std::string& TestName = d.getOperator()->getAsString();
973
974   if (TestName == "and")
975     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
976   else if (TestName == "or")
977     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
978   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
979     return;
980   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
981     return;
982   else
983     throw TestName + ": unknown edge property!";
984 }
985
986 // Emit code that handles the 'case' construct.
987 // Takes a function object that should emit code for every case clause.
988 // Callback's type is
989 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
990 template <typename F>
991 void EmitCaseConstructHandler(const Init* Dag, const char* IndentLevel,
992                               F Callback, bool EmitElseIf,
993                               const OptionDescriptions& OptDescs,
994                               std::ostream& O) {
995   const DagInit* d = &InitPtrToDag(Dag);
996   if (d->getOperator()->getAsString() != "case")
997     throw std::string("EmitCaseConstructHandler should be invoked"
998                       " only on 'case' expressions!");
999
1000   unsigned numArgs = d->getNumArgs();
1001   if (d->getNumArgs() < 2)
1002     throw "There should be at least one clause in the 'case' expression:\n"
1003       + d->getAsString();
1004
1005   for (unsigned i = 0; i != numArgs; ++i) {
1006     const DagInit& Test = InitPtrToDag(d->getArg(i));
1007
1008     // Emit the test.
1009     if (Test.getOperator()->getAsString() == "default") {
1010       if (i+2 != numArgs)
1011         throw std::string("The 'default' clause should be the last in the"
1012                           "'case' construct!");
1013       O << IndentLevel << "else {\n";
1014     }
1015     else {
1016       O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1017       EmitCaseTest(Test, IndentLevel, OptDescs, O);
1018       O << ") {\n";
1019     }
1020
1021     // Emit the corresponding statement.
1022     ++i;
1023     if (i == numArgs)
1024       throw "Case construct handler: no corresponding action "
1025         "found for the test " + Test.getAsString() + '!';
1026
1027     Init* arg = d->getArg(i);
1028     const DagInit* nd = dynamic_cast<DagInit*>(arg);
1029     if (nd && (nd->getOperator()->getAsString() == "case")) {
1030       // Handle the nested 'case'.
1031       EmitCaseConstructHandler(nd, (std::string(IndentLevel) + Indent1).c_str(),
1032                                Callback, EmitElseIf, OptDescs, O);
1033     }
1034     else {
1035       Callback(arg, (std::string(IndentLevel) + Indent1).c_str(), O);
1036     }
1037     O << IndentLevel << "}\n";
1038   }
1039 }
1040
1041 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1042 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1043 std::string SubstituteSpecialCommands(const std::string& cmd) {
1044   size_t cparen = cmd.find(")");
1045   std::string ret;
1046
1047   if (cmd.find("$CALL(") == 0) {
1048     if (cmd.size() == 6)
1049       throw std::string("$CALL invocation: empty argument list!");
1050
1051     ret += "hooks::";
1052     ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1053     ret += "()";
1054   }
1055   else if (cmd.find("$ENV(") == 0) {
1056     if (cmd.size() == 5)
1057       throw std::string("$ENV invocation: empty argument list!");
1058
1059     ret += "checkCString(std::getenv(\"";
1060     ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1061     ret += "\"))";
1062   }
1063   else {
1064     throw "Unknown special command: " + cmd;
1065   }
1066
1067   if (cmd.begin() + cparen + 1 != cmd.end()) {
1068     ret += " + std::string(\"";
1069     ret += (cmd.c_str() + cparen + 1);
1070     ret += "\")";
1071   }
1072
1073   return ret;
1074 }
1075
1076 /// EmitCmdLineVecFill - Emit code that fills in the command line
1077 /// vector. Helper function used by EmitGenerateActionMethod().
1078 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1079                         bool IsJoin, const char* IndentLevel,
1080                         std::ostream& O) {
1081   StrVector StrVec;
1082   SplitString(InitPtrToString(CmdLine), StrVec);
1083   if (StrVec.empty())
1084     throw "Tool " + ToolName + " has empty command line!";
1085
1086   StrVector::const_iterator I = StrVec.begin();
1087   ++I;
1088   for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1089     const std::string& cmd = *I;
1090     O << IndentLevel;
1091     if (cmd.at(0) == '$') {
1092       if (cmd == "$INFILE") {
1093         if (IsJoin)
1094           O << "for (PathVector::const_iterator B = inFiles.begin()"
1095             << ", E = inFiles.end();\n"
1096             << IndentLevel << "B != E; ++B)\n"
1097             << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1098         else
1099           O << "vec.push_back(inFile.toString());\n";
1100       }
1101       else if (cmd == "$OUTFILE") {
1102         O << "vec.push_back(out_file);\n";
1103       }
1104       else {
1105         O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1106         O << ");\n";
1107       }
1108     }
1109     else {
1110       O << "vec.push_back(\"" << cmd << "\");\n";
1111     }
1112   }
1113   O << IndentLevel << "cmd = "
1114     << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1115         : "\"" + StrVec[0] + "\"")
1116     << ";\n";
1117 }
1118
1119 /// EmitCmdLineVecFillCallback - A function object wrapper around
1120 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1121 /// argument to EmitCaseConstructHandler().
1122 class EmitCmdLineVecFillCallback {
1123   bool IsJoin;
1124   const std::string& ToolName;
1125  public:
1126   EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1127     : IsJoin(J), ToolName(TN) {}
1128
1129   void operator()(const Init* Statement, const char* IndentLevel,
1130                   std::ostream& O) const
1131   {
1132     EmitCmdLineVecFill(Statement, ToolName, IsJoin,
1133                        IndentLevel, O);
1134   }
1135 };
1136
1137 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1138 /// implement EmitActionHandler. Emits code for
1139 /// handling the (forward) and (forward_as) option properties.
1140 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1141                                             const char* Indent,
1142                                             const std::string& NewName,
1143                                             std::ostream& O) {
1144   const std::string& Name = NewName.empty()
1145     ? ("-" + D.Name)
1146     : NewName;
1147
1148   switch (D.Type) {
1149   case OptionType::Switch:
1150     O << Indent << "vec.push_back(\"" << Name << "\");\n";
1151     break;
1152   case OptionType::Parameter:
1153     O << Indent << "vec.push_back(\"" << Name << "\");\n";
1154     O << Indent << "vec.push_back(" << D.GenVariableName() << ");\n";
1155     break;
1156   case OptionType::Prefix:
1157     O << Indent << "vec.push_back(\"" << Name << "\" + "
1158       << D.GenVariableName() << ");\n";
1159     break;
1160   case OptionType::PrefixList:
1161     O << Indent << "for (" << D.GenTypeDeclaration()
1162       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1163       << Indent << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1164       << Indent << Indent1 << "vec.push_back(\"" << Name << "\" + "
1165       << "*B);\n";
1166     break;
1167   case OptionType::ParameterList:
1168     O << Indent << "for (" << D.GenTypeDeclaration()
1169       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1170       << Indent << "E = " << D.GenVariableName()
1171       << ".end() ; B != E; ++B) {\n"
1172       << Indent << Indent1 << "vec.push_back(\"" << Name << "\");\n"
1173       << Indent << Indent1 << "vec.push_back(*B);\n"
1174       << Indent << "}\n";
1175     break;
1176   case OptionType::Alias:
1177   default:
1178     throw std::string("Aliases are not allowed in tool option descriptions!");
1179   }
1180 }
1181
1182 /// EmitActionHandler - Emit code that handles actions. Used by
1183 /// EmitGenerateActionMethod() as an argument to
1184 /// EmitCaseConstructHandler().
1185 class EmitActionHandler {
1186   const OptionDescriptions& OptDescs;
1187
1188   void processActionDag(const Init* Statement, const char* IndentLevel,
1189                         std::ostream& O) const
1190   {
1191     const DagInit& Dag = InitPtrToDag(Statement);
1192     const std::string& ActionName = Dag.getOperator()->getAsString();
1193
1194     if (ActionName == "append_cmd") {
1195       checkNumberOfArguments(&Dag, 1);
1196       const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1197       O << IndentLevel << "vec.push_back(\"" << Cmd << "\");\n";
1198     }
1199     else if (ActionName == "forward") {
1200       checkNumberOfArguments(&Dag, 1);
1201       const std::string& Name = InitPtrToString(Dag.getArg(0));
1202       EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1203                                             IndentLevel, "", O);
1204     }
1205     else if (ActionName == "forward_as") {
1206       checkNumberOfArguments(&Dag, 2);
1207       const std::string& Name = InitPtrToString(Dag.getArg(0));
1208       const std::string& NewName = InitPtrToString(Dag.getArg(0));
1209       EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1210                                             IndentLevel, NewName, O);
1211     }
1212     else if (ActionName == "output_suffix") {
1213       checkNumberOfArguments(&Dag, 1);
1214       const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1215       O << IndentLevel << "output_suffix = \"" << OutSuf << "\";\n";
1216     }
1217     else if (ActionName == "stop_compilation") {
1218       O << IndentLevel << "stop_compilation = true;\n";
1219     }
1220     else if (ActionName == "unpack_values") {
1221       checkNumberOfArguments(&Dag, 1);
1222       const std::string& Name = InitPtrToString(Dag.getArg(0));
1223       const OptionDescription& D = OptDescs.FindOption(Name);
1224
1225       if (OptionType::IsList(D.Type)) {
1226         O << IndentLevel << "for (" << D.GenTypeDeclaration()
1227           << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1228           << IndentLevel << "E = " << D.GenVariableName()
1229           << ".end(); B != E; ++B)\n"
1230           << IndentLevel << Indent1 << "llvm::SplitString(*B, vec, \",\");\n";
1231       }
1232       else if (OptionType::IsParameter(D.Type)){
1233         O << Indent3 << "llvm::SplitString("
1234           << D.GenVariableName() << ", vec, \",\");\n";
1235       }
1236       else {
1237         throw "Option '" + D.Name +
1238           "': switches can't have the 'unpack_values' property!";
1239       }
1240     }
1241     else {
1242       throw "Unknown action name: " + ActionName + "!";
1243     }
1244   }
1245  public:
1246   EmitActionHandler(const OptionDescriptions& OD)
1247     : OptDescs(OD) {}
1248
1249   void operator()(const Init* Statement, const char* IndentLevel,
1250                   std::ostream& O) const
1251   {
1252     if (typeid(*Statement) == typeid(ListInit)) {
1253       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1254       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1255            B != E; ++B)
1256         this->processActionDag(*B, IndentLevel, O);
1257     }
1258     else {
1259       this->processActionDag(Statement, IndentLevel, O);
1260     }
1261   }
1262 };
1263
1264 // EmitGenerateActionMethod - Emit one of two versions of the
1265 // Tool::GenerateAction() method.
1266 void EmitGenerateActionMethod (const ToolDescription& D,
1267                                const OptionDescriptions& OptDescs,
1268                                bool IsJoin, std::ostream& O) {
1269   if (IsJoin)
1270     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1271   else
1272     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1273
1274   O << Indent2 << "bool HasChildren,\n"
1275     << Indent2 << "const llvm::sys::Path& TempDir,\n"
1276     << Indent2 << "const InputLanguagesSet& InLangs,\n"
1277     << Indent2 << "const LanguageMap& LangMap) const\n"
1278     << Indent1 << "{\n"
1279     << Indent2 << "std::string cmd;\n"
1280     << Indent2 << "std::vector<std::string> vec;\n"
1281     << Indent2 << "bool stop_compilation = !HasChildren;\n"
1282     << Indent2 << "const char* output_suffix = \"" << D.OutputSuffix << "\";\n"
1283     << Indent2 << "std::string out_file;\n\n";
1284
1285   // For every understood option, emit handling code.
1286   if (D.Actions)
1287     EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1288                              false, OptDescs, O);
1289
1290   O << '\n' << Indent2
1291     << "out_file = OutFilename(" << (IsJoin ? "sys::Path(),\n" : "inFile,\n")
1292     << Indent3 << "TempDir, stop_compilation, output_suffix).toString();\n\n";
1293
1294   // cmd_line is either a string or a 'case' construct.
1295   if (!D.CmdLine)
1296     throw "Tool " + D.Name + " has no cmd_line property!";
1297   else if (typeid(*D.CmdLine) == typeid(StringInit))
1298     EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1299   else
1300     EmitCaseConstructHandler(D.CmdLine, Indent2,
1301                              EmitCmdLineVecFillCallback(IsJoin, D.Name),
1302                              true, OptDescs, O);
1303
1304   // Handle the Sink property.
1305   if (D.isSink()) {
1306     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1307       << Indent3 << "vec.insert(vec.end(), "
1308       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1309       << Indent2 << "}\n";
1310   }
1311
1312   O << Indent2 << "return Action(cmd, vec, stop_compilation, out_file);\n"
1313     << Indent1 << "}\n\n";
1314 }
1315
1316 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1317 /// a given Tool class.
1318 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1319                                 const OptionDescriptions& OptDescs,
1320                                 std::ostream& O) {
1321   if (!ToolDesc.isJoin())
1322     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1323       << Indent2 << "bool HasChildren,\n"
1324       << Indent2 << "const llvm::sys::Path& TempDir,\n"
1325       << Indent2 << "const InputLanguagesSet& InLangs,\n"
1326       << Indent2 << "const LanguageMap& LangMap) const\n"
1327       << Indent1 << "{\n"
1328       << Indent2 << "throw std::runtime_error(\"" << ToolDesc.Name
1329       << " is not a Join tool!\");\n"
1330       << Indent1 << "}\n\n";
1331   else
1332     EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1333
1334   EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1335 }
1336
1337 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1338 /// methods for a given Tool class.
1339 void EmitInOutLanguageMethods (const ToolDescription& D, std::ostream& O) {
1340   O << Indent1 << "const char** InputLanguages() const {\n"
1341     << Indent2 << "return InputLanguages_;\n"
1342     << Indent1 << "}\n\n";
1343
1344   if (D.OutLanguage.empty())
1345     throw "Tool " + D.Name + " has no 'out_language' property!";
1346
1347   O << Indent1 << "const char* OutputLanguage() const {\n"
1348     << Indent2 << "return \"" << D.OutLanguage << "\";\n"
1349     << Indent1 << "}\n\n";
1350 }
1351
1352 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1353 void EmitNameMethod (const ToolDescription& D, std::ostream& O) {
1354   O << Indent1 << "const char* Name() const {\n"
1355     << Indent2 << "return \"" << D.Name << "\";\n"
1356     << Indent1 << "}\n\n";
1357 }
1358
1359 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1360 /// class.
1361 void EmitIsJoinMethod (const ToolDescription& D, std::ostream& O) {
1362   O << Indent1 << "bool IsJoin() const {\n";
1363   if (D.isJoin())
1364     O << Indent2 << "return true;\n";
1365   else
1366     O << Indent2 << "return false;\n";
1367   O << Indent1 << "}\n\n";
1368 }
1369
1370 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1371 /// given Tool class.
1372 void EmitStaticMemberDefinitions(const ToolDescription& D, std::ostream& O) {
1373   if (D.InLanguage.empty())
1374     throw "Tool " + D.Name + " has no 'in_language' property!";
1375
1376   O << "const char* " << D.Name << "::InputLanguages_[] = {";
1377   for (StrVector::const_iterator B = D.InLanguage.begin(),
1378          E = D.InLanguage.end(); B != E; ++B)
1379     O << '\"' << *B << "\", ";
1380   O << "0};\n\n";
1381 }
1382
1383 /// EmitToolClassDefinition - Emit a Tool class definition.
1384 void EmitToolClassDefinition (const ToolDescription& D,
1385                               const OptionDescriptions& OptDescs,
1386                               std::ostream& O) {
1387   if (D.Name == "root")
1388     return;
1389
1390   // Header
1391   O << "class " << D.Name << " : public ";
1392   if (D.isJoin())
1393     O << "JoinTool";
1394   else
1395     O << "Tool";
1396
1397   O << "{\nprivate:\n"
1398     << Indent1 << "static const char* InputLanguages_[];\n\n";
1399
1400   O << "public:\n";
1401   EmitNameMethod(D, O);
1402   EmitInOutLanguageMethods(D, O);
1403   EmitIsJoinMethod(D, O);
1404   EmitGenerateActionMethods(D, OptDescs, O);
1405
1406   // Close class definition
1407   O << "};\n";
1408
1409   EmitStaticMemberDefinitions(D, O);
1410
1411 }
1412
1413 /// EmitOptionDefintions - Iterate over a list of option descriptions
1414 /// and emit registration code.
1415 void EmitOptionDefintions (const OptionDescriptions& descs,
1416                            bool HasSink, bool HasExterns,
1417                            std::ostream& O)
1418 {
1419   std::vector<OptionDescription> Aliases;
1420
1421   // Emit static cl::Option variables.
1422   for (OptionDescriptions::const_iterator B = descs.begin(),
1423          E = descs.end(); B!=E; ++B) {
1424     const OptionDescription& val = B->second;
1425
1426     if (val.Type == OptionType::Alias) {
1427       Aliases.push_back(val);
1428       continue;
1429     }
1430
1431     if (val.isExtern())
1432       O << "extern ";
1433
1434     O << val.GenTypeDeclaration() << ' '
1435       << val.GenVariableName();
1436
1437     if (val.isExtern()) {
1438       O << ";\n";
1439       continue;
1440     }
1441
1442     O << "(\"" << val.Name << '\"';
1443
1444     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1445       O << ", cl::Prefix";
1446
1447     if (val.isRequired()) {
1448       switch (val.Type) {
1449       case OptionType::PrefixList:
1450       case OptionType::ParameterList:
1451         O << ", cl::OneOrMore";
1452         break;
1453       default:
1454         O << ", cl::Required";
1455       }
1456     }
1457
1458     if (val.isReallyHidden() || val.isHidden()) {
1459       if (val.isRequired())
1460         O << " |";
1461       else
1462         O << ",";
1463       if (val.isReallyHidden())
1464         O << " cl::ReallyHidden";
1465       else
1466         O << " cl::Hidden";
1467     }
1468
1469     if (!val.Help.empty())
1470       O << ", cl::desc(\"" << val.Help << "\")";
1471
1472     O << ");\n";
1473   }
1474
1475   // Emit the aliases (they should go after all the 'proper' options).
1476   for (std::vector<OptionDescription>::const_iterator
1477          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1478     const OptionDescription& val = *B;
1479
1480     O << val.GenTypeDeclaration() << ' '
1481       << val.GenVariableName()
1482       << "(\"" << val.Name << '\"';
1483
1484     const OptionDescription& D = descs.FindOption(val.Help);
1485     O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1486
1487     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
1488   }
1489
1490   // Emit the sink option.
1491   if (HasSink)
1492     O << (HasExterns ? "extern cl" : "cl")
1493       << "::list<std::string> " << SinkOptionName
1494       << (HasExterns ? ";\n" : "(cl::Sink);\n");
1495
1496   O << '\n';
1497 }
1498
1499 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1500 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1501 {
1502   // Generate code
1503   O << "namespace {\n\n";
1504   O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1505
1506   // Get the relevant field out of RecordKeeper
1507   const Record* LangMapRecord = Records.getDef("LanguageMap");
1508
1509   // It is allowed for a plugin to have no language map.
1510   if (LangMapRecord) {
1511
1512     ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1513     if (!LangsToSuffixesList)
1514       throw std::string("Error in the language map definition!");
1515
1516     for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1517       const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1518
1519       const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1520       const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1521
1522       for (unsigned i = 0; i < Suffixes->size(); ++i)
1523         O << Indent1 << "langMap[\""
1524           << InitPtrToString(Suffixes->getElement(i))
1525           << "\"] = \"" << Lang << "\";\n";
1526     }
1527   }
1528
1529   O << "}\n\n}\n\n";
1530 }
1531
1532 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1533 /// by EmitEdgeClass().
1534 void IncDecWeight (const Init* i, const char* IndentLevel,
1535                    std::ostream& O) {
1536   const DagInit& d = InitPtrToDag(i);
1537   const std::string& OpName = d.getOperator()->getAsString();
1538
1539   if (OpName == "inc_weight")
1540     O << IndentLevel << "ret += ";
1541   else if (OpName == "dec_weight")
1542     O << IndentLevel << "ret -= ";
1543   else
1544     throw "Unknown operator in edge properties list: " + OpName + '!';
1545
1546   if (d.getNumArgs() > 0)
1547     O << InitPtrToInt(d.getArg(0)) << ";\n";
1548   else
1549     O << "2;\n";
1550
1551 }
1552
1553 /// EmitEdgeClass - Emit a single Edge# class.
1554 void EmitEdgeClass (unsigned N, const std::string& Target,
1555                     DagInit* Case, const OptionDescriptions& OptDescs,
1556                     std::ostream& O) {
1557
1558   // Class constructor.
1559   O << "class Edge" << N << ": public Edge {\n"
1560     << "public:\n"
1561     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1562     << "\") {}\n\n"
1563
1564   // Function Weight().
1565     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1566     << Indent2 << "unsigned ret = 0;\n";
1567
1568   // Handle the 'case' construct.
1569   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1570
1571   O << Indent2 << "return ret;\n"
1572     << Indent1 << "};\n\n};\n\n";
1573 }
1574
1575 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1576 void EmitEdgeClasses (const RecordVector& EdgeVector,
1577                       const OptionDescriptions& OptDescs,
1578                       std::ostream& O) {
1579   int i = 0;
1580   for (RecordVector::const_iterator B = EdgeVector.begin(),
1581          E = EdgeVector.end(); B != E; ++B) {
1582     const Record* Edge = *B;
1583     const std::string& NodeB = Edge->getValueAsString("b");
1584     DagInit* Weight = Edge->getValueAsDag("weight");
1585
1586     if (!isDagEmpty(Weight))
1587       EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
1588     ++i;
1589   }
1590 }
1591
1592 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1593 /// function.
1594 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1595                                    const ToolDescriptions& ToolDescs,
1596                                    std::ostream& O)
1597 {
1598   O << "namespace {\n\n";
1599   O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1600
1601   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1602          E = ToolDescs.end(); B != E; ++B)
1603     O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
1604
1605   O << '\n';
1606
1607   // Insert edges.
1608
1609   int i = 0;
1610   for (RecordVector::const_iterator B = EdgeVector.begin(),
1611          E = EdgeVector.end(); B != E; ++B) {
1612     const Record* Edge = *B;
1613     const std::string& NodeA = Edge->getValueAsString("a");
1614     const std::string& NodeB = Edge->getValueAsString("b");
1615     DagInit* Weight = Edge->getValueAsDag("weight");
1616
1617     O << Indent1 << "G.insertEdge(\"" << NodeA << "\", ";
1618
1619     if (isDagEmpty(Weight))
1620       O << "new SimpleEdge(\"" << NodeB << "\")";
1621     else
1622       O << "new Edge" << i << "()";
1623
1624     O << ");\n";
1625     ++i;
1626   }
1627
1628   O << "}\n\n}\n\n";
1629 }
1630
1631 /// ExtractHookNames - Extract the hook names from all instances of
1632 /// $CALL(HookName) in the provided command line string. Helper
1633 /// function used by FillInHookNames().
1634 class ExtractHookNames {
1635   llvm::StringSet<>& HookNames_;
1636 public:
1637   ExtractHookNames(llvm::StringSet<>& HookNames)
1638   : HookNames_(HookNames_) {}
1639
1640   void operator()(const Init* CmdLine) {
1641     StrVector cmds;
1642     llvm::SplitString(InitPtrToString(CmdLine), cmds);
1643     for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1644          B != E; ++B) {
1645       const std::string& cmd = *B;
1646       if (cmd.find("$CALL(") == 0) {
1647         if (cmd.size() == 6)
1648           throw std::string("$CALL invocation: empty argument list!");
1649         HookNames_.insert(std::string(cmd.begin() + 6,
1650                                      cmd.begin() + cmd.find(")")));
1651       }
1652     }
1653   }
1654 };
1655
1656 /// FillInHookNames - Actually extract the hook names from all command
1657 /// line strings. Helper function used by EmitHookDeclarations().
1658 void FillInHookNames(const ToolDescriptions& ToolDescs,
1659                      llvm::StringSet<>& HookNames)
1660 {
1661   // For all command lines:
1662   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1663          E = ToolDescs.end(); B != E; ++B) {
1664     const ToolDescription& D = *(*B);
1665     if (!D.CmdLine)
1666       continue;
1667     if (dynamic_cast<StringInit*>(D.CmdLine))
1668       // This is a string.
1669       ExtractHookNames(HookNames).operator()(D.CmdLine);
1670     else
1671       // This is a 'case' construct.
1672       WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
1673   }
1674 }
1675
1676 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1677 /// property records and emit hook function declaration for each
1678 /// instance of $CALL(HookName).
1679 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, std::ostream& O) {
1680   llvm::StringSet<> HookNames;
1681   FillInHookNames(ToolDescs, HookNames);
1682   if (HookNames.empty())
1683     return;
1684
1685   O << "namespace hooks {\n";
1686   for (StringSet<>::const_iterator B = HookNames.begin(), E = HookNames.end();
1687        B != E; ++B)
1688     O << Indent1 << "std::string " << B->first() << "();\n";
1689
1690   O << "}\n\n";
1691 }
1692
1693 /// EmitRegisterPlugin - Emit code to register this plugin.
1694 void EmitRegisterPlugin(int Priority, std::ostream& O) {
1695   O << "namespace {\n\n"
1696     << "struct Plugin : public llvmc::BasePlugin {\n\n"
1697     << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
1698     << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1699     << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1700     << Indent1
1701     << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1702     << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1703     << "};\n\n"
1704
1705     << "static llvmc::RegisterPlugin<Plugin> RP;\n\n}\n\n";
1706 }
1707
1708 /// EmitIncludes - Emit necessary #include directives and some
1709 /// additional declarations.
1710 void EmitIncludes(std::ostream& O) {
1711   O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1712     << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1713     << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1714
1715     << "#include \"llvm/ADT/StringExtras.h\"\n"
1716     << "#include \"llvm/Support/CommandLine.h\"\n\n"
1717
1718     << "#include <cstdlib>\n"
1719     << "#include <stdexcept>\n\n"
1720
1721     << "using namespace llvm;\n"
1722     << "using namespace llvmc;\n\n"
1723
1724     << "extern cl::opt<std::string> OutputFilename;\n\n"
1725
1726     << "inline const char* checkCString(const char* s)\n"
1727     << "{ return s == NULL ? \"\" : s; }\n\n";
1728 }
1729
1730
1731 /// PluginData - Holds all information about a plugin.
1732 struct PluginData {
1733   OptionDescriptions OptDescs;
1734   bool HasSink;
1735   bool HasExterns;
1736   ToolDescriptions ToolDescs;
1737   RecordVector Edges;
1738   int Priority;
1739 };
1740
1741 /// HasSink - Go through the list of tool descriptions and check if
1742 /// there are any with the 'sink' property set.
1743 bool HasSink(const ToolDescriptions& ToolDescs) {
1744   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1745          E = ToolDescs.end(); B != E; ++B)
1746     if ((*B)->isSink())
1747       return true;
1748
1749   return false;
1750 }
1751
1752 /// HasExterns - Go through the list of option descriptions and check
1753 /// if there are any external options.
1754 bool HasExterns(const OptionDescriptions& OptDescs) {
1755  for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1756          E = OptDescs.end(); B != E; ++B)
1757     if (B->second.isExtern())
1758       return true;
1759
1760   return false;
1761 }
1762
1763 /// CollectPluginData - Collect tool and option properties,
1764 /// compilation graph edges and plugin priority from the parse tree.
1765 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
1766   // Collect option properties.
1767   const RecordVector& OptionLists =
1768     Records.getAllDerivedDefinitions("OptionList");
1769   CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
1770                             Data.OptDescs);
1771
1772   // Collect tool properties.
1773   const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
1774   CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
1775   Data.HasSink = HasSink(Data.ToolDescs);
1776   Data.HasExterns = HasExterns(Data.OptDescs);
1777
1778   // Collect compilation graph edges.
1779   const RecordVector& CompilationGraphs =
1780     Records.getAllDerivedDefinitions("CompilationGraph");
1781   FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
1782                    Data.Edges);
1783
1784   // Calculate the priority of this plugin.
1785   const RecordVector& Priorities =
1786     Records.getAllDerivedDefinitions("PluginPriority");
1787   Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
1788 }
1789
1790 /// CheckPluginData - Perform some sanity checks on the collected data.
1791 void CheckPluginData(PluginData& Data) {
1792   // Filter out all tools not mentioned in the compilation graph.
1793   FilterNotInGraph(Data.Edges, Data.ToolDescs);
1794
1795   // Typecheck the compilation graph.
1796   TypecheckGraph(Data.Edges, Data.ToolDescs);
1797
1798   // Check that there are no options without side effects (specified
1799   // only in the OptionList).
1800   CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
1801
1802 }
1803
1804 void EmitPluginCode(const PluginData& Data, std::ostream& O) {
1805   // Emit file header.
1806   EmitIncludes(O);
1807
1808   // Emit global option registration code.
1809   EmitOptionDefintions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
1810
1811   // Emit hook declarations.
1812   EmitHookDeclarations(Data.ToolDescs, O);
1813
1814   // Emit PopulateLanguageMap() function
1815   // (a language map maps from file extensions to language names).
1816   EmitPopulateLanguageMap(Records, O);
1817
1818   // Emit Tool classes.
1819   for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
1820          E = Data.ToolDescs.end(); B!=E; ++B)
1821     EmitToolClassDefinition(*(*B), Data.OptDescs, O);
1822
1823   // Emit Edge# classes.
1824   EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
1825
1826   // Emit PopulateCompilationGraph() function.
1827   EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
1828
1829   // Emit code for plugin registration.
1830   EmitRegisterPlugin(Data.Priority, O);
1831
1832   // EOF
1833 }
1834
1835
1836 // End of anonymous namespace
1837 }
1838
1839 /// run - The back-end entry point.
1840 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1841   try {
1842   PluginData Data;
1843
1844   CollectPluginData(Records, Data);
1845   CheckPluginData(Data);
1846
1847   EmitSourceFileHeader("LLVMC Configuration Library", O);
1848   EmitPluginCode(Data, O);
1849
1850   } catch (std::exception& Error) {
1851     throw Error.what() + std::string(" - usually this means a syntax error.");
1852   }
1853 }