77daf627a25f6a60bceaa8e879b641f17bee959d
[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
30 using namespace llvm;
31
32 namespace {
33
34 //===----------------------------------------------------------------------===//
35 /// Typedefs
36
37 typedef std::vector<Record*> RecordVector;
38 typedef std::vector<std::string> StrVector;
39
40 //===----------------------------------------------------------------------===//
41 /// Constants
42
43 // Indentation strings.
44 const char * Indent1 = "    ";
45 const char * Indent2 = "        ";
46 const char * Indent3 = "            ";
47 const char * Indent4 = "                ";
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 int InitPtrToInt(const Init* ptr) {
59   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
60   return val.getValue();
61 }
62
63 const std::string& InitPtrToString(const Init* ptr) {
64   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
65   return val.getValue();
66 }
67
68 const ListInit& InitPtrToList(const Init* ptr) {
69   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
70   return val;
71 }
72
73 const DagInit& InitPtrToDag(const Init* ptr) {
74   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
75   return val;
76 }
77
78 // checkNumberOfArguments - Ensure that the number of args in d is
79 // less than or equal to min_arguments, otherwise throw an exception.
80 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
81   if (d->getNumArgs() < min_arguments)
82     throw "Property " + d->getOperator()->getAsString()
83       + " has too few arguments!";
84 }
85
86 // isDagEmpty - is this DAG marked with an empty marker?
87 bool isDagEmpty (const DagInit* d) {
88   return d->getOperator()->getAsString() == "empty";
89 }
90
91 //===----------------------------------------------------------------------===//
92 /// Back-end specific code
93
94 // A command-line option can have one of the following types:
95 //
96 // Alias - an alias for another option.
97 //
98 // Switch - a simple switch without arguments, e.g. -O2
99 //
100 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
101 // --output=file
102 //
103 // ParameterList - same as Parameter, but more than one occurence
104 // of the option is allowed, e.g. -lm -lpthread
105 //
106 // Prefix - argument is everything after the prefix,
107 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
108 //
109 // PrefixList - same as Prefix, but more than one option occurence is
110 // allowed.
111
112 namespace OptionType {
113   enum OptionType { Alias, Switch,
114                     Parameter, ParameterList, Prefix, PrefixList};
115 }
116
117 bool IsListOptionType (OptionType::OptionType t) {
118   return (t == OptionType::ParameterList || t == OptionType::PrefixList);
119 }
120
121 // Code duplication here is necessary because one option can affect
122 // several tools and those tools may have different actions associated
123 // with this option. GlobalOptionDescriptions are used to generate
124 // the option registration code, while ToolOptionDescriptions are used
125 // to generate tool-specific code.
126
127 /// OptionDescription - Base class for option descriptions.
128 struct OptionDescription {
129   OptionType::OptionType Type;
130   std::string Name;
131
132   OptionDescription(OptionType::OptionType t = OptionType::Switch,
133                     const std::string& n = "")
134   : Type(t), Name(n)
135   {}
136
137   const char* GenTypeDeclaration() const {
138     switch (Type) {
139     case OptionType::Alias:
140       return "cl::alias";
141     case OptionType::PrefixList:
142     case OptionType::ParameterList:
143       return "cl::list<std::string>";
144     case OptionType::Switch:
145       return "cl::opt<bool>";
146     case OptionType::Parameter:
147     case OptionType::Prefix:
148     default:
149       return "cl::opt<std::string>";
150     }
151   }
152
153   // Escape commas and other symbols not allowed in the C++ variable
154   // names. Makes it possible to use options with names like "Wa,"
155   // (useful for prefix options).
156   std::string EscapeVariableName(const std::string& Var) const {
157     std::string ret;
158     for (unsigned i = 0; i != Var.size(); ++i) {
159       if (Var[i] == ',') {
160         ret += "_comma_";
161       }
162       else {
163         ret.push_back(Var[i]);
164       }
165     }
166     return ret;
167   }
168
169   std::string GenVariableName() const {
170     const std::string& EscapedName = EscapeVariableName(Name);
171     switch (Type) {
172     case OptionType::Alias:
173      return "AutoGeneratedAlias" + EscapedName;
174     case OptionType::Switch:
175       return "AutoGeneratedSwitch" + EscapedName;
176     case OptionType::Prefix:
177       return "AutoGeneratedPrefix" + EscapedName;
178     case OptionType::PrefixList:
179       return "AutoGeneratedPrefixList" + EscapedName;
180     case OptionType::Parameter:
181       return "AutoGeneratedParameter" + EscapedName;
182     case OptionType::ParameterList:
183     default:
184       return "AutoGeneratedParameterList" + EscapedName;
185     }
186   }
187
188 };
189
190 // Global option description.
191
192 namespace GlobalOptionDescriptionFlags {
193   enum GlobalOptionDescriptionFlags { Required = 0x1 };
194 }
195
196 struct GlobalOptionDescription : public OptionDescription {
197   std::string Help;
198   unsigned Flags;
199
200   // We need to provide a default constructor because
201   // StringMap can only store DefaultConstructible objects.
202   GlobalOptionDescription() : OptionDescription(), Flags(0)
203   {}
204
205   GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
206                            const std::string& h = DefaultHelpString)
207     : OptionDescription(t, n), Help(h), Flags(0)
208   {}
209
210   bool isRequired() const {
211     return Flags & GlobalOptionDescriptionFlags::Required;
212   }
213   void setRequired() {
214     Flags |= GlobalOptionDescriptionFlags::Required;
215   }
216
217   /// Merge - Merge two option descriptions.
218   void Merge (const GlobalOptionDescription& other)
219   {
220     if (other.Type != Type)
221       throw "Conflicting definitions for the option " + Name + "!";
222
223     if (Help == DefaultHelpString)
224       Help = other.Help;
225     else if (other.Help != DefaultHelpString) {
226       llvm::cerr << "Warning: more than one help string defined for option "
227         + Name + "\n";
228     }
229
230     Flags |= other.Flags;
231   }
232 };
233
234 /// GlobalOptionDescriptions - A GlobalOptionDescription array
235 /// together with some flags affecting generation of option
236 /// declarations.
237 struct GlobalOptionDescriptions {
238   typedef StringMap<GlobalOptionDescription> container_type;
239   typedef container_type::const_iterator const_iterator;
240
241   /// Descriptions - A list of GlobalOptionDescriptions.
242   container_type Descriptions;
243   /// HasSink - Should the emitter generate a "cl::sink" option?
244   bool HasSink;
245
246   const GlobalOptionDescription& FindOption(const std::string& OptName) const {
247     const_iterator I = Descriptions.find(OptName);
248     if (I != Descriptions.end())
249       return I->second;
250     else
251       throw OptName + ": no such option!";
252   }
253
254   // Support for STL-style iteration
255   const_iterator begin() const { return Descriptions.begin(); }
256   const_iterator end() const { return Descriptions.end(); }
257 };
258
259
260 // Tool-local option description.
261
262 // Properties without arguments are implemented as flags.
263 namespace ToolOptionDescriptionFlags {
264   enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
265                                     Forward = 0x2, UnpackValues = 0x4};
266 }
267 namespace OptionPropertyType {
268   enum OptionPropertyType { AppendCmd, OutputSuffix };
269 }
270
271 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
272 OptionProperty;
273 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
274
275 struct ToolOptionDescription : public OptionDescription {
276   unsigned Flags;
277   OptionPropertyList Props;
278
279   // StringMap can only store DefaultConstructible objects
280   ToolOptionDescription() : OptionDescription(), Flags(0) {}
281
282   ToolOptionDescription (OptionType::OptionType t, const std::string& n)
283     : OptionDescription(t, n)
284   {}
285
286   // Various boolean properties
287   bool isStopCompilation() const {
288     return Flags & ToolOptionDescriptionFlags::StopCompilation;
289   }
290   void setStopCompilation() {
291     Flags |= ToolOptionDescriptionFlags::StopCompilation;
292   }
293
294   bool isForward() const {
295     return Flags & ToolOptionDescriptionFlags::Forward;
296   }
297   void setForward() {
298     Flags |= ToolOptionDescriptionFlags::Forward;
299   }
300
301   bool isUnpackValues() const {
302     return Flags & ToolOptionDescriptionFlags::UnpackValues;
303   }
304   void setUnpackValues() {
305     Flags |= ToolOptionDescriptionFlags::UnpackValues;
306   }
307
308   void AddProperty (OptionPropertyType::OptionPropertyType t,
309                     const std::string& val)
310   {
311     Props.push_back(std::make_pair(t, val));
312   }
313 };
314
315 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
316
317 // Tool information record
318
319 namespace ToolFlags {
320   enum ToolFlags { Join = 0x1, Sink = 0x2 };
321 }
322
323 struct ToolProperties : public RefCountedBase<ToolProperties> {
324   std::string Name;
325   Init* CmdLine;
326   StrVector InLanguage;
327   std::string OutLanguage;
328   std::string OutputSuffix;
329   unsigned Flags;
330   ToolOptionDescriptions OptDescs;
331
332   // Various boolean properties
333   void setSink()      { Flags |= ToolFlags::Sink; }
334   bool isSink() const { return Flags & ToolFlags::Sink; }
335   void setJoin()      { Flags |= ToolFlags::Join; }
336   bool isJoin() const { return Flags & ToolFlags::Join; }
337
338   // Default ctor here is needed because StringMap can only store
339   // DefaultConstructible objects
340   ToolProperties() : Flags(0) {}
341   ToolProperties (const std::string& n) : Name(n), Flags(0) {}
342 };
343
344
345 /// ToolPropertiesList - A list of Tool information records
346 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
347 /// constructor (and we want to avoid copying ToolProperties anyway).
348 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
349
350
351 /// CollectProperties - Function object for iterating over a list of
352 /// tool property records.
353 class CollectProperties {
354 private:
355
356   /// Implementation details
357
358   /// PropertyHandler - a function that extracts information
359   /// about a given tool property from its DAG representation
360   typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
361
362   /// PropertyHandlerMap - A map from property names to property
363   /// handlers.
364   typedef StringMap<PropertyHandler> PropertyHandlerMap;
365
366   /// OptionPropertyHandler - a function that extracts information
367   /// about a given option property from its DAG representation.
368   typedef void (CollectProperties::* OptionPropertyHandler)
369   (const DagInit*, GlobalOptionDescription &);
370
371   /// OptionPropertyHandlerMap - A map from option property names to
372   /// option property handlers
373   typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
374
375   // Static maps from strings to CollectProperties methods("handlers")
376   static PropertyHandlerMap propertyHandlers_;
377   static OptionPropertyHandlerMap optionPropertyHandlers_;
378   static bool staticMembersInitialized_;
379
380
381   /// This is where the information is stored
382
383   /// toolProps_ -  Properties of the current Tool.
384   ToolProperties& toolProps_;
385   /// optDescs_ - OptionDescriptions table (used to register options
386   /// globally).
387   GlobalOptionDescriptions& optDescs_;
388
389 public:
390
391   explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
392     : toolProps_(p), optDescs_(d)
393   {
394     if (!staticMembersInitialized_) {
395       // Init tool property handlers
396       propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
397       propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
398       propertyHandlers_["join"] = &CollectProperties::onJoin;
399       propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
400       propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
401       propertyHandlers_["parameter_option"]
402         = &CollectProperties::onParameter;
403       propertyHandlers_["parameter_list_option"] =
404         &CollectProperties::onParameterList;
405       propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
406       propertyHandlers_["prefix_list_option"] =
407         &CollectProperties::onPrefixList;
408       propertyHandlers_["sink"] = &CollectProperties::onSink;
409       propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
410       propertyHandlers_["alias_option"] = &CollectProperties::onAlias;
411
412       // Init option property handlers
413       optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
414       optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
415       optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
416       optionPropertyHandlers_["output_suffix"] =
417         &CollectProperties::onOutputSuffixOptionProp;
418       optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
419       optionPropertyHandlers_["stop_compilation"] =
420         &CollectProperties::onStopCompilation;
421       optionPropertyHandlers_["unpack_values"] =
422         &CollectProperties::onUnpackValues;
423
424       staticMembersInitialized_ = true;
425     }
426   }
427
428   /// operator() - Gets called for every tool property; Just forwards
429   /// to the corresponding property handler.
430   void operator() (Init* i) {
431     const DagInit& d = InitPtrToDag(i);
432     const std::string& property_name = d.getOperator()->getAsString();
433     PropertyHandlerMap::iterator method
434       = propertyHandlers_.find(property_name);
435
436     if (method != propertyHandlers_.end()) {
437       PropertyHandler h = method->second;
438       (this->*h)(&d);
439     }
440     else {
441       throw "Unknown tool property: " + property_name + "!";
442     }
443   }
444
445 private:
446
447   /// Property handlers --
448   /// Functions that extract information about tool properties from
449   /// DAG representation.
450
451   void onCmdLine (const DagInit* d) {
452     checkNumberOfArguments(d, 1);
453     toolProps_.CmdLine = d->getArg(0);
454   }
455
456   void onInLanguage (const DagInit* d) {
457     checkNumberOfArguments(d, 1);
458     Init* arg = d->getArg(0);
459
460     // Find out the argument's type.
461     if (typeid(*arg) == typeid(StringInit)) {
462       // It's a string.
463       toolProps_.InLanguage.push_back(InitPtrToString(arg));
464     }
465     else {
466       // It's a list.
467       const ListInit& lst = InitPtrToList(arg);
468       StrVector& out = toolProps_.InLanguage;
469
470       // Copy strings to the output vector.
471       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
472            B != E; ++B) {
473         out.push_back(InitPtrToString(*B));
474       }
475
476       // Remove duplicates.
477       std::sort(out.begin(), out.end());
478       StrVector::iterator newE = std::unique(out.begin(), out.end());
479       out.erase(newE, out.end());
480     }
481   }
482
483   void onJoin (const DagInit* d) {
484     checkNumberOfArguments(d, 0);
485     toolProps_.setJoin();
486   }
487
488   void onOutLanguage (const DagInit* d) {
489     checkNumberOfArguments(d, 1);
490     toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
491   }
492
493   void onOutputSuffix (const DagInit* d) {
494     checkNumberOfArguments(d, 1);
495     toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
496   }
497
498   void onSink (const DagInit* d) {
499     checkNumberOfArguments(d, 0);
500     optDescs_.HasSink = true;
501     toolProps_.setSink();
502   }
503
504   void onAlias (const DagInit* d) {
505     checkNumberOfArguments(d, 2);
506     // We just need a GlobalOptionDescription for the aliases.
507     insertDescription
508       (GlobalOptionDescription(OptionType::Alias,
509                                InitPtrToString(d->getArg(0)),
510                                InitPtrToString(d->getArg(1))));
511   }
512
513   void onSwitch (const DagInit* d) {
514     addOption(d, OptionType::Switch);
515   }
516
517   void onParameter (const DagInit* d) {
518     addOption(d, OptionType::Parameter);
519   }
520
521   void onParameterList (const DagInit* d) {
522     addOption(d, OptionType::ParameterList);
523   }
524
525   void onPrefix (const DagInit* d) {
526     addOption(d, OptionType::Prefix);
527   }
528
529   void onPrefixList (const DagInit* d) {
530     addOption(d, OptionType::PrefixList);
531   }
532
533   /// Option property handlers --
534   /// Methods that handle properties that are common for all types of
535   /// options (like append_cmd, stop_compilation)
536
537   void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
538     checkNumberOfArguments(d, 1);
539     const std::string& cmd = InitPtrToString(d->getArg(0));
540
541     toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
542   }
543
544   void onOutputSuffixOptionProp (const DagInit* d, GlobalOptionDescription& o) {
545     checkNumberOfArguments(d, 1);
546     const std::string& suf = InitPtrToString(d->getArg(0));
547
548     if (toolProps_.OptDescs[o.Name].Type != OptionType::Switch)
549       throw "Option " + o.Name
550         + " can't have 'output_suffix' property since it isn't a switch!";
551
552     toolProps_.OptDescs[o.Name].AddProperty
553       (OptionPropertyType::OutputSuffix, suf);
554   }
555
556   void onForward (const DagInit* d, GlobalOptionDescription& o) {
557     checkNumberOfArguments(d, 0);
558     toolProps_.OptDescs[o.Name].setForward();
559   }
560
561   void onHelp (const DagInit* d, GlobalOptionDescription& o) {
562     checkNumberOfArguments(d, 1);
563     const std::string& help_message = InitPtrToString(d->getArg(0));
564
565     o.Help = help_message;
566   }
567
568   void onRequired (const DagInit* d, GlobalOptionDescription& o) {
569     checkNumberOfArguments(d, 0);
570     o.setRequired();
571   }
572
573   void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
574     checkNumberOfArguments(d, 0);
575     if (o.Type != OptionType::Switch)
576       throw std::string("Only options of type Switch can stop compilation!");
577     toolProps_.OptDescs[o.Name].setStopCompilation();
578   }
579
580   void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
581     checkNumberOfArguments(d, 0);
582     toolProps_.OptDescs[o.Name].setUnpackValues();
583   }
584
585   /// Helper functions
586
587   // Add an option of type t
588   void addOption (const DagInit* d, OptionType::OptionType t) {
589     checkNumberOfArguments(d, 2);
590     const std::string& name = InitPtrToString(d->getArg(0));
591
592     GlobalOptionDescription o(t, name);
593     toolProps_.OptDescs[name].Type = t;
594     toolProps_.OptDescs[name].Name = name;
595     processOptionProperties(d, o);
596     insertDescription(o);
597   }
598
599   // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
600   void insertDescription (const GlobalOptionDescription& o)
601   {
602     if (optDescs_.Descriptions.count(o.Name)) {
603       GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
604       D.Merge(o);
605     }
606     else {
607       optDescs_.Descriptions[o.Name] = o;
608     }
609   }
610
611   /// processOptionProperties - Go through the list of option
612   /// properties and call a corresponding handler for each.
613   ///
614   /// Parameters:
615   /// name - option name
616   /// d - option property list
617   void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
618     // First argument is option name
619     checkNumberOfArguments(d, 2);
620
621     for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
622       const DagInit& option_property
623         = InitPtrToDag(d->getArg(B));
624       const std::string& option_property_name
625         = option_property.getOperator()->getAsString();
626       OptionPropertyHandlerMap::iterator method
627         = optionPropertyHandlers_.find(option_property_name);
628
629       if (method != optionPropertyHandlers_.end()) {
630         OptionPropertyHandler h = method->second;
631         (this->*h)(&option_property, o);
632       }
633       else {
634         throw "Unknown option property: " + option_property_name + "!";
635       }
636     }
637   }
638 };
639
640 // Static members of CollectProperties
641 CollectProperties::PropertyHandlerMap
642 CollectProperties::propertyHandlers_;
643
644 CollectProperties::OptionPropertyHandlerMap
645 CollectProperties::optionPropertyHandlers_;
646
647 bool CollectProperties::staticMembersInitialized_ = false;
648
649
650 /// CollectToolProperties - Gather information about tool properties
651 /// from the parsed TableGen data (basically a wrapper for the
652 /// CollectProperties function object).
653 void CollectToolProperties (RecordVector::const_iterator B,
654                             RecordVector::const_iterator E,
655                             ToolPropertiesList& TPList,
656                             GlobalOptionDescriptions& OptDescs)
657 {
658   // Iterate over a properties list of every Tool definition
659   for (;B!=E;++B) {
660     Record* T = *B;
661     // Throws an exception if the value does not exist.
662     ListInit* PropList = T->getValueAsListInit("properties");
663
664     IntrusiveRefCntPtr<ToolProperties>
665       ToolProps(new ToolProperties(T->getName()));
666
667     std::for_each(PropList->begin(), PropList->end(),
668                   CollectProperties(*ToolProps, OptDescs));
669     TPList.push_back(ToolProps);
670   }
671 }
672
673 /// CollectToolPropertiesFromOptionList - Gather information about
674 /// *global* option properties from the OptionList.
675 // TOFIX - This is kinda hacky, since it allows to use arbitrary tool
676 // properties in the OptionList. CollectProperties function object
677 // should be split into two parts that collect tool and option
678 // properties, respectively.
679 void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
680                                       RecordVector::const_iterator E,
681                                       GlobalOptionDescriptions& OptDescs)
682 {
683   // Iterate over a properties list of every Tool definition
684   ToolProperties ToolProps("dummy");
685   for (;B!=E;++B) {
686     RecordVector::value_type T = *B;
687     // Throws an exception if the value does not exist.
688     ListInit* PropList = T->getValueAsListInit("options");
689
690     std::for_each(PropList->begin(), PropList->end(),
691                   CollectProperties(ToolProps, OptDescs));
692   }
693 }
694
695 /// EmitCaseTest1Arg - Helper function used by
696 /// EmitCaseConstructHandler.
697 bool EmitCaseTest1Arg(const std::string& TestName,
698                       const DagInit& d,
699                       const GlobalOptionDescriptions& OptDescs,
700                       std::ostream& O) {
701   checkNumberOfArguments(&d, 1);
702   const std::string& OptName = InitPtrToString(d.getArg(0));
703   if (TestName == "switch_on") {
704     const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
705     if (OptDesc.Type != OptionType::Switch)
706       throw OptName + ": incorrect option type!";
707     O << OptDesc.GenVariableName();
708     return true;
709   } else if (TestName == "input_languages_contain") {
710     O << "InLangs.count(\"" << OptName << "\") != 0";
711     return true;
712   } else if (TestName == "in_language") {
713     // Works only for cmd_line!
714     O << "GetLanguage(inFile) == \"" << OptName << '\"';
715     return true;
716   } else if (TestName == "not_empty") {
717     if (OptName == "o") {
718       O << "!OutputFilename.empty()";
719       return true;
720     }
721     else {
722       const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
723       if (OptDesc.Type == OptionType::Switch)
724         throw OptName + ": incorrect option type!";
725       O << '!' << OptDesc.GenVariableName() << ".empty()";
726       return true;
727     }
728   }
729
730   return false;
731 }
732
733 /// EmitCaseTest2Args - Helper function used by
734 /// EmitCaseConstructHandler.
735 bool EmitCaseTest2Args(const std::string& TestName,
736                        const DagInit& d,
737                        const char* IndentLevel,
738                        const GlobalOptionDescriptions& OptDescs,
739                        std::ostream& O) {
740   checkNumberOfArguments(&d, 2);
741   const std::string& OptName = InitPtrToString(d.getArg(0));
742   const std::string& OptArg = InitPtrToString(d.getArg(1));
743   const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
744
745   if (TestName == "parameter_equals") {
746     if (OptDesc.Type != OptionType::Parameter
747         && OptDesc.Type != OptionType::Prefix)
748       throw OptName + ": incorrect option type!";
749     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
750     return true;
751   }
752   else if (TestName == "element_in_list") {
753     if (OptDesc.Type != OptionType::ParameterList
754         && OptDesc.Type != OptionType::PrefixList)
755       throw OptName + ": incorrect option type!";
756     const std::string& VarName = OptDesc.GenVariableName();
757     O << "std::find(" << VarName << ".begin(),\n"
758       << IndentLevel << Indent1 << VarName << ".end(), \""
759       << OptArg << "\") != " << VarName << ".end()";
760     return true;
761   }
762
763   return false;
764 }
765
766 // Forward declaration.
767 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
768 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
769                   const GlobalOptionDescriptions& OptDescs,
770                   std::ostream& O);
771
772 /// EmitLogicalOperationTest - Helper function used by
773 /// EmitCaseConstructHandler.
774 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
775                               const char* IndentLevel,
776                               const GlobalOptionDescriptions& OptDescs,
777                               std::ostream& O) {
778   O << '(';
779   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
780     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
781     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
782     if (j != NumArgs - 1)
783       O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
784     else
785       O << ')';
786   }
787 }
788
789 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
790 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
791                   const GlobalOptionDescriptions& OptDescs,
792                   std::ostream& O) {
793   const std::string& TestName = d.getOperator()->getAsString();
794
795   if (TestName == "and")
796     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
797   else if (TestName == "or")
798     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
799   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
800     return;
801   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
802     return;
803   else
804     throw TestName + ": unknown edge property!";
805 }
806
807 // Emit code that handles the 'case' construct.
808 // Takes a function object that should emit code for every case clause.
809 // Callback's type is
810 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
811 template <typename F>
812 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
813                               const F& Callback, bool EmitElseIf,
814                               const GlobalOptionDescriptions& OptDescs,
815                               std::ostream& O) {
816   assert(d->getOperator()->getAsString() == "case");
817
818   unsigned numArgs = d->getNumArgs();
819   if (d->getNumArgs() < 2)
820     throw "There should be at least one clause in the 'case' expression:\n"
821       + d->getAsString();
822
823   for (unsigned i = 0; i != numArgs; ++i) {
824     const DagInit& Test = InitPtrToDag(d->getArg(i));
825
826     // Emit the test.
827     if (Test.getOperator()->getAsString() == "default") {
828       if (i+2 != numArgs)
829         throw std::string("The 'default' clause should be the last in the"
830                           "'case' construct!");
831       O << IndentLevel << "else {\n";
832     }
833     else {
834       O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
835       EmitCaseTest(Test, IndentLevel, OptDescs, O);
836       O << ") {\n";
837     }
838
839     // Emit the corresponding statement.
840     ++i;
841     if (i == numArgs)
842       throw "Case construct handler: no corresponding action "
843         "found for the test " + Test.getAsString() + '!';
844
845     Init* arg = d->getArg(i);
846     if (dynamic_cast<DagInit*>(arg)
847         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
848       EmitCaseConstructHandler(static_cast<DagInit*>(arg),
849                                (std::string(IndentLevel) + Indent1).c_str(),
850                                Callback, EmitElseIf, OptDescs, O);
851     }
852     else {
853       Callback(arg, IndentLevel, O);
854     }
855     O << IndentLevel << "}\n";
856   }
857 }
858
859 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
860 /// implement EmitOptionPropertyHandlingCode(). Emits code for
861 /// handling the (forward) option property.
862 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
863                                             std::ostream& O) {
864   switch (D.Type) {
865   case OptionType::Switch:
866     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
867     break;
868   case OptionType::Parameter:
869     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
870     O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
871     break;
872   case OptionType::Prefix:
873     O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
874       << D.GenVariableName() << ");\n";
875     break;
876   case OptionType::PrefixList:
877     O << Indent3 << "for (" << D.GenTypeDeclaration()
878       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
879       << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
880       << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
881       << "*B);\n";
882     break;
883   case OptionType::ParameterList:
884     O << Indent3 << "for (" << D.GenTypeDeclaration()
885       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
886       << Indent3 << "E = " << D.GenVariableName()
887       << ".end() ; B != E; ++B) {\n"
888       << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
889       << Indent4 << "vec.push_back(*B);\n"
890       << Indent3 << "}\n";
891     break;
892   case OptionType::Alias:
893   default:
894     throw std::string("Aliases are not allowed in tool option descriptions!");
895   }
896 }
897
898 // ToolOptionHasInterestingProperties - A helper function used by
899 // EmitOptionPropertyHandlingCode() that tells us whether we should
900 // emit any property handling code at all.
901 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
902   bool ret = false;
903   for (OptionPropertyList::const_iterator B = D.Props.begin(),
904          E = D.Props.end(); B != E; ++B) {
905       const OptionProperty& OptProp = *B;
906       if (OptProp.first == OptionPropertyType::AppendCmd)
907         ret = true;
908     }
909   if (D.isForward() || D.isUnpackValues())
910     ret = true;
911   return ret;
912 }
913
914 /// EmitOptionPropertyHandlingCode - Helper function used by
915 /// EmitGenerateActionMethod(). Emits code that handles option
916 /// properties.
917 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
918                                      std::ostream& O)
919 {
920   if (!ToolOptionHasInterestingProperties(D))
921     return;
922   // Start of the if-clause.
923   O << Indent2 << "if (";
924   if (D.Type == OptionType::Switch)
925     O << D.GenVariableName();
926   else
927     O << '!' << D.GenVariableName() << ".empty()";
928
929   O <<") {\n";
930
931   // Handle option properties that take an argument.
932   for (OptionPropertyList::const_iterator B = D.Props.begin(),
933         E = D.Props.end(); B!=E; ++B) {
934     const OptionProperty& val = *B;
935
936     switch (val.first) {
937       // (append_cmd cmd) property
938     case OptionPropertyType::AppendCmd:
939       O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
940       break;
941       // Other properties with argument
942     default:
943       break;
944     }
945   }
946
947   // Handle flags
948
949   // (forward) property
950   if (D.isForward())
951     EmitForwardOptionPropertyHandlingCode(D, O);
952
953   // (unpack_values) property
954   if (D.isUnpackValues()) {
955     if (IsListOptionType(D.Type)) {
956       O << Indent3 << "for (" << D.GenTypeDeclaration()
957         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
958         << Indent3 << "E = " << D.GenVariableName()
959         << ".end(); B != E; ++B)\n"
960         << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
961     }
962     else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
963       O << Indent3 << "llvm::SplitString("
964         << D.GenVariableName() << ", vec, \",\");\n";
965     }
966     else {
967       throw std::string("Switches can't have unpack_values property!");
968     }
969   }
970
971   // End of the if-clause.
972   O << Indent2 << "}\n";
973 }
974
975 /// SubstituteSpecialCommands - Perform string substitution for $CALL
976 /// and $ENV. Helper function used by EmitCmdLineVecFill().
977 std::string SubstituteSpecialCommands(const std::string& cmd) {
978   size_t cparen = cmd.find(")");
979   std::string ret;
980
981   if (cmd.find("$CALL(") == 0) {
982     if (cmd.size() == 6)
983       throw std::string("$CALL invocation: empty argument list!");
984
985     ret += "hooks::";
986     ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
987     ret += "()";
988   }
989   else if (cmd.find("$ENV(") == 0) {
990     if (cmd.size() == 5)
991       throw std::string("$ENV invocation: empty argument list!");
992
993     ret += "std::getenv(\"";
994     ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
995     ret += "\")";
996   }
997   else {
998     throw "Unknown special command: " + cmd;
999   }
1000
1001   if (cmd.begin() + cparen + 1 != cmd.end()) {
1002     ret += " + std::string(\"";
1003     ret += (cmd.c_str() + cparen + 1);
1004     ret += "\")";
1005   }
1006
1007   return ret;
1008 }
1009
1010 /// EmitCmdLineVecFill - Emit code that fills in the command line
1011 /// vector. Helper function used by EmitGenerateActionMethod().
1012 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1013                         bool Version, const char* IndentLevel,
1014                         std::ostream& O) {
1015   StrVector StrVec;
1016   SplitString(InitPtrToString(CmdLine), StrVec);
1017   if (StrVec.empty())
1018     throw "Tool " + ToolName + " has empty command line!";
1019
1020   StrVector::const_iterator I = StrVec.begin();
1021   ++I;
1022   for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1023     const std::string& cmd = *I;
1024     O << IndentLevel;
1025     if (cmd.at(0) == '$') {
1026       if (cmd == "$INFILE") {
1027         if (Version)
1028           O << "for (PathVector::const_iterator B = inFiles.begin()"
1029             << ", E = inFiles.end();\n"
1030             << IndentLevel << "B != E; ++B)\n"
1031             << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1032         else
1033           O << "vec.push_back(inFile.toString());\n";
1034       }
1035       else if (cmd == "$OUTFILE") {
1036         O << "vec.push_back(outFile.toString());\n";
1037       }
1038       else {
1039         O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1040         O << ");\n";
1041       }
1042     }
1043     else {
1044       O << "vec.push_back(\"" << cmd << "\");\n";
1045     }
1046   }
1047   O << IndentLevel << "cmd = "
1048     << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1049         : "\"" + StrVec[0] + "\"")
1050     << ";\n";
1051 }
1052
1053 /// EmitCmdLineVecFillCallback - A function object wrapper around
1054 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1055 /// argument to EmitCaseConstructHandler().
1056 class EmitCmdLineVecFillCallback {
1057   bool Version;
1058   const std::string& ToolName;
1059  public:
1060   EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1061     : Version(Ver), ToolName(TN) {}
1062
1063   void operator()(const Init* Statement, const char* IndentLevel,
1064                   std::ostream& O) const
1065   {
1066     EmitCmdLineVecFill(Statement, ToolName, Version,
1067                        (std::string(IndentLevel) + Indent1).c_str(), O);
1068   }
1069 };
1070
1071 // EmitGenerateActionMethod - Emit one of two versions of the
1072 // Tool::GenerateAction() method.
1073 void EmitGenerateActionMethod (const ToolProperties& P,
1074                                const GlobalOptionDescriptions& OptDescs,
1075                                bool Version, std::ostream& O) {
1076   if (Version)
1077     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1078   else
1079     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1080
1081   O << Indent2 << "const sys::Path& outFile,\n"
1082     << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1083     << Indent1 << "{\n"
1084     << Indent2 << "const char* cmd;\n"
1085     << Indent2 << "std::vector<std::string> vec;\n";
1086
1087   // cmd_line is either a string or a 'case' construct.
1088   if (typeid(*P.CmdLine) == typeid(StringInit))
1089     EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1090   else
1091     EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1092                              EmitCmdLineVecFillCallback(Version, P.Name),
1093                              true, OptDescs, O);
1094
1095   // For every understood option, emit handling code.
1096   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1097         E = P.OptDescs.end(); B != E; ++B) {
1098     const ToolOptionDescription& val = B->second;
1099     EmitOptionPropertyHandlingCode(val, O);
1100   }
1101
1102   // Handle the Sink property.
1103   if (P.isSink()) {
1104     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1105       << Indent3 << "vec.insert(vec.end(), "
1106       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1107       << Indent2 << "}\n";
1108   }
1109
1110   O << Indent2 << "return Action(cmd, vec);\n"
1111     << Indent1 << "}\n\n";
1112 }
1113
1114 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1115 /// a given Tool class.
1116 void EmitGenerateActionMethods (const ToolProperties& P,
1117                                 const GlobalOptionDescriptions& OptDescs,
1118                                 std::ostream& O) {
1119   if (!P.isJoin())
1120     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1121       << Indent2 << "const llvm::sys::Path& outFile,\n"
1122       << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1123       << Indent1 << "{\n"
1124       << Indent2 << "throw std::runtime_error(\"" << P.Name
1125       << " is not a Join tool!\");\n"
1126       << Indent1 << "}\n\n";
1127   else
1128     EmitGenerateActionMethod(P, OptDescs, true, O);
1129
1130   EmitGenerateActionMethod(P, OptDescs, false, O);
1131 }
1132
1133 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1134 /// class.
1135 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1136   O << Indent1 << "bool IsLast() const {\n"
1137     << Indent2 << "bool last = false;\n";
1138
1139   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1140         E = P.OptDescs.end(); B != E; ++B) {
1141     const ToolOptionDescription& val = B->second;
1142
1143     if (val.isStopCompilation())
1144       O << Indent2
1145         << "if (" << val.GenVariableName()
1146         << ")\n" << Indent3 << "last = true;\n";
1147   }
1148
1149   O << Indent2 << "return last;\n"
1150     << Indent1 <<  "}\n\n";
1151 }
1152
1153 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1154 /// methods for a given Tool class.
1155 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1156   O << Indent1 << "const char** InputLanguages() const {\n"
1157     << Indent2 << "return InputLanguages_;\n"
1158     << Indent1 << "}\n\n";
1159
1160   O << Indent1 << "const char* OutputLanguage() const {\n"
1161     << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1162     << Indent1 << "}\n\n";
1163 }
1164
1165 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1166 /// given Tool class.
1167 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1168   O << Indent1 << "const char* OutputSuffix() const {\n"
1169     << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1170
1171   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1172          E = P.OptDescs.end(); B != E; ++B) {
1173     const ToolOptionDescription& OptDesc = B->second;
1174     for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1175            E = OptDesc.Props.end(); B != E; ++B) {
1176       const OptionProperty& OptProp = *B;
1177       if (OptProp.first == OptionPropertyType::OutputSuffix) {
1178         O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1179           << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1180       }
1181     }
1182   }
1183
1184   O << Indent2 << "return ret;\n"
1185     << Indent1 << "}\n\n";
1186 }
1187
1188 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1189 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1190   O << Indent1 << "const char* Name() const {\n"
1191     << Indent2 << "return \"" << P.Name << "\";\n"
1192     << Indent1 << "}\n\n";
1193 }
1194
1195 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1196 /// class.
1197 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1198   O << Indent1 << "bool IsJoin() const {\n";
1199   if (P.isJoin())
1200     O << Indent2 << "return true;\n";
1201   else
1202     O << Indent2 << "return false;\n";
1203   O << Indent1 << "}\n\n";
1204 }
1205
1206 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1207 /// given Tool class.
1208 void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1209   O << "const char* " << P.Name << "::InputLanguages_[] = {";
1210   for (StrVector::const_iterator B = P.InLanguage.begin(),
1211          E = P.InLanguage.end(); B != E; ++B)
1212     O << '\"' << *B << "\", ";
1213   O << "0};\n\n";
1214 }
1215
1216 /// EmitToolClassDefinition - Emit a Tool class definition.
1217 void EmitToolClassDefinition (const ToolProperties& P,
1218                               const GlobalOptionDescriptions& OptDescs,
1219                               std::ostream& O) {
1220   if (P.Name == "root")
1221     return;
1222
1223   // Header
1224   O << "class " << P.Name << " : public ";
1225   if (P.isJoin())
1226     O << "JoinTool";
1227   else
1228     O << "Tool";
1229
1230   O << "{\nprivate:\n"
1231     << Indent1 << "static const char* InputLanguages_[];\n\n";
1232
1233   O << "public:\n";
1234   EmitNameMethod(P, O);
1235   EmitInOutLanguageMethods(P, O);
1236   EmitOutputSuffixMethod(P, O);
1237   EmitIsJoinMethod(P, O);
1238   EmitGenerateActionMethods(P, OptDescs, O);
1239   EmitIsLastMethod(P, O);
1240
1241   // Close class definition
1242   O << "};\n";
1243
1244   EmitStaticMemberDefinitions(P, O);
1245
1246 }
1247
1248 /// EmitOptionDescriptions - Iterate over a list of option
1249 /// descriptions and emit registration code.
1250 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1251                              std::ostream& O)
1252 {
1253   std::vector<GlobalOptionDescription> Aliases;
1254
1255   // Emit static cl::Option variables.
1256   for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1257          E = descs.end(); B!=E; ++B) {
1258     const GlobalOptionDescription& val = B->second;
1259
1260     if (val.Type == OptionType::Alias) {
1261       Aliases.push_back(val);
1262       continue;
1263     }
1264
1265     O << val.GenTypeDeclaration() << ' '
1266       << val.GenVariableName()
1267       << "(\"" << val.Name << '\"';
1268
1269     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1270       O << ", cl::Prefix";
1271
1272     if (val.isRequired()) {
1273       switch (val.Type) {
1274       case OptionType::PrefixList:
1275       case OptionType::ParameterList:
1276         O << ", cl::OneOrMore";
1277         break;
1278       default:
1279         O << ", cl::Required";
1280       }
1281     }
1282
1283     if (!val.Help.empty())
1284       O << ", cl::desc(\"" << val.Help << "\")";
1285
1286     O << ");\n";
1287   }
1288
1289   // Emit the aliases (they should go after all the 'proper' options).
1290   for (std::vector<GlobalOptionDescription>::const_iterator
1291          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1292     const GlobalOptionDescription& val = *B;
1293
1294     O << val.GenTypeDeclaration() << ' '
1295       << val.GenVariableName()
1296       << "(\"" << val.Name << '\"';
1297
1298     GlobalOptionDescriptions::container_type
1299       ::const_iterator F = descs.Descriptions.find(val.Help);
1300     if (F != descs.Descriptions.end())
1301       O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1302     else
1303       throw val.Name + ": alias to an unknown option!";
1304
1305     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
1306   }
1307
1308   // Emit the sink option.
1309   if (descs.HasSink)
1310     O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1311
1312   O << '\n';
1313 }
1314
1315 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1316 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1317 {
1318   // Get the relevant field out of RecordKeeper
1319   Record* LangMapRecord = Records.getDef("LanguageMap");
1320   if (!LangMapRecord)
1321     throw std::string("Language map definition not found!");
1322
1323   ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1324   if (!LangsToSuffixesList)
1325     throw std::string("Error in the language map definition!");
1326
1327   // Generate code
1328   O << "void llvmc::PopulateLanguageMap() {\n";
1329
1330   for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1331     Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1332
1333     const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1334     const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1335
1336     for (unsigned i = 0; i < Suffixes->size(); ++i)
1337       O << Indent1 << "GlobalLanguageMap[\""
1338         << InitPtrToString(Suffixes->getElement(i))
1339         << "\"] = \"" << Lang << "\";\n";
1340   }
1341
1342   O << "}\n\n";
1343 }
1344
1345 /// FillInToolToLang - Fills in two tables that map tool names to
1346 /// (input, output) languages.  Used by the typechecker.
1347 void FillInToolToLang (const ToolPropertiesList& TPList,
1348                        StringMap<StringSet<> >& ToolToInLang,
1349                        StringMap<std::string>& ToolToOutLang) {
1350   for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1351        B != E; ++B) {
1352     const ToolProperties& P = *(*B);
1353     for (StrVector::const_iterator B = P.InLanguage.begin(),
1354            E = P.InLanguage.end(); B != E; ++B)
1355       ToolToInLang[P.Name].insert(*B);
1356     ToolToOutLang[P.Name] = P.OutLanguage;
1357   }
1358 }
1359
1360 /// TypecheckGraph - Check that names for output and input languages
1361 /// on all edges do match.
1362 // TOFIX: It would be nice if this function also checked for cycles
1363 // and multiple default edges in the graph (better error
1364 // reporting). Unfortunately, it is awkward to do right now because
1365 // our intermediate representation is not sufficiently
1366 // sofisticated. Algorithms like these should be run on a real graph
1367 // instead of AST.
1368 void TypecheckGraph (Record* CompilationGraph,
1369                      const ToolPropertiesList& TPList) {
1370   StringMap<StringSet<> > ToolToInLang;
1371   StringMap<std::string> ToolToOutLang;
1372
1373   FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1374   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1375   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1376   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1377
1378   for (unsigned i = 0; i < edges->size(); ++i) {
1379     Record* Edge = edges->getElementAsRecord(i);
1380     Record* A = Edge->getValueAsDef("a");
1381     Record* B = Edge->getValueAsDef("b");
1382     StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1383     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1384     if (IA == IAE)
1385       throw A->getName() + ": no such tool!";
1386     if (IB == IBE)
1387       throw B->getName() + ": no such tool!";
1388     if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1389       throw "Edge " + A->getName() + "->" + B->getName()
1390         + ": output->input language mismatch";
1391     if (B->getName() == "root")
1392       throw std::string("Edges back to the root are not allowed!");
1393   }
1394 }
1395
1396 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1397 /// by EmitEdgeClass().
1398 void IncDecWeight (const Init* i, const char* IndentLevel,
1399                    std::ostream& O) {
1400   const DagInit& d = InitPtrToDag(i);
1401   const std::string& OpName = d.getOperator()->getAsString();
1402
1403   if (OpName == "inc_weight")
1404     O << IndentLevel << Indent1 << "ret += ";
1405   else if (OpName == "dec_weight")
1406     O << IndentLevel << Indent1 << "ret -= ";
1407   else
1408     throw "Unknown operator in edge properties list: " + OpName + '!';
1409
1410   if (d.getNumArgs() > 0)
1411     O << InitPtrToInt(d.getArg(0)) << ";\n";
1412   else
1413     O << "2;\n";
1414
1415 }
1416
1417 /// EmitEdgeClass - Emit a single Edge# class.
1418 void EmitEdgeClass (unsigned N, const std::string& Target,
1419                     DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1420                     std::ostream& O) {
1421
1422   // Class constructor.
1423   O << "class Edge" << N << ": public Edge {\n"
1424     << "public:\n"
1425     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1426     << "\") {}\n\n"
1427
1428   // Function Weight().
1429     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1430     << Indent2 << "unsigned ret = 0;\n";
1431
1432   // Handle the 'case' construct.
1433   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1434
1435   O << Indent2 << "return ret;\n"
1436     << Indent1 << "};\n\n};\n\n";
1437 }
1438
1439 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1440 void EmitEdgeClasses (Record* CompilationGraph,
1441                       const GlobalOptionDescriptions& OptDescs,
1442                       std::ostream& O) {
1443   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1444
1445   for (unsigned i = 0; i < edges->size(); ++i) {
1446     Record* Edge = edges->getElementAsRecord(i);
1447     Record* B = Edge->getValueAsDef("b");
1448     DagInit* Weight = Edge->getValueAsDag("weight");
1449
1450     if (isDagEmpty(Weight))
1451       continue;
1452
1453     EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1454   }
1455 }
1456
1457 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1458 /// function.
1459 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1460                                    std::ostream& O)
1461 {
1462   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1463
1464   // Generate code
1465   O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1466     << Indent1 << "PopulateLanguageMap();\n\n";
1467
1468   // Insert vertices
1469
1470   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1471   if (Tools.empty())
1472     throw std::string("No tool definitions found!");
1473
1474   for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1475     const std::string& Name = (*B)->getName();
1476     if (Name != "root")
1477       O << Indent1 << "G.insertNode(new "
1478         << Name << "());\n";
1479   }
1480
1481   O << '\n';
1482
1483   // Insert edges
1484   for (unsigned i = 0; i < edges->size(); ++i) {
1485     Record* Edge = edges->getElementAsRecord(i);
1486     Record* A = Edge->getValueAsDef("a");
1487     Record* B = Edge->getValueAsDef("b");
1488     DagInit* Weight = Edge->getValueAsDag("weight");
1489
1490     O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1491
1492     if (isDagEmpty(Weight))
1493       O << "new SimpleEdge(\"" << B->getName() << "\")";
1494     else
1495       O << "new Edge" << i << "()";
1496
1497     O << ");\n";
1498   }
1499
1500   O << "}\n\n";
1501 }
1502
1503 /// ExtractHookNames - Extract the hook names from all instances of
1504 /// $CALL(HookName) in the provided command line string. Helper
1505 /// function used by FillInHookNames().
1506 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1507   StrVector cmds;
1508   llvm::SplitString(InitPtrToString(CmdLine), cmds);
1509   for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1510        B != E; ++B) {
1511     const std::string& cmd = *B;
1512     if (cmd.find("$CALL(") == 0) {
1513       if (cmd.size() == 6)
1514         throw std::string("$CALL invocation: empty argument list!");
1515       HookNames.push_back(std::string(cmd.begin() + 6,
1516                                       cmd.begin() + cmd.find(")")));
1517     }
1518   }
1519 }
1520
1521 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1522 /// 'case' expression, handle nesting. Helper function used by
1523 /// FillInHookNames().
1524 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1525   const DagInit& d = InitPtrToDag(Case);
1526   bool even = false;
1527   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1528        B != E; ++B) {
1529     Init* arg = *B;
1530     if (even && dynamic_cast<DagInit*>(arg)
1531         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1532       ExtractHookNamesFromCaseConstruct(arg, HookNames);
1533     else if (even)
1534       ExtractHookNames(arg, HookNames);
1535     even = !even;
1536   }
1537 }
1538
1539 /// FillInHookNames - Actually extract the hook names from all command
1540 /// line strings. Helper function used by EmitHookDeclarations().
1541 void FillInHookNames(const ToolPropertiesList& TPList,
1542                      StrVector& HookNames) {
1543   // For all command lines:
1544   for (ToolPropertiesList::const_iterator B = TPList.begin(),
1545          E = TPList.end(); B != E; ++B) {
1546     const ToolProperties& P = *(*B);
1547     if (!P.CmdLine)
1548       continue;
1549     if (dynamic_cast<StringInit*>(P.CmdLine))
1550       // This is a string.
1551       ExtractHookNames(P.CmdLine, HookNames);
1552     else
1553       // This is a 'case' construct.
1554       ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1555   }
1556 }
1557
1558 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1559 /// property records and emit hook function declaration for each
1560 /// instance of $CALL(HookName).
1561 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1562                           std::ostream& O) {
1563   StrVector HookNames;
1564   FillInHookNames(ToolProps, HookNames);
1565   if (HookNames.empty())
1566     return;
1567   std::sort(HookNames.begin(), HookNames.end());
1568   StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1569
1570   O << "namespace hooks {\n";
1571   for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1572     O << Indent1 << "std::string " << *B << "();\n";
1573
1574   O << "}\n\n";
1575 }
1576
1577 // End of anonymous namespace
1578 }
1579
1580 /// run - The back-end entry point.
1581 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1582   try {
1583
1584   // Emit file header.
1585   EmitSourceFileHeader("LLVMC Configuration Library", O);
1586
1587   // Get a list of all defined Tools.
1588   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1589   if (Tools.empty())
1590     throw std::string("No tool definitions found!");
1591
1592   // Gather information from the Tool description dags.
1593   ToolPropertiesList tool_props;
1594   GlobalOptionDescriptions opt_descs;
1595   CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1596
1597   RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1598   CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1599                                   opt_descs);
1600
1601   // Emit global option registration code.
1602   EmitOptionDescriptions(opt_descs, O);
1603
1604   // Emit hook declarations.
1605   EmitHookDeclarations(tool_props, O);
1606
1607   // Emit PopulateLanguageMap() function
1608   // (a language map maps from file extensions to language names).
1609   EmitPopulateLanguageMap(Records, O);
1610
1611   // Emit Tool classes.
1612   for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1613          E = tool_props.end(); B!=E; ++B)
1614     EmitToolClassDefinition(*(*B), opt_descs, O);
1615
1616   Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1617   if (!CompilationGraphRecord)
1618     throw std::string("Compilation graph description not found!");
1619
1620   // Typecheck the compilation graph.
1621   TypecheckGraph(CompilationGraphRecord, tool_props);
1622
1623   // Emit Edge# classes.
1624   EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1625
1626   // Emit PopulateCompilationGraph() function.
1627   EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1628
1629   // EOF
1630   } catch (std::exception& Error) {
1631     throw Error.what() + std::string(" - usually this means a syntax error.");
1632   }
1633 }