1 //===--- llvmc.cpp - The LLVM Compiler Driver -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
15 //===------------------------------------------------------------------------===
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"
27 //===------------------------------------------------------------------------===
29 //===------------------------------------------------------------------------===
30 cl::opt<CompilerDriver::Phases> FinalPhase(
31 cl::desc("Choose final phase of compilation:"),
32 cl::init(CompilerDriver::LINKING),
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"),
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),
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"),
69 //===------------------------------------------------------------------------===
71 //===------------------------------------------------------------------------===
73 cl::list<std::string> PreprocessorToolOpts("Tpre", cl::ZeroOrMore,
74 cl::desc("Pass specific options to the pre-processor"),
75 cl::value_desc("option"));
77 cl::alias PreprocessorToolOptsAlias("Wp,", cl::ZeroOrMore,
78 cl::desc("Alias for -Tpre"), cl::aliasopt(PreprocessorToolOpts));
80 cl::list<std::string> TranslatorToolOpts("Ttrn", cl::ZeroOrMore,
81 cl::desc("Pass specific options to the assembler"),
82 cl::value_desc("option"));
84 cl::list<std::string> AssemblerToolOpts("Tasm", cl::ZeroOrMore,
85 cl::desc("Pass specific options to the assembler"),
86 cl::value_desc("option"));
88 cl::alias AssemblerToolOptsAlias("Wa,", cl::ZeroOrMore,
89 cl::desc("Alias for -Tasm"), cl::aliasopt(AssemblerToolOpts));
91 cl::list<std::string> OptimizerToolOpts("Topt", cl::ZeroOrMore,
92 cl::desc("Pass specific options to the optimizer"),
93 cl::value_desc("option"));
95 cl::list<std::string> LinkerToolOpts("Tlnk", cl::ZeroOrMore,
96 cl::desc("Pass specific options to the linker"),
97 cl::value_desc("option"));
99 cl::alias LinkerToolOptsAlias("Wl,", cl::ZeroOrMore,
100 cl::desc("Alias for -Tlnk"), cl::aliasopt(LinkerToolOpts));
102 cl::list<std::string> fOpts("f", cl::ZeroOrMore, cl::Prefix,
103 cl::desc("Pass through -f options to compiler tools"),
104 cl::value_desc("optimization option"));
106 cl::list<std::string> MOpts("M", cl::ZeroOrMore, cl::Prefix,
107 cl::desc("Pass through -M options to compiler tools"),
108 cl::value_desc("dependency option"));
110 cl::list<std::string> WOpts("W", cl::ZeroOrMore, cl::Prefix,
111 cl::desc("Pass through -W options to compiler tools"),
112 cl::value_desc("warnings category"));
114 cl::list<std::string> BOpt("B", cl::ZeroOrMore, cl::Prefix,
115 cl::desc("Indicate where llvmc sub-tools are installed"),
116 cl::value_desc("directory path containing bin and lib directories"));
118 //===------------------------------------------------------------------------===
120 //===------------------------------------------------------------------------===
122 cl::list<std::string> LibPaths("L", cl::Prefix,
123 cl::desc("Specify a library search path"), cl::value_desc("directory"));
125 cl::list<std::string> Libraries("l", cl::Prefix,
126 cl::desc("Specify libraries to link to"), cl::value_desc("library prefix"));
128 cl::list<std::string> Includes("I", cl::Prefix,
129 cl::desc("Specify location to search for included source"),
130 cl::value_desc("include directory"));
132 cl::list<std::string> Defines("D", cl::Prefix,
133 cl::desc("Specify a symbol to define for source configuration"),
134 cl::value_desc("symbol definition"));
136 //===------------------------------------------------------------------------===
138 //===------------------------------------------------------------------------===
140 cl::opt<std::string> OutputFilename("o",
141 cl::desc("Override output filename"), cl::value_desc("filename"));
143 cl::opt<std::string> OutputMachine("m", cl::Prefix,
144 cl::desc("Specify a target machine"), cl::value_desc("machine"));
146 cl::opt<bool> Native("native", cl::init(false),
147 cl::desc("Generative native object and executables instead of bytecode"));
149 cl::opt<bool> DebugOutput("g", cl::init(false),
150 cl::desc("Generate objects that include debug symbols"));
152 cl::opt<bool> StripOutput("strip", cl::init(false),
153 cl::desc("Strip all symbols from linked output file"));
155 //===------------------------------------------------------------------------===
156 //=== INFORMATION OPTIONS
157 //===------------------------------------------------------------------------===
159 cl::opt<bool> DryRun("dry-run", cl::Optional, cl::init(false),
160 cl::desc("Do everything but perform the compilation actions"));
162 cl::alias DryRunAlias("y", cl::Optional,
163 cl::desc("Alias for -dry-run"), cl::aliasopt(DryRun));
165 cl::opt<bool> Verbose("verbose", cl::Optional, cl::init(false),
166 cl::desc("Print out each action taken"));
168 cl::alias VerboseAlias("v", cl::Optional,
169 cl::desc("Alias for -verbose"), cl::aliasopt(Verbose));
171 cl::opt<bool> Debug("debug", cl::Optional, cl::init(false),
172 cl::Hidden, cl::desc("Print out debugging information"));
174 cl::alias DebugAlias("d", cl::Optional,
175 cl::desc("Alias for -debug"), cl::aliasopt(Debug));
177 cl::opt<bool> TimeActions("time-actions", cl::Optional, cl::init(false),
178 cl::desc("Print execution time for each action taken"));
180 cl::opt<bool> ShowStats("stats", cl::Optional, cl::init(false),
181 cl::desc("Print statistics accumulated during optimization"));
183 //===------------------------------------------------------------------------===
184 //=== ADVANCED OPTIONS
185 //===------------------------------------------------------------------------===
187 static cl::opt<std::string> ConfigDir("config-dir", cl::Optional,
188 cl::desc("Specify a configuration directory to override defaults"),
189 cl::value_desc("directory"));
191 static cl::opt<bool> EmitRawCode("emit-raw-code", cl::Hidden, cl::Optional,
192 cl::desc("Emit raw, unoptimized code"));
194 static cl::opt<bool> PipeCommands("pipe", cl::Optional,
195 cl::desc("Invoke sub-commands by linking input/output with pipes"));
197 static cl::opt<bool> KeepTemps("keep-temps", cl::Optional,
198 cl::desc("Don't delete the temporary files created during compilation"));
200 //===------------------------------------------------------------------------===
201 //=== POSITIONAL OPTIONS
202 //===------------------------------------------------------------------------===
204 static cl::list<std::string> Files(cl::Positional, cl::OneOrMore,
205 cl::desc("[Sources/objects/libraries]"));
207 static cl::list<std::string> Languages("x", cl::ZeroOrMore,
208 cl::desc("Specify the source language for subsequent files"),
209 cl::value_desc("language"));
211 //===------------------------------------------------------------------------===
212 //=== GetFileType - determine type of a file
213 //===------------------------------------------------------------------------===
214 const std::string GetFileType(const std::string& fname, unsigned pos ) {
215 static std::vector<std::string>::iterator langIt = Languages.begin();
216 static std::string CurrLang = "";
218 // If a -x LANG option has been specified ..
219 if ( langIt != Languages.end() )
220 // If the -x LANG option came before the current file on command line
221 if ( Languages.getPosition( langIt - Languages.begin() ) < pos ) {
223 CurrLang = *langIt++;
227 // If there's a current language in effect
228 if (!CurrLang.empty())
229 return CurrLang; // use that language
231 // otherwise just determine lang from the filename's suffix
232 return fname.substr( fname.rfind('.',fname.size()) + 1 );
235 } // end anonymous namespace
238 /// @brief The main program for llvmc
239 int main(int argc, char **argv) {
240 // Make sure we print stack trace if we get bad signals
241 sys::PrintStackTraceOnErrorSignal();
245 // Parse the command line options
246 cl::ParseCommandLineOptions(argc, argv,
247 " LLVM Compiler Driver (llvmc)\n\n"
248 " This program provides easy invocation of the LLVM tool set\n"
249 " and other compiler tools.\n"
252 // Deal with unimplemented options.
254 throw std::string("Not implemented yet: -pipe");
256 if (OutputFilename.empty())
257 if (OptLevel == CompilerDriver::LINKING)
258 OutputFilename = "a.out";
260 throw std::string("An output file must be specified. Please use the -o option");
262 // Construct the ConfigDataProvider object
263 LLVMC_ConfigDataProvider Provider;
264 Provider.setConfigDir(sys::Path(ConfigDir));
266 // Construct the CompilerDriver object
267 CompilerDriver* CD = CompilerDriver::Get(Provider);
269 // If the LLVM_LIB_SEARCH_PATH environment variable is
270 // set, append it to the list of places to search for libraries
271 std::string srchPath = getenv("LLVM_LIB_SEARCH_PATH");
272 if (!srchPath.empty())
273 LibPaths.push_back(srchPath);
275 // Set the driver flags based on command line options
277 if (Verbose) flags |= CompilerDriver::VERBOSE_FLAG;
278 if (Debug) flags |= CompilerDriver::DEBUG_FLAG;
279 if (DryRun) flags |= CompilerDriver::DRY_RUN_FLAG;
280 if (Native) flags |= CompilerDriver::EMIT_NATIVE_FLAG;
281 if (EmitRawCode) flags |= CompilerDriver::EMIT_RAW_FLAG;
282 if (KeepTemps) flags |= CompilerDriver::KEEP_TEMPS_FLAG;
283 if (ShowStats) flags |= CompilerDriver::SHOW_STATS_FLAG;
284 if (TimeActions) flags |= CompilerDriver::TIME_ACTIONS_FLAG;
285 if (TimePassesIsEnabled) flags |= CompilerDriver::TIME_PASSES_FLAG;
286 if (StripOutput) flags |= CompilerDriver::STRIP_OUTPUT_FLAG;
287 CD->setDriverFlags(flags);
289 // Specify requred parameters
290 CD->setFinalPhase(FinalPhase);
291 CD->setOptimization(OptLevel);
292 CD->setOutputMachine(OutputMachine);
293 CD->setIncludePaths(Includes);
294 CD->setSymbolDefines(Defines);
295 CD->setLibraryPaths(LibPaths);
296 CD->setfPassThrough(fOpts);
297 CD->setMPassThrough(MOpts);
298 CD->setWPassThrough(WOpts);
300 // Provide additional tool arguments
301 if (!PreprocessorToolOpts.empty())
302 CD->setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
303 if (!TranslatorToolOpts.empty())
304 CD->setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
305 if (!OptimizerToolOpts.empty())
306 CD->setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
307 if (!AssemblerToolOpts.empty())
308 CD->setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
309 if (!LinkerToolOpts.empty())
310 CD->setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);
312 // Prepare the list of files to be compiled by the CompilerDriver.
313 CompilerDriver::InputList InpList;
314 std::vector<std::string>::iterator fileIt = Files.begin();
315 std::vector<std::string>::iterator libIt = Libraries.begin();
316 unsigned libPos = 0, filePos = 0;
318 if ( libIt != Libraries.end() )
319 libPos = Libraries.getPosition( libIt - Libraries.begin() );
322 if ( fileIt != Files.end() )
323 filePos = Files.getPosition( fileIt - Files.begin() );
327 if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
329 InpList.push_back( std::make_pair(*fileIt, GetFileType(*fileIt,filePos)));
332 else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
334 InpList.push_back( std::make_pair(*libIt++,""));
337 break; // we're done with the list
340 // Tell the driver to do its thing
341 int result = CD->execute(InpList,sys::Path(OutputFilename));
343 throw std::string("Error executing actions. Terminated.");
347 // All is good, return success
349 } catch (const std::string& msg) {
350 std::cerr << argv[0] << ": " << msg << "\n";
352 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";