blob: 8b79105a79983f9285087d82d07a1b914a2a3458 [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 Glushenkova5922cc2008-05-06 17:22:03 +0000246 const GlobalOptionDescription& FindOption(const std::string& OptName) const {
247 const_iterator I = Descriptions.find(OptName);
248 if (I != Descriptions.end())
249 return I->second;
250 else
251 throw OptName + ": no such option!";
252 }
253
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000254 // Insert new GlobalOptionDescription into GlobalOptionDescriptions list
255 void insertDescription (const GlobalOptionDescription& o)
256 {
257 container_type::iterator I = Descriptions.find(o.Name);
258 if (I != Descriptions.end()) {
259 GlobalOptionDescription& D = I->second;
260 D.Merge(o);
261 }
262 else {
263 Descriptions[o.Name] = o;
264 }
265 }
266
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000267 // Support for STL-style iteration
268 const_iterator begin() const { return Descriptions.begin(); }
269 const_iterator end() const { return Descriptions.end(); }
270};
271
272
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000273// Tool-local option description.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000274
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000275// Properties without arguments are implemented as flags.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000276namespace ToolOptionDescriptionFlags {
277 enum ToolOptionDescriptionFlags { StopCompilation = 0x1,
278 Forward = 0x2, UnpackValues = 0x4};
279}
280namespace OptionPropertyType {
Mikhail Glushenkovabab33b2008-05-30 06:13:02 +0000281 enum OptionPropertyType { AppendCmd, OutputSuffix };
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000282}
283
284typedef std::pair<OptionPropertyType::OptionPropertyType, std::string>
285OptionProperty;
286typedef SmallVector<OptionProperty, 4> OptionPropertyList;
287
288struct ToolOptionDescription : public OptionDescription {
289 unsigned Flags;
290 OptionPropertyList Props;
291
292 // StringMap can only store DefaultConstructible objects
Mikhail Glushenkov18cbe892008-03-27 09:53:47 +0000293 ToolOptionDescription() : OptionDescription(), Flags(0) {}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000294
295 ToolOptionDescription (OptionType::OptionType t, const std::string& n)
296 : OptionDescription(t, n)
297 {}
298
299 // Various boolean properties
300 bool isStopCompilation() const {
301 return Flags & ToolOptionDescriptionFlags::StopCompilation;
302 }
303 void setStopCompilation() {
304 Flags |= ToolOptionDescriptionFlags::StopCompilation;
305 }
306
307 bool isForward() const {
308 return Flags & ToolOptionDescriptionFlags::Forward;
309 }
310 void setForward() {
311 Flags |= ToolOptionDescriptionFlags::Forward;
312 }
313
314 bool isUnpackValues() const {
315 return Flags & ToolOptionDescriptionFlags::UnpackValues;
316 }
317 void setUnpackValues() {
318 Flags |= ToolOptionDescriptionFlags::UnpackValues;
319 }
320
321 void AddProperty (OptionPropertyType::OptionPropertyType t,
322 const std::string& val)
323 {
324 Props.push_back(std::make_pair(t, val));
325 }
326};
327
328typedef StringMap<ToolOptionDescription> ToolOptionDescriptions;
329
330// Tool information record
331
332namespace ToolFlags {
333 enum ToolFlags { Join = 0x1, Sink = 0x2 };
334}
335
336struct ToolProperties : public RefCountedBase<ToolProperties> {
337 std::string Name;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000338 Init* CmdLine;
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000339 StrVector InLanguage;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000340 std::string OutLanguage;
341 std::string OutputSuffix;
342 unsigned Flags;
343 ToolOptionDescriptions OptDescs;
344
345 // Various boolean properties
346 void setSink() { Flags |= ToolFlags::Sink; }
347 bool isSink() const { return Flags & ToolFlags::Sink; }
348 void setJoin() { Flags |= ToolFlags::Join; }
349 bool isJoin() const { return Flags & ToolFlags::Join; }
350
351 // Default ctor here is needed because StringMap can only store
352 // DefaultConstructible objects
Mikhail Glushenkov434816d2008-05-06 18:13:00 +0000353 ToolProperties() : Flags(0) {}
354 ToolProperties (const std::string& n) : Name(n), Flags(0) {}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000355};
356
357
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000358/// ToolPropertiesList - A list of Tool information records
359/// IntrusiveRefCntPtrs are used here because StringMap has no copy
360/// constructor (and we want to avoid copying ToolProperties anyway).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000361typedef std::vector<IntrusiveRefCntPtr<ToolProperties> > ToolPropertiesList;
362
363
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000364/// CollectOptionProperties - Function object for iterating over a
365/// list (usually, a DAG) of option property records.
366class CollectOptionProperties {
367private:
368 // Implementation details.
369
370 /// OptionPropertyHandler - a function that extracts information
371 /// about a given option property from its DAG representation.
372 typedef void (CollectOptionProperties::* OptionPropertyHandler)
373 (const DagInit*);
374
375 /// OptionPropertyHandlerMap - A map from option property names to
376 /// option property handlers
377 typedef StringMap<OptionPropertyHandler> OptionPropertyHandlerMap;
378
379 static OptionPropertyHandlerMap optionPropertyHandlers_;
380 static bool staticMembersInitialized_;
381
382 /// This is where the information is stored
383
384 /// toolProps_ - Properties of the current Tool.
385 ToolProperties* toolProps_;
386 /// optDescs_ - OptionDescriptions table (used to register options
387 /// globally).
388 GlobalOptionDescription& optDesc_;
389
390public:
391
392 explicit CollectOptionProperties(ToolProperties* TP,
393 GlobalOptionDescription& OD)
394 : toolProps_(TP), optDesc_(OD)
395 {
396 if (!staticMembersInitialized_) {
397 optionPropertyHandlers_["append_cmd"] =
398 &CollectOptionProperties::onAppendCmd;
399 optionPropertyHandlers_["forward"] =
400 &CollectOptionProperties::onForward;
401 optionPropertyHandlers_["help"] =
402 &CollectOptionProperties::onHelp;
403 optionPropertyHandlers_["output_suffix"] =
404 &CollectOptionProperties::onOutputSuffix;
405 optionPropertyHandlers_["required"] =
406 &CollectOptionProperties::onRequired;
407 optionPropertyHandlers_["stop_compilation"] =
408 &CollectOptionProperties::onStopCompilation;
409 optionPropertyHandlers_["unpack_values"] =
410 &CollectOptionProperties::onUnpackValues;
411
412 staticMembersInitialized_ = true;
413 }
414 }
415
416 /// operator() - Gets called for every option property; Just forwards
417 /// to the corresponding property handler.
418 void operator() (Init* i) {
419 const DagInit& option_property = InitPtrToDag(i);
420 const std::string& option_property_name
421 = option_property.getOperator()->getAsString();
422 OptionPropertyHandlerMap::iterator method
423 = optionPropertyHandlers_.find(option_property_name);
424
425 if (method != optionPropertyHandlers_.end()) {
426 OptionPropertyHandler h = method->second;
427 (this->*h)(&option_property);
428 }
429 else {
430 throw "Unknown option property: " + option_property_name + "!";
431 }
432 }
433
434private:
435
436 /// Option property handlers --
437 /// Methods that handle properties that are common for all types of
438 /// options (like append_cmd, stop_compilation)
439
440 void onAppendCmd (const DagInit* d) {
441 checkNumberOfArguments(d, 1);
442 checkToolProps(d);
443 const std::string& cmd = InitPtrToString(d->getArg(0));
444
445 toolProps_->OptDescs[optDesc_.Name].
446 AddProperty(OptionPropertyType::AppendCmd, cmd);
447 }
448
449 void onOutputSuffix (const DagInit* d) {
450 checkNumberOfArguments(d, 1);
451 checkToolProps(d);
452 const std::string& suf = InitPtrToString(d->getArg(0));
453
454 if (toolProps_->OptDescs[optDesc_.Name].Type != OptionType::Switch)
455 throw "Option " + optDesc_.Name
456 + " can't have 'output_suffix' property since it isn't a switch!";
457
458 toolProps_->OptDescs[optDesc_.Name].AddProperty
459 (OptionPropertyType::OutputSuffix, suf);
460 }
461
462 void onForward (const DagInit* d) {
463 checkNumberOfArguments(d, 0);
464 checkToolProps(d);
465 toolProps_->OptDescs[optDesc_.Name].setForward();
466 }
467
468 void onHelp (const DagInit* d) {
469 checkNumberOfArguments(d, 1);
470 const std::string& help_message = InitPtrToString(d->getArg(0));
471
472 optDesc_.Help = help_message;
473 }
474
475 void onRequired (const DagInit* d) {
476 checkNumberOfArguments(d, 0);
477 checkToolProps(d);
478 optDesc_.setRequired();
479 }
480
481 void onStopCompilation (const DagInit* d) {
482 checkNumberOfArguments(d, 0);
483 checkToolProps(d);
484 if (optDesc_.Type != OptionType::Switch)
485 throw std::string("Only options of type Switch can stop compilation!");
486 toolProps_->OptDescs[optDesc_.Name].setStopCompilation();
487 }
488
489 void onUnpackValues (const DagInit* d) {
490 checkNumberOfArguments(d, 0);
491 checkToolProps(d);
492 toolProps_->OptDescs[optDesc_.Name].setUnpackValues();
493 }
494
495 // Helper functions
496
497 /// checkToolProps - Throw an error if toolProps_ == 0.
498 void checkToolProps(const DagInit* d) {
499 if (!d)
500 throw "Option property " + d->getOperator()->getAsString()
501 + " can't be used in this context";
502 }
503
504};
505
506CollectOptionProperties::OptionPropertyHandlerMap
507CollectOptionProperties::optionPropertyHandlers_;
508
509bool CollectOptionProperties::staticMembersInitialized_ = false;
510
511
512/// processOptionProperties - Go through the list of option
513/// properties and call a corresponding handler for each.
514void processOptionProperties (const DagInit* d, ToolProperties* t,
515 GlobalOptionDescription& o) {
516 checkNumberOfArguments(d, 2);
517 DagInit::const_arg_iterator B = d->arg_begin();
518 // Skip the first argument: it's always the option name.
519 ++B;
520 std::for_each(B, d->arg_end(), CollectOptionProperties(t, o));
521}
522
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000523/// AddOption - A function object wrapper for
524/// processOptionProperties. Used by CollectProperties and
525/// CollectPropertiesFromOptionList.
526class AddOption {
527private:
528 GlobalOptionDescriptions& OptDescs_;
529 ToolProperties* ToolProps_;
530
531public:
532 explicit AddOption(GlobalOptionDescriptions& OD, ToolProperties* TP = 0)
533 : OptDescs_(OD), ToolProps_(TP)
534 {}
535
536 void operator()(const Init* i) {
537 const DagInit& d = InitPtrToDag(i);
538 checkNumberOfArguments(&d, 2);
539
540 const OptionType::OptionType Type =
541 getOptionType(d.getOperator()->getAsString());
542 const std::string& Name = InitPtrToString(d.getArg(0));
543
544 GlobalOptionDescription OD(Type, Name);
545 if (Type != OptionType::Alias) {
546 processOptionProperties(&d, ToolProps_, OD);
547 if (ToolProps_) {
548 ToolProps_->OptDescs[Name].Type = Type;
549 ToolProps_->OptDescs[Name].Name = Name;
550 }
551 }
552 else {
553 OD.Help = InitPtrToString(d.getArg(1));
554 }
555 OptDescs_.insertDescription(OD);
556 }
557
558private:
559 OptionType::OptionType getOptionType(const std::string& T) const {
560 if (T == "alias_option")
561 return OptionType::Alias;
562 else if (T == "switch_option")
563 return OptionType::Switch;
564 else if (T == "parameter_option")
565 return OptionType::Parameter;
566 else if (T == "parameter_list_option")
567 return OptionType::ParameterList;
568 else if (T == "prefix_option")
569 return OptionType::Prefix;
570 else if (T == "prefix_list_option")
571 return OptionType::PrefixList;
572 else
573 throw "Unknown option type: " + T + '!';
574 }
575};
576
577
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000578/// CollectProperties - Function object for iterating over a list of
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000579/// tool property records.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000580class CollectProperties {
581private:
582
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000583 // Implementation details
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000584
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000585 /// PropertyHandler - a function that extracts information
586 /// about a given tool property from its DAG representation
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000587 typedef void (CollectProperties::*PropertyHandler)(const DagInit*);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000588
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000589 /// PropertyHandlerMap - A map from property names to property
590 /// handlers.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000591 typedef StringMap<PropertyHandler> PropertyHandlerMap;
592
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000593 // Static maps from strings to CollectProperties methods("handlers")
594 static PropertyHandlerMap propertyHandlers_;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000595 static bool staticMembersInitialized_;
596
597
598 /// This is where the information is stored
599
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000600 /// toolProps_ - Properties of the current Tool.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000601 ToolProperties& toolProps_;
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000602 /// optDescs_ - OptionDescriptions table (used to register options
603 /// globally).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000604 GlobalOptionDescriptions& optDescs_;
605
606public:
607
608 explicit CollectProperties (ToolProperties& p, GlobalOptionDescriptions& d)
609 : toolProps_(p), optDescs_(d)
610 {
611 if (!staticMembersInitialized_) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000612 propertyHandlers_["cmd_line"] = &CollectProperties::onCmdLine;
613 propertyHandlers_["in_language"] = &CollectProperties::onInLanguage;
614 propertyHandlers_["join"] = &CollectProperties::onJoin;
615 propertyHandlers_["out_language"] = &CollectProperties::onOutLanguage;
616 propertyHandlers_["output_suffix"] = &CollectProperties::onOutputSuffix;
617 propertyHandlers_["parameter_option"]
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000618 = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000619 propertyHandlers_["parameter_list_option"] =
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000620 &CollectProperties::addOption;
621 propertyHandlers_["prefix_option"] = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000622 propertyHandlers_["prefix_list_option"] =
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000623 &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000624 propertyHandlers_["sink"] = &CollectProperties::onSink;
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000625 propertyHandlers_["switch_option"] = &CollectProperties::addOption;
626 propertyHandlers_["alias_option"] = &CollectProperties::addOption;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000627
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000628 staticMembersInitialized_ = true;
629 }
630 }
631
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +0000632 /// operator() - Gets called for every tool property; Just forwards
633 /// to the corresponding property handler.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000634 void operator() (Init* i) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000635 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkova5922cc2008-05-06 17:22:03 +0000636 const std::string& property_name = d.getOperator()->getAsString();
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000637 PropertyHandlerMap::iterator method
638 = propertyHandlers_.find(property_name);
639
640 if (method != propertyHandlers_.end()) {
641 PropertyHandler h = method->second;
642 (this->*h)(&d);
643 }
644 else {
645 throw "Unknown tool property: " + property_name + "!";
646 }
647 }
648
649private:
650
651 /// Property handlers --
652 /// Functions that extract information about tool properties from
653 /// DAG representation.
654
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000655 void onCmdLine (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000656 checkNumberOfArguments(d, 1);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000657 toolProps_.CmdLine = d->getArg(0);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000658 }
659
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000660 void onInLanguage (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000661 checkNumberOfArguments(d, 1);
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000662 Init* arg = d->getArg(0);
663
664 // Find out the argument's type.
665 if (typeid(*arg) == typeid(StringInit)) {
666 // It's a string.
667 toolProps_.InLanguage.push_back(InitPtrToString(arg));
668 }
669 else {
670 // It's a list.
671 const ListInit& lst = InitPtrToList(arg);
672 StrVector& out = toolProps_.InLanguage;
673
674 // Copy strings to the output vector.
675 for (ListInit::const_iterator B = lst.begin(), E = lst.end();
676 B != E; ++B) {
677 out.push_back(InitPtrToString(*B));
678 }
679
680 // Remove duplicates.
681 std::sort(out.begin(), out.end());
682 StrVector::iterator newE = std::unique(out.begin(), out.end());
683 out.erase(newE, out.end());
684 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000685 }
686
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000687 void onJoin (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000688 checkNumberOfArguments(d, 0);
689 toolProps_.setJoin();
690 }
691
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000692 void onOutLanguage (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000693 checkNumberOfArguments(d, 1);
694 toolProps_.OutLanguage = InitPtrToString(d->getArg(0));
695 }
696
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000697 void onOutputSuffix (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000698 checkNumberOfArguments(d, 1);
699 toolProps_.OutputSuffix = InitPtrToString(d->getArg(0));
700 }
701
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +0000702 void onSink (const DagInit* d) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000703 checkNumberOfArguments(d, 0);
704 optDescs_.HasSink = true;
705 toolProps_.setSink();
706 }
707
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000708 // Just forwards to the AddOption function object. Somewhat
709 // non-optimal, but avoids code duplication.
710 void addOption (const DagInit* d) {
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000711 checkNumberOfArguments(d, 2);
Mikhail Glushenkove62df252008-05-30 06:27:29 +0000712 AddOption(optDescs_, &toolProps_)(d);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000713 }
714
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000715};
716
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000717// Defintions of static members of CollectProperties.
718CollectProperties::PropertyHandlerMap CollectProperties::propertyHandlers_;
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000719bool CollectProperties::staticMembersInitialized_ = false;
720
721
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000722/// CollectToolProperties - Gather information about tool properties
723/// from the parsed TableGen data (basically a wrapper for the
724/// CollectProperties function object).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000725void CollectToolProperties (RecordVector::const_iterator B,
726 RecordVector::const_iterator E,
727 ToolPropertiesList& TPList,
728 GlobalOptionDescriptions& OptDescs)
729{
730 // Iterate over a properties list of every Tool definition
731 for (;B!=E;++B) {
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000732 Record* T = *B;
733 // Throws an exception if the value does not exist.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000734 ListInit* PropList = T->getValueAsListInit("properties");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000735
736 IntrusiveRefCntPtr<ToolProperties>
737 ToolProps(new ToolProperties(T->getName()));
738
739 std::for_each(PropList->begin(), PropList->end(),
740 CollectProperties(*ToolProps, OptDescs));
741 TPList.push_back(ToolProps);
742 }
743}
744
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000745
746/// CollectPropertiesFromOptionList - Gather information about
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000747/// *global* option properties from the OptionList.
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000748void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
749 RecordVector::const_iterator E,
750 GlobalOptionDescriptions& OptDescs)
751{
752 // Iterate over a properties list of every Tool definition
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000753
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000754 for (;B!=E;++B) {
755 RecordVector::value_type T = *B;
756 // Throws an exception if the value does not exist.
757 ListInit* PropList = T->getValueAsListInit("options");
758
Mikhail Glushenkovbf774352008-05-30 06:27:02 +0000759 std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
Mikhail Glushenkovd638e852008-05-30 06:26:08 +0000760 }
761}
762
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000763/// EmitCaseTest1Arg - Helper function used by
764/// EmitCaseConstructHandler.
765bool EmitCaseTest1Arg(const std::string& TestName,
766 const DagInit& d,
767 const GlobalOptionDescriptions& OptDescs,
768 std::ostream& O) {
769 checkNumberOfArguments(&d, 1);
770 const std::string& OptName = InitPtrToString(d.getArg(0));
771 if (TestName == "switch_on") {
772 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
773 if (OptDesc.Type != OptionType::Switch)
774 throw OptName + ": incorrect option type!";
775 O << OptDesc.GenVariableName();
776 return true;
777 } else if (TestName == "input_languages_contain") {
778 O << "InLangs.count(\"" << OptName << "\") != 0";
779 return true;
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +0000780 } else if (TestName == "in_language") {
781 // Works only for cmd_line!
782 O << "GetLanguage(inFile) == \"" << OptName << '\"';
783 return true;
784 } else if (TestName == "not_empty") {
Mikhail Glushenkovb4833872008-05-30 06:24:07 +0000785 if (OptName == "o") {
786 O << "!OutputFilename.empty()";
787 return true;
788 }
789 else {
790 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
791 if (OptDesc.Type == OptionType::Switch)
792 throw OptName + ": incorrect option type!";
793 O << '!' << OptDesc.GenVariableName() << ".empty()";
794 return true;
795 }
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000796 }
797
798 return false;
799}
800
801/// EmitCaseTest2Args - Helper function used by
802/// EmitCaseConstructHandler.
803bool EmitCaseTest2Args(const std::string& TestName,
804 const DagInit& d,
805 const char* IndentLevel,
806 const GlobalOptionDescriptions& OptDescs,
807 std::ostream& O) {
808 checkNumberOfArguments(&d, 2);
809 const std::string& OptName = InitPtrToString(d.getArg(0));
810 const std::string& OptArg = InitPtrToString(d.getArg(1));
811 const GlobalOptionDescription& OptDesc = OptDescs.FindOption(OptName);
812
813 if (TestName == "parameter_equals") {
814 if (OptDesc.Type != OptionType::Parameter
815 && OptDesc.Type != OptionType::Prefix)
816 throw OptName + ": incorrect option type!";
817 O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
818 return true;
819 }
820 else if (TestName == "element_in_list") {
821 if (OptDesc.Type != OptionType::ParameterList
822 && OptDesc.Type != OptionType::PrefixList)
823 throw OptName + ": incorrect option type!";
824 const std::string& VarName = OptDesc.GenVariableName();
825 O << "std::find(" << VarName << ".begin(),\n"
826 << IndentLevel << Indent1 << VarName << ".end(), \""
827 << OptArg << "\") != " << VarName << ".end()";
828 return true;
829 }
830
831 return false;
832}
833
834// Forward declaration.
835// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
836void EmitCaseTest(const DagInit& d, const char* IndentLevel,
837 const GlobalOptionDescriptions& OptDescs,
838 std::ostream& O);
839
840/// EmitLogicalOperationTest - Helper function used by
841/// EmitCaseConstructHandler.
842void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
843 const char* IndentLevel,
844 const GlobalOptionDescriptions& OptDescs,
845 std::ostream& O) {
846 O << '(';
847 for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000848 const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000849 EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
850 if (j != NumArgs - 1)
851 O << ")\n" << IndentLevel << Indent1 << ' ' << LogicOp << " (";
852 else
853 O << ')';
854 }
855}
856
857/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
858void EmitCaseTest(const DagInit& d, const char* IndentLevel,
859 const GlobalOptionDescriptions& OptDescs,
860 std::ostream& O) {
861 const std::string& TestName = d.getOperator()->getAsString();
862
863 if (TestName == "and")
864 EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
865 else if (TestName == "or")
866 EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
867 else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
868 return;
869 else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
870 return;
871 else
872 throw TestName + ": unknown edge property!";
873}
874
875// Emit code that handles the 'case' construct.
876// Takes a function object that should emit code for every case clause.
877// Callback's type is
878// void F(Init* Statement, const char* IndentLevel, std::ostream& O).
879template <typename F>
880void EmitCaseConstructHandler(const DagInit* d, const char* IndentLevel,
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000881 const F& Callback, bool EmitElseIf,
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000882 const GlobalOptionDescriptions& OptDescs,
883 std::ostream& O) {
884 assert(d->getOperator()->getAsString() == "case");
885
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000886 unsigned numArgs = d->getNumArgs();
887 if (d->getNumArgs() < 2)
888 throw "There should be at least one clause in the 'case' expression:\n"
889 + d->getAsString();
890
891 for (unsigned i = 0; i != numArgs; ++i) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +0000892 const DagInit& Test = InitPtrToDag(d->getArg(i));
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000893
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000894 // Emit the test.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000895 if (Test.getOperator()->getAsString() == "default") {
896 if (i+2 != numArgs)
897 throw std::string("The 'default' clause should be the last in the"
898 "'case' construct!");
899 O << IndentLevel << "else {\n";
900 }
901 else {
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000902 O << IndentLevel << ((i != 0 && EmitElseIf) ? "else if (" : "if (");
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000903 EmitCaseTest(Test, IndentLevel, OptDescs, O);
904 O << ") {\n";
905 }
906
Mikhail Glushenkov31681512008-05-30 06:15:47 +0000907 // Emit the corresponding statement.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000908 ++i;
909 if (i == numArgs)
910 throw "Case construct handler: no corresponding action "
911 "found for the test " + Test.getAsString() + '!';
912
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +0000913 Init* arg = d->getArg(i);
914 if (dynamic_cast<DagInit*>(arg)
915 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case") {
916 EmitCaseConstructHandler(static_cast<DagInit*>(arg),
917 (std::string(IndentLevel) + Indent1).c_str(),
918 Callback, EmitElseIf, OptDescs, O);
919 }
920 else {
921 Callback(arg, IndentLevel, O);
922 }
Mikhail Glushenkov35576b02008-05-30 06:10:19 +0000923 O << IndentLevel << "}\n";
924 }
925}
926
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000927/// EmitForwardOptionPropertyHandlingCode - Helper function used to
928/// implement EmitOptionPropertyHandlingCode(). Emits code for
929/// handling the (forward) option property.
930void EmitForwardOptionPropertyHandlingCode (const ToolOptionDescription& D,
931 std::ostream& O) {
932 switch (D.Type) {
933 case OptionType::Switch:
934 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
935 break;
936 case OptionType::Parameter:
937 O << Indent3 << "vec.push_back(\"-" << D.Name << "\");\n";
938 O << Indent3 << "vec.push_back(" << D.GenVariableName() << ");\n";
939 break;
940 case OptionType::Prefix:
941 O << Indent3 << "vec.push_back(\"-" << D.Name << "\" + "
942 << D.GenVariableName() << ");\n";
943 break;
944 case OptionType::PrefixList:
945 O << Indent3 << "for (" << D.GenTypeDeclaration()
946 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
947 << Indent3 << "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n"
948 << Indent4 << "vec.push_back(\"-" << D.Name << "\" + "
949 << "*B);\n";
950 break;
951 case OptionType::ParameterList:
952 O << Indent3 << "for (" << D.GenTypeDeclaration()
953 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
954 << Indent3 << "E = " << D.GenVariableName()
955 << ".end() ; B != E; ++B) {\n"
956 << Indent4 << "vec.push_back(\"-" << D.Name << "\");\n"
957 << Indent4 << "vec.push_back(*B);\n"
958 << Indent3 << "}\n";
959 break;
Mikhail Glushenkovb623c322008-05-30 06:22:52 +0000960 case OptionType::Alias:
961 default:
962 throw std::string("Aliases are not allowed in tool option descriptions!");
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000963 }
964}
965
Mikhail Glushenkovea6ce492008-05-30 06:15:20 +0000966// ToolOptionHasInterestingProperties - A helper function used by
967// EmitOptionPropertyHandlingCode() that tells us whether we should
968// emit any property handling code at all.
Mikhail Glushenkov31f52152008-05-30 06:10:47 +0000969bool ToolOptionHasInterestingProperties(const ToolOptionDescription& D) {
Mikhail Glushenkovea6ce492008-05-30 06:15:20 +0000970 bool ret = false;
971 for (OptionPropertyList::const_iterator B = D.Props.begin(),
972 E = D.Props.end(); B != E; ++B) {
973 const OptionProperty& OptProp = *B;
974 if (OptProp.first == OptionPropertyType::AppendCmd)
975 ret = true;
976 }
977 if (D.isForward() || D.isUnpackValues())
978 ret = true;
979 return ret;
Mikhail Glushenkov31f52152008-05-30 06:10:47 +0000980}
981
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000982/// EmitOptionPropertyHandlingCode - Helper function used by
983/// EmitGenerateActionMethod(). Emits code that handles option
984/// properties.
Mikhail Glushenkov31f52152008-05-30 06:10:47 +0000985void EmitOptionPropertyHandlingCode (const ToolOptionDescription& D,
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000986 std::ostream& O)
987{
Mikhail Glushenkov31f52152008-05-30 06:10:47 +0000988 if (!ToolOptionHasInterestingProperties(D))
989 return;
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000990 // Start of the if-clause.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +0000991 O << Indent2 << "if (";
992 if (D.Type == OptionType::Switch)
993 O << D.GenVariableName();
994 else
995 O << '!' << D.GenVariableName() << ".empty()";
996
997 O <<") {\n";
998
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +0000999 // Handle option properties that take an argument.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001000 for (OptionPropertyList::const_iterator B = D.Props.begin(),
1001 E = D.Props.end(); B!=E; ++B) {
1002 const OptionProperty& val = *B;
1003
1004 switch (val.first) {
1005 // (append_cmd cmd) property
1006 case OptionPropertyType::AppendCmd:
1007 O << Indent3 << "vec.push_back(\"" << val.second << "\");\n";
1008 break;
1009 // Other properties with argument
1010 default:
1011 break;
1012 }
1013 }
1014
1015 // Handle flags
1016
1017 // (forward) property
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001018 if (D.isForward())
1019 EmitForwardOptionPropertyHandlingCode(D, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001020
1021 // (unpack_values) property
1022 if (D.isUnpackValues()) {
1023 if (IsListOptionType(D.Type)) {
1024 O << Indent3 << "for (" << D.GenTypeDeclaration()
1025 << "::iterator B = " << D.GenVariableName() << ".begin(),\n"
1026 << Indent3 << "E = " << D.GenVariableName()
1027 << ".end(); B != E; ++B)\n"
Mikhail Glushenkov028f18e2008-05-06 18:13:45 +00001028 << Indent4 << "llvm::SplitString(*B, vec, \",\");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001029 }
1030 else if (D.Type == OptionType::Prefix || D.Type == OptionType::Parameter){
Mikhail Glushenkov028f18e2008-05-06 18:13:45 +00001031 O << Indent3 << "llvm::SplitString("
1032 << D.GenVariableName() << ", vec, \",\");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001033 }
1034 else {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001035 throw std::string("Switches can't have unpack_values property!");
1036 }
1037 }
1038
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001039 // End of the if-clause.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001040 O << Indent2 << "}\n";
1041}
1042
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001043/// SubstituteSpecialCommands - Perform string substitution for $CALL
1044/// and $ENV. Helper function used by EmitCmdLineVecFill().
1045std::string SubstituteSpecialCommands(const std::string& cmd) {
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001046 size_t cparen = cmd.find(")");
1047 std::string ret;
1048
1049 if (cmd.find("$CALL(") == 0) {
1050 if (cmd.size() == 6)
1051 throw std::string("$CALL invocation: empty argument list!");
1052
1053 ret += "hooks::";
1054 ret += std::string(cmd.begin() + 6, cmd.begin() + cparen);
1055 ret += "()";
1056 }
1057 else if (cmd.find("$ENV(") == 0) {
1058 if (cmd.size() == 5)
1059 throw std::string("$ENV invocation: empty argument list!");
1060
1061 ret += "std::getenv(\"";
1062 ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
1063 ret += "\")";
1064 }
1065 else {
1066 throw "Unknown special command: " + cmd;
1067 }
1068
1069 if (cmd.begin() + cparen + 1 != cmd.end()) {
1070 ret += " + std::string(\"";
1071 ret += (cmd.c_str() + cparen + 1);
1072 ret += "\")";
1073 }
1074
1075 return ret;
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001076}
1077
1078/// EmitCmdLineVecFill - Emit code that fills in the command line
1079/// vector. Helper function used by EmitGenerateActionMethod().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001080void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
1081 bool Version, const char* IndentLevel,
1082 std::ostream& O) {
1083 StrVector StrVec;
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001084 SplitString(InitPtrToString(CmdLine), StrVec);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001085 if (StrVec.empty())
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001086 throw "Tool " + ToolName + " has empty command line!";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001087
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001088 StrVector::const_iterator I = StrVec.begin();
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001089 ++I;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001090 for (StrVector::const_iterator E = StrVec.end(); I != E; ++I) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001091 const std::string& cmd = *I;
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001092 O << IndentLevel;
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001093 if (cmd.at(0) == '$') {
1094 if (cmd == "$INFILE") {
1095 if (Version)
1096 O << "for (PathVector::const_iterator B = inFiles.begin()"
1097 << ", E = inFiles.end();\n"
1098 << IndentLevel << "B != E; ++B)\n"
1099 << IndentLevel << Indent1 << "vec.push_back(B->toString());\n";
1100 else
1101 O << "vec.push_back(inFile.toString());\n";
1102 }
1103 else if (cmd == "$OUTFILE") {
1104 O << "vec.push_back(outFile.toString());\n";
1105 }
1106 else {
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001107 O << "vec.push_back(" << SubstituteSpecialCommands(cmd);
1108 O << ");\n";
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001109 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001110 }
1111 else {
1112 O << "vec.push_back(\"" << cmd << "\");\n";
1113 }
1114 }
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001115 O << IndentLevel << "cmd = "
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001116 << ((StrVec[0][0] == '$') ? SubstituteSpecialCommands(StrVec[0])
1117 : "\"" + StrVec[0] + "\"")
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001118 << ";\n";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001119}
1120
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001121/// EmitCmdLineVecFillCallback - A function object wrapper around
1122/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
1123/// argument to EmitCaseConstructHandler().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001124class EmitCmdLineVecFillCallback {
1125 bool Version;
1126 const std::string& ToolName;
1127 public:
1128 EmitCmdLineVecFillCallback(bool Ver, const std::string& TN)
1129 : Version(Ver), ToolName(TN) {}
1130
1131 void operator()(const Init* Statement, const char* IndentLevel,
1132 std::ostream& O) const
1133 {
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001134 EmitCmdLineVecFill(Statement, ToolName, Version,
1135 (std::string(IndentLevel) + Indent1).c_str(), O);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001136 }
1137};
1138
1139// EmitGenerateActionMethod - Emit one of two versions of the
1140// Tool::GenerateAction() method.
1141void EmitGenerateActionMethod (const ToolProperties& P,
1142 const GlobalOptionDescriptions& OptDescs,
1143 bool Version, std::ostream& O) {
1144 if (Version)
1145 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n";
1146 else
1147 O << Indent1 << "Action GenerateAction(const sys::Path& inFile,\n";
1148
1149 O << Indent2 << "const sys::Path& outFile,\n"
1150 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
1151 << Indent1 << "{\n"
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001152 << Indent2 << "const char* cmd;\n"
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001153 << Indent2 << "std::vector<std::string> vec;\n";
1154
1155 // cmd_line is either a string or a 'case' construct.
1156 if (typeid(*P.CmdLine) == typeid(StringInit))
1157 EmitCmdLineVecFill(P.CmdLine, P.Name, Version, Indent2, O);
1158 else
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001159 EmitCaseConstructHandler(&InitPtrToDag(P.CmdLine), Indent2,
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001160 EmitCmdLineVecFillCallback(Version, P.Name),
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001161 true, OptDescs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001162
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001163 // For every understood option, emit handling code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001164 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1165 E = P.OptDescs.end(); B != E; ++B) {
1166 const ToolOptionDescription& val = B->second;
Mikhail Glushenkov31f52152008-05-30 06:10:47 +00001167 EmitOptionPropertyHandlingCode(val, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001168 }
1169
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001170 // Handle the Sink property.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001171 if (P.isSink()) {
1172 O << Indent2 << "if (!" << SinkOptionName << ".empty()) {\n"
1173 << Indent3 << "vec.insert(vec.end(), "
1174 << SinkOptionName << ".begin(), " << SinkOptionName << ".end());\n"
1175 << Indent2 << "}\n";
1176 }
1177
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001178 O << Indent2 << "return Action(cmd, vec);\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001179 << Indent1 << "}\n\n";
1180}
1181
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001182/// EmitGenerateActionMethods - Emit two GenerateAction() methods for
1183/// a given Tool class.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001184void EmitGenerateActionMethods (const ToolProperties& P,
1185 const GlobalOptionDescriptions& OptDescs,
1186 std::ostream& O) {
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001187 if (!P.isJoin())
1188 O << Indent1 << "Action GenerateAction(const PathVector& inFiles,\n"
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001189 << Indent2 << "const llvm::sys::Path& outFile,\n"
1190 << Indent2 << "const InputLanguagesSet& InLangs) const\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001191 << Indent1 << "{\n"
1192 << Indent2 << "throw std::runtime_error(\"" << P.Name
1193 << " is not a Join tool!\");\n"
1194 << Indent1 << "}\n\n";
1195 else
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001196 EmitGenerateActionMethod(P, OptDescs, true, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001197
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001198 EmitGenerateActionMethod(P, OptDescs, false, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001199}
1200
Mikhail Glushenkov7adcf1e2008-05-09 08:27:26 +00001201/// EmitIsLastMethod - Emit the IsLast() method for a given Tool
1202/// class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001203void EmitIsLastMethod (const ToolProperties& P, std::ostream& O) {
1204 O << Indent1 << "bool IsLast() const {\n"
1205 << Indent2 << "bool last = false;\n";
1206
1207 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1208 E = P.OptDescs.end(); B != E; ++B) {
1209 const ToolOptionDescription& val = B->second;
1210
1211 if (val.isStopCompilation())
1212 O << Indent2
1213 << "if (" << val.GenVariableName()
1214 << ")\n" << Indent3 << "last = true;\n";
1215 }
1216
1217 O << Indent2 << "return last;\n"
1218 << Indent1 << "}\n\n";
1219}
1220
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001221/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
1222/// methods for a given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001223void EmitInOutLanguageMethods (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001224 O << Indent1 << "const char** InputLanguages() const {\n"
1225 << Indent2 << "return InputLanguages_;\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001226 << Indent1 << "}\n\n";
1227
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001228 O << Indent1 << "const char* OutputLanguage() const {\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001229 << Indent2 << "return \"" << P.OutLanguage << "\";\n"
1230 << Indent1 << "}\n\n";
1231}
1232
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001233/// EmitOutputSuffixMethod - Emit the OutputSuffix() method for a
1234/// given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001235void EmitOutputSuffixMethod (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001236 O << Indent1 << "const char* OutputSuffix() const {\n"
Mikhail Glushenkovabab33b2008-05-30 06:13:02 +00001237 << Indent2 << "const char* ret = \"" << P.OutputSuffix << "\";\n";
1238
1239 for (ToolOptionDescriptions::const_iterator B = P.OptDescs.begin(),
1240 E = P.OptDescs.end(); B != E; ++B) {
1241 const ToolOptionDescription& OptDesc = B->second;
1242 for (OptionPropertyList::const_iterator B = OptDesc.Props.begin(),
1243 E = OptDesc.Props.end(); B != E; ++B) {
1244 const OptionProperty& OptProp = *B;
1245 if (OptProp.first == OptionPropertyType::OutputSuffix) {
1246 O << Indent2 << "if (" << OptDesc.GenVariableName() << ")\n"
1247 << Indent3 << "ret = \"" << OptProp.second << "\";\n";
1248 }
1249 }
1250 }
1251
1252 O << Indent2 << "return ret;\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001253 << Indent1 << "}\n\n";
1254}
1255
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001256/// EmitNameMethod - Emit the Name() method for a given Tool class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001257void EmitNameMethod (const ToolProperties& P, std::ostream& O) {
Mikhail Glushenkovd379d162008-05-06 17:24:26 +00001258 O << Indent1 << "const char* Name() const {\n"
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001259 << Indent2 << "return \"" << P.Name << "\";\n"
1260 << Indent1 << "}\n\n";
1261}
1262
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001263/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
1264/// class.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001265void EmitIsJoinMethod (const ToolProperties& P, std::ostream& O) {
1266 O << Indent1 << "bool IsJoin() const {\n";
1267 if (P.isJoin())
1268 O << Indent2 << "return true;\n";
1269 else
1270 O << Indent2 << "return false;\n";
1271 O << Indent1 << "}\n\n";
1272}
1273
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001274/// EmitStaticMemberDefinitions - Emit static member definitions for a
1275/// given Tool class.
1276void EmitStaticMemberDefinitions(const ToolProperties& P, std::ostream& O) {
1277 O << "const char* " << P.Name << "::InputLanguages_[] = {";
1278 for (StrVector::const_iterator B = P.InLanguage.begin(),
1279 E = P.InLanguage.end(); B != E; ++B)
1280 O << '\"' << *B << "\", ";
1281 O << "0};\n\n";
1282}
1283
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001284/// EmitToolClassDefinition - Emit a Tool class definition.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001285void EmitToolClassDefinition (const ToolProperties& P,
1286 const GlobalOptionDescriptions& OptDescs,
1287 std::ostream& O) {
1288 if (P.Name == "root")
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001289 return;
1290
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001291 // Header
Mikhail Glushenkov121889c2008-05-06 17:26:53 +00001292 O << "class " << P.Name << " : public ";
1293 if (P.isJoin())
1294 O << "JoinTool";
1295 else
1296 O << "Tool";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001297
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001298 O << "{\nprivate:\n"
1299 << Indent1 << "static const char* InputLanguages_[];\n\n";
1300
1301 O << "public:\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001302 EmitNameMethod(P, O);
1303 EmitInOutLanguageMethods(P, O);
1304 EmitOutputSuffixMethod(P, O);
1305 EmitIsJoinMethod(P, O);
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001306 EmitGenerateActionMethods(P, OptDescs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001307 EmitIsLastMethod(P, O);
1308
1309 // Close class definition
Mikhail Glushenkov61923cb2008-05-30 06:24:49 +00001310 O << "};\n";
1311
1312 EmitStaticMemberDefinitions(P, O);
1313
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001314}
1315
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001316/// EmitOptionDescriptions - Iterate over a list of option
1317/// descriptions and emit registration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001318void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
1319 std::ostream& O)
1320{
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001321 std::vector<GlobalOptionDescription> Aliases;
1322
Mikhail Glushenkov52a54132008-05-30 06:23:29 +00001323 // Emit static cl::Option variables.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001324 for (GlobalOptionDescriptions::const_iterator B = descs.begin(),
1325 E = descs.end(); B!=E; ++B) {
1326 const GlobalOptionDescription& val = B->second;
1327
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001328 if (val.Type == OptionType::Alias) {
1329 Aliases.push_back(val);
1330 continue;
1331 }
1332
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001333 O << val.GenTypeDeclaration() << ' '
1334 << val.GenVariableName()
1335 << "(\"" << val.Name << '\"';
1336
1337 if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
1338 O << ", cl::Prefix";
1339
1340 if (val.isRequired()) {
1341 switch (val.Type) {
1342 case OptionType::PrefixList:
1343 case OptionType::ParameterList:
1344 O << ", cl::OneOrMore";
1345 break;
1346 default:
1347 O << ", cl::Required";
1348 }
1349 }
1350
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001351 if (!val.Help.empty())
1352 O << ", cl::desc(\"" << val.Help << "\")";
1353
1354 O << ");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001355 }
1356
Mikhail Glushenkovb623c322008-05-30 06:22:52 +00001357 // Emit the aliases (they should go after all the 'proper' options).
1358 for (std::vector<GlobalOptionDescription>::const_iterator
1359 B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
1360 const GlobalOptionDescription& val = *B;
1361
1362 O << val.GenTypeDeclaration() << ' '
1363 << val.GenVariableName()
1364 << "(\"" << val.Name << '\"';
1365
1366 GlobalOptionDescriptions::container_type
1367 ::const_iterator F = descs.Descriptions.find(val.Help);
1368 if (F != descs.Descriptions.end())
1369 O << ", cl::aliasopt(" << F->second.GenVariableName() << ")";
1370 else
1371 throw val.Name + ": alias to an unknown option!";
1372
1373 O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
1374 }
1375
1376 // Emit the sink option.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001377 if (descs.HasSink)
1378 O << "cl::list<std::string> " << SinkOptionName << "(cl::Sink);\n";
1379
1380 O << '\n';
1381}
1382
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001383/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001384void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
1385{
1386 // Get the relevant field out of RecordKeeper
1387 Record* LangMapRecord = Records.getDef("LanguageMap");
1388 if (!LangMapRecord)
1389 throw std::string("Language map definition not found!");
1390
1391 ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
1392 if (!LangsToSuffixesList)
1393 throw std::string("Error in the language map definition!");
1394
1395 // Generate code
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001396 O << "void llvmc::PopulateLanguageMap() {\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001397
1398 for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
1399 Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
1400
1401 const std::string& Lang = LangToSuffixes->getValueAsString("lang");
1402 const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
1403
1404 for (unsigned i = 0; i < Suffixes->size(); ++i)
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001405 O << Indent1 << "GlobalLanguageMap[\""
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001406 << InitPtrToString(Suffixes->getElement(i))
1407 << "\"] = \"" << Lang << "\";\n";
1408 }
1409
1410 O << "}\n\n";
1411}
1412
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001413/// FillInToolToLang - Fills in two tables that map tool names to
1414/// (input, output) languages. Used by the typechecker.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001415void FillInToolToLang (const ToolPropertiesList& TPList,
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001416 StringMap<StringSet<> >& ToolToInLang,
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001417 StringMap<std::string>& ToolToOutLang) {
1418 for (ToolPropertiesList::const_iterator B = TPList.begin(), E = TPList.end();
1419 B != E; ++B) {
1420 const ToolProperties& P = *(*B);
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001421 for (StrVector::const_iterator B = P.InLanguage.begin(),
1422 E = P.InLanguage.end(); B != E; ++B)
1423 ToolToInLang[P.Name].insert(*B);
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001424 ToolToOutLang[P.Name] = P.OutLanguage;
1425 }
1426}
1427
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001428/// TypecheckGraph - Check that names for output and input languages
1429/// on all edges do match.
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001430// TOFIX: It would be nice if this function also checked for cycles
1431// and multiple default edges in the graph (better error
1432// reporting). Unfortunately, it is awkward to do right now because
1433// our intermediate representation is not sufficiently
1434// sofisticated. Algorithms like these should be run on a real graph
1435// instead of AST.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001436void TypecheckGraph (Record* CompilationGraph,
1437 const ToolPropertiesList& TPList) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001438 StringMap<StringSet<> > ToolToInLang;
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001439 StringMap<std::string> ToolToOutLang;
1440
1441 FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
1442 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001443 StringMap<std::string>::iterator IAE = ToolToOutLang.end();
1444 StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001445
1446 for (unsigned i = 0; i < edges->size(); ++i) {
1447 Record* Edge = edges->getElementAsRecord(i);
1448 Record* A = Edge->getValueAsDef("a");
1449 Record* B = Edge->getValueAsDef("b");
1450 StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001451 StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001452 if (IA == IAE)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001453 throw A->getName() + ": no such tool!";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001454 if (IB == IBE)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001455 throw B->getName() + ": no such tool!";
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001456 if (A->getName() != "root" && IB->second.count(IA->second) == 0)
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001457 throw "Edge " + A->getName() + "->" + B->getName()
1458 + ": output->input language mismatch";
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001459 if (B->getName() == "root")
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001460 throw std::string("Edges back to the root are not allowed!");
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001461 }
1462}
1463
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001464/// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
1465/// by EmitEdgeClass().
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001466void IncDecWeight (const Init* i, const char* IndentLevel,
1467 std::ostream& O) {
Mikhail Glushenkov0e92d2f2008-05-30 06:18:16 +00001468 const DagInit& d = InitPtrToDag(i);
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001469 const std::string& OpName = d.getOperator()->getAsString();
1470
1471 if (OpName == "inc_weight")
1472 O << IndentLevel << Indent1 << "ret += ";
1473 else if (OpName == "dec_weight")
1474 O << IndentLevel << Indent1 << "ret -= ";
1475 else
1476 throw "Unknown operator in edge properties list: " + OpName + '!';
1477
1478 if (d.getNumArgs() > 0)
1479 O << InitPtrToInt(d.getArg(0)) << ";\n";
1480 else
1481 O << "2;\n";
1482
Mikhail Glushenkovdfcad6c2008-05-06 18:18:20 +00001483}
1484
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001485/// EmitEdgeClass - Emit a single Edge# class.
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001486void EmitEdgeClass (unsigned N, const std::string& Target,
1487 DagInit* Case, const GlobalOptionDescriptions& OptDescs,
1488 std::ostream& O) {
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001489
1490 // Class constructor.
1491 O << "class Edge" << N << ": public Edge {\n"
1492 << "public:\n"
1493 << Indent1 << "Edge" << N << "() : Edge(\"" << Target
1494 << "\") {}\n\n"
1495
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001496 // Function Weight().
Mikhail Glushenkovd6228882008-05-06 18:15:12 +00001497 << Indent1 << "unsigned Weight(const InputLanguagesSet& InLangs) const {\n"
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001498 << Indent2 << "unsigned ret = 0;\n";
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001499
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001500 // Handle the 'case' construct.
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001501 EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
Mikhail Glushenkov7dbc0ab2008-05-06 18:14:24 +00001502
1503 O << Indent2 << "return ret;\n"
1504 << Indent1 << "};\n\n};\n\n";
Mikhail Glushenkov8d0d5d22008-05-06 17:23:14 +00001505}
1506
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001507/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001508void EmitEdgeClasses (Record* CompilationGraph,
1509 const GlobalOptionDescriptions& OptDescs,
1510 std::ostream& O) {
1511 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
1512
1513 for (unsigned i = 0; i < edges->size(); ++i) {
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001514 Record* Edge = edges->getElementAsRecord(i);
1515 Record* B = Edge->getValueAsDef("b");
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001516 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001517
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001518 if (isDagEmpty(Weight))
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001519 continue;
1520
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001521 EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001522 }
1523}
1524
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001525/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
1526/// function.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001527void EmitPopulateCompilationGraph (Record* CompilationGraph,
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001528 std::ostream& O)
1529{
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001530 ListInit* edges = CompilationGraph->getValueAsListInit("edges");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001531
1532 // Generate code
Mikhail Glushenkov34307a92008-05-06 18:08:59 +00001533 O << "void llvmc::PopulateCompilationGraph(CompilationGraph& G) {\n"
Mikhail Glushenkov242d0e62008-05-30 06:19:52 +00001534 << Indent1 << "PopulateLanguageMap();\n\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001535
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001536 // Insert vertices
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001537
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001538 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1539 if (Tools.empty())
1540 throw std::string("No tool definitions found!");
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001541
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001542 for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
1543 const std::string& Name = (*B)->getName();
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001544 if (Name != "root")
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001545 O << Indent1 << "G.insertNode(new "
1546 << Name << "());\n";
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001547 }
1548
1549 O << '\n';
1550
1551 // Insert edges
Mikhail Glushenkov2cfd2232008-05-06 16:35:25 +00001552 for (unsigned i = 0; i < edges->size(); ++i) {
1553 Record* Edge = edges->getElementAsRecord(i);
1554 Record* A = Edge->getValueAsDef("a");
1555 Record* B = Edge->getValueAsDef("b");
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001556 DagInit* Weight = Edge->getValueAsDag("weight");
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001557
1558 O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
1559
Mikhail Glushenkovdedba642008-05-30 06:08:50 +00001560 if (isDagEmpty(Weight))
Mikhail Glushenkov761958d2008-05-06 16:36:50 +00001561 O << "new SimpleEdge(\"" << B->getName() << "\")";
1562 else
1563 O << "new Edge" << i << "()";
1564
1565 O << ");\n";
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001566 }
1567
1568 O << "}\n\n";
1569}
1570
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001571/// ExtractHookNames - Extract the hook names from all instances of
1572/// $CALL(HookName) in the provided command line string. Helper
1573/// function used by FillInHookNames().
1574void ExtractHookNames(const Init* CmdLine, StrVector& HookNames) {
1575 StrVector cmds;
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001576 llvm::SplitString(InitPtrToString(CmdLine), cmds);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001577 for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
1578 B != E; ++B) {
1579 const std::string& cmd = *B;
1580 if (cmd.find("$CALL(") == 0) {
1581 if (cmd.size() == 6)
1582 throw std::string("$CALL invocation: empty argument list!");
Mikhail Glushenkov1e453b02008-05-30 06:13:29 +00001583 HookNames.push_back(std::string(cmd.begin() + 6,
1584 cmd.begin() + cmd.find(")")));
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001585 }
1586 }
1587}
1588
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001589/// ExtractHookNamesFromCaseConstruct - Extract hook names from the
1590/// 'case' expression, handle nesting. Helper function used by
1591/// FillInHookNames().
1592void ExtractHookNamesFromCaseConstruct(Init* Case, StrVector& HookNames) {
1593 const DagInit& d = InitPtrToDag(Case);
1594 bool even = false;
1595 for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
1596 B != E; ++B) {
1597 Init* arg = *B;
1598 if (even && dynamic_cast<DagInit*>(arg)
1599 && static_cast<DagInit*>(arg)->getOperator()->getAsString() == "case")
1600 ExtractHookNamesFromCaseConstruct(arg, HookNames);
1601 else if (even)
1602 ExtractHookNames(arg, HookNames);
1603 even = !even;
1604 }
1605}
1606
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001607/// FillInHookNames - Actually extract the hook names from all command
1608/// line strings. Helper function used by EmitHookDeclarations().
1609void FillInHookNames(const ToolPropertiesList& TPList,
1610 StrVector& HookNames) {
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001611 // For all command lines:
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001612 for (ToolPropertiesList::const_iterator B = TPList.begin(),
1613 E = TPList.end(); B != E; ++B) {
1614 const ToolProperties& P = *(*B);
1615 if (!P.CmdLine)
1616 continue;
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001617 if (dynamic_cast<StringInit*>(P.CmdLine))
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001618 // This is a string.
1619 ExtractHookNames(P.CmdLine, HookNames);
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001620 else
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001621 // This is a 'case' construct.
Mikhail Glushenkovb24c8b22008-05-30 06:22:15 +00001622 ExtractHookNamesFromCaseConstruct(P.CmdLine, HookNames);
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001623 }
1624}
1625
1626/// EmitHookDeclarations - Parse CmdLine fields of all the tool
1627/// property records and emit hook function declaration for each
1628/// instance of $CALL(HookName).
1629void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
1630 std::ostream& O) {
1631 StrVector HookNames;
1632 FillInHookNames(ToolProps, HookNames);
1633 if (HookNames.empty())
1634 return;
1635 std::sort(HookNames.begin(), HookNames.end());
1636 StrVector::const_iterator E = std::unique(HookNames.begin(), HookNames.end());
1637
1638 O << "namespace hooks {\n";
1639 for (StrVector::const_iterator B = HookNames.begin(); B != E; ++B)
1640 O << Indent1 << "std::string " << *B << "();\n";
1641
1642 O << "}\n\n";
1643}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001644
1645// End of anonymous namespace
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +00001646}
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001647
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001648/// run - The back-end entry point.
Mikhail Glushenkovc1f738d2008-05-06 18:12:03 +00001649void LLVMCConfigurationEmitter::run (std::ostream &O) {
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +00001650 try {
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001651
1652 // Emit file header.
Mikhail Glushenkov34307a92008-05-06 18:08:59 +00001653 EmitSourceFileHeader("LLVMC Configuration Library", O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001654
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001655 // Get a list of all defined Tools.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001656 RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
1657 if (Tools.empty())
1658 throw std::string("No tool definitions found!");
1659
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001660 // Gather information from the Tool description dags.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001661 ToolPropertiesList tool_props;
1662 GlobalOptionDescriptions opt_descs;
1663 CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
1664
Mikhail Glushenkovd638e852008-05-30 06:26:08 +00001665 RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
1666 CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
1667 opt_descs);
1668
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001669 // Emit global option registration code.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001670 EmitOptionDescriptions(opt_descs, O);
1671
Mikhail Glushenkov793f63d2008-05-30 06:12:24 +00001672 // Emit hook declarations.
1673 EmitHookDeclarations(tool_props, O);
1674
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001675 // Emit PopulateLanguageMap() function
1676 // (a language map maps from file extensions to language names).
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001677 EmitPopulateLanguageMap(Records, O);
1678
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001679 // Emit Tool classes.
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001680 for (ToolPropertiesList::const_iterator B = tool_props.begin(),
1681 E = tool_props.end(); B!=E; ++B)
Mikhail Glushenkov35576b02008-05-30 06:10:19 +00001682 EmitToolClassDefinition(*(*B), opt_descs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001683
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001684 Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
1685 if (!CompilationGraphRecord)
1686 throw std::string("Compilation graph description not found!");
1687
1688 // Typecheck the compilation graph.
1689 TypecheckGraph(CompilationGraphRecord, tool_props);
1690
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001691 // Emit Edge# classes.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001692 EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001693
Mikhail Glushenkovbe46ae12008-05-07 21:50:19 +00001694 // Emit PopulateCompilationGraph() function.
Mikhail Glushenkov46d4e972008-05-06 16:36:06 +00001695 EmitPopulateCompilationGraph(CompilationGraphRecord, O);
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001696
1697 // EOF
Mikhail Glushenkovffe736e2008-05-30 06:21:48 +00001698 } catch (std::exception& Error) {
1699 throw Error.what() + std::string(" - usually this means a syntax error.");
1700 }
Anton Korobeynikove9ffb5b2008-03-23 08:57:20 +00001701}