1 //===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting LLVMC configuration code.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMCConfigurationEmitter.h"
17 #include "llvm/ADT/IntrusiveRefCntPtr.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
33 //===----------------------------------------------------------------------===//
36 typedef std::vector<Record*> RecordVector;
37 typedef std::vector<std::string> StrVector;
39 //===----------------------------------------------------------------------===//
43 unsigned TabWidth = 4;
44 unsigned Indent1 = TabWidth*1;
45 unsigned Indent2 = TabWidth*2;
46 unsigned Indent3 = TabWidth*3;
48 // Default help string.
49 const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51 // Name for the "sink" option.
52 const char * SinkOptionName = "AutoGeneratedSinkOption";
54 //===----------------------------------------------------------------------===//
57 /// Id - An 'identity' function object.
60 void operator()(const T&) const {
64 int InitPtrToInt(const Init* ptr) {
65 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
66 return val.getValue();
69 const std::string& InitPtrToString(const Init* ptr) {
70 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
71 return val.getValue();
74 const ListInit& InitPtrToList(const Init* ptr) {
75 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
79 const DagInit& InitPtrToDag(const Init* ptr) {
80 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
84 // checkNumberOfArguments - Ensure that the number of args in d is
85 // greater than or equal to min_arguments, otherwise throw an exception.
86 void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
87 if (!d || d->getNumArgs() < min_arguments)
88 throw d->getOperator()->getAsString() + ": too few arguments!";
91 // isDagEmpty - is this DAG marked with an empty marker?
92 bool isDagEmpty (const DagInit* d) {
93 return d->getOperator()->getAsString() == "empty_dag_marker";
96 // EscapeVariableName - Escape commas and other symbols not allowed
97 // in the C++ variable names. Makes it possible to use options named
98 // like "Wa," (useful for prefix options).
99 std::string EscapeVariableName(const std::string& Var) {
101 for (unsigned i = 0; i != Var.size(); ++i) {
102 char cur_char = Var[i];
103 if (cur_char == ',') {
106 else if (cur_char == '+') {
109 else if (cur_char == '-') {
113 ret.push_back(cur_char);
119 /// oneOf - Does the input string contain this character?
120 bool oneOf(const char* lst, char c) {
128 template <class I, class S>
129 void checkedIncrement(I& P, I E, S ErrorString) {
135 //===----------------------------------------------------------------------===//
136 /// Back-end specific code
139 /// OptionType - One of six different option types. See the
140 /// documentation for detailed description of differences.
141 namespace OptionType {
143 enum OptionType { Alias, Switch, Parameter, ParameterList,
146 bool IsList (OptionType t) {
147 return (t == ParameterList || t == PrefixList);
150 bool IsSwitch (OptionType t) {
151 return (t == Switch);
154 bool IsParameter (OptionType t) {
155 return (t == Parameter || t == Prefix);
160 OptionType::OptionType stringToOptionType(const std::string& T) {
161 if (T == "alias_option")
162 return OptionType::Alias;
163 else if (T == "switch_option")
164 return OptionType::Switch;
165 else if (T == "parameter_option")
166 return OptionType::Parameter;
167 else if (T == "parameter_list_option")
168 return OptionType::ParameterList;
169 else if (T == "prefix_option")
170 return OptionType::Prefix;
171 else if (T == "prefix_list_option")
172 return OptionType::PrefixList;
174 throw "Unknown option type: " + T + '!';
177 namespace OptionDescriptionFlags {
178 enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
179 ReallyHidden = 0x4, Extern = 0x8,
180 OneOrMore = 0x10, ZeroOrOne = 0x20 };
183 /// OptionDescription - Represents data contained in a single
184 /// OptionList entry.
185 struct OptionDescription {
186 OptionType::OptionType Type;
193 OptionDescription(OptionType::OptionType t = OptionType::Switch,
194 const std::string& n = "",
195 const std::string& h = DefaultHelpString)
196 : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
199 /// GenTypeDeclaration - Returns the C++ variable type of this
201 const char* GenTypeDeclaration() const;
203 /// GenVariableName - Returns the variable name used in the
204 /// generated C++ code.
205 std::string GenVariableName() const;
207 /// Merge - Merge two option descriptions.
208 void Merge (const OptionDescription& other);
210 // Misc convenient getters/setters.
212 bool isAlias() const;
214 bool isMultiVal() const;
216 bool isExtern() const;
219 bool isRequired() const;
222 bool isOneOrMore() const;
225 bool isZeroOrOne() const;
228 bool isHidden() const;
231 bool isReallyHidden() const;
232 void setReallyHidden();
234 bool isParameter() const
235 { return OptionType::IsParameter(this->Type); }
237 bool isSwitch() const
238 { return OptionType::IsSwitch(this->Type); }
241 { return OptionType::IsList(this->Type); }
245 void OptionDescription::Merge (const OptionDescription& other)
247 if (other.Type != Type)
248 throw "Conflicting definitions for the option " + Name + "!";
250 if (Help == other.Help || Help == DefaultHelpString)
252 else if (other.Help != DefaultHelpString) {
253 llvm::errs() << "Warning: several different help strings"
254 " defined for option " + Name + "\n";
257 Flags |= other.Flags;
260 bool OptionDescription::isAlias() const {
261 return Type == OptionType::Alias;
264 bool OptionDescription::isMultiVal() const {
268 bool OptionDescription::isExtern() const {
269 return Flags & OptionDescriptionFlags::Extern;
271 void OptionDescription::setExtern() {
272 Flags |= OptionDescriptionFlags::Extern;
275 bool OptionDescription::isRequired() const {
276 return Flags & OptionDescriptionFlags::Required;
278 void OptionDescription::setRequired() {
279 Flags |= OptionDescriptionFlags::Required;
282 bool OptionDescription::isOneOrMore() const {
283 return Flags & OptionDescriptionFlags::OneOrMore;
285 void OptionDescription::setOneOrMore() {
286 Flags |= OptionDescriptionFlags::OneOrMore;
289 bool OptionDescription::isZeroOrOne() const {
290 return Flags & OptionDescriptionFlags::ZeroOrOne;
292 void OptionDescription::setZeroOrOne() {
293 Flags |= OptionDescriptionFlags::ZeroOrOne;
296 bool OptionDescription::isHidden() const {
297 return Flags & OptionDescriptionFlags::Hidden;
299 void OptionDescription::setHidden() {
300 Flags |= OptionDescriptionFlags::Hidden;
303 bool OptionDescription::isReallyHidden() const {
304 return Flags & OptionDescriptionFlags::ReallyHidden;
306 void OptionDescription::setReallyHidden() {
307 Flags |= OptionDescriptionFlags::ReallyHidden;
310 const char* OptionDescription::GenTypeDeclaration() const {
312 case OptionType::Alias:
314 case OptionType::PrefixList:
315 case OptionType::ParameterList:
316 return "cl::list<std::string>";
317 case OptionType::Switch:
318 return "cl::opt<bool>";
319 case OptionType::Parameter:
320 case OptionType::Prefix:
322 return "cl::opt<std::string>";
326 std::string OptionDescription::GenVariableName() const {
327 const std::string& EscapedName = EscapeVariableName(Name);
329 case OptionType::Alias:
330 return "AutoGeneratedAlias_" + EscapedName;
331 case OptionType::PrefixList:
332 case OptionType::ParameterList:
333 return "AutoGeneratedList_" + EscapedName;
334 case OptionType::Switch:
335 return "AutoGeneratedSwitch_" + EscapedName;
336 case OptionType::Prefix:
337 case OptionType::Parameter:
339 return "AutoGeneratedParameter_" + EscapedName;
343 /// OptionDescriptions - An OptionDescription array plus some helper
345 class OptionDescriptions {
346 typedef StringMap<OptionDescription> container_type;
348 /// Descriptions - A list of OptionDescriptions.
349 container_type Descriptions;
352 /// FindOption - exception-throwing wrapper for find().
353 const OptionDescription& FindOption(const std::string& OptName) const;
354 /// FindSwitch - wrapper for FindOption that throws in case the option is not
356 const OptionDescription& FindSwitch(const std::string& OptName) const;
358 /// insertDescription - Insert new OptionDescription into
359 /// OptionDescriptions list
360 void InsertDescription (const OptionDescription& o);
362 // Support for STL-style iteration
363 typedef container_type::const_iterator const_iterator;
364 const_iterator begin() const { return Descriptions.begin(); }
365 const_iterator end() const { return Descriptions.end(); }
368 const OptionDescription&
369 OptionDescriptions::FindOption(const std::string& OptName) const
371 const_iterator I = Descriptions.find(OptName);
372 if (I != Descriptions.end())
375 throw OptName + ": no such option!";
378 const OptionDescription&
379 OptionDescriptions::FindSwitch(const std::string& OptName) const
381 const OptionDescription& OptDesc = this->FindOption(OptName);
382 if (!OptDesc.isSwitch())
383 throw OptName + ": incorrect option type - should be a switch!";
387 void OptionDescriptions::InsertDescription (const OptionDescription& o)
389 container_type::iterator I = Descriptions.find(o.Name);
390 if (I != Descriptions.end()) {
391 OptionDescription& D = I->second;
395 Descriptions[o.Name] = o;
399 /// HandlerTable - A base class for function objects implemented as
400 /// 'tables of handlers'.
404 // Implementation details.
407 typedef void (T::* Handler) (const DagInit*);
408 /// HandlerMap - A map from property names to property handlers
409 typedef StringMap<Handler> HandlerMap;
411 static HandlerMap Handlers_;
412 static bool staticMembersInitialized_;
417 HandlerTable(T* cp) : childPtr(cp)
420 /// operator() - Just forwards to the corresponding property
422 void operator() (Init* i) {
423 const DagInit& property = InitPtrToDag(i);
424 const std::string& property_name = property.getOperator()->getAsString();
425 typename HandlerMap::iterator method = Handlers_.find(property_name);
427 if (method != Handlers_.end()) {
428 Handler h = method->second;
429 (childPtr->*h)(&property);
432 throw "No handler found for property " + property_name + "!";
436 void AddHandler(const char* Property, Handler Handl) {
437 Handlers_[Property] = Handl;
441 template <class T> typename HandlerTable<T>::HandlerMap
442 HandlerTable<T>::Handlers_;
443 template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
446 /// CollectOptionProperties - Function object for iterating over an
447 /// option property list.
448 class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
451 /// optDescs_ - OptionDescriptions table. This is where the
452 /// information is stored.
453 OptionDescription& optDesc_;
457 explicit CollectOptionProperties(OptionDescription& OD)
458 : HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
460 if (!staticMembersInitialized_) {
461 AddHandler("extern", &CollectOptionProperties::onExtern);
462 AddHandler("help", &CollectOptionProperties::onHelp);
463 AddHandler("hidden", &CollectOptionProperties::onHidden);
464 AddHandler("init", &CollectOptionProperties::onInit);
465 AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
466 AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
467 AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
468 AddHandler("required", &CollectOptionProperties::onRequired);
469 AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
471 staticMembersInitialized_ = true;
477 /// Option property handlers --
478 /// Methods that handle option properties such as (help) or (hidden).
480 void onExtern (const DagInit* d) {
481 checkNumberOfArguments(d, 0);
482 optDesc_.setExtern();
485 void onHelp (const DagInit* d) {
486 checkNumberOfArguments(d, 1);
487 optDesc_.Help = InitPtrToString(d->getArg(0));
490 void onHidden (const DagInit* d) {
491 checkNumberOfArguments(d, 0);
492 optDesc_.setHidden();
495 void onReallyHidden (const DagInit* d) {
496 checkNumberOfArguments(d, 0);
497 optDesc_.setReallyHidden();
500 void onRequired (const DagInit* d) {
501 checkNumberOfArguments(d, 0);
502 if (optDesc_.isOneOrMore())
503 throw std::string("An option can't have both (required) "
504 "and (one_or_more) properties!");
505 optDesc_.setRequired();
508 void onInit (const DagInit* d) {
509 checkNumberOfArguments(d, 1);
510 Init* i = d->getArg(0);
511 const std::string& str = i->getAsString();
513 bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
514 correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
517 throw std::string("Incorrect usage of the 'init' option property!");
519 optDesc_.InitVal = i;
522 void onOneOrMore (const DagInit* d) {
523 checkNumberOfArguments(d, 0);
524 if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
525 throw std::string("Only one of (required), (zero_or_one) or "
526 "(one_or_more) properties is allowed!");
527 if (!OptionType::IsList(optDesc_.Type))
528 llvm::errs() << "Warning: specifying the 'one_or_more' property "
529 "on a non-list option will have no effect.\n";
530 optDesc_.setOneOrMore();
533 void onZeroOrOne (const DagInit* d) {
534 checkNumberOfArguments(d, 0);
535 if (optDesc_.isRequired() || optDesc_.isOneOrMore())
536 throw std::string("Only one of (required), (zero_or_one) or "
537 "(one_or_more) properties is allowed!");
538 if (!OptionType::IsList(optDesc_.Type))
539 llvm::errs() << "Warning: specifying the 'zero_or_one' property"
540 "on a non-list option will have no effect.\n";
541 optDesc_.setZeroOrOne();
544 void onMultiVal (const DagInit* d) {
545 checkNumberOfArguments(d, 1);
546 int val = InitPtrToInt(d->getArg(0));
548 throw std::string("Error in the 'multi_val' property: "
549 "the value must be greater than 1!");
550 if (!OptionType::IsList(optDesc_.Type))
551 throw std::string("The multi_val property is valid only "
553 optDesc_.MultiVal = val;
558 /// AddOption - A function object that is applied to every option
559 /// description. Used by CollectOptionDescriptions.
562 OptionDescriptions& OptDescs_;
565 explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
568 void operator()(const Init* i) {
569 const DagInit& d = InitPtrToDag(i);
570 checkNumberOfArguments(&d, 1);
572 const OptionType::OptionType Type =
573 stringToOptionType(d.getOperator()->getAsString());
574 const std::string& Name = InitPtrToString(d.getArg(0));
576 OptionDescription OD(Type, Name);
579 checkNumberOfArguments(&d, 2);
582 // Aliases store the aliased option name in the 'Help' field.
583 OD.Help = InitPtrToString(d.getArg(1));
585 else if (!OD.isExtern()) {
586 processOptionProperties(&d, OD);
588 OptDescs_.InsertDescription(OD);
592 /// processOptionProperties - Go through the list of option
593 /// properties and call a corresponding handler for each.
594 static void processOptionProperties (const DagInit* d, OptionDescription& o) {
595 checkNumberOfArguments(d, 2);
596 DagInit::const_arg_iterator B = d->arg_begin();
597 // Skip the first argument: it's always the option name.
599 std::for_each(B, d->arg_end(), CollectOptionProperties(o));
604 /// CollectOptionDescriptions - Collects option properties from all
606 void CollectOptionDescriptions (RecordVector::const_iterator B,
607 RecordVector::const_iterator E,
608 OptionDescriptions& OptDescs)
610 // For every OptionList:
612 RecordVector::value_type T = *B;
613 // Throws an exception if the value does not exist.
614 ListInit* PropList = T->getValueAsListInit("options");
616 // For every option description in this list:
617 // collect the information and
618 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
622 // Tool information record
624 namespace ToolFlags {
625 enum ToolFlags { Join = 0x1, Sink = 0x2 };
628 struct ToolDescription : public RefCountedBase<ToolDescription> {
632 StrVector InLanguage;
633 std::string OutLanguage;
634 std::string OutputSuffix;
637 // Various boolean properties
638 void setSink() { Flags |= ToolFlags::Sink; }
639 bool isSink() const { return Flags & ToolFlags::Sink; }
640 void setJoin() { Flags |= ToolFlags::Join; }
641 bool isJoin() const { return Flags & ToolFlags::Join; }
643 // Default ctor here is needed because StringMap can only store
644 // DefaultConstructible objects
645 ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
646 ToolDescription (const std::string& n)
647 : Name(n), CmdLine(0), Actions(0), Flags(0)
651 /// ToolDescriptions - A list of Tool information records.
652 typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
655 /// CollectToolProperties - Function object for iterating over a list of
656 /// tool property records.
657 class CollectToolProperties : public HandlerTable<CollectToolProperties> {
660 /// toolDesc_ - Properties of the current Tool. This is where the
661 /// information is stored.
662 ToolDescription& toolDesc_;
666 explicit CollectToolProperties (ToolDescription& d)
667 : HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
669 if (!staticMembersInitialized_) {
671 AddHandler("actions", &CollectToolProperties::onActions);
672 AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
673 AddHandler("in_language", &CollectToolProperties::onInLanguage);
674 AddHandler("join", &CollectToolProperties::onJoin);
675 AddHandler("out_language", &CollectToolProperties::onOutLanguage);
676 AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
677 AddHandler("sink", &CollectToolProperties::onSink);
679 staticMembersInitialized_ = true;
685 /// Property handlers --
686 /// Functions that extract information about tool properties from
687 /// DAG representation.
689 void onActions (const DagInit* d) {
690 checkNumberOfArguments(d, 1);
691 Init* Case = d->getArg(0);
692 if (typeid(*Case) != typeid(DagInit) ||
693 static_cast<DagInit*>(Case)->getOperator()->getAsString() != "case")
695 std::string("The argument to (actions) should be a 'case' construct!");
696 toolDesc_.Actions = Case;
699 void onCmdLine (const DagInit* d) {
700 checkNumberOfArguments(d, 1);
701 toolDesc_.CmdLine = d->getArg(0);
704 void onInLanguage (const DagInit* d) {
705 checkNumberOfArguments(d, 1);
706 Init* arg = d->getArg(0);
708 // Find out the argument's type.
709 if (typeid(*arg) == typeid(StringInit)) {
711 toolDesc_.InLanguage.push_back(InitPtrToString(arg));
715 const ListInit& lst = InitPtrToList(arg);
716 StrVector& out = toolDesc_.InLanguage;
718 // Copy strings to the output vector.
719 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
721 out.push_back(InitPtrToString(*B));
724 // Remove duplicates.
725 std::sort(out.begin(), out.end());
726 StrVector::iterator newE = std::unique(out.begin(), out.end());
727 out.erase(newE, out.end());
731 void onJoin (const DagInit* d) {
732 checkNumberOfArguments(d, 0);
736 void onOutLanguage (const DagInit* d) {
737 checkNumberOfArguments(d, 1);
738 toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
741 void onOutputSuffix (const DagInit* d) {
742 checkNumberOfArguments(d, 1);
743 toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
746 void onSink (const DagInit* d) {
747 checkNumberOfArguments(d, 0);
753 /// CollectToolDescriptions - Gather information about tool properties
754 /// from the parsed TableGen data (basically a wrapper for the
755 /// CollectToolProperties function object).
756 void CollectToolDescriptions (RecordVector::const_iterator B,
757 RecordVector::const_iterator E,
758 ToolDescriptions& ToolDescs)
760 // Iterate over a properties list of every Tool definition
762 const Record* T = *B;
763 // Throws an exception if the value does not exist.
764 ListInit* PropList = T->getValueAsListInit("properties");
766 IntrusiveRefCntPtr<ToolDescription>
767 ToolDesc(new ToolDescription(T->getName()));
769 std::for_each(PropList->begin(), PropList->end(),
770 CollectToolProperties(*ToolDesc));
771 ToolDescs.push_back(ToolDesc);
775 /// FillInEdgeVector - Merge all compilation graph definitions into
776 /// one single edge list.
777 void FillInEdgeVector(RecordVector::const_iterator B,
778 RecordVector::const_iterator E, RecordVector& Out) {
779 for (; B != E; ++B) {
780 const ListInit* edges = (*B)->getValueAsListInit("edges");
782 for (unsigned i = 0; i < edges->size(); ++i)
783 Out.push_back(edges->getElementAsRecord(i));
787 /// CalculatePriority - Calculate the priority of this plugin.
788 int CalculatePriority(RecordVector::const_iterator B,
789 RecordVector::const_iterator E) {
793 priority = static_cast<int>((*B)->getValueAsInt("priority"));
796 throw std::string("More than one 'PluginPriority' instance found: "
797 "most probably an error!");
803 /// NotInGraph - Helper function object for FilterNotInGraph.
806 const llvm::StringSet<>& ToolsInGraph_;
809 NotInGraph(const llvm::StringSet<>& ToolsInGraph)
810 : ToolsInGraph_(ToolsInGraph)
813 bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
814 return (ToolsInGraph_.count(x->Name) == 0);
818 /// FilterNotInGraph - Filter out from ToolDescs all Tools not
819 /// mentioned in the compilation graph definition.
820 void FilterNotInGraph (const RecordVector& EdgeVector,
821 ToolDescriptions& ToolDescs) {
823 // List all tools mentioned in the graph.
824 llvm::StringSet<> ToolsInGraph;
826 for (RecordVector::const_iterator B = EdgeVector.begin(),
827 E = EdgeVector.end(); B != E; ++B) {
829 const Record* Edge = *B;
830 const std::string& NodeA = Edge->getValueAsString("a");
831 const std::string& NodeB = Edge->getValueAsString("b");
834 ToolsInGraph.insert(NodeA);
835 ToolsInGraph.insert(NodeB);
838 // Filter ToolPropertiesList.
839 ToolDescriptions::iterator new_end =
840 std::remove_if(ToolDescs.begin(), ToolDescs.end(),
841 NotInGraph(ToolsInGraph));
842 ToolDescs.erase(new_end, ToolDescs.end());
845 /// FillInToolToLang - Fills in two tables that map tool names to
846 /// (input, output) languages. Helper function used by TypecheckGraph().
847 void FillInToolToLang (const ToolDescriptions& ToolDescs,
848 StringMap<StringSet<> >& ToolToInLang,
849 StringMap<std::string>& ToolToOutLang) {
850 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
851 E = ToolDescs.end(); B != E; ++B) {
852 const ToolDescription& D = *(*B);
853 for (StrVector::const_iterator B = D.InLanguage.begin(),
854 E = D.InLanguage.end(); B != E; ++B)
855 ToolToInLang[D.Name].insert(*B);
856 ToolToOutLang[D.Name] = D.OutLanguage;
860 /// TypecheckGraph - Check that names for output and input languages
861 /// on all edges do match. This doesn't do much when the information
862 /// about the whole graph is not available (i.e. when compiling most
864 void TypecheckGraph (const RecordVector& EdgeVector,
865 const ToolDescriptions& ToolDescs) {
866 StringMap<StringSet<> > ToolToInLang;
867 StringMap<std::string> ToolToOutLang;
869 FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
870 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
871 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
873 for (RecordVector::const_iterator B = EdgeVector.begin(),
874 E = EdgeVector.end(); B != E; ++B) {
875 const Record* Edge = *B;
876 const std::string& NodeA = Edge->getValueAsString("a");
877 const std::string& NodeB = Edge->getValueAsString("b");
878 StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
879 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
881 if (NodeA != "root") {
882 if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
883 throw "Edge " + NodeA + "->" + NodeB
884 + ": output->input language mismatch";
888 throw std::string("Edges back to the root are not allowed!");
892 /// WalkCase - Walks the 'case' expression DAG and invokes
893 /// TestCallback on every test, and StatementCallback on every
894 /// statement. Handles 'case' nesting, but not the 'and' and 'or'
896 // TODO: Re-implement EmitCaseConstructHandler on top of this function?
897 template <typename F1, typename F2>
898 void WalkCase(Init* Case, F1 TestCallback, F2 StatementCallback) {
899 const DagInit& d = InitPtrToDag(Case);
901 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
904 if (even && dynamic_cast<DagInit*>(arg)
905 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
906 WalkCase(arg, TestCallback, StatementCallback);
910 StatementCallback(arg);
915 /// ExtractOptionNames - A helper function object used by
916 /// CheckForSuperfluousOptions() to walk the 'case' DAG.
917 class ExtractOptionNames {
918 llvm::StringSet<>& OptionNames_;
920 void processDag(const Init* Statement) {
921 const DagInit& Stmt = InitPtrToDag(Statement);
922 const std::string& ActionName = Stmt.getOperator()->getAsString();
923 if (ActionName == "forward" || ActionName == "forward_as" ||
924 ActionName == "unpack_values" || ActionName == "switch_on" ||
925 ActionName == "parameter_equals" || ActionName == "element_in_list" ||
926 ActionName == "not_empty" || ActionName == "empty") {
927 checkNumberOfArguments(&Stmt, 1);
928 const std::string& Name = InitPtrToString(Stmt.getArg(0));
929 OptionNames_.insert(Name);
931 else if (ActionName == "and" || ActionName == "or") {
932 for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
933 this->processDag(Stmt.getArg(i));
939 ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
942 void operator()(const Init* Statement) {
943 if (typeid(*Statement) == typeid(ListInit)) {
944 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
945 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
947 this->processDag(*B);
950 this->processDag(Statement);
955 /// CheckForSuperfluousOptions - Check that there are no side
956 /// effect-free options (specified only in the OptionList). Otherwise,
957 /// output a warning.
958 void CheckForSuperfluousOptions (const RecordVector& Edges,
959 const ToolDescriptions& ToolDescs,
960 const OptionDescriptions& OptDescs) {
961 llvm::StringSet<> nonSuperfluousOptions;
963 // Add all options mentioned in the ToolDesc.Actions to the set of
964 // non-superfluous options.
965 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
966 E = ToolDescs.end(); B != E; ++B) {
967 const ToolDescription& TD = *(*B);
968 ExtractOptionNames Callback(nonSuperfluousOptions);
970 WalkCase(TD.Actions, Callback, Callback);
973 // Add all options mentioned in the 'case' clauses of the
974 // OptionalEdges of the compilation graph to the set of
975 // non-superfluous options.
976 for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
978 const Record* Edge = *B;
979 DagInit* Weight = Edge->getValueAsDag("weight");
981 if (!isDagEmpty(Weight))
982 WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
985 // Check that all options in OptDescs belong to the set of
986 // non-superfluous options.
987 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
988 E = OptDescs.end(); B != E; ++B) {
989 const OptionDescription& Val = B->second;
990 if (!nonSuperfluousOptions.count(Val.Name)
991 && Val.Type != OptionType::Alias)
992 llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
993 "Probable cause: this option is specified only in the OptionList.\n";
997 /// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
998 bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
999 if (TestName == "single_input_file") {
1000 O << "InputFilenames.size() == 1";
1003 else if (TestName == "multiple_input_files") {
1004 O << "InputFilenames.size() > 1";
1011 /// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
1012 bool EmitCaseTest1ArgStr(const std::string& TestName,
1014 const OptionDescriptions& OptDescs,
1016 const std::string& OptName = InitPtrToString(d.getArg(0));
1018 if (TestName == "switch_on") {
1019 const OptionDescription& OptDesc = OptDescs.FindSwitch(OptName);
1020 O << OptDesc.GenVariableName();
1023 else if (TestName == "input_languages_contain") {
1024 O << "InLangs.count(\"" << OptName << "\") != 0";
1027 else if (TestName == "in_language") {
1028 // This works only for single-argument Tool::GenerateAction. Join
1029 // tools can process several files in different languages simultaneously.
1031 // TODO: make this work with Edge::Weight (if possible).
1032 O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
1035 else if (TestName == "not_empty" || TestName == "empty") {
1036 const char* Test = (TestName == "empty") ? "" : "!";
1038 if (OptName == "o") {
1039 O << Test << "OutputFilename.empty()";
1043 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1044 if (OptDesc.isSwitch())
1046 + ": incorrect option type - should be a list or parameter!";
1047 O << Test << OptDesc.GenVariableName() << ".empty()";
1055 /// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
1056 bool EmitCaseTest1ArgList(const std::string& TestName,
1058 const OptionDescriptions& OptDescs,
1060 const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
1062 if (TestName == "any_switch_on") {
1063 bool isFirst = true;
1065 for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
1066 const std::string& OptName = InitPtrToString(*B);
1067 const OptionDescription& OptDesc = OptDescs.FindSwitch(OptName);
1073 O << OptDesc.GenVariableName();
1079 // TODO: implement any_not_empty, any_empty, switch_on [..], empty [..]
1084 /// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
1085 bool EmitCaseTest1Arg(const std::string& TestName,
1087 const OptionDescriptions& OptDescs,
1089 checkNumberOfArguments(&d, 1);
1090 if (typeid(*d.getArg(0)) == typeid(ListInit))
1091 return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
1093 return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
1096 /// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
1097 bool EmitCaseTest2Args(const std::string& TestName,
1099 unsigned IndentLevel,
1100 const OptionDescriptions& OptDescs,
1102 checkNumberOfArguments(&d, 2);
1103 const std::string& OptName = InitPtrToString(d.getArg(0));
1104 const std::string& OptArg = InitPtrToString(d.getArg(1));
1105 const OptionDescription& OptDesc = OptDescs.FindOption(OptName);
1107 if (TestName == "parameter_equals") {
1108 if (!OptDesc.isParameter())
1109 throw OptName + ": incorrect option type - should be a parameter!";
1110 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
1113 else if (TestName == "element_in_list") {
1114 if (!OptDesc.isList())
1115 throw OptName + ": incorrect option type - should be a list!";
1116 const std::string& VarName = OptDesc.GenVariableName();
1117 O << "std::find(" << VarName << ".begin(),\n";
1118 O.indent(IndentLevel + Indent1)
1119 << VarName << ".end(), \""
1120 << OptArg << "\") != " << VarName << ".end()";
1127 // Forward declaration.
1128 // EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
1129 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1130 const OptionDescriptions& OptDescs,
1133 /// EmitLogicalOperationTest - Helper function used by
1134 /// EmitCaseConstructHandler.
1135 void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
1136 unsigned IndentLevel,
1137 const OptionDescriptions& OptDescs,
1140 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
1141 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
1142 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1143 if (j != NumArgs - 1) {
1145 O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
1153 void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
1154 const OptionDescriptions& OptDescs, raw_ostream& O)
1156 checkNumberOfArguments(&d, 1);
1157 const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
1159 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
1163 /// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
1164 void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
1165 const OptionDescriptions& OptDescs,
1167 const std::string& TestName = d.getOperator()->getAsString();
1169 if (TestName == "and")
1170 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
1171 else if (TestName == "or")
1172 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
1173 else if (TestName == "not")
1174 EmitLogicalNot(d, IndentLevel, OptDescs, O);
1175 else if (EmitCaseTest0Args(TestName, O))
1177 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
1179 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
1182 throw TestName + ": unknown edge property!";
1185 /// EmitCaseConstructHandler - Emit code that handles the 'case'
1186 /// construct. Takes a function object that should emit code for every case
1188 /// Callback's type is void F(Init* Statement, unsigned IndentLevel,
1189 /// raw_ostream& O).
1190 /// EmitElseIf parameter controls the type of condition that is emitted ('if
1191 /// (..) {...} else if (...) {} ... else {...}' vs. 'if (..) {...} if(...)
1193 template <typename F>
1194 void EmitCaseConstructHandler(const Init* Dag, unsigned IndentLevel,
1195 F Callback, bool EmitElseIf,
1196 const OptionDescriptions& OptDescs,
1198 const DagInit* d = &InitPtrToDag(Dag);
1199 if (d->getOperator()->getAsString() != "case")
1200 throw std::string("EmitCaseConstructHandler should be invoked"
1201 " only on 'case' expressions!");
1203 unsigned numArgs = d->getNumArgs();
1204 if (d->getNumArgs() < 2)
1205 throw "There should be at least one clause in the 'case' expression:\n"
1208 for (unsigned i = 0; i != numArgs; ++i) {
1209 const DagInit& Test = InitPtrToDag(d->getArg(i));
1212 if (Test.getOperator()->getAsString() == "default") {
1214 throw std::string("The 'default' clause should be the last in the"
1215 "'case' construct!");
1216 O.indent(IndentLevel) << "else {\n";
1219 O.indent(IndentLevel) << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
1220 EmitCaseTest(Test, IndentLevel, OptDescs, O);
1224 // Emit the corresponding statement.
1227 throw "Case construct handler: no corresponding action "
1228 "found for the test " + Test.getAsString() + '!';
1230 Init* arg = d->getArg(i);
1231 const DagInit* nd = dynamic_cast<DagInit*>(arg);
1232 if (nd && (nd->getOperator()->getAsString() == "case")) {
1233 // Handle the nested 'case'.
1234 EmitCaseConstructHandler(nd, (IndentLevel + Indent1),
1235 Callback, EmitElseIf, OptDescs, O);
1238 Callback(arg, (IndentLevel + Indent1), O);
1240 O.indent(IndentLevel) << "}\n";
1244 /// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
1245 /// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
1246 /// Helper function used by EmitCmdLineVecFill and.
1247 void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
1248 const char* Delimiters = " \t\n\v\f\r";
1250 { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
1253 if (CmdLine.empty())
1257 std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
1260 for (; B != E; ++B) {
1261 char cur_ch = CmdLine[B];
1265 if (cur_ch == '$') {
1266 cur_st = SpecialCommand;
1269 if (oneOf(Delimiters, cur_ch)) {
1271 B = CmdLine.find_first_not_of(Delimiters, B);
1272 if (B == std::string::npos) {
1283 case SpecialCommand:
1284 if (oneOf(Delimiters, cur_ch)) {
1289 if (cur_ch == '(') {
1291 cur_st = InsideSpecialCommand;
1296 case InsideSpecialCommand:
1297 if (oneOf(Delimiters, cur_ch)) {
1300 if (cur_ch == '\'') {
1301 cur_st = InsideQuotationMarks;
1305 if (cur_ch == ')') {
1309 if (cur_ch == ',') {
1315 case InsideQuotationMarks:
1316 if (cur_ch == '\'') {
1317 cur_st = InsideSpecialCommand;
1323 Out.back().push_back(cur_ch);
1327 /// SubstituteSpecialCommands - Perform string substitution for $CALL
1328 /// and $ENV. Helper function used by EmitCmdLineVecFill().
1329 StrVector::const_iterator SubstituteSpecialCommands
1330 (StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
1333 const std::string& cmd = *Pos;
1335 if (cmd == "$CALL") {
1336 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1337 const std::string& CmdName = *Pos;
1340 throw std::string("$CALL invocation: empty argument list!");
1343 O << CmdName << "(";
1346 bool firstIteration = true;
1348 checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
1349 const std::string& Arg = *Pos;
1350 assert(Arg.size() != 0);
1356 firstIteration = false;
1360 O << '"' << Arg << '"';
1366 else if (cmd == "$ENV") {
1367 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1368 const std::string& EnvName = *Pos;
1371 throw "$ENV invocation: empty argument list!";
1373 O << "checkCString(std::getenv(\"";
1377 checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
1380 throw "Unknown special command: " + cmd;
1383 const std::string& Leftover = *Pos;
1384 assert(Leftover.at(0) == ')');
1385 if (Leftover.size() != 1)
1386 O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
1391 /// EmitCmdLineVecFill - Emit code that fills in the command line
1392 /// vector. Helper function used by EmitGenerateActionMethod().
1393 void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1394 bool IsJoin, unsigned IndentLevel,
1397 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1400 throw "Tool '" + ToolName + "' has empty command line!";
1402 StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1404 // If there is a hook invocation on the place of the first command, skip it.
1405 assert(!StrVec[0].empty());
1406 if (StrVec[0][0] == '$') {
1407 while (I != E && (*I)[0] != ')' )
1410 // Skip the ')' symbol.
1417 bool hasINFILE = false;
1419 for (; I != E; ++I) {
1420 const std::string& cmd = *I;
1421 assert(!cmd.empty());
1422 O.indent(IndentLevel);
1423 if (cmd.at(0) == '$') {
1424 if (cmd == "$INFILE") {
1427 O << "for (PathVector::const_iterator B = inFiles.begin()"
1428 << ", E = inFiles.end();\n";
1429 O.indent(IndentLevel) << "B != E; ++B)\n";
1430 O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
1433 O << "vec.push_back(inFile.str());\n";
1436 else if (cmd == "$OUTFILE") {
1437 O << "vec.push_back(\"\");\n";
1438 O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
1441 O << "vec.push_back(";
1442 I = SubstituteSpecialCommands(I, E, O);
1447 O << "vec.push_back(\"" << cmd << "\");\n";
1451 throw "Tool '" + ToolName + "' doesn't take any input!";
1453 O.indent(IndentLevel) << "cmd = ";
1454 if (StrVec[0][0] == '$')
1455 SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
1457 O << '"' << StrVec[0] << '"';
1461 /// EmitCmdLineVecFillCallback - A function object wrapper around
1462 /// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1463 /// argument to EmitCaseConstructHandler().
1464 class EmitCmdLineVecFillCallback {
1466 const std::string& ToolName;
1468 EmitCmdLineVecFillCallback(bool J, const std::string& TN)
1469 : IsJoin(J), ToolName(TN) {}
1471 void operator()(const Init* Statement, unsigned IndentLevel,
1472 raw_ostream& O) const
1474 EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
1478 /// EmitForwardOptionPropertyHandlingCode - Helper function used to
1479 /// implement EmitActionHandler. Emits code for
1480 /// handling the (forward) and (forward_as) option properties.
1481 void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
1482 unsigned IndentLevel,
1483 const std::string& NewName,
1485 const std::string& Name = NewName.empty()
1488 unsigned IndentLevel1 = IndentLevel + Indent1;
1491 case OptionType::Switch:
1492 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1494 case OptionType::Parameter:
1495 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
1496 O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
1498 case OptionType::Prefix:
1499 O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
1500 << D.GenVariableName() << ");\n";
1502 case OptionType::PrefixList:
1503 O.indent(IndentLevel)
1504 << "for (" << D.GenTypeDeclaration()
1505 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1506 O.indent(IndentLevel)
1507 << "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
1508 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
1509 O.indent(IndentLevel1) << "++B;\n";
1511 for (int i = 1, j = D.MultiVal; i < j; ++i) {
1512 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1513 O.indent(IndentLevel1) << "++B;\n";
1516 O.indent(IndentLevel) << "}\n";
1518 case OptionType::ParameterList:
1519 O.indent(IndentLevel)
1520 << "for (" << D.GenTypeDeclaration() << "::iterator B = "
1521 << D.GenVariableName() << ".begin(),\n";
1522 O.indent(IndentLevel) << "E = " << D.GenVariableName()
1523 << ".end() ; B != E;) {\n";
1524 O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
1526 for (int i = 0, j = D.MultiVal; i < j; ++i) {
1527 O.indent(IndentLevel1) << "vec.push_back(*B);\n";
1528 O.indent(IndentLevel1) << "++B;\n";
1531 O.indent(IndentLevel) << "}\n";
1533 case OptionType::Alias:
1535 throw std::string("Aliases are not allowed in tool option descriptions!");
1539 /// EmitActionHandler - Emit code that handles actions. Used by
1540 /// EmitGenerateActionMethod() as an argument to
1541 /// EmitCaseConstructHandler().
1542 class EmitActionHandler {
1543 const OptionDescriptions& OptDescs;
1545 void processActionDag(const Init* Statement, unsigned IndentLevel,
1546 raw_ostream& O) const
1548 const DagInit& Dag = InitPtrToDag(Statement);
1549 const std::string& ActionName = Dag.getOperator()->getAsString();
1551 if (ActionName == "append_cmd") {
1552 checkNumberOfArguments(&Dag, 1);
1553 const std::string& Cmd = InitPtrToString(Dag.getArg(0));
1555 llvm::SplitString(Cmd, Out);
1557 for (StrVector::const_iterator B = Out.begin(), E = Out.end();
1559 O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
1561 else if (ActionName == "error") {
1562 O.indent(IndentLevel) << "throw std::runtime_error(\"" <<
1563 (Dag.getNumArgs() >= 1 ? InitPtrToString(Dag.getArg(0))
1567 else if (ActionName == "forward") {
1568 checkNumberOfArguments(&Dag, 1);
1569 const std::string& Name = InitPtrToString(Dag.getArg(0));
1570 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1571 IndentLevel, "", O);
1573 else if (ActionName == "forward_as") {
1574 checkNumberOfArguments(&Dag, 2);
1575 const std::string& Name = InitPtrToString(Dag.getArg(0));
1576 const std::string& NewName = InitPtrToString(Dag.getArg(1));
1577 EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
1578 IndentLevel, NewName, O);
1580 else if (ActionName == "output_suffix") {
1581 checkNumberOfArguments(&Dag, 1);
1582 const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
1583 O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
1585 else if (ActionName == "stop_compilation") {
1586 O.indent(IndentLevel) << "stop_compilation = true;\n";
1588 else if (ActionName == "unpack_values") {
1589 checkNumberOfArguments(&Dag, 1);
1590 const std::string& Name = InitPtrToString(Dag.getArg(0));
1591 const OptionDescription& D = OptDescs.FindOption(Name);
1594 throw std::string("Can't use unpack_values with multi-valued options!");
1597 O.indent(IndentLevel)
1598 << "for (" << D.GenTypeDeclaration()
1599 << "::iterator B = " << D.GenVariableName() << ".begin(),\n";
1600 O.indent(IndentLevel)
1601 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n";
1602 O.indent(IndentLevel + Indent1)
1603 << "llvm::SplitString(*B, vec, \",\");\n";
1605 else if (D.isParameter()){
1606 O.indent(IndentLevel) << "llvm::SplitString("
1607 << D.GenVariableName() << ", vec, \",\");\n";
1610 throw "Option '" + D.Name +
1611 "': switches can't have the 'unpack_values' property!";
1615 throw "Unknown action name: " + ActionName + "!";
1619 EmitActionHandler(const OptionDescriptions& OD)
1622 void operator()(const Init* Statement, unsigned IndentLevel,
1623 raw_ostream& O) const
1625 if (typeid(*Statement) == typeid(ListInit)) {
1626 const ListInit& DagList = *static_cast<const ListInit*>(Statement);
1627 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1629 this->processActionDag(*B, IndentLevel, O);
1632 this->processActionDag(Statement, IndentLevel, O);
1637 bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
1639 TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
1641 for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
1643 if (*I == "$OUTFILE")
1650 class IsOutFileIndexCheckRequiredStrCallback {
1654 IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
1657 void operator()(const Init* CmdLine) {
1658 if (IsOutFileIndexCheckRequiredStr(CmdLine))
1663 bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
1665 WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
1669 /// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
1670 /// in EmitGenerateActionMethod() ?
1671 bool IsOutFileIndexCheckRequired (Init* CmdLine) {
1672 if (typeid(*CmdLine) == typeid(StringInit))
1673 return IsOutFileIndexCheckRequiredStr(CmdLine);
1675 return IsOutFileIndexCheckRequiredCase(CmdLine);
1678 // EmitGenerateActionMethod - Emit either a normal or a "join" version of the
1679 // Tool::GenerateAction() method.
1680 void EmitGenerateActionMethod (const ToolDescription& D,
1681 const OptionDescriptions& OptDescs,
1682 bool IsJoin, raw_ostream& O) {
1684 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1686 O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
1688 O.indent(Indent2) << "bool HasChildren,\n";
1689 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1690 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1691 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1692 O.indent(Indent1) << "{\n";
1693 O.indent(Indent2) << "std::string cmd;\n";
1694 O.indent(Indent2) << "std::vector<std::string> vec;\n";
1695 O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
1696 O.indent(Indent2) << "const char* output_suffix = \""
1697 << D.OutputSuffix << "\";\n";
1700 throw "Tool " + D.Name + " has no cmd_line property!";
1702 bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
1703 O.indent(Indent2) << "int out_file_index"
1704 << (IndexCheckRequired ? " = -1" : "")
1707 // Process the cmd_line property.
1708 if (typeid(*D.CmdLine) == typeid(StringInit))
1709 EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
1711 EmitCaseConstructHandler(D.CmdLine, Indent2,
1712 EmitCmdLineVecFillCallback(IsJoin, D.Name),
1715 // For every understood option, emit handling code.
1717 EmitCaseConstructHandler(D.Actions, Indent2, EmitActionHandler(OptDescs),
1718 false, OptDescs, O);
1722 << "std::string out_file = OutFilename("
1723 << (IsJoin ? "sys::Path(),\n" : "inFile,\n");
1724 O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
1726 if (IndexCheckRequired)
1727 O.indent(Indent2) << "if (out_file_index != -1)\n";
1728 O.indent(IndexCheckRequired ? Indent3 : Indent2)
1729 << "vec[out_file_index] = out_file;\n";
1731 // Handle the Sink property.
1733 O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
1734 O.indent(Indent3) << "vec.insert(vec.end(), "
1735 << SinkOptionName << ".begin(), " << SinkOptionName
1737 O.indent(Indent2) << "}\n";
1740 O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
1741 O.indent(Indent1) << "}\n\n";
1744 /// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1745 /// a given Tool class.
1746 void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
1747 const OptionDescriptions& OptDescs,
1749 if (!ToolDesc.isJoin()) {
1750 O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
1751 O.indent(Indent2) << "bool HasChildren,\n";
1752 O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
1753 O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
1754 O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
1755 O.indent(Indent1) << "{\n";
1756 O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
1757 << " is not a Join tool!\");\n";
1758 O.indent(Indent1) << "}\n\n";
1761 EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
1764 EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
1767 /// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1768 /// methods for a given Tool class.
1769 void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
1770 O.indent(Indent1) << "const char** InputLanguages() const {\n";
1771 O.indent(Indent2) << "return InputLanguages_;\n";
1772 O.indent(Indent1) << "}\n\n";
1774 if (D.OutLanguage.empty())
1775 throw "Tool " + D.Name + " has no 'out_language' property!";
1777 O.indent(Indent1) << "const char* OutputLanguage() const {\n";
1778 O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
1779 O.indent(Indent1) << "}\n\n";
1782 /// EmitNameMethod - Emit the Name() method for a given Tool class.
1783 void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
1784 O.indent(Indent1) << "const char* Name() const {\n";
1785 O.indent(Indent2) << "return \"" << D.Name << "\";\n";
1786 O.indent(Indent1) << "}\n\n";
1789 /// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1791 void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
1792 O.indent(Indent1) << "bool IsJoin() const {\n";
1794 O.indent(Indent2) << "return true;\n";
1796 O.indent(Indent2) << "return false;\n";
1797 O.indent(Indent1) << "}\n\n";
1800 /// EmitStaticMemberDefinitions - Emit static member definitions for a
1801 /// given Tool class.
1802 void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
1803 if (D.InLanguage.empty())
1804 throw "Tool " + D.Name + " has no 'in_language' property!";
1806 O << "const char* " << D.Name << "::InputLanguages_[] = {";
1807 for (StrVector::const_iterator B = D.InLanguage.begin(),
1808 E = D.InLanguage.end(); B != E; ++B)
1809 O << '\"' << *B << "\", ";
1813 /// EmitToolClassDefinition - Emit a Tool class definition.
1814 void EmitToolClassDefinition (const ToolDescription& D,
1815 const OptionDescriptions& OptDescs,
1817 if (D.Name == "root")
1821 O << "class " << D.Name << " : public ";
1827 O << "{\nprivate:\n";
1828 O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
1831 EmitNameMethod(D, O);
1832 EmitInOutLanguageMethods(D, O);
1833 EmitIsJoinMethod(D, O);
1834 EmitGenerateActionMethods(D, OptDescs, O);
1836 // Close class definition
1839 EmitStaticMemberDefinitions(D, O);
1843 /// EmitOptionDefinitions - Iterate over a list of option descriptions
1844 /// and emit registration code.
1845 void EmitOptionDefinitions (const OptionDescriptions& descs,
1846 bool HasSink, bool HasExterns,
1849 std::vector<OptionDescription> Aliases;
1851 // Emit static cl::Option variables.
1852 for (OptionDescriptions::const_iterator B = descs.begin(),
1853 E = descs.end(); B!=E; ++B) {
1854 const OptionDescription& val = B->second;
1856 if (val.Type == OptionType::Alias) {
1857 Aliases.push_back(val);
1864 O << val.GenTypeDeclaration() << ' '
1865 << val.GenVariableName();
1867 if (val.isExtern()) {
1872 O << "(\"" << val.Name << "\"\n";
1874 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1875 O << ", cl::Prefix";
1877 if (val.isRequired()) {
1878 if (val.isList() && !val.isMultiVal())
1879 O << ", cl::OneOrMore";
1881 O << ", cl::Required";
1883 else if (val.isOneOrMore() && val.isList()) {
1884 O << ", cl::OneOrMore";
1886 else if (val.isZeroOrOne() && val.isList()) {
1887 O << ", cl::ZeroOrOne";
1890 if (val.isReallyHidden()) {
1891 O << ", cl::ReallyHidden";
1893 else if (val.isHidden()) {
1894 O << ", cl::Hidden";
1897 if (val.MultiVal > 1)
1898 O << ", cl::multi_val(" << val.MultiVal << ')';
1901 const std::string& str = val.InitVal->getAsString();
1902 O << ", cl::init(" << str << ')';
1905 if (!val.Help.empty())
1906 O << ", cl::desc(\"" << val.Help << "\")";
1911 // Emit the aliases (they should go after all the 'proper' options).
1912 for (std::vector<OptionDescription>::const_iterator
1913 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1914 const OptionDescription& val = *B;
1916 O << val.GenTypeDeclaration() << ' '
1917 << val.GenVariableName()
1918 << "(\"" << val.Name << '\"';
1920 const OptionDescription& D = descs.FindOption(val.Help);
1921 O << ", cl::aliasopt(" << D.GenVariableName() << ")";
1923 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1926 // Emit the sink option.
1928 O << (HasExterns ? "extern cl" : "cl")
1929 << "::list<std::string> " << SinkOptionName
1930 << (HasExterns ? ";\n" : "(cl::Sink);\n");
1935 /// PreprocessOptionsCallback - Helper function passed to
1936 /// EmitCaseConstructHandler() by EmitPreprocessOptions().
1937 class PreprocessOptionsCallback {
1938 const OptionDescriptions& OptDescs_;
1940 void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
1941 const std::string& OptName = InitPtrToString(i);
1942 const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
1943 const OptionType::OptionType OptType = OptDesc.Type;
1945 if (OptType == OptionType::Switch) {
1946 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
1948 else if (OptType == OptionType::Parameter
1949 || OptType == OptionType::Prefix) {
1950 O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
1953 throw std::string("'unset_option' can only be applied to "
1954 "switches or parameter/prefix options.");
1958 void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
1960 const DagInit& d = InitPtrToDag(I);
1961 const std::string& OpName = d.getOperator()->getAsString();
1963 // TOFIX: there is some duplication between this function and
1964 // EmitActionHandler.
1965 if (OpName == "warning") {
1966 checkNumberOfArguments(&d, 1);
1967 O.indent(IndentLevel) << "llvm::errs() << \""
1968 << InitPtrToString(d.getArg(0)) << "\";\n";
1970 else if (OpName == "error") {
1971 checkNumberOfArguments(&d, 1);
1972 O.indent(IndentLevel) << "throw std::runtime_error(\""
1973 << InitPtrToString(d.getArg(0))
1976 else if (OpName == "unset_option") {
1977 checkNumberOfArguments(&d, 1);
1978 Init* I = d.getArg(0);
1979 if (typeid(*I) == typeid(ListInit)) {
1980 const ListInit& DagList = *static_cast<const ListInit*>(I);
1981 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
1983 this->onUnsetOption(*B, IndentLevel, O);
1986 this->onUnsetOption(I, IndentLevel, O);
1990 throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
1991 "\nOnly 'warning', 'error' and 'unset_option' are allowed.";
1997 // TODO: Remove duplication.
1998 void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
1999 if (typeid(*I) == typeid(ListInit)) {
2000 const ListInit& DagList = *static_cast<const ListInit*>(I);
2001 for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
2003 this->processDag(*B, IndentLevel, O);
2006 this->processDag(I, IndentLevel, O);
2010 PreprocessOptionsCallback(const OptionDescriptions& OptDescs)
2011 : OptDescs_(OptDescs)
2015 /// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
2016 void EmitPreprocessOptions (const RecordKeeper& Records,
2017 const OptionDescriptions& OptDecs, raw_ostream& O)
2019 O << "void PreprocessOptionsLocal() {\n";
2021 const RecordVector& OptionPreprocessors =
2022 Records.getAllDerivedDefinitions("OptionPreprocessor");
2024 for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
2025 E = OptionPreprocessors.end(); B!=E; ++B) {
2026 DagInit* Case = (*B)->getValueAsDag("preprocessor");
2027 EmitCaseConstructHandler(Case, Indent1, PreprocessOptionsCallback(OptDecs),
2034 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
2035 void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
2037 O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
2039 // Get the relevant field out of RecordKeeper
2040 const Record* LangMapRecord = Records.getDef("LanguageMap");
2042 // It is allowed for a plugin to have no language map.
2043 if (LangMapRecord) {
2045 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
2046 if (!LangsToSuffixesList)
2047 throw std::string("Error in the language map definition!");
2049 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
2050 const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
2052 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
2053 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
2055 for (unsigned i = 0; i < Suffixes->size(); ++i)
2056 O.indent(Indent1) << "langMap[\""
2057 << InitPtrToString(Suffixes->getElement(i))
2058 << "\"] = \"" << Lang << "\";\n";
2065 /// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
2066 /// by EmitEdgeClass().
2067 void IncDecWeight (const Init* i, unsigned IndentLevel,
2069 const DagInit& d = InitPtrToDag(i);
2070 const std::string& OpName = d.getOperator()->getAsString();
2072 if (OpName == "inc_weight") {
2073 O.indent(IndentLevel) << "ret += ";
2075 else if (OpName == "dec_weight") {
2076 O.indent(IndentLevel) << "ret -= ";
2078 else if (OpName == "error") {
2079 checkNumberOfArguments(&d, 1);
2080 O.indent(IndentLevel) << "throw std::runtime_error(\""
2081 << InitPtrToString(d.getArg(0))
2086 throw "Unknown operator in edge properties list: '" + OpName + "'!"
2087 "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
2090 if (d.getNumArgs() > 0)
2091 O << InitPtrToInt(d.getArg(0)) << ";\n";
2097 /// EmitEdgeClass - Emit a single Edge# class.
2098 void EmitEdgeClass (unsigned N, const std::string& Target,
2099 DagInit* Case, const OptionDescriptions& OptDescs,
2102 // Class constructor.
2103 O << "class Edge" << N << ": public Edge {\n"
2105 O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
2108 // Function Weight().
2110 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
2111 O.indent(Indent2) << "unsigned ret = 0;\n";
2113 // Handle the 'case' construct.
2114 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
2116 O.indent(Indent2) << "return ret;\n";
2117 O.indent(Indent1) << "};\n\n};\n\n";
2120 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
2121 void EmitEdgeClasses (const RecordVector& EdgeVector,
2122 const OptionDescriptions& OptDescs,
2125 for (RecordVector::const_iterator B = EdgeVector.begin(),
2126 E = EdgeVector.end(); B != E; ++B) {
2127 const Record* Edge = *B;
2128 const std::string& NodeB = Edge->getValueAsString("b");
2129 DagInit* Weight = Edge->getValueAsDag("weight");
2131 if (!isDagEmpty(Weight))
2132 EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
2137 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
2139 void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
2140 const ToolDescriptions& ToolDescs,
2143 O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
2145 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2146 E = ToolDescs.end(); B != E; ++B)
2147 O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
2154 for (RecordVector::const_iterator B = EdgeVector.begin(),
2155 E = EdgeVector.end(); B != E; ++B) {
2156 const Record* Edge = *B;
2157 const std::string& NodeA = Edge->getValueAsString("a");
2158 const std::string& NodeB = Edge->getValueAsString("b");
2159 DagInit* Weight = Edge->getValueAsDag("weight");
2161 O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
2163 if (isDagEmpty(Weight))
2164 O << "new SimpleEdge(\"" << NodeB << "\")";
2166 O << "new Edge" << i << "()";
2175 /// ExtractHookNames - Extract the hook names from all instances of
2176 /// $CALL(HookName) in the provided command line string. Helper
2177 /// function used by FillInHookNames().
2178 class ExtractHookNames {
2179 llvm::StringMap<unsigned>& HookNames_;
2181 ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
2182 : HookNames_(HookNames) {}
2184 void operator()(const Init* CmdLine) {
2186 TokenizeCmdline(InitPtrToString(CmdLine), cmds);
2187 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
2189 const std::string& cmd = *B;
2191 if (cmd == "$CALL") {
2192 unsigned NumArgs = 0;
2193 checkedIncrement(B, E, "Syntax error in $CALL invocation!");
2194 const std::string& HookName = *B;
2197 if (HookName.at(0) == ')')
2198 throw "$CALL invoked with no arguments!";
2200 while (++B != E && B->at(0) != ')') {
2204 StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
2206 if (H != HookNames_.end() && H->second != NumArgs)
2207 throw "Overloading of hooks is not allowed. Overloaded hook: "
2210 HookNames_[HookName] = NumArgs;
2217 /// FillInHookNames - Actually extract the hook names from all command
2218 /// line strings. Helper function used by EmitHookDeclarations().
2219 void FillInHookNames(const ToolDescriptions& ToolDescs,
2220 llvm::StringMap<unsigned>& HookNames)
2222 // For all command lines:
2223 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2224 E = ToolDescs.end(); B != E; ++B) {
2225 const ToolDescription& D = *(*B);
2228 if (dynamic_cast<StringInit*>(D.CmdLine))
2229 // This is a string.
2230 ExtractHookNames(HookNames).operator()(D.CmdLine);
2232 // This is a 'case' construct.
2233 WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
2237 /// EmitHookDeclarations - Parse CmdLine fields of all the tool
2238 /// property records and emit hook function declaration for each
2239 /// instance of $CALL(HookName).
2240 void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
2241 llvm::StringMap<unsigned> HookNames;
2243 FillInHookNames(ToolDescs, HookNames);
2244 if (HookNames.empty())
2247 O << "namespace hooks {\n";
2248 for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
2249 E = HookNames.end(); B != E; ++B) {
2250 O.indent(Indent1) << "std::string " << B->first() << "(";
2252 for (unsigned i = 0, j = B->second; i < j; ++i) {
2253 O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
2261 /// EmitRegisterPlugin - Emit code to register this plugin.
2262 void EmitRegisterPlugin(int Priority, raw_ostream& O) {
2263 O << "struct Plugin : public llvmc::BasePlugin {\n\n";
2264 O.indent(Indent1) << "int Priority() const { return "
2265 << Priority << "; }\n\n";
2266 O.indent(Indent1) << "void PreprocessOptions() const\n";
2267 O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
2268 O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
2269 O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
2271 << "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
2272 O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
2274 << "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
2277 /// EmitIncludes - Emit necessary #include directives and some
2278 /// additional declarations.
2279 void EmitIncludes(raw_ostream& O) {
2280 O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
2281 << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
2282 << "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
2283 << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
2284 << "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
2286 << "#include \"llvm/ADT/StringExtras.h\"\n"
2287 << "#include \"llvm/Support/CommandLine.h\"\n"
2288 << "#include \"llvm/Support/raw_ostream.h\"\n\n"
2290 << "#include <cstdlib>\n"
2291 << "#include <stdexcept>\n\n"
2293 << "using namespace llvm;\n"
2294 << "using namespace llvmc;\n\n"
2296 << "extern cl::opt<std::string> OutputFilename;\n\n"
2298 << "inline const char* checkCString(const char* s)\n"
2299 << "{ return s == NULL ? \"\" : s; }\n\n";
2303 /// PluginData - Holds all information about a plugin.
2305 OptionDescriptions OptDescs;
2308 ToolDescriptions ToolDescs;
2313 /// HasSink - Go through the list of tool descriptions and check if
2314 /// there are any with the 'sink' property set.
2315 bool HasSink(const ToolDescriptions& ToolDescs) {
2316 for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
2317 E = ToolDescs.end(); B != E; ++B)
2324 /// HasExterns - Go through the list of option descriptions and check
2325 /// if there are any external options.
2326 bool HasExterns(const OptionDescriptions& OptDescs) {
2327 for (OptionDescriptions::const_iterator B = OptDescs.begin(),
2328 E = OptDescs.end(); B != E; ++B)
2329 if (B->second.isExtern())
2335 /// CollectPluginData - Collect tool and option properties,
2336 /// compilation graph edges and plugin priority from the parse tree.
2337 void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
2338 // Collect option properties.
2339 const RecordVector& OptionLists =
2340 Records.getAllDerivedDefinitions("OptionList");
2341 CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
2344 // Collect tool properties.
2345 const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
2346 CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
2347 Data.HasSink = HasSink(Data.ToolDescs);
2348 Data.HasExterns = HasExterns(Data.OptDescs);
2350 // Collect compilation graph edges.
2351 const RecordVector& CompilationGraphs =
2352 Records.getAllDerivedDefinitions("CompilationGraph");
2353 FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
2356 // Calculate the priority of this plugin.
2357 const RecordVector& Priorities =
2358 Records.getAllDerivedDefinitions("PluginPriority");
2359 Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
2362 /// CheckPluginData - Perform some sanity checks on the collected data.
2363 void CheckPluginData(PluginData& Data) {
2364 // Filter out all tools not mentioned in the compilation graph.
2365 FilterNotInGraph(Data.Edges, Data.ToolDescs);
2367 // Typecheck the compilation graph.
2368 TypecheckGraph(Data.Edges, Data.ToolDescs);
2370 // Check that there are no options without side effects (specified
2371 // only in the OptionList).
2372 CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
2376 void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
2377 // Emit file header.
2380 // Emit global option registration code.
2381 EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
2383 // Emit hook declarations.
2384 EmitHookDeclarations(Data.ToolDescs, O);
2386 O << "namespace {\n\n";
2388 // Emit PreprocessOptionsLocal() function.
2389 EmitPreprocessOptions(Records, Data.OptDescs, O);
2391 // Emit PopulateLanguageMapLocal() function
2392 // (language map maps from file extensions to language names).
2393 EmitPopulateLanguageMap(Records, O);
2395 // Emit Tool classes.
2396 for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
2397 E = Data.ToolDescs.end(); B!=E; ++B)
2398 EmitToolClassDefinition(*(*B), Data.OptDescs, O);
2400 // Emit Edge# classes.
2401 EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
2403 // Emit PopulateCompilationGraphLocal() function.
2404 EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
2406 // Emit code for plugin registration.
2407 EmitRegisterPlugin(Data.Priority, O);
2409 O << "} // End anonymous namespace.\n\n";
2411 // Force linkage magic.
2412 O << "namespace llvmc {\n";
2413 O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
2420 // End of anonymous namespace
2423 /// run - The back-end entry point.
2424 void LLVMCConfigurationEmitter::run (raw_ostream &O) {
2428 CollectPluginData(Records, Data);
2429 CheckPluginData(Data);
2431 EmitSourceFileHeader("LLVMC Configuration Library", O);
2432 EmitPluginCode(Data, O);
2434 } catch (std::exception& Error) {
2435 throw Error.what() + std::string(" - usually this means a syntax error.");