Add all the plumbing needed for MC to expand cfi to the old tables in
[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/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/FormattedStream.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/PluginLoader.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/ToolOutputFile.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/Signals.h"
34 #include "llvm/Target/SubtargetFeature.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<bool>
80 RelaxAll("mc-relax-all",
81   cl::desc("When used with filetype=obj, "
82            "relax all fixups in the emitted object file"));
83
84 cl::opt<TargetMachine::CodeGenFileType>
85 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
86   cl::desc("Choose a file type (not all types are supported by all targets):"),
87   cl::values(
88        clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
89                   "Emit an assembly ('.s') file"),
90        clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
91                   "Emit a native object ('.o') file [experimental]"),
92        clEnumValN(TargetMachine::CGFT_Null, "null",
93                   "Emit nothing, for performance testing"),
94        clEnumValEnd));
95
96 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
97                        cl::desc("Do not verify input module"));
98
99 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
100                             cl::desc("Do not use .loc entries"));
101
102 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
103                          cl::desc("Do not use .cfi_* directives"));
104
105 static cl::opt<bool>
106 DisableRedZone("disable-red-zone",
107   cl::desc("Do not emit code that uses the red zone."),
108   cl::init(false));
109
110 static cl::opt<bool>
111 NoImplicitFloats("no-implicit-float",
112   cl::desc("Don't generate implicit floating point instructions (x86-only)"),
113   cl::init(false));
114
115 // GetFileNameRoot - Helper function to get the basename of a filename.
116 static inline std::string
117 GetFileNameRoot(const std::string &InputFilename) {
118   std::string IFN = InputFilename;
119   std::string outputFilename;
120   int Len = IFN.length();
121   if ((Len > 2) &&
122       IFN[Len-3] == '.' &&
123       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
124        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
125     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
126   } else {
127     outputFilename = IFN;
128   }
129   return outputFilename;
130 }
131
132 static tool_output_file *GetOutputStream(const char *TargetName,
133                                          Triple::OSType OS,
134                                          const char *ProgName) {
135   // If we don't yet have an output filename, make one.
136   if (OutputFilename.empty()) {
137     if (InputFilename == "-")
138       OutputFilename = "-";
139     else {
140       OutputFilename = GetFileNameRoot(InputFilename);
141
142       switch (FileType) {
143       default: assert(0 && "Unknown file type");
144       case TargetMachine::CGFT_AssemblyFile:
145         if (TargetName[0] == 'c') {
146           if (TargetName[1] == 0)
147             OutputFilename += ".cbe.c";
148           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
149             OutputFilename += ".cpp";
150           else
151             OutputFilename += ".s";
152         } else
153           OutputFilename += ".s";
154         break;
155       case TargetMachine::CGFT_ObjectFile:
156         if (OS == Triple::Win32)
157           OutputFilename += ".obj";
158         else
159           OutputFilename += ".o";
160         break;
161       case TargetMachine::CGFT_Null:
162         OutputFilename += ".null";
163         break;
164       }
165     }
166   }
167
168   // Decide if we need "binary" output.
169   bool Binary = false;
170   switch (FileType) {
171   default: assert(0 && "Unknown file type");
172   case TargetMachine::CGFT_AssemblyFile:
173     break;
174   case TargetMachine::CGFT_ObjectFile:
175   case TargetMachine::CGFT_Null:
176     Binary = true;
177     break;
178   }
179
180   // Open the file.
181   std::string error;
182   unsigned OpenFlags = 0;
183   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
184   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
185                                                  OpenFlags);
186   if (!error.empty()) {
187     errs() << error << '\n';
188     delete FDOut;
189     return 0;
190   }
191
192   return FDOut;
193 }
194
195 // main - Entry point for the llc compiler.
196 //
197 int main(int argc, char **argv) {
198   sys::PrintStackTraceOnErrorSignal();
199   PrettyStackTraceProgram X(argc, argv);
200
201   // Enable debug stream buffering.
202   EnableDebugBuffering = true;
203
204   LLVMContext &Context = getGlobalContext();
205   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
206
207   // Initialize targets first, so that --version shows registered targets.
208   InitializeAllTargets();
209   InitializeAllAsmPrinters();
210   InitializeAllAsmParsers();
211
212   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
213
214   // Load the module to be compiled...
215   SMDiagnostic Err;
216   std::auto_ptr<Module> M;
217
218   M.reset(ParseIRFile(InputFilename, Err, Context));
219   if (M.get() == 0) {
220     Err.Print(argv[0], errs());
221     return 1;
222   }
223   Module &mod = *M.get();
224
225   // If we are supposed to override the target triple, do so now.
226   if (!TargetTriple.empty())
227     mod.setTargetTriple(Triple::normalize(TargetTriple));
228
229   Triple TheTriple(mod.getTargetTriple());
230   if (TheTriple.getTriple().empty())
231     TheTriple.setTriple(sys::getHostTriple());
232
233   // Allocate target machine.  First, check whether the user has explicitly
234   // specified an architecture to compile for. If so we have to look it up by
235   // name, because it might be a backend that has no mapping to a target triple.
236   const Target *TheTarget = 0;
237   if (!MArch.empty()) {
238     for (TargetRegistry::iterator it = TargetRegistry::begin(),
239            ie = TargetRegistry::end(); it != ie; ++it) {
240       if (MArch == it->getName()) {
241         TheTarget = &*it;
242         break;
243       }
244     }
245
246     if (!TheTarget) {
247       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
248       return 1;
249     }
250
251     // Adjust the triple to match (if known), otherwise stick with the
252     // module/host triple.
253     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
254     if (Type != Triple::UnknownArch)
255       TheTriple.setArch(Type);
256   } else {
257     std::string Err;
258     TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
259     if (TheTarget == 0) {
260       errs() << argv[0] << ": error auto-selecting target for module '"
261              << Err << "'.  Please use the -march option to explicitly "
262              << "pick a target.\n";
263       return 1;
264     }
265   }
266
267   // Package up features to be passed to target/subtarget
268   std::string FeaturesStr;
269   if (MCPU.size() || MAttrs.size()) {
270     SubtargetFeatures Features;
271     Features.setCPU(MCPU);
272     for (unsigned i = 0; i != MAttrs.size(); ++i)
273       Features.AddFeature(MAttrs[i]);
274     FeaturesStr = Features.getString();
275   }
276
277   std::auto_ptr<TargetMachine>
278     target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
279   assert(target.get() && "Could not allocate target machine!");
280   TargetMachine &Target = *target.get();
281
282   if (DisableDotLoc)
283     Target.setMCUseLoc(false);
284
285   if (DisableCFI)
286     Target.setMCUseCFI(false);
287
288   // Disable .loc support for older OS X versions.
289   if (TheTriple.isMacOSX() &&
290       TheTriple.isMacOSXVersionLT(10, 6))
291     Target.setMCUseLoc(false);
292
293   // Figure out where we are going to send the output...
294   OwningPtr<tool_output_file> Out
295     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
296   if (!Out) return 1;
297
298   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
299   switch (OptLevel) {
300   default:
301     errs() << argv[0] << ": invalid optimization level.\n";
302     return 1;
303   case ' ': break;
304   case '0': OLvl = CodeGenOpt::None; break;
305   case '1': OLvl = CodeGenOpt::Less; break;
306   case '2': OLvl = CodeGenOpt::Default; break;
307   case '3': OLvl = CodeGenOpt::Aggressive; break;
308   }
309
310   // Build up all of the passes that we want to do to the module.
311   PassManager PM;
312
313   // Add the target data from the target machine, if it exists, or the module.
314   if (const TargetData *TD = Target.getTargetData())
315     PM.add(new TargetData(*TD));
316   else
317     PM.add(new TargetData(&mod));
318
319   // Override default to generate verbose assembly.
320   Target.setAsmVerbosityDefault(true);
321
322   if (RelaxAll) {
323     if (FileType != TargetMachine::CGFT_ObjectFile)
324       errs() << argv[0]
325              << ": warning: ignoring -mc-relax-all because filetype != obj";
326     else
327       Target.setMCRelaxAll(true);
328   }
329
330   {
331     formatted_raw_ostream FOS(Out->os());
332
333     // Ask the target to add backend passes as necessary.
334     if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
335       errs() << argv[0] << ": target does not support generation of this"
336              << " file type!\n";
337       return 1;
338     }
339
340     // Before executing passes, print the final values of the LLVM options.
341     cl::PrintOptionValues();
342
343     PM.run(mod);
344   }
345
346   // Declare success.
347   Out->keep();
348
349   return 0;
350 }