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