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