blob: d96d164e54f1395a93f836a0aefa8d754d12e42d [file] [log] [blame]
Chris Lattner67e08422003-06-20 15:49:04 +00001//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
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.
Misha Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2cf137b2001-09-07 22:20:50 +00009//
Brian Gaeke33e83b62004-03-16 21:47:20 +000010// This is the llc code generator driver. It provides a convenient
Misha Brukman650ba8e2005-04-22 00:00:37 +000011// command-line interface for generating native assembly-language code
Brian Gaeke33e83b62004-03-16 21:47:20 +000012// or C code, given LLVM bytecode.
Chris Lattner2cf137b2001-09-07 22:20:50 +000013//
Chris Lattnerb27d4742001-10-04 01:40:53 +000014//===----------------------------------------------------------------------===//
Vikram S. Adve2d94a342001-07-21 12:42:29 +000015
Chris Lattner6dd290a2007-05-06 04:55:19 +000016#include "llvm/Bitcode/ReaderWriter.h"
Vikram S. Adve2d94a342001-07-21 12:42:29 +000017#include "llvm/Bytecode/Reader.h"
Bill Wendlingfe5ee142007-02-08 01:41:07 +000018#include "llvm/CodeGen/FileWriters.h"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000019#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Jim Laskey19058c32005-09-01 21:38:21 +000020#include "llvm/Target/SubtargetFeature.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000021#include "llvm/Target/TargetData.h"
Vikram S. Adve9d409352001-09-18 13:10:45 +000022#include "llvm/Target/TargetMachine.h"
Chris Lattner6142ca82004-07-11 04:03:24 +000023#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner89a20ef2002-05-07 20:03:27 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattnered226062001-09-07 21:26:31 +000025#include "llvm/Module.h"
Chris Lattner7139f282002-01-31 00:46:45 +000026#include "llvm/PassManager.h"
Vikram S. Adveeb818692002-09-16 16:35:34 +000027#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
Chris Lattnera0e49f22007-02-07 21:41:02 +000029#include "llvm/Support/Compressor.h"
Chris Lattner76d46322006-12-06 01:18:01 +000030#include "llvm/Support/ManagedStatic.h"
Chris Lattner6dd290a2007-05-06 04:55:19 +000031#include "llvm/Support/MemoryBuffer.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/PluginLoader.h"
Duraid Madinace551ba2005-12-30 02:47:21 +000033#include "llvm/Support/FileUtilities.h"
Reid Spencer8e3830d2005-07-28 02:25:30 +000034#include "llvm/Analysis/Verifier.h"
Chris Lattner278f5152004-05-27 05:41:36 +000035#include "llvm/System/Signals.h"
Chris Lattner06fcc4c2005-06-25 03:32:05 +000036#include "llvm/Config/config.h"
Reid Spencer5113dc52006-06-07 23:03:13 +000037#include "llvm/LinkAllVMCore.h"
Chris Lattner46f1b612001-09-19 16:52:09 +000038#include <fstream>
Reid Spencerf0ebb252004-07-04 12:20:55 +000039#include <iostream>
40#include <memory>
Brian Gaeke960707c2003-11-11 22:41:34 +000041using namespace llvm;
42
Chris Lattner6dd290a2007-05-06 04:55:19 +000043cl::opt<bool> Bitcode("bitcode");
44
45
Vikram S. Adveeb818692002-09-16 16:35:34 +000046// General options for llc. Other pass-specific options are specified
47// within the corresponding llc passes, and target-specific options
48// and back-end code generation options are specified with the target machine.
Misha Brukman650ba8e2005-04-22 00:00:37 +000049//
Chris Lattnerd64b2de2003-04-25 05:26:11 +000050static cl::opt<std::string>
Chris Lattnerf5cad152002-07-22 02:10:13 +000051InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
52
Chris Lattnerd64b2de2003-04-25 05:26:11 +000053static cl::opt<std::string>
Chris Lattnerf5cad152002-07-22 02:10:13 +000054OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
55
56static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
57
Chris Lattner731055e2005-11-08 02:12:17 +000058static cl::opt<bool> Fast("fast",
59 cl::desc("Generate code quickly, potentially sacrificing code quality"));
60
Chris Lattnere568b882005-12-16 04:59:57 +000061static cl::opt<std::string>
Chris Lattner08a04cb2005-12-16 05:19:55 +000062TargetTriple("mtriple", cl::desc("Override target triple for module"));
Chris Lattner731055e2005-11-08 02:12:17 +000063
Chris Lattner6142ca82004-07-11 04:03:24 +000064static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
Chris Lattner09b0eb32005-06-25 03:00:34 +000065MArch("march", cl::desc("Architecture to generate code for:"));
Misha Brukman650ba8e2005-04-22 00:00:37 +000066
Jim Laskey19058c32005-09-01 21:38:21 +000067static cl::opt<std::string>
68MCPU("mcpu",
Chris Lattner0b2bf4c2005-10-23 22:35:42 +000069 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
Jim Laskey19058c32005-09-01 21:38:21 +000070 cl::value_desc("cpu-name"),
71 cl::init(""));
72
73static cl::list<std::string>
74MAttrs("mattr",
75 cl::CommaSeparated,
Chris Lattner0b2bf4c2005-10-23 22:35:42 +000076 cl::desc("Target specific attributes (-mattr=help for details)"),
Chris Lattner41548482005-10-23 22:37:13 +000077 cl::value_desc("a1,+a2,-a3,..."));
Jim Laskey19058c32005-09-01 21:38:21 +000078
Chris Lattner06fcc4c2005-06-25 03:32:05 +000079cl::opt<TargetMachine::CodeGenFileType>
80FileType("filetype", cl::init(TargetMachine::AssemblyFile),
81 cl::desc("Choose a file type (not all types are supported by all targets):"),
82 cl::values(
83 clEnumValN(TargetMachine::AssemblyFile, "asm",
84 " Emit an assembly ('.s') file"),
85 clEnumValN(TargetMachine::ObjectFile, "obj",
Chris Lattner711a5fe2005-10-22 22:00:45 +000086 " Emit a native object ('.o') file [experimental]"),
Chris Lattner06fcc4c2005-06-25 03:32:05 +000087 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
Nate Begemana147cbf2006-08-23 21:29:52 +000088 " Emit a native dynamic library ('.so') file"
89 " [experimental]"),
Chris Lattner06fcc4c2005-06-25 03:32:05 +000090 clEnumValEnd));
91
Reid Spencer8e3830d2005-07-28 02:25:30 +000092cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
Jeff Cohen546fd592005-07-30 18:33:25 +000093 cl::desc("Do not verify input module"));
Reid Spencer8e3830d2005-07-28 02:25:30 +000094
Chris Lattner06fcc4c2005-06-25 03:32:05 +000095
96// GetFileNameRoot - Helper function to get the basename of a filename.
Chris Lattnerd64b2de2003-04-25 05:26:11 +000097static inline std::string
Chris Lattner6142ca82004-07-11 04:03:24 +000098GetFileNameRoot(const std::string &InputFilename) {
Chris Lattnerd64b2de2003-04-25 05:26:11 +000099 std::string IFN = InputFilename;
100 std::string outputFilename;
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000101 int Len = IFN.length();
John Criswella289abf2003-08-28 21:42:29 +0000102 if ((Len > 2) &&
103 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
Chris Lattnerd64b2de2003-04-25 05:26:11 +0000104 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000105 } else {
Chris Lattner97fd6c42001-10-15 17:30:47 +0000106 outputFilename = IFN;
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000107 }
108 return outputFilename;
109}
110
Chris Lattner12e97302006-09-04 04:14:57 +0000111static std::ostream *GetOutputStream(const char *ProgName) {
112 if (OutputFilename != "") {
113 if (OutputFilename == "-")
114 return &std::cout;
115
116 // Specified an output filename?
117 if (!Force && std::ifstream(OutputFilename.c_str())) {
118 // If force is not specified, make sure not to overwrite a file!
119 std::cerr << ProgName << ": error opening '" << OutputFilename
120 << "': file exists!\n"
121 << "Use -f command line argument to force output\n";
122 return 0;
123 }
124 // Make sure that the Out file gets unlinked from the disk if we get a
125 // SIGINT
126 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
127
128 return new std::ofstream(OutputFilename.c_str());
129 }
130
131 if (InputFilename == "-") {
132 OutputFilename = "-";
133 return &std::cout;
134 }
135
136 OutputFilename = GetFileNameRoot(InputFilename);
137
138 switch (FileType) {
139 case TargetMachine::AssemblyFile:
140 if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
141 OutputFilename += ".s";
142 else
143 OutputFilename += ".cbe.c";
144 break;
145 case TargetMachine::ObjectFile:
146 OutputFilename += ".o";
147 break;
148 case TargetMachine::DynamicLibrary:
149 OutputFilename += LTDL_SHLIB_EXT;
150 break;
151 }
152
153 if (!Force && std::ifstream(OutputFilename.c_str())) {
154 // If force is not specified, make sure not to overwrite a file!
155 std::cerr << ProgName << ": error opening '" << OutputFilename
156 << "': file exists!\n"
157 << "Use -f command line argument to force output\n";
158 return 0;
159 }
160
161 // Make sure that the Out file gets unlinked from the disk if we get a
162 // SIGINT
163 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
164
165 std::ostream *Out = new std::ofstream(OutputFilename.c_str());
166 if (!Out->good()) {
167 std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
168 delete Out;
169 return 0;
170 }
171
172 return Out;
173}
Vikram S. Adve9d409352001-09-18 13:10:45 +0000174
Chris Lattner67e08422003-06-20 15:49:04 +0000175// main - Entry point for the llc compiler.
176//
177int main(int argc, char **argv) {
Chris Lattner76d46322006-12-06 01:18:01 +0000178 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Chris Lattner6dd290a2007-05-06 04:55:19 +0000179 cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
180 sys::PrintStackTraceOnErrorSignal();
Chris Lattner69e896b2004-02-19 20:32:39 +0000181
Chris Lattner6dd290a2007-05-06 04:55:19 +0000182 // Load the module to be compiled...
183 std::string ErrorMessage;
184 std::auto_ptr<Module> M;
185
186 if (Bitcode) {
Chris Lattner957d0902007-05-06 05:47:36 +0000187 std::auto_ptr<MemoryBuffer> Buffer(
188 MemoryBuffer::getFileOrSTDIN(&InputFilename[0], InputFilename.size()));
189 if (Buffer.get())
190 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
Chris Lattner6dd290a2007-05-06 04:55:19 +0000191 else
Chris Lattner957d0902007-05-06 05:47:36 +0000192 ErrorMessage = "Error reading file '" + InputFilename + "'";
Chris Lattner6dd290a2007-05-06 04:55:19 +0000193 } else {
194 M.reset(ParseBytecodeFile(InputFilename,
195 Compressor::decompressToNewBuffer,
196 &ErrorMessage));
197 }
198 if (M.get() == 0) {
199 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
200 std::cerr << "Reason: " << ErrorMessage << "\n";
201 return 1;
202 }
203 Module &mod = *M.get();
204
205 // If we are supposed to override the target triple, do so now.
206 if (!TargetTriple.empty())
207 mod.setTargetTriple(TargetTriple);
208
209 // Allocate target machine. First, check whether the user has
210 // explicitly specified an architecture to compile for.
211 if (MArch == 0) {
212 std::string Err;
213 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
214 if (MArch == 0) {
215 std::cerr << argv[0] << ": error auto-selecting target for module '"
216 << Err << "'. Please use the -march option to explicitly "
217 << "pick a target.\n";
Chris Lattnerb1492402003-08-24 14:02:14 +0000218 return 1;
Chris Lattner6142ca82004-07-11 04:03:24 +0000219 }
Chris Lattner5667f0e2002-10-29 21:12:46 +0000220 }
Chris Lattner6dd290a2007-05-06 04:55:19 +0000221
222 // Package up features to be passed to target/subtarget
223 std::string FeaturesStr;
224 if (MCPU.size() || MAttrs.size()) {
225 SubtargetFeatures Features;
226 Features.setCPU(MCPU);
227 for (unsigned i = 0; i != MAttrs.size(); ++i)
228 Features.AddFeature(MAttrs[i]);
229 FeaturesStr = Features.getString();
230 }
231
232 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
233 assert(target.get() && "Could not allocate target machine!");
234 TargetMachine &Target = *target.get();
235
236 // Figure out where we are going to send the output...
237 std::ostream *Out = GetOutputStream(argv[0]);
238 if (Out == 0) return 1;
239
240 // If this target requires addPassesToEmitWholeFile, do it now. This is
241 // used by strange things like the C backend.
242 if (Target.WantsWholeFile()) {
243 PassManager PM;
244 PM.add(new TargetData(*Target.getTargetData()));
245 if (!NoVerify)
246 PM.add(createVerifierPass());
247
248 // Ask the target to add backend passes as necessary.
249 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
250 std::cerr << argv[0] << ": target does not support generation of this"
251 << " file type!\n";
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();
255 return 1;
256 }
257 PM.run(mod);
258 } else {
259 // Build up all of the passes that we want to do to the module.
260 FunctionPassManager Passes(new ExistingModuleProvider(M.get()));
261 Passes.add(new TargetData(*Target.getTargetData()));
262
263#ifndef NDEBUG
264 if (!NoVerify)
265 Passes.add(createVerifierPass());
266#endif
267
268 // Ask the target to add backend passes as necessary.
269 MachineCodeEmitter *MCE = 0;
270
271 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
272 default:
273 assert(0 && "Invalid file model!");
274 return 1;
275 case FileModel::Error:
276 std::cerr << argv[0] << ": target does not support generation of this"
277 << " file type!\n";
278 if (Out != &std::cout) delete Out;
279 // And the Out file is empty and useless, so remove it now.
280 sys::Path(OutputFilename).eraseFromDisk();
281 return 1;
282 case FileModel::AsmFile:
283 break;
284 case FileModel::MachOFile:
285 MCE = AddMachOWriter(Passes, *Out, Target);
286 break;
287 case FileModel::ElfFile:
288 MCE = AddELFWriter(Passes, *Out, Target);
289 break;
290 }
291
292 if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) {
293 std::cerr << argv[0] << ": target does not support generation of this"
294 << " file type!\n";
295 if (Out != &std::cout) delete Out;
296 // And the Out file is empty and useless, so remove it now.
297 sys::Path(OutputFilename).eraseFromDisk();
298 return 1;
299 }
300
301 Passes.doInitialization();
302
303 // Run our queue of passes all at once now, efficiently.
304 // TODO: this could lazily stream functions out of the module.
305 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
306 if (!I->isDeclaration())
307 Passes.run(*I);
308
309 Passes.doFinalization();
310 }
311
312 // Delete the ostream if it's not a stdout stream
313 if (Out != &std::cout) delete Out;
314
315 return 0;
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000316}