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 min_arguments) {
102 if (!d || d->getNumArgs() < min_arguments)
103 throw GetOperatorName(d) + ": too few arguments!";
106 // isDagEmpty - is this DAG marked with an empty marker?
107 bool isDagEmpty (const DagInit* d) {
108 return GetOperatorName(d) == "empty_dag_marker";
111 // EscapeVariableName - Escape commas and other symbols not allowed
112 // in the C++ variable names. Makes it possible to use options named
113 // like "Wa," (useful for prefix options).
114 std::string EscapeVariableName(const std::string& Var) {
116 for (unsigned i = 0; i != Var.size(); ++i) {
117 char cur_char = Var[i];
118 if (cur_char == ',') {
121 else if (cur_char == '+') {
124 else if (cur_char == '-') {
128 ret.push_back(cur_char);
134 /// oneOf - Does the input string contain this character?
135 bool oneOf(const char* lst, char c) {
143 template <class I, class S>
144 void checkedIncrement(I& P, I E, S ErrorString) {
150 // apply is needed because C++'s syntax doesn't let us construct a function
151 // object and call it in the same statement.
152 template<typename F, typename T0>
153 void apply(F Fun, T0& Arg0) {
157 template<typename F, typename T0, typename T1>
158 void apply(F Fun, T0& Arg0, T1& Arg1) {
159 return Fun(Arg0, Arg1);
162 //===----------------------------------------------------------------------===//
163 /// Back-end specific code
166 /// OptionType - One of six different option types. See the
167 /// documentation for detailed description of differences.
168 namespace OptionType {
170 enum OptionType { Alias, Switch, Parameter, ParameterList,
173 bool IsAlias(OptionType t) {
177 bool IsList (OptionType t) {
178 return (t == ParameterList || t == PrefixList);
181 bool IsSwitch (OptionType t) {
182 return (t == Switch);
185 bool IsParameter (OptionType t) {
186 return (t == Parameter || t == Prefix);
191 OptionType::OptionType stringToOptionType(const std::string& T) {
192 if (T == "alias_option")
193 return OptionType::Alias;
194 else if (T == "switch_option")
195 return OptionType::Switch;
196 else if (T == "parameter_option")
197 return OptionType::Parameter;
198 else if (T == "parameter_list_option")
199 return OptionType::ParameterList;
200 else if (T == "prefix_option")
201 return OptionType::Prefix;
202 else if (T == "prefix_list_option")
203 return OptionType::PrefixList;
205 throw "Unknown option type: " + T + '!';
208 namespace OptionDescriptionFlags {
209 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
210 ReallyHidden = 0x4, Extern = 0x8,
211 OneOrMore = 0x10, ZeroOrOne = 0x20 };
214 /// OptionDescription - Represents data contained in a single
215 /// OptionList entry.
216 struct OptionDescription {
217 OptionType::OptionType Type;
224 OptionDescription(OptionType::OptionType t = OptionType::Switch,
225 const std::string& n = "",
226 const std::string& h = DefaultHelpString)
227 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
230 /// GenTypeDeclaration - Returns the C++ variable type of this
232 const char* GenTypeDeclaration() const;
234 /// GenVariableName - Returns the variable name used in the
235 /// generated C++ code.
236 std::string GenVariableName() const;
238 /// Merge - Merge two option descriptions.
239 void Merge (const OptionDescription& other);
241 // Misc convenient getters/setters.
243 bool isAlias() const;
245 bool isMultiVal() const;
247 bool isExtern() const;
250 bool isRequired() const;
253 bool isOneOrMore() const;
256 bool isZeroOrOne() const;
259 bool isHidden() const;
262 bool isReallyHidden() const;
263 void setReallyHidden();
265 bool isSwitch() const
266 { return OptionType::IsSwitch(this->Type); }
268 bool isParameter() const
269 { return OptionType::IsParameter(this->Type); }
272 { return OptionType::IsList(this->Type); }
276 void OptionDescription::Merge (const OptionDescription& other)
278 if (other.Type != Type)
279 throw "Conflicting definitions for the option " + Name + "!";
281 if (Help == other.Help || Help == DefaultHelpString)
283 else if (other.Help != DefaultHelpString) {
284 llvm::errs() << "Warning: several different help strings"
285 " defined for option " + Name + "\n";
288 Flags |= other.Flags;
291 bool OptionDescription::isAlias() const {
292 return OptionType::IsAlias(this->Type);
295 bool OptionDescription::isMultiVal() const {
299 bool OptionDescription::isExtern() const {
300 return Flags & OptionDescriptionFlags::Extern;
302 void OptionDescription::setExtern() {
303 Flags |= OptionDescriptionFlags::Extern;
306 bool OptionDescription::isRequired() const {
307 return Flags & OptionDescriptionFlags::Required;
309 void OptionDescription::setRequired() {
310 Flags |= OptionDescriptionFlags::Required;
313 bool OptionDescription::isOneOrMore() const {
314 return Flags & OptionDescriptionFlags::OneOrMore;
316 void OptionDescription::setOneOrMore() {
317 Flags |= OptionDescriptionFlags::OneOrMore;
320 bool OptionDescription::isZeroOrOne() const {
321 return Flags & OptionDescriptionFlags::ZeroOrOne;
323 void OptionDescription::setZeroOrOne() {
324 Flags |= OptionDescriptionFlags::ZeroOrOne;
327 bool OptionDescription::isHidden() const {
328 return Flags & OptionDescriptionFlags::Hidden;
330 void OptionDescription::setHidden() {
331 Flags |= OptionDescriptionFlags::Hidden;
334 bool OptionDescription::isReallyHidden() const {
335 return Flags & OptionDescriptionFlags::ReallyHidden;
337 void OptionDescription::setReallyHidden() {
338 Flags |= OptionDescriptionFlags::ReallyHidden;
341 const char* OptionDescription::GenTypeDeclaration() const {
343 case OptionType::Alias:
345 case OptionType::PrefixList:
346 case OptionType::ParameterList:
347 return "cl::list<std::string>";
348 case OptionType::Switch:
349 return "cl::opt<bool>";
350 case OptionType::Parameter:
351 case OptionType::Prefix:
353 return "cl::opt<std::string>";
357 std::string OptionDescription::GenVariableName() const {
358 const std::string& EscapedName = EscapeVariableName(Name);
360 case OptionType::Alias:
361 return "AutoGeneratedAlias_" + EscapedName;
362 case OptionType::PrefixList:
363 case OptionType::ParameterList:
364 return "AutoGeneratedList_" + EscapedName;
365 case OptionType::Switch:
366 return "AutoGeneratedSwitch_" + EscapedName;
367 case OptionType::Prefix:
368 case OptionType::Parameter:
370 return "AutoGeneratedParameter_" + EscapedName;
374 /// OptionDescriptions - An OptionDescription array plus some helper
376 class OptionDescriptions {
377 typedef StringMap<OptionDescription> container_type;
379 /// Descriptions - A list of OptionDescriptions.
380 container_type Descriptions;
383 /// FindOption - exception-throwing wrapper for find().
384 const OptionDescription& FindOption(const std::string& OptName) const;
386 // Wrappers for FindOption that throw an exception in case the option has a
388 const OptionDescription& FindSwitch(const std::string& OptName) const;
389 const OptionDescription& FindParameter(const std::string& OptName) const;
390 const OptionDescription& FindList(const std::string& OptName) const;
391 const OptionDescription&
392 FindListOrParameter(const std::string& OptName) const;
394 /// insertDescription - Insert new OptionDescription into
395 /// OptionDescriptions list
396 void InsertDescription (const OptionDescription& o);
398 // Support for STL-style iteration
399 typedef container_type::const_iterator const_iterator;
400 const_iterator begin() const { return Descriptions.begin(); }
401 const_iterator end() const { return Descriptions.end(); }
404 const OptionDescription&
405 OptionDescriptions::FindOption(const std::string& OptName) const {
406 const_iterator I = Descriptions.find(OptName);
407 if (I != Descriptions.end())
410 throw OptName + ": no such option!";
413 const OptionDescription&
414 OptionDescriptions::FindSwitch(const std::string& OptName) const {
415 const OptionDescription& OptDesc = this->FindOption(OptName);
416 if (!OptDesc.isSwitch())
417 throw OptName + ": incorrect option type - should be a switch!";
421 const OptionDescription&
422 OptionDescriptions::FindList(const std::string& OptName) const {
423 const OptionDescription& OptDesc = this->FindOption(OptName);
424 if (!OptDesc.isList())
425 throw OptName + ": incorrect option type - should be a list!";
429 const OptionDescription&
430 OptionDescriptions::FindParameter(const std::string& OptName) const {
431 const OptionDescription& OptDesc = this->FindOption(OptName);
432 if (!OptDesc.isParameter())
433 throw OptName + ": incorrect option type - should be a parameter!";
437 const OptionDescription&
438 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
439 const OptionDescription& OptDesc = this->FindOption(OptName);
440 if (!OptDesc.isList() && !OptDesc.isParameter())
442 + ": incorrect option type - should be a list or parameter!";
446 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
447 container_type::iterator I = Descriptions.find(o.Name);
448 if (I != Descriptions.end()) {
449 OptionDescription& D = I->second;
453 Descriptions[o.Name] = o;
457 /// HandlerTable - A base class for function objects implemented as
458 /// 'tables of handlers'.
462 // Implementation details.
465 typedef void (T::* Handler) (const DagInit*);
466 /// HandlerMap - A map from property names to property handlers
467 typedef StringMap<Handler> HandlerMap;
469 static HandlerMap Handlers_;
470 static bool staticMembersInitialized_;
475 HandlerTable(T* cp) : childPtr(cp)
478 /// operator() - Just forwards to the corresponding property
480 void operator() (Init* i) {
481 const DagInit& property = InitPtrToDag(i);
482 const std::string& property_name = GetOperatorName(property);
483 typename HandlerMap::iterator method = Handlers_.find(property_name);
485 if (method != Handlers_.end()) {
486 Handler h = method->second;
487 (childPtr->*h)(&property);
490 throw "No handler found for property " + property_name + "!";
494 void AddHandler(const char* Property, Handler Handl) {
495 Handlers_[Property] = Handl;
499 template <class T> typename HandlerTable<T>::HandlerMap
500 HandlerTable<T>::Handlers_;
501 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
504 /// CollectOptionProperties - Function object for iterating over an
505 /// option property list.
506 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
509 /// optDescs_ - OptionDescriptions table. This is where the
510 /// information is stored.
511 OptionDescription& optDesc_;
515 explicit CollectOptionProperties(OptionDescription& OD)
516 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
518 if (!staticMembersInitialized_) {
519 AddHandler("extern", &CollectOptionProperties::onExtern);
520 AddHandler("help", &CollectOptionProperties::onHelp);
521 AddHandler("hidden", &CollectOptionProperties::onHidden);
522 AddHandler("init", &CollectOptionProperties::onInit);
523 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
524 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
525 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
526 AddHandler("required", &CollectOptionProperties::onRequired);
527 AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
529 staticMembersInitialized_ = true;
535 /// Option property handlers --
536 /// Methods that handle option properties such as (help) or (hidden).
538 void onExtern (const DagInit* d) {
539 checkNumberOfArguments(d, 0);
540 optDesc_.setExtern();
543 void onHelp (const DagInit* d) {
544 checkNumberOfArguments(d, 1);
545 optDesc_.Help = InitPtrToString(d->getArg(0));
548 void onHidden (const DagInit* d) {
549 checkNumberOfArguments(d, 0);
550 optDesc_.setHidden();
553 void onReallyHidden (const DagInit* d) {
554 checkNumberOfArguments(d, 0);
555 optDesc_.setReallyHidden();
558 void onRequired (const DagInit* d) {
559 checkNumberOfArguments(d, 0);
560 if (optDesc_.isOneOrMore())
561 throw std::string("An option can't have both (required) "
562 "and (one_or_more) properties!");
563 optDesc_.setRequired();
566 void onInit (const DagInit* d) {
567 checkNumberOfArguments(d, 1);
568 Init* i = d->getArg(0);
569 const std::string& str = i->getAsString();
571 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
572 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
575 throw std::string("Incorrect usage of the 'init' option property!");
577 optDesc_.InitVal = i;
580 void onOneOrMore (const DagInit* d) {
581 checkNumberOfArguments(d, 0);
582 if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
583 throw std::string("Only one of (required), (zero_or_one) or "
584 "(one_or_more) properties is allowed!");
585 if (!OptionType::IsList(optDesc_.Type))
586 llvm::errs() << "Warning: specifying the 'one_or_more' property "
587 "on a non-list option will have no effect.\n";
588 optDesc_.setOneOrMore();
591 void onZeroOrOne (const DagInit* d) {
592 checkNumberOfArguments(d, 0);
593 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
594 throw std::string("Only one of (required), (zero_or_one) or "
595 "(one_or_more) properties is allowed!");
596 if (!OptionType::IsList(optDesc_.Type))
597 llvm::errs() << "Warning: specifying the 'zero_or_one' property"
598 "on a non-list option will have no effect.\n";
599 optDesc_.setZeroOrOne();
602 void onMultiVal (const DagInit* d) {
603 checkNumberOfArguments(d, 1);
604 int val = InitPtrToInt(d->getArg(0));
606 throw std::string("Error in the 'multi_val' property: "
607 "the value must be greater than 1!");
608 if (!OptionType::IsList(optDesc_.Type))
609 throw std::string("The multi_val property is valid only "
611 optDesc_.MultiVal = val;
616 /// AddOption - A function object that is applied to every option
617 /// description. Used by CollectOptionDescriptions.
620 OptionDescriptions& OptDescs_;
623 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
626 void operator()(const Init* i) {
627 const DagInit& d = InitPtrToDag(i);
628 checkNumberOfArguments(&d, 1);
630 const OptionType::OptionType Type =
631 stringToOptionType(GetOperatorName(d));
632 const std::string& Name = InitPtrToString(d.getArg(0));
634 OptionDescription OD(Type, Name);
637 checkNumberOfArguments(&d, 2);
640 // Aliases store the aliased option name in the 'Help' field.
641 OD.Help = InitPtrToString(d.getArg(1));
643 else if (!OD.isExtern()) {
644 processOptionProperties(&d, OD);
646 OptDescs_.InsertDescription(OD);
650 /// processOptionProperties - Go through the list of option
651 /// properties and call a corresponding handler for each.
652 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
653 checkNumberOfArguments(d, 2);
654 DagInit::const_arg_iterator B = d->arg_begin();
655 // Skip the first argument: it's always the option name.
657 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
662 /// CollectOptionDescriptions - Collects option properties from all
664 void CollectOptionDescriptions (RecordVector::const_iterator B,
665 RecordVector::const_iterator E,
666 OptionDescriptions& OptDescs)
668 // For every OptionList:
670 RecordVector::value_type T = *B;
671 // Throws an exception if the value does not exist.
672 ListInit* PropList = T->getValueAsListInit("options");
674 // For every option description in this list:
675 // collect the information and
676 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
680 // Tool information record
682 namespace ToolFlags {
683 enum ToolFlags { Join = 0x1, Sink = 0x2 };
686 struct ToolDescription : public RefCountedBase<ToolDescription> {
690 StrVector InLanguage;
691 std::string OutLanguage;
692 std::string OutputSuffix;
695 // Various boolean properties
696 void setSink() { Flags |= ToolFlags::Sink; }
697 bool isSink() const { return Flags & ToolFlags::Sink; }
698 void setJoin() { Flags |= ToolFlags::Join; }
699 bool isJoin() const { return Flags & ToolFlags::Join; }
701 // Default ctor here is needed because StringMap can only store
702 // DefaultConstructible objects
703 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
704 ToolDescription (const std::string& n)
705 : Name(n), CmdLine(0), Actions(0), Flags(0)
709 /// ToolDescriptions - A list of Tool information records.
710 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
713 /// CollectToolProperties - Function object for iterating over a list of
714 /// tool property records.
715 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
718 /// toolDesc_ - Properties of the current Tool. This is where the
719 /// information is stored.
720 ToolDescription& toolDesc_;
724 explicit CollectToolProperties (ToolDescription& d)
725 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
727 if (!staticMembersInitialized_) {
729 AddHandler("actions", &CollectToolProperties::onActions);
730 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
731 AddHandler("in_language", &CollectToolProperties::onInLanguage);
732 AddHandler("join", &CollectToolProperties::onJoin);
733 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
734 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
735 AddHandler("sink", &CollectToolProperties::onSink);
737 staticMembersInitialized_ = true;
743 /// Property handlers --
744 /// Functions that extract information about tool properties from
745 /// DAG representation.
747 void onActions (const DagInit* d) {
748 checkNumberOfArguments(d, 1);
749 Init* Case = d->getArg(0);
750 if (typeid(*Case) != typeid(DagInit) ||
751 GetOperatorName(static_cast<DagInit*>(Case)) != "case")
753 std::string("The argument to (actions) should be a 'case' construct!");
754 toolDesc_.Actions = Case;
757 void onCmdLine (const DagInit* d) {
758 checkNumberOfArguments(d, 1);
759 toolDesc_.CmdLine = d->getArg(0);
762 void onInLanguage (const DagInit* d) {
763 checkNumberOfArguments(d, 1);
764 Init* arg = d->getArg(0);
766 // Find out the argument's type.
767 if (typeid(*arg) == typeid(StringInit)) {
769 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
773 const ListInit& lst = InitPtrToList(arg);
774 StrVector& out = toolDesc_.InLanguage;
776 // Copy strings to the output vector.
777 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
779 out.push_back(InitPtrToString(*B));
782 // Remove duplicates.
783 std::sort(out.begin(), out.end());
784 StrVector::iterator newE = std::unique(out.begin(), out.end());
785 out.erase(newE, out.end());
789 void onJoin (const DagInit* d) {
790 checkNumberOfArguments(d, 0);
794 void onOutLanguage (const DagInit* d) {
795 checkNumberOfArguments(d, 1);
796 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
799 void onOutputSuffix (const DagInit* d) {
800 checkNumberOfArguments(d, 1);
801 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
804 void onSink (const DagInit* d) {
805 checkNumberOfArguments(d, 0);
811 /// CollectToolDescriptions - Gather information about tool properties
812 /// from the parsed TableGen data (basically a wrapper for the
813 /// CollectToolProperties function object).
814 void CollectToolDescriptions (RecordVector::const_iterator B,
815 RecordVector::const_iterator E,
816 ToolDescriptions& ToolDescs)
818 // Iterate over a properties list of every Tool definition
820 const Record* T = *B;
821 // Throws an exception if the value does not exist.
822 ListInit* PropList = T->getValueAsListInit("properties");
824 IntrusiveRefCntPtr<ToolDescription>
825 ToolDesc(new ToolDescription(T->getName()));
827 std::for_each(PropList->begin(), PropList->end(),
828 CollectToolProperties(*ToolDesc));
829 ToolDescs.push_back(ToolDesc);
833 /// FillInEdgeVector - Merge all compilation graph definitions into
834 /// one single edge list.
835 void FillInEdgeVector(RecordVector::const_iterator B,
836 RecordVector::const_iterator E, RecordVector& Out) {
837 for (; B != E; ++B) {
838 const ListInit* edges = (*B)->getValueAsListInit("edges");
840 for (unsigned i = 0; i < edges->size(); ++i)
841 Out.push_back(edges->getElementAsRecord(i));
845 /// CalculatePriority - Calculate the priority of this plugin.
846 int CalculatePriority(RecordVector::const_iterator B,
847 RecordVector::const_iterator E) {
851 priority = static_cast<int>((*B)->getValueAsInt("priority"));
854 throw std::string("More than one 'PluginPriority' instance found: "
855 "most probably an error!");
861 /// NotInGraph - Helper function object for FilterNotInGraph.
864 const llvm::StringSet<>& ToolsInGraph_;
867 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
868 : ToolsInGraph_(ToolsInGraph)
871 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
872 return (ToolsInGraph_.count(x->Name) == 0);
876 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
877 /// mentioned in the compilation graph definition.
878 void FilterNotInGraph (const RecordVector& EdgeVector,
879 ToolDescriptions& ToolDescs) {
881 // List all tools mentioned in the graph.
882 llvm::StringSet<> ToolsInGraph;
884 for (RecordVector::const_iterator B = EdgeVector.begin(),
885 E = EdgeVector.end(); B != E; ++B) {
887 const Record* Edge = *B;
888 const std::string& NodeA = Edge->getValueAsString("a");
889 const std::string& NodeB = Edge->getValueAsString("b");
892 ToolsInGraph.insert(NodeA);
893 ToolsInGraph.insert(NodeB);
896 // Filter ToolPropertiesList.
897 ToolDescriptions::iterator new_end =
898 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
899 NotInGraph(ToolsInGraph));
900 ToolDescs.erase(new_end, ToolDescs.end());
903 /// FillInToolToLang - Fills in two tables that map tool names to
904 /// (input, output) languages. Helper function used by TypecheckGraph().
905 void FillInToolToLang (const ToolDescriptions& ToolDescs,
906 StringMap<StringSet<> >& ToolToInLang,
907 StringMap<std::string>& ToolToOutLang) {
908 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
909 E = ToolDescs.end(); B != E; ++B) {
910 const ToolDescription& D = *(*B);
911 for (StrVector::const_iterator B = D.InLanguage.begin(),
912 E = D.InLanguage.end(); B != E; ++B)
913 ToolToInLang[D.Name].insert(*B);
914 ToolToOutLang[D.Name] = D.OutLanguage;
918 /// TypecheckGraph - Check that names for output and input languages
919 /// on all edges do match. This doesn't do much when the information
920 /// about the whole graph is not available (i.e. when compiling most
922 void TypecheckGraph (const RecordVector& EdgeVector,
923 const ToolDescriptions& ToolDescs) {
924 StringMap<StringSet<> > ToolToInLang;
925 StringMap<std::string> ToolToOutLang;
927 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
928 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
929 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
931 for (RecordVector::const_iterator B = EdgeVector.begin(),
932 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");
936 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
937 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
939 if (NodeA != "root") {
940 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
941 throw "Edge " + NodeA + "->" + NodeB
942 + ": output->input language mismatch";
946 throw std::string("Edges back to the root are not allowed!");
950 /// WalkCase - Walks the 'case' expression DAG and invokes
951 /// TestCallback on every test, and StatementCallback on every
952 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
953 /// combinators (that is, they are passed directly to TestCallback).
954 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
955 /// IndentLevel, bool FirstTest)'.
956 /// StatementCallback must have type 'void StatementCallback(const Init*,
957 /// unsigned IndentLevel)'.
958 template <typename F1, typename F2>
959 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
960 unsigned IndentLevel = 0)
962 const DagInit& d = InitPtrToDag(Case);
965 if (GetOperatorName(d) != "case")
966 throw std::string("WalkCase should be invoked only on 'case' expressions!");
968 if (d.getNumArgs() < 2)
969 throw "There should be at least one clause in the 'case' expression:\n"
974 const unsigned numArgs = d.getNumArgs();
976 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
983 const DagInit& Test = InitPtrToDag(arg);
985 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
986 throw std::string("The 'default' clause should be the last in the"
987 "'case' construct!");
989 throw "Case construct handler: no corresponding action "
990 "found for the test " + Test.getAsString() + '!';
992 TestCallback(&Test, IndentLevel, (i == 1));
996 if (dynamic_cast<DagInit*>(arg)
997 && GetOperatorName(static_cast<DagInit*>(arg)) == "case") {
999 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1002 // Handle statement.
1003 StatementCallback(arg, IndentLevel);
1011 /// ExtractOptionNames - A helper function object used by
1012 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1013 class ExtractOptionNames {
1014 llvm::StringSet<>& OptionNames_;
1016 void processDag(const Init* Statement) {
1017 const DagInit& Stmt = InitPtrToDag(Statement);
1018 const std::string& ActionName = GetOperatorName(Stmt);
1019 if (ActionName == "forward" || ActionName == "forward_as" ||
1020 ActionName == "unpack_values" || ActionName == "switch_on" ||
1021 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
1022 ActionName == "not_empty" || ActionName == "empty") {
1023 checkNumberOfArguments(&Stmt, 1);
1024 const std::string& Name = InitPtrToString(Stmt.getArg(0));
1025 OptionNames_.insert(Name);
1027 else if (ActionName == "and" || ActionName == "or") {
1028 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1029 this->processDag(Stmt.getArg(i));
1035 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1038 void operator()(const Init* Statement) {
1039 if (typeid(*Statement) == typeid(ListInit)) {
1040 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1041 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1043 this->processDag(*B);
1046 this->processDag(Statement);
1050 void operator()(const DagInit* Test, unsigned, bool) {
1051 this->operator()(Test);
1053 void operator()(const Init* Statement, unsigned) {
1054 this->operator()(Statement);
1058 /// CheckForSuperfluousOptions - Check that there are no side
1059 /// effect-free options (specified only in the OptionList). Otherwise,
1060 /// output a warning.
1061 void CheckForSuperfluousOptions (const RecordVector& Edges,
1062 const ToolDescriptions& ToolDescs,
1063 const OptionDescriptions& OptDescs) {
1064 llvm::StringSet<> nonSuperfluousOptions;
1066 // Add all options mentioned in the ToolDesc.Actions to the set of
1067 // non-superfluous options.
1068 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1069 E = ToolDescs.end(); B != E; ++B) {
1070 const ToolDescription& TD = *(*B);
1071 ExtractOptionNames Callback(nonSuperfluousOptions);
1073 WalkCase(TD.Actions, Callback, Callback);
1076 // Add all options mentioned in the 'case' clauses of the
1077 // OptionalEdges of the compilation graph to the set of
1078 // non-superfluous options.
1079 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1081 const Record* Edge = *B;
1082 DagInit* Weight = Edge->getValueAsDag("weight");
1084 if (!isDagEmpty(Weight))
1085 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1088 // Check that all options in OptDescs belong to the set of
1089 // non-superfluous options.
1090 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1091 E = OptDescs.end(); B != E; ++B) {
1092 const OptionDescription& Val = B->second;
1093 if (!nonSuperfluousOptions.count(Val.Name)
1094 && Val.Type != OptionType::Alias)
1095 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1096 "Probable cause: this option is specified only in the OptionList.\n";
1100 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1101 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1102 if (TestName == "single_input_file") {
1103 O << "InputFilenames.size() == 1";
1106 else if (TestName == "multiple_input_files") {
1107 O << "InputFilenames.size() > 1";
1114 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1115 template <typename F>
1116 void EmitListTest(const ListInit& L, const char* LogicOp,
1117 F Callback, raw_ostream& O)
1119 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1121 bool isFirst = true;
1122 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1127 Callback(InitPtrToString(*B), O);
1131 // Callbacks for use with EmitListTest.
1133 class EmitSwitchOn {
1134 const OptionDescriptions& OptDescs_;
1136 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1139 void operator()(const std::string& OptName, raw_ostream& O) const {
1140 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1141 O << OptDesc.GenVariableName();
1145 class EmitEmptyTest {
1147 const OptionDescriptions& OptDescs_;
1149 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1150 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1153 void operator()(const std::string& OptName, raw_ostream& O) const {
1154 const char* Neg = (EmitNegate_ ? "!" : "");
1155 if (OptName == "o") {
1156 O << Neg << "OutputFilename.empty()";
1158 else if (OptName == "save-temps") {
1159 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1162 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1163 O << Neg << OptDesc.GenVariableName() << ".empty()";
1169 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1170 bool EmitCaseTest1ArgList(const std::string& TestName,
1172 const OptionDescriptions& OptDescs,
1174 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1176 if (TestName == "any_switch_on") {
1177 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1180 else if (TestName == "switch_on") {
1181 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1184 else if (TestName == "any_not_empty") {
1185 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1188 else if (TestName == "any_empty") {
1189 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1192 else if (TestName == "not_empty") {
1193 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1196 else if (TestName == "empty") {
1197 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1204 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1205 bool EmitCaseTest1ArgStr(const std::string& TestName,
1207 const OptionDescriptions& OptDescs,
1209 const std::string& OptName = InitPtrToString(d.getArg(0));
1211 if (TestName == "switch_on") {
1212 apply(EmitSwitchOn(OptDescs), OptName, O);
1215 else if (TestName == "input_languages_contain") {
1216 O << "InLangs.count(\"" << OptName << "\") != 0";
1219 else if (TestName == "in_language") {
1220 // This works only for single-argument Tool::GenerateAction. Join
1221 // tools can process several files in different languages simultaneously.
1223 // TODO: make this work with Edge::Weight (if possible).
1224 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1227 else if (TestName == "not_empty" || TestName == "empty") {
1228 bool EmitNegate = (TestName == "not_empty");
1229 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1236 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1237 bool EmitCaseTest1Arg(const std::string& TestName,
1239 const OptionDescriptions& OptDescs,
1241 checkNumberOfArguments(&d, 1);
1242 if (typeid(*d.getArg(0)) == typeid(ListInit))
1243 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1245 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1248 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1249 bool EmitCaseTest2Args(const std::string& TestName,
1251 unsigned IndentLevel,
1252 const OptionDescriptions& OptDescs,
1254 checkNumberOfArguments(&d, 2);
1255 const std::string& OptName = InitPtrToString(d.getArg(0));
1256 const std::string& OptArg = InitPtrToString(d.getArg(1));
1258 if (TestName == "parameter_equals") {
1259 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1260 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1263 else if (TestName == "element_in_list") {
1264 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1265 const std::string& VarName = OptDesc.GenVariableName();
1266 O << "std::find(" << VarName << ".begin(),\n";
1267 O.indent(IndentLevel + Indent1)
1268 << VarName << ".end(), \""
1269 << OptArg << "\") != " << VarName << ".end()";
1276 // Forward declaration.
1277 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1278 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1279 const OptionDescriptions& OptDescs,
1282 /// EmitLogicalOperationTest - Helper function used by
1283 /// EmitCaseConstructHandler.
1284 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1285 unsigned IndentLevel,
1286 const OptionDescriptions& OptDescs,
1289 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1290 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1291 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1292 if (j != NumArgs - 1) {
1294 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1302 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1303 const OptionDescriptions& OptDescs, raw_ostream& O)
1305 checkNumberOfArguments(&d, 1);
1306 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1308 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1312 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1313 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1314 const OptionDescriptions& OptDescs,
1316 const std::string& TestName = GetOperatorName(d);
1318 if (TestName == "and")
1319 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1320 else if (TestName == "or")
1321 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1322 else if (TestName == "not")
1323 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1324 else if (EmitCaseTest0Args(TestName, O))
1326 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1328 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1331 throw TestName + ": unknown edge property!";
1335 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1336 class EmitCaseTestCallback {
1338 const OptionDescriptions& OptDescs_;
1342 EmitCaseTestCallback(bool EmitElseIf,
1343 const OptionDescriptions& OptDescs, raw_ostream& O)
1344 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1347 void operator()(const DagInit* Test, unsigned IndentLevel, bool FirstTest)
1349 if (GetOperatorName(Test) == "default") {
1350 O_.indent(IndentLevel) << "else {\n";
1353 O_.indent(IndentLevel)
1354 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1355 EmitCaseTest(*Test, IndentLevel, OptDescs_, O_);
1361 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1362 template <typename F>
1363 class EmitCaseStatementCallback {
1368 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1369 : Callback_(Callback), O_(O)
1372 void operator() (const Init* Statement, unsigned IndentLevel) {
1374 // Ignore nested 'case' DAG.
1375 if (!(dynamic_cast<const DagInit*>(Statement) &&
1376 GetOperatorName(static_cast<const DagInit*>(Statement)) == "case")) {
1377 if (typeid(*Statement) == typeid(ListInit)) {
1378 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1379 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1381 Callback_(*B, (IndentLevel + Indent1), O_);
1384 Callback_(Statement, (IndentLevel + Indent1), O_);
1387 O_.indent(IndentLevel) << "}\n";
1392 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1393 /// construct. Takes a function object that should emit code for every case
1394 /// clause. Implemented on top of WalkCase.
1395 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1396 /// raw_ostream& O).
1397 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1398 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1400 template <typename F>
1401 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1402 F Callback, bool EmitElseIf,
1403 const OptionDescriptions& OptDescs,
1405 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1406 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1409 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1410 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1411 /// Helper function used by EmitCmdLineVecFill and.
1412 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1413 const char* Delimiters = " \t\n\v\f\r";
1415 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1418 if (CmdLine.empty())
1422 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1425 for (; B != E; ++B) {
1426 char cur_ch = CmdLine[B];
1430 if (cur_ch == '$') {
1431 cur_st = SpecialCommand;
1434 if (oneOf(Delimiters, cur_ch)) {
1436 B = CmdLine.find_first_not_of(Delimiters, B);
1437 if (B == std::string::npos) {
1448 case SpecialCommand:
1449 if (oneOf(Delimiters, cur_ch)) {
1454 if (cur_ch == '(') {
1456 cur_st = InsideSpecialCommand;
1461 case InsideSpecialCommand:
1462 if (oneOf(Delimiters, cur_ch)) {
1465 if (cur_ch == '\'') {
1466 cur_st = InsideQuotationMarks;
1470 if (cur_ch == ')') {
1474 if (cur_ch == ',') {
1480 case InsideQuotationMarks:
1481 if (cur_ch == '\'') {
1482 cur_st = InsideSpecialCommand;
1488 Out.back().push_back(cur_ch);
1492 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1493 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1494 StrVector::const_iterator SubstituteSpecialCommands
1495 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1498 const std::string& cmd = *Pos;
1500 if (cmd == "$CALL") {
1501 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1502 const std::string& CmdName = *Pos;
1505 throw std::string("$CALL invocation: empty argument list!");
1508 O << CmdName << "(";
1511 bool firstIteration = true;
1513 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1514 const std::string& Arg = *Pos;
1515 assert(Arg.size() != 0);
1521 firstIteration = false;
1525 O << '"' << Arg << '"';
1531 else if (cmd == "$ENV") {
1532 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1533 const std::string& EnvName = *Pos;
1536 throw "$ENV invocation: empty argument list!";
1538 O << "checkCString(std::getenv(\"";
1542 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1545 throw "Unknown special command: " + cmd;
1548 const std::string& Leftover = *Pos;
1549 assert(Leftover.at(0) == ')');
1550 if (Leftover.size() != 1)
1551 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1556 /// EmitCmdLineVecFill - Emit code that fills in the command line
1557 /// vector. Helper function used by EmitGenerateActionMethod().
1558 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1559 bool IsJoin, unsigned IndentLevel,
1562 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1565 throw "Tool '" + ToolName + "' has empty command line!";
1567 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1569 // If there is a hook invocation on the place of the first command, skip it.
1570 assert(!StrVec[0].empty());
1571 if (StrVec[0][0] == '$') {
1572 while (I != E && (*I)[0] != ')' )
1575 // Skip the ')' symbol.
1582 bool hasINFILE = false;
1584 for (; I != E; ++I) {
1585 const std::string& cmd = *I;
1586 assert(!cmd.empty());
1587 O.indent(IndentLevel);
1588 if (cmd.at(0) == '$') {
1589 if (cmd == "$INFILE") {
1592 O << "for (PathVector::const_iterator B = inFiles.begin()"
1593 << ", E = inFiles.end();\n";
1594 O.indent(IndentLevel) << "B != E; ++B)\n";
1595 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1598 O << "vec.push_back(inFile.str());\n";
1601 else if (cmd == "$OUTFILE") {
1602 O << "vec.push_back(\"\");\n";
1603 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1606 O << "vec.push_back(";
1607 I = SubstituteSpecialCommands(I, E, O);
1612 O << "vec.push_back(\"" << cmd << "\");\n";
1616 throw "Tool '" + ToolName + "' doesn't take any input!";
1618 O.indent(IndentLevel) << "cmd = ";
1619 if (StrVec[0][0] == '$')
1620 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1622 O << '"' << StrVec[0] << '"';
1626 /// EmitCmdLineVecFillCallback - A function object wrapper around
1627 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1628 /// argument to EmitCaseConstructHandler().
1629 class EmitCmdLineVecFillCallback {
1631 const std::string& ToolName;
1633 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1634 : IsJoin(J), ToolName(TN) {}
1636 void operator()(const Init* Statement, unsigned IndentLevel,
1637 raw_ostream& O) const
1639 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1643 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1644 /// implement EmitActionHandler. Emits code for
1645 /// handling the (forward) and (forward_as) option properties.
1646 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1647 unsigned IndentLevel,
1648 const std::string& NewName,
1650 const std::string& Name = NewName.empty()
1653 unsigned IndentLevel1 = IndentLevel + Indent1;
1656 case OptionType::Switch:
1657 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1659 case OptionType::Parameter:
1660 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1661 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1663 case OptionType::Prefix:
1664 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1665 << D.GenVariableName() << ");\n";
1667 case OptionType::PrefixList:
1668 O.indent(IndentLevel)
1669 << "for (" << D.GenTypeDeclaration()
1670 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1671 O.indent(IndentLevel)
1672 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1673 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1674 O.indent(IndentLevel1) << "++B;\n";
1676 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1677 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1678 O.indent(IndentLevel1) << "++B;\n";
1681 O.indent(IndentLevel) << "}\n";
1683 case OptionType::ParameterList:
1684 O.indent(IndentLevel)
1685 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1686 << D.GenVariableName() << ".begin(),\n";
1687 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1688 << ".end() ; B != E;) {\n";
1689 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1691 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1692 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1693 O.indent(IndentLevel1) << "++B;\n";
1696 O.indent(IndentLevel) << "}\n";
1698 case OptionType::Alias:
1700 throw std::string("Aliases are not allowed in tool option descriptions!");
1704 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1705 /// EmitPreprocessOptionsCallback.
1706 struct ActionHandlingCallbackBase {
1708 void onErrorDag(const DagInit& d,
1709 unsigned IndentLevel, raw_ostream& O) const
1711 O.indent(IndentLevel)
1712 << "throw std::runtime_error(\"" <<
1713 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1718 void onWarningDag(const DagInit& d,
1719 unsigned IndentLevel, raw_ostream& O) const
1721 checkNumberOfArguments(&d, 1);
1722 O.indent(IndentLevel) << "llvm::errs() << \""
1723 << InitPtrToString(d.getArg(0)) << "\";\n";
1728 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1729 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1730 class EmitActionHandlersCallback : ActionHandlingCallbackBase {
1731 const OptionDescriptions& OptDescs;
1733 void processActionDag(const Init* Statement, unsigned IndentLevel,
1734 raw_ostream& O) const
1736 const DagInit& Dag = InitPtrToDag(Statement);
1737 const std::string& ActionName = GetOperatorName(Dag);
1739 if (ActionName == "append_cmd") {
1740 checkNumberOfArguments(&Dag, 1);
1741 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1743 llvm::SplitString(Cmd, Out);
1745 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1747 O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1749 else if (ActionName == "error") {
1750 this->onErrorDag(Dag, IndentLevel, O);
1752 else if (ActionName == "warning") {
1753 this->onWarningDag(Dag, IndentLevel, O);
1755 else if (ActionName == "forward") {
1756 checkNumberOfArguments(&Dag, 1);
1757 const std::string& Name = InitPtrToString(Dag.getArg(0));
1758 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1759 IndentLevel, "", O);
1761 else if (ActionName == "forward_as") {
1762 checkNumberOfArguments(&Dag, 2);
1763 const std::string& Name = InitPtrToString(Dag.getArg(0));
1764 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1765 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1766 IndentLevel, NewName, O);
1768 else if (ActionName == "output_suffix") {
1769 checkNumberOfArguments(&Dag, 1);
1770 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1771 O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1773 else if (ActionName == "stop_compilation") {
1774 O.indent(IndentLevel) << "stop_compilation = true;\n";
1776 else if (ActionName == "unpack_values") {
1777 checkNumberOfArguments(&Dag, 1);
1778 const std::string& Name = InitPtrToString(Dag.getArg(0));
1779 const OptionDescription& D = OptDescs.FindOption(Name);
1782 throw std::string("Can't use unpack_values with multi-valued options!");
1785 O.indent(IndentLevel)
1786 << "for (" << D.GenTypeDeclaration()
1787 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1788 O.indent(IndentLevel)
1789 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n";
1790 O.indent(IndentLevel + Indent1)
1791 << "llvm::SplitString(*B, vec, \",\");\n";
1793 else if (D.isParameter()){
1794 O.indent(IndentLevel) << "llvm::SplitString("
1795 << D.GenVariableName() << ", vec, \",\");\n";
1798 throw "Option '" + D.Name +
1799 "': switches can't have the 'unpack_values' property!";
1803 throw "Unknown action name: " + ActionName + "!";
1807 EmitActionHandlersCallback(const OptionDescriptions& OD)
1810 void operator()(const Init* Statement,
1811 unsigned IndentLevel, raw_ostream& O) const
1813 this->processActionDag(Statement, IndentLevel, O);
1817 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1819 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1821 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1823 if (*I == "$OUTFILE")
1830 class IsOutFileIndexCheckRequiredStrCallback {
1834 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1837 void operator()(const Init* CmdLine) {
1838 // Ignore nested 'case' DAG.
1839 if (typeid(*CmdLine) == typeid(DagInit))
1842 if (IsOutFileIndexCheckRequiredStr(CmdLine))
1846 void operator()(const DagInit* Test, unsigned, bool) {
1847 this->operator()(Test);
1849 void operator()(const Init* Statement, unsigned) {
1850 this->operator()(Statement);
1854 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1856 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1860 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1861 /// in EmitGenerateActionMethod() ?
1862 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1863 if (typeid(*CmdLine) == typeid(StringInit))
1864 return IsOutFileIndexCheckRequiredStr(CmdLine);
1866 return IsOutFileIndexCheckRequiredCase(CmdLine);
1869 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
1870 // Tool::GenerateAction() method.
1871 void EmitGenerateActionMethod (const ToolDescription& D,
1872 const OptionDescriptions& OptDescs,
1873 bool IsJoin, raw_ostream& O) {
1875 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1877 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1879 O.indent(Indent2) << "bool HasChildren,\n";
1880 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1881 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1882 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1883 O.indent(Indent1) << "{\n";
1884 O.indent(Indent2) << "std::string cmd;\n";
1885 O.indent(Indent2) << "std::vector<std::string> vec;\n";
1886 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1887 O.indent(Indent2) << "const char* output_suffix = \""
1888 << D.OutputSuffix << "\";\n";
1891 throw "Tool " + D.Name + " has no cmd_line property!";
1893 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
1894 O.indent(Indent2) << "int out_file_index"
1895 << (IndexCheckRequired ? " = -1" : "")
1898 // Process the cmd_line property.
1899 if (typeid(*D.CmdLine) == typeid(StringInit))
1900 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1902 EmitCaseConstructHandler(D.CmdLine, Indent2,
1903 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1906 // For every understood option, emit handling code.
1908 EmitCaseConstructHandler(D.Actions, Indent2,
1909 EmitActionHandlersCallback(OptDescs),
1910 false, OptDescs, O);
1914 << "std::string out_file = OutFilename("
1915 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
1916 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
1918 if (IndexCheckRequired)
1919 O.indent(Indent2) << "if (out_file_index != -1)\n";
1920 O.indent(IndexCheckRequired ? Indent3 : Indent2)
1921 << "vec[out_file_index] = out_file;\n";
1923 // Handle the Sink property.
1925 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
1926 O.indent(Indent3) << "vec.insert(vec.end(), "
1927 << SinkOptionName << ".begin(), " << SinkOptionName
1929 O.indent(Indent2) << "}\n";
1932 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
1933 O.indent(Indent1) << "}\n\n";
1936 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1937 /// a given Tool class.
1938 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1939 const OptionDescriptions& OptDescs,
1941 if (!ToolDesc.isJoin()) {
1942 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1943 O.indent(Indent2) << "bool HasChildren,\n";
1944 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1945 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1946 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1947 O.indent(Indent1) << "{\n";
1948 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
1949 << " is not a Join tool!\");\n";
1950 O.indent(Indent1) << "}\n\n";
1953 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1956 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1959 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1960 /// methods for a given Tool class.
1961 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
1962 O.indent(Indent1) << "const char** InputLanguages() const {\n";
1963 O.indent(Indent2) << "return InputLanguages_;\n";
1964 O.indent(Indent1) << "}\n\n";
1966 if (D.OutLanguage.empty())
1967 throw "Tool " + D.Name + " has no 'out_language' property!";
1969 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
1970 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
1971 O.indent(Indent1) << "}\n\n";
1974 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1975 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
1976 O.indent(Indent1) << "const char* Name() const {\n";
1977 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
1978 O.indent(Indent1) << "}\n\n";
1981 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1983 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
1984 O.indent(Indent1) << "bool IsJoin() const {\n";
1986 O.indent(Indent2) << "return true;\n";
1988 O.indent(Indent2) << "return false;\n";
1989 O.indent(Indent1) << "}\n\n";
1992 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1993 /// given Tool class.
1994 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
1995 if (D.InLanguage.empty())
1996 throw "Tool " + D.Name + " has no 'in_language' property!";
1998 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1999 for (StrVector::const_iterator B = D.InLanguage.begin(),
2000 E = D.InLanguage.end(); B != E; ++B)
2001 O << '\"' << *B << "\", ";
2005 /// EmitToolClassDefinition - Emit a Tool class definition.
2006 void EmitToolClassDefinition (const ToolDescription& D,
2007 const OptionDescriptions& OptDescs,
2009 if (D.Name == "root")
2013 O << "class " << D.Name << " : public ";
2019 O << "{\nprivate:\n";
2020 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2023 EmitNameMethod(D, O);
2024 EmitInOutLanguageMethods(D, O);
2025 EmitIsJoinMethod(D, O);
2026 EmitGenerateActionMethods(D, OptDescs, O);
2028 // Close class definition
2031 EmitStaticMemberDefinitions(D, O);
2035 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2036 /// and emit registration code.
2037 void EmitOptionDefinitions (const OptionDescriptions& descs,
2038 bool HasSink, bool HasExterns,
2041 std::vector<OptionDescription> Aliases;
2043 // Emit static cl::Option variables.
2044 for (OptionDescriptions::const_iterator B = descs.begin(),
2045 E = descs.end(); B!=E; ++B) {
2046 const OptionDescription& val = B->second;
2048 if (val.Type == OptionType::Alias) {
2049 Aliases.push_back(val);
2056 O << val.GenTypeDeclaration() << ' '
2057 << val.GenVariableName();
2059 if (val.isExtern()) {
2064 O << "(\"" << val.Name << "\"\n";
2066 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2067 O << ", cl::Prefix";
2069 if (val.isRequired()) {
2070 if (val.isList() && !val.isMultiVal())
2071 O << ", cl::OneOrMore";
2073 O << ", cl::Required";
2075 else if (val.isOneOrMore() && val.isList()) {
2076 O << ", cl::OneOrMore";
2078 else if (val.isZeroOrOne() && val.isList()) {
2079 O << ", cl::ZeroOrOne";
2082 if (val.isReallyHidden()) {
2083 O << ", cl::ReallyHidden";
2085 else if (val.isHidden()) {
2086 O << ", cl::Hidden";
2089 if (val.MultiVal > 1)
2090 O << ", cl::multi_val(" << val.MultiVal << ')';
2093 const std::string& str = val.InitVal->getAsString();
2094 O << ", cl::init(" << str << ')';
2097 if (!val.Help.empty())
2098 O << ", cl::desc(\"" << val.Help << "\")";
2103 // Emit the aliases (they should go after all the 'proper' options).
2104 for (std::vector<OptionDescription>::const_iterator
2105 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2106 const OptionDescription& val = *B;
2108 O << val.GenTypeDeclaration() << ' '
2109 << val.GenVariableName()
2110 << "(\"" << val.Name << '\"';
2112 const OptionDescription& D = descs.FindOption(val.Help);
2113 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2115 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2118 // Emit the sink option.
2120 O << (HasExterns ? "extern cl" : "cl")
2121 << "::list<std::string> " << SinkOptionName
2122 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2127 /// EmitPreprocessOptionsCallback - Helper function passed to
2128 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2129 class EmitPreprocessOptionsCallback : ActionHandlingCallbackBase {
2130 const OptionDescriptions& OptDescs_;
2132 void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
2133 const std::string& OptName = InitPtrToString(i);
2134 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2136 if (OptDesc.isSwitch()) {
2137 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2139 else if (OptDesc.isParameter()) {
2140 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2142 else if (OptDesc.isList()) {
2143 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2146 throw "Can't apply 'unset_option' to alias option '" + OptName + "'";
2150 void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
2152 const DagInit& d = InitPtrToDag(I);
2153 const std::string& OpName = GetOperatorName(d);
2155 if (OpName == "warning") {
2156 this->onWarningDag(d, IndentLevel, O);
2158 else if (OpName == "error") {
2159 this->onWarningDag(d, IndentLevel, O);
2161 else if (OpName == "unset_option") {
2162 checkNumberOfArguments(&d, 1);
2163 Init* I = d.getArg(0);
2164 if (typeid(*I) == typeid(ListInit)) {
2165 const ListInit& DagList = *static_cast<const ListInit*>(I);
2166 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2168 this->onUnsetOption(*B, IndentLevel, O);
2171 this->onUnsetOption(I, IndentLevel, O);
2175 throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
2176 "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
2182 void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
2183 this->processDag(I, IndentLevel, O);
2186 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2187 : OptDescs_(OptDescs)
2191 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2192 void EmitPreprocessOptions (const RecordKeeper& Records,
2193 const OptionDescriptions& OptDecs, raw_ostream& O)
2195 O << "void PreprocessOptionsLocal() {\n";
2197 const RecordVector& OptionPreprocessors =
2198 Records.getAllDerivedDefinitions("OptionPreprocessor");
2200 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2201 E = OptionPreprocessors.end(); B!=E; ++B) {
2202 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2203 EmitCaseConstructHandler(Case, Indent1,
2204 EmitPreprocessOptionsCallback(OptDecs),
2211 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2212 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2214 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2216 // Get the relevant field out of RecordKeeper
2217 const Record* LangMapRecord = Records.getDef("LanguageMap");
2219 // It is allowed for a plugin to have no language map.
2220 if (LangMapRecord) {
2222 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2223 if (!LangsToSuffixesList)
2224 throw std::string("Error in the language map definition!");
2226 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2227 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2229 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2230 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2232 for (unsigned i = 0; i < Suffixes->size(); ++i)
2233 O.indent(Indent1) << "langMap[\""
2234 << InitPtrToString(Suffixes->getElement(i))
2235 << "\"] = \"" << Lang << "\";\n";
2242 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2243 /// by EmitEdgeClass().
2244 void IncDecWeight (const Init* i, unsigned IndentLevel,
2246 const DagInit& d = InitPtrToDag(i);
2247 const std::string& OpName = GetOperatorName(d);
2249 if (OpName == "inc_weight") {
2250 O.indent(IndentLevel) << "ret += ";
2252 else if (OpName == "dec_weight") {
2253 O.indent(IndentLevel) << "ret -= ";
2255 else if (OpName == "error") {
2256 checkNumberOfArguments(&d, 1);
2257 O.indent(IndentLevel) << "throw std::runtime_error(\""
2258 << InitPtrToString(d.getArg(0))
2263 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2264 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2267 if (d.getNumArgs() > 0)
2268 O << InitPtrToInt(d.getArg(0)) << ";\n";
2274 /// EmitEdgeClass - Emit a single Edge# class.
2275 void EmitEdgeClass (unsigned N, const std::string& Target,
2276 DagInit* Case, const OptionDescriptions& OptDescs,
2279 // Class constructor.
2280 O << "class Edge" << N << ": public Edge {\n"
2282 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2285 // Function Weight().
2287 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2288 O.indent(Indent2) << "unsigned ret = 0;\n";
2290 // Handle the 'case' construct.
2291 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2293 O.indent(Indent2) << "return ret;\n";
2294 O.indent(Indent1) << "};\n\n};\n\n";
2297 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2298 void EmitEdgeClasses (const RecordVector& EdgeVector,
2299 const OptionDescriptions& OptDescs,
2302 for (RecordVector::const_iterator B = EdgeVector.begin(),
2303 E = EdgeVector.end(); B != E; ++B) {
2304 const Record* Edge = *B;
2305 const std::string& NodeB = Edge->getValueAsString("b");
2306 DagInit* Weight = Edge->getValueAsDag("weight");
2308 if (!isDagEmpty(Weight))
2309 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2314 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2316 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2317 const ToolDescriptions& ToolDescs,
2320 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2322 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2323 E = ToolDescs.end(); B != E; ++B)
2324 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2331 for (RecordVector::const_iterator B = EdgeVector.begin(),
2332 E = EdgeVector.end(); B != E; ++B) {
2333 const Record* Edge = *B;
2334 const std::string& NodeA = Edge->getValueAsString("a");
2335 const std::string& NodeB = Edge->getValueAsString("b");
2336 DagInit* Weight = Edge->getValueAsDag("weight");
2338 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2340 if (isDagEmpty(Weight))
2341 O << "new SimpleEdge(\"" << NodeB << "\")";
2343 O << "new Edge" << i << "()";
2352 /// ExtractHookNames - Extract the hook names from all instances of
2353 /// $CALL(HookName) in the provided command line string. Helper
2354 /// function used by FillInHookNames().
2355 class ExtractHookNames {
2356 llvm::StringMap<unsigned>& HookNames_;
2358 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
2359 : HookNames_(HookNames) {}
2361 void operator()(const Init* CmdLine) {
2364 // Ignore nested 'case' DAG.
2365 if (typeid(*CmdLine) == typeid(DagInit))
2368 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
2369 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2371 const std::string& cmd = *B;
2373 if (cmd == "$CALL") {
2374 unsigned NumArgs = 0;
2375 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2376 const std::string& HookName = *B;
2379 if (HookName.at(0) == ')')
2380 throw "$CALL invoked with no arguments!";
2382 while (++B != E && B->at(0) != ')') {
2386 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
2388 if (H != HookNames_.end() && H->second != NumArgs)
2389 throw "Overloading of hooks is not allowed. Overloaded hook: "
2392 HookNames_[HookName] = NumArgs;
2398 void operator()(const DagInit* Test, unsigned, bool) {
2399 this->operator()(Test);
2401 void operator()(const Init* Statement, unsigned) {
2402 this->operator()(Statement);
2406 /// FillInHookNames - Actually extract the hook names from all command
2407 /// line strings. Helper function used by EmitHookDeclarations().
2408 void FillInHookNames(const ToolDescriptions& ToolDescs,
2409 llvm::StringMap<unsigned>& HookNames)
2411 // For all command lines:
2412 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2413 E = ToolDescs.end(); B != E; ++B) {
2414 const ToolDescription& D = *(*B);
2417 if (dynamic_cast<StringInit*>(D.CmdLine))
2418 // This is a string.
2419 ExtractHookNames(HookNames).operator()(D.CmdLine);
2421 // This is a 'case' construct.
2422 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
2426 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2427 /// property records and emit hook function declaration for each
2428 /// instance of $CALL(HookName).
2429 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
2430 llvm::StringMap<unsigned> HookNames;
2432 FillInHookNames(ToolDescs, HookNames);
2433 if (HookNames.empty())
2436 O << "namespace hooks {\n";
2437 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
2438 E = HookNames.end(); B != E; ++B) {
2439 O.indent(Indent1) << "std::string " << B->first() << "(";
2441 for (unsigned i = 0, j = B->second; i < j; ++i) {
2442 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2450 /// EmitRegisterPlugin - Emit code to register this plugin.
2451 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2452 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2453 O.indent(Indent1) << "int Priority() const { return "
2454 << Priority << "; }\n\n";
2455 O.indent(Indent1) << "void PreprocessOptions() const\n";
2456 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2457 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2458 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2460 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2461 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2463 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2466 /// EmitIncludes - Emit necessary #include directives and some
2467 /// additional declarations.
2468 void EmitIncludes(raw_ostream& O) {
2469 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2470 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2471 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2472 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2473 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2475 << "#include \"llvm/ADT/StringExtras.h\"\n"
2476 << "#include \"llvm/Support/CommandLine.h\"\n"
2477 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2479 << "#include <cstdlib>\n"
2480 << "#include <stdexcept>\n\n"
2482 << "using namespace llvm;\n"
2483 << "using namespace llvmc;\n\n"
2485 << "extern cl::opt<std::string> OutputFilename;\n\n"
2487 << "inline const char* checkCString(const char* s)\n"
2488 << "{ return s == NULL ? \"\" : s; }\n\n";
2492 /// PluginData - Holds all information about a plugin.
2494 OptionDescriptions OptDescs;
2497 ToolDescriptions ToolDescs;
2502 /// HasSink - Go through the list of tool descriptions and check if
2503 /// there are any with the 'sink' property set.
2504 bool HasSink(const ToolDescriptions& ToolDescs) {
2505 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2506 E = ToolDescs.end(); B != E; ++B)
2513 /// HasExterns - Go through the list of option descriptions and check
2514 /// if there are any external options.
2515 bool HasExterns(const OptionDescriptions& OptDescs) {
2516 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2517 E = OptDescs.end(); B != E; ++B)
2518 if (B->second.isExtern())
2524 /// CollectPluginData - Collect tool and option properties,
2525 /// compilation graph edges and plugin priority from the parse tree.
2526 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2527 // Collect option properties.
2528 const RecordVector& OptionLists =
2529 Records.getAllDerivedDefinitions("OptionList");
2530 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2533 // Collect tool properties.
2534 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2535 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2536 Data.HasSink = HasSink(Data.ToolDescs);
2537 Data.HasExterns = HasExterns(Data.OptDescs);
2539 // Collect compilation graph edges.
2540 const RecordVector& CompilationGraphs =
2541 Records.getAllDerivedDefinitions("CompilationGraph");
2542 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2545 // Calculate the priority of this plugin.
2546 const RecordVector& Priorities =
2547 Records.getAllDerivedDefinitions("PluginPriority");
2548 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2551 /// CheckPluginData - Perform some sanity checks on the collected data.
2552 void CheckPluginData(PluginData& Data) {
2553 // Filter out all tools not mentioned in the compilation graph.
2554 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2556 // Typecheck the compilation graph.
2557 TypecheckGraph(Data.Edges, Data.ToolDescs);
2559 // Check that there are no options without side effects (specified
2560 // only in the OptionList).
2561 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2565 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2566 // Emit file header.
2569 // Emit global option registration code.
2570 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2572 // Emit hook declarations.
2573 EmitHookDeclarations(Data.ToolDescs, O);
2575 O << "namespace {\n\n";
2577 // Emit PreprocessOptionsLocal() function.
2578 EmitPreprocessOptions(Records, Data.OptDescs, O);
2580 // Emit PopulateLanguageMapLocal() function
2581 // (language map maps from file extensions to language names).
2582 EmitPopulateLanguageMap(Records, O);
2584 // Emit Tool classes.
2585 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2586 E = Data.ToolDescs.end(); B!=E; ++B)
2587 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2589 // Emit Edge# classes.
2590 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2592 // Emit PopulateCompilationGraphLocal() function.
2593 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2595 // Emit code for plugin registration.
2596 EmitRegisterPlugin(Data.Priority, O);
2598 O << "} // End anonymous namespace.\n\n";
2600 // Force linkage magic.
2601 O << "namespace llvmc {\n";
2602 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2609 // End of anonymous namespace
2612 /// run - The back-end entry point.
2613 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2617 CollectPluginData(Records, Data);
2618 CheckPluginData(Data);
2620 EmitSourceFileHeader("LLVMC Configuration Library", O);
2621 EmitPluginCode(Data, O);
2623 } catch (std::exception& Error) {
2624 throw Error.what() + std::string(" - usually this means a syntax error.");