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"
33 //===----------------------------------------------------------------------===//
36 typedef std::vector<Record*> RecordVector;
37 typedef std::vector<std::string> StrVector;
39 //===----------------------------------------------------------------------===//
43 unsigned TabWidth = 4;
44 unsigned Indent1 = TabWidth*1;
45 unsigned Indent2 = TabWidth*2;
46 unsigned Indent3 = TabWidth*3;
48 // Default help string.
49 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51 // Name for the "sink" option.
52 const char * SinkOptionName = "AutoGeneratedSinkOption";
54 //===----------------------------------------------------------------------===//
57 /// Id - An 'identity' function object.
60 void operator()(const T&) const {
64 int InitPtrToInt(const Init* ptr) {
65 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
66 return val.getValue();
69 const std::string& InitPtrToString(const Init* ptr) {
70 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
71 return val.getValue();
74 const ListInit& InitPtrToList(const Init* ptr) {
75 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
79 const DagInit& InitPtrToDag(const Init* ptr) {
80 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
84 // checkNumberOfArguments - Ensure that the number of args in d is
85 // greater than or equal to min_arguments, otherwise throw an exception.
86 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
87 if (!d || d->getNumArgs() < min_arguments)
88 throw d->getOperator()->getAsString() + ": too few arguments!";
91 // isDagEmpty - is this DAG marked with an empty marker?
92 bool isDagEmpty (const DagInit* d) {
93 return d->getOperator()->getAsString() == "empty_dag_marker";
96 // EscapeVariableName - Escape commas and other symbols not allowed
97 // in the C++ variable names. Makes it possible to use options named
98 // like "Wa," (useful for prefix options).
99 std::string EscapeVariableName(const std::string& Var) {
101 for (unsigned i = 0; i != Var.size(); ++i) {
102 char cur_char = Var[i];
103 if (cur_char == ',') {
106 else if (cur_char == '+') {
109 else if (cur_char == '-') {
113 ret.push_back(cur_char);
119 /// oneOf - Does the input string contain this character?
120 bool oneOf(const char* lst, char c) {
128 template <class I, class S>
129 void checkedIncrement(I& P, I E, S ErrorString) {
135 //===----------------------------------------------------------------------===//
136 /// Back-end specific code
139 /// OptionType - One of six different option types. See the
140 /// documentation for detailed description of differences.
141 namespace OptionType {
143 enum OptionType { Alias, Switch, Parameter, ParameterList,
146 bool IsList (OptionType t) {
147 return (t == ParameterList || t == PrefixList);
150 bool IsSwitch (OptionType t) {
151 return (t == Switch);
154 bool IsParameter (OptionType t) {
155 return (t == Parameter || t == Prefix);
160 OptionType::OptionType stringToOptionType(const std::string& T) {
161 if (T == "alias_option")
162 return OptionType::Alias;
163 else if (T == "switch_option")
164 return OptionType::Switch;
165 else if (T == "parameter_option")
166 return OptionType::Parameter;
167 else if (T == "parameter_list_option")
168 return OptionType::ParameterList;
169 else if (T == "prefix_option")
170 return OptionType::Prefix;
171 else if (T == "prefix_list_option")
172 return OptionType::PrefixList;
174 throw "Unknown option type: " + T + '!';
177 namespace OptionDescriptionFlags {
178 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
179 ReallyHidden = 0x4, Extern = 0x8,
180 OneOrMore = 0x10, ZeroOrOne = 0x20 };
183 /// OptionDescription - Represents data contained in a single
184 /// OptionList entry.
185 struct OptionDescription {
186 OptionType::OptionType Type;
193 OptionDescription(OptionType::OptionType t = OptionType::Switch,
194 const std::string& n = "",
195 const std::string& h = DefaultHelpString)
196 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
199 /// GenTypeDeclaration - Returns the C++ variable type of this
201 const char* GenTypeDeclaration() const;
203 /// GenVariableName - Returns the variable name used in the
204 /// generated C++ code.
205 std::string GenVariableName() const;
207 /// Merge - Merge two option descriptions.
208 void Merge (const OptionDescription& other);
210 // Misc convenient getters/setters.
212 bool isAlias() const;
214 bool isMultiVal() const;
216 bool isExtern() const;
219 bool isRequired() const;
222 bool isOneOrMore() const;
225 bool isZeroOrOne() const;
228 bool isHidden() const;
231 bool isReallyHidden() const;
232 void setReallyHidden();
234 bool isParameter() const
235 { return OptionType::IsParameter(this->Type); }
237 bool isSwitch() const
238 { return OptionType::IsSwitch(this->Type); }
241 { return OptionType::IsList(this->Type); }
245 void OptionDescription::Merge (const OptionDescription& other)
247 if (other.Type != Type)
248 throw "Conflicting definitions for the option " + Name + "!";
250 if (Help == other.Help || Help == DefaultHelpString)
252 else if (other.Help != DefaultHelpString) {
253 llvm::errs() << "Warning: several different help strings"
254 " defined for option " + Name + "\n";
257 Flags |= other.Flags;
260 bool OptionDescription::isAlias() const {
261 return Type == OptionType::Alias;
264 bool OptionDescription::isMultiVal() const {
268 bool OptionDescription::isExtern() const {
269 return Flags & OptionDescriptionFlags::Extern;
271 void OptionDescription::setExtern() {
272 Flags |= OptionDescriptionFlags::Extern;
275 bool OptionDescription::isRequired() const {
276 return Flags & OptionDescriptionFlags::Required;
278 void OptionDescription::setRequired() {
279 Flags |= OptionDescriptionFlags::Required;
282 bool OptionDescription::isOneOrMore() const {
283 return Flags & OptionDescriptionFlags::OneOrMore;
285 void OptionDescription::setOneOrMore() {
286 Flags |= OptionDescriptionFlags::OneOrMore;
289 bool OptionDescription::isZeroOrOne() const {
290 return Flags & OptionDescriptionFlags::ZeroOrOne;
292 void OptionDescription::setZeroOrOne() {
293 Flags |= OptionDescriptionFlags::ZeroOrOne;
296 bool OptionDescription::isHidden() const {
297 return Flags & OptionDescriptionFlags::Hidden;
299 void OptionDescription::setHidden() {
300 Flags |= OptionDescriptionFlags::Hidden;
303 bool OptionDescription::isReallyHidden() const {
304 return Flags & OptionDescriptionFlags::ReallyHidden;
306 void OptionDescription::setReallyHidden() {
307 Flags |= OptionDescriptionFlags::ReallyHidden;
310 const char* OptionDescription::GenTypeDeclaration() const {
312 case OptionType::Alias:
314 case OptionType::PrefixList:
315 case OptionType::ParameterList:
316 return "cl::list<std::string>";
317 case OptionType::Switch:
318 return "cl::opt<bool>";
319 case OptionType::Parameter:
320 case OptionType::Prefix:
322 return "cl::opt<std::string>";
326 std::string OptionDescription::GenVariableName() const {
327 const std::string& EscapedName = EscapeVariableName(Name);
329 case OptionType::Alias:
330 return "AutoGeneratedAlias_" + EscapedName;
331 case OptionType::PrefixList:
332 case OptionType::ParameterList:
333 return "AutoGeneratedList_" + EscapedName;
334 case OptionType::Switch:
335 return "AutoGeneratedSwitch_" + EscapedName;
336 case OptionType::Prefix:
337 case OptionType::Parameter:
339 return "AutoGeneratedParameter_" + EscapedName;
343 /// OptionDescriptions - An OptionDescription array plus some helper
345 class OptionDescriptions {
346 typedef StringMap<OptionDescription> container_type;
348 /// Descriptions - A list of OptionDescriptions.
349 container_type Descriptions;
352 /// FindOption - exception-throwing wrapper for find().
353 const OptionDescription& FindOption(const std::string& OptName) const;
355 /// insertDescription - Insert new OptionDescription into
356 /// OptionDescriptions list
357 void InsertDescription (const OptionDescription& o);
359 // Support for STL-style iteration
360 typedef container_type::const_iterator const_iterator;
361 const_iterator begin() const { return Descriptions.begin(); }
362 const_iterator end() const { return Descriptions.end(); }
365 const OptionDescription&
366 OptionDescriptions::FindOption(const std::string& OptName) const
368 const_iterator I = Descriptions.find(OptName);
369 if (I != Descriptions.end())
372 throw OptName + ": no such option!";
375 void OptionDescriptions::InsertDescription (const OptionDescription& o)
377 container_type::iterator I = Descriptions.find(o.Name);
378 if (I != Descriptions.end()) {
379 OptionDescription& D = I->second;
383 Descriptions[o.Name] = o;
387 /// HandlerTable - A base class for function objects implemented as
388 /// 'tables of handlers'.
392 // Implementation details.
395 typedef void (T::* Handler) (const DagInit*);
396 /// HandlerMap - A map from property names to property handlers
397 typedef StringMap<Handler> HandlerMap;
399 static HandlerMap Handlers_;
400 static bool staticMembersInitialized_;
405 HandlerTable(T* cp) : childPtr(cp)
408 /// operator() - Just forwards to the corresponding property
410 void operator() (Init* i) {
411 const DagInit& property = InitPtrToDag(i);
412 const std::string& property_name = property.getOperator()->getAsString();
413 typename HandlerMap::iterator method = Handlers_.find(property_name);
415 if (method != Handlers_.end()) {
416 Handler h = method->second;
417 (childPtr->*h)(&property);
420 throw "No handler found for property " + property_name + "!";
424 void AddHandler(const char* Property, Handler Handl) {
425 Handlers_[Property] = Handl;
429 template <class T> typename HandlerTable<T>::HandlerMap
430 HandlerTable<T>::Handlers_;
431 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
434 /// CollectOptionProperties - Function object for iterating over an
435 /// option property list.
436 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
439 /// optDescs_ - OptionDescriptions table. This is where the
440 /// information is stored.
441 OptionDescription& optDesc_;
445 explicit CollectOptionProperties(OptionDescription& OD)
446 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
448 if (!staticMembersInitialized_) {
449 AddHandler("extern", &CollectOptionProperties::onExtern);
450 AddHandler("help", &CollectOptionProperties::onHelp);
451 AddHandler("hidden", &CollectOptionProperties::onHidden);
452 AddHandler("init", &CollectOptionProperties::onInit);
453 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
454 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
455 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
456 AddHandler("required", &CollectOptionProperties::onRequired);
457 AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
459 staticMembersInitialized_ = true;
465 /// Option property handlers --
466 /// Methods that handle option properties such as (help) or (hidden).
468 void onExtern (const DagInit* d) {
469 checkNumberOfArguments(d, 0);
470 optDesc_.setExtern();
473 void onHelp (const DagInit* d) {
474 checkNumberOfArguments(d, 1);
475 optDesc_.Help = InitPtrToString(d->getArg(0));
478 void onHidden (const DagInit* d) {
479 checkNumberOfArguments(d, 0);
480 optDesc_.setHidden();
483 void onReallyHidden (const DagInit* d) {
484 checkNumberOfArguments(d, 0);
485 optDesc_.setReallyHidden();
488 void onRequired (const DagInit* d) {
489 checkNumberOfArguments(d, 0);
490 if (optDesc_.isOneOrMore())
491 throw std::string("An option can't have both (required) "
492 "and (one_or_more) properties!");
493 optDesc_.setRequired();
496 void onInit (const DagInit* d) {
497 checkNumberOfArguments(d, 1);
498 Init* i = d->getArg(0);
499 const std::string& str = i->getAsString();
501 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
502 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
505 throw std::string("Incorrect usage of the 'init' option property!");
507 optDesc_.InitVal = i;
510 void onOneOrMore (const DagInit* d) {
511 checkNumberOfArguments(d, 0);
512 if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
513 throw std::string("Only one of (required), (zero_or_one) or "
514 "(one_or_more) properties is allowed!");
515 if (!OptionType::IsList(optDesc_.Type))
516 llvm::errs() << "Warning: specifying the 'one_or_more' property "
517 "on a non-list option will have no effect.\n";
518 optDesc_.setOneOrMore();
521 void onZeroOrOne (const DagInit* d) {
522 checkNumberOfArguments(d, 0);
523 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
524 throw std::string("Only one of (required), (zero_or_one) or "
525 "(one_or_more) properties is allowed!");
526 if (!OptionType::IsList(optDesc_.Type))
527 llvm::errs() << "Warning: specifying the 'zero_or_one' property"
528 "on a non-list option will have no effect.\n";
529 optDesc_.setZeroOrOne();
532 void onMultiVal (const DagInit* d) {
533 checkNumberOfArguments(d, 1);
534 int val = InitPtrToInt(d->getArg(0));
536 throw std::string("Error in the 'multi_val' property: "
537 "the value must be greater than 1!");
538 if (!OptionType::IsList(optDesc_.Type))
539 throw std::string("The multi_val property is valid only "
541 optDesc_.MultiVal = val;
546 /// AddOption - A function object that is applied to every option
547 /// description. Used by CollectOptionDescriptions.
550 OptionDescriptions& OptDescs_;
553 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
556 void operator()(const Init* i) {
557 const DagInit& d = InitPtrToDag(i);
558 checkNumberOfArguments(&d, 1);
560 const OptionType::OptionType Type =
561 stringToOptionType(d.getOperator()->getAsString());
562 const std::string& Name = InitPtrToString(d.getArg(0));
564 OptionDescription OD(Type, Name);
567 checkNumberOfArguments(&d, 2);
570 // Aliases store the aliased option name in the 'Help' field.
571 OD.Help = InitPtrToString(d.getArg(1));
573 else if (!OD.isExtern()) {
574 processOptionProperties(&d, OD);
576 OptDescs_.InsertDescription(OD);
580 /// processOptionProperties - Go through the list of option
581 /// properties and call a corresponding handler for each.
582 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
583 checkNumberOfArguments(d, 2);
584 DagInit::const_arg_iterator B = d->arg_begin();
585 // Skip the first argument: it's always the option name.
587 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
592 /// CollectOptionDescriptions - Collects option properties from all
594 void CollectOptionDescriptions (RecordVector::const_iterator B,
595 RecordVector::const_iterator E,
596 OptionDescriptions& OptDescs)
598 // For every OptionList:
600 RecordVector::value_type T = *B;
601 // Throws an exception if the value does not exist.
602 ListInit* PropList = T->getValueAsListInit("options");
604 // For every option description in this list:
605 // collect the information and
606 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
610 // Tool information record
612 namespace ToolFlags {
613 enum ToolFlags { Join = 0x1, Sink = 0x2 };
616 struct ToolDescription : public RefCountedBase<ToolDescription> {
620 StrVector InLanguage;
621 std::string OutLanguage;
622 std::string OutputSuffix;
625 // Various boolean properties
626 void setSink() { Flags |= ToolFlags::Sink; }
627 bool isSink() const { return Flags & ToolFlags::Sink; }
628 void setJoin() { Flags |= ToolFlags::Join; }
629 bool isJoin() const { return Flags & ToolFlags::Join; }
631 // Default ctor here is needed because StringMap can only store
632 // DefaultConstructible objects
633 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
634 ToolDescription (const std::string& n)
635 : Name(n), CmdLine(0), Actions(0), Flags(0)
639 /// ToolDescriptions - A list of Tool information records.
640 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
643 /// CollectToolProperties - Function object for iterating over a list of
644 /// tool property records.
645 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
648 /// toolDesc_ - Properties of the current Tool. This is where the
649 /// information is stored.
650 ToolDescription& toolDesc_;
654 explicit CollectToolProperties (ToolDescription& d)
655 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
657 if (!staticMembersInitialized_) {
659 AddHandler("actions", &CollectToolProperties::onActions);
660 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
661 AddHandler("in_language", &CollectToolProperties::onInLanguage);
662 AddHandler("join", &CollectToolProperties::onJoin);
663 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
664 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
665 AddHandler("sink", &CollectToolProperties::onSink);
667 staticMembersInitialized_ = true;
673 /// Property handlers --
674 /// Functions that extract information about tool properties from
675 /// DAG representation.
677 void onActions (const DagInit* d) {
678 checkNumberOfArguments(d, 1);
679 Init* Case = d->getArg(0);
680 if (typeid(*Case) != typeid(DagInit) ||
681 static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
683 std::string("The argument to (actions) should be a 'case' construct!");
684 toolDesc_.Actions = Case;
687 void onCmdLine (const DagInit* d) {
688 checkNumberOfArguments(d, 1);
689 toolDesc_.CmdLine = d->getArg(0);
692 void onInLanguage (const DagInit* d) {
693 checkNumberOfArguments(d, 1);
694 Init* arg = d->getArg(0);
696 // Find out the argument's type.
697 if (typeid(*arg) == typeid(StringInit)) {
699 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
703 const ListInit& lst = InitPtrToList(arg);
704 StrVector& out = toolDesc_.InLanguage;
706 // Copy strings to the output vector.
707 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
709 out.push_back(InitPtrToString(*B));
712 // Remove duplicates.
713 std::sort(out.begin(), out.end());
714 StrVector::iterator newE = std::unique(out.begin(), out.end());
715 out.erase(newE, out.end());
719 void onJoin (const DagInit* d) {
720 checkNumberOfArguments(d, 0);
724 void onOutLanguage (const DagInit* d) {
725 checkNumberOfArguments(d, 1);
726 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
729 void onOutputSuffix (const DagInit* d) {
730 checkNumberOfArguments(d, 1);
731 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
734 void onSink (const DagInit* d) {
735 checkNumberOfArguments(d, 0);
741 /// CollectToolDescriptions - Gather information about tool properties
742 /// from the parsed TableGen data (basically a wrapper for the
743 /// CollectToolProperties function object).
744 void CollectToolDescriptions (RecordVector::const_iterator B,
745 RecordVector::const_iterator E,
746 ToolDescriptions& ToolDescs)
748 // Iterate over a properties list of every Tool definition
750 const Record* T = *B;
751 // Throws an exception if the value does not exist.
752 ListInit* PropList = T->getValueAsListInit("properties");
754 IntrusiveRefCntPtr<ToolDescription>
755 ToolDesc(new ToolDescription(T->getName()));
757 std::for_each(PropList->begin(), PropList->end(),
758 CollectToolProperties(*ToolDesc));
759 ToolDescs.push_back(ToolDesc);
763 /// FillInEdgeVector - Merge all compilation graph definitions into
764 /// one single edge list.
765 void FillInEdgeVector(RecordVector::const_iterator B,
766 RecordVector::const_iterator E, RecordVector& Out) {
767 for (; B != E; ++B) {
768 const ListInit* edges = (*B)->getValueAsListInit("edges");
770 for (unsigned i = 0; i < edges->size(); ++i)
771 Out.push_back(edges->getElementAsRecord(i));
775 /// CalculatePriority - Calculate the priority of this plugin.
776 int CalculatePriority(RecordVector::const_iterator B,
777 RecordVector::const_iterator E) {
780 total += static_cast<int>((*B)->getValueAsInt("priority"));
785 /// NotInGraph - Helper function object for FilterNotInGraph.
788 const llvm::StringSet<>& ToolsInGraph_;
791 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
792 : ToolsInGraph_(ToolsInGraph)
795 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
796 return (ToolsInGraph_.count(x->Name) == 0);
800 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
801 /// mentioned in the compilation graph definition.
802 void FilterNotInGraph (const RecordVector& EdgeVector,
803 ToolDescriptions& ToolDescs) {
805 // List all tools mentioned in the graph.
806 llvm::StringSet<> ToolsInGraph;
808 for (RecordVector::const_iterator B = EdgeVector.begin(),
809 E = EdgeVector.end(); B != E; ++B) {
811 const Record* Edge = *B;
812 const std::string& NodeA = Edge->getValueAsString("a");
813 const std::string& NodeB = Edge->getValueAsString("b");
816 ToolsInGraph.insert(NodeA);
817 ToolsInGraph.insert(NodeB);
820 // Filter ToolPropertiesList.
821 ToolDescriptions::iterator new_end =
822 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
823 NotInGraph(ToolsInGraph));
824 ToolDescs.erase(new_end, ToolDescs.end());
827 /// FillInToolToLang - Fills in two tables that map tool names to
828 /// (input, output) languages. Helper function used by TypecheckGraph().
829 void FillInToolToLang (const ToolDescriptions& ToolDescs,
830 StringMap<StringSet<> >& ToolToInLang,
831 StringMap<std::string>& ToolToOutLang) {
832 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
833 E = ToolDescs.end(); B != E; ++B) {
834 const ToolDescription& D = *(*B);
835 for (StrVector::const_iterator B = D.InLanguage.begin(),
836 E = D.InLanguage.end(); B != E; ++B)
837 ToolToInLang[D.Name].insert(*B);
838 ToolToOutLang[D.Name] = D.OutLanguage;
842 /// TypecheckGraph - Check that names for output and input languages
843 /// on all edges do match. This doesn't do much when the information
844 /// about the whole graph is not available (i.e. when compiling most
846 void TypecheckGraph (const RecordVector& EdgeVector,
847 const ToolDescriptions& ToolDescs) {
848 StringMap<StringSet<> > ToolToInLang;
849 StringMap<std::string> ToolToOutLang;
851 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
852 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
853 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
855 for (RecordVector::const_iterator B = EdgeVector.begin(),
856 E = EdgeVector.end(); B != E; ++B) {
857 const Record* Edge = *B;
858 const std::string& NodeA = Edge->getValueAsString("a");
859 const std::string& NodeB = Edge->getValueAsString("b");
860 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
861 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
863 if (NodeA != "root") {
864 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
865 throw "Edge " + NodeA + "->" + NodeB
866 + ": output->input language mismatch";
870 throw std::string("Edges back to the root are not allowed!");
874 /// WalkCase - Walks the 'case' expression DAG and invokes
875 /// TestCallback on every test, and StatementCallback on every
876 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
878 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
879 template <typename F1, typename F2>
880 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
881 const DagInit& d = InitPtrToDag(Case);
883 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
886 if (even && dynamic_cast<DagInit*>(arg)
887 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
888 WalkCase(arg, TestCallback, StatementCallback);
892 StatementCallback(arg);
897 /// ExtractOptionNames - A helper function object used by
898 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
899 class ExtractOptionNames {
900 llvm::StringSet<>& OptionNames_;
902 void processDag(const Init* Statement) {
903 const DagInit& Stmt = InitPtrToDag(Statement);
904 const std::string& ActionName = Stmt.getOperator()->getAsString();
905 if (ActionName == "forward" || ActionName == "forward_as" ||
906 ActionName == "unpack_values" || ActionName == "switch_on" ||
907 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
908 ActionName == "not_empty" || ActionName == "empty") {
909 checkNumberOfArguments(&Stmt, 1);
910 const std::string& Name = InitPtrToString(Stmt.getArg(0));
911 OptionNames_.insert(Name);
913 else if (ActionName == "and" || ActionName == "or") {
914 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
915 this->processDag(Stmt.getArg(i));
921 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
924 void operator()(const Init* Statement) {
925 if (typeid(*Statement) == typeid(ListInit)) {
926 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
927 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
929 this->processDag(*B);
932 this->processDag(Statement);
937 /// CheckForSuperfluousOptions - Check that there are no side
938 /// effect-free options (specified only in the OptionList). Otherwise,
939 /// output a warning.
940 void CheckForSuperfluousOptions (const RecordVector& Edges,
941 const ToolDescriptions& ToolDescs,
942 const OptionDescriptions& OptDescs) {
943 llvm::StringSet<> nonSuperfluousOptions;
945 // Add all options mentioned in the ToolDesc.Actions to the set of
946 // non-superfluous options.
947 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
948 E = ToolDescs.end(); B != E; ++B) {
949 const ToolDescription& TD = *(*B);
950 ExtractOptionNames Callback(nonSuperfluousOptions);
952 WalkCase(TD.Actions, Callback, Callback);
955 // Add all options mentioned in the 'case' clauses of the
956 // OptionalEdges of the compilation graph to the set of
957 // non-superfluous options.
958 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
960 const Record* Edge = *B;
961 DagInit* Weight = Edge->getValueAsDag("weight");
963 if (!isDagEmpty(Weight))
964 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
967 // Check that all options in OptDescs belong to the set of
968 // non-superfluous options.
969 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
970 E = OptDescs.end(); B != E; ++B) {
971 const OptionDescription& Val = B->second;
972 if (!nonSuperfluousOptions.count(Val.Name)
973 && Val.Type != OptionType::Alias)
974 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
975 "Probable cause: this option is specified only in the OptionList.\n";
979 /// EmitCaseTest1Arg - Helper function used by
980 /// EmitCaseConstructHandler.
981 bool EmitCaseTest1Arg(const std::string& TestName,
983 const OptionDescriptions& OptDescs,
985 checkNumberOfArguments(&d, 1);
986 const std::string& OptName = InitPtrToString(d.getArg(0));
988 if (TestName == "switch_on") {
989 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
990 if (!OptDesc.isSwitch())
991 throw OptName + ": incorrect option type - should be a switch!";
992 O << OptDesc.GenVariableName();
994 } else if (TestName == "input_languages_contain") {
995 O << "InLangs.count(\"" << OptName << "\") != 0";
997 } else if (TestName == "in_language") {
998 // This works only for single-argument Tool::GenerateAction. Join
999 // tools can process several files in different languages simultaneously.
1001 // TODO: make this work with Edge::Weight (if possible).
1002 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1004 } else if (TestName == "not_empty" || TestName == "empty") {
1005 const char* Test = (TestName == "empty") ? "" : "!";
1007 if (OptName == "o") {
1008 O << Test << "OutputFilename.empty()";
1012 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1013 if (OptDesc.isSwitch())
1015 + ": incorrect option type - should be a list or parameter!";
1016 O << Test << OptDesc.GenVariableName() << ".empty()";
1024 /// EmitCaseTest2Args - Helper function used by
1025 /// EmitCaseConstructHandler.
1026 bool EmitCaseTest2Args(const std::string& TestName,
1028 unsigned IndentLevel,
1029 const OptionDescriptions& OptDescs,
1031 checkNumberOfArguments(&d, 2);
1032 const std::string& OptName = InitPtrToString(d.getArg(0));
1033 const std::string& OptArg = InitPtrToString(d.getArg(1));
1034 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1036 if (TestName == "parameter_equals") {
1037 if (!OptDesc.isParameter())
1038 throw OptName + ": incorrect option type - should be a parameter!";
1039 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1042 else if (TestName == "element_in_list") {
1043 if (!OptDesc.isList())
1044 throw OptName + ": incorrect option type - should be a list!";
1045 const std::string& VarName = OptDesc.GenVariableName();
1046 O << "std::find(" << VarName << ".begin(),\n";
1047 O.indent(IndentLevel + Indent1)
1048 << VarName << ".end(), \""
1049 << OptArg << "\") != " << VarName << ".end()";
1056 // Forward declaration.
1057 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1058 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1059 const OptionDescriptions& OptDescs,
1062 /// EmitLogicalOperationTest - Helper function used by
1063 /// EmitCaseConstructHandler.
1064 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1065 unsigned IndentLevel,
1066 const OptionDescriptions& OptDescs,
1069 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1070 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1071 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1072 if (j != NumArgs - 1) {
1074 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1082 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1083 const OptionDescriptions& OptDescs, raw_ostream& O)
1085 checkNumberOfArguments(&d, 1);
1086 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1088 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1092 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1093 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1094 const OptionDescriptions& OptDescs,
1096 const std::string& TestName = d.getOperator()->getAsString();
1098 if (TestName == "and")
1099 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1100 else if (TestName == "or")
1101 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1102 else if (TestName == "not")
1103 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1104 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1106 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1109 throw TestName + ": unknown edge property!";
1112 // Emit code that handles the 'case' construct.
1113 // Takes a function object that should emit code for every case clause.
1114 // Callback's type is
1115 // void F(Init* Statement, unsigned IndentLevel, raw_ostream& O).
1116 template <typename F>
1117 void EmitCaseConstructHandler(const Init* Dag, unsigned IndentLevel,
1118 F Callback, bool EmitElseIf,
1119 const OptionDescriptions& OptDescs,
1121 const DagInit* d = &InitPtrToDag(Dag);
1122 if (d->getOperator()->getAsString() != "case")
1123 throw std::string("EmitCaseConstructHandler should be invoked"
1124 " only on 'case' expressions!");
1126 unsigned numArgs = d->getNumArgs();
1127 if (d->getNumArgs() < 2)
1128 throw "There should be at least one clause in the 'case' expression:\n"
1131 for (unsigned i = 0; i != numArgs; ++i) {
1132 const DagInit& Test = InitPtrToDag(d->getArg(i));
1135 if (Test.getOperator()->getAsString() == "default") {
1137 throw std::string("The 'default' clause should be the last in the"
1138 "'case' construct!");
1139 O.indent(IndentLevel) << "else {\n";
1142 O.indent(IndentLevel) << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1143 EmitCaseTest(Test, IndentLevel, OptDescs, O);
1147 // Emit the corresponding statement.
1150 throw "Case construct handler: no corresponding action "
1151 "found for the test " + Test.getAsString() + '!';
1153 Init* arg = d->getArg(i);
1154 const DagInit* nd = dynamic_cast<DagInit*>(arg);
1155 if (nd && (nd->getOperator()->getAsString() == "case")) {
1156 // Handle the nested 'case'.
1157 EmitCaseConstructHandler(nd, (IndentLevel + Indent1),
1158 Callback, EmitElseIf, OptDescs, O);
1161 Callback(arg, (IndentLevel + Indent1), O);
1163 O.indent(IndentLevel) << "}\n";
1167 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1168 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1169 /// Helper function used by EmitCmdLineVecFill and.
1170 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1171 const char* Delimiters = " \t\n\v\f\r";
1173 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1176 if (CmdLine.empty())
1180 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1183 for (; B != E; ++B) {
1184 char cur_ch = CmdLine[B];
1188 if (cur_ch == '$') {
1189 cur_st = SpecialCommand;
1192 if (oneOf(Delimiters, cur_ch)) {
1194 B = CmdLine.find_first_not_of(Delimiters, B);
1195 if (B == std::string::npos) {
1206 case SpecialCommand:
1207 if (oneOf(Delimiters, cur_ch)) {
1212 if (cur_ch == '(') {
1214 cur_st = InsideSpecialCommand;
1219 case InsideSpecialCommand:
1220 if (oneOf(Delimiters, cur_ch)) {
1223 if (cur_ch == '\'') {
1224 cur_st = InsideQuotationMarks;
1228 if (cur_ch == ')') {
1232 if (cur_ch == ',') {
1238 case InsideQuotationMarks:
1239 if (cur_ch == '\'') {
1240 cur_st = InsideSpecialCommand;
1246 Out.back().push_back(cur_ch);
1250 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1251 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1252 StrVector::const_iterator SubstituteSpecialCommands
1253 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1256 const std::string& cmd = *Pos;
1258 if (cmd == "$CALL") {
1259 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1260 const std::string& CmdName = *Pos;
1263 throw std::string("$CALL invocation: empty argument list!");
1266 O << CmdName << "(";
1269 bool firstIteration = true;
1271 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1272 const std::string& Arg = *Pos;
1273 assert(Arg.size() != 0);
1279 firstIteration = false;
1283 O << '"' << Arg << '"';
1289 else if (cmd == "$ENV") {
1290 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1291 const std::string& EnvName = *Pos;
1294 throw "$ENV invocation: empty argument list!";
1296 O << "checkCString(std::getenv(\"";
1300 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1303 throw "Unknown special command: " + cmd;
1306 const std::string& Leftover = *Pos;
1307 assert(Leftover.at(0) == ')');
1308 if (Leftover.size() != 1)
1309 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1314 /// EmitCmdLineVecFill - Emit code that fills in the command line
1315 /// vector. Helper function used by EmitGenerateActionMethod().
1316 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1317 bool IsJoin, unsigned IndentLevel,
1320 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1323 throw "Tool '" + ToolName + "' has empty command line!";
1325 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1327 // If there is a hook invocation on the place of the first command, skip it.
1328 assert(!StrVec[0].empty());
1329 if (StrVec[0][0] == '$') {
1330 while (I != E && (*I)[0] != ')' )
1333 // Skip the ')' symbol.
1340 for (; I != E; ++I) {
1341 const std::string& cmd = *I;
1342 assert(!cmd.empty());
1343 O.indent(IndentLevel);
1344 if (cmd.at(0) == '$') {
1345 if (cmd == "$INFILE") {
1347 O << "for (PathVector::const_iterator B = inFiles.begin()"
1348 << ", E = inFiles.end();\n";
1349 O.indent(IndentLevel) << "B != E; ++B)\n";
1350 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1353 O << "vec.push_back(inFile.str());\n";
1356 else if (cmd == "$OUTFILE") {
1357 O << "vec.push_back(out_file);\n";
1360 O << "vec.push_back(";
1361 I = SubstituteSpecialCommands(I, E, O);
1366 O << "vec.push_back(\"" << cmd << "\");\n";
1369 O.indent(IndentLevel) << "cmd = ";
1371 if (StrVec[0][0] == '$')
1372 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1374 O << '"' << StrVec[0] << '"';
1378 /// EmitCmdLineVecFillCallback - A function object wrapper around
1379 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1380 /// argument to EmitCaseConstructHandler().
1381 class EmitCmdLineVecFillCallback {
1383 const std::string& ToolName;
1385 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1386 : IsJoin(J), ToolName(TN) {}
1388 void operator()(const Init* Statement, unsigned IndentLevel,
1389 raw_ostream& O) const
1391 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1395 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1396 /// implement EmitActionHandler. Emits code for
1397 /// handling the (forward) and (forward_as) option properties.
1398 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1399 unsigned IndentLevel,
1400 const std::string& NewName,
1402 const std::string& Name = NewName.empty()
1405 unsigned IndentLevel1 = IndentLevel + Indent1;
1408 case OptionType::Switch:
1409 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1411 case OptionType::Parameter:
1412 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1413 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1415 case OptionType::Prefix:
1416 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1417 << D.GenVariableName() << ");\n";
1419 case OptionType::PrefixList:
1420 O.indent(IndentLevel)
1421 << "for (" << D.GenTypeDeclaration()
1422 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1423 O.indent(IndentLevel)
1424 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1425 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1426 O.indent(IndentLevel1) << "++B;\n";
1428 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1429 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1430 O.indent(IndentLevel1) << "++B;\n";
1433 O.indent(IndentLevel) << "}\n";
1435 case OptionType::ParameterList:
1436 O.indent(IndentLevel)
1437 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1438 << D.GenVariableName() << ".begin(),\n";
1439 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1440 << ".end() ; B != E;) {\n";
1441 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1443 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1444 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1445 O.indent(IndentLevel1) << "++B;\n";
1448 O.indent(IndentLevel) << "}\n";
1450 case OptionType::Alias:
1452 throw std::string("Aliases are not allowed in tool option descriptions!");
1456 /// EmitActionHandler - Emit code that handles actions. Used by
1457 /// EmitGenerateActionMethod() as an argument to
1458 /// EmitCaseConstructHandler().
1459 class EmitActionHandler {
1460 const OptionDescriptions& OptDescs;
1462 void processActionDag(const Init* Statement, unsigned IndentLevel,
1463 raw_ostream& O) const
1465 const DagInit& Dag = InitPtrToDag(Statement);
1466 const std::string& ActionName = Dag.getOperator()->getAsString();
1468 if (ActionName == "append_cmd") {
1469 checkNumberOfArguments(&Dag, 1);
1470 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1472 llvm::SplitString(Cmd, Out);
1474 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1476 O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1478 else if (ActionName == "error") {
1479 O.indent(IndentLevel) << "throw std::runtime_error(\"" <<
1480 (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1484 else if (ActionName == "forward") {
1485 checkNumberOfArguments(&Dag, 1);
1486 const std::string& Name = InitPtrToString(Dag.getArg(0));
1487 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1488 IndentLevel, "", O);
1490 else if (ActionName == "forward_as") {
1491 checkNumberOfArguments(&Dag, 2);
1492 const std::string& Name = InitPtrToString(Dag.getArg(0));
1493 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1494 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1495 IndentLevel, NewName, O);
1497 else if (ActionName == "output_suffix") {
1498 checkNumberOfArguments(&Dag, 1);
1499 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1500 O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1502 else if (ActionName == "stop_compilation") {
1503 O.indent(IndentLevel) << "stop_compilation = true;\n";
1505 else if (ActionName == "unpack_values") {
1506 checkNumberOfArguments(&Dag, 1);
1507 const std::string& Name = InitPtrToString(Dag.getArg(0));
1508 const OptionDescription& D = OptDescs.FindOption(Name);
1511 throw std::string("Can't use unpack_values with multi-valued options!");
1514 O.indent(IndentLevel)
1515 << "for (" << D.GenTypeDeclaration()
1516 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1517 O.indent(IndentLevel)
1518 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n";
1519 O.indent(IndentLevel + Indent1)
1520 << "llvm::SplitString(*B, vec, \",\");\n";
1522 else if (D.isParameter()){
1523 O.indent(IndentLevel) << "llvm::SplitString("
1524 << D.GenVariableName() << ", vec, \",\");\n";
1527 throw "Option '" + D.Name +
1528 "': switches can't have the 'unpack_values' property!";
1532 throw "Unknown action name: " + ActionName + "!";
1536 EmitActionHandler(const OptionDescriptions& OD)
1539 void operator()(const Init* Statement, unsigned IndentLevel,
1540 raw_ostream& O) const
1542 if (typeid(*Statement) == typeid(ListInit)) {
1543 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1544 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1546 this->processActionDag(*B, IndentLevel, O);
1549 this->processActionDag(Statement, IndentLevel, O);
1554 // EmitGenerateActionMethod - Emit one of two versions of the
1555 // Tool::GenerateAction() method.
1556 void EmitGenerateActionMethod (const ToolDescription& D,
1557 const OptionDescriptions& OptDescs,
1558 bool IsJoin, raw_ostream& O) {
1560 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1562 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1564 O.indent(Indent2) << "bool HasChildren,\n";
1565 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1566 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1567 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1568 O.indent(Indent1) << "{\n";
1569 O.indent(Indent2) << "std::string cmd;\n";
1570 O.indent(Indent2) << "std::vector<std::string> vec;\n";
1571 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1572 O.indent(Indent2) << "const char* output_suffix = \""
1573 << D.OutputSuffix << "\";\n";
1574 O.indent(Indent2) << "std::string out_file;\n\n";
1576 // For every understood option, emit handling code.
1578 EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1579 false, OptDescs, O);
1583 << "out_file = OutFilename(" << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
1584 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
1586 // cmd_line is either a string or a 'case' construct.
1588 throw "Tool " + D.Name + " has no cmd_line property!";
1589 else if (typeid(*D.CmdLine) == typeid(StringInit))
1590 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1592 EmitCaseConstructHandler(D.CmdLine, Indent2,
1593 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1596 // Handle the Sink property.
1598 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
1599 O.indent(Indent3) << "vec.insert(vec.end(), "
1600 << SinkOptionName << ".begin(), " << SinkOptionName
1602 O.indent(Indent2) << "}\n";
1605 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
1606 O.indent(Indent1) << "}\n\n";
1609 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1610 /// a given Tool class.
1611 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1612 const OptionDescriptions& OptDescs,
1614 if (!ToolDesc.isJoin()) {
1615 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1616 O.indent(Indent2) << "bool HasChildren,\n";
1617 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1618 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1619 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1620 O.indent(Indent1) << "{\n";
1621 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
1622 << " is not a Join tool!\");\n";
1623 O.indent(Indent1) << "}\n\n";
1626 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1629 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1632 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1633 /// methods for a given Tool class.
1634 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
1635 O.indent(Indent1) << "const char** InputLanguages() const {\n";
1636 O.indent(Indent2) << "return InputLanguages_;\n";
1637 O.indent(Indent1) << "}\n\n";
1639 if (D.OutLanguage.empty())
1640 throw "Tool " + D.Name + " has no 'out_language' property!";
1642 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
1643 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
1644 O.indent(Indent1) << "}\n\n";
1647 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1648 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
1649 O.indent(Indent1) << "const char* Name() const {\n";
1650 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
1651 O.indent(Indent1) << "}\n\n";
1654 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1656 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
1657 O.indent(Indent1) << "bool IsJoin() const {\n";
1659 O.indent(Indent2) << "return true;\n";
1661 O.indent(Indent2) << "return false;\n";
1662 O.indent(Indent1) << "}\n\n";
1665 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1666 /// given Tool class.
1667 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
1668 if (D.InLanguage.empty())
1669 throw "Tool " + D.Name + " has no 'in_language' property!";
1671 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1672 for (StrVector::const_iterator B = D.InLanguage.begin(),
1673 E = D.InLanguage.end(); B != E; ++B)
1674 O << '\"' << *B << "\", ";
1678 /// EmitToolClassDefinition - Emit a Tool class definition.
1679 void EmitToolClassDefinition (const ToolDescription& D,
1680 const OptionDescriptions& OptDescs,
1682 if (D.Name == "root")
1686 O << "class " << D.Name << " : public ";
1692 O << "{\nprivate:\n";
1693 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
1696 EmitNameMethod(D, O);
1697 EmitInOutLanguageMethods(D, O);
1698 EmitIsJoinMethod(D, O);
1699 EmitGenerateActionMethods(D, OptDescs, O);
1701 // Close class definition
1704 EmitStaticMemberDefinitions(D, O);
1708 /// EmitOptionDefinitions - Iterate over a list of option descriptions
1709 /// and emit registration code.
1710 void EmitOptionDefinitions (const OptionDescriptions& descs,
1711 bool HasSink, bool HasExterns,
1714 std::vector<OptionDescription> Aliases;
1716 // Emit static cl::Option variables.
1717 for (OptionDescriptions::const_iterator B = descs.begin(),
1718 E = descs.end(); B!=E; ++B) {
1719 const OptionDescription& val = B->second;
1721 if (val.Type == OptionType::Alias) {
1722 Aliases.push_back(val);
1729 O << val.GenTypeDeclaration() << ' '
1730 << val.GenVariableName();
1732 if (val.isExtern()) {
1737 O << "(\"" << val.Name << "\"\n";
1739 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1740 O << ", cl::Prefix";
1742 if (val.isRequired()) {
1743 if (val.isList() && !val.isMultiVal())
1744 O << ", cl::OneOrMore";
1746 O << ", cl::Required";
1748 else if (val.isOneOrMore() && val.isList()) {
1749 O << ", cl::OneOrMore";
1751 else if (val.isZeroOrOne() && val.isList()) {
1752 O << ", cl::ZeroOrOne";
1755 if (val.isReallyHidden()) {
1756 O << ", cl::ReallyHidden";
1758 else if (val.isHidden()) {
1759 O << ", cl::Hidden";
1762 if (val.MultiVal > 1)
1763 O << ", cl::multi_val(" << val.MultiVal << ')';
1766 const std::string& str = val.InitVal->getAsString();
1767 O << ", cl::init(" << str << ')';
1770 if (!val.Help.empty())
1771 O << ", cl::desc(\"" << val.Help << "\")";
1776 // Emit the aliases (they should go after all the 'proper' options).
1777 for (std::vector<OptionDescription>::const_iterator
1778 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1779 const OptionDescription& val = *B;
1781 O << val.GenTypeDeclaration() << ' '
1782 << val.GenVariableName()
1783 << "(\"" << val.Name << '\"';
1785 const OptionDescription& D = descs.FindOption(val.Help);
1786 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1788 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1791 // Emit the sink option.
1793 O << (HasExterns ? "extern cl" : "cl")
1794 << "::list<std::string> " << SinkOptionName
1795 << (HasExterns ? ";\n" : "(cl::Sink);\n");
1800 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1801 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
1804 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
1806 // Get the relevant field out of RecordKeeper
1807 const Record* LangMapRecord = Records.getDef("LanguageMap");
1809 // It is allowed for a plugin to have no language map.
1810 if (LangMapRecord) {
1812 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1813 if (!LangsToSuffixesList)
1814 throw std::string("Error in the language map definition!");
1816 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1817 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1819 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1820 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1822 for (unsigned i = 0; i < Suffixes->size(); ++i)
1823 O.indent(Indent1) << "langMap[\""
1824 << InitPtrToString(Suffixes->getElement(i))
1825 << "\"] = \"" << Lang << "\";\n";
1832 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1833 /// by EmitEdgeClass().
1834 void IncDecWeight (const Init* i, unsigned IndentLevel,
1836 const DagInit& d = InitPtrToDag(i);
1837 const std::string& OpName = d.getOperator()->getAsString();
1839 if (OpName == "inc_weight") {
1840 O.indent(IndentLevel) << "ret += ";
1842 else if (OpName == "dec_weight") {
1843 O.indent(IndentLevel) << "ret -= ";
1845 else if (OpName == "error") {
1846 O.indent(IndentLevel)
1847 << "throw std::runtime_error(\"" <<
1848 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1855 throw "Unknown operator in edge properties list: " + OpName + '!' +
1856 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
1858 if (d.getNumArgs() > 0)
1859 O << InitPtrToInt(d.getArg(0)) << ";\n";
1865 /// EmitEdgeClass - Emit a single Edge# class.
1866 void EmitEdgeClass (unsigned N, const std::string& Target,
1867 DagInit* Case, const OptionDescriptions& OptDescs,
1870 // Class constructor.
1871 O << "class Edge" << N << ": public Edge {\n"
1873 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
1876 // Function Weight().
1878 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
1879 O.indent(Indent2) << "unsigned ret = 0;\n";
1881 // Handle the 'case' construct.
1882 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1884 O.indent(Indent2) << "return ret;\n";
1885 O.indent(Indent1) << "};\n\n};\n\n";
1888 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1889 void EmitEdgeClasses (const RecordVector& EdgeVector,
1890 const OptionDescriptions& OptDescs,
1893 for (RecordVector::const_iterator B = EdgeVector.begin(),
1894 E = EdgeVector.end(); B != E; ++B) {
1895 const Record* Edge = *B;
1896 const std::string& NodeB = Edge->getValueAsString("b");
1897 DagInit* Weight = Edge->getValueAsDag("weight");
1899 if (!isDagEmpty(Weight))
1900 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
1905 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1907 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
1908 const ToolDescriptions& ToolDescs,
1911 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
1913 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1914 E = ToolDescs.end(); B != E; ++B)
1915 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
1922 for (RecordVector::const_iterator B = EdgeVector.begin(),
1923 E = EdgeVector.end(); B != E; ++B) {
1924 const Record* Edge = *B;
1925 const std::string& NodeA = Edge->getValueAsString("a");
1926 const std::string& NodeB = Edge->getValueAsString("b");
1927 DagInit* Weight = Edge->getValueAsDag("weight");
1929 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
1931 if (isDagEmpty(Weight))
1932 O << "new SimpleEdge(\"" << NodeB << "\")";
1934 O << "new Edge" << i << "()";
1943 /// ExtractHookNames - Extract the hook names from all instances of
1944 /// $CALL(HookName) in the provided command line string. Helper
1945 /// function used by FillInHookNames().
1946 class ExtractHookNames {
1947 llvm::StringMap<unsigned>& HookNames_;
1949 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
1950 : HookNames_(HookNames) {}
1952 void operator()(const Init* CmdLine) {
1954 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
1955 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1957 const std::string& cmd = *B;
1959 if (cmd == "$CALL") {
1960 unsigned NumArgs = 0;
1961 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
1962 const std::string& HookName = *B;
1965 if (HookName.at(0) == ')')
1966 throw "$CALL invoked with no arguments!";
1968 while (++B != E && B->at(0) != ')') {
1972 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
1974 if (H != HookNames_.end() && H->second != NumArgs)
1975 throw "Overloading of hooks is not allowed. Overloaded hook: "
1978 HookNames_[HookName] = NumArgs;
1985 /// FillInHookNames - Actually extract the hook names from all command
1986 /// line strings. Helper function used by EmitHookDeclarations().
1987 void FillInHookNames(const ToolDescriptions& ToolDescs,
1988 llvm::StringMap<unsigned>& HookNames)
1990 // For all command lines:
1991 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1992 E = ToolDescs.end(); B != E; ++B) {
1993 const ToolDescription& D = *(*B);
1996 if (dynamic_cast<StringInit*>(D.CmdLine))
1997 // This is a string.
1998 ExtractHookNames(HookNames).operator()(D.CmdLine);
2000 // This is a 'case' construct.
2001 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
2005 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2006 /// property records and emit hook function declaration for each
2007 /// instance of $CALL(HookName).
2008 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
2009 llvm::StringMap<unsigned> HookNames;
2011 FillInHookNames(ToolDescs, HookNames);
2012 if (HookNames.empty())
2015 O << "namespace hooks {\n";
2016 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
2017 E = HookNames.end(); B != E; ++B) {
2018 O.indent(Indent1) << "std::string " << B->first() << "(";
2020 for (unsigned i = 0, j = B->second; i < j; ++i) {
2021 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2029 /// EmitRegisterPlugin - Emit code to register this plugin.
2030 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2031 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2032 O.indent(Indent1) << "int Priority() const { return "
2033 << Priority << "; }\n\n";
2034 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2035 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2037 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2038 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2040 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2043 /// EmitIncludes - Emit necessary #include directives and some
2044 /// additional declarations.
2045 void EmitIncludes(raw_ostream& O) {
2046 O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2047 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2048 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2049 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2051 << "#include \"llvm/ADT/StringExtras.h\"\n"
2052 << "#include \"llvm/Support/CommandLine.h\"\n\n"
2054 << "#include <cstdlib>\n"
2055 << "#include <stdexcept>\n\n"
2057 << "using namespace llvm;\n"
2058 << "using namespace llvmc;\n\n"
2060 << "extern cl::opt<std::string> OutputFilename;\n\n"
2062 << "inline const char* checkCString(const char* s)\n"
2063 << "{ return s == NULL ? \"\" : s; }\n\n";
2067 /// PluginData - Holds all information about a plugin.
2069 OptionDescriptions OptDescs;
2072 ToolDescriptions ToolDescs;
2077 /// HasSink - Go through the list of tool descriptions and check if
2078 /// there are any with the 'sink' property set.
2079 bool HasSink(const ToolDescriptions& ToolDescs) {
2080 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2081 E = ToolDescs.end(); B != E; ++B)
2088 /// HasExterns - Go through the list of option descriptions and check
2089 /// if there are any external options.
2090 bool HasExterns(const OptionDescriptions& OptDescs) {
2091 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2092 E = OptDescs.end(); B != E; ++B)
2093 if (B->second.isExtern())
2099 /// CollectPluginData - Collect tool and option properties,
2100 /// compilation graph edges and plugin priority from the parse tree.
2101 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2102 // Collect option properties.
2103 const RecordVector& OptionLists =
2104 Records.getAllDerivedDefinitions("OptionList");
2105 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2108 // Collect tool properties.
2109 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2110 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2111 Data.HasSink = HasSink(Data.ToolDescs);
2112 Data.HasExterns = HasExterns(Data.OptDescs);
2114 // Collect compilation graph edges.
2115 const RecordVector& CompilationGraphs =
2116 Records.getAllDerivedDefinitions("CompilationGraph");
2117 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2120 // Calculate the priority of this plugin.
2121 const RecordVector& Priorities =
2122 Records.getAllDerivedDefinitions("PluginPriority");
2123 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2126 /// CheckPluginData - Perform some sanity checks on the collected data.
2127 void CheckPluginData(PluginData& Data) {
2128 // Filter out all tools not mentioned in the compilation graph.
2129 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2131 // Typecheck the compilation graph.
2132 TypecheckGraph(Data.Edges, Data.ToolDescs);
2134 // Check that there are no options without side effects (specified
2135 // only in the OptionList).
2136 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2140 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2141 // Emit file header.
2144 // Emit global option registration code.
2145 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2147 // Emit hook declarations.
2148 EmitHookDeclarations(Data.ToolDescs, O);
2150 O << "namespace {\n\n";
2152 // Emit PopulateLanguageMap() function
2153 // (a language map maps from file extensions to language names).
2154 EmitPopulateLanguageMap(Records, O);
2156 // Emit Tool classes.
2157 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2158 E = Data.ToolDescs.end(); B!=E; ++B)
2159 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2161 // Emit Edge# classes.
2162 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2164 // Emit PopulateCompilationGraph() function.
2165 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2167 // Emit code for plugin registration.
2168 EmitRegisterPlugin(Data.Priority, O);
2170 O << "} // End anonymous namespace.\n\n";
2172 // Force linkage magic.
2173 O << "namespace llvmc {\n";
2174 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2181 // End of anonymous namespace
2184 /// run - The back-end entry point.
2185 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2189 CollectPluginData(Records, Data);
2190 CheckPluginData(Data);
2192 EmitSourceFileHeader("LLVMC Configuration Library", O);
2193 EmitPluginCode(Data, O);
2195 } catch (std::exception& Error) {
2196 throw Error.what() + std::string(" - usually this means a syntax error.");