Changes For Bug 352
[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/System/Signals.h"
20 #include "llvm/Support/FileUtilities.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include <iostream>
24
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>::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>::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         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         AdditionalArgs.clear();
99       }
100
101     /// @}
102     /// @name Methods
103     /// @{
104     public:
105       virtual void setFinalPhase( Phases phase ) { 
106         finalPhase = phase; 
107       }
108
109       virtual void setOptimization( OptimizationLevels level ) { 
110         optLevel = level; 
111       }
112
113       virtual void setDriverFlags( unsigned flags ) {
114         Flags = flags & DRIVER_FLAGS_MASK; 
115       }
116
117       virtual void setOutputMachine( const std::string& machineName ) {
118         machine = machineName;
119       }
120
121       virtual void setPhaseArgs(Phases phase, const StringVector& opts) {
122         assert(phase <= LINKING && phase >= PREPROCESSING);
123         AdditionalArgs[phase] = opts;
124       }
125
126       virtual void setIncludePaths(const StringVector& paths) {
127         StringVector::const_iterator I = paths.begin();
128         StringVector::const_iterator E = paths.end();
129         while (I != E) {
130           sys::Path tmp;
131           tmp.set_directory(*I);
132           IncludePaths.push_back(tmp);
133           ++I;
134         }
135       }
136
137       virtual void setSymbolDefines(const StringVector& defs) {
138         Defines = defs;
139       }
140
141       virtual void setLibraryPaths(const StringVector& paths) {
142         StringVector::const_iterator I = paths.begin();
143         StringVector::const_iterator E = paths.end();
144         while (I != E) {
145           sys::Path tmp;
146           tmp.set_directory(*I);
147           LibraryPaths.push_back(tmp);
148           ++I;
149         }
150       }
151
152       virtual void addLibraryPath( const sys::Path& libPath ) {
153         LibraryPaths.push_back(libPath);
154       }
155
156     /// @}
157     /// @name Functions
158     /// @{
159     private:
160       bool isSet(DriverFlags flag) {
161         return 0 != ((flag & DRIVER_FLAGS_MASK) & Flags);
162       }
163
164       void cleanup() {
165         if (!isSet(KEEP_TEMPS_FLAG)) {
166           if (TempDir.is_directory() && TempDir.writable())
167             TempDir.destroy_directory(/*remove_contents=*/true);
168         } else {
169           std::cout << "Temporary files are in " << TempDir.get() << "\n";
170         }
171       }
172
173       sys::Path MakeTempFile(const std::string& basename, const std::string& suffix ) {
174         sys::Path result(TempDir);
175         if (!result.append_file(basename))
176           throw basename + ": can't use this file name";
177         if (!result.append_suffix(suffix))
178           throw suffix + ": can't use this file suffix";
179         return result;
180       }
181
182       Action* GetAction(ConfigData* cd, 
183                         const sys::Path& input, 
184                         const sys::Path& output,
185                         Phases phase)
186       {
187         Action* pat = 0; ///< The pattern/template for the action
188         Action* action = new Action; ///< The actual action to execute
189
190         // Get the action pattern
191         switch (phase) {
192           case PREPROCESSING: pat = &cd->PreProcessor; break;
193           case TRANSLATION:   pat = &cd->Translator; break;
194           case OPTIMIZATION:  pat = &cd->Optimizer; break;
195           case ASSEMBLY:      pat = &cd->Assembler; break;
196           case LINKING:       pat = &cd->Linker; break;
197           default:
198             assert(!"Invalid driver phase!");
199             break;
200         }
201         assert(pat != 0 && "Invalid command pattern");
202
203         // Copy over some pattern things that don't need to change
204         action->program = pat->program;
205         action->flags = pat->flags;
206
207         // Do the substitutions from the pattern to the actual
208         StringVector::iterator PI = pat->args.begin();
209         StringVector::iterator PE = pat->args.end();
210         while (PI != PE) {
211           if ((*PI)[0] == '%' && PI->length() >2) {
212             bool found = true;
213             switch ((*PI)[1]) {
214               case 'a':
215                 if (*PI == "%args%") {
216                   if (AdditionalArgs.size() > unsigned(phase))
217                     if (!AdditionalArgs[phase].empty()) {
218                       // Get specific options for each kind of action type
219                       StringVector& addargs = AdditionalArgs[phase];
220                       // Add specific options for each kind of action type
221                       action->args.insert(action->args.end(), addargs.begin(), addargs.end());
222                     }
223                 } else
224                   found = false;
225                 break;
226               case 'd':
227                 if (*PI == "%defs%") {
228                   StringVector::iterator I = Defines.begin();
229                   StringVector::iterator E = Defines.end();
230                   while (I != E) {
231                     action->args.push_back( std::string("-D") + *I);
232                     ++I;
233                   }
234                 } else
235                   found = false;
236                 break;
237               case 'f':
238                 if (*PI == "%force%") {
239                   if (isSet(FORCE_FLAG))
240                     action->args.push_back("-f");
241                 } else
242                   found = false;
243                 break;
244               case 'i':
245                 if (*PI == "%in%") {
246                   action->args.push_back(input.get());
247                 } else if (*PI == "%incls%") {
248                   PathVector::iterator I = IncludePaths.begin();
249                   PathVector::iterator E = IncludePaths.end();
250                   while (I != E) {
251                     action->args.push_back( std::string("-I") + I->get() );
252                     ++I;
253                   }
254                 } else
255                   found = false;
256                 break;
257               case 'l':
258                 if (*PI == "%libs%") {
259                   PathVector::iterator I = LibraryPaths.begin();
260                   PathVector::iterator E = LibraryPaths.end();
261                   while (I != E) {
262                     action->args.push_back( std::string("-L") + I->get() );
263                     ++I;
264                   }
265                 } else
266                   found = false;
267                 break;
268               case 'o':
269                 if (*PI == "%out%") {
270                   action->args.push_back(output.get());
271                 } else if (*PI == "%opt%") {
272                   if (!isSet(EMIT_RAW_FLAG)) {
273                     if (cd->opts.size() > static_cast<unsigned>(optLevel) && 
274                         !cd->opts[optLevel].empty())
275                       action->args.insert(action->args.end(), cd->opts[optLevel].begin(),
276                           cd->opts[optLevel].end());
277                     else
278                       throw std::string("Optimization options for level ") + 
279                             utostr(unsigned(optLevel)) + " were not specified";
280                   }
281                 } else
282                   found = false;
283                 break;
284               case 's':
285                 if (*PI == "%stats%") {
286                   if (isSet(SHOW_STATS_FLAG))
287                     action->args.push_back("-stats");
288                 } else
289                   found = false;
290                 break;
291               case 't':
292                 if (*PI == "%target%") {
293                   action->args.push_back(std::string("-march=") + machine);
294                 } else if (*PI == "%time%") {
295                   if (isSet(TIME_PASSES_FLAG))
296                     action->args.push_back("-time-passes");
297                 } else
298                   found = false;
299                 break;
300               case 'v':
301                 if (*PI == "%verbose%") {
302                   if (isSet(VERBOSE_FLAG))
303                     action->args.push_back("-v");
304                 } else
305                   found  = false;
306                 break;
307               default:
308                 found = false;
309                 break;
310             }
311             if (!found) {
312               // Did it even look like a substitution?
313               if (PI->length()>1 && (*PI)[0] == '%' && 
314                   (*PI)[PI->length()-1] == '%') {
315                 throw std::string("Invalid substitution token: '") + *PI +
316                       "' for command '" + pat->program.get() + "'";
317               } else {
318                 // It's not a legal substitution, just pass it through
319                 action->args.push_back(*PI);
320               }
321             }
322           } else {
323             // Its not a substitution, just put it in the action
324             action->args.push_back(*PI);
325           }
326           PI++;
327         }
328
329         // Finally, we're done
330         return action;
331       }
332
333       bool DoAction(Action*action) {
334         assert(action != 0 && "Invalid Action!");
335         if (isSet(VERBOSE_FLAG))
336           WriteAction(action);
337         if (!isSet(DRY_RUN_FLAG)) {
338           action->program = sys::Program::FindProgramByName(action->program.get());
339           if (action->program.is_empty())
340             throw std::string("Can't find program '") + action->program.get() + "'";
341
342           // Invoke the program
343           return 0 == action->program.ExecuteAndWait(action->args);
344         }
345         return true;
346       }
347
348       /// This method tries various variants of a linkage item's file
349       /// name to see if it can find an appropriate file to link with
350       /// in the directory specified.
351       llvm::sys::Path GetPathForLinkageItem(const std::string& link_item,
352                                             const sys::Path& dir) {
353         sys::Path fullpath(dir);
354         fullpath.append_file(link_item);
355         fullpath.append_suffix("bc");
356         if (fullpath.readable()) 
357           return fullpath;
358         fullpath.elide_suffix();
359         fullpath.append_suffix("o");
360         if (fullpath.readable()) 
361           return fullpath;
362         fullpath = dir;
363         fullpath.append_file(std::string("lib") + link_item);
364         fullpath.append_suffix("a");
365         if (fullpath.readable())
366           return fullpath;
367         fullpath.elide_suffix();
368         fullpath.append_suffix("so");
369         if (fullpath.readable())
370           return fullpath;
371
372         // Didn't find one.
373         fullpath.clear();
374         return fullpath;
375       }
376
377       /// This method processes a linkage item. The item could be a
378       /// Bytecode file needing translation to native code and that is
379       /// dependent on other bytecode libraries, or a native code
380       /// library that should just be linked into the program.
381       bool ProcessLinkageItem(const llvm::sys::Path& link_item,
382                               SetVector<sys::Path>& set,
383                               std::string& err) {
384         // First, see if the unadorned file name is not readable. If so,
385         // we must track down the file in the lib search path.
386         sys::Path fullpath;
387         if (!link_item.readable()) {
388           // First, look for the library using the -L arguments specified
389           // on the command line.
390           PathVector::iterator PI = LibraryPaths.begin();
391           PathVector::iterator PE = LibraryPaths.end();
392           while (PI != PE && fullpath.is_empty()) {
393             fullpath = GetPathForLinkageItem(link_item.get(),*PI);
394             ++PI;
395           }
396
397           // If we didn't find the file in any of the library search paths
398           // so we have to bail. No where else to look.
399           if (fullpath.is_empty()) {
400             err = std::string("Can't find linkage item '") + link_item.get() + "'";
401             return false;
402           }
403         } else {
404           fullpath = link_item;
405         }
406
407         // If we got here fullpath is the path to the file, and its readable.
408         set.insert(fullpath);
409
410         // If its an LLVM bytecode file ...
411         if (CheckMagic(fullpath.get(), "llvm")) {
412           // Process the dependent libraries recursively
413           Module::LibraryListType modlibs;
414           if (GetBytecodeDependentLibraries(fullpath.get(),modlibs)) {
415             // Traverse the dependent libraries list
416             Module::lib_iterator LI = modlibs.begin();
417             Module::lib_iterator LE = modlibs.end();
418             while ( LI != LE ) {
419               if (!ProcessLinkageItem(sys::Path(*LI),set,err)) {
420                 if (err.empty()) {
421                   err = std::string("Library '") + *LI + 
422                         "' is not valid for linking but is required by file '" +
423                         fullpath.get() + "'";
424                 } else {
425                   err += " which is required by file '" + fullpath.get() + "'";
426                 }
427                 return false;
428               }
429               ++LI;
430             }
431           } else if (err.empty()) {
432             err = std::string("The dependent libraries could not be extracted from '")
433                               + fullpath.get();
434             return false;
435           }
436         }
437         return true;
438       }
439
440     /// @}
441     /// @name Methods
442     /// @{
443     public:
444       virtual int execute(const InputList& InpList, const sys::Path& Output ) {
445         try {
446           // Echo the configuration of options if we're running verbose
447           if (isSet(DEBUG_FLAG)) {
448             std::cerr << "Compiler Driver Options:\n";
449             std::cerr << "DryRun = " << isSet(DRY_RUN_FLAG) << "\n";
450             std::cerr << "Verbose = " << isSet(VERBOSE_FLAG) << " \n";
451             std::cerr << "TimeActions = " << isSet(TIME_ACTIONS_FLAG) << "\n";
452             std::cerr << "TimePasses = " << isSet(TIME_PASSES_FLAG) << "\n";
453             std::cerr << "ShowStats = " << isSet(SHOW_STATS_FLAG) << "\n";
454             std::cerr << "EmitRawCode = " << isSet(EMIT_RAW_FLAG) << "\n";
455             std::cerr << "EmitNativeCode = " << isSet(EMIT_NATIVE_FLAG) << "\n";
456             std::cerr << "ForceOutput = " << isSet(FORCE_FLAG) << "\n";
457             std::cerr << "KeepTemps = " << isSet(KEEP_TEMPS_FLAG) << "\n";
458             std::cerr << "OutputMachine = " << machine << "\n";
459             InputList::const_iterator I = InpList.begin();
460             while ( I != InpList.end() ) {
461               std::cerr << "Input: " << I->first.get() << "(" << I->second << ")\n";
462               ++I;
463             }
464             std::cerr << "Output: " << Output.get() << "\n";
465           }
466
467           // If there's no input, we're done.
468           if (InpList.empty())
469             throw std::string("Nothing to compile.");
470
471           // If they are asking for linking and didn't provide an output
472           // file then its an error (no way for us to "make up" a meaningful
473           // file name based on the various linker input files).
474           if (finalPhase == LINKING && Output.is_empty())
475             throw std::string(
476               "An output file name must be specified for linker output");
477
478           // This vector holds all the resulting actions of the following loop.
479           std::vector<Action*> actions;
480
481           /// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases
482           // for each input item
483           SetVector<sys::Path> LinkageItems;
484           sys::Path OutFile(Output);
485           InputList::const_iterator I = InpList.begin();
486           while ( I != InpList.end() ) {
487             // Get the suffix of the file name
488             const std::string& ftype = I->second;
489
490             // If its a library, bytecode file, or object file, save 
491             // it for linking below and short circuit the 
492             // pre-processing/translation/assembly phases
493             if (ftype.empty() ||  ftype == "o" || ftype == "bc") {
494               // We shouldn't get any of these types of files unless we're 
495               // later going to link. Enforce this limit now.
496               if (finalPhase != LINKING) {
497                 throw std::string(
498                   "Pre-compiled objects found but linking not requested");
499               }
500               LinkageItems.insert(I->first);
501               ++I; continue; // short circuit remainder of loop
502             }
503
504             // At this point, we know its something we need to translate
505             // and/or optimize. See if we can get the configuration data
506             // for this kind of file.
507             ConfigData* cd = cdp->ProvideConfigData(I->second);
508             if (cd == 0)
509               throw std::string("Files of type '") + I->second + 
510                     "' are not recognized."; 
511             if (isSet(DEBUG_FLAG))
512               DumpConfigData(cd,I->second);
513
514             // Initialize the input file
515             sys::Path InFile(I->first);
516
517             // PRE-PROCESSING PHASE
518             Action& action = cd->PreProcessor;
519
520             // Get the preprocessing action, if needed, or error if appropriate
521             if (!action.program.is_empty()) {
522               if (action.isSet(REQUIRED_FLAG) || finalPhase == PREPROCESSING) {
523                 if (finalPhase == PREPROCESSING)
524                   actions.push_back(GetAction(cd,InFile,OutFile,PREPROCESSING));
525                 else {
526                   sys::Path TempFile(MakeTempFile(I->first.get(),"E"));
527                   actions.push_back(GetAction(cd,InFile,TempFile,PREPROCESSING));
528                   InFile = TempFile;
529                 }
530               }
531             } else if (finalPhase == PREPROCESSING) {
532               throw cd->langName + " does not support pre-processing";
533             } else if (action.isSet(REQUIRED_FLAG)) {
534               throw std::string("Don't know how to pre-process ") + 
535                     cd->langName + " files";
536             }
537
538             // Short-circuit remaining actions if all they want is pre-processing
539             if (finalPhase == PREPROCESSING) { ++I; continue; };
540
541             /// TRANSLATION PHASE
542             action = cd->Translator;
543
544             // Get the translation action, if needed, or error if appropriate
545             if (!action.program.is_empty()) {
546               if (action.isSet(REQUIRED_FLAG) || finalPhase == TRANSLATION) {
547                 if (finalPhase == TRANSLATION) 
548                   actions.push_back(GetAction(cd,InFile,OutFile,TRANSLATION));
549                 else {
550                   sys::Path TempFile(MakeTempFile(I->first.get(),"trans")); 
551                   actions.push_back(GetAction(cd,InFile,TempFile,TRANSLATION));
552                   InFile = TempFile;
553                 }
554
555                 // ll -> bc Helper
556                 if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
557                   /// The output of the translator is an LLVM Assembly program
558                   /// We need to translate it to bytecode
559                   Action* action = new Action();
560                   action->program.set_file("llvm-as");
561                   action->args.push_back(InFile.get());
562                   action->args.push_back("-o");
563                   InFile.append_suffix("bc");
564                   action->args.push_back(InFile.get());
565                   actions.push_back(action);
566                 }
567               }
568             } else if (finalPhase == TRANSLATION) {
569               throw cd->langName + " does not support translation";
570             } else if (action.isSet(REQUIRED_FLAG)) {
571               throw std::string("Don't know how to translate ") + 
572                     cd->langName + " files";
573             }
574
575             // Short-circuit remaining actions if all they want is translation
576             if (finalPhase == TRANSLATION) { ++I; continue; }
577
578             /// OPTIMIZATION PHASE
579             action = cd->Optimizer;
580
581             // Get the optimization action, if needed, or error if appropriate
582             if (!isSet(EMIT_RAW_FLAG)) {
583               if (!action.program.is_empty()) {
584                 if (action.isSet(REQUIRED_FLAG) || finalPhase == OPTIMIZATION) {
585                   if (finalPhase == OPTIMIZATION)
586                     actions.push_back(GetAction(cd,InFile,OutFile,OPTIMIZATION));
587                   else {
588                     sys::Path TempFile(MakeTempFile(I->first.get(),"opt"));
589                     actions.push_back(GetAction(cd,InFile,TempFile,OPTIMIZATION));
590                     InFile = TempFile;
591                   }
592                   // ll -> bc Helper
593                   if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
594                     /// The output of the translator is an LLVM Assembly program
595                     /// We need to translate it to bytecode
596                     Action* action = new Action();
597                     action->program.set_file("llvm-as");
598                     action->args.push_back(InFile.get());
599                     action->args.push_back("-f");
600                     action->args.push_back("-o");
601                     InFile.append_suffix("bc");
602                     action->args.push_back(InFile.get());
603                     actions.push_back(action);
604                   }
605                 }
606               } else if (finalPhase == OPTIMIZATION) {
607                 throw cd->langName + " does not support optimization";
608               } else if (action.isSet(REQUIRED_FLAG)) {
609                 throw std::string("Don't know how to optimize ") + 
610                     cd->langName + " files";
611               }
612             }
613
614             // Short-circuit remaining actions if all they want is optimization
615             if (finalPhase == OPTIMIZATION) { ++I; continue; }
616
617             /// ASSEMBLY PHASE
618             action = cd->Assembler;
619
620             if (finalPhase == ASSEMBLY || isSet(EMIT_NATIVE_FLAG)) {
621               if (isSet(EMIT_NATIVE_FLAG)) {
622                 if (action.program.is_empty()) {
623                   throw std::string("Native Assembler not specified for ") +
624                         cd->langName + " files";
625                 } else if (finalPhase == ASSEMBLY) {
626                   actions.push_back(GetAction(cd,InFile,OutFile,ASSEMBLY));
627                 } else {
628                   sys::Path TempFile(MakeTempFile(I->first.get(),"S"));
629                   actions.push_back(GetAction(cd,InFile,TempFile,ASSEMBLY));
630                   InFile = TempFile;
631                 }
632               } else {
633                 // Just convert back to llvm assembly with llvm-dis
634                 Action* action = new Action();
635                 action->program.set_file("llvm-dis");
636                 action->args.push_back(InFile.get());
637                 action->args.push_back("-f");
638                 action->args.push_back("-o");
639                 action->args.push_back(OutFile.get());
640                 actions.push_back(action);
641               }
642             }
643
644             // Short-circuit remaining actions if all they want is assembly output
645             if (finalPhase == ASSEMBLY) { ++I; continue; }
646               
647             // Register the OutFile as a link candidate
648             LinkageItems.insert(InFile);
649
650             // Go to next file to be processed
651             ++I;
652           }
653
654           /// RUN THE COMPILATION ACTIONS
655           std::vector<Action*>::iterator AI = actions.begin();
656           std::vector<Action*>::iterator AE = actions.end();
657           while (AI != AE) {
658             if (!DoAction(*AI))
659               throw std::string("Action failed");
660             AI++;
661           }
662
663           /// LINKING PHASE
664           actions.clear();
665           if (finalPhase == LINKING) {
666             if (isSet(EMIT_NATIVE_FLAG)) {
667               throw std::string(
668                 "llvmc doesn't know how to link native code yet");
669             } else {
670               // First, we need to examine the files to ensure that they all contain
671               // bytecode files. Since the final output is bytecode, we can only
672               // link bytecode.
673               SetVector<sys::Path>::const_iterator I = LinkageItems.begin();
674               SetVector<sys::Path>::const_iterator E = LinkageItems.end();
675               std::string errmsg;
676
677               while (I != E && ProcessLinkageItem(*I,LinkageItems,errmsg))
678                 ++I;
679
680               if (!errmsg.empty())
681                 throw errmsg;
682
683               // Insert the system libraries.
684               LibraryPaths.push_back(sys::Path::GetSystemLibraryPath1());
685               LibraryPaths.push_back(sys::Path::GetSystemLibraryPath2());
686
687               // We're emitting bytecode so let's build an llvm-link Action
688               Action* link = new Action();
689               link->program.set_file("llvm-link");
690               for (PathVector::const_iterator I=LinkageItems.begin(), 
691                    E=LinkageItems.end(); I != E; ++I )
692                 link->args.push_back(I->get());
693               if (isSet(VERBOSE_FLAG))
694                 link->args.push_back("-v");
695               link->args.push_back("-f");
696               link->args.push_back("-o");
697               link->args.push_back(OutFile.get());
698               if (isSet(TIME_PASSES_FLAG))
699                 link->args.push_back("-time-passes");
700               if (isSet(SHOW_STATS_FLAG))
701                 link->args.push_back("-stats");
702               actions.push_back(link);
703             }
704           }
705
706           /// RUN THE LINKING ACTIONS
707           AI = actions.begin();
708           AE = actions.end();
709           while (AI != AE) {
710             if (!DoAction(*AI))
711               throw std::string("Action failed");
712             AI++;
713           }
714         } catch (std::string& msg) {
715           cleanup();
716           throw;
717         } catch (...) {
718           cleanup();
719           throw std::string("Unspecified error");
720         }
721         cleanup();
722         return 0;
723       }
724
725     /// @}
726     /// @name Data
727     /// @{
728     private:
729       ConfigDataProvider* cdp;      ///< Where we get configuration data from
730       Phases finalPhase;            ///< The final phase of compilation
731       OptimizationLevels optLevel;  ///< The optimization level to apply
732       unsigned Flags;               ///< The driver flags
733       std::string machine;          ///< Target machine name
734       PathVector LibraryPaths;      ///< -L options
735       PathVector IncludePaths;      ///< -I options
736       StringVector Defines;         ///< -D options
737       sys::Path TempDir;            ///< Name of the temporary directory.
738       StringTable AdditionalArgs;   ///< The -Txyz options
739
740     /// @}
741   };
742 }
743
744 CompilerDriver::~CompilerDriver() {
745 }
746
747 CompilerDriver*
748 CompilerDriver::Get(ConfigDataProvider& CDP) {
749   return new CompilerDriverImpl(CDP);
750 }
751
752 CompilerDriver::ConfigData::ConfigData()
753   : langName()
754   , PreProcessor()
755   , Translator()
756   , Optimizer()
757   , Assembler()
758   , Linker()
759 {
760   StringVector emptyVec;
761   for (unsigned i = 0; i < NUM_PHASES; ++i)
762     opts.push_back(emptyVec);
763 }
764
765 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab