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.
1098 void TypecheckGraph (const RecordVector& EdgeVector,
1099 const ToolDescriptions& ToolDescs) {
1100 StringMap<StringSet<> > ToolToInLang;
1101 StringMap<std::string> ToolToOutLang;
1103 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
1104 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1105 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1107 for (RecordVector::const_iterator B = EdgeVector.begin(),
1108 E = EdgeVector.end(); B != E; ++B) {
1109 const Record* Edge = *B;
1110 const std::string& NodeA = Edge->getValueAsString("a");
1111 const std::string& NodeB = Edge->getValueAsString("b");
1112 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1113 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1115 if (NodeA != "root") {
1116 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1117 throw "Edge " + NodeA + "->" + NodeB
1118 + ": output->input language mismatch";
1121 if (NodeB == "root")
1122 throw "Edges back to the root are not allowed!";
1126 /// WalkCase - Walks the 'case' expression DAG and invokes
1127 /// TestCallback on every test, and StatementCallback on every
1128 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1129 /// combinators (that is, they are passed directly to TestCallback).
1130 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1131 /// IndentLevel, bool FirstTest)'.
1132 /// StatementCallback must have type 'void StatementCallback(const Init*,
1133 /// unsigned IndentLevel)'.
1134 template <typename F1, typename F2>
1135 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1136 unsigned IndentLevel = 0)
1138 const DagInit& d = InitPtrToDag(Case);
1141 if (GetOperatorName(d) != "case")
1142 throw "WalkCase should be invoked only on 'case' expressions!";
1144 if (d.getNumArgs() < 2)
1145 throw "There should be at least one clause in the 'case' expression:\n"
1150 const unsigned numArgs = d.getNumArgs();
1152 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1159 const DagInit& Test = InitPtrToDag(arg);
1161 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1162 throw "The 'default' clause should be the last in the "
1163 "'case' construct!";
1165 throw "Case construct handler: no corresponding action "
1166 "found for the test " + Test.getAsString() + '!';
1168 TestCallback(Test, IndentLevel, (i == 1));
1172 if (dynamic_cast<DagInit*>(arg)
1173 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1175 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1178 // Handle statement.
1179 StatementCallback(arg, IndentLevel);
1187 /// ExtractOptionNames - A helper function object used by
1188 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1189 class ExtractOptionNames {
1190 llvm::StringSet<>& OptionNames_;
1192 void processDag(const Init* Statement) {
1193 const DagInit& Stmt = InitPtrToDag(Statement);
1194 const std::string& ActionName = GetOperatorName(Stmt);
1195 if (ActionName == "forward" || ActionName == "forward_as" ||
1196 ActionName == "forward_value" ||
1197 ActionName == "forward_transformed_value" ||
1198 ActionName == "switch_on" || ActionName == "any_switch_on" ||
1199 ActionName == "parameter_equals" ||
1200 ActionName == "element_in_list" || ActionName == "not_empty" ||
1201 ActionName == "empty") {
1202 CheckNumberOfArguments(Stmt, 1);
1204 Init* Arg = Stmt.getArg(0);
1205 if (typeid(*Arg) == typeid(StringInit)) {
1206 const std::string& Name = InitPtrToString(Arg);
1207 OptionNames_.insert(Name);
1211 const ListInit& List = InitPtrToList(Arg);
1212 for (ListInit::const_iterator B = List.begin(), E = List.end();
1214 const std::string& Name = InitPtrToString(*B);
1215 OptionNames_.insert(Name);
1219 else if (ActionName == "and" || ActionName == "or" || ActionName == "not") {
1220 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1221 this->processDag(Stmt.getArg(i));
1227 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1230 void operator()(const Init* Statement) {
1231 if (typeid(*Statement) == typeid(ListInit)) {
1232 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1233 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1235 this->processDag(*B);
1238 this->processDag(Statement);
1242 void operator()(const DagInit& Test, unsigned, bool) {
1243 this->operator()(&Test);
1245 void operator()(const Init* Statement, unsigned) {
1246 this->operator()(Statement);
1250 /// CheckForSuperfluousOptions - Check that there are no side
1251 /// effect-free options (specified only in the OptionList). Otherwise,
1252 /// output a warning.
1253 void CheckForSuperfluousOptions (const RecordVector& Edges,
1254 const ToolDescriptions& ToolDescs,
1255 const OptionDescriptions& OptDescs) {
1256 llvm::StringSet<> nonSuperfluousOptions;
1258 // Add all options mentioned in the ToolDesc.Actions to the set of
1259 // non-superfluous options.
1260 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1261 E = ToolDescs.end(); B != E; ++B) {
1262 const ToolDescription& TD = *(*B);
1263 ExtractOptionNames Callback(nonSuperfluousOptions);
1265 WalkCase(TD.Actions, Callback, Callback);
1268 // Add all options mentioned in the 'case' clauses of the
1269 // OptionalEdges of the compilation graph to the set of
1270 // non-superfluous options.
1271 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1273 const Record* Edge = *B;
1274 DagInit& Weight = *Edge->getValueAsDag("weight");
1276 if (!IsDagEmpty(Weight))
1277 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1280 // Check that all options in OptDescs belong to the set of
1281 // non-superfluous options.
1282 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1283 E = OptDescs.end(); B != E; ++B) {
1284 const OptionDescription& Val = B->second;
1285 if (!nonSuperfluousOptions.count(Val.Name)
1286 && Val.Type != OptionType::Alias)
1287 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1288 "Probable cause: this option is specified only in the OptionList.\n";
1292 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1293 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1294 if (TestName == "single_input_file") {
1295 O << "InputFilenames.size() == 1";
1298 else if (TestName == "multiple_input_files") {
1299 O << "InputFilenames.size() > 1";
1306 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1307 template <typename F>
1308 void EmitListTest(const ListInit& L, const char* LogicOp,
1309 F Callback, raw_ostream& O)
1311 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1313 bool isFirst = true;
1314 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1318 O << ' ' << LogicOp << ' ';
1319 Callback(InitPtrToString(*B), O);
1323 // Callbacks for use with EmitListTest.
1325 class EmitSwitchOn {
1326 const OptionDescriptions& OptDescs_;
1328 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1331 void operator()(const std::string& OptName, raw_ostream& O) const {
1332 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1333 O << OptDesc.GenVariableName();
1337 class EmitEmptyTest {
1339 const OptionDescriptions& OptDescs_;
1341 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1342 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1345 void operator()(const std::string& OptName, raw_ostream& O) const {
1346 const char* Neg = (EmitNegate_ ? "!" : "");
1347 if (OptName == "o") {
1348 O << Neg << "OutputFilename.empty()";
1350 else if (OptName == "save-temps") {
1351 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1354 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1355 O << Neg << OptDesc.GenVariableName() << ".empty()";
1361 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1362 bool EmitCaseTest1ArgList(const std::string& TestName,
1364 const OptionDescriptions& OptDescs,
1366 const ListInit& L = InitPtrToList(d.getArg(0));
1368 if (TestName == "any_switch_on") {
1369 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1372 else if (TestName == "switch_on") {
1373 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1376 else if (TestName == "any_not_empty") {
1377 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1380 else if (TestName == "any_empty") {
1381 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1384 else if (TestName == "not_empty") {
1385 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1388 else if (TestName == "empty") {
1389 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1396 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1397 bool EmitCaseTest1ArgStr(const std::string& TestName,
1399 const OptionDescriptions& OptDescs,
1401 const std::string& OptName = InitPtrToString(d.getArg(0));
1403 if (TestName == "switch_on") {
1404 apply(EmitSwitchOn(OptDescs), OptName, O);
1407 else if (TestName == "input_languages_contain") {
1408 O << "InLangs.count(\"" << OptName << "\") != 0";
1411 else if (TestName == "in_language") {
1412 // This works only for single-argument Tool::GenerateAction. Join
1413 // tools can process several files in different languages simultaneously.
1415 // TODO: make this work with Edge::Weight (if possible).
1416 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1419 else if (TestName == "not_empty" || TestName == "empty") {
1420 bool EmitNegate = (TestName == "not_empty");
1421 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1428 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1429 bool EmitCaseTest1Arg(const std::string& TestName,
1431 const OptionDescriptions& OptDescs,
1433 CheckNumberOfArguments(d, 1);
1434 if (typeid(*d.getArg(0)) == typeid(ListInit))
1435 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1437 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1440 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1441 bool EmitCaseTest2Args(const std::string& TestName,
1443 unsigned IndentLevel,
1444 const OptionDescriptions& OptDescs,
1446 CheckNumberOfArguments(d, 2);
1447 const std::string& OptName = InitPtrToString(d.getArg(0));
1448 const std::string& OptArg = InitPtrToString(d.getArg(1));
1450 if (TestName == "parameter_equals") {
1451 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1452 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1455 else if (TestName == "element_in_list") {
1456 const OptionDescription& OptDesc = OptDescs.FindParameterList(OptName);
1457 const std::string& VarName = OptDesc.GenVariableName();
1458 O << "std::find(" << VarName << ".begin(),\n";
1459 O.indent(IndentLevel + Indent1)
1460 << VarName << ".end(), \""
1461 << OptArg << "\") != " << VarName << ".end()";
1468 // Forward declaration.
1469 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1470 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1471 const OptionDescriptions& OptDescs,
1474 /// EmitLogicalOperationTest - Helper function used by
1475 /// EmitCaseConstructHandler.
1476 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1477 unsigned IndentLevel,
1478 const OptionDescriptions& OptDescs,
1481 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1482 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1483 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1484 if (j != NumArgs - 1) {
1486 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1494 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1495 const OptionDescriptions& OptDescs, raw_ostream& O)
1497 CheckNumberOfArguments(d, 1);
1498 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1500 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1504 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1505 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1506 const OptionDescriptions& OptDescs,
1508 const std::string& TestName = GetOperatorName(d);
1510 if (TestName == "and")
1511 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1512 else if (TestName == "or")
1513 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1514 else if (TestName == "not")
1515 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1516 else if (EmitCaseTest0Args(TestName, O))
1518 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1520 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1523 throw "Unknown test '" + TestName + "' used in the 'case' construct!";
1527 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1528 class EmitCaseTestCallback {
1530 const OptionDescriptions& OptDescs_;
1534 EmitCaseTestCallback(bool EmitElseIf,
1535 const OptionDescriptions& OptDescs, raw_ostream& O)
1536 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1539 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1541 if (GetOperatorName(Test) == "default") {
1542 O_.indent(IndentLevel) << "else {\n";
1545 O_.indent(IndentLevel)
1546 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1547 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1553 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1554 template <typename F>
1555 class EmitCaseStatementCallback {
1560 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1561 : Callback_(Callback), O_(O)
1564 void operator() (const Init* Statement, unsigned IndentLevel) {
1566 // Ignore nested 'case' DAG.
1567 if (!(dynamic_cast<const DagInit*>(Statement) &&
1568 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1569 if (typeid(*Statement) == typeid(ListInit)) {
1570 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1571 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1573 Callback_(*B, (IndentLevel + Indent1), O_);
1576 Callback_(Statement, (IndentLevel + Indent1), O_);
1579 O_.indent(IndentLevel) << "}\n";
1584 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1585 /// construct. Takes a function object that should emit code for every case
1586 /// clause. Implemented on top of WalkCase.
1587 /// Callback's type is void F(const Init* Statement, unsigned IndentLevel,
1588 /// raw_ostream& O).
1589 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1590 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1592 template <typename F>
1593 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1594 F Callback, bool EmitElseIf,
1595 const OptionDescriptions& OptDescs,
1597 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1598 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1601 /// TokenizeCmdLine - converts from
1602 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1603 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1604 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1605 const char* Delimiters = " \t\n\v\f\r";
1607 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1610 if (CmdLine.empty())
1614 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1617 for (; B != E; ++B) {
1618 char cur_ch = CmdLine[B];
1622 if (cur_ch == '$') {
1623 cur_st = SpecialCommand;
1626 if (OneOf(Delimiters, cur_ch)) {
1628 B = CmdLine.find_first_not_of(Delimiters, B);
1629 if (B == std::string::npos) {
1640 case SpecialCommand:
1641 if (OneOf(Delimiters, cur_ch)) {
1646 if (cur_ch == '(') {
1648 cur_st = InsideSpecialCommand;
1653 case InsideSpecialCommand:
1654 if (OneOf(Delimiters, cur_ch)) {
1657 if (cur_ch == '\'') {
1658 cur_st = InsideQuotationMarks;
1662 if (cur_ch == ')') {
1666 if (cur_ch == ',') {
1672 case InsideQuotationMarks:
1673 if (cur_ch == '\'') {
1674 cur_st = InsideSpecialCommand;
1680 Out.back().push_back(cur_ch);
1684 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1685 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1686 /// SubstituteSpecialCommands().
1687 StrVector::const_iterator
1688 SubstituteCall (StrVector::const_iterator Pos,
1689 StrVector::const_iterator End,
1690 bool IsJoin, raw_ostream& O)
1692 const char* errorMessage = "Syntax error in $CALL invocation!";
1693 CheckedIncrement(Pos, End, errorMessage);
1694 const std::string& CmdName = *Pos;
1697 throw "$CALL invocation: empty argument list!";
1700 O << CmdName << "(";
1703 bool firstIteration = true;
1705 CheckedIncrement(Pos, End, errorMessage);
1706 const std::string& Arg = *Pos;
1707 assert(Arg.size() != 0);
1713 firstIteration = false;
1717 if (Arg == "$INFILE") {
1719 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1721 O << "inFile.c_str()";
1724 O << '"' << Arg << '"';
1733 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1734 /// function used by SubstituteSpecialCommands().
1735 StrVector::const_iterator
1736 SubstituteEnv (StrVector::const_iterator Pos,
1737 StrVector::const_iterator End, raw_ostream& O)
1739 const char* errorMessage = "Syntax error in $ENV invocation!";
1740 CheckedIncrement(Pos, End, errorMessage);
1741 const std::string& EnvName = *Pos;
1744 throw "$ENV invocation: empty argument list!";
1746 O << "checkCString(std::getenv(\"";
1750 CheckedIncrement(Pos, End, errorMessage);
1755 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1756 /// handler code. Helper function used by EmitCmdLineVecFill().
1757 StrVector::const_iterator
1758 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1759 StrVector::const_iterator End,
1760 bool IsJoin, raw_ostream& O)
1763 const std::string& cmd = *Pos;
1765 // Perform substitution.
1766 if (cmd == "$CALL") {
1767 Pos = SubstituteCall(Pos, End, IsJoin, O);
1769 else if (cmd == "$ENV") {
1770 Pos = SubstituteEnv(Pos, End, O);
1773 throw "Unknown special command: " + cmd;
1776 // Handle '$CMD(ARG)/additional/text'.
1777 const std::string& Leftover = *Pos;
1778 assert(Leftover.at(0) == ')');
1779 if (Leftover.size() != 1)
1780 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1785 /// EmitCmdLineVecFill - Emit code that fills in the command line
1786 /// vector. Helper function used by EmitGenerateActionMethod().
1787 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1788 bool IsJoin, unsigned IndentLevel,
1791 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1794 throw "Tool '" + ToolName + "' has empty command line!";
1796 StrVector::const_iterator B = StrVec.begin(), E = StrVec.end();
1798 // Emit the command itself.
1799 assert(!StrVec[0].empty());
1800 O.indent(IndentLevel) << "cmd = ";
1801 if (StrVec[0][0] == '$') {
1802 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1806 O << '"' << StrVec[0] << '"';
1811 // Go through the command arguments.
1813 for (; B != E; ++B) {
1814 const std::string& cmd = *B;
1816 assert(!cmd.empty());
1817 O.indent(IndentLevel);
1819 if (cmd.at(0) == '$') {
1820 O << "vec.push_back(std::make_pair(0, ";
1821 B = SubstituteSpecialCommands(B, E, IsJoin, O);
1825 O << "vec.push_back(std::make_pair(0, \"" << cmd << "\"));\n";
1831 /// EmitForEachListElementCycleHeader - Emit common code for iterating through
1832 /// all elements of a list. Helper function used by
1833 /// EmitForwardOptionPropertyHandlingCode.
1834 void EmitForEachListElementCycleHeader (const OptionDescription& D,
1835 unsigned IndentLevel,
1837 unsigned IndentLevel1 = IndentLevel + Indent1;
1839 O.indent(IndentLevel)
1840 << "for (" << D.GenTypeDeclaration()
1841 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1842 O.indent(IndentLevel)
1843 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1844 O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName()
1845 << ".getPosition(B - " << D.GenVariableName()
1849 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1850 /// implement EmitActionHandler. Emits code for
1851 /// handling the (forward) and (forward_as) option properties.
1852 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1853 unsigned IndentLevel,
1854 const std::string& NewName,
1856 const std::string& Name = NewName.empty()
1859 unsigned IndentLevel1 = IndentLevel + Indent1;
1862 case OptionType::Switch:
1863 O.indent(IndentLevel)
1864 << "vec.push_back(std::make_pair(" << D.GenVariableName()
1865 << ".getPosition(), \"" << Name << "\"));\n";
1867 case OptionType::Parameter:
1868 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1869 << D.GenVariableName()
1870 <<".getPosition(), \"" << Name;
1872 if (!D.isForwardNotSplit()) {
1874 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1875 << D.GenVariableName() << ".getPosition(), "
1876 << D.GenVariableName() << "));\n";
1879 O << "=\" + " << D.GenVariableName() << "));\n";
1882 case OptionType::Prefix:
1883 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1884 << D.GenVariableName() << ".getPosition(), \""
1886 << D.GenVariableName() << "));\n";
1888 case OptionType::PrefixList:
1889 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1890 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1891 << Name << "\" + " << "*B));\n";
1892 O.indent(IndentLevel1) << "++B;\n";
1894 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1895 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1896 O.indent(IndentLevel1) << "++B;\n";
1899 O.indent(IndentLevel) << "}\n";
1901 case OptionType::ParameterList:
1902 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1903 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1904 << Name << "\"));\n";
1906 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1907 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1908 O.indent(IndentLevel1) << "++B;\n";
1911 O.indent(IndentLevel) << "}\n";
1913 case OptionType::SwitchList:
1914 EmitForEachListElementCycleHeader(D, IndentLevel, O);
1915 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1916 << Name << "\"));\n";
1917 O.indent(IndentLevel1) << "++B;\n";
1918 O.indent(IndentLevel) << "}\n";
1920 case OptionType::Alias:
1922 throw "Aliases are not allowed in tool option descriptions!";
1926 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1927 /// EmitPreprocessOptionsCallback.
1928 struct ActionHandlingCallbackBase
1931 void onErrorDag(const DagInit& d,
1932 unsigned IndentLevel, raw_ostream& O) const
1934 O.indent(IndentLevel)
1936 << (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0)) : "Unknown error!")
1938 O.indent(IndentLevel) << "return 1;\n";
1941 void onWarningDag(const DagInit& d,
1942 unsigned IndentLevel, raw_ostream& O) const
1944 CheckNumberOfArguments(d, 1);
1945 O.indent(IndentLevel) << "llvm::errs() << \""
1946 << InitPtrToString(d.getArg(0)) << "\";\n";
1951 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1952 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1953 class EmitActionHandlersCallback;
1955 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1956 (const DagInit&, unsigned, raw_ostream&) const;
1958 class EmitActionHandlersCallback :
1959 public ActionHandlingCallbackBase,
1960 public HandlerTable<EmitActionHandlersCallbackHandler>
1962 typedef EmitActionHandlersCallbackHandler Handler;
1964 const OptionDescriptions& OptDescs;
1966 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1967 /// onAppendCmd and onOutputSuffix.
1968 void EmitHookInvocation(const std::string& Str,
1969 const char* BlockOpen, const char* BlockClose,
1970 unsigned IndentLevel, raw_ostream& O) const
1973 TokenizeCmdLine(Str, Out);
1975 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1977 const std::string& cmd = *B;
1979 O.indent(IndentLevel) << BlockOpen;
1981 if (cmd.at(0) == '$')
1982 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1984 O << '"' << cmd << '"';
1990 void onAppendCmd (const DagInit& Dag,
1991 unsigned IndentLevel, raw_ostream& O) const
1993 CheckNumberOfArguments(Dag, 1);
1994 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1995 "vec.push_back(std::make_pair(65536, ", "));\n",
1999 void onForward (const DagInit& Dag,
2000 unsigned IndentLevel, raw_ostream& O) const
2002 CheckNumberOfArguments(Dag, 1);
2003 const std::string& Name = InitPtrToString(Dag.getArg(0));
2004 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2005 IndentLevel, "", O);
2008 void onForwardAs (const DagInit& Dag,
2009 unsigned IndentLevel, raw_ostream& O) const
2011 CheckNumberOfArguments(Dag, 2);
2012 const std::string& Name = InitPtrToString(Dag.getArg(0));
2013 const std::string& NewName = InitPtrToString(Dag.getArg(1));
2014 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2015 IndentLevel, NewName, O);
2018 void onForwardValue (const DagInit& Dag,
2019 unsigned IndentLevel, raw_ostream& O) const
2021 CheckNumberOfArguments(Dag, 1);
2022 const std::string& Name = InitPtrToString(Dag.getArg(0));
2023 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2025 if (D.isSwitchList()) {
2026 throw std::runtime_error
2027 ("forward_value is not allowed with switch_list");
2030 if (D.isParameter()) {
2031 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2032 << D.GenVariableName() << ".getPosition(), "
2033 << D.GenVariableName() << "));\n";
2036 O.indent(IndentLevel) << "for (" << D.GenTypeDeclaration()
2037 << "::iterator B = " << D.GenVariableName()
2039 O.indent(IndentLevel + Indent1) << " E = " << D.GenVariableName()
2040 << ".end(); B != E; ++B)\n";
2041 O.indent(IndentLevel) << "{\n";
2042 O.indent(IndentLevel + Indent1)
2043 << "unsigned pos = " << D.GenVariableName()
2044 << ".getPosition(B - " << D.GenVariableName()
2046 O.indent(IndentLevel + Indent1)
2047 << "vec.push_back(std::make_pair(pos, *B));\n";
2048 O.indent(IndentLevel) << "}\n";
2052 void onForwardTransformedValue (const DagInit& Dag,
2053 unsigned IndentLevel, raw_ostream& O) const
2055 CheckNumberOfArguments(Dag, 2);
2056 const std::string& Name = InitPtrToString(Dag.getArg(0));
2057 const std::string& Hook = InitPtrToString(Dag.getArg(1));
2058 const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name);
2060 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2061 << D.GenVariableName() << ".getPosition("
2062 << (D.isList() ? "0" : "") << "), "
2063 << "hooks::" << Hook << "(" << D.GenVariableName()
2064 << (D.isParameter() ? ".c_str()" : "") << ")));\n";
2067 void onNoOutFile (const DagInit& Dag,
2068 unsigned IndentLevel, raw_ostream& O) const
2070 CheckNumberOfArguments(Dag, 0);
2071 O.indent(IndentLevel) << "no_out_file = true;\n";
2074 void onOutputSuffix (const DagInit& Dag,
2075 unsigned IndentLevel, raw_ostream& O) const
2077 CheckNumberOfArguments(Dag, 1);
2078 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2079 "output_suffix = ", ";\n", IndentLevel, O);
2082 void onStopCompilation (const DagInit& Dag,
2083 unsigned IndentLevel, raw_ostream& O) const
2085 O.indent(IndentLevel) << "stop_compilation = true;\n";
2089 void onUnpackValues (const DagInit& Dag,
2090 unsigned IndentLevel, raw_ostream& O) const
2092 throw "'unpack_values' is deprecated. "
2093 "Use 'comma_separated' + 'forward_value' instead!";
2098 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
2101 if (!staticMembersInitialized_) {
2102 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
2103 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
2104 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
2105 AddHandler("forward", &EmitActionHandlersCallback::onForward);
2106 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
2107 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
2108 AddHandler("forward_transformed_value",
2109 &EmitActionHandlersCallback::onForwardTransformedValue);
2110 AddHandler("no_out_file",
2111 &EmitActionHandlersCallback::onNoOutFile);
2112 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
2113 AddHandler("stop_compilation",
2114 &EmitActionHandlersCallback::onStopCompilation);
2115 AddHandler("unpack_values",
2116 &EmitActionHandlersCallback::onUnpackValues);
2119 staticMembersInitialized_ = true;
2123 void operator()(const Init* I,
2124 unsigned IndentLevel, raw_ostream& O) const
2126 InvokeDagInitHandler(this, I, IndentLevel, O);
2130 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2131 bool IsJoin, bool Naked,
2134 O.indent(Indent1) << "int GenerateAction(Action& Out,\n";
2137 O.indent(Indent2) << "const PathVector& inFiles,\n";
2139 O.indent(Indent2) << "const sys::Path& inFile,\n";
2141 O.indent(Indent2) << "const bool HasChildren,\n";
2142 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2143 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2144 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2145 O.indent(Indent1) << "{\n";
2148 O.indent(Indent2) << "std::string cmd;\n";
2149 O.indent(Indent2) << "std::string out_file;\n";
2151 << "std::vector<std::pair<unsigned, std::string> > vec;\n";
2152 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2153 O.indent(Indent2) << "bool no_out_file = false;\n";
2154 O.indent(Indent2) << "std::string output_suffix(\""
2155 << D.OutputSuffix << "\");\n";
2159 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2160 // Tool::GenerateAction() method.
2161 void EmitGenerateActionMethod (const ToolDescription& D,
2162 const OptionDescriptions& OptDescs,
2163 bool IsJoin, raw_ostream& O) {
2165 EmitGenerateActionMethodHeader(D, IsJoin, /* Naked = */ false, O);
2168 throw "Tool " + D.Name + " has no cmd_line property!";
2170 // Process the 'command' property.
2172 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2175 // Process the 'actions' list of this tool.
2177 EmitCaseConstructHandler(D.Actions, Indent2,
2178 EmitActionHandlersCallback(OptDescs),
2179 false, OptDescs, O);
2183 if (!D.InFileOption.empty()) {
2185 << "vec.push_back(std::make_pair(InputFilenames.getPosition(0), \""
2186 << D.InFileOption << "\");\n";
2191 << "for (PathVector::const_iterator B = inFiles.begin(),\n";
2192 O.indent(Indent3) << "E = inFiles.end(); B != E; ++B)\n";
2193 O.indent(Indent2) << "{\n";
2194 O.indent(Indent3) << "vec.push_back(std::make_pair("
2195 << "InputFilenames.getPosition(B - inFiles.begin()), "
2197 O.indent(Indent2) << "}\n";
2200 O.indent(Indent2) << "vec.push_back(std::make_pair("
2201 << "InputFilenames.getPosition(0), inFile.str()));\n";
2205 O.indent(Indent2) << "if (!no_out_file) {\n";
2206 if (!D.OutFileOption.empty())
2207 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, \""
2208 << D.OutFileOption << "\"));\n";
2210 O.indent(Indent3) << "out_file = this->OutFilename("
2211 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2212 O.indent(Indent4) <<
2213 "TempDir, stop_compilation, output_suffix.c_str()).str();\n\n";
2214 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, out_file));\n";
2216 O.indent(Indent2) << "}\n\n";
2218 // Handle the Sink property.
2219 std::string SinkOption("autogenerated::");
2220 SinkOption += SinkOptionName;
2222 O.indent(Indent2) << "if (!" << SinkOption << ".empty()) {\n";
2223 O.indent(Indent3) << "for (cl::list<std::string>::iterator B = "
2224 << SinkOption << ".begin(), E = " << SinkOption
2225 << ".end(); B != E; ++B)\n";
2226 O.indent(Indent4) << "vec.push_back(std::make_pair(" << SinkOption
2227 << ".getPosition(B - " << SinkOption
2228 << ".begin()), *B));\n";
2229 O.indent(Indent2) << "}\n";
2232 O.indent(Indent2) << "Out.Construct(cmd, this->SortArgs(vec), "
2233 << "stop_compilation, out_file);\n";
2234 O.indent(Indent2) << "return 0;\n";
2235 O.indent(Indent1) << "}\n\n";
2238 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2239 /// a given Tool class.
2240 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2241 const OptionDescriptions& OptDescs,
2243 if (!ToolDesc.isJoin()) {
2244 EmitGenerateActionMethodHeader(ToolDesc, /* IsJoin = */ true,
2245 /* Naked = */ true, O);
2246 O.indent(Indent2) << "PrintError(\"" << ToolDesc.Name
2247 << " is not a Join tool!\");\n";
2248 O.indent(Indent2) << "return -1;\n";
2249 O.indent(Indent1) << "}\n\n";
2252 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2255 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2258 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2259 /// methods for a given Tool class.
2260 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2261 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2262 O.indent(Indent2) << "return InputLanguages_;\n";
2263 O.indent(Indent1) << "}\n\n";
2265 if (D.OutLanguage.empty())
2266 throw "Tool " + D.Name + " has no 'out_language' property!";
2268 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2269 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2270 O.indent(Indent1) << "}\n\n";
2273 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2274 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2275 O.indent(Indent1) << "const char* Name() const {\n";
2276 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2277 O.indent(Indent1) << "}\n\n";
2280 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2282 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2283 O.indent(Indent1) << "bool IsJoin() const {\n";
2285 O.indent(Indent2) << "return true;\n";
2287 O.indent(Indent2) << "return false;\n";
2288 O.indent(Indent1) << "}\n\n";
2291 /// EmitWorksOnEmptyCallback - Callback used by EmitWorksOnEmptyMethod in
2292 /// conjunction with EmitCaseConstructHandler.
2293 void EmitWorksOnEmptyCallback (const Init* Value,
2294 unsigned IndentLevel, raw_ostream& O) {
2295 CheckBooleanConstant(Value);
2296 O.indent(IndentLevel) << "return " << Value->getAsString() << ";\n";
2299 /// EmitWorksOnEmptyMethod - Emit the WorksOnEmpty() method for a given Tool
2301 void EmitWorksOnEmptyMethod (const ToolDescription& D,
2302 const OptionDescriptions& OptDescs,
2305 O.indent(Indent1) << "bool WorksOnEmpty() const {\n";
2307 O.indent(Indent2) << "return false;\n";
2309 EmitCaseConstructHandler(D.OnEmpty, Indent2, EmitWorksOnEmptyCallback,
2310 /*EmitElseIf = */ true, OptDescs, O);
2311 O.indent(Indent1) << "}\n\n";
2314 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2315 /// given Tool class.
2316 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2317 if (D.InLanguage.empty())
2318 throw "Tool " + D.Name + " has no 'in_language' property!";
2320 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2321 for (StrVector::const_iterator B = D.InLanguage.begin(),
2322 E = D.InLanguage.end(); B != E; ++B)
2323 O << '\"' << *B << "\", ";
2327 /// EmitToolClassDefinition - Emit a Tool class definition.
2328 void EmitToolClassDefinition (const ToolDescription& D,
2329 const OptionDescriptions& OptDescs,
2331 if (D.Name == "root")
2335 O << "class " << D.Name << " : public ";
2341 O << " {\nprivate:\n";
2342 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2345 EmitNameMethod(D, O);
2346 EmitInOutLanguageMethods(D, O);
2347 EmitIsJoinMethod(D, O);
2348 EmitWorksOnEmptyMethod(D, OptDescs, O);
2349 EmitGenerateActionMethods(D, OptDescs, O);
2351 // Close class definition
2354 EmitStaticMemberDefinitions(D, O);
2358 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2359 /// and emit registration code.
2360 void EmitOptionDefinitions (const OptionDescriptions& descs,
2361 bool HasSink, raw_ostream& O)
2363 std::vector<OptionDescription> Aliases;
2365 // Emit static cl::Option variables.
2366 for (OptionDescriptions::const_iterator B = descs.begin(),
2367 E = descs.end(); B!=E; ++B) {
2368 const OptionDescription& val = B->second;
2370 if (val.Type == OptionType::Alias) {
2371 Aliases.push_back(val);
2375 O << val.GenTypeDeclaration() << ' '
2376 << val.GenPlainVariableName();
2378 O << "(\"" << val.Name << "\"\n";
2380 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2381 O << ", cl::Prefix";
2383 if (val.isRequired()) {
2384 if (val.isList() && !val.isMultiVal())
2385 O << ", cl::OneOrMore";
2387 O << ", cl::Required";
2390 if (val.isOptional())
2391 O << ", cl::Optional";
2393 if (val.isOneOrMore())
2394 O << ", cl::OneOrMore";
2396 if (val.isZeroOrMore())
2397 O << ", cl::ZeroOrMore";
2399 if (val.isReallyHidden())
2400 O << ", cl::ReallyHidden";
2401 else if (val.isHidden())
2402 O << ", cl::Hidden";
2404 if (val.isCommaSeparated())
2405 O << ", cl::CommaSeparated";
2407 if (val.MultiVal > 1)
2408 O << ", cl::multi_val(" << val.MultiVal << ')';
2411 const std::string& str = val.InitVal->getAsString();
2412 O << ", cl::init(" << str << ')';
2415 if (!val.Help.empty())
2416 O << ", cl::desc(\"" << val.Help << "\")";
2421 // Emit the aliases (they should go after all the 'proper' options).
2422 for (std::vector<OptionDescription>::const_iterator
2423 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2424 const OptionDescription& val = *B;
2426 O << val.GenTypeDeclaration() << ' '
2427 << val.GenPlainVariableName()
2428 << "(\"" << val.Name << '\"';
2430 const OptionDescription& D = descs.FindOption(val.Help);
2431 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2433 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2436 // Emit the sink option.
2438 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
2443 /// EmitPreprocessOptionsCallback - Helper function passed to
2444 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2446 class EmitPreprocessOptionsCallback;
2449 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2450 (const DagInit&, unsigned, raw_ostream&) const;
2452 class EmitPreprocessOptionsCallback :
2453 public ActionHandlingCallbackBase,
2454 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2456 typedef EmitPreprocessOptionsCallbackHandler Handler;
2458 (EmitPreprocessOptionsCallback::* HandlerImpl)
2459 (const Init*, unsigned, raw_ostream&) const;
2461 const OptionDescriptions& OptDescs_;
2463 void onListOrDag(const DagInit& d, HandlerImpl h,
2464 unsigned IndentLevel, raw_ostream& O) const
2466 CheckNumberOfArguments(d, 1);
2467 const Init* I = d.getArg(0);
2469 // If I is a list, apply h to each element.
2470 if (typeid(*I) == typeid(ListInit)) {
2471 const ListInit& L = *static_cast<const ListInit*>(I);
2472 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2473 ((this)->*(h))(*B, IndentLevel, O);
2475 // Otherwise, apply h to I.
2477 ((this)->*(h))(I, IndentLevel, O);
2481 void onUnsetOptionImpl(const Init* I,
2482 unsigned IndentLevel, raw_ostream& O) const
2484 const std::string& OptName = InitPtrToString(I);
2485 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2487 if (OptDesc.isSwitch()) {
2488 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2490 else if (OptDesc.isParameter()) {
2491 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2493 else if (OptDesc.isList()) {
2494 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2497 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2501 void onUnsetOption(const DagInit& d,
2502 unsigned IndentLevel, raw_ostream& O) const
2504 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2508 void onSetOptionImpl(const DagInit& d,
2509 unsigned IndentLevel, raw_ostream& O) const {
2510 CheckNumberOfArguments(d, 2);
2511 const std::string& OptName = InitPtrToString(d.getArg(0));
2512 const Init* Value = d.getArg(1);
2513 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2515 if (OptDesc.isList()) {
2516 const ListInit& List = InitPtrToList(Value);
2518 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2519 for (ListInit::const_iterator B = List.begin(), E = List.end();
2521 const Init* CurElem = *B;
2522 if (OptDesc.isSwitchList())
2523 CheckBooleanConstant(CurElem);
2525 O.indent(IndentLevel)
2526 << OptDesc.GenVariableName() << ".push_back(\""
2527 << (OptDesc.isSwitchList() ? CurElem->getAsString()
2528 : InitPtrToString(CurElem))
2532 else if (OptDesc.isSwitch()) {
2533 CheckBooleanConstant(Value);
2534 O.indent(IndentLevel) << OptDesc.GenVariableName()
2535 << " = " << Value->getAsString() << ";\n";
2537 else if (OptDesc.isParameter()) {
2538 const std::string& Str = InitPtrToString(Value);
2539 O.indent(IndentLevel) << OptDesc.GenVariableName()
2540 << " = \"" << Str << "\";\n";
2543 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2547 void onSetSwitch(const Init* I,
2548 unsigned IndentLevel, raw_ostream& O) const {
2549 const std::string& OptName = InitPtrToString(I);
2550 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2552 if (OptDesc.isSwitch())
2553 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2555 throw "set_option: -" + OptName + " is not a switch option!";
2558 void onSetOption(const DagInit& d,
2559 unsigned IndentLevel, raw_ostream& O) const
2561 CheckNumberOfArguments(d, 1);
2563 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2564 // boolean, a string or a string list.
2565 if (d.getNumArgs() > 1)
2566 this->onSetOptionImpl(d, IndentLevel, O);
2567 // One argument: (set_option "switch")
2568 // or (set_option ["switch1", "switch2", ...])
2570 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2576 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2577 : OptDescs_(OptDescs)
2579 if (!staticMembersInitialized_) {
2580 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2581 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2582 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2583 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2585 staticMembersInitialized_ = true;
2589 void operator()(const Init* I,
2590 unsigned IndentLevel, raw_ostream& O) const
2592 InvokeDagInitHandler(this, I, IndentLevel, O);
2597 /// EmitPreprocessOptions - Emit the PreprocessOptions() function.
2598 void EmitPreprocessOptions (const RecordKeeper& Records,
2599 const OptionDescriptions& OptDecs, raw_ostream& O)
2601 O << "int PreprocessOptions () {\n";
2603 const RecordVector& OptionPreprocessors =
2604 Records.getAllDerivedDefinitions("OptionPreprocessor");
2606 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2607 E = OptionPreprocessors.end(); B!=E; ++B) {
2608 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2609 EmitCaseConstructHandler(Case, Indent1,
2610 EmitPreprocessOptionsCallback(OptDecs),
2615 O.indent(Indent1) << "return 0;\n";
2619 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
2620 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2622 O << "int PopulateLanguageMap (LanguageMap& langMap) {\n";
2624 const RecordVector& LanguageMaps =
2625 Records.getAllDerivedDefinitions("LanguageMap");
2627 for (RecordVector::const_iterator B = LanguageMaps.begin(),
2628 E = LanguageMaps.end(); B!=E; ++B) {
2629 ListInit* LangsToSuffixesList = (*B)->getValueAsListInit("map");
2630 if (!LangsToSuffixesList)
2631 throw "Error in the language map definition!";
2633 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2634 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2636 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2637 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2639 for (unsigned i = 0; i < Suffixes->size(); ++i)
2640 O.indent(Indent1) << "langMap[\""
2641 << InitPtrToString(Suffixes->getElement(i))
2642 << "\"] = \"" << Lang << "\";\n";
2647 O.indent(Indent1) << "return 0;\n";
2651 /// EmitEdgePropertyHandlerCallback - Emits code that handles edge
2652 /// properties. Helper function passed to EmitCaseConstructHandler() by
2653 /// EmitEdgeClass().
2654 void EmitEdgePropertyHandlerCallback (const Init* i, unsigned IndentLevel,
2656 const DagInit& d = InitPtrToDag(i);
2657 const std::string& OpName = GetOperatorName(d);
2659 if (OpName == "inc_weight") {
2660 O.indent(IndentLevel) << "ret += ";
2662 else if (OpName == "error") {
2663 CheckNumberOfArguments(d, 1);
2664 O.indent(IndentLevel) << "PrintError(\""
2665 << InitPtrToString(d.getArg(0))
2667 O.indent(IndentLevel) << "return -1;\n";
2671 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2672 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2675 if (d.getNumArgs() > 0)
2676 O << InitPtrToInt(d.getArg(0)) << ";\n";
2682 /// EmitEdgeClass - Emit a single Edge# class.
2683 void EmitEdgeClass (unsigned N, const std::string& Target,
2684 DagInit* Case, const OptionDescriptions& OptDescs,
2687 // Class constructor.
2688 O << "class Edge" << N << ": public Edge {\n"
2690 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2693 // Function Weight().
2695 << "int Weight(const InputLanguagesSet& InLangs) const {\n";
2696 O.indent(Indent2) << "unsigned ret = 0;\n";
2698 // Handle the 'case' construct.
2699 EmitCaseConstructHandler(Case, Indent2, EmitEdgePropertyHandlerCallback,
2700 false, OptDescs, O);
2702 O.indent(Indent2) << "return ret;\n";
2703 O.indent(Indent1) << "}\n\n};\n\n";
2706 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2707 void EmitEdgeClasses (const RecordVector& EdgeVector,
2708 const OptionDescriptions& OptDescs,
2711 for (RecordVector::const_iterator B = EdgeVector.begin(),
2712 E = EdgeVector.end(); B != E; ++B) {
2713 const Record* Edge = *B;
2714 const std::string& NodeB = Edge->getValueAsString("b");
2715 DagInit& Weight = *Edge->getValueAsDag("weight");
2717 if (!IsDagEmpty(Weight))
2718 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2723 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph() function.
2724 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2725 const ToolDescriptions& ToolDescs,
2728 O << "int PopulateCompilationGraph (CompilationGraph& G) {\n";
2730 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2731 E = ToolDescs.end(); B != E; ++B)
2732 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2739 for (RecordVector::const_iterator B = EdgeVector.begin(),
2740 E = EdgeVector.end(); B != E; ++B) {
2741 const Record* Edge = *B;
2742 const std::string& NodeA = Edge->getValueAsString("a");
2743 const std::string& NodeB = Edge->getValueAsString("b");
2744 DagInit& Weight = *Edge->getValueAsDag("weight");
2746 O.indent(Indent1) << "if (int ret = G.insertEdge(\"" << NodeA << "\", ";
2748 if (IsDagEmpty(Weight))
2749 O << "new SimpleEdge(\"" << NodeB << "\")";
2751 O << "new Edge" << i << "()";
2754 O.indent(Indent2) << "return ret;\n";
2760 O.indent(Indent1) << "return 0;\n";
2764 /// HookInfo - Information about the hook type and number of arguments.
2767 // A hook can either have a single parameter of type std::vector<std::string>,
2768 // or NumArgs parameters of type const char*.
2769 enum HookType { ListHook, ArgHook };
2774 HookInfo() : Type(ArgHook), NumArgs(1)
2777 HookInfo(HookType T) : Type(T), NumArgs(1)
2780 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2784 typedef llvm::StringMap<HookInfo> HookInfoMap;
2786 /// ExtractHookNames - Extract the hook names from all instances of
2787 /// $CALL(HookName) in the provided command line string/action. Helper
2788 /// function used by FillInHookNames().
2789 class ExtractHookNames {
2790 HookInfoMap& HookNames_;
2791 const OptionDescriptions& OptDescs_;
2793 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2794 : HookNames_(HookNames), OptDescs_(OptDescs)
2797 void onAction (const DagInit& Dag) {
2798 const std::string& Name = GetOperatorName(Dag);
2800 if (Name == "forward_transformed_value") {
2801 CheckNumberOfArguments(Dag, 2);
2802 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2803 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2804 const OptionDescription& D =
2805 OptDescs_.FindParameterListOrParameter(OptName);
2807 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2808 : HookInfo::ArgHook);
2810 else if (Name == "append_cmd" || Name == "output_suffix") {
2811 CheckNumberOfArguments(Dag, 1);
2812 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2816 void onCmdLine(const std::string& Cmd) {
2818 TokenizeCmdLine(Cmd, cmds);
2820 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2822 const std::string& cmd = *B;
2824 if (cmd == "$CALL") {
2825 unsigned NumArgs = 0;
2826 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2827 const std::string& HookName = *B;
2829 if (HookName.at(0) == ')')
2830 throw "$CALL invoked with no arguments!";
2832 while (++B != E && B->at(0) != ')') {
2836 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2838 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2839 H->second.Type != HookInfo::ArgHook)
2840 throw "Overloading of hooks is not allowed. Overloaded hook: "
2843 HookNames_[HookName] = HookInfo(NumArgs);
2848 void operator()(const Init* Arg) {
2850 // We're invoked on an action (either a dag or a dag list).
2851 if (typeid(*Arg) == typeid(DagInit)) {
2852 const DagInit& Dag = InitPtrToDag(Arg);
2853 this->onAction(Dag);
2856 else if (typeid(*Arg) == typeid(ListInit)) {
2857 const ListInit& List = InitPtrToList(Arg);
2858 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2860 const DagInit& Dag = InitPtrToDag(*B);
2861 this->onAction(Dag);
2866 // We're invoked on a command line.
2867 this->onCmdLine(InitPtrToString(Arg));
2870 void operator()(const DagInit* Test, unsigned, bool) {
2871 this->operator()(Test);
2873 void operator()(const Init* Statement, unsigned) {
2874 this->operator()(Statement);
2878 /// FillInHookNames - Actually extract the hook names from all command
2879 /// line strings. Helper function used by EmitHookDeclarations().
2880 void FillInHookNames(const ToolDescriptions& ToolDescs,
2881 const OptionDescriptions& OptDescs,
2882 HookInfoMap& HookNames)
2884 // For all tool descriptions:
2885 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2886 E = ToolDescs.end(); B != E; ++B) {
2887 const ToolDescription& D = *(*B);
2889 // Look for 'forward_transformed_value' in 'actions'.
2891 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2893 // Look for hook invocations in 'cmd_line'.
2896 if (dynamic_cast<StringInit*>(D.CmdLine))
2897 // This is a string.
2898 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2900 // This is a 'case' construct.
2901 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2905 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2906 /// property records and emit hook function declaration for each
2907 /// instance of $CALL(HookName).
2908 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2909 const OptionDescriptions& OptDescs, raw_ostream& O) {
2910 HookInfoMap HookNames;
2912 FillInHookNames(ToolDescs, OptDescs, HookNames);
2913 if (HookNames.empty())
2916 for (HookInfoMap::const_iterator B = HookNames.begin(),
2917 E = HookNames.end(); B != E; ++B) {
2918 const char* HookName = B->first();
2919 const HookInfo& Info = B->second;
2921 O.indent(Indent1) << "std::string " << HookName << "(";
2923 if (Info.Type == HookInfo::ArgHook) {
2924 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2925 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2929 O << "const std::vector<std::string>& Arg";
2936 /// EmitIncludes - Emit necessary #include directives and some
2937 /// additional declarations.
2938 void EmitIncludes(raw_ostream& O) {
2939 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2940 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2941 << "#include \"llvm/CompilerDriver/Error.h\"\n"
2942 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2944 << "#include \"llvm/Support/CommandLine.h\"\n"
2945 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2947 << "#include <algorithm>\n"
2948 << "#include <cstdlib>\n"
2949 << "#include <iterator>\n"
2950 << "#include <stdexcept>\n\n"
2952 << "using namespace llvm;\n"
2953 << "using namespace llvmc;\n\n"
2955 << "inline const char* checkCString(const char* s)\n"
2956 << "{ return s == NULL ? \"\" : s; }\n\n";
2960 /// DriverData - Holds all information about the driver.
2962 OptionDescriptions OptDescs;
2963 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 /// CollectDriverData - Collect compilation graph edges, tool properties and
2980 /// option properties from the parse tree.
2981 void CollectDriverData (const RecordKeeper& Records, DriverData& 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 /// CheckDriverData - Perform some sanity checks on the collected data.
3001 void CheckDriverData(DriverData& 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 EmitDriverCode(const DriverData& Data, raw_ostream& O) {
3014 // Emit file header.
3017 // Emit global option registration code.
3018 O << "namespace llvmc {\n"
3019 << "namespace autogenerated {\n\n";
3020 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, O);
3021 O << "} // End namespace autogenerated.\n"
3022 << "} // End namespace llvmc.\n\n";
3024 // Emit hook declarations.
3025 O << "namespace hooks {\n";
3026 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
3027 O << "} // End namespace hooks.\n\n";
3029 O << "namespace {\n\n";
3030 O << "using namespace llvmc::autogenerated;\n\n";
3032 // Emit Tool classes.
3033 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
3034 E = Data.ToolDescs.end(); B!=E; ++B)
3035 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
3037 // Emit Edge# classes.
3038 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
3040 O << "} // End anonymous namespace.\n\n";
3042 O << "namespace llvmc {\n";
3043 O << "namespace autogenerated {\n\n";
3045 // Emit PreprocessOptions() function.
3046 EmitPreprocessOptions(Records, Data.OptDescs, O);
3048 // Emit PopulateLanguageMap() function
3049 // (language map maps from file extensions to language names).
3050 EmitPopulateLanguageMap(Records, O);
3052 // Emit PopulateCompilationGraph() function.
3053 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
3055 O << "} // End namespace autogenerated.\n";
3056 O << "} // End namespace llvmc.\n\n";
3062 // End of anonymous namespace
3065 /// run - The back-end entry point.
3066 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
3070 CollectDriverData(Records, Data);
3071 CheckDriverData(Data);
3073 this->EmitSourceFileHeader("llvmc-based driver: auto-generated code", O);
3074 EmitDriverCode(Data, O);
3076 } catch (std::exception& Error) {
3077 throw Error.what() + std::string(" - usually this means a syntax error.");