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