Make structs and arrays first-class types, and add assembly
[oota-llvm.git] / utils / TableGen / LLVMCConfigurationEmitter.cpp
1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config --------------===//
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/Support/Streams.h"
22
23 #include <algorithm>
24 #include <cassert>
25 #include <functional>
26 #include <string>
27
28 using namespace llvm;
29
30 namespace {
31
32 //===----------------------------------------------------------------------===//
33 /// Typedefs
34
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
37
38 //===----------------------------------------------------------------------===//
39 /// Constants
40
41 // Indentation strings.
42 const char * Indent1 = "    ";
43 const char * Indent2 = "        ";
44 const char * Indent3 = "            ";
45 const char * Indent4 = "                ";
46
47 // Default help string.
48 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
49
50 // Name for the "sink" option.
51 const char * SinkOptionName = "AutoGeneratedSinkOption";
52
53 //===----------------------------------------------------------------------===//
54 /// Helper functions
55
56 std::string InitPtrToString(Init* ptr) {
57   StringInit& val = dynamic_cast<StringInit&>(*ptr);
58   return val.getValue();
59 }
60
61 int InitPtrToInt(Init* ptr) {
62   IntInit& val = dynamic_cast<IntInit&>(*ptr);
63   return val.getValue();
64 }
65
66 const DagInit& InitPtrToDagInitRef(Init* ptr) {
67   DagInit& val = dynamic_cast<DagInit&>(*ptr);
68   return val;
69 }
70
71
72 // checkNumberOfArguments - Ensure that the number of args in d is
73 // less than or equal to min_arguments, otherwise throw an exception .
74 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
75   if (d->getNumArgs() < min_arguments)
76     throw "Property " + d->getOperator()->getAsString()
77       + " has too few arguments!";
78 }
79
80
81 //===----------------------------------------------------------------------===//
82 /// Back-end specific code
83
84 // A command-line option can have one of the following types:
85 //
86 // Switch - a simple switch w/o arguments, e.g. -O2
87 //
88 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
89 // --output=file
90 //
91 // ParameterList - same as Parameter, but more than one occurence
92 // of the option is allowed, e.g. -lm -lpthread
93 //
94 // Prefix - argument is everything after the prefix,
95 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
96 //
97 // PrefixList - same as Prefix, but more than one option occurence is
98 // allowed
99
100 namespace OptionType {
101   enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
102 }
103
104 bool IsListOptionType (OptionType::OptionType t) {
105   return (t == OptionType::ParameterList || t == OptionType::PrefixList);
106 }
107
108 // Code duplication here is necessary because one option can affect
109 // several tools and those tools may have different actions associated
110 // with this option. GlobalOptionDescriptions are used to generate
111 // the option registration code, while ToolOptionDescriptions are used
112 // to generate tool-specific code.
113
114 /// OptionDescription - Base class for option descriptions.
115 struct OptionDescription {
116   OptionType::OptionType Type;
117   std::string Name;
118
119   OptionDescription(OptionType::OptionType t = OptionType::Switch,
120                     const std::string& n = "")
121   : Type(t), Name(n)
122   {}
123
124   const char* GenTypeDeclaration() const {
125     switch (Type) {
126     case OptionType::PrefixList:
127     case OptionType::ParameterList:
128       return "cl::list<std::string>";
129     case OptionType::Switch:
130       return "cl::opt<bool>";
131     case OptionType::Parameter:
132     case OptionType::Prefix:
133     default:
134       return "cl::opt<std::string>";
135     }
136   }
137
138   // Escape commas and other symbols not allowed in the C++ variable
139   // names. Makes it possible to use options with names like "Wa,"
140   // (useful for prefix options).
141   std::string EscapeVariableName(const std::string& Var) const {
142     std::string ret;
143     for (unsigned i = 0; i != Var.size(); ++i) {
144       if (Var[i] == ',') {
145         ret += "_comma_";
146       }
147       else {
148         ret.push_back(Var[i]);
149       }
150     }
151     return ret;
152   }
153
154   std::string GenVariableName() const {
155     const std::string& EscapedName = EscapeVariableName(Name);
156     switch (Type) {
157     case OptionType::Switch:
158      return "AutoGeneratedSwitch" + EscapedName;
159    case OptionType::Prefix:
160      return "AutoGeneratedPrefix" + EscapedName;
161    case OptionType::PrefixList:
162      return "AutoGeneratedPrefixList" + EscapedName;
163    case OptionType::Parameter:
164      return "AutoGeneratedParameter" + EscapedName;
165    case OptionType::ParameterList:
166    default:
167      return "AutoGeneratedParameterList" + EscapedName;
168    }
169   }
170
171 };
172
173 // Global option description.
174
175 namespace GlobalOptionDescriptionFlags {
176   enum GlobalOptionDescriptionFlags { Required = 0x1 };
177 }
178
179 struct GlobalOptionDescription : public OptionDescription {
180   std::string Help;
181   unsigned Flags;
182
183   // We need to provide a default constructor because
184   // StringMap can only store DefaultConstructible objects.
185   GlobalOptionDescription() : OptionDescription(), Flags(0)
186   {}
187
188   GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
189     : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
190   {}
191
192   bool isRequired() const {
193     return Flags & GlobalOptionDescriptionFlags::Required;
194   }
195   void setRequired() {
196     Flags |= GlobalOptionDescriptionFlags::Required;
197   }
198
199   /// Merge - Merge two option descriptions.
200   void Merge (const GlobalOptionDescription& other)
201   {
202     if (other.Type != Type)
203       throw "Conflicting definitions for the option " + Name + "!";
204
205     if (Help == DefaultHelpString)
206       Help = other.Help;
207     else if (other.Help != DefaultHelpString) {
208       llvm::cerr << "Warning: more than one help string defined for option "
209         + Name + "\n";
210     }
211
212     Flags |= other.Flags;
213   }
214 };
215
216 /// GlobalOptionDescriptions - A GlobalOptionDescription array
217 /// together with some flags affecting generation of option
218 /// declarations.
219 struct GlobalOptionDescriptions {
220   typedef StringMap<GlobalOptionDescription> container_type;
221   typedef container_type::const_iterator const_iterator;
222
223   /// Descriptions - A list of GlobalOptionDescriptions.
224   container_type Descriptions;
225   /// HasSink - Should the emitter generate a "cl::sink" option?
226   bool HasSink;
227
228   const GlobalOptionDescription& FindOption(const std::string& OptName) const {
229     const_iterator I = Descriptions.find(OptName);
230     if (I != Descriptions.end())
231       return I->second;
232     else
233       throw OptName + ": no such option!";
234   }
235
236   // Support for STL-style iteration
237   const_iterator begin() const { return Descriptions.begin(); }
238   const_iterator end() const { return Descriptions.end(); }
239 };
240
241
242 // Tool-local option description.
243
244 // Properties without arguments are implemented as flags.
245 namespace ToolOptionDescriptionFlags {
246   enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
247                                     Forward = 0x2, UnpackValues = 0x4};
248 }
249 namespace OptionPropertyType {
250   enum OptionPropertyType { AppendCmd };
251 }
252
253 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
254 OptionProperty;
255 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
256
257 struct ToolOptionDescription : public OptionDescription {
258   unsigned Flags;
259   OptionPropertyList Props;
260
261   // StringMap can only store DefaultConstructible objects
262   ToolOptionDescription() : OptionDescription(), Flags(0) {}
263
264   ToolOptionDescription (OptionType::OptionType t, const std::string& n)
265     : OptionDescription(t, n)
266   {}
267
268   // Various boolean properties
269   bool isStopCompilation() const {
270     return Flags & ToolOptionDescriptionFlags::StopCompilation;
271   }
272   void setStopCompilation() {
273     Flags |= ToolOptionDescriptionFlags::StopCompilation;
274   }
275
276   bool isForward() const {
277     return Flags & ToolOptionDescriptionFlags::Forward;
278   }
279   void setForward() {
280     Flags |= ToolOptionDescriptionFlags::Forward;
281   }
282
283   bool isUnpackValues() const {
284     return Flags & ToolOptionDescriptionFlags::UnpackValues;
285   }
286   void setUnpackValues() {
287     Flags |= ToolOptionDescriptionFlags::UnpackValues;
288   }
289
290   void AddProperty (OptionPropertyType::OptionPropertyType t,
291                     const std::string& val)
292   {
293     Props.push_back(std::make_pair(t, val));
294   }
295 };
296
297 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
298
299 // Tool information record
300
301 namespace ToolFlags {
302   enum ToolFlags { Join = 0x1, Sink = 0x2 };
303 }
304
305 struct ToolProperties : public RefCountedBase<ToolProperties> {
306   std::string Name;
307   StrVector CmdLine;
308   std::string InLanguage;
309   std::string OutLanguage;
310   std::string OutputSuffix;
311   unsigned Flags;
312   ToolOptionDescriptions OptDescs;
313
314   // Various boolean properties
315   void setSink()      { Flags |= ToolFlags::Sink; }
316   bool isSink() const { return Flags & ToolFlags::Sink; }
317   void setJoin()      { Flags |= ToolFlags::Join; }
318   bool isJoin() const { return Flags & ToolFlags::Join; }
319
320   // Default ctor here is needed because StringMap can only store
321   // DefaultConstructible objects
322   ToolProperties() : Flags(0) {}
323   ToolProperties (const std::string& n) : Name(n), Flags(0) {}
324 };
325
326
327 /// ToolPropertiesList - A list of Tool information records
328 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
329 /// constructor (and we want to avoid copying ToolProperties anyway).
330 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
331
332
333 /// CollectProperties - Function object for iterating over a list of
334 /// tool property records.
335 class CollectProperties {
336 private:
337
338   /// Implementation details
339
340   /// PropertyHandler - a function that extracts information
341   /// about a given tool property from its DAG representation
342   typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
343
344   /// PropertyHandlerMap - A map from property names to property
345   /// handlers.
346   typedef StringMap<PropertyHandler> PropertyHandlerMap;
347
348   /// OptionPropertyHandler - a function that extracts information
349   /// about a given option property from its DAG representation.
350   typedef void (CollectProperties::* OptionPropertyHandler)
351   (const DagInit*, GlobalOptionDescription &);
352
353   /// OptionPropertyHandlerMap - A map from option property names to
354   /// option property handlers
355   typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
356
357   // Static maps from strings to CollectProperties methods("handlers")
358   static PropertyHandlerMap propertyHandlers_;
359   static OptionPropertyHandlerMap optionPropertyHandlers_;
360   static bool staticMembersInitialized_;
361
362
363   /// This is where the information is stored
364
365   /// toolProps_ -  Properties of the current Tool.
366   ToolProperties& toolProps_;
367   /// optDescs_ - OptionDescriptions table (used to register options
368   /// globally).
369   GlobalOptionDescriptions& optDescs_;
370
371 public:
372
373   explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
374     : toolProps_(p), optDescs_(d)
375   {
376     if (!staticMembersInitialized_) {
377       // Init tool property handlers
378       propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
379       propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
380       propertyHandlers_["join"] = &CollectProperties::onJoin;
381       propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
382       propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
383       propertyHandlers_["parameter_option"]
384         = &CollectProperties::onParameter;
385       propertyHandlers_["parameter_list_option"] =
386         &CollectProperties::onParameterList;
387       propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
388       propertyHandlers_["prefix_list_option"] =
389         &CollectProperties::onPrefixList;
390       propertyHandlers_["sink"] = &CollectProperties::onSink;
391       propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
392
393       // Init option property handlers
394       optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
395       optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
396       optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
397       optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
398       optionPropertyHandlers_["stop_compilation"] =
399         &CollectProperties::onStopCompilation;
400       optionPropertyHandlers_["unpack_values"] =
401         &CollectProperties::onUnpackValues;
402
403       staticMembersInitialized_ = true;
404     }
405   }
406
407   /// operator() - Gets called for every tool property; Just forwards
408   /// to the corresponding property handler.
409   void operator() (Init* i) {
410     const DagInit& d = InitPtrToDagInitRef(i);
411     const std::string& property_name = d.getOperator()->getAsString();
412     PropertyHandlerMap::iterator method
413       = propertyHandlers_.find(property_name);
414
415     if (method != propertyHandlers_.end()) {
416       PropertyHandler h = method->second;
417       (this->*h)(&d);
418     }
419     else {
420       throw "Unknown tool property: " + property_name + "!";
421     }
422   }
423
424 private:
425
426   /// Property handlers --
427   /// Functions that extract information about tool properties from
428   /// DAG representation.
429
430   void onCmdLine (const DagInit* d) {
431     checkNumberOfArguments(d, 1);
432     SplitString(InitPtrToString(d->getArg(0)), toolProps_.CmdLine);
433     if (toolProps_.CmdLine.empty())
434       throw "Tool " + toolProps_.Name + " has empty command line!";
435   }
436
437   void onInLanguage (const DagInit* d) {
438     checkNumberOfArguments(d, 1);
439     toolProps_.InLanguage = InitPtrToString(d->getArg(0));
440   }
441
442   void onJoin (const DagInit* d) {
443     checkNumberOfArguments(d, 0);
444     toolProps_.setJoin();
445   }
446
447   void onOutLanguage (const DagInit* d) {
448     checkNumberOfArguments(d, 1);
449     toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
450   }
451
452   void onOutputSuffix (const DagInit* d) {
453     checkNumberOfArguments(d, 1);
454     toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
455   }
456
457   void onSink (const DagInit* d) {
458     checkNumberOfArguments(d, 0);
459     optDescs_.HasSink = true;
460     toolProps_.setSink();
461   }
462
463   void onSwitch (const DagInit* d) {
464     addOption(d, OptionType::Switch);
465   }
466
467   void onParameter (const DagInit* d) {
468     addOption(d, OptionType::Parameter);
469   }
470
471   void onParameterList (const DagInit* d) {
472     addOption(d, OptionType::ParameterList);
473   }
474
475   void onPrefix (const DagInit* d) {
476     addOption(d, OptionType::Prefix);
477   }
478
479   void onPrefixList (const DagInit* d) {
480     addOption(d, OptionType::PrefixList);
481   }
482
483   /// Option property handlers --
484   /// Methods that handle properties that are common for all types of
485   /// options (like append_cmd, stop_compilation)
486
487   void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
488     checkNumberOfArguments(d, 1);
489     std::string const& cmd = InitPtrToString(d->getArg(0));
490
491     toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
492   }
493
494   void onForward (const DagInit* d, GlobalOptionDescription& o) {
495     checkNumberOfArguments(d, 0);
496     toolProps_.OptDescs[o.Name].setForward();
497   }
498
499   void onHelp (const DagInit* d, GlobalOptionDescription& o) {
500     checkNumberOfArguments(d, 1);
501     const std::string& help_message = InitPtrToString(d->getArg(0));
502
503     o.Help = help_message;
504   }
505
506   void onRequired (const DagInit* d, GlobalOptionDescription& o) {
507     checkNumberOfArguments(d, 0);
508     o.setRequired();
509   }
510
511   void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
512     checkNumberOfArguments(d, 0);
513     if (o.Type != OptionType::Switch)
514       throw std::string("Only options of type Switch can stop compilation!");
515     toolProps_.OptDescs[o.Name].setStopCompilation();
516   }
517
518   void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
519     checkNumberOfArguments(d, 0);
520     toolProps_.OptDescs[o.Name].setUnpackValues();
521   }
522
523   /// Helper functions
524
525   // Add an option of type t
526   void addOption (const DagInit* d, OptionType::OptionType t) {
527     checkNumberOfArguments(d, 2);
528     const std::string& name = InitPtrToString(d->getArg(0));
529
530     GlobalOptionDescription o(t, name);
531     toolProps_.OptDescs[name].Type = t;
532     toolProps_.OptDescs[name].Name = name;
533     processOptionProperties(d, o);
534     insertDescription(o);
535   }
536
537   // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
538   void insertDescription (const GlobalOptionDescription& o)
539   {
540     if (optDescs_.Descriptions.count(o.Name)) {
541       GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
542       D.Merge(o);
543     }
544     else {
545       optDescs_.Descriptions[o.Name] = o;
546     }
547   }
548
549   /// processOptionProperties - Go through the list of option
550   /// properties and call a corresponding handler for each.
551   ///
552   /// Parameters:
553   /// name - option name
554   /// d - option property list
555   void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
556     // First argument is option name
557     checkNumberOfArguments(d, 2);
558
559     for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
560       const DagInit& option_property
561         = InitPtrToDagInitRef(d->getArg(B));
562       const std::string& option_property_name
563         = option_property.getOperator()->getAsString();
564       OptionPropertyHandlerMap::iterator method
565         = optionPropertyHandlers_.find(option_property_name);
566
567       if (method != optionPropertyHandlers_.end()) {
568         OptionPropertyHandler h = method->second;
569         (this->*h)(&option_property, o);
570       }
571       else {
572         throw "Unknown option property: " + option_property_name + "!";
573       }
574     }
575   }
576 };
577
578 // Static members of CollectProperties
579 CollectProperties::PropertyHandlerMap
580 CollectProperties::propertyHandlers_;
581
582 CollectProperties::OptionPropertyHandlerMap
583 CollectProperties::optionPropertyHandlers_;
584
585 bool CollectProperties::staticMembersInitialized_ = false;
586
587
588 /// CollectToolProperties - Gather information from the parsed
589 /// TableGen data (basically a wrapper for the CollectProperties
590 /// function object).
591 void CollectToolProperties (RecordVector::const_iterator B,
592                             RecordVector::const_iterator E,
593                             ToolPropertiesList& TPList,
594                             GlobalOptionDescriptions& OptDescs)
595 {
596   // Iterate over a properties list of every Tool definition
597   for (;B!=E;++B) {
598     RecordVector::value_type T = *B;
599     ListInit* PropList = T->getValueAsListInit("properties");
600
601     IntrusiveRefCntPtr<ToolProperties>
602       ToolProps(new ToolProperties(T->getName()));
603
604     std::for_each(PropList->begin(), PropList->end(),
605                   CollectProperties(*ToolProps, OptDescs));
606     TPList.push_back(ToolProps);
607   }
608 }
609
610 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
611 /// implement EmitOptionPropertyHandlingCode(). Emits code for
612 /// handling the (forward) option property.
613 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
614                                             std::ostream& O) {
615   switch (D.Type) {
616   case OptionType::Switch:
617     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
618     break;
619   case OptionType::Parameter:
620     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
621     O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
622     break;
623   case OptionType::Prefix:
624     O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
625       << D.GenVariableName() << ");\n";
626     break;
627   case OptionType::PrefixList:
628     O << Indent3 << "for (" << D.GenTypeDeclaration()
629       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
630       << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
631       << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
632       << "*B);\n";
633     break;
634   case OptionType::ParameterList:
635     O << Indent3 << "for (" << D.GenTypeDeclaration()
636       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
637       << Indent3 << "E = " << D.GenVariableName()
638       << ".end() ; B != E; ++B) {\n"
639       << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
640       << Indent4 << "vec.push_back(*B);\n"
641       << Indent3 << "}\n";
642     break;
643   }
644 }
645
646 /// EmitOptionPropertyHandlingCode - Helper function used by
647 /// EmitGenerateActionMethod(). Emits code that handles option
648 /// properties.
649 void EmitOptionPropertyHandlingCode (const ToolProperties& P,
650                                      const ToolOptionDescription& D,
651                                      std::ostream& O)
652 {
653   // Start of the if-clause.
654   O << Indent2 << "if (";
655   if (D.Type == OptionType::Switch)
656     O << D.GenVariableName();
657   else
658     O << '!' << D.GenVariableName() << ".empty()";
659
660   O <<") {\n";
661
662   // Handle option properties that take an argument.
663   for (OptionPropertyList::const_iterator B = D.Props.begin(),
664         E = D.Props.end(); B!=E; ++B) {
665     const OptionProperty& val = *B;
666
667     switch (val.first) {
668       // (append_cmd cmd) property
669     case OptionPropertyType::AppendCmd:
670       O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
671       break;
672       // Other properties with argument
673     default:
674       break;
675     }
676   }
677
678   // Handle flags
679
680   // (forward) property
681   if (D.isForward())
682     EmitForwardOptionPropertyHandlingCode(D, O);
683
684   // (unpack_values) property
685   if (D.isUnpackValues()) {
686     if (IsListOptionType(D.Type)) {
687       O << Indent3 << "for (" << D.GenTypeDeclaration()
688         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
689         << Indent3 << "E = " << D.GenVariableName()
690         << ".end(); B != E; ++B)\n"
691         << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
692     }
693     else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
694       O << Indent3 << "llvm::SplitString("
695         << D.GenVariableName() << ", vec, \",\");\n";
696     }
697     else {
698       // TOFIX: move this to the type-checking phase
699       throw std::string("Switches can't have unpack_values property!");
700     }
701   }
702
703   // End of the if-clause.
704   O << Indent2 << "}\n";
705 }
706
707 // EmitGenerateActionMethod - Emit one of two versions of the
708 // Tool::GenerateAction() method.
709 void EmitGenerateActionMethod (const ToolProperties& P, bool V, std::ostream& O)
710 {
711   if (V)
712     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
713   else
714     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
715
716   O << Indent2 << "const sys::Path& outFile) const\n"
717     << Indent1 << "{\n"
718     << Indent2 << "std::vector<std::string> vec;\n";
719
720   // Parse CmdLine tool property
721   if(P.CmdLine.empty())
722     throw "Tool " + P.Name + " has empty command line!";
723
724   StrVector::const_iterator I = P.CmdLine.begin();
725   ++I;
726   for (StrVector::const_iterator E = P.CmdLine.end(); I != E; ++I) {
727     const std::string& cmd = *I;
728     O << Indent2;
729     if (cmd == "$INFILE") {
730       if (V)
731         O << "for (PathVector::const_iterator B = inFiles.begin()"
732           << ", E = inFiles.end();\n"
733           << Indent2 << "B != E; ++B)\n"
734           << Indent3 << "vec.push_back(B->toString());\n";
735       else
736         O << "vec.push_back(inFile.toString());\n";
737     }
738     else if (cmd == "$OUTFILE") {
739       O << "vec.push_back(outFile.toString());\n";
740     }
741     else {
742       O << "vec.push_back(\"" << cmd << "\");\n";
743     }
744   }
745
746   // For every understood option, emit handling code.
747   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
748         E = P.OptDescs.end(); B != E; ++B) {
749     const ToolOptionDescription& val = B->second;
750     EmitOptionPropertyHandlingCode(P, val, O);
751   }
752
753   // Handle the Sink property.
754   if (P.isSink()) {
755     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
756       << Indent3 << "vec.insert(vec.end(), "
757       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
758       << Indent2 << "}\n";
759   }
760
761   O << Indent2 << "return Action(\"" << P.CmdLine.at(0) << "\", vec);\n"
762     << Indent1 << "}\n\n";
763 }
764
765 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
766 /// a given Tool class.
767 void EmitGenerateActionMethods (const ToolProperties& P, std::ostream& O) {
768
769   if (!P.isJoin())
770     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
771       << Indent2 << "const llvm::sys::Path& outFile) const\n"
772       << Indent1 << "{\n"
773       << Indent2 << "throw std::runtime_error(\"" << P.Name
774       << " is not a Join tool!\");\n"
775       << Indent1 << "}\n\n";
776   else
777     EmitGenerateActionMethod(P, true, O);
778
779   EmitGenerateActionMethod(P, false, O);
780 }
781
782 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
783 /// class.
784 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
785   O << Indent1 << "bool IsLast() const {\n"
786     << Indent2 << "bool last = false;\n";
787
788   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
789         E = P.OptDescs.end(); B != E; ++B) {
790     const ToolOptionDescription& val = B->second;
791
792     if (val.isStopCompilation())
793       O << Indent2
794         << "if (" << val.GenVariableName()
795         << ")\n" << Indent3 << "last = true;\n";
796   }
797
798   O << Indent2 << "return last;\n"
799     << Indent1 <<  "}\n\n";
800 }
801
802 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
803 /// methods for a given Tool class.
804 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
805   O << Indent1 << "const char* InputLanguage() const {\n"
806     << Indent2 << "return \"" << P.InLanguage << "\";\n"
807     << Indent1 << "}\n\n";
808
809   O << Indent1 << "const char* OutputLanguage() const {\n"
810     << Indent2 << "return \"" << P.OutLanguage << "\";\n"
811     << Indent1 << "}\n\n";
812 }
813
814 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
815 /// given Tool class.
816 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
817   O << Indent1 << "const char* OutputSuffix() const {\n"
818     << Indent2 << "return \"" << P.OutputSuffix << "\";\n"
819     << Indent1 << "}\n\n";
820 }
821
822 /// EmitNameMethod - Emit the Name() method for a given Tool class.
823 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
824   O << Indent1 << "const char* Name() const {\n"
825     << Indent2 << "return \"" << P.Name << "\";\n"
826     << Indent1 << "}\n\n";
827 }
828
829 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
830 /// class.
831 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
832   O << Indent1 << "bool IsJoin() const {\n";
833   if (P.isJoin())
834     O << Indent2 << "return true;\n";
835   else
836     O << Indent2 << "return false;\n";
837   O << Indent1 << "}\n\n";
838 }
839
840 /// EmitToolClassDefinition - Emit a Tool class definition.
841 void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
842
843   if(P.Name == "root")
844     return;
845
846   // Header
847   O << "class " << P.Name << " : public ";
848   if (P.isJoin())
849     O << "JoinTool";
850   else
851     O << "Tool";
852   O << " {\npublic:\n";
853
854   EmitNameMethod(P, O);
855   EmitInOutLanguageMethods(P, O);
856   EmitOutputSuffixMethod(P, O);
857   EmitIsJoinMethod(P, O);
858   EmitGenerateActionMethods(P, O);
859   EmitIsLastMethod(P, O);
860
861   // Close class definition
862   O << "};\n\n";
863 }
864
865 /// EmitOptionDescriptions - Iterate over a list of option
866 /// descriptions and emit registration code.
867 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
868                              std::ostream& O)
869 {
870   // Emit static cl::Option variables
871   for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
872          E = descs.end(); B!=E; ++B) {
873     const GlobalOptionDescription& val = B->second;
874
875     O << val.GenTypeDeclaration() << ' '
876       << val.GenVariableName()
877       << "(\"" << val.Name << '\"';
878
879     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
880       O << ", cl::Prefix";
881
882     if (val.isRequired()) {
883       switch (val.Type) {
884       case OptionType::PrefixList:
885       case OptionType::ParameterList:
886         O << ", cl::OneOrMore";
887         break;
888       default:
889         O << ", cl::Required";
890       }
891     }
892
893     O << ", cl::desc(\"" << val.Help << "\"));\n";
894   }
895
896   if (descs.HasSink)
897     O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
898
899   O << '\n';
900 }
901
902 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
903 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
904 {
905   // Get the relevant field out of RecordKeeper
906   Record* LangMapRecord = Records.getDef("LanguageMap");
907   if (!LangMapRecord)
908     throw std::string("Language map definition not found!");
909
910   ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
911   if (!LangsToSuffixesList)
912     throw std::string("Error in the language map definition!");
913
914   // Generate code
915   O << "void llvmc::PopulateLanguageMap(LanguageMap& language_map) {\n";
916
917   for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
918     Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
919
920     const std::string& Lang = LangToSuffixes->getValueAsString("lang");
921     const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
922
923     for (unsigned i = 0; i < Suffixes->size(); ++i)
924       O << Indent1 << "language_map[\""
925         << InitPtrToString(Suffixes->getElement(i))
926         << "\"] = \"" << Lang << "\";\n";
927   }
928
929   O << "}\n\n";
930 }
931
932 /// FillInToolToLang - Fills in two tables that map tool names to
933 /// (input, output) languages.  Used by the typechecker.
934 void FillInToolToLang (const ToolPropertiesList& TPList,
935                        StringMap<std::string>& ToolToInLang,
936                        StringMap<std::string>& ToolToOutLang) {
937   for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
938        B != E; ++B) {
939     const ToolProperties& P = *(*B);
940     ToolToInLang[P.Name] = P.InLanguage;
941     ToolToOutLang[P.Name] = P.OutLanguage;
942   }
943 }
944
945 /// TypecheckGraph - Check that names for output and input languages
946 /// on all edges do match.
947 // TOFIX: check for cycles.
948 // TOFIX: check for multiple default edges.
949 void TypecheckGraph (Record* CompilationGraph,
950                      const ToolPropertiesList& TPList) {
951   StringMap<std::string> ToolToInLang;
952   StringMap<std::string> ToolToOutLang;
953
954   FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
955   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
956   StringMap<std::string>::iterator IAE = ToolToInLang.end();
957   StringMap<std::string>::iterator IBE = ToolToOutLang.end();
958
959   for (unsigned i = 0; i < edges->size(); ++i) {
960     Record* Edge = edges->getElementAsRecord(i);
961     Record* A = Edge->getValueAsDef("a");
962     Record* B = Edge->getValueAsDef("b");
963     StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
964     StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
965     if(IA == IAE)
966       throw A->getName() + ": no such tool!";
967     if(IB == IBE)
968       throw B->getName() + ": no such tool!";
969     if(A->getName() != "root" && IA->second != IB->second)
970       throw "Edge " + A->getName() + "->" + B->getName()
971         + ": output->input language mismatch";
972     if(B->getName() == "root")
973       throw std::string("Edges back to the root are not allowed!");
974   }
975 }
976
977 /// EmitEdgePropertyTest1Arg - Helper function used by
978 /// EmitEdgePropertyTest.
979 bool EmitEdgePropertyTest1Arg(const std::string& PropName,
980                               const DagInit& Prop,
981                               const GlobalOptionDescriptions& OptDescs,
982                               std::ostream& O) {
983   checkNumberOfArguments(&Prop, 1);
984   const std::string& OptName = InitPtrToString(Prop.getArg(0));
985   if (PropName == "switch_on") {
986     const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
987     if (OptDesc.Type != OptionType::Switch)
988       throw OptName + ": incorrect option type!";
989     O << OptDesc.GenVariableName();
990     return true;
991   } else if (PropName == "if_input_languages_contain") {
992     O << "InLangs.count(\"" << OptName << "\") != 0";
993     return true;
994   }
995
996   return false;
997 }
998
999 /// EmitEdgePropertyTest2Args - Helper function used by
1000 /// EmitEdgePropertyTest.
1001 bool EmitEdgePropertyTest2Args(const std::string& PropName,
1002                                const DagInit& Prop,
1003                                const GlobalOptionDescriptions& OptDescs,
1004                                std::ostream& O) {
1005   checkNumberOfArguments(&Prop, 2);
1006   const std::string& OptName = InitPtrToString(Prop.getArg(0));
1007   const std::string& OptArg = InitPtrToString(Prop.getArg(1));
1008   const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
1009
1010   if (PropName == "parameter_equals") {
1011     if (OptDesc.Type != OptionType::Parameter
1012         && OptDesc.Type != OptionType::Prefix)
1013       throw OptName + ": incorrect option type!";
1014     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1015     return true;
1016   }
1017   else if (PropName == "element_in_list") {
1018     if (OptDesc.Type != OptionType::ParameterList
1019         && OptDesc.Type != OptionType::PrefixList)
1020       throw OptName + ": incorrect option type!";
1021     const std::string& VarName = OptDesc.GenVariableName();
1022     O << "std::find(" << VarName << ".begin(),\n"
1023       << Indent3 << VarName << ".end(), \""
1024       << OptArg << "\") != " << VarName << ".end()";
1025     return true;
1026   }
1027
1028   return false;
1029 }
1030
1031 // Forward declaration.
1032 void EmitEdgePropertyTest(const DagInit& Prop,
1033                           const GlobalOptionDescriptions& OptDescs,
1034                           std::ostream& O);
1035
1036 /// EmitLogicalOperationTest - Helper function used by
1037 /// EmitEdgePropertyTest.
1038 void EmitLogicalOperationTest(const DagInit& Prop, const char* LogicOp,
1039                               const GlobalOptionDescriptions& OptDescs,
1040                               std::ostream& O) {
1041   O << '(';
1042   for (unsigned j = 0, NumArgs = Prop.getNumArgs(); j < NumArgs; ++j) {
1043     const DagInit& InnerProp = InitPtrToDagInitRef(Prop.getArg(j));
1044     EmitEdgePropertyTest(InnerProp, OptDescs, O);
1045     if (j != NumArgs - 1)
1046       O << ")\n" << Indent3 << ' ' << LogicOp << " (";
1047     else
1048       O << ')';
1049   }
1050 }
1051
1052 /// EmitEdgePropertyTest - Helper function used by EmitEdgeClass.
1053 void EmitEdgePropertyTest(const DagInit& Prop,
1054                           const GlobalOptionDescriptions& OptDescs,
1055                           std::ostream& O) {
1056   const std::string& PropName = Prop.getOperator()->getAsString();
1057
1058   if (PropName == "and")
1059     EmitLogicalOperationTest(Prop, "&&", OptDescs, O);
1060   else if (PropName == "or")
1061     EmitLogicalOperationTest(Prop, "||", OptDescs, O);
1062   else if (EmitEdgePropertyTest1Arg(PropName, Prop, OptDescs, O))
1063     return;
1064   else if (EmitEdgePropertyTest2Args(PropName, Prop, OptDescs, O))
1065     return;
1066   else
1067     throw PropName + ": unknown edge property!";
1068 }
1069
1070 /// EmitEdgeClass - Emit a single Edge# class.
1071 void EmitEdgeClass(unsigned N, const std::string& Target,
1072                    ListInit* Props, const GlobalOptionDescriptions& OptDescs,
1073                    std::ostream& O) {
1074
1075   // Class constructor.
1076   O << "class Edge" << N << ": public Edge {\n"
1077     << "public:\n"
1078     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1079     << "\") {}\n\n"
1080
1081   // Function Weight().
1082     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1083     << Indent2 << "unsigned ret = 0;\n";
1084
1085   // Emit tests for every edge property.
1086   for (size_t i = 0, PropsSize = Props->size(); i < PropsSize; ++i) {
1087     const DagInit& Prop = InitPtrToDagInitRef(Props->getElement(i));
1088     const std::string& PropName = Prop.getOperator()->getAsString();
1089     unsigned N = 2;
1090
1091     O << Indent2 << "if (";
1092
1093     if (PropName == "weight") {
1094       checkNumberOfArguments(&Prop, 2);
1095       N = InitPtrToInt(Prop.getArg(0));
1096       const DagInit& InnerProp = InitPtrToDagInitRef(Prop.getArg(1));
1097       EmitEdgePropertyTest(InnerProp, OptDescs, O);
1098     }
1099     else {
1100       EmitEdgePropertyTest(Prop, OptDescs, O);
1101     }
1102
1103     O << ")\n" << Indent3 << "ret += " << N << ";\n";
1104   }
1105
1106   O << Indent2 << "return ret;\n"
1107     << Indent1 << "};\n\n};\n\n";
1108 }
1109
1110 // Emit Edge* classes that represent graph edges.
1111 void EmitEdgeClasses (Record* CompilationGraph,
1112                       const GlobalOptionDescriptions& OptDescs,
1113                       std::ostream& O) {
1114   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1115
1116   for (unsigned i = 0; i < edges->size(); ++i) {
1117     Record* Edge = edges->getElementAsRecord(i);
1118     Record* B = Edge->getValueAsDef("b");
1119     ListInit* Props = Edge->getValueAsListInit("props");
1120
1121     if (Props->empty())
1122       continue;
1123
1124     EmitEdgeClass(i, B->getName(), Props, OptDescs, O);
1125   }
1126 }
1127
1128 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1129 /// function.
1130 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1131                                    std::ostream& O)
1132 {
1133   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1134
1135   // Generate code
1136   O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1137     << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
1138
1139   // Insert vertices
1140
1141   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1142   if (Tools.empty())
1143     throw std::string("No tool definitions found!");
1144
1145   for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1146     const std::string& Name = (*B)->getName();
1147     if(Name != "root")
1148       O << Indent1 << "G.insertNode(new "
1149         << Name << "());\n";
1150   }
1151
1152   O << '\n';
1153
1154   // Insert edges
1155   for (unsigned i = 0; i < edges->size(); ++i) {
1156     Record* Edge = edges->getElementAsRecord(i);
1157     Record* A = Edge->getValueAsDef("a");
1158     Record* B = Edge->getValueAsDef("b");
1159     ListInit* Props = Edge->getValueAsListInit("props");
1160
1161     O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1162
1163     if (Props->empty())
1164       O << "new SimpleEdge(\"" << B->getName() << "\")";
1165     else
1166       O << "new Edge" << i << "()";
1167
1168     O << ");\n";
1169   }
1170
1171   O << "}\n\n";
1172 }
1173
1174
1175 // End of anonymous namespace
1176 }
1177
1178 /// run - The back-end entry point.
1179 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1180
1181   // Emit file header.
1182   EmitSourceFileHeader("LLVMC Configuration Library", O);
1183
1184   // Get a list of all defined Tools.
1185   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1186   if (Tools.empty())
1187     throw std::string("No tool definitions found!");
1188
1189   // Gather information from the Tool description dags.
1190   ToolPropertiesList tool_props;
1191   GlobalOptionDescriptions opt_descs;
1192   CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1193
1194   // Emit global option registration code.
1195   EmitOptionDescriptions(opt_descs, O);
1196
1197   // Emit PopulateLanguageMap() function
1198   // (a language map maps from file extensions to language names).
1199   EmitPopulateLanguageMap(Records, O);
1200
1201   // Emit Tool classes.
1202   for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1203          E = tool_props.end(); B!=E; ++B)
1204     EmitToolClassDefinition(*(*B), O);
1205
1206   Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1207   if (!CompilationGraphRecord)
1208     throw std::string("Compilation graph description not found!");
1209
1210   // Typecheck the compilation graph.
1211   TypecheckGraph(CompilationGraphRecord, tool_props);
1212
1213   // Emit Edge# classes.
1214   EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1215
1216   // Emit PopulateCompilationGraph() function.
1217   EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1218
1219   // EOF
1220 }