08f008e1cc938a6473bd7f6db84ce45c43b8baa9
[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 "llvm/Support/Streams.h"
23
24 #include <algorithm>
25 #include <cassert>
26 #include <functional>
27 #include <stdexcept>
28 #include <string>
29
30 using namespace llvm;
31
32 namespace {
33
34 //===----------------------------------------------------------------------===//
35 /// Typedefs
36
37 typedef std::vector<Record*> RecordVector;
38 typedef std::vector<std::string> StrVector;
39
40 //===----------------------------------------------------------------------===//
41 /// Constants
42
43 // Indentation strings.
44 const char * Indent1 = "    ";
45 const char * Indent2 = "        ";
46 const char * Indent3 = "            ";
47 const char * Indent4 = "                ";
48
49 // Default help string.
50 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51
52 // Name for the "sink" option.
53 const char * SinkOptionName = "AutoGeneratedSinkOption";
54
55 //===----------------------------------------------------------------------===//
56 /// Helper functions
57
58 int InitPtrToInt(const Init* ptr) {
59   const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
60   return val.getValue();
61 }
62
63 const std::string& InitPtrToString(const Init* ptr) {
64   const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
65   return val.getValue();
66 }
67
68 const ListInit& InitPtrToList(const Init* ptr) {
69   const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
70   return val;
71 }
72
73 const DagInit& InitPtrToDag(const Init* ptr) {
74   const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
75   return val;
76 }
77
78 // checkNumberOfArguments - Ensure that the number of args in d is
79 // less than or equal to min_arguments, otherwise throw an exception.
80 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
81   if (d->getNumArgs() < min_arguments)
82     throw "Property " + d->getOperator()->getAsString()
83       + " has too few arguments!";
84 }
85
86 // isDagEmpty - is this DAG marked with an empty marker?
87 bool isDagEmpty (const DagInit* d) {
88   return d->getOperator()->getAsString() == "empty";
89 }
90
91 //===----------------------------------------------------------------------===//
92 /// Back-end specific code
93
94 // A command-line option can have one of the following types:
95 //
96 // Switch - a simple switch w/o arguments, e.g. -O2
97 //
98 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
99 // --output=file
100 //
101 // ParameterList - same as Parameter, but more than one occurence
102 // of the option is allowed, e.g. -lm -lpthread
103 //
104 // Prefix - argument is everything after the prefix,
105 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
106 //
107 // PrefixList - same as Prefix, but more than one option occurence is
108 // allowed
109
110 namespace OptionType {
111   enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
112 }
113
114 bool IsListOptionType (OptionType::OptionType t) {
115   return (t == OptionType::ParameterList || t == OptionType::PrefixList);
116 }
117
118 // Code duplication here is necessary because one option can affect
119 // several tools and those tools may have different actions associated
120 // with this option. GlobalOptionDescriptions are used to generate
121 // the option registration code, while ToolOptionDescriptions are used
122 // to generate tool-specific code.
123
124 /// OptionDescription - Base class for option descriptions.
125 struct OptionDescription {
126   OptionType::OptionType Type;
127   std::string Name;
128
129   OptionDescription(OptionType::OptionType t = OptionType::Switch,
130                     const std::string& n = "")
131   : Type(t), Name(n)
132   {}
133
134   const char* GenTypeDeclaration() const {
135     switch (Type) {
136     case OptionType::PrefixList:
137     case OptionType::ParameterList:
138       return "cl::list<std::string>";
139     case OptionType::Switch:
140       return "cl::opt<bool>";
141     case OptionType::Parameter:
142     case OptionType::Prefix:
143     default:
144       return "cl::opt<std::string>";
145     }
146   }
147
148   // Escape commas and other symbols not allowed in the C++ variable
149   // names. Makes it possible to use options with names like "Wa,"
150   // (useful for prefix options).
151   std::string EscapeVariableName(const std::string& Var) const {
152     std::string ret;
153     for (unsigned i = 0; i != Var.size(); ++i) {
154       if (Var[i] == ',') {
155         ret += "_comma_";
156       }
157       else {
158         ret.push_back(Var[i]);
159       }
160     }
161     return ret;
162   }
163
164   std::string GenVariableName() const {
165     const std::string& EscapedName = EscapeVariableName(Name);
166     switch (Type) {
167     case OptionType::Switch:
168      return "AutoGeneratedSwitch" + EscapedName;
169    case OptionType::Prefix:
170      return "AutoGeneratedPrefix" + EscapedName;
171    case OptionType::PrefixList:
172      return "AutoGeneratedPrefixList" + EscapedName;
173    case OptionType::Parameter:
174      return "AutoGeneratedParameter" + EscapedName;
175    case OptionType::ParameterList:
176    default:
177      return "AutoGeneratedParameterList" + EscapedName;
178    }
179   }
180
181 };
182
183 // Global option description.
184
185 namespace GlobalOptionDescriptionFlags {
186   enum GlobalOptionDescriptionFlags { Required = 0x1 };
187 }
188
189 struct GlobalOptionDescription : public OptionDescription {
190   std::string Help;
191   unsigned Flags;
192
193   // We need to provide a default constructor because
194   // StringMap can only store DefaultConstructible objects.
195   GlobalOptionDescription() : OptionDescription(), Flags(0)
196   {}
197
198   GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
199     : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
200   {}
201
202   bool isRequired() const {
203     return Flags & GlobalOptionDescriptionFlags::Required;
204   }
205   void setRequired() {
206     Flags |= GlobalOptionDescriptionFlags::Required;
207   }
208
209   /// Merge - Merge two option descriptions.
210   void Merge (const GlobalOptionDescription& other)
211   {
212     if (other.Type != Type)
213       throw "Conflicting definitions for the option " + Name + "!";
214
215     if (Help == DefaultHelpString)
216       Help = other.Help;
217     else if (other.Help != DefaultHelpString) {
218       llvm::cerr << "Warning: more than one help string defined for option "
219         + Name + "\n";
220     }
221
222     Flags |= other.Flags;
223   }
224 };
225
226 /// GlobalOptionDescriptions - A GlobalOptionDescription array
227 /// together with some flags affecting generation of option
228 /// declarations.
229 struct GlobalOptionDescriptions {
230   typedef StringMap<GlobalOptionDescription> container_type;
231   typedef container_type::const_iterator const_iterator;
232
233   /// Descriptions - A list of GlobalOptionDescriptions.
234   container_type Descriptions;
235   /// HasSink - Should the emitter generate a "cl::sink" option?
236   bool HasSink;
237
238   const GlobalOptionDescription& FindOption(const std::string& OptName) const {
239     const_iterator I = Descriptions.find(OptName);
240     if (I != Descriptions.end())
241       return I->second;
242     else
243       throw OptName + ": no such option!";
244   }
245
246   // Support for STL-style iteration
247   const_iterator begin() const { return Descriptions.begin(); }
248   const_iterator end() const { return Descriptions.end(); }
249 };
250
251
252 // Tool-local option description.
253
254 // Properties without arguments are implemented as flags.
255 namespace ToolOptionDescriptionFlags {
256   enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
257                                     Forward = 0x2, UnpackValues = 0x4};
258 }
259 namespace OptionPropertyType {
260   enum OptionPropertyType { AppendCmd, OutputSuffix };
261 }
262
263 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
264 OptionProperty;
265 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
266
267 struct ToolOptionDescription : public OptionDescription {
268   unsigned Flags;
269   OptionPropertyList Props;
270
271   // StringMap can only store DefaultConstructible objects
272   ToolOptionDescription() : OptionDescription(), Flags(0) {}
273
274   ToolOptionDescription (OptionType::OptionType t, const std::string& n)
275     : OptionDescription(t, n)
276   {}
277
278   // Various boolean properties
279   bool isStopCompilation() const {
280     return Flags & ToolOptionDescriptionFlags::StopCompilation;
281   }
282   void setStopCompilation() {
283     Flags |= ToolOptionDescriptionFlags::StopCompilation;
284   }
285
286   bool isForward() const {
287     return Flags & ToolOptionDescriptionFlags::Forward;
288   }
289   void setForward() {
290     Flags |= ToolOptionDescriptionFlags::Forward;
291   }
292
293   bool isUnpackValues() const {
294     return Flags & ToolOptionDescriptionFlags::UnpackValues;
295   }
296   void setUnpackValues() {
297     Flags |= ToolOptionDescriptionFlags::UnpackValues;
298   }
299
300   void AddProperty (OptionPropertyType::OptionPropertyType t,
301                     const std::string& val)
302   {
303     Props.push_back(std::make_pair(t, val));
304   }
305 };
306
307 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
308
309 // Tool information record
310
311 namespace ToolFlags {
312   enum ToolFlags { Join = 0x1, Sink = 0x2 };
313 }
314
315 struct ToolProperties : public RefCountedBase<ToolProperties> {
316   std::string Name;
317   Init* CmdLine;
318   StrVector InLanguage;
319   std::string OutLanguage;
320   std::string OutputSuffix;
321   unsigned Flags;
322   ToolOptionDescriptions OptDescs;
323
324   // Various boolean properties
325   void setSink()      { Flags |= ToolFlags::Sink; }
326   bool isSink() const { return Flags & ToolFlags::Sink; }
327   void setJoin()      { Flags |= ToolFlags::Join; }
328   bool isJoin() const { return Flags & ToolFlags::Join; }
329
330   // Default ctor here is needed because StringMap can only store
331   // DefaultConstructible objects
332   ToolProperties() : Flags(0) {}
333   ToolProperties (const std::string& n) : Name(n), Flags(0) {}
334 };
335
336
337 /// ToolPropertiesList - A list of Tool information records
338 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
339 /// constructor (and we want to avoid copying ToolProperties anyway).
340 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
341
342
343 /// CollectProperties - Function object for iterating over a list of
344 /// tool property records.
345 class CollectProperties {
346 private:
347
348   /// Implementation details
349
350   /// PropertyHandler - a function that extracts information
351   /// about a given tool property from its DAG representation
352   typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
353
354   /// PropertyHandlerMap - A map from property names to property
355   /// handlers.
356   typedef StringMap<PropertyHandler> PropertyHandlerMap;
357
358   /// OptionPropertyHandler - a function that extracts information
359   /// about a given option property from its DAG representation.
360   typedef void (CollectProperties::* OptionPropertyHandler)
361   (const DagInit*, GlobalOptionDescription &);
362
363   /// OptionPropertyHandlerMap - A map from option property names to
364   /// option property handlers
365   typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
366
367   // Static maps from strings to CollectProperties methods("handlers")
368   static PropertyHandlerMap propertyHandlers_;
369   static OptionPropertyHandlerMap optionPropertyHandlers_;
370   static bool staticMembersInitialized_;
371
372
373   /// This is where the information is stored
374
375   /// toolProps_ -  Properties of the current Tool.
376   ToolProperties& toolProps_;
377   /// optDescs_ - OptionDescriptions table (used to register options
378   /// globally).
379   GlobalOptionDescriptions& optDescs_;
380
381 public:
382
383   explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
384     : toolProps_(p), optDescs_(d)
385   {
386     if (!staticMembersInitialized_) {
387       // Init tool property handlers
388       propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
389       propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
390       propertyHandlers_["join"] = &CollectProperties::onJoin;
391       propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
392       propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
393       propertyHandlers_["parameter_option"]
394         = &CollectProperties::onParameter;
395       propertyHandlers_["parameter_list_option"] =
396         &CollectProperties::onParameterList;
397       propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
398       propertyHandlers_["prefix_list_option"] =
399         &CollectProperties::onPrefixList;
400       propertyHandlers_["sink"] = &CollectProperties::onSink;
401       propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
402
403       // Init option property handlers
404       optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
405       optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
406       optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
407       optionPropertyHandlers_["output_suffix"] =
408         &CollectProperties::onOutputSuffixOptionProp;
409       optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
410       optionPropertyHandlers_["stop_compilation"] =
411         &CollectProperties::onStopCompilation;
412       optionPropertyHandlers_["unpack_values"] =
413         &CollectProperties::onUnpackValues;
414
415       staticMembersInitialized_ = true;
416     }
417   }
418
419   /// operator() - Gets called for every tool property; Just forwards
420   /// to the corresponding property handler.
421   void operator() (Init* i) {
422     const DagInit& d = InitPtrToDag(i);
423     const std::string& property_name = d.getOperator()->getAsString();
424     PropertyHandlerMap::iterator method
425       = propertyHandlers_.find(property_name);
426
427     if (method != propertyHandlers_.end()) {
428       PropertyHandler h = method->second;
429       (this->*h)(&d);
430     }
431     else {
432       throw "Unknown tool property: " + property_name + "!";
433     }
434   }
435
436 private:
437
438   /// Property handlers --
439   /// Functions that extract information about tool properties from
440   /// DAG representation.
441
442   void onCmdLine (const DagInit* d) {
443     checkNumberOfArguments(d, 1);
444     toolProps_.CmdLine = d->getArg(0);
445   }
446
447   void onInLanguage (const DagInit* d) {
448     checkNumberOfArguments(d, 1);
449     Init* arg = d->getArg(0);
450
451     // Find out the argument's type.
452     if (typeid(*arg) == typeid(StringInit)) {
453       // It's a string.
454       toolProps_.InLanguage.push_back(InitPtrToString(arg));
455     }
456     else {
457       // It's a list.
458       const ListInit& lst = InitPtrToList(arg);
459       StrVector& out = toolProps_.InLanguage;
460
461       // Copy strings to the output vector.
462       for (ListInit::const_iterator B = lst.begin(), E = lst.end();
463            B != E; ++B) {
464         out.push_back(InitPtrToString(*B));
465       }
466
467       // Remove duplicates.
468       std::sort(out.begin(), out.end());
469       StrVector::iterator newE = std::unique(out.begin(), out.end());
470       out.erase(newE, out.end());
471     }
472   }
473
474   void onJoin (const DagInit* d) {
475     checkNumberOfArguments(d, 0);
476     toolProps_.setJoin();
477   }
478
479   void onOutLanguage (const DagInit* d) {
480     checkNumberOfArguments(d, 1);
481     toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
482   }
483
484   void onOutputSuffix (const DagInit* d) {
485     checkNumberOfArguments(d, 1);
486     toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
487   }
488
489   void onSink (const DagInit* d) {
490     checkNumberOfArguments(d, 0);
491     optDescs_.HasSink = true;
492     toolProps_.setSink();
493   }
494
495   void onSwitch (const DagInit* d) {
496     addOption(d, OptionType::Switch);
497   }
498
499   void onParameter (const DagInit* d) {
500     addOption(d, OptionType::Parameter);
501   }
502
503   void onParameterList (const DagInit* d) {
504     addOption(d, OptionType::ParameterList);
505   }
506
507   void onPrefix (const DagInit* d) {
508     addOption(d, OptionType::Prefix);
509   }
510
511   void onPrefixList (const DagInit* d) {
512     addOption(d, OptionType::PrefixList);
513   }
514
515   /// Option property handlers --
516   /// Methods that handle properties that are common for all types of
517   /// options (like append_cmd, stop_compilation)
518
519   void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
520     checkNumberOfArguments(d, 1);
521     const std::string& cmd = InitPtrToString(d->getArg(0));
522
523     toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
524   }
525
526   void onOutputSuffixOptionProp (const DagInit* d, GlobalOptionDescription& o) {
527     checkNumberOfArguments(d, 1);
528     const std::string& suf = InitPtrToString(d->getArg(0));
529
530     if (toolProps_.OptDescs[o.Name].Type != OptionType::Switch)
531       throw "Option " + o.Name
532         + " can't have 'output_suffix' property since it isn't a switch!";
533
534     toolProps_.OptDescs[o.Name].AddProperty
535       (OptionPropertyType::OutputSuffix, suf);
536   }
537
538   void onForward (const DagInit* d, GlobalOptionDescription& o) {
539     checkNumberOfArguments(d, 0);
540     toolProps_.OptDescs[o.Name].setForward();
541   }
542
543   void onHelp (const DagInit* d, GlobalOptionDescription& o) {
544     checkNumberOfArguments(d, 1);
545     const std::string& help_message = InitPtrToString(d->getArg(0));
546
547     o.Help = help_message;
548   }
549
550   void onRequired (const DagInit* d, GlobalOptionDescription& o) {
551     checkNumberOfArguments(d, 0);
552     o.setRequired();
553   }
554
555   void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
556     checkNumberOfArguments(d, 0);
557     if (o.Type != OptionType::Switch)
558       throw std::string("Only options of type Switch can stop compilation!");
559     toolProps_.OptDescs[o.Name].setStopCompilation();
560   }
561
562   void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
563     checkNumberOfArguments(d, 0);
564     toolProps_.OptDescs[o.Name].setUnpackValues();
565   }
566
567   /// Helper functions
568
569   // Add an option of type t
570   void addOption (const DagInit* d, OptionType::OptionType t) {
571     checkNumberOfArguments(d, 2);
572     const std::string& name = InitPtrToString(d->getArg(0));
573
574     GlobalOptionDescription o(t, name);
575     toolProps_.OptDescs[name].Type = t;
576     toolProps_.OptDescs[name].Name = name;
577     processOptionProperties(d, o);
578     insertDescription(o);
579   }
580
581   // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
582   void insertDescription (const GlobalOptionDescription& o)
583   {
584     if (optDescs_.Descriptions.count(o.Name)) {
585       GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
586       D.Merge(o);
587     }
588     else {
589       optDescs_.Descriptions[o.Name] = o;
590     }
591   }
592
593   /// processOptionProperties - Go through the list of option
594   /// properties and call a corresponding handler for each.
595   ///
596   /// Parameters:
597   /// name - option name
598   /// d - option property list
599   void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
600     // First argument is option name
601     checkNumberOfArguments(d, 2);
602
603     for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
604       const DagInit& option_property
605         = InitPtrToDag(d->getArg(B));
606       const std::string& option_property_name
607         = option_property.getOperator()->getAsString();
608       OptionPropertyHandlerMap::iterator method
609         = optionPropertyHandlers_.find(option_property_name);
610
611       if (method != optionPropertyHandlers_.end()) {
612         OptionPropertyHandler h = method->second;
613         (this->*h)(&option_property, o);
614       }
615       else {
616         throw "Unknown option property: " + option_property_name + "!";
617       }
618     }
619   }
620 };
621
622 // Static members of CollectProperties
623 CollectProperties::PropertyHandlerMap
624 CollectProperties::propertyHandlers_;
625
626 CollectProperties::OptionPropertyHandlerMap
627 CollectProperties::optionPropertyHandlers_;
628
629 bool CollectProperties::staticMembersInitialized_ = false;
630
631
632 /// CollectToolProperties - Gather information from the parsed
633 /// TableGen data (basically a wrapper for the CollectProperties
634 /// function object).
635 void CollectToolProperties (RecordVector::const_iterator B,
636                             RecordVector::const_iterator E,
637                             ToolPropertiesList& TPList,
638                             GlobalOptionDescriptions& OptDescs)
639 {
640   // Iterate over a properties list of every Tool definition
641   for (;B!=E;++B) {
642     RecordVector::value_type T = *B;
643     ListInit* PropList = T->getValueAsListInit("properties");
644
645     IntrusiveRefCntPtr<ToolProperties>
646       ToolProps(new ToolProperties(T->getName()));
647
648     std::for_each(PropList->begin(), PropList->end(),
649                   CollectProperties(*ToolProps, OptDescs));
650     TPList.push_back(ToolProps);
651   }
652 }
653
654 /// EmitCaseTest1Arg - Helper function used by
655 /// EmitCaseConstructHandler.
656 bool EmitCaseTest1Arg(const std::string& TestName,
657                       const DagInit& d,
658                       const GlobalOptionDescriptions& OptDescs,
659                       std::ostream& O) {
660   checkNumberOfArguments(&d, 1);
661   const std::string& OptName = InitPtrToString(d.getArg(0));
662   if (TestName == "switch_on") {
663     const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
664     if (OptDesc.Type != OptionType::Switch)
665       throw OptName + ": incorrect option type!";
666     O << OptDesc.GenVariableName();
667     return true;
668   } else if (TestName == "input_languages_contain") {
669     O << "InLangs.count(\"" << OptName << "\") != 0";
670     return true;
671   } else if (TestName == "in_language") {
672     // Works only for cmd_line!
673     O << "GetLanguage(inFile) == \"" << OptName << '\"';
674     return true;
675   } else if (TestName == "not_empty") {
676     const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
677     if (OptDesc.Type == OptionType::Switch)
678       throw OptName + ": incorrect option type!";
679     O << '!' << OptDesc.GenVariableName() << ".empty()";
680     return true;
681   }
682
683   return false;
684 }
685
686 /// EmitCaseTest2Args - Helper function used by
687 /// EmitCaseConstructHandler.
688 bool EmitCaseTest2Args(const std::string& TestName,
689                        const DagInit& d,
690                        const char* IndentLevel,
691                        const GlobalOptionDescriptions& OptDescs,
692                        std::ostream& O) {
693   checkNumberOfArguments(&d, 2);
694   const std::string& OptName = InitPtrToString(d.getArg(0));
695   const std::string& OptArg = InitPtrToString(d.getArg(1));
696   const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
697
698   if (TestName == "parameter_equals") {
699     if (OptDesc.Type != OptionType::Parameter
700         && OptDesc.Type != OptionType::Prefix)
701       throw OptName + ": incorrect option type!";
702     O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
703     return true;
704   }
705   else if (TestName == "element_in_list") {
706     if (OptDesc.Type != OptionType::ParameterList
707         && OptDesc.Type != OptionType::PrefixList)
708       throw OptName + ": incorrect option type!";
709     const std::string& VarName = OptDesc.GenVariableName();
710     O << "std::find(" << VarName << ".begin(),\n"
711       << IndentLevel << Indent1 << VarName << ".end(), \""
712       << OptArg << "\") != " << VarName << ".end()";
713     return true;
714   }
715
716   return false;
717 }
718
719 // Forward declaration.
720 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
721 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
722                   const GlobalOptionDescriptions& OptDescs,
723                   std::ostream& O);
724
725 /// EmitLogicalOperationTest - Helper function used by
726 /// EmitCaseConstructHandler.
727 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
728                               const char* IndentLevel,
729                               const GlobalOptionDescriptions& OptDescs,
730                               std::ostream& O) {
731   O << '(';
732   for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
733     const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
734     EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
735     if (j != NumArgs - 1)
736       O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
737     else
738       O << ')';
739   }
740 }
741
742 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
743 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
744                   const GlobalOptionDescriptions& OptDescs,
745                   std::ostream& O) {
746   const std::string& TestName = d.getOperator()->getAsString();
747
748   if (TestName == "and")
749     EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
750   else if (TestName == "or")
751     EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
752   else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
753     return;
754   else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
755     return;
756   else
757     throw TestName + ": unknown edge property!";
758 }
759
760 // Emit code that handles the 'case' construct.
761 // Takes a function object that should emit code for every case clause.
762 // Callback's type is
763 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
764 template <typename F>
765 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
766                               const F& Callback, bool EmitElseIf,
767                               const GlobalOptionDescriptions& OptDescs,
768                               std::ostream& O) {
769   assert(d->getOperator()->getAsString() == "case");
770
771   unsigned numArgs = d->getNumArgs();
772   if (d->getNumArgs() < 2)
773     throw "There should be at least one clause in the 'case' expression:\n"
774       + d->getAsString();
775
776   for (unsigned i = 0; i != numArgs; ++i) {
777     const DagInit& Test = InitPtrToDag(d->getArg(i));
778
779     // Emit the test.
780     if (Test.getOperator()->getAsString() == "default") {
781       if (i+2 != numArgs)
782         throw std::string("The 'default' clause should be the last in the"
783                           "'case' construct!");
784       O << IndentLevel << "else {\n";
785     }
786     else {
787       O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
788       EmitCaseTest(Test, IndentLevel, OptDescs, O);
789       O << ") {\n";
790     }
791
792     // Emit the corresponding statement.
793     ++i;
794     if (i == numArgs)
795       throw "Case construct handler: no corresponding action "
796         "found for the test " + Test.getAsString() + '!';
797
798     Init* arg = d->getArg(i);
799     if (dynamic_cast<DagInit*>(arg)
800         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
801       EmitCaseConstructHandler(static_cast<DagInit*>(arg),
802                                (std::string(IndentLevel) + Indent1).c_str(),
803                                Callback, EmitElseIf, OptDescs, O);
804     }
805     else {
806       Callback(arg, IndentLevel, O);
807     }
808     O << IndentLevel << "}\n";
809   }
810 }
811
812 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
813 /// implement EmitOptionPropertyHandlingCode(). Emits code for
814 /// handling the (forward) option property.
815 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
816                                             std::ostream& O) {
817   switch (D.Type) {
818   case OptionType::Switch:
819     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
820     break;
821   case OptionType::Parameter:
822     O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
823     O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
824     break;
825   case OptionType::Prefix:
826     O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
827       << D.GenVariableName() << ");\n";
828     break;
829   case OptionType::PrefixList:
830     O << Indent3 << "for (" << D.GenTypeDeclaration()
831       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
832       << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
833       << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
834       << "*B);\n";
835     break;
836   case OptionType::ParameterList:
837     O << Indent3 << "for (" << D.GenTypeDeclaration()
838       << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
839       << Indent3 << "E = " << D.GenVariableName()
840       << ".end() ; B != E; ++B) {\n"
841       << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
842       << Indent4 << "vec.push_back(*B);\n"
843       << Indent3 << "}\n";
844     break;
845   }
846 }
847
848 // ToolOptionHasInterestingProperties - A helper function used by
849 // EmitOptionPropertyHandlingCode() that tells us whether we should
850 // emit any property handling code at all.
851 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
852   bool ret = false;
853   for (OptionPropertyList::const_iterator B = D.Props.begin(),
854          E = D.Props.end(); B != E; ++B) {
855       const OptionProperty& OptProp = *B;
856       if (OptProp.first == OptionPropertyType::AppendCmd)
857         ret = true;
858     }
859   if (D.isForward() || D.isUnpackValues())
860     ret = true;
861   return ret;
862 }
863
864 /// EmitOptionPropertyHandlingCode - Helper function used by
865 /// EmitGenerateActionMethod(). Emits code that handles option
866 /// properties.
867 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
868                                      std::ostream& O)
869 {
870   if (!ToolOptionHasInterestingProperties(D))
871     return;
872   // Start of the if-clause.
873   O << Indent2 << "if (";
874   if (D.Type == OptionType::Switch)
875     O << D.GenVariableName();
876   else
877     O << '!' << D.GenVariableName() << ".empty()";
878
879   O <<") {\n";
880
881   // Handle option properties that take an argument.
882   for (OptionPropertyList::const_iterator B = D.Props.begin(),
883         E = D.Props.end(); B!=E; ++B) {
884     const OptionProperty& val = *B;
885
886     switch (val.first) {
887       // (append_cmd cmd) property
888     case OptionPropertyType::AppendCmd:
889       O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
890       break;
891       // Other properties with argument
892     default:
893       break;
894     }
895   }
896
897   // Handle flags
898
899   // (forward) property
900   if (D.isForward())
901     EmitForwardOptionPropertyHandlingCode(D, O);
902
903   // (unpack_values) property
904   if (D.isUnpackValues()) {
905     if (IsListOptionType(D.Type)) {
906       O << Indent3 << "for (" << D.GenTypeDeclaration()
907         << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
908         << Indent3 << "E = " << D.GenVariableName()
909         << ".end(); B != E; ++B)\n"
910         << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
911     }
912     else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
913       O << Indent3 << "llvm::SplitString("
914         << D.GenVariableName() << ", vec, \",\");\n";
915     }
916     else {
917       throw std::string("Switches can't have unpack_values property!");
918     }
919   }
920
921   // End of the if-clause.
922   O << Indent2 << "}\n";
923 }
924
925 /// SubstituteSpecialCommands - Perform string substitution for $CALL
926 /// and $ENV. Helper function used by EmitCmdLineVecFill().
927 std::string SubstituteSpecialCommands(const std::string& cmd) {
928   size_t cparen = cmd.find(")");
929   std::string ret;
930
931   if (cmd.find("$CALL(") == 0) {
932     if (cmd.size() == 6)
933       throw std::string("$CALL invocation: empty argument list!");
934
935     ret += "hooks::";
936     ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
937     ret += "()";
938   }
939   else if (cmd.find("$ENV(") == 0) {
940     if (cmd.size() == 5)
941       throw std::string("$ENV invocation: empty argument list!");
942
943     ret += "std::getenv(\"";
944     ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
945     ret += "\")";
946   }
947   else {
948     throw "Unknown special command: " + cmd;
949   }
950
951   if (cmd.begin() + cparen + 1 != cmd.end()) {
952     ret += " + std::string(\"";
953     ret += (cmd.c_str() + cparen + 1);
954     ret += "\")";
955   }
956
957   return ret;
958 }
959
960 /// EmitCmdLineVecFill - Emit code that fills in the command line
961 /// vector. Helper function used by EmitGenerateActionMethod().
962 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
963                         bool Version, const char* IndentLevel,
964                         std::ostream& O) {
965   StrVector StrVec;
966   SplitString(InitPtrToString(CmdLine), StrVec);
967   if (StrVec.empty())
968     throw "Tool " + ToolName + " has empty command line!";
969
970   StrVector::const_iterator I = StrVec.begin();
971   ++I;
972   for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
973     const std::string& cmd = *I;
974     O << IndentLevel;
975     if (cmd.at(0) == '$') {
976       if (cmd == "$INFILE") {
977         if (Version)
978           O << "for (PathVector::const_iterator B = inFiles.begin()"
979             << ", E = inFiles.end();\n"
980             << IndentLevel << "B != E; ++B)\n"
981             << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
982         else
983           O << "vec.push_back(inFile.toString());\n";
984       }
985       else if (cmd == "$OUTFILE") {
986         O << "vec.push_back(outFile.toString());\n";
987       }
988       else {
989         O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
990         O << ");\n";
991       }
992     }
993     else {
994       O << "vec.push_back(\"" << cmd << "\");\n";
995     }
996   }
997   O << IndentLevel << "ret = Action("
998     << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
999         : "\"" + StrVec[0] + "\"")
1000     << ", vec);\n";
1001 }
1002
1003 /// EmitCmdLineVecFillCallback - A function object wrapper around
1004 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1005 /// argument to EmitCaseConstructHandler().
1006 class EmitCmdLineVecFillCallback {
1007   bool Version;
1008   const std::string& ToolName;
1009  public:
1010   EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1011     : Version(Ver), ToolName(TN) {}
1012
1013   void operator()(const Init* Statement, const char* IndentLevel,
1014                   std::ostream& O) const
1015   {
1016     EmitCmdLineVecFill(Statement, ToolName, Version,
1017                        (std::string(IndentLevel) + Indent1).c_str(), O);
1018   }
1019 };
1020
1021 // EmitGenerateActionMethod - Emit one of two versions of the
1022 // Tool::GenerateAction() method.
1023 void EmitGenerateActionMethod (const ToolProperties& P,
1024                                const GlobalOptionDescriptions& OptDescs,
1025                                bool Version, std::ostream& O) {
1026   if (Version)
1027     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1028   else
1029     O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1030
1031   O << Indent2 << "const sys::Path& outFile,\n"
1032     << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1033     << Indent1 << "{\n"
1034     << Indent2 << "Action ret;\n"
1035     << Indent2 << "std::vector<std::string> vec;\n";
1036
1037   // cmd_line is either a string or a 'case' construct.
1038   if (typeid(*P.CmdLine) == typeid(StringInit))
1039     EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1040   else
1041     EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1042                              EmitCmdLineVecFillCallback(Version, P.Name),
1043                              true, OptDescs, O);
1044
1045   // For every understood option, emit handling code.
1046   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1047         E = P.OptDescs.end(); B != E; ++B) {
1048     const ToolOptionDescription& val = B->second;
1049     EmitOptionPropertyHandlingCode(val, O);
1050   }
1051
1052   // Handle the Sink property.
1053   if (P.isSink()) {
1054     O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1055       << Indent3 << "vec.insert(vec.end(), "
1056       << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1057       << Indent2 << "}\n";
1058   }
1059
1060   O << Indent2 << "return ret;\n"
1061     << Indent1 << "}\n\n";
1062 }
1063
1064 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1065 /// a given Tool class.
1066 void EmitGenerateActionMethods (const ToolProperties& P,
1067                                 const GlobalOptionDescriptions& OptDescs,
1068                                 std::ostream& O) {
1069   if (!P.isJoin())
1070     O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1071       << Indent2 << "const llvm::sys::Path& outFile,\n"
1072       << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1073       << Indent1 << "{\n"
1074       << Indent2 << "throw std::runtime_error(\"" << P.Name
1075       << " is not a Join tool!\");\n"
1076       << Indent1 << "}\n\n";
1077   else
1078     EmitGenerateActionMethod(P, OptDescs, true, O);
1079
1080   EmitGenerateActionMethod(P, OptDescs, false, O);
1081 }
1082
1083 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1084 /// class.
1085 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1086   O << Indent1 << "bool IsLast() const {\n"
1087     << Indent2 << "bool last = false;\n";
1088
1089   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1090         E = P.OptDescs.end(); B != E; ++B) {
1091     const ToolOptionDescription& val = B->second;
1092
1093     if (val.isStopCompilation())
1094       O << Indent2
1095         << "if (" << val.GenVariableName()
1096         << ")\n" << Indent3 << "last = true;\n";
1097   }
1098
1099   O << Indent2 << "return last;\n"
1100     << Indent1 <<  "}\n\n";
1101 }
1102
1103 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1104 /// methods for a given Tool class.
1105 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1106   O << Indent1 << "StrVector InputLanguages() const {\n"
1107     << Indent2 << "StrVector ret;\n";
1108
1109   for (StrVector::const_iterator B = P.InLanguage.begin(),
1110          E = P.InLanguage.end(); B != E; ++B) {
1111     O << Indent2 << "ret.push_back(\"" << *B << "\");\n";
1112   }
1113
1114   O << Indent2 << "return ret;\n"
1115     << Indent1 << "}\n\n";
1116
1117   O << Indent1 << "const char* OutputLanguage() const {\n"
1118     << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1119     << Indent1 << "}\n\n";
1120 }
1121
1122 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1123 /// given Tool class.
1124 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1125   O << Indent1 << "const char* OutputSuffix() const {\n"
1126     << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1127
1128   for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1129          E = P.OptDescs.end(); B != E; ++B) {
1130     const ToolOptionDescription& OptDesc = B->second;
1131     for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1132            E = OptDesc.Props.end(); B != E; ++B) {
1133       const OptionProperty& OptProp = *B;
1134       if (OptProp.first == OptionPropertyType::OutputSuffix) {
1135         O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1136           << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1137       }
1138     }
1139   }
1140
1141   O << Indent2 << "return ret;\n"
1142     << Indent1 << "}\n\n";
1143 }
1144
1145 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1146 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1147   O << Indent1 << "const char* Name() const {\n"
1148     << Indent2 << "return \"" << P.Name << "\";\n"
1149     << Indent1 << "}\n\n";
1150 }
1151
1152 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1153 /// class.
1154 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1155   O << Indent1 << "bool IsJoin() const {\n";
1156   if (P.isJoin())
1157     O << Indent2 << "return true;\n";
1158   else
1159     O << Indent2 << "return false;\n";
1160   O << Indent1 << "}\n\n";
1161 }
1162
1163 /// EmitToolClassDefinition - Emit a Tool class definition.
1164 void EmitToolClassDefinition (const ToolProperties& P,
1165                               const GlobalOptionDescriptions& OptDescs,
1166                               std::ostream& O) {
1167   if (P.Name == "root")
1168     return;
1169
1170   // Header
1171   O << "class " << P.Name << " : public ";
1172   if (P.isJoin())
1173     O << "JoinTool";
1174   else
1175     O << "Tool";
1176   O << " {\npublic:\n";
1177
1178   EmitNameMethod(P, O);
1179   EmitInOutLanguageMethods(P, O);
1180   EmitOutputSuffixMethod(P, O);
1181   EmitIsJoinMethod(P, O);
1182   EmitGenerateActionMethods(P, OptDescs, O);
1183   EmitIsLastMethod(P, O);
1184
1185   // Close class definition
1186   O << "};\n\n";
1187 }
1188
1189 /// EmitOptionDescriptions - Iterate over a list of option
1190 /// descriptions and emit registration code.
1191 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1192                              std::ostream& O)
1193 {
1194   // Emit static cl::Option variables
1195   for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1196          E = descs.end(); B!=E; ++B) {
1197     const GlobalOptionDescription& val = B->second;
1198
1199     O << val.GenTypeDeclaration() << ' '
1200       << val.GenVariableName()
1201       << "(\"" << val.Name << '\"';
1202
1203     if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1204       O << ", cl::Prefix";
1205
1206     if (val.isRequired()) {
1207       switch (val.Type) {
1208       case OptionType::PrefixList:
1209       case OptionType::ParameterList:
1210         O << ", cl::OneOrMore";
1211         break;
1212       default:
1213         O << ", cl::Required";
1214       }
1215     }
1216
1217     O << ", cl::desc(\"" << val.Help << "\"));\n";
1218   }
1219
1220   if (descs.HasSink)
1221     O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1222
1223   O << '\n';
1224 }
1225
1226 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1227 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1228 {
1229   // Get the relevant field out of RecordKeeper
1230   Record* LangMapRecord = Records.getDef("LanguageMap");
1231   if (!LangMapRecord)
1232     throw std::string("Language map definition not found!");
1233
1234   ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1235   if (!LangsToSuffixesList)
1236     throw std::string("Error in the language map definition!");
1237
1238   // Generate code
1239   O << "void llvmc::PopulateLanguageMap() {\n";
1240
1241   for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1242     Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1243
1244     const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1245     const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1246
1247     for (unsigned i = 0; i < Suffixes->size(); ++i)
1248       O << Indent1 << "GlobalLanguageMap[\""
1249         << InitPtrToString(Suffixes->getElement(i))
1250         << "\"] = \"" << Lang << "\";\n";
1251   }
1252
1253   O << "}\n\n";
1254 }
1255
1256 /// FillInToolToLang - Fills in two tables that map tool names to
1257 /// (input, output) languages.  Used by the typechecker.
1258 void FillInToolToLang (const ToolPropertiesList& TPList,
1259                        StringMap<StringSet<> >& ToolToInLang,
1260                        StringMap<std::string>& ToolToOutLang) {
1261   for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1262        B != E; ++B) {
1263     const ToolProperties& P = *(*B);
1264     for (StrVector::const_iterator B = P.InLanguage.begin(),
1265            E = P.InLanguage.end(); B != E; ++B)
1266       ToolToInLang[P.Name].insert(*B);
1267     ToolToOutLang[P.Name] = P.OutLanguage;
1268   }
1269 }
1270
1271 /// TypecheckGraph - Check that names for output and input languages
1272 /// on all edges do match.
1273 // TOFIX: It would be nice if this function also checked for cycles
1274 // and multiple default edges in the graph (better error
1275 // reporting). Unfortunately, it is awkward to do right now because
1276 // our intermediate representation is not sufficiently
1277 // sofisticated. Algorithms like these should be run on a real graph
1278 // instead of AST.
1279 void TypecheckGraph (Record* CompilationGraph,
1280                      const ToolPropertiesList& TPList) {
1281   StringMap<StringSet<> > ToolToInLang;
1282   StringMap<std::string> ToolToOutLang;
1283
1284   FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1285   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1286   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1287   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1288
1289   for (unsigned i = 0; i < edges->size(); ++i) {
1290     Record* Edge = edges->getElementAsRecord(i);
1291     Record* A = Edge->getValueAsDef("a");
1292     Record* B = Edge->getValueAsDef("b");
1293     StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1294     StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1295     if (IA == IAE)
1296       throw A->getName() + ": no such tool!";
1297     if (IB == IBE)
1298       throw B->getName() + ": no such tool!";
1299     if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1300       throw "Edge " + A->getName() + "->" + B->getName()
1301         + ": output->input language mismatch";
1302     if (B->getName() == "root")
1303       throw std::string("Edges back to the root are not allowed!");
1304   }
1305 }
1306
1307 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1308 /// by EmitEdgeClass().
1309 void IncDecWeight (const Init* i, const char* IndentLevel,
1310                    std::ostream& O) {
1311   const DagInit& d = InitPtrToDag(i);
1312   const std::string& OpName = d.getOperator()->getAsString();
1313
1314   if (OpName == "inc_weight")
1315     O << IndentLevel << Indent1 << "ret += ";
1316   else if (OpName == "dec_weight")
1317     O << IndentLevel << Indent1 << "ret -= ";
1318   else
1319     throw "Unknown operator in edge properties list: " + OpName + '!';
1320
1321   if (d.getNumArgs() > 0)
1322     O << InitPtrToInt(d.getArg(0)) << ";\n";
1323   else
1324     O << "2;\n";
1325
1326 }
1327
1328 /// EmitEdgeClass - Emit a single Edge# class.
1329 void EmitEdgeClass (unsigned N, const std::string& Target,
1330                     DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1331                     std::ostream& O) {
1332
1333   // Class constructor.
1334   O << "class Edge" << N << ": public Edge {\n"
1335     << "public:\n"
1336     << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1337     << "\") {}\n\n"
1338
1339   // Function Weight().
1340     << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1341     << Indent2 << "unsigned ret = 0;\n";
1342
1343   // Handle the 'case' construct.
1344   EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1345
1346   O << Indent2 << "return ret;\n"
1347     << Indent1 << "};\n\n};\n\n";
1348 }
1349
1350 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1351 void EmitEdgeClasses (Record* CompilationGraph,
1352                       const GlobalOptionDescriptions& OptDescs,
1353                       std::ostream& O) {
1354   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1355
1356   for (unsigned i = 0; i < edges->size(); ++i) {
1357     Record* Edge = edges->getElementAsRecord(i);
1358     Record* B = Edge->getValueAsDef("b");
1359     DagInit* Weight = Edge->getValueAsDag("weight");
1360
1361     if (isDagEmpty(Weight))
1362       continue;
1363
1364     EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1365   }
1366 }
1367
1368 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1369 /// function.
1370 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1371                                    std::ostream& O)
1372 {
1373   ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1374
1375   // Generate code
1376   O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1377     << Indent1 << "PopulateLanguageMap();\n\n";
1378
1379   // Insert vertices
1380
1381   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1382   if (Tools.empty())
1383     throw std::string("No tool definitions found!");
1384
1385   for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1386     const std::string& Name = (*B)->getName();
1387     if (Name != "root")
1388       O << Indent1 << "G.insertNode(new "
1389         << Name << "());\n";
1390   }
1391
1392   O << '\n';
1393
1394   // Insert edges
1395   for (unsigned i = 0; i < edges->size(); ++i) {
1396     Record* Edge = edges->getElementAsRecord(i);
1397     Record* A = Edge->getValueAsDef("a");
1398     Record* B = Edge->getValueAsDef("b");
1399     DagInit* Weight = Edge->getValueAsDag("weight");
1400
1401     O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1402
1403     if (isDagEmpty(Weight))
1404       O << "new SimpleEdge(\"" << B->getName() << "\")";
1405     else
1406       O << "new Edge" << i << "()";
1407
1408     O << ");\n";
1409   }
1410
1411   O << "}\n\n";
1412 }
1413
1414 /// ExtractHookNames - Extract the hook names from all instances of
1415 /// $CALL(HookName) in the provided command line string. Helper
1416 /// function used by FillInHookNames().
1417 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1418   StrVector cmds;
1419   llvm::SplitString(InitPtrToString(CmdLine), cmds);
1420   for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1421        B != E; ++B) {
1422     const std::string& cmd = *B;
1423     if (cmd.find("$CALL(") == 0) {
1424       if (cmd.size() == 6)
1425         throw std::string("$CALL invocation: empty argument list!");
1426       HookNames.push_back(std::string(cmd.begin() + 6,
1427                                       cmd.begin() + cmd.find(")")));
1428     }
1429   }
1430 }
1431
1432 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1433 /// 'case' expression, handle nesting. Helper function used by
1434 /// FillInHookNames().
1435 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1436   const DagInit& d = InitPtrToDag(Case);
1437   bool even = false;
1438   for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1439        B != E; ++B) {
1440     Init* arg = *B;
1441     if (even && dynamic_cast<DagInit*>(arg)
1442         && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1443       ExtractHookNamesFromCaseConstruct(arg, HookNames);
1444     else if (even)
1445       ExtractHookNames(arg, HookNames);
1446     even = !even;
1447   }
1448 }
1449
1450 /// FillInHookNames - Actually extract the hook names from all command
1451 /// line strings. Helper function used by EmitHookDeclarations().
1452 void FillInHookNames(const ToolPropertiesList& TPList,
1453                      StrVector& HookNames) {
1454   // For all command lines:
1455   for (ToolPropertiesList::const_iterator B = TPList.begin(),
1456          E = TPList.end(); B != E; ++B) {
1457     const ToolProperties& P = *(*B);
1458     if (!P.CmdLine)
1459       continue;
1460     if (dynamic_cast<StringInit*>(P.CmdLine))
1461       // This is a string.
1462       ExtractHookNames(P.CmdLine, HookNames);
1463     else
1464       // This is a 'case' construct.
1465       ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1466   }
1467 }
1468
1469 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1470 /// property records and emit hook function declaration for each
1471 /// instance of $CALL(HookName).
1472 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1473                           std::ostream& O) {
1474   StrVector HookNames;
1475   FillInHookNames(ToolProps, HookNames);
1476   if (HookNames.empty())
1477     return;
1478   std::sort(HookNames.begin(), HookNames.end());
1479   StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1480
1481   O << "namespace hooks {\n";
1482   for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1483     O << Indent1 << "std::string " << *B << "();\n";
1484
1485   O << "}\n\n";
1486 }
1487
1488 // End of anonymous namespace
1489 }
1490
1491 /// run - The back-end entry point.
1492 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1493   try {
1494
1495   // Emit file header.
1496   EmitSourceFileHeader("LLVMC Configuration Library", O);
1497
1498   // Get a list of all defined Tools.
1499   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1500   if (Tools.empty())
1501     throw std::string("No tool definitions found!");
1502
1503   // Gather information from the Tool description dags.
1504   ToolPropertiesList tool_props;
1505   GlobalOptionDescriptions opt_descs;
1506   CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1507
1508   // Emit global option registration code.
1509   EmitOptionDescriptions(opt_descs, O);
1510
1511   // Emit hook declarations.
1512   EmitHookDeclarations(tool_props, O);
1513
1514   // Emit PopulateLanguageMap() function
1515   // (a language map maps from file extensions to language names).
1516   EmitPopulateLanguageMap(Records, O);
1517
1518   // Emit Tool classes.
1519   for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1520          E = tool_props.end(); B!=E; ++B)
1521     EmitToolClassDefinition(*(*B), opt_descs, O);
1522
1523   Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1524   if (!CompilationGraphRecord)
1525     throw std::string("Compilation graph description not found!");
1526
1527   // Typecheck the compilation graph.
1528   TypecheckGraph(CompilationGraphRecord, tool_props);
1529
1530   // Emit Edge# classes.
1531   EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1532
1533   // Emit PopulateCompilationGraph() function.
1534   EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1535
1536   // EOF
1537   } catch (std::exception& Error) {
1538     throw Error.what() + std::string(" - usually this means a syntax error.");
1539   }
1540 }