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