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 T0&) const {
62 template<typename T0, typename T1>
63 void operator()(const T0&, const T1&) const {
65 template<typename T0, typename T1, typename T2>
66 void operator()(const T0&, const T1&, const T2&) const {
70 int InitPtrToInt(const Init* ptr) {
71 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
72 return val.getValue();
75 const std::string& InitPtrToString(const Init* ptr) {
76 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
77 return val.getValue();
80 const ListInit& InitPtrToList(const Init* ptr) {
81 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
85 const DagInit& InitPtrToDag(const Init* ptr) {
86 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
90 const std::string GetOperatorName(const DagInit* D) {
91 return D->getOperator()->getAsString();
94 const std::string GetOperatorName(const DagInit& D) {
95 return GetOperatorName(&D);
98 // checkNumberOfArguments - Ensure that the number of args in d is
99 // greater than or equal to min_arguments, otherwise throw an exception.
100 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
101 if (!d || d->getNumArgs() < min_arguments)
102 throw GetOperatorName(d) + ": too few arguments!";
105 // isDagEmpty - is this DAG marked with an empty marker?
106 bool isDagEmpty (const DagInit* d) {
107 return GetOperatorName(d) == "empty_dag_marker";
110 // EscapeVariableName - Escape commas and other symbols not allowed
111 // in the C++ variable names. Makes it possible to use options named
112 // like "Wa," (useful for prefix options).
113 std::string EscapeVariableName(const std::string& Var) {
115 for (unsigned i = 0; i != Var.size(); ++i) {
116 char cur_char = Var[i];
117 if (cur_char == ',') {
120 else if (cur_char == '+') {
123 else if (cur_char == '-') {
127 ret.push_back(cur_char);
133 /// oneOf - Does the input string contain this character?
134 bool oneOf(const char* lst, char c) {
142 template <class I, class S>
143 void checkedIncrement(I& P, I E, S ErrorString) {
149 //===----------------------------------------------------------------------===//
150 /// Back-end specific code
153 /// OptionType - One of six different option types. See the
154 /// documentation for detailed description of differences.
155 namespace OptionType {
157 enum OptionType { Alias, Switch, Parameter, ParameterList,
160 bool IsList (OptionType t) {
161 return (t == ParameterList || t == PrefixList);
164 bool IsSwitch (OptionType t) {
165 return (t == Switch);
168 bool IsParameter (OptionType t) {
169 return (t == Parameter || t == Prefix);
174 OptionType::OptionType stringToOptionType(const std::string& T) {
175 if (T == "alias_option")
176 return OptionType::Alias;
177 else if (T == "switch_option")
178 return OptionType::Switch;
179 else if (T == "parameter_option")
180 return OptionType::Parameter;
181 else if (T == "parameter_list_option")
182 return OptionType::ParameterList;
183 else if (T == "prefix_option")
184 return OptionType::Prefix;
185 else if (T == "prefix_list_option")
186 return OptionType::PrefixList;
188 throw "Unknown option type: " + T + '!';
191 namespace OptionDescriptionFlags {
192 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
193 ReallyHidden = 0x4, Extern = 0x8,
194 OneOrMore = 0x10, ZeroOrOne = 0x20 };
197 /// OptionDescription - Represents data contained in a single
198 /// OptionList entry.
199 struct OptionDescription {
200 OptionType::OptionType Type;
207 OptionDescription(OptionType::OptionType t = OptionType::Switch,
208 const std::string& n = "",
209 const std::string& h = DefaultHelpString)
210 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
213 /// GenTypeDeclaration - Returns the C++ variable type of this
215 const char* GenTypeDeclaration() const;
217 /// GenVariableName - Returns the variable name used in the
218 /// generated C++ code.
219 std::string GenVariableName() const;
221 /// Merge - Merge two option descriptions.
222 void Merge (const OptionDescription& other);
224 // Misc convenient getters/setters.
226 bool isAlias() const;
228 bool isMultiVal() const;
230 bool isExtern() const;
233 bool isRequired() const;
236 bool isOneOrMore() const;
239 bool isZeroOrOne() const;
242 bool isHidden() const;
245 bool isReallyHidden() const;
246 void setReallyHidden();
248 bool isParameter() const
249 { return OptionType::IsParameter(this->Type); }
251 bool isSwitch() const
252 { return OptionType::IsSwitch(this->Type); }
255 { return OptionType::IsList(this->Type); }
259 void OptionDescription::Merge (const OptionDescription& other)
261 if (other.Type != Type)
262 throw "Conflicting definitions for the option " + Name + "!";
264 if (Help == other.Help || Help == DefaultHelpString)
266 else if (other.Help != DefaultHelpString) {
267 llvm::errs() << "Warning: several different help strings"
268 " defined for option " + Name + "\n";
271 Flags |= other.Flags;
274 bool OptionDescription::isAlias() const {
275 return Type == OptionType::Alias;
278 bool OptionDescription::isMultiVal() const {
282 bool OptionDescription::isExtern() const {
283 return Flags & OptionDescriptionFlags::Extern;
285 void OptionDescription::setExtern() {
286 Flags |= OptionDescriptionFlags::Extern;
289 bool OptionDescription::isRequired() const {
290 return Flags & OptionDescriptionFlags::Required;
292 void OptionDescription::setRequired() {
293 Flags |= OptionDescriptionFlags::Required;
296 bool OptionDescription::isOneOrMore() const {
297 return Flags & OptionDescriptionFlags::OneOrMore;
299 void OptionDescription::setOneOrMore() {
300 Flags |= OptionDescriptionFlags::OneOrMore;
303 bool OptionDescription::isZeroOrOne() const {
304 return Flags & OptionDescriptionFlags::ZeroOrOne;
306 void OptionDescription::setZeroOrOne() {
307 Flags |= OptionDescriptionFlags::ZeroOrOne;
310 bool OptionDescription::isHidden() const {
311 return Flags & OptionDescriptionFlags::Hidden;
313 void OptionDescription::setHidden() {
314 Flags |= OptionDescriptionFlags::Hidden;
317 bool OptionDescription::isReallyHidden() const {
318 return Flags & OptionDescriptionFlags::ReallyHidden;
320 void OptionDescription::setReallyHidden() {
321 Flags |= OptionDescriptionFlags::ReallyHidden;
324 const char* OptionDescription::GenTypeDeclaration() const {
326 case OptionType::Alias:
328 case OptionType::PrefixList:
329 case OptionType::ParameterList:
330 return "cl::list<std::string>";
331 case OptionType::Switch:
332 return "cl::opt<bool>";
333 case OptionType::Parameter:
334 case OptionType::Prefix:
336 return "cl::opt<std::string>";
340 std::string OptionDescription::GenVariableName() const {
341 const std::string& EscapedName = EscapeVariableName(Name);
343 case OptionType::Alias:
344 return "AutoGeneratedAlias_" + EscapedName;
345 case OptionType::PrefixList:
346 case OptionType::ParameterList:
347 return "AutoGeneratedList_" + EscapedName;
348 case OptionType::Switch:
349 return "AutoGeneratedSwitch_" + EscapedName;
350 case OptionType::Prefix:
351 case OptionType::Parameter:
353 return "AutoGeneratedParameter_" + EscapedName;
357 /// OptionDescriptions - An OptionDescription array plus some helper
359 class OptionDescriptions {
360 typedef StringMap<OptionDescription> container_type;
362 /// Descriptions - A list of OptionDescriptions.
363 container_type Descriptions;
366 /// FindOption - exception-throwing wrapper for find().
367 const OptionDescription& FindOption(const std::string& OptName) const;
368 /// FindSwitch - wrapper for FindOption that throws in case the option is not
370 const OptionDescription& FindSwitch(const std::string& OptName) const;
372 /// insertDescription - Insert new OptionDescription into
373 /// OptionDescriptions list
374 void InsertDescription (const OptionDescription& o);
376 // Support for STL-style iteration
377 typedef container_type::const_iterator const_iterator;
378 const_iterator begin() const { return Descriptions.begin(); }
379 const_iterator end() const { return Descriptions.end(); }
382 const OptionDescription&
383 OptionDescriptions::FindOption(const std::string& OptName) const
385 const_iterator I = Descriptions.find(OptName);
386 if (I != Descriptions.end())
389 throw OptName + ": no such option!";
392 const OptionDescription&
393 OptionDescriptions::FindSwitch(const std::string& OptName) const
395 const OptionDescription& OptDesc = this->FindOption(OptName);
396 if (!OptDesc.isSwitch())
397 throw OptName + ": incorrect option type - should be a switch!";
401 void OptionDescriptions::InsertDescription (const OptionDescription& o)
403 container_type::iterator I = Descriptions.find(o.Name);
404 if (I != Descriptions.end()) {
405 OptionDescription& D = I->second;
409 Descriptions[o.Name] = o;
413 /// HandlerTable - A base class for function objects implemented as
414 /// 'tables of handlers'.
418 // Implementation details.
421 typedef void (T::* Handler) (const DagInit*);
422 /// HandlerMap - A map from property names to property handlers
423 typedef StringMap<Handler> HandlerMap;
425 static HandlerMap Handlers_;
426 static bool staticMembersInitialized_;
431 HandlerTable(T* cp) : childPtr(cp)
434 /// operator() - Just forwards to the corresponding property
436 void operator() (Init* i) {
437 const DagInit& property = InitPtrToDag(i);
438 const std::string& property_name = GetOperatorName(property);
439 typename HandlerMap::iterator method = Handlers_.find(property_name);
441 if (method != Handlers_.end()) {
442 Handler h = method->second;
443 (childPtr->*h)(&property);
446 throw "No handler found for property " + property_name + "!";
450 void AddHandler(const char* Property, Handler Handl) {
451 Handlers_[Property] = Handl;
455 template <class T> typename HandlerTable<T>::HandlerMap
456 HandlerTable<T>::Handlers_;
457 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
460 /// CollectOptionProperties - Function object for iterating over an
461 /// option property list.
462 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
465 /// optDescs_ - OptionDescriptions table. This is where the
466 /// information is stored.
467 OptionDescription& optDesc_;
471 explicit CollectOptionProperties(OptionDescription& OD)
472 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
474 if (!staticMembersInitialized_) {
475 AddHandler("extern", &CollectOptionProperties::onExtern);
476 AddHandler("help", &CollectOptionProperties::onHelp);
477 AddHandler("hidden", &CollectOptionProperties::onHidden);
478 AddHandler("init", &CollectOptionProperties::onInit);
479 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
480 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
481 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
482 AddHandler("required", &CollectOptionProperties::onRequired);
483 AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
485 staticMembersInitialized_ = true;
491 /// Option property handlers --
492 /// Methods that handle option properties such as (help) or (hidden).
494 void onExtern (const DagInit* d) {
495 checkNumberOfArguments(d, 0);
496 optDesc_.setExtern();
499 void onHelp (const DagInit* d) {
500 checkNumberOfArguments(d, 1);
501 optDesc_.Help = InitPtrToString(d->getArg(0));
504 void onHidden (const DagInit* d) {
505 checkNumberOfArguments(d, 0);
506 optDesc_.setHidden();
509 void onReallyHidden (const DagInit* d) {
510 checkNumberOfArguments(d, 0);
511 optDesc_.setReallyHidden();
514 void onRequired (const DagInit* d) {
515 checkNumberOfArguments(d, 0);
516 if (optDesc_.isOneOrMore())
517 throw std::string("An option can't have both (required) "
518 "and (one_or_more) properties!");
519 optDesc_.setRequired();
522 void onInit (const DagInit* d) {
523 checkNumberOfArguments(d, 1);
524 Init* i = d->getArg(0);
525 const std::string& str = i->getAsString();
527 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
528 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
531 throw std::string("Incorrect usage of the 'init' option property!");
533 optDesc_.InitVal = i;
536 void onOneOrMore (const DagInit* d) {
537 checkNumberOfArguments(d, 0);
538 if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
539 throw std::string("Only one of (required), (zero_or_one) or "
540 "(one_or_more) properties is allowed!");
541 if (!OptionType::IsList(optDesc_.Type))
542 llvm::errs() << "Warning: specifying the 'one_or_more' property "
543 "on a non-list option will have no effect.\n";
544 optDesc_.setOneOrMore();
547 void onZeroOrOne (const DagInit* d) {
548 checkNumberOfArguments(d, 0);
549 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
550 throw std::string("Only one of (required), (zero_or_one) or "
551 "(one_or_more) properties is allowed!");
552 if (!OptionType::IsList(optDesc_.Type))
553 llvm::errs() << "Warning: specifying the 'zero_or_one' property"
554 "on a non-list option will have no effect.\n";
555 optDesc_.setZeroOrOne();
558 void onMultiVal (const DagInit* d) {
559 checkNumberOfArguments(d, 1);
560 int val = InitPtrToInt(d->getArg(0));
562 throw std::string("Error in the 'multi_val' property: "
563 "the value must be greater than 1!");
564 if (!OptionType::IsList(optDesc_.Type))
565 throw std::string("The multi_val property is valid only "
567 optDesc_.MultiVal = val;
572 /// AddOption - A function object that is applied to every option
573 /// description. Used by CollectOptionDescriptions.
576 OptionDescriptions& OptDescs_;
579 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
582 void operator()(const Init* i) {
583 const DagInit& d = InitPtrToDag(i);
584 checkNumberOfArguments(&d, 1);
586 const OptionType::OptionType Type =
587 stringToOptionType(GetOperatorName(d));
588 const std::string& Name = InitPtrToString(d.getArg(0));
590 OptionDescription OD(Type, Name);
593 checkNumberOfArguments(&d, 2);
596 // Aliases store the aliased option name in the 'Help' field.
597 OD.Help = InitPtrToString(d.getArg(1));
599 else if (!OD.isExtern()) {
600 processOptionProperties(&d, OD);
602 OptDescs_.InsertDescription(OD);
606 /// processOptionProperties - Go through the list of option
607 /// properties and call a corresponding handler for each.
608 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
609 checkNumberOfArguments(d, 2);
610 DagInit::const_arg_iterator B = d->arg_begin();
611 // Skip the first argument: it's always the option name.
613 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
618 /// CollectOptionDescriptions - Collects option properties from all
620 void CollectOptionDescriptions (RecordVector::const_iterator B,
621 RecordVector::const_iterator E,
622 OptionDescriptions& OptDescs)
624 // For every OptionList:
626 RecordVector::value_type T = *B;
627 // Throws an exception if the value does not exist.
628 ListInit* PropList = T->getValueAsListInit("options");
630 // For every option description in this list:
631 // collect the information and
632 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
636 // Tool information record
638 namespace ToolFlags {
639 enum ToolFlags { Join = 0x1, Sink = 0x2 };
642 struct ToolDescription : public RefCountedBase<ToolDescription> {
646 StrVector InLanguage;
647 std::string OutLanguage;
648 std::string OutputSuffix;
651 // Various boolean properties
652 void setSink() { Flags |= ToolFlags::Sink; }
653 bool isSink() const { return Flags & ToolFlags::Sink; }
654 void setJoin() { Flags |= ToolFlags::Join; }
655 bool isJoin() const { return Flags & ToolFlags::Join; }
657 // Default ctor here is needed because StringMap can only store
658 // DefaultConstructible objects
659 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
660 ToolDescription (const std::string& n)
661 : Name(n), CmdLine(0), Actions(0), Flags(0)
665 /// ToolDescriptions - A list of Tool information records.
666 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
669 /// CollectToolProperties - Function object for iterating over a list of
670 /// tool property records.
671 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
674 /// toolDesc_ - Properties of the current Tool. This is where the
675 /// information is stored.
676 ToolDescription& toolDesc_;
680 explicit CollectToolProperties (ToolDescription& d)
681 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
683 if (!staticMembersInitialized_) {
685 AddHandler("actions", &CollectToolProperties::onActions);
686 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
687 AddHandler("in_language", &CollectToolProperties::onInLanguage);
688 AddHandler("join", &CollectToolProperties::onJoin);
689 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
690 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
691 AddHandler("sink", &CollectToolProperties::onSink);
693 staticMembersInitialized_ = true;
699 /// Property handlers --
700 /// Functions that extract information about tool properties from
701 /// DAG representation.
703 void onActions (const DagInit* d) {
704 checkNumberOfArguments(d, 1);
705 Init* Case = d->getArg(0);
706 if (typeid(*Case) != typeid(DagInit) ||
707 GetOperatorName(static_cast<DagInit*>(Case)) != "case")
709 std::string("The argument to (actions) should be a 'case' construct!");
710 toolDesc_.Actions = Case;
713 void onCmdLine (const DagInit* d) {
714 checkNumberOfArguments(d, 1);
715 toolDesc_.CmdLine = d->getArg(0);
718 void onInLanguage (const DagInit* d) {
719 checkNumberOfArguments(d, 1);
720 Init* arg = d->getArg(0);
722 // Find out the argument's type.
723 if (typeid(*arg) == typeid(StringInit)) {
725 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
729 const ListInit& lst = InitPtrToList(arg);
730 StrVector& out = toolDesc_.InLanguage;
732 // Copy strings to the output vector.
733 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
735 out.push_back(InitPtrToString(*B));
738 // Remove duplicates.
739 std::sort(out.begin(), out.end());
740 StrVector::iterator newE = std::unique(out.begin(), out.end());
741 out.erase(newE, out.end());
745 void onJoin (const DagInit* d) {
746 checkNumberOfArguments(d, 0);
750 void onOutLanguage (const DagInit* d) {
751 checkNumberOfArguments(d, 1);
752 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
755 void onOutputSuffix (const DagInit* d) {
756 checkNumberOfArguments(d, 1);
757 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
760 void onSink (const DagInit* d) {
761 checkNumberOfArguments(d, 0);
767 /// CollectToolDescriptions - Gather information about tool properties
768 /// from the parsed TableGen data (basically a wrapper for the
769 /// CollectToolProperties function object).
770 void CollectToolDescriptions (RecordVector::const_iterator B,
771 RecordVector::const_iterator E,
772 ToolDescriptions& ToolDescs)
774 // Iterate over a properties list of every Tool definition
776 const Record* T = *B;
777 // Throws an exception if the value does not exist.
778 ListInit* PropList = T->getValueAsListInit("properties");
780 IntrusiveRefCntPtr<ToolDescription>
781 ToolDesc(new ToolDescription(T->getName()));
783 std::for_each(PropList->begin(), PropList->end(),
784 CollectToolProperties(*ToolDesc));
785 ToolDescs.push_back(ToolDesc);
789 /// FillInEdgeVector - Merge all compilation graph definitions into
790 /// one single edge list.
791 void FillInEdgeVector(RecordVector::const_iterator B,
792 RecordVector::const_iterator E, RecordVector& Out) {
793 for (; B != E; ++B) {
794 const ListInit* edges = (*B)->getValueAsListInit("edges");
796 for (unsigned i = 0; i < edges->size(); ++i)
797 Out.push_back(edges->getElementAsRecord(i));
801 /// CalculatePriority - Calculate the priority of this plugin.
802 int CalculatePriority(RecordVector::const_iterator B,
803 RecordVector::const_iterator E) {
807 priority = static_cast<int>((*B)->getValueAsInt("priority"));
810 throw std::string("More than one 'PluginPriority' instance found: "
811 "most probably an error!");
817 /// NotInGraph - Helper function object for FilterNotInGraph.
820 const llvm::StringSet<>& ToolsInGraph_;
823 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
824 : ToolsInGraph_(ToolsInGraph)
827 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
828 return (ToolsInGraph_.count(x->Name) == 0);
832 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
833 /// mentioned in the compilation graph definition.
834 void FilterNotInGraph (const RecordVector& EdgeVector,
835 ToolDescriptions& ToolDescs) {
837 // List all tools mentioned in the graph.
838 llvm::StringSet<> ToolsInGraph;
840 for (RecordVector::const_iterator B = EdgeVector.begin(),
841 E = EdgeVector.end(); B != E; ++B) {
843 const Record* Edge = *B;
844 const std::string& NodeA = Edge->getValueAsString("a");
845 const std::string& NodeB = Edge->getValueAsString("b");
848 ToolsInGraph.insert(NodeA);
849 ToolsInGraph.insert(NodeB);
852 // Filter ToolPropertiesList.
853 ToolDescriptions::iterator new_end =
854 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
855 NotInGraph(ToolsInGraph));
856 ToolDescs.erase(new_end, ToolDescs.end());
859 /// FillInToolToLang - Fills in two tables that map tool names to
860 /// (input, output) languages. Helper function used by TypecheckGraph().
861 void FillInToolToLang (const ToolDescriptions& ToolDescs,
862 StringMap<StringSet<> >& ToolToInLang,
863 StringMap<std::string>& ToolToOutLang) {
864 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
865 E = ToolDescs.end(); B != E; ++B) {
866 const ToolDescription& D = *(*B);
867 for (StrVector::const_iterator B = D.InLanguage.begin(),
868 E = D.InLanguage.end(); B != E; ++B)
869 ToolToInLang[D.Name].insert(*B);
870 ToolToOutLang[D.Name] = D.OutLanguage;
874 /// TypecheckGraph - Check that names for output and input languages
875 /// on all edges do match. This doesn't do much when the information
876 /// about the whole graph is not available (i.e. when compiling most
878 void TypecheckGraph (const RecordVector& EdgeVector,
879 const ToolDescriptions& ToolDescs) {
880 StringMap<StringSet<> > ToolToInLang;
881 StringMap<std::string> ToolToOutLang;
883 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
884 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
885 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
887 for (RecordVector::const_iterator B = EdgeVector.begin(),
888 E = EdgeVector.end(); B != E; ++B) {
889 const Record* Edge = *B;
890 const std::string& NodeA = Edge->getValueAsString("a");
891 const std::string& NodeB = Edge->getValueAsString("b");
892 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
893 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
895 if (NodeA != "root") {
896 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
897 throw "Edge " + NodeA + "->" + NodeB
898 + ": output->input language mismatch";
902 throw std::string("Edges back to the root are not allowed!");
906 /// WalkCase - Walks the 'case' expression DAG and invokes
907 /// TestCallback on every test, and StatementCallback on every
908 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
909 /// combinators (that is, they are passed directly to TestCallback).
910 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
911 /// IndentLevel, bool FirstTest)'.
912 /// StatementCallback must have type 'void StatementCallback(const Init*,
913 /// unsigned IndentLevel)'.
914 template <typename F1, typename F2>
915 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
916 unsigned IndentLevel = 0)
918 const DagInit& d = InitPtrToDag(Case);
921 if (GetOperatorName(d) != "case")
922 throw std::string("WalkCase should be invoked only on 'case' expressions!");
924 if (d.getNumArgs() < 2)
925 throw "There should be at least one clause in the 'case' expression:\n"
930 const unsigned numArgs = d.getNumArgs();
932 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
939 const DagInit& Test = InitPtrToDag(arg);
941 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
942 throw std::string("The 'default' clause should be the last in the"
943 "'case' construct!");
945 throw "Case construct handler: no corresponding action "
946 "found for the test " + Test.getAsString() + '!';
948 TestCallback(&Test, IndentLevel, (i == 1));
952 if (dynamic_cast<DagInit*>(arg)
953 && GetOperatorName(static_cast<DagInit*>(arg)) == "case") {
955 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
959 StatementCallback(arg, IndentLevel);
967 /// ExtractOptionNames - A helper function object used by
968 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
969 class ExtractOptionNames {
970 llvm::StringSet<>& OptionNames_;
972 void processDag(const Init* Statement) {
973 const DagInit& Stmt = InitPtrToDag(Statement);
974 const std::string& ActionName = GetOperatorName(Stmt);
975 if (ActionName == "forward" || ActionName == "forward_as" ||
976 ActionName == "unpack_values" || ActionName == "switch_on" ||
977 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
978 ActionName == "not_empty" || ActionName == "empty") {
979 checkNumberOfArguments(&Stmt, 1);
980 const std::string& Name = InitPtrToString(Stmt.getArg(0));
981 OptionNames_.insert(Name);
983 else if (ActionName == "and" || ActionName == "or") {
984 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
985 this->processDag(Stmt.getArg(i));
991 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
994 void operator()(const Init* Statement) {
995 if (typeid(*Statement) == typeid(ListInit)) {
996 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
997 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
999 this->processDag(*B);
1002 this->processDag(Statement);
1006 void operator()(const DagInit* Test, unsigned, bool) {
1007 this->operator()(Test);
1009 void operator()(const Init* Statement, unsigned) {
1010 this->operator()(Statement);
1014 /// CheckForSuperfluousOptions - Check that there are no side
1015 /// effect-free options (specified only in the OptionList). Otherwise,
1016 /// output a warning.
1017 void CheckForSuperfluousOptions (const RecordVector& Edges,
1018 const ToolDescriptions& ToolDescs,
1019 const OptionDescriptions& OptDescs) {
1020 llvm::StringSet<> nonSuperfluousOptions;
1022 // Add all options mentioned in the ToolDesc.Actions to the set of
1023 // non-superfluous options.
1024 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1025 E = ToolDescs.end(); B != E; ++B) {
1026 const ToolDescription& TD = *(*B);
1027 ExtractOptionNames Callback(nonSuperfluousOptions);
1029 WalkCase(TD.Actions, Callback, Callback);
1032 // Add all options mentioned in the 'case' clauses of the
1033 // OptionalEdges of the compilation graph to the set of
1034 // non-superfluous options.
1035 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1037 const Record* Edge = *B;
1038 DagInit* Weight = Edge->getValueAsDag("weight");
1040 if (!isDagEmpty(Weight))
1041 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1044 // Check that all options in OptDescs belong to the set of
1045 // non-superfluous options.
1046 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1047 E = OptDescs.end(); B != E; ++B) {
1048 const OptionDescription& Val = B->second;
1049 if (!nonSuperfluousOptions.count(Val.Name)
1050 && Val.Type != OptionType::Alias)
1051 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1052 "Probable cause: this option is specified only in the OptionList.\n";
1056 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1057 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1058 if (TestName == "single_input_file") {
1059 O << "InputFilenames.size() == 1";
1062 else if (TestName == "multiple_input_files") {
1063 O << "InputFilenames.size() > 1";
1070 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1071 bool EmitCaseTest1ArgStr(const std::string& TestName,
1073 const OptionDescriptions& OptDescs,
1075 const std::string& OptName = InitPtrToString(d.getArg(0));
1077 if (TestName == "switch_on") {
1078 const OptionDescription& OptDesc = OptDescs.FindSwitch(OptName);
1079 O << OptDesc.GenVariableName();
1082 else if (TestName == "input_languages_contain") {
1083 O << "InLangs.count(\"" << OptName << "\") != 0";
1086 else if (TestName == "in_language") {
1087 // This works only for single-argument Tool::GenerateAction. Join
1088 // tools can process several files in different languages simultaneously.
1090 // TODO: make this work with Edge::Weight (if possible).
1091 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1094 else if (TestName == "not_empty" || TestName == "empty") {
1095 const char* Test = (TestName == "empty") ? "" : "!";
1097 if (OptName == "o") {
1098 O << Test << "OutputFilename.empty()";
1102 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1103 if (OptDesc.isSwitch())
1105 + ": incorrect option type - should be a list or parameter!";
1106 O << Test << OptDesc.GenVariableName() << ".empty()";
1114 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1115 bool EmitCaseTest1ArgList(const std::string& TestName,
1117 const OptionDescriptions& OptDescs,
1119 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1121 if (TestName == "any_switch_on") {
1122 bool isFirst = true;
1124 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1125 const std::string& OptName = InitPtrToString(*B);
1126 const OptionDescription& OptDesc = OptDescs.FindSwitch(OptName);
1132 O << OptDesc.GenVariableName();
1138 // TODO: implement any_not_empty, any_empty, switch_on [..], empty [..]
1143 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1144 bool EmitCaseTest1Arg(const std::string& TestName,
1146 const OptionDescriptions& OptDescs,
1148 checkNumberOfArguments(&d, 1);
1149 if (typeid(*d.getArg(0)) == typeid(ListInit))
1150 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1152 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1155 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1156 bool EmitCaseTest2Args(const std::string& TestName,
1158 unsigned IndentLevel,
1159 const OptionDescriptions& OptDescs,
1161 checkNumberOfArguments(&d, 2);
1162 const std::string& OptName = InitPtrToString(d.getArg(0));
1163 const std::string& OptArg = InitPtrToString(d.getArg(1));
1164 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1166 if (TestName == "parameter_equals") {
1167 if (!OptDesc.isParameter())
1168 throw OptName + ": incorrect option type - should be a parameter!";
1169 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1172 else if (TestName == "element_in_list") {
1173 if (!OptDesc.isList())
1174 throw OptName + ": incorrect option type - should be a list!";
1175 const std::string& VarName = OptDesc.GenVariableName();
1176 O << "std::find(" << VarName << ".begin(),\n";
1177 O.indent(IndentLevel + Indent1)
1178 << VarName << ".end(), \""
1179 << OptArg << "\") != " << VarName << ".end()";
1186 // Forward declaration.
1187 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1188 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1189 const OptionDescriptions& OptDescs,
1192 /// EmitLogicalOperationTest - Helper function used by
1193 /// EmitCaseConstructHandler.
1194 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1195 unsigned IndentLevel,
1196 const OptionDescriptions& OptDescs,
1199 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1200 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1201 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1202 if (j != NumArgs - 1) {
1204 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1212 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1213 const OptionDescriptions& OptDescs, raw_ostream& O)
1215 checkNumberOfArguments(&d, 1);
1216 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1218 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1222 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1223 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1224 const OptionDescriptions& OptDescs,
1226 const std::string& TestName = GetOperatorName(d);
1228 if (TestName == "and")
1229 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1230 else if (TestName == "or")
1231 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1232 else if (TestName == "not")
1233 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1234 else if (EmitCaseTest0Args(TestName, O))
1236 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1238 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1241 throw TestName + ": unknown edge property!";
1245 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1246 class EmitCaseTestCallback {
1248 const OptionDescriptions& OptDescs_;
1252 EmitCaseTestCallback(bool EmitElseIf,
1253 const OptionDescriptions& OptDescs, raw_ostream& O)
1254 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1257 void operator()(const DagInit* Test, unsigned IndentLevel, bool FirstTest)
1259 if (GetOperatorName(Test) == "default") {
1260 O_.indent(IndentLevel) << "else {\n";
1263 O_.indent(IndentLevel)
1264 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1265 EmitCaseTest(*Test, IndentLevel, OptDescs_, O_);
1271 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1272 template <typename F>
1273 class EmitCaseStatementCallback {
1278 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1279 : Callback_(Callback), O_(O)
1282 void operator() (const Init* Statement, unsigned IndentLevel) {
1284 // Ignore nested 'case' DAG.
1285 if (!(dynamic_cast<const DagInit*>(Statement) &&
1286 GetOperatorName(static_cast<const DagInit*>(Statement)) == "case")) {
1287 if (typeid(*Statement) == typeid(ListInit)) {
1288 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1289 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1291 Callback_(*B, (IndentLevel + Indent1), O_);
1294 Callback_(Statement, (IndentLevel + Indent1), O_);
1297 O_.indent(IndentLevel) << "}\n";
1302 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1303 /// construct. Takes a function object that should emit code for every case
1304 /// clause. Implemented on top of WalkCase.
1305 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1306 /// raw_ostream& O).
1307 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1308 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1310 template <typename F>
1311 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1312 F Callback, bool EmitElseIf,
1313 const OptionDescriptions& OptDescs,
1315 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1316 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1319 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1320 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1321 /// Helper function used by EmitCmdLineVecFill and.
1322 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1323 const char* Delimiters = " \t\n\v\f\r";
1325 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1328 if (CmdLine.empty())
1332 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1335 for (; B != E; ++B) {
1336 char cur_ch = CmdLine[B];
1340 if (cur_ch == '$') {
1341 cur_st = SpecialCommand;
1344 if (oneOf(Delimiters, cur_ch)) {
1346 B = CmdLine.find_first_not_of(Delimiters, B);
1347 if (B == std::string::npos) {
1358 case SpecialCommand:
1359 if (oneOf(Delimiters, cur_ch)) {
1364 if (cur_ch == '(') {
1366 cur_st = InsideSpecialCommand;
1371 case InsideSpecialCommand:
1372 if (oneOf(Delimiters, cur_ch)) {
1375 if (cur_ch == '\'') {
1376 cur_st = InsideQuotationMarks;
1380 if (cur_ch == ')') {
1384 if (cur_ch == ',') {
1390 case InsideQuotationMarks:
1391 if (cur_ch == '\'') {
1392 cur_st = InsideSpecialCommand;
1398 Out.back().push_back(cur_ch);
1402 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1403 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1404 StrVector::const_iterator SubstituteSpecialCommands
1405 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1408 const std::string& cmd = *Pos;
1410 if (cmd == "$CALL") {
1411 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1412 const std::string& CmdName = *Pos;
1415 throw std::string("$CALL invocation: empty argument list!");
1418 O << CmdName << "(";
1421 bool firstIteration = true;
1423 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1424 const std::string& Arg = *Pos;
1425 assert(Arg.size() != 0);
1431 firstIteration = false;
1435 O << '"' << Arg << '"';
1441 else if (cmd == "$ENV") {
1442 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1443 const std::string& EnvName = *Pos;
1446 throw "$ENV invocation: empty argument list!";
1448 O << "checkCString(std::getenv(\"";
1452 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1455 throw "Unknown special command: " + cmd;
1458 const std::string& Leftover = *Pos;
1459 assert(Leftover.at(0) == ')');
1460 if (Leftover.size() != 1)
1461 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1466 /// EmitCmdLineVecFill - Emit code that fills in the command line
1467 /// vector. Helper function used by EmitGenerateActionMethod().
1468 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1469 bool IsJoin, unsigned IndentLevel,
1472 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1475 throw "Tool '" + ToolName + "' has empty command line!";
1477 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1479 // If there is a hook invocation on the place of the first command, skip it.
1480 assert(!StrVec[0].empty());
1481 if (StrVec[0][0] == '$') {
1482 while (I != E && (*I)[0] != ')' )
1485 // Skip the ')' symbol.
1492 bool hasINFILE = false;
1494 for (; I != E; ++I) {
1495 const std::string& cmd = *I;
1496 assert(!cmd.empty());
1497 O.indent(IndentLevel);
1498 if (cmd.at(0) == '$') {
1499 if (cmd == "$INFILE") {
1502 O << "for (PathVector::const_iterator B = inFiles.begin()"
1503 << ", E = inFiles.end();\n";
1504 O.indent(IndentLevel) << "B != E; ++B)\n";
1505 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1508 O << "vec.push_back(inFile.str());\n";
1511 else if (cmd == "$OUTFILE") {
1512 O << "vec.push_back(\"\");\n";
1513 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1516 O << "vec.push_back(";
1517 I = SubstituteSpecialCommands(I, E, O);
1522 O << "vec.push_back(\"" << cmd << "\");\n";
1526 throw "Tool '" + ToolName + "' doesn't take any input!";
1528 O.indent(IndentLevel) << "cmd = ";
1529 if (StrVec[0][0] == '$')
1530 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1532 O << '"' << StrVec[0] << '"';
1536 /// EmitCmdLineVecFillCallback - A function object wrapper around
1537 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1538 /// argument to EmitCaseConstructHandler().
1539 class EmitCmdLineVecFillCallback {
1541 const std::string& ToolName;
1543 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1544 : IsJoin(J), ToolName(TN) {}
1546 void operator()(const Init* Statement, unsigned IndentLevel,
1547 raw_ostream& O) const
1549 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1553 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1554 /// implement EmitActionHandler. Emits code for
1555 /// handling the (forward) and (forward_as) option properties.
1556 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1557 unsigned IndentLevel,
1558 const std::string& NewName,
1560 const std::string& Name = NewName.empty()
1563 unsigned IndentLevel1 = IndentLevel + Indent1;
1566 case OptionType::Switch:
1567 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1569 case OptionType::Parameter:
1570 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1571 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1573 case OptionType::Prefix:
1574 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1575 << D.GenVariableName() << ");\n";
1577 case OptionType::PrefixList:
1578 O.indent(IndentLevel)
1579 << "for (" << D.GenTypeDeclaration()
1580 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1581 O.indent(IndentLevel)
1582 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1583 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1584 O.indent(IndentLevel1) << "++B;\n";
1586 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1587 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1588 O.indent(IndentLevel1) << "++B;\n";
1591 O.indent(IndentLevel) << "}\n";
1593 case OptionType::ParameterList:
1594 O.indent(IndentLevel)
1595 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1596 << D.GenVariableName() << ".begin(),\n";
1597 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1598 << ".end() ; B != E;) {\n";
1599 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1601 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1602 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1603 O.indent(IndentLevel1) << "++B;\n";
1606 O.indent(IndentLevel) << "}\n";
1608 case OptionType::Alias:
1610 throw std::string("Aliases are not allowed in tool option descriptions!");
1614 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1615 /// EmitPreprocessOptionsCallback.
1616 struct ActionHandlingCallbackBase {
1618 void onErrorDag(const DagInit& d,
1619 unsigned IndentLevel, raw_ostream& O) const
1621 O.indent(IndentLevel)
1622 << "throw std::runtime_error(\"" <<
1623 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1628 void onWarningDag(const DagInit& d,
1629 unsigned IndentLevel, raw_ostream& O) const
1631 checkNumberOfArguments(&d, 1);
1632 O.indent(IndentLevel) << "llvm::errs() << \""
1633 << InitPtrToString(d.getArg(0)) << "\";\n";
1638 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1639 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1640 class EmitActionHandlersCallback : ActionHandlingCallbackBase {
1641 const OptionDescriptions& OptDescs;
1643 void processActionDag(const Init* Statement, unsigned IndentLevel,
1644 raw_ostream& O) const
1646 const DagInit& Dag = InitPtrToDag(Statement);
1647 const std::string& ActionName = GetOperatorName(Dag);
1649 if (ActionName == "append_cmd") {
1650 checkNumberOfArguments(&Dag, 1);
1651 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1653 llvm::SplitString(Cmd, Out);
1655 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1657 O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1659 else if (ActionName == "error") {
1660 this->onErrorDag(Dag, IndentLevel, O);
1662 else if (ActionName == "warning") {
1663 this->onWarningDag(Dag, IndentLevel, O);
1665 else if (ActionName == "forward") {
1666 checkNumberOfArguments(&Dag, 1);
1667 const std::string& Name = InitPtrToString(Dag.getArg(0));
1668 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1669 IndentLevel, "", O);
1671 else if (ActionName == "forward_as") {
1672 checkNumberOfArguments(&Dag, 2);
1673 const std::string& Name = InitPtrToString(Dag.getArg(0));
1674 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1675 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1676 IndentLevel, NewName, O);
1678 else if (ActionName == "output_suffix") {
1679 checkNumberOfArguments(&Dag, 1);
1680 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1681 O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1683 else if (ActionName == "stop_compilation") {
1684 O.indent(IndentLevel) << "stop_compilation = true;\n";
1686 else if (ActionName == "unpack_values") {
1687 checkNumberOfArguments(&Dag, 1);
1688 const std::string& Name = InitPtrToString(Dag.getArg(0));
1689 const OptionDescription& D = OptDescs.FindOption(Name);
1692 throw std::string("Can't use unpack_values with multi-valued options!");
1695 O.indent(IndentLevel)
1696 << "for (" << D.GenTypeDeclaration()
1697 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1698 O.indent(IndentLevel)
1699 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n";
1700 O.indent(IndentLevel + Indent1)
1701 << "llvm::SplitString(*B, vec, \",\");\n";
1703 else if (D.isParameter()){
1704 O.indent(IndentLevel) << "llvm::SplitString("
1705 << D.GenVariableName() << ", vec, \",\");\n";
1708 throw "Option '" + D.Name +
1709 "': switches can't have the 'unpack_values' property!";
1713 throw "Unknown action name: " + ActionName + "!";
1717 EmitActionHandlersCallback(const OptionDescriptions& OD)
1720 void operator()(const Init* Statement,
1721 unsigned IndentLevel, raw_ostream& O) const
1723 this->processActionDag(Statement, IndentLevel, O);
1727 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1729 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1731 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1733 if (*I == "$OUTFILE")
1740 class IsOutFileIndexCheckRequiredStrCallback {
1744 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1747 void operator()(const Init* CmdLine) {
1748 // Ignore nested 'case' DAG.
1749 if (typeid(*CmdLine) == typeid(DagInit))
1752 if (IsOutFileIndexCheckRequiredStr(CmdLine))
1756 void operator()(const DagInit* Test, unsigned, bool) {
1757 this->operator()(Test);
1759 void operator()(const Init* Statement, unsigned) {
1760 this->operator()(Statement);
1764 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1766 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1770 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1771 /// in EmitGenerateActionMethod() ?
1772 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1773 if (typeid(*CmdLine) == typeid(StringInit))
1774 return IsOutFileIndexCheckRequiredStr(CmdLine);
1776 return IsOutFileIndexCheckRequiredCase(CmdLine);
1779 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
1780 // Tool::GenerateAction() method.
1781 void EmitGenerateActionMethod (const ToolDescription& D,
1782 const OptionDescriptions& OptDescs,
1783 bool IsJoin, raw_ostream& O) {
1785 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1787 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1789 O.indent(Indent2) << "bool HasChildren,\n";
1790 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1791 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1792 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1793 O.indent(Indent1) << "{\n";
1794 O.indent(Indent2) << "std::string cmd;\n";
1795 O.indent(Indent2) << "std::vector<std::string> vec;\n";
1796 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1797 O.indent(Indent2) << "const char* output_suffix = \""
1798 << D.OutputSuffix << "\";\n";
1801 throw "Tool " + D.Name + " has no cmd_line property!";
1803 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
1804 O.indent(Indent2) << "int out_file_index"
1805 << (IndexCheckRequired ? " = -1" : "")
1808 // Process the cmd_line property.
1809 if (typeid(*D.CmdLine) == typeid(StringInit))
1810 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1812 EmitCaseConstructHandler(D.CmdLine, Indent2,
1813 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1816 // For every understood option, emit handling code.
1818 EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandlersCallback(OptDescs),
1819 false, OptDescs, O);
1823 << "std::string out_file = OutFilename("
1824 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
1825 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
1827 if (IndexCheckRequired)
1828 O.indent(Indent2) << "if (out_file_index != -1)\n";
1829 O.indent(IndexCheckRequired ? Indent3 : Indent2)
1830 << "vec[out_file_index] = out_file;\n";
1832 // Handle the Sink property.
1834 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
1835 O.indent(Indent3) << "vec.insert(vec.end(), "
1836 << SinkOptionName << ".begin(), " << SinkOptionName
1838 O.indent(Indent2) << "}\n";
1841 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
1842 O.indent(Indent1) << "}\n\n";
1845 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1846 /// a given Tool class.
1847 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1848 const OptionDescriptions& OptDescs,
1850 if (!ToolDesc.isJoin()) {
1851 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1852 O.indent(Indent2) << "bool HasChildren,\n";
1853 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1854 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1855 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1856 O.indent(Indent1) << "{\n";
1857 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
1858 << " is not a Join tool!\");\n";
1859 O.indent(Indent1) << "}\n\n";
1862 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1865 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1868 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1869 /// methods for a given Tool class.
1870 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
1871 O.indent(Indent1) << "const char** InputLanguages() const {\n";
1872 O.indent(Indent2) << "return InputLanguages_;\n";
1873 O.indent(Indent1) << "}\n\n";
1875 if (D.OutLanguage.empty())
1876 throw "Tool " + D.Name + " has no 'out_language' property!";
1878 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
1879 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
1880 O.indent(Indent1) << "}\n\n";
1883 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1884 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
1885 O.indent(Indent1) << "const char* Name() const {\n";
1886 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
1887 O.indent(Indent1) << "}\n\n";
1890 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1892 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
1893 O.indent(Indent1) << "bool IsJoin() const {\n";
1895 O.indent(Indent2) << "return true;\n";
1897 O.indent(Indent2) << "return false;\n";
1898 O.indent(Indent1) << "}\n\n";
1901 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1902 /// given Tool class.
1903 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
1904 if (D.InLanguage.empty())
1905 throw "Tool " + D.Name + " has no 'in_language' property!";
1907 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1908 for (StrVector::const_iterator B = D.InLanguage.begin(),
1909 E = D.InLanguage.end(); B != E; ++B)
1910 O << '\"' << *B << "\", ";
1914 /// EmitToolClassDefinition - Emit a Tool class definition.
1915 void EmitToolClassDefinition (const ToolDescription& D,
1916 const OptionDescriptions& OptDescs,
1918 if (D.Name == "root")
1922 O << "class " << D.Name << " : public ";
1928 O << "{\nprivate:\n";
1929 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
1932 EmitNameMethod(D, O);
1933 EmitInOutLanguageMethods(D, O);
1934 EmitIsJoinMethod(D, O);
1935 EmitGenerateActionMethods(D, OptDescs, O);
1937 // Close class definition
1940 EmitStaticMemberDefinitions(D, O);
1944 /// EmitOptionDefinitions - Iterate over a list of option descriptions
1945 /// and emit registration code.
1946 void EmitOptionDefinitions (const OptionDescriptions& descs,
1947 bool HasSink, bool HasExterns,
1950 std::vector<OptionDescription> Aliases;
1952 // Emit static cl::Option variables.
1953 for (OptionDescriptions::const_iterator B = descs.begin(),
1954 E = descs.end(); B!=E; ++B) {
1955 const OptionDescription& val = B->second;
1957 if (val.Type == OptionType::Alias) {
1958 Aliases.push_back(val);
1965 O << val.GenTypeDeclaration() << ' '
1966 << val.GenVariableName();
1968 if (val.isExtern()) {
1973 O << "(\"" << val.Name << "\"\n";
1975 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1976 O << ", cl::Prefix";
1978 if (val.isRequired()) {
1979 if (val.isList() && !val.isMultiVal())
1980 O << ", cl::OneOrMore";
1982 O << ", cl::Required";
1984 else if (val.isOneOrMore() && val.isList()) {
1985 O << ", cl::OneOrMore";
1987 else if (val.isZeroOrOne() && val.isList()) {
1988 O << ", cl::ZeroOrOne";
1991 if (val.isReallyHidden()) {
1992 O << ", cl::ReallyHidden";
1994 else if (val.isHidden()) {
1995 O << ", cl::Hidden";
1998 if (val.MultiVal > 1)
1999 O << ", cl::multi_val(" << val.MultiVal << ')';
2002 const std::string& str = val.InitVal->getAsString();
2003 O << ", cl::init(" << str << ')';
2006 if (!val.Help.empty())
2007 O << ", cl::desc(\"" << val.Help << "\")";
2012 // Emit the aliases (they should go after all the 'proper' options).
2013 for (std::vector<OptionDescription>::const_iterator
2014 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2015 const OptionDescription& val = *B;
2017 O << val.GenTypeDeclaration() << ' '
2018 << val.GenVariableName()
2019 << "(\"" << val.Name << '\"';
2021 const OptionDescription& D = descs.FindOption(val.Help);
2022 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2024 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2027 // Emit the sink option.
2029 O << (HasExterns ? "extern cl" : "cl")
2030 << "::list<std::string> " << SinkOptionName
2031 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2036 /// EmitPreprocessOptionsCallback - Helper function passed to
2037 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2038 class EmitPreprocessOptionsCallback : ActionHandlingCallbackBase {
2039 const OptionDescriptions& OptDescs_;
2041 void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
2042 const std::string& OptName = InitPtrToString(i);
2043 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2044 const OptionType::OptionType OptType = OptDesc.Type;
2046 if (OptType == OptionType::Switch) {
2047 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2049 else if (OptType == OptionType::Parameter
2050 || OptType == OptionType::Prefix) {
2051 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2054 throw std::string("'unset_option' can only be applied to "
2055 "switches or parameter/prefix options.");
2059 void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
2061 const DagInit& d = InitPtrToDag(I);
2062 const std::string& OpName = GetOperatorName(d);
2064 if (OpName == "warning") {
2065 this->onWarningDag(d, IndentLevel, O);
2067 else if (OpName == "error") {
2068 this->onWarningDag(d, IndentLevel, O);
2070 else if (OpName == "unset_option") {
2071 checkNumberOfArguments(&d, 1);
2072 Init* I = d.getArg(0);
2073 if (typeid(*I) == typeid(ListInit)) {
2074 const ListInit& DagList = *static_cast<const ListInit*>(I);
2075 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2077 this->onUnsetOption(*B, IndentLevel, O);
2080 this->onUnsetOption(I, IndentLevel, O);
2084 throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
2085 "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
2091 void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
2092 this->processDag(I, IndentLevel, O);
2095 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2096 : OptDescs_(OptDescs)
2100 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2101 void EmitPreprocessOptions (const RecordKeeper& Records,
2102 const OptionDescriptions& OptDecs, raw_ostream& O)
2104 O << "void PreprocessOptionsLocal() {\n";
2106 const RecordVector& OptionPreprocessors =
2107 Records.getAllDerivedDefinitions("OptionPreprocessor");
2109 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2110 E = OptionPreprocessors.end(); B!=E; ++B) {
2111 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2112 EmitCaseConstructHandler(Case, Indent1,
2113 EmitPreprocessOptionsCallback(OptDecs),
2120 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2121 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2123 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2125 // Get the relevant field out of RecordKeeper
2126 const Record* LangMapRecord = Records.getDef("LanguageMap");
2128 // It is allowed for a plugin to have no language map.
2129 if (LangMapRecord) {
2131 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2132 if (!LangsToSuffixesList)
2133 throw std::string("Error in the language map definition!");
2135 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2136 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2138 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2139 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2141 for (unsigned i = 0; i < Suffixes->size(); ++i)
2142 O.indent(Indent1) << "langMap[\""
2143 << InitPtrToString(Suffixes->getElement(i))
2144 << "\"] = \"" << Lang << "\";\n";
2151 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2152 /// by EmitEdgeClass().
2153 void IncDecWeight (const Init* i, unsigned IndentLevel,
2155 const DagInit& d = InitPtrToDag(i);
2156 const std::string& OpName = GetOperatorName(d);
2158 if (OpName == "inc_weight") {
2159 O.indent(IndentLevel) << "ret += ";
2161 else if (OpName == "dec_weight") {
2162 O.indent(IndentLevel) << "ret -= ";
2164 else if (OpName == "error") {
2165 checkNumberOfArguments(&d, 1);
2166 O.indent(IndentLevel) << "throw std::runtime_error(\""
2167 << InitPtrToString(d.getArg(0))
2172 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2173 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2176 if (d.getNumArgs() > 0)
2177 O << InitPtrToInt(d.getArg(0)) << ";\n";
2183 /// EmitEdgeClass - Emit a single Edge# class.
2184 void EmitEdgeClass (unsigned N, const std::string& Target,
2185 DagInit* Case, const OptionDescriptions& OptDescs,
2188 // Class constructor.
2189 O << "class Edge" << N << ": public Edge {\n"
2191 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2194 // Function Weight().
2196 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2197 O.indent(Indent2) << "unsigned ret = 0;\n";
2199 // Handle the 'case' construct.
2200 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2202 O.indent(Indent2) << "return ret;\n";
2203 O.indent(Indent1) << "};\n\n};\n\n";
2206 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2207 void EmitEdgeClasses (const RecordVector& EdgeVector,
2208 const OptionDescriptions& OptDescs,
2211 for (RecordVector::const_iterator B = EdgeVector.begin(),
2212 E = EdgeVector.end(); B != E; ++B) {
2213 const Record* Edge = *B;
2214 const std::string& NodeB = Edge->getValueAsString("b");
2215 DagInit* Weight = Edge->getValueAsDag("weight");
2217 if (!isDagEmpty(Weight))
2218 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2223 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2225 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2226 const ToolDescriptions& ToolDescs,
2229 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2231 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2232 E = ToolDescs.end(); B != E; ++B)
2233 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2240 for (RecordVector::const_iterator B = EdgeVector.begin(),
2241 E = EdgeVector.end(); B != E; ++B) {
2242 const Record* Edge = *B;
2243 const std::string& NodeA = Edge->getValueAsString("a");
2244 const std::string& NodeB = Edge->getValueAsString("b");
2245 DagInit* Weight = Edge->getValueAsDag("weight");
2247 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2249 if (isDagEmpty(Weight))
2250 O << "new SimpleEdge(\"" << NodeB << "\")";
2252 O << "new Edge" << i << "()";
2261 /// ExtractHookNames - Extract the hook names from all instances of
2262 /// $CALL(HookName) in the provided command line string. Helper
2263 /// function used by FillInHookNames().
2264 class ExtractHookNames {
2265 llvm::StringMap<unsigned>& HookNames_;
2267 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
2268 : HookNames_(HookNames) {}
2270 void operator()(const Init* CmdLine) {
2273 // Ignore nested 'case' DAG.
2274 if (typeid(*CmdLine) == typeid(DagInit))
2277 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
2278 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2280 const std::string& cmd = *B;
2282 if (cmd == "$CALL") {
2283 unsigned NumArgs = 0;
2284 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2285 const std::string& HookName = *B;
2288 if (HookName.at(0) == ')')
2289 throw "$CALL invoked with no arguments!";
2291 while (++B != E && B->at(0) != ')') {
2295 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
2297 if (H != HookNames_.end() && H->second != NumArgs)
2298 throw "Overloading of hooks is not allowed. Overloaded hook: "
2301 HookNames_[HookName] = NumArgs;
2307 void operator()(const DagInit* Test, unsigned, bool) {
2308 this->operator()(Test);
2310 void operator()(const Init* Statement, unsigned) {
2311 this->operator()(Statement);
2315 /// FillInHookNames - Actually extract the hook names from all command
2316 /// line strings. Helper function used by EmitHookDeclarations().
2317 void FillInHookNames(const ToolDescriptions& ToolDescs,
2318 llvm::StringMap<unsigned>& HookNames)
2320 // For all command lines:
2321 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2322 E = ToolDescs.end(); B != E; ++B) {
2323 const ToolDescription& D = *(*B);
2326 if (dynamic_cast<StringInit*>(D.CmdLine))
2327 // This is a string.
2328 ExtractHookNames(HookNames).operator()(D.CmdLine);
2330 // This is a 'case' construct.
2331 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
2335 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2336 /// property records and emit hook function declaration for each
2337 /// instance of $CALL(HookName).
2338 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
2339 llvm::StringMap<unsigned> HookNames;
2341 FillInHookNames(ToolDescs, HookNames);
2342 if (HookNames.empty())
2345 O << "namespace hooks {\n";
2346 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
2347 E = HookNames.end(); B != E; ++B) {
2348 O.indent(Indent1) << "std::string " << B->first() << "(";
2350 for (unsigned i = 0, j = B->second; i < j; ++i) {
2351 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2359 /// EmitRegisterPlugin - Emit code to register this plugin.
2360 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2361 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2362 O.indent(Indent1) << "int Priority() const { return "
2363 << Priority << "; }\n\n";
2364 O.indent(Indent1) << "void PreprocessOptions() const\n";
2365 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2366 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2367 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2369 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2370 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2372 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2375 /// EmitIncludes - Emit necessary #include directives and some
2376 /// additional declarations.
2377 void EmitIncludes(raw_ostream& O) {
2378 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2379 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2380 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2381 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2382 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2384 << "#include \"llvm/ADT/StringExtras.h\"\n"
2385 << "#include \"llvm/Support/CommandLine.h\"\n"
2386 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2388 << "#include <cstdlib>\n"
2389 << "#include <stdexcept>\n\n"
2391 << "using namespace llvm;\n"
2392 << "using namespace llvmc;\n\n"
2394 << "extern cl::opt<std::string> OutputFilename;\n\n"
2396 << "inline const char* checkCString(const char* s)\n"
2397 << "{ return s == NULL ? \"\" : s; }\n\n";
2401 /// PluginData - Holds all information about a plugin.
2403 OptionDescriptions OptDescs;
2406 ToolDescriptions ToolDescs;
2411 /// HasSink - Go through the list of tool descriptions and check if
2412 /// there are any with the 'sink' property set.
2413 bool HasSink(const ToolDescriptions& ToolDescs) {
2414 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2415 E = ToolDescs.end(); B != E; ++B)
2422 /// HasExterns - Go through the list of option descriptions and check
2423 /// if there are any external options.
2424 bool HasExterns(const OptionDescriptions& OptDescs) {
2425 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2426 E = OptDescs.end(); B != E; ++B)
2427 if (B->second.isExtern())
2433 /// CollectPluginData - Collect tool and option properties,
2434 /// compilation graph edges and plugin priority from the parse tree.
2435 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2436 // Collect option properties.
2437 const RecordVector& OptionLists =
2438 Records.getAllDerivedDefinitions("OptionList");
2439 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2442 // Collect tool properties.
2443 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2444 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2445 Data.HasSink = HasSink(Data.ToolDescs);
2446 Data.HasExterns = HasExterns(Data.OptDescs);
2448 // Collect compilation graph edges.
2449 const RecordVector& CompilationGraphs =
2450 Records.getAllDerivedDefinitions("CompilationGraph");
2451 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2454 // Calculate the priority of this plugin.
2455 const RecordVector& Priorities =
2456 Records.getAllDerivedDefinitions("PluginPriority");
2457 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2460 /// CheckPluginData - Perform some sanity checks on the collected data.
2461 void CheckPluginData(PluginData& Data) {
2462 // Filter out all tools not mentioned in the compilation graph.
2463 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2465 // Typecheck the compilation graph.
2466 TypecheckGraph(Data.Edges, Data.ToolDescs);
2468 // Check that there are no options without side effects (specified
2469 // only in the OptionList).
2470 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2474 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2475 // Emit file header.
2478 // Emit global option registration code.
2479 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2481 // Emit hook declarations.
2482 EmitHookDeclarations(Data.ToolDescs, O);
2484 O << "namespace {\n\n";
2486 // Emit PreprocessOptionsLocal() function.
2487 EmitPreprocessOptions(Records, Data.OptDescs, O);
2489 // Emit PopulateLanguageMapLocal() function
2490 // (language map maps from file extensions to language names).
2491 EmitPopulateLanguageMap(Records, O);
2493 // Emit Tool classes.
2494 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2495 E = Data.ToolDescs.end(); B!=E; ++B)
2496 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2498 // Emit Edge# classes.
2499 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2501 // Emit PopulateCompilationGraphLocal() function.
2502 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2504 // Emit code for plugin registration.
2505 EmitRegisterPlugin(Data.Priority, O);
2507 O << "} // End anonymous namespace.\n\n";
2509 // Force linkage magic.
2510 O << "namespace llvmc {\n";
2511 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2518 // End of anonymous namespace
2521 /// run - The back-end entry point.
2522 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2526 CollectPluginData(Records, Data);
2527 CheckPluginData(Data);
2529 EmitSourceFileHeader("LLVMC Configuration Library", O);
2530 EmitPluginCode(Data, O);
2532 } catch (std::exception& Error) {
2533 throw Error.what() + std::string(" - usually this means a syntax error.");