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 /// OneOf - Does the input string contain this character?
140 bool OneOf(const char* lst, char c) {
148 template <class I, class S>
149 void CheckedIncrement(I& P, I E, S ErrorString) {
155 // apply is needed because C++'s syntax doesn't let us construct a function
156 // object and call it in the same statement.
157 template<typename F, typename T0>
158 void apply(F Fun, T0& Arg0) {
162 template<typename F, typename T0, typename T1>
163 void apply(F Fun, T0& Arg0, T1& Arg1) {
164 return Fun(Arg0, Arg1);
167 //===----------------------------------------------------------------------===//
168 /// Back-end specific code
171 /// OptionType - One of six different option types. See the
172 /// documentation for detailed description of differences.
173 namespace OptionType {
175 enum OptionType { Alias, Switch, Parameter, ParameterList,
178 bool IsAlias(OptionType t) {
182 bool IsList (OptionType t) {
183 return (t == ParameterList || t == PrefixList);
186 bool IsSwitch (OptionType t) {
187 return (t == Switch);
190 bool IsParameter (OptionType t) {
191 return (t == Parameter || t == Prefix);
196 OptionType::OptionType stringToOptionType(const std::string& T) {
197 if (T == "alias_option")
198 return OptionType::Alias;
199 else if (T == "switch_option")
200 return OptionType::Switch;
201 else if (T == "parameter_option")
202 return OptionType::Parameter;
203 else if (T == "parameter_list_option")
204 return OptionType::ParameterList;
205 else if (T == "prefix_option")
206 return OptionType::Prefix;
207 else if (T == "prefix_list_option")
208 return OptionType::PrefixList;
210 throw "Unknown option type: " + T + '!';
213 namespace OptionDescriptionFlags {
214 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
215 ReallyHidden = 0x4, Extern = 0x8,
216 OneOrMore = 0x10, Optional = 0x20,
217 CommaSeparated = 0x40 };
220 /// OptionDescription - Represents data contained in a single
221 /// OptionList entry.
222 struct OptionDescription {
223 OptionType::OptionType Type;
230 OptionDescription(OptionType::OptionType t = OptionType::Switch,
231 const std::string& n = "",
232 const std::string& h = DefaultHelpString)
233 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
236 /// GenTypeDeclaration - Returns the C++ variable type of this
238 const char* GenTypeDeclaration() const;
240 /// GenVariableName - Returns the variable name used in the
241 /// generated C++ code.
242 std::string GenVariableName() const;
244 /// Merge - Merge two option descriptions.
245 void Merge (const OptionDescription& other);
247 // Misc convenient getters/setters.
249 bool isAlias() const;
251 bool isMultiVal() const;
253 bool isCommaSeparated() const;
254 void setCommaSeparated();
256 bool isExtern() const;
259 bool isRequired() const;
262 bool isOneOrMore() const;
265 bool isOptional() const;
268 bool isHidden() const;
271 bool isReallyHidden() const;
272 void setReallyHidden();
274 bool isSwitch() const
275 { return OptionType::IsSwitch(this->Type); }
277 bool isParameter() const
278 { return OptionType::IsParameter(this->Type); }
281 { return OptionType::IsList(this->Type); }
285 void OptionDescription::Merge (const OptionDescription& other)
287 if (other.Type != Type)
288 throw "Conflicting definitions for the option " + Name + "!";
290 if (Help == other.Help || Help == DefaultHelpString)
292 else if (other.Help != DefaultHelpString) {
293 llvm::errs() << "Warning: several different help strings"
294 " defined for option " + Name + "\n";
297 Flags |= other.Flags;
300 bool OptionDescription::isAlias() const {
301 return OptionType::IsAlias(this->Type);
304 bool OptionDescription::isMultiVal() const {
308 bool OptionDescription::isCommaSeparated() const {
309 return Flags & OptionDescriptionFlags::CommaSeparated;
311 void OptionDescription::setCommaSeparated() {
312 Flags |= OptionDescriptionFlags::CommaSeparated;
315 bool OptionDescription::isExtern() const {
316 return Flags & OptionDescriptionFlags::Extern;
318 void OptionDescription::setExtern() {
319 Flags |= OptionDescriptionFlags::Extern;
322 bool OptionDescription::isRequired() const {
323 return Flags & OptionDescriptionFlags::Required;
325 void OptionDescription::setRequired() {
326 Flags |= OptionDescriptionFlags::Required;
329 bool OptionDescription::isOneOrMore() const {
330 return Flags & OptionDescriptionFlags::OneOrMore;
332 void OptionDescription::setOneOrMore() {
333 Flags |= OptionDescriptionFlags::OneOrMore;
336 bool OptionDescription::isOptional() const {
337 return Flags & OptionDescriptionFlags::Optional;
339 void OptionDescription::setOptional() {
340 Flags |= OptionDescriptionFlags::Optional;
343 bool OptionDescription::isHidden() const {
344 return Flags & OptionDescriptionFlags::Hidden;
346 void OptionDescription::setHidden() {
347 Flags |= OptionDescriptionFlags::Hidden;
350 bool OptionDescription::isReallyHidden() const {
351 return Flags & OptionDescriptionFlags::ReallyHidden;
353 void OptionDescription::setReallyHidden() {
354 Flags |= OptionDescriptionFlags::ReallyHidden;
357 const char* OptionDescription::GenTypeDeclaration() const {
359 case OptionType::Alias:
361 case OptionType::PrefixList:
362 case OptionType::ParameterList:
363 return "cl::list<std::string>";
364 case OptionType::Switch:
365 return "cl::opt<bool>";
366 case OptionType::Parameter:
367 case OptionType::Prefix:
369 return "cl::opt<std::string>";
373 std::string OptionDescription::GenVariableName() const {
374 const std::string& EscapedName = EscapeVariableName(Name);
376 case OptionType::Alias:
377 return "AutoGeneratedAlias_" + EscapedName;
378 case OptionType::PrefixList:
379 case OptionType::ParameterList:
380 return "AutoGeneratedList_" + EscapedName;
381 case OptionType::Switch:
382 return "AutoGeneratedSwitch_" + EscapedName;
383 case OptionType::Prefix:
384 case OptionType::Parameter:
386 return "AutoGeneratedParameter_" + EscapedName;
390 /// OptionDescriptions - An OptionDescription array plus some helper
392 class OptionDescriptions {
393 typedef StringMap<OptionDescription> container_type;
395 /// Descriptions - A list of OptionDescriptions.
396 container_type Descriptions;
399 /// FindOption - exception-throwing wrapper for find().
400 const OptionDescription& FindOption(const std::string& OptName) const;
402 // Wrappers for FindOption that throw an exception in case the option has a
404 const OptionDescription& FindSwitch(const std::string& OptName) const;
405 const OptionDescription& FindParameter(const std::string& OptName) const;
406 const OptionDescription& FindList(const std::string& OptName) const;
407 const OptionDescription&
408 FindListOrParameter(const std::string& OptName) const;
410 /// insertDescription - Insert new OptionDescription into
411 /// OptionDescriptions list
412 void InsertDescription (const OptionDescription& o);
414 // Support for STL-style iteration
415 typedef container_type::const_iterator const_iterator;
416 const_iterator begin() const { return Descriptions.begin(); }
417 const_iterator end() const { return Descriptions.end(); }
420 const OptionDescription&
421 OptionDescriptions::FindOption(const std::string& OptName) const {
422 const_iterator I = Descriptions.find(OptName);
423 if (I != Descriptions.end())
426 throw OptName + ": no such option!";
429 const OptionDescription&
430 OptionDescriptions::FindSwitch(const std::string& OptName) const {
431 const OptionDescription& OptDesc = this->FindOption(OptName);
432 if (!OptDesc.isSwitch())
433 throw OptName + ": incorrect option type - should be a switch!";
437 const OptionDescription&
438 OptionDescriptions::FindList(const std::string& OptName) const {
439 const OptionDescription& OptDesc = this->FindOption(OptName);
440 if (!OptDesc.isList())
441 throw OptName + ": incorrect option type - should be a list!";
445 const OptionDescription&
446 OptionDescriptions::FindParameter(const std::string& OptName) const {
447 const OptionDescription& OptDesc = this->FindOption(OptName);
448 if (!OptDesc.isParameter())
449 throw OptName + ": incorrect option type - should be a parameter!";
453 const OptionDescription&
454 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
455 const OptionDescription& OptDesc = this->FindOption(OptName);
456 if (!OptDesc.isList() && !OptDesc.isParameter())
458 + ": incorrect option type - should be a list or parameter!";
462 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
463 container_type::iterator I = Descriptions.find(o.Name);
464 if (I != Descriptions.end()) {
465 OptionDescription& D = I->second;
469 Descriptions[o.Name] = o;
473 /// HandlerTable - A base class for function objects implemented as
474 /// 'tables of handlers'.
475 template <typename Handler>
478 // Implementation details.
480 /// HandlerMap - A map from property names to property handlers
481 typedef StringMap<Handler> HandlerMap;
483 static HandlerMap Handlers_;
484 static bool staticMembersInitialized_;
488 Handler GetHandler (const std::string& HandlerName) const {
489 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
491 if (method != Handlers_.end()) {
492 Handler h = method->second;
496 throw "No handler found for property " + HandlerName + "!";
500 void AddHandler(const char* Property, Handler H) {
501 Handlers_[Property] = H;
506 template <class Handler, class FunctionObject>
507 Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) {
508 const std::string& HandlerName = GetOperatorName(Dag);
509 return Obj->GetHandler(HandlerName);
512 template <class FunctionObject>
513 void InvokeDagInitHandler(FunctionObject* Obj, Init* I) {
514 typedef void (FunctionObject::*Handler) (const DagInit&);
516 const DagInit& Dag = InitPtrToDag(I);
517 Handler h = GetHandler<Handler>(Obj, Dag);
522 template <class FunctionObject>
523 void InvokeDagInitHandler(const FunctionObject* const Obj,
524 const Init* I, unsigned IndentLevel, raw_ostream& O)
526 typedef void (FunctionObject::*Handler)
527 (const DagInit&, unsigned IndentLevel, raw_ostream& O) const;
529 const DagInit& Dag = InitPtrToDag(I);
530 Handler h = GetHandler<Handler>(Obj, Dag);
532 ((Obj)->*(h))(Dag, IndentLevel, O);
536 template <typename H>
537 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
539 template <typename H>
540 bool HandlerTable<H>::staticMembersInitialized_ = false;
543 /// CollectOptionProperties - Function object for iterating over an
544 /// option property list.
545 class CollectOptionProperties;
546 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
549 class CollectOptionProperties
550 : public HandlerTable<CollectOptionPropertiesHandler>
554 /// optDescs_ - OptionDescriptions table. This is where the
555 /// information is stored.
556 OptionDescription& optDesc_;
560 explicit CollectOptionProperties(OptionDescription& OD)
563 if (!staticMembersInitialized_) {
564 AddHandler("extern", &CollectOptionProperties::onExtern);
565 AddHandler("help", &CollectOptionProperties::onHelp);
566 AddHandler("hidden", &CollectOptionProperties::onHidden);
567 AddHandler("init", &CollectOptionProperties::onInit);
568 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
569 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
570 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
571 AddHandler("required", &CollectOptionProperties::onRequired);
572 AddHandler("optional", &CollectOptionProperties::onOptional);
573 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
575 staticMembersInitialized_ = true;
579 /// operator() - Just forwards to the corresponding property
581 void operator() (Init* I) {
582 InvokeDagInitHandler(this, I);
587 /// Option property handlers --
588 /// Methods that handle option properties such as (help) or (hidden).
590 void onExtern (const DagInit& d) {
591 CheckNumberOfArguments(d, 0);
592 optDesc_.setExtern();
595 void onHelp (const DagInit& d) {
596 CheckNumberOfArguments(d, 1);
597 optDesc_.Help = InitPtrToString(d.getArg(0));
600 void onHidden (const DagInit& d) {
601 CheckNumberOfArguments(d, 0);
602 optDesc_.setHidden();
605 void onReallyHidden (const DagInit& d) {
606 CheckNumberOfArguments(d, 0);
607 optDesc_.setReallyHidden();
610 void onCommaSeparated (const DagInit& d) {
611 CheckNumberOfArguments(d, 0);
612 if (!optDesc_.isList())
613 throw "'comma_separated' is valid only on list options!";
614 optDesc_.setCommaSeparated();
617 void onRequired (const DagInit& d) {
618 CheckNumberOfArguments(d, 0);
619 if (optDesc_.isOneOrMore() || optDesc_.isOptional())
620 throw "Only one of (required), (optional) or "
621 "(one_or_more) properties is allowed!";
622 optDesc_.setRequired();
625 void onInit (const DagInit& d) {
626 CheckNumberOfArguments(d, 1);
627 Init* i = d.getArg(0);
628 const std::string& str = i->getAsString();
630 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
631 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
634 throw "Incorrect usage of the 'init' option property!";
636 optDesc_.InitVal = i;
639 void onOneOrMore (const DagInit& d) {
640 CheckNumberOfArguments(d, 0);
641 if (optDesc_.isRequired() || optDesc_.isOptional())
642 throw "Only one of (required), (optional) or "
643 "(one_or_more) properties is allowed!";
644 if (!OptionType::IsList(optDesc_.Type))
645 llvm::errs() << "Warning: specifying the 'one_or_more' property "
646 "on a non-list option will have no effect.\n";
647 optDesc_.setOneOrMore();
650 void onOptional (const DagInit& d) {
651 CheckNumberOfArguments(d, 0);
652 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
653 throw "Only one of (required), (optional) or "
654 "(one_or_more) properties is allowed!";
655 if (!OptionType::IsList(optDesc_.Type))
656 llvm::errs() << "Warning: specifying the 'optional' property"
657 "on a non-list option will have no effect.\n";
658 optDesc_.setOptional();
661 void onMultiVal (const DagInit& d) {
662 CheckNumberOfArguments(d, 1);
663 int val = InitPtrToInt(d.getArg(0));
665 throw "Error in the 'multi_val' property: "
666 "the value must be greater than 1!";
667 if (!OptionType::IsList(optDesc_.Type))
668 throw "The multi_val property is valid only on list options!";
669 optDesc_.MultiVal = val;
674 /// AddOption - A function object that is applied to every option
675 /// description. Used by CollectOptionDescriptions.
678 OptionDescriptions& OptDescs_;
681 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
684 void operator()(const Init* i) {
685 const DagInit& d = InitPtrToDag(i);
686 CheckNumberOfArguments(d, 1);
688 const OptionType::OptionType Type =
689 stringToOptionType(GetOperatorName(d));
690 const std::string& Name = InitPtrToString(d.getArg(0));
692 OptionDescription OD(Type, Name);
695 CheckNumberOfArguments(d, 2);
698 // Aliases store the aliased option name in the 'Help' field.
699 OD.Help = InitPtrToString(d.getArg(1));
701 else if (!OD.isExtern()) {
702 processOptionProperties(d, OD);
704 OptDescs_.InsertDescription(OD);
708 /// processOptionProperties - Go through the list of option
709 /// properties and call a corresponding handler for each.
710 static void processOptionProperties (const DagInit& d, OptionDescription& o) {
711 CheckNumberOfArguments(d, 2);
712 DagInit::const_arg_iterator B = d.arg_begin();
713 // Skip the first argument: it's always the option name.
715 std::for_each(B, d.arg_end(), CollectOptionProperties(o));
720 /// CollectOptionDescriptions - Collects option properties from all
722 void CollectOptionDescriptions (RecordVector::const_iterator B,
723 RecordVector::const_iterator E,
724 OptionDescriptions& OptDescs)
726 // For every OptionList:
728 RecordVector::value_type T = *B;
729 // Throws an exception if the value does not exist.
730 ListInit* PropList = T->getValueAsListInit("options");
732 // For every option description in this list:
733 // collect the information and
734 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
738 // Tool information record
740 namespace ToolFlags {
741 enum ToolFlags { Join = 0x1, Sink = 0x2 };
744 struct ToolDescription : public RefCountedBase<ToolDescription> {
748 StrVector InLanguage;
749 std::string OutLanguage;
750 std::string OutputSuffix;
753 // Various boolean properties
754 void setSink() { Flags |= ToolFlags::Sink; }
755 bool isSink() const { return Flags & ToolFlags::Sink; }
756 void setJoin() { Flags |= ToolFlags::Join; }
757 bool isJoin() const { return Flags & ToolFlags::Join; }
759 // Default ctor here is needed because StringMap can only store
760 // DefaultConstructible objects
761 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
762 ToolDescription (const std::string& n)
763 : Name(n), CmdLine(0), Actions(0), Flags(0)
767 /// ToolDescriptions - A list of Tool information records.
768 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
771 /// CollectToolProperties - Function object for iterating over a list of
772 /// tool property records.
774 class CollectToolProperties;
775 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
778 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
782 /// toolDesc_ - Properties of the current Tool. This is where the
783 /// information is stored.
784 ToolDescription& toolDesc_;
788 explicit CollectToolProperties (ToolDescription& d)
791 if (!staticMembersInitialized_) {
793 AddHandler("actions", &CollectToolProperties::onActions);
794 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
795 AddHandler("in_language", &CollectToolProperties::onInLanguage);
796 AddHandler("join", &CollectToolProperties::onJoin);
797 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
798 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
799 AddHandler("sink", &CollectToolProperties::onSink);
801 staticMembersInitialized_ = true;
805 void operator() (Init* I) {
806 InvokeDagInitHandler(this, I);
811 /// Property handlers --
812 /// Functions that extract information about tool properties from
813 /// DAG representation.
815 void onActions (const DagInit& d) {
816 CheckNumberOfArguments(d, 1);
817 Init* Case = d.getArg(0);
818 if (typeid(*Case) != typeid(DagInit) ||
819 GetOperatorName(static_cast<DagInit&>(*Case)) != "case")
820 throw "The argument to (actions) should be a 'case' construct!";
821 toolDesc_.Actions = Case;
824 void onCmdLine (const DagInit& d) {
825 CheckNumberOfArguments(d, 1);
826 toolDesc_.CmdLine = d.getArg(0);
829 void onInLanguage (const DagInit& d) {
830 CheckNumberOfArguments(d, 1);
831 Init* arg = d.getArg(0);
833 // Find out the argument's type.
834 if (typeid(*arg) == typeid(StringInit)) {
836 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
840 const ListInit& lst = InitPtrToList(arg);
841 StrVector& out = toolDesc_.InLanguage;
843 // Copy strings to the output vector.
844 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
846 out.push_back(InitPtrToString(*B));
849 // Remove duplicates.
850 std::sort(out.begin(), out.end());
851 StrVector::iterator newE = std::unique(out.begin(), out.end());
852 out.erase(newE, out.end());
856 void onJoin (const DagInit& d) {
857 CheckNumberOfArguments(d, 0);
861 void onOutLanguage (const DagInit& d) {
862 CheckNumberOfArguments(d, 1);
863 toolDesc_.OutLanguage = InitPtrToString(d.getArg(0));
866 void onOutputSuffix (const DagInit& d) {
867 CheckNumberOfArguments(d, 1);
868 toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0));
871 void onSink (const DagInit& d) {
872 CheckNumberOfArguments(d, 0);
878 /// CollectToolDescriptions - Gather information about tool properties
879 /// from the parsed TableGen data (basically a wrapper for the
880 /// CollectToolProperties function object).
881 void CollectToolDescriptions (RecordVector::const_iterator B,
882 RecordVector::const_iterator E,
883 ToolDescriptions& ToolDescs)
885 // Iterate over a properties list of every Tool definition
887 const Record* T = *B;
888 // Throws an exception if the value does not exist.
889 ListInit* PropList = T->getValueAsListInit("properties");
891 IntrusiveRefCntPtr<ToolDescription>
892 ToolDesc(new ToolDescription(T->getName()));
894 std::for_each(PropList->begin(), PropList->end(),
895 CollectToolProperties(*ToolDesc));
896 ToolDescs.push_back(ToolDesc);
900 /// FillInEdgeVector - Merge all compilation graph definitions into
901 /// one single edge list.
902 void FillInEdgeVector(RecordVector::const_iterator B,
903 RecordVector::const_iterator E, RecordVector& Out) {
904 for (; B != E; ++B) {
905 const ListInit* edges = (*B)->getValueAsListInit("edges");
907 for (unsigned i = 0; i < edges->size(); ++i)
908 Out.push_back(edges->getElementAsRecord(i));
912 /// CalculatePriority - Calculate the priority of this plugin.
913 int CalculatePriority(RecordVector::const_iterator B,
914 RecordVector::const_iterator E) {
918 priority = static_cast<int>((*B)->getValueAsInt("priority"));
921 throw "More than one 'PluginPriority' instance found: "
922 "most probably an error!";
928 /// NotInGraph - Helper function object for FilterNotInGraph.
931 const llvm::StringSet<>& ToolsInGraph_;
934 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
935 : ToolsInGraph_(ToolsInGraph)
938 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
939 return (ToolsInGraph_.count(x->Name) == 0);
943 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
944 /// mentioned in the compilation graph definition.
945 void FilterNotInGraph (const RecordVector& EdgeVector,
946 ToolDescriptions& ToolDescs) {
948 // List all tools mentioned in the graph.
949 llvm::StringSet<> ToolsInGraph;
951 for (RecordVector::const_iterator B = EdgeVector.begin(),
952 E = EdgeVector.end(); B != E; ++B) {
954 const Record* Edge = *B;
955 const std::string& NodeA = Edge->getValueAsString("a");
956 const std::string& NodeB = Edge->getValueAsString("b");
959 ToolsInGraph.insert(NodeA);
960 ToolsInGraph.insert(NodeB);
963 // Filter ToolPropertiesList.
964 ToolDescriptions::iterator new_end =
965 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
966 NotInGraph(ToolsInGraph));
967 ToolDescs.erase(new_end, ToolDescs.end());
970 /// FillInToolToLang - Fills in two tables that map tool names to
971 /// (input, output) languages. Helper function used by TypecheckGraph().
972 void FillInToolToLang (const ToolDescriptions& ToolDescs,
973 StringMap<StringSet<> >& ToolToInLang,
974 StringMap<std::string>& ToolToOutLang) {
975 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
976 E = ToolDescs.end(); B != E; ++B) {
977 const ToolDescription& D = *(*B);
978 for (StrVector::const_iterator B = D.InLanguage.begin(),
979 E = D.InLanguage.end(); B != E; ++B)
980 ToolToInLang[D.Name].insert(*B);
981 ToolToOutLang[D.Name] = D.OutLanguage;
985 /// TypecheckGraph - Check that names for output and input languages
986 /// on all edges do match. This doesn't do much when the information
987 /// about the whole graph is not available (i.e. when compiling most
989 void TypecheckGraph (const RecordVector& EdgeVector,
990 const ToolDescriptions& ToolDescs) {
991 StringMap<StringSet<> > ToolToInLang;
992 StringMap<std::string> ToolToOutLang;
994 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
995 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
996 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
998 for (RecordVector::const_iterator B = EdgeVector.begin(),
999 E = EdgeVector.end(); B != E; ++B) {
1000 const Record* Edge = *B;
1001 const std::string& NodeA = Edge->getValueAsString("a");
1002 const std::string& NodeB = Edge->getValueAsString("b");
1003 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
1004 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
1006 if (NodeA != "root") {
1007 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
1008 throw "Edge " + NodeA + "->" + NodeB
1009 + ": output->input language mismatch";
1012 if (NodeB == "root")
1013 throw "Edges back to the root are not allowed!";
1017 /// WalkCase - Walks the 'case' expression DAG and invokes
1018 /// TestCallback on every test, and StatementCallback on every
1019 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
1020 /// combinators (that is, they are passed directly to TestCallback).
1021 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1022 /// IndentLevel, bool FirstTest)'.
1023 /// StatementCallback must have type 'void StatementCallback(const Init*,
1024 /// unsigned IndentLevel)'.
1025 template <typename F1, typename F2>
1026 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1027 unsigned IndentLevel = 0)
1029 const DagInit& d = InitPtrToDag(Case);
1032 if (GetOperatorName(d) != "case")
1033 throw "WalkCase should be invoked only on 'case' expressions!";
1035 if (d.getNumArgs() < 2)
1036 throw "There should be at least one clause in the 'case' expression:\n"
1041 const unsigned numArgs = d.getNumArgs();
1043 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1050 const DagInit& Test = InitPtrToDag(arg);
1052 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1053 throw "The 'default' clause should be the last in the "
1054 "'case' construct!";
1056 throw "Case construct handler: no corresponding action "
1057 "found for the test " + Test.getAsString() + '!';
1059 TestCallback(Test, IndentLevel, (i == 1));
1063 if (dynamic_cast<DagInit*>(arg)
1064 && GetOperatorName(static_cast<DagInit&>(*arg)) == "case") {
1066 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1069 // Handle statement.
1070 StatementCallback(arg, IndentLevel);
1078 /// ExtractOptionNames - A helper function object used by
1079 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1080 class ExtractOptionNames {
1081 llvm::StringSet<>& OptionNames_;
1083 void processDag(const Init* Statement) {
1084 const DagInit& Stmt = InitPtrToDag(Statement);
1085 const std::string& ActionName = GetOperatorName(Stmt);
1086 if (ActionName == "forward" || ActionName == "forward_as" ||
1087 ActionName == "forward_value" ||
1088 ActionName == "forward_transformed_value" ||
1089 ActionName == "switch_on" || ActionName == "parameter_equals" ||
1090 ActionName == "element_in_list" || ActionName == "not_empty" ||
1091 ActionName == "empty") {
1092 CheckNumberOfArguments(Stmt, 1);
1093 const std::string& Name = InitPtrToString(Stmt.getArg(0));
1094 OptionNames_.insert(Name);
1096 else if (ActionName == "and" || ActionName == "or") {
1097 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1098 this->processDag(Stmt.getArg(i));
1104 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1107 void operator()(const Init* Statement) {
1108 if (typeid(*Statement) == typeid(ListInit)) {
1109 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1110 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1112 this->processDag(*B);
1115 this->processDag(Statement);
1119 void operator()(const DagInit& Test, unsigned, bool) {
1120 this->operator()(&Test);
1122 void operator()(const Init* Statement, unsigned) {
1123 this->operator()(Statement);
1127 /// CheckForSuperfluousOptions - Check that there are no side
1128 /// effect-free options (specified only in the OptionList). Otherwise,
1129 /// output a warning.
1130 void CheckForSuperfluousOptions (const RecordVector& Edges,
1131 const ToolDescriptions& ToolDescs,
1132 const OptionDescriptions& OptDescs) {
1133 llvm::StringSet<> nonSuperfluousOptions;
1135 // Add all options mentioned in the ToolDesc.Actions to the set of
1136 // non-superfluous options.
1137 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1138 E = ToolDescs.end(); B != E; ++B) {
1139 const ToolDescription& TD = *(*B);
1140 ExtractOptionNames Callback(nonSuperfluousOptions);
1142 WalkCase(TD.Actions, Callback, Callback);
1145 // Add all options mentioned in the 'case' clauses of the
1146 // OptionalEdges of the compilation graph to the set of
1147 // non-superfluous options.
1148 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1150 const Record* Edge = *B;
1151 DagInit& Weight = *Edge->getValueAsDag("weight");
1153 if (!IsDagEmpty(Weight))
1154 WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1157 // Check that all options in OptDescs belong to the set of
1158 // non-superfluous options.
1159 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1160 E = OptDescs.end(); B != E; ++B) {
1161 const OptionDescription& Val = B->second;
1162 if (!nonSuperfluousOptions.count(Val.Name)
1163 && Val.Type != OptionType::Alias)
1164 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1165 "Probable cause: this option is specified only in the OptionList.\n";
1169 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1170 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1171 if (TestName == "single_input_file") {
1172 O << "InputFilenames.size() == 1";
1175 else if (TestName == "multiple_input_files") {
1176 O << "InputFilenames.size() > 1";
1183 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1184 template <typename F>
1185 void EmitListTest(const ListInit& L, const char* LogicOp,
1186 F Callback, raw_ostream& O)
1188 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1190 bool isFirst = true;
1191 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1196 Callback(InitPtrToString(*B), O);
1200 // Callbacks for use with EmitListTest.
1202 class EmitSwitchOn {
1203 const OptionDescriptions& OptDescs_;
1205 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1208 void operator()(const std::string& OptName, raw_ostream& O) const {
1209 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1210 O << OptDesc.GenVariableName();
1214 class EmitEmptyTest {
1216 const OptionDescriptions& OptDescs_;
1218 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1219 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1222 void operator()(const std::string& OptName, raw_ostream& O) const {
1223 const char* Neg = (EmitNegate_ ? "!" : "");
1224 if (OptName == "o") {
1225 O << Neg << "OutputFilename.empty()";
1227 else if (OptName == "save-temps") {
1228 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1231 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1232 O << Neg << OptDesc.GenVariableName() << ".empty()";
1238 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1239 bool EmitCaseTest1ArgList(const std::string& TestName,
1241 const OptionDescriptions& OptDescs,
1243 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1245 if (TestName == "any_switch_on") {
1246 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1249 else if (TestName == "switch_on") {
1250 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1253 else if (TestName == "any_not_empty") {
1254 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1257 else if (TestName == "any_empty") {
1258 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1261 else if (TestName == "not_empty") {
1262 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1265 else if (TestName == "empty") {
1266 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1273 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1274 bool EmitCaseTest1ArgStr(const std::string& TestName,
1276 const OptionDescriptions& OptDescs,
1278 const std::string& OptName = InitPtrToString(d.getArg(0));
1280 if (TestName == "switch_on") {
1281 apply(EmitSwitchOn(OptDescs), OptName, O);
1284 else if (TestName == "input_languages_contain") {
1285 O << "InLangs.count(\"" << OptName << "\") != 0";
1288 else if (TestName == "in_language") {
1289 // This works only for single-argument Tool::GenerateAction. Join
1290 // tools can process several files in different languages simultaneously.
1292 // TODO: make this work with Edge::Weight (if possible).
1293 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1296 else if (TestName == "not_empty" || TestName == "empty") {
1297 bool EmitNegate = (TestName == "not_empty");
1298 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1305 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1306 bool EmitCaseTest1Arg(const std::string& TestName,
1308 const OptionDescriptions& OptDescs,
1310 CheckNumberOfArguments(d, 1);
1311 if (typeid(*d.getArg(0)) == typeid(ListInit))
1312 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1314 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1317 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1318 bool EmitCaseTest2Args(const std::string& TestName,
1320 unsigned IndentLevel,
1321 const OptionDescriptions& OptDescs,
1323 CheckNumberOfArguments(d, 2);
1324 const std::string& OptName = InitPtrToString(d.getArg(0));
1325 const std::string& OptArg = InitPtrToString(d.getArg(1));
1327 if (TestName == "parameter_equals") {
1328 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1329 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1332 else if (TestName == "element_in_list") {
1333 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1334 const std::string& VarName = OptDesc.GenVariableName();
1335 O << "std::find(" << VarName << ".begin(),\n";
1336 O.indent(IndentLevel + Indent1)
1337 << VarName << ".end(), \""
1338 << OptArg << "\") != " << VarName << ".end()";
1345 // Forward declaration.
1346 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1347 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1348 const OptionDescriptions& OptDescs,
1351 /// EmitLogicalOperationTest - Helper function used by
1352 /// EmitCaseConstructHandler.
1353 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1354 unsigned IndentLevel,
1355 const OptionDescriptions& OptDescs,
1358 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1359 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1360 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1361 if (j != NumArgs - 1) {
1363 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1371 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1372 const OptionDescriptions& OptDescs, raw_ostream& O)
1374 CheckNumberOfArguments(d, 1);
1375 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1377 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1381 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1382 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1383 const OptionDescriptions& OptDescs,
1385 const std::string& TestName = GetOperatorName(d);
1387 if (TestName == "and")
1388 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1389 else if (TestName == "or")
1390 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1391 else if (TestName == "not")
1392 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1393 else if (EmitCaseTest0Args(TestName, O))
1395 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1397 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1400 throw TestName + ": unknown edge property!";
1404 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1405 class EmitCaseTestCallback {
1407 const OptionDescriptions& OptDescs_;
1411 EmitCaseTestCallback(bool EmitElseIf,
1412 const OptionDescriptions& OptDescs, raw_ostream& O)
1413 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1416 void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest)
1418 if (GetOperatorName(Test) == "default") {
1419 O_.indent(IndentLevel) << "else {\n";
1422 O_.indent(IndentLevel)
1423 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1424 EmitCaseTest(Test, IndentLevel, OptDescs_, O_);
1430 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1431 template <typename F>
1432 class EmitCaseStatementCallback {
1437 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1438 : Callback_(Callback), O_(O)
1441 void operator() (const Init* Statement, unsigned IndentLevel) {
1443 // Ignore nested 'case' DAG.
1444 if (!(dynamic_cast<const DagInit*>(Statement) &&
1445 GetOperatorName(static_cast<const DagInit&>(*Statement)) == "case")) {
1446 if (typeid(*Statement) == typeid(ListInit)) {
1447 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1448 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1450 Callback_(*B, (IndentLevel + Indent1), O_);
1453 Callback_(Statement, (IndentLevel + Indent1), O_);
1456 O_.indent(IndentLevel) << "}\n";
1461 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1462 /// construct. Takes a function object that should emit code for every case
1463 /// clause. Implemented on top of WalkCase.
1464 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1465 /// raw_ostream& O).
1466 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1467 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1469 template <typename F>
1470 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1471 F Callback, bool EmitElseIf,
1472 const OptionDescriptions& OptDescs,
1474 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1475 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1478 /// TokenizeCmdLine - converts from
1479 /// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to
1480 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"].
1481 void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) {
1482 const char* Delimiters = " \t\n\v\f\r";
1484 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1487 if (CmdLine.empty())
1491 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1494 for (; B != E; ++B) {
1495 char cur_ch = CmdLine[B];
1499 if (cur_ch == '$') {
1500 cur_st = SpecialCommand;
1503 if (OneOf(Delimiters, cur_ch)) {
1505 B = CmdLine.find_first_not_of(Delimiters, B);
1506 if (B == std::string::npos) {
1517 case SpecialCommand:
1518 if (OneOf(Delimiters, cur_ch)) {
1523 if (cur_ch == '(') {
1525 cur_st = InsideSpecialCommand;
1530 case InsideSpecialCommand:
1531 if (OneOf(Delimiters, cur_ch)) {
1534 if (cur_ch == '\'') {
1535 cur_st = InsideQuotationMarks;
1539 if (cur_ch == ')') {
1543 if (cur_ch == ',') {
1549 case InsideQuotationMarks:
1550 if (cur_ch == '\'') {
1551 cur_st = InsideSpecialCommand;
1557 Out.back().push_back(cur_ch);
1561 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1562 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1563 /// SubstituteSpecialCommands().
1564 StrVector::const_iterator
1565 SubstituteCall (StrVector::const_iterator Pos,
1566 StrVector::const_iterator End,
1567 bool IsJoin, raw_ostream& O)
1569 const char* errorMessage = "Syntax error in $CALL invocation!";
1570 CheckedIncrement(Pos, End, errorMessage);
1571 const std::string& CmdName = *Pos;
1574 throw "$CALL invocation: empty argument list!";
1577 O << CmdName << "(";
1580 bool firstIteration = true;
1582 CheckedIncrement(Pos, End, errorMessage);
1583 const std::string& Arg = *Pos;
1584 assert(Arg.size() != 0);
1590 firstIteration = false;
1594 if (Arg == "$INFILE") {
1596 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1598 O << "inFile.c_str()";
1601 O << '"' << Arg << '"';
1610 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1611 /// function used by SubstituteSpecialCommands().
1612 StrVector::const_iterator
1613 SubstituteEnv (StrVector::const_iterator Pos,
1614 StrVector::const_iterator End, raw_ostream& O)
1616 const char* errorMessage = "Syntax error in $ENV invocation!";
1617 CheckedIncrement(Pos, End, errorMessage);
1618 const std::string& EnvName = *Pos;
1621 throw "$ENV invocation: empty argument list!";
1623 O << "checkCString(std::getenv(\"";
1627 CheckedIncrement(Pos, End, errorMessage);
1632 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1633 /// handler code. Helper function used by EmitCmdLineVecFill().
1634 StrVector::const_iterator
1635 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1636 StrVector::const_iterator End,
1637 bool IsJoin, raw_ostream& O)
1640 const std::string& cmd = *Pos;
1642 // Perform substitution.
1643 if (cmd == "$CALL") {
1644 Pos = SubstituteCall(Pos, End, IsJoin, O);
1646 else if (cmd == "$ENV") {
1647 Pos = SubstituteEnv(Pos, End, O);
1650 throw "Unknown special command: " + cmd;
1653 // Handle '$CMD(ARG)/additional/text'.
1654 const std::string& Leftover = *Pos;
1655 assert(Leftover.at(0) == ')');
1656 if (Leftover.size() != 1)
1657 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1662 /// EmitCmdLineVecFill - Emit code that fills in the command line
1663 /// vector. Helper function used by EmitGenerateActionMethod().
1664 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1665 bool IsJoin, unsigned IndentLevel,
1668 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1671 throw "Tool '" + ToolName + "' has empty command line!";
1673 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1675 // If there is a hook invocation on the place of the first command, skip it.
1676 assert(!StrVec[0].empty());
1677 if (StrVec[0][0] == '$') {
1678 while (I != E && (*I)[0] != ')' )
1681 // Skip the ')' symbol.
1688 bool hasINFILE = false;
1690 for (; I != E; ++I) {
1691 const std::string& cmd = *I;
1692 assert(!cmd.empty());
1693 O.indent(IndentLevel);
1694 if (cmd.at(0) == '$') {
1695 if (cmd == "$INFILE") {
1698 O << "for (PathVector::const_iterator B = inFiles.begin()"
1699 << ", E = inFiles.end();\n";
1700 O.indent(IndentLevel) << "B != E; ++B)\n";
1701 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1704 O << "vec.push_back(inFile.str());\n";
1707 else if (cmd == "$OUTFILE") {
1708 O << "vec.push_back(\"\");\n";
1709 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1712 O << "vec.push_back(";
1713 I = SubstituteSpecialCommands(I, E, IsJoin, O);
1718 O << "vec.push_back(\"" << cmd << "\");\n";
1722 throw "Tool '" + ToolName + "' doesn't take any input!";
1724 O.indent(IndentLevel) << "cmd = ";
1725 if (StrVec[0][0] == '$')
1726 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), IsJoin, O);
1728 O << '"' << StrVec[0] << '"';
1732 /// EmitCmdLineVecFillCallback - A function object wrapper around
1733 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1734 /// argument to EmitCaseConstructHandler().
1735 class EmitCmdLineVecFillCallback {
1737 const std::string& ToolName;
1739 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1740 : IsJoin(J), ToolName(TN) {}
1742 void operator()(const Init* Statement, unsigned IndentLevel,
1743 raw_ostream& O) const
1745 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1749 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1750 /// implement EmitActionHandler. Emits code for
1751 /// handling the (forward) and (forward_as) option properties.
1752 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1753 unsigned IndentLevel,
1754 const std::string& NewName,
1756 const std::string& Name = NewName.empty()
1759 unsigned IndentLevel1 = IndentLevel + Indent1;
1762 case OptionType::Switch:
1763 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1765 case OptionType::Parameter:
1766 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1767 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1769 case OptionType::Prefix:
1770 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1771 << D.GenVariableName() << ");\n";
1773 case OptionType::PrefixList:
1774 O.indent(IndentLevel)
1775 << "for (" << D.GenTypeDeclaration()
1776 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1777 O.indent(IndentLevel)
1778 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1779 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1780 O.indent(IndentLevel1) << "++B;\n";
1782 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1783 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1784 O.indent(IndentLevel1) << "++B;\n";
1787 O.indent(IndentLevel) << "}\n";
1789 case OptionType::ParameterList:
1790 O.indent(IndentLevel)
1791 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1792 << D.GenVariableName() << ".begin(),\n";
1793 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1794 << ".end() ; B != E;) {\n";
1795 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1797 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1798 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1799 O.indent(IndentLevel1) << "++B;\n";
1802 O.indent(IndentLevel) << "}\n";
1804 case OptionType::Alias:
1806 throw "Aliases are not allowed in tool option descriptions!";
1810 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1811 /// EmitPreprocessOptionsCallback.
1812 struct ActionHandlingCallbackBase
1815 void onErrorDag(const DagInit& d,
1816 unsigned IndentLevel, raw_ostream& O) const
1818 O.indent(IndentLevel)
1819 << "throw std::runtime_error(\"" <<
1820 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1825 void onWarningDag(const DagInit& d,
1826 unsigned IndentLevel, raw_ostream& O) const
1828 CheckNumberOfArguments(d, 1);
1829 O.indent(IndentLevel) << "llvm::errs() << \""
1830 << InitPtrToString(d.getArg(0)) << "\";\n";
1835 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1836 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1838 class EmitActionHandlersCallback;
1840 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1841 (const DagInit&, unsigned, raw_ostream&) const;
1843 class EmitActionHandlersCallback :
1844 public ActionHandlingCallbackBase,
1845 public HandlerTable<EmitActionHandlersCallbackHandler>
1847 typedef EmitActionHandlersCallbackHandler Handler;
1849 const OptionDescriptions& OptDescs;
1851 /// EmitHookInvocation - Common code for hook invocation from actions. Used by
1852 /// onAppendCmd and onOutputSuffix.
1853 void EmitHookInvocation(const std::string& Str,
1854 const char* BlockOpen, const char* BlockClose,
1855 unsigned IndentLevel, raw_ostream& O) const
1858 TokenizeCmdLine(Str, Out);
1860 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1862 const std::string& cmd = *B;
1864 O.indent(IndentLevel) << BlockOpen;
1866 if (cmd.at(0) == '$')
1867 B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O);
1869 O << '"' << cmd << '"';
1875 void onAppendCmd (const DagInit& Dag,
1876 unsigned IndentLevel, raw_ostream& O) const
1878 CheckNumberOfArguments(Dag, 1);
1879 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1880 "vec.push_back(", ");\n", IndentLevel, O);
1883 void onForward (const DagInit& Dag,
1884 unsigned IndentLevel, raw_ostream& O) const
1886 CheckNumberOfArguments(Dag, 1);
1887 const std::string& Name = InitPtrToString(Dag.getArg(0));
1888 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1889 IndentLevel, "", O);
1892 void onForwardAs (const DagInit& Dag,
1893 unsigned IndentLevel, raw_ostream& O) const
1895 CheckNumberOfArguments(Dag, 2);
1896 const std::string& Name = InitPtrToString(Dag.getArg(0));
1897 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1898 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1899 IndentLevel, NewName, O);
1902 void onForwardValue (const DagInit& Dag,
1903 unsigned IndentLevel, raw_ostream& O) const
1905 CheckNumberOfArguments(Dag, 1);
1906 const std::string& Name = InitPtrToString(Dag.getArg(0));
1907 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1909 if (D.isParameter()) {
1910 O.indent(IndentLevel) << "vec.push_back("
1911 << D.GenVariableName() << ");\n";
1914 O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1915 << ".begin(), " << D.GenVariableName()
1916 << ".end(), std::back_inserter(vec));\n";
1920 void onForwardTransformedValue (const DagInit& Dag,
1921 unsigned IndentLevel, raw_ostream& O) const
1923 CheckNumberOfArguments(Dag, 2);
1924 const std::string& Name = InitPtrToString(Dag.getArg(0));
1925 const std::string& Hook = InitPtrToString(Dag.getArg(1));
1926 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1928 O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1929 << Hook << "(" << D.GenVariableName()
1930 << (D.isParameter() ? ".c_str()" : "") << "));\n";
1933 void onOutputSuffix (const DagInit& Dag,
1934 unsigned IndentLevel, raw_ostream& O) const
1936 CheckNumberOfArguments(Dag, 1);
1937 this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)),
1938 "output_suffix = ", ";\n", IndentLevel, O);
1941 void onStopCompilation (const DagInit& Dag,
1942 unsigned IndentLevel, raw_ostream& O) const
1944 O.indent(IndentLevel) << "stop_compilation = true;\n";
1948 void onUnpackValues (const DagInit& Dag,
1949 unsigned IndentLevel, raw_ostream& O) const
1951 throw "'unpack_values' is deprecated. "
1952 "Use 'comma_separated' + 'forward_value' instead!";
1957 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1960 if (!staticMembersInitialized_) {
1961 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1962 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1963 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1964 AddHandler("forward", &EmitActionHandlersCallback::onForward);
1965 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1966 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
1967 AddHandler("forward_transformed_value",
1968 &EmitActionHandlersCallback::onForwardTransformedValue);
1969 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1970 AddHandler("stop_compilation",
1971 &EmitActionHandlersCallback::onStopCompilation);
1972 AddHandler("unpack_values",
1973 &EmitActionHandlersCallback::onUnpackValues);
1975 staticMembersInitialized_ = true;
1979 void operator()(const Init* I,
1980 unsigned IndentLevel, raw_ostream& O) const
1982 InvokeDagInitHandler(this, I, IndentLevel, O);
1986 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1988 TokenizeCmdLine(InitPtrToString(CmdLine), StrVec);
1990 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1992 if (*I == "$OUTFILE")
1999 class IsOutFileIndexCheckRequiredStrCallback {
2003 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
2006 void operator()(const Init* CmdLine) {
2007 // Ignore nested 'case' DAG.
2008 if (typeid(*CmdLine) == typeid(DagInit))
2011 if (IsOutFileIndexCheckRequiredStr(CmdLine))
2015 void operator()(const DagInit* Test, unsigned, bool) {
2016 this->operator()(Test);
2018 void operator()(const Init* Statement, unsigned) {
2019 this->operator()(Statement);
2023 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
2025 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
2029 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
2030 /// in EmitGenerateActionMethod() ?
2031 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
2032 if (typeid(*CmdLine) == typeid(StringInit))
2033 return IsOutFileIndexCheckRequiredStr(CmdLine);
2035 return IsOutFileIndexCheckRequiredCase(CmdLine);
2038 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2039 bool IsJoin, raw_ostream& O)
2042 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2044 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
2046 O.indent(Indent2) << "bool HasChildren,\n";
2047 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2048 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2049 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2050 O.indent(Indent1) << "{\n";
2051 O.indent(Indent2) << "std::string cmd;\n";
2052 O.indent(Indent2) << "std::vector<std::string> vec;\n";
2053 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2054 O.indent(Indent2) << "const char* output_suffix = \""
2055 << D.OutputSuffix << "\";\n";
2058 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2059 // Tool::GenerateAction() method.
2060 void EmitGenerateActionMethod (const ToolDescription& D,
2061 const OptionDescriptions& OptDescs,
2062 bool IsJoin, raw_ostream& O) {
2064 EmitGenerateActionMethodHeader(D, IsJoin, O);
2067 throw "Tool " + D.Name + " has no cmd_line property!";
2069 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2070 O.indent(Indent2) << "int out_file_index"
2071 << (IndexCheckRequired ? " = -1" : "")
2074 // Process the cmd_line property.
2075 if (typeid(*D.CmdLine) == typeid(StringInit))
2076 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2078 EmitCaseConstructHandler(D.CmdLine, Indent2,
2079 EmitCmdLineVecFillCallback(IsJoin, D.Name),
2082 // For every understood option, emit handling code.
2084 EmitCaseConstructHandler(D.Actions, Indent2,
2085 EmitActionHandlersCallback(OptDescs),
2086 false, OptDescs, O);
2090 << "std::string out_file = OutFilename("
2091 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2092 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2094 if (IndexCheckRequired)
2095 O.indent(Indent2) << "if (out_file_index != -1)\n";
2096 O.indent(IndexCheckRequired ? Indent3 : Indent2)
2097 << "vec[out_file_index] = out_file;\n";
2099 // Handle the Sink property.
2101 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2102 O.indent(Indent3) << "vec.insert(vec.end(), "
2103 << SinkOptionName << ".begin(), " << SinkOptionName
2105 O.indent(Indent2) << "}\n";
2108 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2109 O.indent(Indent1) << "}\n\n";
2112 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2113 /// a given Tool class.
2114 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2115 const OptionDescriptions& OptDescs,
2117 if (!ToolDesc.isJoin()) {
2118 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2119 O.indent(Indent2) << "bool HasChildren,\n";
2120 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2121 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2122 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2123 O.indent(Indent1) << "{\n";
2124 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2125 << " is not a Join tool!\");\n";
2126 O.indent(Indent1) << "}\n\n";
2129 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2132 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2135 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2136 /// methods for a given Tool class.
2137 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2138 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2139 O.indent(Indent2) << "return InputLanguages_;\n";
2140 O.indent(Indent1) << "}\n\n";
2142 if (D.OutLanguage.empty())
2143 throw "Tool " + D.Name + " has no 'out_language' property!";
2145 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2146 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2147 O.indent(Indent1) << "}\n\n";
2150 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2151 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2152 O.indent(Indent1) << "const char* Name() const {\n";
2153 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2154 O.indent(Indent1) << "}\n\n";
2157 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2159 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2160 O.indent(Indent1) << "bool IsJoin() const {\n";
2162 O.indent(Indent2) << "return true;\n";
2164 O.indent(Indent2) << "return false;\n";
2165 O.indent(Indent1) << "}\n\n";
2168 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2169 /// given Tool class.
2170 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2171 if (D.InLanguage.empty())
2172 throw "Tool " + D.Name + " has no 'in_language' property!";
2174 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2175 for (StrVector::const_iterator B = D.InLanguage.begin(),
2176 E = D.InLanguage.end(); B != E; ++B)
2177 O << '\"' << *B << "\", ";
2181 /// EmitToolClassDefinition - Emit a Tool class definition.
2182 void EmitToolClassDefinition (const ToolDescription& D,
2183 const OptionDescriptions& OptDescs,
2185 if (D.Name == "root")
2189 O << "class " << D.Name << " : public ";
2195 O << " {\nprivate:\n";
2196 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2199 EmitNameMethod(D, O);
2200 EmitInOutLanguageMethods(D, O);
2201 EmitIsJoinMethod(D, O);
2202 EmitGenerateActionMethods(D, OptDescs, O);
2204 // Close class definition
2207 EmitStaticMemberDefinitions(D, O);
2211 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2212 /// and emit registration code.
2213 void EmitOptionDefinitions (const OptionDescriptions& descs,
2214 bool HasSink, bool HasExterns,
2217 std::vector<OptionDescription> Aliases;
2219 // Emit static cl::Option variables.
2220 for (OptionDescriptions::const_iterator B = descs.begin(),
2221 E = descs.end(); B!=E; ++B) {
2222 const OptionDescription& val = B->second;
2224 if (val.Type == OptionType::Alias) {
2225 Aliases.push_back(val);
2232 O << val.GenTypeDeclaration() << ' '
2233 << val.GenVariableName();
2235 if (val.isExtern()) {
2240 O << "(\"" << val.Name << "\"\n";
2242 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2243 O << ", cl::Prefix";
2245 if (val.isRequired()) {
2246 if (val.isList() && !val.isMultiVal())
2247 O << ", cl::OneOrMore";
2249 O << ", cl::Required";
2251 else if (val.isOneOrMore() && val.isList()) {
2252 O << ", cl::OneOrMore";
2254 else if (val.isOptional() && val.isList()) {
2255 O << ", cl::Optional";
2258 if (val.isReallyHidden())
2259 O << ", cl::ReallyHidden";
2260 else if (val.isHidden())
2261 O << ", cl::Hidden";
2263 if (val.isCommaSeparated())
2264 O << ", cl::CommaSeparated";
2266 if (val.MultiVal > 1)
2267 O << ", cl::multi_val(" << val.MultiVal << ')';
2270 const std::string& str = val.InitVal->getAsString();
2271 O << ", cl::init(" << str << ')';
2274 if (!val.Help.empty())
2275 O << ", cl::desc(\"" << val.Help << "\")";
2280 // Emit the aliases (they should go after all the 'proper' options).
2281 for (std::vector<OptionDescription>::const_iterator
2282 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2283 const OptionDescription& val = *B;
2285 O << val.GenTypeDeclaration() << ' '
2286 << val.GenVariableName()
2287 << "(\"" << val.Name << '\"';
2289 const OptionDescription& D = descs.FindOption(val.Help);
2290 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2292 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2295 // Emit the sink option.
2297 O << (HasExterns ? "extern cl" : "cl")
2298 << "::list<std::string> " << SinkOptionName
2299 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2304 /// EmitPreprocessOptionsCallback - Helper function passed to
2305 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2307 class EmitPreprocessOptionsCallback;
2310 (EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler)
2311 (const DagInit&, unsigned, raw_ostream&) const;
2313 class EmitPreprocessOptionsCallback :
2314 public ActionHandlingCallbackBase,
2315 public HandlerTable<EmitPreprocessOptionsCallbackHandler>
2317 typedef EmitPreprocessOptionsCallbackHandler Handler;
2319 (EmitPreprocessOptionsCallback::* HandlerImpl)
2320 (const Init*, unsigned, raw_ostream&) const;
2322 const OptionDescriptions& OptDescs_;
2324 void onListOrDag(const DagInit& d, HandlerImpl h,
2325 unsigned IndentLevel, raw_ostream& O) const
2327 CheckNumberOfArguments(d, 1);
2328 const Init* I = d.getArg(0);
2330 // If I is a list, apply h to each element.
2331 if (typeid(*I) == typeid(ListInit)) {
2332 const ListInit& L = *static_cast<const ListInit*>(I);
2333 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B)
2334 ((this)->*(h))(*B, IndentLevel, O);
2336 // Otherwise, apply h to I.
2338 ((this)->*(h))(I, IndentLevel, O);
2342 void onUnsetOptionImpl(const Init* I,
2343 unsigned IndentLevel, raw_ostream& O) const
2345 const std::string& OptName = InitPtrToString(I);
2346 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2348 if (OptDesc.isSwitch()) {
2349 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2351 else if (OptDesc.isParameter()) {
2352 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2354 else if (OptDesc.isList()) {
2355 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2358 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2362 void onUnsetOption(const DagInit& d,
2363 unsigned IndentLevel, raw_ostream& O) const
2365 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl,
2369 void onSetOptionImpl(const DagInit& d,
2370 unsigned IndentLevel, raw_ostream& O) const {
2371 CheckNumberOfArguments(d, 2);
2372 const std::string& OptName = InitPtrToString(d.getArg(0));
2373 const Init* Value = d.getArg(1);
2374 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2376 if (OptDesc.isList()) {
2377 const ListInit& List = InitPtrToList(Value);
2379 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2380 for (ListInit::const_iterator B = List.begin(), E = List.end();
2382 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".push_back(\""
2383 << InitPtrToString(*B) << "\");\n";
2386 else if (OptDesc.isSwitch()) {
2387 CheckBooleanConstant(Value);
2388 O.indent(IndentLevel) << OptDesc.GenVariableName()
2389 << " = " << Value->getAsString() << ";\n";
2391 else if (OptDesc.isParameter()) {
2392 const std::string& Str = InitPtrToString(Value);
2393 O.indent(IndentLevel) << OptDesc.GenVariableName()
2394 << " = \"" << Str << "\";\n";
2397 throw "Can't apply 'set_option' to alias option -" + OptName + " !";
2401 void onSetSwitch(const Init* I,
2402 unsigned IndentLevel, raw_ostream& O) const {
2403 const std::string& OptName = InitPtrToString(I);
2404 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2406 if (OptDesc.isSwitch())
2407 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n";
2409 throw "set_option: -" + OptName + " is not a switch option!";
2412 void onSetOption(const DagInit& d,
2413 unsigned IndentLevel, raw_ostream& O) const
2415 CheckNumberOfArguments(d, 1);
2417 // Two arguments: (set_option "parameter", VALUE), where VALUE can be a
2418 // boolean, a string or a string list.
2419 if (d.getNumArgs() > 1)
2420 this->onSetOptionImpl(d, IndentLevel, O);
2421 // One argument: (set_option "switch")
2422 // or (set_option ["switch1", "switch2", ...])
2424 this->onListOrDag(d, &EmitPreprocessOptionsCallback::onSetSwitch,
2430 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2431 : OptDescs_(OptDescs)
2433 if (!staticMembersInitialized_) {
2434 AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag);
2435 AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag);
2436 AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption);
2437 AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption);
2439 staticMembersInitialized_ = true;
2443 void operator()(const Init* I,
2444 unsigned IndentLevel, raw_ostream& O) const
2446 InvokeDagInitHandler(this, I, IndentLevel, O);
2451 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2452 void EmitPreprocessOptions (const RecordKeeper& Records,
2453 const OptionDescriptions& OptDecs, raw_ostream& O)
2455 O << "void PreprocessOptionsLocal() {\n";
2457 const RecordVector& OptionPreprocessors =
2458 Records.getAllDerivedDefinitions("OptionPreprocessor");
2460 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2461 E = OptionPreprocessors.end(); B!=E; ++B) {
2462 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2463 EmitCaseConstructHandler(Case, Indent1,
2464 EmitPreprocessOptionsCallback(OptDecs),
2471 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2472 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2474 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2476 // Get the relevant field out of RecordKeeper
2477 const Record* LangMapRecord = Records.getDef("LanguageMap");
2479 // It is allowed for a plugin to have no language map.
2480 if (LangMapRecord) {
2482 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2483 if (!LangsToSuffixesList)
2484 throw "Error in the language map definition!";
2486 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2487 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2489 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2490 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2492 for (unsigned i = 0; i < Suffixes->size(); ++i)
2493 O.indent(Indent1) << "langMap[\""
2494 << InitPtrToString(Suffixes->getElement(i))
2495 << "\"] = \"" << Lang << "\";\n";
2502 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2503 /// by EmitEdgeClass().
2504 void IncDecWeight (const Init* i, unsigned IndentLevel,
2506 const DagInit& d = InitPtrToDag(i);
2507 const std::string& OpName = GetOperatorName(d);
2509 if (OpName == "inc_weight") {
2510 O.indent(IndentLevel) << "ret += ";
2512 else if (OpName == "dec_weight") {
2513 O.indent(IndentLevel) << "ret -= ";
2515 else if (OpName == "error") {
2516 CheckNumberOfArguments(d, 1);
2517 O.indent(IndentLevel) << "throw std::runtime_error(\""
2518 << InitPtrToString(d.getArg(0))
2523 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2524 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2527 if (d.getNumArgs() > 0)
2528 O << InitPtrToInt(d.getArg(0)) << ";\n";
2534 /// EmitEdgeClass - Emit a single Edge# class.
2535 void EmitEdgeClass (unsigned N, const std::string& Target,
2536 DagInit* Case, const OptionDescriptions& OptDescs,
2539 // Class constructor.
2540 O << "class Edge" << N << ": public Edge {\n"
2542 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2545 // Function Weight().
2547 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2548 O.indent(Indent2) << "unsigned ret = 0;\n";
2550 // Handle the 'case' construct.
2551 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2553 O.indent(Indent2) << "return ret;\n";
2554 O.indent(Indent1) << "}\n\n};\n\n";
2557 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2558 void EmitEdgeClasses (const RecordVector& EdgeVector,
2559 const OptionDescriptions& OptDescs,
2562 for (RecordVector::const_iterator B = EdgeVector.begin(),
2563 E = EdgeVector.end(); B != E; ++B) {
2564 const Record* Edge = *B;
2565 const std::string& NodeB = Edge->getValueAsString("b");
2566 DagInit& Weight = *Edge->getValueAsDag("weight");
2568 if (!IsDagEmpty(Weight))
2569 EmitEdgeClass(i, NodeB, &Weight, OptDescs, O);
2574 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2576 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2577 const ToolDescriptions& ToolDescs,
2580 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2582 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2583 E = ToolDescs.end(); B != E; ++B)
2584 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2591 for (RecordVector::const_iterator B = EdgeVector.begin(),
2592 E = EdgeVector.end(); B != E; ++B) {
2593 const Record* Edge = *B;
2594 const std::string& NodeA = Edge->getValueAsString("a");
2595 const std::string& NodeB = Edge->getValueAsString("b");
2596 DagInit& Weight = *Edge->getValueAsDag("weight");
2598 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2600 if (IsDagEmpty(Weight))
2601 O << "new SimpleEdge(\"" << NodeB << "\")";
2603 O << "new Edge" << i << "()";
2612 /// HookInfo - Information about the hook type and number of arguments.
2615 // A hook can either have a single parameter of type std::vector<std::string>,
2616 // or NumArgs parameters of type const char*.
2617 enum HookType { ListHook, ArgHook };
2622 HookInfo() : Type(ArgHook), NumArgs(1)
2625 HookInfo(HookType T) : Type(T), NumArgs(1)
2628 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2632 typedef llvm::StringMap<HookInfo> HookInfoMap;
2634 /// ExtractHookNames - Extract the hook names from all instances of
2635 /// $CALL(HookName) in the provided command line string/action. Helper
2636 /// function used by FillInHookNames().
2637 class ExtractHookNames {
2638 HookInfoMap& HookNames_;
2639 const OptionDescriptions& OptDescs_;
2641 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2642 : HookNames_(HookNames), OptDescs_(OptDescs)
2645 void onAction (const DagInit& Dag) {
2646 const std::string& Name = GetOperatorName(Dag);
2648 if (Name == "forward_transformed_value") {
2649 CheckNumberOfArguments(Dag, 2);
2650 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2651 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2652 const OptionDescription& D = OptDescs_.FindOption(OptName);
2654 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2655 : HookInfo::ArgHook);
2657 else if (Name == "append_cmd" || Name == "output_suffix") {
2658 CheckNumberOfArguments(Dag, 1);
2659 this->onCmdLine(InitPtrToString(Dag.getArg(0)));
2663 void onCmdLine(const std::string& Cmd) {
2665 TokenizeCmdLine(Cmd, cmds);
2667 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2669 const std::string& cmd = *B;
2671 if (cmd == "$CALL") {
2672 unsigned NumArgs = 0;
2673 CheckedIncrement(B, E, "Syntax error in $CALL invocation!");
2674 const std::string& HookName = *B;
2676 if (HookName.at(0) == ')')
2677 throw "$CALL invoked with no arguments!";
2679 while (++B != E && B->at(0) != ')') {
2683 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2685 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2686 H->second.Type != HookInfo::ArgHook)
2687 throw "Overloading of hooks is not allowed. Overloaded hook: "
2690 HookNames_[HookName] = HookInfo(NumArgs);
2695 void operator()(const Init* Arg) {
2697 // We're invoked on an action (either a dag or a dag list).
2698 if (typeid(*Arg) == typeid(DagInit)) {
2699 const DagInit& Dag = InitPtrToDag(Arg);
2700 this->onAction(Dag);
2703 else if (typeid(*Arg) == typeid(ListInit)) {
2704 const ListInit& List = InitPtrToList(Arg);
2705 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2707 const DagInit& Dag = InitPtrToDag(*B);
2708 this->onAction(Dag);
2713 // We're invoked on a command line.
2714 this->onCmdLine(InitPtrToString(Arg));
2717 void operator()(const DagInit* Test, unsigned, bool) {
2718 this->operator()(Test);
2720 void operator()(const Init* Statement, unsigned) {
2721 this->operator()(Statement);
2725 /// FillInHookNames - Actually extract the hook names from all command
2726 /// line strings. Helper function used by EmitHookDeclarations().
2727 void FillInHookNames(const ToolDescriptions& ToolDescs,
2728 const OptionDescriptions& OptDescs,
2729 HookInfoMap& HookNames)
2731 // For all tool descriptions:
2732 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2733 E = ToolDescs.end(); B != E; ++B) {
2734 const ToolDescription& D = *(*B);
2736 // Look for 'forward_transformed_value' in 'actions'.
2738 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2740 // Look for hook invocations in 'cmd_line'.
2743 if (dynamic_cast<StringInit*>(D.CmdLine))
2744 // This is a string.
2745 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2747 // This is a 'case' construct.
2748 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2752 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2753 /// property records and emit hook function declaration for each
2754 /// instance of $CALL(HookName).
2755 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2756 const OptionDescriptions& OptDescs, raw_ostream& O) {
2757 HookInfoMap HookNames;
2759 FillInHookNames(ToolDescs, OptDescs, HookNames);
2760 if (HookNames.empty())
2763 O << "namespace hooks {\n";
2764 for (HookInfoMap::const_iterator B = HookNames.begin(),
2765 E = HookNames.end(); B != E; ++B) {
2766 const char* HookName = B->first();
2767 const HookInfo& Info = B->second;
2769 O.indent(Indent1) << "std::string " << HookName << "(";
2771 if (Info.Type == HookInfo::ArgHook) {
2772 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2773 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2777 O << "const std::vector<std::string>& Arg";
2785 /// EmitRegisterPlugin - Emit code to register this plugin.
2786 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2787 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2788 O.indent(Indent1) << "int Priority() const { return "
2789 << Priority << "; }\n\n";
2790 O.indent(Indent1) << "void PreprocessOptions() const\n";
2791 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2792 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2793 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2795 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2796 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2798 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2801 /// EmitIncludes - Emit necessary #include directives and some
2802 /// additional declarations.
2803 void EmitIncludes(raw_ostream& O) {
2804 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2805 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2806 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2807 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2808 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2810 << "#include \"llvm/Support/CommandLine.h\"\n"
2811 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2813 << "#include <algorithm>\n"
2814 << "#include <cstdlib>\n"
2815 << "#include <iterator>\n"
2816 << "#include <stdexcept>\n\n"
2818 << "using namespace llvm;\n"
2819 << "using namespace llvmc;\n\n"
2821 << "extern cl::opt<std::string> OutputFilename;\n\n"
2823 << "inline const char* checkCString(const char* s)\n"
2824 << "{ return s == NULL ? \"\" : s; }\n\n";
2828 /// PluginData - Holds all information about a plugin.
2830 OptionDescriptions OptDescs;
2833 ToolDescriptions ToolDescs;
2838 /// HasSink - Go through the list of tool descriptions and check if
2839 /// there are any with the 'sink' property set.
2840 bool HasSink(const ToolDescriptions& ToolDescs) {
2841 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2842 E = ToolDescs.end(); B != E; ++B)
2849 /// HasExterns - Go through the list of option descriptions and check
2850 /// if there are any external options.
2851 bool HasExterns(const OptionDescriptions& OptDescs) {
2852 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2853 E = OptDescs.end(); B != E; ++B)
2854 if (B->second.isExtern())
2860 /// CollectPluginData - Collect tool and option properties,
2861 /// compilation graph edges and plugin priority from the parse tree.
2862 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2863 // Collect option properties.
2864 const RecordVector& OptionLists =
2865 Records.getAllDerivedDefinitions("OptionList");
2866 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2869 // Collect tool properties.
2870 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2871 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2872 Data.HasSink = HasSink(Data.ToolDescs);
2873 Data.HasExterns = HasExterns(Data.OptDescs);
2875 // Collect compilation graph edges.
2876 const RecordVector& CompilationGraphs =
2877 Records.getAllDerivedDefinitions("CompilationGraph");
2878 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2881 // Calculate the priority of this plugin.
2882 const RecordVector& Priorities =
2883 Records.getAllDerivedDefinitions("PluginPriority");
2884 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2887 /// CheckPluginData - Perform some sanity checks on the collected data.
2888 void CheckPluginData(PluginData& Data) {
2889 // Filter out all tools not mentioned in the compilation graph.
2890 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2892 // Typecheck the compilation graph.
2893 TypecheckGraph(Data.Edges, Data.ToolDescs);
2895 // Check that there are no options without side effects (specified
2896 // only in the OptionList).
2897 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2901 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2902 // Emit file header.
2905 // Emit global option registration code.
2906 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2908 // Emit hook declarations.
2909 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2911 O << "namespace {\n\n";
2913 // Emit PreprocessOptionsLocal() function.
2914 EmitPreprocessOptions(Records, Data.OptDescs, O);
2916 // Emit PopulateLanguageMapLocal() function
2917 // (language map maps from file extensions to language names).
2918 EmitPopulateLanguageMap(Records, O);
2920 // Emit Tool classes.
2921 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2922 E = Data.ToolDescs.end(); B!=E; ++B)
2923 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2925 // Emit Edge# classes.
2926 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2928 // Emit PopulateCompilationGraphLocal() function.
2929 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2931 // Emit code for plugin registration.
2932 EmitRegisterPlugin(Data.Priority, O);
2934 O << "} // End anonymous namespace.\n\n";
2936 // Force linkage magic.
2937 O << "namespace llvmc {\n";
2938 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2945 // End of anonymous namespace
2948 /// run - The back-end entry point.
2949 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2953 CollectPluginData(Records, Data);
2954 CheckPluginData(Data);
2956 EmitSourceFileHeader("LLVMC Configuration Library", O);
2957 EmitPluginCode(Data, O);
2959 } catch (std::exception& Error) {
2960 throw Error.what() + std::string(" - usually this means a syntax error.");