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