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