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"
34 //===----------------------------------------------------------------------===//
37 typedef std::vector<Record*> RecordVector;
38 typedef std::vector<std::string> StrVector;
40 //===----------------------------------------------------------------------===//
43 // Indentation strings.
44 const char * Indent1 = " ";
45 const char * Indent2 = " ";
46 const char * Indent3 = " ";
47 const char * Indent4 = " ";
49 // Default help string.
50 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
52 // Name for the "sink" option.
53 const char * SinkOptionName = "AutoGeneratedSinkOption";
55 //===----------------------------------------------------------------------===//
58 int InitPtrToInt(const Init* ptr) {
59 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
60 return val.getValue();
63 const std::string& InitPtrToString(const Init* ptr) {
64 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
65 return val.getValue();
68 const ListInit& InitPtrToList(const Init* ptr) {
69 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
73 const DagInit& InitPtrToDag(const Init* ptr) {
74 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
78 // checkNumberOfArguments - Ensure that the number of args in d is
79 // less than or equal to min_arguments, otherwise throw an exception.
80 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
81 if (d->getNumArgs() < min_arguments)
82 throw "Property " + d->getOperator()->getAsString()
83 + " has too few arguments!";
86 // isDagEmpty - is this DAG marked with an empty marker?
87 bool isDagEmpty (const DagInit* d) {
88 return d->getOperator()->getAsString() == "empty";
91 //===----------------------------------------------------------------------===//
92 /// Back-end specific code
94 // A command-line option can have one of the following types:
96 // Alias - an alias for another option.
98 // Switch - a simple switch without arguments, e.g. -O2
100 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
103 // ParameterList - same as Parameter, but more than one occurence
104 // of the option is allowed, e.g. -lm -lpthread
106 // Prefix - argument is everything after the prefix,
107 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
109 // PrefixList - same as Prefix, but more than one option occurence is
112 namespace OptionType {
113 enum OptionType { Alias, Switch,
114 Parameter, ParameterList, Prefix, PrefixList};
117 bool IsListOptionType (OptionType::OptionType t) {
118 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
121 // Code duplication here is necessary because one option can affect
122 // several tools and those tools may have different actions associated
123 // with this option. GlobalOptionDescriptions are used to generate
124 // the option registration code, while ToolOptionDescriptions are used
125 // to generate tool-specific code.
127 /// OptionDescription - Base class for option descriptions.
128 struct OptionDescription {
129 OptionType::OptionType Type;
132 OptionDescription(OptionType::OptionType t = OptionType::Switch,
133 const std::string& n = "")
137 const char* GenTypeDeclaration() const {
139 case OptionType::Alias:
141 case OptionType::PrefixList:
142 case OptionType::ParameterList:
143 return "cl::list<std::string>";
144 case OptionType::Switch:
145 return "cl::opt<bool>";
146 case OptionType::Parameter:
147 case OptionType::Prefix:
149 return "cl::opt<std::string>";
153 // Escape commas and other symbols not allowed in the C++ variable
154 // names. Makes it possible to use options with names like "Wa,"
155 // (useful for prefix options).
156 std::string EscapeVariableName(const std::string& Var) const {
158 for (unsigned i = 0; i != Var.size(); ++i) {
163 ret.push_back(Var[i]);
169 std::string GenVariableName() const {
170 const std::string& EscapedName = EscapeVariableName(Name);
172 case OptionType::Alias:
173 return "AutoGeneratedAlias" + EscapedName;
174 case OptionType::Switch:
175 return "AutoGeneratedSwitch" + EscapedName;
176 case OptionType::Prefix:
177 return "AutoGeneratedPrefix" + EscapedName;
178 case OptionType::PrefixList:
179 return "AutoGeneratedPrefixList" + EscapedName;
180 case OptionType::Parameter:
181 return "AutoGeneratedParameter" + EscapedName;
182 case OptionType::ParameterList:
184 return "AutoGeneratedParameterList" + EscapedName;
190 // Global option description.
192 namespace GlobalOptionDescriptionFlags {
193 enum GlobalOptionDescriptionFlags { Required = 0x1 };
196 struct GlobalOptionDescription : public OptionDescription {
200 // We need to provide a default constructor because
201 // StringMap can only store DefaultConstructible objects.
202 GlobalOptionDescription() : OptionDescription(), Flags(0)
205 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
206 const std::string& h = DefaultHelpString)
207 : OptionDescription(t, n), Help(h), Flags(0)
210 bool isRequired() const {
211 return Flags & GlobalOptionDescriptionFlags::Required;
214 Flags |= GlobalOptionDescriptionFlags::Required;
217 /// Merge - Merge two option descriptions.
218 void Merge (const GlobalOptionDescription& other)
220 if (other.Type != Type)
221 throw "Conflicting definitions for the option " + Name + "!";
223 if (Help == DefaultHelpString)
225 else if (other.Help != DefaultHelpString) {
226 llvm::cerr << "Warning: more than one help string defined for option "
230 Flags |= other.Flags;
234 /// GlobalOptionDescriptions - A GlobalOptionDescription array
235 /// together with some flags affecting generation of option
237 struct GlobalOptionDescriptions {
238 typedef StringMap<GlobalOptionDescription> container_type;
239 typedef container_type::const_iterator const_iterator;
241 /// Descriptions - A list of GlobalOptionDescriptions.
242 container_type Descriptions;
243 /// HasSink - Should the emitter generate a "cl::sink" option?
246 /// FindOption - exception-throwing wrapper for find().
247 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
248 const_iterator I = Descriptions.find(OptName);
249 if (I != Descriptions.end())
252 throw OptName + ": no such option!";
255 /// insertDescription - Insert new GlobalOptionDescription into
256 /// GlobalOptionDescriptions list
257 void insertDescription (const GlobalOptionDescription& o)
259 container_type::iterator I = Descriptions.find(o.Name);
260 if (I != Descriptions.end()) {
261 GlobalOptionDescription& D = I->second;
265 Descriptions[o.Name] = o;
269 // Support for STL-style iteration
270 const_iterator begin() const { return Descriptions.begin(); }
271 const_iterator end() const { return Descriptions.end(); }
275 // Tool-local option description.
277 // Properties without arguments are implemented as flags.
278 namespace ToolOptionDescriptionFlags {
279 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
280 Forward = 0x2, UnpackValues = 0x4};
282 namespace OptionPropertyType {
283 enum OptionPropertyType { AppendCmd, OutputSuffix };
286 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
288 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
290 struct ToolOptionDescription : public OptionDescription {
292 OptionPropertyList Props;
294 // StringMap can only store DefaultConstructible objects
295 ToolOptionDescription() : OptionDescription(), Flags(0) {}
297 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
298 : OptionDescription(t, n)
301 // Various boolean properties
302 bool isStopCompilation() const {
303 return Flags & ToolOptionDescriptionFlags::StopCompilation;
305 void setStopCompilation() {
306 Flags |= ToolOptionDescriptionFlags::StopCompilation;
309 bool isForward() const {
310 return Flags & ToolOptionDescriptionFlags::Forward;
313 Flags |= ToolOptionDescriptionFlags::Forward;
316 bool isUnpackValues() const {
317 return Flags & ToolOptionDescriptionFlags::UnpackValues;
319 void setUnpackValues() {
320 Flags |= ToolOptionDescriptionFlags::UnpackValues;
323 void AddProperty (OptionPropertyType::OptionPropertyType t,
324 const std::string& val)
326 Props.push_back(std::make_pair(t, val));
330 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
332 // Tool information record
334 namespace ToolFlags {
335 enum ToolFlags { Join = 0x1, Sink = 0x2 };
338 struct ToolProperties : public RefCountedBase<ToolProperties> {
341 StrVector InLanguage;
342 std::string OutLanguage;
343 std::string OutputSuffix;
345 ToolOptionDescriptions OptDescs;
347 // Various boolean properties
348 void setSink() { Flags |= ToolFlags::Sink; }
349 bool isSink() const { return Flags & ToolFlags::Sink; }
350 void setJoin() { Flags |= ToolFlags::Join; }
351 bool isJoin() const { return Flags & ToolFlags::Join; }
353 // Default ctor here is needed because StringMap can only store
354 // DefaultConstructible objects
355 ToolProperties() : CmdLine(0), Flags(0) {}
356 ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
360 /// ToolPropertiesList - A list of Tool information records
361 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
362 /// constructor (and we want to avoid copying ToolProperties anyway).
363 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
366 /// CollectOptionProperties - Function object for iterating over a
367 /// list (usually, a DAG) of option property records.
368 class CollectOptionProperties {
370 // Implementation details.
372 /// OptionPropertyHandler - a function that extracts information
373 /// about a given option property from its DAG representation.
374 typedef void (CollectOptionProperties::* OptionPropertyHandler)
377 /// OptionPropertyHandlerMap - A map from option property names to
378 /// option property handlers
379 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
381 static OptionPropertyHandlerMap optionPropertyHandlers_;
382 static bool staticMembersInitialized_;
384 /// This is where the information is stored
386 /// toolProps_ - Properties of the current Tool.
387 ToolProperties* toolProps_;
388 /// optDescs_ - OptionDescriptions table (used to register options
390 GlobalOptionDescription& optDesc_;
394 explicit CollectOptionProperties(ToolProperties* TP,
395 GlobalOptionDescription& OD)
396 : toolProps_(TP), optDesc_(OD)
398 if (!staticMembersInitialized_) {
399 optionPropertyHandlers_["append_cmd"] =
400 &CollectOptionProperties::onAppendCmd;
401 optionPropertyHandlers_["forward"] =
402 &CollectOptionProperties::onForward;
403 optionPropertyHandlers_["help"] =
404 &CollectOptionProperties::onHelp;
405 optionPropertyHandlers_["output_suffix"] =
406 &CollectOptionProperties::onOutputSuffix;
407 optionPropertyHandlers_["required"] =
408 &CollectOptionProperties::onRequired;
409 optionPropertyHandlers_["stop_compilation"] =
410 &CollectOptionProperties::onStopCompilation;
411 optionPropertyHandlers_["unpack_values"] =
412 &CollectOptionProperties::onUnpackValues;
414 staticMembersInitialized_ = true;
418 /// operator() - Gets called for every option property; Just forwards
419 /// to the corresponding property handler.
420 void operator() (Init* i) {
421 const DagInit& option_property = InitPtrToDag(i);
422 const std::string& option_property_name
423 = option_property.getOperator()->getAsString();
424 OptionPropertyHandlerMap::iterator method
425 = optionPropertyHandlers_.find(option_property_name);
427 if (method != optionPropertyHandlers_.end()) {
428 OptionPropertyHandler h = method->second;
429 (this->*h)(&option_property);
432 throw "Unknown option property: " + option_property_name + "!";
438 /// Option property handlers --
439 /// Methods that handle properties that are common for all types of
440 /// options (like append_cmd, stop_compilation)
442 void onAppendCmd (const DagInit* d) {
443 checkNumberOfArguments(d, 1);
445 const std::string& cmd = InitPtrToString(d->getArg(0));
447 toolProps_->OptDescs[optDesc_.Name].
448 AddProperty(OptionPropertyType::AppendCmd, cmd);
451 void onOutputSuffix (const DagInit* d) {
452 checkNumberOfArguments(d, 1);
454 const std::string& suf = InitPtrToString(d->getArg(0));
456 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
457 throw "Option " + optDesc_.Name
458 + " can't have 'output_suffix' property since it isn't a switch!";
460 toolProps_->OptDescs[optDesc_.Name].AddProperty
461 (OptionPropertyType::OutputSuffix, suf);
464 void onForward (const DagInit* d) {
465 checkNumberOfArguments(d, 0);
467 toolProps_->OptDescs[optDesc_.Name].setForward();
470 void onHelp (const DagInit* d) {
471 checkNumberOfArguments(d, 1);
472 const std::string& help_message = InitPtrToString(d->getArg(0));
474 optDesc_.Help = help_message;
477 void onRequired (const DagInit* d) {
478 checkNumberOfArguments(d, 0);
480 optDesc_.setRequired();
483 void onStopCompilation (const DagInit* d) {
484 checkNumberOfArguments(d, 0);
486 if (optDesc_.Type != OptionType::Switch)
487 throw std::string("Only options of type Switch can stop compilation!");
488 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
491 void onUnpackValues (const DagInit* d) {
492 checkNumberOfArguments(d, 0);
494 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
499 /// checkToolProps - Throw an error if toolProps_ == 0.
500 void checkToolProps(const DagInit* d) {
502 throw "Option property " + d->getOperator()->getAsString()
503 + " can't be used in this context";
508 CollectOptionProperties::OptionPropertyHandlerMap
509 CollectOptionProperties::optionPropertyHandlers_;
511 bool CollectOptionProperties::staticMembersInitialized_ = false;
514 /// processOptionProperties - Go through the list of option
515 /// properties and call a corresponding handler for each.
516 void processOptionProperties (const DagInit* d, ToolProperties* t,
517 GlobalOptionDescription& o) {
518 checkNumberOfArguments(d, 2);
519 DagInit::const_arg_iterator B = d->arg_begin();
520 // Skip the first argument: it's always the option name.
522 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
525 /// AddOption - A function object wrapper for
526 /// processOptionProperties. Used by CollectProperties and
527 /// CollectPropertiesFromOptionList.
530 GlobalOptionDescriptions& OptDescs_;
531 ToolProperties* ToolProps_;
534 explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
535 : OptDescs_(OD), ToolProps_(TP)
538 void operator()(const Init* i) {
539 const DagInit& d = InitPtrToDag(i);
540 checkNumberOfArguments(&d, 2);
542 const OptionType::OptionType Type =
543 getOptionType(d.getOperator()->getAsString());
544 const std::string& Name = InitPtrToString(d.getArg(0));
546 GlobalOptionDescription OD(Type, Name);
547 if (Type != OptionType::Alias) {
548 processOptionProperties(&d, ToolProps_, OD);
550 ToolProps_->OptDescs[Name].Type = Type;
551 ToolProps_->OptDescs[Name].Name = Name;
555 OD.Help = InitPtrToString(d.getArg(1));
557 OptDescs_.insertDescription(OD);
561 OptionType::OptionType getOptionType(const std::string& T) const {
562 if (T == "alias_option")
563 return OptionType::Alias;
564 else if (T == "switch_option")
565 return OptionType::Switch;
566 else if (T == "parameter_option")
567 return OptionType::Parameter;
568 else if (T == "parameter_list_option")
569 return OptionType::ParameterList;
570 else if (T == "prefix_option")
571 return OptionType::Prefix;
572 else if (T == "prefix_list_option")
573 return OptionType::PrefixList;
575 throw "Unknown option type: " + T + '!';
580 /// CollectProperties - Function object for iterating over a list of
581 /// tool property records.
582 class CollectProperties {
585 // Implementation details
587 /// PropertyHandler - a function that extracts information
588 /// about a given tool property from its DAG representation
589 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
591 /// PropertyHandlerMap - A map from property names to property
593 typedef StringMap<PropertyHandler> PropertyHandlerMap;
595 // Static maps from strings to CollectProperties methods("handlers")
596 static PropertyHandlerMap propertyHandlers_;
597 static bool staticMembersInitialized_;
600 /// This is where the information is stored
602 /// toolProps_ - Properties of the current Tool.
603 ToolProperties& toolProps_;
604 /// optDescs_ - OptionDescriptions table (used to register options
606 GlobalOptionDescriptions& optDescs_;
610 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
611 : toolProps_(p), optDescs_(d)
613 if (!staticMembersInitialized_) {
614 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
615 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
616 propertyHandlers_["join"] = &CollectProperties::onJoin;
617 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
618 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
619 propertyHandlers_["parameter_option"]
620 = &CollectProperties::addOption;
621 propertyHandlers_["parameter_list_option"] =
622 &CollectProperties::addOption;
623 propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
624 propertyHandlers_["prefix_list_option"] =
625 &CollectProperties::addOption;
626 propertyHandlers_["sink"] = &CollectProperties::onSink;
627 propertyHandlers_["switch_option"] = &CollectProperties::addOption;
628 propertyHandlers_["alias_option"] = &CollectProperties::addOption;
630 staticMembersInitialized_ = true;
634 /// operator() - Gets called for every tool property; Just forwards
635 /// to the corresponding property handler.
636 void operator() (Init* i) {
637 const DagInit& d = InitPtrToDag(i);
638 const std::string& property_name = d.getOperator()->getAsString();
639 PropertyHandlerMap::iterator method
640 = propertyHandlers_.find(property_name);
642 if (method != propertyHandlers_.end()) {
643 PropertyHandler h = method->second;
647 throw "Unknown tool property: " + property_name + "!";
653 /// Property handlers --
654 /// Functions that extract information about tool properties from
655 /// DAG representation.
657 void onCmdLine (const DagInit* d) {
658 checkNumberOfArguments(d, 1);
659 toolProps_.CmdLine = d->getArg(0);
662 void onInLanguage (const DagInit* d) {
663 checkNumberOfArguments(d, 1);
664 Init* arg = d->getArg(0);
666 // Find out the argument's type.
667 if (typeid(*arg) == typeid(StringInit)) {
669 toolProps_.InLanguage.push_back(InitPtrToString(arg));
673 const ListInit& lst = InitPtrToList(arg);
674 StrVector& out = toolProps_.InLanguage;
676 // Copy strings to the output vector.
677 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
679 out.push_back(InitPtrToString(*B));
682 // Remove duplicates.
683 std::sort(out.begin(), out.end());
684 StrVector::iterator newE = std::unique(out.begin(), out.end());
685 out.erase(newE, out.end());
689 void onJoin (const DagInit* d) {
690 checkNumberOfArguments(d, 0);
691 toolProps_.setJoin();
694 void onOutLanguage (const DagInit* d) {
695 checkNumberOfArguments(d, 1);
696 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
699 void onOutputSuffix (const DagInit* d) {
700 checkNumberOfArguments(d, 1);
701 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
704 void onSink (const DagInit* d) {
705 checkNumberOfArguments(d, 0);
706 optDescs_.HasSink = true;
707 toolProps_.setSink();
710 // Just forwards to the AddOption function object. Somewhat
711 // non-optimal, but avoids code duplication.
712 void addOption (const DagInit* d) {
713 checkNumberOfArguments(d, 2);
714 AddOption(optDescs_, &toolProps_)(d);
719 // Defintions of static members of CollectProperties.
720 CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
721 bool CollectProperties::staticMembersInitialized_ = false;
724 /// CollectToolProperties - Gather information about tool properties
725 /// from the parsed TableGen data (basically a wrapper for the
726 /// CollectProperties function object).
727 void CollectToolProperties (RecordVector::const_iterator B,
728 RecordVector::const_iterator E,
729 ToolPropertiesList& TPList,
730 GlobalOptionDescriptions& OptDescs)
732 // Iterate over a properties list of every Tool definition
735 // Throws an exception if the value does not exist.
736 ListInit* PropList = T->getValueAsListInit("properties");
738 IntrusiveRefCntPtr<ToolProperties>
739 ToolProps(new ToolProperties(T->getName()));
741 std::for_each(PropList->begin(), PropList->end(),
742 CollectProperties(*ToolProps, OptDescs));
743 TPList.push_back(ToolProps);
748 /// CollectPropertiesFromOptionList - Gather information about
749 /// *global* option properties from the OptionList.
750 void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
751 RecordVector::const_iterator E,
752 GlobalOptionDescriptions& OptDescs)
754 // Iterate over a properties list of every Tool definition
756 RecordVector::value_type T = *B;
757 // Throws an exception if the value does not exist.
758 ListInit* PropList = T->getValueAsListInit("options");
760 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
764 /// CheckForSuperfluousOptions - Check that there are no side
765 /// effect-free options (specified only in the OptionList). Otherwise,
766 /// output a warning.
767 void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
768 const GlobalOptionDescriptions& OptDescs) {
769 llvm::StringSet<> nonSuperfluousOptions;
771 // Add all options mentioned in the TPList to the set of
772 // non-superfluous options.
773 for (ToolPropertiesList::const_iterator B = TPList.begin(),
774 E = TPList.end(); B != E; ++B) {
775 const ToolProperties& TP = *(*B);
776 for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
777 E = TP.OptDescs.end(); B != E; ++B) {
778 nonSuperfluousOptions.insert(B->first());
782 // Check that all options in OptDescs belong to the set of
783 // non-superfluous options.
784 for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
785 E = OptDescs.end(); B != E; ++B) {
786 const GlobalOptionDescription& Val = B->second;
787 if (!nonSuperfluousOptions.count(Val.Name)
788 && Val.Type != OptionType::Alias)
789 cerr << "Warning: option '-" << Val.Name << "' has no effect! "
790 "Probable cause: this option is specified only in the OptionList.\n";
794 /// EmitCaseTest1Arg - Helper function used by
795 /// EmitCaseConstructHandler.
796 bool EmitCaseTest1Arg(const std::string& TestName,
798 const GlobalOptionDescriptions& OptDescs,
800 // TOFIX - Add a mechanism for OS detection.
801 checkNumberOfArguments(&d, 1);
802 const std::string& OptName = InitPtrToString(d.getArg(0));
803 if (TestName == "switch_on") {
804 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
805 if (OptDesc.Type != OptionType::Switch)
806 throw OptName + ": incorrect option type!";
807 O << OptDesc.GenVariableName();
809 } else if (TestName == "input_languages_contain") {
810 O << "InLangs.count(\"" << OptName << "\") != 0";
812 } else if (TestName == "in_language") {
813 // Works only for cmd_line!
814 O << "GetLanguage(inFile) == \"" << OptName << '\"';
816 } else if (TestName == "not_empty") {
817 if (OptName == "o") {
818 O << "!OutputFilename.empty()";
822 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
823 if (OptDesc.Type == OptionType::Switch)
824 throw OptName + ": incorrect option type!";
825 O << '!' << OptDesc.GenVariableName() << ".empty()";
833 /// EmitCaseTest2Args - Helper function used by
834 /// EmitCaseConstructHandler.
835 bool EmitCaseTest2Args(const std::string& TestName,
837 const char* IndentLevel,
838 const GlobalOptionDescriptions& OptDescs,
840 checkNumberOfArguments(&d, 2);
841 const std::string& OptName = InitPtrToString(d.getArg(0));
842 const std::string& OptArg = InitPtrToString(d.getArg(1));
843 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
845 if (TestName == "parameter_equals") {
846 if (OptDesc.Type != OptionType::Parameter
847 && OptDesc.Type != OptionType::Prefix)
848 throw OptName + ": incorrect option type!";
849 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
852 else if (TestName == "element_in_list") {
853 if (OptDesc.Type != OptionType::ParameterList
854 && OptDesc.Type != OptionType::PrefixList)
855 throw OptName + ": incorrect option type!";
856 const std::string& VarName = OptDesc.GenVariableName();
857 O << "std::find(" << VarName << ".begin(),\n"
858 << IndentLevel << Indent1 << VarName << ".end(), \""
859 << OptArg << "\") != " << VarName << ".end()";
866 // Forward declaration.
867 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
868 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
869 const GlobalOptionDescriptions& OptDescs,
872 /// EmitLogicalOperationTest - Helper function used by
873 /// EmitCaseConstructHandler.
874 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
875 const char* IndentLevel,
876 const GlobalOptionDescriptions& OptDescs,
879 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
880 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
881 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
882 if (j != NumArgs - 1)
883 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
889 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
890 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
891 const GlobalOptionDescriptions& OptDescs,
893 const std::string& TestName = d.getOperator()->getAsString();
895 if (TestName == "and")
896 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
897 else if (TestName == "or")
898 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
899 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
901 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
904 throw TestName + ": unknown edge property!";
907 // Emit code that handles the 'case' construct.
908 // Takes a function object that should emit code for every case clause.
909 // Callback's type is
910 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
911 template <typename F>
912 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
913 F Callback, bool EmitElseIf,
914 const GlobalOptionDescriptions& OptDescs,
916 assert(d->getOperator()->getAsString() == "case");
918 unsigned numArgs = d->getNumArgs();
919 if (d->getNumArgs() < 2)
920 throw "There should be at least one clause in the 'case' expression:\n"
923 for (unsigned i = 0; i != numArgs; ++i) {
924 const DagInit& Test = InitPtrToDag(d->getArg(i));
927 if (Test.getOperator()->getAsString() == "default") {
929 throw std::string("The 'default' clause should be the last in the"
930 "'case' construct!");
931 O << IndentLevel << "else {\n";
934 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
935 EmitCaseTest(Test, IndentLevel, OptDescs, O);
939 // Emit the corresponding statement.
942 throw "Case construct handler: no corresponding action "
943 "found for the test " + Test.getAsString() + '!';
945 Init* arg = d->getArg(i);
946 if (dynamic_cast<DagInit*>(arg)
947 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
948 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
949 (std::string(IndentLevel) + Indent1).c_str(),
950 Callback, EmitElseIf, OptDescs, O);
953 Callback(arg, IndentLevel, O);
955 O << IndentLevel << "}\n";
959 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
960 /// implement EmitOptionPropertyHandlingCode(). Emits code for
961 /// handling the (forward) option property.
962 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
965 case OptionType::Switch:
966 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
968 case OptionType::Parameter:
969 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
970 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
972 case OptionType::Prefix:
973 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
974 << D.GenVariableName() << ");\n";
976 case OptionType::PrefixList:
977 O << Indent3 << "for (" << D.GenTypeDeclaration()
978 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
979 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
980 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
983 case OptionType::ParameterList:
984 O << Indent3 << "for (" << D.GenTypeDeclaration()
985 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
986 << Indent3 << "E = " << D.GenVariableName()
987 << ".end() ; B != E; ++B) {\n"
988 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
989 << Indent4 << "vec.push_back(*B);\n"
992 case OptionType::Alias:
994 throw std::string("Aliases are not allowed in tool option descriptions!");
998 // ToolOptionHasInterestingProperties - A helper function used by
999 // EmitOptionPropertyHandlingCode() that tells us whether we should
1000 // emit any property handling code at all.
1001 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
1003 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1004 E = D.Props.end(); B != E; ++B) {
1005 const OptionProperty& OptProp = *B;
1006 if (OptProp.first == OptionPropertyType::AppendCmd)
1009 if (D.isForward() || D.isUnpackValues())
1014 /// EmitOptionPropertyHandlingCode - Helper function used by
1015 /// EmitGenerateActionMethod(). Emits code that handles option
1017 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
1020 if (!ToolOptionHasInterestingProperties(D))
1022 // Start of the if-clause.
1023 O << Indent2 << "if (";
1024 if (D.Type == OptionType::Switch)
1025 O << D.GenVariableName();
1027 O << '!' << D.GenVariableName() << ".empty()";
1031 // Handle option properties that take an argument.
1032 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1033 E = D.Props.end(); B!=E; ++B) {
1034 const OptionProperty& val = *B;
1036 switch (val.first) {
1037 // (append_cmd cmd) property
1038 case OptionPropertyType::AppendCmd:
1039 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1041 // Other properties with argument
1049 // (forward) property
1051 EmitForwardOptionPropertyHandlingCode(D, O);
1053 // (unpack_values) property
1054 if (D.isUnpackValues()) {
1055 if (IsListOptionType(D.Type)) {
1056 O << Indent3 << "for (" << D.GenTypeDeclaration()
1057 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1058 << Indent3 << "E = " << D.GenVariableName()
1059 << ".end(); B != E; ++B)\n"
1060 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
1062 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
1063 O << Indent3 << "llvm::SplitString("
1064 << D.GenVariableName() << ", vec, \",\");\n";
1067 throw std::string("Switches can't have unpack_values property!");
1071 // End of the if-clause.
1072 O << Indent2 << "}\n";
1075 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1076 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1077 std::string SubstituteSpecialCommands(const std::string& cmd) {
1078 size_t cparen = cmd.find(")");
1081 if (cmd.find("$CALL(") == 0) {
1082 if (cmd.size() == 6)
1083 throw std::string("$CALL invocation: empty argument list!");
1086 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1089 else if (cmd.find("$ENV(") == 0) {
1090 if (cmd.size() == 5)
1091 throw std::string("$ENV invocation: empty argument list!");
1093 ret += "std::getenv(\"";
1094 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1098 throw "Unknown special command: " + cmd;
1101 if (cmd.begin() + cparen + 1 != cmd.end()) {
1102 ret += " + std::string(\"";
1103 ret += (cmd.c_str() + cparen + 1);
1110 /// EmitCmdLineVecFill - Emit code that fills in the command line
1111 /// vector. Helper function used by EmitGenerateActionMethod().
1112 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1113 bool Version, const char* IndentLevel,
1116 SplitString(InitPtrToString(CmdLine), StrVec);
1118 throw "Tool " + ToolName + " has empty command line!";
1120 StrVector::const_iterator I = StrVec.begin();
1122 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1123 const std::string& cmd = *I;
1125 if (cmd.at(0) == '$') {
1126 if (cmd == "$INFILE") {
1128 O << "for (PathVector::const_iterator B = inFiles.begin()"
1129 << ", E = inFiles.end();\n"
1130 << IndentLevel << "B != E; ++B)\n"
1131 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1133 O << "vec.push_back(inFile.toString());\n";
1135 else if (cmd == "$OUTFILE") {
1136 O << "vec.push_back(outFile.toString());\n";
1139 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1144 O << "vec.push_back(\"" << cmd << "\");\n";
1147 O << IndentLevel << "cmd = "
1148 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1149 : "\"" + StrVec[0] + "\"")
1153 /// EmitCmdLineVecFillCallback - A function object wrapper around
1154 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1155 /// argument to EmitCaseConstructHandler().
1156 class EmitCmdLineVecFillCallback {
1158 const std::string& ToolName;
1160 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1161 : Version(Ver), ToolName(TN) {}
1163 void operator()(const Init* Statement, const char* IndentLevel,
1164 std::ostream& O) const
1166 EmitCmdLineVecFill(Statement, ToolName, Version,
1167 (std::string(IndentLevel) + Indent1).c_str(), O);
1171 // EmitGenerateActionMethod - Emit one of two versions of the
1172 // Tool::GenerateAction() method.
1173 void EmitGenerateActionMethod (const ToolProperties& P,
1174 const GlobalOptionDescriptions& OptDescs,
1175 bool Version, std::ostream& O) {
1177 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1179 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1181 O << Indent2 << "const sys::Path& outFile,\n"
1182 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1184 << Indent2 << "const char* cmd;\n"
1185 << Indent2 << "std::vector<std::string> vec;\n";
1187 // cmd_line is either a string or a 'case' construct.
1188 if (typeid(*P.CmdLine) == typeid(StringInit))
1189 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1191 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1192 EmitCmdLineVecFillCallback(Version, P.Name),
1195 // For every understood option, emit handling code.
1196 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1197 E = P.OptDescs.end(); B != E; ++B) {
1198 const ToolOptionDescription& val = B->second;
1199 EmitOptionPropertyHandlingCode(val, O);
1202 // Handle the Sink property.
1204 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1205 << Indent3 << "vec.insert(vec.end(), "
1206 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1207 << Indent2 << "}\n";
1210 O << Indent2 << "return Action(cmd, vec);\n"
1211 << Indent1 << "}\n\n";
1214 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1215 /// a given Tool class.
1216 void EmitGenerateActionMethods (const ToolProperties& P,
1217 const GlobalOptionDescriptions& OptDescs,
1220 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1221 << Indent2 << "const llvm::sys::Path& outFile,\n"
1222 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1224 << Indent2 << "throw std::runtime_error(\"" << P.Name
1225 << " is not a Join tool!\");\n"
1226 << Indent1 << "}\n\n";
1228 EmitGenerateActionMethod(P, OptDescs, true, O);
1230 EmitGenerateActionMethod(P, OptDescs, false, O);
1233 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1235 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1236 O << Indent1 << "bool IsLast() const {\n"
1237 << Indent2 << "bool last = false;\n";
1239 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1240 E = P.OptDescs.end(); B != E; ++B) {
1241 const ToolOptionDescription& val = B->second;
1243 if (val.isStopCompilation())
1245 << "if (" << val.GenVariableName()
1246 << ")\n" << Indent3 << "last = true;\n";
1249 O << Indent2 << "return last;\n"
1250 << Indent1 << "}\n\n";
1253 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1254 /// methods for a given Tool class.
1255 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1256 O << Indent1 << "const char** InputLanguages() const {\n"
1257 << Indent2 << "return InputLanguages_;\n"
1258 << Indent1 << "}\n\n";
1260 O << Indent1 << "const char* OutputLanguage() const {\n"
1261 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1262 << Indent1 << "}\n\n";
1265 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1266 /// given Tool class.
1267 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1268 O << Indent1 << "const char* OutputSuffix() const {\n"
1269 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1271 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1272 E = P.OptDescs.end(); B != E; ++B) {
1273 const ToolOptionDescription& OptDesc = B->second;
1274 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1275 E = OptDesc.Props.end(); B != E; ++B) {
1276 const OptionProperty& OptProp = *B;
1277 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1278 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1279 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1284 O << Indent2 << "return ret;\n"
1285 << Indent1 << "}\n\n";
1288 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1289 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1290 O << Indent1 << "const char* Name() const {\n"
1291 << Indent2 << "return \"" << P.Name << "\";\n"
1292 << Indent1 << "}\n\n";
1295 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1297 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1298 O << Indent1 << "bool IsJoin() const {\n";
1300 O << Indent2 << "return true;\n";
1302 O << Indent2 << "return false;\n";
1303 O << Indent1 << "}\n\n";
1306 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1307 /// given Tool class.
1308 void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1309 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1310 for (StrVector::const_iterator B = P.InLanguage.begin(),
1311 E = P.InLanguage.end(); B != E; ++B)
1312 O << '\"' << *B << "\", ";
1316 /// EmitToolClassDefinition - Emit a Tool class definition.
1317 void EmitToolClassDefinition (const ToolProperties& P,
1318 const GlobalOptionDescriptions& OptDescs,
1320 if (P.Name == "root")
1324 O << "class " << P.Name << " : public ";
1330 O << "{\nprivate:\n"
1331 << Indent1 << "static const char* InputLanguages_[];\n\n";
1334 EmitNameMethod(P, O);
1335 EmitInOutLanguageMethods(P, O);
1336 EmitOutputSuffixMethod(P, O);
1337 EmitIsJoinMethod(P, O);
1338 EmitGenerateActionMethods(P, OptDescs, O);
1339 EmitIsLastMethod(P, O);
1341 // Close class definition
1344 EmitStaticMemberDefinitions(P, O);
1348 /// EmitOptionDescriptions - Iterate over a list of option
1349 /// descriptions and emit registration code.
1350 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1353 std::vector<GlobalOptionDescription> Aliases;
1355 // Emit static cl::Option variables.
1356 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1357 E = descs.end(); B!=E; ++B) {
1358 const GlobalOptionDescription& val = B->second;
1360 if (val.Type == OptionType::Alias) {
1361 Aliases.push_back(val);
1365 O << val.GenTypeDeclaration() << ' '
1366 << val.GenVariableName()
1367 << "(\"" << val.Name << '\"';
1369 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1370 O << ", cl::Prefix";
1372 if (val.isRequired()) {
1374 case OptionType::PrefixList:
1375 case OptionType::ParameterList:
1376 O << ", cl::OneOrMore";
1379 O << ", cl::Required";
1383 if (!val.Help.empty())
1384 O << ", cl::desc(\"" << val.Help << "\")";
1389 // Emit the aliases (they should go after all the 'proper' options).
1390 for (std::vector<GlobalOptionDescription>::const_iterator
1391 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1392 const GlobalOptionDescription& val = *B;
1394 O << val.GenTypeDeclaration() << ' '
1395 << val.GenVariableName()
1396 << "(\"" << val.Name << '\"';
1398 GlobalOptionDescriptions::container_type
1399 ::const_iterator F = descs.Descriptions.find(val.Help);
1400 if (F != descs.Descriptions.end())
1401 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1403 throw val.Name + ": alias to an unknown option!";
1405 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1408 // Emit the sink option.
1410 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1415 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1416 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1418 // Get the relevant field out of RecordKeeper
1419 Record* LangMapRecord = Records.getDef("LanguageMap");
1421 throw std::string("Language map definition not found!");
1423 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1424 if (!LangsToSuffixesList)
1425 throw std::string("Error in the language map definition!");
1428 O << "void llvmc::PopulateLanguageMap() {\n";
1430 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1431 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1433 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1434 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1436 for (unsigned i = 0; i < Suffixes->size(); ++i)
1437 O << Indent1 << "GlobalLanguageMap[\""
1438 << InitPtrToString(Suffixes->getElement(i))
1439 << "\"] = \"" << Lang << "\";\n";
1445 /// FillInToolToLang - Fills in two tables that map tool names to
1446 /// (input, output) languages. Used by the typechecker.
1447 void FillInToolToLang (const ToolPropertiesList& TPList,
1448 StringMap<StringSet<> >& ToolToInLang,
1449 StringMap<std::string>& ToolToOutLang) {
1450 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1452 const ToolProperties& P = *(*B);
1453 for (StrVector::const_iterator B = P.InLanguage.begin(),
1454 E = P.InLanguage.end(); B != E; ++B)
1455 ToolToInLang[P.Name].insert(*B);
1456 ToolToOutLang[P.Name] = P.OutLanguage;
1460 /// TypecheckGraph - Check that names for output and input languages
1461 /// on all edges do match.
1462 // TOFIX: It would be nice if this function also checked for cycles
1463 // and multiple default edges in the graph (better error
1464 // reporting). Unfortunately, it is awkward to do right now because
1465 // our intermediate representation is not sufficiently
1466 // sofisticated. Algorithms like these should be run on a real graph
1468 void TypecheckGraph (Record* CompilationGraph,
1469 const ToolPropertiesList& TPList) {
1470 StringMap<StringSet<> > ToolToInLang;
1471 StringMap<std::string> ToolToOutLang;
1473 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1474 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1475 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1476 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1478 for (unsigned i = 0; i < edges->size(); ++i) {
1479 Record* Edge = edges->getElementAsRecord(i);
1480 Record* A = Edge->getValueAsDef("a");
1481 Record* B = Edge->getValueAsDef("b");
1482 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1483 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1485 throw A->getName() + ": no such tool!";
1487 throw B->getName() + ": no such tool!";
1488 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1489 throw "Edge " + A->getName() + "->" + B->getName()
1490 + ": output->input language mismatch";
1491 if (B->getName() == "root")
1492 throw std::string("Edges back to the root are not allowed!");
1496 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1497 /// by EmitEdgeClass().
1498 void IncDecWeight (const Init* i, const char* IndentLevel,
1500 const DagInit& d = InitPtrToDag(i);
1501 const std::string& OpName = d.getOperator()->getAsString();
1503 if (OpName == "inc_weight")
1504 O << IndentLevel << Indent1 << "ret += ";
1505 else if (OpName == "dec_weight")
1506 O << IndentLevel << Indent1 << "ret -= ";
1508 throw "Unknown operator in edge properties list: " + OpName + '!';
1510 if (d.getNumArgs() > 0)
1511 O << InitPtrToInt(d.getArg(0)) << ";\n";
1517 /// EmitEdgeClass - Emit a single Edge# class.
1518 void EmitEdgeClass (unsigned N, const std::string& Target,
1519 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1522 // Class constructor.
1523 O << "class Edge" << N << ": public Edge {\n"
1525 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1528 // Function Weight().
1529 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1530 << Indent2 << "unsigned ret = 0;\n";
1532 // Handle the 'case' construct.
1533 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1535 O << Indent2 << "return ret;\n"
1536 << Indent1 << "};\n\n};\n\n";
1539 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1540 void EmitEdgeClasses (Record* CompilationGraph,
1541 const GlobalOptionDescriptions& OptDescs,
1543 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1545 for (unsigned i = 0; i < edges->size(); ++i) {
1546 Record* Edge = edges->getElementAsRecord(i);
1547 Record* B = Edge->getValueAsDef("b");
1548 DagInit* Weight = Edge->getValueAsDag("weight");
1550 if (isDagEmpty(Weight))
1553 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1557 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1559 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1562 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1565 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1566 << Indent1 << "PopulateLanguageMap();\n\n";
1570 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1572 throw std::string("No tool definitions found!");
1574 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1575 const std::string& Name = (*B)->getName();
1577 O << Indent1 << "G.insertNode(new "
1578 << Name << "());\n";
1584 for (unsigned i = 0; i < edges->size(); ++i) {
1585 Record* Edge = edges->getElementAsRecord(i);
1586 Record* A = Edge->getValueAsDef("a");
1587 Record* B = Edge->getValueAsDef("b");
1588 DagInit* Weight = Edge->getValueAsDag("weight");
1590 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1592 if (isDagEmpty(Weight))
1593 O << "new SimpleEdge(\"" << B->getName() << "\")";
1595 O << "new Edge" << i << "()";
1603 /// ExtractHookNames - Extract the hook names from all instances of
1604 /// $CALL(HookName) in the provided command line string. Helper
1605 /// function used by FillInHookNames().
1606 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1608 llvm::SplitString(InitPtrToString(CmdLine), cmds);
1609 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1611 const std::string& cmd = *B;
1612 if (cmd.find("$CALL(") == 0) {
1613 if (cmd.size() == 6)
1614 throw std::string("$CALL invocation: empty argument list!");
1615 HookNames.push_back(std::string(cmd.begin() + 6,
1616 cmd.begin() + cmd.find(")")));
1621 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1622 /// 'case' expression, handle nesting. Helper function used by
1623 /// FillInHookNames().
1624 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1625 const DagInit& d = InitPtrToDag(Case);
1627 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1630 if (even && dynamic_cast<DagInit*>(arg)
1631 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1632 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1634 ExtractHookNames(arg, HookNames);
1639 /// FillInHookNames - Actually extract the hook names from all command
1640 /// line strings. Helper function used by EmitHookDeclarations().
1641 void FillInHookNames(const ToolPropertiesList& TPList,
1642 StrVector& HookNames) {
1643 // For all command lines:
1644 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1645 E = TPList.end(); B != E; ++B) {
1646 const ToolProperties& P = *(*B);
1649 if (dynamic_cast<StringInit*>(P.CmdLine))
1650 // This is a string.
1651 ExtractHookNames(P.CmdLine, HookNames);
1653 // This is a 'case' construct.
1654 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1658 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1659 /// property records and emit hook function declaration for each
1660 /// instance of $CALL(HookName).
1661 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1663 StrVector HookNames;
1664 FillInHookNames(ToolProps, HookNames);
1665 if (HookNames.empty())
1667 std::sort(HookNames.begin(), HookNames.end());
1668 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1670 O << "namespace hooks {\n";
1671 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1672 O << Indent1 << "std::string " << *B << "();\n";
1677 // End of anonymous namespace
1680 /// run - The back-end entry point.
1681 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1684 // Emit file header.
1685 EmitSourceFileHeader("LLVMC Configuration Library", O);
1687 // Get a list of all defined Tools.
1688 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1690 throw std::string("No tool definitions found!");
1692 // Gather information from the Tool description dags.
1693 ToolPropertiesList tool_props;
1694 GlobalOptionDescriptions opt_descs;
1695 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1697 RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1698 CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1701 // Check that there are no options without side effects (specified
1702 // only in the OptionList).
1703 CheckForSuperfluousOptions(tool_props, opt_descs);
1705 // Emit global option registration code.
1706 EmitOptionDescriptions(opt_descs, O);
1708 // Emit hook declarations.
1709 EmitHookDeclarations(tool_props, O);
1711 // Emit PopulateLanguageMap() function
1712 // (a language map maps from file extensions to language names).
1713 EmitPopulateLanguageMap(Records, O);
1715 // Emit Tool classes.
1716 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1717 E = tool_props.end(); B!=E; ++B)
1718 EmitToolClassDefinition(*(*B), opt_descs, O);
1720 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1721 if (!CompilationGraphRecord)
1722 throw std::string("Compilation graph description not found!");
1724 // Typecheck the compilation graph.
1725 TypecheckGraph(CompilationGraphRecord, tool_props);
1727 // Emit Edge# classes.
1728 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1730 // Emit PopulateCompilationGraph() function.
1731 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1734 } catch (std::exception& Error) {
1735 throw Error.what() + std::string(" - usually this means a syntax error.");