- Move CodeModel from a TargetMachine global option to MCCodeGenInfo.
[oota-llvm.git] / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Pass.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Support/IRReader.h"
22 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
23 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/MC/SubtargetFeature.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/PluginLoader.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/ToolOutputFile.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/Signals.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/Target/TargetSelect.h"
39 #include <memory>
40 using namespace llvm;
41
42 // 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.
45 //
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52 // Determine optimization level.
53 static cl::opt<char>
54 OptLevel("O",
55          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
56                   "(default = '-O2')"),
57          cl::Prefix,
58          cl::ZeroOrMore,
59          cl::init(' '));
60
61 static cl::opt<std::string>
62 TargetTriple("mtriple", cl::desc("Override target triple for module"));
63
64 static cl::opt<std::string>
65 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
66
67 static cl::opt<std::string>
68 MCPU("mcpu",
69   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70   cl::value_desc("cpu-name"),
71   cl::init(""));
72
73 static cl::list<std::string>
74 MAttrs("mattr",
75   cl::CommaSeparated,
76   cl::desc("Target specific attributes (-mattr=help for details)"),
77   cl::value_desc("a1,+a2,-a3,..."));
78
79 static cl::opt<Reloc::Model>
80 RelocModel("relocation-model",
81              cl::desc("Choose relocation model"),
82              cl::init(Reloc::Default),
83              cl::values(
84             clEnumValN(Reloc::Default, "default",
85                        "Target default relocation model"),
86             clEnumValN(Reloc::Static, "static",
87                        "Non-relocatable code"),
88             clEnumValN(Reloc::PIC_, "pic",
89                        "Fully relocatable, position independent code"),
90             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
91                        "Relocatable external references, non-relocatable code"),
92             clEnumValEnd));
93
94 static cl::opt<llvm::CodeModel::Model>
95 CMModel("code-model",
96         cl::desc("Choose code model"),
97         cl::init(CodeModel::Default),
98         cl::values(clEnumValN(CodeModel::Default, "default",
99                               "Target default code model"),
100                    clEnumValN(CodeModel::Small, "small",
101                               "Small code model"),
102                    clEnumValN(CodeModel::Kernel, "kernel",
103                               "Kernel code model"),
104                    clEnumValN(CodeModel::Medium, "medium",
105                               "Medium code model"),
106                    clEnumValN(CodeModel::Large, "large",
107                               "Large code model"),
108                    clEnumValEnd));
109
110 static cl::opt<bool>
111 RelaxAll("mc-relax-all",
112   cl::desc("When used with filetype=obj, "
113            "relax all fixups in the emitted object file"));
114
115 cl::opt<TargetMachine::CodeGenFileType>
116 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
117   cl::desc("Choose a file type (not all types are supported by all targets):"),
118   cl::values(
119        clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
120                   "Emit an assembly ('.s') file"),
121        clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
122                   "Emit a native object ('.o') file [experimental]"),
123        clEnumValN(TargetMachine::CGFT_Null, "null",
124                   "Emit nothing, for performance testing"),
125        clEnumValEnd));
126
127 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
128                        cl::desc("Do not verify input module"));
129
130 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
131                             cl::desc("Do not use .loc entries"));
132
133 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
134                          cl::desc("Do not use .cfi_* directives"));
135
136 static cl::opt<bool>
137 DisableRedZone("disable-red-zone",
138   cl::desc("Do not emit code that uses the red zone."),
139   cl::init(false));
140
141 // GetFileNameRoot - Helper function to get the basename of a filename.
142 static inline std::string
143 GetFileNameRoot(const std::string &InputFilename) {
144   std::string IFN = InputFilename;
145   std::string outputFilename;
146   int Len = IFN.length();
147   if ((Len > 2) &&
148       IFN[Len-3] == '.' &&
149       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
150        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
151     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
152   } else {
153     outputFilename = IFN;
154   }
155   return outputFilename;
156 }
157
158 static tool_output_file *GetOutputStream(const char *TargetName,
159                                          Triple::OSType OS,
160                                          const char *ProgName) {
161   // If we don't yet have an output filename, make one.
162   if (OutputFilename.empty()) {
163     if (InputFilename == "-")
164       OutputFilename = "-";
165     else {
166       OutputFilename = GetFileNameRoot(InputFilename);
167
168       switch (FileType) {
169       default: assert(0 && "Unknown file type");
170       case TargetMachine::CGFT_AssemblyFile:
171         if (TargetName[0] == 'c') {
172           if (TargetName[1] == 0)
173             OutputFilename += ".cbe.c";
174           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
175             OutputFilename += ".cpp";
176           else
177             OutputFilename += ".s";
178         } else
179           OutputFilename += ".s";
180         break;
181       case TargetMachine::CGFT_ObjectFile:
182         if (OS == Triple::Win32)
183           OutputFilename += ".obj";
184         else
185           OutputFilename += ".o";
186         break;
187       case TargetMachine::CGFT_Null:
188         OutputFilename += ".null";
189         break;
190       }
191     }
192   }
193
194   // Decide if we need "binary" output.
195   bool Binary = false;
196   switch (FileType) {
197   default: assert(0 && "Unknown file type");
198   case TargetMachine::CGFT_AssemblyFile:
199     break;
200   case TargetMachine::CGFT_ObjectFile:
201   case TargetMachine::CGFT_Null:
202     Binary = true;
203     break;
204   }
205
206   // Open the file.
207   std::string error;
208   unsigned OpenFlags = 0;
209   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
210   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
211                                                  OpenFlags);
212   if (!error.empty()) {
213     errs() << error << '\n';
214     delete FDOut;
215     return 0;
216   }
217
218   return FDOut;
219 }
220
221 // main - Entry point for the llc compiler.
222 //
223 int main(int argc, char **argv) {
224   sys::PrintStackTraceOnErrorSignal();
225   PrettyStackTraceProgram X(argc, argv);
226
227   // Enable debug stream buffering.
228   EnableDebugBuffering = true;
229
230   LLVMContext &Context = getGlobalContext();
231   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
232
233   // Initialize targets first, so that --version shows registered targets.
234   InitializeAllTargets();
235   InitializeAllMCAsmInfos();
236   InitializeAllMCCodeGenInfos();
237   InitializeAllMCSubtargetInfos();
238   InitializeAllAsmPrinters();
239   InitializeAllAsmParsers();
240
241   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
242
243   // Load the module to be compiled...
244   SMDiagnostic Err;
245   std::auto_ptr<Module> M;
246
247   M.reset(ParseIRFile(InputFilename, Err, Context));
248   if (M.get() == 0) {
249     Err.Print(argv[0], errs());
250     return 1;
251   }
252   Module &mod = *M.get();
253
254   // If we are supposed to override the target triple, do so now.
255   if (!TargetTriple.empty())
256     mod.setTargetTriple(Triple::normalize(TargetTriple));
257
258   Triple TheTriple(mod.getTargetTriple());
259   if (TheTriple.getTriple().empty())
260     TheTriple.setTriple(sys::getHostTriple());
261
262   // Allocate target machine.  First, check whether the user has explicitly
263   // specified an architecture to compile for. If so we have to look it up by
264   // name, because it might be a backend that has no mapping to a target triple.
265   const Target *TheTarget = 0;
266   if (!MArch.empty()) {
267     for (TargetRegistry::iterator it = TargetRegistry::begin(),
268            ie = TargetRegistry::end(); it != ie; ++it) {
269       if (MArch == it->getName()) {
270         TheTarget = &*it;
271         break;
272       }
273     }
274
275     if (!TheTarget) {
276       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
277       return 1;
278     }
279
280     // Adjust the triple to match (if known), otherwise stick with the
281     // module/host triple.
282     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
283     if (Type != Triple::UnknownArch)
284       TheTriple.setArch(Type);
285   } else {
286     std::string Err;
287     TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
288     if (TheTarget == 0) {
289       errs() << argv[0] << ": error auto-selecting target for module '"
290              << Err << "'.  Please use the -march option to explicitly "
291              << "pick a target.\n";
292       return 1;
293     }
294   }
295
296   // Package up features to be passed to target/subtarget
297   std::string FeaturesStr;
298   if (MAttrs.size()) {
299     SubtargetFeatures Features;
300     for (unsigned i = 0; i != MAttrs.size(); ++i)
301       Features.AddFeature(MAttrs[i]);
302     FeaturesStr = Features.getString();
303   }
304
305   std::auto_ptr<TargetMachine>
306     target(TheTarget->createTargetMachine(TheTriple.getTriple(),
307                                           MCPU, FeaturesStr,
308                                           RelocModel, CMModel));
309   assert(target.get() && "Could not allocate target machine!");
310   TargetMachine &Target = *target.get();
311
312   if (DisableDotLoc)
313     Target.setMCUseLoc(false);
314
315   if (DisableCFI)
316     Target.setMCUseCFI(false);
317
318   // Disable .loc support for older OS X versions.
319   if (TheTriple.isMacOSX() &&
320       TheTriple.isMacOSXVersionLT(10, 6))
321     Target.setMCUseLoc(false);
322
323   // Figure out where we are going to send the output...
324   OwningPtr<tool_output_file> Out
325     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
326   if (!Out) return 1;
327
328   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
329   switch (OptLevel) {
330   default:
331     errs() << argv[0] << ": invalid optimization level.\n";
332     return 1;
333   case ' ': break;
334   case '0': OLvl = CodeGenOpt::None; break;
335   case '1': OLvl = CodeGenOpt::Less; break;
336   case '2': OLvl = CodeGenOpt::Default; break;
337   case '3': OLvl = CodeGenOpt::Aggressive; break;
338   }
339
340   // Build up all of the passes that we want to do to the module.
341   PassManager PM;
342
343   // Add the target data from the target machine, if it exists, or the module.
344   if (const TargetData *TD = Target.getTargetData())
345     PM.add(new TargetData(*TD));
346   else
347     PM.add(new TargetData(&mod));
348
349   // Override default to generate verbose assembly.
350   Target.setAsmVerbosityDefault(true);
351
352   if (RelaxAll) {
353     if (FileType != TargetMachine::CGFT_ObjectFile)
354       errs() << argv[0]
355              << ": warning: ignoring -mc-relax-all because filetype != obj";
356     else
357       Target.setMCRelaxAll(true);
358   }
359
360   {
361     formatted_raw_ostream FOS(Out->os());
362
363     // Ask the target to add backend passes as necessary.
364     if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
365       errs() << argv[0] << ": target does not support generation of this"
366              << " file type!\n";
367       return 1;
368     }
369
370     // Before executing passes, print the final values of the LLVM options.
371     cl::PrintOptionValues();
372
373     PM.run(mod);
374   }
375
376   // Declare success.
377   Out->keep();
378
379   return 0;
380 }