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, Extern = 0x8,
238 OneOrMore = 0x10, Optional = 0x20,
239 CommaSeparated = 0x40, ForwardNotSplit = 0x80,
240 ZeroOrMore = 0x100 };
243 /// OptionDescription - Represents data contained in a single
244 /// OptionList entry.
245 struct OptionDescription {
246 OptionType::OptionType Type;
253 OptionDescription(OptionType::OptionType t = OptionType::Switch,
254 const std::string& n = "",
255 const std::string& h = DefaultHelpString)
256 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
259 /// GenTypeDeclaration - Returns the C++ variable type of this
261 const char* GenTypeDeclaration() const;
263 /// GenVariableName - Returns the variable name used in the
264 /// generated C++ code.
265 std::string GenVariableName() const;
267 /// Merge - Merge two option descriptions.
268 void Merge (const OptionDescription& other);
270 /// CheckConsistency - Check that the flags are consistent.
271 void CheckConsistency() const;
273 // Misc convenient getters/setters.
275 bool isAlias() const;
277 bool isMultiVal() const;
279 bool isCommaSeparated() const;
280 void setCommaSeparated();
282 bool isExtern() const;
285 bool isForwardNotSplit() const;
286 void setForwardNotSplit();
288 bool isRequired() const;
291 bool isOneOrMore() const;
294 bool isZeroOrMore() const;
295 void setZeroOrMore();
297 bool isOptional() const;
300 bool isHidden() const;
303 bool isReallyHidden() const;
304 void setReallyHidden();
306 bool isSwitch() const
307 { return OptionType::IsSwitch(this->Type); }
309 bool isSwitchList() const
310 { return OptionType::IsSwitchList(this->Type); }
312 bool isParameter() const
313 { return OptionType::IsParameter(this->Type); }
316 { return OptionType::IsList(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::isExtern() const {
372 return Flags & OptionDescriptionFlags::Extern;
374 void OptionDescription::setExtern() {
375 Flags |= OptionDescriptionFlags::Extern;
378 bool OptionDescription::isRequired() const {
379 return Flags & OptionDescriptionFlags::Required;
381 void OptionDescription::setRequired() {
382 Flags |= OptionDescriptionFlags::Required;
385 bool OptionDescription::isOneOrMore() const {
386 return Flags & OptionDescriptionFlags::OneOrMore;
388 void OptionDescription::setOneOrMore() {
389 Flags |= OptionDescriptionFlags::OneOrMore;
392 bool OptionDescription::isZeroOrMore() const {
393 return Flags & OptionDescriptionFlags::ZeroOrMore;
395 void OptionDescription::setZeroOrMore() {
396 Flags |= OptionDescriptionFlags::ZeroOrMore;
399 bool OptionDescription::isOptional() const {
400 return Flags & OptionDescriptionFlags::Optional;
402 void OptionDescription::setOptional() {
403 Flags |= OptionDescriptionFlags::Optional;
406 bool OptionDescription::isHidden() const {
407 return Flags & OptionDescriptionFlags::Hidden;
409 void OptionDescription::setHidden() {
410 Flags |= OptionDescriptionFlags::Hidden;
413 bool OptionDescription::isReallyHidden() const {
414 return Flags & OptionDescriptionFlags::ReallyHidden;
416 void OptionDescription::setReallyHidden() {
417 Flags |= OptionDescriptionFlags::ReallyHidden;
420 const char* OptionDescription::GenTypeDeclaration() const {
422 case OptionType::Alias:
424 case OptionType::PrefixList:
425 case OptionType::ParameterList:
426 return "cl::list<std::string>";
427 case OptionType::Switch:
428 return "cl::opt<bool>";
429 case OptionType::SwitchList:
430 return "cl::list<bool>";
431 case OptionType::Parameter:
432 case OptionType::Prefix:
434 return "cl::opt<std::string>";
438 std::string OptionDescription::GenVariableName() const {
439 const std::string& EscapedName = EscapeVariableName(Name);
441 case OptionType::Alias:
442 return "AutoGeneratedAlias_" + EscapedName;
443 case OptionType::PrefixList:
444 case OptionType::ParameterList:
445 return "AutoGeneratedList_" + EscapedName;
446 case OptionType::Switch:
447 return "AutoGeneratedSwitch_" + EscapedName;
448 case OptionType::SwitchList:
449 return "AutoGeneratedSwitchList_" + EscapedName;
450 case OptionType::Prefix:
451 case OptionType::Parameter:
453 return "AutoGeneratedParameter_" + EscapedName;
457 /// OptionDescriptions - An OptionDescription array plus some helper
459 class OptionDescriptions {
460 typedef StringMap<OptionDescription> container_type;
462 /// Descriptions - A list of OptionDescriptions.
463 container_type Descriptions;
466 /// FindOption - exception-throwing wrapper for find().
467 const OptionDescription& FindOption(const std::string& OptName) const;
469 // Wrappers for FindOption that throw an exception in case the option has a
471 const OptionDescription& FindSwitch(const std::string& OptName) const;
472 const OptionDescription& FindParameter(const std::string& OptName) const;
473 const OptionDescription& FindList(const std::string& OptName) const;
474 const OptionDescription&
475 FindListOrParameter(const std::string& OptName) const;
477 /// insertDescription - Insert new OptionDescription into
478 /// OptionDescriptions list
479 void InsertDescription (const OptionDescription& o);
481 // Support for STL-style iteration
482 typedef container_type::const_iterator const_iterator;
483 const_iterator begin() const { return Descriptions.begin(); }
484 const_iterator end() const { return Descriptions.end(); }
487 const OptionDescription&
488 OptionDescriptions::FindOption(const std::string& OptName) const {
489 const_iterator I = Descriptions.find(OptName);
490 if (I != Descriptions.end())
493 throw OptName + ": no such option!";
496 const OptionDescription&
497 OptionDescriptions::FindSwitch(const std::string& OptName) const {
498 const OptionDescription& OptDesc = this->FindOption(OptName);
499 if (!OptDesc.isSwitch())
500 throw OptName + ": incorrect option type - should be a switch!";
504 const OptionDescription&
505 OptionDescriptions::FindList(const std::string& OptName) const {
506 const OptionDescription& OptDesc = this->FindOption(OptName);
507 if (!OptDesc.isList())
508 throw OptName + ": incorrect option type - should be a list!";
512 const OptionDescription&
513 OptionDescriptions::FindParameter(const std::string& OptName) const {
514 const OptionDescription& OptDesc = this->FindOption(OptName);
515 if (!OptDesc.isParameter())
516 throw OptName + ": incorrect option type - should be a parameter!";
520 const OptionDescription&
521 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
522 const OptionDescription& OptDesc = this->FindOption(OptName);
523 if (!OptDesc.isList() && !OptDesc.isParameter())
525 + ": incorrect option type - should be a list or parameter!";
529 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
530 container_type::iterator I = Descriptions.find(o.Name);
531 if (I != Descriptions.end()) {
532 OptionDescription& D = I->second;
536 Descriptions[o.Name] = o;
540 /// HandlerTable - A base class for function objects implemented as
541 /// 'tables of handlers'.
542 template <typename Handler>
545 // Implementation details.
547 /// HandlerMap - A map from property names to property handlers
548 typedef StringMap<Handler> HandlerMap;
550 static HandlerMap Handlers_;
551 static bool staticMembersInitialized_;
555 Handler GetHandler (const std::string& HandlerName) const {
556 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
558 if (method != Handlers_.end()) {
559 Handler h = method->second;
563 throw "No handler found for property " + HandlerName + "!";
567 void AddHandler(const char* Property, Handler H) {
568 Handlers_[Property] = H;
573 template <class Handler, class FunctionObject>
574 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
575 const std::string& HandlerName = GetOperatorName(Dag);
576 return Obj->GetHandler(HandlerName);
579 template <class FunctionObject>
580 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
581 typedef void (FunctionObject::*Handler) (const DagInit&);
583 const DagInit& Dag = InitPtrToDag(I);
584 Handler h = GetHandler<Handler>(Obj, Dag);
589 template <class FunctionObject>
590 void InvokeDagInitHandler(const FunctionObject* const Obj,
591 const Init* I, unsigned IndentLevel, raw_ostream& O)
593 typedef void (FunctionObject::*Handler)
594 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
596 const DagInit& Dag = InitPtrToDag(I);
597 Handler h = GetHandler<Handler>(Obj, Dag);
599 ((Obj)->*(h))(Dag, IndentLevel, O);
603 template <typename H>
604 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
606 template <typename H>
607 bool HandlerTable<H>::staticMembersInitialized_ = false;
610 /// CollectOptionProperties - Function object for iterating over an
611 /// option property list.
612 class CollectOptionProperties;
613 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
616 class CollectOptionProperties
617 : public HandlerTable<CollectOptionPropertiesHandler>
621 /// optDescs_ - OptionDescriptions table. This is where the
622 /// information is stored.
623 OptionDescription& optDesc_;
627 explicit CollectOptionProperties(OptionDescription& OD)
630 if (!staticMembersInitialized_) {
631 AddHandler("extern", &CollectOptionProperties::onExtern);
632 AddHandler("help", &CollectOptionProperties::onHelp);
633 AddHandler("hidden", &CollectOptionProperties::onHidden);
634 AddHandler("init", &CollectOptionProperties::onInit);
635 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
636 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
637 AddHandler("zero_or_more", &CollectOptionProperties::onZeroOrMore);
638 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
639 AddHandler("required", &CollectOptionProperties::onRequired);
640 AddHandler("optional", &CollectOptionProperties::onOptional);
641 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
642 AddHandler("forward_not_split",
643 &CollectOptionProperties::onForwardNotSplit);
645 staticMembersInitialized_ = true;
649 /// operator() - Just forwards to the corresponding property
651 void operator() (Init* I) {
652 InvokeDagInitHandler(this, I);
657 /// Option property handlers --
658 /// Methods that handle option properties such as (help) or (hidden).
660 void onExtern (const DagInit& d) {
661 CheckNumberOfArguments(d, 0);
662 optDesc_.setExtern();
665 void onHelp (const DagInit& d) {
666 CheckNumberOfArguments(d, 1);
667 optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0)));
670 void onHidden (const DagInit& d) {
671 CheckNumberOfArguments(d, 0);
672 optDesc_.setHidden();
675 void onReallyHidden (const DagInit& d) {
676 CheckNumberOfArguments(d, 0);
677 optDesc_.setReallyHidden();
680 void onCommaSeparated (const DagInit& d) {
681 CheckNumberOfArguments(d, 0);
682 if (!optDesc_.isList())
683 throw "'comma_separated' is valid only on list options!";
684 optDesc_.setCommaSeparated();
687 void onForwardNotSplit (const DagInit& d) {
688 CheckNumberOfArguments(d, 0);
689 if (!optDesc_.isParameter())
690 throw "'forward_not_split' is valid only for parameter options!";
691 optDesc_.setForwardNotSplit();
694 void onRequired (const DagInit& d) {
695 CheckNumberOfArguments(d, 0);
697 optDesc_.setRequired();
698 optDesc_.CheckConsistency();
701 void onInit (const DagInit& d) {
702 CheckNumberOfArguments(d, 1);
703 Init* i = d.getArg(0);
704 const std::string& str = i->getAsString();
706 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
707 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
710 throw "Incorrect usage of the 'init' option property!";
712 optDesc_.InitVal = i;
715 void onOneOrMore (const DagInit& d) {
716 CheckNumberOfArguments(d, 0);
718 optDesc_.setOneOrMore();
719 optDesc_.CheckConsistency();
722 void onZeroOrMore (const DagInit& d) {
723 CheckNumberOfArguments(d, 0);
725 if (optDesc_.isList())
726 llvm::errs() << "Warning: specifying the 'zero_or_more' property "
727 "on a list option has no effect.\n";
729 optDesc_.setZeroOrMore();
730 optDesc_.CheckConsistency();
733 void onOptional (const DagInit& d) {
734 CheckNumberOfArguments(d, 0);
736 if (!optDesc_.isList())
737 llvm::errs() << "Warning: specifying the 'optional' property"
738 "on a non-list option has no effect.\n";
740 optDesc_.setOptional();
741 optDesc_.CheckConsistency();
744 void onMultiVal (const DagInit& d) {
745 CheckNumberOfArguments(d, 1);
746 int val = InitPtrToInt(d.getArg(0));
748 throw "Error in the 'multi_val' property: "
749 "the value must be greater than 1!";
750 if (!optDesc_.isList())
751 throw "The multi_val property is valid only on list options!";
752 optDesc_.MultiVal = val;
757 /// AddOption - A function object that is applied to every option
758 /// description. Used by CollectOptionDescriptions.
761 OptionDescriptions& OptDescs_;
764 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
767 void operator()(const Init* i) {
768 const DagInit& d = InitPtrToDag(i);
769 CheckNumberOfArguments(d, 1);
771 const OptionType::OptionType Type =
772 stringToOptionType(GetOperatorName(d));
773 const std::string& Name = InitPtrToString(d.getArg(0));
775 OptionDescription OD(Type, Name);
778 CheckNumberOfArguments(d, 2);
781 // Aliases store the aliased option name in the 'Help' field.
782 OD.Help = InitPtrToString(d.getArg(1));
784 else if (!OD.isExtern()) {
785 processOptionProperties(d, OD);
787 OptDescs_.InsertDescription(OD);
791 /// processOptionProperties - Go through the list of option
792 /// properties and call a corresponding handler for each.
793 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
794 CheckNumberOfArguments(d, 2);
795 DagInit::const_arg_iterator B = d.arg_begin();
796 // Skip the first argument: it's always the option name.
798 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
803 /// CollectOptionDescriptions - Collects option properties from all
805 void CollectOptionDescriptions (RecordVector::const_iterator B,
806 RecordVector::const_iterator E,
807 OptionDescriptions& OptDescs)
809 // For every OptionList:
811 RecordVector::value_type T = *B;
812 // Throws an exception if the value does not exist.
813 ListInit* PropList = T->getValueAsListInit("options");
815 // For every option description in this list:
816 // collect the information and
817 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
821 // Tool information record
823 namespace ToolFlags {
824 enum ToolFlags { Join = 0x1, Sink = 0x2 };
827 struct ToolDescription : public RefCountedBase<ToolDescription> {
831 StrVector InLanguage;
832 std::string InFileOption;
833 std::string OutFileOption;
834 std::string OutLanguage;
835 std::string OutputSuffix;
839 // Various boolean properties
840 void setSink() { Flags |= ToolFlags::Sink; }
841 bool isSink() const { return Flags & ToolFlags::Sink; }
842 void setJoin() { Flags |= ToolFlags::Join; }
843 bool isJoin() const { return Flags & ToolFlags::Join; }
845 // Default ctor here is needed because StringMap can only store
846 // DefaultConstructible objects
848 : CmdLine(0), Actions(0), OutFileOption("-o"),
851 ToolDescription (const std::string& n)
852 : Name(n), CmdLine(0), Actions(0), OutFileOption("-o"),
857 /// ToolDescriptions - A list of Tool information records.
858 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
861 /// CollectToolProperties - Function object for iterating over a list of
862 /// tool property records.
864 class CollectToolProperties;
865 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
868 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
872 /// toolDesc_ - Properties of the current Tool. This is where the
873 /// information is stored.
874 ToolDescription& toolDesc_;
878 explicit CollectToolProperties (ToolDescription& d)
881 if (!staticMembersInitialized_) {
883 AddHandler("actions", &CollectToolProperties::onActions);
884 AddHandler("command", &CollectToolProperties::onCommand);
885 AddHandler("in_language", &CollectToolProperties::onInLanguage);
886 AddHandler("join", &CollectToolProperties::onJoin);
887 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
889 AddHandler("out_file_option", &CollectToolProperties::onOutFileOption);
890 AddHandler("in_file_option", &CollectToolProperties::onInFileOption);
892 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
893 AddHandler("sink", &CollectToolProperties::onSink);
894 AddHandler("works_on_empty", &CollectToolProperties::onWorksOnEmpty);
896 staticMembersInitialized_ = true;
900 void operator() (Init* I) {
901 InvokeDagInitHandler(this, I);
906 /// Property handlers --
907 /// Functions that extract information about tool properties from
908 /// DAG representation.
910 void onActions (const DagInit& d) {
911 CheckNumberOfArguments(d, 1);
912 Init* Case = d.getArg(0);
913 if (typeid(*Case) != typeid(DagInit) ||
914 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
915 throw "The argument to (actions) should be a 'case' construct!";
916 toolDesc_.Actions = Case;
919 void onCommand (const DagInit& d) {
920 CheckNumberOfArguments(d, 1);
921 toolDesc_.CmdLine = d.getArg(0);
924 void onInLanguage (const DagInit& d) {
925 CheckNumberOfArguments(d, 1);
926 Init* arg = d.getArg(0);
928 // Find out the argument's type.
929 if (typeid(*arg) == typeid(StringInit)) {
931 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
935 const ListInit& lst = InitPtrToList(arg);
936 StrVector& out = toolDesc_.InLanguage;
938 // Copy strings to the output vector.
939 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
941 out.push_back(InitPtrToString(*B));
944 // Remove duplicates.
945 std::sort(out.begin(), out.end());
946 StrVector::iterator newE = std::unique(out.begin(), out.end());
947 out.erase(newE, out.end());
951 void onJoin (const DagInit& d) {
952 CheckNumberOfArguments(d, 0);
956 void onOutLanguage (const DagInit& d) {
957 CheckNumberOfArguments(d, 1);
958 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
961 void onOutFileOption (const DagInit& d) {
962 CheckNumberOfArguments(d, 1);
963 toolDesc_.OutFileOption = InitPtrToString(d.getArg(0));
966 void onInFileOption (const DagInit& d) {
967 CheckNumberOfArguments(d, 1);
968 toolDesc_.InFileOption = InitPtrToString(d.getArg(0));
971 void onOutputSuffix (const DagInit& d) {
972 CheckNumberOfArguments(d, 1);
973 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
976 void onSink (const DagInit& d) {
977 CheckNumberOfArguments(d, 0);
981 void onWorksOnEmpty (const DagInit& d) {
982 toolDesc_.OnEmpty = d.getArg(0);
987 /// CollectToolDescriptions - Gather information about tool properties
988 /// from the parsed TableGen data (basically a wrapper for the
989 /// CollectToolProperties function object).
990 void CollectToolDescriptions (RecordVector::const_iterator B,
991 RecordVector::const_iterator E,
992 ToolDescriptions& ToolDescs)
994 // Iterate over a properties list of every Tool definition
996 const Record* T = *B;
997 // Throws an exception if the value does not exist.
998 ListInit* PropList = T->getValueAsListInit("properties");
1000 IntrusiveRefCntPtr<ToolDescription>
1001 ToolDesc(new ToolDescription(T->getName()));
1003 std::for_each(PropList->begin(), PropList->end(),
1004 CollectToolProperties(*ToolDesc));
1005 ToolDescs.push_back(ToolDesc);
1009 /// FillInEdgeVector - Merge all compilation graph definitions into
1010 /// one single edge list.
1011 void FillInEdgeVector(RecordVector::const_iterator B,
1012 RecordVector::const_iterator E, RecordVector& Out) {
1013 for (; B != E; ++B) {
1014 const ListInit* edges = (*B)->getValueAsListInit("edges");
1016 for (unsigned i = 0; i < edges->size(); ++i)
1017 Out.push_back(edges->getElementAsRecord(i));
1021 /// CalculatePriority - Calculate the priority of this plugin.
1022 int CalculatePriority(RecordVector::const_iterator B,
1023 RecordVector::const_iterator E) {
1027 priority = static_cast<int>((*B)->getValueAsInt("priority"));
1030 throw "More than one 'PluginPriority' instance found: "
1031 "most probably an error!";
1037 /// NotInGraph - Helper function object for FilterNotInGraph.
1040 const llvm::StringSet<>& ToolsInGraph_;
1043 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
1044 : ToolsInGraph_(ToolsInGraph)
1047 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
1048 return (ToolsInGraph_.count(x->Name) == 0);
1052 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
1053 /// mentioned in the compilation graph definition.
1054 void FilterNotInGraph (const RecordVector& EdgeVector,
1055 ToolDescriptions& ToolDescs) {
1057 // List all tools mentioned in the graph.
1058 llvm::StringSet<> ToolsInGraph;
1060 for (RecordVector::const_iterator B = EdgeVector.begin(),
1061 E = EdgeVector.end(); B != E; ++B) {
1063 const Record* Edge = *B;
1064 const std::string& NodeA = Edge->getValueAsString("a");
1065 const std::string& NodeB = Edge->getValueAsString("b");
1067 if (NodeA != "root")
1068 ToolsInGraph.insert(NodeA);
1069 ToolsInGraph.insert(NodeB);
1072 // Filter ToolPropertiesList.
1073 ToolDescriptions::iterator new_end =
1074 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
1075 NotInGraph(ToolsInGraph));
1076 ToolDescs.erase(new_end, ToolDescs.end());
1079 /// FillInToolToLang - Fills in two tables that map tool names to
1080 /// (input, output) languages. Helper function used by TypecheckGraph().
1081 void FillInToolToLang (const ToolDescriptions& ToolDescs,
1082 StringMap<StringSet<> >& ToolToInLang,
1083 StringMap<std::string>& ToolToOutLang) {
1084 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1085 E = ToolDescs.end(); B != E; ++B) {
1086 const ToolDescription& D = *(*B);
1087 for (StrVector::const_iterator B = D.InLanguage.begin(),
1088 E = D.InLanguage.end(); B != E; ++B)
1089 ToolToInLang[D.Name].insert(*B);
1090 ToolToOutLang[D.Name] = D.OutLanguage;
1094 /// TypecheckGraph - Check that names for output and input languages
1095 /// on all edges do match. This doesn't do much when the information
1096 /// about the whole graph is not available (i.e. when compiling most
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.FindList(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 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1832 /// implement EmitActionHandler. Emits code for
1833 /// handling the (forward) and (forward_as) option properties.
1834 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1835 unsigned IndentLevel,
1836 const std::string& NewName,
1838 const std::string& Name = NewName.empty()
1841 unsigned IndentLevel1 = IndentLevel + Indent1;
1844 case OptionType::Switch:
1845 O.indent(IndentLevel)
1846 << "vec.push_back(std::make_pair(" << D.GenVariableName()
1847 << ".getPosition(), \"" << Name << "\"));\n";
1849 case OptionType::Parameter:
1850 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1851 << D.GenVariableName()
1852 <<".getPosition(), \"" << Name;
1854 if (!D.isForwardNotSplit()) {
1856 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1857 << D.GenVariableName() << ".getPosition(), "
1858 << D.GenVariableName() << "));\n";
1861 O << "=\" + " << D.GenVariableName() << "));\n";
1864 case OptionType::Prefix:
1865 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
1866 << D.GenVariableName() << ".getPosition(), \""
1868 << D.GenVariableName() << "));\n";
1870 case OptionType::PrefixList:
1871 // TODO: remove duplication across PrefixList / ParameterList / SwitchList
1873 O.indent(IndentLevel)
1874 << "for (" << D.GenTypeDeclaration()
1875 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1876 O.indent(IndentLevel)
1877 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1878 O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName()
1879 << ".getPosition(B - " << D.GenVariableName()
1881 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1882 << Name << "\" + " << "*B));\n";
1883 O.indent(IndentLevel1) << "++B;\n";
1885 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1886 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1887 O.indent(IndentLevel1) << "++B;\n";
1890 O.indent(IndentLevel) << "}\n";
1892 case OptionType::ParameterList:
1893 O.indent(IndentLevel)
1894 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1895 << D.GenVariableName() << ".begin(),\n";
1896 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1897 << ".end() ; B != E;) {\n";
1898 O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName()
1899 << ".getPosition(B - " << D.GenVariableName()
1901 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1902 << Name << "\"));\n";
1904 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1905 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n";
1906 O.indent(IndentLevel1) << "++B;\n";
1909 O.indent(IndentLevel) << "}\n";
1911 case OptionType::SwitchList:
1912 O.indent(IndentLevel)
1913 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1914 << D.GenVariableName() << ".begin(),\n";
1915 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1916 << ".end() ; B != E;) {\n";
1917 O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName()
1918 << ".getPosition(B - " << D.GenVariableName()
1920 O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \""
1921 << Name << "\"));\n";
1922 O.indent(IndentLevel1) << "++B;\n";
1923 O.indent(IndentLevel) << "}\n";
1925 case OptionType::Alias:
1927 throw "Aliases are not allowed in tool option descriptions!";
1931 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1932 /// EmitPreprocessOptionsCallback.
1933 struct ActionHandlingCallbackBase
1936 void onErrorDag(const DagInit& d,
1937 unsigned IndentLevel, raw_ostream& O) const
1939 O.indent(IndentLevel)
1940 << "throw std::runtime_error(\"" <<
1941 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1946 void onWarningDag(const DagInit& d,
1947 unsigned IndentLevel, raw_ostream& O) const
1949 CheckNumberOfArguments(d, 1);
1950 O.indent(IndentLevel) << "llvm::errs() << \""
1951 << InitPtrToString(d.getArg(0)) << "\";\n";
1956 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1957 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1959 class EmitActionHandlersCallback;
1961 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1962 (const DagInit&, unsigned, raw_ostream&) const;
1964 class EmitActionHandlersCallback :
1965 public ActionHandlingCallbackBase,
1966 public HandlerTable<EmitActionHandlersCallbackHandler>
1968 typedef EmitActionHandlersCallbackHandler Handler;
1970 const OptionDescriptions& OptDescs;
1972 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1973 /// onAppendCmd and onOutputSuffix.
1974 void EmitHookInvocation(const std::string& Str,
1975 const char* BlockOpen, const char* BlockClose,
1976 unsigned IndentLevel, raw_ostream& O) const
1979 TokenizeCmdLine(Str, Out);
1981 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1983 const std::string& cmd = *B;
1985 O.indent(IndentLevel) << BlockOpen;
1987 if (cmd.at(0) == '$')
1988 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1990 O << '"' << cmd << '"';
1996 void onAppendCmd (const DagInit& Dag,
1997 unsigned IndentLevel, raw_ostream& O) const
1999 CheckNumberOfArguments(Dag, 1);
2000 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2001 "vec.push_back(std::make_pair(65536, ", "));\n",
2005 void onForward (const DagInit& Dag,
2006 unsigned IndentLevel, raw_ostream& O) const
2008 CheckNumberOfArguments(Dag, 1);
2009 const std::string& Name = InitPtrToString(Dag.getArg(0));
2010 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2011 IndentLevel, "", O);
2014 void onForwardAs (const DagInit& Dag,
2015 unsigned IndentLevel, raw_ostream& O) const
2017 CheckNumberOfArguments(Dag, 2);
2018 const std::string& Name = InitPtrToString(Dag.getArg(0));
2019 const std::string& NewName = InitPtrToString(Dag.getArg(1));
2020 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
2021 IndentLevel, NewName, O);
2024 void onForwardValue (const DagInit& Dag,
2025 unsigned IndentLevel, raw_ostream& O) const
2027 CheckNumberOfArguments(Dag, 1);
2028 const std::string& Name = InitPtrToString(Dag.getArg(0));
2029 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
2031 if (D.isSwitchList()) {
2032 throw std::runtime_error
2033 ("forward_value is not allowed with switch_list");
2036 if (D.isParameter()) {
2037 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2038 << D.GenVariableName() << ".getPosition(), "
2039 << D.GenVariableName() << "));\n";
2042 O.indent(IndentLevel) << "for (" << D.GenTypeDeclaration()
2043 << "::iterator B = " << D.GenVariableName()
2045 O.indent(IndentLevel + Indent1) << " E = " << D.GenVariableName()
2046 << ".end(); B != E; ++B)\n";
2047 O.indent(IndentLevel) << "{\n";
2048 O.indent(IndentLevel + Indent1)
2049 << "unsigned pos = " << D.GenVariableName()
2050 << ".getPosition(B - " << D.GenVariableName()
2052 O.indent(IndentLevel + Indent1)
2053 << "vec.push_back(std::make_pair(pos, *B));\n";
2054 O.indent(IndentLevel) << "}\n";
2058 void onForwardTransformedValue (const DagInit& Dag,
2059 unsigned IndentLevel, raw_ostream& O) const
2061 CheckNumberOfArguments(Dag, 2);
2062 const std::string& Name = InitPtrToString(Dag.getArg(0));
2063 const std::string& Hook = InitPtrToString(Dag.getArg(1));
2064 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
2066 O.indent(IndentLevel) << "vec.push_back(std::make_pair("
2067 << D.GenVariableName() << ".getPosition("
2068 << (D.isList() ? "0" : "") << "), "
2069 << "hooks::" << Hook << "(" << D.GenVariableName()
2070 << (D.isParameter() ? ".c_str()" : "") << ")));\n";
2073 void onNoOutFile (const DagInit& Dag,
2074 unsigned IndentLevel, raw_ostream& O) const
2076 CheckNumberOfArguments(Dag, 0);
2077 O.indent(IndentLevel) << "no_out_file = true;\n";
2080 void onOutputSuffix (const DagInit& Dag,
2081 unsigned IndentLevel, raw_ostream& O) const
2083 CheckNumberOfArguments(Dag, 1);
2084 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
2085 "output_suffix = ", ";\n", IndentLevel, O);
2088 void onStopCompilation (const DagInit& Dag,
2089 unsigned IndentLevel, raw_ostream& O) const
2091 O.indent(IndentLevel) << "stop_compilation = true;\n";
2095 void onUnpackValues (const DagInit& Dag,
2096 unsigned IndentLevel, raw_ostream& O) const
2098 throw "'unpack_values' is deprecated. "
2099 "Use 'comma_separated' + 'forward_value' instead!";
2104 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
2107 if (!staticMembersInitialized_) {
2108 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
2109 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
2110 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
2111 AddHandler("forward", &EmitActionHandlersCallback::onForward);
2112 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
2113 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
2114 AddHandler("forward_transformed_value",
2115 &EmitActionHandlersCallback::onForwardTransformedValue);
2116 AddHandler("no_out_file",
2117 &EmitActionHandlersCallback::onNoOutFile);
2118 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
2119 AddHandler("stop_compilation",
2120 &EmitActionHandlersCallback::onStopCompilation);
2121 AddHandler("unpack_values",
2122 &EmitActionHandlersCallback::onUnpackValues);
2125 staticMembersInitialized_ = true;
2129 void operator()(const Init* I,
2130 unsigned IndentLevel, raw_ostream& O) const
2132 InvokeDagInitHandler(this, I, IndentLevel, O);
2136 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2137 bool IsJoin, raw_ostream& O)
2140 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2142 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
2144 O.indent(Indent2) << "bool HasChildren,\n";
2145 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2146 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2147 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2148 O.indent(Indent1) << "{\n";
2149 O.indent(Indent2) << "std::string cmd;\n";
2150 O.indent(Indent2) << "std::string out_file;\n";
2151 O.indent(Indent2) << "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) << "const char* output_suffix = \""
2155 << D.OutputSuffix << "\";\n";
2158 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2159 // Tool::GenerateAction() method.
2160 void EmitGenerateActionMethod (const ToolDescription& D,
2161 const OptionDescriptions& OptDescs,
2162 bool IsJoin, raw_ostream& O) {
2164 EmitGenerateActionMethodHeader(D, IsJoin, O);
2167 throw "Tool " + D.Name + " has no cmd_line property!";
2169 // Process the 'command' property.
2171 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2174 // Process the 'actions' list of this tool.
2176 EmitCaseConstructHandler(D.Actions, Indent2,
2177 EmitActionHandlersCallback(OptDescs),
2178 false, OptDescs, O);
2182 if (!D.InFileOption.empty()) {
2184 << "vec.push_back(std::make_pair(InputFilenames.getPosition(0), \""
2185 << D.InFileOption << "\");\n";
2190 << "for (PathVector::const_iterator B = inFiles.begin(),\n";
2191 O.indent(Indent3) << "E = inFiles.end(); B != E; ++B)\n";
2192 O.indent(Indent2) << "{\n";
2193 O.indent(Indent3) << "vec.push_back(std::make_pair("
2194 << "InputFilenames.getPosition(B - inFiles.begin()), "
2196 O.indent(Indent2) << "}\n";
2199 O.indent(Indent2) << "vec.push_back(std::make_pair("
2200 << "InputFilenames.getPosition(0), inFile.str()));\n";
2204 O.indent(Indent2) << "if (!no_out_file) {\n";
2205 if (!D.OutFileOption.empty())
2206 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, \""
2207 << D.OutFileOption << "\"));\n";
2209 O.indent(Indent3) << "out_file = this->OutFilename("
2210 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2211 O.indent(Indent4) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2212 O.indent(Indent3) << "vec.push_back(std::make_pair(65536, out_file));\n";
2214 O.indent(Indent2) << "}\n\n";
2216 // Handle the Sink property.
2218 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2219 O.indent(Indent3) << "for (cl::list<std::string>::iterator B = "
2220 << SinkOptionName << ".begin(), E = " << SinkOptionName
2221 << ".end(); B != E; ++B)\n";
2222 O.indent(Indent4) << "vec.push_back(std::make_pair(" << SinkOptionName
2223 << ".getPosition(B - " << SinkOptionName
2224 << ".begin()), *B));\n";
2225 O.indent(Indent2) << "}\n";
2228 O.indent(Indent2) << "return Action(cmd, this->SortArgs(vec), "
2229 << "stop_compilation, out_file);\n";
2230 O.indent(Indent1) << "}\n\n";
2233 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2234 /// a given Tool class.
2235 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2236 const OptionDescriptions& OptDescs,
2238 if (!ToolDesc.isJoin()) {
2239 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2240 O.indent(Indent2) << "bool HasChildren,\n";
2241 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2242 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2243 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2244 O.indent(Indent1) << "{\n";
2245 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2246 << " is not a Join tool!\");\n";
2247 O.indent(Indent1) << "}\n\n";
2250 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2253 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2256 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2257 /// methods for a given Tool class.
2258 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2259 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2260 O.indent(Indent2) << "return InputLanguages_;\n";
2261 O.indent(Indent1) << "}\n\n";
2263 if (D.OutLanguage.empty())
2264 throw "Tool " + D.Name + " has no 'out_language' property!";
2266 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2267 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2268 O.indent(Indent1) << "}\n\n";
2271 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2272 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2273 O.indent(Indent1) << "const char* Name() const {\n";
2274 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2275 O.indent(Indent1) << "}\n\n";
2278 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2280 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2281 O.indent(Indent1) << "bool IsJoin() const {\n";
2283 O.indent(Indent2) << "return true;\n";
2285 O.indent(Indent2) << "return false;\n";
2286 O.indent(Indent1) << "}\n\n";
2289 /// EmitWorksOnEmptyCallback - Callback used by EmitWorksOnEmptyMethod in
2290 /// conjunction with EmitCaseConstructHandler.
2291 void EmitWorksOnEmptyCallback (const Init* Value,
2292 unsigned IndentLevel, raw_ostream& O) {
2293 CheckBooleanConstant(Value);
2294 O.indent(IndentLevel) << "return " << Value->getAsString() << ";\n";
2297 /// EmitWorksOnEmptyMethod - Emit the WorksOnEmpty() method for a given Tool
2299 void EmitWorksOnEmptyMethod (const ToolDescription& D,
2300 const OptionDescriptions& OptDescs,
2303 O.indent(Indent1) << "bool WorksOnEmpty() const {\n";
2305 O.indent(Indent2) << "return false;\n";
2307 EmitCaseConstructHandler(D.OnEmpty, Indent2, EmitWorksOnEmptyCallback,
2308 /*EmitElseIf = */ true, OptDescs, O);
2309 O.indent(Indent1) << "}\n\n";
2312 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2313 /// given Tool class.
2314 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2315 if (D.InLanguage.empty())
2316 throw "Tool " + D.Name + " has no 'in_language' property!";
2318 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2319 for (StrVector::const_iterator B = D.InLanguage.begin(),
2320 E = D.InLanguage.end(); B != E; ++B)
2321 O << '\"' << *B << "\", ";
2325 /// EmitToolClassDefinition - Emit a Tool class definition.
2326 void EmitToolClassDefinition (const ToolDescription& D,
2327 const OptionDescriptions& OptDescs,
2329 if (D.Name == "root")
2333 O << "class " << D.Name << " : public ";
2339 O << " {\nprivate:\n";
2340 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2343 EmitNameMethod(D, O);
2344 EmitInOutLanguageMethods(D, O);
2345 EmitIsJoinMethod(D, O);
2346 EmitWorksOnEmptyMethod(D, OptDescs, O);
2347 EmitGenerateActionMethods(D, OptDescs, O);
2349 // Close class definition
2352 EmitStaticMemberDefinitions(D, O);
2356 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2357 /// and emit registration code.
2358 void EmitOptionDefinitions (const OptionDescriptions& descs,
2359 bool HasSink, bool HasExterns,
2362 std::vector<OptionDescription> Aliases;
2364 // Emit static cl::Option variables.
2365 for (OptionDescriptions::const_iterator B = descs.begin(),
2366 E = descs.end(); B!=E; ++B) {
2367 const OptionDescription& val = B->second;
2369 if (val.Type == OptionType::Alias) {
2370 Aliases.push_back(val);
2377 O << val.GenTypeDeclaration() << ' '
2378 << val.GenVariableName();
2380 if (val.isExtern()) {
2385 O << "(\"" << val.Name << "\"\n";
2387 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2388 O << ", cl::Prefix";
2390 if (val.isRequired()) {
2391 if (val.isList() && !val.isMultiVal())
2392 O << ", cl::OneOrMore";
2394 O << ", cl::Required";
2397 if (val.isOptional())
2398 O << ", cl::Optional";
2400 if (val.isOneOrMore())
2401 O << ", cl::OneOrMore";
2403 if (val.isZeroOrMore())
2404 O << ", cl::ZeroOrMore";
2406 if (val.isReallyHidden())
2407 O << ", cl::ReallyHidden";
2408 else if (val.isHidden())
2409 O << ", cl::Hidden";
2411 if (val.isCommaSeparated())
2412 O << ", cl::CommaSeparated";
2414 if (val.MultiVal > 1)
2415 O << ", cl::multi_val(" << val.MultiVal << ')';
2418 const std::string& str = val.InitVal->getAsString();
2419 O << ", cl::init(" << str << ')';
2422 if (!val.Help.empty())
2423 O << ", cl::desc(\"" << val.Help << "\")";
2428 // Emit the aliases (they should go after all the 'proper' options).
2429 for (std::vector<OptionDescription>::const_iterator
2430 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2431 const OptionDescription& val = *B;
2433 O << val.GenTypeDeclaration() << ' '
2434 << val.GenVariableName()
2435 << "(\"" << val.Name << '\"';
2437 const OptionDescription& D = descs.FindOption(val.Help);
2438 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2440 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2443 // Emit the sink option.
2445 O << (HasExterns ? "extern cl" : "cl")
2446 << "::list<std::string> " << SinkOptionName
2447 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2452 /// EmitPreprocessOptionsCallback - Helper function passed to
2453 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2455 class EmitPreprocessOptionsCallback;
2458 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2459 (const DagInit&, unsigned, raw_ostream&) const;
2461 class EmitPreprocessOptionsCallback :
2462 public ActionHandlingCallbackBase,
2463 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2465 typedef EmitPreprocessOptionsCallbackHandler Handler;
2467 (EmitPreprocessOptionsCallback::* HandlerImpl)
2468 (const Init*, unsigned, raw_ostream&) const;
2470 const OptionDescriptions& OptDescs_;
2472 void onListOrDag(const DagInit& d, HandlerImpl h,
2473 unsigned IndentLevel, raw_ostream& O) const
2475 CheckNumberOfArguments(d, 1);
2476 const Init* I = d.getArg(0);
2478 // If I is a list, apply h to each element.
2479 if (typeid(*I) == typeid(ListInit)) {
2480 const ListInit& L = *static_cast<const ListInit*>(I);
2481 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2482 ((this)->*(h))(*B, IndentLevel, O);
2484 // Otherwise, apply h to I.
2486 ((this)->*(h))(I, IndentLevel, O);
2490 void onUnsetOptionImpl(const Init* I,
2491 unsigned IndentLevel, raw_ostream& O) const
2493 const std::string& OptName = InitPtrToString(I);
2494 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2496 if (OptDesc.isSwitch()) {
2497 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2499 else if (OptDesc.isParameter()) {
2500 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2502 else if (OptDesc.isList()) {
2503 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2506 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2510 void onUnsetOption(const DagInit& d,
2511 unsigned IndentLevel, raw_ostream& O) const
2513 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2517 void onSetOptionImpl(const DagInit& d,
2518 unsigned IndentLevel, raw_ostream& O) const {
2519 CheckNumberOfArguments(d, 2);
2520 const std::string& OptName = InitPtrToString(d.getArg(0));
2521 const Init* Value = d.getArg(1);
2522 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2524 if (OptDesc.isList()) {
2525 const ListInit& List = InitPtrToList(Value);
2527 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2528 for (ListInit::const_iterator B = List.begin(), E = List.end();
2530 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".push_back(\""
2531 << InitPtrToString(*B) << "\");\n";
2534 else if (OptDesc.isSwitch()) {
2535 CheckBooleanConstant(Value);
2536 O.indent(IndentLevel) << OptDesc.GenVariableName()
2537 << " = " << Value->getAsString() << ";\n";
2539 else if (OptDesc.isParameter()) {
2540 const std::string& Str = InitPtrToString(Value);
2541 O.indent(IndentLevel) << OptDesc.GenVariableName()
2542 << " = \"" << Str << "\";\n";
2545 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2549 void onSetSwitch(const Init* I,
2550 unsigned IndentLevel, raw_ostream& O) const {
2551 const std::string& OptName = InitPtrToString(I);
2552 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2554 if (OptDesc.isSwitch())
2555 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2557 throw "set_option: -" + OptName + " is not a switch option!";
2560 void onSetOption(const DagInit& d,
2561 unsigned IndentLevel, raw_ostream& O) const
2563 CheckNumberOfArguments(d, 1);
2565 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2566 // boolean, a string or a string list.
2567 if (d.getNumArgs() > 1)
2568 this->onSetOptionImpl(d, IndentLevel, O);
2569 // One argument: (set_option "switch")
2570 // or (set_option ["switch1", "switch2", ...])
2572 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2578 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2579 : OptDescs_(OptDescs)
2581 if (!staticMembersInitialized_) {
2582 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2583 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2584 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2585 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2587 staticMembersInitialized_ = true;
2591 void operator()(const Init* I,
2592 unsigned IndentLevel, raw_ostream& O) const
2594 InvokeDagInitHandler(this, I, IndentLevel, O);
2599 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2600 void EmitPreprocessOptions (const RecordKeeper& Records,
2601 const OptionDescriptions& OptDecs, raw_ostream& O)
2603 O << "void PreprocessOptionsLocal() {\n";
2605 const RecordVector& OptionPreprocessors =
2606 Records.getAllDerivedDefinitions("OptionPreprocessor");
2608 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2609 E = OptionPreprocessors.end(); B!=E; ++B) {
2610 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2611 EmitCaseConstructHandler(Case, Indent1,
2612 EmitPreprocessOptionsCallback(OptDecs),
2619 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2620 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2622 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2624 // Get the relevant field out of RecordKeeper
2625 const Record* LangMapRecord = Records.getDef("LanguageMap");
2627 // It is allowed for a plugin to have no language map.
2628 if (LangMapRecord) {
2630 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2631 if (!LangsToSuffixesList)
2632 throw "Error in the language map definition!";
2634 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2635 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2637 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2638 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2640 for (unsigned i = 0; i < Suffixes->size(); ++i)
2641 O.indent(Indent1) << "langMap[\""
2642 << InitPtrToString(Suffixes->getElement(i))
2643 << "\"] = \"" << Lang << "\";\n";
2650 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2651 /// by EmitEdgeClass().
2652 void IncDecWeight (const Init* i, unsigned IndentLevel,
2654 const DagInit& d = InitPtrToDag(i);
2655 const std::string& OpName = GetOperatorName(d);
2657 if (OpName == "inc_weight") {
2658 O.indent(IndentLevel) << "ret += ";
2660 else if (OpName == "dec_weight") {
2661 O.indent(IndentLevel) << "ret -= ";
2663 else if (OpName == "error") {
2664 CheckNumberOfArguments(d, 1);
2665 O.indent(IndentLevel) << "throw std::runtime_error(\""
2666 << InitPtrToString(d.getArg(0))
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 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2696 O.indent(Indent2) << "unsigned ret = 0;\n";
2698 // Handle the 'case' construct.
2699 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2701 O.indent(Indent2) << "return ret;\n";
2702 O.indent(Indent1) << "}\n\n};\n\n";
2705 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2706 void EmitEdgeClasses (const RecordVector& EdgeVector,
2707 const OptionDescriptions& OptDescs,
2710 for (RecordVector::const_iterator B = EdgeVector.begin(),
2711 E = EdgeVector.end(); B != E; ++B) {
2712 const Record* Edge = *B;
2713 const std::string& NodeB = Edge->getValueAsString("b");
2714 DagInit& Weight = *Edge->getValueAsDag("weight");
2716 if (!IsDagEmpty(Weight))
2717 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2722 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2724 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2725 const ToolDescriptions& ToolDescs,
2728 O << "void PopulateCompilationGraphLocal(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) << "G.insertEdge(\"" << NodeA << "\", ";
2748 if (IsDagEmpty(Weight))
2749 O << "new SimpleEdge(\"" << NodeB << "\")";
2751 O << "new Edge" << i << "()";
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 = OptDescs_.FindOption(OptName);
2802 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2803 : HookInfo::ArgHook);
2805 else if (Name == "append_cmd" || Name == "output_suffix") {
2806 CheckNumberOfArguments(Dag, 1);
2807 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2811 void onCmdLine(const std::string& Cmd) {
2813 TokenizeCmdLine(Cmd, cmds);
2815 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2817 const std::string& cmd = *B;
2819 if (cmd == "$CALL") {
2820 unsigned NumArgs = 0;
2821 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2822 const std::string& HookName = *B;
2824 if (HookName.at(0) == ')')
2825 throw "$CALL invoked with no arguments!";
2827 while (++B != E && B->at(0) != ')') {
2831 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2833 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2834 H->second.Type != HookInfo::ArgHook)
2835 throw "Overloading of hooks is not allowed. Overloaded hook: "
2838 HookNames_[HookName] = HookInfo(NumArgs);
2843 void operator()(const Init* Arg) {
2845 // We're invoked on an action (either a dag or a dag list).
2846 if (typeid(*Arg) == typeid(DagInit)) {
2847 const DagInit& Dag = InitPtrToDag(Arg);
2848 this->onAction(Dag);
2851 else if (typeid(*Arg) == typeid(ListInit)) {
2852 const ListInit& List = InitPtrToList(Arg);
2853 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2855 const DagInit& Dag = InitPtrToDag(*B);
2856 this->onAction(Dag);
2861 // We're invoked on a command line.
2862 this->onCmdLine(InitPtrToString(Arg));
2865 void operator()(const DagInit* Test, unsigned, bool) {
2866 this->operator()(Test);
2868 void operator()(const Init* Statement, unsigned) {
2869 this->operator()(Statement);
2873 /// FillInHookNames - Actually extract the hook names from all command
2874 /// line strings. Helper function used by EmitHookDeclarations().
2875 void FillInHookNames(const ToolDescriptions& ToolDescs,
2876 const OptionDescriptions& OptDescs,
2877 HookInfoMap& HookNames)
2879 // For all tool descriptions:
2880 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2881 E = ToolDescs.end(); B != E; ++B) {
2882 const ToolDescription& D = *(*B);
2884 // Look for 'forward_transformed_value' in 'actions'.
2886 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2888 // Look for hook invocations in 'cmd_line'.
2891 if (dynamic_cast<StringInit*>(D.CmdLine))
2892 // This is a string.
2893 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2895 // This is a 'case' construct.
2896 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2900 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2901 /// property records and emit hook function declaration for each
2902 /// instance of $CALL(HookName).
2903 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2904 const OptionDescriptions& OptDescs, raw_ostream& O) {
2905 HookInfoMap HookNames;
2907 FillInHookNames(ToolDescs, OptDescs, HookNames);
2908 if (HookNames.empty())
2911 O << "namespace hooks {\n";
2912 for (HookInfoMap::const_iterator B = HookNames.begin(),
2913 E = HookNames.end(); B != E; ++B) {
2914 const char* HookName = B->first();
2915 const HookInfo& Info = B->second;
2917 O.indent(Indent1) << "std::string " << HookName << "(";
2919 if (Info.Type == HookInfo::ArgHook) {
2920 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2921 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2925 O << "const std::vector<std::string>& Arg";
2933 /// EmitRegisterPlugin - Emit code to register this plugin.
2934 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2935 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2936 O.indent(Indent1) << "int Priority() const { return "
2937 << Priority << "; }\n\n";
2938 O.indent(Indent1) << "void PreprocessOptions() const\n";
2939 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2940 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2941 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2943 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2944 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2946 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2949 /// EmitIncludes - Emit necessary #include directives and some
2950 /// additional declarations.
2951 void EmitIncludes(raw_ostream& O) {
2952 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2953 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2954 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2955 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2956 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2958 << "#include \"llvm/Support/CommandLine.h\"\n"
2959 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2961 << "#include <algorithm>\n"
2962 << "#include <cstdlib>\n"
2963 << "#include <iterator>\n"
2964 << "#include <stdexcept>\n\n"
2966 << "using namespace llvm;\n"
2967 << "using namespace llvmc;\n\n"
2969 << "extern cl::opt<std::string> OutputFilename;\n\n"
2971 << "inline const char* checkCString(const char* s)\n"
2972 << "{ return s == NULL ? \"\" : s; }\n\n";
2976 /// PluginData - Holds all information about a plugin.
2978 OptionDescriptions OptDescs;
2981 ToolDescriptions ToolDescs;
2986 /// HasSink - Go through the list of tool descriptions and check if
2987 /// there are any with the 'sink' property set.
2988 bool HasSink(const ToolDescriptions& ToolDescs) {
2989 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2990 E = ToolDescs.end(); B != E; ++B)
2997 /// HasExterns - Go through the list of option descriptions and check
2998 /// if there are any external options.
2999 bool HasExterns(const OptionDescriptions& OptDescs) {
3000 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
3001 E = OptDescs.end(); B != E; ++B)
3002 if (B->second.isExtern())
3008 /// CollectPluginData - Collect tool and option properties,
3009 /// compilation graph edges and plugin priority from the parse tree.
3010 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
3011 // Collect option properties.
3012 const RecordVector& OptionLists =
3013 Records.getAllDerivedDefinitions("OptionList");
3014 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
3017 // Collect tool properties.
3018 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
3019 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
3020 Data.HasSink = HasSink(Data.ToolDescs);
3021 Data.HasExterns = HasExterns(Data.OptDescs);
3023 // Collect compilation graph edges.
3024 const RecordVector& CompilationGraphs =
3025 Records.getAllDerivedDefinitions("CompilationGraph");
3026 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
3029 // Calculate the priority of this plugin.
3030 const RecordVector& Priorities =
3031 Records.getAllDerivedDefinitions("PluginPriority");
3032 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
3035 /// CheckPluginData - Perform some sanity checks on the collected data.
3036 void CheckPluginData(PluginData& Data) {
3037 // Filter out all tools not mentioned in the compilation graph.
3038 FilterNotInGraph(Data.Edges, Data.ToolDescs);
3040 // Typecheck the compilation graph.
3041 TypecheckGraph(Data.Edges, Data.ToolDescs);
3043 // Check that there are no options without side effects (specified
3044 // only in the OptionList).
3045 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
3048 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
3049 // Emit file header.
3052 // Emit global option registration code.
3053 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
3055 // Emit hook declarations.
3056 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
3058 O << "namespace {\n\n";
3060 // Emit PreprocessOptionsLocal() function.
3061 EmitPreprocessOptions(Records, Data.OptDescs, O);
3063 // Emit PopulateLanguageMapLocal() function
3064 // (language map maps from file extensions to language names).
3065 EmitPopulateLanguageMap(Records, O);
3067 // Emit Tool classes.
3068 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
3069 E = Data.ToolDescs.end(); B!=E; ++B)
3070 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
3072 // Emit Edge# classes.
3073 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
3075 // Emit PopulateCompilationGraphLocal() function.
3076 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
3078 // Emit code for plugin registration.
3079 EmitRegisterPlugin(Data.Priority, O);
3081 O << "} // End anonymous namespace.\n\n";
3083 // Force linkage magic.
3084 O << "namespace llvmc {\n";
3085 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
3092 // End of anonymous namespace
3095 /// run - The back-end entry point.
3096 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
3100 CollectPluginData(Records, Data);
3101 CheckPluginData(Data);
3103 this->EmitSourceFileHeader("LLVMC Configuration Library", O);
3104 EmitPluginCode(Data, O);
3106 } catch (std::exception& Error) {
3107 throw Error.what() + std::string(" - usually this means a syntax error.");