blob: c976ee261ecd89202d7a9b31f092b454f6010656 [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
Gabor Greife16561c2007-07-05 17:07:56 +000012// or C code, given LLVM bitcode.
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"
Bill Wendlingfe5ee142007-02-08 01:41:07 +000017#include "llvm/CodeGen/FileWriters.h"
Chris Lattner5af6a3f2006-08-01 22:34:35 +000018#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Jim Laskey19058c32005-09-01 21:38:21 +000019#include "llvm/Target/SubtargetFeature.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000020#include "llvm/Target/TargetData.h"
Vikram S. Adve9d409352001-09-18 13:10:45 +000021#include "llvm/Target/TargetMachine.h"
Chris Lattner6142ca82004-07-11 04:03:24 +000022#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner89a20ef2002-05-07 20:03:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattnered226062001-09-07 21:26:31 +000024#include "llvm/Module.h"
Chris Lattnerf5599ef2007-05-06 09:32:02 +000025#include "llvm/ModuleProvider.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 Lattner76d46322006-12-06 01:18:01 +000029#include "llvm/Support/ManagedStatic.h"
Chris Lattner6dd290a2007-05-06 04:55:19 +000030#include "llvm/Support/MemoryBuffer.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/PluginLoader.h"
Duraid Madinace551ba2005-12-30 02:47:21 +000032#include "llvm/Support/FileUtilities.h"
Reid Spencer8e3830d2005-07-28 02:25:30 +000033#include "llvm/Analysis/Verifier.h"
Chris Lattner278f5152004-05-27 05:41:36 +000034#include "llvm/System/Signals.h"
Chris Lattner06fcc4c2005-06-25 03:32:05 +000035#include "llvm/Config/config.h"
Reid Spencer5113dc52006-06-07 23:03:13 +000036#include "llvm/LinkAllVMCore.h"
Chris Lattner46f1b612001-09-19 16:52:09 +000037#include <fstream>
Reid Spencerf0ebb252004-07-04 12:20:55 +000038#include <iostream>
39#include <memory>
Brian Gaeke960707c2003-11-11 22:41:34 +000040using namespace llvm;
41
Vikram S. Adveeb818692002-09-16 16:35:34 +000042// General options for llc. Other pass-specific options are specified
43// within the corresponding llc passes, and target-specific options
44// and back-end code generation options are specified with the target machine.
Misha Brukman650ba8e2005-04-22 00:00:37 +000045//
Chris Lattnerd64b2de2003-04-25 05:26:11 +000046static cl::opt<std::string>
Gabor Greife16561c2007-07-05 17:07:56 +000047InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000048
Chris Lattnerd64b2de2003-04-25 05:26:11 +000049static cl::opt<std::string>
Chris Lattnerf5cad152002-07-22 02:10:13 +000050OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
53
Chris Lattner731055e2005-11-08 02:12:17 +000054static cl::opt<bool> Fast("fast",
55 cl::desc("Generate code quickly, potentially sacrificing code quality"));
56
Chris Lattnere568b882005-12-16 04:59:57 +000057static cl::opt<std::string>
Chris Lattner08a04cb2005-12-16 05:19:55 +000058TargetTriple("mtriple", cl::desc("Override target triple for module"));
Chris Lattner731055e2005-11-08 02:12:17 +000059
Gordon Henriksenef5d08f2007-10-17 21:28:48 +000060static cl::opt<const TargetMachineRegistry::entry*, false,
61 TargetMachineRegistry::Parser>
Chris Lattner09b0eb32005-06-25 03:00:34 +000062MArch("march", cl::desc("Architecture to generate code for:"));
Misha Brukman650ba8e2005-04-22 00:00:37 +000063
Jim Laskey19058c32005-09-01 21:38:21 +000064static cl::opt<std::string>
65MCPU("mcpu",
Chris Lattner0b2bf4c2005-10-23 22:35:42 +000066 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
Jim Laskey19058c32005-09-01 21:38:21 +000067 cl::value_desc("cpu-name"),
68 cl::init(""));
69
70static cl::list<std::string>
71MAttrs("mattr",
72 cl::CommaSeparated,
Chris Lattner0b2bf4c2005-10-23 22:35:42 +000073 cl::desc("Target specific attributes (-mattr=help for details)"),
Chris Lattner41548482005-10-23 22:37:13 +000074 cl::value_desc("a1,+a2,-a3,..."));
Jim Laskey19058c32005-09-01 21:38:21 +000075
Chris Lattner06fcc4c2005-06-25 03:32:05 +000076cl::opt<TargetMachine::CodeGenFileType>
77FileType("filetype", cl::init(TargetMachine::AssemblyFile),
78 cl::desc("Choose a file type (not all types are supported by all targets):"),
79 cl::values(
80 clEnumValN(TargetMachine::AssemblyFile, "asm",
81 " Emit an assembly ('.s') file"),
82 clEnumValN(TargetMachine::ObjectFile, "obj",
Chris Lattner711a5fe2005-10-22 22:00:45 +000083 " Emit a native object ('.o') file [experimental]"),
Chris Lattner06fcc4c2005-06-25 03:32:05 +000084 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
Nate Begemana147cbf2006-08-23 21:29:52 +000085 " Emit a native dynamic library ('.so') file"
86 " [experimental]"),
Chris Lattner06fcc4c2005-06-25 03:32:05 +000087 clEnumValEnd));
88
Reid Spencer8e3830d2005-07-28 02:25:30 +000089cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
Jeff Cohen546fd592005-07-30 18:33:25 +000090 cl::desc("Do not verify input module"));
Reid Spencer8e3830d2005-07-28 02:25:30 +000091
Chris Lattner06fcc4c2005-06-25 03:32:05 +000092
93// GetFileNameRoot - Helper function to get the basename of a filename.
Chris Lattnerd64b2de2003-04-25 05:26:11 +000094static inline std::string
Chris Lattner6142ca82004-07-11 04:03:24 +000095GetFileNameRoot(const std::string &InputFilename) {
Chris Lattnerd64b2de2003-04-25 05:26:11 +000096 std::string IFN = InputFilename;
97 std::string outputFilename;
Vikram S. Adve2f084b22001-10-14 23:29:28 +000098 int Len = IFN.length();
John Criswella289abf2003-08-28 21:42:29 +000099 if ((Len > 2) &&
100 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
Chris Lattnerd64b2de2003-04-25 05:26:11 +0000101 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000102 } else {
Chris Lattner97fd6c42001-10-15 17:30:47 +0000103 outputFilename = IFN;
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000104 }
105 return outputFilename;
106}
107
Chris Lattner12e97302006-09-04 04:14:57 +0000108static std::ostream *GetOutputStream(const char *ProgName) {
109 if (OutputFilename != "") {
110 if (OutputFilename == "-")
111 return &std::cout;
112
113 // Specified an output filename?
114 if (!Force && std::ifstream(OutputFilename.c_str())) {
115 // If force is not specified, make sure not to overwrite a file!
116 std::cerr << ProgName << ": error opening '" << OutputFilename
117 << "': file exists!\n"
118 << "Use -f command line argument to force output\n";
119 return 0;
120 }
121 // Make sure that the Out file gets unlinked from the disk if we get a
122 // SIGINT
123 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
124
125 return new std::ofstream(OutputFilename.c_str());
126 }
127
128 if (InputFilename == "-") {
129 OutputFilename = "-";
130 return &std::cout;
131 }
132
133 OutputFilename = GetFileNameRoot(InputFilename);
134
135 switch (FileType) {
136 case TargetMachine::AssemblyFile:
137 if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
138 OutputFilename += ".s";
139 else
140 OutputFilename += ".cbe.c";
141 break;
142 case TargetMachine::ObjectFile:
143 OutputFilename += ".o";
144 break;
145 case TargetMachine::DynamicLibrary:
146 OutputFilename += LTDL_SHLIB_EXT;
147 break;
148 }
149
150 if (!Force && std::ifstream(OutputFilename.c_str())) {
151 // If force is not specified, make sure not to overwrite a file!
152 std::cerr << ProgName << ": error opening '" << OutputFilename
153 << "': file exists!\n"
154 << "Use -f command line argument to force output\n";
155 return 0;
156 }
157
158 // Make sure that the Out file gets unlinked from the disk if we get a
159 // SIGINT
160 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
161
162 std::ostream *Out = new std::ofstream(OutputFilename.c_str());
163 if (!Out->good()) {
164 std::cerr << ProgName << ": error opening " << OutputFilename << "!\n";
165 delete Out;
166 return 0;
167 }
168
169 return Out;
170}
Vikram S. Adve9d409352001-09-18 13:10:45 +0000171
Chris Lattner67e08422003-06-20 15:49:04 +0000172// main - Entry point for the llc compiler.
173//
174int main(int argc, char **argv) {
Chris Lattner76d46322006-12-06 01:18:01 +0000175 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Dan Gohman2c6a8212007-10-08 15:45:12 +0000176 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
Chris Lattner6dd290a2007-05-06 04:55:19 +0000177 sys::PrintStackTraceOnErrorSignal();
Chris Lattner69e896b2004-02-19 20:32:39 +0000178
Chris Lattner6dd290a2007-05-06 04:55:19 +0000179 // Load the module to be compiled...
180 std::string ErrorMessage;
181 std::auto_ptr<Module> M;
182
Chris Lattnerf5599ef2007-05-06 09:32:02 +0000183 std::auto_ptr<MemoryBuffer> Buffer(
Chris Lattner9e9a34c2007-05-06 23:45:49 +0000184 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
Chris Lattnerf5599ef2007-05-06 09:32:02 +0000185 if (Buffer.get())
186 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
Chris Lattner6dd290a2007-05-06 04:55:19 +0000187 if (M.get() == 0) {
Gabor Greife16561c2007-07-05 17:07:56 +0000188 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
Chris Lattner6dd290a2007-05-06 04:55:19 +0000189 std::cerr << "Reason: " << ErrorMessage << "\n";
190 return 1;
191 }
192 Module &mod = *M.get();
193
194 // If we are supposed to override the target triple, do so now.
195 if (!TargetTriple.empty())
196 mod.setTargetTriple(TargetTriple);
197
198 // Allocate target machine. First, check whether the user has
199 // explicitly specified an architecture to compile for.
200 if (MArch == 0) {
201 std::string Err;
202 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
203 if (MArch == 0) {
204 std::cerr << argv[0] << ": error auto-selecting target for module '"
205 << Err << "'. Please use the -march option to explicitly "
206 << "pick a target.\n";
Chris Lattnerb1492402003-08-24 14:02:14 +0000207 return 1;
Chris Lattner6142ca82004-07-11 04:03:24 +0000208 }
Chris Lattner5667f0e2002-10-29 21:12:46 +0000209 }
Chris Lattner6dd290a2007-05-06 04:55:19 +0000210
211 // Package up features to be passed to target/subtarget
212 std::string FeaturesStr;
213 if (MCPU.size() || MAttrs.size()) {
214 SubtargetFeatures Features;
215 Features.setCPU(MCPU);
216 for (unsigned i = 0; i != MAttrs.size(); ++i)
217 Features.AddFeature(MAttrs[i]);
218 FeaturesStr = Features.getString();
219 }
220
221 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
222 assert(target.get() && "Could not allocate target machine!");
223 TargetMachine &Target = *target.get();
224
225 // Figure out where we are going to send the output...
226 std::ostream *Out = GetOutputStream(argv[0]);
227 if (Out == 0) return 1;
228
229 // If this target requires addPassesToEmitWholeFile, do it now. This is
230 // used by strange things like the C backend.
231 if (Target.WantsWholeFile()) {
232 PassManager PM;
233 PM.add(new TargetData(*Target.getTargetData()));
234 if (!NoVerify)
235 PM.add(createVerifierPass());
236
237 // Ask the target to add backend passes as necessary.
238 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
239 std::cerr << argv[0] << ": target does not support generation of this"
240 << " file type!\n";
241 if (Out != &std::cout) delete Out;
242 // And the Out file is empty and useless, so remove it now.
243 sys::Path(OutputFilename).eraseFromDisk();
244 return 1;
245 }
246 PM.run(mod);
247 } else {
248 // Build up all of the passes that we want to do to the module.
249 FunctionPassManager Passes(new ExistingModuleProvider(M.get()));
250 Passes.add(new TargetData(*Target.getTargetData()));
251
252#ifndef NDEBUG
253 if (!NoVerify)
254 Passes.add(createVerifierPass());
255#endif
256
257 // Ask the target to add backend passes as necessary.
258 MachineCodeEmitter *MCE = 0;
259
260 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
261 default:
262 assert(0 && "Invalid file model!");
263 return 1;
264 case FileModel::Error:
265 std::cerr << argv[0] << ": target does not support generation of this"
266 << " file type!\n";
267 if (Out != &std::cout) delete Out;
268 // And the Out file is empty and useless, so remove it now.
269 sys::Path(OutputFilename).eraseFromDisk();
270 return 1;
271 case FileModel::AsmFile:
272 break;
273 case FileModel::MachOFile:
274 MCE = AddMachOWriter(Passes, *Out, Target);
275 break;
276 case FileModel::ElfFile:
277 MCE = AddELFWriter(Passes, *Out, Target);
278 break;
279 }
280
281 if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) {
282 std::cerr << argv[0] << ": target does not support generation of this"
283 << " file type!\n";
284 if (Out != &std::cout) delete Out;
285 // And the Out file is empty and useless, so remove it now.
286 sys::Path(OutputFilename).eraseFromDisk();
287 return 1;
288 }
289
290 Passes.doInitialization();
291
292 // Run our queue of passes all at once now, efficiently.
293 // TODO: this could lazily stream functions out of the module.
294 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
295 if (!I->isDeclaration())
296 Passes.run(*I);
297
298 Passes.doFinalization();
299 }
300
301 // Delete the ostream if it's not a stdout stream
302 if (Out != &std::cout) delete Out;
303
304 return 0;
Vikram S. Adve2f084b22001-10-14 23:29:28 +0000305}