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 = "AutoGeneratedSinkOption";
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;
266 /// Merge - Merge two option descriptions.
267 void Merge (const OptionDescription& other);
269 /// CheckConsistency - Check that the flags are consistent.
270 void CheckConsistency() const;
272 // Misc convenient getters/setters.
274 bool isAlias() const;
276 bool isMultiVal() const;
278 bool isCommaSeparated() const;
279 void setCommaSeparated();
281 bool isForwardNotSplit() const;
282 void setForwardNotSplit();
284 bool isRequired() const;
287 bool isOneOrMore() const;
290 bool isZeroOrMore() const;
291 void setZeroOrMore();
293 bool isOptional() const;
296 bool isHidden() const;
299 bool isReallyHidden() const;
300 void setReallyHidden();
302 bool isSwitch() const
303 { return OptionType::IsSwitch(this->Type); }
305 bool isSwitchList() const
306 { return OptionType::IsSwitchList(this->Type); }
308 bool isParameter() const
309 { return OptionType::IsParameter(this->Type); }
312 { return OptionType::IsList(this->Type); }
314 bool isParameterList() const
315 { return (OptionType::IsList(this->Type)
316 && !OptionType::IsSwitchList(this->Type)); }
320 void OptionDescription::CheckConsistency() const {
323 i += this->isRequired();
324 i += this->isOptional();
325 i += this->isOneOrMore();
326 i += this->isZeroOrMore();
329 throw "Only one of (required), (optional), (one_or_more) or "
330 "(zero_or_more) properties is allowed!";
334 void OptionDescription::Merge (const OptionDescription& other)
336 if (other.Type != Type)
337 throw "Conflicting definitions for the option " + Name + "!";
339 if (Help == other.Help || Help == DefaultHelpString)
341 else if (other.Help != DefaultHelpString) {
342 llvm::errs() << "Warning: several different help strings"
343 " defined for option " + Name + "\n";
346 Flags |= other.Flags;
349 bool OptionDescription::isAlias() const {
350 return OptionType::IsAlias(this->Type);
353 bool OptionDescription::isMultiVal() const {
357 bool OptionDescription::isCommaSeparated() const {
358 return Flags & OptionDescriptionFlags::CommaSeparated;
360 void OptionDescription::setCommaSeparated() {
361 Flags |= OptionDescriptionFlags::CommaSeparated;
364 bool OptionDescription::isForwardNotSplit() const {
365 return Flags & OptionDescriptionFlags::ForwardNotSplit;
367 void OptionDescription::setForwardNotSplit() {
368 Flags |= OptionDescriptionFlags::ForwardNotSplit;
371 bool OptionDescription::isRequired() const {
372 return Flags & OptionDescriptionFlags::Required;
374 void OptionDescription::setRequired() {
375 Flags |= OptionDescriptionFlags::Required;
378 bool OptionDescription::isOneOrMore() const {
379 return Flags & OptionDescriptionFlags::OneOrMore;
381 void OptionDescription::setOneOrMore() {
382 Flags |= OptionDescriptionFlags::OneOrMore;
385 bool OptionDescription::isZeroOrMore() const {
386 return Flags & OptionDescriptionFlags::ZeroOrMore;
388 void OptionDescription::setZeroOrMore() {
389 Flags |= OptionDescriptionFlags::ZeroOrMore;
392 bool OptionDescription::isOptional() const {
393 return Flags & OptionDescriptionFlags::Optional;
395 void OptionDescription::setOptional() {
396 Flags |= OptionDescriptionFlags::Optional;
399 bool OptionDescription::isHidden() const {
400 return Flags & OptionDescriptionFlags::Hidden;
402 void OptionDescription::setHidden() {
403 Flags |= OptionDescriptionFlags::Hidden;
406 bool OptionDescription::isReallyHidden() const {
407 return Flags & OptionDescriptionFlags::ReallyHidden;
409 void OptionDescription::setReallyHidden() {
410 Flags |= OptionDescriptionFlags::ReallyHidden;
413 const char* OptionDescription::GenTypeDeclaration() const {
415 case OptionType::Alias:
417 case OptionType::PrefixList:
418 case OptionType::ParameterList:
419 return "cl::list<std::string>";
420 case OptionType::Switch:
421 return "cl::opt<bool>";
422 case OptionType::SwitchList:
423 return "cl::list<bool>";
424 case OptionType::Parameter:
425 case OptionType::Prefix:
427 return "cl::opt<std::string>";
431 std::string OptionDescription::GenVariableName() const {
432 const std::string& EscapedName = EscapeVariableName(Name);
434 case OptionType::Alias:
435 return "AutoGeneratedAlias_" + EscapedName;
436 case OptionType::PrefixList:
437 case OptionType::ParameterList:
438 return "AutoGeneratedList_" + EscapedName;
439 case OptionType::Switch:
440 return "AutoGeneratedSwitch_" + EscapedName;
441 case OptionType::SwitchList:
442 return "AutoGeneratedSwitchList_" + EscapedName;
443 case OptionType::Prefix:
444 case OptionType::Parameter:
446 return "AutoGeneratedParameter_" + EscapedName;
450 /// OptionDescriptions - An OptionDescription array plus some helper
452 class OptionDescriptions {
453 typedef StringMap<OptionDescription> container_type;
455 /// Descriptions - A list of OptionDescriptions.
456 container_type Descriptions;
459 /// FindOption - exception-throwing wrapper for find().
460 const OptionDescription& FindOption(const std::string& OptName) const;
462 // Wrappers for FindOption that throw an exception in case the option has a
464 const OptionDescription& FindSwitch(const std::string& OptName) const;
465 const OptionDescription& FindParameter(const std::string& OptName) const;
466 const OptionDescription& FindList(const std::string& OptName) const;
467 const OptionDescription& FindParameterList(const std::string& OptName) const;
468 const OptionDescription&
469 FindListOrParameter(const std::string& OptName) const;
470 const OptionDescription&
471 FindParameterListOrParameter(const std::string& OptName) const;
473 /// insertDescription - Insert new OptionDescription into
474 /// OptionDescriptions list
475 void InsertDescription (const OptionDescription& o);
477 // Support for STL-style iteration
478 typedef container_type::const_iterator const_iterator;
479 const_iterator begin() const { return Descriptions.begin(); }
480 const_iterator end() const { return Descriptions.end(); }
483 const OptionDescription&
484 OptionDescriptions::FindOption(const std::string& OptName) const {
485 const_iterator I = Descriptions.find(OptName);
486 if (I != Descriptions.end())
489 throw OptName + ": no such option!";
492 const OptionDescription&
493 OptionDescriptions::FindSwitch(const std::string& OptName) const {
494 const OptionDescription& OptDesc = this->FindOption(OptName);
495 if (!OptDesc.isSwitch())
496 throw OptName + ": incorrect option type - should be a switch!";
500 const OptionDescription&
501 OptionDescriptions::FindList(const std::string& OptName) const {
502 const OptionDescription& OptDesc = this->FindOption(OptName);
503 if (!OptDesc.isList())
504 throw OptName + ": incorrect option type - should be a list!";
508 const OptionDescription&
509 OptionDescriptions::FindParameterList(const std::string& OptName) const {
510 const OptionDescription& OptDesc = this->FindOption(OptName);
511 if (!OptDesc.isList() || OptDesc.isSwitchList())
512 throw OptName + ": incorrect option type - should be a parameter list!";
516 const OptionDescription&
517 OptionDescriptions::FindParameter(const std::string& OptName) const {
518 const OptionDescription& OptDesc = this->FindOption(OptName);
519 if (!OptDesc.isParameter())
520 throw OptName + ": incorrect option type - should be a parameter!";
524 const OptionDescription&
525 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
526 const OptionDescription& OptDesc = this->FindOption(OptName);
527 if (!OptDesc.isList() && !OptDesc.isParameter())
529 + ": incorrect option type - should be a list or parameter!";
533 const OptionDescription&
534 OptionDescriptions::FindParameterListOrParameter
535 (const std::string& OptName) const {
536 const OptionDescription& OptDesc = this->FindOption(OptName);
537 if ((!OptDesc.isList() && !OptDesc.isParameter()) || OptDesc.isSwitchList())
539 + ": incorrect option type - should be a parameter list or parameter!";
543 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
544 container_type::iterator I = Descriptions.find(o.Name);
545 if (I != Descriptions.end()) {
546 OptionDescription& D = I->second;
550 Descriptions[o.Name] = o;
554 /// HandlerTable - A base class for function objects implemented as
555 /// 'tables of handlers'.
556 template <typename Handler>
559 // Implementation details.
561 /// HandlerMap - A map from property names to property handlers
562 typedef StringMap<Handler> HandlerMap;
564 static HandlerMap Handlers_;
565 static bool staticMembersInitialized_;
569 Handler GetHandler (const std::string& HandlerName) const {
570 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
572 if (method != Handlers_.end()) {
573 Handler h = method->second;
577 throw "No handler found for property " + HandlerName + "!";
581 void AddHandler(const char* Property, Handler H) {
582 Handlers_[Property] = H;
587 template <class Handler, class FunctionObject>
588 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
589 const std::string& HandlerName = GetOperatorName(Dag);
590 return Obj->GetHandler(HandlerName);
593 template <class FunctionObject>
594 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
595 typedef void (FunctionObject::*Handler) (const DagInit&);
597 const DagInit& Dag = InitPtrToDag(I);
598 Handler h = GetHandler<Handler>(Obj, Dag);
603 template <class FunctionObject>
604 void InvokeDagInitHandler(const FunctionObject* const Obj,
605 const Init* I, unsigned IndentLevel, raw_ostream& O)
607 typedef void (FunctionObject::*Handler)
608 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
610 const DagInit& Dag = InitPtrToDag(I);
611 Handler h = GetHandler<Handler>(Obj, Dag);
613 ((Obj)->*(h))(Dag, IndentLevel, O);
617 template <typename H>
618 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
620 template <typename H>
621 bool HandlerTable<H>::staticMembersInitialized_ = false;
624 /// CollectOptionProperties - Function object for iterating over an
625 /// option property list.
626 class CollectOptionProperties;
627 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
630 class CollectOptionProperties
631 : public HandlerTable<CollectOptionPropertiesHandler>
635 /// optDescs_ - OptionDescriptions table. This is where the
636 /// information is stored.
637 OptionDescription& optDesc_;
641 explicit CollectOptionProperties(OptionDescription& OD)
644 if (!staticMembersInitialized_) {
645 AddHandler("help", &CollectOptionProperties::onHelp);
646 AddHandler("hidden", &CollectOptionProperties::onHidden);
647 AddHandler("init", &CollectOptionProperties::onInit);
648 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
649 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
650 AddHandler("zero_or_more", &CollectOptionProperties::onZeroOrMore);
651 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
652 AddHandler("required", &CollectOptionProperties::onRequired);
653 AddHandler("optional", &CollectOptionProperties::onOptional);
654 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
655 AddHandler("forward_not_split",
656 &CollectOptionProperties::onForwardNotSplit);
658 staticMembersInitialized_ = true;
662 /// operator() - Just forwards to the corresponding property
664 void operator() (Init* I) {
665 InvokeDagInitHandler(this, I);
670 /// Option property handlers --
671 /// Methods that handle option properties such as (help) or (hidden).
673 void onHelp (const DagInit& d) {
674 CheckNumberOfArguments(d, 1);
675 optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0)));
678 void onHidden (const DagInit& d) {
679 CheckNumberOfArguments(d, 0);
680 optDesc_.setHidden();
683 void onReallyHidden (const DagInit& d) {
684 CheckNumberOfArguments(d, 0);
685 optDesc_.setReallyHidden();
688 void onCommaSeparated (const DagInit& d) {
689 CheckNumberOfArguments(d, 0);
690 if (!optDesc_.isParameterList())
691 throw "'comma_separated' is valid only on parameter list options!";
692 optDesc_.setCommaSeparated();
695 void onForwardNotSplit (const DagInit& d) {
696 CheckNumberOfArguments(d, 0);
697 if (!optDesc_.isParameter())
698 throw "'forward_not_split' is valid only for parameter options!";
699 optDesc_.setForwardNotSplit();
702 void onRequired (const DagInit& d) {
703 CheckNumberOfArguments(d, 0);
705 optDesc_.setRequired();
706 optDesc_.CheckConsistency();
709 void onInit (const DagInit& d) {
710 CheckNumberOfArguments(d, 1);
711 Init* i = d.getArg(0);
712 const std::string& str = i->getAsString();
714 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
715 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
718 throw "Incorrect usage of the 'init' option property!";
720 optDesc_.InitVal = i;
723 void onOneOrMore (const DagInit& d) {
724 CheckNumberOfArguments(d, 0);
726 optDesc_.setOneOrMore();
727 optDesc_.CheckConsistency();
730 void onZeroOrMore (const DagInit& d) {
731 CheckNumberOfArguments(d, 0);
733 if (optDesc_.isList())
734 llvm::errs() << "Warning: specifying the 'zero_or_more' property "
735 "on a list option has no effect.\n";
737 optDesc_.setZeroOrMore();
738 optDesc_.CheckConsistency();
741 void onOptional (const DagInit& d) {
742 CheckNumberOfArguments(d, 0);
744 if (!optDesc_.isList())
745 llvm::errs() << "Warning: specifying the 'optional' property"
746 "on a non-list option has no effect.\n";
748 optDesc_.setOptional();
749 optDesc_.CheckConsistency();
752 void onMultiVal (const DagInit& d) {
753 CheckNumberOfArguments(d, 1);
754 int val = InitPtrToInt(d.getArg(0));
756 throw "Error in the 'multi_val' property: "
757 "the value must be greater than 1!";
758 if (!optDesc_.isParameterList())
759 throw "The multi_val property is valid only on list options!";
760 optDesc_.MultiVal = val;
765 /// AddOption - A function object that is applied to every option
766 /// description. Used by CollectOptionDescriptions.
769 OptionDescriptions& OptDescs_;
772 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
775 void operator()(const Init* i) {
776 const DagInit& d = InitPtrToDag(i);
777 CheckNumberOfArguments(d, 1);
779 const OptionType::OptionType Type =
780 stringToOptionType(GetOperatorName(d));
781 const std::string& Name = InitPtrToString(d.getArg(0));
783 OptionDescription OD(Type, Name);
786 CheckNumberOfArguments(d, 2);
789 // Aliases store the aliased option name in the 'Help' field.
790 OD.Help = InitPtrToString(d.getArg(1));
793 processOptionProperties(d, OD);
796 OptDescs_.InsertDescription(OD);
800 /// processOptionProperties - Go through the list of option
801 /// properties and call a corresponding handler for each.
802 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
803 CheckNumberOfArguments(d, 2);
804 DagInit::const_arg_iterator B = d.arg_begin();
805 // Skip the first argument: it's always the option name.
807 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
812 /// CollectOptionDescriptions - Collects option properties from all
814 void CollectOptionDescriptions (RecordVector::const_iterator B,
815 RecordVector::const_iterator E,
816 OptionDescriptions& OptDescs)
818 // For every OptionList:
820 RecordVector::value_type T = *B;
821 // Throws an exception if the value does not exist.
822 ListInit* PropList = T->getValueAsListInit("options");
824 // For every option description in this list:
825 // collect the information and
826 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
830 // Tool information record
832 namespace ToolFlags {
833 enum ToolFlags { Join = 0x1, Sink = 0x2 };
836 struct ToolDescription : public RefCountedBase<ToolDescription> {
840 StrVector InLanguage;
841 std::string InFileOption;
842 std::string OutFileOption;
843 std::string OutLanguage;
844 std::string OutputSuffix;
848 // Various boolean properties
849 void setSink() { Flags |= ToolFlags::Sink; }
850 bool isSink() const { return Flags & ToolFlags::Sink; }
851 void setJoin() { Flags |= ToolFlags::Join; }
852 bool isJoin() const { return Flags & ToolFlags::Join; }
854 // Default ctor here is needed because StringMap can only store
855 // DefaultConstructible objects
857 : CmdLine(0), Actions(0), OutFileOption("-o"),
860 ToolDescription (const std::string& n)
861 : Name(n), CmdLine(0), Actions(0), OutFileOption("-o"),
866 /// ToolDescriptions - A list of Tool information records.
867 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
870 /// CollectToolProperties - Function object for iterating over a list of
871 /// tool property records.
873 class CollectToolProperties;
874 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
877 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
881 /// toolDesc_ - Properties of the current Tool. This is where the
882 /// information is stored.
883 ToolDescription& toolDesc_;
887 explicit CollectToolProperties (ToolDescription& d)
890 if (!staticMembersInitialized_) {
892 AddHandler("actions", &CollectToolProperties::onActions);
893 AddHandler("command", &CollectToolProperties::onCommand);
894 AddHandler("in_language", &CollectToolProperties::onInLanguage);
895 AddHandler("join", &CollectToolProperties::onJoin);
896 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
898 AddHandler("out_file_option", &CollectToolProperties::onOutFileOption);
899 AddHandler("in_file_option", &CollectToolProperties::onInFileOption);
901 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
902 AddHandler("sink", &CollectToolProperties::onSink);
903 AddHandler("works_on_empty", &CollectToolProperties::onWorksOnEmpty);
905 staticMembersInitialized_ = true;
909 void operator() (Init* I) {
910 InvokeDagInitHandler(this, I);
915 /// Property handlers --
916 /// Functions that extract information about tool properties from
917 /// DAG representation.
919 void onActions (const DagInit& d) {
920 CheckNumberOfArguments(d, 1);
921 Init* Case = d.getArg(0);
922 if (typeid(*Case) != typeid(DagInit) ||
923 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
924 throw "The argument to (actions) should be a 'case' construct!";
925 toolDesc_.Actions = Case;
928 void onCommand (const DagInit& d) {
929 CheckNumberOfArguments(d, 1);
930 toolDesc_.CmdLine = d.getArg(0);
933 void onInLanguage (const DagInit& d) {
934 CheckNumberOfArguments(d, 1);
935 Init* arg = d.getArg(0);
937 // Find out the argument's type.
938 if (typeid(*arg) == typeid(StringInit)) {
940 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
944 const ListInit& lst = InitPtrToList(arg);
945 StrVector& out = toolDesc_.InLanguage;
947 // Copy strings to the output vector.
948 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
950 out.push_back(InitPtrToString(*B));
953 // Remove duplicates.
954 std::sort(out.begin(), out.end());
955 StrVector::iterator newE = std::unique(out.begin(), out.end());
956 out.erase(newE, out.end());
960 void onJoin (const DagInit& d) {
961 CheckNumberOfArguments(d, 0);
965 void onOutLanguage (const DagInit& d) {
966 CheckNumberOfArguments(d, 1);
967 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
970 void onOutFileOption (const DagInit& d) {
971 CheckNumberOfArguments(d, 1);
972 toolDesc_.OutFileOption = InitPtrToString(d.getArg(0));
975 void onInFileOption (const DagInit& d) {
976 CheckNumberOfArguments(d, 1);
977 toolDesc_.InFileOption = InitPtrToString(d.getArg(0));
980 void onOutputSuffix (const DagInit& d) {
981 CheckNumberOfArguments(d, 1);
982 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
985 void onSink (const DagInit& d) {
986 CheckNumberOfArguments(d, 0);
990 void onWorksOnEmpty (const DagInit& d) {
991 toolDesc_.OnEmpty = d.getArg(0);
996 /// CollectToolDescriptions - Gather information about tool properties
997 /// from the parsed TableGen data (basically a wrapper for the
998 /// CollectToolProperties function object).
999 void CollectToolDescriptions (RecordVector::const_iterator B,
1000 RecordVector::const_iterator E,
1001 ToolDescriptions& ToolDescs)
1003 // Iterate over a properties list of every Tool definition
1005 const Record* T = *B;
1006 // Throws an exception if the value does not exist.
1007 ListInit* PropList = T->getValueAsListInit("properties");
1009 IntrusiveRefCntPtr<ToolDescription>
1010 ToolDesc(new ToolDescription(T->getName()));
1012 std::for_each(PropList->begin(), PropList->end(),
1013 CollectToolProperties(*ToolDesc));
1014 ToolDescs.push_back(ToolDesc);
1018 /// FillInEdgeVector - Merge all compilation graph definitions into
1019 /// one single edge list.
1020 void FillInEdgeVector(RecordVector::const_iterator B,
1021 RecordVector::const_iterator E, RecordVector& Out) {
1022 for (; B != E; ++B) {
1023 const ListInit* edges = (*B)->getValueAsListInit("edges");
1025 for (unsigned i = 0; i < edges->size(); ++i)
1026 Out.push_back(edges->getElementAsRecord(i));
1030 /// NotInGraph - Helper function object for FilterNotInGraph.
1033 const llvm::StringSet<>& ToolsInGraph_;
1036 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
1037 : ToolsInGraph_(ToolsInGraph)
1040 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
1041 return (ToolsInGraph_.count(x->Name) == 0);
1045 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
1046 /// mentioned in the compilation graph definition.
1047 void FilterNotInGraph (const RecordVector& EdgeVector,
1048 ToolDescriptions& ToolDescs) {
1050 // List all tools mentioned in the graph.
1051 llvm::StringSet<> ToolsInGraph;
1053 for (RecordVector::const_iterator B = EdgeVector.begin(),
1054 E = EdgeVector.end(); B != E; ++B) {
1056 const Record* Edge = *B;
1057 const std::string& NodeA = Edge->getValueAsString("a");
1058 const std::string& NodeB = Edge->getValueAsString("b");
1060 if (NodeA != "root")
1061 ToolsInGraph.insert(NodeA);
1062 ToolsInGraph.insert(NodeB);
1065 // Filter ToolPropertiesList.
1066 ToolDescriptions::iterator new_end =
1067 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
1068 NotInGraph(ToolsInGraph));
1069 ToolDescs.erase(new_end, ToolDescs.end());
1072 /// FillInToolToLang - Fills in two tables that map tool names to
1073 /// (input, output) languages. Helper function used by TypecheckGraph().
1074 void FillInToolToLang (const ToolDescriptions& ToolDescs,
1075 StringMap<StringSet<> >& ToolToInLang,
1076 StringMap<std::string>& ToolToOutLang) {
1077 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1078 E = ToolDescs.end(); B != E; ++B) {
1079 const ToolDescription& D = *(*B);
1080 for (StrVector::const_iterator B = D.InLanguage.begin(),
1081 E = D.InLanguage.end(); B != E; ++B)
1082 ToolToInLang[D.Name].insert(*B);
1083 ToolToOutLang[D.Name] = D.OutLanguage;
1087 /// TypecheckGraph - Check that names for output and input languages
1088 /// on all edges do match. This doesn't do much when the information
1089 /// about the whole graph is not available (i.e. when compiling most
1091 void TypecheckGraph (const RecordVector& EdgeVector,
1092 const ToolDescriptions& ToolDescs) {
1093 StringMap<StringSet<> > ToolToInLang;
1094 StringMap<std::string> ToolToOutLang;
1096 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
1097 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1098 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1100 for (RecordVector::const_iterator B = EdgeVector.begin(),
1101 E = EdgeVector.end(); B != E; ++B) {
1102 const Record* Edge = *B;
1103 const std::string& NodeA = Edge->getValueAsString("a");
1104 const std::string& NodeB = Edge->getValueAsString("b");
1105 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1106 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1108 if (NodeA != "root") {
1109 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1110 throw "Edge " + NodeA + "->" + NodeB
1111 + ": output->input language mismatch";
1114 if (NodeB == "root")
1115 throw "Edges back to the root are not allowed!";
1119 /// WalkCase - Walks the 'case' expression DAG and invokes
1120 /// TestCallback on every test, and StatementCallback on every
1121 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1122 /// combinators (that is, they are passed directly to TestCallback).
1123 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1124 /// IndentLevel, bool FirstTest)'.
1125 /// StatementCallback must have type 'void StatementCallback(const Init*,
1126 /// unsigned IndentLevel)'.
1127 template <typename F1, typename F2>
1128 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1129 unsigned IndentLevel = 0)
1131 const DagInit& d = InitPtrToDag(Case);
1134 if (GetOperatorName(d) != "case")
1135 throw "WalkCase should be invoked only on 'case' expressions!";
1137 if (d.getNumArgs() < 2)
1138 throw "There should be at least one clause in the 'case' expression:\n"
1143 const unsigned numArgs = d.getNumArgs();
1145 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1152 const DagInit& Test = InitPtrToDag(arg);
1154 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1155 throw "The 'default' clause should be the last in the "
1156 "'case' construct!";
1158 throw "Case construct handler: no corresponding action "
1159 "found for the test " + Test.getAsString() + '!';
1161 TestCallback(Test, IndentLevel, (i == 1));
1165 if (dynamic_cast<DagInit*>(arg)
1166 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1168 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1171 // Handle statement.
1172 StatementCallback(arg, IndentLevel);
1180 /// ExtractOptionNames - A helper function object used by
1181 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1182 class ExtractOptionNames {
1183 llvm::StringSet<>& OptionNames_;
1185 void processDag(const Init* Statement) {
1186 const DagInit& Stmt = InitPtrToDag(Statement);
1187 const std::string& ActionName = GetOperatorName(Stmt);
1188 if (ActionName == "forward" || ActionName == "forward_as" ||
1189 ActionName == "forward_value" ||
1190 ActionName == "forward_transformed_value" ||
1191 ActionName == "switch_on" || ActionName == "any_switch_on" ||
1192 ActionName == "parameter_equals" ||
1193 ActionName == "element_in_list" || ActionName == "not_empty" ||
1194 ActionName == "empty") {
1195 CheckNumberOfArguments(Stmt, 1);
1197 Init* Arg = Stmt.getArg(0);
1198 if (typeid(*Arg) == typeid(StringInit)) {
1199 const std::string& Name = InitPtrToString(Arg);
1200 OptionNames_.insert(Name);
1204 const ListInit& List = InitPtrToList(Arg);
1205 for (ListInit::const_iterator B = List.begin(), E = List.end();
1207 const std::string& Name = InitPtrToString(*B);
1208 OptionNames_.insert(Name);
1212 else if (ActionName == "and" || ActionName == "or" || ActionName == "not") {
1213 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1214 this->processDag(Stmt.getArg(i));
1220 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1223 void operator()(const Init* Statement) {
1224 if (typeid(*Statement) == typeid(ListInit)) {
1225 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1226 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1228 this->processDag(*B);
1231 this->processDag(Statement);
1235 void operator()(const DagInit& Test, unsigned, bool) {
1236 this->operator()(&Test);
1238 void operator()(const Init* Statement, unsigned) {
1239 this->operator()(Statement);
1243 /// CheckForSuperfluousOptions - Check that there are no side
1244 /// effect-free options (specified only in the OptionList). Otherwise,
1245 /// output a warning.
1246 void CheckForSuperfluousOptions (const RecordVector& Edges,
1247 const ToolDescriptions& ToolDescs,
1248 const OptionDescriptions& OptDescs) {
1249 llvm::StringSet<> nonSuperfluousOptions;
1251 // Add all options mentioned in the ToolDesc.Actions to the set of
1252 // non-superfluous options.
1253 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1254 E = ToolDescs.end(); B != E; ++B) {
1255 const ToolDescription& TD = *(*B);
1256 ExtractOptionNames Callback(nonSuperfluousOptions);
1258 WalkCase(TD.Actions, Callback, Callback);
1261 // Add all options mentioned in the 'case' clauses of the
1262 // OptionalEdges of the compilation graph to the set of
1263 // non-superfluous options.
1264 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1266 const Record* Edge = *B;
1267 DagInit& Weight = *Edge->getValueAsDag("weight");
1269 if (!IsDagEmpty(Weight))
1270 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1273 // Check that all options in OptDescs belong to the set of
1274 // non-superfluous options.
1275 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1276 E = OptDescs.end(); B != E; ++B) {
1277 const OptionDescription& Val = B->second;
1278 if (!nonSuperfluousOptions.count(Val.Name)
1279 && Val.Type != OptionType::Alias)
1280 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1281 "Probable cause: this option is specified only in the OptionList.\n";
1285 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1286 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1287 if (TestName == "single_input_file") {
1288 O << "InputFilenames.size() == 1";
1291 else if (TestName == "multiple_input_files") {
1292 O << "InputFilenames.size() > 1";
1299 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1300 template <typename F>
1301 void EmitListTest(const ListInit& L, const char* LogicOp,
1302 F Callback, raw_ostream& O)
1304 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1306 bool isFirst = true;
1307 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1311 O << ' ' << LogicOp << ' ';
1312 Callback(InitPtrToString(*B), O);
1316 // Callbacks for use with EmitListTest.
1318 class EmitSwitchOn {
1319 const OptionDescriptions& OptDescs_;
1321 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1324 void operator()(const std::string& OptName, raw_ostream& O) const {
1325 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1326 O << OptDesc.GenVariableName();
1330 class EmitEmptyTest {
1332 const OptionDescriptions& OptDescs_;
1334 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1335 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1338 void operator()(const std::string& OptName, raw_ostream& O) const {
1339 const char* Neg = (EmitNegate_ ? "!" : "");
1340 if (OptName == "o") {
1341 O << Neg << "OutputFilename.empty()";
1343 else if (OptName == "save-temps") {
1344 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1347 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1348 O << Neg << OptDesc.GenVariableName() << ".empty()";
1354 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1355 bool EmitCaseTest1ArgList(const std::string& TestName,
1357 const OptionDescriptions& OptDescs,
1359 const ListInit& L = InitPtrToList(d.getArg(0));
1361 if (TestName == "any_switch_on") {
1362 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1365 else if (TestName == "switch_on") {
1366 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1369 else if (TestName == "any_not_empty") {
1370 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1373 else if (TestName == "any_empty") {
1374 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1377 else if (TestName == "not_empty") {
1378 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1381 else if (TestName == "empty") {
1382 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1389 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1390 bool EmitCaseTest1ArgStr(const std::string& TestName,
1392 const OptionDescriptions& OptDescs,
1394 const std::string& OptName = InitPtrToString(d.getArg(0));
1396 if (TestName == "switch_on") {
1397 apply(EmitSwitchOn(OptDescs), OptName, O);
1400 else if (TestName == "input_languages_contain") {
1401 O << "InLangs.count(\"" << OptName << "\") != 0";
1404 else if (TestName == "in_language") {
1405 // This works only for single-argument Tool::GenerateAction. Join
1406 // tools can process several files in different languages simultaneously.
1408 // TODO: make this work with Edge::Weight (if possible).
1409 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1412 else if (TestName == "not_empty" || TestName == "empty") {
1413 bool EmitNegate = (TestName == "not_empty");
1414 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1421 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1422 bool EmitCaseTest1Arg(const std::string& TestName,
1424 const OptionDescriptions& OptDescs,
1426 CheckNumberOfArguments(d, 1);
1427 if (typeid(*d.getArg(0)) == typeid(ListInit))
1428 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1430 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1433 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1434 bool EmitCaseTest2Args(const std::string& TestName,
1436 unsigned IndentLevel,
1437 const OptionDescriptions& OptDescs,
1439 CheckNumberOfArguments(d, 2);
1440 const std::string& OptName = InitPtrToString(d.getArg(0));
1441 const std::string& OptArg = InitPtrToString(d.getArg(1));
1443 if (TestName == "parameter_equals") {
1444 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1445 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1448 else if (TestName == "element_in_list") {
1449 const OptionDescription& OptDesc = OptDescs.FindParameterList(OptName);
1450 const std::string& VarName = OptDesc.GenVariableName();
1451 O << "std::find(" << VarName << ".begin(),\n";
1452 O.indent(IndentLevel + Indent1)
1453 << VarName << ".end(), \""
1454 << OptArg << "\") != " << VarName << ".end()";
1461 // Forward declaration.
1462 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1463 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1464 const OptionDescriptions& OptDescs,
1467 /// EmitLogicalOperationTest - Helper function used by
1468 /// EmitCaseConstructHandler.
1469 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1470 unsigned IndentLevel,
1471 const OptionDescriptions& OptDescs,
1474 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1475 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1476 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1477 if (j != NumArgs - 1) {
1479 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1487 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1488 const OptionDescriptions& OptDescs, raw_ostream& O)
1490 CheckNumberOfArguments(d, 1);
1491 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1493 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1497 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1498 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1499 const OptionDescriptions& OptDescs,
1501 const std::string& TestName = GetOperatorName(d);
1503 if (TestName == "and")
1504 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1505 else if (TestName == "or")
1506 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1507 else if (TestName == "not")
1508 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1509 else if (EmitCaseTest0Args(TestName, O))
1511 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1513 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1516 throw "Unknown test '" + TestName + "' used in the 'case' construct!";
1520 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1521 class EmitCaseTestCallback {
1523 const OptionDescriptions& OptDescs_;
1527 EmitCaseTestCallback(bool EmitElseIf,
1528 const OptionDescriptions& OptDescs, raw_ostream& O)
1529 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1532 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1534 if (GetOperatorName(Test) == "default") {
1535 O_.indent(IndentLevel) << "else {\n";
1538 O_.indent(IndentLevel)
1539 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1540 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1546 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1547 template <typename F>
1548 class EmitCaseStatementCallback {
1553 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1554 : Callback_(Callback), O_(O)
1557 void operator() (const Init* Statement, unsigned IndentLevel) {
1559 // Ignore nested 'case' DAG.
1560 if (!(dynamic_cast<const DagInit*>(Statement) &&
1561 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1562 if (typeid(*Statement) == typeid(ListInit)) {
1563 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1564 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1566 Callback_(*B, (IndentLevel + Indent1), O_);
1569 Callback_(Statement, (IndentLevel + Indent1), O_);
1572 O_.indent(IndentLevel) << "}\n";
1577 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1578 /// construct. Takes a function object that should emit code for every case
1579 /// clause. Implemented on top of WalkCase.
1580 /// Callback's type is void F(const Init* Statement, unsigned IndentLevel,
1581 /// raw_ostream& O).
1582 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1583 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1585 template <typename F>
1586 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1587 F Callback, bool EmitElseIf,
1588 const OptionDescriptions& OptDescs,
1590 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1591 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1594 /// TokenizeCmdLine - converts from
1595 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1596 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1597 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1598 const char* Delimiters = " \t\n\v\f\r";
1600 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1603 if (CmdLine.empty())
1607 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1610 for (; B != E; ++B) {
1611 char cur_ch = CmdLine[B];
1615 if (cur_ch == '$') {
1616 cur_st = SpecialCommand;
1619 if (OneOf(Delimiters, cur_ch)) {
1621 B = CmdLine.find_first_not_of(Delimiters, B);
1622 if (B == std::string::npos) {
1633 case SpecialCommand:
1634 if (OneOf(Delimiters, cur_ch)) {
1639 if (cur_ch == '(') {
1641 cur_st = InsideSpecialCommand;
1646 case InsideSpecialCommand:
1647 if (OneOf(Delimiters, cur_ch)) {
1650 if (cur_ch == '\'') {
1651 cur_st = InsideQuotationMarks;
1655 if (cur_ch == ')') {
1659 if (cur_ch == ',') {
1665 case InsideQuotationMarks:
1666 if (cur_ch == '\'') {
1667 cur_st = InsideSpecialCommand;
1673 Out.back().push_back(cur_ch);
1677 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1678 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1679 /// SubstituteSpecialCommands().
1680 StrVector::const_iterator
1681 SubstituteCall (StrVector::const_iterator Pos,
1682 StrVector::const_iterator End,
1683 bool IsJoin, raw_ostream& O)
1685 const char* errorMessage = "Syntax error in $CALL invocation!";
1686 CheckedIncrement(Pos, End, errorMessage);
1687 const std::string& CmdName = *Pos;
1690 throw "$CALL invocation: empty argument list!";
1693 O << CmdName << "(";
1696 bool firstIteration = true;
1698 CheckedIncrement(Pos, End, errorMessage);
1699 const std::string& Arg = *Pos;
1700 assert(Arg.size() != 0);
1706 firstIteration = false;
1710 if (Arg == "$INFILE") {
1712 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1714 O << "inFile.c_str()";
1717 O << '"' << Arg << '"';
1726 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1727 /// function used by SubstituteSpecialCommands().
1728 StrVector::const_iterator
1729 SubstituteEnv (StrVector::const_iterator Pos,
1730 StrVector::const_iterator End, raw_ostream& O)
1732 const char* errorMessage = "Syntax error in $ENV invocation!";
1733 CheckedIncrement(Pos, End, errorMessage);
1734 const std::string& EnvName = *Pos;
1737 throw "$ENV invocation: empty argument list!";
1739 O << "checkCString(std::getenv(\"";
1743 CheckedIncrement(Pos, End, errorMessage);
1748 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1749 /// handler code. Helper function used by EmitCmdLineVecFill().
1750 StrVector::const_iterator
1751 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1752 StrVector::const_iterator End,
1753 bool IsJoin, raw_ostream& O)
1756 const std::string& cmd = *Pos;
1758 // Perform substitution.
1759 if (cmd == "$CALL") {
1760 Pos = SubstituteCall(Pos, End, IsJoin, O);
1762 else if (cmd == "$ENV") {
1763 Pos = SubstituteEnv(Pos, End, O);
1766 throw "Unknown special command: " + cmd;
1769 // Handle '$CMD(ARG)/additional/text'.
1770 const std::string& Leftover = *Pos;
1771 assert(Leftover.at(0) == ')');
1772 if (Leftover.size() != 1)
1773 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1778 /// EmitCmdLineVecFill - Emit code that fills in the command line
1779 /// vector. Helper function used by EmitGenerateActionMethod().
1780 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1781 bool IsJoin, unsigned IndentLevel,
1784 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1787 throw "Tool '" + ToolName + "' has empty command line!";
1789 StrVector::const_iterator B = StrVec.begin(), E = StrVec.end();
1791 // Emit the command itself.
1792 assert(!StrVec[0].empty());
1793 O.indent(IndentLevel) << "cmd = ";
1794 if (StrVec[0][0] == '$') {
1795 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1799 O << '"' << StrVec[0] << '"';
1804 // Go through the command arguments.
1806 for (; B != E; ++B) {
1807 const std::string& cmd = *B;
1809 assert(!cmd.empty());
1810 O.indent(IndentLevel);
1812 if (cmd.at(0) == '$') {
1813 O << "vec.push_back(std::make_pair(0, ";
1814 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1818 O << "vec.push_back(std::make_pair(0, \"" << cmd << "\"));\n";
1824 /// EmitForEachListElementCycleHeader - Emit common code for iterating through
1825 /// all elements of a list. Helper function used by
1826 /// EmitForwardOptionPropertyHandlingCode.
1827 void EmitForEachListElementCycleHeader (const OptionDescription& D,
1828 unsigned IndentLevel,
1830 unsigned IndentLevel1 = IndentLevel + Indent1;
1832 O.indent(IndentLevel)
1833 << "for (" << D.GenTypeDeclaration()
1834 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1835 O.indent(IndentLevel)
1836 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1837 O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName()
1838 << ".getPosition(B - " << D.GenVariableName()
1842 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1843 /// implement EmitActionHandler. Emits code for
1844 /// handling the (forward) and (forward_as) option properties.
1845 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1846 unsigned IndentLevel,
1847 const std::string& NewName,
1849 const std::string& Name = NewName.empty()
1852 unsigned IndentLevel1 = IndentLevel + Indent1;
1855 case OptionType::Switch:
1856 O.indent(IndentLevel)
1857 << "vec.push_back(std::make_pair(" << D.GenVariableName()
1858 << ".getPosition(), \"" << Name << "\"));\n";
1860 case OptionType::Parameter:
1861 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1862 << D.GenVariableName()
1863 <<".getPosition(), \"" << Name;
1865 if (!D.isForwardNotSplit()) {
1867 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1868 << D.GenVariableName() << ".getPosition(), "
1869 << D.GenVariableName() << "));\n";
1872 O << "=\" + " << D.GenVariableName() << "));\n";
1875 case OptionType::Prefix:
1876 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1877 << D.GenVariableName() << ".getPosition(), \""
1879 << D.GenVariableName() << "));\n";
1881 case OptionType::PrefixList:
1882 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1883 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1884 << Name << "\" + " << "*B));\n";
1885 O.indent(IndentLevel1) << "++B;\n";
1887 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1888 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1889 O.indent(IndentLevel1) << "++B;\n";
1892 O.indent(IndentLevel) << "}\n";
1894 case OptionType::ParameterList:
1895 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1896 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1897 << Name << "\"));\n";
1899 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1900 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1901 O.indent(IndentLevel1) << "++B;\n";
1904 O.indent(IndentLevel) << "}\n";
1906 case OptionType::SwitchList:
1907 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1908 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1909 << Name << "\"));\n";
1910 O.indent(IndentLevel1) << "++B;\n";
1911 O.indent(IndentLevel) << "}\n";
1913 case OptionType::Alias:
1915 throw "Aliases are not allowed in tool option descriptions!";
1919 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1920 /// EmitPreprocessOptionsCallback.
1921 struct ActionHandlingCallbackBase
1924 void onErrorDag(const DagInit& d,
1925 unsigned IndentLevel, raw_ostream& O) const
1927 O.indent(IndentLevel)
1929 << (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0)) : "Unknown error!")
1931 O.indent(IndentLevel) << "return 1;\n";
1934 void onWarningDag(const DagInit& d,
1935 unsigned IndentLevel, raw_ostream& O) const
1937 CheckNumberOfArguments(d, 1);
1938 O.indent(IndentLevel) << "llvm::errs() << \""
1939 << InitPtrToString(d.getArg(0)) << "\";\n";
1944 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1945 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1947 class EmitActionHandlersCallback;
1949 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1950 (const DagInit&, unsigned, raw_ostream&) const;
1952 class EmitActionHandlersCallback :
1953 public ActionHandlingCallbackBase,
1954 public HandlerTable<EmitActionHandlersCallbackHandler>
1956 typedef EmitActionHandlersCallbackHandler Handler;
1958 const OptionDescriptions& OptDescs;
1960 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1961 /// onAppendCmd and onOutputSuffix.
1962 void EmitHookInvocation(const std::string& Str,
1963 const char* BlockOpen, const char* BlockClose,
1964 unsigned IndentLevel, raw_ostream& O) const
1967 TokenizeCmdLine(Str, Out);
1969 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1971 const std::string& cmd = *B;
1973 O.indent(IndentLevel) << BlockOpen;
1975 if (cmd.at(0) == '$')
1976 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1978 O << '"' << cmd << '"';
1984 void onAppendCmd (const DagInit& Dag,
1985 unsigned IndentLevel, raw_ostream& O) const
1987 CheckNumberOfArguments(Dag, 1);
1988 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1989 "vec.push_back(std::make_pair(65536, ", "));\n",
1993 void onForward (const DagInit& Dag,
1994 unsigned IndentLevel, raw_ostream& O) const
1996 CheckNumberOfArguments(Dag, 1);
1997 const std::string& Name = InitPtrToString(Dag.getArg(0));
1998 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1999 IndentLevel, "", O);
2002 void onForwardAs (const DagInit& Dag,
2003 unsigned IndentLevel, raw_ostream& O) const
2005 CheckNumberOfArguments(Dag, 2);
2006 const std::string& Name = InitPtrToString(Dag.getArg(0));
2007 const std::string& NewName = InitPtrToString(Dag.getArg(1));
2008 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2009 IndentLevel, NewName, O);
2012 void onForwardValue (const DagInit& Dag,
2013 unsigned IndentLevel, raw_ostream& O) const
2015 CheckNumberOfArguments(Dag, 1);
2016 const std::string& Name = InitPtrToString(Dag.getArg(0));
2017 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2019 if (D.isSwitchList()) {
2020 throw std::runtime_error
2021 ("forward_value is not allowed with switch_list");
2024 if (D.isParameter()) {
2025 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2026 << D.GenVariableName() << ".getPosition(), "
2027 << D.GenVariableName() << "));\n";
2030 O.indent(IndentLevel) << "for (" << D.GenTypeDeclaration()
2031 << "::iterator B = " << D.GenVariableName()
2033 O.indent(IndentLevel + Indent1) << " E = " << D.GenVariableName()
2034 << ".end(); B != E; ++B)\n";
2035 O.indent(IndentLevel) << "{\n";
2036 O.indent(IndentLevel + Indent1)
2037 << "unsigned pos = " << D.GenVariableName()
2038 << ".getPosition(B - " << D.GenVariableName()
2040 O.indent(IndentLevel + Indent1)
2041 << "vec.push_back(std::make_pair(pos, *B));\n";
2042 O.indent(IndentLevel) << "}\n";
2046 void onForwardTransformedValue (const DagInit& Dag,
2047 unsigned IndentLevel, raw_ostream& O) const
2049 CheckNumberOfArguments(Dag, 2);
2050 const std::string& Name = InitPtrToString(Dag.getArg(0));
2051 const std::string& Hook = InitPtrToString(Dag.getArg(1));
2052 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2054 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2055 << D.GenVariableName() << ".getPosition("
2056 << (D.isList() ? "0" : "") << "), "
2057 << "hooks::" << Hook << "(" << D.GenVariableName()
2058 << (D.isParameter() ? ".c_str()" : "") << ")));\n";
2061 void onNoOutFile (const DagInit& Dag,
2062 unsigned IndentLevel, raw_ostream& O) const
2064 CheckNumberOfArguments(Dag, 0);
2065 O.indent(IndentLevel) << "no_out_file = true;\n";
2068 void onOutputSuffix (const DagInit& Dag,
2069 unsigned IndentLevel, raw_ostream& O) const
2071 CheckNumberOfArguments(Dag, 1);
2072 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2073 "output_suffix = ", ";\n", IndentLevel, O);
2076 void onStopCompilation (const DagInit& Dag,
2077 unsigned IndentLevel, raw_ostream& O) const
2079 O.indent(IndentLevel) << "stop_compilation = true;\n";
2083 void onUnpackValues (const DagInit& Dag,
2084 unsigned IndentLevel, raw_ostream& O) const
2086 throw "'unpack_values' is deprecated. "
2087 "Use 'comma_separated' + 'forward_value' instead!";
2092 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
2095 if (!staticMembersInitialized_) {
2096 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
2097 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
2098 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
2099 AddHandler("forward", &EmitActionHandlersCallback::onForward);
2100 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
2101 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
2102 AddHandler("forward_transformed_value",
2103 &EmitActionHandlersCallback::onForwardTransformedValue);
2104 AddHandler("no_out_file",
2105 &EmitActionHandlersCallback::onNoOutFile);
2106 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
2107 AddHandler("stop_compilation",
2108 &EmitActionHandlersCallback::onStopCompilation);
2109 AddHandler("unpack_values",
2110 &EmitActionHandlersCallback::onUnpackValues);
2113 staticMembersInitialized_ = true;
2117 void operator()(const Init* I,
2118 unsigned IndentLevel, raw_ostream& O) const
2120 InvokeDagInitHandler(this, I, IndentLevel, O);
2124 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2125 bool IsJoin, bool Naked,
2128 O.indent(Indent1) << "int GenerateAction(Action& Out,\n";
2131 O.indent(Indent2) << "const PathVector& inFiles,\n";
2133 O.indent(Indent2) << "const sys::Path& inFile,\n";
2135 O.indent(Indent2) << "const bool HasChildren,\n";
2136 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2137 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2138 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2139 O.indent(Indent1) << "{\n";
2142 O.indent(Indent2) << "std::string cmd;\n";
2143 O.indent(Indent2) << "std::string out_file;\n";
2145 << "std::vector<std::pair<unsigned, std::string> > vec;\n";
2146 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2147 O.indent(Indent2) << "bool no_out_file = false;\n";
2148 O.indent(Indent2) << "std::string output_suffix(\""
2149 << D.OutputSuffix << "\");\n";
2153 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2154 // Tool::GenerateAction() method.
2155 void EmitGenerateActionMethod (const ToolDescription& D,
2156 const OptionDescriptions& OptDescs,
2157 bool IsJoin, raw_ostream& O) {
2159 EmitGenerateActionMethodHeader(D, IsJoin, /* Naked = */ false, O);
2162 throw "Tool " + D.Name + " has no cmd_line property!";
2164 // Process the 'command' property.
2166 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2169 // Process the 'actions' list of this tool.
2171 EmitCaseConstructHandler(D.Actions, Indent2,
2172 EmitActionHandlersCallback(OptDescs),
2173 false, OptDescs, O);
2177 if (!D.InFileOption.empty()) {
2179 << "vec.push_back(std::make_pair(InputFilenames.getPosition(0), \""
2180 << D.InFileOption << "\");\n";
2185 << "for (PathVector::const_iterator B = inFiles.begin(),\n";
2186 O.indent(Indent3) << "E = inFiles.end(); B != E; ++B)\n";
2187 O.indent(Indent2) << "{\n";
2188 O.indent(Indent3) << "vec.push_back(std::make_pair("
2189 << "InputFilenames.getPosition(B - inFiles.begin()), "
2191 O.indent(Indent2) << "}\n";
2194 O.indent(Indent2) << "vec.push_back(std::make_pair("
2195 << "InputFilenames.getPosition(0), inFile.str()));\n";
2199 O.indent(Indent2) << "if (!no_out_file) {\n";
2200 if (!D.OutFileOption.empty())
2201 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, \""
2202 << D.OutFileOption << "\"));\n";
2204 O.indent(Indent3) << "out_file = this->OutFilename("
2205 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2206 O.indent(Indent4) <<
2207 "TempDir, stop_compilation, output_suffix.c_str()).str();\n\n";
2208 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, out_file));\n";
2210 O.indent(Indent2) << "}\n\n";
2212 // Handle the Sink property.
2214 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2215 O.indent(Indent3) << "for (cl::list<std::string>::iterator B = "
2216 << SinkOptionName << ".begin(), E = " << SinkOptionName
2217 << ".end(); B != E; ++B)\n";
2218 O.indent(Indent4) << "vec.push_back(std::make_pair(" << SinkOptionName
2219 << ".getPosition(B - " << SinkOptionName
2220 << ".begin()), *B));\n";
2221 O.indent(Indent2) << "}\n";
2224 O.indent(Indent2) << "Out.Construct(cmd, this->SortArgs(vec), "
2225 << "stop_compilation, out_file);\n";
2226 O.indent(Indent2) << "return 0;\n";
2227 O.indent(Indent1) << "}\n\n";
2230 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2231 /// a given Tool class.
2232 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2233 const OptionDescriptions& OptDescs,
2235 if (!ToolDesc.isJoin()) {
2236 EmitGenerateActionMethodHeader(ToolDesc, /* IsJoin = */ true,
2237 /* Naked = */ true, O);
2238 O.indent(Indent2) << "PrintError(\"" << ToolDesc.Name
2239 << " is not a Join tool!\");\n";
2240 O.indent(Indent2) << "return -1;\n";
2241 O.indent(Indent1) << "}\n\n";
2244 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2247 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2250 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2251 /// methods for a given Tool class.
2252 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2253 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2254 O.indent(Indent2) << "return InputLanguages_;\n";
2255 O.indent(Indent1) << "}\n\n";
2257 if (D.OutLanguage.empty())
2258 throw "Tool " + D.Name + " has no 'out_language' property!";
2260 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2261 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2262 O.indent(Indent1) << "}\n\n";
2265 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2266 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2267 O.indent(Indent1) << "const char* Name() const {\n";
2268 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2269 O.indent(Indent1) << "}\n\n";
2272 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2274 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2275 O.indent(Indent1) << "bool IsJoin() const {\n";
2277 O.indent(Indent2) << "return true;\n";
2279 O.indent(Indent2) << "return false;\n";
2280 O.indent(Indent1) << "}\n\n";
2283 /// EmitWorksOnEmptyCallback - Callback used by EmitWorksOnEmptyMethod in
2284 /// conjunction with EmitCaseConstructHandler.
2285 void EmitWorksOnEmptyCallback (const Init* Value,
2286 unsigned IndentLevel, raw_ostream& O) {
2287 CheckBooleanConstant(Value);
2288 O.indent(IndentLevel) << "return " << Value->getAsString() << ";\n";
2291 /// EmitWorksOnEmptyMethod - Emit the WorksOnEmpty() method for a given Tool
2293 void EmitWorksOnEmptyMethod (const ToolDescription& D,
2294 const OptionDescriptions& OptDescs,
2297 O.indent(Indent1) << "bool WorksOnEmpty() const {\n";
2299 O.indent(Indent2) << "return false;\n";
2301 EmitCaseConstructHandler(D.OnEmpty, Indent2, EmitWorksOnEmptyCallback,
2302 /*EmitElseIf = */ true, OptDescs, O);
2303 O.indent(Indent1) << "}\n\n";
2306 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2307 /// given Tool class.
2308 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2309 if (D.InLanguage.empty())
2310 throw "Tool " + D.Name + " has no 'in_language' property!";
2312 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2313 for (StrVector::const_iterator B = D.InLanguage.begin(),
2314 E = D.InLanguage.end(); B != E; ++B)
2315 O << '\"' << *B << "\", ";
2319 /// EmitToolClassDefinition - Emit a Tool class definition.
2320 void EmitToolClassDefinition (const ToolDescription& D,
2321 const OptionDescriptions& OptDescs,
2323 if (D.Name == "root")
2327 O << "class " << D.Name << " : public ";
2333 O << " {\nprivate:\n";
2334 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2337 EmitNameMethod(D, O);
2338 EmitInOutLanguageMethods(D, O);
2339 EmitIsJoinMethod(D, O);
2340 EmitWorksOnEmptyMethod(D, OptDescs, O);
2341 EmitGenerateActionMethods(D, OptDescs, O);
2343 // Close class definition
2346 EmitStaticMemberDefinitions(D, O);
2350 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2351 /// and emit registration code.
2352 void EmitOptionDefinitions (const OptionDescriptions& descs,
2353 bool HasSink, raw_ostream& O)
2355 std::vector<OptionDescription> Aliases;
2357 // Emit static cl::Option variables.
2358 for (OptionDescriptions::const_iterator B = descs.begin(),
2359 E = descs.end(); B!=E; ++B) {
2360 const OptionDescription& val = B->second;
2362 if (val.Type == OptionType::Alias) {
2363 Aliases.push_back(val);
2367 O << val.GenTypeDeclaration() << ' '
2368 << val.GenVariableName();
2370 O << "(\"" << val.Name << "\"\n";
2372 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2373 O << ", cl::Prefix";
2375 if (val.isRequired()) {
2376 if (val.isList() && !val.isMultiVal())
2377 O << ", cl::OneOrMore";
2379 O << ", cl::Required";
2382 if (val.isOptional())
2383 O << ", cl::Optional";
2385 if (val.isOneOrMore())
2386 O << ", cl::OneOrMore";
2388 if (val.isZeroOrMore())
2389 O << ", cl::ZeroOrMore";
2391 if (val.isReallyHidden())
2392 O << ", cl::ReallyHidden";
2393 else if (val.isHidden())
2394 O << ", cl::Hidden";
2396 if (val.isCommaSeparated())
2397 O << ", cl::CommaSeparated";
2399 if (val.MultiVal > 1)
2400 O << ", cl::multi_val(" << val.MultiVal << ')';
2403 const std::string& str = val.InitVal->getAsString();
2404 O << ", cl::init(" << str << ')';
2407 if (!val.Help.empty())
2408 O << ", cl::desc(\"" << val.Help << "\")";
2413 // Emit the aliases (they should go after all the 'proper' options).
2414 for (std::vector<OptionDescription>::const_iterator
2415 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2416 const OptionDescription& val = *B;
2418 O << val.GenTypeDeclaration() << ' '
2419 << val.GenVariableName()
2420 << "(\"" << val.Name << '\"';
2422 const OptionDescription& D = descs.FindOption(val.Help);
2423 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2425 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2428 // Emit the sink option.
2430 O << "cl" << "::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
2435 /// EmitPreprocessOptionsCallback - Helper function passed to
2436 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2438 class EmitPreprocessOptionsCallback;
2441 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2442 (const DagInit&, unsigned, raw_ostream&) const;
2444 class EmitPreprocessOptionsCallback :
2445 public ActionHandlingCallbackBase,
2446 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2448 typedef EmitPreprocessOptionsCallbackHandler Handler;
2450 (EmitPreprocessOptionsCallback::* HandlerImpl)
2451 (const Init*, unsigned, raw_ostream&) const;
2453 const OptionDescriptions& OptDescs_;
2455 void onListOrDag(const DagInit& d, HandlerImpl h,
2456 unsigned IndentLevel, raw_ostream& O) const
2458 CheckNumberOfArguments(d, 1);
2459 const Init* I = d.getArg(0);
2461 // If I is a list, apply h to each element.
2462 if (typeid(*I) == typeid(ListInit)) {
2463 const ListInit& L = *static_cast<const ListInit*>(I);
2464 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2465 ((this)->*(h))(*B, IndentLevel, O);
2467 // Otherwise, apply h to I.
2469 ((this)->*(h))(I, IndentLevel, O);
2473 void onUnsetOptionImpl(const Init* I,
2474 unsigned IndentLevel, raw_ostream& O) const
2476 const std::string& OptName = InitPtrToString(I);
2477 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2479 if (OptDesc.isSwitch()) {
2480 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2482 else if (OptDesc.isParameter()) {
2483 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2485 else if (OptDesc.isList()) {
2486 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2489 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2493 void onUnsetOption(const DagInit& d,
2494 unsigned IndentLevel, raw_ostream& O) const
2496 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2500 void onSetOptionImpl(const DagInit& d,
2501 unsigned IndentLevel, raw_ostream& O) const {
2502 CheckNumberOfArguments(d, 2);
2503 const std::string& OptName = InitPtrToString(d.getArg(0));
2504 const Init* Value = d.getArg(1);
2505 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2507 if (OptDesc.isList()) {
2508 const ListInit& List = InitPtrToList(Value);
2510 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2511 for (ListInit::const_iterator B = List.begin(), E = List.end();
2513 const Init* CurElem = *B;
2514 if (OptDesc.isSwitchList())
2515 CheckBooleanConstant(CurElem);
2517 O.indent(IndentLevel)
2518 << OptDesc.GenVariableName() << ".push_back(\""
2519 << (OptDesc.isSwitchList() ? CurElem->getAsString()
2520 : InitPtrToString(CurElem))
2524 else if (OptDesc.isSwitch()) {
2525 CheckBooleanConstant(Value);
2526 O.indent(IndentLevel) << OptDesc.GenVariableName()
2527 << " = " << Value->getAsString() << ";\n";
2529 else if (OptDesc.isParameter()) {
2530 const std::string& Str = InitPtrToString(Value);
2531 O.indent(IndentLevel) << OptDesc.GenVariableName()
2532 << " = \"" << Str << "\";\n";
2535 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2539 void onSetSwitch(const Init* I,
2540 unsigned IndentLevel, raw_ostream& O) const {
2541 const std::string& OptName = InitPtrToString(I);
2542 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2544 if (OptDesc.isSwitch())
2545 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2547 throw "set_option: -" + OptName + " is not a switch option!";
2550 void onSetOption(const DagInit& d,
2551 unsigned IndentLevel, raw_ostream& O) const
2553 CheckNumberOfArguments(d, 1);
2555 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2556 // boolean, a string or a string list.
2557 if (d.getNumArgs() > 1)
2558 this->onSetOptionImpl(d, IndentLevel, O);
2559 // One argument: (set_option "switch")
2560 // or (set_option ["switch1", "switch2", ...])
2562 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2568 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2569 : OptDescs_(OptDescs)
2571 if (!staticMembersInitialized_) {
2572 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2573 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2574 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2575 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2577 staticMembersInitialized_ = true;
2581 void operator()(const Init* I,
2582 unsigned IndentLevel, raw_ostream& O) const
2584 InvokeDagInitHandler(this, I, IndentLevel, O);
2589 /// EmitPreprocessOptions - Emit the PreprocessOptions() function.
2590 void EmitPreprocessOptions (const RecordKeeper& Records,
2591 const OptionDescriptions& OptDecs, raw_ostream& O)
2593 O << "int PreprocessOptions () {\n";
2595 const RecordVector& OptionPreprocessors =
2596 Records.getAllDerivedDefinitions("OptionPreprocessor");
2598 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2599 E = OptionPreprocessors.end(); B!=E; ++B) {
2600 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2601 EmitCaseConstructHandler(Case, Indent1,
2602 EmitPreprocessOptionsCallback(OptDecs),
2607 O.indent(Indent1) << "return 0;\n";
2611 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
2612 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2614 O << "int PopulateLanguageMap (LanguageMap& langMap) {\n";
2616 // Get the relevant field out of RecordKeeper
2617 // TODO: change this to getAllDerivedDefinitions.
2618 const Record* LangMapRecord = Records.getDef("LanguageMap");
2620 // It is allowed for a plugin to have no language map.
2621 if (LangMapRecord) {
2623 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2624 if (!LangsToSuffixesList)
2625 throw "Error in the language map definition!";
2627 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2628 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2630 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2631 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2633 for (unsigned i = 0; i < Suffixes->size(); ++i)
2634 O.indent(Indent1) << "langMap[\""
2635 << InitPtrToString(Suffixes->getElement(i))
2636 << "\"] = \"" << Lang << "\";\n";
2641 O.indent(Indent1) << "return 0;\n";
2645 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2646 /// by EmitEdgeClass().
2647 void IncDecWeight (const Init* i, unsigned IndentLevel,
2649 const DagInit& d = InitPtrToDag(i);
2650 const std::string& OpName = GetOperatorName(d);
2652 if (OpName == "inc_weight") {
2653 O.indent(IndentLevel) << "ret += ";
2655 else if (OpName == "dec_weight") {
2656 O.indent(IndentLevel) << "ret -= ";
2658 else if (OpName == "error") {
2660 CheckNumberOfArguments(d, 1);
2661 O.indent(IndentLevel) << "PrintError(\""
2662 << InitPtrToString(d.getArg(0))
2664 O.indent(IndentLevel) << "return -1;\n";
2668 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2669 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2672 if (d.getNumArgs() > 0)
2673 O << InitPtrToInt(d.getArg(0)) << ";\n";
2679 /// EmitEdgeClass - Emit a single Edge# class.
2680 void EmitEdgeClass (unsigned N, const std::string& Target,
2681 DagInit* Case, const OptionDescriptions& OptDescs,
2684 // Class constructor.
2685 O << "class Edge" << N << ": public Edge {\n"
2687 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2690 // Function Weight().
2692 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2693 O.indent(Indent2) << "unsigned ret = 0;\n";
2695 // Handle the 'case' construct.
2696 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2698 O.indent(Indent2) << "return ret;\n";
2699 O.indent(Indent1) << "}\n\n};\n\n";
2702 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2703 void EmitEdgeClasses (const RecordVector& EdgeVector,
2704 const OptionDescriptions& OptDescs,
2707 for (RecordVector::const_iterator B = EdgeVector.begin(),
2708 E = EdgeVector.end(); B != E; ++B) {
2709 const Record* Edge = *B;
2710 const std::string& NodeB = Edge->getValueAsString("b");
2711 DagInit& Weight = *Edge->getValueAsDag("weight");
2713 if (!IsDagEmpty(Weight))
2714 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2719 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph() function.
2720 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2721 const ToolDescriptions& ToolDescs,
2724 O << "int PopulateCompilationGraph (CompilationGraph& G) {\n";
2726 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2727 E = ToolDescs.end(); B != E; ++B)
2728 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2735 for (RecordVector::const_iterator B = EdgeVector.begin(),
2736 E = EdgeVector.end(); B != E; ++B) {
2737 const Record* Edge = *B;
2738 const std::string& NodeA = Edge->getValueAsString("a");
2739 const std::string& NodeB = Edge->getValueAsString("b");
2740 DagInit& Weight = *Edge->getValueAsDag("weight");
2742 O.indent(Indent1) << "if (int ret = G.insertEdge(\"" << NodeA << "\", ";
2744 if (IsDagEmpty(Weight))
2745 O << "new SimpleEdge(\"" << NodeB << "\")";
2747 O << "new Edge" << i << "()";
2750 O.indent(Indent2) << "return ret;\n";
2756 O.indent(Indent1) << "return 0;\n";
2760 /// HookInfo - Information about the hook type and number of arguments.
2763 // A hook can either have a single parameter of type std::vector<std::string>,
2764 // or NumArgs parameters of type const char*.
2765 enum HookType { ListHook, ArgHook };
2770 HookInfo() : Type(ArgHook), NumArgs(1)
2773 HookInfo(HookType T) : Type(T), NumArgs(1)
2776 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2780 typedef llvm::StringMap<HookInfo> HookInfoMap;
2782 /// ExtractHookNames - Extract the hook names from all instances of
2783 /// $CALL(HookName) in the provided command line string/action. Helper
2784 /// function used by FillInHookNames().
2785 class ExtractHookNames {
2786 HookInfoMap& HookNames_;
2787 const OptionDescriptions& OptDescs_;
2789 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2790 : HookNames_(HookNames), OptDescs_(OptDescs)
2793 void onAction (const DagInit& Dag) {
2794 const std::string& Name = GetOperatorName(Dag);
2796 if (Name == "forward_transformed_value") {
2797 CheckNumberOfArguments(Dag, 2);
2798 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2799 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2800 const OptionDescription& D =
2801 OptDescs_.FindParameterListOrParameter(OptName);
2803 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2804 : HookInfo::ArgHook);
2806 else if (Name == "append_cmd" || Name == "output_suffix") {
2807 CheckNumberOfArguments(Dag, 1);
2808 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2812 void onCmdLine(const std::string& Cmd) {
2814 TokenizeCmdLine(Cmd, cmds);
2816 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2818 const std::string& cmd = *B;
2820 if (cmd == "$CALL") {
2821 unsigned NumArgs = 0;
2822 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2823 const std::string& HookName = *B;
2825 if (HookName.at(0) == ')')
2826 throw "$CALL invoked with no arguments!";
2828 while (++B != E && B->at(0) != ')') {
2832 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2834 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2835 H->second.Type != HookInfo::ArgHook)
2836 throw "Overloading of hooks is not allowed. Overloaded hook: "
2839 HookNames_[HookName] = HookInfo(NumArgs);
2844 void operator()(const Init* Arg) {
2846 // We're invoked on an action (either a dag or a dag list).
2847 if (typeid(*Arg) == typeid(DagInit)) {
2848 const DagInit& Dag = InitPtrToDag(Arg);
2849 this->onAction(Dag);
2852 else if (typeid(*Arg) == typeid(ListInit)) {
2853 const ListInit& List = InitPtrToList(Arg);
2854 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2856 const DagInit& Dag = InitPtrToDag(*B);
2857 this->onAction(Dag);
2862 // We're invoked on a command line.
2863 this->onCmdLine(InitPtrToString(Arg));
2866 void operator()(const DagInit* Test, unsigned, bool) {
2867 this->operator()(Test);
2869 void operator()(const Init* Statement, unsigned) {
2870 this->operator()(Statement);
2874 /// FillInHookNames - Actually extract the hook names from all command
2875 /// line strings. Helper function used by EmitHookDeclarations().
2876 void FillInHookNames(const ToolDescriptions& ToolDescs,
2877 const OptionDescriptions& OptDescs,
2878 HookInfoMap& HookNames)
2880 // For all tool descriptions:
2881 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2882 E = ToolDescs.end(); B != E; ++B) {
2883 const ToolDescription& D = *(*B);
2885 // Look for 'forward_transformed_value' in 'actions'.
2887 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2889 // Look for hook invocations in 'cmd_line'.
2892 if (dynamic_cast<StringInit*>(D.CmdLine))
2893 // This is a string.
2894 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2896 // This is a 'case' construct.
2897 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2901 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2902 /// property records and emit hook function declaration for each
2903 /// instance of $CALL(HookName).
2904 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2905 const OptionDescriptions& OptDescs, raw_ostream& O) {
2906 HookInfoMap HookNames;
2908 FillInHookNames(ToolDescs, OptDescs, HookNames);
2909 if (HookNames.empty())
2912 O << "namespace hooks {\n";
2913 for (HookInfoMap::const_iterator B = HookNames.begin(),
2914 E = HookNames.end(); B != E; ++B) {
2915 const char* HookName = B->first();
2916 const HookInfo& Info = B->second;
2918 O.indent(Indent1) << "std::string " << HookName << "(";
2920 if (Info.Type == HookInfo::ArgHook) {
2921 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2922 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2926 O << "const std::vector<std::string>& Arg";
2934 /// EmitIncludes - Emit necessary #include directives and some
2935 /// additional declarations.
2936 void EmitIncludes(raw_ostream& O) {
2937 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2938 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2939 << "#include \"llvm/CompilerDriver/Error.h\"\n"
2940 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2942 << "#include \"llvm/Support/CommandLine.h\"\n"
2943 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2945 << "#include <algorithm>\n"
2946 << "#include <cstdlib>\n"
2947 << "#include <iterator>\n"
2948 << "#include <stdexcept>\n\n"
2950 << "using namespace llvm;\n"
2951 << "using namespace llvmc;\n\n"
2953 << "extern cl::opt<std::string> OutputFilename;\n\n"
2955 << "inline const char* checkCString(const char* s)\n"
2956 << "{ return s == NULL ? \"\" : s; }\n\n";
2960 /// PluginData - Holds all information about a plugin.
2962 OptionDescriptions OptDescs;
2964 ToolDescriptions ToolDescs;
2968 /// HasSink - Go through the list of tool descriptions and check if
2969 /// there are any with the 'sink' property set.
2970 bool HasSink(const ToolDescriptions& ToolDescs) {
2971 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2972 E = ToolDescs.end(); B != E; ++B)
2979 /// CollectPluginData - Collect compilation graph edges, tool properties and
2980 /// option properties from the parse tree.
2981 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2982 // Collect option properties.
2983 const RecordVector& OptionLists =
2984 Records.getAllDerivedDefinitions("OptionList");
2985 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2988 // Collect tool properties.
2989 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2990 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2991 Data.HasSink = HasSink(Data.ToolDescs);
2993 // Collect compilation graph edges.
2994 const RecordVector& CompilationGraphs =
2995 Records.getAllDerivedDefinitions("CompilationGraph");
2996 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
3000 /// CheckPluginData - Perform some sanity checks on the collected data.
3001 void CheckPluginData(PluginData& Data) {
3002 // Filter out all tools not mentioned in the compilation graph.
3003 FilterNotInGraph(Data.Edges, Data.ToolDescs);
3005 // Typecheck the compilation graph.
3006 TypecheckGraph(Data.Edges, Data.ToolDescs);
3008 // Check that there are no options without side effects (specified
3009 // only in the OptionList).
3010 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
3013 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
3014 // Emit file header.
3017 // Emit global option registration code.
3018 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, O);
3020 // Emit hook declarations.
3021 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
3023 O << "namespace {\n\n";
3025 // Emit Tool classes.
3026 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
3027 E = Data.ToolDescs.end(); B!=E; ++B)
3028 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
3030 // Emit Edge# classes.
3031 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
3033 O << "} // End anonymous namespace.\n\n";
3035 O << "namespace llvmc {\n";
3036 O << "namespace autogenerated {\n\n";
3038 // Emit PreprocessOptions() function.
3039 EmitPreprocessOptions(Records, Data.OptDescs, O);
3041 // Emit PopulateLanguageMap() function
3042 // (language map maps from file extensions to language names).
3043 EmitPopulateLanguageMap(Records, O);
3045 // Emit PopulateCompilationGraph() function.
3046 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
3048 O << "} // End namespace autogenerated.\n";
3049 O << "} // End namespace llvmc.\n\n";
3055 // End of anonymous namespace
3058 /// run - The back-end entry point.
3059 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
3063 CollectPluginData(Records, Data);
3064 CheckPluginData(Data);
3066 this->EmitSourceFileHeader("LLVMC Configuration Library", O);
3067 EmitPluginCode(Data, O);
3069 } catch (std::exception& Error) {
3070 throw Error.what() + std::string(" - usually this means a syntax error.");