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"
22 #include "llvm/Support/Streams.h"
34 //===----------------------------------------------------------------------===//
37 typedef std::vector<Record*> RecordVector;
38 typedef std::vector<std::string> StrVector;
40 //===----------------------------------------------------------------------===//
43 // Indentation strings.
44 const char * Indent1 = " ";
45 const char * Indent2 = " ";
46 const char * Indent3 = " ";
47 const char * Indent4 = " ";
49 // Default help string.
50 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
52 // Name for the "sink" option.
53 const char * SinkOptionName = "AutoGeneratedSinkOption";
55 //===----------------------------------------------------------------------===//
58 int InitPtrToInt(const Init* ptr) {
59 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
60 return val.getValue();
63 const std::string& InitPtrToString(const Init* ptr) {
64 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
65 return val.getValue();
68 const ListInit& InitPtrToList(const Init* ptr) {
69 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
73 const DagInit& InitPtrToDag(const Init* ptr) {
74 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
78 // checkNumberOfArguments - Ensure that the number of args in d is
79 // less than or equal to min_arguments, otherwise throw an exception.
80 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
81 if (d->getNumArgs() < min_arguments)
82 throw "Property " + d->getOperator()->getAsString()
83 + " has too few arguments!";
86 // isDagEmpty - is this DAG marked with an empty marker?
87 bool isDagEmpty (const DagInit* d) {
88 return d->getOperator()->getAsString() == "empty";
91 //===----------------------------------------------------------------------===//
92 /// Back-end specific code
94 // A command-line option can have one of the following types:
96 // Alias - an alias for another option.
98 // Switch - a simple switch without arguments, e.g. -O2
100 // Parameter - an option that takes one(and only one) argument, e.g. -o file,
103 // ParameterList - same as Parameter, but more than one occurence
104 // of the option is allowed, e.g. -lm -lpthread
106 // Prefix - argument is everything after the prefix,
107 // e.g. -Wa,-foo,-bar, -DNAME=VALUE
109 // PrefixList - same as Prefix, but more than one option occurence is
112 namespace OptionType {
113 enum OptionType { Alias, Switch,
114 Parameter, ParameterList, Prefix, PrefixList};
117 bool IsListOptionType (OptionType::OptionType t) {
118 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
121 // Code duplication here is necessary because one option can affect
122 // several tools and those tools may have different actions associated
123 // with this option. GlobalOptionDescriptions are used to generate
124 // the option registration code, while ToolOptionDescriptions are used
125 // to generate tool-specific code.
127 /// OptionDescription - Base class for option descriptions.
128 struct OptionDescription {
129 OptionType::OptionType Type;
132 OptionDescription(OptionType::OptionType t = OptionType::Switch,
133 const std::string& n = "")
137 const char* GenTypeDeclaration() const {
139 case OptionType::Alias:
141 case OptionType::PrefixList:
142 case OptionType::ParameterList:
143 return "cl::list<std::string>";
144 case OptionType::Switch:
145 return "cl::opt<bool>";
146 case OptionType::Parameter:
147 case OptionType::Prefix:
149 return "cl::opt<std::string>";
153 // Escape commas and other symbols not allowed in the C++ variable
154 // names. Makes it possible to use options with names like "Wa,"
155 // (useful for prefix options).
156 std::string EscapeVariableName(const std::string& Var) const {
158 for (unsigned i = 0; i != Var.size(); ++i) {
163 ret.push_back(Var[i]);
169 std::string GenVariableName() const {
170 const std::string& EscapedName = EscapeVariableName(Name);
172 case OptionType::Alias:
173 return "AutoGeneratedAlias" + EscapedName;
174 case OptionType::Switch:
175 return "AutoGeneratedSwitch" + EscapedName;
176 case OptionType::Prefix:
177 return "AutoGeneratedPrefix" + EscapedName;
178 case OptionType::PrefixList:
179 return "AutoGeneratedPrefixList" + EscapedName;
180 case OptionType::Parameter:
181 return "AutoGeneratedParameter" + EscapedName;
182 case OptionType::ParameterList:
184 return "AutoGeneratedParameterList" + EscapedName;
190 // Global option description.
192 namespace GlobalOptionDescriptionFlags {
193 enum GlobalOptionDescriptionFlags { Required = 0x1 };
196 struct GlobalOptionDescription : public OptionDescription {
200 // We need to provide a default constructor because
201 // StringMap can only store DefaultConstructible objects.
202 GlobalOptionDescription() : OptionDescription(), Flags(0)
205 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
206 const std::string& h = DefaultHelpString)
207 : OptionDescription(t, n), Help(h), Flags(0)
210 bool isRequired() const {
211 return Flags & GlobalOptionDescriptionFlags::Required;
214 Flags |= GlobalOptionDescriptionFlags::Required;
217 /// Merge - Merge two option descriptions.
218 void Merge (const GlobalOptionDescription& other)
220 if (other.Type != Type)
221 throw "Conflicting definitions for the option " + Name + "!";
223 if (Help == DefaultHelpString)
225 else if (other.Help != DefaultHelpString) {
226 llvm::cerr << "Warning: more than one help string defined for option "
230 Flags |= other.Flags;
234 /// GlobalOptionDescriptions - A GlobalOptionDescription array
235 /// together with some flags affecting generation of option
237 struct GlobalOptionDescriptions {
238 typedef StringMap<GlobalOptionDescription> container_type;
239 typedef container_type::const_iterator const_iterator;
241 /// Descriptions - A list of GlobalOptionDescriptions.
242 container_type Descriptions;
243 /// HasSink - Should the emitter generate a "cl::sink" option?
246 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
247 const_iterator I = Descriptions.find(OptName);
248 if (I != Descriptions.end())
251 throw OptName + ": no such option!";
254 // Support for STL-style iteration
255 const_iterator begin() const { return Descriptions.begin(); }
256 const_iterator end() const { return Descriptions.end(); }
260 // Tool-local option description.
262 // Properties without arguments are implemented as flags.
263 namespace ToolOptionDescriptionFlags {
264 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
265 Forward = 0x2, UnpackValues = 0x4};
267 namespace OptionPropertyType {
268 enum OptionPropertyType { AppendCmd, OutputSuffix };
271 typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
273 typedef SmallVector<OptionProperty, 4> OptionPropertyList;
275 struct ToolOptionDescription : public OptionDescription {
277 OptionPropertyList Props;
279 // StringMap can only store DefaultConstructible objects
280 ToolOptionDescription() : OptionDescription(), Flags(0) {}
282 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
283 : OptionDescription(t, n)
286 // Various boolean properties
287 bool isStopCompilation() const {
288 return Flags & ToolOptionDescriptionFlags::StopCompilation;
290 void setStopCompilation() {
291 Flags |= ToolOptionDescriptionFlags::StopCompilation;
294 bool isForward() const {
295 return Flags & ToolOptionDescriptionFlags::Forward;
298 Flags |= ToolOptionDescriptionFlags::Forward;
301 bool isUnpackValues() const {
302 return Flags & ToolOptionDescriptionFlags::UnpackValues;
304 void setUnpackValues() {
305 Flags |= ToolOptionDescriptionFlags::UnpackValues;
308 void AddProperty (OptionPropertyType::OptionPropertyType t,
309 const std::string& val)
311 Props.push_back(std::make_pair(t, val));
315 typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
317 // Tool information record
319 namespace ToolFlags {
320 enum ToolFlags { Join = 0x1, Sink = 0x2 };
323 struct ToolProperties : public RefCountedBase<ToolProperties> {
326 StrVector InLanguage;
327 std::string OutLanguage;
328 std::string OutputSuffix;
330 ToolOptionDescriptions OptDescs;
332 // Various boolean properties
333 void setSink() { Flags |= ToolFlags::Sink; }
334 bool isSink() const { return Flags & ToolFlags::Sink; }
335 void setJoin() { Flags |= ToolFlags::Join; }
336 bool isJoin() const { return Flags & ToolFlags::Join; }
338 // Default ctor here is needed because StringMap can only store
339 // DefaultConstructible objects
340 ToolProperties() : Flags(0) {}
341 ToolProperties (const std::string& n) : Name(n), Flags(0) {}
345 /// ToolPropertiesList - A list of Tool information records
346 /// IntrusiveRefCntPtrs are used here because StringMap has no copy
347 /// constructor (and we want to avoid copying ToolProperties anyway).
348 typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
351 /// CollectProperties - Function object for iterating over a list of
352 /// tool property records.
353 class CollectProperties {
356 /// Implementation details
358 /// PropertyHandler - a function that extracts information
359 /// about a given tool property from its DAG representation
360 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
362 /// PropertyHandlerMap - A map from property names to property
364 typedef StringMap<PropertyHandler> PropertyHandlerMap;
366 /// OptionPropertyHandler - a function that extracts information
367 /// about a given option property from its DAG representation.
368 typedef void (CollectProperties::* OptionPropertyHandler)
369 (const DagInit*, GlobalOptionDescription &);
371 /// OptionPropertyHandlerMap - A map from option property names to
372 /// option property handlers
373 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
375 // Static maps from strings to CollectProperties methods("handlers")
376 static PropertyHandlerMap propertyHandlers_;
377 static OptionPropertyHandlerMap optionPropertyHandlers_;
378 static bool staticMembersInitialized_;
381 /// This is where the information is stored
383 /// toolProps_ - Properties of the current Tool.
384 ToolProperties& toolProps_;
385 /// optDescs_ - OptionDescriptions table (used to register options
387 GlobalOptionDescriptions& optDescs_;
391 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
392 : toolProps_(p), optDescs_(d)
394 if (!staticMembersInitialized_) {
395 // Init tool property handlers
396 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
397 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
398 propertyHandlers_["join"] = &CollectProperties::onJoin;
399 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
400 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
401 propertyHandlers_["parameter_option"]
402 = &CollectProperties::onParameter;
403 propertyHandlers_["parameter_list_option"] =
404 &CollectProperties::onParameterList;
405 propertyHandlers_["prefix_option"] = &CollectProperties::onPrefix;
406 propertyHandlers_["prefix_list_option"] =
407 &CollectProperties::onPrefixList;
408 propertyHandlers_["sink"] = &CollectProperties::onSink;
409 propertyHandlers_["switch_option"] = &CollectProperties::onSwitch;
410 propertyHandlers_["alias_option"] = &CollectProperties::onAlias;
412 // Init option property handlers
413 optionPropertyHandlers_["append_cmd"] = &CollectProperties::onAppendCmd;
414 optionPropertyHandlers_["forward"] = &CollectProperties::onForward;
415 optionPropertyHandlers_["help"] = &CollectProperties::onHelp;
416 optionPropertyHandlers_["output_suffix"] =
417 &CollectProperties::onOutputSuffixOptionProp;
418 optionPropertyHandlers_["required"] = &CollectProperties::onRequired;
419 optionPropertyHandlers_["stop_compilation"] =
420 &CollectProperties::onStopCompilation;
421 optionPropertyHandlers_["unpack_values"] =
422 &CollectProperties::onUnpackValues;
424 staticMembersInitialized_ = true;
428 /// operator() - Gets called for every tool property; Just forwards
429 /// to the corresponding property handler.
430 void operator() (Init* i) {
431 const DagInit& d = InitPtrToDag(i);
432 const std::string& property_name = d.getOperator()->getAsString();
433 PropertyHandlerMap::iterator method
434 = propertyHandlers_.find(property_name);
436 if (method != propertyHandlers_.end()) {
437 PropertyHandler h = method->second;
441 throw "Unknown tool property: " + property_name + "!";
447 /// Property handlers --
448 /// Functions that extract information about tool properties from
449 /// DAG representation.
451 void onCmdLine (const DagInit* d) {
452 checkNumberOfArguments(d, 1);
453 toolProps_.CmdLine = d->getArg(0);
456 void onInLanguage (const DagInit* d) {
457 checkNumberOfArguments(d, 1);
458 Init* arg = d->getArg(0);
460 // Find out the argument's type.
461 if (typeid(*arg) == typeid(StringInit)) {
463 toolProps_.InLanguage.push_back(InitPtrToString(arg));
467 const ListInit& lst = InitPtrToList(arg);
468 StrVector& out = toolProps_.InLanguage;
470 // Copy strings to the output vector.
471 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
473 out.push_back(InitPtrToString(*B));
476 // Remove duplicates.
477 std::sort(out.begin(), out.end());
478 StrVector::iterator newE = std::unique(out.begin(), out.end());
479 out.erase(newE, out.end());
483 void onJoin (const DagInit* d) {
484 checkNumberOfArguments(d, 0);
485 toolProps_.setJoin();
488 void onOutLanguage (const DagInit* d) {
489 checkNumberOfArguments(d, 1);
490 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
493 void onOutputSuffix (const DagInit* d) {
494 checkNumberOfArguments(d, 1);
495 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
498 void onSink (const DagInit* d) {
499 checkNumberOfArguments(d, 0);
500 optDescs_.HasSink = true;
501 toolProps_.setSink();
504 void onAlias (const DagInit* d) {
505 checkNumberOfArguments(d, 2);
506 // We just need a GlobalOptionDescription for the aliases.
508 (GlobalOptionDescription(OptionType::Alias,
509 InitPtrToString(d->getArg(0)),
510 InitPtrToString(d->getArg(1))));
513 void onSwitch (const DagInit* d) {
514 addOption(d, OptionType::Switch);
517 void onParameter (const DagInit* d) {
518 addOption(d, OptionType::Parameter);
521 void onParameterList (const DagInit* d) {
522 addOption(d, OptionType::ParameterList);
525 void onPrefix (const DagInit* d) {
526 addOption(d, OptionType::Prefix);
529 void onPrefixList (const DagInit* d) {
530 addOption(d, OptionType::PrefixList);
533 /// Option property handlers --
534 /// Methods that handle properties that are common for all types of
535 /// options (like append_cmd, stop_compilation)
537 void onAppendCmd (const DagInit* d, GlobalOptionDescription& o) {
538 checkNumberOfArguments(d, 1);
539 const std::string& cmd = InitPtrToString(d->getArg(0));
541 toolProps_.OptDescs[o.Name].AddProperty(OptionPropertyType::AppendCmd, cmd);
544 void onOutputSuffixOptionProp (const DagInit* d, GlobalOptionDescription& o) {
545 checkNumberOfArguments(d, 1);
546 const std::string& suf = InitPtrToString(d->getArg(0));
548 if (toolProps_.OptDescs[o.Name].Type != OptionType::Switch)
549 throw "Option " + o.Name
550 + " can't have 'output_suffix' property since it isn't a switch!";
552 toolProps_.OptDescs[o.Name].AddProperty
553 (OptionPropertyType::OutputSuffix, suf);
556 void onForward (const DagInit* d, GlobalOptionDescription& o) {
557 checkNumberOfArguments(d, 0);
558 toolProps_.OptDescs[o.Name].setForward();
561 void onHelp (const DagInit* d, GlobalOptionDescription& o) {
562 checkNumberOfArguments(d, 1);
563 const std::string& help_message = InitPtrToString(d->getArg(0));
565 o.Help = help_message;
568 void onRequired (const DagInit* d, GlobalOptionDescription& o) {
569 checkNumberOfArguments(d, 0);
573 void onStopCompilation (const DagInit* d, GlobalOptionDescription& o) {
574 checkNumberOfArguments(d, 0);
575 if (o.Type != OptionType::Switch)
576 throw std::string("Only options of type Switch can stop compilation!");
577 toolProps_.OptDescs[o.Name].setStopCompilation();
580 void onUnpackValues (const DagInit* d, GlobalOptionDescription& o) {
581 checkNumberOfArguments(d, 0);
582 toolProps_.OptDescs[o.Name].setUnpackValues();
587 // Add an option of type t
588 void addOption (const DagInit* d, OptionType::OptionType t) {
589 checkNumberOfArguments(d, 2);
590 const std::string& name = InitPtrToString(d->getArg(0));
592 GlobalOptionDescription o(t, name);
593 toolProps_.OptDescs[name].Type = t;
594 toolProps_.OptDescs[name].Name = name;
595 processOptionProperties(d, o);
596 insertDescription(o);
599 // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
600 void insertDescription (const GlobalOptionDescription& o)
602 if (optDescs_.Descriptions.count(o.Name)) {
603 GlobalOptionDescription& D = optDescs_.Descriptions[o.Name];
607 optDescs_.Descriptions[o.Name] = o;
611 /// processOptionProperties - Go through the list of option
612 /// properties and call a corresponding handler for each.
615 /// name - option name
616 /// d - option property list
617 void processOptionProperties (const DagInit* d, GlobalOptionDescription& o) {
618 // First argument is option name
619 checkNumberOfArguments(d, 2);
621 for (unsigned B = 1, E = d->getNumArgs(); B!=E; ++B) {
622 const DagInit& option_property
623 = InitPtrToDag(d->getArg(B));
624 const std::string& option_property_name
625 = option_property.getOperator()->getAsString();
626 OptionPropertyHandlerMap::iterator method
627 = optionPropertyHandlers_.find(option_property_name);
629 if (method != optionPropertyHandlers_.end()) {
630 OptionPropertyHandler h = method->second;
631 (this->*h)(&option_property, o);
634 throw "Unknown option property: " + option_property_name + "!";
640 // Static members of CollectProperties
641 CollectProperties::PropertyHandlerMap
642 CollectProperties::propertyHandlers_;
644 CollectProperties::OptionPropertyHandlerMap
645 CollectProperties::optionPropertyHandlers_;
647 bool CollectProperties::staticMembersInitialized_ = false;
650 /// CollectToolProperties - Gather information from the parsed
651 /// TableGen data (basically a wrapper for the CollectProperties
652 /// function object).
653 void CollectToolProperties (RecordVector::const_iterator B,
654 RecordVector::const_iterator E,
655 ToolPropertiesList& TPList,
656 GlobalOptionDescriptions& OptDescs)
658 // Iterate over a properties list of every Tool definition
660 RecordVector::value_type T = *B;
661 ListInit* PropList = T->getValueAsListInit("properties");
663 IntrusiveRefCntPtr<ToolProperties>
664 ToolProps(new ToolProperties(T->getName()));
666 std::for_each(PropList->begin(), PropList->end(),
667 CollectProperties(*ToolProps, OptDescs));
668 TPList.push_back(ToolProps);
672 /// EmitCaseTest1Arg - Helper function used by
673 /// EmitCaseConstructHandler.
674 bool EmitCaseTest1Arg(const std::string& TestName,
676 const GlobalOptionDescriptions& OptDescs,
678 checkNumberOfArguments(&d, 1);
679 const std::string& OptName = InitPtrToString(d.getArg(0));
680 if (TestName == "switch_on") {
681 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
682 if (OptDesc.Type != OptionType::Switch)
683 throw OptName + ": incorrect option type!";
684 O << OptDesc.GenVariableName();
686 } else if (TestName == "input_languages_contain") {
687 O << "InLangs.count(\"" << OptName << "\") != 0";
689 } else if (TestName == "in_language") {
690 // Works only for cmd_line!
691 O << "GetLanguage(inFile) == \"" << OptName << '\"';
693 } else if (TestName == "not_empty") {
694 if (OptName == "o") {
695 O << "!OutputFilename.empty()";
699 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
700 if (OptDesc.Type == OptionType::Switch)
701 throw OptName + ": incorrect option type!";
702 O << '!' << OptDesc.GenVariableName() << ".empty()";
710 /// EmitCaseTest2Args - Helper function used by
711 /// EmitCaseConstructHandler.
712 bool EmitCaseTest2Args(const std::string& TestName,
714 const char* IndentLevel,
715 const GlobalOptionDescriptions& OptDescs,
717 checkNumberOfArguments(&d, 2);
718 const std::string& OptName = InitPtrToString(d.getArg(0));
719 const std::string& OptArg = InitPtrToString(d.getArg(1));
720 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
722 if (TestName == "parameter_equals") {
723 if (OptDesc.Type != OptionType::Parameter
724 && OptDesc.Type != OptionType::Prefix)
725 throw OptName + ": incorrect option type!";
726 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
729 else if (TestName == "element_in_list") {
730 if (OptDesc.Type != OptionType::ParameterList
731 && OptDesc.Type != OptionType::PrefixList)
732 throw OptName + ": incorrect option type!";
733 const std::string& VarName = OptDesc.GenVariableName();
734 O << "std::find(" << VarName << ".begin(),\n"
735 << IndentLevel << Indent1 << VarName << ".end(), \""
736 << OptArg << "\") != " << VarName << ".end()";
743 // Forward declaration.
744 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
745 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
746 const GlobalOptionDescriptions& OptDescs,
749 /// EmitLogicalOperationTest - Helper function used by
750 /// EmitCaseConstructHandler.
751 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
752 const char* IndentLevel,
753 const GlobalOptionDescriptions& OptDescs,
756 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
757 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
758 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
759 if (j != NumArgs - 1)
760 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
766 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
767 void EmitCaseTest(const DagInit& d, const char* IndentLevel,
768 const GlobalOptionDescriptions& OptDescs,
770 const std::string& TestName = d.getOperator()->getAsString();
772 if (TestName == "and")
773 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
774 else if (TestName == "or")
775 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
776 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
778 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
781 throw TestName + ": unknown edge property!";
784 // Emit code that handles the 'case' construct.
785 // Takes a function object that should emit code for every case clause.
786 // Callback's type is
787 // void F(Init* Statement, const char* IndentLevel, std::ostream& O).
788 template <typename F>
789 void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
790 const F& Callback, bool EmitElseIf,
791 const GlobalOptionDescriptions& OptDescs,
793 assert(d->getOperator()->getAsString() == "case");
795 unsigned numArgs = d->getNumArgs();
796 if (d->getNumArgs() < 2)
797 throw "There should be at least one clause in the 'case' expression:\n"
800 for (unsigned i = 0; i != numArgs; ++i) {
801 const DagInit& Test = InitPtrToDag(d->getArg(i));
804 if (Test.getOperator()->getAsString() == "default") {
806 throw std::string("The 'default' clause should be the last in the"
807 "'case' construct!");
808 O << IndentLevel << "else {\n";
811 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
812 EmitCaseTest(Test, IndentLevel, OptDescs, O);
816 // Emit the corresponding statement.
819 throw "Case construct handler: no corresponding action "
820 "found for the test " + Test.getAsString() + '!';
822 Init* arg = d->getArg(i);
823 if (dynamic_cast<DagInit*>(arg)
824 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
825 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
826 (std::string(IndentLevel) + Indent1).c_str(),
827 Callback, EmitElseIf, OptDescs, O);
830 Callback(arg, IndentLevel, O);
832 O << IndentLevel << "}\n";
836 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
837 /// implement EmitOptionPropertyHandlingCode(). Emits code for
838 /// handling the (forward) option property.
839 void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
842 case OptionType::Switch:
843 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
845 case OptionType::Parameter:
846 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
847 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
849 case OptionType::Prefix:
850 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
851 << D.GenVariableName() << ");\n";
853 case OptionType::PrefixList:
854 O << Indent3 << "for (" << D.GenTypeDeclaration()
855 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
856 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
857 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
860 case OptionType::ParameterList:
861 O << Indent3 << "for (" << D.GenTypeDeclaration()
862 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
863 << Indent3 << "E = " << D.GenVariableName()
864 << ".end() ; B != E; ++B) {\n"
865 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
866 << Indent4 << "vec.push_back(*B);\n"
869 case OptionType::Alias:
871 throw std::string("Aliases are not allowed in tool option descriptions!");
875 // ToolOptionHasInterestingProperties - A helper function used by
876 // EmitOptionPropertyHandlingCode() that tells us whether we should
877 // emit any property handling code at all.
878 bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
880 for (OptionPropertyList::const_iterator B = D.Props.begin(),
881 E = D.Props.end(); B != E; ++B) {
882 const OptionProperty& OptProp = *B;
883 if (OptProp.first == OptionPropertyType::AppendCmd)
886 if (D.isForward() || D.isUnpackValues())
891 /// EmitOptionPropertyHandlingCode - Helper function used by
892 /// EmitGenerateActionMethod(). Emits code that handles option
894 void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
897 if (!ToolOptionHasInterestingProperties(D))
899 // Start of the if-clause.
900 O << Indent2 << "if (";
901 if (D.Type == OptionType::Switch)
902 O << D.GenVariableName();
904 O << '!' << D.GenVariableName() << ".empty()";
908 // Handle option properties that take an argument.
909 for (OptionPropertyList::const_iterator B = D.Props.begin(),
910 E = D.Props.end(); B!=E; ++B) {
911 const OptionProperty& val = *B;
914 // (append_cmd cmd) property
915 case OptionPropertyType::AppendCmd:
916 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
918 // Other properties with argument
926 // (forward) property
928 EmitForwardOptionPropertyHandlingCode(D, O);
930 // (unpack_values) property
931 if (D.isUnpackValues()) {
932 if (IsListOptionType(D.Type)) {
933 O << Indent3 << "for (" << D.GenTypeDeclaration()
934 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
935 << Indent3 << "E = " << D.GenVariableName()
936 << ".end(); B != E; ++B)\n"
937 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
939 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
940 O << Indent3 << "llvm::SplitString("
941 << D.GenVariableName() << ", vec, \",\");\n";
944 throw std::string("Switches can't have unpack_values property!");
948 // End of the if-clause.
949 O << Indent2 << "}\n";
952 /// SubstituteSpecialCommands - Perform string substitution for $CALL
953 /// and $ENV. Helper function used by EmitCmdLineVecFill().
954 std::string SubstituteSpecialCommands(const std::string& cmd) {
955 size_t cparen = cmd.find(")");
958 if (cmd.find("$CALL(") == 0) {
960 throw std::string("$CALL invocation: empty argument list!");
963 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
966 else if (cmd.find("$ENV(") == 0) {
968 throw std::string("$ENV invocation: empty argument list!");
970 ret += "std::getenv(\"";
971 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
975 throw "Unknown special command: " + cmd;
978 if (cmd.begin() + cparen + 1 != cmd.end()) {
979 ret += " + std::string(\"";
980 ret += (cmd.c_str() + cparen + 1);
987 /// EmitCmdLineVecFill - Emit code that fills in the command line
988 /// vector. Helper function used by EmitGenerateActionMethod().
989 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
990 bool Version, const char* IndentLevel,
993 SplitString(InitPtrToString(CmdLine), StrVec);
995 throw "Tool " + ToolName + " has empty command line!";
997 StrVector::const_iterator I = StrVec.begin();
999 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
1000 const std::string& cmd = *I;
1002 if (cmd.at(0) == '$') {
1003 if (cmd == "$INFILE") {
1005 O << "for (PathVector::const_iterator B = inFiles.begin()"
1006 << ", E = inFiles.end();\n"
1007 << IndentLevel << "B != E; ++B)\n"
1008 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1010 O << "vec.push_back(inFile.toString());\n";
1012 else if (cmd == "$OUTFILE") {
1013 O << "vec.push_back(outFile.toString());\n";
1016 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1021 O << "vec.push_back(\"" << cmd << "\");\n";
1024 O << IndentLevel << "cmd = "
1025 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1026 : "\"" + StrVec[0] + "\"")
1030 /// EmitCmdLineVecFillCallback - A function object wrapper around
1031 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1032 /// argument to EmitCaseConstructHandler().
1033 class EmitCmdLineVecFillCallback {
1035 const std::string& ToolName;
1037 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1038 : Version(Ver), ToolName(TN) {}
1040 void operator()(const Init* Statement, const char* IndentLevel,
1041 std::ostream& O) const
1043 EmitCmdLineVecFill(Statement, ToolName, Version,
1044 (std::string(IndentLevel) + Indent1).c_str(), O);
1048 // EmitGenerateActionMethod - Emit one of two versions of the
1049 // Tool::GenerateAction() method.
1050 void EmitGenerateActionMethod (const ToolProperties& P,
1051 const GlobalOptionDescriptions& OptDescs,
1052 bool Version, std::ostream& O) {
1054 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1056 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1058 O << Indent2 << "const sys::Path& outFile,\n"
1059 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1061 << Indent2 << "std::string cmd;\n"
1062 << Indent2 << "std::vector<std::string> vec;\n";
1064 // cmd_line is either a string or a 'case' construct.
1065 if (typeid(*P.CmdLine) == typeid(StringInit))
1066 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1068 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
1069 EmitCmdLineVecFillCallback(Version, P.Name),
1072 // For every understood option, emit handling code.
1073 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1074 E = P.OptDescs.end(); B != E; ++B) {
1075 const ToolOptionDescription& val = B->second;
1076 EmitOptionPropertyHandlingCode(val, O);
1079 // Handle the Sink property.
1081 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1082 << Indent3 << "vec.insert(vec.end(), "
1083 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1084 << Indent2 << "}\n";
1087 O << Indent2 << "return Action(cmd, vec);\n"
1088 << Indent1 << "}\n\n";
1091 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1092 /// a given Tool class.
1093 void EmitGenerateActionMethods (const ToolProperties& P,
1094 const GlobalOptionDescriptions& OptDescs,
1097 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
1098 << Indent2 << "const llvm::sys::Path& outFile,\n"
1099 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1101 << Indent2 << "throw std::runtime_error(\"" << P.Name
1102 << " is not a Join tool!\");\n"
1103 << Indent1 << "}\n\n";
1105 EmitGenerateActionMethod(P, OptDescs, true, O);
1107 EmitGenerateActionMethod(P, OptDescs, false, O);
1110 /// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1112 void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1113 O << Indent1 << "bool IsLast() const {\n"
1114 << Indent2 << "bool last = false;\n";
1116 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1117 E = P.OptDescs.end(); B != E; ++B) {
1118 const ToolOptionDescription& val = B->second;
1120 if (val.isStopCompilation())
1122 << "if (" << val.GenVariableName()
1123 << ")\n" << Indent3 << "last = true;\n";
1126 O << Indent2 << "return last;\n"
1127 << Indent1 << "}\n\n";
1130 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1131 /// methods for a given Tool class.
1132 void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
1133 O << Indent1 << "StrVector InputLanguages() const {\n"
1134 << Indent2 << "StrVector ret;\n";
1136 for (StrVector::const_iterator B = P.InLanguage.begin(),
1137 E = P.InLanguage.end(); B != E; ++B) {
1138 O << Indent2 << "ret.push_back(\"" << *B << "\");\n";
1141 O << Indent2 << "return ret;\n"
1142 << Indent1 << "}\n\n";
1144 O << Indent1 << "const char* OutputLanguage() const {\n"
1145 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1146 << Indent1 << "}\n\n";
1149 /// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1150 /// given Tool class.
1151 void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
1152 O << Indent1 << "const char* OutputSuffix() const {\n"
1153 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1155 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1156 E = P.OptDescs.end(); B != E; ++B) {
1157 const ToolOptionDescription& OptDesc = B->second;
1158 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1159 E = OptDesc.Props.end(); B != E; ++B) {
1160 const OptionProperty& OptProp = *B;
1161 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1162 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1163 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1168 O << Indent2 << "return ret;\n"
1169 << Indent1 << "}\n\n";
1172 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1173 void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
1174 O << Indent1 << "const char* Name() const {\n"
1175 << Indent2 << "return \"" << P.Name << "\";\n"
1176 << Indent1 << "}\n\n";
1179 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1181 void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1182 O << Indent1 << "bool IsJoin() const {\n";
1184 O << Indent2 << "return true;\n";
1186 O << Indent2 << "return false;\n";
1187 O << Indent1 << "}\n\n";
1190 /// EmitToolClassDefinition - Emit a Tool class definition.
1191 void EmitToolClassDefinition (const ToolProperties& P,
1192 const GlobalOptionDescriptions& OptDescs,
1194 if (P.Name == "root")
1198 O << "class " << P.Name << " : public ";
1203 O << " {\npublic:\n";
1205 EmitNameMethod(P, O);
1206 EmitInOutLanguageMethods(P, O);
1207 EmitOutputSuffixMethod(P, O);
1208 EmitIsJoinMethod(P, O);
1209 EmitGenerateActionMethods(P, OptDescs, O);
1210 EmitIsLastMethod(P, O);
1212 // Close class definition
1216 /// EmitOptionDescriptions - Iterate over a list of option
1217 /// descriptions and emit registration code.
1218 void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1221 std::vector<GlobalOptionDescription> Aliases;
1223 // Emit static cl::Option variables.
1224 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1225 E = descs.end(); B!=E; ++B) {
1226 const GlobalOptionDescription& val = B->second;
1228 if (val.Type == OptionType::Alias) {
1229 Aliases.push_back(val);
1233 O << val.GenTypeDeclaration() << ' '
1234 << val.GenVariableName()
1235 << "(\"" << val.Name << '\"';
1237 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1238 O << ", cl::Prefix";
1240 if (val.isRequired()) {
1242 case OptionType::PrefixList:
1243 case OptionType::ParameterList:
1244 O << ", cl::OneOrMore";
1247 O << ", cl::Required";
1251 if (!val.Help.empty())
1252 O << ", cl::desc(\"" << val.Help << "\")";
1257 // Emit the aliases (they should go after all the 'proper' options).
1258 for (std::vector<GlobalOptionDescription>::const_iterator
1259 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1260 const GlobalOptionDescription& val = *B;
1262 O << val.GenTypeDeclaration() << ' '
1263 << val.GenVariableName()
1264 << "(\"" << val.Name << '\"';
1266 GlobalOptionDescriptions::container_type
1267 ::const_iterator F = descs.Descriptions.find(val.Help);
1268 if (F != descs.Descriptions.end())
1269 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1271 throw val.Name + ": alias to an unknown option!";
1273 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1276 // Emit the sink option.
1278 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1283 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
1284 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1286 // Get the relevant field out of RecordKeeper
1287 Record* LangMapRecord = Records.getDef("LanguageMap");
1289 throw std::string("Language map definition not found!");
1291 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1292 if (!LangsToSuffixesList)
1293 throw std::string("Error in the language map definition!");
1296 O << "void llvmc::PopulateLanguageMap() {\n";
1298 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1299 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1301 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1302 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1304 for (unsigned i = 0; i < Suffixes->size(); ++i)
1305 O << Indent1 << "GlobalLanguageMap[\""
1306 << InitPtrToString(Suffixes->getElement(i))
1307 << "\"] = \"" << Lang << "\";\n";
1313 /// FillInToolToLang - Fills in two tables that map tool names to
1314 /// (input, output) languages. Used by the typechecker.
1315 void FillInToolToLang (const ToolPropertiesList& TPList,
1316 StringMap<StringSet<> >& ToolToInLang,
1317 StringMap<std::string>& ToolToOutLang) {
1318 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1320 const ToolProperties& P = *(*B);
1321 for (StrVector::const_iterator B = P.InLanguage.begin(),
1322 E = P.InLanguage.end(); B != E; ++B)
1323 ToolToInLang[P.Name].insert(*B);
1324 ToolToOutLang[P.Name] = P.OutLanguage;
1328 /// TypecheckGraph - Check that names for output and input languages
1329 /// on all edges do match.
1330 // TOFIX: It would be nice if this function also checked for cycles
1331 // and multiple default edges in the graph (better error
1332 // reporting). Unfortunately, it is awkward to do right now because
1333 // our intermediate representation is not sufficiently
1334 // sofisticated. Algorithms like these should be run on a real graph
1336 void TypecheckGraph (Record* CompilationGraph,
1337 const ToolPropertiesList& TPList) {
1338 StringMap<StringSet<> > ToolToInLang;
1339 StringMap<std::string> ToolToOutLang;
1341 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1342 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1343 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1344 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
1346 for (unsigned i = 0; i < edges->size(); ++i) {
1347 Record* Edge = edges->getElementAsRecord(i);
1348 Record* A = Edge->getValueAsDef("a");
1349 Record* B = Edge->getValueAsDef("b");
1350 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
1351 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
1353 throw A->getName() + ": no such tool!";
1355 throw B->getName() + ": no such tool!";
1356 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
1357 throw "Edge " + A->getName() + "->" + B->getName()
1358 + ": output->input language mismatch";
1359 if (B->getName() == "root")
1360 throw std::string("Edges back to the root are not allowed!");
1364 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1365 /// by EmitEdgeClass().
1366 void IncDecWeight (const Init* i, const char* IndentLevel,
1368 const DagInit& d = InitPtrToDag(i);
1369 const std::string& OpName = d.getOperator()->getAsString();
1371 if (OpName == "inc_weight")
1372 O << IndentLevel << Indent1 << "ret += ";
1373 else if (OpName == "dec_weight")
1374 O << IndentLevel << Indent1 << "ret -= ";
1376 throw "Unknown operator in edge properties list: " + OpName + '!';
1378 if (d.getNumArgs() > 0)
1379 O << InitPtrToInt(d.getArg(0)) << ";\n";
1385 /// EmitEdgeClass - Emit a single Edge# class.
1386 void EmitEdgeClass (unsigned N, const std::string& Target,
1387 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1390 // Class constructor.
1391 O << "class Edge" << N << ": public Edge {\n"
1393 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1396 // Function Weight().
1397 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
1398 << Indent2 << "unsigned ret = 0;\n";
1400 // Handle the 'case' construct.
1401 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
1403 O << Indent2 << "return ret;\n"
1404 << Indent1 << "};\n\n};\n\n";
1407 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
1408 void EmitEdgeClasses (Record* CompilationGraph,
1409 const GlobalOptionDescriptions& OptDescs,
1411 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1413 for (unsigned i = 0; i < edges->size(); ++i) {
1414 Record* Edge = edges->getElementAsRecord(i);
1415 Record* B = Edge->getValueAsDef("b");
1416 DagInit* Weight = Edge->getValueAsDag("weight");
1418 if (isDagEmpty(Weight))
1421 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
1425 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1427 void EmitPopulateCompilationGraph (Record* CompilationGraph,
1430 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1433 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
1434 << Indent1 << "PopulateLanguageMap();\n\n";
1438 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1440 throw std::string("No tool definitions found!");
1442 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1443 const std::string& Name = (*B)->getName();
1445 O << Indent1 << "G.insertNode(new "
1446 << Name << "());\n";
1452 for (unsigned i = 0; i < edges->size(); ++i) {
1453 Record* Edge = edges->getElementAsRecord(i);
1454 Record* A = Edge->getValueAsDef("a");
1455 Record* B = Edge->getValueAsDef("b");
1456 DagInit* Weight = Edge->getValueAsDag("weight");
1458 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1460 if (isDagEmpty(Weight))
1461 O << "new SimpleEdge(\"" << B->getName() << "\")";
1463 O << "new Edge" << i << "()";
1471 /// ExtractHookNames - Extract the hook names from all instances of
1472 /// $CALL(HookName) in the provided command line string. Helper
1473 /// function used by FillInHookNames().
1474 void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1476 llvm::SplitString(InitPtrToString(CmdLine), cmds);
1477 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1479 const std::string& cmd = *B;
1480 if (cmd.find("$CALL(") == 0) {
1481 if (cmd.size() == 6)
1482 throw std::string("$CALL invocation: empty argument list!");
1483 HookNames.push_back(std::string(cmd.begin() + 6,
1484 cmd.begin() + cmd.find(")")));
1489 /// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1490 /// 'case' expression, handle nesting. Helper function used by
1491 /// FillInHookNames().
1492 void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1493 const DagInit& d = InitPtrToDag(Case);
1495 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1498 if (even && dynamic_cast<DagInit*>(arg)
1499 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1500 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1502 ExtractHookNames(arg, HookNames);
1507 /// FillInHookNames - Actually extract the hook names from all command
1508 /// line strings. Helper function used by EmitHookDeclarations().
1509 void FillInHookNames(const ToolPropertiesList& TPList,
1510 StrVector& HookNames) {
1511 // For all command lines:
1512 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1513 E = TPList.end(); B != E; ++B) {
1514 const ToolProperties& P = *(*B);
1517 if (dynamic_cast<StringInit*>(P.CmdLine))
1518 // This is a string.
1519 ExtractHookNames(P.CmdLine, HookNames);
1521 // This is a 'case' construct.
1522 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
1526 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
1527 /// property records and emit hook function declaration for each
1528 /// instance of $CALL(HookName).
1529 void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1531 StrVector HookNames;
1532 FillInHookNames(ToolProps, HookNames);
1533 if (HookNames.empty())
1535 std::sort(HookNames.begin(), HookNames.end());
1536 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1538 O << "namespace hooks {\n";
1539 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1540 O << Indent1 << "std::string " << *B << "();\n";
1545 // End of anonymous namespace
1548 /// run - The back-end entry point.
1549 void LLVMCConfigurationEmitter::run (std::ostream &O) {
1552 // Emit file header.
1553 EmitSourceFileHeader("LLVMC Configuration Library", O);
1555 // Get a list of all defined Tools.
1556 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1558 throw std::string("No tool definitions found!");
1560 // Gather information from the Tool description dags.
1561 ToolPropertiesList tool_props;
1562 GlobalOptionDescriptions opt_descs;
1563 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1565 // Emit global option registration code.
1566 EmitOptionDescriptions(opt_descs, O);
1568 // Emit hook declarations.
1569 EmitHookDeclarations(tool_props, O);
1571 // Emit PopulateLanguageMap() function
1572 // (a language map maps from file extensions to language names).
1573 EmitPopulateLanguageMap(Records, O);
1575 // Emit Tool classes.
1576 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1577 E = tool_props.end(); B!=E; ++B)
1578 EmitToolClassDefinition(*(*B), opt_descs, O);
1580 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1581 if (!CompilationGraphRecord)
1582 throw std::string("Compilation graph description not found!");
1584 // Typecheck the compilation graph.
1585 TypecheckGraph(CompilationGraphRecord, tool_props);
1587 // Emit Edge# classes.
1588 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
1590 // Emit PopulateCompilationGraph() function.
1591 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
1594 } catch (std::exception& Error) {
1595 throw Error.what() + std::string(" - usually this means a syntax error.");