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 int InitPtrToInt(Init* ptr) {
62 IntInit& val = dynamic_cast<IntInit&>(*ptr);
63 return val.getValue();
66 const DagInit& InitPtrToDagInitRef(Init* ptr) {
67 DagInit& val = dynamic_cast<DagInit&>(*ptr);
72 // checkNumberOfArguments - Ensure that the number of args in d is
73 // less than or equal to min_arguments, otherwise throw an exception .
74 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
75 if (d->getNumArgs() < min_arguments)
76 throw "Property " + d->getOperator()->getAsString()
77 + " has too few arguments!";
81 //===----------------------------------------------------------------------===//
82 /// Back-end specific code
84 // A command-line option can have one of the following types:
86 // Switch - a simple switch w/o arguments, e.g. -O2
88 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
91 // ParameterList - same as Parameter, but more than one occurence
92 // of the option is allowed, e.g. -lm -lpthread
94 // Prefix - argument is everything after the prefix,
95 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
97 // PrefixList - same as Prefix, but more than one option occurence is
100 namespace OptionType {
101 enum OptionType { Switch, Parameter, ParameterList, Prefix, PrefixList};
104 bool IsListOptionType (OptionType::OptionType t) {
105 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
108 // Code duplication here is necessary because one option can affect
109 // several tools and those tools may have different actions associated
110 // with this option. GlobalOptionDescriptions are used to generate
111 // the option registration code, while ToolOptionDescriptions are used
112 // to generate tool-specific code.
114 /// OptionDescription - Base class for option descriptions.
115 struct OptionDescription {
116 OptionType::OptionType Type;
119 OptionDescription(OptionType::OptionType t = OptionType::Switch,
120 const std::string& n = "")
124 const char* GenTypeDeclaration() const {
126 case OptionType::PrefixList:
127 case OptionType::ParameterList:
128 return "cl::list<std::string>";
129 case OptionType::Switch:
130 return "cl::opt<bool>";
131 case OptionType::Parameter:
132 case OptionType::Prefix:
134 return "cl::opt<std::string>";
138 std::string GenVariableName() const {
140 case OptionType::Switch:
141 return "AutoGeneratedSwitch" + Name;
142 case OptionType::Prefix:
143 return "AutoGeneratedPrefix" + Name;
144 case OptionType::PrefixList:
145 return "AutoGeneratedPrefixList" + Name;
146 case OptionType::Parameter:
147 return "AutoGeneratedParameter" + Name;
148 case OptionType::ParameterList:
150 return "AutoGeneratedParameterList" + Name;
156 // Global option description.
158 namespace GlobalOptionDescriptionFlags {
159 enum GlobalOptionDescriptionFlags { Required = 0x1 };
162 struct GlobalOptionDescription : public OptionDescription {
166 // We need t provide a default constructor since
167 // StringMap can only store DefaultConstructible objects
168 GlobalOptionDescription() : OptionDescription(), Flags(0)
171 GlobalOptionDescription (OptionType::OptionType t, const std::string& n)
172 : OptionDescription(t, n), Help(DefaultHelpString), Flags(0)
175 bool isRequired() const {
176 return Flags & GlobalOptionDescriptionFlags::Required;
179 Flags |= GlobalOptionDescriptionFlags::Required;
182 /// Merge - Merge two option descriptions.
183 void Merge (const GlobalOptionDescription& other)
185 if (other.Type != Type)
186 throw "Conflicting definitions for the option " + Name + "!";
188 if (Help == DefaultHelpString)
190 else if (other.Help != DefaultHelpString) {
191 llvm::cerr << "Warning: more than one help string defined for option "
195 Flags |= other.Flags;
199 /// GlobalOptionDescriptions - A GlobalOptionDescription array
200 /// together with some flags affecting generation of option
202 struct GlobalOptionDescriptions {
203 typedef StringMap<GlobalOptionDescription> container_type;
204 typedef container_type::const_iterator const_iterator;
206 /// Descriptions - A list of GlobalOptionDescriptions.
207 container_type Descriptions;
208 /// HasSink - Should the emitter generate a "cl::sink" option?
211 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
212 const_iterator I = Descriptions.find(OptName);
213 if (I != Descriptions.end())
216 throw OptName + ": no such option!";
219 // Support for STL-style iteration
220 const_iterator begin() const { return Descriptions.begin(); }
221 const_iterator end() const { return Descriptions.end(); }
225 // Tool-local option description
227 // Properties without arguments are implemented as flags
228 namespace ToolOptionDescriptionFlags {
229 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
230 Forward = 0x2, UnpackValues = 0x4};
232 namespace OptionPropertyType {
233 enum OptionPropertyType { AppendCmd };
236 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
238 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
240 struct ToolOptionDescription : public OptionDescription {
242 OptionPropertyList Props;
244 // StringMap can only store DefaultConstructible objects
245 ToolOptionDescription() : OptionDescription(), Flags(0) {}
247 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
248 : OptionDescription(t, n)
251 // Various boolean properties
252 bool isStopCompilation() const {
253 return Flags & ToolOptionDescriptionFlags::StopCompilation;
255 void setStopCompilation() {
256 Flags |= ToolOptionDescriptionFlags::StopCompilation;
259 bool isForward() const {
260 return Flags & ToolOptionDescriptionFlags::Forward;
263 Flags |= ToolOptionDescriptionFlags::Forward;
266 bool isUnpackValues() const {
267 return Flags & ToolOptionDescriptionFlags::UnpackValues;
269 void setUnpackValues() {
270 Flags |= ToolOptionDescriptionFlags::UnpackValues;
273 void AddProperty (OptionPropertyType::OptionPropertyType t,
274 const std::string& val)
276 Props.push_back(std::make_pair(t, val));
280 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
282 // Tool information record
284 namespace ToolFlags {
285 enum ToolFlags { Join = 0x1, Sink = 0x2 };
288 struct ToolProperties : public RefCountedBase<ToolProperties> {
291 std::string InLanguage;
292 std::string OutLanguage;
293 std::string OutputSuffix;
295 ToolOptionDescriptions OptDescs;
297 // Various boolean properties
298 void setSink() { Flags |= ToolFlags::Sink; }
299 bool isSink() const { return Flags & ToolFlags::Sink; }
300 void setJoin() { Flags |= ToolFlags::Join; }
301 bool isJoin() const { return Flags & ToolFlags::Join; }
303 // Default ctor here is needed because StringMap can only store
304 // DefaultConstructible objects
305 ToolProperties() : Flags(0) {}
306 ToolProperties (const std::string& n) : Name(n), Flags(0) {}
310 /// ToolPropertiesList - A list of Tool information records
311 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
312 /// constructor (and we want to avoid copying ToolProperties anyway).
313 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
316 /// CollectProperties - Function object for iterating over a list of
317 /// tool property records
318 class CollectProperties {
321 /// Implementation details
323 /// PropertyHandler - a function that extracts information
324 /// about a given tool property from its DAG representation
325 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
327 /// PropertyHandlerMap - A map from property names to property
329 typedef StringMap<PropertyHandler> PropertyHandlerMap;
331 /// OptionPropertyHandler - a function that extracts information
332 /// about a given option property from its DAG representation.
333 typedef void (CollectProperties::* OptionPropertyHandler)
334 (const DagInit*, GlobalOptionDescription &);
336 /// OptionPropertyHandlerMap - A map from option property names to
337 /// option property handlers
338 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
340 // Static maps from strings to CollectProperties methods("handlers")
341 static PropertyHandlerMap propertyHandlers_;
342 static OptionPropertyHandlerMap optionPropertyHandlers_;
343 static bool staticMembersInitialized_;
346 /// This is where the information is stored
348 /// toolProps_ - Properties of the current Tool.
349 ToolProperties& toolProps_;
350 /// optDescs_ - OptionDescriptions table (used to register options
352 GlobalOptionDescriptions& optDescs_;
356 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
357 : toolProps_(p), optDescs_(d)
359 if (!staticMembersInitialized_) {
360 // Init tool property handlers
361 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
362 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
363 propertyHandlers_["join"] = &CollectProperties::onJoin;
364 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
365 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
366 propertyHandlers_["parameter_option"]
367 = &CollectProperties::onParameter;
368 propertyHandlers_["parameter_list_option"] =
369 &CollectProperties::onParameterList;
370 propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
371 propertyHandlers_["prefix_list_option"] =
372 &CollectProperties::onPrefixList;
373 propertyHandlers_["sink"] = &CollectProperties::onSink;
374 propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
376 // Init option property handlers
377 optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
378 optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
379 optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
380 optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
381 optionPropertyHandlers_["stop_compilation"] =
382 &CollectProperties::onStopCompilation;
383 optionPropertyHandlers_["unpack_values"] =
384 &CollectProperties::onUnpackValues;
386 staticMembersInitialized_ = true;
390 /// operator() - Gets called for every tool property; Just forwards
391 /// to the corresponding property handler.
392 void operator() (Init* i) {
393 const DagInit& d = InitPtrToDagInitRef(i);
394 const std::string& property_name = d.getOperator()->getAsString();
395 PropertyHandlerMap::iterator method
396 = propertyHandlers_.find(property_name);
398 if (method != propertyHandlers_.end()) {
399 PropertyHandler h = method->second;
403 throw "Unknown tool property: " + property_name + "!";
409 /// Property handlers --
410 /// Functions that extract information about tool properties from
411 /// DAG representation.
413 void onCmdLine (const DagInit* d) {
414 checkNumberOfArguments(d, 1);
415 SplitString(InitPtrToString(d->getArg(0)), toolProps_.CmdLine);
416 if (toolProps_.CmdLine.empty())
417 throw "Tool " + toolProps_.Name + " has empty command line!";
420 void onInLanguage (const DagInit* d) {
421 checkNumberOfArguments(d, 1);
422 toolProps_.InLanguage = InitPtrToString(d->getArg(0));
425 void onJoin (const DagInit* d) {
426 checkNumberOfArguments(d, 0);
427 toolProps_.setJoin();
430 void onOutLanguage (const DagInit* d) {
431 checkNumberOfArguments(d, 1);
432 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
435 void onOutputSuffix (const DagInit* d) {
436 checkNumberOfArguments(d, 1);
437 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
440 void onSink (const DagInit* d) {
441 checkNumberOfArguments(d, 0);
442 optDescs_.HasSink = true;
443 toolProps_.setSink();
446 void onSwitch (const DagInit* d) {
447 addOption(d, OptionType::Switch);
450 void onParameter (const DagInit* d) {
451 addOption(d, OptionType::Parameter);
454 void onParameterList (const DagInit* d) {
455 addOption(d, OptionType::ParameterList);
458 void onPrefix (const DagInit* d) {
459 addOption(d, OptionType::Prefix);
462 void onPrefixList (const DagInit* d) {
463 addOption(d, OptionType::PrefixList);
466 /// Option property handlers --
467 /// Methods that handle properties that are common for all types of
468 /// options (like append_cmd, stop_compilation)
470 void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
471 checkNumberOfArguments(d, 1);
472 std::string const& cmd = InitPtrToString(d->getArg(0));
474 toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
477 void onForward (const DagInit* d, GlobalOptionDescription& o) {
478 checkNumberOfArguments(d, 0);
479 toolProps_.OptDescs[o.Name].setForward();
482 void onHelp (const DagInit* d, GlobalOptionDescription& o) {
483 checkNumberOfArguments(d, 1);
484 const std::string& help_message = InitPtrToString(d->getArg(0));
486 o.Help = help_message;
489 void onRequired (const DagInit* d, GlobalOptionDescription& o) {
490 checkNumberOfArguments(d, 0);
494 void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
495 checkNumberOfArguments(d, 0);
496 if (o.Type != OptionType::Switch)
497 throw std::string("Only options of type Switch can stop compilation!");
498 toolProps_.OptDescs[o.Name].setStopCompilation();
501 void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
502 checkNumberOfArguments(d, 0);
503 toolProps_.OptDescs[o.Name].setUnpackValues();
508 // Add an option of type t
509 void addOption (const DagInit* d, OptionType::OptionType t) {
510 checkNumberOfArguments(d, 2);
511 const std::string& name = InitPtrToString(d->getArg(0));
513 GlobalOptionDescription o(t, name);
514 toolProps_.OptDescs[name].Type = t;
515 toolProps_.OptDescs[name].Name = name;
516 processOptionProperties(d, o);
517 insertDescription(o);
520 // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
521 void insertDescription (const GlobalOptionDescription& o)
523 if (optDescs_.Descriptions.count(o.Name)) {
524 GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
528 optDescs_.Descriptions[o.Name] = o;
532 /// processOptionProperties - Go through the list of option
533 /// properties and call a corresponding handler for each.
536 /// name - option name
537 /// d - option property list
538 void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
539 // First argument is option name
540 checkNumberOfArguments(d, 2);
542 for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
543 const DagInit& option_property
544 = InitPtrToDagInitRef(d->getArg(B));
545 const std::string& option_property_name
546 = option_property.getOperator()->getAsString();
547 OptionPropertyHandlerMap::iterator method
548 = optionPropertyHandlers_.find(option_property_name);
550 if (method != optionPropertyHandlers_.end()) {
551 OptionPropertyHandler h = method->second;
552 (this->*h)(&option_property, o);
555 throw "Unknown option property: " + option_property_name + "!";
561 // Static members of CollectProperties
562 CollectProperties::PropertyHandlerMap
563 CollectProperties::propertyHandlers_;
565 CollectProperties::OptionPropertyHandlerMap
566 CollectProperties::optionPropertyHandlers_;
568 bool CollectProperties::staticMembersInitialized_ = false;
571 /// CollectToolProperties - Gather information from the parsed
572 /// TableGen data (basically a wrapper for CollectProperties).
573 void CollectToolProperties (RecordVector::const_iterator B,
574 RecordVector::const_iterator E,
575 ToolPropertiesList& TPList,
576 GlobalOptionDescriptions& OptDescs)
578 // Iterate over a properties list of every Tool definition
580 RecordVector::value_type T = *B;
581 ListInit* PropList = T->getValueAsListInit("properties");
583 IntrusiveRefCntPtr<ToolProperties>
584 ToolProps(new ToolProperties(T->getName()));
586 std::for_each(PropList->begin(), PropList->end(),
587 CollectProperties(*ToolProps, OptDescs));
588 TPList.push_back(ToolProps);
592 /// EmitOptionPropertyHandlingCode - Used by EmitGenerateActionMethod.
593 void EmitOptionPropertyHandlingCode (const ToolProperties& P,
594 const ToolOptionDescription& D,
598 O << Indent2 << "if (";
599 if (D.Type == OptionType::Switch)
600 O << D.GenVariableName();
602 O << '!' << D.GenVariableName() << ".empty()";
606 // Handle option properties that take an argument
607 for (OptionPropertyList::const_iterator B = D.Props.begin(),
608 E = D.Props.end(); B!=E; ++B) {
609 const OptionProperty& val = *B;
612 // (append_cmd cmd) property
613 case OptionPropertyType::AppendCmd:
614 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
616 // Other properties with argument
624 // (forward) property
627 case OptionType::Switch:
628 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
630 case OptionType::Parameter:
631 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
632 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
634 case OptionType::Prefix:
635 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
636 << D.GenVariableName() << ");\n";
638 case OptionType::PrefixList:
639 O << Indent3 << "for (" << D.GenTypeDeclaration()
640 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
641 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
642 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
645 case OptionType::ParameterList:
646 O << Indent3 << "for (" << D.GenTypeDeclaration()
647 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
648 << Indent3 << "E = " << D.GenVariableName()
649 << ".end() ; B != E; ++B) {\n"
650 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
651 << Indent4 << "vec.push_back(*B);\n"
657 // (unpack_values) property
658 if (D.isUnpackValues()) {
659 if (IsListOptionType(D.Type)) {
660 O << Indent3 << "for (" << D.GenTypeDeclaration()
661 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
662 << Indent3 << "E = " << D.GenVariableName()
663 << ".end(); B != E; ++B)\n"
664 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
666 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
667 O << Indent3 << "llvm::SplitString("
668 << D.GenVariableName() << ", vec, \",\");\n";
671 // TOFIX: move this to the type-checking phase
672 throw std::string("Switches can't have unpack_values property!");
677 O << Indent2 << "}\n";
680 // EmitGenerateActionMethod - Emit one of two versions of
681 // GenerateAction method.
682 void EmitGenerateActionMethod (const ToolProperties& P, int V, std::ostream& O)
684 assert(V==1 || V==2);
686 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
688 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
690 O << Indent2 << "const sys::Path& outFile) const\n"
692 << Indent2 << "std::vector<std::string> vec;\n";
694 // Parse CmdLine tool property
695 if(P.CmdLine.empty())
696 throw "Tool " + P.Name + " has empty command line!";
698 StrVector::const_iterator I = P.CmdLine.begin();
700 for (StrVector::const_iterator E = P.CmdLine.end(); I != E; ++I) {
701 const std::string& cmd = *I;
703 if (cmd == "$INFILE") {
705 O << "for (PathVector::const_iterator B = inFiles.begin()"
706 << ", E = inFiles.end();\n"
707 << Indent2 << "B != E; ++B)\n"
708 << Indent3 << "vec.push_back(B->toString());\n";
710 O << "vec.push_back(inFile.toString());\n";
712 else if (cmd == "$OUTFILE") {
713 O << "vec.push_back(outFile.toString());\n";
716 O << "vec.push_back(\"" << cmd << "\");\n";
720 // For every understood option, emit handling code
721 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
722 E = P.OptDescs.end(); B != E; ++B) {
723 const ToolOptionDescription& val = B->second;
724 EmitOptionPropertyHandlingCode(P, val, O);
727 // Handle Sink property
729 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
730 << Indent3 << "vec.insert(vec.end(), "
731 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
735 O << Indent2 << "return Action(\"" << P.CmdLine.at(0) << "\", vec);\n"
736 << Indent1 << "}\n\n";
739 /// EmitGenerateActionMethods - Emit two GenerateAction methods for a given
741 void EmitGenerateActionMethods (const ToolProperties& P, std::ostream& O) {
744 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
745 << Indent2 << "const llvm::sys::Path& outFile) const\n"
747 << Indent2 << "throw std::runtime_error(\"" << P.Name
748 << " is not a Join tool!\");\n"
749 << Indent1 << "}\n\n";
751 EmitGenerateActionMethod(P, 1, O);
753 EmitGenerateActionMethod(P, 2, O);
756 /// EmitIsLastMethod - Emit IsLast() method for a given Tool class
757 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
758 O << Indent1 << "bool IsLast() const {\n"
759 << Indent2 << "bool last = false;\n";
761 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
762 E = P.OptDescs.end(); B != E; ++B) {
763 const ToolOptionDescription& val = B->second;
765 if (val.isStopCompilation())
767 << "if (" << val.GenVariableName()
768 << ")\n" << Indent3 << "last = true;\n";
771 O << Indent2 << "return last;\n"
772 << Indent1 << "}\n\n";
775 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
776 /// methods for a given Tool class.
777 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
778 O << Indent1 << "const char* InputLanguage() const {\n"
779 << Indent2 << "return \"" << P.InLanguage << "\";\n"
780 << Indent1 << "}\n\n";
782 O << Indent1 << "const char* OutputLanguage() const {\n"
783 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
784 << Indent1 << "}\n\n";
787 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
788 /// given Tool class.
789 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
790 O << Indent1 << "const char* OutputSuffix() const {\n"
791 << Indent2 << "return \"" << P.OutputSuffix << "\";\n"
792 << Indent1 << "}\n\n";
795 /// EmitNameMethod - Emit the Name() method for a given Tool class.
796 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
797 O << Indent1 << "const char* Name() const {\n"
798 << Indent2 << "return \"" << P.Name << "\";\n"
799 << Indent1 << "}\n\n";
802 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
804 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
805 O << Indent1 << "bool IsJoin() const {\n";
807 O << Indent2 << "return true;\n";
809 O << Indent2 << "return false;\n";
810 O << Indent1 << "}\n\n";
813 /// EmitToolClassDefinition - Emit a Tool class definition.
814 void EmitToolClassDefinition (const ToolProperties& P, std::ostream& O) {
820 O << "class " << P.Name << " : public ";
825 O << " {\npublic:\n";
827 EmitNameMethod(P, O);
828 EmitInOutLanguageMethods(P, O);
829 EmitOutputSuffixMethod(P, O);
830 EmitIsJoinMethod(P, O);
831 EmitGenerateActionMethods(P, O);
832 EmitIsLastMethod(P, O);
834 // Close class definition
838 /// EmitOptionDescriptions - Iterate over a list of option
839 /// descriptions and emit registration code.
840 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
843 // Emit static cl::Option variables
844 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
845 E = descs.end(); B!=E; ++B) {
846 const GlobalOptionDescription& val = B->second;
848 O << val.GenTypeDeclaration() << ' '
849 << val.GenVariableName()
850 << "(\"" << val.Name << '\"';
852 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
855 if (val.isRequired()) {
857 case OptionType::PrefixList:
858 case OptionType::ParameterList:
859 O << ", cl::OneOrMore";
862 O << ", cl::Required";
866 O << ", cl::desc(\"" << val.Help << "\"));\n";
870 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
875 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
876 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
878 // Get the relevant field out of RecordKeeper
879 Record* LangMapRecord = Records.getDef("LanguageMap");
881 throw std::string("Language map definition not found!");
883 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
884 if (!LangsToSuffixesList)
885 throw std::string("Error in the language map definition!");
888 O << "void llvmc::PopulateLanguageMap(LanguageMap& language_map) {\n";
890 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
891 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
893 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
894 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
896 for (unsigned i = 0; i < Suffixes->size(); ++i)
897 O << Indent1 << "language_map[\""
898 << InitPtrToString(Suffixes->getElement(i))
899 << "\"] = \"" << Lang << "\";\n";
905 /// FillInToolToLang - Fills in two tables that map tool names to
906 /// (input, output) languages. Used by the typechecker.
907 void FillInToolToLang (const ToolPropertiesList& TPList,
908 StringMap<std::string>& ToolToInLang,
909 StringMap<std::string>& ToolToOutLang) {
910 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
912 const ToolProperties& P = *(*B);
913 ToolToInLang[P.Name] = P.InLanguage;
914 ToolToOutLang[P.Name] = P.OutLanguage;
918 /// TypecheckGraph - Check that names for output and input languages
919 /// on all edges do match.
920 // TOFIX: check for cycles.
921 // TOFIX: check for multiple default edges.
922 void TypecheckGraph (Record* CompilationGraph,
923 const ToolPropertiesList& TPList) {
924 StringMap<std::string> ToolToInLang;
925 StringMap<std::string> ToolToOutLang;
927 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
928 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
929 StringMap<std::string>::iterator IAE = ToolToInLang.end();
930 StringMap<std::string>::iterator IBE = ToolToOutLang.end();
932 for (unsigned i = 0; i < edges->size(); ++i) {
933 Record* Edge = edges->getElementAsRecord(i);
934 Record* A = Edge->getValueAsDef("a");
935 Record* B = Edge->getValueAsDef("b");
936 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
937 StringMap<std::string>::iterator IB = ToolToInLang.find(B->getName());
939 throw A->getName() + ": no such tool!";
941 throw B->getName() + ": no such tool!";
942 if(A->getName() != "root" && IA->second != IB->second)
943 throw "Edge " + A->getName() + "->" + B->getName()
944 + ": output->input language mismatch";
945 if(B->getName() == "root")
946 throw std::string("Edges back to the root are not allowed!");
950 /// EmitEdgePropertyTest1Arg - Helper function used by
951 /// EmitEdgePropertyTest.
952 bool EmitEdgePropertyTest1Arg(const std::string& PropName,
954 const GlobalOptionDescriptions& OptDescs,
956 checkNumberOfArguments(&Prop, 1);
957 const std::string& OptName = InitPtrToString(Prop.getArg(0));
958 if (PropName == "switch_on") {
959 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
960 if (OptDesc.Type != OptionType::Switch)
961 throw OptName + ": incorrect option type!";
962 O << OptDesc.GenVariableName();
964 } else if (PropName == "if_input_languages_contain") {
965 O << "InLangs.count(\"" << OptName << "\") != 0";
972 /// EmitEdgePropertyTest2Args - Helper function used by
973 /// EmitEdgePropertyTest.
974 bool EmitEdgePropertyTest2Args(const std::string& PropName,
976 const GlobalOptionDescriptions& OptDescs,
978 checkNumberOfArguments(&Prop, 2);
979 const std::string& OptName = InitPtrToString(Prop.getArg(0));
980 const std::string& OptArg = InitPtrToString(Prop.getArg(1));
981 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
983 if (PropName == "parameter_equals") {
984 if (OptDesc.Type != OptionType::Parameter
985 && OptDesc.Type != OptionType::Prefix)
986 throw OptName + ": incorrect option type!";
987 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
990 else if (PropName == "element_in_list") {
991 if (OptDesc.Type != OptionType::ParameterList
992 && OptDesc.Type != OptionType::PrefixList)
993 throw OptName + ": incorrect option type!";
994 const std::string& VarName = OptDesc.GenVariableName();
995 O << "std::find(" << VarName << ".begin(),\n"
996 << Indent3 << VarName << ".end(), \""
997 << OptArg << "\") != " << VarName << ".end()";
1004 // Forward declaration.
1005 void EmitEdgePropertyTest(const DagInit& Prop,
1006 const GlobalOptionDescriptions& OptDescs,
1009 /// EmitLogicalOperationTest - Helper function used by
1010 /// EmitEdgePropertyTest.
1011 void EmitLogicalOperationTest(const DagInit& Prop, const char* LogicOp,
1012 const GlobalOptionDescriptions& OptDescs,
1015 for (unsigned j = 0, NumArgs = Prop.getNumArgs(); j < NumArgs; ++j) {
1016 const DagInit& InnerProp = InitPtrToDagInitRef(Prop.getArg(j));
1017 EmitEdgePropertyTest(InnerProp, OptDescs, O);
1018 if (j != NumArgs - 1)
1019 O << ")\n" << Indent3 << ' ' << LogicOp << " (";
1025 /// EmitEdgePropertyTest - Helper function used by EmitEdgeClass.
1026 void EmitEdgePropertyTest(const DagInit& Prop,
1027 const GlobalOptionDescriptions& OptDescs,
1029 const std::string& PropName = Prop.getOperator()->getAsString();
1031 if (PropName == "and")
1032 EmitLogicalOperationTest(Prop, "&&", OptDescs, O);
1033 else if (PropName == "or")
1034 EmitLogicalOperationTest(Prop, "||", OptDescs, O);
1035 else if (EmitEdgePropertyTest1Arg(PropName, Prop, OptDescs, O))
1037 else if (EmitEdgePropertyTest2Args(PropName, Prop, OptDescs, O))
1040 throw PropName + ": unknown edge property!";
1043 /// EmitEdgeClass - Emit a single Edge# class.
1044 void EmitEdgeClass(unsigned N, const std::string& Target,
1045 ListInit* Props, const GlobalOptionDescriptions& OptDescs,
1048 // Class constructor.
1049 O << "class Edge" << N << ": public Edge {\n"
1051 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1054 // Function Weight().
1055 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1056 << Indent2 << "unsigned ret = 0;\n";
1058 // Emit tests for every edge property.
1059 for (size_t i = 0, PropsSize = Props->size(); i < PropsSize; ++i) {
1060 const DagInit& Prop = InitPtrToDagInitRef(Props->getElement(i));
1061 const std::string& PropName = Prop.getOperator()->getAsString();
1064 O << Indent2 << "if (";
1066 if (PropName == "weight") {
1067 checkNumberOfArguments(&Prop, 2);
1068 N = InitPtrToInt(Prop.getArg(0));
1069 const DagInit& InnerProp = InitPtrToDagInitRef(Prop.getArg(1));
1070 EmitEdgePropertyTest(InnerProp, OptDescs, O);
1073 EmitEdgePropertyTest(Prop, OptDescs, O);
1076 O << ")\n" << Indent3 << "ret += " << N << ";\n";
1079 O << Indent2 << "return ret;\n"
1080 << Indent1 << "};\n\n};\n\n";
1083 // Emit Edge* classes that represent graph edges.
1084 void EmitEdgeClasses (Record* CompilationGraph,
1085 const GlobalOptionDescriptions& OptDescs,
1087 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1089 for (unsigned i = 0; i < edges->size(); ++i) {
1090 Record* Edge = edges->getElementAsRecord(i);
1091 Record* B = Edge->getValueAsDef("b");
1092 ListInit* Props = Edge->getValueAsListInit("props");
1097 EmitEdgeClass(i, B->getName(), Props, OptDescs, O);
1101 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1103 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1106 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1109 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1110 << Indent1 << "PopulateLanguageMap(G.ExtsToLangs);\n\n";
1114 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1116 throw std::string("No tool definitions found!");
1118 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1119 const std::string& Name = (*B)->getName();
1121 O << Indent1 << "G.insertNode(new "
1122 << Name << "());\n";
1128 for (unsigned i = 0; i < edges->size(); ++i) {
1129 Record* Edge = edges->getElementAsRecord(i);
1130 Record* A = Edge->getValueAsDef("a");
1131 Record* B = Edge->getValueAsDef("b");
1132 ListInit* Props = Edge->getValueAsListInit("props");
1134 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1137 O << "new SimpleEdge(\"" << B->getName() << "\")";
1139 O << "new Edge" << i << "()";
1148 // End of anonymous namespace
1151 /// run - The back-end entry point.
1152 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1154 // Emit file header.
1155 EmitSourceFileHeader("LLVMC Configuration Library", O);
1157 // Get a list of all defined Tools.
1158 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1160 throw std::string("No tool definitions found!");
1162 // Gather information from the Tool description dags.
1163 ToolPropertiesList tool_props;
1164 GlobalOptionDescriptions opt_descs;
1165 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1167 // Emit global option registration code.
1168 EmitOptionDescriptions(opt_descs, O);
1170 // Emit PopulateLanguageMap() function
1171 // (a language map maps from file extensions to language names).
1172 EmitPopulateLanguageMap(Records, O);
1174 // Emit Tool classes.
1175 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1176 E = tool_props.end(); B!=E; ++B)
1177 EmitToolClassDefinition(*(*B), O);
1179 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1180 if (!CompilationGraphRecord)
1181 throw std::string("Compilation graph description not found!");
1183 // Typecheck the compilation graph.
1184 TypecheckGraph(CompilationGraphRecord, tool_props);
1186 // Emit Edge# classes.
1187 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1189 // Emit PopulateCompilationGraph() function.
1190 EmitPopulateCompilationGraph(CompilationGraphRecord, O);