1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the llc code generator driver. It provides a convenient
11 // command-line interface for generating native assembly-language code
12 // or C code, given LLVM bytecode.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Bytecode/Reader.h"
17 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
18 #include "llvm/Target/SubtargetFeature.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetMachineRegistry.h"
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Module.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/PluginLoader.h"
29 #include "llvm/Support/FileUtilities.h"
30 #include "llvm/Analysis/Verifier.h"
31 #include "llvm/System/Signals.h"
32 #include "llvm/Config/config.h"
33 #include "llvm/LinkAllVMCore.h"
40 // General options for llc. Other pass-specific options are specified
41 // within the corresponding llc passes, and target-specific options
42 // and back-end code generation options are specified with the target machine.
44 static cl::opt<std::string>
45 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
47 static cl::opt<std::string>
48 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
50 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
52 static cl::opt<bool> Fast("fast",
53 cl::desc("Generate code quickly, potentially sacrificing code quality"));
55 static cl::opt<std::string>
56 TargetTriple("mtriple", cl::desc("Override target triple for module"));
58 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
59 MArch("march", cl::desc("Architecture to generate code for:"));
61 static cl::opt<std::string>
63 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
64 cl::value_desc("cpu-name"),
67 static cl::list<std::string>
70 cl::desc("Target specific attributes (-mattr=help for details)"),
71 cl::value_desc("a1,+a2,-a3,..."));
73 cl::opt<TargetMachine::CodeGenFileType>
74 FileType("filetype", cl::init(TargetMachine::AssemblyFile),
75 cl::desc("Choose a file type (not all types are supported by all targets):"),
77 clEnumValN(TargetMachine::AssemblyFile, "asm",
78 " Emit an assembly ('.s') file"),
79 clEnumValN(TargetMachine::ObjectFile, "obj",
80 " Emit a native object ('.o') file [experimental]"),
81 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
82 " Emit a native dynamic library ('.so') file"
86 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
87 cl::desc("Do not verify input module"));
90 // GetFileNameRoot - Helper function to get the basename of a filename.
91 static inline std::string
92 GetFileNameRoot(const std::string &InputFilename) {
93 std::string IFN = InputFilename;
94 std::string outputFilename;
95 int Len = IFN.length();
97 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
98 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
100 outputFilename = IFN;
102 return outputFilename;
105 static std::ostream *GetOutputStream(const char *ProgName) {
106 if (OutputFilename != "") {
107 if (OutputFilename == "-")
110 // Specified an output filename?
111 if (!Force && std::ifstream(OutputFilename.c_str())) {
112 // If force is not specified, make sure not to overwrite a file!
113 std::cerr << ProgName << ": error opening '" << OutputFilename
114 << "': file exists!\n"
115 << "Use -f command line argument to force output\n";
118 // Make sure that the Out file gets unlinked from the disk if we get a
120 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
122 return new std::ofstream(OutputFilename.c_str());
125 if (InputFilename == "-") {
126 OutputFilename = "-";
130 OutputFilename = GetFileNameRoot(InputFilename);
133 case TargetMachine::AssemblyFile:
134 if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
135 OutputFilename += ".s";
137 OutputFilename += ".cbe.c";
139 case TargetMachine::ObjectFile:
140 OutputFilename += ".o";
142 case TargetMachine::DynamicLibrary:
143 OutputFilename += LTDL_SHLIB_EXT;
147 if (!Force && std::ifstream(OutputFilename.c_str())) {
148 // If force is not specified, make sure not to overwrite a file!
149 std::cerr << ProgName << ": error opening '" << OutputFilename
150 << "': file exists!\n"
151 << "Use -f command line argument to force output\n";
155 // Make sure that the Out file gets unlinked from the disk if we get a
157 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
159 std::ostream *Out = new std::ofstream(OutputFilename.c_str());
161 std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
169 // main - Entry point for the llc compiler.
171 int main(int argc, char **argv) {
172 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
174 cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
175 sys::PrintStackTraceOnErrorSignal();
177 // Load the module to be compiled...
178 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
180 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
183 Module &mod = *M.get();
185 // If we are supposed to override the target triple, do so now.
186 if (!TargetTriple.empty())
187 mod.setTargetTriple(TargetTriple);
189 // Allocate target machine. First, check whether the user has
190 // explicitly specified an architecture to compile for.
193 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
195 std::cerr << argv[0] << ": error auto-selecting target for module '"
196 << Err << "'. Please use the -march option to explicitly "
197 << "pick a target.\n";
202 // Package up features to be passed to target/subtarget
203 std::string FeaturesStr;
204 if (MCPU.size() || MAttrs.size()) {
205 SubtargetFeatures Features;
206 Features.setCPU(MCPU);
207 for (unsigned i = 0; i != MAttrs.size(); ++i)
208 Features.AddFeature(MAttrs[i]);
209 FeaturesStr = Features.getString();
212 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
213 assert(target.get() && "Could not allocate target machine!");
214 TargetMachine &Target = *target.get();
216 // Figure out where we are going to send the output...
217 std::ostream *Out = GetOutputStream(argv[0]);
218 if (Out == 0) return 1;
220 // If this target requires addPassesToEmitWholeFile, do it now. This is
221 // used by strange things like the C backend.
222 if (Target.WantsWholeFile()) {
224 PM.add(new TargetData(*Target.getTargetData()));
226 PM.add(createVerifierPass());
228 // Ask the target to add backend passes as necessary.
229 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
230 std::cerr << argv[0] << ": target does not support generation of this"
232 if (Out != &std::cout) delete Out;
233 // And the Out file is empty and useless, so remove it now.
234 sys::Path(OutputFilename).eraseFromDisk();
239 // Build up all of the passes that we want to do to the module.
240 FunctionPassManager Passes(new ExistingModuleProvider(M.get()));
241 Passes.add(new TargetData(*Target.getTargetData()));
245 Passes.add(createVerifierPass());
248 // Ask the target to add backend passes as necessary.
249 if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
250 std::cerr << argv[0] << ": target does not support generation of this"
252 if (Out != &std::cout) delete Out;
253 // And the Out file is empty and useless, so remove it now.
254 sys::Path(OutputFilename).eraseFromDisk();
258 Passes.doInitialization();
260 // Run our queue of passes all at once now, efficiently.
261 // TODO: this could lazily stream functions out of the module.
262 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
263 if (!I->isExternal())
266 Passes.doFinalization();
269 // Delete the ostream if it's not a stdout stream
270 if (Out != &std::cout) delete Out;
273 } catch (const std::string& msg) {
274 std::cerr << argv[0] << ": " << msg << "\n";
276 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";