Fix PR2596: out of bound reference.
[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   // TOFIX - Add a mechanism for OS detection.
800   checkNumberOfArguments(&d, 1);
801   const std::string& OptName = InitPtrToString(d.getArg(0));
802   if (TestName == "switch_on") {
803     const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
804     if (OptDesc.Type != OptionType::Switch)
805       throw OptName + ": incorrect option type!";
806     O << OptDesc.GenVariableName();
807     return true;
808   } else if (TestName == "input_languages_contain") {
809     O << "InLangs.count(\"" << OptName << "\") != 0";
810     return true;
811   } else if (TestName == "in_language") {
812     // Works only for cmd_line!
813     O << "GetLanguage(inFile) == \"" << OptName << '\"';
814     return true;
815   } else if (TestName == "not_empty") {
816     if (OptName == "o") {
817       O << "!OutputFilename.empty()";
818       return true;
819     }
820     else {
821       const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
822       if (OptDesc.Type == OptionType::Switch)
823         throw OptName + ": incorrect option type!";
824       O << '!' << OptDesc.GenVariableName() << ".empty()";
825       return true;
826     }
827   }
828
829   return false;
830 }
831
832 /// EmitCaseTest2Args - Helper function used by
833 /// EmitCaseConstructHandler.
834 bool EmitCaseTest2Args(const std::string& TestName,
835                        const DagInit& d,
836                        const char* IndentLevel,
837                        const GlobalOptionDescriptions& OptDescs,
838                        std::ostream& O) {
839   checkNumberOfArguments(&d, 2);
840   const std::string& OptName = InitPtrToString(d.getArg(0));
841   const std::string& OptArg = InitPtrToString(d.getArg(1));
842   const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
843
844   if (TestName == "parameter_equals") {
845     if (OptDesc.Type != OptionType::Parameter
846         && OptDesc.Type != OptionType::Prefix)
847       throw OptName + ": incorrect option type!";
848     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
849     return true;
850   }
851   else if (TestName == "element_in_list") {
852     if (OptDesc.Type != OptionType::ParameterList
853         && OptDesc.Type != OptionType::PrefixList)
854       throw OptName + ": incorrect option type!";
855     const std::string& VarName = OptDesc.GenVariableName();
856     O << "std::find(" << VarName << ".begin(),\n"
857       << IndentLevel << Indent1 << VarName << ".end(), \""
858       << OptArg << "\") != " << VarName << ".end()";
859     return true;
860   }
861
862   return false;
863 }
864
865 // Forward declaration.
866 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
867 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
868                   const GlobalOptionDescriptions& OptDescs,
869                   std::ostream& O);
870
871 /// EmitLogicalOperationTest - Helper function used by
872 /// EmitCaseConstructHandler.
873 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
874                               const char* IndentLevel,
875                               const GlobalOptionDescriptions& OptDescs,
876                               std::ostream& O) {
877   O << '(';
878   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
879     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
880     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
881     if (j != NumArgs - 1)
882       O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
883     else
884       O << ')';
885   }
886 }
887
888 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
889 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
890                   const GlobalOptionDescriptions& OptDescs,
891                   std::ostream& O) {
892   const std::string& TestName = d.getOperator()->getAsString();
893
894   if (TestName == "and")
895     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
896   else if (TestName == "or")
897     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
898   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
899     return;
900   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
901     return;
902   else
903     throw TestName + ": unknown edge property!";
904 }
905
906 // Emit code that handles the 'case' construct.
907 // Takes a function object that should emit code for every case clause.
908 // Callback's type is
909 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
910 template <typename F>
911 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
912                               F Callback, bool EmitElseIf,
913                               const GlobalOptionDescriptions& OptDescs,
914                               std::ostream& O) {
915   assert(d->getOperator()->getAsString() == "case");
916
917   unsigned numArgs = d->getNumArgs();
918   if (d->getNumArgs() < 2)
919     throw "There should be at least one clause in the 'case' expression:\n"
920       + d->getAsString();
921
922   for (unsigned i = 0; i != numArgs; ++i) {
923     const DagInit& Test = InitPtrToDag(d->getArg(i));
924
925     // Emit the test.
926     if (Test.getOperator()->getAsString() == "default") {
927       if (i+2 != numArgs)
928         throw std::string("The 'default' clause should be the last in the"
929                           "'case' construct!");
930       O << IndentLevel << "else {\n";
931     }
932     else {
933       O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
934       EmitCaseTest(Test, IndentLevel, OptDescs, O);
935       O << ") {\n";
936     }
937
938     // Emit the corresponding statement.
939     ++i;
940     if (i == numArgs)
941       throw "Case construct handler: no corresponding action "
942         "found for the test " + Test.getAsString() + '!';
943
944     Init* arg = d->getArg(i);
945     if (dynamic_cast<DagInit*>(arg)
946         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
947       EmitCaseConstructHandler(static_cast<DagInit*>(arg),
948                                (std::string(IndentLevel) + Indent1).c_str(),
949                                Callback, EmitElseIf, OptDescs, O);
950     }
951     else {
952       Callback(arg, IndentLevel, O);
953     }
954     O << IndentLevel << "}\n";
955   }
956 }
957
958 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
959 /// implement EmitOptionPropertyHandlingCode(). Emits code for
960 /// handling the (forward) option property.
961 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
962                                             std::ostream& O) {
963   switch (D.Type) {
964   case OptionType::Switch:
965     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
966     break;
967   case OptionType::Parameter:
968     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
969     O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
970     break;
971   case OptionType::Prefix:
972     O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
973       << D.GenVariableName() << ");\n";
974     break;
975   case OptionType::PrefixList:
976     O << Indent3 << "for (" << D.GenTypeDeclaration()
977       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
978       << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
979       << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
980       << "*B);\n";
981     break;
982   case OptionType::ParameterList:
983     O << Indent3 << "for (" << D.GenTypeDeclaration()
984       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
985       << Indent3 << "E = " << D.GenVariableName()
986       << ".end() ; B != E; ++B) {\n"
987       << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
988       << Indent4 << "vec.push_back(*B);\n"
989       << Indent3 << "}\n";
990     break;
991   case OptionType::Alias:
992   default:
993     throw std::string("Aliases are not allowed in tool option descriptions!");
994   }
995 }
996
997 // ToolOptionHasInterestingProperties - A helper function used by
998 // EmitOptionPropertyHandlingCode() that tells us whether we should
999 // emit any property handling code at all.
1000 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
1001   bool ret = false;
1002   for (OptionPropertyList::const_iterator B = D.Props.begin(),
1003          E = D.Props.end(); B != E; ++B) {
1004       const OptionProperty& OptProp = *B;
1005       if (OptProp.first == OptionPropertyType::AppendCmd)
1006         ret = true;
1007     }
1008   if (D.isForward() || D.isUnpackValues())
1009     ret = true;
1010   return ret;
1011 }
1012
1013 /// EmitOptionPropertyHandlingCode - Helper function used by
1014 /// EmitGenerateActionMethod(). Emits code that handles option
1015 /// properties.
1016 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
1017                                      std::ostream& O)
1018 {
1019   if (!ToolOptionHasInterestingProperties(D))
1020     return;
1021   // Start of the if-clause.
1022   O << Indent2 << "if (";
1023   if (D.Type == OptionType::Switch)
1024     O << D.GenVariableName();
1025   else
1026     O << '!' << D.GenVariableName() << ".empty()";
1027
1028   O <<") {\n";
1029
1030   // Handle option properties that take an argument.
1031   for (OptionPropertyList::const_iterator B = D.Props.begin(),
1032         E = D.Props.end(); B!=E; ++B) {
1033     const OptionProperty& val = *B;
1034
1035     switch (val.first) {
1036       // (append_cmd cmd) property
1037     case OptionPropertyType::AppendCmd:
1038       O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1039       break;
1040       // Other properties with argument
1041     default:
1042       break;
1043     }
1044   }
1045
1046   // Handle flags
1047
1048   // (forward) property
1049   if (D.isForward())
1050     EmitForwardOptionPropertyHandlingCode(D, O);
1051
1052   // (unpack_values) property
1053   if (D.isUnpackValues()) {
1054     if (IsListOptionType(D.Type)) {
1055       O << Indent3 << "for (" << D.GenTypeDeclaration()
1056         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1057         << Indent3 << "E = " << D.GenVariableName()
1058         << ".end(); B != E; ++B)\n"
1059         << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
1060     }
1061     else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
1062       O << Indent3 << "llvm::SplitString("
1063         << D.GenVariableName() << ", vec, \",\");\n";
1064     }
1065     else {
1066       throw std::string("Switches can't have unpack_values property!");
1067     }
1068   }
1069
1070   // End of the if-clause.
1071   O << Indent2 << "}\n";
1072 }
1073
1074 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1075 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1076 std::string SubstituteSpecialCommands(const std::string& cmd) {
1077   size_t cparen = cmd.find(")");
1078   std::string ret;
1079
1080   if (cmd.find("$CALL(") == 0) {
1081     if (cmd.size() == 6)
1082       throw std::string("$CALL invocation: empty argument list!");
1083
1084     ret += "hooks::";
1085     ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1086     ret += "()";
1087   }
1088   else if (cmd.find("$ENV(") == 0) {
1089     if (cmd.size() == 5)
1090       throw std::string("$ENV invocation: empty argument list!");
1091
1092     ret += "std::getenv(\"";
1093     ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1094     ret += "\")";
1095   }
1096   else {
1097     throw "Unknown special command: " + cmd;
1098   }
1099
1100   if (cmd.begin() + cparen + 1 != cmd.end()) {
1101     ret += " + std::string(\"";
1102     ret += (cmd.c_str() + cparen + 1);
1103     ret += "\")";
1104   }
1105
1106   return ret;
1107 }
1108
1109 /// EmitCmdLineVecFill - Emit code that fills in the command line
1110 /// vector. Helper function used by EmitGenerateActionMethod().
1111 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1112                         bool Version, const char* IndentLevel,
1113                         std::ostream& O) {
1114   StrVector StrVec;
1115   SplitString(InitPtrToString(CmdLine), StrVec);
1116   if (StrVec.empty())
1117     throw "Tool " + ToolName + " has empty command line!";
1118
1119   StrVector::const_iterator I = StrVec.begin();
1120   ++I;
1121   for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1122     const std::string& cmd = *I;
1123     O << IndentLevel;
1124     if (cmd.at(0) == '$') {
1125       if (cmd == "$INFILE") {
1126         if (Version)
1127           O << "for (PathVector::const_iterator B = inFiles.begin()"
1128             << ", E = inFiles.end();\n"
1129             << IndentLevel << "B != E; ++B)\n"
1130             << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1131         else
1132           O << "vec.push_back(inFile.toString());\n";
1133       }
1134       else if (cmd == "$OUTFILE") {
1135         O << "vec.push_back(outFile.toString());\n";
1136       }
1137       else {
1138         O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1139         O << ");\n";
1140       }
1141     }
1142     else {
1143       O << "vec.push_back(\"" << cmd << "\");\n";
1144     }
1145   }
1146   O << IndentLevel << "cmd = "
1147     << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1148         : "\"" + StrVec[0] + "\"")
1149     << ";\n";
1150 }
1151
1152 /// EmitCmdLineVecFillCallback - A function object wrapper around
1153 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1154 /// argument to EmitCaseConstructHandler().
1155 class EmitCmdLineVecFillCallback {
1156   bool Version;
1157   const std::string& ToolName;
1158  public:
1159   EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1160     : Version(Ver), ToolName(TN) {}
1161
1162   void operator()(const Init* Statement, const char* IndentLevel,
1163                   std::ostream& O) const
1164   {
1165     EmitCmdLineVecFill(Statement, ToolName, Version,
1166                        (std::string(IndentLevel) + Indent1).c_str(), O);
1167   }
1168 };
1169
1170 // EmitGenerateActionMethod - Emit one of two versions of the
1171 // Tool::GenerateAction() method.
1172 void EmitGenerateActionMethod (const ToolProperties& P,
1173                                const GlobalOptionDescriptions& OptDescs,
1174                                bool Version, std::ostream& O) {
1175   if (Version)
1176     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1177   else
1178     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1179
1180   O << Indent2 << "const sys::Path& outFile,\n"
1181     << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1182     << Indent1 << "{\n"
1183     << Indent2 << "const char* cmd;\n"
1184     << Indent2 << "std::vector<std::string> vec;\n";
1185
1186   // cmd_line is either a string or a 'case' construct.
1187   if (typeid(*P.CmdLine) == typeid(StringInit))
1188     EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1189   else
1190     EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1191                              EmitCmdLineVecFillCallback(Version, P.Name),
1192                              true, OptDescs, O);
1193
1194   // For every understood option, emit handling code.
1195   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1196         E = P.OptDescs.end(); B != E; ++B) {
1197     const ToolOptionDescription& val = B->second;
1198     EmitOptionPropertyHandlingCode(val, O);
1199   }
1200
1201   // Handle the Sink property.
1202   if (P.isSink()) {
1203     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1204       << Indent3 << "vec.insert(vec.end(), "
1205       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1206       << Indent2 << "}\n";
1207   }
1208
1209   O << Indent2 << "return Action(cmd, vec);\n"
1210     << Indent1 << "}\n\n";
1211 }
1212
1213 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1214 /// a given Tool class.
1215 void EmitGenerateActionMethods (const ToolProperties& P,
1216                                 const GlobalOptionDescriptions& OptDescs,
1217                                 std::ostream& O) {
1218   if (!P.isJoin())
1219     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1220       << Indent2 << "const llvm::sys::Path& outFile,\n"
1221       << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1222       << Indent1 << "{\n"
1223       << Indent2 << "throw std::runtime_error(\"" << P.Name
1224       << " is not a Join tool!\");\n"
1225       << Indent1 << "}\n\n";
1226   else
1227     EmitGenerateActionMethod(P, OptDescs, true, O);
1228
1229   EmitGenerateActionMethod(P, OptDescs, false, O);
1230 }
1231
1232 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1233 /// class.
1234 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1235   O << Indent1 << "bool IsLast() const {\n"
1236     << Indent2 << "bool last = false;\n";
1237
1238   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1239         E = P.OptDescs.end(); B != E; ++B) {
1240     const ToolOptionDescription& val = B->second;
1241
1242     if (val.isStopCompilation())
1243       O << Indent2
1244         << "if (" << val.GenVariableName()
1245         << ")\n" << Indent3 << "last = true;\n";
1246   }
1247
1248   O << Indent2 << "return last;\n"
1249     << Indent1 <<  "}\n\n";
1250 }
1251
1252 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1253 /// methods for a given Tool class.
1254 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1255   O << Indent1 << "const char** InputLanguages() const {\n"
1256     << Indent2 << "return InputLanguages_;\n"
1257     << Indent1 << "}\n\n";
1258
1259   O << Indent1 << "const char* OutputLanguage() const {\n"
1260     << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1261     << Indent1 << "}\n\n";
1262 }
1263
1264 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1265 /// given Tool class.
1266 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1267   O << Indent1 << "const char* OutputSuffix() const {\n"
1268     << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1269
1270   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1271          E = P.OptDescs.end(); B != E; ++B) {
1272     const ToolOptionDescription& OptDesc = B->second;
1273     for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1274            E = OptDesc.Props.end(); B != E; ++B) {
1275       const OptionProperty& OptProp = *B;
1276       if (OptProp.first == OptionPropertyType::OutputSuffix) {
1277         O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1278           << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1279       }
1280     }
1281   }
1282
1283   O << Indent2 << "return ret;\n"
1284     << Indent1 << "}\n\n";
1285 }
1286
1287 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1288 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1289   O << Indent1 << "const char* Name() const {\n"
1290     << Indent2 << "return \"" << P.Name << "\";\n"
1291     << Indent1 << "}\n\n";
1292 }
1293
1294 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1295 /// class.
1296 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1297   O << Indent1 << "bool IsJoin() const {\n";
1298   if (P.isJoin())
1299     O << Indent2 << "return true;\n";
1300   else
1301     O << Indent2 << "return false;\n";
1302   O << Indent1 << "}\n\n";
1303 }
1304
1305 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1306 /// given Tool class.
1307 void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1308   O << "const char* " << P.Name << "::InputLanguages_[] = {";
1309   for (StrVector::const_iterator B = P.InLanguage.begin(),
1310          E = P.InLanguage.end(); B != E; ++B)
1311     O << '\"' << *B << "\", ";
1312   O << "0};\n\n";
1313 }
1314
1315 /// EmitToolClassDefinition - Emit a Tool class definition.
1316 void EmitToolClassDefinition (const ToolProperties& P,
1317                               const GlobalOptionDescriptions& OptDescs,
1318                               std::ostream& O) {
1319   if (P.Name == "root")
1320     return;
1321
1322   // Header
1323   O << "class " << P.Name << " : public ";
1324   if (P.isJoin())
1325     O << "JoinTool";
1326   else
1327     O << "Tool";
1328
1329   O << "{\nprivate:\n"
1330     << Indent1 << "static const char* InputLanguages_[];\n\n";
1331
1332   O << "public:\n";
1333   EmitNameMethod(P, O);
1334   EmitInOutLanguageMethods(P, O);
1335   EmitOutputSuffixMethod(P, O);
1336   EmitIsJoinMethod(P, O);
1337   EmitGenerateActionMethods(P, OptDescs, O);
1338   EmitIsLastMethod(P, O);
1339
1340   // Close class definition
1341   O << "};\n";
1342
1343   EmitStaticMemberDefinitions(P, O);
1344
1345 }
1346
1347 /// EmitOptionDescriptions - Iterate over a list of option
1348 /// descriptions and emit registration code.
1349 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1350                              std::ostream& O)
1351 {
1352   std::vector<GlobalOptionDescription> Aliases;
1353
1354   // Emit static cl::Option variables.
1355   for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1356          E = descs.end(); B!=E; ++B) {
1357     const GlobalOptionDescription& val = B->second;
1358
1359     if (val.Type == OptionType::Alias) {
1360       Aliases.push_back(val);
1361       continue;
1362     }
1363
1364     O << val.GenTypeDeclaration() << ' '
1365       << val.GenVariableName()
1366       << "(\"" << val.Name << '\"';
1367
1368     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1369       O << ", cl::Prefix";
1370
1371     if (val.isRequired()) {
1372       switch (val.Type) {
1373       case OptionType::PrefixList:
1374       case OptionType::ParameterList:
1375         O << ", cl::OneOrMore";
1376         break;
1377       default:
1378         O << ", cl::Required";
1379       }
1380     }
1381
1382     if (!val.Help.empty())
1383       O << ", cl::desc(\"" << val.Help << "\")";
1384
1385     O << ");\n";
1386   }
1387
1388   // Emit the aliases (they should go after all the 'proper' options).
1389   for (std::vector<GlobalOptionDescription>::const_iterator
1390          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1391     const GlobalOptionDescription& val = *B;
1392
1393     O << val.GenTypeDeclaration() << ' '
1394       << val.GenVariableName()
1395       << "(\"" << val.Name << '\"';
1396
1397     GlobalOptionDescriptions::container_type
1398       ::const_iterator F = descs.Descriptions.find(val.Help);
1399     if (F != descs.Descriptions.end())
1400       O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1401     else
1402       throw val.Name + ": alias to an unknown option!";
1403
1404     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
1405   }
1406
1407   // Emit the sink option.
1408   if (descs.HasSink)
1409     O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1410
1411   O << '\n';
1412 }
1413
1414 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1415 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1416 {
1417   // Get the relevant field out of RecordKeeper
1418   Record* LangMapRecord = Records.getDef("LanguageMap");
1419   if (!LangMapRecord)
1420     throw std::string("Language map definition not found!");
1421
1422   ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1423   if (!LangsToSuffixesList)
1424     throw std::string("Error in the language map definition!");
1425
1426   // Generate code
1427   O << "void llvmc::PopulateLanguageMap() {\n";
1428
1429   for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1430     Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1431
1432     const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1433     const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1434
1435     for (unsigned i = 0; i < Suffixes->size(); ++i)
1436       O << Indent1 << "GlobalLanguageMap[\""
1437         << InitPtrToString(Suffixes->getElement(i))
1438         << "\"] = \"" << Lang << "\";\n";
1439   }
1440
1441   O << "}\n\n";
1442 }
1443
1444 /// FillInToolToLang - Fills in two tables that map tool names to
1445 /// (input, output) languages.  Used by the typechecker.
1446 void FillInToolToLang (const ToolPropertiesList& TPList,
1447                        StringMap<StringSet<> >& ToolToInLang,
1448                        StringMap<std::string>& ToolToOutLang) {
1449   for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1450        B != E; ++B) {
1451     const ToolProperties& P = *(*B);
1452     for (StrVector::const_iterator B = P.InLanguage.begin(),
1453            E = P.InLanguage.end(); B != E; ++B)
1454       ToolToInLang[P.Name].insert(*B);
1455     ToolToOutLang[P.Name] = P.OutLanguage;
1456   }
1457 }
1458
1459 /// TypecheckGraph - Check that names for output and input languages
1460 /// on all edges do match.
1461 // TOFIX: It would be nice if this function also checked for cycles
1462 // and multiple default edges in the graph (better error
1463 // reporting). Unfortunately, it is awkward to do right now because
1464 // our intermediate representation is not sufficiently
1465 // sofisticated. Algorithms like these should be run on a real graph
1466 // instead of AST.
1467 void TypecheckGraph (Record* CompilationGraph,
1468                      const ToolPropertiesList& TPList) {
1469   StringMap<StringSet<> > ToolToInLang;
1470   StringMap<std::string> ToolToOutLang;
1471
1472   FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1473   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1474   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1475   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1476
1477   for (unsigned i = 0; i < edges->size(); ++i) {
1478     Record* Edge = edges->getElementAsRecord(i);
1479     Record* A = Edge->getValueAsDef("a");
1480     Record* B = Edge->getValueAsDef("b");
1481     StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1482     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1483     if (IA == IAE)
1484       throw A->getName() + ": no such tool!";
1485     if (IB == IBE)
1486       throw B->getName() + ": no such tool!";
1487     if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1488       throw "Edge " + A->getName() + "->" + B->getName()
1489         + ": output->input language mismatch";
1490     if (B->getName() == "root")
1491       throw std::string("Edges back to the root are not allowed!");
1492   }
1493 }
1494
1495 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1496 /// by EmitEdgeClass().
1497 void IncDecWeight (const Init* i, const char* IndentLevel,
1498                    std::ostream& O) {
1499   const DagInit& d = InitPtrToDag(i);
1500   const std::string& OpName = d.getOperator()->getAsString();
1501
1502   if (OpName == "inc_weight")
1503     O << IndentLevel << Indent1 << "ret += ";
1504   else if (OpName == "dec_weight")
1505     O << IndentLevel << Indent1 << "ret -= ";
1506   else
1507     throw "Unknown operator in edge properties list: " + OpName + '!';
1508
1509   if (d.getNumArgs() > 0)
1510     O << InitPtrToInt(d.getArg(0)) << ";\n";
1511   else
1512     O << "2;\n";
1513
1514 }
1515
1516 /// EmitEdgeClass - Emit a single Edge# class.
1517 void EmitEdgeClass (unsigned N, const std::string& Target,
1518                     DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1519                     std::ostream& O) {
1520
1521   // Class constructor.
1522   O << "class Edge" << N << ": public Edge {\n"
1523     << "public:\n"
1524     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1525     << "\") {}\n\n"
1526
1527   // Function Weight().
1528     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1529     << Indent2 << "unsigned ret = 0;\n";
1530
1531   // Handle the 'case' construct.
1532   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1533
1534   O << Indent2 << "return ret;\n"
1535     << Indent1 << "};\n\n};\n\n";
1536 }
1537
1538 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1539 void EmitEdgeClasses (Record* CompilationGraph,
1540                       const GlobalOptionDescriptions& OptDescs,
1541                       std::ostream& O) {
1542   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1543
1544   for (unsigned i = 0; i < edges->size(); ++i) {
1545     Record* Edge = edges->getElementAsRecord(i);
1546     Record* B = Edge->getValueAsDef("b");
1547     DagInit* Weight = Edge->getValueAsDag("weight");
1548
1549     if (isDagEmpty(Weight))
1550       continue;
1551
1552     EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1553   }
1554 }
1555
1556 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1557 /// function.
1558 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1559                                    std::ostream& O)
1560 {
1561   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1562
1563   // Generate code
1564   O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1565     << Indent1 << "PopulateLanguageMap();\n\n";
1566
1567   // Insert vertices
1568
1569   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1570   if (Tools.empty())
1571     throw std::string("No tool definitions found!");
1572
1573   for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1574     const std::string& Name = (*B)->getName();
1575     if (Name != "root")
1576       O << Indent1 << "G.insertNode(new "
1577         << Name << "());\n";
1578   }
1579
1580   O << '\n';
1581
1582   // Insert edges
1583   for (unsigned i = 0; i < edges->size(); ++i) {
1584     Record* Edge = edges->getElementAsRecord(i);
1585     Record* A = Edge->getValueAsDef("a");
1586     Record* B = Edge->getValueAsDef("b");
1587     DagInit* Weight = Edge->getValueAsDag("weight");
1588
1589     O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1590
1591     if (isDagEmpty(Weight))
1592       O << "new SimpleEdge(\"" << B->getName() << "\")";
1593     else
1594       O << "new Edge" << i << "()";
1595
1596     O << ");\n";
1597   }
1598
1599   O << "}\n\n";
1600 }
1601
1602 /// ExtractHookNames - Extract the hook names from all instances of
1603 /// $CALL(HookName) in the provided command line string. Helper
1604 /// function used by FillInHookNames().
1605 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1606   StrVector cmds;
1607   llvm::SplitString(InitPtrToString(CmdLine), cmds);
1608   for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1609        B != E; ++B) {
1610     const std::string& cmd = *B;
1611     if (cmd.find("$CALL(") == 0) {
1612       if (cmd.size() == 6)
1613         throw std::string("$CALL invocation: empty argument list!");
1614       HookNames.push_back(std::string(cmd.begin() + 6,
1615                                       cmd.begin() + cmd.find(")")));
1616     }
1617   }
1618 }
1619
1620 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1621 /// 'case' expression, handle nesting. Helper function used by
1622 /// FillInHookNames().
1623 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1624   const DagInit& d = InitPtrToDag(Case);
1625   bool even = false;
1626   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1627        B != E; ++B) {
1628     Init* arg = *B;
1629     if (even && dynamic_cast<DagInit*>(arg)
1630         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1631       ExtractHookNamesFromCaseConstruct(arg, HookNames);
1632     else if (even)
1633       ExtractHookNames(arg, HookNames);
1634     even = !even;
1635   }
1636 }
1637
1638 /// FillInHookNames - Actually extract the hook names from all command
1639 /// line strings. Helper function used by EmitHookDeclarations().
1640 void FillInHookNames(const ToolPropertiesList& TPList,
1641                      StrVector& HookNames) {
1642   // For all command lines:
1643   for (ToolPropertiesList::const_iterator B = TPList.begin(),
1644          E = TPList.end(); B != E; ++B) {
1645     const ToolProperties& P = *(*B);
1646     if (!P.CmdLine)
1647       continue;
1648     if (dynamic_cast<StringInit*>(P.CmdLine))
1649       // This is a string.
1650       ExtractHookNames(P.CmdLine, HookNames);
1651     else
1652       // This is a 'case' construct.
1653       ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1654   }
1655 }
1656
1657 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1658 /// property records and emit hook function declaration for each
1659 /// instance of $CALL(HookName).
1660 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1661                           std::ostream& O) {
1662   StrVector HookNames;
1663   FillInHookNames(ToolProps, HookNames);
1664   if (HookNames.empty())
1665     return;
1666   std::sort(HookNames.begin(), HookNames.end());
1667   StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1668
1669   O << "namespace hooks {\n";
1670   for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1671     O << Indent1 << "std::string " << *B << "();\n";
1672
1673   O << "}\n\n";
1674 }
1675
1676 // End of anonymous namespace
1677 }
1678
1679 /// run - The back-end entry point.
1680 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1681   try {
1682
1683   // Emit file header.
1684   EmitSourceFileHeader("LLVMC Configuration Library", O);
1685
1686   // Get a list of all defined Tools.
1687   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1688   if (Tools.empty())
1689     throw std::string("No tool definitions found!");
1690
1691   // Gather information from the Tool description dags.
1692   ToolPropertiesList tool_props;
1693   GlobalOptionDescriptions opt_descs;
1694   CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1695
1696   RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1697   CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1698                                   opt_descs);
1699
1700   // Check that there are no options without side effects (specified
1701   // only in the OptionList).
1702   CheckForSuperfluousOptions(tool_props, opt_descs);
1703
1704   // Emit global option registration code.
1705   EmitOptionDescriptions(opt_descs, O);
1706
1707   // Emit hook declarations.
1708   EmitHookDeclarations(tool_props, O);
1709
1710   // Emit PopulateLanguageMap() function
1711   // (a language map maps from file extensions to language names).
1712   EmitPopulateLanguageMap(Records, O);
1713
1714   // Emit Tool classes.
1715   for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1716          E = tool_props.end(); B!=E; ++B)
1717     EmitToolClassDefinition(*(*B), opt_descs, O);
1718
1719   Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1720   if (!CompilationGraphRecord)
1721     throw std::string("Compilation graph description not found!");
1722
1723   // Typecheck the compilation graph.
1724   TypecheckGraph(CompilationGraphRecord, tool_props);
1725
1726   // Emit Edge# classes.
1727   EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1728
1729   // Emit PopulateCompilationGraph() function.
1730   EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1731
1732   // EOF
1733   } catch (std::exception& Error) {
1734     throw Error.what() + std::string(" - usually this means a syntax error.");
1735   }
1736 }