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