First draft of the OptionPreprocessor.
[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 <algorithm>
23 #include <cassert>
24 #include <functional>
25 #include <stdexcept>
26 #include <string>
27 #include <typeinfo>
28
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.
43 unsigned TabWidth = 4;
44 unsigned Indent1  = TabWidth*1;
45 unsigned Indent2  = TabWidth*2;
46 unsigned Indent3  = TabWidth*3;
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 /// Id - An 'identity' function object.
58 struct Id {
59   template<typename T>
60   void operator()(const T&) const {
61   }
62 };
63
64 int InitPtrToInt(const Init* ptr) {
65   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
66   return val.getValue();
67 }
68
69 const std::string& InitPtrToString(const Init* ptr) {
70   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
71   return val.getValue();
72 }
73
74 const ListInit& InitPtrToList(const Init* ptr) {
75   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
76   return val;
77 }
78
79 const DagInit& InitPtrToDag(const Init* ptr) {
80   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
81   return val;
82 }
83
84 // checkNumberOfArguments - Ensure that the number of args in d is
85 // greater than or equal to min_arguments, otherwise throw an exception.
86 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
87   if (!d || d->getNumArgs() < min_arguments)
88     throw d->getOperator()->getAsString() + ": too few arguments!";
89 }
90
91 // isDagEmpty - is this DAG marked with an empty marker?
92 bool isDagEmpty (const DagInit* d) {
93   return d->getOperator()->getAsString() == "empty_dag_marker";
94 }
95
96 // EscapeVariableName - Escape commas and other symbols not allowed
97 // in the C++ variable names. Makes it possible to use options named
98 // like "Wa," (useful for prefix options).
99 std::string EscapeVariableName(const std::string& Var) {
100   std::string ret;
101   for (unsigned i = 0; i != Var.size(); ++i) {
102     char cur_char = Var[i];
103     if (cur_char == ',') {
104       ret += "_comma_";
105     }
106     else if (cur_char == '+') {
107       ret += "_plus_";
108     }
109     else if (cur_char == '-') {
110       ret += "_dash_";
111     }
112     else {
113       ret.push_back(cur_char);
114     }
115   }
116   return ret;
117 }
118
119 /// oneOf - Does the input string contain this character?
120 bool oneOf(const char* lst, char c) {
121   while (*lst) {
122     if (*lst++ == c)
123       return true;
124   }
125   return false;
126 }
127
128 template <class I, class S>
129 void checkedIncrement(I& P, I E, S ErrorString) {
130   ++P;
131   if (P == E)
132     throw ErrorString;
133 }
134
135 //===----------------------------------------------------------------------===//
136 /// Back-end specific code
137
138
139 /// OptionType - One of six different option types. See the
140 /// documentation for detailed description of differences.
141 namespace OptionType {
142
143   enum OptionType { Alias, Switch, Parameter, ParameterList,
144                     Prefix, PrefixList};
145
146   bool IsList (OptionType t) {
147     return (t == ParameterList || t == PrefixList);
148   }
149
150   bool IsSwitch (OptionType t) {
151     return (t == Switch);
152   }
153
154   bool IsParameter (OptionType t) {
155     return (t == Parameter || t == Prefix);
156   }
157
158 }
159
160 OptionType::OptionType stringToOptionType(const std::string& T) {
161   if (T == "alias_option")
162     return OptionType::Alias;
163   else if (T == "switch_option")
164     return OptionType::Switch;
165   else if (T == "parameter_option")
166     return OptionType::Parameter;
167   else if (T == "parameter_list_option")
168     return OptionType::ParameterList;
169   else if (T == "prefix_option")
170     return OptionType::Prefix;
171   else if (T == "prefix_list_option")
172     return OptionType::PrefixList;
173   else
174     throw "Unknown option type: " + T + '!';
175 }
176
177 namespace OptionDescriptionFlags {
178   enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
179                                 ReallyHidden = 0x4, Extern = 0x8,
180                                 OneOrMore = 0x10, ZeroOrOne = 0x20 };
181 }
182
183 /// OptionDescription - Represents data contained in a single
184 /// OptionList entry.
185 struct OptionDescription {
186   OptionType::OptionType Type;
187   std::string Name;
188   unsigned Flags;
189   std::string Help;
190   unsigned MultiVal;
191   Init* InitVal;
192
193   OptionDescription(OptionType::OptionType t = OptionType::Switch,
194                     const std::string& n = "",
195                     const std::string& h = DefaultHelpString)
196     : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
197   {}
198
199   /// GenTypeDeclaration - Returns the C++ variable type of this
200   /// option.
201   const char* GenTypeDeclaration() const;
202
203   /// GenVariableName - Returns the variable name used in the
204   /// generated C++ code.
205   std::string GenVariableName() const;
206
207   /// Merge - Merge two option descriptions.
208   void Merge (const OptionDescription& other);
209
210   // Misc convenient getters/setters.
211
212   bool isAlias() const;
213
214   bool isMultiVal() const;
215
216   bool isExtern() const;
217   void setExtern();
218
219   bool isRequired() const;
220   void setRequired();
221
222   bool isOneOrMore() const;
223   void setOneOrMore();
224
225   bool isZeroOrOne() const;
226   void setZeroOrOne();
227
228   bool isHidden() const;
229   void setHidden();
230
231   bool isReallyHidden() const;
232   void setReallyHidden();
233
234   bool isParameter() const
235   { return OptionType::IsParameter(this->Type); }
236
237   bool isSwitch() const
238   { return OptionType::IsSwitch(this->Type); }
239
240   bool isList() const
241   { return OptionType::IsList(this->Type); }
242
243 };
244
245 void OptionDescription::Merge (const OptionDescription& other)
246 {
247   if (other.Type != Type)
248     throw "Conflicting definitions for the option " + Name + "!";
249
250   if (Help == other.Help || Help == DefaultHelpString)
251     Help = other.Help;
252   else if (other.Help != DefaultHelpString) {
253     llvm::errs() << "Warning: several different help strings"
254       " defined for option " + Name + "\n";
255   }
256
257   Flags |= other.Flags;
258 }
259
260 bool OptionDescription::isAlias() const {
261   return Type == OptionType::Alias;
262 }
263
264 bool OptionDescription::isMultiVal() const {
265   return MultiVal > 1;
266 }
267
268 bool OptionDescription::isExtern() const {
269   return Flags & OptionDescriptionFlags::Extern;
270 }
271 void OptionDescription::setExtern() {
272   Flags |= OptionDescriptionFlags::Extern;
273 }
274
275 bool OptionDescription::isRequired() const {
276   return Flags & OptionDescriptionFlags::Required;
277 }
278 void OptionDescription::setRequired() {
279   Flags |= OptionDescriptionFlags::Required;
280 }
281
282 bool OptionDescription::isOneOrMore() const {
283   return Flags & OptionDescriptionFlags::OneOrMore;
284 }
285 void OptionDescription::setOneOrMore() {
286   Flags |= OptionDescriptionFlags::OneOrMore;
287 }
288
289 bool OptionDescription::isZeroOrOne() const {
290   return Flags & OptionDescriptionFlags::ZeroOrOne;
291 }
292 void OptionDescription::setZeroOrOne() {
293   Flags |= OptionDescriptionFlags::ZeroOrOne;
294 }
295
296 bool OptionDescription::isHidden() const {
297   return Flags & OptionDescriptionFlags::Hidden;
298 }
299 void OptionDescription::setHidden() {
300   Flags |= OptionDescriptionFlags::Hidden;
301 }
302
303 bool OptionDescription::isReallyHidden() const {
304   return Flags & OptionDescriptionFlags::ReallyHidden;
305 }
306 void OptionDescription::setReallyHidden() {
307   Flags |= OptionDescriptionFlags::ReallyHidden;
308 }
309
310 const char* OptionDescription::GenTypeDeclaration() const {
311   switch (Type) {
312   case OptionType::Alias:
313     return "cl::alias";
314   case OptionType::PrefixList:
315   case OptionType::ParameterList:
316     return "cl::list<std::string>";
317   case OptionType::Switch:
318     return "cl::opt<bool>";
319   case OptionType::Parameter:
320   case OptionType::Prefix:
321   default:
322     return "cl::opt<std::string>";
323   }
324 }
325
326 std::string OptionDescription::GenVariableName() const {
327   const std::string& EscapedName = EscapeVariableName(Name);
328   switch (Type) {
329   case OptionType::Alias:
330     return "AutoGeneratedAlias_" + EscapedName;
331   case OptionType::PrefixList:
332   case OptionType::ParameterList:
333     return "AutoGeneratedList_" + EscapedName;
334   case OptionType::Switch:
335     return "AutoGeneratedSwitch_" + EscapedName;
336   case OptionType::Prefix:
337   case OptionType::Parameter:
338   default:
339     return "AutoGeneratedParameter_" + EscapedName;
340   }
341 }
342
343 /// OptionDescriptions - An OptionDescription array plus some helper
344 /// functions.
345 class OptionDescriptions {
346   typedef StringMap<OptionDescription> container_type;
347
348   /// Descriptions - A list of OptionDescriptions.
349   container_type Descriptions;
350
351 public:
352   /// FindOption - exception-throwing wrapper for find().
353   const OptionDescription& FindOption(const std::string& OptName) const;
354   /// FindSwitch - wrapper for FindOption that throws in case the option is not
355   /// a switch.
356   const OptionDescription& FindSwitch(const std::string& OptName) const;
357
358   /// insertDescription - Insert new OptionDescription into
359   /// OptionDescriptions list
360   void InsertDescription (const OptionDescription& o);
361
362   // Support for STL-style iteration
363   typedef container_type::const_iterator const_iterator;
364   const_iterator begin() const { return Descriptions.begin(); }
365   const_iterator end() const { return Descriptions.end(); }
366 };
367
368 const OptionDescription&
369 OptionDescriptions::FindOption(const std::string& OptName) const
370 {
371   const_iterator I = Descriptions.find(OptName);
372   if (I != Descriptions.end())
373     return I->second;
374   else
375     throw OptName + ": no such option!";
376 }
377
378 const OptionDescription&
379 OptionDescriptions::FindSwitch(const std::string& OptName) const
380 {
381   const OptionDescription& OptDesc = this->FindOption(OptName);
382   if (!OptDesc.isSwitch())
383     throw OptName + ": incorrect option type - should be a switch!";
384   return OptDesc;
385 }
386
387 void OptionDescriptions::InsertDescription (const OptionDescription& o)
388 {
389   container_type::iterator I = Descriptions.find(o.Name);
390   if (I != Descriptions.end()) {
391     OptionDescription& D = I->second;
392     D.Merge(o);
393   }
394   else {
395     Descriptions[o.Name] = o;
396   }
397 }
398
399 /// HandlerTable - A base class for function objects implemented as
400 /// 'tables of handlers'.
401 template <class T>
402 class HandlerTable {
403 protected:
404   // Implementation details.
405
406   /// Handler -
407   typedef void (T::* Handler) (const DagInit*);
408   /// HandlerMap - A map from property names to property handlers
409   typedef StringMap<Handler> HandlerMap;
410
411   static HandlerMap Handlers_;
412   static bool staticMembersInitialized_;
413
414   T* childPtr;
415 public:
416
417   HandlerTable(T* cp) : childPtr(cp)
418   {}
419
420   /// operator() - Just forwards to the corresponding property
421   /// handler.
422   void operator() (Init* i) {
423     const DagInit& property = InitPtrToDag(i);
424     const std::string& property_name = property.getOperator()->getAsString();
425     typename HandlerMap::iterator method = Handlers_.find(property_name);
426
427     if (method != Handlers_.end()) {
428       Handler h = method->second;
429       (childPtr->*h)(&property);
430     }
431     else {
432       throw "No handler found for property " + property_name + "!";
433     }
434   }
435
436   void AddHandler(const char* Property, Handler Handl) {
437     Handlers_[Property] = Handl;
438   }
439 };
440
441 template <class T> typename HandlerTable<T>::HandlerMap
442 HandlerTable<T>::Handlers_;
443 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
444
445
446 /// CollectOptionProperties - Function object for iterating over an
447 /// option property list.
448 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
449 private:
450
451   /// optDescs_ - OptionDescriptions table. This is where the
452   /// information is stored.
453   OptionDescription& optDesc_;
454
455 public:
456
457   explicit CollectOptionProperties(OptionDescription& OD)
458     : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
459   {
460     if (!staticMembersInitialized_) {
461       AddHandler("extern", &CollectOptionProperties::onExtern);
462       AddHandler("help", &CollectOptionProperties::onHelp);
463       AddHandler("hidden", &CollectOptionProperties::onHidden);
464       AddHandler("init", &CollectOptionProperties::onInit);
465       AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
466       AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
467       AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
468       AddHandler("required", &CollectOptionProperties::onRequired);
469       AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
470
471       staticMembersInitialized_ = true;
472     }
473   }
474
475 private:
476
477   /// Option property handlers --
478   /// Methods that handle option properties such as (help) or (hidden).
479
480   void onExtern (const DagInit* d) {
481     checkNumberOfArguments(d, 0);
482     optDesc_.setExtern();
483   }
484
485   void onHelp (const DagInit* d) {
486     checkNumberOfArguments(d, 1);
487     optDesc_.Help = InitPtrToString(d->getArg(0));
488   }
489
490   void onHidden (const DagInit* d) {
491     checkNumberOfArguments(d, 0);
492     optDesc_.setHidden();
493   }
494
495   void onReallyHidden (const DagInit* d) {
496     checkNumberOfArguments(d, 0);
497     optDesc_.setReallyHidden();
498   }
499
500   void onRequired (const DagInit* d) {
501     checkNumberOfArguments(d, 0);
502     if (optDesc_.isOneOrMore())
503       throw std::string("An option can't have both (required) "
504                         "and (one_or_more) properties!");
505     optDesc_.setRequired();
506   }
507
508   void onInit (const DagInit* d) {
509     checkNumberOfArguments(d, 1);
510     Init* i = d->getArg(0);
511     const std::string& str = i->getAsString();
512
513     bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
514     correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
515
516     if (!correct)
517       throw std::string("Incorrect usage of the 'init' option property!");
518
519     optDesc_.InitVal = i;
520   }
521
522   void onOneOrMore (const DagInit* d) {
523     checkNumberOfArguments(d, 0);
524     if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
525       throw std::string("Only one of (required), (zero_or_one) or "
526                         "(one_or_more) properties is allowed!");
527     if (!OptionType::IsList(optDesc_.Type))
528       llvm::errs() << "Warning: specifying the 'one_or_more' property "
529         "on a non-list option will have no effect.\n";
530     optDesc_.setOneOrMore();
531   }
532
533   void onZeroOrOne (const DagInit* d) {
534     checkNumberOfArguments(d, 0);
535     if (optDesc_.isRequired() || optDesc_.isOneOrMore())
536       throw std::string("Only one of (required), (zero_or_one) or "
537                         "(one_or_more) properties is allowed!");
538     if (!OptionType::IsList(optDesc_.Type))
539       llvm::errs() << "Warning: specifying the 'zero_or_one' property"
540         "on a non-list option will have no effect.\n";
541     optDesc_.setZeroOrOne();
542   }
543
544   void onMultiVal (const DagInit* d) {
545     checkNumberOfArguments(d, 1);
546     int val = InitPtrToInt(d->getArg(0));
547     if (val < 2)
548       throw std::string("Error in the 'multi_val' property: "
549                         "the value must be greater than 1!");
550     if (!OptionType::IsList(optDesc_.Type))
551       throw std::string("The multi_val property is valid only "
552                         "on list options!");
553     optDesc_.MultiVal = val;
554   }
555
556 };
557
558 /// AddOption - A function object that is applied to every option
559 /// description. Used by CollectOptionDescriptions.
560 class AddOption {
561 private:
562   OptionDescriptions& OptDescs_;
563
564 public:
565   explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
566   {}
567
568   void operator()(const Init* i) {
569     const DagInit& d = InitPtrToDag(i);
570     checkNumberOfArguments(&d, 1);
571
572     const OptionType::OptionType Type =
573       stringToOptionType(d.getOperator()->getAsString());
574     const std::string& Name = InitPtrToString(d.getArg(0));
575
576     OptionDescription OD(Type, Name);
577
578     if (!OD.isExtern())
579       checkNumberOfArguments(&d, 2);
580
581     if (OD.isAlias()) {
582       // Aliases store the aliased option name in the 'Help' field.
583       OD.Help = InitPtrToString(d.getArg(1));
584     }
585     else if (!OD.isExtern()) {
586       processOptionProperties(&d, OD);
587     }
588     OptDescs_.InsertDescription(OD);
589   }
590
591 private:
592   /// processOptionProperties - Go through the list of option
593   /// properties and call a corresponding handler for each.
594   static void processOptionProperties (const DagInit* d, OptionDescription& o) {
595     checkNumberOfArguments(d, 2);
596     DagInit::const_arg_iterator B = d->arg_begin();
597     // Skip the first argument: it's always the option name.
598     ++B;
599     std::for_each(B, d->arg_end(), CollectOptionProperties(o));
600   }
601
602 };
603
604 /// CollectOptionDescriptions - Collects option properties from all
605 /// OptionLists.
606 void CollectOptionDescriptions (RecordVector::const_iterator B,
607                                 RecordVector::const_iterator E,
608                                 OptionDescriptions& OptDescs)
609 {
610   // For every OptionList:
611   for (; B!=E; ++B) {
612     RecordVector::value_type T = *B;
613     // Throws an exception if the value does not exist.
614     ListInit* PropList = T->getValueAsListInit("options");
615
616     // For every option description in this list:
617     // collect the information and
618     std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
619   }
620 }
621
622 // Tool information record
623
624 namespace ToolFlags {
625   enum ToolFlags { Join = 0x1, Sink = 0x2 };
626 }
627
628 struct ToolDescription : public RefCountedBase<ToolDescription> {
629   std::string Name;
630   Init* CmdLine;
631   Init* Actions;
632   StrVector InLanguage;
633   std::string OutLanguage;
634   std::string OutputSuffix;
635   unsigned Flags;
636
637   // Various boolean properties
638   void setSink()      { Flags |= ToolFlags::Sink; }
639   bool isSink() const { return Flags & ToolFlags::Sink; }
640   void setJoin()      { Flags |= ToolFlags::Join; }
641   bool isJoin() const { return Flags & ToolFlags::Join; }
642
643   // Default ctor here is needed because StringMap can only store
644   // DefaultConstructible objects
645   ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
646   ToolDescription (const std::string& n)
647   : Name(n), CmdLine(0), Actions(0), Flags(0)
648   {}
649 };
650
651 /// ToolDescriptions - A list of Tool information records.
652 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
653
654
655 /// CollectToolProperties - Function object for iterating over a list of
656 /// tool property records.
657 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
658 private:
659
660   /// toolDesc_ - Properties of the current Tool. This is where the
661   /// information is stored.
662   ToolDescription& toolDesc_;
663
664 public:
665
666   explicit CollectToolProperties (ToolDescription& d)
667     : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
668   {
669     if (!staticMembersInitialized_) {
670
671       AddHandler("actions", &CollectToolProperties::onActions);
672       AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
673       AddHandler("in_language", &CollectToolProperties::onInLanguage);
674       AddHandler("join", &CollectToolProperties::onJoin);
675       AddHandler("out_language", &CollectToolProperties::onOutLanguage);
676       AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
677       AddHandler("sink", &CollectToolProperties::onSink);
678
679       staticMembersInitialized_ = true;
680     }
681   }
682
683 private:
684
685   /// Property handlers --
686   /// Functions that extract information about tool properties from
687   /// DAG representation.
688
689   void onActions (const DagInit* d) {
690     checkNumberOfArguments(d, 1);
691     Init* Case = d->getArg(0);
692     if (typeid(*Case) != typeid(DagInit) ||
693         static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
694       throw
695         std::string("The argument to (actions) should be a 'case' construct!");
696     toolDesc_.Actions = Case;
697   }
698
699   void onCmdLine (const DagInit* d) {
700     checkNumberOfArguments(d, 1);
701     toolDesc_.CmdLine = d->getArg(0);
702   }
703
704   void onInLanguage (const DagInit* d) {
705     checkNumberOfArguments(d, 1);
706     Init* arg = d->getArg(0);
707
708     // Find out the argument's type.
709     if (typeid(*arg) == typeid(StringInit)) {
710       // It's a string.
711       toolDesc_.InLanguage.push_back(InitPtrToString(arg));
712     }
713     else {
714       // It's a list.
715       const ListInit& lst = InitPtrToList(arg);
716       StrVector& out = toolDesc_.InLanguage;
717
718       // Copy strings to the output vector.
719       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
720            B != E; ++B) {
721         out.push_back(InitPtrToString(*B));
722       }
723
724       // Remove duplicates.
725       std::sort(out.begin(), out.end());
726       StrVector::iterator newE = std::unique(out.begin(), out.end());
727       out.erase(newE, out.end());
728     }
729   }
730
731   void onJoin (const DagInit* d) {
732     checkNumberOfArguments(d, 0);
733     toolDesc_.setJoin();
734   }
735
736   void onOutLanguage (const DagInit* d) {
737     checkNumberOfArguments(d, 1);
738     toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
739   }
740
741   void onOutputSuffix (const DagInit* d) {
742     checkNumberOfArguments(d, 1);
743     toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
744   }
745
746   void onSink (const DagInit* d) {
747     checkNumberOfArguments(d, 0);
748     toolDesc_.setSink();
749   }
750
751 };
752
753 /// CollectToolDescriptions - Gather information about tool properties
754 /// from the parsed TableGen data (basically a wrapper for the
755 /// CollectToolProperties function object).
756 void CollectToolDescriptions (RecordVector::const_iterator B,
757                               RecordVector::const_iterator E,
758                               ToolDescriptions& ToolDescs)
759 {
760   // Iterate over a properties list of every Tool definition
761   for (;B!=E;++B) {
762     const Record* T = *B;
763     // Throws an exception if the value does not exist.
764     ListInit* PropList = T->getValueAsListInit("properties");
765
766     IntrusiveRefCntPtr<ToolDescription>
767       ToolDesc(new ToolDescription(T->getName()));
768
769     std::for_each(PropList->begin(), PropList->end(),
770                   CollectToolProperties(*ToolDesc));
771     ToolDescs.push_back(ToolDesc);
772   }
773 }
774
775 /// FillInEdgeVector - Merge all compilation graph definitions into
776 /// one single edge list.
777 void FillInEdgeVector(RecordVector::const_iterator B,
778                       RecordVector::const_iterator E, RecordVector& Out) {
779   for (; B != E; ++B) {
780     const ListInit* edges = (*B)->getValueAsListInit("edges");
781
782     for (unsigned i = 0; i < edges->size(); ++i)
783       Out.push_back(edges->getElementAsRecord(i));
784   }
785 }
786
787 /// CalculatePriority - Calculate the priority of this plugin.
788 int CalculatePriority(RecordVector::const_iterator B,
789                       RecordVector::const_iterator E) {
790   int priority = 0;
791
792   if (B != E) {
793     priority  = static_cast<int>((*B)->getValueAsInt("priority"));
794
795     if (++B != E)
796       throw std::string("More than one 'PluginPriority' instance found: "
797                         "most probably an error!");
798   }
799
800   return priority;
801 }
802
803 /// NotInGraph - Helper function object for FilterNotInGraph.
804 struct NotInGraph {
805 private:
806   const llvm::StringSet<>& ToolsInGraph_;
807
808 public:
809   NotInGraph(const llvm::StringSet<>& ToolsInGraph)
810   : ToolsInGraph_(ToolsInGraph)
811   {}
812
813   bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
814     return (ToolsInGraph_.count(x->Name) == 0);
815   }
816 };
817
818 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
819 /// mentioned in the compilation graph definition.
820 void FilterNotInGraph (const RecordVector& EdgeVector,
821                        ToolDescriptions& ToolDescs) {
822
823   // List all tools mentioned in the graph.
824   llvm::StringSet<> ToolsInGraph;
825
826   for (RecordVector::const_iterator B = EdgeVector.begin(),
827          E = EdgeVector.end(); B != E; ++B) {
828
829     const Record* Edge = *B;
830     const std::string& NodeA = Edge->getValueAsString("a");
831     const std::string& NodeB = Edge->getValueAsString("b");
832
833     if (NodeA != "root")
834       ToolsInGraph.insert(NodeA);
835     ToolsInGraph.insert(NodeB);
836   }
837
838   // Filter ToolPropertiesList.
839   ToolDescriptions::iterator new_end =
840     std::remove_if(ToolDescs.begin(), ToolDescs.end(),
841                    NotInGraph(ToolsInGraph));
842   ToolDescs.erase(new_end, ToolDescs.end());
843 }
844
845 /// FillInToolToLang - Fills in two tables that map tool names to
846 /// (input, output) languages.  Helper function used by TypecheckGraph().
847 void FillInToolToLang (const ToolDescriptions& ToolDescs,
848                        StringMap<StringSet<> >& ToolToInLang,
849                        StringMap<std::string>& ToolToOutLang) {
850   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
851          E = ToolDescs.end(); B != E; ++B) {
852     const ToolDescription& D = *(*B);
853     for (StrVector::const_iterator B = D.InLanguage.begin(),
854            E = D.InLanguage.end(); B != E; ++B)
855       ToolToInLang[D.Name].insert(*B);
856     ToolToOutLang[D.Name] = D.OutLanguage;
857   }
858 }
859
860 /// TypecheckGraph - Check that names for output and input languages
861 /// on all edges do match. This doesn't do much when the information
862 /// about the whole graph is not available (i.e. when compiling most
863 /// plugins).
864 void TypecheckGraph (const RecordVector& EdgeVector,
865                      const ToolDescriptions& ToolDescs) {
866   StringMap<StringSet<> > ToolToInLang;
867   StringMap<std::string> ToolToOutLang;
868
869   FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
870   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
871   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
872
873   for (RecordVector::const_iterator B = EdgeVector.begin(),
874          E = EdgeVector.end(); B != E; ++B) {
875     const Record* Edge = *B;
876     const std::string& NodeA = Edge->getValueAsString("a");
877     const std::string& NodeB = Edge->getValueAsString("b");
878     StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
879     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
880
881     if (NodeA != "root") {
882       if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
883         throw "Edge " + NodeA + "->" + NodeB
884           + ": output->input language mismatch";
885     }
886
887     if (NodeB == "root")
888       throw std::string("Edges back to the root are not allowed!");
889   }
890 }
891
892 /// WalkCase - Walks the 'case' expression DAG and invokes
893 /// TestCallback on every test, and StatementCallback on every
894 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
895 /// combinators.
896 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
897 template <typename F1, typename F2>
898 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
899   const DagInit& d = InitPtrToDag(Case);
900   bool even = false;
901   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
902        B != E; ++B) {
903     Init* arg = *B;
904     if (even && dynamic_cast<DagInit*>(arg)
905         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
906       WalkCase(arg, TestCallback, StatementCallback);
907     else if (!even)
908       TestCallback(arg);
909     else
910       StatementCallback(arg);
911     even = !even;
912   }
913 }
914
915 /// ExtractOptionNames - A helper function object used by
916 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
917 class ExtractOptionNames {
918   llvm::StringSet<>& OptionNames_;
919
920   void processDag(const Init* Statement) {
921     const DagInit& Stmt = InitPtrToDag(Statement);
922     const std::string& ActionName = Stmt.getOperator()->getAsString();
923     if (ActionName == "forward" || ActionName == "forward_as" ||
924         ActionName == "unpack_values" || ActionName == "switch_on" ||
925         ActionName == "parameter_equals" || ActionName == "element_in_list" ||
926         ActionName == "not_empty" || ActionName == "empty") {
927       checkNumberOfArguments(&Stmt, 1);
928       const std::string& Name = InitPtrToString(Stmt.getArg(0));
929       OptionNames_.insert(Name);
930     }
931     else if (ActionName == "and" || ActionName == "or") {
932       for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
933         this->processDag(Stmt.getArg(i));
934       }
935     }
936   }
937
938 public:
939   ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
940   {}
941
942   void operator()(const Init* Statement) {
943     if (typeid(*Statement) == typeid(ListInit)) {
944       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
945       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
946            B != E; ++B)
947         this->processDag(*B);
948     }
949     else {
950       this->processDag(Statement);
951     }
952   }
953 };
954
955 /// CheckForSuperfluousOptions - Check that there are no side
956 /// effect-free options (specified only in the OptionList). Otherwise,
957 /// output a warning.
958 void CheckForSuperfluousOptions (const RecordVector& Edges,
959                                  const ToolDescriptions& ToolDescs,
960                                  const OptionDescriptions& OptDescs) {
961   llvm::StringSet<> nonSuperfluousOptions;
962
963   // Add all options mentioned in the ToolDesc.Actions to the set of
964   // non-superfluous options.
965   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
966          E = ToolDescs.end(); B != E; ++B) {
967     const ToolDescription& TD = *(*B);
968     ExtractOptionNames Callback(nonSuperfluousOptions);
969     if (TD.Actions)
970       WalkCase(TD.Actions, Callback, Callback);
971   }
972
973   // Add all options mentioned in the 'case' clauses of the
974   // OptionalEdges of the compilation graph to the set of
975   // non-superfluous options.
976   for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
977        B != E; ++B) {
978     const Record* Edge = *B;
979     DagInit* Weight = Edge->getValueAsDag("weight");
980
981     if (!isDagEmpty(Weight))
982       WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
983   }
984
985   // Check that all options in OptDescs belong to the set of
986   // non-superfluous options.
987   for (OptionDescriptions::const_iterator B = OptDescs.begin(),
988          E = OptDescs.end(); B != E; ++B) {
989     const OptionDescription& Val = B->second;
990     if (!nonSuperfluousOptions.count(Val.Name)
991         && Val.Type != OptionType::Alias)
992       llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
993         "Probable cause: this option is specified only in the OptionList.\n";
994   }
995 }
996
997 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
998 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
999   if (TestName == "single_input_file") {
1000     O << "InputFilenames.size() == 1";
1001     return true;
1002   }
1003   else if (TestName == "multiple_input_files") {
1004     O << "InputFilenames.size() > 1";
1005     return true;
1006   }
1007
1008   return false;
1009 }
1010
1011 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1012 bool EmitCaseTest1ArgStr(const std::string& TestName,
1013                          const DagInit& d,
1014                          const OptionDescriptions& OptDescs,
1015                          raw_ostream& O) {
1016   const std::string& OptName = InitPtrToString(d.getArg(0));
1017
1018   if (TestName == "switch_on") {
1019     const OptionDescription& OptDesc = OptDescs.FindSwitch(OptName);
1020     O << OptDesc.GenVariableName();
1021     return true;
1022   }
1023   else if (TestName == "input_languages_contain") {
1024     O << "InLangs.count(\"" << OptName << "\") != 0";
1025     return true;
1026   }
1027   else if (TestName == "in_language") {
1028     // This works only for single-argument Tool::GenerateAction. Join
1029     // tools can process several files in different languages simultaneously.
1030
1031     // TODO: make this work with Edge::Weight (if possible).
1032     O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1033     return true;
1034   }
1035   else if (TestName == "not_empty" || TestName == "empty") {
1036     const char* Test = (TestName == "empty") ? "" : "!";
1037
1038     if (OptName == "o") {
1039       O << Test << "OutputFilename.empty()";
1040       return true;
1041     }
1042     else {
1043       const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1044       if (OptDesc.isSwitch())
1045         throw OptName
1046           + ": incorrect option type - should be a list or parameter!";
1047       O << Test << OptDesc.GenVariableName() << ".empty()";
1048       return true;
1049     }
1050   }
1051
1052   return false;
1053 }
1054
1055 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1056 bool EmitCaseTest1ArgList(const std::string& TestName,
1057                           const DagInit& d,
1058                           const OptionDescriptions& OptDescs,
1059                           raw_ostream& O) {
1060   const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1061
1062   if (TestName == "any_switch_on") {
1063     bool isFirst = true;
1064
1065     for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1066       const std::string& OptName = InitPtrToString(*B);
1067       const OptionDescription& OptDesc = OptDescs.FindSwitch(OptName);
1068
1069       if (isFirst)
1070         isFirst = false;
1071       else
1072         O << " || ";
1073       O << OptDesc.GenVariableName();
1074     }
1075
1076     return true;
1077   }
1078
1079   // TODO: implement any_not_empty, any_empty, switch_on [..], empty [..]
1080
1081   return false;
1082 }
1083
1084 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1085 bool EmitCaseTest1Arg(const std::string& TestName,
1086                       const DagInit& d,
1087                       const OptionDescriptions& OptDescs,
1088                       raw_ostream& O) {
1089   checkNumberOfArguments(&d, 1);
1090   if (typeid(*d.getArg(0)) == typeid(ListInit))
1091     return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1092   else
1093     return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1094 }
1095
1096 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1097 bool EmitCaseTest2Args(const std::string& TestName,
1098                        const DagInit& d,
1099                        unsigned IndentLevel,
1100                        const OptionDescriptions& OptDescs,
1101                        raw_ostream& O) {
1102   checkNumberOfArguments(&d, 2);
1103   const std::string& OptName = InitPtrToString(d.getArg(0));
1104   const std::string& OptArg = InitPtrToString(d.getArg(1));
1105   const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1106
1107   if (TestName == "parameter_equals") {
1108     if (!OptDesc.isParameter())
1109       throw OptName + ": incorrect option type - should be a parameter!";
1110     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1111     return true;
1112   }
1113   else if (TestName == "element_in_list") {
1114     if (!OptDesc.isList())
1115       throw OptName + ": incorrect option type - should be a list!";
1116     const std::string& VarName = OptDesc.GenVariableName();
1117     O << "std::find(" << VarName << ".begin(),\n";
1118     O.indent(IndentLevel + Indent1)
1119       << VarName << ".end(), \""
1120       << OptArg << "\") != " << VarName << ".end()";
1121     return true;
1122   }
1123
1124   return false;
1125 }
1126
1127 // Forward declaration.
1128 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1129 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1130                   const OptionDescriptions& OptDescs,
1131                   raw_ostream& O);
1132
1133 /// EmitLogicalOperationTest - Helper function used by
1134 /// EmitCaseConstructHandler.
1135 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1136                               unsigned IndentLevel,
1137                               const OptionDescriptions& OptDescs,
1138                               raw_ostream& O) {
1139   O << '(';
1140   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1141     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1142     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1143     if (j != NumArgs - 1) {
1144       O << ")\n";
1145       O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1146     }
1147     else {
1148       O << ')';
1149     }
1150   }
1151 }
1152
1153 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1154                     const OptionDescriptions& OptDescs, raw_ostream& O)
1155 {
1156   checkNumberOfArguments(&d, 1);
1157   const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1158   O << "! (";
1159   EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1160   O << ")";
1161 }
1162
1163 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1164 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1165                   const OptionDescriptions& OptDescs,
1166                   raw_ostream& O) {
1167   const std::string& TestName = d.getOperator()->getAsString();
1168
1169   if (TestName == "and")
1170     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1171   else if (TestName == "or")
1172     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1173   else if (TestName == "not")
1174     EmitLogicalNot(d, IndentLevel, OptDescs, O);
1175   else if (EmitCaseTest0Args(TestName, O))
1176     return;
1177   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1178     return;
1179   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1180     return;
1181   else
1182     throw TestName + ": unknown edge property!";
1183 }
1184
1185 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1186 /// construct. Takes a function object that should emit code for every case
1187 /// clause.
1188 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1189 /// raw_ostream& O).
1190 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1191 /// (..) {...} else if (...) {} ... else {...}' vs. 'if (..)  {...} if(...)
1192 /// {...} ...').
1193 template <typename F>
1194 void EmitCaseConstructHandler(const Init* Dag, unsigned IndentLevel,
1195                               F Callback, bool EmitElseIf,
1196                               const OptionDescriptions& OptDescs,
1197                               raw_ostream& O) {
1198   const DagInit* d = &InitPtrToDag(Dag);
1199   if (d->getOperator()->getAsString() != "case")
1200     throw std::string("EmitCaseConstructHandler should be invoked"
1201                       " only on 'case' expressions!");
1202
1203   unsigned numArgs = d->getNumArgs();
1204   if (d->getNumArgs() < 2)
1205     throw "There should be at least one clause in the 'case' expression:\n"
1206       + d->getAsString();
1207
1208   for (unsigned i = 0; i != numArgs; ++i) {
1209     const DagInit& Test = InitPtrToDag(d->getArg(i));
1210
1211     // Emit the test.
1212     if (Test.getOperator()->getAsString() == "default") {
1213       if (i+2 != numArgs)
1214         throw std::string("The 'default' clause should be the last in the"
1215                           "'case' construct!");
1216       O.indent(IndentLevel) << "else {\n";
1217     }
1218     else {
1219       O.indent(IndentLevel) << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1220       EmitCaseTest(Test, IndentLevel, OptDescs, O);
1221       O << ") {\n";
1222     }
1223
1224     // Emit the corresponding statement.
1225     ++i;
1226     if (i == numArgs)
1227       throw "Case construct handler: no corresponding action "
1228         "found for the test " + Test.getAsString() + '!';
1229
1230     Init* arg = d->getArg(i);
1231     const DagInit* nd = dynamic_cast<DagInit*>(arg);
1232     if (nd && (nd->getOperator()->getAsString() == "case")) {
1233       // Handle the nested 'case'.
1234       EmitCaseConstructHandler(nd, (IndentLevel + Indent1),
1235                                Callback, EmitElseIf, OptDescs, O);
1236     }
1237     else {
1238       Callback(arg, (IndentLevel + Indent1), O);
1239     }
1240     O.indent(IndentLevel) << "}\n";
1241   }
1242 }
1243
1244 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1245 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1246 /// Helper function used by EmitCmdLineVecFill and.
1247 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1248   const char* Delimiters = " \t\n\v\f\r";
1249   enum TokenizerState
1250   { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1251   cur_st  = Normal;
1252
1253   if (CmdLine.empty())
1254     return;
1255   Out.push_back("");
1256
1257   std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1258     E = CmdLine.size();
1259
1260   for (; B != E; ++B) {
1261     char cur_ch = CmdLine[B];
1262
1263     switch (cur_st) {
1264     case Normal:
1265       if (cur_ch == '$') {
1266         cur_st = SpecialCommand;
1267         break;
1268       }
1269       if (oneOf(Delimiters, cur_ch)) {
1270         // Skip whitespace
1271         B = CmdLine.find_first_not_of(Delimiters, B);
1272         if (B == std::string::npos) {
1273           B = E-1;
1274           continue;
1275         }
1276         --B;
1277         Out.push_back("");
1278         continue;
1279       }
1280       break;
1281
1282
1283     case SpecialCommand:
1284       if (oneOf(Delimiters, cur_ch)) {
1285         cur_st = Normal;
1286         Out.push_back("");
1287         continue;
1288       }
1289       if (cur_ch == '(') {
1290         Out.push_back("");
1291         cur_st = InsideSpecialCommand;
1292         continue;
1293       }
1294       break;
1295
1296     case InsideSpecialCommand:
1297       if (oneOf(Delimiters, cur_ch)) {
1298         continue;
1299       }
1300       if (cur_ch == '\'') {
1301         cur_st = InsideQuotationMarks;
1302         Out.push_back("");
1303         continue;
1304       }
1305       if (cur_ch == ')') {
1306         cur_st = Normal;
1307         Out.push_back("");
1308       }
1309       if (cur_ch == ',') {
1310         continue;
1311       }
1312
1313       break;
1314
1315     case InsideQuotationMarks:
1316       if (cur_ch == '\'') {
1317         cur_st = InsideSpecialCommand;
1318         continue;
1319       }
1320       break;
1321     }
1322
1323     Out.back().push_back(cur_ch);
1324   }
1325 }
1326
1327 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1328 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1329 StrVector::const_iterator SubstituteSpecialCommands
1330 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1331 {
1332
1333   const std::string& cmd = *Pos;
1334
1335   if (cmd == "$CALL") {
1336     checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1337     const std::string& CmdName = *Pos;
1338
1339     if (CmdName == ")")
1340       throw std::string("$CALL invocation: empty argument list!");
1341
1342     O << "hooks::";
1343     O << CmdName << "(";
1344
1345
1346     bool firstIteration = true;
1347     while (true) {
1348       checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1349       const std::string& Arg = *Pos;
1350       assert(Arg.size() != 0);
1351
1352       if (Arg[0] == ')')
1353         break;
1354
1355       if (firstIteration)
1356         firstIteration = false;
1357       else
1358         O << ", ";
1359
1360       O << '"' << Arg << '"';
1361     }
1362
1363     O << ')';
1364
1365   }
1366   else if (cmd == "$ENV") {
1367     checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1368     const std::string& EnvName = *Pos;
1369
1370     if (EnvName == ")")
1371       throw "$ENV invocation: empty argument list!";
1372
1373     O << "checkCString(std::getenv(\"";
1374     O << EnvName;
1375     O << "\"))";
1376
1377     checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1378   }
1379   else {
1380     throw "Unknown special command: " + cmd;
1381   }
1382
1383   const std::string& Leftover = *Pos;
1384   assert(Leftover.at(0) == ')');
1385   if (Leftover.size() != 1)
1386     O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1387
1388   return Pos;
1389 }
1390
1391 /// EmitCmdLineVecFill - Emit code that fills in the command line
1392 /// vector. Helper function used by EmitGenerateActionMethod().
1393 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1394                         bool IsJoin, unsigned IndentLevel,
1395                         raw_ostream& O) {
1396   StrVector StrVec;
1397   TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1398
1399   if (StrVec.empty())
1400     throw "Tool '" + ToolName + "' has empty command line!";
1401
1402   StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1403
1404   // If there is a hook invocation on the place of the first command, skip it.
1405   assert(!StrVec[0].empty());
1406   if (StrVec[0][0] == '$') {
1407     while (I != E && (*I)[0] != ')' )
1408       ++I;
1409
1410     // Skip the ')' symbol.
1411     ++I;
1412   }
1413   else {
1414     ++I;
1415   }
1416
1417   bool hasINFILE = false;
1418
1419   for (; I != E; ++I) {
1420     const std::string& cmd = *I;
1421     assert(!cmd.empty());
1422     O.indent(IndentLevel);
1423     if (cmd.at(0) == '$') {
1424       if (cmd == "$INFILE") {
1425         hasINFILE = true;
1426         if (IsJoin) {
1427           O << "for (PathVector::const_iterator B = inFiles.begin()"
1428             << ", E = inFiles.end();\n";
1429           O.indent(IndentLevel) << "B != E; ++B)\n";
1430           O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1431         }
1432         else {
1433           O << "vec.push_back(inFile.str());\n";
1434         }
1435       }
1436       else if (cmd == "$OUTFILE") {
1437         O << "vec.push_back(\"\");\n";
1438         O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1439       }
1440       else {
1441         O << "vec.push_back(";
1442         I = SubstituteSpecialCommands(I, E, O);
1443         O << ");\n";
1444       }
1445     }
1446     else {
1447       O << "vec.push_back(\"" << cmd << "\");\n";
1448     }
1449   }
1450   if (!hasINFILE)
1451     throw "Tool '" + ToolName + "' doesn't take any input!";
1452
1453   O.indent(IndentLevel) << "cmd = ";
1454   if (StrVec[0][0] == '$')
1455     SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1456   else
1457     O << '"' << StrVec[0] << '"';
1458   O << ";\n";
1459 }
1460
1461 /// EmitCmdLineVecFillCallback - A function object wrapper around
1462 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1463 /// argument to EmitCaseConstructHandler().
1464 class EmitCmdLineVecFillCallback {
1465   bool IsJoin;
1466   const std::string& ToolName;
1467  public:
1468   EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1469     : IsJoin(J), ToolName(TN) {}
1470
1471   void operator()(const Init* Statement, unsigned IndentLevel,
1472                   raw_ostream& O) const
1473   {
1474     EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1475   }
1476 };
1477
1478 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1479 /// implement EmitActionHandler. Emits code for
1480 /// handling the (forward) and (forward_as) option properties.
1481 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1482                                             unsigned IndentLevel,
1483                                             const std::string& NewName,
1484                                             raw_ostream& O) {
1485   const std::string& Name = NewName.empty()
1486     ? ("-" + D.Name)
1487     : NewName;
1488   unsigned IndentLevel1 = IndentLevel + Indent1;
1489
1490   switch (D.Type) {
1491   case OptionType::Switch:
1492     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1493     break;
1494   case OptionType::Parameter:
1495     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1496     O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1497     break;
1498   case OptionType::Prefix:
1499     O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1500                           << D.GenVariableName() << ");\n";
1501     break;
1502   case OptionType::PrefixList:
1503     O.indent(IndentLevel)
1504       << "for (" << D.GenTypeDeclaration()
1505       << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1506     O.indent(IndentLevel)
1507       << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1508     O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1509     O.indent(IndentLevel1) << "++B;\n";
1510
1511     for (int i = 1, j = D.MultiVal; i < j; ++i) {
1512       O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1513       O.indent(IndentLevel1) << "++B;\n";
1514     }
1515
1516     O.indent(IndentLevel) << "}\n";
1517     break;
1518   case OptionType::ParameterList:
1519     O.indent(IndentLevel)
1520       << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1521       << D.GenVariableName() << ".begin(),\n";
1522     O.indent(IndentLevel) << "E = " << D.GenVariableName()
1523                           << ".end() ; B != E;) {\n";
1524     O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1525
1526     for (int i = 0, j = D.MultiVal; i < j; ++i) {
1527       O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1528       O.indent(IndentLevel1) << "++B;\n";
1529     }
1530
1531     O.indent(IndentLevel) << "}\n";
1532     break;
1533   case OptionType::Alias:
1534   default:
1535     throw std::string("Aliases are not allowed in tool option descriptions!");
1536   }
1537 }
1538
1539 /// EmitActionHandler - Emit code that handles actions. Used by
1540 /// EmitGenerateActionMethod() as an argument to
1541 /// EmitCaseConstructHandler().
1542 class EmitActionHandler {
1543   const OptionDescriptions& OptDescs;
1544
1545   void processActionDag(const Init* Statement, unsigned IndentLevel,
1546                         raw_ostream& O) const
1547   {
1548     const DagInit& Dag = InitPtrToDag(Statement);
1549     const std::string& ActionName = Dag.getOperator()->getAsString();
1550
1551     if (ActionName == "append_cmd") {
1552       checkNumberOfArguments(&Dag, 1);
1553       const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1554       StrVector Out;
1555       llvm::SplitString(Cmd, Out);
1556
1557       for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1558            B != E; ++B)
1559         O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1560     }
1561     else if (ActionName == "error") {
1562       O.indent(IndentLevel) << "throw std::runtime_error(\"" <<
1563         (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1564          : "Unknown error!")
1565         << "\");\n";
1566     }
1567     else if (ActionName == "forward") {
1568       checkNumberOfArguments(&Dag, 1);
1569       const std::string& Name = InitPtrToString(Dag.getArg(0));
1570       EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1571                                             IndentLevel, "", O);
1572     }
1573     else if (ActionName == "forward_as") {
1574       checkNumberOfArguments(&Dag, 2);
1575       const std::string& Name = InitPtrToString(Dag.getArg(0));
1576       const std::string& NewName = InitPtrToString(Dag.getArg(1));
1577       EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1578                                             IndentLevel, NewName, O);
1579     }
1580     else if (ActionName == "output_suffix") {
1581       checkNumberOfArguments(&Dag, 1);
1582       const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1583       O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1584     }
1585     else if (ActionName == "stop_compilation") {
1586       O.indent(IndentLevel) << "stop_compilation = true;\n";
1587     }
1588     else if (ActionName == "unpack_values") {
1589       checkNumberOfArguments(&Dag, 1);
1590       const std::string& Name = InitPtrToString(Dag.getArg(0));
1591       const OptionDescription& D = OptDescs.FindOption(Name);
1592
1593       if (D.isMultiVal())
1594         throw std::string("Can't use unpack_values with multi-valued options!");
1595
1596       if (D.isList()) {
1597         O.indent(IndentLevel)
1598           << "for (" << D.GenTypeDeclaration()
1599           << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1600         O.indent(IndentLevel)
1601           << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n";
1602         O.indent(IndentLevel + Indent1)
1603           << "llvm::SplitString(*B, vec, \",\");\n";
1604       }
1605       else if (D.isParameter()){
1606         O.indent(IndentLevel) << "llvm::SplitString("
1607                               << D.GenVariableName() << ", vec, \",\");\n";
1608       }
1609       else {
1610         throw "Option '" + D.Name +
1611           "': switches can't have the 'unpack_values' property!";
1612       }
1613     }
1614     else {
1615       throw "Unknown action name: " + ActionName + "!";
1616     }
1617   }
1618  public:
1619   EmitActionHandler(const OptionDescriptions& OD)
1620     : OptDescs(OD) {}
1621
1622   void operator()(const Init* Statement, unsigned IndentLevel,
1623                   raw_ostream& O) const
1624   {
1625     if (typeid(*Statement) == typeid(ListInit)) {
1626       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1627       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1628            B != E; ++B)
1629         this->processActionDag(*B, IndentLevel, O);
1630     }
1631     else {
1632       this->processActionDag(Statement, IndentLevel, O);
1633     }
1634   }
1635 };
1636
1637 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1638   StrVector StrVec;
1639   TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1640
1641   for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1642        I != E; ++I) {
1643     if (*I == "$OUTFILE")
1644       return false;
1645   }
1646
1647   return true;
1648 }
1649
1650 class IsOutFileIndexCheckRequiredStrCallback {
1651   bool* ret_;
1652
1653 public:
1654   IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1655   {}
1656
1657   void operator()(const Init* CmdLine) {
1658     if (IsOutFileIndexCheckRequiredStr(CmdLine))
1659       *ret_ = true;
1660   }
1661 };
1662
1663 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1664   bool ret = false;
1665   WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1666   return ret;
1667 }
1668
1669 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1670 /// in EmitGenerateActionMethod() ?
1671 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1672   if (typeid(*CmdLine) == typeid(StringInit))
1673     return IsOutFileIndexCheckRequiredStr(CmdLine);
1674   else
1675     return IsOutFileIndexCheckRequiredCase(CmdLine);
1676 }
1677
1678 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
1679 // Tool::GenerateAction() method.
1680 void EmitGenerateActionMethod (const ToolDescription& D,
1681                                const OptionDescriptions& OptDescs,
1682                                bool IsJoin, raw_ostream& O) {
1683   if (IsJoin)
1684     O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1685   else
1686     O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1687
1688   O.indent(Indent2) << "bool HasChildren,\n";
1689   O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1690   O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1691   O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1692   O.indent(Indent1) << "{\n";
1693   O.indent(Indent2) << "std::string cmd;\n";
1694   O.indent(Indent2) << "std::vector<std::string> vec;\n";
1695   O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1696   O.indent(Indent2) << "const char* output_suffix = \""
1697                     << D.OutputSuffix << "\";\n";
1698
1699   if (!D.CmdLine)
1700     throw "Tool " + D.Name + " has no cmd_line property!";
1701
1702   bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
1703   O.indent(Indent2) << "int out_file_index"
1704                     << (IndexCheckRequired ? " = -1" : "")
1705                     << ";\n\n";
1706
1707   // Process the cmd_line property.
1708   if (typeid(*D.CmdLine) == typeid(StringInit))
1709     EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1710   else
1711     EmitCaseConstructHandler(D.CmdLine, Indent2,
1712                              EmitCmdLineVecFillCallback(IsJoin, D.Name),
1713                              true, OptDescs, O);
1714
1715   // For every understood option, emit handling code.
1716   if (D.Actions)
1717     EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1718                              false, OptDescs, O);
1719
1720   O << '\n';
1721   O.indent(Indent2)
1722     << "std::string out_file = OutFilename("
1723     << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
1724   O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
1725
1726   if (IndexCheckRequired)
1727     O.indent(Indent2) << "if (out_file_index != -1)\n";
1728   O.indent(IndexCheckRequired ? Indent3 : Indent2)
1729     << "vec[out_file_index] = out_file;\n";
1730
1731   // Handle the Sink property.
1732   if (D.isSink()) {
1733     O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
1734     O.indent(Indent3) << "vec.insert(vec.end(), "
1735                       << SinkOptionName << ".begin(), " << SinkOptionName
1736                       << ".end());\n";
1737     O.indent(Indent2) << "}\n";
1738   }
1739
1740   O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
1741   O.indent(Indent1) << "}\n\n";
1742 }
1743
1744 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1745 /// a given Tool class.
1746 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1747                                 const OptionDescriptions& OptDescs,
1748                                 raw_ostream& O) {
1749   if (!ToolDesc.isJoin()) {
1750     O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1751     O.indent(Indent2) << "bool HasChildren,\n";
1752     O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1753     O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1754     O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1755     O.indent(Indent1) << "{\n";
1756     O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
1757                       << " is not a Join tool!\");\n";
1758     O.indent(Indent1) << "}\n\n";
1759   }
1760   else {
1761     EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1762   }
1763
1764   EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1765 }
1766
1767 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1768 /// methods for a given Tool class.
1769 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
1770   O.indent(Indent1) << "const char** InputLanguages() const {\n";
1771   O.indent(Indent2) << "return InputLanguages_;\n";
1772   O.indent(Indent1) << "}\n\n";
1773
1774   if (D.OutLanguage.empty())
1775     throw "Tool " + D.Name + " has no 'out_language' property!";
1776
1777   O.indent(Indent1) << "const char* OutputLanguage() const {\n";
1778   O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
1779   O.indent(Indent1) << "}\n\n";
1780 }
1781
1782 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1783 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
1784   O.indent(Indent1) << "const char* Name() const {\n";
1785   O.indent(Indent2) << "return \"" << D.Name << "\";\n";
1786   O.indent(Indent1) << "}\n\n";
1787 }
1788
1789 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1790 /// class.
1791 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
1792   O.indent(Indent1) << "bool IsJoin() const {\n";
1793   if (D.isJoin())
1794     O.indent(Indent2) << "return true;\n";
1795   else
1796     O.indent(Indent2) << "return false;\n";
1797   O.indent(Indent1) << "}\n\n";
1798 }
1799
1800 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1801 /// given Tool class.
1802 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
1803   if (D.InLanguage.empty())
1804     throw "Tool " + D.Name + " has no 'in_language' property!";
1805
1806   O << "const char* " << D.Name << "::InputLanguages_[] = {";
1807   for (StrVector::const_iterator B = D.InLanguage.begin(),
1808          E = D.InLanguage.end(); B != E; ++B)
1809     O << '\"' << *B << "\", ";
1810   O << "0};\n\n";
1811 }
1812
1813 /// EmitToolClassDefinition - Emit a Tool class definition.
1814 void EmitToolClassDefinition (const ToolDescription& D,
1815                               const OptionDescriptions& OptDescs,
1816                               raw_ostream& O) {
1817   if (D.Name == "root")
1818     return;
1819
1820   // Header
1821   O << "class " << D.Name << " : public ";
1822   if (D.isJoin())
1823     O << "JoinTool";
1824   else
1825     O << "Tool";
1826
1827   O << "{\nprivate:\n";
1828   O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
1829
1830   O << "public:\n";
1831   EmitNameMethod(D, O);
1832   EmitInOutLanguageMethods(D, O);
1833   EmitIsJoinMethod(D, O);
1834   EmitGenerateActionMethods(D, OptDescs, O);
1835
1836   // Close class definition
1837   O << "};\n";
1838
1839   EmitStaticMemberDefinitions(D, O);
1840
1841 }
1842
1843 /// EmitOptionDefinitions - Iterate over a list of option descriptions
1844 /// and emit registration code.
1845 void EmitOptionDefinitions (const OptionDescriptions& descs,
1846                             bool HasSink, bool HasExterns,
1847                             raw_ostream& O)
1848 {
1849   std::vector<OptionDescription> Aliases;
1850
1851   // Emit static cl::Option variables.
1852   for (OptionDescriptions::const_iterator B = descs.begin(),
1853          E = descs.end(); B!=E; ++B) {
1854     const OptionDescription& val = B->second;
1855
1856     if (val.Type == OptionType::Alias) {
1857       Aliases.push_back(val);
1858       continue;
1859     }
1860
1861     if (val.isExtern())
1862       O << "extern ";
1863
1864     O << val.GenTypeDeclaration() << ' '
1865       << val.GenVariableName();
1866
1867     if (val.isExtern()) {
1868       O << ";\n";
1869       continue;
1870     }
1871
1872     O << "(\"" << val.Name << "\"\n";
1873
1874     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1875       O << ", cl::Prefix";
1876
1877     if (val.isRequired()) {
1878       if (val.isList() && !val.isMultiVal())
1879         O << ", cl::OneOrMore";
1880       else
1881         O << ", cl::Required";
1882     }
1883     else if (val.isOneOrMore() && val.isList()) {
1884         O << ", cl::OneOrMore";
1885     }
1886     else if (val.isZeroOrOne() && val.isList()) {
1887         O << ", cl::ZeroOrOne";
1888     }
1889
1890     if (val.isReallyHidden()) {
1891       O << ", cl::ReallyHidden";
1892     }
1893     else if (val.isHidden()) {
1894       O << ", cl::Hidden";
1895     }
1896
1897     if (val.MultiVal > 1)
1898       O << ", cl::multi_val(" << val.MultiVal << ')';
1899
1900     if (val.InitVal) {
1901       const std::string& str = val.InitVal->getAsString();
1902       O << ", cl::init(" << str << ')';
1903     }
1904
1905     if (!val.Help.empty())
1906       O << ", cl::desc(\"" << val.Help << "\")";
1907
1908     O << ");\n\n";
1909   }
1910
1911   // Emit the aliases (they should go after all the 'proper' options).
1912   for (std::vector<OptionDescription>::const_iterator
1913          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1914     const OptionDescription& val = *B;
1915
1916     O << val.GenTypeDeclaration() << ' '
1917       << val.GenVariableName()
1918       << "(\"" << val.Name << '\"';
1919
1920     const OptionDescription& D = descs.FindOption(val.Help);
1921     O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1922
1923     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
1924   }
1925
1926   // Emit the sink option.
1927   if (HasSink)
1928     O << (HasExterns ? "extern cl" : "cl")
1929       << "::list<std::string> " << SinkOptionName
1930       << (HasExterns ? ";\n" : "(cl::Sink);\n");
1931
1932   O << '\n';
1933 }
1934
1935 /// PreprocessOptionsCallback - Helper function passed to
1936 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
1937 class PreprocessOptionsCallback {
1938   const OptionDescriptions& OptDescs_;
1939
1940   void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
1941     const std::string& OptName = InitPtrToString(i);
1942     const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
1943     const OptionType::OptionType OptType = OptDesc.Type;
1944
1945     if (OptType == OptionType::Switch) {
1946       O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
1947     }
1948     else if (OptType == OptionType::Parameter
1949              || OptType == OptionType::Prefix) {
1950       O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
1951     }
1952     else {
1953       throw std::string("'unset_option' can only be applied to "
1954                         "switches or parameter/prefix options.");
1955     }
1956   }
1957
1958   void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
1959   {
1960     const DagInit& d = InitPtrToDag(I);
1961     const std::string& OpName = d.getOperator()->getAsString();
1962
1963     // TOFIX: there is some duplication between this function and
1964     // EmitActionHandler.
1965     if (OpName == "warning") {
1966       checkNumberOfArguments(&d, 1);
1967       O.indent(IndentLevel) << "llvm::errs() << \""
1968                             << InitPtrToString(d.getArg(0)) << "\";\n";
1969     }
1970     else if (OpName == "error") {
1971       checkNumberOfArguments(&d, 1);
1972       O.indent(IndentLevel) << "throw std::runtime_error(\""
1973                             << InitPtrToString(d.getArg(0))
1974                             << "\");\n";
1975     }
1976     else if (OpName == "unset_option") {
1977       checkNumberOfArguments(&d, 1);
1978       Init* I = d.getArg(0);
1979       if (typeid(*I) == typeid(ListInit)) {
1980         const ListInit& DagList = *static_cast<const ListInit*>(I);
1981         for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1982              B != E; ++B)
1983           this->onUnsetOption(*B, IndentLevel, O);
1984       }
1985       else {
1986         this->onUnsetOption(I, IndentLevel, O);
1987       }
1988     }
1989     else {
1990       throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
1991         "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
1992     }
1993   }
1994
1995 public:
1996
1997   // TODO: Remove duplication.
1998   void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
1999     if (typeid(*I) == typeid(ListInit)) {
2000       const ListInit& DagList = *static_cast<const ListInit*>(I);
2001       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2002            B != E; ++B)
2003         this->processDag(*B, IndentLevel, O);
2004     }
2005     else {
2006       this->processDag(I, IndentLevel, O);
2007     }
2008   }
2009
2010   PreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2011   : OptDescs_(OptDescs)
2012   {}
2013 };
2014
2015 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2016 void EmitPreprocessOptions (const RecordKeeper& Records,
2017                             const OptionDescriptions& OptDecs, raw_ostream& O)
2018 {
2019   O << "void PreprocessOptionsLocal() {\n";
2020
2021   const RecordVector& OptionPreprocessors =
2022     Records.getAllDerivedDefinitions("OptionPreprocessor");
2023
2024   for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2025          E = OptionPreprocessors.end(); B!=E; ++B) {
2026     DagInit* Case = (*B)->getValueAsDag("preprocessor");
2027     EmitCaseConstructHandler(Case, Indent1, PreprocessOptionsCallback(OptDecs),
2028                              false, OptDecs, O);
2029   }
2030
2031   O << "}\n\n";
2032 }
2033
2034 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2035 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2036 {
2037   O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2038
2039   // Get the relevant field out of RecordKeeper
2040   const Record* LangMapRecord = Records.getDef("LanguageMap");
2041
2042   // It is allowed for a plugin to have no language map.
2043   if (LangMapRecord) {
2044
2045     ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2046     if (!LangsToSuffixesList)
2047       throw std::string("Error in the language map definition!");
2048
2049     for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2050       const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2051
2052       const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2053       const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2054
2055       for (unsigned i = 0; i < Suffixes->size(); ++i)
2056         O.indent(Indent1) << "langMap[\""
2057                           << InitPtrToString(Suffixes->getElement(i))
2058                           << "\"] = \"" << Lang << "\";\n";
2059     }
2060   }
2061
2062   O << "}\n\n";
2063 }
2064
2065 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2066 /// by EmitEdgeClass().
2067 void IncDecWeight (const Init* i, unsigned IndentLevel,
2068                    raw_ostream& O) {
2069   const DagInit& d = InitPtrToDag(i);
2070   const std::string& OpName = d.getOperator()->getAsString();
2071
2072   if (OpName == "inc_weight") {
2073     O.indent(IndentLevel) << "ret += ";
2074   }
2075   else if (OpName == "dec_weight") {
2076     O.indent(IndentLevel) << "ret -= ";
2077   }
2078   else if (OpName == "error") {
2079     checkNumberOfArguments(&d, 1);
2080     O.indent(IndentLevel) << "throw std::runtime_error(\""
2081                           << InitPtrToString(d.getArg(0))
2082                           << "\");\n";
2083     return;
2084   }
2085   else {
2086     throw "Unknown operator in edge properties list: '" + OpName + "'!"
2087       "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2088   }
2089
2090   if (d.getNumArgs() > 0)
2091     O << InitPtrToInt(d.getArg(0)) << ";\n";
2092   else
2093     O << "2;\n";
2094
2095 }
2096
2097 /// EmitEdgeClass - Emit a single Edge# class.
2098 void EmitEdgeClass (unsigned N, const std::string& Target,
2099                     DagInit* Case, const OptionDescriptions& OptDescs,
2100                     raw_ostream& O) {
2101
2102   // Class constructor.
2103   O << "class Edge" << N << ": public Edge {\n"
2104     << "public:\n";
2105   O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2106                     << "\") {}\n\n";
2107
2108   // Function Weight().
2109   O.indent(Indent1)
2110     << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2111   O.indent(Indent2) << "unsigned ret = 0;\n";
2112
2113   // Handle the 'case' construct.
2114   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2115
2116   O.indent(Indent2) << "return ret;\n";
2117   O.indent(Indent1) << "};\n\n};\n\n";
2118 }
2119
2120 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2121 void EmitEdgeClasses (const RecordVector& EdgeVector,
2122                       const OptionDescriptions& OptDescs,
2123                       raw_ostream& O) {
2124   int i = 0;
2125   for (RecordVector::const_iterator B = EdgeVector.begin(),
2126          E = EdgeVector.end(); B != E; ++B) {
2127     const Record* Edge = *B;
2128     const std::string& NodeB = Edge->getValueAsString("b");
2129     DagInit* Weight = Edge->getValueAsDag("weight");
2130
2131     if (!isDagEmpty(Weight))
2132       EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2133     ++i;
2134   }
2135 }
2136
2137 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2138 /// function.
2139 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2140                                    const ToolDescriptions& ToolDescs,
2141                                    raw_ostream& O)
2142 {
2143   O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2144
2145   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2146          E = ToolDescs.end(); B != E; ++B)
2147     O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2148
2149   O << '\n';
2150
2151   // Insert edges.
2152
2153   int i = 0;
2154   for (RecordVector::const_iterator B = EdgeVector.begin(),
2155          E = EdgeVector.end(); B != E; ++B) {
2156     const Record* Edge = *B;
2157     const std::string& NodeA = Edge->getValueAsString("a");
2158     const std::string& NodeB = Edge->getValueAsString("b");
2159     DagInit* Weight = Edge->getValueAsDag("weight");
2160
2161     O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2162
2163     if (isDagEmpty(Weight))
2164       O << "new SimpleEdge(\"" << NodeB << "\")";
2165     else
2166       O << "new Edge" << i << "()";
2167
2168     O << ");\n";
2169     ++i;
2170   }
2171
2172   O << "}\n\n";
2173 }
2174
2175 /// ExtractHookNames - Extract the hook names from all instances of
2176 /// $CALL(HookName) in the provided command line string. Helper
2177 /// function used by FillInHookNames().
2178 class ExtractHookNames {
2179   llvm::StringMap<unsigned>& HookNames_;
2180 public:
2181   ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
2182   : HookNames_(HookNames) {}
2183
2184   void operator()(const Init* CmdLine) {
2185     StrVector cmds;
2186     TokenizeCmdline(InitPtrToString(CmdLine), cmds);
2187     for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2188          B != E; ++B) {
2189       const std::string& cmd = *B;
2190
2191       if (cmd == "$CALL") {
2192         unsigned NumArgs = 0;
2193         checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2194         const std::string& HookName = *B;
2195
2196
2197         if (HookName.at(0) == ')')
2198           throw "$CALL invoked with no arguments!";
2199
2200         while (++B != E && B->at(0) != ')') {
2201           ++NumArgs;
2202         }
2203
2204         StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
2205
2206         if (H != HookNames_.end() && H->second != NumArgs)
2207           throw "Overloading of hooks is not allowed. Overloaded hook: "
2208             + HookName;
2209         else
2210           HookNames_[HookName] = NumArgs;
2211
2212       }
2213     }
2214   }
2215 };
2216
2217 /// FillInHookNames - Actually extract the hook names from all command
2218 /// line strings. Helper function used by EmitHookDeclarations().
2219 void FillInHookNames(const ToolDescriptions& ToolDescs,
2220                      llvm::StringMap<unsigned>& HookNames)
2221 {
2222   // For all command lines:
2223   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2224          E = ToolDescs.end(); B != E; ++B) {
2225     const ToolDescription& D = *(*B);
2226     if (!D.CmdLine)
2227       continue;
2228     if (dynamic_cast<StringInit*>(D.CmdLine))
2229       // This is a string.
2230       ExtractHookNames(HookNames).operator()(D.CmdLine);
2231     else
2232       // This is a 'case' construct.
2233       WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
2234   }
2235 }
2236
2237 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2238 /// property records and emit hook function declaration for each
2239 /// instance of $CALL(HookName).
2240 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
2241   llvm::StringMap<unsigned> HookNames;
2242
2243   FillInHookNames(ToolDescs, HookNames);
2244   if (HookNames.empty())
2245     return;
2246
2247   O << "namespace hooks {\n";
2248   for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
2249          E = HookNames.end(); B != E; ++B) {
2250     O.indent(Indent1) << "std::string " << B->first() << "(";
2251
2252     for (unsigned i = 0, j = B->second; i < j; ++i) {
2253       O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2254     }
2255
2256     O <<");\n";
2257   }
2258   O << "}\n\n";
2259 }
2260
2261 /// EmitRegisterPlugin - Emit code to register this plugin.
2262 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2263   O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2264   O.indent(Indent1) << "int Priority() const { return "
2265                     << Priority << "; }\n\n";
2266   O.indent(Indent1) << "void PreprocessOptions() const\n";
2267   O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2268   O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2269   O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2270   O.indent(Indent1)
2271     << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2272   O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2273                     << "};\n\n"
2274                     << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2275 }
2276
2277 /// EmitIncludes - Emit necessary #include directives and some
2278 /// additional declarations.
2279 void EmitIncludes(raw_ostream& O) {
2280   O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2281     << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2282     << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2283     << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2284     << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2285
2286     << "#include \"llvm/ADT/StringExtras.h\"\n"
2287     << "#include \"llvm/Support/CommandLine.h\"\n"
2288     << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2289
2290     << "#include <cstdlib>\n"
2291     << "#include <stdexcept>\n\n"
2292
2293     << "using namespace llvm;\n"
2294     << "using namespace llvmc;\n\n"
2295
2296     << "extern cl::opt<std::string> OutputFilename;\n\n"
2297
2298     << "inline const char* checkCString(const char* s)\n"
2299     << "{ return s == NULL ? \"\" : s; }\n\n";
2300 }
2301
2302
2303 /// PluginData - Holds all information about a plugin.
2304 struct PluginData {
2305   OptionDescriptions OptDescs;
2306   bool HasSink;
2307   bool HasExterns;
2308   ToolDescriptions ToolDescs;
2309   RecordVector Edges;
2310   int Priority;
2311 };
2312
2313 /// HasSink - Go through the list of tool descriptions and check if
2314 /// there are any with the 'sink' property set.
2315 bool HasSink(const ToolDescriptions& ToolDescs) {
2316   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2317          E = ToolDescs.end(); B != E; ++B)
2318     if ((*B)->isSink())
2319       return true;
2320
2321   return false;
2322 }
2323
2324 /// HasExterns - Go through the list of option descriptions and check
2325 /// if there are any external options.
2326 bool HasExterns(const OptionDescriptions& OptDescs) {
2327  for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2328          E = OptDescs.end(); B != E; ++B)
2329     if (B->second.isExtern())
2330       return true;
2331
2332   return false;
2333 }
2334
2335 /// CollectPluginData - Collect tool and option properties,
2336 /// compilation graph edges and plugin priority from the parse tree.
2337 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2338   // Collect option properties.
2339   const RecordVector& OptionLists =
2340     Records.getAllDerivedDefinitions("OptionList");
2341   CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2342                             Data.OptDescs);
2343
2344   // Collect tool properties.
2345   const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2346   CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2347   Data.HasSink = HasSink(Data.ToolDescs);
2348   Data.HasExterns = HasExterns(Data.OptDescs);
2349
2350   // Collect compilation graph edges.
2351   const RecordVector& CompilationGraphs =
2352     Records.getAllDerivedDefinitions("CompilationGraph");
2353   FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2354                    Data.Edges);
2355
2356   // Calculate the priority of this plugin.
2357   const RecordVector& Priorities =
2358     Records.getAllDerivedDefinitions("PluginPriority");
2359   Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2360 }
2361
2362 /// CheckPluginData - Perform some sanity checks on the collected data.
2363 void CheckPluginData(PluginData& Data) {
2364   // Filter out all tools not mentioned in the compilation graph.
2365   FilterNotInGraph(Data.Edges, Data.ToolDescs);
2366
2367   // Typecheck the compilation graph.
2368   TypecheckGraph(Data.Edges, Data.ToolDescs);
2369
2370   // Check that there are no options without side effects (specified
2371   // only in the OptionList).
2372   CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2373
2374 }
2375
2376 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2377   // Emit file header.
2378   EmitIncludes(O);
2379
2380   // Emit global option registration code.
2381   EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2382
2383   // Emit hook declarations.
2384   EmitHookDeclarations(Data.ToolDescs, O);
2385
2386   O << "namespace {\n\n";
2387
2388   // Emit PreprocessOptionsLocal() function.
2389   EmitPreprocessOptions(Records, Data.OptDescs, O);
2390
2391   // Emit PopulateLanguageMapLocal() function
2392   // (language map maps from file extensions to language names).
2393   EmitPopulateLanguageMap(Records, O);
2394
2395   // Emit Tool classes.
2396   for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2397          E = Data.ToolDescs.end(); B!=E; ++B)
2398     EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2399
2400   // Emit Edge# classes.
2401   EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2402
2403   // Emit PopulateCompilationGraphLocal() function.
2404   EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2405
2406   // Emit code for plugin registration.
2407   EmitRegisterPlugin(Data.Priority, O);
2408
2409   O << "} // End anonymous namespace.\n\n";
2410
2411   // Force linkage magic.
2412   O << "namespace llvmc {\n";
2413   O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2414   O << "}\n";
2415
2416   // EOF
2417 }
2418
2419
2420 // End of anonymous namespace
2421 }
2422
2423 /// run - The back-end entry point.
2424 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2425   try {
2426   PluginData Data;
2427
2428   CollectPluginData(Records, Data);
2429   CheckPluginData(Data);
2430
2431   EmitSourceFileHeader("LLVMC Configuration Library", O);
2432   EmitPluginCode(Data, O);
2433
2434   } catch (std::exception& Error) {
2435     throw Error.what() + std::string(" - usually this means a syntax error.");
2436   }
2437 }