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