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/StringMap.h"
19 #include "llvm/ADT/StringSet.h"
32 //===----------------------------------------------------------------------===//
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
38 //===----------------------------------------------------------------------===//
42 const unsigned TabWidth = 4;
43 const unsigned Indent1 = TabWidth*1;
44 const unsigned Indent2 = TabWidth*2;
45 const unsigned Indent3 = TabWidth*3;
46 const unsigned Indent4 = TabWidth*4;
48 // Default help string.
49 const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51 // Name for the "sink" option.
52 const char * const SinkOptionName = "SinkOption";
54 //===----------------------------------------------------------------------===//
57 /// Id - An 'identity' function object.
60 void operator()(const T0&) const {
62 template<typename T0, typename T1>
63 void operator()(const T0&, const T1&) const {
65 template<typename T0, typename T1, typename T2>
66 void operator()(const T0&, const T1&, const T2&) const {
70 int InitPtrToInt(const Init* ptr) {
71 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
72 return val.getValue();
75 const std::string& InitPtrToString(const Init* ptr) {
76 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
77 return val.getValue();
80 const ListInit& InitPtrToList(const Init* ptr) {
81 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
85 const DagInit& InitPtrToDag(const Init* ptr) {
86 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
90 const std::string GetOperatorName(const DagInit& D) {
91 return D.getOperator()->getAsString();
94 /// CheckBooleanConstant - Check that the provided value is a boolean constant.
95 void CheckBooleanConstant(const Init* I) {
96 const DefInit& val = dynamic_cast<const DefInit&>(*I);
97 const std::string& str = val.getAsString();
99 if (str != "true" && str != "false") {
100 throw "Incorrect boolean value: '" + str +
101 "': must be either 'true' or 'false'";
105 // CheckNumberOfArguments - Ensure that the number of args in d is
106 // greater than or equal to min_arguments, otherwise throw an exception.
107 void CheckNumberOfArguments (const DagInit& d, unsigned minArgs) {
108 if (d.getNumArgs() < minArgs)
109 throw GetOperatorName(d) + ": too few arguments!";
112 // IsDagEmpty - is this DAG marked with an empty marker?
113 bool IsDagEmpty (const DagInit& d) {
114 return GetOperatorName(d) == "empty_dag_marker";
117 // EscapeVariableName - Escape commas and other symbols not allowed
118 // in the C++ variable names. Makes it possible to use options named
119 // like "Wa," (useful for prefix options).
120 std::string EscapeVariableName (const std::string& Var) {
122 for (unsigned i = 0; i != Var.size(); ++i) {
123 char cur_char = Var[i];
124 if (cur_char == ',') {
127 else if (cur_char == '+') {
130 else if (cur_char == '-') {
134 ret.push_back(cur_char);
140 /// EscapeQuotes - Replace '"' with '\"'.
141 std::string EscapeQuotes (const std::string& Var) {
143 for (unsigned i = 0; i != Var.size(); ++i) {
144 char cur_char = Var[i];
145 if (cur_char == '"') {
149 ret.push_back(cur_char);
155 /// OneOf - Does the input string contain this character?
156 bool OneOf(const char* lst, char c) {
164 template <class I, class S>
165 void CheckedIncrement(I& P, I E, S ErrorString) {
171 // apply is needed because C++'s syntax doesn't let us construct a function
172 // object and call it in the same statement.
173 template<typename F, typename T0>
174 void apply(F Fun, T0& Arg0) {
178 template<typename F, typename T0, typename T1>
179 void apply(F Fun, T0& Arg0, T1& Arg1) {
180 return Fun(Arg0, Arg1);
183 //===----------------------------------------------------------------------===//
184 /// Back-end specific code
187 /// OptionType - One of six different option types. See the
188 /// documentation for detailed description of differences.
189 namespace OptionType {
191 enum OptionType { Alias, Switch, SwitchList,
192 Parameter, ParameterList, Prefix, PrefixList };
194 bool IsAlias(OptionType t) {
198 bool IsList (OptionType t) {
199 return (t == SwitchList || t == ParameterList || t == PrefixList);
202 bool IsSwitch (OptionType t) {
203 return (t == Switch);
206 bool IsSwitchList (OptionType t) {
207 return (t == SwitchList);
210 bool IsParameter (OptionType t) {
211 return (t == Parameter || t == Prefix);
216 OptionType::OptionType stringToOptionType(const std::string& T) {
217 if (T == "alias_option")
218 return OptionType::Alias;
219 else if (T == "switch_option")
220 return OptionType::Switch;
221 else if (T == "switch_list_option")
222 return OptionType::SwitchList;
223 else if (T == "parameter_option")
224 return OptionType::Parameter;
225 else if (T == "parameter_list_option")
226 return OptionType::ParameterList;
227 else if (T == "prefix_option")
228 return OptionType::Prefix;
229 else if (T == "prefix_list_option")
230 return OptionType::PrefixList;
232 throw "Unknown option type: " + T + '!';
235 namespace OptionDescriptionFlags {
236 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
237 ReallyHidden = 0x4, OneOrMore = 0x8,
238 Optional = 0x10, CommaSeparated = 0x20,
239 ForwardNotSplit = 0x40, ZeroOrMore = 0x80 };
242 /// OptionDescription - Represents data contained in a single
243 /// OptionList entry.
244 struct OptionDescription {
245 OptionType::OptionType Type;
252 OptionDescription(OptionType::OptionType t = OptionType::Switch,
253 const std::string& n = "",
254 const std::string& h = DefaultHelpString)
255 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
258 /// GenTypeDeclaration - Returns the C++ variable type of this
260 const char* GenTypeDeclaration() const;
262 /// GenVariableName - Returns the variable name used in the
263 /// generated C++ code.
264 std::string GenVariableName() const
265 { return "autogenerated::" + GenOptionType() + EscapeVariableName(Name); }
267 /// GenPlainVariableName - Returns the variable name without the namespace
269 std::string GenPlainVariableName() const
270 { return GenOptionType() + EscapeVariableName(Name); }
272 /// Merge - Merge two option descriptions.
273 void Merge (const OptionDescription& other);
275 /// CheckConsistency - Check that the flags are consistent.
276 void CheckConsistency() const;
278 // Misc convenient getters/setters.
280 bool isAlias() const;
282 bool isMultiVal() const;
284 bool isCommaSeparated() const;
285 void setCommaSeparated();
287 bool isForwardNotSplit() const;
288 void setForwardNotSplit();
290 bool isRequired() const;
293 bool isOneOrMore() const;
296 bool isZeroOrMore() const;
297 void setZeroOrMore();
299 bool isOptional() const;
302 bool isHidden() const;
305 bool isReallyHidden() const;
306 void setReallyHidden();
308 bool isSwitch() const
309 { return OptionType::IsSwitch(this->Type); }
311 bool isSwitchList() const
312 { return OptionType::IsSwitchList(this->Type); }
314 bool isParameter() const
315 { return OptionType::IsParameter(this->Type); }
318 { return OptionType::IsList(this->Type); }
320 bool isParameterList() const
321 { return (OptionType::IsList(this->Type)
322 && !OptionType::IsSwitchList(this->Type)); }
326 // GenOptionType - Helper function used by GenVariableName().
327 std::string GenOptionType() const;
330 void OptionDescription::CheckConsistency() const {
333 i += this->isRequired();
334 i += this->isOptional();
335 i += this->isOneOrMore();
336 i += this->isZeroOrMore();
339 throw "Only one of (required), (optional), (one_or_more) or "
340 "(zero_or_more) properties is allowed!";
344 void OptionDescription::Merge (const OptionDescription& other)
346 if (other.Type != Type)
347 throw "Conflicting definitions for the option " + Name + "!";
349 if (Help == other.Help || Help == DefaultHelpString)
351 else if (other.Help != DefaultHelpString) {
352 llvm::errs() << "Warning: several different help strings"
353 " defined for option " + Name + "\n";
356 Flags |= other.Flags;
359 bool OptionDescription::isAlias() const {
360 return OptionType::IsAlias(this->Type);
363 bool OptionDescription::isMultiVal() const {
367 bool OptionDescription::isCommaSeparated() const {
368 return Flags & OptionDescriptionFlags::CommaSeparated;
370 void OptionDescription::setCommaSeparated() {
371 Flags |= OptionDescriptionFlags::CommaSeparated;
374 bool OptionDescription::isForwardNotSplit() const {
375 return Flags & OptionDescriptionFlags::ForwardNotSplit;
377 void OptionDescription::setForwardNotSplit() {
378 Flags |= OptionDescriptionFlags::ForwardNotSplit;
381 bool OptionDescription::isRequired() const {
382 return Flags & OptionDescriptionFlags::Required;
384 void OptionDescription::setRequired() {
385 Flags |= OptionDescriptionFlags::Required;
388 bool OptionDescription::isOneOrMore() const {
389 return Flags & OptionDescriptionFlags::OneOrMore;
391 void OptionDescription::setOneOrMore() {
392 Flags |= OptionDescriptionFlags::OneOrMore;
395 bool OptionDescription::isZeroOrMore() const {
396 return Flags & OptionDescriptionFlags::ZeroOrMore;
398 void OptionDescription::setZeroOrMore() {
399 Flags |= OptionDescriptionFlags::ZeroOrMore;
402 bool OptionDescription::isOptional() const {
403 return Flags & OptionDescriptionFlags::Optional;
405 void OptionDescription::setOptional() {
406 Flags |= OptionDescriptionFlags::Optional;
409 bool OptionDescription::isHidden() const {
410 return Flags & OptionDescriptionFlags::Hidden;
412 void OptionDescription::setHidden() {
413 Flags |= OptionDescriptionFlags::Hidden;
416 bool OptionDescription::isReallyHidden() const {
417 return Flags & OptionDescriptionFlags::ReallyHidden;
419 void OptionDescription::setReallyHidden() {
420 Flags |= OptionDescriptionFlags::ReallyHidden;
423 const char* OptionDescription::GenTypeDeclaration() const {
425 case OptionType::Alias:
427 case OptionType::PrefixList:
428 case OptionType::ParameterList:
429 return "cl::list<std::string>";
430 case OptionType::Switch:
431 return "cl::opt<bool>";
432 case OptionType::SwitchList:
433 return "cl::list<bool>";
434 case OptionType::Parameter:
435 case OptionType::Prefix:
437 return "cl::opt<std::string>";
441 std::string OptionDescription::GenOptionType() const {
443 case OptionType::Alias:
445 case OptionType::PrefixList:
446 case OptionType::ParameterList:
448 case OptionType::Switch:
450 case OptionType::SwitchList:
451 return "SwitchList_";
452 case OptionType::Prefix:
453 case OptionType::Parameter:
459 /// OptionDescriptions - An OptionDescription array plus some helper
461 class OptionDescriptions {
462 typedef StringMap<OptionDescription> container_type;
464 /// Descriptions - A list of OptionDescriptions.
465 container_type Descriptions;
468 /// FindOption - exception-throwing wrapper for find().
469 const OptionDescription& FindOption(const std::string& OptName) const;
471 // Wrappers for FindOption that throw an exception in case the option has a
473 const OptionDescription& FindSwitch(const std::string& OptName) const;
474 const OptionDescription& FindParameter(const std::string& OptName) const;
475 const OptionDescription& FindList(const std::string& OptName) const;
476 const OptionDescription& FindParameterList(const std::string& OptName) const;
477 const OptionDescription&
478 FindListOrParameter(const std::string& OptName) const;
479 const OptionDescription&
480 FindParameterListOrParameter(const std::string& OptName) const;
482 /// insertDescription - Insert new OptionDescription into
483 /// OptionDescriptions list
484 void InsertDescription (const OptionDescription& o);
486 // Support for STL-style iteration
487 typedef container_type::const_iterator const_iterator;
488 const_iterator begin() const { return Descriptions.begin(); }
489 const_iterator end() const { return Descriptions.end(); }
492 const OptionDescription&
493 OptionDescriptions::FindOption(const std::string& OptName) const {
494 const_iterator I = Descriptions.find(OptName);
495 if (I != Descriptions.end())
498 throw OptName + ": no such option!";
501 const OptionDescription&
502 OptionDescriptions::FindSwitch(const std::string& OptName) const {
503 const OptionDescription& OptDesc = this->FindOption(OptName);
504 if (!OptDesc.isSwitch())
505 throw OptName + ": incorrect option type - should be a switch!";
509 const OptionDescription&
510 OptionDescriptions::FindList(const std::string& OptName) const {
511 const OptionDescription& OptDesc = this->FindOption(OptName);
512 if (!OptDesc.isList())
513 throw OptName + ": incorrect option type - should be a list!";
517 const OptionDescription&
518 OptionDescriptions::FindParameterList(const std::string& OptName) const {
519 const OptionDescription& OptDesc = this->FindOption(OptName);
520 if (!OptDesc.isList() || OptDesc.isSwitchList())
521 throw OptName + ": incorrect option type - should be a parameter list!";
525 const OptionDescription&
526 OptionDescriptions::FindParameter(const std::string& OptName) const {
527 const OptionDescription& OptDesc = this->FindOption(OptName);
528 if (!OptDesc.isParameter())
529 throw OptName + ": incorrect option type - should be a parameter!";
533 const OptionDescription&
534 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
535 const OptionDescription& OptDesc = this->FindOption(OptName);
536 if (!OptDesc.isList() && !OptDesc.isParameter())
538 + ": incorrect option type - should be a list or parameter!";
542 const OptionDescription&
543 OptionDescriptions::FindParameterListOrParameter
544 (const std::string& OptName) const {
545 const OptionDescription& OptDesc = this->FindOption(OptName);
546 if ((!OptDesc.isList() && !OptDesc.isParameter()) || OptDesc.isSwitchList())
548 + ": incorrect option type - should be a parameter list or parameter!";
552 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
553 container_type::iterator I = Descriptions.find(o.Name);
554 if (I != Descriptions.end()) {
555 OptionDescription& D = I->second;
559 Descriptions[o.Name] = o;
563 /// HandlerTable - A base class for function objects implemented as
564 /// 'tables of handlers'.
565 template <typename Handler>
568 // Implementation details.
570 /// HandlerMap - A map from property names to property handlers
571 typedef StringMap<Handler> HandlerMap;
573 static HandlerMap Handlers_;
574 static bool staticMembersInitialized_;
578 Handler GetHandler (const std::string& HandlerName) const {
579 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
581 if (method != Handlers_.end()) {
582 Handler h = method->second;
586 throw "No handler found for property " + HandlerName + "!";
590 void AddHandler(const char* Property, Handler H) {
591 Handlers_[Property] = H;
596 template <class Handler, class FunctionObject>
597 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
598 const std::string& HandlerName = GetOperatorName(Dag);
599 return Obj->GetHandler(HandlerName);
602 template <class FunctionObject>
603 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
604 typedef void (FunctionObject::*Handler) (const DagInit&);
606 const DagInit& Dag = InitPtrToDag(I);
607 Handler h = GetHandler<Handler>(Obj, Dag);
612 template <class FunctionObject>
613 void InvokeDagInitHandler(const FunctionObject* const Obj,
614 const Init* I, unsigned IndentLevel, raw_ostream& O)
616 typedef void (FunctionObject::*Handler)
617 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
619 const DagInit& Dag = InitPtrToDag(I);
620 Handler h = GetHandler<Handler>(Obj, Dag);
622 ((Obj)->*(h))(Dag, IndentLevel, O);
626 template <typename H>
627 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
629 template <typename H>
630 bool HandlerTable<H>::staticMembersInitialized_ = false;
633 /// CollectOptionProperties - Function object for iterating over an
634 /// option property list.
635 class CollectOptionProperties;
636 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
639 class CollectOptionProperties
640 : public HandlerTable<CollectOptionPropertiesHandler>
644 /// optDescs_ - OptionDescriptions table. This is where the
645 /// information is stored.
646 OptionDescription& optDesc_;
650 explicit CollectOptionProperties(OptionDescription& OD)
653 if (!staticMembersInitialized_) {
654 AddHandler("help", &CollectOptionProperties::onHelp);
655 AddHandler("hidden", &CollectOptionProperties::onHidden);
656 AddHandler("init", &CollectOptionProperties::onInit);
657 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
658 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
659 AddHandler("zero_or_more", &CollectOptionProperties::onZeroOrMore);
660 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
661 AddHandler("required", &CollectOptionProperties::onRequired);
662 AddHandler("optional", &CollectOptionProperties::onOptional);
663 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
664 AddHandler("forward_not_split",
665 &CollectOptionProperties::onForwardNotSplit);
667 staticMembersInitialized_ = true;
671 /// operator() - Just forwards to the corresponding property
673 void operator() (Init* I) {
674 InvokeDagInitHandler(this, I);
679 /// Option property handlers --
680 /// Methods that handle option properties such as (help) or (hidden).
682 void onHelp (const DagInit& d) {
683 CheckNumberOfArguments(d, 1);
684 optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0)));
687 void onHidden (const DagInit& d) {
688 CheckNumberOfArguments(d, 0);
689 optDesc_.setHidden();
692 void onReallyHidden (const DagInit& d) {
693 CheckNumberOfArguments(d, 0);
694 optDesc_.setReallyHidden();
697 void onCommaSeparated (const DagInit& d) {
698 CheckNumberOfArguments(d, 0);
699 if (!optDesc_.isParameterList())
700 throw "'comma_separated' is valid only on parameter list options!";
701 optDesc_.setCommaSeparated();
704 void onForwardNotSplit (const DagInit& d) {
705 CheckNumberOfArguments(d, 0);
706 if (!optDesc_.isParameter())
707 throw "'forward_not_split' is valid only for parameter options!";
708 optDesc_.setForwardNotSplit();
711 void onRequired (const DagInit& d) {
712 CheckNumberOfArguments(d, 0);
714 optDesc_.setRequired();
715 optDesc_.CheckConsistency();
718 void onInit (const DagInit& d) {
719 CheckNumberOfArguments(d, 1);
720 Init* i = d.getArg(0);
721 const std::string& str = i->getAsString();
723 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
724 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
727 throw "Incorrect usage of the 'init' option property!";
729 optDesc_.InitVal = i;
732 void onOneOrMore (const DagInit& d) {
733 CheckNumberOfArguments(d, 0);
735 optDesc_.setOneOrMore();
736 optDesc_.CheckConsistency();
739 void onZeroOrMore (const DagInit& d) {
740 CheckNumberOfArguments(d, 0);
742 if (optDesc_.isList())
743 llvm::errs() << "Warning: specifying the 'zero_or_more' property "
744 "on a list option has no effect.\n";
746 optDesc_.setZeroOrMore();
747 optDesc_.CheckConsistency();
750 void onOptional (const DagInit& d) {
751 CheckNumberOfArguments(d, 0);
753 if (!optDesc_.isList())
754 llvm::errs() << "Warning: specifying the 'optional' property"
755 "on a non-list option has no effect.\n";
757 optDesc_.setOptional();
758 optDesc_.CheckConsistency();
761 void onMultiVal (const DagInit& d) {
762 CheckNumberOfArguments(d, 1);
763 int val = InitPtrToInt(d.getArg(0));
765 throw "Error in the 'multi_val' property: "
766 "the value must be greater than 1!";
767 if (!optDesc_.isParameterList())
768 throw "The multi_val property is valid only on list options!";
769 optDesc_.MultiVal = val;
774 /// AddOption - A function object that is applied to every option
775 /// description. Used by CollectOptionDescriptions.
778 OptionDescriptions& OptDescs_;
781 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
784 void operator()(const Init* i) {
785 const DagInit& d = InitPtrToDag(i);
786 CheckNumberOfArguments(d, 1);
788 const OptionType::OptionType Type =
789 stringToOptionType(GetOperatorName(d));
790 const std::string& Name = InitPtrToString(d.getArg(0));
792 OptionDescription OD(Type, Name);
795 CheckNumberOfArguments(d, 2);
798 // Aliases store the aliased option name in the 'Help' field.
799 OD.Help = InitPtrToString(d.getArg(1));
802 processOptionProperties(d, OD);
805 OptDescs_.InsertDescription(OD);
809 /// processOptionProperties - Go through the list of option
810 /// properties and call a corresponding handler for each.
811 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
812 CheckNumberOfArguments(d, 2);
813 DagInit::const_arg_iterator B = d.arg_begin();
814 // Skip the first argument: it's always the option name.
816 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
821 /// CollectOptionDescriptions - Collects option properties from all
823 void CollectOptionDescriptions (RecordVector::const_iterator B,
824 RecordVector::const_iterator E,
825 OptionDescriptions& OptDescs)
827 // For every OptionList:
829 RecordVector::value_type T = *B;
830 // Throws an exception if the value does not exist.
831 ListInit* PropList = T->getValueAsListInit("options");
833 // For every option description in this list:
834 // collect the information and
835 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
839 // Tool information record
841 namespace ToolFlags {
842 enum ToolFlags { Join = 0x1, Sink = 0x2 };
845 struct ToolDescription : public RefCountedBase<ToolDescription> {
849 StrVector InLanguage;
850 std::string InFileOption;
851 std::string OutFileOption;
852 std::string OutLanguage;
853 std::string OutputSuffix;
857 // Various boolean properties
858 void setSink() { Flags |= ToolFlags::Sink; }
859 bool isSink() const { return Flags & ToolFlags::Sink; }
860 void setJoin() { Flags |= ToolFlags::Join; }
861 bool isJoin() const { return Flags & ToolFlags::Join; }
863 // Default ctor here is needed because StringMap can only store
864 // DefaultConstructible objects
866 : CmdLine(0), Actions(0), OutFileOption("-o"),
869 ToolDescription (const std::string& n)
870 : Name(n), CmdLine(0), Actions(0), OutFileOption("-o"),
875 /// ToolDescriptions - A list of Tool information records.
876 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
879 /// CollectToolProperties - Function object for iterating over a list of
880 /// tool property records.
882 class CollectToolProperties;
883 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
886 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
890 /// toolDesc_ - Properties of the current Tool. This is where the
891 /// information is stored.
892 ToolDescription& toolDesc_;
896 explicit CollectToolProperties (ToolDescription& d)
899 if (!staticMembersInitialized_) {
901 AddHandler("actions", &CollectToolProperties::onActions);
902 AddHandler("command", &CollectToolProperties::onCommand);
903 AddHandler("in_language", &CollectToolProperties::onInLanguage);
904 AddHandler("join", &CollectToolProperties::onJoin);
905 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
907 AddHandler("out_file_option", &CollectToolProperties::onOutFileOption);
908 AddHandler("in_file_option", &CollectToolProperties::onInFileOption);
910 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
911 AddHandler("sink", &CollectToolProperties::onSink);
912 AddHandler("works_on_empty", &CollectToolProperties::onWorksOnEmpty);
914 staticMembersInitialized_ = true;
918 void operator() (Init* I) {
919 InvokeDagInitHandler(this, I);
924 /// Property handlers --
925 /// Functions that extract information about tool properties from
926 /// DAG representation.
928 void onActions (const DagInit& d) {
929 CheckNumberOfArguments(d, 1);
930 Init* Case = d.getArg(0);
931 if (typeid(*Case) != typeid(DagInit) ||
932 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
933 throw "The argument to (actions) should be a 'case' construct!";
934 toolDesc_.Actions = Case;
937 void onCommand (const DagInit& d) {
938 CheckNumberOfArguments(d, 1);
939 toolDesc_.CmdLine = d.getArg(0);
942 void onInLanguage (const DagInit& d) {
943 CheckNumberOfArguments(d, 1);
944 Init* arg = d.getArg(0);
946 // Find out the argument's type.
947 if (typeid(*arg) == typeid(StringInit)) {
949 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
953 const ListInit& lst = InitPtrToList(arg);
954 StrVector& out = toolDesc_.InLanguage;
956 // Copy strings to the output vector.
957 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
959 out.push_back(InitPtrToString(*B));
962 // Remove duplicates.
963 std::sort(out.begin(), out.end());
964 StrVector::iterator newE = std::unique(out.begin(), out.end());
965 out.erase(newE, out.end());
969 void onJoin (const DagInit& d) {
970 CheckNumberOfArguments(d, 0);
974 void onOutLanguage (const DagInit& d) {
975 CheckNumberOfArguments(d, 1);
976 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
979 void onOutFileOption (const DagInit& d) {
980 CheckNumberOfArguments(d, 1);
981 toolDesc_.OutFileOption = InitPtrToString(d.getArg(0));
984 void onInFileOption (const DagInit& d) {
985 CheckNumberOfArguments(d, 1);
986 toolDesc_.InFileOption = InitPtrToString(d.getArg(0));
989 void onOutputSuffix (const DagInit& d) {
990 CheckNumberOfArguments(d, 1);
991 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
994 void onSink (const DagInit& d) {
995 CheckNumberOfArguments(d, 0);
999 void onWorksOnEmpty (const DagInit& d) {
1000 toolDesc_.OnEmpty = d.getArg(0);
1005 /// CollectToolDescriptions - Gather information about tool properties
1006 /// from the parsed TableGen data (basically a wrapper for the
1007 /// CollectToolProperties function object).
1008 void CollectToolDescriptions (RecordVector::const_iterator B,
1009 RecordVector::const_iterator E,
1010 ToolDescriptions& ToolDescs)
1012 // Iterate over a properties list of every Tool definition
1014 const Record* T = *B;
1015 // Throws an exception if the value does not exist.
1016 ListInit* PropList = T->getValueAsListInit("properties");
1018 IntrusiveRefCntPtr<ToolDescription>
1019 ToolDesc(new ToolDescription(T->getName()));
1021 std::for_each(PropList->begin(), PropList->end(),
1022 CollectToolProperties(*ToolDesc));
1023 ToolDescs.push_back(ToolDesc);
1027 /// FillInEdgeVector - Merge all compilation graph definitions into
1028 /// one single edge list.
1029 void FillInEdgeVector(RecordVector::const_iterator B,
1030 RecordVector::const_iterator E, RecordVector& Out) {
1031 for (; B != E; ++B) {
1032 const ListInit* edges = (*B)->getValueAsListInit("edges");
1034 for (unsigned i = 0; i < edges->size(); ++i)
1035 Out.push_back(edges->getElementAsRecord(i));
1039 /// NotInGraph - Helper function object for FilterNotInGraph.
1042 const llvm::StringSet<>& ToolsInGraph_;
1045 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
1046 : ToolsInGraph_(ToolsInGraph)
1049 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
1050 return (ToolsInGraph_.count(x->Name) == 0);
1054 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
1055 /// mentioned in the compilation graph definition.
1056 void FilterNotInGraph (const RecordVector& EdgeVector,
1057 ToolDescriptions& ToolDescs) {
1059 // List all tools mentioned in the graph.
1060 llvm::StringSet<> ToolsInGraph;
1062 for (RecordVector::const_iterator B = EdgeVector.begin(),
1063 E = EdgeVector.end(); B != E; ++B) {
1065 const Record* Edge = *B;
1066 const std::string& NodeA = Edge->getValueAsString("a");
1067 const std::string& NodeB = Edge->getValueAsString("b");
1069 if (NodeA != "root")
1070 ToolsInGraph.insert(NodeA);
1071 ToolsInGraph.insert(NodeB);
1074 // Filter ToolPropertiesList.
1075 ToolDescriptions::iterator new_end =
1076 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
1077 NotInGraph(ToolsInGraph));
1078 ToolDescs.erase(new_end, ToolDescs.end());
1081 /// FillInToolToLang - Fills in two tables that map tool names to
1082 /// (input, output) languages. Helper function used by TypecheckGraph().
1083 void FillInToolToLang (const ToolDescriptions& ToolDescs,
1084 StringMap<StringSet<> >& ToolToInLang,
1085 StringMap<std::string>& ToolToOutLang) {
1086 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1087 E = ToolDescs.end(); B != E; ++B) {
1088 const ToolDescription& D = *(*B);
1089 for (StrVector::const_iterator B = D.InLanguage.begin(),
1090 E = D.InLanguage.end(); B != E; ++B)
1091 ToolToInLang[D.Name].insert(*B);
1092 ToolToOutLang[D.Name] = D.OutLanguage;
1096 /// TypecheckGraph - Check that names for output and input languages
1097 /// on all edges do match. This doesn't do much when the information
1098 /// about the whole graph is not available (i.e. when compiling most
1100 void TypecheckGraph (const RecordVector& EdgeVector,
1101 const ToolDescriptions& ToolDescs) {
1102 StringMap<StringSet<> > ToolToInLang;
1103 StringMap<std::string> ToolToOutLang;
1105 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
1106 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1107 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1109 for (RecordVector::const_iterator B = EdgeVector.begin(),
1110 E = EdgeVector.end(); B != E; ++B) {
1111 const Record* Edge = *B;
1112 const std::string& NodeA = Edge->getValueAsString("a");
1113 const std::string& NodeB = Edge->getValueAsString("b");
1114 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1115 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1117 if (NodeA != "root") {
1118 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1119 throw "Edge " + NodeA + "->" + NodeB
1120 + ": output->input language mismatch";
1123 if (NodeB == "root")
1124 throw "Edges back to the root are not allowed!";
1128 /// WalkCase - Walks the 'case' expression DAG and invokes
1129 /// TestCallback on every test, and StatementCallback on every
1130 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1131 /// combinators (that is, they are passed directly to TestCallback).
1132 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1133 /// IndentLevel, bool FirstTest)'.
1134 /// StatementCallback must have type 'void StatementCallback(const Init*,
1135 /// unsigned IndentLevel)'.
1136 template <typename F1, typename F2>
1137 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1138 unsigned IndentLevel = 0)
1140 const DagInit& d = InitPtrToDag(Case);
1143 if (GetOperatorName(d) != "case")
1144 throw "WalkCase should be invoked only on 'case' expressions!";
1146 if (d.getNumArgs() < 2)
1147 throw "There should be at least one clause in the 'case' expression:\n"
1152 const unsigned numArgs = d.getNumArgs();
1154 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1161 const DagInit& Test = InitPtrToDag(arg);
1163 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1164 throw "The 'default' clause should be the last in the "
1165 "'case' construct!";
1167 throw "Case construct handler: no corresponding action "
1168 "found for the test " + Test.getAsString() + '!';
1170 TestCallback(Test, IndentLevel, (i == 1));
1174 if (dynamic_cast<DagInit*>(arg)
1175 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1177 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1180 // Handle statement.
1181 StatementCallback(arg, IndentLevel);
1189 /// ExtractOptionNames - A helper function object used by
1190 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1191 class ExtractOptionNames {
1192 llvm::StringSet<>& OptionNames_;
1194 void processDag(const Init* Statement) {
1195 const DagInit& Stmt = InitPtrToDag(Statement);
1196 const std::string& ActionName = GetOperatorName(Stmt);
1197 if (ActionName == "forward" || ActionName == "forward_as" ||
1198 ActionName == "forward_value" ||
1199 ActionName == "forward_transformed_value" ||
1200 ActionName == "switch_on" || ActionName == "any_switch_on" ||
1201 ActionName == "parameter_equals" ||
1202 ActionName == "element_in_list" || ActionName == "not_empty" ||
1203 ActionName == "empty") {
1204 CheckNumberOfArguments(Stmt, 1);
1206 Init* Arg = Stmt.getArg(0);
1207 if (typeid(*Arg) == typeid(StringInit)) {
1208 const std::string& Name = InitPtrToString(Arg);
1209 OptionNames_.insert(Name);
1213 const ListInit& List = InitPtrToList(Arg);
1214 for (ListInit::const_iterator B = List.begin(), E = List.end();
1216 const std::string& Name = InitPtrToString(*B);
1217 OptionNames_.insert(Name);
1221 else if (ActionName == "and" || ActionName == "or" || ActionName == "not") {
1222 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1223 this->processDag(Stmt.getArg(i));
1229 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1232 void operator()(const Init* Statement) {
1233 if (typeid(*Statement) == typeid(ListInit)) {
1234 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1235 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1237 this->processDag(*B);
1240 this->processDag(Statement);
1244 void operator()(const DagInit& Test, unsigned, bool) {
1245 this->operator()(&Test);
1247 void operator()(const Init* Statement, unsigned) {
1248 this->operator()(Statement);
1252 /// CheckForSuperfluousOptions - Check that there are no side
1253 /// effect-free options (specified only in the OptionList). Otherwise,
1254 /// output a warning.
1255 void CheckForSuperfluousOptions (const RecordVector& Edges,
1256 const ToolDescriptions& ToolDescs,
1257 const OptionDescriptions& OptDescs) {
1258 llvm::StringSet<> nonSuperfluousOptions;
1260 // Add all options mentioned in the ToolDesc.Actions to the set of
1261 // non-superfluous options.
1262 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1263 E = ToolDescs.end(); B != E; ++B) {
1264 const ToolDescription& TD = *(*B);
1265 ExtractOptionNames Callback(nonSuperfluousOptions);
1267 WalkCase(TD.Actions, Callback, Callback);
1270 // Add all options mentioned in the 'case' clauses of the
1271 // OptionalEdges of the compilation graph to the set of
1272 // non-superfluous options.
1273 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1275 const Record* Edge = *B;
1276 DagInit& Weight = *Edge->getValueAsDag("weight");
1278 if (!IsDagEmpty(Weight))
1279 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1282 // Check that all options in OptDescs belong to the set of
1283 // non-superfluous options.
1284 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1285 E = OptDescs.end(); B != E; ++B) {
1286 const OptionDescription& Val = B->second;
1287 if (!nonSuperfluousOptions.count(Val.Name)
1288 && Val.Type != OptionType::Alias)
1289 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1290 "Probable cause: this option is specified only in the OptionList.\n";
1294 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1295 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1296 if (TestName == "single_input_file") {
1297 O << "InputFilenames.size() == 1";
1300 else if (TestName == "multiple_input_files") {
1301 O << "InputFilenames.size() > 1";
1308 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1309 template <typename F>
1310 void EmitListTest(const ListInit& L, const char* LogicOp,
1311 F Callback, raw_ostream& O)
1313 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1315 bool isFirst = true;
1316 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1320 O << ' ' << LogicOp << ' ';
1321 Callback(InitPtrToString(*B), O);
1325 // Callbacks for use with EmitListTest.
1327 class EmitSwitchOn {
1328 const OptionDescriptions& OptDescs_;
1330 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1333 void operator()(const std::string& OptName, raw_ostream& O) const {
1334 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1335 O << OptDesc.GenVariableName();
1339 class EmitEmptyTest {
1341 const OptionDescriptions& OptDescs_;
1343 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1344 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1347 void operator()(const std::string& OptName, raw_ostream& O) const {
1348 const char* Neg = (EmitNegate_ ? "!" : "");
1349 if (OptName == "o") {
1350 O << Neg << "OutputFilename.empty()";
1352 else if (OptName == "save-temps") {
1353 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1356 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1357 O << Neg << OptDesc.GenVariableName() << ".empty()";
1363 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1364 bool EmitCaseTest1ArgList(const std::string& TestName,
1366 const OptionDescriptions& OptDescs,
1368 const ListInit& L = InitPtrToList(d.getArg(0));
1370 if (TestName == "any_switch_on") {
1371 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1374 else if (TestName == "switch_on") {
1375 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1378 else if (TestName == "any_not_empty") {
1379 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1382 else if (TestName == "any_empty") {
1383 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1386 else if (TestName == "not_empty") {
1387 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1390 else if (TestName == "empty") {
1391 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1398 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1399 bool EmitCaseTest1ArgStr(const std::string& TestName,
1401 const OptionDescriptions& OptDescs,
1403 const std::string& OptName = InitPtrToString(d.getArg(0));
1405 if (TestName == "switch_on") {
1406 apply(EmitSwitchOn(OptDescs), OptName, O);
1409 else if (TestName == "input_languages_contain") {
1410 O << "InLangs.count(\"" << OptName << "\") != 0";
1413 else if (TestName == "in_language") {
1414 // This works only for single-argument Tool::GenerateAction. Join
1415 // tools can process several files in different languages simultaneously.
1417 // TODO: make this work with Edge::Weight (if possible).
1418 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1421 else if (TestName == "not_empty" || TestName == "empty") {
1422 bool EmitNegate = (TestName == "not_empty");
1423 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1430 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1431 bool EmitCaseTest1Arg(const std::string& TestName,
1433 const OptionDescriptions& OptDescs,
1435 CheckNumberOfArguments(d, 1);
1436 if (typeid(*d.getArg(0)) == typeid(ListInit))
1437 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1439 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1442 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1443 bool EmitCaseTest2Args(const std::string& TestName,
1445 unsigned IndentLevel,
1446 const OptionDescriptions& OptDescs,
1448 CheckNumberOfArguments(d, 2);
1449 const std::string& OptName = InitPtrToString(d.getArg(0));
1450 const std::string& OptArg = InitPtrToString(d.getArg(1));
1452 if (TestName == "parameter_equals") {
1453 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1454 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1457 else if (TestName == "element_in_list") {
1458 const OptionDescription& OptDesc = OptDescs.FindParameterList(OptName);
1459 const std::string& VarName = OptDesc.GenVariableName();
1460 O << "std::find(" << VarName << ".begin(),\n";
1461 O.indent(IndentLevel + Indent1)
1462 << VarName << ".end(), \""
1463 << OptArg << "\") != " << VarName << ".end()";
1470 // Forward declaration.
1471 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1472 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1473 const OptionDescriptions& OptDescs,
1476 /// EmitLogicalOperationTest - Helper function used by
1477 /// EmitCaseConstructHandler.
1478 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1479 unsigned IndentLevel,
1480 const OptionDescriptions& OptDescs,
1483 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1484 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1485 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1486 if (j != NumArgs - 1) {
1488 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1496 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1497 const OptionDescriptions& OptDescs, raw_ostream& O)
1499 CheckNumberOfArguments(d, 1);
1500 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1502 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1506 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1507 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1508 const OptionDescriptions& OptDescs,
1510 const std::string& TestName = GetOperatorName(d);
1512 if (TestName == "and")
1513 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1514 else if (TestName == "or")
1515 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1516 else if (TestName == "not")
1517 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1518 else if (EmitCaseTest0Args(TestName, O))
1520 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1522 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1525 throw "Unknown test '" + TestName + "' used in the 'case' construct!";
1529 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1530 class EmitCaseTestCallback {
1532 const OptionDescriptions& OptDescs_;
1536 EmitCaseTestCallback(bool EmitElseIf,
1537 const OptionDescriptions& OptDescs, raw_ostream& O)
1538 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1541 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1543 if (GetOperatorName(Test) == "default") {
1544 O_.indent(IndentLevel) << "else {\n";
1547 O_.indent(IndentLevel)
1548 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1549 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1555 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1556 template <typename F>
1557 class EmitCaseStatementCallback {
1562 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1563 : Callback_(Callback), O_(O)
1566 void operator() (const Init* Statement, unsigned IndentLevel) {
1568 // Ignore nested 'case' DAG.
1569 if (!(dynamic_cast<const DagInit*>(Statement) &&
1570 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1571 if (typeid(*Statement) == typeid(ListInit)) {
1572 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1573 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1575 Callback_(*B, (IndentLevel + Indent1), O_);
1578 Callback_(Statement, (IndentLevel + Indent1), O_);
1581 O_.indent(IndentLevel) << "}\n";
1586 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1587 /// construct. Takes a function object that should emit code for every case
1588 /// clause. Implemented on top of WalkCase.
1589 /// Callback's type is void F(const Init* Statement, unsigned IndentLevel,
1590 /// raw_ostream& O).
1591 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1592 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1594 template <typename F>
1595 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1596 F Callback, bool EmitElseIf,
1597 const OptionDescriptions& OptDescs,
1599 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1600 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1603 /// TokenizeCmdLine - converts from
1604 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1605 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1606 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1607 const char* Delimiters = " \t\n\v\f\r";
1609 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1612 if (CmdLine.empty())
1616 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1619 for (; B != E; ++B) {
1620 char cur_ch = CmdLine[B];
1624 if (cur_ch == '$') {
1625 cur_st = SpecialCommand;
1628 if (OneOf(Delimiters, cur_ch)) {
1630 B = CmdLine.find_first_not_of(Delimiters, B);
1631 if (B == std::string::npos) {
1642 case SpecialCommand:
1643 if (OneOf(Delimiters, cur_ch)) {
1648 if (cur_ch == '(') {
1650 cur_st = InsideSpecialCommand;
1655 case InsideSpecialCommand:
1656 if (OneOf(Delimiters, cur_ch)) {
1659 if (cur_ch == '\'') {
1660 cur_st = InsideQuotationMarks;
1664 if (cur_ch == ')') {
1668 if (cur_ch == ',') {
1674 case InsideQuotationMarks:
1675 if (cur_ch == '\'') {
1676 cur_st = InsideSpecialCommand;
1682 Out.back().push_back(cur_ch);
1686 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1687 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1688 /// SubstituteSpecialCommands().
1689 StrVector::const_iterator
1690 SubstituteCall (StrVector::const_iterator Pos,
1691 StrVector::const_iterator End,
1692 bool IsJoin, raw_ostream& O)
1694 const char* errorMessage = "Syntax error in $CALL invocation!";
1695 CheckedIncrement(Pos, End, errorMessage);
1696 const std::string& CmdName = *Pos;
1699 throw "$CALL invocation: empty argument list!";
1702 O << CmdName << "(";
1705 bool firstIteration = true;
1707 CheckedIncrement(Pos, End, errorMessage);
1708 const std::string& Arg = *Pos;
1709 assert(Arg.size() != 0);
1715 firstIteration = false;
1719 if (Arg == "$INFILE") {
1721 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1723 O << "inFile.c_str()";
1726 O << '"' << Arg << '"';
1735 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1736 /// function used by SubstituteSpecialCommands().
1737 StrVector::const_iterator
1738 SubstituteEnv (StrVector::const_iterator Pos,
1739 StrVector::const_iterator End, raw_ostream& O)
1741 const char* errorMessage = "Syntax error in $ENV invocation!";
1742 CheckedIncrement(Pos, End, errorMessage);
1743 const std::string& EnvName = *Pos;
1746 throw "$ENV invocation: empty argument list!";
1748 O << "checkCString(std::getenv(\"";
1752 CheckedIncrement(Pos, End, errorMessage);
1757 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1758 /// handler code. Helper function used by EmitCmdLineVecFill().
1759 StrVector::const_iterator
1760 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1761 StrVector::const_iterator End,
1762 bool IsJoin, raw_ostream& O)
1765 const std::string& cmd = *Pos;
1767 // Perform substitution.
1768 if (cmd == "$CALL") {
1769 Pos = SubstituteCall(Pos, End, IsJoin, O);
1771 else if (cmd == "$ENV") {
1772 Pos = SubstituteEnv(Pos, End, O);
1775 throw "Unknown special command: " + cmd;
1778 // Handle '$CMD(ARG)/additional/text'.
1779 const std::string& Leftover = *Pos;
1780 assert(Leftover.at(0) == ')');
1781 if (Leftover.size() != 1)
1782 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1787 /// EmitCmdLineVecFill - Emit code that fills in the command line
1788 /// vector. Helper function used by EmitGenerateActionMethod().
1789 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1790 bool IsJoin, unsigned IndentLevel,
1793 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1796 throw "Tool '" + ToolName + "' has empty command line!";
1798 StrVector::const_iterator B = StrVec.begin(), E = StrVec.end();
1800 // Emit the command itself.
1801 assert(!StrVec[0].empty());
1802 O.indent(IndentLevel) << "cmd = ";
1803 if (StrVec[0][0] == '$') {
1804 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1808 O << '"' << StrVec[0] << '"';
1813 // Go through the command arguments.
1815 for (; B != E; ++B) {
1816 const std::string& cmd = *B;
1818 assert(!cmd.empty());
1819 O.indent(IndentLevel);
1821 if (cmd.at(0) == '$') {
1822 O << "vec.push_back(std::make_pair(0, ";
1823 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1827 O << "vec.push_back(std::make_pair(0, \"" << cmd << "\"));\n";
1833 /// EmitForEachListElementCycleHeader - Emit common code for iterating through
1834 /// all elements of a list. Helper function used by
1835 /// EmitForwardOptionPropertyHandlingCode.
1836 void EmitForEachListElementCycleHeader (const OptionDescription& D,
1837 unsigned IndentLevel,
1839 unsigned IndentLevel1 = IndentLevel + Indent1;
1841 O.indent(IndentLevel)
1842 << "for (" << D.GenTypeDeclaration()
1843 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1844 O.indent(IndentLevel)
1845 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1846 O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName()
1847 << ".getPosition(B - " << D.GenVariableName()
1851 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1852 /// implement EmitActionHandler. Emits code for
1853 /// handling the (forward) and (forward_as) option properties.
1854 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1855 unsigned IndentLevel,
1856 const std::string& NewName,
1858 const std::string& Name = NewName.empty()
1861 unsigned IndentLevel1 = IndentLevel + Indent1;
1864 case OptionType::Switch:
1865 O.indent(IndentLevel)
1866 << "vec.push_back(std::make_pair(" << D.GenVariableName()
1867 << ".getPosition(), \"" << Name << "\"));\n";
1869 case OptionType::Parameter:
1870 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1871 << D.GenVariableName()
1872 <<".getPosition(), \"" << Name;
1874 if (!D.isForwardNotSplit()) {
1876 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1877 << D.GenVariableName() << ".getPosition(), "
1878 << D.GenVariableName() << "));\n";
1881 O << "=\" + " << D.GenVariableName() << "));\n";
1884 case OptionType::Prefix:
1885 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1886 << D.GenVariableName() << ".getPosition(), \""
1888 << D.GenVariableName() << "));\n";
1890 case OptionType::PrefixList:
1891 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1892 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1893 << Name << "\" + " << "*B));\n";
1894 O.indent(IndentLevel1) << "++B;\n";
1896 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1897 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1898 O.indent(IndentLevel1) << "++B;\n";
1901 O.indent(IndentLevel) << "}\n";
1903 case OptionType::ParameterList:
1904 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1905 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1906 << Name << "\"));\n";
1908 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1909 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1910 O.indent(IndentLevel1) << "++B;\n";
1913 O.indent(IndentLevel) << "}\n";
1915 case OptionType::SwitchList:
1916 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1917 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1918 << Name << "\"));\n";
1919 O.indent(IndentLevel1) << "++B;\n";
1920 O.indent(IndentLevel) << "}\n";
1922 case OptionType::Alias:
1924 throw "Aliases are not allowed in tool option descriptions!";
1928 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1929 /// EmitPreprocessOptionsCallback.
1930 struct ActionHandlingCallbackBase
1933 void onErrorDag(const DagInit& d,
1934 unsigned IndentLevel, raw_ostream& O) const
1936 O.indent(IndentLevel)
1938 << (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0)) : "Unknown error!")
1940 O.indent(IndentLevel) << "return 1;\n";
1943 void onWarningDag(const DagInit& d,
1944 unsigned IndentLevel, raw_ostream& O) const
1946 CheckNumberOfArguments(d, 1);
1947 O.indent(IndentLevel) << "llvm::errs() << \""
1948 << InitPtrToString(d.getArg(0)) << "\";\n";
1953 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1954 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1956 class EmitActionHandlersCallback;
1958 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1959 (const DagInit&, unsigned, raw_ostream&) const;
1961 class EmitActionHandlersCallback :
1962 public ActionHandlingCallbackBase,
1963 public HandlerTable<EmitActionHandlersCallbackHandler>
1965 typedef EmitActionHandlersCallbackHandler Handler;
1967 const OptionDescriptions& OptDescs;
1969 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1970 /// onAppendCmd and onOutputSuffix.
1971 void EmitHookInvocation(const std::string& Str,
1972 const char* BlockOpen, const char* BlockClose,
1973 unsigned IndentLevel, raw_ostream& O) const
1976 TokenizeCmdLine(Str, Out);
1978 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1980 const std::string& cmd = *B;
1982 O.indent(IndentLevel) << BlockOpen;
1984 if (cmd.at(0) == '$')
1985 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1987 O << '"' << cmd << '"';
1993 void onAppendCmd (const DagInit& Dag,
1994 unsigned IndentLevel, raw_ostream& O) const
1996 CheckNumberOfArguments(Dag, 1);
1997 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1998 "vec.push_back(std::make_pair(65536, ", "));\n",
2002 void onForward (const DagInit& Dag,
2003 unsigned IndentLevel, raw_ostream& O) const
2005 CheckNumberOfArguments(Dag, 1);
2006 const std::string& Name = InitPtrToString(Dag.getArg(0));
2007 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2008 IndentLevel, "", O);
2011 void onForwardAs (const DagInit& Dag,
2012 unsigned IndentLevel, raw_ostream& O) const
2014 CheckNumberOfArguments(Dag, 2);
2015 const std::string& Name = InitPtrToString(Dag.getArg(0));
2016 const std::string& NewName = InitPtrToString(Dag.getArg(1));
2017 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2018 IndentLevel, NewName, O);
2021 void onForwardValue (const DagInit& Dag,
2022 unsigned IndentLevel, raw_ostream& O) const
2024 CheckNumberOfArguments(Dag, 1);
2025 const std::string& Name = InitPtrToString(Dag.getArg(0));
2026 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2028 if (D.isSwitchList()) {
2029 throw std::runtime_error
2030 ("forward_value is not allowed with switch_list");
2033 if (D.isParameter()) {
2034 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2035 << D.GenVariableName() << ".getPosition(), "
2036 << D.GenVariableName() << "));\n";
2039 O.indent(IndentLevel) << "for (" << D.GenTypeDeclaration()
2040 << "::iterator B = " << D.GenVariableName()
2042 O.indent(IndentLevel + Indent1) << " E = " << D.GenVariableName()
2043 << ".end(); B != E; ++B)\n";
2044 O.indent(IndentLevel) << "{\n";
2045 O.indent(IndentLevel + Indent1)
2046 << "unsigned pos = " << D.GenVariableName()
2047 << ".getPosition(B - " << D.GenVariableName()
2049 O.indent(IndentLevel + Indent1)
2050 << "vec.push_back(std::make_pair(pos, *B));\n";
2051 O.indent(IndentLevel) << "}\n";
2055 void onForwardTransformedValue (const DagInit& Dag,
2056 unsigned IndentLevel, raw_ostream& O) const
2058 CheckNumberOfArguments(Dag, 2);
2059 const std::string& Name = InitPtrToString(Dag.getArg(0));
2060 const std::string& Hook = InitPtrToString(Dag.getArg(1));
2061 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2063 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2064 << D.GenVariableName() << ".getPosition("
2065 << (D.isList() ? "0" : "") << "), "
2066 << "hooks::" << Hook << "(" << D.GenVariableName()
2067 << (D.isParameter() ? ".c_str()" : "") << ")));\n";
2070 void onNoOutFile (const DagInit& Dag,
2071 unsigned IndentLevel, raw_ostream& O) const
2073 CheckNumberOfArguments(Dag, 0);
2074 O.indent(IndentLevel) << "no_out_file = true;\n";
2077 void onOutputSuffix (const DagInit& Dag,
2078 unsigned IndentLevel, raw_ostream& O) const
2080 CheckNumberOfArguments(Dag, 1);
2081 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2082 "output_suffix = ", ";\n", IndentLevel, O);
2085 void onStopCompilation (const DagInit& Dag,
2086 unsigned IndentLevel, raw_ostream& O) const
2088 O.indent(IndentLevel) << "stop_compilation = true;\n";
2092 void onUnpackValues (const DagInit& Dag,
2093 unsigned IndentLevel, raw_ostream& O) const
2095 throw "'unpack_values' is deprecated. "
2096 "Use 'comma_separated' + 'forward_value' instead!";
2101 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
2104 if (!staticMembersInitialized_) {
2105 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
2106 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
2107 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
2108 AddHandler("forward", &EmitActionHandlersCallback::onForward);
2109 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
2110 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
2111 AddHandler("forward_transformed_value",
2112 &EmitActionHandlersCallback::onForwardTransformedValue);
2113 AddHandler("no_out_file",
2114 &EmitActionHandlersCallback::onNoOutFile);
2115 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
2116 AddHandler("stop_compilation",
2117 &EmitActionHandlersCallback::onStopCompilation);
2118 AddHandler("unpack_values",
2119 &EmitActionHandlersCallback::onUnpackValues);
2122 staticMembersInitialized_ = true;
2126 void operator()(const Init* I,
2127 unsigned IndentLevel, raw_ostream& O) const
2129 InvokeDagInitHandler(this, I, IndentLevel, O);
2133 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2134 bool IsJoin, bool Naked,
2137 O.indent(Indent1) << "int GenerateAction(Action& Out,\n";
2140 O.indent(Indent2) << "const PathVector& inFiles,\n";
2142 O.indent(Indent2) << "const sys::Path& inFile,\n";
2144 O.indent(Indent2) << "const bool HasChildren,\n";
2145 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2146 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2147 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2148 O.indent(Indent1) << "{\n";
2151 O.indent(Indent2) << "std::string cmd;\n";
2152 O.indent(Indent2) << "std::string out_file;\n";
2154 << "std::vector<std::pair<unsigned, std::string> > vec;\n";
2155 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2156 O.indent(Indent2) << "bool no_out_file = false;\n";
2157 O.indent(Indent2) << "std::string output_suffix(\""
2158 << D.OutputSuffix << "\");\n";
2162 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2163 // Tool::GenerateAction() method.
2164 void EmitGenerateActionMethod (const ToolDescription& D,
2165 const OptionDescriptions& OptDescs,
2166 bool IsJoin, raw_ostream& O) {
2168 EmitGenerateActionMethodHeader(D, IsJoin, /* Naked = */ false, O);
2171 throw "Tool " + D.Name + " has no cmd_line property!";
2173 // Process the 'command' property.
2175 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2178 // Process the 'actions' list of this tool.
2180 EmitCaseConstructHandler(D.Actions, Indent2,
2181 EmitActionHandlersCallback(OptDescs),
2182 false, OptDescs, O);
2186 if (!D.InFileOption.empty()) {
2188 << "vec.push_back(std::make_pair(InputFilenames.getPosition(0), \""
2189 << D.InFileOption << "\");\n";
2194 << "for (PathVector::const_iterator B = inFiles.begin(),\n";
2195 O.indent(Indent3) << "E = inFiles.end(); B != E; ++B)\n";
2196 O.indent(Indent2) << "{\n";
2197 O.indent(Indent3) << "vec.push_back(std::make_pair("
2198 << "InputFilenames.getPosition(B - inFiles.begin()), "
2200 O.indent(Indent2) << "}\n";
2203 O.indent(Indent2) << "vec.push_back(std::make_pair("
2204 << "InputFilenames.getPosition(0), inFile.str()));\n";
2208 O.indent(Indent2) << "if (!no_out_file) {\n";
2209 if (!D.OutFileOption.empty())
2210 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, \""
2211 << D.OutFileOption << "\"));\n";
2213 O.indent(Indent3) << "out_file = this->OutFilename("
2214 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2215 O.indent(Indent4) <<
2216 "TempDir, stop_compilation, output_suffix.c_str()).str();\n\n";
2217 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, out_file));\n";
2219 O.indent(Indent2) << "}\n\n";
2221 // Handle the Sink property.
2222 std::string SinkOption("autogenerated::");
2223 SinkOption += SinkOptionName;
2225 O.indent(Indent2) << "if (!" << SinkOption << ".empty()) {\n";
2226 O.indent(Indent3) << "for (cl::list<std::string>::iterator B = "
2227 << SinkOption << ".begin(), E = " << SinkOption
2228 << ".end(); B != E; ++B)\n";
2229 O.indent(Indent4) << "vec.push_back(std::make_pair(" << SinkOption
2230 << ".getPosition(B - " << SinkOption
2231 << ".begin()), *B));\n";
2232 O.indent(Indent2) << "}\n";
2235 O.indent(Indent2) << "Out.Construct(cmd, this->SortArgs(vec), "
2236 << "stop_compilation, out_file);\n";
2237 O.indent(Indent2) << "return 0;\n";
2238 O.indent(Indent1) << "}\n\n";
2241 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2242 /// a given Tool class.
2243 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2244 const OptionDescriptions& OptDescs,
2246 if (!ToolDesc.isJoin()) {
2247 EmitGenerateActionMethodHeader(ToolDesc, /* IsJoin = */ true,
2248 /* Naked = */ true, O);
2249 O.indent(Indent2) << "PrintError(\"" << ToolDesc.Name
2250 << " is not a Join tool!\");\n";
2251 O.indent(Indent2) << "return -1;\n";
2252 O.indent(Indent1) << "}\n\n";
2255 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2258 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2261 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2262 /// methods for a given Tool class.
2263 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2264 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2265 O.indent(Indent2) << "return InputLanguages_;\n";
2266 O.indent(Indent1) << "}\n\n";
2268 if (D.OutLanguage.empty())
2269 throw "Tool " + D.Name + " has no 'out_language' property!";
2271 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2272 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2273 O.indent(Indent1) << "}\n\n";
2276 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2277 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2278 O.indent(Indent1) << "const char* Name() const {\n";
2279 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2280 O.indent(Indent1) << "}\n\n";
2283 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2285 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2286 O.indent(Indent1) << "bool IsJoin() const {\n";
2288 O.indent(Indent2) << "return true;\n";
2290 O.indent(Indent2) << "return false;\n";
2291 O.indent(Indent1) << "}\n\n";
2294 /// EmitWorksOnEmptyCallback - Callback used by EmitWorksOnEmptyMethod in
2295 /// conjunction with EmitCaseConstructHandler.
2296 void EmitWorksOnEmptyCallback (const Init* Value,
2297 unsigned IndentLevel, raw_ostream& O) {
2298 CheckBooleanConstant(Value);
2299 O.indent(IndentLevel) << "return " << Value->getAsString() << ";\n";
2302 /// EmitWorksOnEmptyMethod - Emit the WorksOnEmpty() method for a given Tool
2304 void EmitWorksOnEmptyMethod (const ToolDescription& D,
2305 const OptionDescriptions& OptDescs,
2308 O.indent(Indent1) << "bool WorksOnEmpty() const {\n";
2310 O.indent(Indent2) << "return false;\n";
2312 EmitCaseConstructHandler(D.OnEmpty, Indent2, EmitWorksOnEmptyCallback,
2313 /*EmitElseIf = */ true, OptDescs, O);
2314 O.indent(Indent1) << "}\n\n";
2317 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2318 /// given Tool class.
2319 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2320 if (D.InLanguage.empty())
2321 throw "Tool " + D.Name + " has no 'in_language' property!";
2323 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2324 for (StrVector::const_iterator B = D.InLanguage.begin(),
2325 E = D.InLanguage.end(); B != E; ++B)
2326 O << '\"' << *B << "\", ";
2330 /// EmitToolClassDefinition - Emit a Tool class definition.
2331 void EmitToolClassDefinition (const ToolDescription& D,
2332 const OptionDescriptions& OptDescs,
2334 if (D.Name == "root")
2338 O << "class " << D.Name << " : public ";
2344 O << " {\nprivate:\n";
2345 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2348 EmitNameMethod(D, O);
2349 EmitInOutLanguageMethods(D, O);
2350 EmitIsJoinMethod(D, O);
2351 EmitWorksOnEmptyMethod(D, OptDescs, O);
2352 EmitGenerateActionMethods(D, OptDescs, O);
2354 // Close class definition
2357 EmitStaticMemberDefinitions(D, O);
2361 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2362 /// and emit registration code.
2363 void EmitOptionDefinitions (const OptionDescriptions& descs,
2364 bool HasSink, raw_ostream& O)
2366 std::vector<OptionDescription> Aliases;
2368 // Emit static cl::Option variables.
2369 for (OptionDescriptions::const_iterator B = descs.begin(),
2370 E = descs.end(); B!=E; ++B) {
2371 const OptionDescription& val = B->second;
2373 if (val.Type == OptionType::Alias) {
2374 Aliases.push_back(val);
2378 O << val.GenTypeDeclaration() << ' '
2379 << val.GenPlainVariableName();
2381 O << "(\"" << val.Name << "\"\n";
2383 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2384 O << ", cl::Prefix";
2386 if (val.isRequired()) {
2387 if (val.isList() && !val.isMultiVal())
2388 O << ", cl::OneOrMore";
2390 O << ", cl::Required";
2393 if (val.isOptional())
2394 O << ", cl::Optional";
2396 if (val.isOneOrMore())
2397 O << ", cl::OneOrMore";
2399 if (val.isZeroOrMore())
2400 O << ", cl::ZeroOrMore";
2402 if (val.isReallyHidden())
2403 O << ", cl::ReallyHidden";
2404 else if (val.isHidden())
2405 O << ", cl::Hidden";
2407 if (val.isCommaSeparated())
2408 O << ", cl::CommaSeparated";
2410 if (val.MultiVal > 1)
2411 O << ", cl::multi_val(" << val.MultiVal << ')';
2414 const std::string& str = val.InitVal->getAsString();
2415 O << ", cl::init(" << str << ')';
2418 if (!val.Help.empty())
2419 O << ", cl::desc(\"" << val.Help << "\")";
2424 // Emit the aliases (they should go after all the 'proper' options).
2425 for (std::vector<OptionDescription>::const_iterator
2426 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2427 const OptionDescription& val = *B;
2429 O << val.GenTypeDeclaration() << ' '
2430 << val.GenVariableName()
2431 << "(\"" << val.Name << '\"';
2433 const OptionDescription& D = descs.FindOption(val.Help);
2434 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2436 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2439 // Emit the sink option.
2441 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
2446 /// EmitPreprocessOptionsCallback - Helper function passed to
2447 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2449 class EmitPreprocessOptionsCallback;
2452 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2453 (const DagInit&, unsigned, raw_ostream&) const;
2455 class EmitPreprocessOptionsCallback :
2456 public ActionHandlingCallbackBase,
2457 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2459 typedef EmitPreprocessOptionsCallbackHandler Handler;
2461 (EmitPreprocessOptionsCallback::* HandlerImpl)
2462 (const Init*, unsigned, raw_ostream&) const;
2464 const OptionDescriptions& OptDescs_;
2466 void onListOrDag(const DagInit& d, HandlerImpl h,
2467 unsigned IndentLevel, raw_ostream& O) const
2469 CheckNumberOfArguments(d, 1);
2470 const Init* I = d.getArg(0);
2472 // If I is a list, apply h to each element.
2473 if (typeid(*I) == typeid(ListInit)) {
2474 const ListInit& L = *static_cast<const ListInit*>(I);
2475 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2476 ((this)->*(h))(*B, IndentLevel, O);
2478 // Otherwise, apply h to I.
2480 ((this)->*(h))(I, IndentLevel, O);
2484 void onUnsetOptionImpl(const Init* I,
2485 unsigned IndentLevel, raw_ostream& O) const
2487 const std::string& OptName = InitPtrToString(I);
2488 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2490 if (OptDesc.isSwitch()) {
2491 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2493 else if (OptDesc.isParameter()) {
2494 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2496 else if (OptDesc.isList()) {
2497 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2500 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2504 void onUnsetOption(const DagInit& d,
2505 unsigned IndentLevel, raw_ostream& O) const
2507 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2511 void onSetOptionImpl(const DagInit& d,
2512 unsigned IndentLevel, raw_ostream& O) const {
2513 CheckNumberOfArguments(d, 2);
2514 const std::string& OptName = InitPtrToString(d.getArg(0));
2515 const Init* Value = d.getArg(1);
2516 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2518 if (OptDesc.isList()) {
2519 const ListInit& List = InitPtrToList(Value);
2521 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2522 for (ListInit::const_iterator B = List.begin(), E = List.end();
2524 const Init* CurElem = *B;
2525 if (OptDesc.isSwitchList())
2526 CheckBooleanConstant(CurElem);
2528 O.indent(IndentLevel)
2529 << OptDesc.GenVariableName() << ".push_back(\""
2530 << (OptDesc.isSwitchList() ? CurElem->getAsString()
2531 : InitPtrToString(CurElem))
2535 else if (OptDesc.isSwitch()) {
2536 CheckBooleanConstant(Value);
2537 O.indent(IndentLevel) << OptDesc.GenVariableName()
2538 << " = " << Value->getAsString() << ";\n";
2540 else if (OptDesc.isParameter()) {
2541 const std::string& Str = InitPtrToString(Value);
2542 O.indent(IndentLevel) << OptDesc.GenVariableName()
2543 << " = \"" << Str << "\";\n";
2546 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2550 void onSetSwitch(const Init* I,
2551 unsigned IndentLevel, raw_ostream& O) const {
2552 const std::string& OptName = InitPtrToString(I);
2553 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2555 if (OptDesc.isSwitch())
2556 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2558 throw "set_option: -" + OptName + " is not a switch option!";
2561 void onSetOption(const DagInit& d,
2562 unsigned IndentLevel, raw_ostream& O) const
2564 CheckNumberOfArguments(d, 1);
2566 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2567 // boolean, a string or a string list.
2568 if (d.getNumArgs() > 1)
2569 this->onSetOptionImpl(d, IndentLevel, O);
2570 // One argument: (set_option "switch")
2571 // or (set_option ["switch1", "switch2", ...])
2573 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2579 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2580 : OptDescs_(OptDescs)
2582 if (!staticMembersInitialized_) {
2583 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2584 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2585 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2586 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2588 staticMembersInitialized_ = true;
2592 void operator()(const Init* I,
2593 unsigned IndentLevel, raw_ostream& O) const
2595 InvokeDagInitHandler(this, I, IndentLevel, O);
2600 /// EmitPreprocessOptions - Emit the PreprocessOptions() function.
2601 void EmitPreprocessOptions (const RecordKeeper& Records,
2602 const OptionDescriptions& OptDecs, raw_ostream& O)
2604 O << "int PreprocessOptions () {\n";
2606 const RecordVector& OptionPreprocessors =
2607 Records.getAllDerivedDefinitions("OptionPreprocessor");
2609 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2610 E = OptionPreprocessors.end(); B!=E; ++B) {
2611 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2612 EmitCaseConstructHandler(Case, Indent1,
2613 EmitPreprocessOptionsCallback(OptDecs),
2618 O.indent(Indent1) << "return 0;\n";
2622 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
2623 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2625 O << "int PopulateLanguageMap (LanguageMap& langMap) {\n";
2627 // Get the relevant field out of RecordKeeper
2628 // TODO: change this to getAllDerivedDefinitions.
2629 const Record* LangMapRecord = Records.getDef("LanguageMap");
2631 // It is allowed for a plugin to have no language map.
2632 if (LangMapRecord) {
2634 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2635 if (!LangsToSuffixesList)
2636 throw "Error in the language map definition!";
2638 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2639 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2641 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2642 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2644 for (unsigned i = 0; i < Suffixes->size(); ++i)
2645 O.indent(Indent1) << "langMap[\""
2646 << InitPtrToString(Suffixes->getElement(i))
2647 << "\"] = \"" << Lang << "\";\n";
2652 O.indent(Indent1) << "return 0;\n";
2656 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2657 /// by EmitEdgeClass().
2658 void IncDecWeight (const Init* i, unsigned IndentLevel,
2660 const DagInit& d = InitPtrToDag(i);
2661 const std::string& OpName = GetOperatorName(d);
2663 if (OpName == "inc_weight") {
2664 O.indent(IndentLevel) << "ret += ";
2666 else if (OpName == "dec_weight") {
2667 O.indent(IndentLevel) << "ret -= ";
2669 else if (OpName == "error") {
2671 CheckNumberOfArguments(d, 1);
2672 O.indent(IndentLevel) << "PrintError(\""
2673 << InitPtrToString(d.getArg(0))
2675 O.indent(IndentLevel) << "return -1;\n";
2679 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2680 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2683 if (d.getNumArgs() > 0)
2684 O << InitPtrToInt(d.getArg(0)) << ";\n";
2690 /// EmitEdgeClass - Emit a single Edge# class.
2691 void EmitEdgeClass (unsigned N, const std::string& Target,
2692 DagInit* Case, const OptionDescriptions& OptDescs,
2695 // Class constructor.
2696 O << "class Edge" << N << ": public Edge {\n"
2698 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2701 // Function Weight().
2703 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2704 O.indent(Indent2) << "unsigned ret = 0;\n";
2706 // Handle the 'case' construct.
2707 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2709 O.indent(Indent2) << "return ret;\n";
2710 O.indent(Indent1) << "}\n\n};\n\n";
2713 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2714 void EmitEdgeClasses (const RecordVector& EdgeVector,
2715 const OptionDescriptions& OptDescs,
2718 for (RecordVector::const_iterator B = EdgeVector.begin(),
2719 E = EdgeVector.end(); B != E; ++B) {
2720 const Record* Edge = *B;
2721 const std::string& NodeB = Edge->getValueAsString("b");
2722 DagInit& Weight = *Edge->getValueAsDag("weight");
2724 if (!IsDagEmpty(Weight))
2725 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2730 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph() function.
2731 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2732 const ToolDescriptions& ToolDescs,
2735 O << "int PopulateCompilationGraph (CompilationGraph& G) {\n";
2737 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2738 E = ToolDescs.end(); B != E; ++B)
2739 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2746 for (RecordVector::const_iterator B = EdgeVector.begin(),
2747 E = EdgeVector.end(); B != E; ++B) {
2748 const Record* Edge = *B;
2749 const std::string& NodeA = Edge->getValueAsString("a");
2750 const std::string& NodeB = Edge->getValueAsString("b");
2751 DagInit& Weight = *Edge->getValueAsDag("weight");
2753 O.indent(Indent1) << "if (int ret = G.insertEdge(\"" << NodeA << "\", ";
2755 if (IsDagEmpty(Weight))
2756 O << "new SimpleEdge(\"" << NodeB << "\")";
2758 O << "new Edge" << i << "()";
2761 O.indent(Indent2) << "return ret;\n";
2767 O.indent(Indent1) << "return 0;\n";
2771 /// HookInfo - Information about the hook type and number of arguments.
2774 // A hook can either have a single parameter of type std::vector<std::string>,
2775 // or NumArgs parameters of type const char*.
2776 enum HookType { ListHook, ArgHook };
2781 HookInfo() : Type(ArgHook), NumArgs(1)
2784 HookInfo(HookType T) : Type(T), NumArgs(1)
2787 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2791 typedef llvm::StringMap<HookInfo> HookInfoMap;
2793 /// ExtractHookNames - Extract the hook names from all instances of
2794 /// $CALL(HookName) in the provided command line string/action. Helper
2795 /// function used by FillInHookNames().
2796 class ExtractHookNames {
2797 HookInfoMap& HookNames_;
2798 const OptionDescriptions& OptDescs_;
2800 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2801 : HookNames_(HookNames), OptDescs_(OptDescs)
2804 void onAction (const DagInit& Dag) {
2805 const std::string& Name = GetOperatorName(Dag);
2807 if (Name == "forward_transformed_value") {
2808 CheckNumberOfArguments(Dag, 2);
2809 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2810 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2811 const OptionDescription& D =
2812 OptDescs_.FindParameterListOrParameter(OptName);
2814 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2815 : HookInfo::ArgHook);
2817 else if (Name == "append_cmd" || Name == "output_suffix") {
2818 CheckNumberOfArguments(Dag, 1);
2819 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2823 void onCmdLine(const std::string& Cmd) {
2825 TokenizeCmdLine(Cmd, cmds);
2827 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2829 const std::string& cmd = *B;
2831 if (cmd == "$CALL") {
2832 unsigned NumArgs = 0;
2833 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2834 const std::string& HookName = *B;
2836 if (HookName.at(0) == ')')
2837 throw "$CALL invoked with no arguments!";
2839 while (++B != E && B->at(0) != ')') {
2843 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2845 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2846 H->second.Type != HookInfo::ArgHook)
2847 throw "Overloading of hooks is not allowed. Overloaded hook: "
2850 HookNames_[HookName] = HookInfo(NumArgs);
2855 void operator()(const Init* Arg) {
2857 // We're invoked on an action (either a dag or a dag list).
2858 if (typeid(*Arg) == typeid(DagInit)) {
2859 const DagInit& Dag = InitPtrToDag(Arg);
2860 this->onAction(Dag);
2863 else if (typeid(*Arg) == typeid(ListInit)) {
2864 const ListInit& List = InitPtrToList(Arg);
2865 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2867 const DagInit& Dag = InitPtrToDag(*B);
2868 this->onAction(Dag);
2873 // We're invoked on a command line.
2874 this->onCmdLine(InitPtrToString(Arg));
2877 void operator()(const DagInit* Test, unsigned, bool) {
2878 this->operator()(Test);
2880 void operator()(const Init* Statement, unsigned) {
2881 this->operator()(Statement);
2885 /// FillInHookNames - Actually extract the hook names from all command
2886 /// line strings. Helper function used by EmitHookDeclarations().
2887 void FillInHookNames(const ToolDescriptions& ToolDescs,
2888 const OptionDescriptions& OptDescs,
2889 HookInfoMap& HookNames)
2891 // For all tool descriptions:
2892 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2893 E = ToolDescs.end(); B != E; ++B) {
2894 const ToolDescription& D = *(*B);
2896 // Look for 'forward_transformed_value' in 'actions'.
2898 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2900 // Look for hook invocations in 'cmd_line'.
2903 if (dynamic_cast<StringInit*>(D.CmdLine))
2904 // This is a string.
2905 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2907 // This is a 'case' construct.
2908 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2912 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2913 /// property records and emit hook function declaration for each
2914 /// instance of $CALL(HookName).
2915 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2916 const OptionDescriptions& OptDescs, raw_ostream& O) {
2917 HookInfoMap HookNames;
2919 FillInHookNames(ToolDescs, OptDescs, HookNames);
2920 if (HookNames.empty())
2923 for (HookInfoMap::const_iterator B = HookNames.begin(),
2924 E = HookNames.end(); B != E; ++B) {
2925 const char* HookName = B->first();
2926 const HookInfo& Info = B->second;
2928 O.indent(Indent1) << "std::string " << HookName << "(";
2930 if (Info.Type == HookInfo::ArgHook) {
2931 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2932 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2936 O << "const std::vector<std::string>& Arg";
2943 /// EmitIncludes - Emit necessary #include directives and some
2944 /// additional declarations.
2945 void EmitIncludes(raw_ostream& O) {
2946 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2947 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2948 << "#include \"llvm/CompilerDriver/Error.h\"\n"
2949 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2951 << "#include \"llvm/Support/CommandLine.h\"\n"
2952 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2954 << "#include <algorithm>\n"
2955 << "#include <cstdlib>\n"
2956 << "#include <iterator>\n"
2957 << "#include <stdexcept>\n\n"
2959 << "using namespace llvm;\n"
2960 << "using namespace llvmc;\n\n"
2962 << "inline const char* checkCString(const char* s)\n"
2963 << "{ return s == NULL ? \"\" : s; }\n\n";
2967 /// PluginData - Holds all information about a plugin.
2969 OptionDescriptions OptDescs;
2971 ToolDescriptions ToolDescs;
2975 /// HasSink - Go through the list of tool descriptions and check if
2976 /// there are any with the 'sink' property set.
2977 bool HasSink(const ToolDescriptions& ToolDescs) {
2978 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2979 E = ToolDescs.end(); B != E; ++B)
2986 /// CollectPluginData - Collect compilation graph edges, tool properties and
2987 /// option properties from the parse tree.
2988 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2989 // Collect option properties.
2990 const RecordVector& OptionLists =
2991 Records.getAllDerivedDefinitions("OptionList");
2992 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2995 // Collect tool properties.
2996 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2997 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2998 Data.HasSink = HasSink(Data.ToolDescs);
3000 // Collect compilation graph edges.
3001 const RecordVector& CompilationGraphs =
3002 Records.getAllDerivedDefinitions("CompilationGraph");
3003 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
3007 /// CheckPluginData - Perform some sanity checks on the collected data.
3008 void CheckPluginData(PluginData& Data) {
3009 // Filter out all tools not mentioned in the compilation graph.
3010 FilterNotInGraph(Data.Edges, Data.ToolDescs);
3012 // Typecheck the compilation graph.
3013 TypecheckGraph(Data.Edges, Data.ToolDescs);
3015 // Check that there are no options without side effects (specified
3016 // only in the OptionList).
3017 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
3020 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
3021 // Emit file header.
3024 // Emit global option registration code.
3025 O << "namespace llvmc {\n"
3026 << "namespace autogenerated {\n\n";
3027 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, O);
3028 O << "} // End namespace autogenerated.\n"
3029 << "} // End namespace llvmc.\n\n";
3031 // Emit hook declarations.
3032 O << "namespace hooks {\n";
3033 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
3034 O << "} // End namespace hooks.\n\n";
3036 O << "namespace {\n\n";
3037 O << "using namespace llvmc::autogenerated;\n\n";
3039 // Emit Tool classes.
3040 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
3041 E = Data.ToolDescs.end(); B!=E; ++B)
3042 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
3044 // Emit Edge# classes.
3045 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
3047 O << "} // End anonymous namespace.\n\n";
3049 O << "namespace llvmc {\n";
3050 O << "namespace autogenerated {\n\n";
3052 // Emit PreprocessOptions() function.
3053 EmitPreprocessOptions(Records, Data.OptDescs, O);
3055 // Emit PopulateLanguageMap() function
3056 // (language map maps from file extensions to language names).
3057 EmitPopulateLanguageMap(Records, O);
3059 // Emit PopulateCompilationGraph() function.
3060 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
3062 O << "} // End namespace autogenerated.\n";
3063 O << "} // End namespace llvmc.\n\n";
3069 // End of anonymous namespace
3072 /// run - The back-end entry point.
3073 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
3077 CollectPluginData(Records, Data);
3078 CheckPluginData(Data);
3080 this->EmitSourceFileHeader("LLVMC Configuration Library", O);
3081 EmitPluginCode(Data, O);
3083 } catch (std::exception& Error) {
3084 throw Error.what() + std::string(" - usually this means a syntax error.");