1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
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/ADT/StringSet.h"
22 #include "llvm/Support/Streams.h"
35 //===----------------------------------------------------------------------===//
38 typedef std::vector<Record*> RecordVector;
39 typedef std::vector<std::string> StrVector;
41 //===----------------------------------------------------------------------===//
44 // Indentation strings.
45 const char * Indent1 = " ";
46 const char * Indent2 = " ";
47 const char * Indent3 = " ";
48 const char * Indent4 = " ";
50 // Default help string.
51 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
53 // Name for the "sink" option.
54 const char * SinkOptionName = "AutoGeneratedSinkOption";
56 //===----------------------------------------------------------------------===//
59 int InitPtrToInt(const Init* ptr) {
60 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
61 return val.getValue();
64 const std::string& InitPtrToString(const Init* ptr) {
65 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
66 return val.getValue();
69 const ListInit& InitPtrToList(const Init* ptr) {
70 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
74 const DagInit& InitPtrToDag(const Init* ptr) {
75 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
79 // checkNumberOfArguments - Ensure that the number of args in d is
80 // less than or equal to min_arguments, otherwise throw an exception.
81 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
82 if (d->getNumArgs() < min_arguments)
83 throw "Property " + d->getOperator()->getAsString()
84 + " has too few arguments!";
87 // isDagEmpty - is this DAG marked with an empty marker?
88 bool isDagEmpty (const DagInit* d) {
89 return d->getOperator()->getAsString() == "empty";
92 //===----------------------------------------------------------------------===//
93 /// Back-end specific code
95 // A command-line option can have one of the following types:
97 // Alias - an alias for another option.
99 // Switch - a simple switch without arguments, e.g. -O2
101 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
104 // ParameterList - same as Parameter, but more than one occurence
105 // of the option is allowed, e.g. -lm -lpthread
107 // Prefix - argument is everything after the prefix,
108 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
110 // PrefixList - same as Prefix, but more than one option occurence is
113 namespace OptionType {
114 enum OptionType { Alias, Switch,
115 Parameter, ParameterList, Prefix, PrefixList};
118 bool IsListOptionType (OptionType::OptionType t) {
119 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
122 // Code duplication here is necessary because one option can affect
123 // several tools and those tools may have different actions associated
124 // with this option. GlobalOptionDescriptions are used to generate
125 // the option registration code, while ToolOptionDescriptions are used
126 // to generate tool-specific code.
128 /// OptionDescription - Base class for option descriptions.
129 struct OptionDescription {
130 OptionType::OptionType Type;
133 OptionDescription(OptionType::OptionType t = OptionType::Switch,
134 const std::string& n = "")
138 const char* GenTypeDeclaration() const {
140 case OptionType::Alias:
142 case OptionType::PrefixList:
143 case OptionType::ParameterList:
144 return "cl::list<std::string>";
145 case OptionType::Switch:
146 return "cl::opt<bool>";
147 case OptionType::Parameter:
148 case OptionType::Prefix:
150 return "cl::opt<std::string>";
154 // Escape commas and other symbols not allowed in the C++ variable
155 // names. Makes it possible to use options with names like "Wa,"
156 // (useful for prefix options).
157 std::string EscapeVariableName(const std::string& Var) const {
159 for (unsigned i = 0; i != Var.size(); ++i) {
160 char cur_char = Var[i];
161 if (cur_char == ',') {
164 else if (cur_char == '+') {
167 else if (cur_char == '-') {
171 ret.push_back(cur_char);
177 std::string GenVariableName() const {
178 const std::string& EscapedName = EscapeVariableName(Name);
180 case OptionType::Alias:
181 return "AutoGeneratedAlias" + EscapedName;
182 case OptionType::Switch:
183 return "AutoGeneratedSwitch" + EscapedName;
184 case OptionType::Prefix:
185 return "AutoGeneratedPrefix" + EscapedName;
186 case OptionType::PrefixList:
187 return "AutoGeneratedPrefixList" + EscapedName;
188 case OptionType::Parameter:
189 return "AutoGeneratedParameter" + EscapedName;
190 case OptionType::ParameterList:
192 return "AutoGeneratedParameterList" + EscapedName;
198 // Global option description.
200 namespace GlobalOptionDescriptionFlags {
201 enum GlobalOptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
202 ReallyHidden = 0x4 };
205 struct GlobalOptionDescription : public OptionDescription {
209 // We need to provide a default constructor because
210 // StringMap can only store DefaultConstructible objects.
211 GlobalOptionDescription() : OptionDescription(), Flags(0)
214 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
215 const std::string& h = DefaultHelpString)
216 : OptionDescription(t, n), Help(h), Flags(0)
219 bool isRequired() const {
220 return Flags & GlobalOptionDescriptionFlags::Required;
223 Flags |= GlobalOptionDescriptionFlags::Required;
226 bool isHidden() const {
227 return Flags & GlobalOptionDescriptionFlags::Hidden;
230 Flags |= GlobalOptionDescriptionFlags::Hidden;
233 bool isReallyHidden() const {
234 return Flags & GlobalOptionDescriptionFlags::ReallyHidden;
236 void setReallyHidden() {
237 Flags |= GlobalOptionDescriptionFlags::ReallyHidden;
240 /// Merge - Merge two option descriptions.
241 void Merge (const GlobalOptionDescription& other)
243 if (other.Type != Type)
244 throw "Conflicting definitions for the option " + Name + "!";
246 if (Help == other.Help || Help == DefaultHelpString)
248 else if (other.Help != DefaultHelpString) {
249 llvm::cerr << "Warning: several different help strings"
250 " defined for option " + Name + "\n";
253 Flags |= other.Flags;
257 /// GlobalOptionDescriptions - A GlobalOptionDescription array
258 /// together with some flags affecting generation of option
260 struct GlobalOptionDescriptions {
261 typedef StringMap<GlobalOptionDescription> container_type;
262 typedef container_type::const_iterator const_iterator;
264 /// Descriptions - A list of GlobalOptionDescriptions.
265 container_type Descriptions;
266 /// HasSink - Should the emitter generate a "cl::sink" option?
269 /// FindOption - exception-throwing wrapper for find().
270 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
271 const_iterator I = Descriptions.find(OptName);
272 if (I != Descriptions.end())
275 throw OptName + ": no such option!";
278 /// insertDescription - Insert new GlobalOptionDescription into
279 /// GlobalOptionDescriptions list
280 void insertDescription (const GlobalOptionDescription& o)
282 container_type::iterator I = Descriptions.find(o.Name);
283 if (I != Descriptions.end()) {
284 GlobalOptionDescription& D = I->second;
288 Descriptions[o.Name] = o;
292 // Support for STL-style iteration
293 const_iterator begin() const { return Descriptions.begin(); }
294 const_iterator end() const { return Descriptions.end(); }
298 // Tool-local option description.
300 // Properties without arguments are implemented as flags.
301 namespace ToolOptionDescriptionFlags {
302 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
303 Forward = 0x2, UnpackValues = 0x4};
305 namespace OptionPropertyType {
306 enum OptionPropertyType { AppendCmd, ForwardAs, OutputSuffix };
309 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
311 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
313 struct ToolOptionDescription : public OptionDescription {
315 OptionPropertyList Props;
317 // StringMap can only store DefaultConstructible objects
318 ToolOptionDescription() : OptionDescription(), Flags(0) {}
320 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
321 : OptionDescription(t, n)
324 // Various boolean properties
325 bool isStopCompilation() const {
326 return Flags & ToolOptionDescriptionFlags::StopCompilation;
328 void setStopCompilation() {
329 Flags |= ToolOptionDescriptionFlags::StopCompilation;
332 bool isForward() const {
333 return Flags & ToolOptionDescriptionFlags::Forward;
336 Flags |= ToolOptionDescriptionFlags::Forward;
339 bool isUnpackValues() const {
340 return Flags & ToolOptionDescriptionFlags::UnpackValues;
342 void setUnpackValues() {
343 Flags |= ToolOptionDescriptionFlags::UnpackValues;
346 void AddProperty (OptionPropertyType::OptionPropertyType t,
347 const std::string& val)
349 Props.push_back(std::make_pair(t, val));
353 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
355 // Tool information record
357 namespace ToolFlags {
358 enum ToolFlags { Join = 0x1, Sink = 0x2 };
361 struct ToolProperties : public RefCountedBase<ToolProperties> {
364 StrVector InLanguage;
365 std::string OutLanguage;
366 std::string OutputSuffix;
368 ToolOptionDescriptions OptDescs;
370 // Various boolean properties
371 void setSink() { Flags |= ToolFlags::Sink; }
372 bool isSink() const { return Flags & ToolFlags::Sink; }
373 void setJoin() { Flags |= ToolFlags::Join; }
374 bool isJoin() const { return Flags & ToolFlags::Join; }
376 // Default ctor here is needed because StringMap can only store
377 // DefaultConstructible objects
378 ToolProperties() : CmdLine(0), Flags(0) {}
379 ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
383 /// ToolPropertiesList - A list of Tool information records
384 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
385 /// constructor (and we want to avoid copying ToolProperties anyway).
386 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
389 /// CollectOptionProperties - Function object for iterating over a
390 /// list (usually, a DAG) of option property records.
391 class CollectOptionProperties {
393 // Implementation details.
395 /// OptionPropertyHandler - a function that extracts information
396 /// about a given option property from its DAG representation.
397 typedef void (CollectOptionProperties::* OptionPropertyHandler)
400 /// OptionPropertyHandlerMap - A map from option property names to
401 /// option property handlers
402 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
404 static OptionPropertyHandlerMap optionPropertyHandlers_;
405 static bool staticMembersInitialized_;
407 /// This is where the information is stored
409 /// toolProps_ - Properties of the current Tool.
410 ToolProperties* toolProps_;
411 /// optDescs_ - OptionDescriptions table (used to register options
413 GlobalOptionDescription& optDesc_;
417 explicit CollectOptionProperties(ToolProperties* TP,
418 GlobalOptionDescription& OD)
419 : toolProps_(TP), optDesc_(OD)
421 if (!staticMembersInitialized_) {
422 optionPropertyHandlers_["append_cmd"] =
423 &CollectOptionProperties::onAppendCmd;
424 optionPropertyHandlers_["forward"] =
425 &CollectOptionProperties::onForward;
426 optionPropertyHandlers_["forward_as"] =
427 &CollectOptionProperties::onForwardAs;
428 optionPropertyHandlers_["help"] =
429 &CollectOptionProperties::onHelp;
430 optionPropertyHandlers_["hidden"] =
431 &CollectOptionProperties::onHidden;
432 optionPropertyHandlers_["output_suffix"] =
433 &CollectOptionProperties::onOutputSuffix;
434 optionPropertyHandlers_["really_hidden"] =
435 &CollectOptionProperties::onReallyHidden;
436 optionPropertyHandlers_["required"] =
437 &CollectOptionProperties::onRequired;
438 optionPropertyHandlers_["stop_compilation"] =
439 &CollectOptionProperties::onStopCompilation;
440 optionPropertyHandlers_["unpack_values"] =
441 &CollectOptionProperties::onUnpackValues;
443 staticMembersInitialized_ = true;
447 /// operator() - Gets called for every option property; Just forwards
448 /// to the corresponding property handler.
449 void operator() (Init* i) {
450 const DagInit& option_property = InitPtrToDag(i);
451 const std::string& option_property_name
452 = option_property.getOperator()->getAsString();
453 OptionPropertyHandlerMap::iterator method
454 = optionPropertyHandlers_.find(option_property_name);
456 if (method != optionPropertyHandlers_.end()) {
457 OptionPropertyHandler h = method->second;
458 (this->*h)(&option_property);
461 throw "Unknown option property: " + option_property_name + "!";
467 /// Option property handlers --
468 /// Methods that handle properties that are common for all types of
469 /// options (like append_cmd, stop_compilation)
471 void onAppendCmd (const DagInit* d) {
472 checkNumberOfArguments(d, 1);
474 const std::string& cmd = InitPtrToString(d->getArg(0));
476 toolProps_->OptDescs[optDesc_.Name].
477 AddProperty(OptionPropertyType::AppendCmd, cmd);
480 void onOutputSuffix (const DagInit* d) {
481 checkNumberOfArguments(d, 1);
483 const std::string& suf = InitPtrToString(d->getArg(0));
485 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
486 throw "Option " + optDesc_.Name
487 + " can't have 'output_suffix' property since it isn't a switch!";
489 toolProps_->OptDescs[optDesc_.Name].AddProperty
490 (OptionPropertyType::OutputSuffix, suf);
493 void onForward (const DagInit* d) {
494 checkNumberOfArguments(d, 0);
496 toolProps_->OptDescs[optDesc_.Name].setForward();
499 void onForwardAs (const DagInit* d) {
500 checkNumberOfArguments(d, 1);
502 const std::string& cmd = InitPtrToString(d->getArg(0));
504 toolProps_->OptDescs[optDesc_.Name].
505 AddProperty(OptionPropertyType::ForwardAs, cmd);
508 void onHelp (const DagInit* d) {
509 checkNumberOfArguments(d, 1);
510 const std::string& help_message = InitPtrToString(d->getArg(0));
512 optDesc_.Help = help_message;
515 void onHidden (const DagInit* d) {
516 checkNumberOfArguments(d, 0);
518 optDesc_.setHidden();
521 void onReallyHidden (const DagInit* d) {
522 checkNumberOfArguments(d, 0);
524 optDesc_.setReallyHidden();
527 void onRequired (const DagInit* d) {
528 checkNumberOfArguments(d, 0);
530 optDesc_.setRequired();
533 void onStopCompilation (const DagInit* d) {
534 checkNumberOfArguments(d, 0);
536 if (optDesc_.Type != OptionType::Switch)
537 throw std::string("Only options of type Switch can stop compilation!");
538 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
541 void onUnpackValues (const DagInit* d) {
542 checkNumberOfArguments(d, 0);
544 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
549 /// checkToolProps - Throw an error if toolProps_ == 0.
550 void checkToolProps(const DagInit* d) {
552 throw "Option property " + d->getOperator()->getAsString()
553 + " can't be used in this context";
558 CollectOptionProperties::OptionPropertyHandlerMap
559 CollectOptionProperties::optionPropertyHandlers_;
561 bool CollectOptionProperties::staticMembersInitialized_ = false;
564 /// processOptionProperties - Go through the list of option
565 /// properties and call a corresponding handler for each.
566 void processOptionProperties (const DagInit* d, ToolProperties* t,
567 GlobalOptionDescription& o) {
568 checkNumberOfArguments(d, 2);
569 DagInit::const_arg_iterator B = d->arg_begin();
570 // Skip the first argument: it's always the option name.
572 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
575 /// AddOption - A function object wrapper for
576 /// processOptionProperties. Used by CollectProperties and
577 /// CollectPropertiesFromOptionList.
580 GlobalOptionDescriptions& OptDescs_;
581 ToolProperties* ToolProps_;
584 explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
585 : OptDescs_(OD), ToolProps_(TP)
588 void operator()(const Init* i) {
589 const DagInit& d = InitPtrToDag(i);
590 checkNumberOfArguments(&d, 2);
592 const OptionType::OptionType Type =
593 getOptionType(d.getOperator()->getAsString());
594 const std::string& Name = InitPtrToString(d.getArg(0));
596 GlobalOptionDescription OD(Type, Name);
597 if (Type != OptionType::Alias) {
598 processOptionProperties(&d, ToolProps_, OD);
600 ToolProps_->OptDescs[Name].Type = Type;
601 ToolProps_->OptDescs[Name].Name = Name;
605 OD.Help = InitPtrToString(d.getArg(1));
607 OptDescs_.insertDescription(OD);
611 OptionType::OptionType getOptionType(const std::string& T) const {
612 if (T == "alias_option")
613 return OptionType::Alias;
614 else if (T == "switch_option")
615 return OptionType::Switch;
616 else if (T == "parameter_option")
617 return OptionType::Parameter;
618 else if (T == "parameter_list_option")
619 return OptionType::ParameterList;
620 else if (T == "prefix_option")
621 return OptionType::Prefix;
622 else if (T == "prefix_list_option")
623 return OptionType::PrefixList;
625 throw "Unknown option type: " + T + '!';
630 /// CollectProperties - Function object for iterating over a list of
631 /// tool property records.
632 class CollectProperties {
635 // Implementation details
637 /// PropertyHandler - a function that extracts information
638 /// about a given tool property from its DAG representation
639 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
641 /// PropertyHandlerMap - A map from property names to property
643 typedef StringMap<PropertyHandler> PropertyHandlerMap;
645 // Static maps from strings to CollectProperties methods("handlers")
646 static PropertyHandlerMap propertyHandlers_;
647 static bool staticMembersInitialized_;
650 /// This is where the information is stored
652 /// toolProps_ - Properties of the current Tool.
653 ToolProperties& toolProps_;
654 /// optDescs_ - OptionDescriptions table (used to register options
656 GlobalOptionDescriptions& optDescs_;
660 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
661 : toolProps_(p), optDescs_(d)
663 if (!staticMembersInitialized_) {
664 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
665 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
666 propertyHandlers_["join"] = &CollectProperties::onJoin;
667 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
668 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
669 propertyHandlers_["parameter_option"]
670 = &CollectProperties::addOption;
671 propertyHandlers_["parameter_list_option"] =
672 &CollectProperties::addOption;
673 propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
674 propertyHandlers_["prefix_list_option"] =
675 &CollectProperties::addOption;
676 propertyHandlers_["sink"] = &CollectProperties::onSink;
677 propertyHandlers_["switch_option"] = &CollectProperties::addOption;
678 propertyHandlers_["alias_option"] = &CollectProperties::addOption;
680 staticMembersInitialized_ = true;
684 /// operator() - Gets called for every tool property; Just forwards
685 /// to the corresponding property handler.
686 void operator() (Init* i) {
687 const DagInit& d = InitPtrToDag(i);
688 const std::string& property_name = d.getOperator()->getAsString();
689 PropertyHandlerMap::iterator method
690 = propertyHandlers_.find(property_name);
692 if (method != propertyHandlers_.end()) {
693 PropertyHandler h = method->second;
697 throw "Unknown tool property: " + property_name + "!";
703 /// Property handlers --
704 /// Functions that extract information about tool properties from
705 /// DAG representation.
707 void onCmdLine (const DagInit* d) {
708 checkNumberOfArguments(d, 1);
709 toolProps_.CmdLine = d->getArg(0);
712 void onInLanguage (const DagInit* d) {
713 checkNumberOfArguments(d, 1);
714 Init* arg = d->getArg(0);
716 // Find out the argument's type.
717 if (typeid(*arg) == typeid(StringInit)) {
719 toolProps_.InLanguage.push_back(InitPtrToString(arg));
723 const ListInit& lst = InitPtrToList(arg);
724 StrVector& out = toolProps_.InLanguage;
726 // Copy strings to the output vector.
727 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
729 out.push_back(InitPtrToString(*B));
732 // Remove duplicates.
733 std::sort(out.begin(), out.end());
734 StrVector::iterator newE = std::unique(out.begin(), out.end());
735 out.erase(newE, out.end());
739 void onJoin (const DagInit* d) {
740 checkNumberOfArguments(d, 0);
741 toolProps_.setJoin();
744 void onOutLanguage (const DagInit* d) {
745 checkNumberOfArguments(d, 1);
746 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
749 void onOutputSuffix (const DagInit* d) {
750 checkNumberOfArguments(d, 1);
751 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
754 void onSink (const DagInit* d) {
755 checkNumberOfArguments(d, 0);
756 optDescs_.HasSink = true;
757 toolProps_.setSink();
760 // Just forwards to the AddOption function object. Somewhat
761 // non-optimal, but avoids code duplication.
762 void addOption (const DagInit* d) {
763 checkNumberOfArguments(d, 2);
764 AddOption(optDescs_, &toolProps_)(d);
769 // Defintions of static members of CollectProperties.
770 CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
771 bool CollectProperties::staticMembersInitialized_ = false;
774 /// CollectToolProperties - Gather information about tool properties
775 /// from the parsed TableGen data (basically a wrapper for the
776 /// CollectProperties function object).
777 void CollectToolProperties (RecordVector::const_iterator B,
778 RecordVector::const_iterator E,
779 ToolPropertiesList& TPList,
780 GlobalOptionDescriptions& OptDescs)
782 // Iterate over a properties list of every Tool definition
784 const Record* T = *B;
785 // Throws an exception if the value does not exist.
786 ListInit* PropList = T->getValueAsListInit("properties");
788 IntrusiveRefCntPtr<ToolProperties>
789 ToolProps(new ToolProperties(T->getName()));
791 std::for_each(PropList->begin(), PropList->end(),
792 CollectProperties(*ToolProps, OptDescs));
793 TPList.push_back(ToolProps);
798 /// CollectPropertiesFromOptionLists - Gather information about
799 /// *global* option properties from all OptionLists.
800 void CollectPropertiesFromOptionLists (RecordVector::const_iterator B,
801 RecordVector::const_iterator E,
802 GlobalOptionDescriptions& OptDescs)
804 // Iterate over a properties list of every Tool definition
806 RecordVector::value_type T = *B;
807 // Throws an exception if the value does not exist.
808 ListInit* PropList = T->getValueAsListInit("options");
810 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
814 /// CheckForSuperfluousOptions - Check that there are no side
815 /// effect-free options (specified only in the OptionList). Otherwise,
816 /// output a warning.
817 void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
818 const GlobalOptionDescriptions& OptDescs) {
819 llvm::StringSet<> nonSuperfluousOptions;
821 // Add all options mentioned in the TPList to the set of
822 // non-superfluous options.
823 for (ToolPropertiesList::const_iterator B = TPList.begin(),
824 E = TPList.end(); B != E; ++B) {
825 const ToolProperties& TP = *(*B);
826 for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
827 E = TP.OptDescs.end(); B != E; ++B) {
828 nonSuperfluousOptions.insert(B->first());
832 // Check that all options in OptDescs belong to the set of
833 // non-superfluous options.
834 for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
835 E = OptDescs.end(); B != E; ++B) {
836 const GlobalOptionDescription& Val = B->second;
837 if (!nonSuperfluousOptions.count(Val.Name)
838 && Val.Type != OptionType::Alias)
839 llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
840 "Probable cause: this option is specified only in the OptionList.\n";
844 /// EmitCaseTest1Arg - Helper function used by
845 /// EmitCaseConstructHandler.
846 bool EmitCaseTest1Arg(const std::string& TestName,
848 const GlobalOptionDescriptions& OptDescs,
850 checkNumberOfArguments(&d, 1);
851 const std::string& OptName = InitPtrToString(d.getArg(0));
852 if (TestName == "switch_on") {
853 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
854 if (OptDesc.Type != OptionType::Switch)
855 throw OptName + ": incorrect option type!";
856 O << OptDesc.GenVariableName();
858 } else if (TestName == "input_languages_contain") {
859 O << "InLangs.count(\"" << OptName << "\") != 0";
861 } else if (TestName == "in_language") {
862 // This works only for single-argument Tool::GenerateAction. Join
863 // tools can process several files in different languages simultaneously.
865 // TODO: make this work with Edge::Weight (if possible).
866 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
868 } else if (TestName == "not_empty") {
869 if (OptName == "o") {
870 O << "!OutputFilename.empty()";
874 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
875 if (OptDesc.Type == OptionType::Switch)
876 throw OptName + ": incorrect option type!";
877 O << '!' << OptDesc.GenVariableName() << ".empty()";
885 /// EmitCaseTest2Args - Helper function used by
886 /// EmitCaseConstructHandler.
887 bool EmitCaseTest2Args(const std::string& TestName,
889 const char* IndentLevel,
890 const GlobalOptionDescriptions& OptDescs,
892 checkNumberOfArguments(&d, 2);
893 const std::string& OptName = InitPtrToString(d.getArg(0));
894 const std::string& OptArg = InitPtrToString(d.getArg(1));
895 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
897 if (TestName == "parameter_equals") {
898 if (OptDesc.Type != OptionType::Parameter
899 && OptDesc.Type != OptionType::Prefix)
900 throw OptName + ": incorrect option type!";
901 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
904 else if (TestName == "element_in_list") {
905 if (OptDesc.Type != OptionType::ParameterList
906 && OptDesc.Type != OptionType::PrefixList)
907 throw OptName + ": incorrect option type!";
908 const std::string& VarName = OptDesc.GenVariableName();
909 O << "std::find(" << VarName << ".begin(),\n"
910 << IndentLevel << Indent1 << VarName << ".end(), \""
911 << OptArg << "\") != " << VarName << ".end()";
918 // Forward declaration.
919 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
920 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
921 const GlobalOptionDescriptions& OptDescs,
924 /// EmitLogicalOperationTest - Helper function used by
925 /// EmitCaseConstructHandler.
926 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
927 const char* IndentLevel,
928 const GlobalOptionDescriptions& OptDescs,
931 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
932 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
933 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
934 if (j != NumArgs - 1)
935 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
941 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
942 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
943 const GlobalOptionDescriptions& OptDescs,
945 const std::string& TestName = d.getOperator()->getAsString();
947 if (TestName == "and")
948 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
949 else if (TestName == "or")
950 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
951 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
953 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
956 throw TestName + ": unknown edge property!";
959 // Emit code that handles the 'case' construct.
960 // Takes a function object that should emit code for every case clause.
961 // Callback's type is
962 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
963 template <typename F>
964 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
965 F Callback, bool EmitElseIf,
966 const GlobalOptionDescriptions& OptDescs,
968 assert(d->getOperator()->getAsString() == "case");
970 unsigned numArgs = d->getNumArgs();
971 if (d->getNumArgs() < 2)
972 throw "There should be at least one clause in the 'case' expression:\n"
975 for (unsigned i = 0; i != numArgs; ++i) {
976 const DagInit& Test = InitPtrToDag(d->getArg(i));
979 if (Test.getOperator()->getAsString() == "default") {
981 throw std::string("The 'default' clause should be the last in the"
982 "'case' construct!");
983 O << IndentLevel << "else {\n";
986 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
987 EmitCaseTest(Test, IndentLevel, OptDescs, O);
991 // Emit the corresponding statement.
994 throw "Case construct handler: no corresponding action "
995 "found for the test " + Test.getAsString() + '!';
997 Init* arg = d->getArg(i);
998 if (dynamic_cast<DagInit*>(arg)
999 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
1000 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
1001 (std::string(IndentLevel) + Indent1).c_str(),
1002 Callback, EmitElseIf, OptDescs, O);
1005 Callback(arg, IndentLevel, O);
1007 O << IndentLevel << "}\n";
1011 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1012 /// implement EmitOptionPropertyHandlingCode(). Emits code for
1013 /// handling the (forward) and (forward_as) option properties.
1014 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
1015 const std::string& NewName,
1017 const std::string& Name = NewName.empty()
1022 case OptionType::Switch:
1023 O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
1025 case OptionType::Parameter:
1026 O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
1027 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
1029 case OptionType::Prefix:
1030 O << Indent3 << "vec.push_back(\"" << Name << "\" + "
1031 << D.GenVariableName() << ");\n";
1033 case OptionType::PrefixList:
1034 O << Indent3 << "for (" << D.GenTypeDeclaration()
1035 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1036 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1037 << Indent4 << "vec.push_back(\"" << Name << "\" + "
1040 case OptionType::ParameterList:
1041 O << Indent3 << "for (" << D.GenTypeDeclaration()
1042 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1043 << Indent3 << "E = " << D.GenVariableName()
1044 << ".end() ; B != E; ++B) {\n"
1045 << Indent4 << "vec.push_back(\"" << Name << "\");\n"
1046 << Indent4 << "vec.push_back(*B);\n"
1047 << Indent3 << "}\n";
1049 case OptionType::Alias:
1051 throw std::string("Aliases are not allowed in tool option descriptions!");
1055 // ToolOptionHasInterestingProperties - A helper function used by
1056 // EmitOptionPropertyHandlingCode() that tells us whether we should
1057 // emit any property handling code at all.
1058 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
1060 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1061 E = D.Props.end(); B != E; ++B) {
1062 const OptionProperty& OptProp = *B;
1063 if (OptProp.first == OptionPropertyType::AppendCmd
1064 || OptProp.first == OptionPropertyType::ForwardAs)
1067 if (D.isForward() || D.isUnpackValues())
1072 /// EmitOptionPropertyHandlingCode - Helper function used by
1073 /// EmitGenerateActionMethod(). Emits code that handles option
1075 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
1078 if (!ToolOptionHasInterestingProperties(D))
1080 // Start of the if-clause.
1081 O << Indent2 << "if (";
1082 if (D.Type == OptionType::Switch)
1083 O << D.GenVariableName();
1085 O << '!' << D.GenVariableName() << ".empty()";
1089 // Handle option properties that take an argument.
1090 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1091 E = D.Props.end(); B!=E; ++B) {
1092 const OptionProperty& val = *B;
1094 switch (val.first) {
1095 // (append_cmd cmd) property
1096 case OptionPropertyType::AppendCmd:
1097 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1099 // (forward_as) property
1100 case OptionPropertyType::ForwardAs:
1101 EmitForwardOptionPropertyHandlingCode(D, val.second, O);
1103 // Other properties with argument
1111 // (forward) property
1113 EmitForwardOptionPropertyHandlingCode(D, "", O);
1115 // (unpack_values) property
1116 if (D.isUnpackValues()) {
1117 if (IsListOptionType(D.Type)) {
1118 O << Indent3 << "for (" << D.GenTypeDeclaration()
1119 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1120 << Indent3 << "E = " << D.GenVariableName()
1121 << ".end(); B != E; ++B)\n"
1122 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
1124 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
1125 O << Indent3 << "llvm::SplitString("
1126 << D.GenVariableName() << ", vec, \",\");\n";
1129 throw std::string("Switches can't have unpack_values property!");
1133 // End of the if-clause.
1134 O << Indent2 << "}\n";
1137 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1138 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1139 std::string SubstituteSpecialCommands(const std::string& cmd) {
1140 size_t cparen = cmd.find(")");
1143 if (cmd.find("$CALL(") == 0) {
1144 if (cmd.size() == 6)
1145 throw std::string("$CALL invocation: empty argument list!");
1148 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1151 else if (cmd.find("$ENV(") == 0) {
1152 if (cmd.size() == 5)
1153 throw std::string("$ENV invocation: empty argument list!");
1155 ret += "checkCString(std::getenv(\"";
1156 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1160 throw "Unknown special command: " + cmd;
1163 if (cmd.begin() + cparen + 1 != cmd.end()) {
1164 ret += " + std::string(\"";
1165 ret += (cmd.c_str() + cparen + 1);
1172 /// EmitCmdLineVecFill - Emit code that fills in the command line
1173 /// vector. Helper function used by EmitGenerateActionMethod().
1174 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1175 bool Version, const char* IndentLevel,
1178 SplitString(InitPtrToString(CmdLine), StrVec);
1180 throw "Tool " + ToolName + " has empty command line!";
1182 StrVector::const_iterator I = StrVec.begin();
1184 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1185 const std::string& cmd = *I;
1187 if (cmd.at(0) == '$') {
1188 if (cmd == "$INFILE") {
1190 O << "for (PathVector::const_iterator B = inFiles.begin()"
1191 << ", E = inFiles.end();\n"
1192 << IndentLevel << "B != E; ++B)\n"
1193 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1195 O << "vec.push_back(inFile.toString());\n";
1197 else if (cmd == "$OUTFILE") {
1198 O << "vec.push_back(outFile.toString());\n";
1201 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1206 O << "vec.push_back(\"" << cmd << "\");\n";
1209 O << IndentLevel << "cmd = "
1210 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1211 : "\"" + StrVec[0] + "\"")
1215 /// EmitCmdLineVecFillCallback - A function object wrapper around
1216 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1217 /// argument to EmitCaseConstructHandler().
1218 class EmitCmdLineVecFillCallback {
1220 const std::string& ToolName;
1222 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1223 : Version(Ver), ToolName(TN) {}
1225 void operator()(const Init* Statement, const char* IndentLevel,
1226 std::ostream& O) const
1228 EmitCmdLineVecFill(Statement, ToolName, Version,
1229 (std::string(IndentLevel) + Indent1).c_str(), O);
1233 // EmitGenerateActionMethod - Emit one of two versions of the
1234 // Tool::GenerateAction() method.
1235 void EmitGenerateActionMethod (const ToolProperties& P,
1236 const GlobalOptionDescriptions& OptDescs,
1237 bool Version, std::ostream& O) {
1239 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1241 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1243 O << Indent2 << "const sys::Path& outFile,\n"
1244 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1245 << Indent2 << "const LanguageMap& LangMap) const\n"
1247 << Indent2 << "std::string cmd;\n"
1248 << Indent2 << "std::vector<std::string> vec;\n";
1250 // cmd_line is either a string or a 'case' construct.
1251 if (typeid(*P.CmdLine) == typeid(StringInit))
1252 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1254 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1255 EmitCmdLineVecFillCallback(Version, P.Name),
1258 // For every understood option, emit handling code.
1259 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1260 E = P.OptDescs.end(); B != E; ++B) {
1261 const ToolOptionDescription& val = B->second;
1262 EmitOptionPropertyHandlingCode(val, O);
1265 // Handle the Sink property.
1267 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1268 << Indent3 << "vec.insert(vec.end(), "
1269 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1270 << Indent2 << "}\n";
1273 O << Indent2 << "return Action(cmd, vec);\n"
1274 << Indent1 << "}\n\n";
1277 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1278 /// a given Tool class.
1279 void EmitGenerateActionMethods (const ToolProperties& P,
1280 const GlobalOptionDescriptions& OptDescs,
1283 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1284 << Indent2 << "const llvm::sys::Path& outFile,\n"
1285 << Indent2 << "const InputLanguagesSet& InLangs,\n"
1286 << Indent2 << "const LanguageMap& LangMap) const\n"
1288 << Indent2 << "throw std::runtime_error(\"" << P.Name
1289 << " is not a Join tool!\");\n"
1290 << Indent1 << "}\n\n";
1292 EmitGenerateActionMethod(P, OptDescs, true, O);
1294 EmitGenerateActionMethod(P, OptDescs, false, O);
1297 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1299 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1300 O << Indent1 << "bool IsLast() const {\n"
1301 << Indent2 << "bool last = false;\n";
1303 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1304 E = P.OptDescs.end(); B != E; ++B) {
1305 const ToolOptionDescription& val = B->second;
1307 if (val.isStopCompilation())
1309 << "if (" << val.GenVariableName()
1310 << ")\n" << Indent3 << "last = true;\n";
1313 O << Indent2 << "return last;\n"
1314 << Indent1 << "}\n\n";
1317 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1318 /// methods for a given Tool class.
1319 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1320 O << Indent1 << "const char** InputLanguages() const {\n"
1321 << Indent2 << "return InputLanguages_;\n"
1322 << Indent1 << "}\n\n";
1324 O << Indent1 << "const char* OutputLanguage() const {\n"
1325 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1326 << Indent1 << "}\n\n";
1329 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1330 /// given Tool class.
1331 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1332 O << Indent1 << "const char* OutputSuffix() const {\n"
1333 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1335 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1336 E = P.OptDescs.end(); B != E; ++B) {
1337 const ToolOptionDescription& OptDesc = B->second;
1338 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1339 E = OptDesc.Props.end(); B != E; ++B) {
1340 const OptionProperty& OptProp = *B;
1341 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1342 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1343 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1348 O << Indent2 << "return ret;\n"
1349 << Indent1 << "}\n\n";
1352 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1353 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1354 O << Indent1 << "const char* Name() const {\n"
1355 << Indent2 << "return \"" << P.Name << "\";\n"
1356 << Indent1 << "}\n\n";
1359 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1361 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1362 O << Indent1 << "bool IsJoin() const {\n";
1364 O << Indent2 << "return true;\n";
1366 O << Indent2 << "return false;\n";
1367 O << Indent1 << "}\n\n";
1370 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1371 /// given Tool class.
1372 void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1373 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1374 for (StrVector::const_iterator B = P.InLanguage.begin(),
1375 E = P.InLanguage.end(); B != E; ++B)
1376 O << '\"' << *B << "\", ";
1380 /// EmitToolClassDefinition - Emit a Tool class definition.
1381 void EmitToolClassDefinition (const ToolProperties& P,
1382 const GlobalOptionDescriptions& OptDescs,
1384 if (P.Name == "root")
1388 O << "class " << P.Name << " : public ";
1394 O << "{\nprivate:\n"
1395 << Indent1 << "static const char* InputLanguages_[];\n\n";
1398 EmitNameMethod(P, O);
1399 EmitInOutLanguageMethods(P, O);
1400 EmitOutputSuffixMethod(P, O);
1401 EmitIsJoinMethod(P, O);
1402 EmitGenerateActionMethods(P, OptDescs, O);
1403 EmitIsLastMethod(P, O);
1405 // Close class definition
1408 EmitStaticMemberDefinitions(P, O);
1412 /// EmitOptionDescriptions - Iterate over a list of option
1413 /// descriptions and emit registration code.
1414 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1417 std::vector<GlobalOptionDescription> Aliases;
1419 // Emit static cl::Option variables.
1420 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1421 E = descs.end(); B!=E; ++B) {
1422 const GlobalOptionDescription& val = B->second;
1424 if (val.Type == OptionType::Alias) {
1425 Aliases.push_back(val);
1429 O << val.GenTypeDeclaration() << ' '
1430 << val.GenVariableName()
1431 << "(\"" << val.Name << '\"';
1433 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1434 O << ", cl::Prefix";
1436 if (val.isRequired()) {
1438 case OptionType::PrefixList:
1439 case OptionType::ParameterList:
1440 O << ", cl::OneOrMore";
1443 O << ", cl::Required";
1447 if (val.isReallyHidden() || val.isHidden()) {
1448 if (val.isRequired())
1452 if (val.isReallyHidden())
1453 O << " cl::ReallyHidden";
1458 if (!val.Help.empty())
1459 O << ", cl::desc(\"" << val.Help << "\")";
1464 // Emit the aliases (they should go after all the 'proper' options).
1465 for (std::vector<GlobalOptionDescription>::const_iterator
1466 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1467 const GlobalOptionDescription& val = *B;
1469 O << val.GenTypeDeclaration() << ' '
1470 << val.GenVariableName()
1471 << "(\"" << val.Name << '\"';
1473 GlobalOptionDescriptions::container_type
1474 ::const_iterator F = descs.Descriptions.find(val.Help);
1475 if (F != descs.Descriptions.end())
1476 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1478 throw val.Name + ": alias to an unknown option!";
1480 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1483 // Emit the sink option.
1485 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1490 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1491 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1494 O << "namespace {\n\n";
1495 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1497 // Get the relevant field out of RecordKeeper
1498 const Record* LangMapRecord = Records.getDef("LanguageMap");
1500 // It is allowed for a plugin to have no language map.
1501 if (LangMapRecord) {
1503 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1504 if (!LangsToSuffixesList)
1505 throw std::string("Error in the language map definition!");
1507 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1508 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1510 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1511 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1513 for (unsigned i = 0; i < Suffixes->size(); ++i)
1514 O << Indent1 << "langMap[\""
1515 << InitPtrToString(Suffixes->getElement(i))
1516 << "\"] = \"" << Lang << "\";\n";
1523 /// FillInToolToLang - Fills in two tables that map tool names to
1524 /// (input, output) languages. Used by the typechecker.
1525 void FillInToolToLang (const ToolPropertiesList& TPList,
1526 StringMap<StringSet<> >& ToolToInLang,
1527 StringMap<std::string>& ToolToOutLang) {
1528 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1530 const ToolProperties& P = *(*B);
1531 for (StrVector::const_iterator B = P.InLanguage.begin(),
1532 E = P.InLanguage.end(); B != E; ++B)
1533 ToolToInLang[P.Name].insert(*B);
1534 ToolToOutLang[P.Name] = P.OutLanguage;
1538 /// TypecheckGraph - Check that names for output and input languages
1539 /// on all edges do match. This doesn't do much when the information
1540 /// about the whole graph is not available (i.e. when compiling most
1542 void TypecheckGraph (const RecordVector& EdgeVector,
1543 const ToolPropertiesList& TPList) {
1544 StringMap<StringSet<> > ToolToInLang;
1545 StringMap<std::string> ToolToOutLang;
1547 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1548 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1549 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1551 for (RecordVector::const_iterator B = EdgeVector.begin(),
1552 E = EdgeVector.end(); B != E; ++B) {
1553 const Record* Edge = *B;
1554 const std::string& A = Edge->getValueAsString("a");
1555 const std::string& B = Edge->getValueAsString("b");
1556 StringMap<std::string>::iterator IA = ToolToOutLang.find(A);
1557 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B);
1560 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1561 throw "Edge " + A + "->" + B
1562 + ": output->input language mismatch";
1566 throw std::string("Edges back to the root are not allowed!");
1570 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1571 /// by EmitEdgeClass().
1572 void IncDecWeight (const Init* i, const char* IndentLevel,
1574 const DagInit& d = InitPtrToDag(i);
1575 const std::string& OpName = d.getOperator()->getAsString();
1577 if (OpName == "inc_weight")
1578 O << IndentLevel << Indent1 << "ret += ";
1579 else if (OpName == "dec_weight")
1580 O << IndentLevel << Indent1 << "ret -= ";
1582 throw "Unknown operator in edge properties list: " + OpName + '!';
1584 if (d.getNumArgs() > 0)
1585 O << InitPtrToInt(d.getArg(0)) << ";\n";
1591 /// EmitEdgeClass - Emit a single Edge# class.
1592 void EmitEdgeClass (unsigned N, const std::string& Target,
1593 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1596 // Class constructor.
1597 O << "class Edge" << N << ": public Edge {\n"
1599 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1602 // Function Weight().
1603 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1604 << Indent2 << "unsigned ret = 0;\n";
1606 // Handle the 'case' construct.
1607 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1609 O << Indent2 << "return ret;\n"
1610 << Indent1 << "};\n\n};\n\n";
1613 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1614 void EmitEdgeClasses (const RecordVector& EdgeVector,
1615 const GlobalOptionDescriptions& OptDescs,
1618 for (RecordVector::const_iterator B = EdgeVector.begin(),
1619 E = EdgeVector.end(); B != E; ++B) {
1620 const Record* Edge = *B;
1621 const std::string& B = Edge->getValueAsString("b");
1622 DagInit* Weight = Edge->getValueAsDag("weight");
1624 if (!isDagEmpty(Weight))
1625 EmitEdgeClass(i, B, Weight, OptDescs, O);
1630 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1632 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1633 const ToolPropertiesList& ToolProps,
1636 O << "namespace {\n\n";
1637 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1639 for (ToolPropertiesList::const_iterator B = ToolProps.begin(),
1640 E = ToolProps.end(); B != E; ++B)
1641 O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
1648 for (RecordVector::const_iterator B = EdgeVector.begin(),
1649 E = EdgeVector.end(); B != E; ++B) {
1650 const Record* Edge = *B;
1651 const std::string& A = Edge->getValueAsString("a");
1652 const std::string& B = Edge->getValueAsString("b");
1653 DagInit* Weight = Edge->getValueAsDag("weight");
1655 O << Indent1 << "G.insertEdge(\"" << A << "\", ";
1657 if (isDagEmpty(Weight))
1658 O << "new SimpleEdge(\"" << B << "\")";
1660 O << "new Edge" << i << "()";
1669 /// ExtractHookNames - Extract the hook names from all instances of
1670 /// $CALL(HookName) in the provided command line string. Helper
1671 /// function used by FillInHookNames().
1672 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1674 llvm::SplitString(InitPtrToString(CmdLine), cmds);
1675 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1677 const std::string& cmd = *B;
1678 if (cmd.find("$CALL(") == 0) {
1679 if (cmd.size() == 6)
1680 throw std::string("$CALL invocation: empty argument list!");
1681 HookNames.push_back(std::string(cmd.begin() + 6,
1682 cmd.begin() + cmd.find(")")));
1687 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1688 /// 'case' expression, handle nesting. Helper function used by
1689 /// FillInHookNames().
1690 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1691 const DagInit& d = InitPtrToDag(Case);
1693 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1696 if (even && dynamic_cast<DagInit*>(arg)
1697 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1698 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1700 ExtractHookNames(arg, HookNames);
1705 /// FillInHookNames - Actually extract the hook names from all command
1706 /// line strings. Helper function used by EmitHookDeclarations().
1707 void FillInHookNames(const ToolPropertiesList& TPList,
1708 StrVector& HookNames) {
1709 // For all command lines:
1710 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1711 E = TPList.end(); B != E; ++B) {
1712 const ToolProperties& P = *(*B);
1715 if (dynamic_cast<StringInit*>(P.CmdLine))
1716 // This is a string.
1717 ExtractHookNames(P.CmdLine, HookNames);
1719 // This is a 'case' construct.
1720 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1724 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1725 /// property records and emit hook function declaration for each
1726 /// instance of $CALL(HookName).
1727 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1729 StrVector HookNames;
1730 FillInHookNames(ToolProps, HookNames);
1731 if (HookNames.empty())
1733 std::sort(HookNames.begin(), HookNames.end());
1734 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1736 O << "namespace hooks {\n";
1737 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1738 O << Indent1 << "std::string " << *B << "();\n";
1743 /// EmitRegisterPlugin - Emit code to register this plugin.
1744 void EmitRegisterPlugin(int Priority, std::ostream& O) {
1745 O << "namespace {\n\n"
1746 << "struct Plugin : public llvmc::BasePlugin {\n\n"
1747 << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
1748 << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
1749 << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
1751 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
1752 << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
1755 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n}\n\n";
1758 /// EmitIncludes - Emit necessary #include directives and some
1759 /// additional declarations.
1760 void EmitIncludes(std::ostream& O) {
1761 O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
1762 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
1763 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
1765 << "#include \"llvm/ADT/StringExtras.h\"\n"
1766 << "#include \"llvm/Support/CommandLine.h\"\n\n"
1768 << "#include <cstdlib>\n"
1769 << "#include <stdexcept>\n\n"
1771 << "using namespace llvm;\n"
1772 << "using namespace llvmc;\n\n"
1774 << "extern cl::opt<std::string> OutputFilename;\n\n"
1776 << "inline const char* checkCString(const char* s)\n"
1777 << "{ return s == NULL ? \"\" : s; }\n\n";
1780 /// NotInGraph - Helper function object for FilterNotInGraph.
1783 const llvm::StringSet<>& ToolsInGraph_;
1786 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
1787 : ToolsInGraph_(ToolsInGraph)
1790 bool operator()(const IntrusiveRefCntPtr<ToolProperties>& x) {
1791 return (ToolsInGraph_.count(x->Name) == 0);
1795 /// FilterNotInGraph - Filter out from ToolProps all Tools not
1796 /// mentioned in the compilation graph definition.
1797 void FilterNotInGraph (const RecordVector& EdgeVector,
1798 ToolPropertiesList& ToolProps) {
1800 // List all tools mentioned in the graph.
1801 llvm::StringSet<> ToolsInGraph;
1803 for (RecordVector::const_iterator B = EdgeVector.begin(),
1804 E = EdgeVector.end(); B != E; ++B) {
1806 const Record* Edge = *B;
1807 const std::string& A = Edge->getValueAsString("a");
1808 const std::string& B = Edge->getValueAsString("b");
1811 ToolsInGraph.insert(A);
1812 ToolsInGraph.insert(B);
1815 // Filter ToolPropertiesList.
1816 ToolPropertiesList::iterator new_end =
1817 std::remove_if(ToolProps.begin(), ToolProps.end(),
1818 NotInGraph(ToolsInGraph));
1819 ToolProps.erase(new_end, ToolProps.end());
1822 /// CalculatePriority - Calculate the priority of this plugin.
1823 int CalculatePriority(RecordVector::const_iterator B,
1824 RecordVector::const_iterator E) {
1827 total += static_cast<int>((*B)->getValueAsInt("priority"));
1832 /// FillInEdgeVector - Merge all compilation graph definitions into
1833 /// one single edge list.
1834 void FillInEdgeVector(RecordVector::const_iterator B,
1835 RecordVector::const_iterator E, RecordVector& Out) {
1836 for (; B != E; ++B) {
1837 const ListInit* edges = (*B)->getValueAsListInit("edges");
1839 for (unsigned i = 0; i < edges->size(); ++i)
1840 Out.push_back(edges->getElementAsRecord(i));
1844 // End of anonymous namespace
1847 /// run - The back-end entry point.
1848 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1851 // Emit file header.
1852 EmitSourceFileHeader("LLVMC Configuration Library", O);
1855 // Collect tool properties.
1856 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1857 ToolPropertiesList ToolProps;
1858 GlobalOptionDescriptions OptDescs;
1859 CollectToolProperties(Tools.begin(), Tools.end(), ToolProps, OptDescs);
1861 // Collect option properties.
1862 const RecordVector& OptionLists =
1863 Records.getAllDerivedDefinitions("OptionList");
1864 CollectPropertiesFromOptionLists(OptionLists.begin(), OptionLists.end(),
1867 // Collect compilation graph edges.
1868 const RecordVector& CompilationGraphs =
1869 Records.getAllDerivedDefinitions("CompilationGraph");
1870 RecordVector EdgeVector;
1871 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
1874 // Filter out all tools not mentioned in the compilation graph.
1875 FilterNotInGraph(EdgeVector, ToolProps);
1877 // Typecheck the compilation graph.
1878 TypecheckGraph(EdgeVector, ToolProps);
1880 // Check that there are no options without side effects (specified
1881 // only in the OptionList).
1882 CheckForSuperfluousOptions(ToolProps, OptDescs);
1884 // Emit global option registration code.
1885 EmitOptionDescriptions(OptDescs, O);
1887 // Emit hook declarations.
1888 EmitHookDeclarations(ToolProps, O);
1890 // Emit PopulateLanguageMap() function
1891 // (a language map maps from file extensions to language names).
1892 EmitPopulateLanguageMap(Records, O);
1894 // Emit Tool classes.
1895 for (ToolPropertiesList::const_iterator B = ToolProps.begin(),
1896 E = ToolProps.end(); B!=E; ++B)
1897 EmitToolClassDefinition(*(*B), OptDescs, O);
1899 // Emit Edge# classes.
1900 EmitEdgeClasses(EdgeVector, OptDescs, O);
1902 // Emit PopulateCompilationGraph() function.
1903 EmitPopulateCompilationGraph(EdgeVector, ToolProps, O);
1905 // Emit code for plugin registration.
1906 const RecordVector& Priorities =
1907 Records.getAllDerivedDefinitions("PluginPriority");
1908 EmitRegisterPlugin(CalculatePriority(Priorities.begin(),
1909 Priorities.end()), O);
1912 } catch (std::exception& Error) {
1913 throw Error.what() + std::string(" - usually this means a syntax error.");