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"
33 //===----------------------------------------------------------------------===//
36 typedef std::vector<Record*> RecordVector;
37 typedef std::vector<std::string> StrVector;
39 //===----------------------------------------------------------------------===//
42 // Indentation strings.
43 const char * Indent1 = " ";
44 const char * Indent2 = " ";
45 const char * Indent3 = " ";
46 const char * Indent4 = " ";
48 // Default help string.
49 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51 // Name for the "sink" option.
52 const char * SinkOptionName = "AutoGeneratedSinkOption";
54 //===----------------------------------------------------------------------===//
57 int InitPtrToInt(const Init* ptr) {
58 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
59 return val.getValue();
62 const std::string& InitPtrToString(const Init* ptr) {
63 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
64 return val.getValue();
67 const ListInit& InitPtrToList(const Init* ptr) {
68 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
72 const DagInit& InitPtrToDag(const Init* ptr) {
73 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
77 // checkNumberOfArguments - Ensure that the number of args in d is
78 // less than or equal to min_arguments, otherwise throw an exception.
79 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
80 if (d->getNumArgs() < min_arguments)
81 throw "Property " + d->getOperator()->getAsString()
82 + " has too few arguments!";
85 // isDagEmpty - is this DAG marked with an empty marker?
86 bool isDagEmpty (const DagInit* d) {
87 return d->getOperator()->getAsString() == "empty";
90 //===----------------------------------------------------------------------===//
91 /// Back-end specific code
93 // A command-line option can have one of the following types:
95 // Alias - an alias for another option.
97 // Switch - a simple switch without arguments, e.g. -O2
99 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
102 // ParameterList - same as Parameter, but more than one occurence
103 // of the option is allowed, e.g. -lm -lpthread
105 // Prefix - argument is everything after the prefix,
106 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
108 // PrefixList - same as Prefix, but more than one option occurence is
111 namespace OptionType {
112 enum OptionType { Alias, Switch,
113 Parameter, ParameterList, Prefix, PrefixList};
116 bool IsListOptionType (OptionType::OptionType t) {
117 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
120 // Code duplication here is necessary because one option can affect
121 // several tools and those tools may have different actions associated
122 // with this option. GlobalOptionDescriptions are used to generate
123 // the option registration code, while ToolOptionDescriptions are used
124 // to generate tool-specific code.
126 /// OptionDescription - Base class for option descriptions.
127 struct OptionDescription {
128 OptionType::OptionType Type;
131 OptionDescription(OptionType::OptionType t = OptionType::Switch,
132 const std::string& n = "")
136 const char* GenTypeDeclaration() const {
138 case OptionType::Alias:
140 case OptionType::PrefixList:
141 case OptionType::ParameterList:
142 return "cl::list<std::string>";
143 case OptionType::Switch:
144 return "cl::opt<bool>";
145 case OptionType::Parameter:
146 case OptionType::Prefix:
148 return "cl::opt<std::string>";
152 // Escape commas and other symbols not allowed in the C++ variable
153 // names. Makes it possible to use options with names like "Wa,"
154 // (useful for prefix options).
155 std::string EscapeVariableName(const std::string& Var) const {
157 for (unsigned i = 0; i != Var.size(); ++i) {
158 char cur_char = Var[i];
159 if (cur_char == ',') {
162 else if (cur_char == '+') {
165 else if (cur_char == ',') {
169 ret.push_back(cur_char);
175 std::string GenVariableName() const {
176 const std::string& EscapedName = EscapeVariableName(Name);
178 case OptionType::Alias:
179 return "AutoGeneratedAlias" + EscapedName;
180 case OptionType::Switch:
181 return "AutoGeneratedSwitch" + EscapedName;
182 case OptionType::Prefix:
183 return "AutoGeneratedPrefix" + EscapedName;
184 case OptionType::PrefixList:
185 return "AutoGeneratedPrefixList" + EscapedName;
186 case OptionType::Parameter:
187 return "AutoGeneratedParameter" + EscapedName;
188 case OptionType::ParameterList:
190 return "AutoGeneratedParameterList" + EscapedName;
196 // Global option description.
198 namespace GlobalOptionDescriptionFlags {
199 enum GlobalOptionDescriptionFlags { Required = 0x1 };
202 struct GlobalOptionDescription : public OptionDescription {
206 // We need to provide a default constructor because
207 // StringMap can only store DefaultConstructible objects.
208 GlobalOptionDescription() : OptionDescription(), Flags(0)
211 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
212 const std::string& h = DefaultHelpString)
213 : OptionDescription(t, n), Help(h), Flags(0)
216 bool isRequired() const {
217 return Flags & GlobalOptionDescriptionFlags::Required;
220 Flags |= GlobalOptionDescriptionFlags::Required;
223 /// Merge - Merge two option descriptions.
224 void Merge (const GlobalOptionDescription& other)
226 if (other.Type != Type)
227 throw "Conflicting definitions for the option " + Name + "!";
229 if (Help == DefaultHelpString)
231 else if (other.Help != DefaultHelpString) {
232 llvm::cerr << "Warning: more than one help string defined for option "
236 Flags |= other.Flags;
240 /// GlobalOptionDescriptions - A GlobalOptionDescription array
241 /// together with some flags affecting generation of option
243 struct GlobalOptionDescriptions {
244 typedef StringMap<GlobalOptionDescription> container_type;
245 typedef container_type::const_iterator const_iterator;
247 /// Descriptions - A list of GlobalOptionDescriptions.
248 container_type Descriptions;
249 /// HasSink - Should the emitter generate a "cl::sink" option?
252 /// FindOption - exception-throwing wrapper for find().
253 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
254 const_iterator I = Descriptions.find(OptName);
255 if (I != Descriptions.end())
258 throw OptName + ": no such option!";
261 /// insertDescription - Insert new GlobalOptionDescription into
262 /// GlobalOptionDescriptions list
263 void insertDescription (const GlobalOptionDescription& o)
265 container_type::iterator I = Descriptions.find(o.Name);
266 if (I != Descriptions.end()) {
267 GlobalOptionDescription& D = I->second;
271 Descriptions[o.Name] = o;
275 // Support for STL-style iteration
276 const_iterator begin() const { return Descriptions.begin(); }
277 const_iterator end() const { return Descriptions.end(); }
281 // Tool-local option description.
283 // Properties without arguments are implemented as flags.
284 namespace ToolOptionDescriptionFlags {
285 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
286 Forward = 0x2, UnpackValues = 0x4};
288 namespace OptionPropertyType {
289 enum OptionPropertyType { AppendCmd, ForwardAs, OutputSuffix };
292 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
294 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
296 struct ToolOptionDescription : public OptionDescription {
298 OptionPropertyList Props;
300 // StringMap can only store DefaultConstructible objects
301 ToolOptionDescription() : OptionDescription(), Flags(0) {}
303 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
304 : OptionDescription(t, n)
307 // Various boolean properties
308 bool isStopCompilation() const {
309 return Flags & ToolOptionDescriptionFlags::StopCompilation;
311 void setStopCompilation() {
312 Flags |= ToolOptionDescriptionFlags::StopCompilation;
315 bool isForward() const {
316 return Flags & ToolOptionDescriptionFlags::Forward;
319 Flags |= ToolOptionDescriptionFlags::Forward;
322 bool isUnpackValues() const {
323 return Flags & ToolOptionDescriptionFlags::UnpackValues;
325 void setUnpackValues() {
326 Flags |= ToolOptionDescriptionFlags::UnpackValues;
329 void AddProperty (OptionPropertyType::OptionPropertyType t,
330 const std::string& val)
332 Props.push_back(std::make_pair(t, val));
336 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
338 // Tool information record
340 namespace ToolFlags {
341 enum ToolFlags { Join = 0x1, Sink = 0x2 };
344 struct ToolProperties : public RefCountedBase<ToolProperties> {
347 StrVector InLanguage;
348 std::string OutLanguage;
349 std::string OutputSuffix;
351 ToolOptionDescriptions OptDescs;
353 // Various boolean properties
354 void setSink() { Flags |= ToolFlags::Sink; }
355 bool isSink() const { return Flags & ToolFlags::Sink; }
356 void setJoin() { Flags |= ToolFlags::Join; }
357 bool isJoin() const { return Flags & ToolFlags::Join; }
359 // Default ctor here is needed because StringMap can only store
360 // DefaultConstructible objects
361 ToolProperties() : CmdLine(0), Flags(0) {}
362 ToolProperties (const std::string& n) : Name(n), CmdLine(0), Flags(0) {}
366 /// ToolPropertiesList - A list of Tool information records
367 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
368 /// constructor (and we want to avoid copying ToolProperties anyway).
369 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
372 /// CollectOptionProperties - Function object for iterating over a
373 /// list (usually, a DAG) of option property records.
374 class CollectOptionProperties {
376 // Implementation details.
378 /// OptionPropertyHandler - a function that extracts information
379 /// about a given option property from its DAG representation.
380 typedef void (CollectOptionProperties::* OptionPropertyHandler)
383 /// OptionPropertyHandlerMap - A map from option property names to
384 /// option property handlers
385 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
387 static OptionPropertyHandlerMap optionPropertyHandlers_;
388 static bool staticMembersInitialized_;
390 /// This is where the information is stored
392 /// toolProps_ - Properties of the current Tool.
393 ToolProperties* toolProps_;
394 /// optDescs_ - OptionDescriptions table (used to register options
396 GlobalOptionDescription& optDesc_;
400 explicit CollectOptionProperties(ToolProperties* TP,
401 GlobalOptionDescription& OD)
402 : toolProps_(TP), optDesc_(OD)
404 if (!staticMembersInitialized_) {
405 optionPropertyHandlers_["append_cmd"] =
406 &CollectOptionProperties::onAppendCmd;
407 optionPropertyHandlers_["forward"] =
408 &CollectOptionProperties::onForward;
409 optionPropertyHandlers_["forward_as"] =
410 &CollectOptionProperties::onForwardAs;
411 optionPropertyHandlers_["help"] =
412 &CollectOptionProperties::onHelp;
413 optionPropertyHandlers_["output_suffix"] =
414 &CollectOptionProperties::onOutputSuffix;
415 optionPropertyHandlers_["required"] =
416 &CollectOptionProperties::onRequired;
417 optionPropertyHandlers_["stop_compilation"] =
418 &CollectOptionProperties::onStopCompilation;
419 optionPropertyHandlers_["unpack_values"] =
420 &CollectOptionProperties::onUnpackValues;
422 staticMembersInitialized_ = true;
426 /// operator() - Gets called for every option property; Just forwards
427 /// to the corresponding property handler.
428 void operator() (Init* i) {
429 const DagInit& option_property = InitPtrToDag(i);
430 const std::string& option_property_name
431 = option_property.getOperator()->getAsString();
432 OptionPropertyHandlerMap::iterator method
433 = optionPropertyHandlers_.find(option_property_name);
435 if (method != optionPropertyHandlers_.end()) {
436 OptionPropertyHandler h = method->second;
437 (this->*h)(&option_property);
440 throw "Unknown option property: " + option_property_name + "!";
446 /// Option property handlers --
447 /// Methods that handle properties that are common for all types of
448 /// options (like append_cmd, stop_compilation)
450 void onAppendCmd (const DagInit* d) {
451 checkNumberOfArguments(d, 1);
453 const std::string& cmd = InitPtrToString(d->getArg(0));
455 toolProps_->OptDescs[optDesc_.Name].
456 AddProperty(OptionPropertyType::AppendCmd, cmd);
459 void onOutputSuffix (const DagInit* d) {
460 checkNumberOfArguments(d, 1);
462 const std::string& suf = InitPtrToString(d->getArg(0));
464 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
465 throw "Option " + optDesc_.Name
466 + " can't have 'output_suffix' property since it isn't a switch!";
468 toolProps_->OptDescs[optDesc_.Name].AddProperty
469 (OptionPropertyType::OutputSuffix, suf);
472 void onForward (const DagInit* d) {
473 checkNumberOfArguments(d, 0);
475 toolProps_->OptDescs[optDesc_.Name].setForward();
478 void onForwardAs (const DagInit* d) {
479 checkNumberOfArguments(d, 1);
481 const std::string& cmd = InitPtrToString(d->getArg(0));
483 toolProps_->OptDescs[optDesc_.Name].
484 AddProperty(OptionPropertyType::ForwardAs, cmd);
487 void onHelp (const DagInit* d) {
488 checkNumberOfArguments(d, 1);
489 const std::string& help_message = InitPtrToString(d->getArg(0));
491 optDesc_.Help = help_message;
494 void onRequired (const DagInit* d) {
495 checkNumberOfArguments(d, 0);
497 optDesc_.setRequired();
500 void onStopCompilation (const DagInit* d) {
501 checkNumberOfArguments(d, 0);
503 if (optDesc_.Type != OptionType::Switch)
504 throw std::string("Only options of type Switch can stop compilation!");
505 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
508 void onUnpackValues (const DagInit* d) {
509 checkNumberOfArguments(d, 0);
511 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
516 /// checkToolProps - Throw an error if toolProps_ == 0.
517 void checkToolProps(const DagInit* d) {
519 throw "Option property " + d->getOperator()->getAsString()
520 + " can't be used in this context";
525 CollectOptionProperties::OptionPropertyHandlerMap
526 CollectOptionProperties::optionPropertyHandlers_;
528 bool CollectOptionProperties::staticMembersInitialized_ = false;
531 /// processOptionProperties - Go through the list of option
532 /// properties and call a corresponding handler for each.
533 void processOptionProperties (const DagInit* d, ToolProperties* t,
534 GlobalOptionDescription& o) {
535 checkNumberOfArguments(d, 2);
536 DagInit::const_arg_iterator B = d->arg_begin();
537 // Skip the first argument: it's always the option name.
539 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
542 /// AddOption - A function object wrapper for
543 /// processOptionProperties. Used by CollectProperties and
544 /// CollectPropertiesFromOptionList.
547 GlobalOptionDescriptions& OptDescs_;
548 ToolProperties* ToolProps_;
551 explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
552 : OptDescs_(OD), ToolProps_(TP)
555 void operator()(const Init* i) {
556 const DagInit& d = InitPtrToDag(i);
557 checkNumberOfArguments(&d, 2);
559 const OptionType::OptionType Type =
560 getOptionType(d.getOperator()->getAsString());
561 const std::string& Name = InitPtrToString(d.getArg(0));
563 GlobalOptionDescription OD(Type, Name);
564 if (Type != OptionType::Alias) {
565 processOptionProperties(&d, ToolProps_, OD);
567 ToolProps_->OptDescs[Name].Type = Type;
568 ToolProps_->OptDescs[Name].Name = Name;
572 OD.Help = InitPtrToString(d.getArg(1));
574 OptDescs_.insertDescription(OD);
578 OptionType::OptionType getOptionType(const std::string& T) const {
579 if (T == "alias_option")
580 return OptionType::Alias;
581 else if (T == "switch_option")
582 return OptionType::Switch;
583 else if (T == "parameter_option")
584 return OptionType::Parameter;
585 else if (T == "parameter_list_option")
586 return OptionType::ParameterList;
587 else if (T == "prefix_option")
588 return OptionType::Prefix;
589 else if (T == "prefix_list_option")
590 return OptionType::PrefixList;
592 throw "Unknown option type: " + T + '!';
597 /// CollectProperties - Function object for iterating over a list of
598 /// tool property records.
599 class CollectProperties {
602 // Implementation details
604 /// PropertyHandler - a function that extracts information
605 /// about a given tool property from its DAG representation
606 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
608 /// PropertyHandlerMap - A map from property names to property
610 typedef StringMap<PropertyHandler> PropertyHandlerMap;
612 // Static maps from strings to CollectProperties methods("handlers")
613 static PropertyHandlerMap propertyHandlers_;
614 static bool staticMembersInitialized_;
617 /// This is where the information is stored
619 /// toolProps_ - Properties of the current Tool.
620 ToolProperties& toolProps_;
621 /// optDescs_ - OptionDescriptions table (used to register options
623 GlobalOptionDescriptions& optDescs_;
627 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
628 : toolProps_(p), optDescs_(d)
630 if (!staticMembersInitialized_) {
631 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
632 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
633 propertyHandlers_["join"] = &CollectProperties::onJoin;
634 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
635 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
636 propertyHandlers_["parameter_option"]
637 = &CollectProperties::addOption;
638 propertyHandlers_["parameter_list_option"] =
639 &CollectProperties::addOption;
640 propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
641 propertyHandlers_["prefix_list_option"] =
642 &CollectProperties::addOption;
643 propertyHandlers_["sink"] = &CollectProperties::onSink;
644 propertyHandlers_["switch_option"] = &CollectProperties::addOption;
645 propertyHandlers_["alias_option"] = &CollectProperties::addOption;
647 staticMembersInitialized_ = true;
651 /// operator() - Gets called for every tool property; Just forwards
652 /// to the corresponding property handler.
653 void operator() (Init* i) {
654 const DagInit& d = InitPtrToDag(i);
655 const std::string& property_name = d.getOperator()->getAsString();
656 PropertyHandlerMap::iterator method
657 = propertyHandlers_.find(property_name);
659 if (method != propertyHandlers_.end()) {
660 PropertyHandler h = method->second;
664 throw "Unknown tool property: " + property_name + "!";
670 /// Property handlers --
671 /// Functions that extract information about tool properties from
672 /// DAG representation.
674 void onCmdLine (const DagInit* d) {
675 checkNumberOfArguments(d, 1);
676 toolProps_.CmdLine = d->getArg(0);
679 void onInLanguage (const DagInit* d) {
680 checkNumberOfArguments(d, 1);
681 Init* arg = d->getArg(0);
683 // Find out the argument's type.
684 if (typeid(*arg) == typeid(StringInit)) {
686 toolProps_.InLanguage.push_back(InitPtrToString(arg));
690 const ListInit& lst = InitPtrToList(arg);
691 StrVector& out = toolProps_.InLanguage;
693 // Copy strings to the output vector.
694 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
696 out.push_back(InitPtrToString(*B));
699 // Remove duplicates.
700 std::sort(out.begin(), out.end());
701 StrVector::iterator newE = std::unique(out.begin(), out.end());
702 out.erase(newE, out.end());
706 void onJoin (const DagInit* d) {
707 checkNumberOfArguments(d, 0);
708 toolProps_.setJoin();
711 void onOutLanguage (const DagInit* d) {
712 checkNumberOfArguments(d, 1);
713 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
716 void onOutputSuffix (const DagInit* d) {
717 checkNumberOfArguments(d, 1);
718 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
721 void onSink (const DagInit* d) {
722 checkNumberOfArguments(d, 0);
723 optDescs_.HasSink = true;
724 toolProps_.setSink();
727 // Just forwards to the AddOption function object. Somewhat
728 // non-optimal, but avoids code duplication.
729 void addOption (const DagInit* d) {
730 checkNumberOfArguments(d, 2);
731 AddOption(optDescs_, &toolProps_)(d);
736 // Defintions of static members of CollectProperties.
737 CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
738 bool CollectProperties::staticMembersInitialized_ = false;
741 /// CollectToolProperties - Gather information about tool properties
742 /// from the parsed TableGen data (basically a wrapper for the
743 /// CollectProperties function object).
744 void CollectToolProperties (RecordVector::const_iterator B,
745 RecordVector::const_iterator E,
746 ToolPropertiesList& TPList,
747 GlobalOptionDescriptions& OptDescs)
749 // Iterate over a properties list of every Tool definition
752 // Throws an exception if the value does not exist.
753 ListInit* PropList = T->getValueAsListInit("properties");
755 IntrusiveRefCntPtr<ToolProperties>
756 ToolProps(new ToolProperties(T->getName()));
758 std::for_each(PropList->begin(), PropList->end(),
759 CollectProperties(*ToolProps, OptDescs));
760 TPList.push_back(ToolProps);
765 /// CollectPropertiesFromOptionList - Gather information about
766 /// *global* option properties from the OptionList.
767 void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
768 RecordVector::const_iterator E,
769 GlobalOptionDescriptions& OptDescs)
771 // Iterate over a properties list of every Tool definition
773 RecordVector::value_type T = *B;
774 // Throws an exception if the value does not exist.
775 ListInit* PropList = T->getValueAsListInit("options");
777 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
781 /// CheckForSuperfluousOptions - Check that there are no side
782 /// effect-free options (specified only in the OptionList). Otherwise,
783 /// output a warning.
784 void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
785 const GlobalOptionDescriptions& OptDescs) {
786 llvm::StringSet<> nonSuperfluousOptions;
788 // Add all options mentioned in the TPList to the set of
789 // non-superfluous options.
790 for (ToolPropertiesList::const_iterator B = TPList.begin(),
791 E = TPList.end(); B != E; ++B) {
792 const ToolProperties& TP = *(*B);
793 for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
794 E = TP.OptDescs.end(); B != E; ++B) {
795 nonSuperfluousOptions.insert(B->first());
799 // Check that all options in OptDescs belong to the set of
800 // non-superfluous options.
801 for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
802 E = OptDescs.end(); B != E; ++B) {
803 const GlobalOptionDescription& Val = B->second;
804 if (!nonSuperfluousOptions.count(Val.Name)
805 && Val.Type != OptionType::Alias)
806 cerr << "Warning: option '-" << Val.Name << "' has no effect! "
807 "Probable cause: this option is specified only in the OptionList.\n";
811 /// EmitCaseTest1Arg - Helper function used by
812 /// EmitCaseConstructHandler.
813 bool EmitCaseTest1Arg(const std::string& TestName,
815 const GlobalOptionDescriptions& OptDescs,
817 checkNumberOfArguments(&d, 1);
818 const std::string& OptName = InitPtrToString(d.getArg(0));
819 if (TestName == "switch_on") {
820 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
821 if (OptDesc.Type != OptionType::Switch)
822 throw OptName + ": incorrect option type!";
823 O << OptDesc.GenVariableName();
825 } else if (TestName == "input_languages_contain") {
826 O << "InLangs.count(\"" << OptName << "\") != 0";
828 } else if (TestName == "in_language") {
829 // Works only for cmd_line!
830 O << "GetLanguage(inFile) == \"" << OptName << '\"';
832 } else if (TestName == "not_empty") {
833 if (OptName == "o") {
834 O << "!OutputFilename.empty()";
838 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
839 if (OptDesc.Type == OptionType::Switch)
840 throw OptName + ": incorrect option type!";
841 O << '!' << OptDesc.GenVariableName() << ".empty()";
849 /// EmitCaseTest2Args - Helper function used by
850 /// EmitCaseConstructHandler.
851 bool EmitCaseTest2Args(const std::string& TestName,
853 const char* IndentLevel,
854 const GlobalOptionDescriptions& OptDescs,
856 checkNumberOfArguments(&d, 2);
857 const std::string& OptName = InitPtrToString(d.getArg(0));
858 const std::string& OptArg = InitPtrToString(d.getArg(1));
859 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
861 if (TestName == "parameter_equals") {
862 if (OptDesc.Type != OptionType::Parameter
863 && OptDesc.Type != OptionType::Prefix)
864 throw OptName + ": incorrect option type!";
865 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
868 else if (TestName == "element_in_list") {
869 if (OptDesc.Type != OptionType::ParameterList
870 && OptDesc.Type != OptionType::PrefixList)
871 throw OptName + ": incorrect option type!";
872 const std::string& VarName = OptDesc.GenVariableName();
873 O << "std::find(" << VarName << ".begin(),\n"
874 << IndentLevel << Indent1 << VarName << ".end(), \""
875 << OptArg << "\") != " << VarName << ".end()";
882 // Forward declaration.
883 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
884 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
885 const GlobalOptionDescriptions& OptDescs,
888 /// EmitLogicalOperationTest - Helper function used by
889 /// EmitCaseConstructHandler.
890 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
891 const char* IndentLevel,
892 const GlobalOptionDescriptions& OptDescs,
895 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
896 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
897 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
898 if (j != NumArgs - 1)
899 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
905 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
906 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
907 const GlobalOptionDescriptions& OptDescs,
909 const std::string& TestName = d.getOperator()->getAsString();
911 if (TestName == "and")
912 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
913 else if (TestName == "or")
914 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
915 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
917 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
920 throw TestName + ": unknown edge property!";
923 // Emit code that handles the 'case' construct.
924 // Takes a function object that should emit code for every case clause.
925 // Callback's type is
926 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
927 template <typename F>
928 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
929 F Callback, bool EmitElseIf,
930 const GlobalOptionDescriptions& OptDescs,
932 assert(d->getOperator()->getAsString() == "case");
934 unsigned numArgs = d->getNumArgs();
935 if (d->getNumArgs() < 2)
936 throw "There should be at least one clause in the 'case' expression:\n"
939 for (unsigned i = 0; i != numArgs; ++i) {
940 const DagInit& Test = InitPtrToDag(d->getArg(i));
943 if (Test.getOperator()->getAsString() == "default") {
945 throw std::string("The 'default' clause should be the last in the"
946 "'case' construct!");
947 O << IndentLevel << "else {\n";
950 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
951 EmitCaseTest(Test, IndentLevel, OptDescs, O);
955 // Emit the corresponding statement.
958 throw "Case construct handler: no corresponding action "
959 "found for the test " + Test.getAsString() + '!';
961 Init* arg = d->getArg(i);
962 if (dynamic_cast<DagInit*>(arg)
963 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
964 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
965 (std::string(IndentLevel) + Indent1).c_str(),
966 Callback, EmitElseIf, OptDescs, O);
969 Callback(arg, IndentLevel, O);
971 O << IndentLevel << "}\n";
975 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
976 /// implement EmitOptionPropertyHandlingCode(). Emits code for
977 /// handling the (forward) and (forward_as) option properties.
978 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
979 const std::string& NewName,
981 const std::string& Name = NewName.empty()
986 case OptionType::Switch:
987 O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
989 case OptionType::Parameter:
990 O << Indent3 << "vec.push_back(\"" << Name << "\");\n";
991 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
993 case OptionType::Prefix:
994 O << Indent3 << "vec.push_back(\"" << Name << "\" + "
995 << D.GenVariableName() << ");\n";
997 case OptionType::PrefixList:
998 O << Indent3 << "for (" << D.GenTypeDeclaration()
999 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1000 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
1001 << Indent4 << "vec.push_back(\"" << Name << "\" + "
1004 case OptionType::ParameterList:
1005 O << Indent3 << "for (" << D.GenTypeDeclaration()
1006 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1007 << Indent3 << "E = " << D.GenVariableName()
1008 << ".end() ; B != E; ++B) {\n"
1009 << Indent4 << "vec.push_back(\"" << Name << "\");\n"
1010 << Indent4 << "vec.push_back(*B);\n"
1011 << Indent3 << "}\n";
1013 case OptionType::Alias:
1015 throw std::string("Aliases are not allowed in tool option descriptions!");
1019 // ToolOptionHasInterestingProperties - A helper function used by
1020 // EmitOptionPropertyHandlingCode() that tells us whether we should
1021 // emit any property handling code at all.
1022 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
1024 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1025 E = D.Props.end(); B != E; ++B) {
1026 const OptionProperty& OptProp = *B;
1027 if (OptProp.first == OptionPropertyType::AppendCmd
1028 || OptProp.first == OptionPropertyType::ForwardAs)
1031 if (D.isForward() || D.isUnpackValues())
1036 /// EmitOptionPropertyHandlingCode - Helper function used by
1037 /// EmitGenerateActionMethod(). Emits code that handles option
1039 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
1042 if (!ToolOptionHasInterestingProperties(D))
1044 // Start of the if-clause.
1045 O << Indent2 << "if (";
1046 if (D.Type == OptionType::Switch)
1047 O << D.GenVariableName();
1049 O << '!' << D.GenVariableName() << ".empty()";
1053 // Handle option properties that take an argument.
1054 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1055 E = D.Props.end(); B!=E; ++B) {
1056 const OptionProperty& val = *B;
1058 switch (val.first) {
1059 // (append_cmd cmd) property
1060 case OptionPropertyType::AppendCmd:
1061 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1063 // (forward_as) property
1064 case OptionPropertyType::ForwardAs:
1065 EmitForwardOptionPropertyHandlingCode(D, val.second, O);
1067 // Other properties with argument
1075 // (forward) property
1077 EmitForwardOptionPropertyHandlingCode(D, "", O);
1079 // (unpack_values) property
1080 if (D.isUnpackValues()) {
1081 if (IsListOptionType(D.Type)) {
1082 O << Indent3 << "for (" << D.GenTypeDeclaration()
1083 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1084 << Indent3 << "E = " << D.GenVariableName()
1085 << ".end(); B != E; ++B)\n"
1086 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
1088 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
1089 O << Indent3 << "llvm::SplitString("
1090 << D.GenVariableName() << ", vec, \",\");\n";
1093 throw std::string("Switches can't have unpack_values property!");
1097 // End of the if-clause.
1098 O << Indent2 << "}\n";
1101 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1102 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1103 std::string SubstituteSpecialCommands(const std::string& cmd) {
1104 size_t cparen = cmd.find(")");
1107 if (cmd.find("$CALL(") == 0) {
1108 if (cmd.size() == 6)
1109 throw std::string("$CALL invocation: empty argument list!");
1112 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1115 else if (cmd.find("$ENV(") == 0) {
1116 if (cmd.size() == 5)
1117 throw std::string("$ENV invocation: empty argument list!");
1119 ret += "std::getenv(\"";
1120 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1124 throw "Unknown special command: " + cmd;
1127 if (cmd.begin() + cparen + 1 != cmd.end()) {
1128 ret += " + std::string(\"";
1129 ret += (cmd.c_str() + cparen + 1);
1136 /// EmitCmdLineVecFill - Emit code that fills in the command line
1137 /// vector. Helper function used by EmitGenerateActionMethod().
1138 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1139 bool Version, const char* IndentLevel,
1142 SplitString(InitPtrToString(CmdLine), StrVec);
1144 throw "Tool " + ToolName + " has empty command line!";
1146 StrVector::const_iterator I = StrVec.begin();
1148 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1149 const std::string& cmd = *I;
1151 if (cmd.at(0) == '$') {
1152 if (cmd == "$INFILE") {
1154 O << "for (PathVector::const_iterator B = inFiles.begin()"
1155 << ", E = inFiles.end();\n"
1156 << IndentLevel << "B != E; ++B)\n"
1157 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1159 O << "vec.push_back(inFile.toString());\n";
1161 else if (cmd == "$OUTFILE") {
1162 O << "vec.push_back(outFile.toString());\n";
1165 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1170 O << "vec.push_back(\"" << cmd << "\");\n";
1173 O << IndentLevel << "cmd = "
1174 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1175 : "\"" + StrVec[0] + "\"")
1179 /// EmitCmdLineVecFillCallback - A function object wrapper around
1180 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1181 /// argument to EmitCaseConstructHandler().
1182 class EmitCmdLineVecFillCallback {
1184 const std::string& ToolName;
1186 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1187 : Version(Ver), ToolName(TN) {}
1189 void operator()(const Init* Statement, const char* IndentLevel,
1190 std::ostream& O) const
1192 EmitCmdLineVecFill(Statement, ToolName, Version,
1193 (std::string(IndentLevel) + Indent1).c_str(), O);
1197 // EmitGenerateActionMethod - Emit one of two versions of the
1198 // Tool::GenerateAction() method.
1199 void EmitGenerateActionMethod (const ToolProperties& P,
1200 const GlobalOptionDescriptions& OptDescs,
1201 bool Version, std::ostream& O) {
1203 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1205 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1207 O << Indent2 << "const sys::Path& outFile,\n"
1208 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1210 << Indent2 << "const char* cmd;\n"
1211 << Indent2 << "std::vector<std::string> vec;\n";
1213 // cmd_line is either a string or a 'case' construct.
1214 if (typeid(*P.CmdLine) == typeid(StringInit))
1215 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1217 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1218 EmitCmdLineVecFillCallback(Version, P.Name),
1221 // For every understood option, emit handling code.
1222 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1223 E = P.OptDescs.end(); B != E; ++B) {
1224 const ToolOptionDescription& val = B->second;
1225 EmitOptionPropertyHandlingCode(val, O);
1228 // Handle the Sink property.
1230 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1231 << Indent3 << "vec.insert(vec.end(), "
1232 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1233 << Indent2 << "}\n";
1236 O << Indent2 << "return Action(cmd, vec);\n"
1237 << Indent1 << "}\n\n";
1240 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1241 /// a given Tool class.
1242 void EmitGenerateActionMethods (const ToolProperties& P,
1243 const GlobalOptionDescriptions& OptDescs,
1246 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1247 << Indent2 << "const llvm::sys::Path& outFile,\n"
1248 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1250 << Indent2 << "throw std::runtime_error(\"" << P.Name
1251 << " is not a Join tool!\");\n"
1252 << Indent1 << "}\n\n";
1254 EmitGenerateActionMethod(P, OptDescs, true, O);
1256 EmitGenerateActionMethod(P, OptDescs, false, O);
1259 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1261 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1262 O << Indent1 << "bool IsLast() const {\n"
1263 << Indent2 << "bool last = false;\n";
1265 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1266 E = P.OptDescs.end(); B != E; ++B) {
1267 const ToolOptionDescription& val = B->second;
1269 if (val.isStopCompilation())
1271 << "if (" << val.GenVariableName()
1272 << ")\n" << Indent3 << "last = true;\n";
1275 O << Indent2 << "return last;\n"
1276 << Indent1 << "}\n\n";
1279 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1280 /// methods for a given Tool class.
1281 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1282 O << Indent1 << "const char** InputLanguages() const {\n"
1283 << Indent2 << "return InputLanguages_;\n"
1284 << Indent1 << "}\n\n";
1286 O << Indent1 << "const char* OutputLanguage() const {\n"
1287 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1288 << Indent1 << "}\n\n";
1291 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1292 /// given Tool class.
1293 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1294 O << Indent1 << "const char* OutputSuffix() const {\n"
1295 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1297 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1298 E = P.OptDescs.end(); B != E; ++B) {
1299 const ToolOptionDescription& OptDesc = B->second;
1300 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1301 E = OptDesc.Props.end(); B != E; ++B) {
1302 const OptionProperty& OptProp = *B;
1303 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1304 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1305 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1310 O << Indent2 << "return ret;\n"
1311 << Indent1 << "}\n\n";
1314 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1315 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1316 O << Indent1 << "const char* Name() const {\n"
1317 << Indent2 << "return \"" << P.Name << "\";\n"
1318 << Indent1 << "}\n\n";
1321 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1323 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1324 O << Indent1 << "bool IsJoin() const {\n";
1326 O << Indent2 << "return true;\n";
1328 O << Indent2 << "return false;\n";
1329 O << Indent1 << "}\n\n";
1332 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1333 /// given Tool class.
1334 void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1335 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1336 for (StrVector::const_iterator B = P.InLanguage.begin(),
1337 E = P.InLanguage.end(); B != E; ++B)
1338 O << '\"' << *B << "\", ";
1342 /// EmitToolClassDefinition - Emit a Tool class definition.
1343 void EmitToolClassDefinition (const ToolProperties& P,
1344 const GlobalOptionDescriptions& OptDescs,
1346 if (P.Name == "root")
1350 O << "class " << P.Name << " : public ";
1356 O << "{\nprivate:\n"
1357 << Indent1 << "static const char* InputLanguages_[];\n\n";
1360 EmitNameMethod(P, O);
1361 EmitInOutLanguageMethods(P, O);
1362 EmitOutputSuffixMethod(P, O);
1363 EmitIsJoinMethod(P, O);
1364 EmitGenerateActionMethods(P, OptDescs, O);
1365 EmitIsLastMethod(P, O);
1367 // Close class definition
1370 EmitStaticMemberDefinitions(P, O);
1374 /// EmitOptionDescriptions - Iterate over a list of option
1375 /// descriptions and emit registration code.
1376 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1379 std::vector<GlobalOptionDescription> Aliases;
1381 // Emit static cl::Option variables.
1382 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1383 E = descs.end(); B!=E; ++B) {
1384 const GlobalOptionDescription& val = B->second;
1386 if (val.Type == OptionType::Alias) {
1387 Aliases.push_back(val);
1391 O << val.GenTypeDeclaration() << ' '
1392 << val.GenVariableName()
1393 << "(\"" << val.Name << '\"';
1395 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1396 O << ", cl::Prefix";
1398 if (val.isRequired()) {
1400 case OptionType::PrefixList:
1401 case OptionType::ParameterList:
1402 O << ", cl::OneOrMore";
1405 O << ", cl::Required";
1409 if (!val.Help.empty())
1410 O << ", cl::desc(\"" << val.Help << "\")";
1415 // Emit the aliases (they should go after all the 'proper' options).
1416 for (std::vector<GlobalOptionDescription>::const_iterator
1417 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1418 const GlobalOptionDescription& val = *B;
1420 O << val.GenTypeDeclaration() << ' '
1421 << val.GenVariableName()
1422 << "(\"" << val.Name << '\"';
1424 GlobalOptionDescriptions::container_type
1425 ::const_iterator F = descs.Descriptions.find(val.Help);
1426 if (F != descs.Descriptions.end())
1427 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1429 throw val.Name + ": alias to an unknown option!";
1431 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1434 // Emit the sink option.
1436 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1441 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1442 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1444 // Get the relevant field out of RecordKeeper
1445 Record* LangMapRecord = Records.getDef("LanguageMap");
1447 throw std::string("Language map definition not found!");
1449 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1450 if (!LangsToSuffixesList)
1451 throw std::string("Error in the language map definition!");
1454 O << "void llvmc::PopulateLanguageMap() {\n";
1456 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1457 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1459 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1460 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1462 for (unsigned i = 0; i < Suffixes->size(); ++i)
1463 O << Indent1 << "GlobalLanguageMap[\""
1464 << InitPtrToString(Suffixes->getElement(i))
1465 << "\"] = \"" << Lang << "\";\n";
1471 /// FillInToolToLang - Fills in two tables that map tool names to
1472 /// (input, output) languages. Used by the typechecker.
1473 void FillInToolToLang (const ToolPropertiesList& TPList,
1474 StringMap<StringSet<> >& ToolToInLang,
1475 StringMap<std::string>& ToolToOutLang) {
1476 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1478 const ToolProperties& P = *(*B);
1479 for (StrVector::const_iterator B = P.InLanguage.begin(),
1480 E = P.InLanguage.end(); B != E; ++B)
1481 ToolToInLang[P.Name].insert(*B);
1482 ToolToOutLang[P.Name] = P.OutLanguage;
1486 /// TypecheckGraph - Check that names for output and input languages
1487 /// on all edges do match.
1488 // TOFIX: It would be nice if this function also checked for cycles
1489 // and multiple default edges in the graph (better error
1490 // reporting). Unfortunately, it is awkward to do right now because
1491 // our intermediate representation is not sufficiently
1492 // sophisticated. Algorithms like these require a real graph instead of
1494 void TypecheckGraph (Record* CompilationGraph,
1495 const ToolPropertiesList& TPList) {
1496 StringMap<StringSet<> > ToolToInLang;
1497 StringMap<std::string> ToolToOutLang;
1499 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1500 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1501 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1502 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1504 for (unsigned i = 0; i < edges->size(); ++i) {
1505 Record* Edge = edges->getElementAsRecord(i);
1506 Record* A = Edge->getValueAsDef("a");
1507 Record* B = Edge->getValueAsDef("b");
1508 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1509 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1511 throw A->getName() + ": no such tool!";
1513 throw B->getName() + ": no such tool!";
1514 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1515 throw "Edge " + A->getName() + "->" + B->getName()
1516 + ": output->input language mismatch";
1517 if (B->getName() == "root")
1518 throw std::string("Edges back to the root are not allowed!");
1522 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1523 /// by EmitEdgeClass().
1524 void IncDecWeight (const Init* i, const char* IndentLevel,
1526 const DagInit& d = InitPtrToDag(i);
1527 const std::string& OpName = d.getOperator()->getAsString();
1529 if (OpName == "inc_weight")
1530 O << IndentLevel << Indent1 << "ret += ";
1531 else if (OpName == "dec_weight")
1532 O << IndentLevel << Indent1 << "ret -= ";
1534 throw "Unknown operator in edge properties list: " + OpName + '!';
1536 if (d.getNumArgs() > 0)
1537 O << InitPtrToInt(d.getArg(0)) << ";\n";
1543 /// EmitEdgeClass - Emit a single Edge# class.
1544 void EmitEdgeClass (unsigned N, const std::string& Target,
1545 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1548 // Class constructor.
1549 O << "class Edge" << N << ": public Edge {\n"
1551 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1554 // Function Weight().
1555 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1556 << Indent2 << "unsigned ret = 0;\n";
1558 // Handle the 'case' construct.
1559 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1561 O << Indent2 << "return ret;\n"
1562 << Indent1 << "};\n\n};\n\n";
1565 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1566 void EmitEdgeClasses (Record* CompilationGraph,
1567 const GlobalOptionDescriptions& OptDescs,
1569 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1571 for (unsigned i = 0; i < edges->size(); ++i) {
1572 Record* Edge = edges->getElementAsRecord(i);
1573 Record* B = Edge->getValueAsDef("b");
1574 DagInit* Weight = Edge->getValueAsDag("weight");
1576 if (isDagEmpty(Weight))
1579 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1583 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1585 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1588 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1591 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1592 << Indent1 << "PopulateLanguageMap();\n\n";
1596 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1598 throw std::string("No tool definitions found!");
1600 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1601 const std::string& Name = (*B)->getName();
1603 O << Indent1 << "G.insertNode(new "
1604 << Name << "());\n";
1610 for (unsigned i = 0; i < edges->size(); ++i) {
1611 Record* Edge = edges->getElementAsRecord(i);
1612 Record* A = Edge->getValueAsDef("a");
1613 Record* B = Edge->getValueAsDef("b");
1614 DagInit* Weight = Edge->getValueAsDag("weight");
1616 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1618 if (isDagEmpty(Weight))
1619 O << "new SimpleEdge(\"" << B->getName() << "\")";
1621 O << "new Edge" << i << "()";
1629 /// ExtractHookNames - Extract the hook names from all instances of
1630 /// $CALL(HookName) in the provided command line string. Helper
1631 /// function used by FillInHookNames().
1632 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1634 llvm::SplitString(InitPtrToString(CmdLine), cmds);
1635 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1637 const std::string& cmd = *B;
1638 if (cmd.find("$CALL(") == 0) {
1639 if (cmd.size() == 6)
1640 throw std::string("$CALL invocation: empty argument list!");
1641 HookNames.push_back(std::string(cmd.begin() + 6,
1642 cmd.begin() + cmd.find(")")));
1647 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1648 /// 'case' expression, handle nesting. Helper function used by
1649 /// FillInHookNames().
1650 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1651 const DagInit& d = InitPtrToDag(Case);
1653 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1656 if (even && dynamic_cast<DagInit*>(arg)
1657 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1658 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1660 ExtractHookNames(arg, HookNames);
1665 /// FillInHookNames - Actually extract the hook names from all command
1666 /// line strings. Helper function used by EmitHookDeclarations().
1667 void FillInHookNames(const ToolPropertiesList& TPList,
1668 StrVector& HookNames) {
1669 // For all command lines:
1670 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1671 E = TPList.end(); B != E; ++B) {
1672 const ToolProperties& P = *(*B);
1675 if (dynamic_cast<StringInit*>(P.CmdLine))
1676 // This is a string.
1677 ExtractHookNames(P.CmdLine, HookNames);
1679 // This is a 'case' construct.
1680 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1684 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1685 /// property records and emit hook function declaration for each
1686 /// instance of $CALL(HookName).
1687 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1689 StrVector HookNames;
1690 FillInHookNames(ToolProps, HookNames);
1691 if (HookNames.empty())
1693 std::sort(HookNames.begin(), HookNames.end());
1694 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1696 O << "namespace hooks {\n";
1697 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1698 O << Indent1 << "std::string " << *B << "();\n";
1703 // End of anonymous namespace
1706 /// run - The back-end entry point.
1707 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1710 // Emit file header.
1711 EmitSourceFileHeader("LLVMC Configuration Library", O);
1713 // Get a list of all defined Tools.
1714 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1716 throw std::string("No tool definitions found!");
1718 // Gather information from the Tool description dags.
1719 ToolPropertiesList tool_props;
1720 GlobalOptionDescriptions opt_descs;
1721 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1723 RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1724 CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1727 // Check that there are no options without side effects (specified
1728 // only in the OptionList).
1729 CheckForSuperfluousOptions(tool_props, opt_descs);
1731 // Emit global option registration code.
1732 EmitOptionDescriptions(opt_descs, O);
1734 // Emit hook declarations.
1735 EmitHookDeclarations(tool_props, O);
1737 // Emit PopulateLanguageMap() function
1738 // (a language map maps from file extensions to language names).
1739 EmitPopulateLanguageMap(Records, O);
1741 // Emit Tool classes.
1742 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1743 E = tool_props.end(); B!=E; ++B)
1744 EmitToolClassDefinition(*(*B), opt_descs, O);
1746 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1747 if (!CompilationGraphRecord)
1748 throw std::string("Compilation graph description not found!");
1750 // Typecheck the compilation graph.
1751 TypecheckGraph(CompilationGraphRecord, tool_props);
1753 // Emit Edge# classes.
1754 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1756 // Emit PopulateCompilationGraph() function.
1757 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1760 } catch (std::exception& Error) {
1761 throw Error.what() + std::string(" - usually this means a syntax error.");