1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting LLVMC configuration code.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMCConfigurationEmitter.h"
17 #include "llvm/ADT/IntrusiveRefCntPtr.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
32 //===----------------------------------------------------------------------===//
35 typedef std::vector<Record*> RecordVector;
36 typedef std::vector<std::string> StrVector;
38 //===----------------------------------------------------------------------===//
42 static const unsigned TabWidth = 4;
43 static const unsigned Indent1 = TabWidth*1;
44 static const unsigned Indent2 = TabWidth*2;
45 static const unsigned Indent3 = TabWidth*3;
47 // Default help string.
48 static const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
50 // Name for the "sink" option.
51 static const char * const SinkOptionName = "AutoGeneratedSinkOption";
55 //===----------------------------------------------------------------------===//
58 /// Id - An 'identity' function object.
61 void operator()(const T0&) const {
63 template<typename T0, typename T1>
64 void operator()(const T0&, const T1&) const {
66 template<typename T0, typename T1, typename T2>
67 void operator()(const T0&, const T1&, const T2&) const {
71 int InitPtrToInt(const Init* ptr) {
72 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
73 return val.getValue();
76 const std::string& InitPtrToString(const Init* ptr) {
77 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
78 return val.getValue();
81 const ListInit& InitPtrToList(const Init* ptr) {
82 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
86 const DagInit& InitPtrToDag(const Init* ptr) {
87 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
91 const std::string GetOperatorName(const DagInit* D) {
92 return D->getOperator()->getAsString();
95 const std::string GetOperatorName(const DagInit& D) {
96 return GetOperatorName(&D);
99 // checkNumberOfArguments - Ensure that the number of args in d is
100 // greater than or equal to min_arguments, otherwise throw an exception.
101 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
102 if (!d || d->getNumArgs() < min_arguments)
103 throw GetOperatorName(d) + ": too few arguments!";
106 // isDagEmpty - is this DAG marked with an empty marker?
107 bool isDagEmpty (const DagInit* d) {
108 return GetOperatorName(d) == "empty_dag_marker";
111 // EscapeVariableName - Escape commas and other symbols not allowed
112 // in the C++ variable names. Makes it possible to use options named
113 // like "Wa," (useful for prefix options).
114 std::string EscapeVariableName(const std::string& Var) {
116 for (unsigned i = 0; i != Var.size(); ++i) {
117 char cur_char = Var[i];
118 if (cur_char == ',') {
121 else if (cur_char == '+') {
124 else if (cur_char == '-') {
128 ret.push_back(cur_char);
134 /// oneOf - Does the input string contain this character?
135 bool oneOf(const char* lst, char c) {
143 template <class I, class S>
144 void checkedIncrement(I& P, I E, S ErrorString) {
150 // apply is needed because C++'s syntax doesn't let us construct a function
151 // object and call it in the same statement.
152 template<typename F, typename T0>
153 void apply(F Fun, T0& Arg0) {
157 template<typename F, typename T0, typename T1>
158 void apply(F Fun, T0& Arg0, T1& Arg1) {
159 return Fun(Arg0, Arg1);
162 //===----------------------------------------------------------------------===//
163 /// Back-end specific code
166 /// OptionType - One of six different option types. See the
167 /// documentation for detailed description of differences.
168 namespace OptionType {
170 enum OptionType { Alias, Switch, Parameter, ParameterList,
173 bool IsAlias(OptionType t) {
177 bool IsList (OptionType t) {
178 return (t == ParameterList || t == PrefixList);
181 bool IsSwitch (OptionType t) {
182 return (t == Switch);
185 bool IsParameter (OptionType t) {
186 return (t == Parameter || t == Prefix);
191 OptionType::OptionType stringToOptionType(const std::string& T) {
192 if (T == "alias_option")
193 return OptionType::Alias;
194 else if (T == "switch_option")
195 return OptionType::Switch;
196 else if (T == "parameter_option")
197 return OptionType::Parameter;
198 else if (T == "parameter_list_option")
199 return OptionType::ParameterList;
200 else if (T == "prefix_option")
201 return OptionType::Prefix;
202 else if (T == "prefix_list_option")
203 return OptionType::PrefixList;
205 throw "Unknown option type: " + T + '!';
208 namespace OptionDescriptionFlags {
209 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
210 ReallyHidden = 0x4, Extern = 0x8,
211 OneOrMore = 0x10, ZeroOrOne = 0x20 };
214 /// OptionDescription - Represents data contained in a single
215 /// OptionList entry.
216 struct OptionDescription {
217 OptionType::OptionType Type;
224 OptionDescription(OptionType::OptionType t = OptionType::Switch,
225 const std::string& n = "",
226 const std::string& h = DefaultHelpString)
227 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
230 /// GenTypeDeclaration - Returns the C++ variable type of this
232 const char* GenTypeDeclaration() const;
234 /// GenVariableName - Returns the variable name used in the
235 /// generated C++ code.
236 std::string GenVariableName() const;
238 /// Merge - Merge two option descriptions.
239 void Merge (const OptionDescription& other);
241 // Misc convenient getters/setters.
243 bool isAlias() const;
245 bool isMultiVal() const;
247 bool isExtern() const;
250 bool isRequired() const;
253 bool isOneOrMore() const;
256 bool isZeroOrOne() const;
259 bool isHidden() const;
262 bool isReallyHidden() const;
263 void setReallyHidden();
265 bool isSwitch() const
266 { return OptionType::IsSwitch(this->Type); }
268 bool isParameter() const
269 { return OptionType::IsParameter(this->Type); }
272 { return OptionType::IsList(this->Type); }
276 void OptionDescription::Merge (const OptionDescription& other)
278 if (other.Type != Type)
279 throw "Conflicting definitions for the option " + Name + "!";
281 if (Help == other.Help || Help == DefaultHelpString)
283 else if (other.Help != DefaultHelpString) {
284 llvm::errs() << "Warning: several different help strings"
285 " defined for option " + Name + "\n";
288 Flags |= other.Flags;
291 bool OptionDescription::isAlias() const {
292 return OptionType::IsAlias(this->Type);
295 bool OptionDescription::isMultiVal() const {
299 bool OptionDescription::isExtern() const {
300 return Flags & OptionDescriptionFlags::Extern;
302 void OptionDescription::setExtern() {
303 Flags |= OptionDescriptionFlags::Extern;
306 bool OptionDescription::isRequired() const {
307 return Flags & OptionDescriptionFlags::Required;
309 void OptionDescription::setRequired() {
310 Flags |= OptionDescriptionFlags::Required;
313 bool OptionDescription::isOneOrMore() const {
314 return Flags & OptionDescriptionFlags::OneOrMore;
316 void OptionDescription::setOneOrMore() {
317 Flags |= OptionDescriptionFlags::OneOrMore;
320 bool OptionDescription::isZeroOrOne() const {
321 return Flags & OptionDescriptionFlags::ZeroOrOne;
323 void OptionDescription::setZeroOrOne() {
324 Flags |= OptionDescriptionFlags::ZeroOrOne;
327 bool OptionDescription::isHidden() const {
328 return Flags & OptionDescriptionFlags::Hidden;
330 void OptionDescription::setHidden() {
331 Flags |= OptionDescriptionFlags::Hidden;
334 bool OptionDescription::isReallyHidden() const {
335 return Flags & OptionDescriptionFlags::ReallyHidden;
337 void OptionDescription::setReallyHidden() {
338 Flags |= OptionDescriptionFlags::ReallyHidden;
341 const char* OptionDescription::GenTypeDeclaration() const {
343 case OptionType::Alias:
345 case OptionType::PrefixList:
346 case OptionType::ParameterList:
347 return "cl::list<std::string>";
348 case OptionType::Switch:
349 return "cl::opt<bool>";
350 case OptionType::Parameter:
351 case OptionType::Prefix:
353 return "cl::opt<std::string>";
357 std::string OptionDescription::GenVariableName() const {
358 const std::string& EscapedName = EscapeVariableName(Name);
360 case OptionType::Alias:
361 return "AutoGeneratedAlias_" + EscapedName;
362 case OptionType::PrefixList:
363 case OptionType::ParameterList:
364 return "AutoGeneratedList_" + EscapedName;
365 case OptionType::Switch:
366 return "AutoGeneratedSwitch_" + EscapedName;
367 case OptionType::Prefix:
368 case OptionType::Parameter:
370 return "AutoGeneratedParameter_" + EscapedName;
374 /// OptionDescriptions - An OptionDescription array plus some helper
376 class OptionDescriptions {
377 typedef StringMap<OptionDescription> container_type;
379 /// Descriptions - A list of OptionDescriptions.
380 container_type Descriptions;
383 /// FindOption - exception-throwing wrapper for find().
384 const OptionDescription& FindOption(const std::string& OptName) const;
386 // Wrappers for FindOption that throw an exception in case the option has a
388 const OptionDescription& FindSwitch(const std::string& OptName) const;
389 const OptionDescription& FindParameter(const std::string& OptName) const;
390 const OptionDescription& FindList(const std::string& OptName) const;
391 const OptionDescription&
392 FindListOrParameter(const std::string& OptName) const;
394 /// insertDescription - Insert new OptionDescription into
395 /// OptionDescriptions list
396 void InsertDescription (const OptionDescription& o);
398 // Support for STL-style iteration
399 typedef container_type::const_iterator const_iterator;
400 const_iterator begin() const { return Descriptions.begin(); }
401 const_iterator end() const { return Descriptions.end(); }
404 const OptionDescription&
405 OptionDescriptions::FindOption(const std::string& OptName) const {
406 const_iterator I = Descriptions.find(OptName);
407 if (I != Descriptions.end())
410 throw OptName + ": no such option!";
413 const OptionDescription&
414 OptionDescriptions::FindSwitch(const std::string& OptName) const {
415 const OptionDescription& OptDesc = this->FindOption(OptName);
416 if (!OptDesc.isSwitch())
417 throw OptName + ": incorrect option type - should be a switch!";
421 const OptionDescription&
422 OptionDescriptions::FindList(const std::string& OptName) const {
423 const OptionDescription& OptDesc = this->FindOption(OptName);
424 if (!OptDesc.isList())
425 throw OptName + ": incorrect option type - should be a list!";
429 const OptionDescription&
430 OptionDescriptions::FindParameter(const std::string& OptName) const {
431 const OptionDescription& OptDesc = this->FindOption(OptName);
432 if (!OptDesc.isParameter())
433 throw OptName + ": incorrect option type - should be a parameter!";
437 const OptionDescription&
438 OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
439 const OptionDescription& OptDesc = this->FindOption(OptName);
440 if (!OptDesc.isList() && !OptDesc.isParameter())
442 + ": incorrect option type - should be a list or parameter!";
446 void OptionDescriptions::InsertDescription (const OptionDescription& o) {
447 container_type::iterator I = Descriptions.find(o.Name);
448 if (I != Descriptions.end()) {
449 OptionDescription& D = I->second;
453 Descriptions[o.Name] = o;
457 /// HandlerTable - A base class for function objects implemented as
458 /// 'tables of handlers'.
459 template <typename Handler>
462 // Implementation details.
464 /// HandlerMap - A map from property names to property handlers
465 typedef StringMap<Handler> HandlerMap;
467 static HandlerMap Handlers_;
468 static bool staticMembersInitialized_;
472 Handler GetHandler (const std::string& HandlerName) const {
473 typename HandlerMap::iterator method = Handlers_.find(HandlerName);
475 if (method != Handlers_.end()) {
476 Handler h = method->second;
480 throw "No handler found for property " + HandlerName + "!";
484 void AddHandler(const char* Property, Handler H) {
485 Handlers_[Property] = H;
490 template <class FunctionObject>
491 void InvokeDagInitHandler(FunctionObject* Obj, Init* i) {
492 typedef void (FunctionObject::*Handler) (const DagInit*);
494 const DagInit& property = InitPtrToDag(i);
495 const std::string& property_name = GetOperatorName(property);
496 Handler h = Obj->GetHandler(property_name);
498 ((Obj)->*(h))(&property);
501 template <typename H>
502 typename HandlerTable<H>::HandlerMap HandlerTable<H>::Handlers_;
504 template <typename H>
505 bool HandlerTable<H>::staticMembersInitialized_ = false;
508 /// CollectOptionProperties - Function object for iterating over an
509 /// option property list.
510 class CollectOptionProperties;
511 typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler)
514 class CollectOptionProperties
515 : public HandlerTable<CollectOptionPropertiesHandler>
519 /// optDescs_ - OptionDescriptions table. This is where the
520 /// information is stored.
521 OptionDescription& optDesc_;
525 explicit CollectOptionProperties(OptionDescription& OD)
528 if (!staticMembersInitialized_) {
529 AddHandler("extern", &CollectOptionProperties::onExtern);
530 AddHandler("help", &CollectOptionProperties::onHelp);
531 AddHandler("hidden", &CollectOptionProperties::onHidden);
532 AddHandler("init", &CollectOptionProperties::onInit);
533 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
534 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
535 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
536 AddHandler("required", &CollectOptionProperties::onRequired);
537 AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
539 staticMembersInitialized_ = true;
543 /// operator() - Just forwards to the corresponding property
545 void operator() (Init* i) {
546 InvokeDagInitHandler(this, i);
551 /// Option property handlers --
552 /// Methods that handle option properties such as (help) or (hidden).
554 void onExtern (const DagInit* d) {
555 checkNumberOfArguments(d, 0);
556 optDesc_.setExtern();
559 void onHelp (const DagInit* d) {
560 checkNumberOfArguments(d, 1);
561 optDesc_.Help = InitPtrToString(d->getArg(0));
564 void onHidden (const DagInit* d) {
565 checkNumberOfArguments(d, 0);
566 optDesc_.setHidden();
569 void onReallyHidden (const DagInit* d) {
570 checkNumberOfArguments(d, 0);
571 optDesc_.setReallyHidden();
574 void onRequired (const DagInit* d) {
575 checkNumberOfArguments(d, 0);
576 if (optDesc_.isOneOrMore())
577 throw std::string("An option can't have both (required) "
578 "and (one_or_more) properties!");
579 optDesc_.setRequired();
582 void onInit (const DagInit* d) {
583 checkNumberOfArguments(d, 1);
584 Init* i = d->getArg(0);
585 const std::string& str = i->getAsString();
587 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
588 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
591 throw std::string("Incorrect usage of the 'init' option property!");
593 optDesc_.InitVal = i;
596 void onOneOrMore (const DagInit* d) {
597 checkNumberOfArguments(d, 0);
598 if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
599 throw std::string("Only one of (required), (zero_or_one) or "
600 "(one_or_more) properties is allowed!");
601 if (!OptionType::IsList(optDesc_.Type))
602 llvm::errs() << "Warning: specifying the 'one_or_more' property "
603 "on a non-list option will have no effect.\n";
604 optDesc_.setOneOrMore();
607 void onZeroOrOne (const DagInit* d) {
608 checkNumberOfArguments(d, 0);
609 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
610 throw std::string("Only one of (required), (zero_or_one) or "
611 "(one_or_more) properties is allowed!");
612 if (!OptionType::IsList(optDesc_.Type))
613 llvm::errs() << "Warning: specifying the 'zero_or_one' property"
614 "on a non-list option will have no effect.\n";
615 optDesc_.setZeroOrOne();
618 void onMultiVal (const DagInit* d) {
619 checkNumberOfArguments(d, 1);
620 int val = InitPtrToInt(d->getArg(0));
622 throw std::string("Error in the 'multi_val' property: "
623 "the value must be greater than 1!");
624 if (!OptionType::IsList(optDesc_.Type))
625 throw std::string("The multi_val property is valid only "
627 optDesc_.MultiVal = val;
632 /// AddOption - A function object that is applied to every option
633 /// description. Used by CollectOptionDescriptions.
636 OptionDescriptions& OptDescs_;
639 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
642 void operator()(const Init* i) {
643 const DagInit& d = InitPtrToDag(i);
644 checkNumberOfArguments(&d, 1);
646 const OptionType::OptionType Type =
647 stringToOptionType(GetOperatorName(d));
648 const std::string& Name = InitPtrToString(d.getArg(0));
650 OptionDescription OD(Type, Name);
653 checkNumberOfArguments(&d, 2);
656 // Aliases store the aliased option name in the 'Help' field.
657 OD.Help = InitPtrToString(d.getArg(1));
659 else if (!OD.isExtern()) {
660 processOptionProperties(&d, OD);
662 OptDescs_.InsertDescription(OD);
666 /// processOptionProperties - Go through the list of option
667 /// properties and call a corresponding handler for each.
668 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
669 checkNumberOfArguments(d, 2);
670 DagInit::const_arg_iterator B = d->arg_begin();
671 // Skip the first argument: it's always the option name.
673 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
678 /// CollectOptionDescriptions - Collects option properties from all
680 void CollectOptionDescriptions (RecordVector::const_iterator B,
681 RecordVector::const_iterator E,
682 OptionDescriptions& OptDescs)
684 // For every OptionList:
686 RecordVector::value_type T = *B;
687 // Throws an exception if the value does not exist.
688 ListInit* PropList = T->getValueAsListInit("options");
690 // For every option description in this list:
691 // collect the information and
692 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
696 // Tool information record
698 namespace ToolFlags {
699 enum ToolFlags { Join = 0x1, Sink = 0x2 };
702 struct ToolDescription : public RefCountedBase<ToolDescription> {
706 StrVector InLanguage;
707 std::string OutLanguage;
708 std::string OutputSuffix;
711 // Various boolean properties
712 void setSink() { Flags |= ToolFlags::Sink; }
713 bool isSink() const { return Flags & ToolFlags::Sink; }
714 void setJoin() { Flags |= ToolFlags::Join; }
715 bool isJoin() const { return Flags & ToolFlags::Join; }
717 // Default ctor here is needed because StringMap can only store
718 // DefaultConstructible objects
719 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
720 ToolDescription (const std::string& n)
721 : Name(n), CmdLine(0), Actions(0), Flags(0)
725 /// ToolDescriptions - A list of Tool information records.
726 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
729 /// CollectToolProperties - Function object for iterating over a list of
730 /// tool property records.
732 class CollectToolProperties;
733 typedef void (CollectToolProperties::* CollectToolPropertiesHandler)
736 class CollectToolProperties : public HandlerTable<CollectToolPropertiesHandler>
740 /// toolDesc_ - Properties of the current Tool. This is where the
741 /// information is stored.
742 ToolDescription& toolDesc_;
746 explicit CollectToolProperties (ToolDescription& d)
749 if (!staticMembersInitialized_) {
751 AddHandler("actions", &CollectToolProperties::onActions);
752 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
753 AddHandler("in_language", &CollectToolProperties::onInLanguage);
754 AddHandler("join", &CollectToolProperties::onJoin);
755 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
756 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
757 AddHandler("sink", &CollectToolProperties::onSink);
759 staticMembersInitialized_ = true;
763 void operator() (Init* i) {
764 InvokeDagInitHandler(this, i);
769 /// Property handlers --
770 /// Functions that extract information about tool properties from
771 /// DAG representation.
773 void onActions (const DagInit* d) {
774 checkNumberOfArguments(d, 1);
775 Init* Case = d->getArg(0);
776 if (typeid(*Case) != typeid(DagInit) ||
777 GetOperatorName(static_cast<DagInit*>(Case)) != "case")
779 std::string("The argument to (actions) should be a 'case' construct!");
780 toolDesc_.Actions = Case;
783 void onCmdLine (const DagInit* d) {
784 checkNumberOfArguments(d, 1);
785 toolDesc_.CmdLine = d->getArg(0);
788 void onInLanguage (const DagInit* d) {
789 checkNumberOfArguments(d, 1);
790 Init* arg = d->getArg(0);
792 // Find out the argument's type.
793 if (typeid(*arg) == typeid(StringInit)) {
795 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
799 const ListInit& lst = InitPtrToList(arg);
800 StrVector& out = toolDesc_.InLanguage;
802 // Copy strings to the output vector.
803 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
805 out.push_back(InitPtrToString(*B));
808 // Remove duplicates.
809 std::sort(out.begin(), out.end());
810 StrVector::iterator newE = std::unique(out.begin(), out.end());
811 out.erase(newE, out.end());
815 void onJoin (const DagInit* d) {
816 checkNumberOfArguments(d, 0);
820 void onOutLanguage (const DagInit* d) {
821 checkNumberOfArguments(d, 1);
822 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
825 void onOutputSuffix (const DagInit* d) {
826 checkNumberOfArguments(d, 1);
827 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
830 void onSink (const DagInit* d) {
831 checkNumberOfArguments(d, 0);
837 /// CollectToolDescriptions - Gather information about tool properties
838 /// from the parsed TableGen data (basically a wrapper for the
839 /// CollectToolProperties function object).
840 void CollectToolDescriptions (RecordVector::const_iterator B,
841 RecordVector::const_iterator E,
842 ToolDescriptions& ToolDescs)
844 // Iterate over a properties list of every Tool definition
846 const Record* T = *B;
847 // Throws an exception if the value does not exist.
848 ListInit* PropList = T->getValueAsListInit("properties");
850 IntrusiveRefCntPtr<ToolDescription>
851 ToolDesc(new ToolDescription(T->getName()));
853 std::for_each(PropList->begin(), PropList->end(),
854 CollectToolProperties(*ToolDesc));
855 ToolDescs.push_back(ToolDesc);
859 /// FillInEdgeVector - Merge all compilation graph definitions into
860 /// one single edge list.
861 void FillInEdgeVector(RecordVector::const_iterator B,
862 RecordVector::const_iterator E, RecordVector& Out) {
863 for (; B != E; ++B) {
864 const ListInit* edges = (*B)->getValueAsListInit("edges");
866 for (unsigned i = 0; i < edges->size(); ++i)
867 Out.push_back(edges->getElementAsRecord(i));
871 /// CalculatePriority - Calculate the priority of this plugin.
872 int CalculatePriority(RecordVector::const_iterator B,
873 RecordVector::const_iterator E) {
877 priority = static_cast<int>((*B)->getValueAsInt("priority"));
880 throw std::string("More than one 'PluginPriority' instance found: "
881 "most probably an error!");
887 /// NotInGraph - Helper function object for FilterNotInGraph.
890 const llvm::StringSet<>& ToolsInGraph_;
893 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
894 : ToolsInGraph_(ToolsInGraph)
897 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
898 return (ToolsInGraph_.count(x->Name) == 0);
902 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
903 /// mentioned in the compilation graph definition.
904 void FilterNotInGraph (const RecordVector& EdgeVector,
905 ToolDescriptions& ToolDescs) {
907 // List all tools mentioned in the graph.
908 llvm::StringSet<> ToolsInGraph;
910 for (RecordVector::const_iterator B = EdgeVector.begin(),
911 E = EdgeVector.end(); B != E; ++B) {
913 const Record* Edge = *B;
914 const std::string& NodeA = Edge->getValueAsString("a");
915 const std::string& NodeB = Edge->getValueAsString("b");
918 ToolsInGraph.insert(NodeA);
919 ToolsInGraph.insert(NodeB);
922 // Filter ToolPropertiesList.
923 ToolDescriptions::iterator new_end =
924 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
925 NotInGraph(ToolsInGraph));
926 ToolDescs.erase(new_end, ToolDescs.end());
929 /// FillInToolToLang - Fills in two tables that map tool names to
930 /// (input, output) languages. Helper function used by TypecheckGraph().
931 void FillInToolToLang (const ToolDescriptions& ToolDescs,
932 StringMap<StringSet<> >& ToolToInLang,
933 StringMap<std::string>& ToolToOutLang) {
934 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
935 E = ToolDescs.end(); B != E; ++B) {
936 const ToolDescription& D = *(*B);
937 for (StrVector::const_iterator B = D.InLanguage.begin(),
938 E = D.InLanguage.end(); B != E; ++B)
939 ToolToInLang[D.Name].insert(*B);
940 ToolToOutLang[D.Name] = D.OutLanguage;
944 /// TypecheckGraph - Check that names for output and input languages
945 /// on all edges do match. This doesn't do much when the information
946 /// about the whole graph is not available (i.e. when compiling most
948 void TypecheckGraph (const RecordVector& EdgeVector,
949 const ToolDescriptions& ToolDescs) {
950 StringMap<StringSet<> > ToolToInLang;
951 StringMap<std::string> ToolToOutLang;
953 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
954 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
955 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
957 for (RecordVector::const_iterator B = EdgeVector.begin(),
958 E = EdgeVector.end(); B != E; ++B) {
959 const Record* Edge = *B;
960 const std::string& NodeA = Edge->getValueAsString("a");
961 const std::string& NodeB = Edge->getValueAsString("b");
962 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
963 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
965 if (NodeA != "root") {
966 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
967 throw "Edge " + NodeA + "->" + NodeB
968 + ": output->input language mismatch";
972 throw std::string("Edges back to the root are not allowed!");
976 /// WalkCase - Walks the 'case' expression DAG and invokes
977 /// TestCallback on every test, and StatementCallback on every
978 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
979 /// combinators (that is, they are passed directly to TestCallback).
980 /// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
981 /// IndentLevel, bool FirstTest)'.
982 /// StatementCallback must have type 'void StatementCallback(const Init*,
983 /// unsigned IndentLevel)'.
984 template <typename F1, typename F2>
985 void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
986 unsigned IndentLevel = 0)
988 const DagInit& d = InitPtrToDag(Case);
991 if (GetOperatorName(d) != "case")
992 throw std::string("WalkCase should be invoked only on 'case' expressions!");
994 if (d.getNumArgs() < 2)
995 throw "There should be at least one clause in the 'case' expression:\n"
1000 const unsigned numArgs = d.getNumArgs();
1002 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1009 const DagInit& Test = InitPtrToDag(arg);
1011 if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
1012 throw std::string("The 'default' clause should be the last in the"
1013 "'case' construct!");
1015 throw "Case construct handler: no corresponding action "
1016 "found for the test " + Test.getAsString() + '!';
1018 TestCallback(&Test, IndentLevel, (i == 1));
1022 if (dynamic_cast<DagInit*>(arg)
1023 && GetOperatorName(static_cast<DagInit*>(arg)) == "case") {
1025 WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
1028 // Handle statement.
1029 StatementCallback(arg, IndentLevel);
1037 /// ExtractOptionNames - A helper function object used by
1038 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
1039 class ExtractOptionNames {
1040 llvm::StringSet<>& OptionNames_;
1042 void processDag(const Init* Statement) {
1043 const DagInit& Stmt = InitPtrToDag(Statement);
1044 const std::string& ActionName = GetOperatorName(Stmt);
1045 if (ActionName == "forward" || ActionName == "forward_as" ||
1046 ActionName == "unpack_values" || ActionName == "switch_on" ||
1047 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
1048 ActionName == "not_empty" || ActionName == "empty") {
1049 checkNumberOfArguments(&Stmt, 1);
1050 const std::string& Name = InitPtrToString(Stmt.getArg(0));
1051 OptionNames_.insert(Name);
1053 else if (ActionName == "and" || ActionName == "or") {
1054 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
1055 this->processDag(Stmt.getArg(i));
1061 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
1064 void operator()(const Init* Statement) {
1065 if (typeid(*Statement) == typeid(ListInit)) {
1066 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1067 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1069 this->processDag(*B);
1072 this->processDag(Statement);
1076 void operator()(const DagInit* Test, unsigned, bool) {
1077 this->operator()(Test);
1079 void operator()(const Init* Statement, unsigned) {
1080 this->operator()(Statement);
1084 /// CheckForSuperfluousOptions - Check that there are no side
1085 /// effect-free options (specified only in the OptionList). Otherwise,
1086 /// output a warning.
1087 void CheckForSuperfluousOptions (const RecordVector& Edges,
1088 const ToolDescriptions& ToolDescs,
1089 const OptionDescriptions& OptDescs) {
1090 llvm::StringSet<> nonSuperfluousOptions;
1092 // Add all options mentioned in the ToolDesc.Actions to the set of
1093 // non-superfluous options.
1094 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
1095 E = ToolDescs.end(); B != E; ++B) {
1096 const ToolDescription& TD = *(*B);
1097 ExtractOptionNames Callback(nonSuperfluousOptions);
1099 WalkCase(TD.Actions, Callback, Callback);
1102 // Add all options mentioned in the 'case' clauses of the
1103 // OptionalEdges of the compilation graph to the set of
1104 // non-superfluous options.
1105 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
1107 const Record* Edge = *B;
1108 DagInit* Weight = Edge->getValueAsDag("weight");
1110 if (!isDagEmpty(Weight))
1111 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
1114 // Check that all options in OptDescs belong to the set of
1115 // non-superfluous options.
1116 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
1117 E = OptDescs.end(); B != E; ++B) {
1118 const OptionDescription& Val = B->second;
1119 if (!nonSuperfluousOptions.count(Val.Name)
1120 && Val.Type != OptionType::Alias)
1121 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
1122 "Probable cause: this option is specified only in the OptionList.\n";
1126 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
1127 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
1128 if (TestName == "single_input_file") {
1129 O << "InputFilenames.size() == 1";
1132 else if (TestName == "multiple_input_files") {
1133 O << "InputFilenames.size() > 1";
1140 /// EmitListTest - Helper function used by EmitCaseTest1ArgList().
1141 template <typename F>
1142 void EmitListTest(const ListInit& L, const char* LogicOp,
1143 F Callback, raw_ostream& O)
1145 // This is a lot like EmitLogicalOperationTest, but works on ListInits instead
1147 bool isFirst = true;
1148 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1153 Callback(InitPtrToString(*B), O);
1157 // Callbacks for use with EmitListTest.
1159 class EmitSwitchOn {
1160 const OptionDescriptions& OptDescs_;
1162 EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
1165 void operator()(const std::string& OptName, raw_ostream& O) const {
1166 const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
1167 O << OptDesc.GenVariableName();
1171 class EmitEmptyTest {
1173 const OptionDescriptions& OptDescs_;
1175 EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
1176 : EmitNegate_(EmitNegate), OptDescs_(OptDescs)
1179 void operator()(const std::string& OptName, raw_ostream& O) const {
1180 const char* Neg = (EmitNegate_ ? "!" : "");
1181 if (OptName == "o") {
1182 O << Neg << "OutputFilename.empty()";
1184 else if (OptName == "save-temps") {
1185 O << Neg << "(SaveTemps == SaveTempsEnum::Unset)";
1188 const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
1189 O << Neg << OptDesc.GenVariableName() << ".empty()";
1195 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1196 bool EmitCaseTest1ArgList(const std::string& TestName,
1198 const OptionDescriptions& OptDescs,
1200 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1202 if (TestName == "any_switch_on") {
1203 EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
1206 else if (TestName == "switch_on") {
1207 EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
1210 else if (TestName == "any_not_empty") {
1211 EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
1214 else if (TestName == "any_empty") {
1215 EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
1218 else if (TestName == "not_empty") {
1219 EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
1222 else if (TestName == "empty") {
1223 EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
1230 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1231 bool EmitCaseTest1ArgStr(const std::string& TestName,
1233 const OptionDescriptions& OptDescs,
1235 const std::string& OptName = InitPtrToString(d.getArg(0));
1237 if (TestName == "switch_on") {
1238 apply(EmitSwitchOn(OptDescs), OptName, O);
1241 else if (TestName == "input_languages_contain") {
1242 O << "InLangs.count(\"" << OptName << "\") != 0";
1245 else if (TestName == "in_language") {
1246 // This works only for single-argument Tool::GenerateAction. Join
1247 // tools can process several files in different languages simultaneously.
1249 // TODO: make this work with Edge::Weight (if possible).
1250 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1253 else if (TestName == "not_empty" || TestName == "empty") {
1254 bool EmitNegate = (TestName == "not_empty");
1255 apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
1262 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1263 bool EmitCaseTest1Arg(const std::string& TestName,
1265 const OptionDescriptions& OptDescs,
1267 checkNumberOfArguments(&d, 1);
1268 if (typeid(*d.getArg(0)) == typeid(ListInit))
1269 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1271 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1274 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1275 bool EmitCaseTest2Args(const std::string& TestName,
1277 unsigned IndentLevel,
1278 const OptionDescriptions& OptDescs,
1280 checkNumberOfArguments(&d, 2);
1281 const std::string& OptName = InitPtrToString(d.getArg(0));
1282 const std::string& OptArg = InitPtrToString(d.getArg(1));
1284 if (TestName == "parameter_equals") {
1285 const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
1286 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1289 else if (TestName == "element_in_list") {
1290 const OptionDescription& OptDesc = OptDescs.FindList(OptName);
1291 const std::string& VarName = OptDesc.GenVariableName();
1292 O << "std::find(" << VarName << ".begin(),\n";
1293 O.indent(IndentLevel + Indent1)
1294 << VarName << ".end(), \""
1295 << OptArg << "\") != " << VarName << ".end()";
1302 // Forward declaration.
1303 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1304 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1305 const OptionDescriptions& OptDescs,
1308 /// EmitLogicalOperationTest - Helper function used by
1309 /// EmitCaseConstructHandler.
1310 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1311 unsigned IndentLevel,
1312 const OptionDescriptions& OptDescs,
1315 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1316 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1317 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1318 if (j != NumArgs - 1) {
1320 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1328 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1329 const OptionDescriptions& OptDescs, raw_ostream& O)
1331 checkNumberOfArguments(&d, 1);
1332 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1334 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1338 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1339 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1340 const OptionDescriptions& OptDescs,
1342 const std::string& TestName = GetOperatorName(d);
1344 if (TestName == "and")
1345 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1346 else if (TestName == "or")
1347 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1348 else if (TestName == "not")
1349 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1350 else if (EmitCaseTest0Args(TestName, O))
1352 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1354 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1357 throw TestName + ": unknown edge property!";
1361 /// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
1362 class EmitCaseTestCallback {
1364 const OptionDescriptions& OptDescs_;
1368 EmitCaseTestCallback(bool EmitElseIf,
1369 const OptionDescriptions& OptDescs, raw_ostream& O)
1370 : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
1373 void operator()(const DagInit* Test, unsigned IndentLevel, bool FirstTest)
1375 if (GetOperatorName(Test) == "default") {
1376 O_.indent(IndentLevel) << "else {\n";
1379 O_.indent(IndentLevel)
1380 << ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
1381 EmitCaseTest(*Test, IndentLevel, OptDescs_, O_);
1387 /// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
1388 template <typename F>
1389 class EmitCaseStatementCallback {
1394 EmitCaseStatementCallback(F Callback, raw_ostream& O)
1395 : Callback_(Callback), O_(O)
1398 void operator() (const Init* Statement, unsigned IndentLevel) {
1400 // Ignore nested 'case' DAG.
1401 if (!(dynamic_cast<const DagInit*>(Statement) &&
1402 GetOperatorName(static_cast<const DagInit*>(Statement)) == "case")) {
1403 if (typeid(*Statement) == typeid(ListInit)) {
1404 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1405 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1407 Callback_(*B, (IndentLevel + Indent1), O_);
1410 Callback_(Statement, (IndentLevel + Indent1), O_);
1413 O_.indent(IndentLevel) << "}\n";
1418 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1419 /// construct. Takes a function object that should emit code for every case
1420 /// clause. Implemented on top of WalkCase.
1421 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1422 /// raw_ostream& O).
1423 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1424 /// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
1426 template <typename F>
1427 void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
1428 F Callback, bool EmitElseIf,
1429 const OptionDescriptions& OptDescs,
1431 WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
1432 EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
1435 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1436 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1437 /// Helper function used by EmitCmdLineVecFill and.
1438 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1439 const char* Delimiters = " \t\n\v\f\r";
1441 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1444 if (CmdLine.empty())
1448 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1451 for (; B != E; ++B) {
1452 char cur_ch = CmdLine[B];
1456 if (cur_ch == '$') {
1457 cur_st = SpecialCommand;
1460 if (oneOf(Delimiters, cur_ch)) {
1462 B = CmdLine.find_first_not_of(Delimiters, B);
1463 if (B == std::string::npos) {
1474 case SpecialCommand:
1475 if (oneOf(Delimiters, cur_ch)) {
1480 if (cur_ch == '(') {
1482 cur_st = InsideSpecialCommand;
1487 case InsideSpecialCommand:
1488 if (oneOf(Delimiters, cur_ch)) {
1491 if (cur_ch == '\'') {
1492 cur_st = InsideQuotationMarks;
1496 if (cur_ch == ')') {
1500 if (cur_ch == ',') {
1506 case InsideQuotationMarks:
1507 if (cur_ch == '\'') {
1508 cur_st = InsideSpecialCommand;
1514 Out.back().push_back(cur_ch);
1518 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1519 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1520 StrVector::const_iterator SubstituteSpecialCommands
1521 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1524 const std::string& cmd = *Pos;
1526 if (cmd == "$CALL") {
1527 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1528 const std::string& CmdName = *Pos;
1531 throw std::string("$CALL invocation: empty argument list!");
1534 O << CmdName << "(";
1537 bool firstIteration = true;
1539 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1540 const std::string& Arg = *Pos;
1541 assert(Arg.size() != 0);
1547 firstIteration = false;
1551 O << '"' << Arg << '"';
1557 else if (cmd == "$ENV") {
1558 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1559 const std::string& EnvName = *Pos;
1562 throw "$ENV invocation: empty argument list!";
1564 O << "checkCString(std::getenv(\"";
1568 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1571 throw "Unknown special command: " + cmd;
1574 const std::string& Leftover = *Pos;
1575 assert(Leftover.at(0) == ')');
1576 if (Leftover.size() != 1)
1577 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1582 /// EmitCmdLineVecFill - Emit code that fills in the command line
1583 /// vector. Helper function used by EmitGenerateActionMethod().
1584 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1585 bool IsJoin, unsigned IndentLevel,
1588 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1591 throw "Tool '" + ToolName + "' has empty command line!";
1593 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1595 // If there is a hook invocation on the place of the first command, skip it.
1596 assert(!StrVec[0].empty());
1597 if (StrVec[0][0] == '$') {
1598 while (I != E && (*I)[0] != ')' )
1601 // Skip the ')' symbol.
1608 bool hasINFILE = false;
1610 for (; I != E; ++I) {
1611 const std::string& cmd = *I;
1612 assert(!cmd.empty());
1613 O.indent(IndentLevel);
1614 if (cmd.at(0) == '$') {
1615 if (cmd == "$INFILE") {
1618 O << "for (PathVector::const_iterator B = inFiles.begin()"
1619 << ", E = inFiles.end();\n";
1620 O.indent(IndentLevel) << "B != E; ++B)\n";
1621 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1624 O << "vec.push_back(inFile.str());\n";
1627 else if (cmd == "$OUTFILE") {
1628 O << "vec.push_back(\"\");\n";
1629 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1632 O << "vec.push_back(";
1633 I = SubstituteSpecialCommands(I, E, O);
1638 O << "vec.push_back(\"" << cmd << "\");\n";
1642 throw "Tool '" + ToolName + "' doesn't take any input!";
1644 O.indent(IndentLevel) << "cmd = ";
1645 if (StrVec[0][0] == '$')
1646 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1648 O << '"' << StrVec[0] << '"';
1652 /// EmitCmdLineVecFillCallback - A function object wrapper around
1653 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1654 /// argument to EmitCaseConstructHandler().
1655 class EmitCmdLineVecFillCallback {
1657 const std::string& ToolName;
1659 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1660 : IsJoin(J), ToolName(TN) {}
1662 void operator()(const Init* Statement, unsigned IndentLevel,
1663 raw_ostream& O) const
1665 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1669 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1670 /// implement EmitActionHandler. Emits code for
1671 /// handling the (forward) and (forward_as) option properties.
1672 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1673 unsigned IndentLevel,
1674 const std::string& NewName,
1676 const std::string& Name = NewName.empty()
1679 unsigned IndentLevel1 = IndentLevel + Indent1;
1682 case OptionType::Switch:
1683 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1685 case OptionType::Parameter:
1686 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1687 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1689 case OptionType::Prefix:
1690 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1691 << D.GenVariableName() << ");\n";
1693 case OptionType::PrefixList:
1694 O.indent(IndentLevel)
1695 << "for (" << D.GenTypeDeclaration()
1696 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1697 O.indent(IndentLevel)
1698 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1699 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1700 O.indent(IndentLevel1) << "++B;\n";
1702 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1703 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1704 O.indent(IndentLevel1) << "++B;\n";
1707 O.indent(IndentLevel) << "}\n";
1709 case OptionType::ParameterList:
1710 O.indent(IndentLevel)
1711 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1712 << D.GenVariableName() << ".begin(),\n";
1713 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1714 << ".end() ; B != E;) {\n";
1715 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1717 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1718 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1719 O.indent(IndentLevel1) << "++B;\n";
1722 O.indent(IndentLevel) << "}\n";
1724 case OptionType::Alias:
1726 throw std::string("Aliases are not allowed in tool option descriptions!");
1730 /// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
1731 /// EmitPreprocessOptionsCallback.
1732 struct ActionHandlingCallbackBase {
1734 void onErrorDag(const DagInit& d,
1735 unsigned IndentLevel, raw_ostream& O) const
1737 O.indent(IndentLevel)
1738 << "throw std::runtime_error(\"" <<
1739 (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
1744 void onWarningDag(const DagInit& d,
1745 unsigned IndentLevel, raw_ostream& O) const
1747 checkNumberOfArguments(&d, 1);
1748 O.indent(IndentLevel) << "llvm::errs() << \""
1749 << InitPtrToString(d.getArg(0)) << "\";\n";
1754 /// EmitActionHandlersCallback - Emit code that handles actions. Used by
1755 /// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
1756 class EmitActionHandlersCallback;
1757 typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler)
1758 (const DagInit&, unsigned, raw_ostream&) const;
1760 class EmitActionHandlersCallback
1761 : public ActionHandlingCallbackBase,
1762 public HandlerTable<EmitActionHandlersCallbackHandler>
1764 const OptionDescriptions& OptDescs;
1765 typedef EmitActionHandlersCallbackHandler Handler;
1767 void onAppendCmd (const DagInit& Dag,
1768 unsigned IndentLevel, raw_ostream& O) const
1770 checkNumberOfArguments(&Dag, 1);
1771 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1773 llvm::SplitString(Cmd, Out);
1775 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1777 O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1780 void onForward (const DagInit& Dag,
1781 unsigned IndentLevel, raw_ostream& O) const
1783 checkNumberOfArguments(&Dag, 1);
1784 const std::string& Name = InitPtrToString(Dag.getArg(0));
1785 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1786 IndentLevel, "", O);
1789 void onForwardAs (const DagInit& Dag,
1790 unsigned IndentLevel, raw_ostream& O) const
1792 checkNumberOfArguments(&Dag, 2);
1793 const std::string& Name = InitPtrToString(Dag.getArg(0));
1794 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1795 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1796 IndentLevel, NewName, O);
1799 void onOutputSuffix (const DagInit& Dag,
1800 unsigned IndentLevel, raw_ostream& O) const
1802 checkNumberOfArguments(&Dag, 1);
1803 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1804 O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1807 void onStopCompilation (const DagInit& Dag,
1808 unsigned IndentLevel, raw_ostream& O) const
1810 O.indent(IndentLevel) << "stop_compilation = true;\n";
1814 void onUnpackValues (const DagInit& Dag,
1815 unsigned IndentLevel, raw_ostream& O) const
1817 checkNumberOfArguments(&Dag, 1);
1818 const std::string& Name = InitPtrToString(Dag.getArg(0));
1819 const OptionDescription& D = OptDescs.FindOption(Name);
1822 throw std::string("Can't use unpack_values with multi-valued options!");
1825 O.indent(IndentLevel)
1826 << "for (" << D.GenTypeDeclaration()
1827 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1828 O.indent(IndentLevel)
1829 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n";
1830 O.indent(IndentLevel + Indent1)
1831 << "llvm::SplitString(*B, vec, \",\");\n";
1833 else if (D.isParameter()){
1834 O.indent(IndentLevel) << "llvm::SplitString("
1835 << D.GenVariableName() << ", vec, \",\");\n";
1838 throw "Option '" + D.Name +
1839 "': switches can't have the 'unpack_values' property!";
1845 explicit EmitActionHandlersCallback(const OptionDescriptions& OD)
1848 if (!staticMembersInitialized_) {
1849 AddHandler("error", &EmitActionHandlersCallback::onErrorDag);
1850 AddHandler("warning", &EmitActionHandlersCallback::onWarningDag);
1851 AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd);
1852 AddHandler("forward", &EmitActionHandlersCallback::onForward);
1853 AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs);
1854 AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix);
1855 AddHandler("stop_compilation",
1856 &EmitActionHandlersCallback::onStopCompilation);
1857 AddHandler("unpack_values",
1858 &EmitActionHandlersCallback::onUnpackValues);
1860 staticMembersInitialized_ = true;
1864 void operator()(const Init* Statement,
1865 unsigned IndentLevel, raw_ostream& O) const
1867 const DagInit& Dag = InitPtrToDag(Statement);
1868 const std::string& ActionName = GetOperatorName(Dag);
1869 Handler h = GetHandler(ActionName);
1871 ((this)->*(h))(Dag, IndentLevel, O);
1875 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1877 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1879 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1881 if (*I == "$OUTFILE")
1888 class IsOutFileIndexCheckRequiredStrCallback {
1892 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1895 void operator()(const Init* CmdLine) {
1896 // Ignore nested 'case' DAG.
1897 if (typeid(*CmdLine) == typeid(DagInit))
1900 if (IsOutFileIndexCheckRequiredStr(CmdLine))
1904 void operator()(const DagInit* Test, unsigned, bool) {
1905 this->operator()(Test);
1907 void operator()(const Init* Statement, unsigned) {
1908 this->operator()(Statement);
1912 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1914 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1918 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1919 /// in EmitGenerateActionMethod() ?
1920 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1921 if (typeid(*CmdLine) == typeid(StringInit))
1922 return IsOutFileIndexCheckRequiredStr(CmdLine);
1924 return IsOutFileIndexCheckRequiredCase(CmdLine);
1927 void EmitGenerateActionMethodHeader(const ToolDescription& D,
1928 bool IsJoin, raw_ostream& O)
1931 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1933 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1935 O.indent(Indent2) << "bool HasChildren,\n";
1936 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1937 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1938 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1939 O.indent(Indent1) << "{\n";
1940 O.indent(Indent2) << "std::string cmd;\n";
1941 O.indent(Indent2) << "std::vector<std::string> vec;\n";
1942 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1943 O.indent(Indent2) << "const char* output_suffix = \""
1944 << D.OutputSuffix << "\";\n";
1947 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
1948 // Tool::GenerateAction() method.
1949 void EmitGenerateActionMethod (const ToolDescription& D,
1950 const OptionDescriptions& OptDescs,
1951 bool IsJoin, raw_ostream& O) {
1953 EmitGenerateActionMethodHeader(D, IsJoin, O);
1956 throw "Tool " + D.Name + " has no cmd_line property!";
1958 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
1959 O.indent(Indent2) << "int out_file_index"
1960 << (IndexCheckRequired ? " = -1" : "")
1963 // Process the cmd_line property.
1964 if (typeid(*D.CmdLine) == typeid(StringInit))
1965 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1967 EmitCaseConstructHandler(D.CmdLine, Indent2,
1968 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1971 // For every understood option, emit handling code.
1973 EmitCaseConstructHandler(D.Actions, Indent2,
1974 EmitActionHandlersCallback(OptDescs),
1975 false, OptDescs, O);
1979 << "std::string out_file = OutFilename("
1980 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
1981 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
1983 if (IndexCheckRequired)
1984 O.indent(Indent2) << "if (out_file_index != -1)\n";
1985 O.indent(IndexCheckRequired ? Indent3 : Indent2)
1986 << "vec[out_file_index] = out_file;\n";
1988 // Handle the Sink property.
1990 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
1991 O.indent(Indent3) << "vec.insert(vec.end(), "
1992 << SinkOptionName << ".begin(), " << SinkOptionName
1994 O.indent(Indent2) << "}\n";
1997 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
1998 O.indent(Indent1) << "}\n\n";
2001 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
2002 /// a given Tool class.
2003 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
2004 const OptionDescriptions& OptDescs,
2006 if (!ToolDesc.isJoin()) {
2007 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
2008 O.indent(Indent2) << "bool HasChildren,\n";
2009 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
2010 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
2011 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
2012 O.indent(Indent1) << "{\n";
2013 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
2014 << " is not a Join tool!\");\n";
2015 O.indent(Indent1) << "}\n\n";
2018 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
2021 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
2024 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
2025 /// methods for a given Tool class.
2026 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
2027 O.indent(Indent1) << "const char** InputLanguages() const {\n";
2028 O.indent(Indent2) << "return InputLanguages_;\n";
2029 O.indent(Indent1) << "}\n\n";
2031 if (D.OutLanguage.empty())
2032 throw "Tool " + D.Name + " has no 'out_language' property!";
2034 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
2035 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
2036 O.indent(Indent1) << "}\n\n";
2039 /// EmitNameMethod - Emit the Name() method for a given Tool class.
2040 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
2041 O.indent(Indent1) << "const char* Name() const {\n";
2042 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
2043 O.indent(Indent1) << "}\n\n";
2046 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
2048 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
2049 O.indent(Indent1) << "bool IsJoin() const {\n";
2051 O.indent(Indent2) << "return true;\n";
2053 O.indent(Indent2) << "return false;\n";
2054 O.indent(Indent1) << "}\n\n";
2057 /// EmitStaticMemberDefinitions - Emit static member definitions for a
2058 /// given Tool class.
2059 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
2060 if (D.InLanguage.empty())
2061 throw "Tool " + D.Name + " has no 'in_language' property!";
2063 O << "const char* " << D.Name << "::InputLanguages_[] = {";
2064 for (StrVector::const_iterator B = D.InLanguage.begin(),
2065 E = D.InLanguage.end(); B != E; ++B)
2066 O << '\"' << *B << "\", ";
2070 /// EmitToolClassDefinition - Emit a Tool class definition.
2071 void EmitToolClassDefinition (const ToolDescription& D,
2072 const OptionDescriptions& OptDescs,
2074 if (D.Name == "root")
2078 O << "class " << D.Name << " : public ";
2084 O << "{\nprivate:\n";
2085 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
2088 EmitNameMethod(D, O);
2089 EmitInOutLanguageMethods(D, O);
2090 EmitIsJoinMethod(D, O);
2091 EmitGenerateActionMethods(D, OptDescs, O);
2093 // Close class definition
2096 EmitStaticMemberDefinitions(D, O);
2100 /// EmitOptionDefinitions - Iterate over a list of option descriptions
2101 /// and emit registration code.
2102 void EmitOptionDefinitions (const OptionDescriptions& descs,
2103 bool HasSink, bool HasExterns,
2106 std::vector<OptionDescription> Aliases;
2108 // Emit static cl::Option variables.
2109 for (OptionDescriptions::const_iterator B = descs.begin(),
2110 E = descs.end(); B!=E; ++B) {
2111 const OptionDescription& val = B->second;
2113 if (val.Type == OptionType::Alias) {
2114 Aliases.push_back(val);
2121 O << val.GenTypeDeclaration() << ' '
2122 << val.GenVariableName();
2124 if (val.isExtern()) {
2129 O << "(\"" << val.Name << "\"\n";
2131 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
2132 O << ", cl::Prefix";
2134 if (val.isRequired()) {
2135 if (val.isList() && !val.isMultiVal())
2136 O << ", cl::OneOrMore";
2138 O << ", cl::Required";
2140 else if (val.isOneOrMore() && val.isList()) {
2141 O << ", cl::OneOrMore";
2143 else if (val.isZeroOrOne() && val.isList()) {
2144 O << ", cl::ZeroOrOne";
2147 if (val.isReallyHidden()) {
2148 O << ", cl::ReallyHidden";
2150 else if (val.isHidden()) {
2151 O << ", cl::Hidden";
2154 if (val.MultiVal > 1)
2155 O << ", cl::multi_val(" << val.MultiVal << ')';
2158 const std::string& str = val.InitVal->getAsString();
2159 O << ", cl::init(" << str << ')';
2162 if (!val.Help.empty())
2163 O << ", cl::desc(\"" << val.Help << "\")";
2168 // Emit the aliases (they should go after all the 'proper' options).
2169 for (std::vector<OptionDescription>::const_iterator
2170 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
2171 const OptionDescription& val = *B;
2173 O << val.GenTypeDeclaration() << ' '
2174 << val.GenVariableName()
2175 << "(\"" << val.Name << '\"';
2177 const OptionDescription& D = descs.FindOption(val.Help);
2178 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
2180 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
2183 // Emit the sink option.
2185 O << (HasExterns ? "extern cl" : "cl")
2186 << "::list<std::string> " << SinkOptionName
2187 << (HasExterns ? ";\n" : "(cl::Sink);\n");
2192 /// EmitPreprocessOptionsCallback - Helper function passed to
2193 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
2194 class EmitPreprocessOptionsCallback : ActionHandlingCallbackBase {
2195 const OptionDescriptions& OptDescs_;
2197 void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
2198 const std::string& OptName = InitPtrToString(i);
2199 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
2201 if (OptDesc.isSwitch()) {
2202 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
2204 else if (OptDesc.isParameter()) {
2205 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
2207 else if (OptDesc.isList()) {
2208 O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
2211 throw "Can't apply 'unset_option' to alias option '" + OptName + "'";
2215 void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
2217 const DagInit& d = InitPtrToDag(I);
2218 const std::string& OpName = GetOperatorName(d);
2220 if (OpName == "warning") {
2221 this->onWarningDag(d, IndentLevel, O);
2223 else if (OpName == "error") {
2224 this->onWarningDag(d, IndentLevel, O);
2226 else if (OpName == "unset_option") {
2227 checkNumberOfArguments(&d, 1);
2228 Init* I = d.getArg(0);
2229 if (typeid(*I) == typeid(ListInit)) {
2230 const ListInit& DagList = *static_cast<const ListInit*>(I);
2231 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2233 this->onUnsetOption(*B, IndentLevel, O);
2236 this->onUnsetOption(I, IndentLevel, O);
2240 throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
2241 "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
2247 void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
2248 this->processDag(I, IndentLevel, O);
2251 EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2252 : OptDescs_(OptDescs)
2256 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2257 void EmitPreprocessOptions (const RecordKeeper& Records,
2258 const OptionDescriptions& OptDecs, raw_ostream& O)
2260 O << "void PreprocessOptionsLocal() {\n";
2262 const RecordVector& OptionPreprocessors =
2263 Records.getAllDerivedDefinitions("OptionPreprocessor");
2265 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2266 E = OptionPreprocessors.end(); B!=E; ++B) {
2267 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2268 EmitCaseConstructHandler(Case, Indent1,
2269 EmitPreprocessOptionsCallback(OptDecs),
2276 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2277 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2279 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2281 // Get the relevant field out of RecordKeeper
2282 const Record* LangMapRecord = Records.getDef("LanguageMap");
2284 // It is allowed for a plugin to have no language map.
2285 if (LangMapRecord) {
2287 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2288 if (!LangsToSuffixesList)
2289 throw std::string("Error in the language map definition!");
2291 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2292 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2294 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2295 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2297 for (unsigned i = 0; i < Suffixes->size(); ++i)
2298 O.indent(Indent1) << "langMap[\""
2299 << InitPtrToString(Suffixes->getElement(i))
2300 << "\"] = \"" << Lang << "\";\n";
2307 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2308 /// by EmitEdgeClass().
2309 void IncDecWeight (const Init* i, unsigned IndentLevel,
2311 const DagInit& d = InitPtrToDag(i);
2312 const std::string& OpName = GetOperatorName(d);
2314 if (OpName == "inc_weight") {
2315 O.indent(IndentLevel) << "ret += ";
2317 else if (OpName == "dec_weight") {
2318 O.indent(IndentLevel) << "ret -= ";
2320 else if (OpName == "error") {
2321 checkNumberOfArguments(&d, 1);
2322 O.indent(IndentLevel) << "throw std::runtime_error(\""
2323 << InitPtrToString(d.getArg(0))
2328 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2329 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2332 if (d.getNumArgs() > 0)
2333 O << InitPtrToInt(d.getArg(0)) << ";\n";
2339 /// EmitEdgeClass - Emit a single Edge# class.
2340 void EmitEdgeClass (unsigned N, const std::string& Target,
2341 DagInit* Case, const OptionDescriptions& OptDescs,
2344 // Class constructor.
2345 O << "class Edge" << N << ": public Edge {\n"
2347 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2350 // Function Weight().
2352 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2353 O.indent(Indent2) << "unsigned ret = 0;\n";
2355 // Handle the 'case' construct.
2356 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2358 O.indent(Indent2) << "return ret;\n";
2359 O.indent(Indent1) << "};\n\n};\n\n";
2362 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2363 void EmitEdgeClasses (const RecordVector& EdgeVector,
2364 const OptionDescriptions& OptDescs,
2367 for (RecordVector::const_iterator B = EdgeVector.begin(),
2368 E = EdgeVector.end(); B != E; ++B) {
2369 const Record* Edge = *B;
2370 const std::string& NodeB = Edge->getValueAsString("b");
2371 DagInit* Weight = Edge->getValueAsDag("weight");
2373 if (!isDagEmpty(Weight))
2374 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2379 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2381 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2382 const ToolDescriptions& ToolDescs,
2385 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2387 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2388 E = ToolDescs.end(); B != E; ++B)
2389 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2396 for (RecordVector::const_iterator B = EdgeVector.begin(),
2397 E = EdgeVector.end(); B != E; ++B) {
2398 const Record* Edge = *B;
2399 const std::string& NodeA = Edge->getValueAsString("a");
2400 const std::string& NodeB = Edge->getValueAsString("b");
2401 DagInit* Weight = Edge->getValueAsDag("weight");
2403 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2405 if (isDagEmpty(Weight))
2406 O << "new SimpleEdge(\"" << NodeB << "\")";
2408 O << "new Edge" << i << "()";
2417 /// ExtractHookNames - Extract the hook names from all instances of
2418 /// $CALL(HookName) in the provided command line string. Helper
2419 /// function used by FillInHookNames().
2420 class ExtractHookNames {
2421 llvm::StringMap<unsigned>& HookNames_;
2423 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
2424 : HookNames_(HookNames) {}
2426 void operator()(const Init* CmdLine) {
2429 // Ignore nested 'case' DAG.
2430 if (typeid(*CmdLine) == typeid(DagInit))
2433 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
2434 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2436 const std::string& cmd = *B;
2438 if (cmd == "$CALL") {
2439 unsigned NumArgs = 0;
2440 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2441 const std::string& HookName = *B;
2444 if (HookName.at(0) == ')')
2445 throw "$CALL invoked with no arguments!";
2447 while (++B != E && B->at(0) != ')') {
2451 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
2453 if (H != HookNames_.end() && H->second != NumArgs)
2454 throw "Overloading of hooks is not allowed. Overloaded hook: "
2457 HookNames_[HookName] = NumArgs;
2463 void operator()(const DagInit* Test, unsigned, bool) {
2464 this->operator()(Test);
2466 void operator()(const Init* Statement, unsigned) {
2467 this->operator()(Statement);
2471 /// FillInHookNames - Actually extract the hook names from all command
2472 /// line strings. Helper function used by EmitHookDeclarations().
2473 void FillInHookNames(const ToolDescriptions& ToolDescs,
2474 llvm::StringMap<unsigned>& HookNames)
2476 // For all command lines:
2477 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2478 E = ToolDescs.end(); B != E; ++B) {
2479 const ToolDescription& D = *(*B);
2482 if (dynamic_cast<StringInit*>(D.CmdLine))
2483 // This is a string.
2484 ExtractHookNames(HookNames).operator()(D.CmdLine);
2486 // This is a 'case' construct.
2487 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
2491 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2492 /// property records and emit hook function declaration for each
2493 /// instance of $CALL(HookName).
2494 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
2495 llvm::StringMap<unsigned> HookNames;
2497 FillInHookNames(ToolDescs, HookNames);
2498 if (HookNames.empty())
2501 O << "namespace hooks {\n";
2502 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
2503 E = HookNames.end(); B != E; ++B) {
2504 O.indent(Indent1) << "std::string " << B->first() << "(";
2506 for (unsigned i = 0, j = B->second; i < j; ++i) {
2507 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2515 /// EmitRegisterPlugin - Emit code to register this plugin.
2516 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2517 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2518 O.indent(Indent1) << "int Priority() const { return "
2519 << Priority << "; }\n\n";
2520 O.indent(Indent1) << "void PreprocessOptions() const\n";
2521 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2522 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2523 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2525 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2526 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2528 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2531 /// EmitIncludes - Emit necessary #include directives and some
2532 /// additional declarations.
2533 void EmitIncludes(raw_ostream& O) {
2534 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2535 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2536 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2537 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2538 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2540 << "#include \"llvm/ADT/StringExtras.h\"\n"
2541 << "#include \"llvm/Support/CommandLine.h\"\n"
2542 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2544 << "#include <cstdlib>\n"
2545 << "#include <stdexcept>\n\n"
2547 << "using namespace llvm;\n"
2548 << "using namespace llvmc;\n\n"
2550 << "extern cl::opt<std::string> OutputFilename;\n\n"
2552 << "inline const char* checkCString(const char* s)\n"
2553 << "{ return s == NULL ? \"\" : s; }\n\n";
2557 /// PluginData - Holds all information about a plugin.
2559 OptionDescriptions OptDescs;
2562 ToolDescriptions ToolDescs;
2567 /// HasSink - Go through the list of tool descriptions and check if
2568 /// there are any with the 'sink' property set.
2569 bool HasSink(const ToolDescriptions& ToolDescs) {
2570 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2571 E = ToolDescs.end(); B != E; ++B)
2578 /// HasExterns - Go through the list of option descriptions and check
2579 /// if there are any external options.
2580 bool HasExterns(const OptionDescriptions& OptDescs) {
2581 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2582 E = OptDescs.end(); B != E; ++B)
2583 if (B->second.isExtern())
2589 /// CollectPluginData - Collect tool and option properties,
2590 /// compilation graph edges and plugin priority from the parse tree.
2591 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2592 // Collect option properties.
2593 const RecordVector& OptionLists =
2594 Records.getAllDerivedDefinitions("OptionList");
2595 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2598 // Collect tool properties.
2599 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2600 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2601 Data.HasSink = HasSink(Data.ToolDescs);
2602 Data.HasExterns = HasExterns(Data.OptDescs);
2604 // Collect compilation graph edges.
2605 const RecordVector& CompilationGraphs =
2606 Records.getAllDerivedDefinitions("CompilationGraph");
2607 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2610 // Calculate the priority of this plugin.
2611 const RecordVector& Priorities =
2612 Records.getAllDerivedDefinitions("PluginPriority");
2613 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2616 /// CheckPluginData - Perform some sanity checks on the collected data.
2617 void CheckPluginData(PluginData& Data) {
2618 // Filter out all tools not mentioned in the compilation graph.
2619 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2621 // Typecheck the compilation graph.
2622 TypecheckGraph(Data.Edges, Data.ToolDescs);
2624 // Check that there are no options without side effects (specified
2625 // only in the OptionList).
2626 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2630 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2631 // Emit file header.
2634 // Emit global option registration code.
2635 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2637 // Emit hook declarations.
2638 EmitHookDeclarations(Data.ToolDescs, O);
2640 O << "namespace {\n\n";
2642 // Emit PreprocessOptionsLocal() function.
2643 EmitPreprocessOptions(Records, Data.OptDescs, O);
2645 // Emit PopulateLanguageMapLocal() function
2646 // (language map maps from file extensions to language names).
2647 EmitPopulateLanguageMap(Records, O);
2649 // Emit Tool classes.
2650 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2651 E = Data.ToolDescs.end(); B!=E; ++B)
2652 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2654 // Emit Edge# classes.
2655 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2657 // Emit PopulateCompilationGraphLocal() function.
2658 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2660 // Emit code for plugin registration.
2661 EmitRegisterPlugin(Data.Priority, O);
2663 O << "} // End anonymous namespace.\n\n";
2665 // Force linkage magic.
2666 O << "namespace llvmc {\n";
2667 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2674 // End of anonymous namespace
2677 /// run - The back-end entry point.
2678 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2682 CollectPluginData(Records, Data);
2683 CheckPluginData(Data);
2685 EmitSourceFileHeader("LLVMC Configuration Library", O);
2686 EmitPluginCode(Data, O);
2688 } catch (std::exception& Error) {
2689 throw Error.what() + std::string(" - usually this means a syntax error.");