1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting LLVMC configuration code.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMCConfigurationEmitter.h"
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/Support/Streams.h"
32 //===----------------------------------------------------------------------===//
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
38 //===----------------------------------------------------------------------===//
41 // Indentation strings
42 const char * Indent1 = " ";
43 const char * Indent2 = " ";
44 const char * Indent3 = " ";
45 const char * Indent4 = " ";
47 // Default help string
48 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50 // Name for the "sink" option
51 const char * SinkOptionName = "AutoGeneratedSinkOption";
53 //===----------------------------------------------------------------------===//
56 std::string InitPtrToString(Init* ptr) {
57 StringInit& val = dynamic_cast<StringInit&>(*ptr);
58 return val.getValue();
61 // Ensure that the number of args in d is <= min_arguments,
62 // throw exception otherwise
63 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
64 if (d->getNumArgs() < min_arguments)
65 throw "Property " + d->getOperator()->getAsString()
66 + " has too few arguments!";
70 //===----------------------------------------------------------------------===//
71 /// Back-end specific code
73 // A command-line option can have one of the following types:
75 // Switch - a simple switch w/o arguments, e.g. -O2
77 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
80 // ParameterList - same as Parameter, but more than one occurence
81 // of the option is allowed, e.g. -lm -lpthread
83 // Prefix - argument is everything after the prefix,
84 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
86 // PrefixList - same as Prefix, but more than one option occurence is
89 namespace OptionType {
90 enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
93 bool IsListOptionType (OptionType::OptionType t) {
94 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
97 // Code duplication here is necessary because one option can affect
98 // several tools and those tools may have different actions associated
99 // with this option. GlobalOptionDescriptions are used to generate
100 // the option registration code, while ToolOptionDescriptions are used
101 // to generate tool-specific code.
103 // Base class for option descriptions
105 struct OptionDescription {
106 OptionType::OptionType Type;
109 OptionDescription(OptionType::OptionType t = OptionType::Switch,
110 const std::string& n = "")
114 const char* GenTypeDeclaration() const {
116 case OptionType::PrefixList:
117 case OptionType::ParameterList:
118 return "cl::list<std::string>";
119 case OptionType::Switch:
120 return "cl::opt<bool>";
121 case OptionType::Parameter:
122 case OptionType::Prefix:
124 return "cl::opt<std::string>";
128 std::string GenVariableName() const {
130 case OptionType::Switch:
131 return "AutoGeneratedSwitch" + Name;
132 case OptionType::Prefix:
133 return "AutoGeneratedPrefix" + Name;
134 case OptionType::PrefixList:
135 return "AutoGeneratedPrefixList" + Name;
136 case OptionType::Parameter:
137 return "AutoGeneratedParameter" + Name;
138 case OptionType::ParameterList:
140 return "AutoGeneratedParameterList" + Name;
146 // Global option description
148 namespace GlobalOptionDescriptionFlags {
149 enum GlobalOptionDescriptionFlags { Required = 0x1 };
152 struct GlobalOptionDescription : public OptionDescription {
156 // We need t provide a default constructor since
157 // StringMap can only store DefaultConstructible objects
158 GlobalOptionDescription() : OptionDescription(), Flags(0)
161 GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
162 : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
165 bool isRequired() const {
166 return Flags & GlobalOptionDescriptionFlags::Required;
169 Flags |= GlobalOptionDescriptionFlags::Required;
172 // Merge two option descriptions
173 void Merge (const GlobalOptionDescription& other)
175 if (other.Type != Type)
176 throw "Conflicting definitions for the option " + Name + "!";
178 if (Help.empty() && !other.Help.empty())
180 else if (!Help.empty() && !other.Help.empty())
181 cerr << "Warning: more than one help string defined for option "
184 Flags |= other.Flags;
188 // A GlobalOptionDescription array
189 // + some flags affecting generation of option declarations
190 struct GlobalOptionDescriptions {
191 typedef StringMap<GlobalOptionDescription> container_type;
192 typedef container_type::const_iterator const_iterator;
194 // A list of GlobalOptionDescriptions
195 container_type Descriptions;
196 // Should the emitter generate a "cl::sink" option?
199 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
200 const_iterator I = Descriptions.find(OptName);
201 if (I != Descriptions.end())
204 throw OptName + ": no such option!";
207 // Support for STL-style iteration
208 const_iterator begin() const { return Descriptions.begin(); }
209 const_iterator end() const { return Descriptions.end(); }
213 // Tool-local option description
215 // Properties without arguments are implemented as flags
216 namespace ToolOptionDescriptionFlags {
217 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
218 Forward = 0x2, UnpackValues = 0x4};
220 namespace OptionPropertyType {
221 enum OptionPropertyType { AppendCmd };
224 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
226 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
228 struct ToolOptionDescription : public OptionDescription {
230 OptionPropertyList Props;
232 // StringMap can only store DefaultConstructible objects
233 ToolOptionDescription() : OptionDescription(), Flags(0) {}
235 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
236 : OptionDescription(t, n)
239 // Various boolean properties
240 bool isStopCompilation() const {
241 return Flags & ToolOptionDescriptionFlags::StopCompilation;
243 void setStopCompilation() {
244 Flags |= ToolOptionDescriptionFlags::StopCompilation;
247 bool isForward() const {
248 return Flags & ToolOptionDescriptionFlags::Forward;
251 Flags |= ToolOptionDescriptionFlags::Forward;
254 bool isUnpackValues() const {
255 return Flags & ToolOptionDescriptionFlags::UnpackValues;
257 void setUnpackValues() {
258 Flags |= ToolOptionDescriptionFlags::UnpackValues;
261 void AddProperty (OptionPropertyType::OptionPropertyType t,
262 const std::string& val)
264 Props.push_back(std::make_pair(t, val));
268 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
270 // Tool information record
272 namespace ToolFlags {
273 enum ToolFlags { Join = 0x1, Sink = 0x2 };
276 struct ToolProperties : public RefCountedBase<ToolProperties> {
279 std::string InLanguage;
280 std::string OutLanguage;
281 std::string OutputSuffix;
283 ToolOptionDescriptions OptDescs;
285 // Various boolean properties
286 void setSink() { Flags |= ToolFlags::Sink; }
287 bool isSink() const { return Flags & ToolFlags::Sink; }
288 void setJoin() { Flags |= ToolFlags::Join; }
289 bool isJoin() const { return Flags & ToolFlags::Join; }
291 // Default ctor here is needed because StringMap can only store
292 // DefaultConstructible objects
294 ToolProperties (const std::string& n) : Name(n) {}
298 // A list of Tool information records
299 // IntrusiveRefCntPtrs are used because StringMap has no copy constructor
300 // (and we want to avoid copying ToolProperties anyway)
301 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
304 // Function object for iterating over a list of tool property records
305 class CollectProperties {
308 /// Implementation details
310 // "Property handler" - a function that extracts information
311 // about a given tool property from its DAG representation
312 typedef void (CollectProperties::*PropertyHandler)(DagInit*);
314 // Map from property names -> property handlers
315 typedef StringMap<PropertyHandler> PropertyHandlerMap;
317 // "Option property handler" - a function that extracts information
318 // about a given option property from its DAG representation
319 typedef void (CollectProperties::*
320 OptionPropertyHandler)(DagInit*, GlobalOptionDescription &);
322 // Map from option property names -> option property handlers
323 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
325 // Static maps from strings to CollectProperties methods("handlers")
326 static PropertyHandlerMap propertyHandlers_;
327 static OptionPropertyHandlerMap optionPropertyHandlers_;
328 static bool staticMembersInitialized_;
331 /// This is where the information is stored
333 // Current Tool properties
334 ToolProperties& toolProps_;
335 // OptionDescriptions table(used to register options globally)
336 GlobalOptionDescriptions& optDescs_;
340 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
341 : toolProps_(p), optDescs_(d)
343 if (!staticMembersInitialized_) {
344 // Init tool property handlers
345 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
346 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
347 propertyHandlers_["join"] = &CollectProperties::onJoin;
348 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
349 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
350 propertyHandlers_["parameter_option"]
351 = &CollectProperties::onParameter;
352 propertyHandlers_["parameter_list_option"] =
353 &CollectProperties::onParameterList;
354 propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
355 propertyHandlers_["prefix_list_option"] =
356 &CollectProperties::onPrefixList;
357 propertyHandlers_["sink"] = &CollectProperties::onSink;
358 propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
360 // Init option property handlers
361 optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
362 optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
363 optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
364 optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
365 optionPropertyHandlers_["stop_compilation"] =
366 &CollectProperties::onStopCompilation;
367 optionPropertyHandlers_["unpack_values"] =
368 &CollectProperties::onUnpackValues;
370 staticMembersInitialized_ = true;
374 // Gets called for every tool property;
375 // Just forwards to the corresponding property handler.
376 void operator() (Init* i) {
377 DagInit& d = dynamic_cast<DagInit&>(*i);
378 const std::string& property_name = d.getOperator()->getAsString();
379 PropertyHandlerMap::iterator method
380 = propertyHandlers_.find(property_name);
382 if (method != propertyHandlers_.end()) {
383 PropertyHandler h = method->second;
387 throw "Unknown tool property: " + property_name + "!";
393 /// Property handlers --
394 /// Functions that extract information about tool properties from
395 /// DAG representation.
397 void onCmdLine (DagInit* d) {
398 checkNumberOfArguments(d, 1);
399 SplitString(InitPtrToString(d->getArg(0)), toolProps_.CmdLine);
400 if (toolProps_.CmdLine.empty())
401 throw "Tool " + toolProps_.Name + " has empty command line!";
404 void onInLanguage (DagInit* d) {
405 checkNumberOfArguments(d, 1);
406 toolProps_.InLanguage = InitPtrToString(d->getArg(0));
409 void onJoin (DagInit* d) {
410 checkNumberOfArguments(d, 0);
411 toolProps_.setJoin();
414 void onOutLanguage (DagInit* d) {
415 checkNumberOfArguments(d, 1);
416 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
419 void onOutputSuffix (DagInit* d) {
420 checkNumberOfArguments(d, 1);
421 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
424 void onSink (DagInit* d) {
425 checkNumberOfArguments(d, 0);
426 optDescs_.HasSink = true;
427 toolProps_.setSink();
430 void onSwitch (DagInit* d) { addOption(d, OptionType::Switch); }
431 void onParameter (DagInit* d) { addOption(d, OptionType::Parameter); }
432 void onParameterList (DagInit* d) { addOption(d, OptionType::ParameterList); }
433 void onPrefix (DagInit* d) { addOption(d, OptionType::Prefix); }
434 void onPrefixList (DagInit* d) { addOption(d, OptionType::PrefixList); }
436 /// Option property handlers --
437 /// Methods that handle properties that are common for all types of
438 /// options (like append_cmd, stop_compilation)
440 void onAppendCmd (DagInit* d, GlobalOptionDescription& o) {
441 checkNumberOfArguments(d, 1);
442 std::string const& cmd = InitPtrToString(d->getArg(0));
444 toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
447 void onForward (DagInit* d, GlobalOptionDescription& o) {
448 checkNumberOfArguments(d, 0);
449 toolProps_.OptDescs[o.Name].setForward();
452 void onHelp (DagInit* d, GlobalOptionDescription& o) {
453 checkNumberOfArguments(d, 1);
454 const std::string& help_message = InitPtrToString(d->getArg(0));
456 o.Help = help_message;
459 void onRequired (DagInit* d, GlobalOptionDescription& o) {
460 checkNumberOfArguments(d, 0);
464 void onStopCompilation (DagInit* d, GlobalOptionDescription& o) {
465 checkNumberOfArguments(d, 0);
466 if (o.Type != OptionType::Switch)
467 throw std::string("Only options of type Switch can stop compilation!");
468 toolProps_.OptDescs[o.Name].setStopCompilation();
471 void onUnpackValues (DagInit* d, GlobalOptionDescription& o) {
472 checkNumberOfArguments(d, 0);
473 toolProps_.OptDescs[o.Name].setUnpackValues();
478 // Add an option of type t
479 void addOption (DagInit* d, OptionType::OptionType t) {
480 checkNumberOfArguments(d, 2);
481 const std::string& name = InitPtrToString(d->getArg(0));
483 GlobalOptionDescription o(t, name);
484 toolProps_.OptDescs[name].Type = t;
485 toolProps_.OptDescs[name].Name = name;
486 processOptionProperties(d, o);
487 insertDescription(o);
490 // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
491 void insertDescription (const GlobalOptionDescription& o)
493 if (optDescs_.Descriptions.count(o.Name)) {
494 GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
498 optDescs_.Descriptions[o.Name] = o;
502 // Go through the list of option properties and call a corresponding
506 // name - option name
507 // d - option property list
508 void processOptionProperties (DagInit* d, GlobalOptionDescription& o) {
509 // First argument is option name
510 checkNumberOfArguments(d, 2);
512 for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
513 DagInit& option_property
514 = dynamic_cast<DagInit&>(*d->getArg(B));
515 const std::string& option_property_name
516 = option_property.getOperator()->getAsString();
517 OptionPropertyHandlerMap::iterator method
518 = optionPropertyHandlers_.find(option_property_name);
520 if (method != optionPropertyHandlers_.end()) {
521 OptionPropertyHandler h = method->second;
522 (this->*h)(&option_property, o);
525 throw "Unknown option property: " + option_property_name + "!";
531 // Static members of CollectProperties
532 CollectProperties::PropertyHandlerMap
533 CollectProperties::propertyHandlers_;
535 CollectProperties::OptionPropertyHandlerMap
536 CollectProperties::optionPropertyHandlers_;
538 bool CollectProperties::staticMembersInitialized_ = false;
541 // Gather information from the parsed TableGen data
542 // (Basically a wrapper for CollectProperties)
543 void CollectToolProperties (RecordVector::const_iterator B,
544 RecordVector::const_iterator E,
545 ToolPropertiesList& TPList,
546 GlobalOptionDescriptions& OptDescs)
548 // Iterate over a properties list of every Tool definition
550 RecordVector::value_type T = *B;
551 ListInit* PropList = T->getValueAsListInit("properties");
553 IntrusiveRefCntPtr<ToolProperties>
554 ToolProps(new ToolProperties(T->getName()));
556 std::for_each(PropList->begin(), PropList->end(),
557 CollectProperties(*ToolProps, OptDescs));
558 TPList.push_back(ToolProps);
562 // Used by EmitGenerateActionMethod
563 void EmitOptionPropertyHandlingCode (const ToolProperties& P,
564 const ToolOptionDescription& D,
568 O << Indent2 << "if (";
569 if (D.Type == OptionType::Switch)
570 O << D.GenVariableName();
572 O << '!' << D.GenVariableName() << ".empty()";
576 // Handle option properties that take an argument
577 for (OptionPropertyList::const_iterator B = D.Props.begin(),
578 E = D.Props.end(); B!=E; ++B) {
579 const OptionProperty& val = *B;
582 // (append_cmd cmd) property
583 case OptionPropertyType::AppendCmd:
584 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
586 // Other properties with argument
594 // (forward) property
597 case OptionType::Switch:
598 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
600 case OptionType::Parameter:
601 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
602 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
604 case OptionType::Prefix:
605 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
606 << D.GenVariableName() << ");\n";
608 case OptionType::PrefixList:
609 O << Indent3 << "for (" << D.GenTypeDeclaration()
610 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
611 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
612 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
615 case OptionType::ParameterList:
616 O << Indent3 << "for (" << D.GenTypeDeclaration()
617 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
618 << Indent3 << "E = " << D.GenVariableName()
619 << ".end() ; B != E; ++B) {\n"
620 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
621 << Indent4 << "vec.push_back(*B);\n"
627 // (unpack_values) property
628 if (D.isUnpackValues()) {
629 if (IsListOptionType(D.Type)) {
630 O << Indent3 << "for (" << D.GenTypeDeclaration()
631 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
632 << Indent3 << "E = " << D.GenVariableName()
633 << ".end(); B != E; ++B)\n"
634 << Indent4 << "Tool::UnpackValues(*B, vec);\n";
636 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
637 O << Indent3 << "Tool::UnpackValues("
638 << D.GenVariableName() << ", vec);\n";
641 // TOFIX: move this to the type-checking phase
642 throw std::string("Switches can't have unpack_values property!");
647 O << Indent2 << "}\n";
650 // Emite one of two versions of GenerateAction method
651 void EmitGenerateActionMethod (const ToolProperties& P, int V, std::ostream& O)
653 assert(V==1 || V==2);
655 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
657 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
659 O << Indent2 << "const sys::Path& outFile) const\n"
661 << Indent2 << "std::vector<std::string> vec;\n";
663 // Parse CmdLine tool property
664 if(P.CmdLine.empty())
665 throw "Tool " + P.Name + " has empty command line!";
667 StrVector::const_iterator I = P.CmdLine.begin();
669 for (StrVector::const_iterator E = P.CmdLine.end(); I != E; ++I) {
670 const std::string& cmd = *I;
672 if (cmd == "$INFILE") {
674 O << "for (PathVector::const_iterator B = inFiles.begin()"
675 << ", E = inFiles.end();\n"
676 << Indent2 << "B != E; ++B)\n"
677 << Indent3 << "vec.push_back(B->toString());\n";
679 O << "vec.push_back(inFile.toString());\n";
681 else if (cmd == "$OUTFILE") {
682 O << "vec.push_back(outFile.toString());\n";
685 O << "vec.push_back(\"" << cmd << "\");\n";
689 // For every understood option, emit handling code
690 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
691 E = P.OptDescs.end(); B != E; ++B) {
692 const ToolOptionDescription& val = B->second;
693 EmitOptionPropertyHandlingCode(P, val, O);
696 // Handle Sink property
698 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
699 << Indent3 << "vec.insert(vec.end(), "
700 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
704 O << Indent2 << "return Action(\"" << P.CmdLine.at(0) << "\", vec);\n"
705 << Indent1 << "}\n\n";
708 // Emit GenerateAction methods for Tool classes
709 void EmitGenerateActionMethods (const ToolProperties& P, std::ostream& O) {
712 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
713 << Indent2 << "const llvm::sys::Path& outFile) const\n"
715 << Indent2 << "throw std::runtime_error(\"" << P.Name
716 << " is not a Join tool!\");\n"
717 << Indent1 << "}\n\n";
719 EmitGenerateActionMethod(P, 1, O);
721 EmitGenerateActionMethod(P, 2, O);
724 // Emit IsLast() method for Tool classes
725 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
726 O << Indent1 << "bool IsLast() const {\n"
727 << Indent2 << "bool last = false;\n";
729 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
730 E = P.OptDescs.end(); B != E; ++B) {
731 const ToolOptionDescription& val = B->second;
733 if (val.isStopCompilation())
735 << "if (" << val.GenVariableName()
736 << ")\n" << Indent3 << "last = true;\n";
739 O << Indent2 << "return last;\n"
740 << Indent1 << "}\n\n";
743 // Emit static [Input,Output]Language() methods for Tool classes
744 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
745 O << Indent1 << "const char* InputLanguage() const {\n"
746 << Indent2 << "return \"" << P.InLanguage << "\";\n"
747 << Indent1 << "}\n\n";
749 O << Indent1 << "const char* OutputLanguage() const {\n"
750 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
751 << Indent1 << "}\n\n";
754 // Emit static [Input,Output]Language() methods for Tool classes
755 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
756 O << Indent1 << "const char* OutputSuffix() const {\n"
757 << Indent2 << "return \"" << P.OutputSuffix << "\";\n"
758 << Indent1 << "}\n\n";
761 // Emit static Name() method for Tool classes
762 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
763 O << Indent1 << "const char* Name() const {\n"
764 << Indent2 << "return \"" << P.Name << "\";\n"
765 << Indent1 << "}\n\n";
768 // Emit static Name() method for Tool classes
769 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
770 O << Indent1 << "bool IsJoin() const {\n";
772 O << Indent2 << "return true;\n";
774 O << Indent2 << "return false;\n";
775 O << Indent1 << "}\n\n";
778 // Emit a Tool class definition
779 void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
785 O << "class " << P.Name << " : public ";
790 O << " {\npublic:\n";
792 EmitNameMethod(P, O);
793 EmitInOutLanguageMethods(P, O);
794 EmitOutputSuffixMethod(P, O);
795 EmitIsJoinMethod(P, O);
796 EmitGenerateActionMethods(P, O);
797 EmitIsLastMethod(P, O);
799 // Close class definition
803 // Iterate over a list of option descriptions and emit registration code
804 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
807 // Emit static cl::Option variables
808 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
809 E = descs.end(); B!=E; ++B) {
810 const GlobalOptionDescription& val = B->second;
812 O << val.GenTypeDeclaration() << ' '
813 << val.GenVariableName()
814 << "(\"" << val.Name << '\"';
816 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
819 if (val.isRequired()) {
821 case OptionType::PrefixList:
822 case OptionType::ParameterList:
823 O << ", cl::OneOrMore";
826 O << ", cl::Required";
830 O << ", cl::desc(\"" << val.Help << "\"));\n";
834 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
839 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
841 // Get the relevant field out of RecordKeeper
842 Record* LangMapRecord = Records.getDef("LanguageMap");
844 throw std::string("Language map definition not found!");
846 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
847 if (!LangsToSuffixesList)
848 throw std::string("Error in the language map definition!");
851 O << "void llvmc::PopulateLanguageMap(LanguageMap& language_map) {\n";
853 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
854 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
856 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
857 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
859 for (unsigned i = 0; i < Suffixes->size(); ++i)
860 O << Indent1 << "language_map[\""
861 << InitPtrToString(Suffixes->getElement(i))
862 << "\"] = \"" << Lang << "\";\n";
868 // Fills in two tables that map tool names to (input, output) languages.
869 // Used by the typechecker.
870 void FillInToolToLang (const ToolPropertiesList& TPList,
871 StringMap<std::string>& ToolToInLang,
872 StringMap<std::string>& ToolToOutLang) {
873 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
875 const ToolProperties& P = *(*B);
876 ToolToInLang[P.Name] = P.InLanguage;
877 ToolToOutLang[P.Name] = P.OutLanguage;
881 // Check that all output and input language names match.
882 // TOFIX: check for cycles.
883 // TOFIX: check for multiple default edges.
884 void TypecheckGraph (Record* CompilationGraph,
885 const ToolPropertiesList& TPList) {
886 StringMap<std::string> ToolToInLang;
887 StringMap<std::string> ToolToOutLang;
889 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
890 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
891 StringMap<std::string>::iterator IAE = ToolToInLang.end();
892 StringMap<std::string>::iterator IBE = ToolToOutLang.end();
894 for (unsigned i = 0; i < edges->size(); ++i) {
895 Record* Edge = edges->getElementAsRecord(i);
896 Record* A = Edge->getValueAsDef("a");
897 Record* B = Edge->getValueAsDef("b");
898 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
899 StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
901 throw A->getName() + ": no such tool!";
903 throw B->getName() + ": no such tool!";
904 if(A->getName() != "root" && IA->second != IB->second)
905 throw "Edge " + A->getName() + "->" + B->getName()
906 + ": output->input language mismatch";
907 if(B->getName() == "root")
908 throw std::string("Edges back to the root are not allowed!");
912 // Helper function used by EmitEdgePropertyTest.
913 void EmitEdgePropertyTest1Arg(const DagInit& Prop,
914 const GlobalOptionDescriptions& OptDescs,
916 checkNumberOfArguments(&Prop, 1);
917 const std::string& OptName = InitPtrToString(Prop.getArg(0));
918 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
919 if (OptDesc.Type != OptionType::Switch)
920 throw OptName + ": incorrect option type!";
921 O << OptDesc.GenVariableName();
924 // Helper function used by EmitEdgePropertyTest.
925 void EmitEdgePropertyTest2Args(const std::string& PropName,
927 const GlobalOptionDescriptions& OptDescs,
929 checkNumberOfArguments(&Prop, 2);
930 const std::string& OptName = InitPtrToString(Prop.getArg(0));
931 const std::string& OptArg = InitPtrToString(Prop.getArg(1));
932 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
934 if (PropName == "parameter_equals") {
935 if (OptDesc.Type != OptionType::Parameter
936 && OptDesc.Type != OptionType::Prefix)
937 throw OptName + ": incorrect option type!";
938 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
940 else if (PropName == "element_in_list") {
941 if (OptDesc.Type != OptionType::ParameterList
942 && OptDesc.Type != OptionType::PrefixList)
943 throw OptName + ": incorrect option type!";
944 const std::string& VarName = OptDesc.GenVariableName();
945 O << "std::find(" << VarName << ".begin(),\n"
946 << Indent3 << VarName << ".end(), \""
947 << OptArg << "\") != " << VarName << ".end()";
950 throw PropName + ": unknown edge property!";
953 // Helper function used by EmitEdgeClass.
954 void EmitEdgePropertyTest(const std::string& PropName,
956 const GlobalOptionDescriptions& OptDescs,
958 if (PropName == "switch_on")
959 EmitEdgePropertyTest1Arg(Prop, OptDescs, O);
961 EmitEdgePropertyTest2Args(PropName, Prop, OptDescs, O);
964 // Emit a single Edge* class.
965 void EmitEdgeClass(unsigned N, const std::string& Target,
966 ListInit* Props, const GlobalOptionDescriptions& OptDescs,
968 bool IsDefault = false;
970 // Class constructor.
971 O << "class Edge" << N << ": public Edge {\n"
973 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
976 // Function isEnabled().
977 << Indent1 << "bool isEnabled() const {\n"
978 << Indent2 << "bool ret = false;\n";
980 for (size_t i = 0, PropsSize = Props->size(); i < PropsSize; ++i) {
981 const DagInit& Prop = dynamic_cast<DagInit&>(*Props->getElement(i));
982 const std::string& PropName = Prop.getOperator()->getAsString();
984 if (PropName == "default")
987 O << Indent2 << "if (ret || (";
988 if (PropName == "and") {
990 for (unsigned j = 0, NumArgs = Prop.getNumArgs(); j < NumArgs; ++j) {
991 const DagInit& InnerProp = dynamic_cast<DagInit&>(*Prop.getArg(j));
992 const std::string& InnerPropName =
993 InnerProp.getOperator()->getAsString();
994 EmitEdgePropertyTest(InnerPropName, InnerProp, OptDescs, O);
995 if (j != NumArgs - 1)
996 O << ")\n" << Indent3 << " && (";
1002 EmitEdgePropertyTest(PropName, Prop, OptDescs, O);
1004 O << "))\n" << Indent3 << "ret = true;\n";
1007 O << Indent2 << "return ret;\n"
1008 << Indent1 << "};\n\n"
1010 // Function isDefault().
1011 << Indent1 << "bool isDefault() const { return ";
1019 // Emit Edge* classes that represent graph edges.
1020 void EmitEdgeClasses (Record* CompilationGraph,
1021 const GlobalOptionDescriptions& OptDescs,
1023 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1025 for (unsigned i = 0; i < edges->size(); ++i) {
1026 Record* Edge = edges->getElementAsRecord(i);
1027 Record* B = Edge->getValueAsDef("b");
1028 ListInit* Props = Edge->getValueAsListInit("props");
1033 EmitEdgeClass(i, B->getName(), Props, OptDescs, O);
1037 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1040 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1043 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1044 << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
1048 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1050 throw std::string("No tool definitions found!");
1052 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1053 const std::string& Name = (*B)->getName();
1055 O << Indent1 << "G.insertNode(new "
1056 << Name << "());\n";
1062 for (unsigned i = 0; i < edges->size(); ++i) {
1063 Record* Edge = edges->getElementAsRecord(i);
1064 Record* A = Edge->getValueAsDef("a");
1065 Record* B = Edge->getValueAsDef("b");
1066 ListInit* Props = Edge->getValueAsListInit("props");
1068 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1071 O << "new SimpleEdge(\"" << B->getName() << "\")";
1073 O << "new Edge" << i << "()";
1082 // End of anonymous namespace
1085 // Back-end entry point
1086 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1088 EmitSourceFileHeader("LLVMC Configuration Library", O);
1090 // Get a list of all defined Tools
1091 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1093 throw std::string("No tool definitions found!");
1095 // Gather information from the Tool descriptions
1096 ToolPropertiesList tool_props;
1097 GlobalOptionDescriptions opt_descs;
1098 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1100 // Emit global option registration code
1101 EmitOptionDescriptions(opt_descs, O);
1103 // Emit PopulateLanguageMap function
1104 // (a language map maps from file extensions to language names)
1105 EmitPopulateLanguageMap(Records, O);
1107 // Emit Tool classes
1108 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1109 E = tool_props.end(); B!=E; ++B)
1110 EmitToolClassDefinition(*(*B), O);
1112 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1113 if (!CompilationGraphRecord)
1114 throw std::string("Compilation graph description not found!");
1116 // Typecheck the compilation graph.
1117 TypecheckGraph(CompilationGraphRecord, tool_props);
1119 // Emit Edge* classes.
1120 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1122 // Emit PopulateCompilationGraph function
1123 EmitPopulateCompilationGraph(CompilationGraphRecord, O);