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;
47 // Default help string.
48 const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50 // Name for the "sink" option.
51 const char * const SinkOptionName = "AutoGeneratedSinkOption";
53 //===----------------------------------------------------------------------===//
56 /// Id - An 'identity' function object.
59 void operator()(const T0&) const {
61 template<typename T0, typename T1>
62 void operator()(const T0&, const T1&) const {
64 template<typename T0, typename T1, typename T2>
65 void operator()(const T0&, const T1&, const T2&) const {
69 int InitPtrToInt(const Init* ptr) {
70 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
71 return val.getValue();
74 const std::string& InitPtrToString(const Init* ptr) {
75 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
76 return val.getValue();
79 const ListInit& InitPtrToList(const Init* ptr) {
80 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
84 const DagInit& InitPtrToDag(const Init* ptr) {
85 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
89 const std::string GetOperatorName(const DagInit& D) {
90 return D.getOperator()->getAsString();
93 /// CheckBooleanConstant - Check that the provided value is a boolean constant.
94 void CheckBooleanConstant(const Init* I) {
95 const DefInit& val = dynamic_cast<const DefInit&>(*I);
96 const std::string& str = val.getAsString();
98 if (str != "true" && str != "false") {
99 throw "Incorrect boolean value: '" + str +
100 "': must be either 'true' or 'false'";
104 // CheckNumberOfArguments - Ensure that the number of args in d is
105 // greater than or equal to min_arguments, otherwise throw an exception.
106 void CheckNumberOfArguments (const DagInit& d, unsigned minArgs) {
107 if (d.getNumArgs() < minArgs)
108 throw GetOperatorName(d) + ": too few arguments!";
111 // IsDagEmpty - is this DAG marked with an empty marker?
112 bool IsDagEmpty (const DagInit& d) {
113 return GetOperatorName(d) == "empty_dag_marker";
116 // EscapeVariableName - Escape commas and other symbols not allowed
117 // in the C++ variable names. Makes it possible to use options named
118 // like "Wa," (useful for prefix options).
119 std::string EscapeVariableName (const std::string& Var) {
121 for (unsigned i = 0; i != Var.size(); ++i) {
122 char cur_char = Var[i];
123 if (cur_char == ',') {
126 else if (cur_char == '+') {
129 else if (cur_char == '-') {
133 ret.push_back(cur_char);
139 /// EscapeQuotes - Replace '"' with '\"'.
140 std::string EscapeQuotes (const std::string& Var) {
142 for (unsigned i = 0; i != Var.size(); ++i) {
143 char cur_char = Var[i];
144 if (cur_char == '"') {
148 ret.push_back(cur_char);
154 /// OneOf - Does the input string contain this character?
155 bool OneOf(const char* lst, char c) {
163 template <class I, class S>
164 void CheckedIncrement(I& P, I E, S ErrorString) {
170 // apply is needed because C++'s syntax doesn't let us construct a function
171 // object and call it in the same statement.
172 template<typename F, typename T0>
173 void apply(F Fun, T0& Arg0) {
177 template<typename F, typename T0, typename T1>
178 void apply(F Fun, T0& Arg0, T1& Arg1) {
179 return Fun(Arg0, Arg1);
182 //===----------------------------------------------------------------------===//
183 /// Back-end specific code
186 /// OptionType - One of six different option types. See the
187 /// documentation for detailed description of differences.
188 namespace OptionType {
190 enum OptionType { Alias, Switch, Parameter, ParameterList,
193 bool IsAlias(OptionType t) {
197 bool IsList (OptionType t) {
198 return (t == ParameterList || t == PrefixList);
201 bool IsSwitch (OptionType t) {
202 return (t == Switch);
205 bool IsParameter (OptionType t) {
206 return (t == Parameter || t == Prefix);
211 OptionType::OptionType stringToOptionType(const std::string& T) {
212 if (T == "alias_option")
213 return OptionType::Alias;
214 else if (T == "switch_option")
215 return OptionType::Switch;
216 else if (T == "parameter_option")
217 return OptionType::Parameter;
218 else if (T == "parameter_list_option")
219 return OptionType::ParameterList;
220 else if (T == "prefix_option")
221 return OptionType::Prefix;
222 else if (T == "prefix_list_option")
223 return OptionType::PrefixList;
225 throw "Unknown option type: " + T + '!';
228 namespace OptionDescriptionFlags {
229 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
230 ReallyHidden = 0x4, Extern = 0x8,
231 OneOrMore = 0x10, Optional = 0x20,
232 CommaSeparated = 0x40, ForwardNotSplit = 0x80 };
235 /// OptionDescription - Represents data contained in a single
236 /// OptionList entry.
237 struct OptionDescription {
238 OptionType::OptionType Type;
245 OptionDescription(OptionType::OptionType t = OptionType::Switch,
246 const std::string& n = "",
247 const std::string& h = DefaultHelpString)
248 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
251 /// GenTypeDeclaration - Returns the C++ variable type of this
253 const char* GenTypeDeclaration() const;
255 /// GenVariableName - Returns the variable name used in the
256 /// generated C++ code.
257 std::string GenVariableName() const;
259 /// Merge - Merge two option descriptions.
260 void Merge (const OptionDescription& other);
262 // Misc convenient getters/setters.
264 bool isAlias() const;
266 bool isMultiVal() const;
268 bool isCommaSeparated() const;
269 void setCommaSeparated();
271 bool isExtern() const;
274 bool isForwardNotSplit() const;
275 void setForwardNotSplit();
277 bool isRequired() const;
280 bool isOneOrMore() const;
283 bool isOptional() const;
286 bool isHidden() const;
289 bool isReallyHidden() const;
290 void setReallyHidden();
292 bool isSwitch() const
293 { return OptionType::IsSwitch(this->Type); }
295 bool isParameter() const
296 { return OptionType::IsParameter(this->Type); }
299 { return OptionType::IsList(this->Type); }
303 void OptionDescription::Merge (const OptionDescription& other)
305 if (other.Type != Type)
306 throw "Conflicting definitions for the option " + Name + "!";
308 if (Help == other.Help || Help == DefaultHelpString)
310 else if (other.Help != DefaultHelpString) {
311 llvm::errs() << "Warning: several different help strings"
312 " defined for option " + Name + "\n";
315 Flags |= other.Flags;
318 bool OptionDescription::isAlias() const {
319 return OptionType::IsAlias(this->Type);
322 bool OptionDescription::isMultiVal() const {
326 bool OptionDescription::isCommaSeparated() const {
327 return Flags & OptionDescriptionFlags::CommaSeparated;
329 void OptionDescription::setCommaSeparated() {
330 Flags |= OptionDescriptionFlags::CommaSeparated;
333 bool OptionDescription::isForwardNotSplit() const {
334 return Flags & OptionDescriptionFlags::ForwardNotSplit;
336 void OptionDescription::setForwardNotSplit() {
337 Flags |= OptionDescriptionFlags::ForwardNotSplit;
340 bool OptionDescription::isExtern() const {
341 return Flags & OptionDescriptionFlags::Extern;
343 void OptionDescription::setExtern() {
344 Flags |= OptionDescriptionFlags::Extern;
347 bool OptionDescription::isRequired() const {
348 return Flags & OptionDescriptionFlags::Required;
350 void OptionDescription::setRequired() {
351 Flags |= OptionDescriptionFlags::Required;
354 bool OptionDescription::isOneOrMore() const {
355 return Flags & OptionDescriptionFlags::OneOrMore;
357 void OptionDescription::setOneOrMore() {
358 Flags |= OptionDescriptionFlags::OneOrMore;
361 bool OptionDescription::isOptional() const {
362 return Flags & OptionDescriptionFlags::Optional;
364 void OptionDescription::setOptional() {
365 Flags |= OptionDescriptionFlags::Optional;
368 bool OptionDescription::isHidden() const {
369 return Flags & OptionDescriptionFlags::Hidden;
371 void OptionDescription::setHidden() {
372 Flags |= OptionDescriptionFlags::Hidden;
375 bool OptionDescription::isReallyHidden() const {
376 return Flags & OptionDescriptionFlags::ReallyHidden;
378 void OptionDescription::setReallyHidden() {
379 Flags |= OptionDescriptionFlags::ReallyHidden;
382 const char* OptionDescription::GenTypeDeclaration() const {
384 case OptionType::Alias:
386 case OptionType::PrefixList:
387 case OptionType::ParameterList:
388 return "cl::list<std::string>";
389 case OptionType::Switch:
390 return "cl::opt<bool>";
391 case OptionType::Parameter:
392 case OptionType::Prefix:
394 return "cl::opt<std::string>";
398 std::string OptionDescription::GenVariableName() const {
399 const std::string& EscapedName = EscapeVariableName(Name);
401 case OptionType::Alias:
402 return "AutoGeneratedAlias_" + EscapedName;
403 case OptionType::PrefixList:
404 case OptionType::ParameterList:
405 return "AutoGeneratedList_" + EscapedName;
406 case OptionType::Switch:
407 return "AutoGeneratedSwitch_" + EscapedName;
408 case OptionType::Prefix:
409 case OptionType::Parameter:
411 return "AutoGeneratedParameter_" + EscapedName;
415 /// OptionDescriptions - An OptionDescription array plus some helper
417 class OptionDescriptions {
418 typedef StringMap<OptionDescription> container_type;
420 /// Descriptions - A list of OptionDescriptions.
421 container_type Descriptions;
424 /// FindOption - exception-throwing wrapper for find().
425 const OptionDescription& FindOption(const std::string& OptName) const;
427 // Wrappers for FindOption that throw an exception in case the option has a
429 const OptionDescription& FindSwitch(const std::string& OptName) const;
430 const OptionDescription& FindParameter(const std::string& OptName) const;
431 const OptionDescription& FindList(const std::string& OptName) const;
432 const OptionDescription&
433 FindListOrParameter(const std::string& OptName) const;
435 /// insertDescription - Insert new OptionDescription into
436 /// OptionDescriptions list
437 void InsertDescription (const OptionDescription& o);
439 // Support for STL-style iteration
440 typedef container_type::const_iterator const_iterator;
441 const_iterator begin() const { return Descriptions.begin(); }
442 const_iterator end() const { return Descriptions.end(); }
445 const OptionDescription&
446 OptionDescriptions::FindOption(const std::string& OptName) const {
447 const_iterator I = Descriptions.find(OptName);
448 if (I != Descriptions.end())
451 throw OptName + ": no such option!";
454 const OptionDescription&
455 OptionDescriptions::FindSwitch(const std::string& OptName) const {
456 const OptionDescription& OptDesc = this->FindOption(OptName);
457 if (!OptDesc.isSwitch())
458 throw OptName + ": incorrect option type - should be a switch!";
462 const OptionDescription&
463 OptionDescriptions::FindList(const std::string& OptName) const {
464 const OptionDescription& OptDesc = this->FindOption(OptName);
465 if (!OptDesc.isList())
466 throw OptName + ": incorrect option type - should be a list!";
470 const OptionDescription&
471 OptionDescriptions::FindParameter(const std::string& OptName) const {
472 const OptionDescription& OptDesc = this->FindOption(OptName);
473 if (!OptDesc.isParameter())
474 throw OptName + ": incorrect option type - should be a parameter!";
478 const OptionDescription&
479 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
480 const OptionDescription& OptDesc = this->FindOption(OptName);
481 if (!OptDesc.isList() && !OptDesc.isParameter())
483 + ": incorrect option type - should be a list or parameter!";
487 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
488 container_type::iterator I = Descriptions.find(o.Name);
489 if (I != Descriptions.end()) {
490 OptionDescription& D = I->second;
494 Descriptions[o.Name] = o;
498 /// HandlerTable - A base class for function objects implemented as
499 /// 'tables of handlers'.
500 template <typename Handler>
503 // Implementation details.
505 /// HandlerMap - A map from property names to property handlers
506 typedef StringMap<Handler> HandlerMap;
508 static HandlerMap Handlers_;
509 static bool staticMembersInitialized_;
513 Handler GetHandler (const std::string& HandlerName) const {
514 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
516 if (method != Handlers_.end()) {
517 Handler h = method->second;
521 throw "No handler found for property " + HandlerName + "!";
525 void AddHandler(const char* Property, Handler H) {
526 Handlers_[Property] = H;
531 template <class Handler, class FunctionObject>
532 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
533 const std::string& HandlerName = GetOperatorName(Dag);
534 return Obj->GetHandler(HandlerName);
537 template <class FunctionObject>
538 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
539 typedef void (FunctionObject::*Handler) (const DagInit&);
541 const DagInit& Dag = InitPtrToDag(I);
542 Handler h = GetHandler<Handler>(Obj, Dag);
547 template <class FunctionObject>
548 void InvokeDagInitHandler(const FunctionObject* const Obj,
549 const Init* I, unsigned IndentLevel, raw_ostream& O)
551 typedef void (FunctionObject::*Handler)
552 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
554 const DagInit& Dag = InitPtrToDag(I);
555 Handler h = GetHandler<Handler>(Obj, Dag);
557 ((Obj)->*(h))(Dag, IndentLevel, O);
561 template <typename H>
562 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
564 template <typename H>
565 bool HandlerTable<H>::staticMembersInitialized_ = false;
568 /// CollectOptionProperties - Function object for iterating over an
569 /// option property list.
570 class CollectOptionProperties;
571 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
574 class CollectOptionProperties
575 : public HandlerTable<CollectOptionPropertiesHandler>
579 /// optDescs_ - OptionDescriptions table. This is where the
580 /// information is stored.
581 OptionDescription& optDesc_;
585 explicit CollectOptionProperties(OptionDescription& OD)
588 if (!staticMembersInitialized_) {
589 AddHandler("extern", &CollectOptionProperties::onExtern);
590 AddHandler("help", &CollectOptionProperties::onHelp);
591 AddHandler("hidden", &CollectOptionProperties::onHidden);
592 AddHandler("init", &CollectOptionProperties::onInit);
593 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
594 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
595 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
596 AddHandler("required", &CollectOptionProperties::onRequired);
597 AddHandler("optional", &CollectOptionProperties::onOptional);
598 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
599 AddHandler("forward_not_split",
600 &CollectOptionProperties::onForwardNotSplit);
602 staticMembersInitialized_ = true;
606 /// operator() - Just forwards to the corresponding property
608 void operator() (Init* I) {
609 InvokeDagInitHandler(this, I);
614 /// Option property handlers --
615 /// Methods that handle option properties such as (help) or (hidden).
617 void onExtern (const DagInit& d) {
618 CheckNumberOfArguments(d, 0);
619 optDesc_.setExtern();
622 void onHelp (const DagInit& d) {
623 CheckNumberOfArguments(d, 1);
624 optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0)));
627 void onHidden (const DagInit& d) {
628 CheckNumberOfArguments(d, 0);
629 optDesc_.setHidden();
632 void onReallyHidden (const DagInit& d) {
633 CheckNumberOfArguments(d, 0);
634 optDesc_.setReallyHidden();
637 void onCommaSeparated (const DagInit& d) {
638 CheckNumberOfArguments(d, 0);
639 if (!optDesc_.isList())
640 throw "'comma_separated' is valid only on list options!";
641 optDesc_.setCommaSeparated();
644 void onForwardNotSplit (const DagInit& d) {
645 CheckNumberOfArguments(d, 0);
646 if (!optDesc_.isParameter())
647 throw "'forward_not_split' is valid only for parameter options!";
648 optDesc_.setForwardNotSplit();
651 void onRequired (const DagInit& d) {
652 CheckNumberOfArguments(d, 0);
653 if (optDesc_.isOneOrMore() || optDesc_.isOptional())
654 throw "Only one of (required), (optional) or "
655 "(one_or_more) properties is allowed!";
656 optDesc_.setRequired();
659 void onInit (const DagInit& d) {
660 CheckNumberOfArguments(d, 1);
661 Init* i = d.getArg(0);
662 const std::string& str = i->getAsString();
664 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
665 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
668 throw "Incorrect usage of the 'init' option property!";
670 optDesc_.InitVal = i;
673 void onOneOrMore (const DagInit& d) {
674 CheckNumberOfArguments(d, 0);
675 if (optDesc_.isRequired() || optDesc_.isOptional())
676 throw "Only one of (required), (optional) or "
677 "(one_or_more) properties is allowed!";
678 if (!OptionType::IsList(optDesc_.Type))
679 llvm::errs() << "Warning: specifying the 'one_or_more' property "
680 "on a non-list option will have no effect.\n";
681 optDesc_.setOneOrMore();
684 void onOptional (const DagInit& d) {
685 CheckNumberOfArguments(d, 0);
686 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
687 throw "Only one of (required), (optional) or "
688 "(one_or_more) properties is allowed!";
689 if (!OptionType::IsList(optDesc_.Type))
690 llvm::errs() << "Warning: specifying the 'optional' property"
691 "on a non-list option will have no effect.\n";
692 optDesc_.setOptional();
695 void onMultiVal (const DagInit& d) {
696 CheckNumberOfArguments(d, 1);
697 int val = InitPtrToInt(d.getArg(0));
699 throw "Error in the 'multi_val' property: "
700 "the value must be greater than 1!";
701 if (!OptionType::IsList(optDesc_.Type))
702 throw "The multi_val property is valid only on list options!";
703 optDesc_.MultiVal = val;
708 /// AddOption - A function object that is applied to every option
709 /// description. Used by CollectOptionDescriptions.
712 OptionDescriptions& OptDescs_;
715 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
718 void operator()(const Init* i) {
719 const DagInit& d = InitPtrToDag(i);
720 CheckNumberOfArguments(d, 1);
722 const OptionType::OptionType Type =
723 stringToOptionType(GetOperatorName(d));
724 const std::string& Name = InitPtrToString(d.getArg(0));
726 OptionDescription OD(Type, Name);
729 CheckNumberOfArguments(d, 2);
732 // Aliases store the aliased option name in the 'Help' field.
733 OD.Help = InitPtrToString(d.getArg(1));
735 else if (!OD.isExtern()) {
736 processOptionProperties(d, OD);
738 OptDescs_.InsertDescription(OD);
742 /// processOptionProperties - Go through the list of option
743 /// properties and call a corresponding handler for each.
744 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
745 CheckNumberOfArguments(d, 2);
746 DagInit::const_arg_iterator B = d.arg_begin();
747 // Skip the first argument: it's always the option name.
749 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
754 /// CollectOptionDescriptions - Collects option properties from all
756 void CollectOptionDescriptions (RecordVector::const_iterator B,
757 RecordVector::const_iterator E,
758 OptionDescriptions& OptDescs)
760 // For every OptionList:
762 RecordVector::value_type T = *B;
763 // Throws an exception if the value does not exist.
764 ListInit* PropList = T->getValueAsListInit("options");
766 // For every option description in this list:
767 // collect the information and
768 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
772 // Tool information record
774 namespace ToolFlags {
775 enum ToolFlags { Join = 0x1, Sink = 0x2 };
778 struct ToolDescription : public RefCountedBase<ToolDescription> {
782 StrVector InLanguage;
783 std::string OutLanguage;
784 std::string OutputSuffix;
787 // Various boolean properties
788 void setSink() { Flags |= ToolFlags::Sink; }
789 bool isSink() const { return Flags & ToolFlags::Sink; }
790 void setJoin() { Flags |= ToolFlags::Join; }
791 bool isJoin() const { return Flags & ToolFlags::Join; }
793 // Default ctor here is needed because StringMap can only store
794 // DefaultConstructible objects
795 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
796 ToolDescription (const std::string& n)
797 : Name(n), CmdLine(0), Actions(0), Flags(0)
801 /// ToolDescriptions - A list of Tool information records.
802 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
805 /// CollectToolProperties - Function object for iterating over a list of
806 /// tool property records.
808 class CollectToolProperties;
809 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
812 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
816 /// toolDesc_ - Properties of the current Tool. This is where the
817 /// information is stored.
818 ToolDescription& toolDesc_;
822 explicit CollectToolProperties (ToolDescription& d)
825 if (!staticMembersInitialized_) {
827 AddHandler("actions", &CollectToolProperties::onActions);
828 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
829 AddHandler("in_language", &CollectToolProperties::onInLanguage);
830 AddHandler("join", &CollectToolProperties::onJoin);
831 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
832 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
833 AddHandler("sink", &CollectToolProperties::onSink);
835 staticMembersInitialized_ = true;
839 void operator() (Init* I) {
840 InvokeDagInitHandler(this, I);
845 /// Property handlers --
846 /// Functions that extract information about tool properties from
847 /// DAG representation.
849 void onActions (const DagInit& d) {
850 CheckNumberOfArguments(d, 1);
851 Init* Case = d.getArg(0);
852 if (typeid(*Case) != typeid(DagInit) ||
853 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
854 throw "The argument to (actions) should be a 'case' construct!";
855 toolDesc_.Actions = Case;
858 void onCmdLine (const DagInit& d) {
859 CheckNumberOfArguments(d, 1);
860 toolDesc_.CmdLine = d.getArg(0);
863 void onInLanguage (const DagInit& d) {
864 CheckNumberOfArguments(d, 1);
865 Init* arg = d.getArg(0);
867 // Find out the argument's type.
868 if (typeid(*arg) == typeid(StringInit)) {
870 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
874 const ListInit& lst = InitPtrToList(arg);
875 StrVector& out = toolDesc_.InLanguage;
877 // Copy strings to the output vector.
878 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
880 out.push_back(InitPtrToString(*B));
883 // Remove duplicates.
884 std::sort(out.begin(), out.end());
885 StrVector::iterator newE = std::unique(out.begin(), out.end());
886 out.erase(newE, out.end());
890 void onJoin (const DagInit& d) {
891 CheckNumberOfArguments(d, 0);
895 void onOutLanguage (const DagInit& d) {
896 CheckNumberOfArguments(d, 1);
897 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
900 void onOutputSuffix (const DagInit& d) {
901 CheckNumberOfArguments(d, 1);
902 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
905 void onSink (const DagInit& d) {
906 CheckNumberOfArguments(d, 0);
912 /// CollectToolDescriptions - Gather information about tool properties
913 /// from the parsed TableGen data (basically a wrapper for the
914 /// CollectToolProperties function object).
915 void CollectToolDescriptions (RecordVector::const_iterator B,
916 RecordVector::const_iterator E,
917 ToolDescriptions& ToolDescs)
919 // Iterate over a properties list of every Tool definition
921 const Record* T = *B;
922 // Throws an exception if the value does not exist.
923 ListInit* PropList = T->getValueAsListInit("properties");
925 IntrusiveRefCntPtr<ToolDescription>
926 ToolDesc(new ToolDescription(T->getName()));
928 std::for_each(PropList->begin(), PropList->end(),
929 CollectToolProperties(*ToolDesc));
930 ToolDescs.push_back(ToolDesc);
934 /// FillInEdgeVector - Merge all compilation graph definitions into
935 /// one single edge list.
936 void FillInEdgeVector(RecordVector::const_iterator B,
937 RecordVector::const_iterator E, RecordVector& Out) {
938 for (; B != E; ++B) {
939 const ListInit* edges = (*B)->getValueAsListInit("edges");
941 for (unsigned i = 0; i < edges->size(); ++i)
942 Out.push_back(edges->getElementAsRecord(i));
946 /// CalculatePriority - Calculate the priority of this plugin.
947 int CalculatePriority(RecordVector::const_iterator B,
948 RecordVector::const_iterator E) {
952 priority = static_cast<int>((*B)->getValueAsInt("priority"));
955 throw "More than one 'PluginPriority' instance found: "
956 "most probably an error!";
962 /// NotInGraph - Helper function object for FilterNotInGraph.
965 const llvm::StringSet<>& ToolsInGraph_;
968 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
969 : ToolsInGraph_(ToolsInGraph)
972 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
973 return (ToolsInGraph_.count(x->Name) == 0);
977 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
978 /// mentioned in the compilation graph definition.
979 void FilterNotInGraph (const RecordVector& EdgeVector,
980 ToolDescriptions& ToolDescs) {
982 // List all tools mentioned in the graph.
983 llvm::StringSet<> ToolsInGraph;
985 for (RecordVector::const_iterator B = EdgeVector.begin(),
986 E = EdgeVector.end(); B != E; ++B) {
988 const Record* Edge = *B;
989 const std::string& NodeA = Edge->getValueAsString("a");
990 const std::string& NodeB = Edge->getValueAsString("b");
993 ToolsInGraph.insert(NodeA);
994 ToolsInGraph.insert(NodeB);
997 // Filter ToolPropertiesList.
998 ToolDescriptions::iterator new_end =
999 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
1000 NotInGraph(ToolsInGraph));
1001 ToolDescs.erase(new_end, ToolDescs.end());
1004 /// FillInToolToLang - Fills in two tables that map tool names to
1005 /// (input, output) languages. Helper function used by TypecheckGraph().
1006 void FillInToolToLang (const ToolDescriptions& ToolDescs,
1007 StringMap<StringSet<> >& ToolToInLang,
1008 StringMap<std::string>& ToolToOutLang) {
1009 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1010 E = ToolDescs.end(); B != E; ++B) {
1011 const ToolDescription& D = *(*B);
1012 for (StrVector::const_iterator B = D.InLanguage.begin(),
1013 E = D.InLanguage.end(); B != E; ++B)
1014 ToolToInLang[D.Name].insert(*B);
1015 ToolToOutLang[D.Name] = D.OutLanguage;
1019 /// TypecheckGraph - Check that names for output and input languages
1020 /// on all edges do match. This doesn't do much when the information
1021 /// about the whole graph is not available (i.e. when compiling most
1023 void TypecheckGraph (const RecordVector& EdgeVector,
1024 const ToolDescriptions& ToolDescs) {
1025 StringMap<StringSet<> > ToolToInLang;
1026 StringMap<std::string> ToolToOutLang;
1028 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
1029 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1030 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1032 for (RecordVector::const_iterator B = EdgeVector.begin(),
1033 E = EdgeVector.end(); B != E; ++B) {
1034 const Record* Edge = *B;
1035 const std::string& NodeA = Edge->getValueAsString("a");
1036 const std::string& NodeB = Edge->getValueAsString("b");
1037 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1038 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1040 if (NodeA != "root") {
1041 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1042 throw "Edge " + NodeA + "->" + NodeB
1043 + ": output->input language mismatch";
1046 if (NodeB == "root")
1047 throw "Edges back to the root are not allowed!";
1051 /// WalkCase - Walks the 'case' expression DAG and invokes
1052 /// TestCallback on every test, and StatementCallback on every
1053 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1054 /// combinators (that is, they are passed directly to TestCallback).
1055 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1056 /// IndentLevel, bool FirstTest)'.
1057 /// StatementCallback must have type 'void StatementCallback(const Init*,
1058 /// unsigned IndentLevel)'.
1059 template <typename F1, typename F2>
1060 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1061 unsigned IndentLevel = 0)
1063 const DagInit& d = InitPtrToDag(Case);
1066 if (GetOperatorName(d) != "case")
1067 throw "WalkCase should be invoked only on 'case' expressions!";
1069 if (d.getNumArgs() < 2)
1070 throw "There should be at least one clause in the 'case' expression:\n"
1075 const unsigned numArgs = d.getNumArgs();
1077 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1084 const DagInit& Test = InitPtrToDag(arg);
1086 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1087 throw "The 'default' clause should be the last in the "
1088 "'case' construct!";
1090 throw "Case construct handler: no corresponding action "
1091 "found for the test " + Test.getAsString() + '!';
1093 TestCallback(Test, IndentLevel, (i == 1));
1097 if (dynamic_cast<DagInit*>(arg)
1098 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1100 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1103 // Handle statement.
1104 StatementCallback(arg, IndentLevel);
1112 /// ExtractOptionNames - A helper function object used by
1113 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1114 class ExtractOptionNames {
1115 llvm::StringSet<>& OptionNames_;
1117 void processDag(const Init* Statement) {
1118 const DagInit& Stmt = InitPtrToDag(Statement);
1119 const std::string& ActionName = GetOperatorName(Stmt);
1120 if (ActionName == "forward" || ActionName == "forward_as" ||
1121 ActionName == "forward_value" ||
1122 ActionName == "forward_transformed_value" ||
1123 ActionName == "switch_on" || ActionName == "any_switch_on" ||
1124 ActionName == "parameter_equals" ||
1125 ActionName == "element_in_list" || ActionName == "not_empty" ||
1126 ActionName == "empty") {
1127 CheckNumberOfArguments(Stmt, 1);
1129 Init* Arg = Stmt.getArg(0);
1130 if (typeid(*Arg) == typeid(StringInit)) {
1131 const std::string& Name = InitPtrToString(Arg);
1132 OptionNames_.insert(Name);
1136 const ListInit& List = InitPtrToList(Arg);
1137 for (ListInit::const_iterator B = List.begin(), E = List.end();
1139 const std::string& Name = InitPtrToString(*B);
1140 OptionNames_.insert(Name);
1144 else if (ActionName == "and" || ActionName == "or" || ActionName == "not") {
1145 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1146 this->processDag(Stmt.getArg(i));
1152 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1155 void operator()(const Init* Statement) {
1156 if (typeid(*Statement) == typeid(ListInit)) {
1157 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1158 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1160 this->processDag(*B);
1163 this->processDag(Statement);
1167 void operator()(const DagInit& Test, unsigned, bool) {
1168 this->operator()(&Test);
1170 void operator()(const Init* Statement, unsigned) {
1171 this->operator()(Statement);
1175 /// CheckForSuperfluousOptions - Check that there are no side
1176 /// effect-free options (specified only in the OptionList). Otherwise,
1177 /// output a warning.
1178 void CheckForSuperfluousOptions (const RecordVector& Edges,
1179 const ToolDescriptions& ToolDescs,
1180 const OptionDescriptions& OptDescs) {
1181 llvm::StringSet<> nonSuperfluousOptions;
1183 // Add all options mentioned in the ToolDesc.Actions to the set of
1184 // non-superfluous options.
1185 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1186 E = ToolDescs.end(); B != E; ++B) {
1187 const ToolDescription& TD = *(*B);
1188 ExtractOptionNames Callback(nonSuperfluousOptions);
1190 WalkCase(TD.Actions, Callback, Callback);
1193 // Add all options mentioned in the 'case' clauses of the
1194 // OptionalEdges of the compilation graph to the set of
1195 // non-superfluous options.
1196 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1198 const Record* Edge = *B;
1199 DagInit& Weight = *Edge->getValueAsDag("weight");
1201 if (!IsDagEmpty(Weight))
1202 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1205 // Check that all options in OptDescs belong to the set of
1206 // non-superfluous options.
1207 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1208 E = OptDescs.end(); B != E; ++B) {
1209 const OptionDescription& Val = B->second;
1210 if (!nonSuperfluousOptions.count(Val.Name)
1211 && Val.Type != OptionType::Alias)
1212 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1213 "Probable cause: this option is specified only in the OptionList.\n";
1217 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1218 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1219 if (TestName == "single_input_file") {
1220 O << "InputFilenames.size() == 1";
1223 else if (TestName == "multiple_input_files") {
1224 O << "InputFilenames.size() > 1";
1231 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1232 template <typename F>
1233 void EmitListTest(const ListInit& L, const char* LogicOp,
1234 F Callback, raw_ostream& O)
1236 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1238 bool isFirst = true;
1239 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1243 O << ' ' << LogicOp << ' ';
1244 Callback(InitPtrToString(*B), O);
1248 // Callbacks for use with EmitListTest.
1250 class EmitSwitchOn {
1251 const OptionDescriptions& OptDescs_;
1253 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1256 void operator()(const std::string& OptName, raw_ostream& O) const {
1257 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1258 O << OptDesc.GenVariableName();
1262 class EmitEmptyTest {
1264 const OptionDescriptions& OptDescs_;
1266 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1267 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1270 void operator()(const std::string& OptName, raw_ostream& O) const {
1271 const char* Neg = (EmitNegate_ ? "!" : "");
1272 if (OptName == "o") {
1273 O << Neg << "OutputFilename.empty()";
1275 else if (OptName == "save-temps") {
1276 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1279 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1280 O << Neg << OptDesc.GenVariableName() << ".empty()";
1286 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1287 bool EmitCaseTest1ArgList(const std::string& TestName,
1289 const OptionDescriptions& OptDescs,
1291 const ListInit& L = InitPtrToList(d.getArg(0));
1293 if (TestName == "any_switch_on") {
1294 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1297 else if (TestName == "switch_on") {
1298 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1301 else if (TestName == "any_not_empty") {
1302 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1305 else if (TestName == "any_empty") {
1306 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1309 else if (TestName == "not_empty") {
1310 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1313 else if (TestName == "empty") {
1314 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1321 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1322 bool EmitCaseTest1ArgStr(const std::string& TestName,
1324 const OptionDescriptions& OptDescs,
1326 const std::string& OptName = InitPtrToString(d.getArg(0));
1328 if (TestName == "switch_on") {
1329 apply(EmitSwitchOn(OptDescs), OptName, O);
1332 else if (TestName == "input_languages_contain") {
1333 O << "InLangs.count(\"" << OptName << "\") != 0";
1336 else if (TestName == "in_language") {
1337 // This works only for single-argument Tool::GenerateAction. Join
1338 // tools can process several files in different languages simultaneously.
1340 // TODO: make this work with Edge::Weight (if possible).
1341 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1344 else if (TestName == "not_empty" || TestName == "empty") {
1345 bool EmitNegate = (TestName == "not_empty");
1346 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1353 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1354 bool EmitCaseTest1Arg(const std::string& TestName,
1356 const OptionDescriptions& OptDescs,
1358 CheckNumberOfArguments(d, 1);
1359 if (typeid(*d.getArg(0)) == typeid(ListInit))
1360 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1362 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1365 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1366 bool EmitCaseTest2Args(const std::string& TestName,
1368 unsigned IndentLevel,
1369 const OptionDescriptions& OptDescs,
1371 CheckNumberOfArguments(d, 2);
1372 const std::string& OptName = InitPtrToString(d.getArg(0));
1373 const std::string& OptArg = InitPtrToString(d.getArg(1));
1375 if (TestName == "parameter_equals") {
1376 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1377 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1380 else if (TestName == "element_in_list") {
1381 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1382 const std::string& VarName = OptDesc.GenVariableName();
1383 O << "std::find(" << VarName << ".begin(),\n";
1384 O.indent(IndentLevel + Indent1)
1385 << VarName << ".end(), \""
1386 << OptArg << "\") != " << VarName << ".end()";
1393 // Forward declaration.
1394 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1395 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1396 const OptionDescriptions& OptDescs,
1399 /// EmitLogicalOperationTest - Helper function used by
1400 /// EmitCaseConstructHandler.
1401 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1402 unsigned IndentLevel,
1403 const OptionDescriptions& OptDescs,
1406 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1407 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1408 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1409 if (j != NumArgs - 1) {
1411 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1419 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1420 const OptionDescriptions& OptDescs, raw_ostream& O)
1422 CheckNumberOfArguments(d, 1);
1423 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1425 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1429 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1430 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1431 const OptionDescriptions& OptDescs,
1433 const std::string& TestName = GetOperatorName(d);
1435 if (TestName == "and")
1436 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1437 else if (TestName == "or")
1438 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1439 else if (TestName == "not")
1440 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1441 else if (EmitCaseTest0Args(TestName, O))
1443 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1445 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1448 throw "Unknown test '" + TestName + "' used in the 'case' construct!";
1452 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1453 class EmitCaseTestCallback {
1455 const OptionDescriptions& OptDescs_;
1459 EmitCaseTestCallback(bool EmitElseIf,
1460 const OptionDescriptions& OptDescs, raw_ostream& O)
1461 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1464 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1466 if (GetOperatorName(Test) == "default") {
1467 O_.indent(IndentLevel) << "else {\n";
1470 O_.indent(IndentLevel)
1471 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1472 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1478 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1479 template <typename F>
1480 class EmitCaseStatementCallback {
1485 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1486 : Callback_(Callback), O_(O)
1489 void operator() (const Init* Statement, unsigned IndentLevel) {
1491 // Ignore nested 'case' DAG.
1492 if (!(dynamic_cast<const DagInit*>(Statement) &&
1493 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1494 if (typeid(*Statement) == typeid(ListInit)) {
1495 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1496 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1498 Callback_(*B, (IndentLevel + Indent1), O_);
1501 Callback_(Statement, (IndentLevel + Indent1), O_);
1504 O_.indent(IndentLevel) << "}\n";
1509 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1510 /// construct. Takes a function object that should emit code for every case
1511 /// clause. Implemented on top of WalkCase.
1512 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1513 /// raw_ostream& O).
1514 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1515 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1517 template <typename F>
1518 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1519 F Callback, bool EmitElseIf,
1520 const OptionDescriptions& OptDescs,
1522 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1523 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1526 /// TokenizeCmdLine - converts from
1527 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1528 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1529 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1530 const char* Delimiters = " \t\n\v\f\r";
1532 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1535 if (CmdLine.empty())
1539 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1542 for (; B != E; ++B) {
1543 char cur_ch = CmdLine[B];
1547 if (cur_ch == '$') {
1548 cur_st = SpecialCommand;
1551 if (OneOf(Delimiters, cur_ch)) {
1553 B = CmdLine.find_first_not_of(Delimiters, B);
1554 if (B == std::string::npos) {
1565 case SpecialCommand:
1566 if (OneOf(Delimiters, cur_ch)) {
1571 if (cur_ch == '(') {
1573 cur_st = InsideSpecialCommand;
1578 case InsideSpecialCommand:
1579 if (OneOf(Delimiters, cur_ch)) {
1582 if (cur_ch == '\'') {
1583 cur_st = InsideQuotationMarks;
1587 if (cur_ch == ')') {
1591 if (cur_ch == ',') {
1597 case InsideQuotationMarks:
1598 if (cur_ch == '\'') {
1599 cur_st = InsideSpecialCommand;
1605 Out.back().push_back(cur_ch);
1609 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1610 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1611 /// SubstituteSpecialCommands().
1612 StrVector::const_iterator
1613 SubstituteCall (StrVector::const_iterator Pos,
1614 StrVector::const_iterator End,
1615 bool IsJoin, raw_ostream& O)
1617 const char* errorMessage = "Syntax error in $CALL invocation!";
1618 CheckedIncrement(Pos, End, errorMessage);
1619 const std::string& CmdName = *Pos;
1622 throw "$CALL invocation: empty argument list!";
1625 O << CmdName << "(";
1628 bool firstIteration = true;
1630 CheckedIncrement(Pos, End, errorMessage);
1631 const std::string& Arg = *Pos;
1632 assert(Arg.size() != 0);
1638 firstIteration = false;
1642 if (Arg == "$INFILE") {
1644 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1646 O << "inFile.c_str()";
1649 O << '"' << Arg << '"';
1658 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1659 /// function used by SubstituteSpecialCommands().
1660 StrVector::const_iterator
1661 SubstituteEnv (StrVector::const_iterator Pos,
1662 StrVector::const_iterator End, raw_ostream& O)
1664 const char* errorMessage = "Syntax error in $ENV invocation!";
1665 CheckedIncrement(Pos, End, errorMessage);
1666 const std::string& EnvName = *Pos;
1669 throw "$ENV invocation: empty argument list!";
1671 O << "checkCString(std::getenv(\"";
1675 CheckedIncrement(Pos, End, errorMessage);
1680 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1681 /// handler code. Helper function used by EmitCmdLineVecFill().
1682 StrVector::const_iterator
1683 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1684 StrVector::const_iterator End,
1685 bool IsJoin, raw_ostream& O)
1688 const std::string& cmd = *Pos;
1690 // Perform substitution.
1691 if (cmd == "$CALL") {
1692 Pos = SubstituteCall(Pos, End, IsJoin, O);
1694 else if (cmd == "$ENV") {
1695 Pos = SubstituteEnv(Pos, End, O);
1698 throw "Unknown special command: " + cmd;
1701 // Handle '$CMD(ARG)/additional/text'.
1702 const std::string& Leftover = *Pos;
1703 assert(Leftover.at(0) == ')');
1704 if (Leftover.size() != 1)
1705 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1710 /// EmitCmdLineVecFill - Emit code that fills in the command line
1711 /// vector. Helper function used by EmitGenerateActionMethod().
1712 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1713 bool IsJoin, unsigned IndentLevel,
1716 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1719 throw "Tool '" + ToolName + "' has empty command line!";
1721 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1723 // If there is a hook invocation on the place of the first command, skip it.
1724 assert(!StrVec[0].empty());
1725 if (StrVec[0][0] == '$') {
1726 while (I != E && (*I)[0] != ')' )
1729 // Skip the ')' symbol.
1736 bool hasINFILE = false;
1738 for (; I != E; ++I) {
1739 const std::string& cmd = *I;
1740 assert(!cmd.empty());
1741 O.indent(IndentLevel);
1742 if (cmd.at(0) == '$') {
1743 if (cmd == "$INFILE") {
1746 O << "for (PathVector::const_iterator B = inFiles.begin()"
1747 << ", E = inFiles.end();\n";
1748 O.indent(IndentLevel) << "B != E; ++B)\n";
1749 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1752 O << "vec.push_back(inFile.str());\n";
1755 else if (cmd == "$OUTFILE") {
1756 O << "vec.push_back(\"\");\n";
1757 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1760 O << "vec.push_back(";
1761 I = SubstituteSpecialCommands(I, E, IsJoin, O);
1766 O << "vec.push_back(\"" << cmd << "\");\n";
1770 throw "Tool '" + ToolName + "' doesn't take any input!";
1772 O.indent(IndentLevel) << "cmd = ";
1773 if (StrVec[0][0] == '$')
1774 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), IsJoin, O);
1776 O << '"' << StrVec[0] << '"';
1780 /// EmitCmdLineVecFillCallback - A function object wrapper around
1781 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1782 /// argument to EmitCaseConstructHandler().
1783 class EmitCmdLineVecFillCallback {
1785 const std::string& ToolName;
1787 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1788 : IsJoin(J), ToolName(TN) {}
1790 void operator()(const Init* Statement, unsigned IndentLevel,
1791 raw_ostream& O) const
1793 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1797 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1798 /// implement EmitActionHandler. Emits code for
1799 /// handling the (forward) and (forward_as) option properties.
1800 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1801 unsigned IndentLevel,
1802 const std::string& NewName,
1804 const std::string& Name = NewName.empty()
1807 unsigned IndentLevel1 = IndentLevel + Indent1;
1810 case OptionType::Switch:
1811 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1813 case OptionType::Parameter:
1814 O.indent(IndentLevel) << "vec.push_back(\"" << Name;
1816 if (!D.isForwardNotSplit()) {
1818 O.indent(IndentLevel) << "vec.push_back("
1819 << D.GenVariableName() << ");\n";
1822 O << "=\" + " << D.GenVariableName() << ");\n";
1825 case OptionType::Prefix:
1826 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1827 << D.GenVariableName() << ");\n";
1829 case OptionType::PrefixList:
1830 O.indent(IndentLevel)
1831 << "for (" << D.GenTypeDeclaration()
1832 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1833 O.indent(IndentLevel)
1834 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1835 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1836 O.indent(IndentLevel1) << "++B;\n";
1838 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1839 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1840 O.indent(IndentLevel1) << "++B;\n";
1843 O.indent(IndentLevel) << "}\n";
1845 case OptionType::ParameterList:
1846 O.indent(IndentLevel)
1847 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1848 << D.GenVariableName() << ".begin(),\n";
1849 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1850 << ".end() ; B != E;) {\n";
1851 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1853 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1854 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1855 O.indent(IndentLevel1) << "++B;\n";
1858 O.indent(IndentLevel) << "}\n";
1860 case OptionType::Alias:
1862 throw "Aliases are not allowed in tool option descriptions!";
1866 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1867 /// EmitPreprocessOptionsCallback.
1868 struct ActionHandlingCallbackBase
1871 void onErrorDag(const DagInit& d,
1872 unsigned IndentLevel, raw_ostream& O) const
1874 O.indent(IndentLevel)
1875 << "throw std::runtime_error(\"" <<
1876 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1881 void onWarningDag(const DagInit& d,
1882 unsigned IndentLevel, raw_ostream& O) const
1884 CheckNumberOfArguments(d, 1);
1885 O.indent(IndentLevel) << "llvm::errs() << \""
1886 << InitPtrToString(d.getArg(0)) << "\";\n";
1891 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1892 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1894 class EmitActionHandlersCallback;
1896 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1897 (const DagInit&, unsigned, raw_ostream&) const;
1899 class EmitActionHandlersCallback :
1900 public ActionHandlingCallbackBase,
1901 public HandlerTable<EmitActionHandlersCallbackHandler>
1903 typedef EmitActionHandlersCallbackHandler Handler;
1905 const OptionDescriptions& OptDescs;
1907 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1908 /// onAppendCmd and onOutputSuffix.
1909 void EmitHookInvocation(const std::string& Str,
1910 const char* BlockOpen, const char* BlockClose,
1911 unsigned IndentLevel, raw_ostream& O) const
1914 TokenizeCmdLine(Str, Out);
1916 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1918 const std::string& cmd = *B;
1920 O.indent(IndentLevel) << BlockOpen;
1922 if (cmd.at(0) == '$')
1923 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1925 O << '"' << cmd << '"';
1931 void onAppendCmd (const DagInit& Dag,
1932 unsigned IndentLevel, raw_ostream& O) const
1934 CheckNumberOfArguments(Dag, 1);
1935 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1936 "vec.push_back(", ");\n", IndentLevel, O);
1939 void onForward (const DagInit& Dag,
1940 unsigned IndentLevel, raw_ostream& O) const
1942 CheckNumberOfArguments(Dag, 1);
1943 const std::string& Name = InitPtrToString(Dag.getArg(0));
1944 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1945 IndentLevel, "", O);
1948 void onForwardAs (const DagInit& Dag,
1949 unsigned IndentLevel, raw_ostream& O) const
1951 CheckNumberOfArguments(Dag, 2);
1952 const std::string& Name = InitPtrToString(Dag.getArg(0));
1953 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1954 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1955 IndentLevel, NewName, O);
1958 void onForwardValue (const DagInit& Dag,
1959 unsigned IndentLevel, raw_ostream& O) const
1961 CheckNumberOfArguments(Dag, 1);
1962 const std::string& Name = InitPtrToString(Dag.getArg(0));
1963 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1965 if (D.isParameter()) {
1966 O.indent(IndentLevel) << "vec.push_back("
1967 << D.GenVariableName() << ");\n";
1970 O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1971 << ".begin(), " << D.GenVariableName()
1972 << ".end(), std::back_inserter(vec));\n";
1976 void onForwardTransformedValue (const DagInit& Dag,
1977 unsigned IndentLevel, raw_ostream& O) const
1979 CheckNumberOfArguments(Dag, 2);
1980 const std::string& Name = InitPtrToString(Dag.getArg(0));
1981 const std::string& Hook = InitPtrToString(Dag.getArg(1));
1982 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1984 O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1985 << Hook << "(" << D.GenVariableName()
1986 << (D.isParameter() ? ".c_str()" : "") << "));\n";
1989 void onOutputSuffix (const DagInit& Dag,
1990 unsigned IndentLevel, raw_ostream& O) const
1992 CheckNumberOfArguments(Dag, 1);
1993 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1994 "output_suffix = ", ";\n", IndentLevel, O);
1997 void onStopCompilation (const DagInit& Dag,
1998 unsigned IndentLevel, raw_ostream& O) const
2000 O.indent(IndentLevel) << "stop_compilation = true;\n";
2004 void onUnpackValues (const DagInit& Dag,
2005 unsigned IndentLevel, raw_ostream& O) const
2007 throw "'unpack_values' is deprecated. "
2008 "Use 'comma_separated' + 'forward_value' instead!";
2013 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
2016 if (!staticMembersInitialized_) {
2017 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
2018 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
2019 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
2020 AddHandler("forward", &EmitActionHandlersCallback::onForward);
2021 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
2022 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
2023 AddHandler("forward_transformed_value",
2024 &EmitActionHandlersCallback::onForwardTransformedValue);
2025 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
2026 AddHandler("stop_compilation",
2027 &EmitActionHandlersCallback::onStopCompilation);
2028 AddHandler("unpack_values",
2029 &EmitActionHandlersCallback::onUnpackValues);
2031 staticMembersInitialized_ = true;
2035 void operator()(const Init* I,
2036 unsigned IndentLevel, raw_ostream& O) const
2038 InvokeDagInitHandler(this, I, IndentLevel, O);
2042 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
2044 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
2046 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
2048 if (*I == "$OUTFILE")
2055 class IsOutFileIndexCheckRequiredStrCallback {
2059 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
2062 void operator()(const Init* CmdLine) {
2063 // Ignore nested 'case' DAG.
2064 if (typeid(*CmdLine) == typeid(DagInit))
2067 if (IsOutFileIndexCheckRequiredStr(CmdLine))
2071 void operator()(const DagInit* Test, unsigned, bool) {
2072 this->operator()(Test);
2074 void operator()(const Init* Statement, unsigned) {
2075 this->operator()(Statement);
2079 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
2081 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
2085 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
2086 /// in EmitGenerateActionMethod() ?
2087 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
2088 if (typeid(*CmdLine) == typeid(StringInit))
2089 return IsOutFileIndexCheckRequiredStr(CmdLine);
2091 return IsOutFileIndexCheckRequiredCase(CmdLine);
2094 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2095 bool IsJoin, raw_ostream& O)
2098 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2100 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
2102 O.indent(Indent2) << "bool HasChildren,\n";
2103 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2104 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2105 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2106 O.indent(Indent1) << "{\n";
2107 O.indent(Indent2) << "std::string cmd;\n";
2108 O.indent(Indent2) << "std::vector<std::string> vec;\n";
2109 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2110 O.indent(Indent2) << "const char* output_suffix = \""
2111 << D.OutputSuffix << "\";\n";
2114 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2115 // Tool::GenerateAction() method.
2116 void EmitGenerateActionMethod (const ToolDescription& D,
2117 const OptionDescriptions& OptDescs,
2118 bool IsJoin, raw_ostream& O) {
2120 EmitGenerateActionMethodHeader(D, IsJoin, O);
2123 throw "Tool " + D.Name + " has no cmd_line property!";
2125 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2126 O.indent(Indent2) << "int out_file_index"
2127 << (IndexCheckRequired ? " = -1" : "")
2130 // Process the cmd_line property.
2131 if (typeid(*D.CmdLine) == typeid(StringInit))
2132 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2134 EmitCaseConstructHandler(D.CmdLine, Indent2,
2135 EmitCmdLineVecFillCallback(IsJoin, D.Name),
2138 // For every understood option, emit handling code.
2140 EmitCaseConstructHandler(D.Actions, Indent2,
2141 EmitActionHandlersCallback(OptDescs),
2142 false, OptDescs, O);
2146 << "std::string out_file = OutFilename("
2147 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2148 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2150 if (IndexCheckRequired)
2151 O.indent(Indent2) << "if (out_file_index != -1)\n";
2152 O.indent(IndexCheckRequired ? Indent3 : Indent2)
2153 << "vec[out_file_index] = out_file;\n";
2155 // Handle the Sink property.
2157 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2158 O.indent(Indent3) << "vec.insert(vec.end(), "
2159 << SinkOptionName << ".begin(), " << SinkOptionName
2161 O.indent(Indent2) << "}\n";
2164 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2165 O.indent(Indent1) << "}\n\n";
2168 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2169 /// a given Tool class.
2170 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2171 const OptionDescriptions& OptDescs,
2173 if (!ToolDesc.isJoin()) {
2174 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2175 O.indent(Indent2) << "bool HasChildren,\n";
2176 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2177 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2178 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2179 O.indent(Indent1) << "{\n";
2180 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2181 << " is not a Join tool!\");\n";
2182 O.indent(Indent1) << "}\n\n";
2185 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2188 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2191 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2192 /// methods for a given Tool class.
2193 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2194 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2195 O.indent(Indent2) << "return InputLanguages_;\n";
2196 O.indent(Indent1) << "}\n\n";
2198 if (D.OutLanguage.empty())
2199 throw "Tool " + D.Name + " has no 'out_language' property!";
2201 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2202 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2203 O.indent(Indent1) << "}\n\n";
2206 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2207 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2208 O.indent(Indent1) << "const char* Name() const {\n";
2209 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2210 O.indent(Indent1) << "}\n\n";
2213 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2215 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2216 O.indent(Indent1) << "bool IsJoin() const {\n";
2218 O.indent(Indent2) << "return true;\n";
2220 O.indent(Indent2) << "return false;\n";
2221 O.indent(Indent1) << "}\n\n";
2224 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2225 /// given Tool class.
2226 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2227 if (D.InLanguage.empty())
2228 throw "Tool " + D.Name + " has no 'in_language' property!";
2230 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2231 for (StrVector::const_iterator B = D.InLanguage.begin(),
2232 E = D.InLanguage.end(); B != E; ++B)
2233 O << '\"' << *B << "\", ";
2237 /// EmitToolClassDefinition - Emit a Tool class definition.
2238 void EmitToolClassDefinition (const ToolDescription& D,
2239 const OptionDescriptions& OptDescs,
2241 if (D.Name == "root")
2245 O << "class " << D.Name << " : public ";
2251 O << " {\nprivate:\n";
2252 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2255 EmitNameMethod(D, O);
2256 EmitInOutLanguageMethods(D, O);
2257 EmitIsJoinMethod(D, O);
2258 EmitGenerateActionMethods(D, OptDescs, O);
2260 // Close class definition
2263 EmitStaticMemberDefinitions(D, O);
2267 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2268 /// and emit registration code.
2269 void EmitOptionDefinitions (const OptionDescriptions& descs,
2270 bool HasSink, bool HasExterns,
2273 std::vector<OptionDescription> Aliases;
2275 // Emit static cl::Option variables.
2276 for (OptionDescriptions::const_iterator B = descs.begin(),
2277 E = descs.end(); B!=E; ++B) {
2278 const OptionDescription& val = B->second;
2280 if (val.Type == OptionType::Alias) {
2281 Aliases.push_back(val);
2288 O << val.GenTypeDeclaration() << ' '
2289 << val.GenVariableName();
2291 if (val.isExtern()) {
2296 O << "(\"" << val.Name << "\"\n";
2298 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2299 O << ", cl::Prefix";
2301 if (val.isRequired()) {
2302 if (val.isList() && !val.isMultiVal())
2303 O << ", cl::OneOrMore";
2305 O << ", cl::Required";
2307 else if (val.isOneOrMore() && val.isList()) {
2308 O << ", cl::OneOrMore";
2310 else if (val.isOptional() && val.isList()) {
2311 O << ", cl::Optional";
2314 if (val.isReallyHidden())
2315 O << ", cl::ReallyHidden";
2316 else if (val.isHidden())
2317 O << ", cl::Hidden";
2319 if (val.isCommaSeparated())
2320 O << ", cl::CommaSeparated";
2322 if (val.MultiVal > 1)
2323 O << ", cl::multi_val(" << val.MultiVal << ')';
2326 const std::string& str = val.InitVal->getAsString();
2327 O << ", cl::init(" << str << ')';
2330 if (!val.Help.empty())
2331 O << ", cl::desc(\"" << val.Help << "\")";
2336 // Emit the aliases (they should go after all the 'proper' options).
2337 for (std::vector<OptionDescription>::const_iterator
2338 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2339 const OptionDescription& val = *B;
2341 O << val.GenTypeDeclaration() << ' '
2342 << val.GenVariableName()
2343 << "(\"" << val.Name << '\"';
2345 const OptionDescription& D = descs.FindOption(val.Help);
2346 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2348 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2351 // Emit the sink option.
2353 O << (HasExterns ? "extern cl" : "cl")
2354 << "::list<std::string> " << SinkOptionName
2355 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2360 /// EmitPreprocessOptionsCallback - Helper function passed to
2361 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2363 class EmitPreprocessOptionsCallback;
2366 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2367 (const DagInit&, unsigned, raw_ostream&) const;
2369 class EmitPreprocessOptionsCallback :
2370 public ActionHandlingCallbackBase,
2371 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2373 typedef EmitPreprocessOptionsCallbackHandler Handler;
2375 (EmitPreprocessOptionsCallback::* HandlerImpl)
2376 (const Init*, unsigned, raw_ostream&) const;
2378 const OptionDescriptions& OptDescs_;
2380 void onListOrDag(const DagInit& d, HandlerImpl h,
2381 unsigned IndentLevel, raw_ostream& O) const
2383 CheckNumberOfArguments(d, 1);
2384 const Init* I = d.getArg(0);
2386 // If I is a list, apply h to each element.
2387 if (typeid(*I) == typeid(ListInit)) {
2388 const ListInit& L = *static_cast<const ListInit*>(I);
2389 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2390 ((this)->*(h))(*B, IndentLevel, O);
2392 // Otherwise, apply h to I.
2394 ((this)->*(h))(I, IndentLevel, O);
2398 void onUnsetOptionImpl(const Init* I,
2399 unsigned IndentLevel, raw_ostream& O) const
2401 const std::string& OptName = InitPtrToString(I);
2402 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2404 if (OptDesc.isSwitch()) {
2405 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2407 else if (OptDesc.isParameter()) {
2408 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2410 else if (OptDesc.isList()) {
2411 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2414 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2418 void onUnsetOption(const DagInit& d,
2419 unsigned IndentLevel, raw_ostream& O) const
2421 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2425 void onSetOptionImpl(const DagInit& d,
2426 unsigned IndentLevel, raw_ostream& O) const {
2427 CheckNumberOfArguments(d, 2);
2428 const std::string& OptName = InitPtrToString(d.getArg(0));
2429 const Init* Value = d.getArg(1);
2430 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2432 if (OptDesc.isList()) {
2433 const ListInit& List = InitPtrToList(Value);
2435 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2436 for (ListInit::const_iterator B = List.begin(), E = List.end();
2438 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".push_back(\""
2439 << InitPtrToString(*B) << "\");\n";
2442 else if (OptDesc.isSwitch()) {
2443 CheckBooleanConstant(Value);
2444 O.indent(IndentLevel) << OptDesc.GenVariableName()
2445 << " = " << Value->getAsString() << ";\n";
2447 else if (OptDesc.isParameter()) {
2448 const std::string& Str = InitPtrToString(Value);
2449 O.indent(IndentLevel) << OptDesc.GenVariableName()
2450 << " = \"" << Str << "\";\n";
2453 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2457 void onSetSwitch(const Init* I,
2458 unsigned IndentLevel, raw_ostream& O) const {
2459 const std::string& OptName = InitPtrToString(I);
2460 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2462 if (OptDesc.isSwitch())
2463 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2465 throw "set_option: -" + OptName + " is not a switch option!";
2468 void onSetOption(const DagInit& d,
2469 unsigned IndentLevel, raw_ostream& O) const
2471 CheckNumberOfArguments(d, 1);
2473 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2474 // boolean, a string or a string list.
2475 if (d.getNumArgs() > 1)
2476 this->onSetOptionImpl(d, IndentLevel, O);
2477 // One argument: (set_option "switch")
2478 // or (set_option ["switch1", "switch2", ...])
2480 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2486 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2487 : OptDescs_(OptDescs)
2489 if (!staticMembersInitialized_) {
2490 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2491 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2492 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2493 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2495 staticMembersInitialized_ = true;
2499 void operator()(const Init* I,
2500 unsigned IndentLevel, raw_ostream& O) const
2502 InvokeDagInitHandler(this, I, IndentLevel, O);
2507 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2508 void EmitPreprocessOptions (const RecordKeeper& Records,
2509 const OptionDescriptions& OptDecs, raw_ostream& O)
2511 O << "void PreprocessOptionsLocal() {\n";
2513 const RecordVector& OptionPreprocessors =
2514 Records.getAllDerivedDefinitions("OptionPreprocessor");
2516 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2517 E = OptionPreprocessors.end(); B!=E; ++B) {
2518 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2519 EmitCaseConstructHandler(Case, Indent1,
2520 EmitPreprocessOptionsCallback(OptDecs),
2527 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2528 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2530 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2532 // Get the relevant field out of RecordKeeper
2533 const Record* LangMapRecord = Records.getDef("LanguageMap");
2535 // It is allowed for a plugin to have no language map.
2536 if (LangMapRecord) {
2538 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2539 if (!LangsToSuffixesList)
2540 throw "Error in the language map definition!";
2542 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2543 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2545 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2546 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2548 for (unsigned i = 0; i < Suffixes->size(); ++i)
2549 O.indent(Indent1) << "langMap[\""
2550 << InitPtrToString(Suffixes->getElement(i))
2551 << "\"] = \"" << Lang << "\";\n";
2558 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2559 /// by EmitEdgeClass().
2560 void IncDecWeight (const Init* i, unsigned IndentLevel,
2562 const DagInit& d = InitPtrToDag(i);
2563 const std::string& OpName = GetOperatorName(d);
2565 if (OpName == "inc_weight") {
2566 O.indent(IndentLevel) << "ret += ";
2568 else if (OpName == "dec_weight") {
2569 O.indent(IndentLevel) << "ret -= ";
2571 else if (OpName == "error") {
2572 CheckNumberOfArguments(d, 1);
2573 O.indent(IndentLevel) << "throw std::runtime_error(\""
2574 << InitPtrToString(d.getArg(0))
2579 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2580 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2583 if (d.getNumArgs() > 0)
2584 O << InitPtrToInt(d.getArg(0)) << ";\n";
2590 /// EmitEdgeClass - Emit a single Edge# class.
2591 void EmitEdgeClass (unsigned N, const std::string& Target,
2592 DagInit* Case, const OptionDescriptions& OptDescs,
2595 // Class constructor.
2596 O << "class Edge" << N << ": public Edge {\n"
2598 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2601 // Function Weight().
2603 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2604 O.indent(Indent2) << "unsigned ret = 0;\n";
2606 // Handle the 'case' construct.
2607 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2609 O.indent(Indent2) << "return ret;\n";
2610 O.indent(Indent1) << "}\n\n};\n\n";
2613 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2614 void EmitEdgeClasses (const RecordVector& EdgeVector,
2615 const OptionDescriptions& OptDescs,
2618 for (RecordVector::const_iterator B = EdgeVector.begin(),
2619 E = EdgeVector.end(); B != E; ++B) {
2620 const Record* Edge = *B;
2621 const std::string& NodeB = Edge->getValueAsString("b");
2622 DagInit& Weight = *Edge->getValueAsDag("weight");
2624 if (!IsDagEmpty(Weight))
2625 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2630 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2632 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2633 const ToolDescriptions& ToolDescs,
2636 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2638 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2639 E = ToolDescs.end(); B != E; ++B)
2640 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2647 for (RecordVector::const_iterator B = EdgeVector.begin(),
2648 E = EdgeVector.end(); B != E; ++B) {
2649 const Record* Edge = *B;
2650 const std::string& NodeA = Edge->getValueAsString("a");
2651 const std::string& NodeB = Edge->getValueAsString("b");
2652 DagInit& Weight = *Edge->getValueAsDag("weight");
2654 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2656 if (IsDagEmpty(Weight))
2657 O << "new SimpleEdge(\"" << NodeB << "\")";
2659 O << "new Edge" << i << "()";
2668 /// HookInfo - Information about the hook type and number of arguments.
2671 // A hook can either have a single parameter of type std::vector<std::string>,
2672 // or NumArgs parameters of type const char*.
2673 enum HookType { ListHook, ArgHook };
2678 HookInfo() : Type(ArgHook), NumArgs(1)
2681 HookInfo(HookType T) : Type(T), NumArgs(1)
2684 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2688 typedef llvm::StringMap<HookInfo> HookInfoMap;
2690 /// ExtractHookNames - Extract the hook names from all instances of
2691 /// $CALL(HookName) in the provided command line string/action. Helper
2692 /// function used by FillInHookNames().
2693 class ExtractHookNames {
2694 HookInfoMap& HookNames_;
2695 const OptionDescriptions& OptDescs_;
2697 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2698 : HookNames_(HookNames), OptDescs_(OptDescs)
2701 void onAction (const DagInit& Dag) {
2702 const std::string& Name = GetOperatorName(Dag);
2704 if (Name == "forward_transformed_value") {
2705 CheckNumberOfArguments(Dag, 2);
2706 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2707 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2708 const OptionDescription& D = OptDescs_.FindOption(OptName);
2710 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2711 : HookInfo::ArgHook);
2713 else if (Name == "append_cmd" || Name == "output_suffix") {
2714 CheckNumberOfArguments(Dag, 1);
2715 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2719 void onCmdLine(const std::string& Cmd) {
2721 TokenizeCmdLine(Cmd, cmds);
2723 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2725 const std::string& cmd = *B;
2727 if (cmd == "$CALL") {
2728 unsigned NumArgs = 0;
2729 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2730 const std::string& HookName = *B;
2732 if (HookName.at(0) == ')')
2733 throw "$CALL invoked with no arguments!";
2735 while (++B != E && B->at(0) != ')') {
2739 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2741 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2742 H->second.Type != HookInfo::ArgHook)
2743 throw "Overloading of hooks is not allowed. Overloaded hook: "
2746 HookNames_[HookName] = HookInfo(NumArgs);
2751 void operator()(const Init* Arg) {
2753 // We're invoked on an action (either a dag or a dag list).
2754 if (typeid(*Arg) == typeid(DagInit)) {
2755 const DagInit& Dag = InitPtrToDag(Arg);
2756 this->onAction(Dag);
2759 else if (typeid(*Arg) == typeid(ListInit)) {
2760 const ListInit& List = InitPtrToList(Arg);
2761 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2763 const DagInit& Dag = InitPtrToDag(*B);
2764 this->onAction(Dag);
2769 // We're invoked on a command line.
2770 this->onCmdLine(InitPtrToString(Arg));
2773 void operator()(const DagInit* Test, unsigned, bool) {
2774 this->operator()(Test);
2776 void operator()(const Init* Statement, unsigned) {
2777 this->operator()(Statement);
2781 /// FillInHookNames - Actually extract the hook names from all command
2782 /// line strings. Helper function used by EmitHookDeclarations().
2783 void FillInHookNames(const ToolDescriptions& ToolDescs,
2784 const OptionDescriptions& OptDescs,
2785 HookInfoMap& HookNames)
2787 // For all tool descriptions:
2788 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2789 E = ToolDescs.end(); B != E; ++B) {
2790 const ToolDescription& D = *(*B);
2792 // Look for 'forward_transformed_value' in 'actions'.
2794 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2796 // Look for hook invocations in 'cmd_line'.
2799 if (dynamic_cast<StringInit*>(D.CmdLine))
2800 // This is a string.
2801 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2803 // This is a 'case' construct.
2804 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2808 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2809 /// property records and emit hook function declaration for each
2810 /// instance of $CALL(HookName).
2811 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2812 const OptionDescriptions& OptDescs, raw_ostream& O) {
2813 HookInfoMap HookNames;
2815 FillInHookNames(ToolDescs, OptDescs, HookNames);
2816 if (HookNames.empty())
2819 O << "namespace hooks {\n";
2820 for (HookInfoMap::const_iterator B = HookNames.begin(),
2821 E = HookNames.end(); B != E; ++B) {
2822 const char* HookName = B->first();
2823 const HookInfo& Info = B->second;
2825 O.indent(Indent1) << "std::string " << HookName << "(";
2827 if (Info.Type == HookInfo::ArgHook) {
2828 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2829 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2833 O << "const std::vector<std::string>& Arg";
2841 /// EmitRegisterPlugin - Emit code to register this plugin.
2842 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2843 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2844 O.indent(Indent1) << "int Priority() const { return "
2845 << Priority << "; }\n\n";
2846 O.indent(Indent1) << "void PreprocessOptions() const\n";
2847 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2848 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2849 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2851 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2852 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2854 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2857 /// EmitIncludes - Emit necessary #include directives and some
2858 /// additional declarations.
2859 void EmitIncludes(raw_ostream& O) {
2860 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2861 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2862 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2863 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2864 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2866 << "#include \"llvm/Support/CommandLine.h\"\n"
2867 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2869 << "#include <algorithm>\n"
2870 << "#include <cstdlib>\n"
2871 << "#include <iterator>\n"
2872 << "#include <stdexcept>\n\n"
2874 << "using namespace llvm;\n"
2875 << "using namespace llvmc;\n\n"
2877 << "extern cl::opt<std::string> OutputFilename;\n\n"
2879 << "inline const char* checkCString(const char* s)\n"
2880 << "{ return s == NULL ? \"\" : s; }\n\n";
2884 /// PluginData - Holds all information about a plugin.
2886 OptionDescriptions OptDescs;
2889 ToolDescriptions ToolDescs;
2894 /// HasSink - Go through the list of tool descriptions and check if
2895 /// there are any with the 'sink' property set.
2896 bool HasSink(const ToolDescriptions& ToolDescs) {
2897 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2898 E = ToolDescs.end(); B != E; ++B)
2905 /// HasExterns - Go through the list of option descriptions and check
2906 /// if there are any external options.
2907 bool HasExterns(const OptionDescriptions& OptDescs) {
2908 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2909 E = OptDescs.end(); B != E; ++B)
2910 if (B->second.isExtern())
2916 /// CollectPluginData - Collect tool and option properties,
2917 /// compilation graph edges and plugin priority from the parse tree.
2918 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2919 // Collect option properties.
2920 const RecordVector& OptionLists =
2921 Records.getAllDerivedDefinitions("OptionList");
2922 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2925 // Collect tool properties.
2926 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2927 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2928 Data.HasSink = HasSink(Data.ToolDescs);
2929 Data.HasExterns = HasExterns(Data.OptDescs);
2931 // Collect compilation graph edges.
2932 const RecordVector& CompilationGraphs =
2933 Records.getAllDerivedDefinitions("CompilationGraph");
2934 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2937 // Calculate the priority of this plugin.
2938 const RecordVector& Priorities =
2939 Records.getAllDerivedDefinitions("PluginPriority");
2940 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2943 /// CheckPluginData - Perform some sanity checks on the collected data.
2944 void CheckPluginData(PluginData& Data) {
2945 // Filter out all tools not mentioned in the compilation graph.
2946 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2948 // Typecheck the compilation graph.
2949 TypecheckGraph(Data.Edges, Data.ToolDescs);
2951 // Check that there are no options without side effects (specified
2952 // only in the OptionList).
2953 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2956 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2957 // Emit file header.
2960 // Emit global option registration code.
2961 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2963 // Emit hook declarations.
2964 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2966 O << "namespace {\n\n";
2968 // Emit PreprocessOptionsLocal() function.
2969 EmitPreprocessOptions(Records, Data.OptDescs, O);
2971 // Emit PopulateLanguageMapLocal() function
2972 // (language map maps from file extensions to language names).
2973 EmitPopulateLanguageMap(Records, O);
2975 // Emit Tool classes.
2976 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2977 E = Data.ToolDescs.end(); B!=E; ++B)
2978 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2980 // Emit Edge# classes.
2981 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2983 // Emit PopulateCompilationGraphLocal() function.
2984 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2986 // Emit code for plugin registration.
2987 EmitRegisterPlugin(Data.Priority, O);
2989 O << "} // End anonymous namespace.\n\n";
2991 // Force linkage magic.
2992 O << "namespace llvmc {\n";
2993 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
3000 // End of anonymous namespace
3003 /// run - The back-end entry point.
3004 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
3008 CollectPluginData(Records, Data);
3009 CheckPluginData(Data);
3011 EmitSourceFileHeader("LLVMC Configuration Library", O);
3012 EmitPluginCode(Data, O);
3014 } catch (std::exception& Error) {
3015 throw Error.what() + std::string(" - usually this means a syntax error.");