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