Comment fix.
[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/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
22 #include <algorithm>
23 #include <cassert>
24 #include <functional>
25 #include <stdexcept>
26 #include <string>
27 #include <typeinfo>
28
29 using namespace llvm;
30
31 namespace {
32
33 //===----------------------------------------------------------------------===//
34 /// Typedefs
35
36 typedef std::vector<Record*> RecordVector;
37 typedef std::vector<std::string> StrVector;
38
39 //===----------------------------------------------------------------------===//
40 /// Constants
41
42 // Indentation strings.
43 const char * Indent1 = "    ";
44 const char * Indent2 = "        ";
45 const char * Indent3 = "            ";
46
47 // Default help string.
48 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
49
50 // Name for the "sink" option.
51 const char * SinkOptionName = "AutoGeneratedSinkOption";
52
53 //===----------------------------------------------------------------------===//
54 /// Helper functions
55
56 /// Id - An 'identity' function object.
57 struct Id {
58   template<typename T>
59   void operator()(const T&) const {
60   }
61 };
62
63 int InitPtrToInt(const Init* ptr) {
64   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
65   return val.getValue();
66 }
67
68 const std::string& InitPtrToString(const Init* ptr) {
69   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
70   return val.getValue();
71 }
72
73 const ListInit& InitPtrToList(const Init* ptr) {
74   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
75   return val;
76 }
77
78 const DagInit& InitPtrToDag(const Init* ptr) {
79   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
80   return val;
81 }
82
83 // checkNumberOfArguments - Ensure that the number of args in d is
84 // greater than or equal to min_arguments, otherwise throw an exception.
85 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
86   if (!d || d->getNumArgs() < min_arguments)
87     throw d->getOperator()->getAsString() + ": too few arguments!";
88 }
89
90 // isDagEmpty - is this DAG marked with an empty marker?
91 bool isDagEmpty (const DagInit* d) {
92   return d->getOperator()->getAsString() == "empty";
93 }
94
95 // EscapeVariableName - Escape commas and other symbols not allowed
96 // in the C++ variable names. Makes it possible to use options named
97 // like "Wa," (useful for prefix options).
98 std::string EscapeVariableName(const std::string& Var) {
99   std::string ret;
100   for (unsigned i = 0; i != Var.size(); ++i) {
101     char cur_char = Var[i];
102     if (cur_char == ',') {
103       ret += "_comma_";
104     }
105     else if (cur_char == '+') {
106       ret += "_plus_";
107     }
108     else if (cur_char == '-') {
109       ret += "_dash_";
110     }
111     else {
112       ret.push_back(cur_char);
113     }
114   }
115   return ret;
116 }
117
118 /// oneOf - Does the input string contain this character?
119 bool oneOf(const char* lst, char c) {
120   while (*lst) {
121     if (*lst++ == c)
122       return true;
123   }
124   return false;
125 }
126
127 template <class I, class S>
128 void checkedIncrement(I& P, I E, S ErrorString) {
129   ++P;
130   if (P == E)
131     throw ErrorString;
132 }
133
134 //===----------------------------------------------------------------------===//
135 /// Back-end specific code
136
137
138 /// OptionType - One of six different option types. See the
139 /// documentation for detailed description of differences.
140 namespace OptionType {
141   enum OptionType { Alias, Switch, Parameter, ParameterList,
142                     Prefix, PrefixList};
143
144 bool IsList (OptionType t) {
145   return (t == ParameterList || t == PrefixList);
146 }
147
148 bool IsSwitch (OptionType t) {
149   return (t == Switch);
150 }
151
152 bool IsParameter (OptionType t) {
153   return (t == Parameter || t == Prefix);
154 }
155
156 }
157
158 OptionType::OptionType stringToOptionType(const std::string& T) {
159   if (T == "alias_option")
160     return OptionType::Alias;
161   else if (T == "switch_option")
162     return OptionType::Switch;
163   else if (T == "parameter_option")
164     return OptionType::Parameter;
165   else if (T == "parameter_list_option")
166     return OptionType::ParameterList;
167   else if (T == "prefix_option")
168     return OptionType::Prefix;
169   else if (T == "prefix_list_option")
170     return OptionType::PrefixList;
171   else
172     throw "Unknown option type: " + T + '!';
173 }
174
175 namespace OptionDescriptionFlags {
176   enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
177                                 ReallyHidden = 0x4, Extern = 0x8,
178                                 OneOrMore = 0x10, ZeroOrOne = 0x20 };
179 }
180
181 /// OptionDescription - Represents data contained in a single
182 /// OptionList entry.
183 struct OptionDescription {
184   OptionType::OptionType Type;
185   std::string Name;
186   unsigned Flags;
187   std::string Help;
188   unsigned MultiVal;
189
190   OptionDescription(OptionType::OptionType t = OptionType::Switch,
191                     const std::string& n = "",
192                     const std::string& h = DefaultHelpString)
193     : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1)
194   {}
195
196   /// GenTypeDeclaration - Returns the C++ variable type of this
197   /// option.
198   const char* GenTypeDeclaration() const;
199
200   /// GenVariableName - Returns the variable name used in the
201   /// generated C++ code.
202   std::string GenVariableName() const;
203
204   /// Merge - Merge two option descriptions.
205   void Merge (const OptionDescription& other);
206
207   // Misc convenient getters/setters.
208
209   bool isAlias() const;
210
211   bool isMultiVal() const;
212
213   bool isExtern() const;
214   void setExtern();
215
216   bool isRequired() const;
217   void setRequired();
218
219   bool isOneOrMore() const;
220   void setOneOrMore();
221
222   bool isZeroOrOne() const;
223   void setZeroOrOne();
224
225   bool isHidden() const;
226   void setHidden();
227
228   bool isReallyHidden() const;
229   void setReallyHidden();
230
231 };
232
233 void OptionDescription::Merge (const OptionDescription& other)
234 {
235   if (other.Type != Type)
236     throw "Conflicting definitions for the option " + Name + "!";
237
238   if (Help == other.Help || Help == DefaultHelpString)
239     Help = other.Help;
240   else if (other.Help != DefaultHelpString) {
241     llvm::errs() << "Warning: several different help strings"
242       " defined for option " + Name + "\n";
243   }
244
245   Flags |= other.Flags;
246 }
247
248 bool OptionDescription::isAlias() const {
249   return Type == OptionType::Alias;
250 }
251
252 bool OptionDescription::isMultiVal() const {
253   return MultiVal > 1;
254 }
255
256 bool OptionDescription::isExtern() const {
257   return Flags & OptionDescriptionFlags::Extern;
258 }
259 void OptionDescription::setExtern() {
260   Flags |= OptionDescriptionFlags::Extern;
261 }
262
263 bool OptionDescription::isRequired() const {
264   return Flags & OptionDescriptionFlags::Required;
265 }
266 void OptionDescription::setRequired() {
267   Flags |= OptionDescriptionFlags::Required;
268 }
269
270 bool OptionDescription::isOneOrMore() const {
271   return Flags & OptionDescriptionFlags::OneOrMore;
272 }
273 void OptionDescription::setOneOrMore() {
274   Flags |= OptionDescriptionFlags::OneOrMore;
275 }
276
277 bool OptionDescription::isZeroOrOne() const {
278   return Flags & OptionDescriptionFlags::ZeroOrOne;
279 }
280 void OptionDescription::setZeroOrOne() {
281   Flags |= OptionDescriptionFlags::ZeroOrOne;
282 }
283
284 bool OptionDescription::isHidden() const {
285   return Flags & OptionDescriptionFlags::Hidden;
286 }
287 void OptionDescription::setHidden() {
288   Flags |= OptionDescriptionFlags::Hidden;
289 }
290
291 bool OptionDescription::isReallyHidden() const {
292   return Flags & OptionDescriptionFlags::ReallyHidden;
293 }
294 void OptionDescription::setReallyHidden() {
295   Flags |= OptionDescriptionFlags::ReallyHidden;
296 }
297
298 const char* OptionDescription::GenTypeDeclaration() const {
299   switch (Type) {
300   case OptionType::Alias:
301     return "cl::alias";
302   case OptionType::PrefixList:
303   case OptionType::ParameterList:
304     return "cl::list<std::string>";
305   case OptionType::Switch:
306     return "cl::opt<bool>";
307   case OptionType::Parameter:
308   case OptionType::Prefix:
309   default:
310     return "cl::opt<std::string>";
311   }
312 }
313
314 std::string OptionDescription::GenVariableName() const {
315   const std::string& EscapedName = EscapeVariableName(Name);
316   switch (Type) {
317   case OptionType::Alias:
318     return "AutoGeneratedAlias_" + EscapedName;
319   case OptionType::PrefixList:
320   case OptionType::ParameterList:
321     return "AutoGeneratedList_" + EscapedName;
322   case OptionType::Switch:
323     return "AutoGeneratedSwitch_" + EscapedName;
324   case OptionType::Prefix:
325   case OptionType::Parameter:
326   default:
327     return "AutoGeneratedParameter_" + EscapedName;
328   }
329 }
330
331 /// OptionDescriptions - An OptionDescription array plus some helper
332 /// functions.
333 class OptionDescriptions {
334   typedef StringMap<OptionDescription> container_type;
335
336   /// Descriptions - A list of OptionDescriptions.
337   container_type Descriptions;
338
339 public:
340   /// FindOption - exception-throwing wrapper for find().
341   const OptionDescription& FindOption(const std::string& OptName) const;
342
343   /// insertDescription - Insert new OptionDescription into
344   /// OptionDescriptions list
345   void InsertDescription (const OptionDescription& o);
346
347   // Support for STL-style iteration
348   typedef container_type::const_iterator const_iterator;
349   const_iterator begin() const { return Descriptions.begin(); }
350   const_iterator end() const { return Descriptions.end(); }
351 };
352
353 const OptionDescription&
354 OptionDescriptions::FindOption(const std::string& OptName) const
355 {
356   const_iterator I = Descriptions.find(OptName);
357   if (I != Descriptions.end())
358     return I->second;
359   else
360     throw OptName + ": no such option!";
361 }
362
363 void OptionDescriptions::InsertDescription (const OptionDescription& o)
364 {
365   container_type::iterator I = Descriptions.find(o.Name);
366   if (I != Descriptions.end()) {
367     OptionDescription& D = I->second;
368     D.Merge(o);
369   }
370   else {
371     Descriptions[o.Name] = o;
372   }
373 }
374
375 /// HandlerTable - A base class for function objects implemented as
376 /// 'tables of handlers'.
377 template <class T>
378 class HandlerTable {
379 protected:
380   // Implementation details.
381
382   /// Handler -
383   typedef void (T::* Handler) (const DagInit*);
384   /// HandlerMap - A map from property names to property handlers
385   typedef StringMap<Handler> HandlerMap;
386
387   static HandlerMap Handlers_;
388   static bool staticMembersInitialized_;
389
390   T* childPtr;
391 public:
392
393   HandlerTable(T* cp) : childPtr(cp)
394   {}
395
396   /// operator() - Just forwards to the corresponding property
397   /// handler.
398   void operator() (Init* i) {
399     const DagInit& property = InitPtrToDag(i);
400     const std::string& property_name = property.getOperator()->getAsString();
401     typename HandlerMap::iterator method = Handlers_.find(property_name);
402
403     if (method != Handlers_.end()) {
404       Handler h = method->second;
405       (childPtr->*h)(&property);
406     }
407     else {
408       throw "No handler found for property " + property_name + "!";
409     }
410   }
411
412   void AddHandler(const char* Property, Handler Handl) {
413     Handlers_[Property] = Handl;
414   }
415 };
416
417 template <class T> typename HandlerTable<T>::HandlerMap
418 HandlerTable<T>::Handlers_;
419 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
420
421
422 /// CollectOptionProperties - Function object for iterating over an
423 /// option property list.
424 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
425 private:
426
427   /// optDescs_ - OptionDescriptions table. This is where the
428   /// information is stored.
429   OptionDescription& optDesc_;
430
431 public:
432
433   explicit CollectOptionProperties(OptionDescription& OD)
434     : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
435   {
436     if (!staticMembersInitialized_) {
437       AddHandler("extern", &CollectOptionProperties::onExtern);
438       AddHandler("help", &CollectOptionProperties::onHelp);
439       AddHandler("hidden", &CollectOptionProperties::onHidden);
440       AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
441       AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
442       AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
443       AddHandler("required", &CollectOptionProperties::onRequired);
444       AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
445
446       staticMembersInitialized_ = true;
447     }
448   }
449
450 private:
451
452   /// Option property handlers --
453   /// Methods that handle option properties such as (help) or (hidden).
454
455   void onExtern (const DagInit* d) {
456     checkNumberOfArguments(d, 0);
457     optDesc_.setExtern();
458   }
459
460   void onHelp (const DagInit* d) {
461     checkNumberOfArguments(d, 1);
462     optDesc_.Help = InitPtrToString(d->getArg(0));
463   }
464
465   void onHidden (const DagInit* d) {
466     checkNumberOfArguments(d, 0);
467     optDesc_.setHidden();
468   }
469
470   void onReallyHidden (const DagInit* d) {
471     checkNumberOfArguments(d, 0);
472     optDesc_.setReallyHidden();
473   }
474
475   void onRequired (const DagInit* d) {
476     checkNumberOfArguments(d, 0);
477     if (optDesc_.isOneOrMore())
478       throw std::string("An option can't have both (required) "
479                         "and (one_or_more) properties!");
480     optDesc_.setRequired();
481   }
482
483   void onOneOrMore (const DagInit* d) {
484     checkNumberOfArguments(d, 0);
485     if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
486       throw std::string("Only one of (required), (zero_or_one) or "
487                         "(one_or_more) properties is allowed!");
488     if (!OptionType::IsList(optDesc_.Type))
489       llvm::errs() << "Warning: specifying the 'one_or_more' property "
490         "on a non-list option will have no effect.\n";
491     optDesc_.setOneOrMore();
492   }
493
494   void onZeroOrOne (const DagInit* d) {
495     checkNumberOfArguments(d, 0);
496     if (optDesc_.isRequired() || optDesc_.isOneOrMore())
497       throw std::string("Only one of (required), (zero_or_one) or "
498                         "(one_or_more) properties is allowed!");
499     if (!OptionType::IsList(optDesc_.Type))
500       llvm::errs() << "Warning: specifying the 'zero_or_one' property"
501         "on a non-list option will have no effect.\n";
502     optDesc_.setZeroOrOne();
503   }
504
505   void onMultiVal (const DagInit* d) {
506     checkNumberOfArguments(d, 1);
507     int val = InitPtrToInt(d->getArg(0));
508     if (val < 2)
509       throw std::string("Error in the 'multi_val' property: "
510                         "the value must be greater than 1!");
511     if (!OptionType::IsList(optDesc_.Type))
512       throw std::string("The multi_val property is valid only "
513                         "on list options!");
514     optDesc_.MultiVal = val;
515   }
516
517 };
518
519 /// AddOption - A function object that is applied to every option
520 /// description. Used by CollectOptionDescriptions.
521 class AddOption {
522 private:
523   OptionDescriptions& OptDescs_;
524
525 public:
526   explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
527   {}
528
529   void operator()(const Init* i) {
530     const DagInit& d = InitPtrToDag(i);
531     checkNumberOfArguments(&d, 1);
532
533     const OptionType::OptionType Type =
534       stringToOptionType(d.getOperator()->getAsString());
535     const std::string& Name = InitPtrToString(d.getArg(0));
536
537     OptionDescription OD(Type, Name);
538
539     if (!OD.isExtern())
540       checkNumberOfArguments(&d, 2);
541
542     if (OD.isAlias()) {
543       // Aliases store the aliased option name in the 'Help' field.
544       OD.Help = InitPtrToString(d.getArg(1));
545     }
546     else if (!OD.isExtern()) {
547       processOptionProperties(&d, OD);
548     }
549     OptDescs_.InsertDescription(OD);
550   }
551
552 private:
553   /// processOptionProperties - Go through the list of option
554   /// properties and call a corresponding handler for each.
555   static void processOptionProperties (const DagInit* d, OptionDescription& o) {
556     checkNumberOfArguments(d, 2);
557     DagInit::const_arg_iterator B = d->arg_begin();
558     // Skip the first argument: it's always the option name.
559     ++B;
560     std::for_each(B, d->arg_end(), CollectOptionProperties(o));
561   }
562
563 };
564
565 /// CollectOptionDescriptions - Collects option properties from all
566 /// OptionLists.
567 void CollectOptionDescriptions (RecordVector::const_iterator B,
568                                 RecordVector::const_iterator E,
569                                 OptionDescriptions& OptDescs)
570 {
571   // For every OptionList:
572   for (; B!=E; ++B) {
573     RecordVector::value_type T = *B;
574     // Throws an exception if the value does not exist.
575     ListInit* PropList = T->getValueAsListInit("options");
576
577     // For every option description in this list:
578     // collect the information and
579     std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
580   }
581 }
582
583 // Tool information record
584
585 namespace ToolFlags {
586   enum ToolFlags { Join = 0x1, Sink = 0x2 };
587 }
588
589 struct ToolDescription : public RefCountedBase<ToolDescription> {
590   std::string Name;
591   Init* CmdLine;
592   Init* Actions;
593   StrVector InLanguage;
594   std::string OutLanguage;
595   std::string OutputSuffix;
596   unsigned Flags;
597
598   // Various boolean properties
599   void setSink()      { Flags |= ToolFlags::Sink; }
600   bool isSink() const { return Flags & ToolFlags::Sink; }
601   void setJoin()      { Flags |= ToolFlags::Join; }
602   bool isJoin() const { return Flags & ToolFlags::Join; }
603
604   // Default ctor here is needed because StringMap can only store
605   // DefaultConstructible objects
606   ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
607   ToolDescription (const std::string& n)
608   : Name(n), CmdLine(0), Actions(0), Flags(0)
609   {}
610 };
611
612 /// ToolDescriptions - A list of Tool information records.
613 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
614
615
616 /// CollectToolProperties - Function object for iterating over a list of
617 /// tool property records.
618 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
619 private:
620
621   /// toolDesc_ - Properties of the current Tool. This is where the
622   /// information is stored.
623   ToolDescription& toolDesc_;
624
625 public:
626
627   explicit CollectToolProperties (ToolDescription& d)
628     : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
629   {
630     if (!staticMembersInitialized_) {
631
632       AddHandler("actions", &CollectToolProperties::onActions);
633       AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
634       AddHandler("in_language", &CollectToolProperties::onInLanguage);
635       AddHandler("join", &CollectToolProperties::onJoin);
636       AddHandler("out_language", &CollectToolProperties::onOutLanguage);
637       AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
638       AddHandler("sink", &CollectToolProperties::onSink);
639
640       staticMembersInitialized_ = true;
641     }
642   }
643
644 private:
645
646   /// Property handlers --
647   /// Functions that extract information about tool properties from
648   /// DAG representation.
649
650   void onActions (const DagInit* d) {
651     checkNumberOfArguments(d, 1);
652     Init* Case = d->getArg(0);
653     if (typeid(*Case) != typeid(DagInit) ||
654         static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
655       throw
656         std::string("The argument to (actions) should be a 'case' construct!");
657     toolDesc_.Actions = Case;
658   }
659
660   void onCmdLine (const DagInit* d) {
661     checkNumberOfArguments(d, 1);
662     toolDesc_.CmdLine = d->getArg(0);
663   }
664
665   void onInLanguage (const DagInit* d) {
666     checkNumberOfArguments(d, 1);
667     Init* arg = d->getArg(0);
668
669     // Find out the argument's type.
670     if (typeid(*arg) == typeid(StringInit)) {
671       // It's a string.
672       toolDesc_.InLanguage.push_back(InitPtrToString(arg));
673     }
674     else {
675       // It's a list.
676       const ListInit& lst = InitPtrToList(arg);
677       StrVector& out = toolDesc_.InLanguage;
678
679       // Copy strings to the output vector.
680       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
681            B != E; ++B) {
682         out.push_back(InitPtrToString(*B));
683       }
684
685       // Remove duplicates.
686       std::sort(out.begin(), out.end());
687       StrVector::iterator newE = std::unique(out.begin(), out.end());
688       out.erase(newE, out.end());
689     }
690   }
691
692   void onJoin (const DagInit* d) {
693     checkNumberOfArguments(d, 0);
694     toolDesc_.setJoin();
695   }
696
697   void onOutLanguage (const DagInit* d) {
698     checkNumberOfArguments(d, 1);
699     toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
700   }
701
702   void onOutputSuffix (const DagInit* d) {
703     checkNumberOfArguments(d, 1);
704     toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
705   }
706
707   void onSink (const DagInit* d) {
708     checkNumberOfArguments(d, 0);
709     toolDesc_.setSink();
710   }
711
712 };
713
714 /// CollectToolDescriptions - Gather information about tool properties
715 /// from the parsed TableGen data (basically a wrapper for the
716 /// CollectToolProperties function object).
717 void CollectToolDescriptions (RecordVector::const_iterator B,
718                               RecordVector::const_iterator E,
719                               ToolDescriptions& ToolDescs)
720 {
721   // Iterate over a properties list of every Tool definition
722   for (;B!=E;++B) {
723     const Record* T = *B;
724     // Throws an exception if the value does not exist.
725     ListInit* PropList = T->getValueAsListInit("properties");
726
727     IntrusiveRefCntPtr<ToolDescription>
728       ToolDesc(new ToolDescription(T->getName()));
729
730     std::for_each(PropList->begin(), PropList->end(),
731                   CollectToolProperties(*ToolDesc));
732     ToolDescs.push_back(ToolDesc);
733   }
734 }
735
736 /// FillInEdgeVector - Merge all compilation graph definitions into
737 /// one single edge list.
738 void FillInEdgeVector(RecordVector::const_iterator B,
739                       RecordVector::const_iterator E, RecordVector& Out) {
740   for (; B != E; ++B) {
741     const ListInit* edges = (*B)->getValueAsListInit("edges");
742
743     for (unsigned i = 0; i < edges->size(); ++i)
744       Out.push_back(edges->getElementAsRecord(i));
745   }
746 }
747
748 /// CalculatePriority - Calculate the priority of this plugin.
749 int CalculatePriority(RecordVector::const_iterator B,
750                       RecordVector::const_iterator E) {
751   int total = 0;
752   for (; B!=E; ++B) {
753     total += static_cast<int>((*B)->getValueAsInt("priority"));
754   }
755   return total;
756 }
757
758 /// NotInGraph - Helper function object for FilterNotInGraph.
759 struct NotInGraph {
760 private:
761   const llvm::StringSet<>& ToolsInGraph_;
762
763 public:
764   NotInGraph(const llvm::StringSet<>& ToolsInGraph)
765   : ToolsInGraph_(ToolsInGraph)
766   {}
767
768   bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
769     return (ToolsInGraph_.count(x->Name) == 0);
770   }
771 };
772
773 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
774 /// mentioned in the compilation graph definition.
775 void FilterNotInGraph (const RecordVector& EdgeVector,
776                        ToolDescriptions& ToolDescs) {
777
778   // List all tools mentioned in the graph.
779   llvm::StringSet<> ToolsInGraph;
780
781   for (RecordVector::const_iterator B = EdgeVector.begin(),
782          E = EdgeVector.end(); B != E; ++B) {
783
784     const Record* Edge = *B;
785     const std::string& NodeA = Edge->getValueAsString("a");
786     const std::string& NodeB = Edge->getValueAsString("b");
787
788     if (NodeA != "root")
789       ToolsInGraph.insert(NodeA);
790     ToolsInGraph.insert(NodeB);
791   }
792
793   // Filter ToolPropertiesList.
794   ToolDescriptions::iterator new_end =
795     std::remove_if(ToolDescs.begin(), ToolDescs.end(),
796                    NotInGraph(ToolsInGraph));
797   ToolDescs.erase(new_end, ToolDescs.end());
798 }
799
800 /// FillInToolToLang - Fills in two tables that map tool names to
801 /// (input, output) languages.  Helper function used by TypecheckGraph().
802 void FillInToolToLang (const ToolDescriptions& ToolDescs,
803                        StringMap<StringSet<> >& ToolToInLang,
804                        StringMap<std::string>& ToolToOutLang) {
805   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
806          E = ToolDescs.end(); B != E; ++B) {
807     const ToolDescription& D = *(*B);
808     for (StrVector::const_iterator B = D.InLanguage.begin(),
809            E = D.InLanguage.end(); B != E; ++B)
810       ToolToInLang[D.Name].insert(*B);
811     ToolToOutLang[D.Name] = D.OutLanguage;
812   }
813 }
814
815 /// TypecheckGraph - Check that names for output and input languages
816 /// on all edges do match. This doesn't do much when the information
817 /// about the whole graph is not available (i.e. when compiling most
818 /// plugins).
819 void TypecheckGraph (const RecordVector& EdgeVector,
820                      const ToolDescriptions& ToolDescs) {
821   StringMap<StringSet<> > ToolToInLang;
822   StringMap<std::string> ToolToOutLang;
823
824   FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
825   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
826   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
827
828   for (RecordVector::const_iterator B = EdgeVector.begin(),
829          E = EdgeVector.end(); B != E; ++B) {
830     const Record* Edge = *B;
831     const std::string& NodeA = Edge->getValueAsString("a");
832     const std::string& NodeB = Edge->getValueAsString("b");
833     StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
834     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
835
836     if (NodeA != "root") {
837       if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
838         throw "Edge " + NodeA + "->" + NodeB
839           + ": output->input language mismatch";
840     }
841
842     if (NodeB == "root")
843       throw std::string("Edges back to the root are not allowed!");
844   }
845 }
846
847 /// WalkCase - Walks the 'case' expression DAG and invokes
848 /// TestCallback on every test, and StatementCallback on every
849 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
850 /// combinators.
851 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
852 template <typename F1, typename F2>
853 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
854   const DagInit& d = InitPtrToDag(Case);
855   bool even = false;
856   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
857        B != E; ++B) {
858     Init* arg = *B;
859     if (even && dynamic_cast<DagInit*>(arg)
860         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
861       WalkCase(arg, TestCallback, StatementCallback);
862     else if (!even)
863       TestCallback(arg);
864     else
865       StatementCallback(arg);
866     even = !even;
867   }
868 }
869
870 /// ExtractOptionNames - A helper function object used by
871 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
872 class ExtractOptionNames {
873   llvm::StringSet<>& OptionNames_;
874
875   void processDag(const Init* Statement) {
876     const DagInit& Stmt = InitPtrToDag(Statement);
877     const std::string& ActionName = Stmt.getOperator()->getAsString();
878     if (ActionName == "forward" || ActionName == "forward_as" ||
879         ActionName == "unpack_values" || ActionName == "switch_on" ||
880         ActionName == "parameter_equals" || ActionName == "element_in_list" ||
881         ActionName == "not_empty" || ActionName == "empty") {
882       checkNumberOfArguments(&Stmt, 1);
883       const std::string& Name = InitPtrToString(Stmt.getArg(0));
884       OptionNames_.insert(Name);
885     }
886     else if (ActionName == "and" || ActionName == "or") {
887       for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
888         this->processDag(Stmt.getArg(i));
889       }
890     }
891   }
892
893 public:
894   ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
895   {}
896
897   void operator()(const Init* Statement) {
898     if (typeid(*Statement) == typeid(ListInit)) {
899       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
900       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
901            B != E; ++B)
902         this->processDag(*B);
903     }
904     else {
905       this->processDag(Statement);
906     }
907   }
908 };
909
910 /// CheckForSuperfluousOptions - Check that there are no side
911 /// effect-free options (specified only in the OptionList). Otherwise,
912 /// output a warning.
913 void CheckForSuperfluousOptions (const RecordVector& Edges,
914                                  const ToolDescriptions& ToolDescs,
915                                  const OptionDescriptions& OptDescs) {
916   llvm::StringSet<> nonSuperfluousOptions;
917
918   // Add all options mentioned in the ToolDesc.Actions to the set of
919   // non-superfluous options.
920   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
921          E = ToolDescs.end(); B != E; ++B) {
922     const ToolDescription& TD = *(*B);
923     ExtractOptionNames Callback(nonSuperfluousOptions);
924     if (TD.Actions)
925       WalkCase(TD.Actions, Callback, Callback);
926   }
927
928   // Add all options mentioned in the 'case' clauses of the
929   // OptionalEdges of the compilation graph to the set of
930   // non-superfluous options.
931   for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
932        B != E; ++B) {
933     const Record* Edge = *B;
934     DagInit* Weight = Edge->getValueAsDag("weight");
935
936     if (!isDagEmpty(Weight))
937       WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
938   }
939
940   // Check that all options in OptDescs belong to the set of
941   // non-superfluous options.
942   for (OptionDescriptions::const_iterator B = OptDescs.begin(),
943          E = OptDescs.end(); B != E; ++B) {
944     const OptionDescription& Val = B->second;
945     if (!nonSuperfluousOptions.count(Val.Name)
946         && Val.Type != OptionType::Alias)
947       llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
948         "Probable cause: this option is specified only in the OptionList.\n";
949   }
950 }
951
952 /// EmitCaseTest1Arg - Helper function used by
953 /// EmitCaseConstructHandler.
954 bool EmitCaseTest1Arg(const std::string& TestName,
955                       const DagInit& d,
956                       const OptionDescriptions& OptDescs,
957                       raw_ostream& O) {
958   checkNumberOfArguments(&d, 1);
959   const std::string& OptName = InitPtrToString(d.getArg(0));
960
961   if (TestName == "switch_on") {
962     const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
963     if (!OptionType::IsSwitch(OptDesc.Type))
964       throw OptName + ": incorrect option type - should be a switch!";
965     O << OptDesc.GenVariableName();
966     return true;
967   } else if (TestName == "input_languages_contain") {
968     O << "InLangs.count(\"" << OptName << "\") != 0";
969     return true;
970   } else if (TestName == "in_language") {
971     // This works only for single-argument Tool::GenerateAction. Join
972     // tools can process several files in different languages simultaneously.
973
974     // TODO: make this work with Edge::Weight (if possible).
975     O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
976     return true;
977   } else if (TestName == "not_empty" || TestName == "empty") {
978     const char* Test = (TestName == "empty") ? "" : "!";
979
980     if (OptName == "o") {
981       O << Test << "OutputFilename.empty()";
982       return true;
983     }
984     else {
985       const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
986       if (OptionType::IsSwitch(OptDesc.Type))
987         throw OptName
988           + ": incorrect option type - should be a list or parameter!";
989       O << Test << OptDesc.GenVariableName() << ".empty()";
990       return true;
991     }
992   }
993
994   return false;
995 }
996
997 /// EmitCaseTest2Args - Helper function used by
998 /// EmitCaseConstructHandler.
999 bool EmitCaseTest2Args(const std::string& TestName,
1000                        const DagInit& d,
1001                        const char* IndentLevel,
1002                        const OptionDescriptions& OptDescs,
1003                        raw_ostream& O) {
1004   checkNumberOfArguments(&d, 2);
1005   const std::string& OptName = InitPtrToString(d.getArg(0));
1006   const std::string& OptArg = InitPtrToString(d.getArg(1));
1007   const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1008
1009   if (TestName == "parameter_equals") {
1010     if (!OptionType::IsParameter(OptDesc.Type))
1011       throw OptName + ": incorrect option type - should be a parameter!";
1012     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1013     return true;
1014   }
1015   else if (TestName == "element_in_list") {
1016     if (!OptionType::IsList(OptDesc.Type))
1017       throw OptName + ": incorrect option type - should be a list!";
1018     const std::string& VarName = OptDesc.GenVariableName();
1019     O << "std::find(" << VarName << ".begin(),\n"
1020       << IndentLevel << Indent1 << VarName << ".end(), \""
1021       << OptArg << "\") != " << VarName << ".end()";
1022     return true;
1023   }
1024
1025   return false;
1026 }
1027
1028 // Forward declaration.
1029 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1030 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
1031                   const OptionDescriptions& OptDescs,
1032                   raw_ostream& O);
1033
1034 /// EmitLogicalOperationTest - Helper function used by
1035 /// EmitCaseConstructHandler.
1036 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1037                               const char* IndentLevel,
1038                               const OptionDescriptions& OptDescs,
1039                               raw_ostream& O) {
1040   O << '(';
1041   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1042     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1043     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1044     if (j != NumArgs - 1)
1045       O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
1046     else
1047       O << ')';
1048   }
1049 }
1050
1051 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1052 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
1053                   const OptionDescriptions& OptDescs,
1054                   raw_ostream& O) {
1055   const std::string& TestName = d.getOperator()->getAsString();
1056
1057   if (TestName == "and")
1058     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1059   else if (TestName == "or")
1060     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1061   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1062     return;
1063   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1064     return;
1065   else
1066     throw TestName + ": unknown edge property!";
1067 }
1068
1069 // Emit code that handles the 'case' construct.
1070 // Takes a function object that should emit code for every case clause.
1071 // Callback's type is
1072 // void F(Init* Statement, const char* IndentLevel, raw_ostream& O).
1073 template <typename F>
1074 void EmitCaseConstructHandler(const Init* Dag, const char* IndentLevel,
1075                               F Callback, bool EmitElseIf,
1076                               const OptionDescriptions& OptDescs,
1077                               raw_ostream& O) {
1078   const DagInit* d = &InitPtrToDag(Dag);
1079   if (d->getOperator()->getAsString() != "case")
1080     throw std::string("EmitCaseConstructHandler should be invoked"
1081                       " only on 'case' expressions!");
1082
1083   unsigned numArgs = d->getNumArgs();
1084   if (d->getNumArgs() < 2)
1085     throw "There should be at least one clause in the 'case' expression:\n"
1086       + d->getAsString();
1087
1088   for (unsigned i = 0; i != numArgs; ++i) {
1089     const DagInit& Test = InitPtrToDag(d->getArg(i));
1090
1091     // Emit the test.
1092     if (Test.getOperator()->getAsString() == "default") {
1093       if (i+2 != numArgs)
1094         throw std::string("The 'default' clause should be the last in the"
1095                           "'case' construct!");
1096       O << IndentLevel << "else {\n";
1097     }
1098     else {
1099       O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1100       EmitCaseTest(Test, IndentLevel, OptDescs, O);
1101       O << ") {\n";
1102     }
1103
1104     // Emit the corresponding statement.
1105     ++i;
1106     if (i == numArgs)
1107       throw "Case construct handler: no corresponding action "
1108         "found for the test " + Test.getAsString() + '!';
1109
1110     Init* arg = d->getArg(i);
1111     const DagInit* nd = dynamic_cast<DagInit*>(arg);
1112     if (nd && (nd->getOperator()->getAsString() == "case")) {
1113       // Handle the nested 'case'.
1114       EmitCaseConstructHandler(nd, (std::string(IndentLevel) + Indent1).c_str(),
1115                                Callback, EmitElseIf, OptDescs, O);
1116     }
1117     else {
1118       Callback(arg, (std::string(IndentLevel) + Indent1).c_str(), O);
1119     }
1120     O << IndentLevel << "}\n";
1121   }
1122 }
1123
1124 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1125 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1126 /// Helper function used by EmitCmdLineVecFill and.
1127 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1128   const char* Delimiters = " \t\n\v\f\r";
1129   enum TokenizerState
1130   { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1131   cur_st  = Normal;
1132
1133   if (CmdLine.empty())
1134     return;
1135   Out.push_back("");
1136
1137   std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1138     E = CmdLine.size();
1139
1140   for (; B != E; ++B) {
1141     char cur_ch = CmdLine[B];
1142
1143     switch (cur_st) {
1144     case Normal:
1145       if (cur_ch == '$') {
1146         cur_st = SpecialCommand;
1147         break;
1148       }
1149       if (oneOf(Delimiters, cur_ch)) {
1150         // Skip whitespace
1151         B = CmdLine.find_first_not_of(Delimiters, B);
1152         if (B == std::string::npos) {
1153           B = E-1;
1154           continue;
1155         }
1156         --B;
1157         Out.push_back("");
1158         continue;
1159       }
1160       break;
1161
1162
1163     case SpecialCommand:
1164       if (oneOf(Delimiters, cur_ch)) {
1165         cur_st = Normal;
1166         Out.push_back("");
1167         continue;
1168       }
1169       if (cur_ch == '(') {
1170         Out.push_back("");
1171         cur_st = InsideSpecialCommand;
1172         continue;
1173       }
1174       break;
1175
1176     case InsideSpecialCommand:
1177       if (oneOf(Delimiters, cur_ch)) {
1178         continue;
1179       }
1180       if (cur_ch == '\'') {
1181         cur_st = InsideQuotationMarks;
1182         Out.push_back("");
1183         continue;
1184       }
1185       if (cur_ch == ')') {
1186         cur_st = Normal;
1187         Out.push_back("");
1188       }
1189       if (cur_ch == ',') {
1190         continue;
1191       }
1192
1193       break;
1194
1195     case InsideQuotationMarks:
1196       if (cur_ch == '\'') {
1197         cur_st = InsideSpecialCommand;
1198         continue;
1199       }
1200       break;
1201     }
1202
1203     Out.back().push_back(cur_ch);
1204   }
1205 }
1206
1207 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1208 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1209 StrVector::const_iterator SubstituteSpecialCommands
1210 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1211 {
1212
1213   const std::string& cmd = *Pos;
1214
1215   if (cmd == "$CALL") {
1216     checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1217     const std::string& CmdName = *Pos;
1218
1219     if (CmdName == ")")
1220       throw std::string("$CALL invocation: empty argument list!");
1221
1222     O << "hooks::";
1223     O << CmdName << "(";
1224
1225
1226     bool firstIteration = true;
1227     while (true) {
1228       checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1229       const std::string& Arg = *Pos;
1230       assert(Arg.size() != 0);
1231
1232       if (Arg[0] == ')')
1233         break;
1234
1235       if (firstIteration)
1236         firstIteration = false;
1237       else
1238         O << ", ";
1239
1240       O << '"' << Arg << '"';
1241     }
1242
1243     O << ')';
1244
1245   }
1246   else if (cmd == "$ENV") {
1247     checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1248     const std::string& EnvName = *Pos;
1249
1250     if (EnvName == ")")
1251       throw "$ENV invocation: empty argument list!";
1252
1253     O << "checkCString(std::getenv(\"";
1254     O << EnvName;
1255     O << "\"))";
1256
1257     checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1258   }
1259   else {
1260     throw "Unknown special command: " + cmd;
1261   }
1262
1263   const std::string& Leftover = *Pos;
1264   assert(Leftover.at(0) == ')');
1265   if (Leftover.size() != 1)
1266     O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1267
1268   return Pos;
1269 }
1270
1271 /// EmitCmdLineVecFill - Emit code that fills in the command line
1272 /// vector. Helper function used by EmitGenerateActionMethod().
1273 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1274                         bool IsJoin, const char* IndentLevel,
1275                         raw_ostream& O) {
1276   StrVector StrVec;
1277   TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1278
1279   if (StrVec.empty())
1280     throw "Tool '" + ToolName + "' has empty command line!";
1281
1282   StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1283
1284   // If there is a hook invocation on the place of the first command, skip it.
1285   assert(!StrVec[0].empty());
1286   if (StrVec[0][0] == '$') {
1287     while (I != E && (*I)[0] != ')' )
1288       ++I;
1289
1290     // Skip the ')' symbol.
1291     ++I;
1292   }
1293   else {
1294     ++I;
1295   }
1296
1297   for (; I != E; ++I) {
1298     const std::string& cmd = *I;
1299     assert(!cmd.empty());
1300     O << IndentLevel;
1301     if (cmd.at(0) == '$') {
1302       if (cmd == "$INFILE") {
1303         if (IsJoin)
1304           O << "for (PathVector::const_iterator B = inFiles.begin()"
1305             << ", E = inFiles.end();\n"
1306             << IndentLevel << "B != E; ++B)\n"
1307             << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1308         else
1309           O << "vec.push_back(inFile.toString());\n";
1310       }
1311       else if (cmd == "$OUTFILE") {
1312         O << "vec.push_back(out_file);\n";
1313       }
1314       else {
1315         O << "vec.push_back(";
1316         I = SubstituteSpecialCommands(I, E, O);
1317         O << ");\n";
1318       }
1319     }
1320     else {
1321       O << "vec.push_back(\"" << cmd << "\");\n";
1322     }
1323   }
1324   O << IndentLevel << "cmd = ";
1325
1326   if (StrVec[0][0] == '$')
1327     SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1328   else
1329     O << '"' << StrVec[0] << '"';
1330   O << ";\n";
1331 }
1332
1333 /// EmitCmdLineVecFillCallback - A function object wrapper around
1334 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1335 /// argument to EmitCaseConstructHandler().
1336 class EmitCmdLineVecFillCallback {
1337   bool IsJoin;
1338   const std::string& ToolName;
1339  public:
1340   EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1341     : IsJoin(J), ToolName(TN) {}
1342
1343   void operator()(const Init* Statement, const char* IndentLevel,
1344                   raw_ostream& O) const
1345   {
1346     EmitCmdLineVecFill(Statement, ToolName, IsJoin,
1347                        IndentLevel, O);
1348   }
1349 };
1350
1351 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1352 /// implement EmitActionHandler. Emits code for
1353 /// handling the (forward) and (forward_as) option properties.
1354 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1355                                             const char* Indent,
1356                                             const std::string& NewName,
1357                                             raw_ostream& O) {
1358   const std::string& Name = NewName.empty()
1359     ? ("-" + D.Name)
1360     : NewName;
1361
1362   switch (D.Type) {
1363   case OptionType::Switch:
1364     O << Indent << "vec.push_back(\"" << Name << "\");\n";
1365     break;
1366   case OptionType::Parameter:
1367     O << Indent << "vec.push_back(\"" << Name << "\");\n";
1368     O << Indent << "vec.push_back(" << D.GenVariableName() << ");\n";
1369     break;
1370   case OptionType::Prefix:
1371     O << Indent << "vec.push_back(\"" << Name << "\" + "
1372       << D.GenVariableName() << ");\n";
1373     break;
1374   case OptionType::PrefixList:
1375     O << Indent << "for (" << D.GenTypeDeclaration()
1376       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1377       << Indent << "E = " << D.GenVariableName() << ".end(); B != E;) {\n"
1378       << Indent << Indent1 << "vec.push_back(\"" << Name << "\" + "
1379       << "*B);\n"
1380       << Indent << Indent1 << "++B;\n";
1381
1382     for (int i = 1, j = D.MultiVal; i < j; ++i) {
1383       O << Indent << Indent1 << "vec.push_back(*B);\n"
1384         << Indent << Indent1 << "++B;\n";
1385     }
1386
1387     O << Indent << "}\n";
1388     break;
1389   case OptionType::ParameterList:
1390     O << Indent << "for (" << D.GenTypeDeclaration()
1391       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1392       << Indent << "E = " << D.GenVariableName()
1393       << ".end() ; B != E;) {\n"
1394       << Indent << Indent1 << "vec.push_back(\"" << Name << "\");\n";
1395
1396     for (int i = 0, j = D.MultiVal; i < j; ++i) {
1397       O << Indent << Indent1 << "vec.push_back(*B);\n"
1398         << Indent << Indent1 << "++B;\n";
1399     }
1400
1401     O << Indent << "}\n";
1402     break;
1403   case OptionType::Alias:
1404   default:
1405     throw std::string("Aliases are not allowed in tool option descriptions!");
1406   }
1407 }
1408
1409 /// EmitActionHandler - Emit code that handles actions. Used by
1410 /// EmitGenerateActionMethod() as an argument to
1411 /// EmitCaseConstructHandler().
1412 class EmitActionHandler {
1413   const OptionDescriptions& OptDescs;
1414
1415   void processActionDag(const Init* Statement, const char* IndentLevel,
1416                         raw_ostream& O) const
1417   {
1418     const DagInit& Dag = InitPtrToDag(Statement);
1419     const std::string& ActionName = Dag.getOperator()->getAsString();
1420
1421     if (ActionName == "append_cmd") {
1422       checkNumberOfArguments(&Dag, 1);
1423       const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1424       StrVector Out;
1425       llvm::SplitString(Cmd, Out);
1426
1427       for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1428            B != E; ++B)
1429         O << IndentLevel << "vec.push_back(\"" << *B << "\");\n";
1430     }
1431     else if (ActionName == "error") {
1432       O << IndentLevel << "throw std::runtime_error(\"" <<
1433         (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1434          : "Unknown error!")
1435         << "\");\n";
1436     }
1437     else if (ActionName == "forward") {
1438       checkNumberOfArguments(&Dag, 1);
1439       const std::string& Name = InitPtrToString(Dag.getArg(0));
1440       EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1441                                             IndentLevel, "", O);
1442     }
1443     else if (ActionName == "forward_as") {
1444       checkNumberOfArguments(&Dag, 2);
1445       const std::string& Name = InitPtrToString(Dag.getArg(0));
1446       const std::string& NewName = InitPtrToString(Dag.getArg(1));
1447       EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1448                                             IndentLevel, NewName, O);
1449     }
1450     else if (ActionName == "output_suffix") {
1451       checkNumberOfArguments(&Dag, 1);
1452       const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1453       O << IndentLevel << "output_suffix = \"" << OutSuf << "\";\n";
1454     }
1455     else if (ActionName == "stop_compilation") {
1456       O << IndentLevel << "stop_compilation = true;\n";
1457     }
1458     else if (ActionName == "unpack_values") {
1459       checkNumberOfArguments(&Dag, 1);
1460       const std::string& Name = InitPtrToString(Dag.getArg(0));
1461       const OptionDescription& D = OptDescs.FindOption(Name);
1462
1463       if (D.isMultiVal())
1464         throw std::string("Can't use unpack_values with multi-valued options!");
1465
1466       if (OptionType::IsList(D.Type)) {
1467         O << IndentLevel << "for (" << D.GenTypeDeclaration()
1468           << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1469           << IndentLevel << "E = " << D.GenVariableName()
1470           << ".end(); B != E; ++B)\n"
1471           << IndentLevel << Indent1 << "llvm::SplitString(*B, vec, \",\");\n";
1472       }
1473       else if (OptionType::IsParameter(D.Type)){
1474         O << Indent3 << "llvm::SplitString("
1475           << D.GenVariableName() << ", vec, \",\");\n";
1476       }
1477       else {
1478         throw "Option '" + D.Name +
1479           "': switches can't have the 'unpack_values' property!";
1480       }
1481     }
1482     else {
1483       throw "Unknown action name: " + ActionName + "!";
1484     }
1485   }
1486  public:
1487   EmitActionHandler(const OptionDescriptions& OD)
1488     : OptDescs(OD) {}
1489
1490   void operator()(const Init* Statement, const char* IndentLevel,
1491                   raw_ostream& O) const
1492   {
1493     if (typeid(*Statement) == typeid(ListInit)) {
1494       const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1495       for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1496            B != E; ++B)
1497         this->processActionDag(*B, IndentLevel, O);
1498     }
1499     else {
1500       this->processActionDag(Statement, IndentLevel, O);
1501     }
1502   }
1503 };
1504
1505 // EmitGenerateActionMethod - Emit one of two versions of the
1506 // Tool::GenerateAction() method.
1507 void EmitGenerateActionMethod (const ToolDescription& D,
1508                                const OptionDescriptions& OptDescs,
1509                                bool IsJoin, raw_ostream& O) {
1510   if (IsJoin)
1511     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1512   else
1513     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1514
1515   O << Indent2 << "bool HasChildren,\n"
1516     << Indent2 << "const llvm::sys::Path& TempDir,\n"
1517     << Indent2 << "const InputLanguagesSet& InLangs,\n"
1518     << Indent2 << "const LanguageMap& LangMap) const\n"
1519     << Indent1 << "{\n"
1520     << Indent2 << "std::string cmd;\n"
1521     << Indent2 << "std::vector<std::string> vec;\n"
1522     << Indent2 << "bool stop_compilation = !HasChildren;\n"
1523     << Indent2 << "const char* output_suffix = \"" << D.OutputSuffix << "\";\n"
1524     << Indent2 << "std::string out_file;\n\n";
1525
1526   // For every understood option, emit handling code.
1527   if (D.Actions)
1528     EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1529                              false, OptDescs, O);
1530
1531   O << '\n' << Indent2
1532     << "out_file = OutFilename(" << (IsJoin ? "sys::Path(),\n" : "inFile,\n")
1533     << Indent3 << "TempDir, stop_compilation, output_suffix).toString();\n\n";
1534
1535   // cmd_line is either a string or a 'case' construct.
1536   if (!D.CmdLine)
1537     throw "Tool " + D.Name + " has no cmd_line property!";
1538   else if (typeid(*D.CmdLine) == typeid(StringInit))
1539     EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1540   else
1541     EmitCaseConstructHandler(D.CmdLine, Indent2,
1542                              EmitCmdLineVecFillCallback(IsJoin, D.Name),
1543                              true, OptDescs, O);
1544
1545   // Handle the Sink property.
1546   if (D.isSink()) {
1547     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1548       << Indent3 << "vec.insert(vec.end(), "
1549       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1550       << Indent2 << "}\n";
1551   }
1552
1553   O << Indent2 << "return Action(cmd, vec, stop_compilation, out_file);\n"
1554     << Indent1 << "}\n\n";
1555 }
1556
1557 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1558 /// a given Tool class.
1559 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1560                                 const OptionDescriptions& OptDescs,
1561                                 raw_ostream& O) {
1562   if (!ToolDesc.isJoin())
1563     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1564       << Indent2 << "bool HasChildren,\n"
1565       << Indent2 << "const llvm::sys::Path& TempDir,\n"
1566       << Indent2 << "const InputLanguagesSet& InLangs,\n"
1567       << Indent2 << "const LanguageMap& LangMap) const\n"
1568       << Indent1 << "{\n"
1569       << Indent2 << "throw std::runtime_error(\"" << ToolDesc.Name
1570       << " is not a Join tool!\");\n"
1571       << Indent1 << "}\n\n";
1572   else
1573     EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1574
1575   EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1576 }
1577
1578 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1579 /// methods for a given Tool class.
1580 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
1581   O << Indent1 << "const char** InputLanguages() const {\n"
1582     << Indent2 << "return InputLanguages_;\n"
1583     << Indent1 << "}\n\n";
1584
1585   if (D.OutLanguage.empty())
1586     throw "Tool " + D.Name + " has no 'out_language' property!";
1587
1588   O << Indent1 << "const char* OutputLanguage() const {\n"
1589     << Indent2 << "return \"" << D.OutLanguage << "\";\n"
1590     << Indent1 << "}\n\n";
1591 }
1592
1593 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1594 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
1595   O << Indent1 << "const char* Name() const {\n"
1596     << Indent2 << "return \"" << D.Name << "\";\n"
1597     << Indent1 << "}\n\n";
1598 }
1599
1600 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1601 /// class.
1602 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
1603   O << Indent1 << "bool IsJoin() const {\n";
1604   if (D.isJoin())
1605     O << Indent2 << "return true;\n";
1606   else
1607     O << Indent2 << "return false;\n";
1608   O << Indent1 << "}\n\n";
1609 }
1610
1611 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1612 /// given Tool class.
1613 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
1614   if (D.InLanguage.empty())
1615     throw "Tool " + D.Name + " has no 'in_language' property!";
1616
1617   O << "const char* " << D.Name << "::InputLanguages_[] = {";
1618   for (StrVector::const_iterator B = D.InLanguage.begin(),
1619          E = D.InLanguage.end(); B != E; ++B)
1620     O << '\"' << *B << "\", ";
1621   O << "0};\n\n";
1622 }
1623
1624 /// EmitToolClassDefinition - Emit a Tool class definition.
1625 void EmitToolClassDefinition (const ToolDescription& D,
1626                               const OptionDescriptions& OptDescs,
1627                               raw_ostream& O) {
1628   if (D.Name == "root")
1629     return;
1630
1631   // Header
1632   O << "class " << D.Name << " : public ";
1633   if (D.isJoin())
1634     O << "JoinTool";
1635   else
1636     O << "Tool";
1637
1638   O << "{\nprivate:\n"
1639     << Indent1 << "static const char* InputLanguages_[];\n\n";
1640
1641   O << "public:\n";
1642   EmitNameMethod(D, O);
1643   EmitInOutLanguageMethods(D, O);
1644   EmitIsJoinMethod(D, O);
1645   EmitGenerateActionMethods(D, OptDescs, O);
1646
1647   // Close class definition
1648   O << "};\n";
1649
1650   EmitStaticMemberDefinitions(D, O);
1651
1652 }
1653
1654 /// EmitOptionDefinitions - Iterate over a list of option descriptions
1655 /// and emit registration code.
1656 void EmitOptionDefinitions (const OptionDescriptions& descs,
1657                             bool HasSink, bool HasExterns,
1658                             raw_ostream& O)
1659 {
1660   std::vector<OptionDescription> Aliases;
1661
1662   // Emit static cl::Option variables.
1663   for (OptionDescriptions::const_iterator B = descs.begin(),
1664          E = descs.end(); B!=E; ++B) {
1665     const OptionDescription& val = B->second;
1666
1667     if (val.Type == OptionType::Alias) {
1668       Aliases.push_back(val);
1669       continue;
1670     }
1671
1672     if (val.isExtern())
1673       O << "extern ";
1674
1675     O << val.GenTypeDeclaration() << ' '
1676       << val.GenVariableName();
1677
1678     if (val.isExtern()) {
1679       O << ";\n";
1680       continue;
1681     }
1682
1683     O << "(\"" << val.Name << "\"\n";
1684
1685     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1686       O << ", cl::Prefix";
1687
1688     if (val.isRequired()) {
1689       if (OptionType::IsList(val.Type) && !val.isMultiVal())
1690         O << ", cl::OneOrMore";
1691       else
1692         O << ", cl::Required";
1693     }
1694     else if (val.isOneOrMore() && OptionType::IsList(val.Type)) {
1695         O << ", cl::OneOrMore";
1696     }
1697     else if (val.isZeroOrOne() && OptionType::IsList(val.Type)) {
1698         O << ", cl::ZeroOrOne";
1699     }
1700
1701     if (val.isReallyHidden()) {
1702       O << ", cl::ReallyHidden";
1703     }
1704     else if (val.isHidden()) {
1705       O << ", cl::Hidden";
1706     }
1707
1708     if (val.MultiVal > 1)
1709       O << ", cl::multi_val(" << val.MultiVal << ")";
1710
1711     if (!val.Help.empty())
1712       O << ", cl::desc(\"" << val.Help << "\")";
1713
1714     O << ");\n\n";
1715   }
1716
1717   // Emit the aliases (they should go after all the 'proper' options).
1718   for (std::vector<OptionDescription>::const_iterator
1719          B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1720     const OptionDescription& val = *B;
1721
1722     O << val.GenTypeDeclaration() << ' '
1723       << val.GenVariableName()
1724       << "(\"" << val.Name << '\"';
1725
1726     const OptionDescription& D = descs.FindOption(val.Help);
1727     O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1728
1729     O << ", cl::desc(\"" << "An alias for -" + val.Help  << "\"));\n";
1730   }
1731
1732   // Emit the sink option.
1733   if (HasSink)
1734     O << (HasExterns ? "extern cl" : "cl")
1735       << "::list<std::string> " << SinkOptionName
1736       << (HasExterns ? ";\n" : "(cl::Sink);\n");
1737
1738   O << '\n';
1739 }
1740
1741 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1742 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
1743 {
1744   // Generate code
1745   O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1746
1747   // Get the relevant field out of RecordKeeper
1748   const Record* LangMapRecord = Records.getDef("LanguageMap");
1749
1750   // It is allowed for a plugin to have no language map.
1751   if (LangMapRecord) {
1752
1753     ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1754     if (!LangsToSuffixesList)
1755       throw std::string("Error in the language map definition!");
1756
1757     for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1758       const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1759
1760       const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1761       const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1762
1763       for (unsigned i = 0; i < Suffixes->size(); ++i)
1764         O << Indent1 << "langMap[\""
1765           << InitPtrToString(Suffixes->getElement(i))
1766           << "\"] = \"" << Lang << "\";\n";
1767     }
1768   }
1769
1770   O << "}\n\n";
1771 }
1772
1773 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1774 /// by EmitEdgeClass().
1775 void IncDecWeight (const Init* i, const char* IndentLevel,
1776                    raw_ostream& O) {
1777   const DagInit& d = InitPtrToDag(i);
1778   const std::string& OpName = d.getOperator()->getAsString();
1779
1780   if (OpName == "inc_weight") {
1781     O << IndentLevel << "ret += ";
1782   }
1783   else if (OpName == "dec_weight") {
1784     O << IndentLevel << "ret -= ";
1785   }
1786   else if (OpName == "error") {
1787     O << IndentLevel << "throw std::runtime_error(\"" <<
1788         (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1789          : "Unknown error!")
1790       << "\");\n";
1791     return;
1792   }
1793
1794   else
1795     throw "Unknown operator in edge properties list: " + OpName + '!' +
1796       "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
1797
1798   if (d.getNumArgs() > 0)
1799     O << InitPtrToInt(d.getArg(0)) << ";\n";
1800   else
1801     O << "2;\n";
1802
1803 }
1804
1805 /// EmitEdgeClass - Emit a single Edge# class.
1806 void EmitEdgeClass (unsigned N, const std::string& Target,
1807                     DagInit* Case, const OptionDescriptions& OptDescs,
1808                     raw_ostream& O) {
1809
1810   // Class constructor.
1811   O << "class Edge" << N << ": public Edge {\n"
1812     << "public:\n"
1813     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1814     << "\") {}\n\n"
1815
1816   // Function Weight().
1817     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1818     << Indent2 << "unsigned ret = 0;\n";
1819
1820   // Handle the 'case' construct.
1821   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1822
1823   O << Indent2 << "return ret;\n"
1824     << Indent1 << "};\n\n};\n\n";
1825 }
1826
1827 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1828 void EmitEdgeClasses (const RecordVector& EdgeVector,
1829                       const OptionDescriptions& OptDescs,
1830                       raw_ostream& O) {
1831   int i = 0;
1832   for (RecordVector::const_iterator B = EdgeVector.begin(),
1833          E = EdgeVector.end(); B != E; ++B) {
1834     const Record* Edge = *B;
1835     const std::string& NodeB = Edge->getValueAsString("b");
1836     DagInit* Weight = Edge->getValueAsDag("weight");
1837
1838     if (!isDagEmpty(Weight))
1839       EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
1840     ++i;
1841   }
1842 }
1843
1844 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1845 /// function.
1846 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1847                                    const ToolDescriptions& ToolDescs,
1848                                    raw_ostream& O)
1849 {
1850   O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1851
1852   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1853          E = ToolDescs.end(); B != E; ++B)
1854     O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
1855
1856   O << '\n';
1857
1858   // Insert edges.
1859
1860   int i = 0;
1861   for (RecordVector::const_iterator B = EdgeVector.begin(),
1862          E = EdgeVector.end(); B != E; ++B) {
1863     const Record* Edge = *B;
1864     const std::string& NodeA = Edge->getValueAsString("a");
1865     const std::string& NodeB = Edge->getValueAsString("b");
1866     DagInit* Weight = Edge->getValueAsDag("weight");
1867
1868     O << Indent1 << "G.insertEdge(\"" << NodeA << "\", ";
1869
1870     if (isDagEmpty(Weight))
1871       O << "new SimpleEdge(\"" << NodeB << "\")";
1872     else
1873       O << "new Edge" << i << "()";
1874
1875     O << ");\n";
1876     ++i;
1877   }
1878
1879   O << "}\n\n";
1880 }
1881
1882 /// ExtractHookNames - Extract the hook names from all instances of
1883 /// $CALL(HookName) in the provided command line string. Helper
1884 /// function used by FillInHookNames().
1885 class ExtractHookNames {
1886   llvm::StringMap<unsigned>& HookNames_;
1887 public:
1888   ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
1889   : HookNames_(HookNames) {}
1890
1891   void operator()(const Init* CmdLine) {
1892     StrVector cmds;
1893     TokenizeCmdline(InitPtrToString(CmdLine), cmds);
1894     for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1895          B != E; ++B) {
1896       const std::string& cmd = *B;
1897
1898       if (cmd == "$CALL") {
1899         unsigned NumArgs = 0;
1900         checkedIncrement(B, E, "Syntax error in $CALL invocation!");
1901         const std::string& HookName = *B;
1902
1903
1904         if (HookName.at(0) == ')')
1905           throw "$CALL invoked with no arguments!";
1906
1907         while (++B != E && B->at(0) != ')') {
1908           ++NumArgs;
1909         }
1910
1911         StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
1912
1913         if (H != HookNames_.end() && H->second != NumArgs)
1914           throw "Overloading of hooks is not allowed. Overloaded hook: "
1915             + HookName;
1916         else
1917           HookNames_[HookName] = NumArgs;
1918
1919       }
1920     }
1921   }
1922 };
1923
1924 /// FillInHookNames - Actually extract the hook names from all command
1925 /// line strings. Helper function used by EmitHookDeclarations().
1926 void FillInHookNames(const ToolDescriptions& ToolDescs,
1927                      llvm::StringMap<unsigned>& HookNames)
1928 {
1929   // For all command lines:
1930   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1931          E = ToolDescs.end(); B != E; ++B) {
1932     const ToolDescription& D = *(*B);
1933     if (!D.CmdLine)
1934       continue;
1935     if (dynamic_cast<StringInit*>(D.CmdLine))
1936       // This is a string.
1937       ExtractHookNames(HookNames).operator()(D.CmdLine);
1938     else
1939       // This is a 'case' construct.
1940       WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
1941   }
1942 }
1943
1944 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1945 /// property records and emit hook function declaration for each
1946 /// instance of $CALL(HookName).
1947 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
1948   llvm::StringMap<unsigned> HookNames;
1949
1950   FillInHookNames(ToolDescs, HookNames);
1951   if (HookNames.empty())
1952     return;
1953
1954   O << "namespace hooks {\n";
1955   for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
1956          E = HookNames.end(); B != E; ++B) {
1957     O << Indent1 << "std::string " << B->first() << "(";
1958
1959     for (unsigned i = 0, j = B->second; i < j; ++i) {
1960       O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
1961     }
1962
1963     O <<");\n";
1964   }
1965   O << "}\n\n";
1966 }
1967
1968 /// EmitRegisterPlugin - Emit code to register this plugin.
1969 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
1970   O << "struct Plugin : public llvmc::BasePlugin {\n\n"
1971     << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
1972     << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1973     << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1974     << Indent1
1975     << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1976     << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1977     << "};\n\n"
1978
1979     << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
1980 }
1981
1982 /// EmitIncludes - Emit necessary #include directives and some
1983 /// additional declarations.
1984 void EmitIncludes(raw_ostream& O) {
1985   O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1986     << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
1987     << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1988     << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1989
1990     << "#include \"llvm/ADT/StringExtras.h\"\n"
1991     << "#include \"llvm/Support/CommandLine.h\"\n\n"
1992
1993     << "#include <cstdlib>\n"
1994     << "#include <stdexcept>\n\n"
1995
1996     << "using namespace llvm;\n"
1997     << "using namespace llvmc;\n\n"
1998
1999     << "extern cl::opt<std::string> OutputFilename;\n\n"
2000
2001     << "inline const char* checkCString(const char* s)\n"
2002     << "{ return s == NULL ? \"\" : s; }\n\n";
2003 }
2004
2005
2006 /// PluginData - Holds all information about a plugin.
2007 struct PluginData {
2008   OptionDescriptions OptDescs;
2009   bool HasSink;
2010   bool HasExterns;
2011   ToolDescriptions ToolDescs;
2012   RecordVector Edges;
2013   int Priority;
2014 };
2015
2016 /// HasSink - Go through the list of tool descriptions and check if
2017 /// there are any with the 'sink' property set.
2018 bool HasSink(const ToolDescriptions& ToolDescs) {
2019   for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2020          E = ToolDescs.end(); B != E; ++B)
2021     if ((*B)->isSink())
2022       return true;
2023
2024   return false;
2025 }
2026
2027 /// HasExterns - Go through the list of option descriptions and check
2028 /// if there are any external options.
2029 bool HasExterns(const OptionDescriptions& OptDescs) {
2030  for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2031          E = OptDescs.end(); B != E; ++B)
2032     if (B->second.isExtern())
2033       return true;
2034
2035   return false;
2036 }
2037
2038 /// CollectPluginData - Collect tool and option properties,
2039 /// compilation graph edges and plugin priority from the parse tree.
2040 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2041   // Collect option properties.
2042   const RecordVector& OptionLists =
2043     Records.getAllDerivedDefinitions("OptionList");
2044   CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2045                             Data.OptDescs);
2046
2047   // Collect tool properties.
2048   const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2049   CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2050   Data.HasSink = HasSink(Data.ToolDescs);
2051   Data.HasExterns = HasExterns(Data.OptDescs);
2052
2053   // Collect compilation graph edges.
2054   const RecordVector& CompilationGraphs =
2055     Records.getAllDerivedDefinitions("CompilationGraph");
2056   FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2057                    Data.Edges);
2058
2059   // Calculate the priority of this plugin.
2060   const RecordVector& Priorities =
2061     Records.getAllDerivedDefinitions("PluginPriority");
2062   Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2063 }
2064
2065 /// CheckPluginData - Perform some sanity checks on the collected data.
2066 void CheckPluginData(PluginData& Data) {
2067   // Filter out all tools not mentioned in the compilation graph.
2068   FilterNotInGraph(Data.Edges, Data.ToolDescs);
2069
2070   // Typecheck the compilation graph.
2071   TypecheckGraph(Data.Edges, Data.ToolDescs);
2072
2073   // Check that there are no options without side effects (specified
2074   // only in the OptionList).
2075   CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2076
2077 }
2078
2079 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2080   // Emit file header.
2081   EmitIncludes(O);
2082
2083   // Emit global option registration code.
2084   EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2085
2086   // Emit hook declarations.
2087   EmitHookDeclarations(Data.ToolDescs, O);
2088
2089   O << "namespace {\n\n";
2090
2091   // Emit PopulateLanguageMap() function
2092   // (a language map maps from file extensions to language names).
2093   EmitPopulateLanguageMap(Records, O);
2094
2095   // Emit Tool classes.
2096   for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2097          E = Data.ToolDescs.end(); B!=E; ++B)
2098     EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2099
2100   // Emit Edge# classes.
2101   EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2102
2103   // Emit PopulateCompilationGraph() function.
2104   EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2105
2106   // Emit code for plugin registration.
2107   EmitRegisterPlugin(Data.Priority, O);
2108
2109   O << "} // End anonymous namespace.\n\n";
2110
2111   // Force linkage magic.
2112   O << "namespace llvmc {\n";
2113   O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2114   O << "}\n";
2115
2116   // EOF
2117 }
2118
2119
2120 // End of anonymous namespace
2121 }
2122
2123 /// run - The back-end entry point.
2124 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2125   try {
2126   PluginData Data;
2127
2128   CollectPluginData(Records, Data);
2129   CheckPluginData(Data);
2130
2131   EmitSourceFileHeader("LLVMC Configuration Library", O);
2132   EmitPluginCode(Data, O);
2133
2134   } catch (std::exception& Error) {
2135     throw Error.what() + std::string(" - usually this means a syntax error.");
2136   }
2137 }