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