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