da6058033f9a6a88ccb2e4b8f8c790ad9e9ffc48
[oota-llvm.git] / tools / llvmc / llvmc.cpp
1 //===--- llvmc.cpp - The LLVM Compiler Driver -------------------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 //  This tool provides a single point of access to the LLVM compilation tools.
11 //  It has many options. To discover the options supported please refer to the
12 //  tools' manual page (docs/CommandGuide/html/llvmc.html) or run the tool with
13 //  the --help option.
14 // 
15 //===------------------------------------------------------------------------===
16
17 #include "CompilerDriver.h"
18 #include "Configuration.h"
19 #include "llvm/Pass.h"
20 #include "llvm/System/Signals.h"
21 #include "llvm/Support/CommandLine.h"
22 #include <iostream>
23
24 using namespace llvm;
25
26 namespace {
27 //===------------------------------------------------------------------------===
28 //===          PHASE OPTIONS
29 //===------------------------------------------------------------------------===
30 cl::opt<CompilerDriver::Phases> FinalPhase(
31   cl::desc("Choose final phase of compilation:"), 
32   cl::init(CompilerDriver::LINKING),
33   cl::values(
34     clEnumValN(CompilerDriver::PREPROCESSING,"E",
35       "Stop compilation after pre-processing phase"),
36     clEnumValN(CompilerDriver::TRANSLATION, "t",
37       "Stop compilation after translation phase"),
38     clEnumValN(CompilerDriver::OPTIMIZATION,"c",
39       "Stop compilation after optimization phase"),
40     clEnumValN(CompilerDriver::ASSEMBLY,"S",
41       "Stop compilation after assembly phase"),
42     clEnumValEnd
43   )
44 );
45
46 //===------------------------------------------------------------------------===
47 //===          OPTIMIZATION OPTIONS
48 //===------------------------------------------------------------------------===
49 cl::opt<CompilerDriver::OptimizationLevels> OptLevel(
50   cl::desc("Choose level of optimization to apply:"),
51   cl::init(CompilerDriver::OPT_FAST_COMPILE),
52   cl::values(
53     clEnumValN(CompilerDriver::OPT_FAST_COMPILE,"O0",
54       "An alias for the -O1 option."),
55     clEnumValN(CompilerDriver::OPT_FAST_COMPILE,"O1",
56       "Optimize for compilation speed, not execution speed."),
57     clEnumValN(CompilerDriver::OPT_SIMPLE,"O2",
58       "Perform simple translation time optimizations"),
59     clEnumValN(CompilerDriver::OPT_AGGRESSIVE,"O3",
60       "Perform aggressive translation time optimizations"),
61     clEnumValN(CompilerDriver::OPT_LINK_TIME,"O4",
62       "Perform link time optimizations"),
63     clEnumValN(CompilerDriver::OPT_AGGRESSIVE_LINK_TIME,"O5",
64       "Perform aggressive link time optimizations"),
65     clEnumValEnd
66   )
67 );
68
69 //===------------------------------------------------------------------------===
70 //===          TOOL OPTIONS
71 //===------------------------------------------------------------------------===
72
73 cl::list<std::string> PreprocessorToolOpts("Tpre", cl::ZeroOrMore,
74   cl::desc("Pass specific options to the pre-processor"), 
75   cl::value_desc("option"));
76
77 cl::list<std::string> TranslatorToolOpts("Ttrn", cl::ZeroOrMore,
78   cl::desc("Pass specific options to the assembler"),
79   cl::value_desc("option"));
80
81 cl::list<std::string> AssemblerToolOpts("Tasm", cl::ZeroOrMore,
82   cl::desc("Pass specific options to the assembler"),
83   cl::value_desc("option"));
84
85 cl::list<std::string> OptimizerToolOpts("Topt", cl::ZeroOrMore,
86   cl::desc("Pass specific options to the optimizer"),
87   cl::value_desc("option"));
88
89 cl::list<std::string> LinkerToolOpts("Tlnk", cl::ZeroOrMore,
90   cl::desc("Pass specific options to the linker"),
91   cl::value_desc("option"));
92
93 cl::list<std::string> fOpts("f", cl::ZeroOrMore, cl::Prefix,
94   cl::desc("Pass through -f options to compiler tools"),
95   cl::value_desc("optimization option"));
96
97 cl::list<std::string> MOpts("M", cl::ZeroOrMore, cl::Prefix,
98   cl::desc("Pass through -M options to compiler tools"),
99   cl::value_desc("dependency option"));
100
101 cl::list<std::string> WOpts("W", cl::ZeroOrMore, cl::Prefix,
102   cl::desc("Pass through -W options to compiler tools"),
103   cl::value_desc("warnings category"));
104
105 //===------------------------------------------------------------------------===
106 //===          INPUT OPTIONS
107 //===------------------------------------------------------------------------===
108
109 cl::list<std::string> LibPaths("L", cl::Prefix,
110   cl::desc("Specify a library search path"), cl::value_desc("directory"));
111                                                                                                                                             
112 cl::list<std::string> Libraries("l", cl::Prefix,
113   cl::desc("Specify libraries to link to"), cl::value_desc("library prefix"));
114
115 cl::list<std::string> Includes("I", cl::Prefix,
116   cl::desc("Specify location to search for included source"), 
117   cl::value_desc("include directory"));
118
119 cl::list<std::string> Defines("D", cl::Prefix,
120   cl::desc("Specify a symbol to define for source configuration"),
121   cl::value_desc("symbol definition"));
122
123
124 //===------------------------------------------------------------------------===
125 //===          OUTPUT OPTIONS
126 //===------------------------------------------------------------------------===
127
128 cl::opt<std::string> OutputFilename("o", 
129   cl::desc("Override output filename"), cl::value_desc("filename"));
130
131 cl::opt<bool> ForceOutput("F", cl::Optional, cl::init(false),
132   cl::desc("Force output files to be overridden"));
133
134 cl::opt<std::string> OutputMachine("m", cl::Prefix,
135   cl::desc("Specify a target machine"), cl::value_desc("machine"));
136                                                                                                                                             
137 cl::opt<bool> Native("native", cl::init(false),
138   cl::desc("Generative native object and executables instead of bytecode"));
139
140 cl::opt<bool> DebugOutput("g", cl::init(false),
141   cl::desc("Generate objects that include debug symbols"));
142
143 cl::opt<bool> StripOutput("strip", cl::init(false),
144   cl::desc("Strip all symbols from linked output file"));
145
146 //===------------------------------------------------------------------------===
147 //===          INFORMATION OPTIONS
148 //===------------------------------------------------------------------------===
149
150 cl::opt<bool> DryRun("dry-run", cl::Optional, cl::init(false),
151   cl::desc("Do everything but perform the compilation actions"));
152
153 cl::alias DryRunAlias("y", cl::Optional,
154   cl::desc("Alias for -dry-run"), cl::aliasopt(DryRun));
155
156 cl::opt<bool> Verbose("verbose", cl::Optional, cl::init(false),
157   cl::desc("Print out each action taken"));
158
159 cl::alias VerboseAlias("v", cl::Optional, 
160   cl::desc("Alias for -verbose"), cl::aliasopt(Verbose));
161
162 cl::opt<bool> Debug("debug", cl::Optional, cl::init(false), 
163   cl::Hidden, cl::desc("Print out debugging information"));
164
165 cl::alias DebugAlias("d", cl::Optional,
166   cl::desc("Alias for -debug"), cl::aliasopt(Debug));
167
168 cl::opt<bool> TimeActions("time-actions", cl::Optional, cl::init(false),
169   cl::desc("Print execution time for each action taken"));
170
171 cl::opt<bool> ShowStats("stats", cl::Optional, cl::init(false),
172   cl::desc("Print statistics accumulated during optimization"));
173
174 //===------------------------------------------------------------------------===
175 //===          ADVANCED OPTIONS
176 //===------------------------------------------------------------------------===
177
178 static cl::opt<std::string> ConfigDir("config-dir", cl::Optional,
179   cl::desc("Specify a configuration directory to override defaults"),
180   cl::value_desc("directory"));
181
182 static cl::opt<bool> EmitRawCode("emit-raw-code", cl::Hidden, cl::Optional,
183   cl::desc("Emit raw, unoptimized code"));
184
185 static cl::opt<bool> PipeCommands("pipe", cl::Optional,
186   cl::desc("Invoke sub-commands by linking input/output with pipes"));
187
188 static cl::opt<bool> KeepTemps("keep-temps", cl::Optional,
189   cl::desc("Don't delete the temporary files created during compilation"));
190
191 //===------------------------------------------------------------------------===
192 //===          POSITIONAL OPTIONS
193 //===------------------------------------------------------------------------===
194
195 static cl::list<std::string> Files(cl::Positional, cl::OneOrMore,
196   cl::desc("[Sources/objects/libraries]"));
197
198 static cl::list<std::string> Languages("x", cl::ZeroOrMore,
199   cl::desc("Specify the source language for subsequent files"),
200   cl::value_desc("language"));
201
202 //===------------------------------------------------------------------------===
203 //===          GetFileType - determine type of a file
204 //===------------------------------------------------------------------------===
205 const std::string GetFileType(const std::string& fname, unsigned pos ) {
206   static std::vector<std::string>::iterator langIt = Languages.begin();
207   static std::string CurrLang = "";
208
209   // If a -x LANG option has been specified ..
210   if ( langIt != Languages.end() )
211     // If the -x LANG option came before the current file on command line
212     if ( Languages.getPosition( langIt - Languages.begin() ) < pos ) {
213       // use that language
214       CurrLang = *langIt++;
215       return CurrLang;
216     }
217
218   // If there's a current language in effect
219   if (!CurrLang.empty())
220     return CurrLang; // use that language
221
222   // otherwise just determine lang from the filename's suffix
223   return fname.substr( fname.rfind('.',fname.size()) + 1 );
224 }
225
226 } // end anonymous namespace
227
228
229 /// @brief The main program for llvmc
230 int main(int argc, char **argv) {
231   // Make sure we print stack trace if we get bad signals
232   sys::PrintStackTraceOnErrorSignal();
233
234   try {
235
236     // Parse the command line options
237     cl::ParseCommandLineOptions(argc, argv, 
238       " LLVM Compiler Driver (llvmc)\n\n"
239       "  This program provides easy invocation of the LLVM tool set\n"
240       "  and other compiler tools.\n"
241     );
242
243     // Deal with unimplemented options.
244     if (PipeCommands)
245       throw std::string("Not implemented yet: -pipe");
246
247     if (OutputFilename.empty())
248       if (OptLevel == CompilerDriver::LINKING)
249         OutputFilename = "a.out";
250       else
251         throw std::string("An output file must be specified. Please use the -o option");
252
253     // Construct the ConfigDataProvider object
254     LLVMC_ConfigDataProvider Provider;
255     Provider.setConfigDir(sys::Path(ConfigDir));
256
257     // Construct the CompilerDriver object
258     CompilerDriver* CD = CompilerDriver::Get(Provider);
259
260     // If the LLVM_LIB_SEARCH_PATH environment variable is
261     // set, append it to the list of places to search for libraries
262     std::string srchPath = getenv("LLVM_LIB_SEARCH_PATH");
263     if (!srchPath.empty())
264       LibPaths.push_back(srchPath);
265
266     // Set the driver flags based on command line options
267     unsigned flags = 0;
268     if (Verbose)        flags |= CompilerDriver::VERBOSE_FLAG;
269     if (Debug)          flags |= CompilerDriver::DEBUG_FLAG;
270     if (DryRun)         flags |= CompilerDriver::DRY_RUN_FLAG;
271     if (ForceOutput)    flags |= CompilerDriver::FORCE_FLAG;
272     if (Native)         flags |= CompilerDriver::EMIT_NATIVE_FLAG;
273     if (EmitRawCode)    flags |= CompilerDriver::EMIT_RAW_FLAG;
274     if (KeepTemps)      flags |= CompilerDriver::KEEP_TEMPS_FLAG;
275     if (ShowStats)      flags |= CompilerDriver::SHOW_STATS_FLAG;
276     if (TimeActions)    flags |= CompilerDriver::TIME_ACTIONS_FLAG;
277     if (TimePassesIsEnabled) flags |= CompilerDriver::TIME_PASSES_FLAG;
278     if (StripOutput)    flags |= CompilerDriver::STRIP_OUTPUT_FLAG;
279     CD->setDriverFlags(flags);
280
281     // Specify requred parameters
282     CD->setFinalPhase(FinalPhase);
283     CD->setOptimization(OptLevel);
284     CD->setOutputMachine(OutputMachine);
285     CD->setIncludePaths(Includes);
286     CD->setSymbolDefines(Defines);
287     CD->setLibraryPaths(LibPaths);
288     CD->setfPassThrough(fOpts);
289     CD->setMPassThrough(MOpts);
290     CD->setWPassThrough(WOpts);
291
292     // Provide additional tool arguments
293     if (!PreprocessorToolOpts.empty())
294         CD->setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
295     if (!TranslatorToolOpts.empty())
296         CD->setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
297     if (!OptimizerToolOpts.empty())
298         CD->setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
299     if (!AssemblerToolOpts.empty())
300         CD->setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
301     if (!LinkerToolOpts.empty())
302         CD->setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);
303
304     // Prepare the list of files to be compiled by the CompilerDriver.
305     CompilerDriver::InputList InpList;
306     std::vector<std::string>::iterator fileIt = Files.begin();
307     std::vector<std::string>::iterator libIt  = Libraries.begin();
308     unsigned libPos = 0, filePos = 0;
309     while ( 1 ) {
310       if ( libIt != Libraries.end() )
311         libPos = Libraries.getPosition( libIt - Libraries.begin() );
312       else
313         libPos = 0;
314       if ( fileIt != Files.end() )
315         filePos = Files.getPosition( fileIt - Files.begin() );
316       else
317         filePos = 0;
318
319       if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
320         // Add a source file
321         InpList.push_back( std::make_pair(*fileIt, GetFileType(*fileIt,filePos)));
322         ++fileIt;
323       }
324       else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
325         // Add a library
326         InpList.push_back( std::make_pair(*libIt++,""));
327       }
328       else
329         break; // we're done with the list
330     }
331
332     // Tell the driver to do its thing
333     int result = CD->execute(InpList,sys::Path(OutputFilename));
334     if (result != 0) {
335       throw std::string("Error executing actions. Terminated.");
336       return result;
337     }
338
339     // All is good, return success
340     return 0;
341   } catch (const std::string& msg) {
342     std::cerr << argv[0] << ": " << msg << "\n";
343   } catch (...) {
344     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
345   }
346 }