blob: 15803f244f8545fc59e65355d261d28001a88096 [file] [log] [blame]
Mikhail Glushenkov2d3327f2008-05-30 06:20:54 +00001//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open
6// Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Mikhail Glushenkov34307a92008-05-06 18:08:59 +000010// This tablegen backend is responsible for emitting LLVMC configuration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000011//
12//===----------------------------------------------------------------------===//
13
Mikhail Glushenkov41405722008-05-06 18:09:29 +000014#include "LLVMCConfigurationEmitter.h"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000015#include "Record.h"
16
17#include "llvm/ADT/IntrusiveRefCntPtr.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringMap.h"
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +000021#include "llvm/ADT/StringSet.h"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000022#include "llvm/Support/Streams.h"
23
24#include <algorithm>
25#include <cassert>
26#include <functional>
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +000027#include <stdexcept>
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000028#include <string>
29
30using namespace llvm;
31
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +000032namespace {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000033
34//===----------------------------------------------------------------------===//
35/// Typedefs
36
37typedef std::vector<Record*> RecordVector;
38typedef std::vector<std::string> StrVector;
39
40//===----------------------------------------------------------------------===//
41/// Constants
42
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000043// Indentation strings.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000044const char * Indent1 = " ";
45const char * Indent2 = " ";
46const char * Indent3 = " ";
47const char * Indent4 = " ";
48
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000049// Default help string.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000050const char * DefaultHelpString = "NO HELP MESSAGE PROVIDED";
51
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000052// Name for the "sink" option.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000053const char * SinkOptionName = "AutoGeneratedSinkOption";
54
55//===----------------------------------------------------------------------===//
56/// Helper functions
57
Mikhail Glushenkov35576b02008-05-30 06:10:19 +000058int InitPtrToInt(const Init* ptr) {
59 const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +000060 return val.getValue();
61}
62
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +000063const std::string& InitPtrToString(const Init* ptr) {
64 const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
65 return val.getValue();
66}
67
68const ListInit& InitPtrToList(const Init* ptr) {
69 const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
70 return val;
71}
72
73const DagInit& InitPtrToDag(const Init* ptr) {
Mikhail Glushenkov35576b02008-05-30 06:10:19 +000074 const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +000075 return val;
76}
77
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +000078// checkNumberOfArguments - Ensure that the number of args in d is
Mikhail Glushenkovdedba642008-05-30 06:08:50 +000079// less than or equal to min_arguments, otherwise throw an exception.
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +000080void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
81 if (d->getNumArgs() < min_arguments)
82 throw "Property " + d->getOperator()->getAsString()
83 + " has too few arguments!";
84}
85
Mikhail Glushenkovdedba642008-05-30 06:08:50 +000086// isDagEmpty - is this DAG marked with an empty marker?
87bool isDagEmpty (const DagInit* d) {
88 return d->getOperator()->getAsString() == "empty";
89}
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +000090
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000091//===----------------------------------------------------------------------===//
92/// Back-end specific code
93
94// A command-line option can have one of the following types:
95//
Mikhail Glushenkovb623c322008-05-30 06:22:52 +000096// Alias - an alias for another option.
97//
98// Switch - a simple switch without arguments, e.g. -O2
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +000099//
100// Parameter - an option that takes one(and only one) argument, e.g. -o file,
101// --output=file
102//
103// ParameterList - same as Parameter, but more than one occurence
104// of the option is allowed, e.g. -lm -lpthread
105//
106// Prefix - argument is everything after the prefix,
107// e.g. -Wa,-foo,-bar, -DNAME=VALUE
108//
109// PrefixList - same as Prefix, but more than one option occurence is
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000110// allowed.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000111
112namespace OptionType {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000113 enum OptionType { Alias, Switch,
114 Parameter, ParameterList, Prefix, PrefixList};
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000115}
116
117bool IsListOptionType (OptionType::OptionType t) {
118 return (t == OptionType::ParameterList || t == OptionType::PrefixList);
119}
120
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.
126
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000127/// OptionDescription - Base class for option descriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000128struct OptionDescription {
129 OptionType::OptionType Type;
130 std::string Name;
131
132 OptionDescription(OptionType::OptionType t = OptionType::Switch,
133 const std::string& n = "")
134 : Type(t), Name(n)
135 {}
136
137 const char* GenTypeDeclaration() const {
138 switch (Type) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000139 case OptionType::Alias:
140 return "cl::alias";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000141 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:
148 default:
149 return "cl::opt<std::string>";
150 }
151 }
152
Mikhail Glushenkov4019e952008-05-12 16:33:06 +0000153 // 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 {
157 std::string ret;
158 for (unsigned i = 0; i != Var.size(); ++i) {
159 if (Var[i] == ',') {
160 ret += "_comma_";
161 }
162 else {
163 ret.push_back(Var[i]);
164 }
165 }
166 return ret;
167 }
168
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000169 std::string GenVariableName() const {
Mikhail Glushenkov4019e952008-05-12 16:33:06 +0000170 const std::string& EscapedName = EscapeVariableName(Name);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000171 switch (Type) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000172 case OptionType::Alias:
173 return "AutoGeneratedAlias" + EscapedName;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000174 case OptionType::Switch:
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000175 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:
183 default:
184 return "AutoGeneratedParameterList" + EscapedName;
185 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000186 }
187
188};
189
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000190// Global option description.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000191
192namespace GlobalOptionDescriptionFlags {
193 enum GlobalOptionDescriptionFlags { Required = 0x1 };
194}
195
196struct GlobalOptionDescription : public OptionDescription {
197 std::string Help;
198 unsigned Flags;
199
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000200 // We need to provide a default constructor because
201 // StringMap can only store DefaultConstructible objects.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000202 GlobalOptionDescription() : OptionDescription(), Flags(0)
203 {}
204
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000205 GlobalOptionDescription (OptionType::OptionType t, const std::string& n,
206 const std::string& h = DefaultHelpString)
207 : OptionDescription(t, n), Help(h), Flags(0)
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000208 {}
209
210 bool isRequired() const {
211 return Flags & GlobalOptionDescriptionFlags::Required;
212 }
213 void setRequired() {
214 Flags |= GlobalOptionDescriptionFlags::Required;
215 }
216
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000217 /// Merge - Merge two option descriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000218 void Merge (const GlobalOptionDescription& other)
219 {
220 if (other.Type != Type)
221 throw "Conflicting definitions for the option " + Name + "!";
222
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000223 if (Help == DefaultHelpString)
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000224 Help = other.Help;
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000225 else if (other.Help != DefaultHelpString) {
226 llvm::cerr << "Warning: more than one help string defined for option "
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000227 + Name + "\n";
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000228 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000229
230 Flags |= other.Flags;
231 }
232};
233
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000234/// GlobalOptionDescriptions - A GlobalOptionDescription array
235/// together with some flags affecting generation of option
236/// declarations.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000237struct GlobalOptionDescriptions {
238 typedef StringMap<GlobalOptionDescription> container_type;
239 typedef container_type::const_iterator const_iterator;
240
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000241 /// Descriptions - A list of GlobalOptionDescriptions.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000242 container_type Descriptions;
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000243 /// HasSink - Should the emitter generate a "cl::sink" option?
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000244 bool HasSink;
245
Mikhail Glushenkove5fcb552008-05-30 06:28:37 +0000246 /// FindOption - exception-throwing wrapper for find().
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +0000247 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
248 const_iterator I = Descriptions.find(OptName);
249 if (I != Descriptions.end())
250 return I->second;
251 else
252 throw OptName + ": no such option!";
253 }
254
Mikhail Glushenkove5fcb552008-05-30 06:28:37 +0000255 /// insertDescription - Insert new GlobalOptionDescription into
256 /// GlobalOptionDescriptions list
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000257 void insertDescription (const GlobalOptionDescription& o)
258 {
259 container_type::iterator I = Descriptions.find(o.Name);
260 if (I != Descriptions.end()) {
261 GlobalOptionDescription& D = I->second;
262 D.Merge(o);
263 }
264 else {
265 Descriptions[o.Name] = o;
266 }
267 }
268
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000269 // Support for STL-style iteration
270 const_iterator begin() const { return Descriptions.begin(); }
271 const_iterator end() const { return Descriptions.end(); }
272};
273
274
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000275// Tool-local option description.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000276
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000277// Properties without arguments are implemented as flags.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000278namespace ToolOptionDescriptionFlags {
279 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
280 Forward = 0x2, UnpackValues = 0x4};
281}
282namespace OptionPropertyType {
Mikhail Glushenkovabab33b2008-05-30 06:13:02 +0000283 enum OptionPropertyType { AppendCmd, OutputSuffix };
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000284}
285
286typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
287OptionProperty;
288typedef SmallVector<OptionProperty, 4> OptionPropertyList;
289
290struct ToolOptionDescription : public OptionDescription {
291 unsigned Flags;
292 OptionPropertyList Props;
293
294 // StringMap can only store DefaultConstructible objects
Mikhail Glushenkov18cbe892008-03-27 09:53:47 +0000295 ToolOptionDescription() : OptionDescription(), Flags(0) {}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000296
297 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
298 : OptionDescription(t, n)
299 {}
300
301 // Various boolean properties
302 bool isStopCompilation() const {
303 return Flags & ToolOptionDescriptionFlags::StopCompilation;
304 }
305 void setStopCompilation() {
306 Flags |= ToolOptionDescriptionFlags::StopCompilation;
307 }
308
309 bool isForward() const {
310 return Flags & ToolOptionDescriptionFlags::Forward;
311 }
312 void setForward() {
313 Flags |= ToolOptionDescriptionFlags::Forward;
314 }
315
316 bool isUnpackValues() const {
317 return Flags & ToolOptionDescriptionFlags::UnpackValues;
318 }
319 void setUnpackValues() {
320 Flags |= ToolOptionDescriptionFlags::UnpackValues;
321 }
322
323 void AddProperty (OptionPropertyType::OptionPropertyType t,
324 const std::string& val)
325 {
326 Props.push_back(std::make_pair(t, val));
327 }
328};
329
330typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
331
332// Tool information record
333
334namespace ToolFlags {
335 enum ToolFlags { Join = 0x1, Sink = 0x2 };
336}
337
338struct ToolProperties : public RefCountedBase<ToolProperties> {
339 std::string Name;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000340 Init* CmdLine;
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000341 StrVector InLanguage;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000342 std::string OutLanguage;
343 std::string OutputSuffix;
344 unsigned Flags;
345 ToolOptionDescriptions OptDescs;
346
347 // Various boolean properties
348 void setSink() { Flags |= ToolFlags::Sink; }
349 bool isSink() const { return Flags & ToolFlags::Sink; }
350 void setJoin() { Flags |= ToolFlags::Join; }
351 bool isJoin() const { return Flags & ToolFlags::Join; }
352
353 // Default ctor here is needed because StringMap can only store
354 // DefaultConstructible objects
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000355 ToolProperties() : Flags(0) {}
356 ToolProperties (const std::string& n) : Name(n), Flags(0) {}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000357};
358
359
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000360/// ToolPropertiesList - A list of Tool information records
361/// IntrusiveRefCntPtrs are used here because StringMap has no copy
362/// constructor (and we want to avoid copying ToolProperties anyway).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000363typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
364
365
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000366/// CollectOptionProperties - Function object for iterating over a
367/// list (usually, a DAG) of option property records.
368class CollectOptionProperties {
369private:
370 // Implementation details.
371
372 /// OptionPropertyHandler - a function that extracts information
373 /// about a given option property from its DAG representation.
374 typedef void (CollectOptionProperties::* OptionPropertyHandler)
375 (const DagInit*);
376
377 /// OptionPropertyHandlerMap - A map from option property names to
378 /// option property handlers
379 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
380
381 static OptionPropertyHandlerMap optionPropertyHandlers_;
382 static bool staticMembersInitialized_;
383
384 /// This is where the information is stored
385
386 /// toolProps_ - Properties of the current Tool.
387 ToolProperties* toolProps_;
388 /// optDescs_ - OptionDescriptions table (used to register options
389 /// globally).
390 GlobalOptionDescription& optDesc_;
391
392public:
393
394 explicit CollectOptionProperties(ToolProperties* TP,
395 GlobalOptionDescription& OD)
396 : toolProps_(TP), optDesc_(OD)
397 {
398 if (!staticMembersInitialized_) {
399 optionPropertyHandlers_["append_cmd"] =
400 &CollectOptionProperties::onAppendCmd;
401 optionPropertyHandlers_["forward"] =
402 &CollectOptionProperties::onForward;
403 optionPropertyHandlers_["help"] =
404 &CollectOptionProperties::onHelp;
405 optionPropertyHandlers_["output_suffix"] =
406 &CollectOptionProperties::onOutputSuffix;
407 optionPropertyHandlers_["required"] =
408 &CollectOptionProperties::onRequired;
409 optionPropertyHandlers_["stop_compilation"] =
410 &CollectOptionProperties::onStopCompilation;
411 optionPropertyHandlers_["unpack_values"] =
412 &CollectOptionProperties::onUnpackValues;
413
414 staticMembersInitialized_ = true;
415 }
416 }
417
418 /// operator() - Gets called for every option property; Just forwards
419 /// to the corresponding property handler.
420 void operator() (Init* i) {
421 const DagInit& option_property = InitPtrToDag(i);
422 const std::string& option_property_name
423 = option_property.getOperator()->getAsString();
424 OptionPropertyHandlerMap::iterator method
425 = optionPropertyHandlers_.find(option_property_name);
426
427 if (method != optionPropertyHandlers_.end()) {
428 OptionPropertyHandler h = method->second;
429 (this->*h)(&option_property);
430 }
431 else {
432 throw "Unknown option property: " + option_property_name + "!";
433 }
434 }
435
436private:
437
438 /// Option property handlers --
439 /// Methods that handle properties that are common for all types of
440 /// options (like append_cmd, stop_compilation)
441
442 void onAppendCmd (const DagInit* d) {
443 checkNumberOfArguments(d, 1);
444 checkToolProps(d);
445 const std::string& cmd = InitPtrToString(d->getArg(0));
446
447 toolProps_->OptDescs[optDesc_.Name].
448 AddProperty(OptionPropertyType::AppendCmd, cmd);
449 }
450
451 void onOutputSuffix (const DagInit* d) {
452 checkNumberOfArguments(d, 1);
453 checkToolProps(d);
454 const std::string& suf = InitPtrToString(d->getArg(0));
455
456 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
457 throw "Option " + optDesc_.Name
458 + " can't have 'output_suffix' property since it isn't a switch!";
459
460 toolProps_->OptDescs[optDesc_.Name].AddProperty
461 (OptionPropertyType::OutputSuffix, suf);
462 }
463
464 void onForward (const DagInit* d) {
465 checkNumberOfArguments(d, 0);
466 checkToolProps(d);
467 toolProps_->OptDescs[optDesc_.Name].setForward();
468 }
469
470 void onHelp (const DagInit* d) {
471 checkNumberOfArguments(d, 1);
472 const std::string& help_message = InitPtrToString(d->getArg(0));
473
474 optDesc_.Help = help_message;
475 }
476
477 void onRequired (const DagInit* d) {
478 checkNumberOfArguments(d, 0);
479 checkToolProps(d);
480 optDesc_.setRequired();
481 }
482
483 void onStopCompilation (const DagInit* d) {
484 checkNumberOfArguments(d, 0);
485 checkToolProps(d);
486 if (optDesc_.Type != OptionType::Switch)
487 throw std::string("Only options of type Switch can stop compilation!");
488 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
489 }
490
491 void onUnpackValues (const DagInit* d) {
492 checkNumberOfArguments(d, 0);
493 checkToolProps(d);
494 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
495 }
496
497 // Helper functions
498
499 /// checkToolProps - Throw an error if toolProps_ == 0.
500 void checkToolProps(const DagInit* d) {
501 if (!d)
502 throw "Option property " + d->getOperator()->getAsString()
503 + " can't be used in this context";
504 }
505
506};
507
508CollectOptionProperties::OptionPropertyHandlerMap
509CollectOptionProperties::optionPropertyHandlers_;
510
511bool CollectOptionProperties::staticMembersInitialized_ = false;
512
513
514/// processOptionProperties - Go through the list of option
515/// properties and call a corresponding handler for each.
516void processOptionProperties (const DagInit* d, ToolProperties* t,
517 GlobalOptionDescription& o) {
518 checkNumberOfArguments(d, 2);
519 DagInit::const_arg_iterator B = d->arg_begin();
520 // Skip the first argument: it's always the option name.
521 ++B;
522 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
523}
524
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000525/// AddOption - A function object wrapper for
526/// processOptionProperties. Used by CollectProperties and
527/// CollectPropertiesFromOptionList.
528class AddOption {
529private:
530 GlobalOptionDescriptions& OptDescs_;
531 ToolProperties* ToolProps_;
532
533public:
534 explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
535 : OptDescs_(OD), ToolProps_(TP)
536 {}
537
538 void operator()(const Init* i) {
539 const DagInit& d = InitPtrToDag(i);
540 checkNumberOfArguments(&d, 2);
541
542 const OptionType::OptionType Type =
543 getOptionType(d.getOperator()->getAsString());
544 const std::string& Name = InitPtrToString(d.getArg(0));
545
546 GlobalOptionDescription OD(Type, Name);
547 if (Type != OptionType::Alias) {
548 processOptionProperties(&d, ToolProps_, OD);
549 if (ToolProps_) {
550 ToolProps_->OptDescs[Name].Type = Type;
551 ToolProps_->OptDescs[Name].Name = Name;
552 }
553 }
554 else {
555 OD.Help = InitPtrToString(d.getArg(1));
556 }
557 OptDescs_.insertDescription(OD);
558 }
559
560private:
561 OptionType::OptionType getOptionType(const std::string& T) const {
562 if (T == "alias_option")
563 return OptionType::Alias;
564 else if (T == "switch_option")
565 return OptionType::Switch;
566 else if (T == "parameter_option")
567 return OptionType::Parameter;
568 else if (T == "parameter_list_option")
569 return OptionType::ParameterList;
570 else if (T == "prefix_option")
571 return OptionType::Prefix;
572 else if (T == "prefix_list_option")
573 return OptionType::PrefixList;
574 else
575 throw "Unknown option type: " + T + '!';
576 }
577};
578
579
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000580/// CollectProperties - Function object for iterating over a list of
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000581/// tool property records.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000582class CollectProperties {
583private:
584
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000585 // Implementation details
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000586
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000587 /// PropertyHandler - a function that extracts information
588 /// about a given tool property from its DAG representation
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000589 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000590
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000591 /// PropertyHandlerMap - A map from property names to property
592 /// handlers.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000593 typedef StringMap<PropertyHandler> PropertyHandlerMap;
594
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000595 // Static maps from strings to CollectProperties methods("handlers")
596 static PropertyHandlerMap propertyHandlers_;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000597 static bool staticMembersInitialized_;
598
599
600 /// This is where the information is stored
601
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000602 /// toolProps_ - Properties of the current Tool.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000603 ToolProperties& toolProps_;
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000604 /// optDescs_ - OptionDescriptions table (used to register options
605 /// globally).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000606 GlobalOptionDescriptions& optDescs_;
607
608public:
609
610 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
611 : toolProps_(p), optDescs_(d)
612 {
613 if (!staticMembersInitialized_) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000614 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
615 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
616 propertyHandlers_["join"] = &CollectProperties::onJoin;
617 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
618 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
619 propertyHandlers_["parameter_option"]
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000620 = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000621 propertyHandlers_["parameter_list_option"] =
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000622 &CollectProperties::addOption;
623 propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000624 propertyHandlers_["prefix_list_option"] =
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000625 &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000626 propertyHandlers_["sink"] = &CollectProperties::onSink;
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000627 propertyHandlers_["switch_option"] = &CollectProperties::addOption;
628 propertyHandlers_["alias_option"] = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000629
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000630 staticMembersInitialized_ = true;
631 }
632 }
633
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000634 /// operator() - Gets called for every tool property; Just forwards
635 /// to the corresponding property handler.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000636 void operator() (Init* i) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000637 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +0000638 const std::string& property_name = d.getOperator()->getAsString();
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000639 PropertyHandlerMap::iterator method
640 = propertyHandlers_.find(property_name);
641
642 if (method != propertyHandlers_.end()) {
643 PropertyHandler h = method->second;
644 (this->*h)(&d);
645 }
646 else {
647 throw "Unknown tool property: " + property_name + "!";
648 }
649 }
650
651private:
652
653 /// Property handlers --
654 /// Functions that extract information about tool properties from
655 /// DAG representation.
656
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000657 void onCmdLine (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000658 checkNumberOfArguments(d, 1);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000659 toolProps_.CmdLine = d->getArg(0);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000660 }
661
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000662 void onInLanguage (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000663 checkNumberOfArguments(d, 1);
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000664 Init* arg = d->getArg(0);
665
666 // Find out the argument's type.
667 if (typeid(*arg) == typeid(StringInit)) {
668 // It's a string.
669 toolProps_.InLanguage.push_back(InitPtrToString(arg));
670 }
671 else {
672 // It's a list.
673 const ListInit& lst = InitPtrToList(arg);
674 StrVector& out = toolProps_.InLanguage;
675
676 // Copy strings to the output vector.
677 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
678 B != E; ++B) {
679 out.push_back(InitPtrToString(*B));
680 }
681
682 // Remove duplicates.
683 std::sort(out.begin(), out.end());
684 StrVector::iterator newE = std::unique(out.begin(), out.end());
685 out.erase(newE, out.end());
686 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000687 }
688
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000689 void onJoin (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000690 checkNumberOfArguments(d, 0);
691 toolProps_.setJoin();
692 }
693
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000694 void onOutLanguage (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000695 checkNumberOfArguments(d, 1);
696 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
697 }
698
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000699 void onOutputSuffix (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000700 checkNumberOfArguments(d, 1);
701 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
702 }
703
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000704 void onSink (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000705 checkNumberOfArguments(d, 0);
706 optDescs_.HasSink = true;
707 toolProps_.setSink();
708 }
709
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000710 // Just forwards to the AddOption function object. Somewhat
711 // non-optimal, but avoids code duplication.
712 void addOption (const DagInit* d) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000713 checkNumberOfArguments(d, 2);
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000714 AddOption(optDescs_, &toolProps_)(d);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000715 }
716
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000717};
718
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000719// Defintions of static members of CollectProperties.
720CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000721bool CollectProperties::staticMembersInitialized_ = false;
722
723
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000724/// CollectToolProperties - Gather information about tool properties
725/// from the parsed TableGen data (basically a wrapper for the
726/// CollectProperties function object).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000727void CollectToolProperties (RecordVector::const_iterator B,
728 RecordVector::const_iterator E,
729 ToolPropertiesList& TPList,
730 GlobalOptionDescriptions& OptDescs)
731{
732 // Iterate over a properties list of every Tool definition
733 for (;B!=E;++B) {
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000734 Record* T = *B;
735 // Throws an exception if the value does not exist.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000736 ListInit* PropList = T->getValueAsListInit("properties");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000737
738 IntrusiveRefCntPtr<ToolProperties>
739 ToolProps(new ToolProperties(T->getName()));
740
741 std::for_each(PropList->begin(), PropList->end(),
742 CollectProperties(*ToolProps, OptDescs));
743 TPList.push_back(ToolProps);
744 }
745}
746
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000747
748/// CollectPropertiesFromOptionList - Gather information about
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000749/// *global* option properties from the OptionList.
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000750void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
751 RecordVector::const_iterator E,
752 GlobalOptionDescriptions& OptDescs)
753{
754 // Iterate over a properties list of every Tool definition
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000755 for (;B!=E;++B) {
756 RecordVector::value_type T = *B;
757 // Throws an exception if the value does not exist.
758 ListInit* PropList = T->getValueAsListInit("options");
759
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000760 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000761 }
762}
763
Mikhail Glushenkove5fcb552008-05-30 06:28:37 +0000764/// CheckForSuperfluousOptions - Check that there are no side
765/// effect-free options (specified only in the OptionList). Otherwise,
766/// output a warning.
767void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
768 const GlobalOptionDescriptions& OptDescs) {
769 llvm::StringSet<> nonSuperfluousOptions;
770
771 // Add all options mentioned in the TPList to the set of
772 // non-superfluous options.
773 for (ToolPropertiesList::const_iterator B = TPList.begin(),
774 E = TPList.end(); B != E; ++B) {
775 const ToolProperties& TP = *(*B);
776 for (ToolOptionDescriptions::const_iterator B = TP.OptDescs.begin(),
777 E = TP.OptDescs.end(); B != E; ++B) {
778 nonSuperfluousOptions.insert(B->first());
779 }
780 }
781
782 // Check that all options in OptDescs belong to the set of
783 // non-superfluous options.
784 for (GlobalOptionDescriptions::const_iterator B = OptDescs.begin(),
785 E = OptDescs.end(); B != E; ++B) {
786 const GlobalOptionDescription& Val = B->second;
787 if (!nonSuperfluousOptions.count(Val.Name)
788 && Val.Type != OptionType::Alias)
789 cerr << "Warning: option '-" << Val.Name << "' has no effect! "
790 "Probable cause: this option is specified only in the OptionList.\n";
791 }
792}
793
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000794/// EmitCaseTest1Arg - Helper function used by
795/// EmitCaseConstructHandler.
796bool EmitCaseTest1Arg(const std::string& TestName,
797 const DagInit& d,
798 const GlobalOptionDescriptions& OptDescs,
799 std::ostream& O) {
Mikhail Glushenkove5fcb552008-05-30 06:28:37 +0000800 // TOFIX - Add a mechanism for OS detection.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000801 checkNumberOfArguments(&d, 1);
802 const std::string& OptName = InitPtrToString(d.getArg(0));
803 if (TestName == "switch_on") {
804 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
805 if (OptDesc.Type != OptionType::Switch)
806 throw OptName + ": incorrect option type!";
807 O << OptDesc.GenVariableName();
808 return true;
809 } else if (TestName == "input_languages_contain") {
810 O << "InLangs.count(\"" << OptName << "\") != 0";
811 return true;
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +0000812 } else if (TestName == "in_language") {
813 // Works only for cmd_line!
814 O << "GetLanguage(inFile) == \"" << OptName << '\"';
815 return true;
816 } else if (TestName == "not_empty") {
Mikhail Glushenkovb4833872008-05-30 06:24:07 +0000817 if (OptName == "o") {
818 O << "!OutputFilename.empty()";
819 return true;
820 }
821 else {
822 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
823 if (OptDesc.Type == OptionType::Switch)
824 throw OptName + ": incorrect option type!";
825 O << '!' << OptDesc.GenVariableName() << ".empty()";
826 return true;
827 }
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000828 }
829
830 return false;
831}
832
833/// EmitCaseTest2Args - Helper function used by
834/// EmitCaseConstructHandler.
835bool EmitCaseTest2Args(const std::string& TestName,
836 const DagInit& d,
837 const char* IndentLevel,
838 const GlobalOptionDescriptions& OptDescs,
839 std::ostream& O) {
840 checkNumberOfArguments(&d, 2);
841 const std::string& OptName = InitPtrToString(d.getArg(0));
842 const std::string& OptArg = InitPtrToString(d.getArg(1));
843 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
844
845 if (TestName == "parameter_equals") {
846 if (OptDesc.Type != OptionType::Parameter
847 && OptDesc.Type != OptionType::Prefix)
848 throw OptName + ": incorrect option type!";
849 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
850 return true;
851 }
852 else if (TestName == "element_in_list") {
853 if (OptDesc.Type != OptionType::ParameterList
854 && OptDesc.Type != OptionType::PrefixList)
855 throw OptName + ": incorrect option type!";
856 const std::string& VarName = OptDesc.GenVariableName();
857 O << "std::find(" << VarName << ".begin(),\n"
858 << IndentLevel << Indent1 << VarName << ".end(), \""
859 << OptArg << "\") != " << VarName << ".end()";
860 return true;
861 }
862
863 return false;
864}
865
866// Forward declaration.
867// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
868void EmitCaseTest(const DagInit& d, const char* IndentLevel,
869 const GlobalOptionDescriptions& OptDescs,
870 std::ostream& O);
871
872/// EmitLogicalOperationTest - Helper function used by
873/// EmitCaseConstructHandler.
874void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
875 const char* IndentLevel,
876 const GlobalOptionDescriptions& OptDescs,
877 std::ostream& O) {
878 O << '(';
879 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000880 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000881 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
882 if (j != NumArgs - 1)
883 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
884 else
885 O << ')';
886 }
887}
888
889/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
890void EmitCaseTest(const DagInit& d, const char* IndentLevel,
891 const GlobalOptionDescriptions& OptDescs,
892 std::ostream& O) {
893 const std::string& TestName = d.getOperator()->getAsString();
894
895 if (TestName == "and")
896 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
897 else if (TestName == "or")
898 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
899 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
900 return;
901 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
902 return;
903 else
904 throw TestName + ": unknown edge property!";
905}
906
907// Emit code that handles the 'case' construct.
908// Takes a function object that should emit code for every case clause.
909// Callback's type is
910// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
911template <typename F>
912void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
Mikhail Glushenkov1d95e9f2008-05-31 13:43:21 +0000913 F Callback, bool EmitElseIf,
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000914 const GlobalOptionDescriptions& OptDescs,
915 std::ostream& O) {
916 assert(d->getOperator()->getAsString() == "case");
917
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000918 unsigned numArgs = d->getNumArgs();
919 if (d->getNumArgs() < 2)
920 throw "There should be at least one clause in the 'case' expression:\n"
921 + d->getAsString();
922
923 for (unsigned i = 0; i != numArgs; ++i) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000924 const DagInit& Test = InitPtrToDag(d->getArg(i));
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000925
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000926 // Emit the test.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000927 if (Test.getOperator()->getAsString() == "default") {
928 if (i+2 != numArgs)
929 throw std::string("The 'default' clause should be the last in the"
930 "'case' construct!");
931 O << IndentLevel << "else {\n";
932 }
933 else {
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000934 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000935 EmitCaseTest(Test, IndentLevel, OptDescs, O);
936 O << ") {\n";
937 }
938
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000939 // Emit the corresponding statement.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000940 ++i;
941 if (i == numArgs)
942 throw "Case construct handler: no corresponding action "
943 "found for the test " + Test.getAsString() + '!';
944
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000945 Init* arg = d->getArg(i);
946 if (dynamic_cast<DagInit*>(arg)
947 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
948 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
949 (std::string(IndentLevel) + Indent1).c_str(),
950 Callback, EmitElseIf, OptDescs, O);
951 }
952 else {
953 Callback(arg, IndentLevel, O);
954 }
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000955 O << IndentLevel << "}\n";
956 }
957}
958
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000959/// EmitForwardOptionPropertyHandlingCode - Helper function used to
960/// implement EmitOptionPropertyHandlingCode(). Emits code for
961/// handling the (forward) option property.
962void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
963 std::ostream& O) {
964 switch (D.Type) {
965 case OptionType::Switch:
966 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
967 break;
968 case OptionType::Parameter:
969 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
970 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
971 break;
972 case OptionType::Prefix:
973 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
974 << D.GenVariableName() << ");\n";
975 break;
976 case OptionType::PrefixList:
977 O << Indent3 << "for (" << D.GenTypeDeclaration()
978 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
979 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
980 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
981 << "*B);\n";
982 break;
983 case OptionType::ParameterList:
984 O << Indent3 << "for (" << D.GenTypeDeclaration()
985 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
986 << Indent3 << "E = " << D.GenVariableName()
987 << ".end() ; B != E; ++B) {\n"
988 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
989 << Indent4 << "vec.push_back(*B);\n"
990 << Indent3 << "}\n";
991 break;
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000992 case OptionType::Alias:
993 default:
994 throw std::string("Aliases are not allowed in tool option descriptions!");
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000995 }
996}
997
Mikhail Glushenkovea6ce492008-05-30 06:15:20 +0000998// ToolOptionHasInterestingProperties - A helper function used by
999// EmitOptionPropertyHandlingCode() that tells us whether we should
1000// emit any property handling code at all.
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001001bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
Mikhail Glushenkovea6ce492008-05-30 06:15:20 +00001002 bool ret = false;
1003 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1004 E = D.Props.end(); B != E; ++B) {
1005 const OptionProperty& OptProp = *B;
1006 if (OptProp.first == OptionPropertyType::AppendCmd)
1007 ret = true;
1008 }
1009 if (D.isForward() || D.isUnpackValues())
1010 ret = true;
1011 return ret;
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001012}
1013
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001014/// EmitOptionPropertyHandlingCode - Helper function used by
1015/// EmitGenerateActionMethod(). Emits code that handles option
1016/// properties.
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001017void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001018 std::ostream& O)
1019{
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001020 if (!ToolOptionHasInterestingProperties(D))
1021 return;
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001022 // Start of the if-clause.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001023 O << Indent2 << "if (";
1024 if (D.Type == OptionType::Switch)
1025 O << D.GenVariableName();
1026 else
1027 O << '!' << D.GenVariableName() << ".empty()";
1028
1029 O <<") {\n";
1030
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001031 // Handle option properties that take an argument.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001032 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1033 E = D.Props.end(); B!=E; ++B) {
1034 const OptionProperty& val = *B;
1035
1036 switch (val.first) {
1037 // (append_cmd cmd) property
1038 case OptionPropertyType::AppendCmd:
1039 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1040 break;
1041 // Other properties with argument
1042 default:
1043 break;
1044 }
1045 }
1046
1047 // Handle flags
1048
1049 // (forward) property
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001050 if (D.isForward())
1051 EmitForwardOptionPropertyHandlingCode(D, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001052
1053 // (unpack_values) property
1054 if (D.isUnpackValues()) {
1055 if (IsListOptionType(D.Type)) {
1056 O << Indent3 << "for (" << D.GenTypeDeclaration()
1057 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1058 << Indent3 << "E = " << D.GenVariableName()
1059 << ".end(); B != E; ++B)\n"
Mikhail Glushenkov028f18e2008-05-06 18:13:45 +00001060 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001061 }
1062 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
Mikhail Glushenkov028f18e2008-05-06 18:13:45 +00001063 O << Indent3 << "llvm::SplitString("
1064 << D.GenVariableName() << ", vec, \",\");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001065 }
1066 else {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001067 throw std::string("Switches can't have unpack_values property!");
1068 }
1069 }
1070
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001071 // End of the if-clause.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001072 O << Indent2 << "}\n";
1073}
1074
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001075/// SubstituteSpecialCommands - Perform string substitution for $CALL
1076/// and $ENV. Helper function used by EmitCmdLineVecFill().
1077std::string SubstituteSpecialCommands(const std::string& cmd) {
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001078 size_t cparen = cmd.find(")");
1079 std::string ret;
1080
1081 if (cmd.find("$CALL(") == 0) {
1082 if (cmd.size() == 6)
1083 throw std::string("$CALL invocation: empty argument list!");
1084
1085 ret += "hooks::";
1086 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1087 ret += "()";
1088 }
1089 else if (cmd.find("$ENV(") == 0) {
1090 if (cmd.size() == 5)
1091 throw std::string("$ENV invocation: empty argument list!");
1092
1093 ret += "std::getenv(\"";
1094 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1095 ret += "\")";
1096 }
1097 else {
1098 throw "Unknown special command: " + cmd;
1099 }
1100
1101 if (cmd.begin() + cparen + 1 != cmd.end()) {
1102 ret += " + std::string(\"";
1103 ret += (cmd.c_str() + cparen + 1);
1104 ret += "\")";
1105 }
1106
1107 return ret;
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001108}
1109
1110/// EmitCmdLineVecFill - Emit code that fills in the command line
1111/// vector. Helper function used by EmitGenerateActionMethod().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001112void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1113 bool Version, const char* IndentLevel,
1114 std::ostream& O) {
1115 StrVector StrVec;
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001116 SplitString(InitPtrToString(CmdLine), StrVec);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001117 if (StrVec.empty())
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001118 throw "Tool " + ToolName + " has empty command line!";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001119
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001120 StrVector::const_iterator I = StrVec.begin();
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001121 ++I;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001122 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001123 const std::string& cmd = *I;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001124 O << IndentLevel;
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001125 if (cmd.at(0) == '$') {
1126 if (cmd == "$INFILE") {
1127 if (Version)
1128 O << "for (PathVector::const_iterator B = inFiles.begin()"
1129 << ", E = inFiles.end();\n"
1130 << IndentLevel << "B != E; ++B)\n"
1131 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1132 else
1133 O << "vec.push_back(inFile.toString());\n";
1134 }
1135 else if (cmd == "$OUTFILE") {
1136 O << "vec.push_back(outFile.toString());\n";
1137 }
1138 else {
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001139 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1140 O << ");\n";
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001141 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001142 }
1143 else {
1144 O << "vec.push_back(\"" << cmd << "\");\n";
1145 }
1146 }
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001147 O << IndentLevel << "cmd = "
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001148 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1149 : "\"" + StrVec[0] + "\"")
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001150 << ";\n";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001151}
1152
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001153/// EmitCmdLineVecFillCallback - A function object wrapper around
1154/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1155/// argument to EmitCaseConstructHandler().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001156class EmitCmdLineVecFillCallback {
1157 bool Version;
1158 const std::string& ToolName;
1159 public:
1160 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1161 : Version(Ver), ToolName(TN) {}
1162
1163 void operator()(const Init* Statement, const char* IndentLevel,
1164 std::ostream& O) const
1165 {
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001166 EmitCmdLineVecFill(Statement, ToolName, Version,
1167 (std::string(IndentLevel) + Indent1).c_str(), O);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001168 }
1169};
1170
1171// EmitGenerateActionMethod - Emit one of two versions of the
1172// Tool::GenerateAction() method.
1173void EmitGenerateActionMethod (const ToolProperties& P,
1174 const GlobalOptionDescriptions& OptDescs,
1175 bool Version, std::ostream& O) {
1176 if (Version)
1177 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1178 else
1179 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1180
1181 O << Indent2 << "const sys::Path& outFile,\n"
1182 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1183 << Indent1 << "{\n"
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001184 << Indent2 << "const char* cmd;\n"
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001185 << Indent2 << "std::vector<std::string> vec;\n";
1186
1187 // cmd_line is either a string or a 'case' construct.
1188 if (typeid(*P.CmdLine) == typeid(StringInit))
1189 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1190 else
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001191 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001192 EmitCmdLineVecFillCallback(Version, P.Name),
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001193 true, OptDescs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001194
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001195 // For every understood option, emit handling code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001196 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1197 E = P.OptDescs.end(); B != E; ++B) {
1198 const ToolOptionDescription& val = B->second;
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001199 EmitOptionPropertyHandlingCode(val, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001200 }
1201
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001202 // Handle the Sink property.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001203 if (P.isSink()) {
1204 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1205 << Indent3 << "vec.insert(vec.end(), "
1206 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1207 << Indent2 << "}\n";
1208 }
1209
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001210 O << Indent2 << "return Action(cmd, vec);\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001211 << Indent1 << "}\n\n";
1212}
1213
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001214/// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1215/// a given Tool class.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001216void EmitGenerateActionMethods (const ToolProperties& P,
1217 const GlobalOptionDescriptions& OptDescs,
1218 std::ostream& O) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001219 if (!P.isJoin())
1220 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001221 << Indent2 << "const llvm::sys::Path& outFile,\n"
1222 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001223 << Indent1 << "{\n"
1224 << Indent2 << "throw std::runtime_error(\"" << P.Name
1225 << " is not a Join tool!\");\n"
1226 << Indent1 << "}\n\n";
1227 else
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001228 EmitGenerateActionMethod(P, OptDescs, true, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001229
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001230 EmitGenerateActionMethod(P, OptDescs, false, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001231}
1232
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001233/// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1234/// class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001235void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1236 O << Indent1 << "bool IsLast() const {\n"
1237 << Indent2 << "bool last = false;\n";
1238
1239 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1240 E = P.OptDescs.end(); B != E; ++B) {
1241 const ToolOptionDescription& val = B->second;
1242
1243 if (val.isStopCompilation())
1244 O << Indent2
1245 << "if (" << val.GenVariableName()
1246 << ")\n" << Indent3 << "last = true;\n";
1247 }
1248
1249 O << Indent2 << "return last;\n"
1250 << Indent1 << "}\n\n";
1251}
1252
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001253/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1254/// methods for a given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001255void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001256 O << Indent1 << "const char** InputLanguages() const {\n"
1257 << Indent2 << "return InputLanguages_;\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001258 << Indent1 << "}\n\n";
1259
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001260 O << Indent1 << "const char* OutputLanguage() const {\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001261 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1262 << Indent1 << "}\n\n";
1263}
1264
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001265/// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1266/// given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001267void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001268 O << Indent1 << "const char* OutputSuffix() const {\n"
Mikhail Glushenkovabab33b2008-05-30 06:13:02 +00001269 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1270
1271 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1272 E = P.OptDescs.end(); B != E; ++B) {
1273 const ToolOptionDescription& OptDesc = B->second;
1274 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1275 E = OptDesc.Props.end(); B != E; ++B) {
1276 const OptionProperty& OptProp = *B;
1277 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1278 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1279 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1280 }
1281 }
1282 }
1283
1284 O << Indent2 << "return ret;\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001285 << Indent1 << "}\n\n";
1286}
1287
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001288/// EmitNameMethod - Emit the Name() method for a given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001289void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001290 O << Indent1 << "const char* Name() const {\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001291 << Indent2 << "return \"" << P.Name << "\";\n"
1292 << Indent1 << "}\n\n";
1293}
1294
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001295/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1296/// class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001297void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1298 O << Indent1 << "bool IsJoin() const {\n";
1299 if (P.isJoin())
1300 O << Indent2 << "return true;\n";
1301 else
1302 O << Indent2 << "return false;\n";
1303 O << Indent1 << "}\n\n";
1304}
1305
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001306/// EmitStaticMemberDefinitions - Emit static member definitions for a
1307/// given Tool class.
1308void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1309 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1310 for (StrVector::const_iterator B = P.InLanguage.begin(),
1311 E = P.InLanguage.end(); B != E; ++B)
1312 O << '\"' << *B << "\", ";
1313 O << "0};\n\n";
1314}
1315
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001316/// EmitToolClassDefinition - Emit a Tool class definition.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001317void EmitToolClassDefinition (const ToolProperties& P,
1318 const GlobalOptionDescriptions& OptDescs,
1319 std::ostream& O) {
1320 if (P.Name == "root")
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001321 return;
1322
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001323 // Header
Mikhail Glushenkov121889c2008-05-06 17:26:53 +00001324 O << "class " << P.Name << " : public ";
1325 if (P.isJoin())
1326 O << "JoinTool";
1327 else
1328 O << "Tool";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001329
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001330 O << "{\nprivate:\n"
1331 << Indent1 << "static const char* InputLanguages_[];\n\n";
1332
1333 O << "public:\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001334 EmitNameMethod(P, O);
1335 EmitInOutLanguageMethods(P, O);
1336 EmitOutputSuffixMethod(P, O);
1337 EmitIsJoinMethod(P, O);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001338 EmitGenerateActionMethods(P, OptDescs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001339 EmitIsLastMethod(P, O);
1340
1341 // Close class definition
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001342 O << "};\n";
1343
1344 EmitStaticMemberDefinitions(P, O);
1345
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001346}
1347
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001348/// EmitOptionDescriptions - Iterate over a list of option
1349/// descriptions and emit registration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001350void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1351 std::ostream& O)
1352{
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001353 std::vector<GlobalOptionDescription> Aliases;
1354
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001355 // Emit static cl::Option variables.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001356 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1357 E = descs.end(); B!=E; ++B) {
1358 const GlobalOptionDescription& val = B->second;
1359
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001360 if (val.Type == OptionType::Alias) {
1361 Aliases.push_back(val);
1362 continue;
1363 }
1364
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001365 O << val.GenTypeDeclaration() << ' '
1366 << val.GenVariableName()
1367 << "(\"" << val.Name << '\"';
1368
1369 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1370 O << ", cl::Prefix";
1371
1372 if (val.isRequired()) {
1373 switch (val.Type) {
1374 case OptionType::PrefixList:
1375 case OptionType::ParameterList:
1376 O << ", cl::OneOrMore";
1377 break;
1378 default:
1379 O << ", cl::Required";
1380 }
1381 }
1382
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001383 if (!val.Help.empty())
1384 O << ", cl::desc(\"" << val.Help << "\")";
1385
1386 O << ");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001387 }
1388
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001389 // Emit the aliases (they should go after all the 'proper' options).
1390 for (std::vector<GlobalOptionDescription>::const_iterator
1391 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1392 const GlobalOptionDescription& val = *B;
1393
1394 O << val.GenTypeDeclaration() << ' '
1395 << val.GenVariableName()
1396 << "(\"" << val.Name << '\"';
1397
1398 GlobalOptionDescriptions::container_type
1399 ::const_iterator F = descs.Descriptions.find(val.Help);
1400 if (F != descs.Descriptions.end())
1401 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1402 else
1403 throw val.Name + ": alias to an unknown option!";
1404
1405 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1406 }
1407
1408 // Emit the sink option.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001409 if (descs.HasSink)
1410 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1411
1412 O << '\n';
1413}
1414
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001415/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001416void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1417{
1418 // Get the relevant field out of RecordKeeper
1419 Record* LangMapRecord = Records.getDef("LanguageMap");
1420 if (!LangMapRecord)
1421 throw std::string("Language map definition not found!");
1422
1423 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1424 if (!LangsToSuffixesList)
1425 throw std::string("Error in the language map definition!");
1426
1427 // Generate code
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001428 O << "void llvmc::PopulateLanguageMap() {\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001429
1430 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1431 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1432
1433 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1434 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1435
1436 for (unsigned i = 0; i < Suffixes->size(); ++i)
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001437 O << Indent1 << "GlobalLanguageMap[\""
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001438 << InitPtrToString(Suffixes->getElement(i))
1439 << "\"] = \"" << Lang << "\";\n";
1440 }
1441
1442 O << "}\n\n";
1443}
1444
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001445/// FillInToolToLang - Fills in two tables that map tool names to
1446/// (input, output) languages. Used by the typechecker.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001447void FillInToolToLang (const ToolPropertiesList& TPList,
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001448 StringMap<StringSet<> >& ToolToInLang,
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001449 StringMap<std::string>& ToolToOutLang) {
1450 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1451 B != E; ++B) {
1452 const ToolProperties& P = *(*B);
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001453 for (StrVector::const_iterator B = P.InLanguage.begin(),
1454 E = P.InLanguage.end(); B != E; ++B)
1455 ToolToInLang[P.Name].insert(*B);
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001456 ToolToOutLang[P.Name] = P.OutLanguage;
1457 }
1458}
1459
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001460/// TypecheckGraph - Check that names for output and input languages
1461/// on all edges do match.
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001462// TOFIX: It would be nice if this function also checked for cycles
1463// and multiple default edges in the graph (better error
1464// reporting). Unfortunately, it is awkward to do right now because
1465// our intermediate representation is not sufficiently
1466// sofisticated. Algorithms like these should be run on a real graph
1467// instead of AST.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001468void TypecheckGraph (Record* CompilationGraph,
1469 const ToolPropertiesList& TPList) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001470 StringMap<StringSet<> > ToolToInLang;
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001471 StringMap<std::string> ToolToOutLang;
1472
1473 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1474 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001475 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1476 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001477
1478 for (unsigned i = 0; i < edges->size(); ++i) {
1479 Record* Edge = edges->getElementAsRecord(i);
1480 Record* A = Edge->getValueAsDef("a");
1481 Record* B = Edge->getValueAsDef("b");
1482 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001483 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001484 if (IA == IAE)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001485 throw A->getName() + ": no such tool!";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001486 if (IB == IBE)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001487 throw B->getName() + ": no such tool!";
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001488 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001489 throw "Edge " + A->getName() + "->" + B->getName()
1490 + ": output->input language mismatch";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001491 if (B->getName() == "root")
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001492 throw std::string("Edges back to the root are not allowed!");
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001493 }
1494}
1495
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001496/// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1497/// by EmitEdgeClass().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001498void IncDecWeight (const Init* i, const char* IndentLevel,
1499 std::ostream& O) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001500 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001501 const std::string& OpName = d.getOperator()->getAsString();
1502
1503 if (OpName == "inc_weight")
1504 O << IndentLevel << Indent1 << "ret += ";
1505 else if (OpName == "dec_weight")
1506 O << IndentLevel << Indent1 << "ret -= ";
1507 else
1508 throw "Unknown operator in edge properties list: " + OpName + '!';
1509
1510 if (d.getNumArgs() > 0)
1511 O << InitPtrToInt(d.getArg(0)) << ";\n";
1512 else
1513 O << "2;\n";
1514
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +00001515}
1516
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001517/// EmitEdgeClass - Emit a single Edge# class.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001518void EmitEdgeClass (unsigned N, const std::string& Target,
1519 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1520 std::ostream& O) {
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001521
1522 // Class constructor.
1523 O << "class Edge" << N << ": public Edge {\n"
1524 << "public:\n"
1525 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1526 << "\") {}\n\n"
1527
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001528 // Function Weight().
Mikhail Glushenkovd6228882008-05-06 18:15:12 +00001529 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001530 << Indent2 << "unsigned ret = 0;\n";
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001531
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001532 // Handle the 'case' construct.
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001533 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001534
1535 O << Indent2 << "return ret;\n"
1536 << Indent1 << "};\n\n};\n\n";
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001537}
1538
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001539/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001540void EmitEdgeClasses (Record* CompilationGraph,
1541 const GlobalOptionDescriptions& OptDescs,
1542 std::ostream& O) {
1543 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1544
1545 for (unsigned i = 0; i < edges->size(); ++i) {
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001546 Record* Edge = edges->getElementAsRecord(i);
1547 Record* B = Edge->getValueAsDef("b");
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001548 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001549
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001550 if (isDagEmpty(Weight))
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001551 continue;
1552
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001553 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001554 }
1555}
1556
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001557/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1558/// function.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001559void EmitPopulateCompilationGraph (Record* CompilationGraph,
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001560 std::ostream& O)
1561{
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001562 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001563
1564 // Generate code
Mikhail Glushenkov34307a92008-05-06 18:08:59 +00001565 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001566 << Indent1 << "PopulateLanguageMap();\n\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001567
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001568 // Insert vertices
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001569
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001570 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1571 if (Tools.empty())
1572 throw std::string("No tool definitions found!");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001573
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001574 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1575 const std::string& Name = (*B)->getName();
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001576 if (Name != "root")
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001577 O << Indent1 << "G.insertNode(new "
1578 << Name << "());\n";
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001579 }
1580
1581 O << '\n';
1582
1583 // Insert edges
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001584 for (unsigned i = 0; i < edges->size(); ++i) {
1585 Record* Edge = edges->getElementAsRecord(i);
1586 Record* A = Edge->getValueAsDef("a");
1587 Record* B = Edge->getValueAsDef("b");
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001588 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001589
1590 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1591
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001592 if (isDagEmpty(Weight))
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001593 O << "new SimpleEdge(\"" << B->getName() << "\")";
1594 else
1595 O << "new Edge" << i << "()";
1596
1597 O << ");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001598 }
1599
1600 O << "}\n\n";
1601}
1602
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001603/// ExtractHookNames - Extract the hook names from all instances of
1604/// $CALL(HookName) in the provided command line string. Helper
1605/// function used by FillInHookNames().
1606void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1607 StrVector cmds;
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001608 llvm::SplitString(InitPtrToString(CmdLine), cmds);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001609 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1610 B != E; ++B) {
1611 const std::string& cmd = *B;
1612 if (cmd.find("$CALL(") == 0) {
1613 if (cmd.size() == 6)
1614 throw std::string("$CALL invocation: empty argument list!");
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001615 HookNames.push_back(std::string(cmd.begin() + 6,
1616 cmd.begin() + cmd.find(")")));
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001617 }
1618 }
1619}
1620
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001621/// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1622/// 'case' expression, handle nesting. Helper function used by
1623/// FillInHookNames().
1624void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1625 const DagInit& d = InitPtrToDag(Case);
1626 bool even = false;
1627 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1628 B != E; ++B) {
1629 Init* arg = *B;
1630 if (even && dynamic_cast<DagInit*>(arg)
1631 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1632 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1633 else if (even)
1634 ExtractHookNames(arg, HookNames);
1635 even = !even;
1636 }
1637}
1638
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001639/// FillInHookNames - Actually extract the hook names from all command
1640/// line strings. Helper function used by EmitHookDeclarations().
1641void FillInHookNames(const ToolPropertiesList& TPList,
1642 StrVector& HookNames) {
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001643 // For all command lines:
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001644 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1645 E = TPList.end(); B != E; ++B) {
1646 const ToolProperties& P = *(*B);
1647 if (!P.CmdLine)
1648 continue;
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001649 if (dynamic_cast<StringInit*>(P.CmdLine))
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001650 // This is a string.
1651 ExtractHookNames(P.CmdLine, HookNames);
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001652 else
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001653 // This is a 'case' construct.
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001654 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001655 }
1656}
1657
1658/// EmitHookDeclarations - Parse CmdLine fields of all the tool
1659/// property records and emit hook function declaration for each
1660/// instance of $CALL(HookName).
1661void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1662 std::ostream& O) {
1663 StrVector HookNames;
1664 FillInHookNames(ToolProps, HookNames);
1665 if (HookNames.empty())
1666 return;
1667 std::sort(HookNames.begin(), HookNames.end());
1668 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1669
1670 O << "namespace hooks {\n";
1671 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1672 O << Indent1 << "std::string " << *B << "();\n";
1673
1674 O << "}\n\n";
1675}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001676
1677// End of anonymous namespace
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +00001678}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001679
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001680/// run - The back-end entry point.
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +00001681void LLVMCConfigurationEmitter::run (std::ostream &O) {
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +00001682 try {
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001683
1684 // Emit file header.
Mikhail Glushenkov34307a92008-05-06 18:08:59 +00001685 EmitSourceFileHeader("LLVMC Configuration Library", O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001686
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001687 // Get a list of all defined Tools.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001688 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1689 if (Tools.empty())
1690 throw std::string("No tool definitions found!");
1691
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001692 // Gather information from the Tool description dags.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001693 ToolPropertiesList tool_props;
1694 GlobalOptionDescriptions opt_descs;
1695 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1696
Mikhail Glushenkovd638e852008-05-30 06:26:08 +00001697 RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1698 CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1699 opt_descs);
1700
Mikhail Glushenkove5fcb552008-05-30 06:28:37 +00001701 // Check that there are no options without side effects (specified
1702 // only in the OptionList).
1703 CheckForSuperfluousOptions(tool_props, opt_descs);
1704
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001705 // Emit global option registration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001706 EmitOptionDescriptions(opt_descs, O);
1707
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001708 // Emit hook declarations.
1709 EmitHookDeclarations(tool_props, O);
1710
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001711 // Emit PopulateLanguageMap() function
1712 // (a language map maps from file extensions to language names).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001713 EmitPopulateLanguageMap(Records, O);
1714
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001715 // Emit Tool classes.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001716 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1717 E = tool_props.end(); B!=E; ++B)
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001718 EmitToolClassDefinition(*(*B), opt_descs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001719
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001720 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1721 if (!CompilationGraphRecord)
1722 throw std::string("Compilation graph description not found!");
1723
1724 // Typecheck the compilation graph.
1725 TypecheckGraph(CompilationGraphRecord, tool_props);
1726
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001727 // Emit Edge# classes.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001728 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001729
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001730 // Emit PopulateCompilationGraph() function.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001731 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001732
1733 // EOF
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +00001734 } catch (std::exception& Error) {
1735 throw Error.what() + std::string(" - usually this means a syntax error.");
1736 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001737}