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