#include <functional>
#include <stdexcept>
#include <string>
+#include <typeinfo>
using namespace llvm;
std::string EscapeVariableName(const std::string& Var) const {
std::string ret;
for (unsigned i = 0; i != Var.size(); ++i) {
- if (Var[i] == ',') {
+ char cur_char = Var[i];
+ if (cur_char == ',') {
ret += "_comma_";
}
+ else if (cur_char == '+') {
+ ret += "_plus_";
+ }
+ else if (cur_char == '-') {
+ ret += "_dash_";
+ }
else {
- ret.push_back(Var[i]);
+ ret.push_back(cur_char);
}
}
return ret;
// Global option description.
namespace GlobalOptionDescriptionFlags {
- enum GlobalOptionDescriptionFlags { Required = 0x1 };
+ enum GlobalOptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
+ ReallyHidden = 0x4 };
}
struct GlobalOptionDescription : public OptionDescription {
Flags |= GlobalOptionDescriptionFlags::Required;
}
+ bool isHidden() const {
+ return Flags & GlobalOptionDescriptionFlags::Hidden;
+ }
+ void setHidden() {
+ Flags |= GlobalOptionDescriptionFlags::Hidden;
+ }
+
+ bool isReallyHidden() const {
+ return Flags & GlobalOptionDescriptionFlags::ReallyHidden;
+ }
+ void setReallyHidden() {
+ Flags |= GlobalOptionDescriptionFlags::ReallyHidden;
+ }
+
/// Merge - Merge two option descriptions.
void Merge (const GlobalOptionDescription& other)
{
if (other.Type != Type)
throw "Conflicting definitions for the option " + Name + "!";
- if (Help == DefaultHelpString)
+ if (Help == other.Help || Help == DefaultHelpString)
Help = other.Help;
else if (other.Help != DefaultHelpString) {
- llvm::cerr << "Warning: more than one help string defined for option "
- + Name + "\n";
+ llvm::cerr << "Warning: several different help strings"
+ " defined for option " + Name + "\n";
}
Flags |= other.Flags;
/// HasSink - Should the emitter generate a "cl::sink" option?
bool HasSink;
+ /// FindOption - exception-throwing wrapper for find().
const GlobalOptionDescription& FindOption(const std::string& OptName) const {
const_iterator I = Descriptions.find(OptName);
if (I != Descriptions.end())
throw OptName + ": no such option!";
}
+ /// insertDescription - Insert new GlobalOptionDescription into
+ /// GlobalOptionDescriptions list
+ void insertDescription (const GlobalOptionDescription& o)
+ {
+ container_type::iterator I = Descriptions.find(o.Name);
+ if (I != Descriptions.end()) {
+ GlobalOptionDescription& D = I->second;
+ D.Merge(o);
+ }
+ else {
+ Descriptions[o.Name] = o;
+ }
+ }
+
// Support for STL-style iteration
const_iterator begin() const { return Descriptions.begin(); }
const_iterator end() const { return Descriptions.end(); }
Forward = 0x2, UnpackValues = 0x4};
}
namespace OptionPropertyType {
- enum OptionPropertyType { AppendCmd, OutputSuffix };
+ enum OptionPropertyType { AppendCmd, ForwardAs, OutputSuffix };
}
typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
// Default ctor here is needed because StringMap can only store
// DefaultConstructible objects
- ToolProperties() : Flags(0) {}
- ToolProperties (const std::string& n) : Name(n), Flags(0) {}
+ ToolProperties() : CmdLine(0), Flags(0) {}
+ ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
};
typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
+/// CollectOptionProperties - Function object for iterating over a
+/// list (usually, a DAG) of option property records.
+class CollectOptionProperties {
+private:
+ // Implementation details.
+
+ /// OptionPropertyHandler - a function that extracts information
+ /// about a given option property from its DAG representation.
+ typedef void (CollectOptionProperties::* OptionPropertyHandler)
+ (const DagInit*);
+
+ /// OptionPropertyHandlerMap - A map from option property names to
+ /// option property handlers
+ typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
+
+ static OptionPropertyHandlerMap optionPropertyHandlers_;
+ static bool staticMembersInitialized_;
+
+ /// This is where the information is stored
+
+ /// toolProps_ - Properties of the current Tool.
+ ToolProperties* toolProps_;
+ /// optDescs_ - OptionDescriptions table (used to register options
+ /// globally).
+ GlobalOptionDescription& optDesc_;
+
+public:
+
+ explicit CollectOptionProperties(ToolProperties* TP,
+ GlobalOptionDescription& OD)
+ : toolProps_(TP), optDesc_(OD)
+ {
+ if (!staticMembersInitialized_) {
+ optionPropertyHandlers_["append_cmd"] =
+ &CollectOptionProperties::onAppendCmd;
+ optionPropertyHandlers_["forward"] =
+ &CollectOptionProperties::onForward;
+ optionPropertyHandlers_["forward_as"] =
+ &CollectOptionProperties::onForwardAs;
+ optionPropertyHandlers_["help"] =
+ &CollectOptionProperties::onHelp;
+ optionPropertyHandlers_["hidden"] =
+ &CollectOptionProperties::onHidden;
+ optionPropertyHandlers_["output_suffix"] =
+ &CollectOptionProperties::onOutputSuffix;
+ optionPropertyHandlers_["really_hidden"] =
+ &CollectOptionProperties::onReallyHidden;
+ optionPropertyHandlers_["required"] =
+ &CollectOptionProperties::onRequired;
+ optionPropertyHandlers_["stop_compilation"] =
+ &CollectOptionProperties::onStopCompilation;
+ optionPropertyHandlers_["unpack_values"] =
+ &CollectOptionProperties::onUnpackValues;
+
+ staticMembersInitialized_ = true;
+ }
+ }
+
+ /// operator() - Gets called for every option property; Just forwards
+ /// to the corresponding property handler.
+ void operator() (Init* i) {
+ const DagInit& option_property = InitPtrToDag(i);
+ const std::string& option_property_name
+ = option_property.getOperator()->getAsString();
+ OptionPropertyHandlerMap::iterator method
+ = optionPropertyHandlers_.find(option_property_name);
+
+ if (method != optionPropertyHandlers_.end()) {
+ OptionPropertyHandler h = method->second;
+ (this->*h)(&option_property);
+ }
+ else {
+ throw "Unknown option property: " + option_property_name + "!";
+ }
+ }
+
+private:
+
+ /// Option property handlers --
+ /// Methods that handle properties that are common for all types of
+ /// options (like append_cmd, stop_compilation)
+
+ void onAppendCmd (const DagInit* d) {
+ checkNumberOfArguments(d, 1);
+ checkToolProps(d);
+ const std::string& cmd = InitPtrToString(d->getArg(0));
+
+ toolProps_->OptDescs[optDesc_.Name].
+ AddProperty(OptionPropertyType::AppendCmd, cmd);
+ }
+
+ void onOutputSuffix (const DagInit* d) {
+ checkNumberOfArguments(d, 1);
+ checkToolProps(d);
+ const std::string& suf = InitPtrToString(d->getArg(0));
+
+ if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
+ throw "Option " + optDesc_.Name
+ + " can't have 'output_suffix' property since it isn't a switch!";
+
+ toolProps_->OptDescs[optDesc_.Name].AddProperty
+ (OptionPropertyType::OutputSuffix, suf);
+ }
+
+ void onForward (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ toolProps_->OptDescs[optDesc_.Name].setForward();
+ }
+
+ void onForwardAs (const DagInit* d) {
+ checkNumberOfArguments(d, 1);
+ checkToolProps(d);
+ const std::string& cmd = InitPtrToString(d->getArg(0));
+
+ toolProps_->OptDescs[optDesc_.Name].
+ AddProperty(OptionPropertyType::ForwardAs, cmd);
+ }
+
+ void onHelp (const DagInit* d) {
+ checkNumberOfArguments(d, 1);
+ const std::string& help_message = InitPtrToString(d->getArg(0));
+
+ optDesc_.Help = help_message;
+ }
+
+ void onHidden (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ optDesc_.setHidden();
+ }
+
+ void onReallyHidden (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ optDesc_.setReallyHidden();
+ }
+
+ void onRequired (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ optDesc_.setRequired();
+ }
+
+ void onStopCompilation (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ if (optDesc_.Type != OptionType::Switch)
+ throw std::string("Only options of type Switch can stop compilation!");
+ toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
+ }
+
+ void onUnpackValues (const DagInit* d) {
+ checkNumberOfArguments(d, 0);
+ checkToolProps(d);
+ toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
+ }
+
+ // Helper functions
+
+ /// checkToolProps - Throw an error if toolProps_ == 0.
+ void checkToolProps(const DagInit* d) {
+ if (!d)
+ throw "Option property " + d->getOperator()->getAsString()
+ + " can't be used in this context";
+ }
+
+};
+
+CollectOptionProperties::OptionPropertyHandlerMap
+CollectOptionProperties::optionPropertyHandlers_;
+
+bool CollectOptionProperties::staticMembersInitialized_ = false;
+
+
+/// processOptionProperties - Go through the list of option
+/// properties and call a corresponding handler for each.
+void processOptionProperties (const DagInit* d, ToolProperties* t,
+ GlobalOptionDescription& o) {
+ checkNumberOfArguments(d, 2);
+ DagInit::const_arg_iterator B = d->arg_begin();
+ // Skip the first argument: it's always the option name.
+ ++B;
+ std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
+}
+
+/// AddOption - A function object wrapper for
+/// processOptionProperties. Used by CollectProperties and
+/// CollectPropertiesFromOptionList.
+class AddOption {
+private:
+ GlobalOptionDescriptions& OptDescs_;
+ ToolProperties* ToolProps_;
+
+public:
+ explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
+ : OptDescs_(OD), ToolProps_(TP)
+ {}
+
+ void operator()(const Init* i) {
+ const DagInit& d = InitPtrToDag(i);
+ checkNumberOfArguments(&d, 2);
+
+ const OptionType::OptionType Type =
+ getOptionType(d.getOperator()->getAsString());
+ const std::string& Name = InitPtrToString(d.getArg(0));
+
+ GlobalOptionDescription OD(Type, Name);
+ if (Type != OptionType::Alias) {
+ processOptionProperties(&d, ToolProps_, OD);
+ if (ToolProps_) {
+ ToolProps_->OptDescs[Name].Type = Type;
+ ToolProps_->OptDescs[Name].Name = Name;
+ }
+ }
+ else {
+ OD.Help = InitPtrToString(d.getArg(1));
+ }
+ OptDescs_.insertDescription(OD);
+ }
+
+private:
+ OptionType::OptionType getOptionType(const std::string& T) const {
+ if (T == "alias_option")
+ return OptionType::Alias;
+ else if (T == "switch_option")
+ return OptionType::Switch;
+ else if (T == "parameter_option")
+ return OptionType::Parameter;
+ else if (T == "parameter_list_option")
+ return OptionType::ParameterList;
+ else if (T == "prefix_option")
+ return OptionType::Prefix;
+ else if (T == "prefix_list_option")
+ return OptionType::PrefixList;
+ else
+ throw "Unknown option type: " + T + '!';
+ }
+};
+
+
/// CollectProperties - Function object for iterating over a list of
/// tool property records.
class CollectProperties {
private:
- /// Implementation details
+ // Implementation details
/// PropertyHandler - a function that extracts information
/// about a given tool property from its DAG representation
/// handlers.
typedef StringMap<PropertyHandler> PropertyHandlerMap;
- /// OptionPropertyHandler - a function that extracts information
- /// about a given option property from its DAG representation.
- typedef void (CollectProperties::* OptionPropertyHandler)
- (const DagInit*, GlobalOptionDescription &);
-
- /// OptionPropertyHandlerMap - A map from option property names to
- /// option property handlers
- typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
-
// Static maps from strings to CollectProperties methods("handlers")
static PropertyHandlerMap propertyHandlers_;
- static OptionPropertyHandlerMap optionPropertyHandlers_;
static bool staticMembersInitialized_;
: toolProps_(p), optDescs_(d)
{
if (!staticMembersInitialized_) {
- // Init tool property handlers
propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
propertyHandlers_["join"] = &CollectProperties::onJoin;
propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
propertyHandlers_["parameter_option"]
- = &CollectProperties::onParameter;
+ = &CollectProperties::addOption;
propertyHandlers_["parameter_list_option"] =
- &CollectProperties::onParameterList;
- propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
+ &CollectProperties::addOption;
+ propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
propertyHandlers_["prefix_list_option"] =
- &CollectProperties::onPrefixList;
+ &CollectProperties::addOption;
propertyHandlers_["sink"] = &CollectProperties::onSink;
- propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
- propertyHandlers_["alias_option"] = &CollectProperties::onAlias;
-
- // Init option property handlers
- optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
- optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
- optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
- optionPropertyHandlers_["output_suffix"] =
- &CollectProperties::onOutputSuffixOptionProp;
- optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
- optionPropertyHandlers_["stop_compilation"] =
- &CollectProperties::onStopCompilation;
- optionPropertyHandlers_["unpack_values"] =
- &CollectProperties::onUnpackValues;
+ propertyHandlers_["switch_option"] = &CollectProperties::addOption;
+ propertyHandlers_["alias_option"] = &CollectProperties::addOption;
staticMembersInitialized_ = true;
}
toolProps_.setSink();
}
- void onAlias (const DagInit* d) {
- checkNumberOfArguments(d, 2);
- // We just need a GlobalOptionDescription for the aliases.
- insertDescription
- (GlobalOptionDescription(OptionType::Alias,
- InitPtrToString(d->getArg(0)),
- InitPtrToString(d->getArg(1))));
- }
-
- void onSwitch (const DagInit* d) {
- addOption(d, OptionType::Switch);
- }
-
- void onParameter (const DagInit* d) {
- addOption(d, OptionType::Parameter);
- }
-
- void onParameterList (const DagInit* d) {
- addOption(d, OptionType::ParameterList);
- }
-
- void onPrefix (const DagInit* d) {
- addOption(d, OptionType::Prefix);
- }
-
- void onPrefixList (const DagInit* d) {
- addOption(d, OptionType::PrefixList);
- }
-
- /// Option property handlers --
- /// Methods that handle properties that are common for all types of
- /// options (like append_cmd, stop_compilation)
-
- void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 1);
- const std::string& cmd = InitPtrToString(d->getArg(0));
-
- toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
- }
-
- void onOutputSuffixOptionProp (const DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 1);
- const std::string& suf = InitPtrToString(d->getArg(0));
-
- if (toolProps_.OptDescs[o.Name].Type != OptionType::Switch)
- throw "Option " + o.Name
- + " can't have 'output_suffix' property since it isn't a switch!";
-
- toolProps_.OptDescs[o.Name].AddProperty
- (OptionPropertyType::OutputSuffix, suf);
- }
-
- void onForward (const DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 0);
- toolProps_.OptDescs[o.Name].setForward();
- }
-
- void onHelp (const DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 1);
- const std::string& help_message = InitPtrToString(d->getArg(0));
-
- o.Help = help_message;
- }
-
- void onRequired (const DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 0);
- o.setRequired();
- }
-
- void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 0);
- if (o.Type != OptionType::Switch)
- throw std::string("Only options of type Switch can stop compilation!");
- toolProps_.OptDescs[o.Name].setStopCompilation();
- }
-
- void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
- checkNumberOfArguments(d, 0);
- toolProps_.OptDescs[o.Name].setUnpackValues();
- }
-
- /// Helper functions
-
- // Add an option of type t
- void addOption (const DagInit* d, OptionType::OptionType t) {
+ // Just forwards to the AddOption function object. Somewhat
+ // non-optimal, but avoids code duplication.
+ void addOption (const DagInit* d) {
checkNumberOfArguments(d, 2);
- const std::string& name = InitPtrToString(d->getArg(0));
-
- GlobalOptionDescription o(t, name);
- toolProps_.OptDescs[name].Type = t;
- toolProps_.OptDescs[name].Name = name;
- processOptionProperties(d, o);
- insertDescription(o);
- }
-
- // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
- void insertDescription (const GlobalOptionDescription& o)
- {
- if (optDescs_.Descriptions.count(o.Name)) {
- GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
- D.Merge(o);
- }
- else {
- optDescs_.Descriptions[o.Name] = o;
- }
+ AddOption(optDescs_, &toolProps_)(d);
}
- /// processOptionProperties - Go through the list of option
- /// properties and call a corresponding handler for each.
- ///
- /// Parameters:
- /// name - option name
- /// d - option property list
- void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
- // First argument is option name
- checkNumberOfArguments(d, 2);
-
- for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
- const DagInit& option_property
- = InitPtrToDag(d->getArg(B));
- const std::string& option_property_name
- = option_property.getOperator()->getAsString();
- OptionPropertyHandlerMap::iterator method
- = optionPropertyHandlers_.find(option_property_name);
-
- if (method != optionPropertyHandlers_.end()) {
- OptionPropertyHandler h = method->second;
- (this->*h)(&option_property, o);
- }
- else {
- throw "Unknown option property: " + option_property_name + "!";
- }
- }
- }
};
-// Static members of CollectProperties
-CollectProperties::PropertyHandlerMap
-CollectProperties::propertyHandlers_;
-
-CollectProperties::OptionPropertyHandlerMap
-CollectProperties::optionPropertyHandlers_;
-
+// Defintions of static members of CollectProperties.
+CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
bool CollectProperties::staticMembersInitialized_ = false;
-/// CollectToolProperties - Gather information from the parsed
-/// TableGen data (basically a wrapper for the CollectProperties
-/// function object).
+/// CollectToolProperties - Gather information about tool properties
+/// from the parsed TableGen data (basically a wrapper for the
+/// CollectProperties function object).
void CollectToolProperties (RecordVector::const_iterator B,
RecordVector::const_iterator E,
ToolPropertiesList& TPList,
{
// Iterate over a properties list of every Tool definition
for (;B!=E;++B) {
- RecordVector::value_type T = *B;
+ const Record* T = *B;
+ // Throws an exception if the value does not exist.
ListInit* PropList = T->getValueAsListInit("properties");
IntrusiveRefCntPtr<ToolProperties>
}
}
+
+/// CollectPropertiesFromOptionLists - Gather information about
+/// *global* option properties from all OptionLists.
+void CollectPropertiesFromOptionLists (RecordVector::const_iterator B,
+ RecordVector::const_iterator E,
+ GlobalOptionDescriptions& OptDescs)
+{
+ // Iterate over a properties list of every Tool definition
+ for (; B!=E; ++B) {
+ RecordVector::value_type T = *B;
+ // Throws an exception if the value does not exist.
+ ListInit* PropList = T->getValueAsListInit("options");
+
+ std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
+ }
+}
+
+/// CheckForSuperfluousOptions - Check that there are no side
+/// effect-free options (specified only in the OptionList). Otherwise,
+/// output a warning.
+void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
+ const GlobalOptionDescriptions& OptDescs) {
+ llvm::StringSet<> nonSuperfluousOptions;
+
+ // Add all options mentioned in the TPList to the set of
+ // non-superfluous options.
+ for (ToolPropertiesList::const_iterator B = TPList.begin(),
+ E = TPList.end(); B != E; ++B) {
+ const ToolProperties& TP = *(*B);
+ for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
+ E = TP.OptDescs.end(); B != E; ++B) {
+ nonSuperfluousOptions.insert(B->first());
+ }
+ }
+
+ // Check that all options in OptDescs belong to the set of
+ // non-superfluous options.
+ for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
+ E = OptDescs.end(); B != E; ++B) {
+ const GlobalOptionDescription& Val = B->second;
+ if (!nonSuperfluousOptions.count(Val.Name)
+ && Val.Type != OptionType::Alias)
+ llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
+ "Probable cause: this option is specified only in the OptionList.\n";
+ }
+}
+
/// EmitCaseTest1Arg - Helper function used by
/// EmitCaseConstructHandler.
bool EmitCaseTest1Arg(const std::string& TestName,
O << "InLangs.count(\"" << OptName << "\") != 0";
return true;
} else if (TestName == "in_language") {
- // Works only for cmd_line!
- O << "GetLanguage(inFile) == \"" << OptName << '\"';
+ // This works only for single-argument Tool::GenerateAction. Join
+ // tools can process several files in different languages simultaneously.
+
+ // TODO: make this work with Edge::Weight (if possible).
+ O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
return true;
} else if (TestName == "not_empty") {
if (OptName == "o") {
// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
template <typename F>
void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
- const F& Callback, bool EmitElseIf,
+ F Callback, bool EmitElseIf,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
assert(d->getOperator()->getAsString() == "case");
/// EmitForwardOptionPropertyHandlingCode - Helper function used to
/// implement EmitOptionPropertyHandlingCode(). Emits code for
-/// handling the (forward) option property.
+/// handling the (forward) and (forward_as) option properties.
void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
+ const std::string& NewName,
std::ostream& O) {
+ const std::string& Name = NewName.empty()
+ ? ("-" + D.Name)
+ : NewName;
+
switch (D.Type) {
case OptionType::Switch:
- O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
+ O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
break;
case OptionType::Parameter:
- O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
+ O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
break;
case OptionType::Prefix:
- O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
+ O << Indent3 << "vec.push_back(\"" << Name << "\" + "
<< D.GenVariableName() << ");\n";
break;
case OptionType::PrefixList:
O << Indent3 << "for (" << D.GenTypeDeclaration()
<< "::iterator B = " << D.GenVariableName() << ".begin(),\n"
<< Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
- << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
+ << Indent4 << "vec.push_back(\"" << Name << "\" + "
<< "*B);\n";
break;
case OptionType::ParameterList:
<< "::iterator B = " << D.GenVariableName() << ".begin(),\n"
<< Indent3 << "E = " << D.GenVariableName()
<< ".end() ; B != E; ++B) {\n"
- << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
+ << Indent4 << "vec.push_back(\"" << Name << "\");\n"
<< Indent4 << "vec.push_back(*B);\n"
<< Indent3 << "}\n";
break;
for (OptionPropertyList::const_iterator B = D.Props.begin(),
E = D.Props.end(); B != E; ++B) {
const OptionProperty& OptProp = *B;
- if (OptProp.first == OptionPropertyType::AppendCmd)
+ if (OptProp.first == OptionPropertyType::AppendCmd
+ || OptProp.first == OptionPropertyType::ForwardAs)
ret = true;
}
if (D.isForward() || D.isUnpackValues())
case OptionPropertyType::AppendCmd:
O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
break;
+ // (forward_as) property
+ case OptionPropertyType::ForwardAs:
+ EmitForwardOptionPropertyHandlingCode(D, val.second, O);
+ break;
// Other properties with argument
default:
break;
// (forward) property
if (D.isForward())
- EmitForwardOptionPropertyHandlingCode(D, O);
+ EmitForwardOptionPropertyHandlingCode(D, "", O);
// (unpack_values) property
if (D.isUnpackValues()) {
if (cmd.size() == 5)
throw std::string("$ENV invocation: empty argument list!");
- ret += "std::getenv(\"";
+ ret += "checkCString(std::getenv(\"";
ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
- ret += "\")";
+ ret += "\"))";
}
else {
throw "Unknown special command: " + cmd;
O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
O << Indent2 << "const sys::Path& outFile,\n"
- << Indent2 << "const InputLanguagesSet& InLangs) const\n"
+ << Indent2 << "const InputLanguagesSet& InLangs,\n"
+ << Indent2 << "const LanguageMap& LangMap) const\n"
<< Indent1 << "{\n"
<< Indent2 << "std::string cmd;\n"
<< Indent2 << "std::vector<std::string> vec;\n";
if (!P.isJoin())
O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
<< Indent2 << "const llvm::sys::Path& outFile,\n"
- << Indent2 << "const InputLanguagesSet& InLangs) const\n"
+ << Indent2 << "const InputLanguagesSet& InLangs,\n"
+ << Indent2 << "const LanguageMap& LangMap) const\n"
<< Indent1 << "{\n"
<< Indent2 << "throw std::runtime_error(\"" << P.Name
<< " is not a Join tool!\");\n"
/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
/// methods for a given Tool class.
void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
- O << Indent1 << "StrVector InputLanguages() const {\n"
- << Indent2 << "StrVector ret;\n";
-
- for (StrVector::const_iterator B = P.InLanguage.begin(),
- E = P.InLanguage.end(); B != E; ++B) {
- O << Indent2 << "ret.push_back(\"" << *B << "\");\n";
- }
-
- O << Indent2 << "return ret;\n"
+ O << Indent1 << "const char** InputLanguages() const {\n"
+ << Indent2 << "return InputLanguages_;\n"
<< Indent1 << "}\n\n";
O << Indent1 << "const char* OutputLanguage() const {\n"
O << Indent1 << "}\n\n";
}
+/// EmitStaticMemberDefinitions - Emit static member definitions for a
+/// given Tool class.
+void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
+ O << "const char* " << P.Name << "::InputLanguages_[] = {";
+ for (StrVector::const_iterator B = P.InLanguage.begin(),
+ E = P.InLanguage.end(); B != E; ++B)
+ O << '\"' << *B << "\", ";
+ O << "0};\n\n";
+}
+
/// EmitToolClassDefinition - Emit a Tool class definition.
void EmitToolClassDefinition (const ToolProperties& P,
const GlobalOptionDescriptions& OptDescs,
O << "JoinTool";
else
O << "Tool";
- O << " {\npublic:\n";
+ O << "{\nprivate:\n"
+ << Indent1 << "static const char* InputLanguages_[];\n\n";
+
+ O << "public:\n";
EmitNameMethod(P, O);
EmitInOutLanguageMethods(P, O);
EmitOutputSuffixMethod(P, O);
EmitIsLastMethod(P, O);
// Close class definition
- O << "};\n\n";
+ O << "};\n";
+
+ EmitStaticMemberDefinitions(P, O);
+
}
/// EmitOptionDescriptions - Iterate over a list of option
}
}
+ if (val.isReallyHidden() || val.isHidden()) {
+ if (val.isRequired())
+ O << " |";
+ else
+ O << ",";
+ if (val.isReallyHidden())
+ O << " cl::ReallyHidden";
+ else
+ O << " cl::Hidden";
+ }
+
if (!val.Help.empty())
O << ", cl::desc(\"" << val.Help << "\")";
/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
{
+ // Generate code
+ O << "namespace {\n\n";
+ O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
+
// Get the relevant field out of RecordKeeper
- Record* LangMapRecord = Records.getDef("LanguageMap");
- if (!LangMapRecord)
- throw std::string("Language map definition not found!");
+ const Record* LangMapRecord = Records.getDef("LanguageMap");
- ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
- if (!LangsToSuffixesList)
- throw std::string("Error in the language map definition!");
+ // It is allowed for a plugin to have no language map.
+ if (LangMapRecord) {
- // Generate code
- O << "void llvmc::PopulateLanguageMap() {\n";
+ ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
+ if (!LangsToSuffixesList)
+ throw std::string("Error in the language map definition!");
- for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
- Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
+ for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
+ const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
- const std::string& Lang = LangToSuffixes->getValueAsString("lang");
- const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
+ const std::string& Lang = LangToSuffixes->getValueAsString("lang");
+ const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
- for (unsigned i = 0; i < Suffixes->size(); ++i)
- O << Indent1 << "GlobalLanguageMap[\""
- << InitPtrToString(Suffixes->getElement(i))
- << "\"] = \"" << Lang << "\";\n";
+ for (unsigned i = 0; i < Suffixes->size(); ++i)
+ O << Indent1 << "langMap[\""
+ << InitPtrToString(Suffixes->getElement(i))
+ << "\"] = \"" << Lang << "\";\n";
+ }
}
- O << "}\n\n";
+ O << "}\n\n}\n\n";
}
/// FillInToolToLang - Fills in two tables that map tool names to
}
/// TypecheckGraph - Check that names for output and input languages
-/// on all edges do match.
-// TOFIX: It would be nice if this function also checked for cycles
-// and multiple default edges in the graph (better error
-// reporting). Unfortunately, it is awkward to do right now because
-// our intermediate representation is not sufficiently
-// sofisticated. Algorithms like these should be run on a real graph
-// instead of AST.
-void TypecheckGraph (Record* CompilationGraph,
+/// on all edges do match. This doesn't do much when the information
+/// about the whole graph is not available (i.e. when compiling most
+/// plugins).
+void TypecheckGraph (const RecordVector& EdgeVector,
const ToolPropertiesList& TPList) {
StringMap<StringSet<> > ToolToInLang;
StringMap<std::string> ToolToOutLang;
FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
- ListInit* edges = CompilationGraph->getValueAsListInit("edges");
StringMap<std::string>::iterator IAE = ToolToOutLang.end();
StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
- for (unsigned i = 0; i < edges->size(); ++i) {
- Record* Edge = edges->getElementAsRecord(i);
- Record* A = Edge->getValueAsDef("a");
- Record* B = Edge->getValueAsDef("b");
- StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
- StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
- if (IA == IAE)
- throw A->getName() + ": no such tool!";
- if (IB == IBE)
- throw B->getName() + ": no such tool!";
- if (A->getName() != "root" && IB->second.count(IA->second) == 0)
- throw "Edge " + A->getName() + "->" + B->getName()
- + ": output->input language mismatch";
- if (B->getName() == "root")
+ for (RecordVector::const_iterator B = EdgeVector.begin(),
+ E = EdgeVector.end(); B != E; ++B) {
+ const Record* Edge = *B;
+ const std::string& A = Edge->getValueAsString("a");
+ const std::string& B = Edge->getValueAsString("b");
+ StringMap<std::string>::iterator IA = ToolToOutLang.find(A);
+ StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B);
+
+ if (A != "root") {
+ if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
+ throw "Edge " + A + "->" + B
+ + ": output->input language mismatch";
+ }
+
+ if (B == "root")
throw std::string("Edges back to the root are not allowed!");
}
}
}
/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
-void EmitEdgeClasses (Record* CompilationGraph,
+void EmitEdgeClasses (const RecordVector& EdgeVector,
const GlobalOptionDescriptions& OptDescs,
std::ostream& O) {
- ListInit* edges = CompilationGraph->getValueAsListInit("edges");
-
- for (unsigned i = 0; i < edges->size(); ++i) {
- Record* Edge = edges->getElementAsRecord(i);
- Record* B = Edge->getValueAsDef("b");
+ int i = 0;
+ for (RecordVector::const_iterator B = EdgeVector.begin(),
+ E = EdgeVector.end(); B != E; ++B) {
+ const Record* Edge = *B;
+ const std::string& B = Edge->getValueAsString("b");
DagInit* Weight = Edge->getValueAsDag("weight");
- if (isDagEmpty(Weight))
- continue;
-
- EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
+ if (!isDagEmpty(Weight))
+ EmitEdgeClass(i, B, Weight, OptDescs, O);
+ ++i;
}
}
/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
/// function.
-void EmitPopulateCompilationGraph (Record* CompilationGraph,
+void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
+ const ToolPropertiesList& ToolProps,
std::ostream& O)
{
- ListInit* edges = CompilationGraph->getValueAsListInit("edges");
+ O << "namespace {\n\n";
+ O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
- // Generate code
- O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
- << Indent1 << "PopulateLanguageMap();\n\n";
-
- // Insert vertices
-
- RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
- if (Tools.empty())
- throw std::string("No tool definitions found!");
-
- for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
- const std::string& Name = (*B)->getName();
- if (Name != "root")
- O << Indent1 << "G.insertNode(new "
- << Name << "());\n";
- }
+ for (ToolPropertiesList::const_iterator B = ToolProps.begin(),
+ E = ToolProps.end(); B != E; ++B)
+ O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
O << '\n';
- // Insert edges
- for (unsigned i = 0; i < edges->size(); ++i) {
- Record* Edge = edges->getElementAsRecord(i);
- Record* A = Edge->getValueAsDef("a");
- Record* B = Edge->getValueAsDef("b");
+ // Insert edges.
+
+ int i = 0;
+ for (RecordVector::const_iterator B = EdgeVector.begin(),
+ E = EdgeVector.end(); B != E; ++B) {
+ const Record* Edge = *B;
+ const std::string& A = Edge->getValueAsString("a");
+ const std::string& B = Edge->getValueAsString("b");
DagInit* Weight = Edge->getValueAsDag("weight");
- O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
+ O << Indent1 << "G.insertEdge(\"" << A << "\", ";
if (isDagEmpty(Weight))
- O << "new SimpleEdge(\"" << B->getName() << "\")";
+ O << "new SimpleEdge(\"" << B << "\")";
else
O << "new Edge" << i << "()";
O << ");\n";
+ ++i;
}
- O << "}\n\n";
+ O << "}\n\n}\n\n";
}
/// ExtractHookNames - Extract the hook names from all instances of
O << "}\n\n";
}
+/// EmitRegisterPlugin - Emit code to register this plugin.
+void EmitRegisterPlugin(int Priority, std::ostream& O) {
+ O << "namespace {\n\n"
+ << "struct Plugin : public llvmc::BasePlugin {\n\n"
+ << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
+ << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
+ << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
+ << Indent1
+ << "void PopulateCompilationGraph(CompilationGraph& graph) const\n"
+ << Indent1 << "{ PopulateCompilationGraphLocal(graph); }\n"
+ << "};\n\n"
+
+ << "static llvmc::RegisterPlugin<Plugin> RP;\n\n}\n\n";
+}
+
+/// EmitIncludes - Emit necessary #include directives and some
+/// additional declarations.
+void EmitIncludes(std::ostream& O) {
+ O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
+ << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
+ << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
+
+ << "#include \"llvm/ADT/StringExtras.h\"\n"
+ << "#include \"llvm/Support/CommandLine.h\"\n\n"
+
+ << "#include <cstdlib>\n"
+ << "#include <stdexcept>\n\n"
+
+ << "using namespace llvm;\n"
+ << "using namespace llvmc;\n\n"
+
+ << "extern cl::opt<std::string> OutputFilename;\n\n"
+
+ << "inline const char* checkCString(const char* s)\n"
+ << "{ return s == NULL ? \"\" : s; }\n\n";
+}
+
+/// NotInGraph - Helper function object for FilterNotInGraph.
+struct NotInGraph {
+private:
+ const llvm::StringSet<>& ToolsInGraph_;
+
+public:
+ NotInGraph(const llvm::StringSet<>& ToolsInGraph)
+ : ToolsInGraph_(ToolsInGraph)
+ {}
+
+ bool operator()(const IntrusiveRefCntPtr<ToolProperties>& x) {
+ return (ToolsInGraph_.count(x->Name) == 0);
+ }
+};
+
+/// FilterNotInGraph - Filter out from ToolProps all Tools not
+/// mentioned in the compilation graph definition.
+void FilterNotInGraph (const RecordVector& EdgeVector,
+ ToolPropertiesList& ToolProps) {
+
+ // List all tools mentioned in the graph.
+ llvm::StringSet<> ToolsInGraph;
+
+ for (RecordVector::const_iterator B = EdgeVector.begin(),
+ E = EdgeVector.end(); B != E; ++B) {
+
+ const Record* Edge = *B;
+ const std::string& A = Edge->getValueAsString("a");
+ const std::string& B = Edge->getValueAsString("b");
+
+ if (A != "root")
+ ToolsInGraph.insert(A);
+ ToolsInGraph.insert(B);
+ }
+
+ // Filter ToolPropertiesList.
+ ToolPropertiesList::iterator new_end =
+ std::remove_if(ToolProps.begin(), ToolProps.end(),
+ NotInGraph(ToolsInGraph));
+ ToolProps.erase(new_end, ToolProps.end());
+}
+
+/// CalculatePriority - Calculate the priority of this plugin.
+int CalculatePriority(RecordVector::const_iterator B,
+ RecordVector::const_iterator E) {
+ int total = 0;
+ for (; B!=E; ++B) {
+ total += static_cast<int>((*B)->getValueAsInt("priority"));
+ }
+ return total;
+}
+
+/// FillInEdgeVector - Merge all compilation graph definitions into
+/// one single edge list.
+void FillInEdgeVector(RecordVector::const_iterator B,
+ RecordVector::const_iterator E, RecordVector& Out) {
+ for (; B != E; ++B) {
+ const ListInit* edges = (*B)->getValueAsListInit("edges");
+
+ for (unsigned i = 0; i < edges->size(); ++i)
+ Out.push_back(edges->getElementAsRecord(i));
+ }
+}
+
// End of anonymous namespace
}
// Emit file header.
EmitSourceFileHeader("LLVMC Configuration Library", O);
+ EmitIncludes(O);
- // Get a list of all defined Tools.
+ // Collect tool properties.
RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
- if (Tools.empty())
- throw std::string("No tool definitions found!");
+ ToolPropertiesList ToolProps;
+ GlobalOptionDescriptions OptDescs;
+ CollectToolProperties(Tools.begin(), Tools.end(), ToolProps, OptDescs);
+
+ // Collect option properties.
+ const RecordVector& OptionLists =
+ Records.getAllDerivedDefinitions("OptionList");
+ CollectPropertiesFromOptionLists(OptionLists.begin(), OptionLists.end(),
+ OptDescs);
+
+ // Collect compilation graph edges.
+ const RecordVector& CompilationGraphs =
+ Records.getAllDerivedDefinitions("CompilationGraph");
+ RecordVector EdgeVector;
+ FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
+ EdgeVector);
+
+ // Filter out all tools not mentioned in the compilation graph.
+ FilterNotInGraph(EdgeVector, ToolProps);
+
+ // Typecheck the compilation graph.
+ TypecheckGraph(EdgeVector, ToolProps);
- // Gather information from the Tool description dags.
- ToolPropertiesList tool_props;
- GlobalOptionDescriptions opt_descs;
- CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
+ // Check that there are no options without side effects (specified
+ // only in the OptionList).
+ CheckForSuperfluousOptions(ToolProps, OptDescs);
// Emit global option registration code.
- EmitOptionDescriptions(opt_descs, O);
+ EmitOptionDescriptions(OptDescs, O);
// Emit hook declarations.
- EmitHookDeclarations(tool_props, O);
+ EmitHookDeclarations(ToolProps, O);
// Emit PopulateLanguageMap() function
// (a language map maps from file extensions to language names).
EmitPopulateLanguageMap(Records, O);
// Emit Tool classes.
- for (ToolPropertiesList::const_iterator B = tool_props.begin(),
- E = tool_props.end(); B!=E; ++B)
- EmitToolClassDefinition(*(*B), opt_descs, O);
-
- Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
- if (!CompilationGraphRecord)
- throw std::string("Compilation graph description not found!");
-
- // Typecheck the compilation graph.
- TypecheckGraph(CompilationGraphRecord, tool_props);
+ for (ToolPropertiesList::const_iterator B = ToolProps.begin(),
+ E = ToolProps.end(); B!=E; ++B)
+ EmitToolClassDefinition(*(*B), OptDescs, O);
// Emit Edge# classes.
- EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
+ EmitEdgeClasses(EdgeVector, OptDescs, O);
// Emit PopulateCompilationGraph() function.
- EmitPopulateCompilationGraph(CompilationGraphRecord, O);
+ EmitPopulateCompilationGraph(EdgeVector, ToolProps, O);
+
+ // Emit code for plugin registration.
+ const RecordVector& Priorities =
+ Records.getAllDerivedDefinitions("PluginPriority");
+ EmitRegisterPlugin(CalculatePriority(Priorities.begin(),
+ Priorities.end()), O);
// EOF
} catch (std::exception& Error) {