Add support for the new "target data" information in .ll files. This provides
[oota-llvm.git] / tools / llvmc / CompilerDriver.cpp
1 //===- CompilerDriver.cpp - The LLVM Compiler Driver ------------*- C++ -*-===//
2 //
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 //
11 // This file implements the bulk of the LLVM Compiler Driver (llvmc).
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CompilerDriver.h"
16 #include "ConfigLexer.h"
17 #include "llvm/Module.h"
18 #include "llvm/Bytecode/Reader.h"
19 #include "llvm/Support/Timer.h"
20 #include "llvm/System/Signals.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Config/alloca.h"
24 #include <iostream>
25 using namespace llvm;
26
27 namespace {
28
29 void WriteAction(CompilerDriver::Action* action ) {
30   std::cerr << action->program.c_str();
31   std::vector<std::string>::const_iterator I = action->args.begin();
32   while (I != action->args.end()) {
33     std::cerr << ' ' << *I;
34     ++I;
35   }
36   std::cerr << '\n';
37 }
38
39 void DumpAction(CompilerDriver::Action* action) {
40   std::cerr << "command = " << action->program.c_str();
41   std::vector<std::string>::const_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
50 void 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.
68 static const char* DefaultFastCompileOptimizations[] = {
69   "-simplifycfg", "-mem2reg", "-instcombine"
70 };
71
72 class CompilerDriverImpl : public CompilerDriver {
73 /// @name Constructors
74 /// @{
75 public:
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     AdditionalArgs.reserve(NUM_PHASES);
87     StringVector emptyVec;
88     for (unsigned i = 0; i < NUM_PHASES; ++i)
89       AdditionalArgs.push_back(emptyVec);
90   }
91
92   virtual ~CompilerDriverImpl() {
93     cleanup();
94     cdp = 0;
95     LibraryPaths.clear();
96     IncludePaths.clear();
97     Defines.clear();
98     TempDir.clear();
99     AdditionalArgs.clear();
100     fOptions.clear();
101     MOptions.clear();
102     WOptions.clear();
103   }
104
105 /// @}
106 /// @name Methods
107 /// @{
108 public:
109   virtual void setFinalPhase(Phases phase) {
110     finalPhase = phase;
111   }
112
113   virtual void setOptimization(OptimizationLevels level) {
114     optLevel = level;
115   }
116
117   virtual void setDriverFlags(unsigned flags) {
118     Flags = flags & DRIVER_FLAGS_MASK;
119   }
120
121   virtual void setOutputMachine(const std::string& machineName) {
122     machine = machineName;
123   }
124
125   virtual void setPhaseArgs(Phases phase, const StringVector& opts) {
126     assert(phase <= LINKING && phase >= PREPROCESSING);
127     AdditionalArgs[phase] = opts;
128   }
129
130   virtual void setIncludePaths(const StringVector& paths) {
131     StringVector::const_iterator I = paths.begin();
132     StringVector::const_iterator E = paths.end();
133     while (I != E) {
134       sys::Path tmp;
135       tmp.set(*I);
136       IncludePaths.push_back(tmp);
137       ++I;
138     }
139   }
140
141   virtual void setSymbolDefines(const StringVector& defs) {
142     Defines = defs;
143   }
144
145   virtual void setLibraryPaths(const StringVector& paths) {
146     StringVector::const_iterator I = paths.begin();
147     StringVector::const_iterator E = paths.end();
148     while (I != E) {
149       sys::Path tmp;
150       tmp.set(*I);
151       LibraryPaths.push_back(tmp);
152       ++I;
153     }
154   }
155
156   virtual void addLibraryPath(const sys::Path& libPath) {
157     LibraryPaths.push_back(libPath);
158   }
159
160   virtual void addToolPath(const sys::Path& toolPath) {
161     ToolPaths.push_back(toolPath);
162   }
163
164   virtual void setfPassThrough(const StringVector& fOpts) {
165     fOptions = fOpts;
166   }
167
168   /// @brief Set the list of -M options to be passed through
169   virtual void setMPassThrough(const StringVector& MOpts) {
170     MOptions = MOpts;
171   }
172
173   /// @brief Set the list of -W options to be passed through
174   virtual void setWPassThrough(const StringVector& WOpts) {
175     WOptions = WOpts;
176   }
177
178 /// @}
179 /// @name Functions
180 /// @{
181 private:
182   bool isSet(DriverFlags flag) {
183     return 0 != ((flag & DRIVER_FLAGS_MASK) & Flags);
184   }
185
186   void cleanup() {
187     if (!isSet(KEEP_TEMPS_FLAG)) {
188       sys::FileStatus Status;
189       if (!TempDir.getFileStatus(Status) && Status.isDir)
190         TempDir.eraseFromDisk(/*remove_contents=*/true);
191     } else {
192       std::cout << "Temporary files are in " << TempDir << "\n";
193     }
194   }
195
196   sys::Path MakeTempFile(const std::string& basename,
197                          const std::string& suffix,
198                          std::string* ErrMsg) {
199     if (TempDir.isEmpty()) {
200       TempDir = sys::Path::GetTemporaryDirectory(ErrMsg);
201       if (TempDir.isEmpty())
202         return sys::Path();
203       sys::RemoveDirectoryOnSignal(TempDir);
204     }
205     sys::Path result(TempDir);
206     if (!result.appendComponent(basename)) {
207       if (ErrMsg)
208         *ErrMsg = basename + ": can't use this file name";
209       return sys::Path();
210     }
211     if (!result.appendSuffix(suffix)) {
212       if (ErrMsg)
213         *ErrMsg = suffix + ": can't use this file suffix";
214       return sys::Path();
215     }
216     return result;
217   }
218
219   Action* GetAction(ConfigData* cd,
220                     const sys::Path& input,
221                     const sys::Path& output,
222                     Phases phase)
223   {
224     Action* pat = 0; ///< The pattern/template for the action
225     Action* action = new Action; ///< The actual action to execute
226
227     // Get the action pattern
228     switch (phase) {
229       case PREPROCESSING: pat = &cd->PreProcessor; break;
230       case TRANSLATION:   pat = &cd->Translator; break;
231       case OPTIMIZATION:  pat = &cd->Optimizer; break;
232       case ASSEMBLY:      pat = &cd->Assembler; break;
233       case LINKING:       pat = &cd->Linker; break;
234       default:
235         assert(!"Invalid driver phase!");
236         break;
237     }
238     assert(pat != 0 && "Invalid command pattern");
239
240     // Copy over some pattern things that don't need to change
241     action->flags = pat->flags;
242
243     // See if program starts with wildcard...
244     std::string programName=pat->program.toString();
245     if (programName[0] == '%' && programName.length() >2) {
246       switch(programName[1]){
247       case 'b':
248         if (programName.substr(0,8) == "%bindir%") {
249           std::string tmp(LLVM_BINDIR);
250           tmp.append(programName.substr(8));
251           pat->program.set(tmp);
252         }
253         break;
254       case 'l':
255         if (programName.substr(0,12) == "%llvmgccdir%"){
256           std::string tmp(LLVMGCCDIR);
257           tmp.append(programName.substr(12));
258           pat->program.set(tmp);
259         }else if (programName.substr(0,13) == "%llvmgccarch%"){
260           std::string tmp(LLVMGCCARCH);
261           tmp.append(programName.substr(13));
262           pat->program.set(tmp);
263         }else if (programName.substr(0,9) == "%llvmgcc%"){
264           std::string tmp(LLVMGCC);
265           tmp.append(programName.substr(9));
266           pat->program.set(tmp);
267         }else if (programName.substr(0,9) == "%llvmgxx%"){
268           std::string tmp(LLVMGXX);
269           tmp.append(programName.substr(9));
270           pat->program.set(tmp);
271         }else if (programName.substr(0,9) == "%llvmcc1%"){
272           std::string tmp(LLVMCC1);
273           tmp.append(programName.substr(9));
274           pat->program.set(tmp);
275         }else if (programName.substr(0,13) == "%llvmcc1plus%"){
276           std::string tmp(LLVMCC1PLUS);
277           tmp.append(programName.substr(13));
278           pat->program.set(tmp);
279         }else if (programName.substr(0,8) == "%libdir%") {
280           std::string tmp(LLVM_LIBDIR);
281           tmp.append(programName.substr(8));
282           pat->program.set(tmp);
283         }
284           break;
285       }
286     }
287     action->program = pat->program;
288
289     // Do the substitutions from the pattern to the actual
290     StringVector::iterator PI = pat->args.begin();
291     StringVector::iterator PE = pat->args.end();
292     while (PI != PE) {
293       if ((*PI)[0] == '%' && PI->length() >2) {
294         bool found = true;
295         switch ((*PI)[1]) {
296           case 'a':
297             if (*PI == "%args%") {
298               if (AdditionalArgs.size() > unsigned(phase))
299                 if (!AdditionalArgs[phase].empty()) {
300                   // Get specific options for each kind of action type
301                   StringVector& addargs = AdditionalArgs[phase];
302                   // Add specific options for each kind of action type
303                   action->args.insert(action->args.end(), addargs.begin(),
304                                       addargs.end());
305                 }
306             } else
307               found = false;
308             break;
309           case 'b':
310             if (*PI == "%bindir%") {
311               std::string tmp(*PI);
312               tmp.replace(0,8,LLVM_BINDIR);
313               action->args.push_back(tmp);
314             } else
315               found = false;
316             break;
317           case 'd':
318             if (*PI == "%defs%") {
319               StringVector::iterator I = Defines.begin();
320               StringVector::iterator E = Defines.end();
321               while (I != E) {
322                 action->args.push_back( std::string("-D") + *I);
323                 ++I;
324               }
325             } else
326               found = false;
327             break;
328           case 'f':
329             if (*PI == "%fOpts%") {
330               if (!fOptions.empty())
331                 action->args.insert(action->args.end(), fOptions.begin(),
332                                     fOptions.end());
333             } else
334               found = false;
335             break;
336           case 'i':
337             if (*PI == "%in%") {
338               action->args.push_back(input.toString());
339             } else if (*PI == "%incls%") {
340               PathVector::iterator I = IncludePaths.begin();
341               PathVector::iterator E = IncludePaths.end();
342               while (I != E) {
343                 action->args.push_back( std::string("-I") + I->toString() );
344                 ++I;
345               }
346             } else
347               found = false;
348             break;
349           case 'l':
350             if ((*PI)[1] == 'l') {
351               std::string tmp(*PI);
352               if (*PI == "%llvmgccdir%")
353                 tmp.replace(0,12,LLVMGCCDIR);
354               else if (*PI == "%llvmgccarch%")
355                 tmp.replace(0,13,LLVMGCCARCH);
356               else if (*PI == "%llvmgcc%")
357                 tmp.replace(0,9,LLVMGCC);
358               else if (*PI == "%llvmgxx%")
359                 tmp.replace(0,9,LLVMGXX);
360               else if (*PI == "%llvmcc1%")
361                 tmp.replace(0,9,LLVMCC1);
362               else if (*PI == "%llvmcc1plus%")
363                 tmp.replace(0,9,LLVMCC1);
364               else
365                 found = false;
366               if (found)
367                 action->args.push_back(tmp);
368             } else if (*PI == "%libs%") {
369               PathVector::iterator I = LibraryPaths.begin();
370               PathVector::iterator E = LibraryPaths.end();
371               while (I != E) {
372                 action->args.push_back( std::string("-L") + I->toString() );
373                 ++I;
374               }
375             } else if (*PI == "%libdir%") {
376               std::string tmp(*PI);
377               tmp.replace(0,8,LLVM_LIBDIR);
378               action->args.push_back(tmp);
379             } else
380               found = false;
381             break;
382           case 'o':
383             if (*PI == "%out%") {
384               action->args.push_back(output.toString());
385             } else if (*PI == "%opt%") {
386               if (!isSet(EMIT_RAW_FLAG)) {
387                 if (cd->opts.size() > static_cast<unsigned>(optLevel) &&
388                     !cd->opts[optLevel].empty())
389                   action->args.insert(action->args.end(),
390                                       cd->opts[optLevel].begin(),
391                                       cd->opts[optLevel].end());
392                 else
393                   throw std::string("Optimization options for level ") +
394                         utostr(unsigned(optLevel)) + " were not specified";
395               }
396             } else
397               found = false;
398             break;
399           case 's':
400             if (*PI == "%stats%") {
401               if (isSet(SHOW_STATS_FLAG))
402                 action->args.push_back("-stats");
403             } else
404               found = false;
405             break;
406           case 't':
407             if (*PI == "%target%") {
408               action->args.push_back(std::string("-march=") + machine);
409             } else if (*PI == "%time%") {
410               if (isSet(TIME_PASSES_FLAG))
411                 action->args.push_back("-time-passes");
412             } else
413               found = false;
414             break;
415           case 'v':
416             if (*PI == "%verbose%") {
417               if (isSet(VERBOSE_FLAG))
418                 action->args.push_back("-v");
419             } else
420               found  = false;
421             break;
422           case 'M':
423             if (*PI == "%Mopts%") {
424               if (!MOptions.empty())
425                 action->args.insert(action->args.end(), MOptions.begin(),
426                                     MOptions.end());
427             } else
428               found = false;
429             break;
430           case 'W':
431             if (*PI == "%Wopts%") {
432               for (StringVector::iterator I = WOptions.begin(),
433                    E = WOptions.end(); I != E ; ++I ) {
434                 action->args.push_back(std::string("-W") + *I);
435               }
436             } else
437               found = false;
438             break;
439           default:
440             found = false;
441             break;
442         }
443         if (!found) {
444           // Did it even look like a substitution?
445           if (PI->length()>1 && (*PI)[0] == '%' &&
446               (*PI)[PI->length()-1] == '%') {
447             throw std::string("Invalid substitution token: '") + *PI +
448                   "' for command '" + pat->program.toString() + "'";
449           } else if (!PI->empty()) {
450             // It's not a legal substitution, just pass it through
451             action->args.push_back(*PI);
452           }
453         }
454       } else if (!PI->empty()) {
455         // Its not a substitution, just put it in the action
456         action->args.push_back(*PI);
457       }
458       PI++;
459     }
460
461     // Finally, we're done
462     return action;
463   }
464
465   int DoAction(Action*action, std::string& ErrMsg) {
466     assert(action != 0 && "Invalid Action!");
467     if (isSet(VERBOSE_FLAG))
468       WriteAction(action);
469     if (!isSet(DRY_RUN_FLAG)) {
470       sys::Path progpath = sys::Program::FindProgramByName(
471         action->program.toString());
472       if (progpath.isEmpty())
473         throw std::string("Can't find program '" +
474                           action->program.toString()+"'");
475       else if (progpath.canExecute())
476         action->program = progpath;
477       else
478         throw std::string("Program '"+action->program.toString()+
479                           "' is not executable.");
480
481       // Invoke the program
482       const char** Args = (const char**)
483         alloca(sizeof(const char*)*(action->args.size()+2));
484       Args[0] = action->program.toString().c_str();
485       for (unsigned i = 1; i <= action->args.size(); ++i)
486         Args[i] = action->args[i-1].c_str();
487       Args[action->args.size()+1] = 0;  // null terminate list.
488       if (isSet(TIME_ACTIONS_FLAG)) {
489         Timer timer(action->program.toString());
490         timer.startTimer();
491         int resultCode = 
492           sys::Program::ExecuteAndWait(action->program, Args,0,0,0,&ErrMsg);
493         timer.stopTimer();
494         timer.print(timer,std::cerr);
495         return resultCode;
496       }
497       else
498         return 
499           sys::Program::ExecuteAndWait(action->program, Args, 0,0,0, &ErrMsg);
500     }
501     return 0;
502   }
503
504   /// This method tries various variants of a linkage item's file
505   /// name to see if it can find an appropriate file to link with
506   /// in the directories of the LibraryPaths.
507   llvm::sys::Path GetPathForLinkageItem(const std::string& link_item,
508                                         bool native = false) {
509     sys::Path fullpath;
510     fullpath.set(link_item);
511     if (fullpath.canRead())
512       return fullpath;
513     for (PathVector::iterator PI = LibraryPaths.begin(),
514          PE = LibraryPaths.end(); PI != PE; ++PI) {
515       fullpath.set(PI->toString());
516       fullpath.appendComponent(link_item);
517       if (fullpath.canRead())
518         return fullpath;
519       if (native) {
520         fullpath.appendSuffix("a");
521       } else {
522         fullpath.appendSuffix("bc");
523         if (fullpath.canRead())
524           return fullpath;
525         fullpath.eraseSuffix();
526         fullpath.appendSuffix("o");
527         if (fullpath.canRead())
528           return fullpath;
529         fullpath = *PI;
530         fullpath.appendComponent(std::string("lib") + link_item);
531         fullpath.appendSuffix("a");
532         if (fullpath.canRead())
533           return fullpath;
534         fullpath.eraseSuffix();
535         fullpath.appendSuffix("so");
536         if (fullpath.canRead())
537           return fullpath;
538       }
539     }
540
541     // Didn't find one.
542     fullpath.clear();
543     return fullpath;
544   }
545
546   /// This method processes a linkage item. The item could be a
547   /// Bytecode file needing translation to native code and that is
548   /// dependent on other bytecode libraries, or a native code
549   /// library that should just be linked into the program.
550   bool ProcessLinkageItem(const llvm::sys::Path& link_item,
551                           SetVector<sys::Path>& set,
552                           std::string& err) {
553     // First, see if the unadorned file name is not readable. If so,
554     // we must track down the file in the lib search path.
555     sys::Path fullpath;
556     if (!link_item.canRead()) {
557       // look for the library using the -L arguments specified
558       // on the command line.
559       fullpath = GetPathForLinkageItem(link_item.toString());
560
561       // If we didn't find the file in any of the library search paths
562       // we have to bail. No where else to look.
563       if (fullpath.isEmpty()) {
564         err =
565           std::string("Can't find linkage item '") + link_item.toString() + "'";
566         return false;
567       }
568     } else {
569       fullpath = link_item;
570     }
571
572     // If we got here fullpath is the path to the file, and its readable.
573     set.insert(fullpath);
574
575     // If its an LLVM bytecode file ...
576     if (fullpath.isBytecodeFile()) {
577       // Process the dependent libraries recursively
578       Module::LibraryListType modlibs;
579       if (GetBytecodeDependentLibraries(fullpath.toString(),modlibs,&err)) {
580         // Traverse the dependent libraries list
581         Module::lib_iterator LI = modlibs.begin();
582         Module::lib_iterator LE = modlibs.end();
583         while ( LI != LE ) {
584           if (!ProcessLinkageItem(sys::Path(*LI),set,err)) {
585             if (err.empty()) {
586               err = std::string("Library '") + *LI +
587                     "' is not valid for linking but is required by file '" +
588                     fullpath.toString() + "'";
589             } else {
590               err += " which is required by file '" + fullpath.toString() + "'";
591             }
592             return false;
593           }
594           ++LI;
595         }
596       } else if (err.empty()) {
597         err = std::string(
598           "The dependent libraries could not be extracted from '") +
599           fullpath.toString();
600         return false;
601       } else 
602         return false;
603     }
604     return true;
605   }
606
607 /// @}
608 /// @name Methods
609 /// @{
610 public:
611   virtual int execute(const InputList& InpList, const sys::Path& Output, std::string& ErrMsg ) {
612     try {
613       // Echo the configuration of options if we're running verbose
614       if (isSet(DEBUG_FLAG)) {
615         std::cerr << "Compiler Driver Options:\n";
616         std::cerr << "DryRun = " << isSet(DRY_RUN_FLAG) << "\n";
617         std::cerr << "Verbose = " << isSet(VERBOSE_FLAG) << " \n";
618         std::cerr << "TimeActions = " << isSet(TIME_ACTIONS_FLAG) << "\n";
619         std::cerr << "TimePasses = " << isSet(TIME_PASSES_FLAG) << "\n";
620         std::cerr << "ShowStats = " << isSet(SHOW_STATS_FLAG) << "\n";
621         std::cerr << "EmitRawCode = " << isSet(EMIT_RAW_FLAG) << "\n";
622         std::cerr << "EmitNativeCode = " << isSet(EMIT_NATIVE_FLAG) << "\n";
623         std::cerr << "KeepTemps = " << isSet(KEEP_TEMPS_FLAG) << "\n";
624         std::cerr << "OutputMachine = " << machine << "\n";
625         InputList::const_iterator I = InpList.begin();
626         while ( I != InpList.end() ) {
627           std::cerr << "Input: " << I->first << "(" << I->second
628                     << ")\n";
629           ++I;
630         }
631         std::cerr << "Output: " << Output << "\n";
632       }
633
634       // If there's no input, we're done.
635       if (InpList.empty())
636         throw std::string("Nothing to compile.");
637
638       // If they are asking for linking and didn't provide an output
639       // file then its an error (no way for us to "make up" a meaningful
640       // file name based on the various linker input files).
641       if (finalPhase == LINKING && Output.isEmpty())
642         throw std::string(
643           "An output file name must be specified for linker output");
644
645       // If they are not asking for linking, provided an output file and
646       // there is more than one input file, its an error
647       if (finalPhase != LINKING && !Output.isEmpty() && InpList.size() > 1)
648         throw std::string("An output file name cannot be specified ") +
649           "with more than one input file name when not linking";
650
651       // This vector holds all the resulting actions of the following loop.
652       std::vector<Action*> actions;
653
654       /// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases
655       // for each input item
656       SetVector<sys::Path> LinkageItems;
657       StringVector LibFiles;
658       InputList::const_iterator I = InpList.begin();
659       for (InputList::const_iterator I = InpList.begin(), E = InpList.end();
660            I != E; ++I ) {
661         // Get the suffix of the file name
662         const std::string& ftype = I->second;
663
664         // If its a library, bytecode file, or object file, save
665         // it for linking below and short circuit the
666         // pre-processing/translation/assembly phases
667         if (ftype.empty() ||  ftype == "o" || ftype == "bc" || ftype=="a") {
668           // We shouldn't get any of these types of files unless we're
669           // later going to link. Enforce this limit now.
670           if (finalPhase != LINKING) {
671             throw std::string(
672               "Pre-compiled objects found but linking not requested");
673           }
674           if (ftype.empty())
675             LibFiles.push_back(I->first.toString());
676           else
677             LinkageItems.insert(I->first);
678           continue; // short circuit remainder of loop
679         }
680
681         // At this point, we know its something we need to translate
682         // and/or optimize. See if we can get the configuration data
683         // for this kind of file.
684         ConfigData* cd = cdp->ProvideConfigData(I->second);
685         if (cd == 0)
686           throw std::string("Files of type '") + I->second +
687                 "' are not recognized.";
688         if (isSet(DEBUG_FLAG))
689           DumpConfigData(cd,I->second);
690
691         // Add the config data's library paths to the end of the list
692         for (StringVector::iterator LPI = cd->libpaths.begin(),
693              LPE = cd->libpaths.end(); LPI != LPE; ++LPI){
694           LibraryPaths.push_back(sys::Path(*LPI));
695         }
696
697         // Initialize the input and output files
698         sys::Path InFile(I->first);
699         sys::Path OutFile(I->first.getBasename());
700
701         // PRE-PROCESSING PHASE
702         Action& action = cd->PreProcessor;
703
704         // Get the preprocessing action, if needed, or error if appropriate
705         if (!action.program.isEmpty()) {
706           if (action.isSet(REQUIRED_FLAG) || finalPhase == PREPROCESSING) {
707             if (finalPhase == PREPROCESSING) {
708               if (Output.isEmpty()) {
709                 OutFile.appendSuffix("E");
710                 actions.push_back(GetAction(cd,InFile,OutFile,PREPROCESSING));
711               } else {
712                 actions.push_back(GetAction(cd,InFile,Output,PREPROCESSING));
713               }
714             } else {
715               sys::Path TempFile(
716                   MakeTempFile(I->first.getBasename(),"E",&ErrMsg));
717               if (TempFile.isEmpty())
718                 return 1;
719               actions.push_back(GetAction(cd,InFile,TempFile,
720                 PREPROCESSING));
721               InFile = TempFile;
722             }
723           }
724         } else if (finalPhase == PREPROCESSING) {
725           throw cd->langName + " does not support pre-processing";
726         } else if (action.isSet(REQUIRED_FLAG)) {
727           throw std::string("Don't know how to pre-process ") +
728                 cd->langName + " files";
729         }
730
731         // Short-circuit remaining actions if all they want is
732         // pre-processing
733         if (finalPhase == PREPROCESSING) { continue; };
734
735         /// TRANSLATION PHASE
736         action = cd->Translator;
737
738         // Get the translation action, if needed, or error if appropriate
739         if (!action.program.isEmpty()) {
740           if (action.isSet(REQUIRED_FLAG) || finalPhase == TRANSLATION) {
741             if (finalPhase == TRANSLATION) {
742               if (Output.isEmpty()) {
743                 OutFile.appendSuffix("o");
744                 actions.push_back(GetAction(cd,InFile,OutFile,TRANSLATION));
745               } else {
746                 actions.push_back(GetAction(cd,InFile,Output,TRANSLATION));
747               }
748             } else {
749               sys::Path TempFile(
750                   MakeTempFile(I->first.getBasename(),"trans", &ErrMsg));
751               if (TempFile.isEmpty())
752                 return 1;
753               actions.push_back(GetAction(cd,InFile,TempFile,TRANSLATION));
754               InFile = TempFile;
755             }
756
757             // ll -> bc Helper
758             if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
759               /// The output of the translator is an LLVM Assembly program
760               /// We need to translate it to bytecode
761               Action* action = new Action();
762               action->program.set("llvm-as");
763               action->args.push_back(InFile.toString());
764               action->args.push_back("-o");
765               InFile.appendSuffix("bc");
766               action->args.push_back(InFile.toString());
767               actions.push_back(action);
768             }
769           }
770         } else if (finalPhase == TRANSLATION) {
771           throw cd->langName + " does not support translation";
772         } else if (action.isSet(REQUIRED_FLAG)) {
773           throw std::string("Don't know how to translate ") +
774                 cd->langName + " files";
775         }
776
777         // Short-circuit remaining actions if all they want is translation
778         if (finalPhase == TRANSLATION) { continue; }
779
780         /// OPTIMIZATION PHASE
781         action = cd->Optimizer;
782
783         // Get the optimization action, if needed, or error if appropriate
784         if (!isSet(EMIT_RAW_FLAG)) {
785           if (!action.program.isEmpty()) {
786             if (action.isSet(REQUIRED_FLAG) || finalPhase == OPTIMIZATION) {
787               if (finalPhase == OPTIMIZATION) {
788                 if (Output.isEmpty()) {
789                   OutFile.appendSuffix("o");
790                   actions.push_back(GetAction(cd,InFile,OutFile,OPTIMIZATION));
791                 } else {
792                   actions.push_back(GetAction(cd,InFile,Output,OPTIMIZATION));
793                 }
794               } else {
795                 sys::Path TempFile(
796                   MakeTempFile(I->first.getBasename(),"opt", &ErrMsg));
797                 if (TempFile.isEmpty())
798                   return 1;
799                 actions.push_back(GetAction(cd,InFile,TempFile,OPTIMIZATION));
800                 InFile = TempFile;
801               }
802               // ll -> bc Helper
803               if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
804                 /// The output of the optimizer is an LLVM Assembly program
805                 /// We need to translate it to bytecode with llvm-as
806                 Action* action = new Action();
807                 action->program.set("llvm-as");
808                 action->args.push_back(InFile.toString());
809                 action->args.push_back("-f");
810                 action->args.push_back("-o");
811                 InFile.appendSuffix("bc");
812                 action->args.push_back(InFile.toString());
813                 actions.push_back(action);
814               }
815             }
816           } else if (finalPhase == OPTIMIZATION) {
817             throw cd->langName + " does not support optimization";
818           } else if (action.isSet(REQUIRED_FLAG)) {
819             throw std::string("Don't know how to optimize ") +
820                 cd->langName + " files";
821           }
822         }
823
824         // Short-circuit remaining actions if all they want is optimization
825         if (finalPhase == OPTIMIZATION) { continue; }
826
827         /// ASSEMBLY PHASE
828         action = cd->Assembler;
829
830         if (finalPhase == ASSEMBLY) {
831
832           // Build either a native compilation action or a disassembly action
833           Action* action = new Action();
834           if (isSet(EMIT_NATIVE_FLAG)) {
835             // Use llc to get the native assembly file
836             action->program.set("llc");
837             action->args.push_back(InFile.toString());
838             action->args.push_back("-f");
839             action->args.push_back("-o");
840             if (Output.isEmpty()) {
841               OutFile.appendSuffix("o");
842               action->args.push_back(OutFile.toString());
843             } else {
844               action->args.push_back(Output.toString());
845             }
846             actions.push_back(action);
847           } else {
848             // Just convert back to llvm assembly with llvm-dis
849             action->program.set("llvm-dis");
850             action->args.push_back(InFile.toString());
851             action->args.push_back("-f");
852             action->args.push_back("-o");
853             if (Output.isEmpty()) {
854               OutFile.appendSuffix("ll");
855               action->args.push_back(OutFile.toString());
856             } else {
857               action->args.push_back(Output.toString());
858             }
859           }
860
861           // Put the action on the list
862           actions.push_back(action);
863
864           // Short circuit the rest of the loop, we don't want to link
865           continue;
866         }
867
868         // Register the result of the actions as a link candidate
869         LinkageItems.insert(InFile);
870
871       } // end while loop over each input file
872
873       /// RUN THE COMPILATION ACTIONS
874       std::vector<Action*>::iterator AI = actions.begin();
875       std::vector<Action*>::iterator AE = actions.end();
876       while (AI != AE) {
877         int ActionResult = DoAction(*AI, ErrMsg);
878         if (ActionResult != 0)
879           return ActionResult;
880         AI++;
881       }
882
883       /// LINKING PHASE
884       if (finalPhase == LINKING) {
885
886         // Insert the platform-specific system libraries to the path list
887         std::vector<sys::Path> SysLibs;
888         sys::Path::GetSystemLibraryPaths(SysLibs);
889         LibraryPaths.insert(LibraryPaths.end(), SysLibs.begin(), SysLibs.end());
890
891         // Set up the linking action with llvm-ld
892         Action* link = new Action();
893         link->program.set("llvm-ld");
894
895         // Add in the optimization level requested
896         switch (optLevel) {
897           case OPT_FAST_COMPILE:
898             link->args.push_back("-O1");
899             break;
900           case OPT_SIMPLE:
901             link->args.push_back("-O2");
902             break;
903           case OPT_AGGRESSIVE:
904             link->args.push_back("-O3");
905             break;
906           case OPT_LINK_TIME:
907             link->args.push_back("-O4");
908             break;
909           case OPT_AGGRESSIVE_LINK_TIME:
910             link->args.push_back("-O5");
911             break;
912           case OPT_NONE:
913             break;
914         }
915
916         // Add in all the linkage items we generated. This includes the
917         // output from the translation/optimization phases as well as any
918         // -l arguments specified.
919         for (PathVector::const_iterator I=LinkageItems.begin(),
920              E=LinkageItems.end(); I != E; ++I )
921           link->args.push_back(I->toString());
922
923         // Add in all the libraries we found.
924         for (StringVector::const_iterator I=LibFiles.begin(),
925              E=LibFiles.end(); I != E; ++I )
926           link->args.push_back(std::string("-l")+*I);
927
928         // Add in all the library paths to the command line
929         for (PathVector::const_iterator I=LibraryPaths.begin(),
930              E=LibraryPaths.end(); I != E; ++I)
931           link->args.push_back( std::string("-L") + I->toString());
932
933         // Add in the additional linker arguments requested
934         for (StringVector::const_iterator I=AdditionalArgs[LINKING].begin(),
935              E=AdditionalArgs[LINKING].end(); I != E; ++I)
936           link->args.push_back( *I );
937
938         // Add in other optional flags
939         if (isSet(EMIT_NATIVE_FLAG))
940           link->args.push_back("-native");
941         if (isSet(VERBOSE_FLAG))
942           link->args.push_back("-v");
943         if (isSet(TIME_PASSES_FLAG))
944           link->args.push_back("-time-passes");
945         if (isSet(SHOW_STATS_FLAG))
946           link->args.push_back("-stats");
947         if (isSet(STRIP_OUTPUT_FLAG))
948           link->args.push_back("-s");
949         if (isSet(DEBUG_FLAG)) {
950           link->args.push_back("-debug");
951           link->args.push_back("-debug-pass=Details");
952         }
953
954         // Add in mandatory flags
955         link->args.push_back("-o");
956         link->args.push_back(Output.toString());
957
958         // Execute the link
959         int ActionResult = DoAction(link, ErrMsg);
960         if (ActionResult != 0)
961           return ActionResult;
962       }
963     } catch (std::string& msg) {
964       cleanup();
965       throw;
966     } catch (...) {
967       cleanup();
968       throw std::string("Unspecified error");
969     }
970     cleanup();
971     return 0;
972   }
973
974 /// @}
975 /// @name Data
976 /// @{
977 private:
978   ConfigDataProvider* cdp;      ///< Where we get configuration data from
979   Phases finalPhase;            ///< The final phase of compilation
980   OptimizationLevels optLevel;  ///< The optimization level to apply
981   unsigned Flags;               ///< The driver flags
982   std::string machine;          ///< Target machine name
983   PathVector LibraryPaths;      ///< -L options
984   PathVector IncludePaths;      ///< -I options
985   PathVector ToolPaths;         ///< -B options
986   StringVector Defines;         ///< -D options
987   sys::Path TempDir;            ///< Name of the temporary directory.
988   StringTable AdditionalArgs;   ///< The -Txyz options
989   StringVector fOptions;        ///< -f options
990   StringVector MOptions;        ///< -M options
991   StringVector WOptions;        ///< -W options
992
993 /// @}
994 };
995 }
996
997 CompilerDriver::~CompilerDriver() {
998 }
999
1000 CompilerDriver::ConfigDataProvider::~ConfigDataProvider() {}
1001
1002 CompilerDriver*
1003 CompilerDriver::Get(ConfigDataProvider& CDP) {
1004   return new CompilerDriverImpl(CDP);
1005 }
1006
1007 CompilerDriver::ConfigData::ConfigData()
1008   : langName()
1009   , PreProcessor()
1010   , Translator()
1011   , Optimizer()
1012   , Assembler()
1013   , Linker()
1014 {
1015   StringVector emptyVec;
1016   for (unsigned i = 0; i < NUM_PHASES; ++i)
1017     opts.push_back(emptyVec);
1018 }