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/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
32 //===----------------------------------------------------------------------===//
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
38 //===----------------------------------------------------------------------===//
42 static const unsigned TabWidth = 4;
43 static const unsigned Indent1 = TabWidth*1;
44 static const unsigned Indent2 = TabWidth*2;
45 static const unsigned Indent3 = TabWidth*3;
47 // Default help string.
48 static const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50 // Name for the "sink" option.
51 static const char * const SinkOptionName = "AutoGeneratedSinkOption";
55 //===----------------------------------------------------------------------===//
58 /// Id - An 'identity' function object.
61 void operator()(const T0&) const {
63 template<typename T0, typename T1>
64 void operator()(const T0&, const T1&) const {
66 template<typename T0, typename T1, typename T2>
67 void operator()(const T0&, const T1&, const T2&) const {
71 int InitPtrToInt(const Init* ptr) {
72 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
73 return val.getValue();
76 const std::string& InitPtrToString(const Init* ptr) {
77 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
78 return val.getValue();
81 const ListInit& InitPtrToList(const Init* ptr) {
82 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
86 const DagInit& InitPtrToDag(const Init* ptr) {
87 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
91 const std::string GetOperatorName(const DagInit* D) {
92 return D->getOperator()->getAsString();
95 const std::string GetOperatorName(const DagInit& D) {
96 return GetOperatorName(&D);
99 // checkNumberOfArguments - Ensure that the number of args in d is
100 // greater than or equal to min_arguments, otherwise throw an exception.
101 void checkNumberOfArguments (const DagInit* d, unsigned minArgs) {
102 if (!d || d->getNumArgs() < minArgs)
103 throw GetOperatorName(d) + ": too few arguments!";
105 void checkNumberOfArguments (const DagInit& d, unsigned minArgs) {
106 checkNumberOfArguments(&d, minArgs);
109 // isDagEmpty - is this DAG marked with an empty marker?
110 bool isDagEmpty (const DagInit* d) {
111 return GetOperatorName(d) == "empty_dag_marker";
114 // EscapeVariableName - Escape commas and other symbols not allowed
115 // in the C++ variable names. Makes it possible to use options named
116 // like "Wa," (useful for prefix options).
117 std::string EscapeVariableName(const std::string& Var) {
119 for (unsigned i = 0; i != Var.size(); ++i) {
120 char cur_char = Var[i];
121 if (cur_char == ',') {
124 else if (cur_char == '+') {
127 else if (cur_char == '-') {
131 ret.push_back(cur_char);
137 /// oneOf - Does the input string contain this character?
138 bool oneOf(const char* lst, char c) {
146 template <class I, class S>
147 void checkedIncrement(I& P, I E, S ErrorString) {
153 // apply is needed because C++'s syntax doesn't let us construct a function
154 // object and call it in the same statement.
155 template<typename F, typename T0>
156 void apply(F Fun, T0& Arg0) {
160 template<typename F, typename T0, typename T1>
161 void apply(F Fun, T0& Arg0, T1& Arg1) {
162 return Fun(Arg0, Arg1);
165 //===----------------------------------------------------------------------===//
166 /// Back-end specific code
169 /// OptionType - One of six different option types. See the
170 /// documentation for detailed description of differences.
171 namespace OptionType {
173 enum OptionType { Alias, Switch, Parameter, ParameterList,
176 bool IsAlias(OptionType t) {
180 bool IsList (OptionType t) {
181 return (t == ParameterList || t == PrefixList);
184 bool IsSwitch (OptionType t) {
185 return (t == Switch);
188 bool IsParameter (OptionType t) {
189 return (t == Parameter || t == Prefix);
194 OptionType::OptionType stringToOptionType(const std::string& T) {
195 if (T == "alias_option")
196 return OptionType::Alias;
197 else if (T == "switch_option")
198 return OptionType::Switch;
199 else if (T == "parameter_option")
200 return OptionType::Parameter;
201 else if (T == "parameter_list_option")
202 return OptionType::ParameterList;
203 else if (T == "prefix_option")
204 return OptionType::Prefix;
205 else if (T == "prefix_list_option")
206 return OptionType::PrefixList;
208 throw "Unknown option type: " + T + '!';
211 namespace OptionDescriptionFlags {
212 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
213 ReallyHidden = 0x4, Extern = 0x8,
214 OneOrMore = 0x10, Optional = 0x20,
215 CommaSeparated = 0x40 };
218 /// OptionDescription - Represents data contained in a single
219 /// OptionList entry.
220 struct OptionDescription {
221 OptionType::OptionType Type;
228 OptionDescription(OptionType::OptionType t = OptionType::Switch,
229 const std::string& n = "",
230 const std::string& h = DefaultHelpString)
231 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
234 /// GenTypeDeclaration - Returns the C++ variable type of this
236 const char* GenTypeDeclaration() const;
238 /// GenVariableName - Returns the variable name used in the
239 /// generated C++ code.
240 std::string GenVariableName() const;
242 /// Merge - Merge two option descriptions.
243 void Merge (const OptionDescription& other);
245 // Misc convenient getters/setters.
247 bool isAlias() const;
249 bool isMultiVal() const;
251 bool isCommaSeparated() const;
252 void setCommaSeparated();
254 bool isExtern() const;
257 bool isRequired() const;
260 bool isOneOrMore() const;
263 bool isOptional() const;
266 bool isHidden() const;
269 bool isReallyHidden() const;
270 void setReallyHidden();
272 bool isSwitch() const
273 { return OptionType::IsSwitch(this->Type); }
275 bool isParameter() const
276 { return OptionType::IsParameter(this->Type); }
279 { return OptionType::IsList(this->Type); }
283 void OptionDescription::Merge (const OptionDescription& other)
285 if (other.Type != Type)
286 throw "Conflicting definitions for the option " + Name + "!";
288 if (Help == other.Help || Help == DefaultHelpString)
290 else if (other.Help != DefaultHelpString) {
291 llvm::errs() << "Warning: several different help strings"
292 " defined for option " + Name + "\n";
295 Flags |= other.Flags;
298 bool OptionDescription::isAlias() const {
299 return OptionType::IsAlias(this->Type);
302 bool OptionDescription::isMultiVal() const {
306 bool OptionDescription::isCommaSeparated() const {
307 return Flags & OptionDescriptionFlags::CommaSeparated;
309 void OptionDescription::setCommaSeparated() {
310 Flags |= OptionDescriptionFlags::CommaSeparated;
313 bool OptionDescription::isExtern() const {
314 return Flags & OptionDescriptionFlags::Extern;
316 void OptionDescription::setExtern() {
317 Flags |= OptionDescriptionFlags::Extern;
320 bool OptionDescription::isRequired() const {
321 return Flags & OptionDescriptionFlags::Required;
323 void OptionDescription::setRequired() {
324 Flags |= OptionDescriptionFlags::Required;
327 bool OptionDescription::isOneOrMore() const {
328 return Flags & OptionDescriptionFlags::OneOrMore;
330 void OptionDescription::setOneOrMore() {
331 Flags |= OptionDescriptionFlags::OneOrMore;
334 bool OptionDescription::isOptional() const {
335 return Flags & OptionDescriptionFlags::Optional;
337 void OptionDescription::setOptional() {
338 Flags |= OptionDescriptionFlags::Optional;
341 bool OptionDescription::isHidden() const {
342 return Flags & OptionDescriptionFlags::Hidden;
344 void OptionDescription::setHidden() {
345 Flags |= OptionDescriptionFlags::Hidden;
348 bool OptionDescription::isReallyHidden() const {
349 return Flags & OptionDescriptionFlags::ReallyHidden;
351 void OptionDescription::setReallyHidden() {
352 Flags |= OptionDescriptionFlags::ReallyHidden;
355 const char* OptionDescription::GenTypeDeclaration() const {
357 case OptionType::Alias:
359 case OptionType::PrefixList:
360 case OptionType::ParameterList:
361 return "cl::list<std::string>";
362 case OptionType::Switch:
363 return "cl::opt<bool>";
364 case OptionType::Parameter:
365 case OptionType::Prefix:
367 return "cl::opt<std::string>";
371 std::string OptionDescription::GenVariableName() const {
372 const std::string& EscapedName = EscapeVariableName(Name);
374 case OptionType::Alias:
375 return "AutoGeneratedAlias_" + EscapedName;
376 case OptionType::PrefixList:
377 case OptionType::ParameterList:
378 return "AutoGeneratedList_" + EscapedName;
379 case OptionType::Switch:
380 return "AutoGeneratedSwitch_" + EscapedName;
381 case OptionType::Prefix:
382 case OptionType::Parameter:
384 return "AutoGeneratedParameter_" + EscapedName;
388 /// OptionDescriptions - An OptionDescription array plus some helper
390 class OptionDescriptions {
391 typedef StringMap<OptionDescription> container_type;
393 /// Descriptions - A list of OptionDescriptions.
394 container_type Descriptions;
397 /// FindOption - exception-throwing wrapper for find().
398 const OptionDescription& FindOption(const std::string& OptName) const;
400 // Wrappers for FindOption that throw an exception in case the option has a
402 const OptionDescription& FindSwitch(const std::string& OptName) const;
403 const OptionDescription& FindParameter(const std::string& OptName) const;
404 const OptionDescription& FindList(const std::string& OptName) const;
405 const OptionDescription&
406 FindListOrParameter(const std::string& OptName) const;
408 /// insertDescription - Insert new OptionDescription into
409 /// OptionDescriptions list
410 void InsertDescription (const OptionDescription& o);
412 // Support for STL-style iteration
413 typedef container_type::const_iterator const_iterator;
414 const_iterator begin() const { return Descriptions.begin(); }
415 const_iterator end() const { return Descriptions.end(); }
418 const OptionDescription&
419 OptionDescriptions::FindOption(const std::string& OptName) const {
420 const_iterator I = Descriptions.find(OptName);
421 if (I != Descriptions.end())
424 throw OptName + ": no such option!";
427 const OptionDescription&
428 OptionDescriptions::FindSwitch(const std::string& OptName) const {
429 const OptionDescription& OptDesc = this->FindOption(OptName);
430 if (!OptDesc.isSwitch())
431 throw OptName + ": incorrect option type - should be a switch!";
435 const OptionDescription&
436 OptionDescriptions::FindList(const std::string& OptName) const {
437 const OptionDescription& OptDesc = this->FindOption(OptName);
438 if (!OptDesc.isList())
439 throw OptName + ": incorrect option type - should be a list!";
443 const OptionDescription&
444 OptionDescriptions::FindParameter(const std::string& OptName) const {
445 const OptionDescription& OptDesc = this->FindOption(OptName);
446 if (!OptDesc.isParameter())
447 throw OptName + ": incorrect option type - should be a parameter!";
451 const OptionDescription&
452 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
453 const OptionDescription& OptDesc = this->FindOption(OptName);
454 if (!OptDesc.isList() && !OptDesc.isParameter())
456 + ": incorrect option type - should be a list or parameter!";
460 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
461 container_type::iterator I = Descriptions.find(o.Name);
462 if (I != Descriptions.end()) {
463 OptionDescription& D = I->second;
467 Descriptions[o.Name] = o;
471 /// HandlerTable - A base class for function objects implemented as
472 /// 'tables of handlers'.
473 template <typename Handler>
476 // Implementation details.
478 /// HandlerMap - A map from property names to property handlers
479 typedef StringMap<Handler> HandlerMap;
481 static HandlerMap Handlers_;
482 static bool staticMembersInitialized_;
486 Handler GetHandler (const std::string& HandlerName) const {
487 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
489 if (method != Handlers_.end()) {
490 Handler h = method->second;
494 throw "No handler found for property " + HandlerName + "!";
498 void AddHandler(const char* Property, Handler H) {
499 Handlers_[Property] = H;
504 template <class FunctionObject>
505 void InvokeDagInitHandler(FunctionObject* Obj, Init* i) {
506 typedef void (FunctionObject::*Handler) (const DagInit*);
508 const DagInit& property = InitPtrToDag(i);
509 const std::string& property_name = GetOperatorName(property);
510 Handler h = Obj->GetHandler(property_name);
512 ((Obj)->*(h))(&property);
515 template <typename H>
516 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
518 template <typename H>
519 bool HandlerTable<H>::staticMembersInitialized_ = false;
522 /// CollectOptionProperties - Function object for iterating over an
523 /// option property list.
524 class CollectOptionProperties;
525 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
528 class CollectOptionProperties
529 : public HandlerTable<CollectOptionPropertiesHandler>
533 /// optDescs_ - OptionDescriptions table. This is where the
534 /// information is stored.
535 OptionDescription& optDesc_;
539 explicit CollectOptionProperties(OptionDescription& OD)
542 if (!staticMembersInitialized_) {
543 AddHandler("extern", &CollectOptionProperties::onExtern);
544 AddHandler("help", &CollectOptionProperties::onHelp);
545 AddHandler("hidden", &CollectOptionProperties::onHidden);
546 AddHandler("init", &CollectOptionProperties::onInit);
547 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
548 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
549 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
550 AddHandler("required", &CollectOptionProperties::onRequired);
551 AddHandler("optional", &CollectOptionProperties::onOptional);
552 AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated);
554 staticMembersInitialized_ = true;
558 /// operator() - Just forwards to the corresponding property
560 void operator() (Init* i) {
561 InvokeDagInitHandler(this, i);
566 /// Option property handlers --
567 /// Methods that handle option properties such as (help) or (hidden).
569 void onExtern (const DagInit* d) {
570 checkNumberOfArguments(d, 0);
571 optDesc_.setExtern();
574 void onHelp (const DagInit* d) {
575 checkNumberOfArguments(d, 1);
576 optDesc_.Help = InitPtrToString(d->getArg(0));
579 void onHidden (const DagInit* d) {
580 checkNumberOfArguments(d, 0);
581 optDesc_.setHidden();
584 void onReallyHidden (const DagInit* d) {
585 checkNumberOfArguments(d, 0);
586 optDesc_.setReallyHidden();
589 void onCommaSeparated (const DagInit* d) {
590 checkNumberOfArguments(d, 0);
591 if (!optDesc_.isList())
592 throw "'comma_separated' is valid only on list options!";
593 optDesc_.setCommaSeparated();
596 void onRequired (const DagInit* d) {
597 checkNumberOfArguments(d, 0);
598 if (optDesc_.isOneOrMore() || optDesc_.isOptional())
599 throw "Only one of (required), (optional) or "
600 "(one_or_more) properties is allowed!";
601 optDesc_.setRequired();
604 void onInit (const DagInit* d) {
605 checkNumberOfArguments(d, 1);
606 Init* i = d->getArg(0);
607 const std::string& str = i->getAsString();
609 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
610 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
613 throw "Incorrect usage of the 'init' option property!";
615 optDesc_.InitVal = i;
618 void onOneOrMore (const DagInit* d) {
619 checkNumberOfArguments(d, 0);
620 if (optDesc_.isRequired() || optDesc_.isOptional())
621 throw "Only one of (required), (optional) or "
622 "(one_or_more) properties is allowed!";
623 if (!OptionType::IsList(optDesc_.Type))
624 llvm::errs() << "Warning: specifying the 'one_or_more' property "
625 "on a non-list option will have no effect.\n";
626 optDesc_.setOneOrMore();
629 void onOptional (const DagInit* d) {
630 checkNumberOfArguments(d, 0);
631 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
632 throw "Only one of (required), (optional) or "
633 "(one_or_more) properties is allowed!";
634 if (!OptionType::IsList(optDesc_.Type))
635 llvm::errs() << "Warning: specifying the 'optional' property"
636 "on a non-list option will have no effect.\n";
637 optDesc_.setOptional();
640 void onMultiVal (const DagInit* d) {
641 checkNumberOfArguments(d, 1);
642 int val = InitPtrToInt(d->getArg(0));
644 throw "Error in the 'multi_val' property: "
645 "the value must be greater than 1!";
646 if (!OptionType::IsList(optDesc_.Type))
647 throw "The multi_val property is valid only on list options!";
648 optDesc_.MultiVal = val;
653 /// AddOption - A function object that is applied to every option
654 /// description. Used by CollectOptionDescriptions.
657 OptionDescriptions& OptDescs_;
660 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
663 void operator()(const Init* i) {
664 const DagInit& d = InitPtrToDag(i);
665 checkNumberOfArguments(&d, 1);
667 const OptionType::OptionType Type =
668 stringToOptionType(GetOperatorName(d));
669 const std::string& Name = InitPtrToString(d.getArg(0));
671 OptionDescription OD(Type, Name);
674 checkNumberOfArguments(&d, 2);
677 // Aliases store the aliased option name in the 'Help' field.
678 OD.Help = InitPtrToString(d.getArg(1));
680 else if (!OD.isExtern()) {
681 processOptionProperties(&d, OD);
683 OptDescs_.InsertDescription(OD);
687 /// processOptionProperties - Go through the list of option
688 /// properties and call a corresponding handler for each.
689 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
690 checkNumberOfArguments(d, 2);
691 DagInit::const_arg_iterator B = d->arg_begin();
692 // Skip the first argument: it's always the option name.
694 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
699 /// CollectOptionDescriptions - Collects option properties from all
701 void CollectOptionDescriptions (RecordVector::const_iterator B,
702 RecordVector::const_iterator E,
703 OptionDescriptions& OptDescs)
705 // For every OptionList:
707 RecordVector::value_type T = *B;
708 // Throws an exception if the value does not exist.
709 ListInit* PropList = T->getValueAsListInit("options");
711 // For every option description in this list:
712 // collect the information and
713 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
717 // Tool information record
719 namespace ToolFlags {
720 enum ToolFlags { Join = 0x1, Sink = 0x2 };
723 struct ToolDescription : public RefCountedBase<ToolDescription> {
727 StrVector InLanguage;
728 std::string OutLanguage;
729 std::string OutputSuffix;
732 // Various boolean properties
733 void setSink() { Flags |= ToolFlags::Sink; }
734 bool isSink() const { return Flags & ToolFlags::Sink; }
735 void setJoin() { Flags |= ToolFlags::Join; }
736 bool isJoin() const { return Flags & ToolFlags::Join; }
738 // Default ctor here is needed because StringMap can only store
739 // DefaultConstructible objects
740 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
741 ToolDescription (const std::string& n)
742 : Name(n), CmdLine(0), Actions(0), Flags(0)
746 /// ToolDescriptions - A list of Tool information records.
747 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
750 /// CollectToolProperties - Function object for iterating over a list of
751 /// tool property records.
753 class CollectToolProperties;
754 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
757 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
761 /// toolDesc_ - Properties of the current Tool. This is where the
762 /// information is stored.
763 ToolDescription& toolDesc_;
767 explicit CollectToolProperties (ToolDescription& d)
770 if (!staticMembersInitialized_) {
772 AddHandler("actions", &CollectToolProperties::onActions);
773 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
774 AddHandler("in_language", &CollectToolProperties::onInLanguage);
775 AddHandler("join", &CollectToolProperties::onJoin);
776 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
777 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
778 AddHandler("sink", &CollectToolProperties::onSink);
780 staticMembersInitialized_ = true;
784 void operator() (Init* i) {
785 InvokeDagInitHandler(this, i);
790 /// Property handlers --
791 /// Functions that extract information about tool properties from
792 /// DAG representation.
794 void onActions (const DagInit* d) {
795 checkNumberOfArguments(d, 1);
796 Init* Case = d->getArg(0);
797 if (typeid(*Case) != typeid(DagInit) ||
798 GetOperatorName(static_cast<DagInit*>(Case)) != "case")
799 throw "The argument to (actions) should be a 'case' construct!";
800 toolDesc_.Actions = Case;
803 void onCmdLine (const DagInit* d) {
804 checkNumberOfArguments(d, 1);
805 toolDesc_.CmdLine = d->getArg(0);
808 void onInLanguage (const DagInit* d) {
809 checkNumberOfArguments(d, 1);
810 Init* arg = d->getArg(0);
812 // Find out the argument's type.
813 if (typeid(*arg) == typeid(StringInit)) {
815 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
819 const ListInit& lst = InitPtrToList(arg);
820 StrVector& out = toolDesc_.InLanguage;
822 // Copy strings to the output vector.
823 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
825 out.push_back(InitPtrToString(*B));
828 // Remove duplicates.
829 std::sort(out.begin(), out.end());
830 StrVector::iterator newE = std::unique(out.begin(), out.end());
831 out.erase(newE, out.end());
835 void onJoin (const DagInit* d) {
836 checkNumberOfArguments(d, 0);
840 void onOutLanguage (const DagInit* d) {
841 checkNumberOfArguments(d, 1);
842 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
845 void onOutputSuffix (const DagInit* d) {
846 checkNumberOfArguments(d, 1);
847 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
850 void onSink (const DagInit* d) {
851 checkNumberOfArguments(d, 0);
857 /// CollectToolDescriptions - Gather information about tool properties
858 /// from the parsed TableGen data (basically a wrapper for the
859 /// CollectToolProperties function object).
860 void CollectToolDescriptions (RecordVector::const_iterator B,
861 RecordVector::const_iterator E,
862 ToolDescriptions& ToolDescs)
864 // Iterate over a properties list of every Tool definition
866 const Record* T = *B;
867 // Throws an exception if the value does not exist.
868 ListInit* PropList = T->getValueAsListInit("properties");
870 IntrusiveRefCntPtr<ToolDescription>
871 ToolDesc(new ToolDescription(T->getName()));
873 std::for_each(PropList->begin(), PropList->end(),
874 CollectToolProperties(*ToolDesc));
875 ToolDescs.push_back(ToolDesc);
879 /// FillInEdgeVector - Merge all compilation graph definitions into
880 /// one single edge list.
881 void FillInEdgeVector(RecordVector::const_iterator B,
882 RecordVector::const_iterator E, RecordVector& Out) {
883 for (; B != E; ++B) {
884 const ListInit* edges = (*B)->getValueAsListInit("edges");
886 for (unsigned i = 0; i < edges->size(); ++i)
887 Out.push_back(edges->getElementAsRecord(i));
891 /// CalculatePriority - Calculate the priority of this plugin.
892 int CalculatePriority(RecordVector::const_iterator B,
893 RecordVector::const_iterator E) {
897 priority = static_cast<int>((*B)->getValueAsInt("priority"));
900 throw "More than one 'PluginPriority' instance found: "
901 "most probably an error!";
907 /// NotInGraph - Helper function object for FilterNotInGraph.
910 const llvm::StringSet<>& ToolsInGraph_;
913 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
914 : ToolsInGraph_(ToolsInGraph)
917 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
918 return (ToolsInGraph_.count(x->Name) == 0);
922 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
923 /// mentioned in the compilation graph definition.
924 void FilterNotInGraph (const RecordVector& EdgeVector,
925 ToolDescriptions& ToolDescs) {
927 // List all tools mentioned in the graph.
928 llvm::StringSet<> ToolsInGraph;
930 for (RecordVector::const_iterator B = EdgeVector.begin(),
931 E = EdgeVector.end(); B != E; ++B) {
933 const Record* Edge = *B;
934 const std::string& NodeA = Edge->getValueAsString("a");
935 const std::string& NodeB = Edge->getValueAsString("b");
938 ToolsInGraph.insert(NodeA);
939 ToolsInGraph.insert(NodeB);
942 // Filter ToolPropertiesList.
943 ToolDescriptions::iterator new_end =
944 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
945 NotInGraph(ToolsInGraph));
946 ToolDescs.erase(new_end, ToolDescs.end());
949 /// FillInToolToLang - Fills in two tables that map tool names to
950 /// (input, output) languages. Helper function used by TypecheckGraph().
951 void FillInToolToLang (const ToolDescriptions& ToolDescs,
952 StringMap<StringSet<> >& ToolToInLang,
953 StringMap<std::string>& ToolToOutLang) {
954 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
955 E = ToolDescs.end(); B != E; ++B) {
956 const ToolDescription& D = *(*B);
957 for (StrVector::const_iterator B = D.InLanguage.begin(),
958 E = D.InLanguage.end(); B != E; ++B)
959 ToolToInLang[D.Name].insert(*B);
960 ToolToOutLang[D.Name] = D.OutLanguage;
964 /// TypecheckGraph - Check that names for output and input languages
965 /// on all edges do match. This doesn't do much when the information
966 /// about the whole graph is not available (i.e. when compiling most
968 void TypecheckGraph (const RecordVector& EdgeVector,
969 const ToolDescriptions& ToolDescs) {
970 StringMap<StringSet<> > ToolToInLang;
971 StringMap<std::string> ToolToOutLang;
973 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
974 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
975 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
977 for (RecordVector::const_iterator B = EdgeVector.begin(),
978 E = EdgeVector.end(); B != E; ++B) {
979 const Record* Edge = *B;
980 const std::string& NodeA = Edge->getValueAsString("a");
981 const std::string& NodeB = Edge->getValueAsString("b");
982 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
983 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
985 if (NodeA != "root") {
986 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
987 throw "Edge " + NodeA + "->" + NodeB
988 + ": output->input language mismatch";
992 throw "Edges back to the root are not allowed!";
996 /// WalkCase - Walks the 'case' expression DAG and invokes
997 /// TestCallback on every test, and StatementCallback on every
998 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
999 /// combinators (that is, they are passed directly to TestCallback).
1000 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
1001 /// IndentLevel, bool FirstTest)'.
1002 /// StatementCallback must have type 'void StatementCallback(const Init*,
1003 /// unsigned IndentLevel)'.
1004 template <typename F1, typename F2>
1005 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
1006 unsigned IndentLevel = 0)
1008 const DagInit& d = InitPtrToDag(Case);
1011 if (GetOperatorName(d) != "case")
1012 throw "WalkCase should be invoked only on 'case' expressions!";
1014 if (d.getNumArgs() < 2)
1015 throw "There should be at least one clause in the 'case' expression:\n"
1020 const unsigned numArgs = d.getNumArgs();
1022 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1029 const DagInit& Test = InitPtrToDag(arg);
1031 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1032 throw "The 'default' clause should be the last in the "
1033 "'case' construct!";
1035 throw "Case construct handler: no corresponding action "
1036 "found for the test " + Test.getAsString() + '!';
1038 TestCallback(&Test, IndentLevel, (i == 1));
1042 if (dynamic_cast<DagInit*>(arg)
1043 && GetOperatorName(static_cast<DagInit*>(arg)) == "case") {
1045 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1048 // Handle statement.
1049 StatementCallback(arg, IndentLevel);
1057 /// ExtractOptionNames - A helper function object used by
1058 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1059 class ExtractOptionNames {
1060 llvm::StringSet<>& OptionNames_;
1062 void processDag(const Init* Statement) {
1063 const DagInit& Stmt = InitPtrToDag(Statement);
1064 const std::string& ActionName = GetOperatorName(Stmt);
1065 if (ActionName == "forward" || ActionName == "forward_as" ||
1066 ActionName == "forward_value" ||
1067 ActionName == "forward_transformed_value" ||
1068 ActionName == "switch_on" || ActionName == "parameter_equals" ||
1069 ActionName == "element_in_list" || ActionName == "not_empty" ||
1070 ActionName == "empty") {
1071 checkNumberOfArguments(&Stmt, 1);
1072 const std::string& Name = InitPtrToString(Stmt.getArg(0));
1073 OptionNames_.insert(Name);
1075 else if (ActionName == "and" || ActionName == "or") {
1076 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1077 this->processDag(Stmt.getArg(i));
1083 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1086 void operator()(const Init* Statement) {
1087 if (typeid(*Statement) == typeid(ListInit)) {
1088 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1089 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1091 this->processDag(*B);
1094 this->processDag(Statement);
1098 void operator()(const DagInit* Test, unsigned, bool) {
1099 this->operator()(Test);
1101 void operator()(const Init* Statement, unsigned) {
1102 this->operator()(Statement);
1106 /// CheckForSuperfluousOptions - Check that there are no side
1107 /// effect-free options (specified only in the OptionList). Otherwise,
1108 /// output a warning.
1109 void CheckForSuperfluousOptions (const RecordVector& Edges,
1110 const ToolDescriptions& ToolDescs,
1111 const OptionDescriptions& OptDescs) {
1112 llvm::StringSet<> nonSuperfluousOptions;
1114 // Add all options mentioned in the ToolDesc.Actions to the set of
1115 // non-superfluous options.
1116 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1117 E = ToolDescs.end(); B != E; ++B) {
1118 const ToolDescription& TD = *(*B);
1119 ExtractOptionNames Callback(nonSuperfluousOptions);
1121 WalkCase(TD.Actions, Callback, Callback);
1124 // Add all options mentioned in the 'case' clauses of the
1125 // OptionalEdges of the compilation graph to the set of
1126 // non-superfluous options.
1127 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1129 const Record* Edge = *B;
1130 DagInit* Weight = Edge->getValueAsDag("weight");
1132 if (!isDagEmpty(Weight))
1133 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1136 // Check that all options in OptDescs belong to the set of
1137 // non-superfluous options.
1138 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1139 E = OptDescs.end(); B != E; ++B) {
1140 const OptionDescription& Val = B->second;
1141 if (!nonSuperfluousOptions.count(Val.Name)
1142 && Val.Type != OptionType::Alias)
1143 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1144 "Probable cause: this option is specified only in the OptionList.\n";
1148 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1149 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1150 if (TestName == "single_input_file") {
1151 O << "InputFilenames.size() == 1";
1154 else if (TestName == "multiple_input_files") {
1155 O << "InputFilenames.size() > 1";
1162 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1163 template <typename F>
1164 void EmitListTest(const ListInit& L, const char* LogicOp,
1165 F Callback, raw_ostream& O)
1167 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1169 bool isFirst = true;
1170 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1175 Callback(InitPtrToString(*B), O);
1179 // Callbacks for use with EmitListTest.
1181 class EmitSwitchOn {
1182 const OptionDescriptions& OptDescs_;
1184 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1187 void operator()(const std::string& OptName, raw_ostream& O) const {
1188 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1189 O << OptDesc.GenVariableName();
1193 class EmitEmptyTest {
1195 const OptionDescriptions& OptDescs_;
1197 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1198 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1201 void operator()(const std::string& OptName, raw_ostream& O) const {
1202 const char* Neg = (EmitNegate_ ? "!" : "");
1203 if (OptName == "o") {
1204 O << Neg << "OutputFilename.empty()";
1206 else if (OptName == "save-temps") {
1207 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1210 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1211 O << Neg << OptDesc.GenVariableName() << ".empty()";
1217 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1218 bool EmitCaseTest1ArgList(const std::string& TestName,
1220 const OptionDescriptions& OptDescs,
1222 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1224 if (TestName == "any_switch_on") {
1225 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1228 else if (TestName == "switch_on") {
1229 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1232 else if (TestName == "any_not_empty") {
1233 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1236 else if (TestName == "any_empty") {
1237 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1240 else if (TestName == "not_empty") {
1241 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1244 else if (TestName == "empty") {
1245 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1252 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1253 bool EmitCaseTest1ArgStr(const std::string& TestName,
1255 const OptionDescriptions& OptDescs,
1257 const std::string& OptName = InitPtrToString(d.getArg(0));
1259 if (TestName == "switch_on") {
1260 apply(EmitSwitchOn(OptDescs), OptName, O);
1263 else if (TestName == "input_languages_contain") {
1264 O << "InLangs.count(\"" << OptName << "\") != 0";
1267 else if (TestName == "in_language") {
1268 // This works only for single-argument Tool::GenerateAction. Join
1269 // tools can process several files in different languages simultaneously.
1271 // TODO: make this work with Edge::Weight (if possible).
1272 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1275 else if (TestName == "not_empty" || TestName == "empty") {
1276 bool EmitNegate = (TestName == "not_empty");
1277 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1284 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1285 bool EmitCaseTest1Arg(const std::string& TestName,
1287 const OptionDescriptions& OptDescs,
1289 checkNumberOfArguments(&d, 1);
1290 if (typeid(*d.getArg(0)) == typeid(ListInit))
1291 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1293 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1296 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1297 bool EmitCaseTest2Args(const std::string& TestName,
1299 unsigned IndentLevel,
1300 const OptionDescriptions& OptDescs,
1302 checkNumberOfArguments(&d, 2);
1303 const std::string& OptName = InitPtrToString(d.getArg(0));
1304 const std::string& OptArg = InitPtrToString(d.getArg(1));
1306 if (TestName == "parameter_equals") {
1307 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1308 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1311 else if (TestName == "element_in_list") {
1312 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1313 const std::string& VarName = OptDesc.GenVariableName();
1314 O << "std::find(" << VarName << ".begin(),\n";
1315 O.indent(IndentLevel + Indent1)
1316 << VarName << ".end(), \""
1317 << OptArg << "\") != " << VarName << ".end()";
1324 // Forward declaration.
1325 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1326 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1327 const OptionDescriptions& OptDescs,
1330 /// EmitLogicalOperationTest - Helper function used by
1331 /// EmitCaseConstructHandler.
1332 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1333 unsigned IndentLevel,
1334 const OptionDescriptions& OptDescs,
1337 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1338 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1339 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1340 if (j != NumArgs - 1) {
1342 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1350 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1351 const OptionDescriptions& OptDescs, raw_ostream& O)
1353 checkNumberOfArguments(&d, 1);
1354 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1356 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1360 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1361 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1362 const OptionDescriptions& OptDescs,
1364 const std::string& TestName = GetOperatorName(d);
1366 if (TestName == "and")
1367 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1368 else if (TestName == "or")
1369 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1370 else if (TestName == "not")
1371 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1372 else if (EmitCaseTest0Args(TestName, O))
1374 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1376 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1379 throw TestName + ": unknown edge property!";
1383 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1384 class EmitCaseTestCallback {
1386 const OptionDescriptions& OptDescs_;
1390 EmitCaseTestCallback(bool EmitElseIf,
1391 const OptionDescriptions& OptDescs, raw_ostream& O)
1392 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1395 void operator()(const DagInit* Test, unsigned IndentLevel, bool FirstTest)
1397 if (GetOperatorName(Test) == "default") {
1398 O_.indent(IndentLevel) << "else {\n";
1401 O_.indent(IndentLevel)
1402 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1403 EmitCaseTest(*Test, IndentLevel, OptDescs_, O_);
1409 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1410 template <typename F>
1411 class EmitCaseStatementCallback {
1416 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1417 : Callback_(Callback), O_(O)
1420 void operator() (const Init* Statement, unsigned IndentLevel) {
1422 // Ignore nested 'case' DAG.
1423 if (!(dynamic_cast<const DagInit*>(Statement) &&
1424 GetOperatorName(static_cast<const DagInit*>(Statement)) == "case")) {
1425 if (typeid(*Statement) == typeid(ListInit)) {
1426 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1427 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1429 Callback_(*B, (IndentLevel + Indent1), O_);
1432 Callback_(Statement, (IndentLevel + Indent1), O_);
1435 O_.indent(IndentLevel) << "}\n";
1440 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1441 /// construct. Takes a function object that should emit code for every case
1442 /// clause. Implemented on top of WalkCase.
1443 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1444 /// raw_ostream& O).
1445 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1446 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1448 template <typename F>
1449 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1450 F Callback, bool EmitElseIf,
1451 const OptionDescriptions& OptDescs,
1453 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1454 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1457 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1458 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1459 /// Helper function used by EmitCmdLineVecFill and.
1460 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1461 const char* Delimiters = " \t\n\v\f\r";
1463 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1466 if (CmdLine.empty())
1470 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1473 for (; B != E; ++B) {
1474 char cur_ch = CmdLine[B];
1478 if (cur_ch == '$') {
1479 cur_st = SpecialCommand;
1482 if (oneOf(Delimiters, cur_ch)) {
1484 B = CmdLine.find_first_not_of(Delimiters, B);
1485 if (B == std::string::npos) {
1496 case SpecialCommand:
1497 if (oneOf(Delimiters, cur_ch)) {
1502 if (cur_ch == '(') {
1504 cur_st = InsideSpecialCommand;
1509 case InsideSpecialCommand:
1510 if (oneOf(Delimiters, cur_ch)) {
1513 if (cur_ch == '\'') {
1514 cur_st = InsideQuotationMarks;
1518 if (cur_ch == ')') {
1522 if (cur_ch == ',') {
1528 case InsideQuotationMarks:
1529 if (cur_ch == '\'') {
1530 cur_st = InsideSpecialCommand;
1536 Out.back().push_back(cur_ch);
1540 /// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output
1541 /// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by
1542 /// SubstituteSpecialCommands().
1543 StrVector::const_iterator
1544 SubstituteCall (StrVector::const_iterator Pos,
1545 StrVector::const_iterator End,
1546 bool IsJoin, raw_ostream& O)
1548 const char* errorMessage = "Syntax error in $CALL invocation!";
1549 checkedIncrement(Pos, End, errorMessage);
1550 const std::string& CmdName = *Pos;
1553 throw "$CALL invocation: empty argument list!";
1556 O << CmdName << "(";
1559 bool firstIteration = true;
1561 checkedIncrement(Pos, End, errorMessage);
1562 const std::string& Arg = *Pos;
1563 assert(Arg.size() != 0);
1569 firstIteration = false;
1573 if (Arg == "$INFILE") {
1575 throw "$CALL(Hook, $INFILE) can't be used with a Join tool!";
1577 O << "inFile.c_str()";
1580 O << '"' << Arg << '"';
1589 /// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper
1590 /// function used by SubstituteSpecialCommands().
1591 StrVector::const_iterator
1592 SubstituteEnv (StrVector::const_iterator Pos,
1593 StrVector::const_iterator End, raw_ostream& O)
1595 const char* errorMessage = "Syntax error in $ENV invocation!";
1596 checkedIncrement(Pos, End, errorMessage);
1597 const std::string& EnvName = *Pos;
1600 throw "$ENV invocation: empty argument list!";
1602 O << "checkCString(std::getenv(\"";
1606 checkedIncrement(Pos, End, errorMessage);
1611 /// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output
1612 /// handler code. Helper function used by EmitCmdLineVecFill().
1613 StrVector::const_iterator
1614 SubstituteSpecialCommands (StrVector::const_iterator Pos,
1615 StrVector::const_iterator End,
1616 bool IsJoin, raw_ostream& O)
1619 const std::string& cmd = *Pos;
1621 // Perform substitution.
1622 if (cmd == "$CALL") {
1623 Pos = SubstituteCall(Pos, End, IsJoin, O);
1625 else if (cmd == "$ENV") {
1626 Pos = SubstituteEnv(Pos, End, O);
1629 throw "Unknown special command: " + cmd;
1632 // Handle '$CMD(ARG)/additional/text'.
1633 const std::string& Leftover = *Pos;
1634 assert(Leftover.at(0) == ')');
1635 if (Leftover.size() != 1)
1636 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1641 /// EmitCmdLineVecFill - Emit code that fills in the command line
1642 /// vector. Helper function used by EmitGenerateActionMethod().
1643 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1644 bool IsJoin, unsigned IndentLevel,
1647 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1650 throw "Tool '" + ToolName + "' has empty command line!";
1652 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1654 // If there is a hook invocation on the place of the first command, skip it.
1655 assert(!StrVec[0].empty());
1656 if (StrVec[0][0] == '$') {
1657 while (I != E && (*I)[0] != ')' )
1660 // Skip the ')' symbol.
1667 bool hasINFILE = false;
1669 for (; I != E; ++I) {
1670 const std::string& cmd = *I;
1671 assert(!cmd.empty());
1672 O.indent(IndentLevel);
1673 if (cmd.at(0) == '$') {
1674 if (cmd == "$INFILE") {
1677 O << "for (PathVector::const_iterator B = inFiles.begin()"
1678 << ", E = inFiles.end();\n";
1679 O.indent(IndentLevel) << "B != E; ++B)\n";
1680 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1683 O << "vec.push_back(inFile.str());\n";
1686 else if (cmd == "$OUTFILE") {
1687 O << "vec.push_back(\"\");\n";
1688 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1691 O << "vec.push_back(";
1692 I = SubstituteSpecialCommands(I, E, IsJoin, O);
1697 O << "vec.push_back(\"" << cmd << "\");\n";
1701 throw "Tool '" + ToolName + "' doesn't take any input!";
1703 O.indent(IndentLevel) << "cmd = ";
1704 if (StrVec[0][0] == '$')
1705 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), IsJoin, O);
1707 O << '"' << StrVec[0] << '"';
1711 /// EmitCmdLineVecFillCallback - A function object wrapper around
1712 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1713 /// argument to EmitCaseConstructHandler().
1714 class EmitCmdLineVecFillCallback {
1716 const std::string& ToolName;
1718 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1719 : IsJoin(J), ToolName(TN) {}
1721 void operator()(const Init* Statement, unsigned IndentLevel,
1722 raw_ostream& O) const
1724 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1728 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1729 /// implement EmitActionHandler. Emits code for
1730 /// handling the (forward) and (forward_as) option properties.
1731 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1732 unsigned IndentLevel,
1733 const std::string& NewName,
1735 const std::string& Name = NewName.empty()
1738 unsigned IndentLevel1 = IndentLevel + Indent1;
1741 case OptionType::Switch:
1742 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1744 case OptionType::Parameter:
1745 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1746 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1748 case OptionType::Prefix:
1749 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1750 << D.GenVariableName() << ");\n";
1752 case OptionType::PrefixList:
1753 O.indent(IndentLevel)
1754 << "for (" << D.GenTypeDeclaration()
1755 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1756 O.indent(IndentLevel)
1757 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1758 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1759 O.indent(IndentLevel1) << "++B;\n";
1761 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1762 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1763 O.indent(IndentLevel1) << "++B;\n";
1766 O.indent(IndentLevel) << "}\n";
1768 case OptionType::ParameterList:
1769 O.indent(IndentLevel)
1770 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1771 << D.GenVariableName() << ".begin(),\n";
1772 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1773 << ".end() ; B != E;) {\n";
1774 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1776 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1777 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1778 O.indent(IndentLevel1) << "++B;\n";
1781 O.indent(IndentLevel) << "}\n";
1783 case OptionType::Alias:
1785 throw "Aliases are not allowed in tool option descriptions!";
1789 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1790 /// EmitPreprocessOptionsCallback.
1791 struct ActionHandlingCallbackBase {
1793 void onErrorDag(const DagInit& d,
1794 unsigned IndentLevel, raw_ostream& O) const
1796 O.indent(IndentLevel)
1797 << "throw std::runtime_error(\"" <<
1798 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1803 void onWarningDag(const DagInit& d,
1804 unsigned IndentLevel, raw_ostream& O) const
1806 checkNumberOfArguments(&d, 1);
1807 O.indent(IndentLevel) << "llvm::errs() << \""
1808 << InitPtrToString(d.getArg(0)) << "\";\n";
1813 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1814 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1815 class EmitActionHandlersCallback;
1816 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1817 (const DagInit&, unsigned, raw_ostream&) const;
1819 class EmitActionHandlersCallback
1820 : public ActionHandlingCallbackBase,
1821 public HandlerTable<EmitActionHandlersCallbackHandler>
1823 const OptionDescriptions& OptDescs;
1824 typedef EmitActionHandlersCallbackHandler Handler;
1826 void onAppendCmd (const DagInit& Dag,
1827 unsigned IndentLevel, raw_ostream& O) const
1829 checkNumberOfArguments(&Dag, 1);
1830 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1832 llvm::SplitString(Cmd, Out);
1834 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1836 O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1839 void onForward (const DagInit& Dag,
1840 unsigned IndentLevel, raw_ostream& O) const
1842 checkNumberOfArguments(&Dag, 1);
1843 const std::string& Name = InitPtrToString(Dag.getArg(0));
1844 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1845 IndentLevel, "", O);
1848 void onForwardAs (const DagInit& Dag,
1849 unsigned IndentLevel, raw_ostream& O) const
1851 checkNumberOfArguments(&Dag, 2);
1852 const std::string& Name = InitPtrToString(Dag.getArg(0));
1853 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1854 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1855 IndentLevel, NewName, O);
1858 void onForwardValue (const DagInit& Dag,
1859 unsigned IndentLevel, raw_ostream& O) const
1861 checkNumberOfArguments(&Dag, 1);
1862 const std::string& Name = InitPtrToString(Dag.getArg(0));
1863 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1865 if (D.isParameter()) {
1866 O.indent(IndentLevel) << "vec.push_back("
1867 << D.GenVariableName() << ");\n";
1870 O.indent(IndentLevel) << "std::copy(" << D.GenVariableName()
1871 << ".begin(), " << D.GenVariableName()
1872 << ".end(), std::back_inserter(vec));\n";
1876 void onForwardTransformedValue (const DagInit& Dag,
1877 unsigned IndentLevel, raw_ostream& O) const
1879 checkNumberOfArguments(&Dag, 2);
1880 const std::string& Name = InitPtrToString(Dag.getArg(0));
1881 const std::string& Hook = InitPtrToString(Dag.getArg(1));
1882 const OptionDescription& D = OptDescs.FindListOrParameter(Name);
1884 O.indent(IndentLevel) << "vec.push_back(" << "hooks::"
1885 << Hook << "(" << D.GenVariableName()
1886 << (D.isParameter() ? ".c_str()" : "") << "));\n";
1890 void onOutputSuffix (const DagInit& Dag,
1891 unsigned IndentLevel, raw_ostream& O) const
1893 checkNumberOfArguments(&Dag, 1);
1894 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1895 O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1898 void onStopCompilation (const DagInit& Dag,
1899 unsigned IndentLevel, raw_ostream& O) const
1901 O.indent(IndentLevel) << "stop_compilation = true;\n";
1905 void onUnpackValues (const DagInit& Dag,
1906 unsigned IndentLevel, raw_ostream& O) const
1908 throw "'unpack_values' is deprecated. "
1909 "Use 'comma_separated' + 'forward_value' instead!";
1914 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1917 if (!staticMembersInitialized_) {
1918 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1919 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1920 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1921 AddHandler("forward", &EmitActionHandlersCallback::onForward);
1922 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1923 AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue);
1924 AddHandler("forward_transformed_value",
1925 &EmitActionHandlersCallback::onForwardTransformedValue);
1926 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1927 AddHandler("stop_compilation",
1928 &EmitActionHandlersCallback::onStopCompilation);
1929 AddHandler("unpack_values",
1930 &EmitActionHandlersCallback::onUnpackValues);
1932 staticMembersInitialized_ = true;
1936 void operator()(const Init* Statement,
1937 unsigned IndentLevel, raw_ostream& O) const
1939 const DagInit& Dag = InitPtrToDag(Statement);
1940 const std::string& ActionName = GetOperatorName(Dag);
1941 Handler h = GetHandler(ActionName);
1943 ((this)->*(h))(Dag, IndentLevel, O);
1947 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1949 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1951 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1953 if (*I == "$OUTFILE")
1960 class IsOutFileIndexCheckRequiredStrCallback {
1964 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1967 void operator()(const Init* CmdLine) {
1968 // Ignore nested 'case' DAG.
1969 if (typeid(*CmdLine) == typeid(DagInit))
1972 if (IsOutFileIndexCheckRequiredStr(CmdLine))
1976 void operator()(const DagInit* Test, unsigned, bool) {
1977 this->operator()(Test);
1979 void operator()(const Init* Statement, unsigned) {
1980 this->operator()(Statement);
1984 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1986 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1990 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1991 /// in EmitGenerateActionMethod() ?
1992 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1993 if (typeid(*CmdLine) == typeid(StringInit))
1994 return IsOutFileIndexCheckRequiredStr(CmdLine);
1996 return IsOutFileIndexCheckRequiredCase(CmdLine);
1999 void EmitGenerateActionMethodHeader(const ToolDescription& D,
2000 bool IsJoin, raw_ostream& O)
2003 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2005 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
2007 O.indent(Indent2) << "bool HasChildren,\n";
2008 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2009 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2010 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2011 O.indent(Indent1) << "{\n";
2012 O.indent(Indent2) << "std::string cmd;\n";
2013 O.indent(Indent2) << "std::vector<std::string> vec;\n";
2014 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
2015 O.indent(Indent2) << "const char* output_suffix = \""
2016 << D.OutputSuffix << "\";\n";
2019 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
2020 // Tool::GenerateAction() method.
2021 void EmitGenerateActionMethod (const ToolDescription& D,
2022 const OptionDescriptions& OptDescs,
2023 bool IsJoin, raw_ostream& O) {
2025 EmitGenerateActionMethodHeader(D, IsJoin, O);
2028 throw "Tool " + D.Name + " has no cmd_line property!";
2030 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
2031 O.indent(Indent2) << "int out_file_index"
2032 << (IndexCheckRequired ? " = -1" : "")
2035 // Process the cmd_line property.
2036 if (typeid(*D.CmdLine) == typeid(StringInit))
2037 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
2039 EmitCaseConstructHandler(D.CmdLine, Indent2,
2040 EmitCmdLineVecFillCallback(IsJoin, D.Name),
2043 // For every understood option, emit handling code.
2045 EmitCaseConstructHandler(D.Actions, Indent2,
2046 EmitActionHandlersCallback(OptDescs),
2047 false, OptDescs, O);
2051 << "std::string out_file = OutFilename("
2052 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
2053 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
2055 if (IndexCheckRequired)
2056 O.indent(Indent2) << "if (out_file_index != -1)\n";
2057 O.indent(IndexCheckRequired ? Indent3 : Indent2)
2058 << "vec[out_file_index] = out_file;\n";
2060 // Handle the Sink property.
2062 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
2063 O.indent(Indent3) << "vec.insert(vec.end(), "
2064 << SinkOptionName << ".begin(), " << SinkOptionName
2066 O.indent(Indent2) << "}\n";
2069 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
2070 O.indent(Indent1) << "}\n\n";
2073 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2074 /// a given Tool class.
2075 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2076 const OptionDescriptions& OptDescs,
2078 if (!ToolDesc.isJoin()) {
2079 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2080 O.indent(Indent2) << "bool HasChildren,\n";
2081 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2082 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2083 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2084 O.indent(Indent1) << "{\n";
2085 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2086 << " is not a Join tool!\");\n";
2087 O.indent(Indent1) << "}\n\n";
2090 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2093 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2096 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2097 /// methods for a given Tool class.
2098 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2099 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2100 O.indent(Indent2) << "return InputLanguages_;\n";
2101 O.indent(Indent1) << "}\n\n";
2103 if (D.OutLanguage.empty())
2104 throw "Tool " + D.Name + " has no 'out_language' property!";
2106 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2107 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2108 O.indent(Indent1) << "}\n\n";
2111 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2112 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2113 O.indent(Indent1) << "const char* Name() const {\n";
2114 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2115 O.indent(Indent1) << "}\n\n";
2118 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2120 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2121 O.indent(Indent1) << "bool IsJoin() const {\n";
2123 O.indent(Indent2) << "return true;\n";
2125 O.indent(Indent2) << "return false;\n";
2126 O.indent(Indent1) << "}\n\n";
2129 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2130 /// given Tool class.
2131 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2132 if (D.InLanguage.empty())
2133 throw "Tool " + D.Name + " has no 'in_language' property!";
2135 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2136 for (StrVector::const_iterator B = D.InLanguage.begin(),
2137 E = D.InLanguage.end(); B != E; ++B)
2138 O << '\"' << *B << "\", ";
2142 /// EmitToolClassDefinition - Emit a Tool class definition.
2143 void EmitToolClassDefinition (const ToolDescription& D,
2144 const OptionDescriptions& OptDescs,
2146 if (D.Name == "root")
2150 O << "class " << D.Name << " : public ";
2156 O << "{\nprivate:\n";
2157 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2160 EmitNameMethod(D, O);
2161 EmitInOutLanguageMethods(D, O);
2162 EmitIsJoinMethod(D, O);
2163 EmitGenerateActionMethods(D, OptDescs, O);
2165 // Close class definition
2168 EmitStaticMemberDefinitions(D, O);
2172 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2173 /// and emit registration code.
2174 void EmitOptionDefinitions (const OptionDescriptions& descs,
2175 bool HasSink, bool HasExterns,
2178 std::vector<OptionDescription> Aliases;
2180 // Emit static cl::Option variables.
2181 for (OptionDescriptions::const_iterator B = descs.begin(),
2182 E = descs.end(); B!=E; ++B) {
2183 const OptionDescription& val = B->second;
2185 if (val.Type == OptionType::Alias) {
2186 Aliases.push_back(val);
2193 O << val.GenTypeDeclaration() << ' '
2194 << val.GenVariableName();
2196 if (val.isExtern()) {
2201 O << "(\"" << val.Name << "\"\n";
2203 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2204 O << ", cl::Prefix";
2206 if (val.isRequired()) {
2207 if (val.isList() && !val.isMultiVal())
2208 O << ", cl::OneOrMore";
2210 O << ", cl::Required";
2212 else if (val.isOneOrMore() && val.isList()) {
2213 O << ", cl::OneOrMore";
2215 else if (val.isOptional() && val.isList()) {
2216 O << ", cl::Optional";
2219 if (val.isReallyHidden())
2220 O << ", cl::ReallyHidden";
2221 else if (val.isHidden())
2222 O << ", cl::Hidden";
2224 if (val.isCommaSeparated())
2225 O << ", cl::CommaSeparated";
2227 if (val.MultiVal > 1)
2228 O << ", cl::multi_val(" << val.MultiVal << ')';
2231 const std::string& str = val.InitVal->getAsString();
2232 O << ", cl::init(" << str << ')';
2235 if (!val.Help.empty())
2236 O << ", cl::desc(\"" << val.Help << "\")";
2241 // Emit the aliases (they should go after all the 'proper' options).
2242 for (std::vector<OptionDescription>::const_iterator
2243 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2244 const OptionDescription& val = *B;
2246 O << val.GenTypeDeclaration() << ' '
2247 << val.GenVariableName()
2248 << "(\"" << val.Name << '\"';
2250 const OptionDescription& D = descs.FindOption(val.Help);
2251 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2253 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2256 // Emit the sink option.
2258 O << (HasExterns ? "extern cl" : "cl")
2259 << "::list<std::string> " << SinkOptionName
2260 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2265 /// EmitPreprocessOptionsCallback - Helper function passed to
2266 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2267 class EmitPreprocessOptionsCallback : ActionHandlingCallbackBase {
2268 const OptionDescriptions& OptDescs_;
2270 void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
2271 const std::string& OptName = InitPtrToString(i);
2272 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2274 if (OptDesc.isSwitch()) {
2275 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2277 else if (OptDesc.isParameter()) {
2278 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2280 else if (OptDesc.isList()) {
2281 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2284 throw "Can't apply 'unset_option' to alias option '" + OptName + "'!";
2288 void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
2290 const DagInit& d = InitPtrToDag(I);
2291 const std::string& OpName = GetOperatorName(d);
2293 if (OpName == "warning") {
2294 this->onWarningDag(d, IndentLevel, O);
2296 else if (OpName == "error") {
2297 this->onWarningDag(d, IndentLevel, O);
2299 else if (OpName == "unset_option") {
2300 checkNumberOfArguments(&d, 1);
2301 Init* I = d.getArg(0);
2302 if (typeid(*I) == typeid(ListInit)) {
2303 const ListInit& DagList = *static_cast<const ListInit*>(I);
2304 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2306 this->onUnsetOption(*B, IndentLevel, O);
2309 this->onUnsetOption(I, IndentLevel, O);
2313 throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
2314 "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
2320 void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
2321 this->processDag(I, IndentLevel, O);
2324 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2325 : OptDescs_(OptDescs)
2329 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2330 void EmitPreprocessOptions (const RecordKeeper& Records,
2331 const OptionDescriptions& OptDecs, raw_ostream& O)
2333 O << "void PreprocessOptionsLocal() {\n";
2335 const RecordVector& OptionPreprocessors =
2336 Records.getAllDerivedDefinitions("OptionPreprocessor");
2338 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2339 E = OptionPreprocessors.end(); B!=E; ++B) {
2340 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2341 EmitCaseConstructHandler(Case, Indent1,
2342 EmitPreprocessOptionsCallback(OptDecs),
2349 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2350 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2352 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2354 // Get the relevant field out of RecordKeeper
2355 const Record* LangMapRecord = Records.getDef("LanguageMap");
2357 // It is allowed for a plugin to have no language map.
2358 if (LangMapRecord) {
2360 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2361 if (!LangsToSuffixesList)
2362 throw "Error in the language map definition!";
2364 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2365 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2367 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2368 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2370 for (unsigned i = 0; i < Suffixes->size(); ++i)
2371 O.indent(Indent1) << "langMap[\""
2372 << InitPtrToString(Suffixes->getElement(i))
2373 << "\"] = \"" << Lang << "\";\n";
2380 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2381 /// by EmitEdgeClass().
2382 void IncDecWeight (const Init* i, unsigned IndentLevel,
2384 const DagInit& d = InitPtrToDag(i);
2385 const std::string& OpName = GetOperatorName(d);
2387 if (OpName == "inc_weight") {
2388 O.indent(IndentLevel) << "ret += ";
2390 else if (OpName == "dec_weight") {
2391 O.indent(IndentLevel) << "ret -= ";
2393 else if (OpName == "error") {
2394 checkNumberOfArguments(&d, 1);
2395 O.indent(IndentLevel) << "throw std::runtime_error(\""
2396 << InitPtrToString(d.getArg(0))
2401 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2402 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2405 if (d.getNumArgs() > 0)
2406 O << InitPtrToInt(d.getArg(0)) << ";\n";
2412 /// EmitEdgeClass - Emit a single Edge# class.
2413 void EmitEdgeClass (unsigned N, const std::string& Target,
2414 DagInit* Case, const OptionDescriptions& OptDescs,
2417 // Class constructor.
2418 O << "class Edge" << N << ": public Edge {\n"
2420 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2423 // Function Weight().
2425 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2426 O.indent(Indent2) << "unsigned ret = 0;\n";
2428 // Handle the 'case' construct.
2429 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2431 O.indent(Indent2) << "return ret;\n";
2432 O.indent(Indent1) << "};\n\n};\n\n";
2435 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2436 void EmitEdgeClasses (const RecordVector& EdgeVector,
2437 const OptionDescriptions& OptDescs,
2440 for (RecordVector::const_iterator B = EdgeVector.begin(),
2441 E = EdgeVector.end(); B != E; ++B) {
2442 const Record* Edge = *B;
2443 const std::string& NodeB = Edge->getValueAsString("b");
2444 DagInit* Weight = Edge->getValueAsDag("weight");
2446 if (!isDagEmpty(Weight))
2447 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2452 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2454 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2455 const ToolDescriptions& ToolDescs,
2458 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2460 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2461 E = ToolDescs.end(); B != E; ++B)
2462 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2469 for (RecordVector::const_iterator B = EdgeVector.begin(),
2470 E = EdgeVector.end(); B != E; ++B) {
2471 const Record* Edge = *B;
2472 const std::string& NodeA = Edge->getValueAsString("a");
2473 const std::string& NodeB = Edge->getValueAsString("b");
2474 DagInit* Weight = Edge->getValueAsDag("weight");
2476 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2478 if (isDagEmpty(Weight))
2479 O << "new SimpleEdge(\"" << NodeB << "\")";
2481 O << "new Edge" << i << "()";
2490 /// HookInfo - Information about the hook type and number of arguments.
2493 // A hook can either have a single parameter of type std::vector<std::string>,
2494 // or NumArgs parameters of type const char*.
2495 enum HookType { ListHook, ArgHook };
2500 HookInfo() : Type(ArgHook), NumArgs(1)
2503 HookInfo(HookType T) : Type(T), NumArgs(1)
2506 HookInfo(unsigned N) : Type(ArgHook), NumArgs(N)
2510 typedef llvm::StringMap<HookInfo> HookInfoMap;
2512 /// ExtractHookNames - Extract the hook names from all instances of
2513 /// $CALL(HookName) in the provided command line string/action. Helper
2514 /// function used by FillInHookNames().
2515 class ExtractHookNames {
2516 HookInfoMap& HookNames_;
2517 const OptionDescriptions& OptDescs_;
2519 ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs)
2520 : HookNames_(HookNames), OptDescs_(OptDescs)
2523 void onAction (const DagInit& Dag) {
2524 if (GetOperatorName(Dag) == "forward_transformed_value") {
2525 checkNumberOfArguments(Dag, 2);
2526 const std::string& OptName = InitPtrToString(Dag.getArg(0));
2527 const std::string& HookName = InitPtrToString(Dag.getArg(1));
2528 const OptionDescription& D = OptDescs_.FindOption(OptName);
2530 HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook
2531 : HookInfo::ArgHook);
2535 void operator()(const Init* Arg) {
2537 // We're invoked on an action (either a dag or a dag list).
2538 if (typeid(*Arg) == typeid(DagInit)) {
2539 const DagInit& Dag = InitPtrToDag(Arg);
2540 this->onAction(Dag);
2543 else if (typeid(*Arg) == typeid(ListInit)) {
2544 const ListInit& List = InitPtrToList(Arg);
2545 for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E;
2547 const DagInit& Dag = InitPtrToDag(*B);
2548 this->onAction(Dag);
2553 // We're invoked on a command line.
2555 TokenizeCmdline(InitPtrToString(Arg), cmds);
2556 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2558 const std::string& cmd = *B;
2560 if (cmd == "$CALL") {
2561 unsigned NumArgs = 0;
2562 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2563 const std::string& HookName = *B;
2566 if (HookName.at(0) == ')')
2567 throw "$CALL invoked with no arguments!";
2569 while (++B != E && B->at(0) != ')') {
2573 HookInfoMap::const_iterator H = HookNames_.find(HookName);
2575 if (H != HookNames_.end() && H->second.NumArgs != NumArgs &&
2576 H->second.Type != HookInfo::ArgHook)
2577 throw "Overloading of hooks is not allowed. Overloaded hook: "
2580 HookNames_[HookName] = HookInfo(NumArgs);
2586 void operator()(const DagInit* Test, unsigned, bool) {
2587 this->operator()(Test);
2589 void operator()(const Init* Statement, unsigned) {
2590 this->operator()(Statement);
2594 /// FillInHookNames - Actually extract the hook names from all command
2595 /// line strings. Helper function used by EmitHookDeclarations().
2596 void FillInHookNames(const ToolDescriptions& ToolDescs,
2597 const OptionDescriptions& OptDescs,
2598 HookInfoMap& HookNames)
2600 // For all tool descriptions:
2601 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2602 E = ToolDescs.end(); B != E; ++B) {
2603 const ToolDescription& D = *(*B);
2605 // Look for 'forward_transformed_value' in 'actions'.
2607 WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs));
2609 // Look for hook invocations in 'cmd_line'.
2612 if (dynamic_cast<StringInit*>(D.CmdLine))
2613 // This is a string.
2614 ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine);
2616 // This is a 'case' construct.
2617 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs));
2621 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2622 /// property records and emit hook function declaration for each
2623 /// instance of $CALL(HookName).
2624 void EmitHookDeclarations(const ToolDescriptions& ToolDescs,
2625 const OptionDescriptions& OptDescs, raw_ostream& O) {
2626 HookInfoMap HookNames;
2628 FillInHookNames(ToolDescs, OptDescs, HookNames);
2629 if (HookNames.empty())
2632 O << "namespace hooks {\n";
2633 for (HookInfoMap::const_iterator B = HookNames.begin(),
2634 E = HookNames.end(); B != E; ++B) {
2635 const char* HookName = B->first();
2636 const HookInfo& Info = B->second;
2638 O.indent(Indent1) << "std::string " << HookName << "(";
2640 if (Info.Type == HookInfo::ArgHook) {
2641 for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) {
2642 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2646 O << "const std::vector<std::string>& Arg";
2654 /// EmitRegisterPlugin - Emit code to register this plugin.
2655 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2656 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2657 O.indent(Indent1) << "int Priority() const { return "
2658 << Priority << "; }\n\n";
2659 O.indent(Indent1) << "void PreprocessOptions() const\n";
2660 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2661 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2662 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2664 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2665 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2667 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2670 /// EmitIncludes - Emit necessary #include directives and some
2671 /// additional declarations.
2672 void EmitIncludes(raw_ostream& O) {
2673 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2674 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2675 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2676 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2677 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2679 << "#include \"llvm/Support/CommandLine.h\"\n"
2680 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2682 << "#include <algorithm>\n"
2683 << "#include <cstdlib>\n"
2684 << "#include <iterator>\n"
2685 << "#include <stdexcept>\n\n"
2687 << "using namespace llvm;\n"
2688 << "using namespace llvmc;\n\n"
2690 << "extern cl::opt<std::string> OutputFilename;\n\n"
2692 << "inline const char* checkCString(const char* s)\n"
2693 << "{ return s == NULL ? \"\" : s; }\n\n";
2697 /// PluginData - Holds all information about a plugin.
2699 OptionDescriptions OptDescs;
2702 ToolDescriptions ToolDescs;
2707 /// HasSink - Go through the list of tool descriptions and check if
2708 /// there are any with the 'sink' property set.
2709 bool HasSink(const ToolDescriptions& ToolDescs) {
2710 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2711 E = ToolDescs.end(); B != E; ++B)
2718 /// HasExterns - Go through the list of option descriptions and check
2719 /// if there are any external options.
2720 bool HasExterns(const OptionDescriptions& OptDescs) {
2721 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2722 E = OptDescs.end(); B != E; ++B)
2723 if (B->second.isExtern())
2729 /// CollectPluginData - Collect tool and option properties,
2730 /// compilation graph edges and plugin priority from the parse tree.
2731 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2732 // Collect option properties.
2733 const RecordVector& OptionLists =
2734 Records.getAllDerivedDefinitions("OptionList");
2735 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2738 // Collect tool properties.
2739 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2740 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2741 Data.HasSink = HasSink(Data.ToolDescs);
2742 Data.HasExterns = HasExterns(Data.OptDescs);
2744 // Collect compilation graph edges.
2745 const RecordVector& CompilationGraphs =
2746 Records.getAllDerivedDefinitions("CompilationGraph");
2747 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2750 // Calculate the priority of this plugin.
2751 const RecordVector& Priorities =
2752 Records.getAllDerivedDefinitions("PluginPriority");
2753 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2756 /// CheckPluginData - Perform some sanity checks on the collected data.
2757 void CheckPluginData(PluginData& Data) {
2758 // Filter out all tools not mentioned in the compilation graph.
2759 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2761 // Typecheck the compilation graph.
2762 TypecheckGraph(Data.Edges, Data.ToolDescs);
2764 // Check that there are no options without side effects (specified
2765 // only in the OptionList).
2766 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2770 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2771 // Emit file header.
2774 // Emit global option registration code.
2775 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2777 // Emit hook declarations.
2778 EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O);
2780 O << "namespace {\n\n";
2782 // Emit PreprocessOptionsLocal() function.
2783 EmitPreprocessOptions(Records, Data.OptDescs, O);
2785 // Emit PopulateLanguageMapLocal() function
2786 // (language map maps from file extensions to language names).
2787 EmitPopulateLanguageMap(Records, O);
2789 // Emit Tool classes.
2790 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2791 E = Data.ToolDescs.end(); B!=E; ++B)
2792 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2794 // Emit Edge# classes.
2795 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2797 // Emit PopulateCompilationGraphLocal() function.
2798 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2800 // Emit code for plugin registration.
2801 EmitRegisterPlugin(Data.Priority, O);
2803 O << "} // End anonymous namespace.\n\n";
2805 // Force linkage magic.
2806 O << "namespace llvmc {\n";
2807 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2814 // End of anonymous namespace
2817 /// run - The back-end entry point.
2818 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2822 CollectPluginData(Records, Data);
2823 CheckPluginData(Data);
2825 EmitSourceFileHeader("LLVMC Configuration Library", O);
2826 EmitPluginCode(Data, O);
2828 } catch (std::exception& Error) {
2829 throw Error.what() + std::string(" - usually this means a syntax error.");