blob: dfd1f6b073eaeb32f2e56e7e8f6a953e16f8af7f [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
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 bitcode.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Bitcode/ReaderWriter.h"
17#include "llvm/CodeGen/FileWriters.h"
18#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Anton Korobeynikov6a2122d2008-08-17 14:33:01 +000019#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "llvm/Target/SubtargetFeature.h"
21#include "llvm/Target/TargetData.h"
22#include "llvm/Target/TargetMachine.h"
23#include "llvm/Target/TargetMachineRegistry.h"
24#include "llvm/Transforms/Scalar.h"
25#include "llvm/Module.h"
26#include "llvm/ModuleProvider.h"
27#include "llvm/PassManager.h"
28#include "llvm/Pass.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/ManagedStatic.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/PluginLoader.h"
33#include "llvm/Support/FileUtilities.h"
34#include "llvm/Analysis/Verifier.h"
35#include "llvm/System/Signals.h"
36#include "llvm/Config/config.h"
37#include "llvm/LinkAllVMCore.h"
38#include <fstream>
39#include <iostream>
40#include <memory>
41using namespace llvm;
42
43// General options for llc. Other pass-specific options are specified
44// within the corresponding llc passes, and target-specific options
45// and back-end code generation options are specified with the target machine.
46//
47static cl::opt<std::string>
48InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
49
50static cl::opt<std::string>
51OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
52
53static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
54
55static cl::opt<bool> Fast("fast",
56 cl::desc("Generate code quickly, potentially sacrificing code quality"));
57
58static cl::opt<std::string>
59TargetTriple("mtriple", cl::desc("Override target triple for module"));
60
Gordon Henriksen99e34ab2007-10-17 21:28:48 +000061static cl::opt<const TargetMachineRegistry::entry*, false,
62 TargetMachineRegistry::Parser>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063MArch("march", cl::desc("Architecture to generate code for:"));
64
65static cl::opt<std::string>
66MCPU("mcpu",
67 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
68 cl::value_desc("cpu-name"),
69 cl::init(""));
70
71static cl::list<std::string>
72MAttrs("mattr",
73 cl::CommaSeparated,
74 cl::desc("Target specific attributes (-mattr=help for details)"),
75 cl::value_desc("a1,+a2,-a3,..."));
76
77cl::opt<TargetMachine::CodeGenFileType>
78FileType("filetype", cl::init(TargetMachine::AssemblyFile),
79 cl::desc("Choose a file type (not all types are supported by all targets):"),
80 cl::values(
81 clEnumValN(TargetMachine::AssemblyFile, "asm",
82 " Emit an assembly ('.s') file"),
83 clEnumValN(TargetMachine::ObjectFile, "obj",
84 " Emit a native object ('.o') file [experimental]"),
85 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
86 " Emit a native dynamic library ('.so') file"
87 " [experimental]"),
88 clEnumValEnd));
89
90cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
91 cl::desc("Do not verify input module"));
92
93
94// GetFileNameRoot - Helper function to get the basename of a filename.
95static inline std::string
96GetFileNameRoot(const std::string &InputFilename) {
97 std::string IFN = InputFilename;
98 std::string outputFilename;
99 int Len = IFN.length();
100 if ((Len > 2) &&
101 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
102 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
103 } else {
104 outputFilename = IFN;
105 }
106 return outputFilename;
107}
108
109static std::ostream *GetOutputStream(const char *ProgName) {
110 if (OutputFilename != "") {
111 if (OutputFilename == "-")
112 return &std::cout;
113
114 // Specified an output filename?
115 if (!Force && std::ifstream(OutputFilename.c_str())) {
116 // If force is not specified, make sure not to overwrite a file!
117 std::cerr << ProgName << ": error opening '" << OutputFilename
118 << "': file exists!\n"
119 << "Use -f command line argument to force output\n";
120 return 0;
121 }
122 // Make sure that the Out file gets unlinked from the disk if we get a
123 // SIGINT
124 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
125
126 return new std::ofstream(OutputFilename.c_str());
127 }
128
129 if (InputFilename == "-") {
130 OutputFilename = "-";
131 return &std::cout;
132 }
133
134 OutputFilename = GetFileNameRoot(InputFilename);
135
136 switch (FileType) {
137 case TargetMachine::AssemblyFile:
Anton Korobeynikovb87de74b2008-04-23 22:29:24 +0000138 if (MArch->Name[0] == 'c') {
139 if (MArch->Name[1] == 0)
140 OutputFilename += ".cbe.c";
141 else if (MArch->Name[1] == 'p' && MArch->Name[2] == 'p')
142 OutputFilename += ".cpp";
143 else
144 OutputFilename += ".s";
145 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 OutputFilename += ".s";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 break;
148 case TargetMachine::ObjectFile:
149 OutputFilename += ".o";
150 break;
151 case TargetMachine::DynamicLibrary:
152 OutputFilename += LTDL_SHLIB_EXT;
153 break;
154 }
155
156 if (!Force && std::ifstream(OutputFilename.c_str())) {
157 // If force is not specified, make sure not to overwrite a file!
158 std::cerr << ProgName << ": error opening '" << OutputFilename
159 << "': file exists!\n"
160 << "Use -f command line argument to force output\n";
161 return 0;
162 }
163
164 // Make sure that the Out file gets unlinked from the disk if we get a
165 // SIGINT
166 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
167
168 std::ostream *Out = new std::ofstream(OutputFilename.c_str());
169 if (!Out->good()) {
170 std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
171 delete Out;
172 return 0;
173 }
174
175 return Out;
176}
177
178// main - Entry point for the llc compiler.
179//
180int main(int argc, char **argv) {
181 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Dan Gohman6099df82007-10-08 15:45:12 +0000182 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 sys::PrintStackTraceOnErrorSignal();
184
185 // Load the module to be compiled...
186 std::string ErrorMessage;
187 std::auto_ptr<Module> M;
188
189 std::auto_ptr<MemoryBuffer> Buffer(
190 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
191 if (Buffer.get())
192 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
193 if (M.get() == 0) {
194 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
195 std::cerr << "Reason: " << ErrorMessage << "\n";
196 return 1;
197 }
198 Module &mod = *M.get();
199
200 // If we are supposed to override the target triple, do so now.
201 if (!TargetTriple.empty())
202 mod.setTargetTriple(TargetTriple);
203
204 // Allocate target machine. First, check whether the user has
205 // explicitly specified an architecture to compile for.
206 if (MArch == 0) {
207 std::string Err;
208 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
209 if (MArch == 0) {
210 std::cerr << argv[0] << ": error auto-selecting target for module '"
211 << Err << "'. Please use the -march option to explicitly "
212 << "pick a target.\n";
213 return 1;
214 }
215 }
216
217 // Package up features to be passed to target/subtarget
218 std::string FeaturesStr;
219 if (MCPU.size() || MAttrs.size()) {
220 SubtargetFeatures Features;
221 Features.setCPU(MCPU);
222 for (unsigned i = 0; i != MAttrs.size(); ++i)
223 Features.AddFeature(MAttrs[i]);
224 FeaturesStr = Features.getString();
225 }
226
227 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
228 assert(target.get() && "Could not allocate target machine!");
229 TargetMachine &Target = *target.get();
230
231 // Figure out where we are going to send the output...
232 std::ostream *Out = GetOutputStream(argv[0]);
233 if (Out == 0) return 1;
234
235 // If this target requires addPassesToEmitWholeFile, do it now. This is
236 // used by strange things like the C backend.
237 if (Target.WantsWholeFile()) {
238 PassManager PM;
239 PM.add(new TargetData(*Target.getTargetData()));
240 if (!NoVerify)
241 PM.add(createVerifierPass());
242
243 // Ask the target to add backend passes as necessary.
244 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
245 std::cerr << argv[0] << ": target does not support generation of this"
246 << " file type!\n";
247 if (Out != &std::cout) delete Out;
248 // And the Out file is empty and useless, so remove it now.
249 sys::Path(OutputFilename).eraseFromDisk();
250 return 1;
251 }
252 PM.run(mod);
253 } else {
254 // Build up all of the passes that we want to do to the module.
Dan Gohmana16244e2008-04-16 15:56:26 +0000255 ExistingModuleProvider Provider(M.release());
256 FunctionPassManager Passes(&Provider);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 Passes.add(new TargetData(*Target.getTargetData()));
258
259#ifndef NDEBUG
260 if (!NoVerify)
261 Passes.add(createVerifierPass());
262#endif
263
264 // Ask the target to add backend passes as necessary.
265 MachineCodeEmitter *MCE = 0;
266
267 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
268 default:
269 assert(0 && "Invalid file model!");
270 return 1;
271 case FileModel::Error:
272 std::cerr << argv[0] << ": target does not support generation of this"
273 << " file type!\n";
274 if (Out != &std::cout) delete Out;
275 // And the Out file is empty and useless, so remove it now.
276 sys::Path(OutputFilename).eraseFromDisk();
277 return 1;
278 case FileModel::AsmFile:
279 break;
280 case FileModel::MachOFile:
281 MCE = AddMachOWriter(Passes, *Out, Target);
282 break;
283 case FileModel::ElfFile:
284 MCE = AddELFWriter(Passes, *Out, Target);
285 break;
286 }
287
288 if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) {
289 std::cerr << argv[0] << ": target does not support generation of this"
290 << " file type!\n";
291 if (Out != &std::cout) delete Out;
292 // And the Out file is empty and useless, so remove it now.
293 sys::Path(OutputFilename).eraseFromDisk();
294 return 1;
295 }
296
297 Passes.doInitialization();
298
299 // Run our queue of passes all at once now, efficiently.
300 // TODO: this could lazily stream functions out of the module.
301 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
302 if (!I->isDeclaration())
303 Passes.run(*I);
304
305 Passes.doFinalization();
306 }
307
308 // Delete the ostream if it's not a stdout stream
309 if (Out != &std::cout) delete Out;
310
311 return 0;
312}