blob: 26e4ceeb39e7fb61dda2aee1c1049dac831a6d95 [file] [log] [blame]
Reid Spencera3f18552004-08-13 20:25:54 +00001//===- CompilerDriver.cpp - The LLVM Compiler Driver ------------*- C++ -*-===//
Reid Spencer5c56dc12004-08-13 20:22:43 +00002//
3//
4// The LLVM Compiler Infrastructure
5//
6// This file was developed by Reid Spencer and is distributed under the
7// University of Illinois Open Source License. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10//
Reid Spencera3f18552004-08-13 20:25:54 +000011// This file implements the bulk of the LLVM Compiler Driver (llvmc).
Reid Spencer5c56dc12004-08-13 20:22:43 +000012//
13//===------------------------------------------------------------------------===
14
15#include "CompilerDriver.h"
Reid Spencerbf437722004-08-15 08:19:46 +000016#include "ConfigLexer.h"
Reid Spencera01439a2004-08-24 13:55:17 +000017#include "llvm/Module.h"
Reid Spencer52c2dc12004-08-29 19:26:56 +000018#include "llvm/Bytecode/Reader.h"
Reid Spencer54fafe42004-09-14 01:58:45 +000019#include "llvm/Support/Timer.h"
Reid Spencer93426ba2004-08-29 20:02:28 +000020#include "llvm/System/Signals.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/StringExtras.h"
Reid Spencer5c56dc12004-08-13 20:22:43 +000023#include <iostream>
24
25using namespace llvm;
26
27namespace {
Reid Spencer5c56dc12004-08-13 20:22:43 +000028
Reid Spenceraf77d742004-10-28 04:05:06 +000029void WriteAction(CompilerDriver::Action* action ) {
30 std::cerr << action->program.c_str();
31 std::vector<std::string>::iterator I = action->args.begin();
32 while (I != action->args.end()) {
33 std::cerr << " " + *I;
34 ++I;
35 }
36 std::cerr << "\n";
37}
38
39void DumpAction(CompilerDriver::Action* action) {
40 std::cerr << "command = " << action->program.c_str();
41 std::vector<std::string>::iterator I = action->args.begin();
42 while (I != action->args.end()) {
43 std::cerr << " " + *I;
44 ++I;
45 }
46 std::cerr << "\n";
47 std::cerr << "flags = " << action->flags << "\n";
48}
49
50void DumpConfigData(CompilerDriver::ConfigData* cd, const std::string& type ){
51 std::cerr << "Configuration Data For '" << cd->langName << "' (" << type
52 << ")\n";
53 std::cerr << "PreProcessor: ";
54 DumpAction(&cd->PreProcessor);
55 std::cerr << "Translator: ";
56 DumpAction(&cd->Translator);
57 std::cerr << "Optimizer: ";
58 DumpAction(&cd->Optimizer);
59 std::cerr << "Assembler: ";
60 DumpAction(&cd->Assembler);
61 std::cerr << "Linker: ";
62 DumpAction(&cd->Linker);
63}
64
65/// This specifies the passes to run for OPT_FAST_COMPILE (-O1)
66/// which should reduce the volume of code and make compilation
67/// faster. This is also safe on any llvm module.
68static const char* DefaultFastCompileOptimizations[] = {
69 "-simplifycfg", "-mem2reg", "-instcombine"
70};
71
72class CompilerDriverImpl : public CompilerDriver {
73/// @name Constructors
74/// @{
75public:
76 CompilerDriverImpl(ConfigDataProvider& confDatProv )
77 : cdp(&confDatProv)
78 , finalPhase(LINKING)
79 , optLevel(OPT_FAST_COMPILE)
80 , Flags(0)
81 , machine()
82 , LibraryPaths()
83 , TempDir()
84 , AdditionalArgs()
85 {
86 TempDir = sys::Path::GetTemporaryDirectory();
87 sys::RemoveDirectoryOnSignal(TempDir);
88 AdditionalArgs.reserve(NUM_PHASES);
89 StringVector emptyVec;
90 for (unsigned i = 0; i < NUM_PHASES; ++i)
91 AdditionalArgs.push_back(emptyVec);
92 }
93
94 virtual ~CompilerDriverImpl() {
95 cleanup();
96 cdp = 0;
97 LibraryPaths.clear();
98 IncludePaths.clear();
99 Defines.clear();
100 TempDir.clear();
101 AdditionalArgs.clear();
102 fOptions.clear();
103 MOptions.clear();
104 WOptions.clear();
105 }
106
107/// @}
108/// @name Methods
109/// @{
110public:
111 virtual void setFinalPhase( Phases phase ) {
112 finalPhase = phase;
113 }
114
115 virtual void setOptimization( OptimizationLevels level ) {
116 optLevel = level;
117 }
118
119 virtual void setDriverFlags( unsigned flags ) {
120 Flags = flags & DRIVER_FLAGS_MASK;
121 }
122
123 virtual void setOutputMachine( const std::string& machineName ) {
124 machine = machineName;
125 }
126
127 virtual void setPhaseArgs(Phases phase, const StringVector& opts) {
128 assert(phase <= LINKING && phase >= PREPROCESSING);
129 AdditionalArgs[phase] = opts;
130 }
131
132 virtual void setIncludePaths(const StringVector& paths) {
133 StringVector::const_iterator I = paths.begin();
134 StringVector::const_iterator E = paths.end();
135 while (I != E) {
136 sys::Path tmp;
Reid Spencer07adb282004-11-05 22:15:36 +0000137 tmp.setDirectory(*I);
Reid Spenceraf77d742004-10-28 04:05:06 +0000138 IncludePaths.push_back(tmp);
Reid Spencer68fb37a2004-08-14 09:37:15 +0000139 ++I;
140 }
Reid Spencer68fb37a2004-08-14 09:37:15 +0000141 }
142
Reid Spenceraf77d742004-10-28 04:05:06 +0000143 virtual void setSymbolDefines(const StringVector& defs) {
144 Defines = defs;
145 }
146
147 virtual void setLibraryPaths(const StringVector& paths) {
148 StringVector::const_iterator I = paths.begin();
149 StringVector::const_iterator E = paths.end();
150 while (I != E) {
151 sys::Path tmp;
Reid Spencer07adb282004-11-05 22:15:36 +0000152 tmp.setDirectory(*I);
Reid Spenceraf77d742004-10-28 04:05:06 +0000153 LibraryPaths.push_back(tmp);
Reid Spencerbf437722004-08-15 08:19:46 +0000154 ++I;
155 }
Reid Spencerbf437722004-08-15 08:19:46 +0000156 }
157
Reid Spenceraf77d742004-10-28 04:05:06 +0000158 virtual void addLibraryPath( const sys::Path& libPath ) {
159 LibraryPaths.push_back(libPath);
Reid Spencer68fb37a2004-08-14 09:37:15 +0000160 }
Reid Spencer5c56dc12004-08-13 20:22:43 +0000161
Reid Spencer07adb282004-11-05 22:15:36 +0000162 virtual void addToolPath( const sys::Path& toolPath ) {
163 ToolPaths.push_back(toolPath);
164 }
165
Reid Spenceraf77d742004-10-28 04:05:06 +0000166 virtual void setfPassThrough(const StringVector& fOpts) {
167 fOptions = fOpts;
168 }
Reid Spencer5c56dc12004-08-13 20:22:43 +0000169
Reid Spenceraf77d742004-10-28 04:05:06 +0000170 /// @brief Set the list of -M options to be passed through
171 virtual void setMPassThrough(const StringVector& MOpts) {
172 MOptions = MOpts;
173 }
Reid Spencerbae68252004-08-19 04:49:47 +0000174
Reid Spenceraf77d742004-10-28 04:05:06 +0000175 /// @brief Set the list of -W options to be passed through
176 virtual void setWPassThrough(const StringVector& WOpts) {
177 WOptions = WOpts;
178 }
179/// @}
180/// @name Functions
181/// @{
182private:
183 bool isSet(DriverFlags flag) {
184 return 0 != ((flag & DRIVER_FLAGS_MASK) & Flags);
185 }
Reid Spencerbae68252004-08-19 04:49:47 +0000186
Reid Spenceraf77d742004-10-28 04:05:06 +0000187 void cleanup() {
188 if (!isSet(KEEP_TEMPS_FLAG)) {
Reid Spencer07adb282004-11-05 22:15:36 +0000189 if (TempDir.isDirectory() && TempDir.writable())
190 TempDir.destroyDirectory(/*remove_contents=*/true);
Reid Spenceraf77d742004-10-28 04:05:06 +0000191 } else {
192 std::cout << "Temporary files are in " << TempDir.get() << "\n";
193 }
194 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000195
Reid Spenceraf77d742004-10-28 04:05:06 +0000196 sys::Path MakeTempFile(const std::string& basename,
197 const std::string& suffix ) {
198 sys::Path result(TempDir);
Reid Spencer07adb282004-11-05 22:15:36 +0000199 if (!result.appendFile(basename))
Reid Spenceraf77d742004-10-28 04:05:06 +0000200 throw basename + ": can't use this file name";
Reid Spencer07adb282004-11-05 22:15:36 +0000201 if (!result.appendSuffix(suffix))
Reid Spenceraf77d742004-10-28 04:05:06 +0000202 throw suffix + ": can't use this file suffix";
203 return result;
204 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000205
Reid Spenceraf77d742004-10-28 04:05:06 +0000206 Action* GetAction(ConfigData* cd,
207 const sys::Path& input,
208 const sys::Path& output,
209 Phases phase)
210 {
211 Action* pat = 0; ///< The pattern/template for the action
212 Action* action = new Action; ///< The actual action to execute
Reid Spencer52c2dc12004-08-29 19:26:56 +0000213
Reid Spenceraf77d742004-10-28 04:05:06 +0000214 // Get the action pattern
215 switch (phase) {
216 case PREPROCESSING: pat = &cd->PreProcessor; break;
217 case TRANSLATION: pat = &cd->Translator; break;
218 case OPTIMIZATION: pat = &cd->Optimizer; break;
219 case ASSEMBLY: pat = &cd->Assembler; break;
220 case LINKING: pat = &cd->Linker; break;
221 default:
222 assert(!"Invalid driver phase!");
223 break;
224 }
225 assert(pat != 0 && "Invalid command pattern");
Reid Spencer52c2dc12004-08-29 19:26:56 +0000226
Reid Spenceraf77d742004-10-28 04:05:06 +0000227 // Copy over some pattern things that don't need to change
228 action->program = pat->program;
229 action->flags = pat->flags;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000230
Reid Spenceraf77d742004-10-28 04:05:06 +0000231 // Do the substitutions from the pattern to the actual
232 StringVector::iterator PI = pat->args.begin();
233 StringVector::iterator PE = pat->args.end();
234 while (PI != PE) {
235 if ((*PI)[0] == '%' && PI->length() >2) {
236 bool found = true;
237 switch ((*PI)[1]) {
238 case 'a':
239 if (*PI == "%args%") {
240 if (AdditionalArgs.size() > unsigned(phase))
241 if (!AdditionalArgs[phase].empty()) {
242 // Get specific options for each kind of action type
243 StringVector& addargs = AdditionalArgs[phase];
244 // Add specific options for each kind of action type
245 action->args.insert(action->args.end(), addargs.begin(),
246 addargs.end());
247 }
248 } else
249 found = false;
250 break;
251 case 'd':
252 if (*PI == "%defs%") {
253 StringVector::iterator I = Defines.begin();
254 StringVector::iterator E = Defines.end();
255 while (I != E) {
256 action->args.push_back( std::string("-D") + *I);
257 ++I;
258 }
259 } else
260 found = false;
261 break;
262 case 'f':
263 if (*PI == "%fOpts%") {
264 action->args.insert(action->args.end(), fOptions.begin(),
265 fOptions.end());
266 } else
267 found = false;
268 break;
269 case 'i':
270 if (*PI == "%in%") {
271 action->args.push_back(input.get());
272 } else if (*PI == "%incls%") {
273 PathVector::iterator I = IncludePaths.begin();
274 PathVector::iterator E = IncludePaths.end();
275 while (I != E) {
276 action->args.push_back( std::string("-I") + I->get() );
277 ++I;
278 }
279 } else
280 found = false;
281 break;
282 case 'l':
283 if (*PI == "%libs%") {
284 PathVector::iterator I = LibraryPaths.begin();
285 PathVector::iterator E = LibraryPaths.end();
286 while (I != E) {
287 action->args.push_back( std::string("-L") + I->get() );
288 ++I;
289 }
290 } else
291 found = false;
292 break;
293 case 'o':
294 if (*PI == "%out%") {
295 action->args.push_back(output.get());
296 } else if (*PI == "%opt%") {
297 if (!isSet(EMIT_RAW_FLAG)) {
298 if (cd->opts.size() > static_cast<unsigned>(optLevel) &&
299 !cd->opts[optLevel].empty())
300 action->args.insert(action->args.end(),
301 cd->opts[optLevel].begin(),
302 cd->opts[optLevel].end());
303 else
304 throw std::string("Optimization options for level ") +
305 utostr(unsigned(optLevel)) + " were not specified";
306 }
307 } else
308 found = false;
309 break;
310 case 's':
311 if (*PI == "%stats%") {
312 if (isSet(SHOW_STATS_FLAG))
313 action->args.push_back("-stats");
314 } else
315 found = false;
316 break;
317 case 't':
318 if (*PI == "%target%") {
319 action->args.push_back(std::string("-march=") + machine);
320 } else if (*PI == "%time%") {
321 if (isSet(TIME_PASSES_FLAG))
322 action->args.push_back("-time-passes");
323 } else
324 found = false;
325 break;
326 case 'v':
327 if (*PI == "%verbose%") {
328 if (isSet(VERBOSE_FLAG))
329 action->args.push_back("-v");
330 } else
331 found = false;
332 break;
333 case 'M':
334 if (*PI == "%Mopts") {
335 action->args.insert(action->args.end(), MOptions.begin(),
336 MOptions.end());
337 } else
338 found = false;
339 break;
340 case 'W':
341 if (*PI == "%Wopts") {
342 action->args.insert(action->args.end(), WOptions.begin(),
343 WOptions.end());
344 } else
345 found = false;
346 break;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000347 default:
Reid Spenceraf77d742004-10-28 04:05:06 +0000348 found = false;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000349 break;
350 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000351 if (!found) {
352 // Did it even look like a substitution?
353 if (PI->length()>1 && (*PI)[0] == '%' &&
354 (*PI)[PI->length()-1] == '%') {
355 throw std::string("Invalid substitution token: '") + *PI +
356 "' for command '" + pat->program.get() + "'";
Reid Spencer52c2dc12004-08-29 19:26:56 +0000357 } else {
Reid Spenceraf77d742004-10-28 04:05:06 +0000358 // It's not a legal substitution, just pass it through
Reid Spencer52c2dc12004-08-29 19:26:56 +0000359 action->args.push_back(*PI);
360 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000361 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000362 } else {
363 // Its not a substitution, just put it in the action
364 action->args.push_back(*PI);
Reid Spencer52c2dc12004-08-29 19:26:56 +0000365 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000366 PI++;
367 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000368
Reid Spenceraf77d742004-10-28 04:05:06 +0000369 // Finally, we're done
370 return action;
371 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000372
Reid Spenceraf77d742004-10-28 04:05:06 +0000373 bool DoAction(Action*action) {
374 assert(action != 0 && "Invalid Action!");
375 if (isSet(VERBOSE_FLAG))
376 WriteAction(action);
377 if (!isSet(DRY_RUN_FLAG)) {
378 sys::Path progpath = sys::Program::FindProgramByName(
379 action->program.get());
Reid Spencer07adb282004-11-05 22:15:36 +0000380 if (progpath.isEmpty())
Reid Spenceraf77d742004-10-28 04:05:06 +0000381 throw std::string("Can't find program '"+progpath.get()+"'");
382 else if (progpath.executable())
383 action->program = progpath;
384 else
385 throw std::string("Program '"+progpath.get()+"' is not executable.");
386
387 // Invoke the program
388 if (isSet(TIME_ACTIONS_FLAG)) {
389 Timer timer(action->program.get());
390 timer.startTimer();
391 int resultCode =
392 sys::Program::ExecuteAndWait(action->program,action->args);
393 timer.stopTimer();
394 timer.print(timer,std::cerr);
395 return resultCode == 0;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000396 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000397 else
398 return 0 ==
399 sys::Program::ExecuteAndWait(action->program, action->args);
400 }
401 return true;
402 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000403
Reid Spenceraf77d742004-10-28 04:05:06 +0000404 /// This method tries various variants of a linkage item's file
405 /// name to see if it can find an appropriate file to link with
406 /// in the directory specified.
407 llvm::sys::Path GetPathForLinkageItem(const std::string& link_item,
408 const sys::Path& dir,
409 bool native = false) {
410 sys::Path fullpath(dir);
Reid Spencer07adb282004-11-05 22:15:36 +0000411 fullpath.appendFile(link_item);
Reid Spenceraf77d742004-10-28 04:05:06 +0000412 if (native) {
Reid Spencer07adb282004-11-05 22:15:36 +0000413 fullpath.appendSuffix("a");
Reid Spenceraf77d742004-10-28 04:05:06 +0000414 } else {
Reid Spencer07adb282004-11-05 22:15:36 +0000415 fullpath.appendSuffix("bc");
Reid Spenceraf77d742004-10-28 04:05:06 +0000416 if (fullpath.readable())
Reid Spencer52c2dc12004-08-29 19:26:56 +0000417 return fullpath;
Reid Spencer07adb282004-11-05 22:15:36 +0000418 fullpath.elideSuffix();
419 fullpath.appendSuffix("o");
Reid Spenceraf77d742004-10-28 04:05:06 +0000420 if (fullpath.readable())
421 return fullpath;
422 fullpath = dir;
Reid Spencer07adb282004-11-05 22:15:36 +0000423 fullpath.appendFile(std::string("lib") + link_item);
424 fullpath.appendSuffix("a");
Reid Spenceraf77d742004-10-28 04:05:06 +0000425 if (fullpath.readable())
426 return fullpath;
Reid Spencer07adb282004-11-05 22:15:36 +0000427 fullpath.elideSuffix();
428 fullpath.appendSuffix("so");
Reid Spenceraf77d742004-10-28 04:05:06 +0000429 if (fullpath.readable())
430 return fullpath;
431 }
432
433 // Didn't find one.
434 fullpath.clear();
435 return fullpath;
436 }
437
438 /// This method processes a linkage item. The item could be a
439 /// Bytecode file needing translation to native code and that is
440 /// dependent on other bytecode libraries, or a native code
441 /// library that should just be linked into the program.
442 bool ProcessLinkageItem(const llvm::sys::Path& link_item,
443 SetVector<sys::Path>& set,
444 std::string& err) {
445 // First, see if the unadorned file name is not readable. If so,
446 // we must track down the file in the lib search path.
447 sys::Path fullpath;
448 if (!link_item.readable()) {
449 // First, look for the library using the -L arguments specified
450 // on the command line.
451 PathVector::iterator PI = LibraryPaths.begin();
452 PathVector::iterator PE = LibraryPaths.end();
Reid Spencer07adb282004-11-05 22:15:36 +0000453 while (PI != PE && fullpath.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000454 fullpath = GetPathForLinkageItem(link_item.get(),*PI);
455 ++PI;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000456 }
457
Reid Spenceraf77d742004-10-28 04:05:06 +0000458 // If we didn't find the file in any of the library search paths
459 // so we have to bail. No where else to look.
Reid Spencer07adb282004-11-05 22:15:36 +0000460 if (fullpath.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000461 err =
462 std::string("Can't find linkage item '") + link_item.get() + "'";
463 return false;
464 }
465 } else {
466 fullpath = link_item;
467 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000468
Reid Spenceraf77d742004-10-28 04:05:06 +0000469 // If we got here fullpath is the path to the file, and its readable.
470 set.insert(fullpath);
Reid Spencer52c2dc12004-08-29 19:26:56 +0000471
Reid Spenceraf77d742004-10-28 04:05:06 +0000472 // If its an LLVM bytecode file ...
Reid Spencer07adb282004-11-05 22:15:36 +0000473 if (fullpath.isBytecodeFile()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000474 // Process the dependent libraries recursively
475 Module::LibraryListType modlibs;
476 if (GetBytecodeDependentLibraries(fullpath.get(),modlibs)) {
477 // Traverse the dependent libraries list
478 Module::lib_iterator LI = modlibs.begin();
479 Module::lib_iterator LE = modlibs.end();
480 while ( LI != LE ) {
481 if (!ProcessLinkageItem(sys::Path(*LI),set,err)) {
482 if (err.empty()) {
483 err = std::string("Library '") + *LI +
484 "' is not valid for linking but is required by file '" +
485 fullpath.get() + "'";
486 } else {
487 err += " which is required by file '" + fullpath.get() + "'";
Reid Spencer52c2dc12004-08-29 19:26:56 +0000488 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000489 return false;
490 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000491 ++LI;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000492 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000493 } else if (err.empty()) {
494 err = std::string(
495 "The dependent libraries could not be extracted from '") +
496 fullpath.get();
497 return false;
498 }
499 }
500 return true;
501 }
502
503/// @}
504/// @name Methods
505/// @{
506public:
507 virtual int execute(const InputList& InpList, const sys::Path& Output ) {
508 try {
509 // Echo the configuration of options if we're running verbose
510 if (isSet(DEBUG_FLAG)) {
511 std::cerr << "Compiler Driver Options:\n";
512 std::cerr << "DryRun = " << isSet(DRY_RUN_FLAG) << "\n";
513 std::cerr << "Verbose = " << isSet(VERBOSE_FLAG) << " \n";
514 std::cerr << "TimeActions = " << isSet(TIME_ACTIONS_FLAG) << "\n";
515 std::cerr << "TimePasses = " << isSet(TIME_PASSES_FLAG) << "\n";
516 std::cerr << "ShowStats = " << isSet(SHOW_STATS_FLAG) << "\n";
517 std::cerr << "EmitRawCode = " << isSet(EMIT_RAW_FLAG) << "\n";
518 std::cerr << "EmitNativeCode = " << isSet(EMIT_NATIVE_FLAG) << "\n";
519 std::cerr << "KeepTemps = " << isSet(KEEP_TEMPS_FLAG) << "\n";
520 std::cerr << "OutputMachine = " << machine << "\n";
521 InputList::const_iterator I = InpList.begin();
522 while ( I != InpList.end() ) {
523 std::cerr << "Input: " << I->first.get() << "(" << I->second
524 << ")\n";
525 ++I;
526 }
527 std::cerr << "Output: " << Output.get() << "\n";
Reid Spencer52c2dc12004-08-29 19:26:56 +0000528 }
529
Reid Spenceraf77d742004-10-28 04:05:06 +0000530 // If there's no input, we're done.
531 if (InpList.empty())
532 throw std::string("Nothing to compile.");
Reid Spencer52c2dc12004-08-29 19:26:56 +0000533
Reid Spenceraf77d742004-10-28 04:05:06 +0000534 // If they are asking for linking and didn't provide an output
535 // file then its an error (no way for us to "make up" a meaningful
536 // file name based on the various linker input files).
Reid Spencer07adb282004-11-05 22:15:36 +0000537 if (finalPhase == LINKING && Output.isEmpty())
Reid Spenceraf77d742004-10-28 04:05:06 +0000538 throw std::string(
539 "An output file name must be specified for linker output");
Reid Spencer52c2dc12004-08-29 19:26:56 +0000540
Reid Spenceraf77d742004-10-28 04:05:06 +0000541 // If they are not asking for linking, provided an output file and
542 // there is more than one input file, its an error
Reid Spencer07adb282004-11-05 22:15:36 +0000543 if (finalPhase != LINKING && !Output.isEmpty() && InpList.size() > 1)
Reid Spenceraf77d742004-10-28 04:05:06 +0000544 throw std::string("An output file name cannot be specified ") +
545 "with more than one input file name when not linking";
546
547 // This vector holds all the resulting actions of the following loop.
548 std::vector<Action*> actions;
549
550 /// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases
551 // for each input item
552 SetVector<sys::Path> LinkageItems;
553 std::vector<std::string> LibFiles;
554 InputList::const_iterator I = InpList.begin();
Reid Spencer679a7232004-11-20 20:39:33 +0000555 for (InputList::const_iterator I = InpList.begin(), E = InpList.end();
556 I != E; ++I ) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000557 // Get the suffix of the file name
558 const std::string& ftype = I->second;
559
560 // If its a library, bytecode file, or object file, save
561 // it for linking below and short circuit the
562 // pre-processing/translation/assembly phases
563 if (ftype.empty() || ftype == "o" || ftype == "bc" || ftype=="a") {
564 // We shouldn't get any of these types of files unless we're
565 // later going to link. Enforce this limit now.
566 if (finalPhase != LINKING) {
Reid Spencer52c2dc12004-08-29 19:26:56 +0000567 throw std::string(
Reid Spenceraf77d742004-10-28 04:05:06 +0000568 "Pre-compiled objects found but linking not requested");
569 }
570 if (ftype.empty())
571 LibFiles.push_back(I->first.get());
572 else
573 LinkageItems.insert(I->first);
Reid Spencer679a7232004-11-20 20:39:33 +0000574 continue; // short circuit remainder of loop
Reid Spenceraf77d742004-10-28 04:05:06 +0000575 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000576
Reid Spenceraf77d742004-10-28 04:05:06 +0000577 // At this point, we know its something we need to translate
578 // and/or optimize. See if we can get the configuration data
579 // for this kind of file.
580 ConfigData* cd = cdp->ProvideConfigData(I->second);
581 if (cd == 0)
582 throw std::string("Files of type '") + I->second +
583 "' are not recognized.";
584 if (isSet(DEBUG_FLAG))
585 DumpConfigData(cd,I->second);
Reid Spencer54fafe42004-09-14 01:58:45 +0000586
Reid Spenceraf77d742004-10-28 04:05:06 +0000587 // Initialize the input and output files
588 sys::Path InFile(I->first);
Reid Spencer07adb282004-11-05 22:15:36 +0000589 sys::Path OutFile(I->first.getBasename());
Reid Spencer52c2dc12004-08-29 19:26:56 +0000590
Reid Spenceraf77d742004-10-28 04:05:06 +0000591 // PRE-PROCESSING PHASE
592 Action& action = cd->PreProcessor;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000593
Reid Spenceraf77d742004-10-28 04:05:06 +0000594 // Get the preprocessing action, if needed, or error if appropriate
Reid Spencer07adb282004-11-05 22:15:36 +0000595 if (!action.program.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000596 if (action.isSet(REQUIRED_FLAG) || finalPhase == PREPROCESSING) {
597 if (finalPhase == PREPROCESSING) {
Reid Spencer679a7232004-11-20 20:39:33 +0000598 if (Output.isEmpty()) {
599 OutFile.appendSuffix("E");
600 actions.push_back(GetAction(cd,InFile,OutFile,PREPROCESSING));
601 } else {
602 actions.push_back(GetAction(cd,InFile,Output,PREPROCESSING));
603 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000604 } else {
Reid Spencer07adb282004-11-05 22:15:36 +0000605 sys::Path TempFile(MakeTempFile(I->first.getBasename(),"E"));
Reid Spenceraf77d742004-10-28 04:05:06 +0000606 actions.push_back(GetAction(cd,InFile,TempFile,
607 PREPROCESSING));
608 InFile = TempFile;
609 }
610 }
611 } else if (finalPhase == PREPROCESSING) {
612 throw cd->langName + " does not support pre-processing";
613 } else if (action.isSet(REQUIRED_FLAG)) {
614 throw std::string("Don't know how to pre-process ") +
615 cd->langName + " files";
616 }
617
618 // Short-circuit remaining actions if all they want is
619 // pre-processing
Reid Spencer679a7232004-11-20 20:39:33 +0000620 if (finalPhase == PREPROCESSING) { continue; };
Reid Spenceraf77d742004-10-28 04:05:06 +0000621
622 /// TRANSLATION PHASE
623 action = cd->Translator;
624
625 // Get the translation action, if needed, or error if appropriate
Reid Spencer07adb282004-11-05 22:15:36 +0000626 if (!action.program.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000627 if (action.isSet(REQUIRED_FLAG) || finalPhase == TRANSLATION) {
628 if (finalPhase == TRANSLATION) {
Reid Spencer679a7232004-11-20 20:39:33 +0000629 if (Output.isEmpty()) {
630 OutFile.appendSuffix("o");
631 actions.push_back(GetAction(cd,InFile,OutFile,TRANSLATION));
632 } else {
633 actions.push_back(GetAction(cd,InFile,Output,TRANSLATION));
634 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000635 } else {
Reid Spencer07adb282004-11-05 22:15:36 +0000636 sys::Path TempFile(MakeTempFile(I->first.getBasename(),"trans"));
Reid Spenceraf77d742004-10-28 04:05:06 +0000637 actions.push_back(GetAction(cd,InFile,TempFile,TRANSLATION));
638 InFile = TempFile;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000639 }
640
Reid Spenceraf77d742004-10-28 04:05:06 +0000641 // ll -> bc Helper
642 if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
643 /// The output of the translator is an LLVM Assembly program
644 /// We need to translate it to bytecode
645 Action* action = new Action();
Reid Spencer07adb282004-11-05 22:15:36 +0000646 action->program.setFile("llvm-as");
Reid Spenceraf77d742004-10-28 04:05:06 +0000647 action->args.push_back(InFile.get());
648 action->args.push_back("-o");
Reid Spencer07adb282004-11-05 22:15:36 +0000649 InFile.appendSuffix("bc");
Reid Spenceraf77d742004-10-28 04:05:06 +0000650 action->args.push_back(InFile.get());
651 actions.push_back(action);
Reid Spencer52c2dc12004-08-29 19:26:56 +0000652 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000653 }
654 } else if (finalPhase == TRANSLATION) {
655 throw cd->langName + " does not support translation";
656 } else if (action.isSet(REQUIRED_FLAG)) {
657 throw std::string("Don't know how to translate ") +
658 cd->langName + " files";
659 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000660
Reid Spenceraf77d742004-10-28 04:05:06 +0000661 // Short-circuit remaining actions if all they want is translation
Reid Spencer679a7232004-11-20 20:39:33 +0000662 if (finalPhase == TRANSLATION) { continue; }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000663
Reid Spenceraf77d742004-10-28 04:05:06 +0000664 /// OPTIMIZATION PHASE
665 action = cd->Optimizer;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000666
Reid Spenceraf77d742004-10-28 04:05:06 +0000667 // Get the optimization action, if needed, or error if appropriate
668 if (!isSet(EMIT_RAW_FLAG)) {
Reid Spencer07adb282004-11-05 22:15:36 +0000669 if (!action.program.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000670 if (action.isSet(REQUIRED_FLAG) || finalPhase == OPTIMIZATION) {
671 if (finalPhase == OPTIMIZATION) {
Reid Spencer679a7232004-11-20 20:39:33 +0000672 if (Output.isEmpty()) {
673 OutFile.appendSuffix("o");
674 actions.push_back(GetAction(cd,InFile,OutFile,OPTIMIZATION));
675 } else {
676 actions.push_back(GetAction(cd,InFile,Output,OPTIMIZATION));
677 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000678 } else {
Reid Spencer07adb282004-11-05 22:15:36 +0000679 sys::Path TempFile(MakeTempFile(I->first.getBasename(),"opt"));
Reid Spenceraf77d742004-10-28 04:05:06 +0000680 actions.push_back(GetAction(cd,InFile,TempFile,OPTIMIZATION));
681 InFile = TempFile;
682 }
683 // ll -> bc Helper
684 if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
685 /// The output of the optimizer is an LLVM Assembly program
686 /// We need to translate it to bytecode with llvm-as
Reid Spencer52c2dc12004-08-29 19:26:56 +0000687 Action* action = new Action();
Reid Spencer07adb282004-11-05 22:15:36 +0000688 action->program.setFile("llvm-as");
Reid Spencer52c2dc12004-08-29 19:26:56 +0000689 action->args.push_back(InFile.get());
690 action->args.push_back("-f");
691 action->args.push_back("-o");
Reid Spencer07adb282004-11-05 22:15:36 +0000692 InFile.appendSuffix("bc");
Reid Spenceraf77d742004-10-28 04:05:06 +0000693 action->args.push_back(InFile.get());
Reid Spencer52c2dc12004-08-29 19:26:56 +0000694 actions.push_back(action);
695 }
696 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000697 } else if (finalPhase == OPTIMIZATION) {
698 throw cd->langName + " does not support optimization";
699 } else if (action.isSet(REQUIRED_FLAG)) {
700 throw std::string("Don't know how to optimize ") +
701 cd->langName + " files";
Reid Spencer52c2dc12004-08-29 19:26:56 +0000702 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000703 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000704
705 // Short-circuit remaining actions if all they want is optimization
Reid Spencer679a7232004-11-20 20:39:33 +0000706 if (finalPhase == OPTIMIZATION) { continue; }
Reid Spenceraf77d742004-10-28 04:05:06 +0000707
708 /// ASSEMBLY PHASE
709 action = cd->Assembler;
710
711 if (finalPhase == ASSEMBLY) {
Reid Spencer679a7232004-11-20 20:39:33 +0000712
713 // Build either a native compilation action or a disassembly action
714 Action* action = new Action();
Reid Spenceraf77d742004-10-28 04:05:06 +0000715 if (isSet(EMIT_NATIVE_FLAG)) {
716 // Use llc to get the native assembly file
Reid Spencer07adb282004-11-05 22:15:36 +0000717 action->program.setFile("llc");
Reid Spenceraf77d742004-10-28 04:05:06 +0000718 action->args.push_back(InFile.get());
719 action->args.push_back("-f");
720 action->args.push_back("-o");
Reid Spencer679a7232004-11-20 20:39:33 +0000721 if (Output.isEmpty()) {
722 OutFile.appendSuffix("o");
723 action->args.push_back(OutFile.get());
724 } else {
725 action->args.push_back(Output.get());
726 }
727 actions.push_back(action);
Reid Spenceraf77d742004-10-28 04:05:06 +0000728 } else {
729 // Just convert back to llvm assembly with llvm-dis
Reid Spencer07adb282004-11-05 22:15:36 +0000730 action->program.setFile("llvm-dis");
Reid Spenceraf77d742004-10-28 04:05:06 +0000731 action->args.push_back(InFile.get());
732 action->args.push_back("-f");
733 action->args.push_back("-o");
Reid Spencer679a7232004-11-20 20:39:33 +0000734 if (Output.isEmpty()) {
735 OutFile.appendSuffix("ll");
736 action->args.push_back(OutFile.get());
737 } else {
738 action->args.push_back(Output.get());
739 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000740 }
741
Reid Spencer679a7232004-11-20 20:39:33 +0000742 // Put the action on the list
743 actions.push_back(action);
744
Reid Spenceraf77d742004-10-28 04:05:06 +0000745 // Short circuit the rest of the loop, we don't want to link
Reid Spenceraf77d742004-10-28 04:05:06 +0000746 continue;
747 }
748
749 // Register the result of the actions as a link candidate
750 LinkageItems.insert(InFile);
751
Reid Spenceraf77d742004-10-28 04:05:06 +0000752 } // end while loop over each input file
753
754 /// RUN THE COMPILATION ACTIONS
755 std::vector<Action*>::iterator AI = actions.begin();
756 std::vector<Action*>::iterator AE = actions.end();
757 while (AI != AE) {
758 if (!DoAction(*AI))
759 throw std::string("Action failed");
760 AI++;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000761 }
762
Reid Spenceraf77d742004-10-28 04:05:06 +0000763 /// LINKING PHASE
764 if (finalPhase == LINKING) {
Reid Spencer52c2dc12004-08-29 19:26:56 +0000765
Reid Spenceraf77d742004-10-28 04:05:06 +0000766 // Insert the platform-specific system libraries to the path list
767 LibraryPaths.push_back(sys::Path::GetSystemLibraryPath1());
768 LibraryPaths.push_back(sys::Path::GetSystemLibraryPath2());
769
770 // Set up the linking action with llvm-ld
771 Action* link = new Action();
Reid Spencer07adb282004-11-05 22:15:36 +0000772 link->program.setFile("llvm-ld");
Reid Spenceraf77d742004-10-28 04:05:06 +0000773
774 // Add in the optimization level requested
775 switch (optLevel) {
776 case OPT_FAST_COMPILE:
777 link->args.push_back("-O1");
778 break;
779 case OPT_SIMPLE:
780 link->args.push_back("-O2");
781 break;
782 case OPT_AGGRESSIVE:
783 link->args.push_back("-O3");
784 break;
785 case OPT_LINK_TIME:
786 link->args.push_back("-O4");
787 break;
788 case OPT_AGGRESSIVE_LINK_TIME:
789 link->args.push_back("-O5");
790 break;
791 case OPT_NONE:
792 break;
793 }
794
795 // Add in all the linkage items we generated. This includes the
796 // output from the translation/optimization phases as well as any
797 // -l arguments specified.
798 for (PathVector::const_iterator I=LinkageItems.begin(),
799 E=LinkageItems.end(); I != E; ++I )
800 link->args.push_back(I->get());
801
802 // Add in all the libraries we found.
803 for (std::vector<std::string>::const_iterator I=LibFiles.begin(),
804 E=LibFiles.end(); I != E; ++I )
805 link->args.push_back(std::string("-l")+*I);
806
807 // Add in all the library paths to the command line
808 for (PathVector::const_iterator I=LibraryPaths.begin(),
809 E=LibraryPaths.end(); I != E; ++I)
810 link->args.push_back( std::string("-L") + I->get());
811
812 // Add in the additional linker arguments requested
813 for (StringVector::const_iterator I=AdditionalArgs[LINKING].begin(),
814 E=AdditionalArgs[LINKING].end(); I != E; ++I)
815 link->args.push_back( *I );
816
817 // Add in other optional flags
818 if (isSet(EMIT_NATIVE_FLAG))
819 link->args.push_back("-native");
820 if (isSet(VERBOSE_FLAG))
821 link->args.push_back("-v");
822 if (isSet(TIME_PASSES_FLAG))
823 link->args.push_back("-time-passes");
824 if (isSet(SHOW_STATS_FLAG))
825 link->args.push_back("-stats");
826 if (isSet(STRIP_OUTPUT_FLAG))
827 link->args.push_back("-s");
828 if (isSet(DEBUG_FLAG)) {
829 link->args.push_back("-debug");
830 link->args.push_back("-debug-pass=Details");
831 }
832
833 // Add in mandatory flags
834 link->args.push_back("-o");
835 link->args.push_back(Output.get());
836
837 // Execute the link
838 if (!DoAction(link))
839 throw std::string("Action failed");
840 }
841 } catch (std::string& msg) {
842 cleanup();
843 throw;
844 } catch (...) {
845 cleanup();
846 throw std::string("Unspecified error");
847 }
848 cleanup();
849 return 0;
850 }
851
852/// @}
853/// @name Data
854/// @{
855private:
856 ConfigDataProvider* cdp; ///< Where we get configuration data from
857 Phases finalPhase; ///< The final phase of compilation
858 OptimizationLevels optLevel; ///< The optimization level to apply
859 unsigned Flags; ///< The driver flags
860 std::string machine; ///< Target machine name
861 PathVector LibraryPaths; ///< -L options
862 PathVector IncludePaths; ///< -I options
Reid Spencer07adb282004-11-05 22:15:36 +0000863 PathVector ToolPaths; ///< -B options
Reid Spenceraf77d742004-10-28 04:05:06 +0000864 StringVector Defines; ///< -D options
865 sys::Path TempDir; ///< Name of the temporary directory.
866 StringTable AdditionalArgs; ///< The -Txyz options
867 StringVector fOptions; ///< -f options
868 StringVector MOptions; ///< -M options
869 StringVector WOptions; ///< -W options
870
871/// @}
872};
Reid Spencer5c56dc12004-08-13 20:22:43 +0000873}
874
875CompilerDriver::~CompilerDriver() {
Reid Spencer52c2dc12004-08-29 19:26:56 +0000876}
877
878CompilerDriver*
879CompilerDriver::Get(ConfigDataProvider& CDP) {
880 return new CompilerDriverImpl(CDP);
Reid Spencerbae68252004-08-19 04:49:47 +0000881}
882
883CompilerDriver::ConfigData::ConfigData()
884 : langName()
885 , PreProcessor()
886 , Translator()
887 , Optimizer()
888 , Assembler()
889 , Linker()
890{
891 StringVector emptyVec;
892 for (unsigned i = 0; i < NUM_PHASES; ++i)
893 opts.push_back(emptyVec);
Reid Spencer5c56dc12004-08-13 20:22:43 +0000894}
895
Reid Spencer5c56dc12004-08-13 20:22:43 +0000896// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab