llc.cpp revision 224133
1262706Serwin//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2135446Strhodes//
3135446Strhodes//                     The LLVM Compiler Infrastructure
4193149Sdougb//
5135446Strhodes// This file is distributed under the University of Illinois Open Source
6135446Strhodes// License. See LICENSE.TXT for details.
7135446Strhodes//
8135446Strhodes//===----------------------------------------------------------------------===//
9135446Strhodes//
10135446Strhodes// This is the llc code generator driver. It provides a convenient
11135446Strhodes// command-line interface for generating native assembly-language code
12135446Strhodes// or C code, given LLVM bitcode.
13135446Strhodes//
14135446Strhodes//===----------------------------------------------------------------------===//
15135446Strhodes
16234010Sdougb#include "llvm/LLVMContext.h"
17135446Strhodes#include "llvm/Module.h"
18135446Strhodes#include "llvm/PassManager.h"
19135446Strhodes#include "llvm/Pass.h"
20135446Strhodes#include "llvm/ADT/Triple.h"
21135446Strhodes#include "llvm/Support/IRReader.h"
22135446Strhodes#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
23135446Strhodes#include "llvm/CodeGen/LinkAllCodegenComponents.h"
24135446Strhodes#include "llvm/Config/config.h"
25135446Strhodes#include "llvm/MC/SubtargetFeature.h"
26135446Strhodes#include "llvm/Support/CommandLine.h"
27135446Strhodes#include "llvm/Support/Debug.h"
28135446Strhodes#include "llvm/Support/FormattedStream.h"
29224092Sdougb#include "llvm/Support/ManagedStatic.h"
30224092Sdougb#include "llvm/Support/PluginLoader.h"
31153816Sdougb#include "llvm/Support/PrettyStackTrace.h"
32262706Serwin#include "llvm/Support/ToolOutputFile.h"
33262706Serwin#include "llvm/Support/Host.h"
34262706Serwin#include "llvm/Support/Signals.h"
35224092Sdougb#include "llvm/Target/TargetData.h"
36224092Sdougb#include "llvm/Target/TargetMachine.h"
37193149Sdougb#include "llvm/Target/TargetRegistry.h"
38254402Serwin#include "llvm/Target/TargetSelect.h"
39262706Serwin#include <memory>
40262706Serwinusing namespace llvm;
41262706Serwin
42193149Sdougb// General options for llc.  Other pass-specific options are specified
43135446Strhodes// within the corresponding llc passes, and target-specific options
44135446Strhodes// and back-end code generation options are specified with the target machine.
45135446Strhodes//
46135446Strhodesstatic cl::opt<std::string>
47135446StrhodesInputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48135446Strhodes
49135446Strhodesstatic cl::opt<std::string>
50135446StrhodesOutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51135446Strhodes
52135446Strhodes// Determine optimization level.
53135446Strhodesstatic cl::opt<char>
54135446StrhodesOptLevel("O",
55135446Strhodes         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
56135446Strhodes                  "(default = '-O2')"),
57135446Strhodes         cl::Prefix,
58135446Strhodes         cl::ZeroOrMore,
59135446Strhodes         cl::init(' '));
60
61static cl::opt<std::string>
62TargetTriple("mtriple", cl::desc("Override target triple for module"));
63
64static cl::opt<std::string>
65MArch("march", cl::desc("Architecture to generate code for (see --version)"));
66
67static cl::opt<std::string>
68MCPU("mcpu",
69  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70  cl::value_desc("cpu-name"),
71  cl::init(""));
72
73static cl::list<std::string>
74MAttrs("mattr",
75  cl::CommaSeparated,
76  cl::desc("Target specific attributes (-mattr=help for details)"),
77  cl::value_desc("a1,+a2,-a3,..."));
78
79static cl::opt<bool>
80RelaxAll("mc-relax-all",
81  cl::desc("When used with filetype=obj, "
82           "relax all fixups in the emitted object file"));
83
84cl::opt<TargetMachine::CodeGenFileType>
85FileType("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
96cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
97                       cl::desc("Do not verify input module"));
98
99cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
100                            cl::desc("Do not use .loc entries"));
101
102cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
103                         cl::desc("Do not use .cfi_* directives"));
104
105static cl::opt<bool>
106DisableRedZone("disable-red-zone",
107  cl::desc("Do not emit code that uses the red zone."),
108  cl::init(false));
109
110// GetFileNameRoot - Helper function to get the basename of a filename.
111static inline std::string
112GetFileNameRoot(const std::string &InputFilename) {
113  std::string IFN = InputFilename;
114  std::string outputFilename;
115  int Len = IFN.length();
116  if ((Len > 2) &&
117      IFN[Len-3] == '.' &&
118      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
119       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
120    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
121  } else {
122    outputFilename = IFN;
123  }
124  return outputFilename;
125}
126
127static tool_output_file *GetOutputStream(const char *TargetName,
128                                         Triple::OSType OS,
129                                         const char *ProgName) {
130  // If we don't yet have an output filename, make one.
131  if (OutputFilename.empty()) {
132    if (InputFilename == "-")
133      OutputFilename = "-";
134    else {
135      OutputFilename = GetFileNameRoot(InputFilename);
136
137      switch (FileType) {
138      default: assert(0 && "Unknown file type");
139      case TargetMachine::CGFT_AssemblyFile:
140        if (TargetName[0] == 'c') {
141          if (TargetName[1] == 0)
142            OutputFilename += ".cbe.c";
143          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
144            OutputFilename += ".cpp";
145          else
146            OutputFilename += ".s";
147        } else
148          OutputFilename += ".s";
149        break;
150      case TargetMachine::CGFT_ObjectFile:
151        if (OS == Triple::Win32)
152          OutputFilename += ".obj";
153        else
154          OutputFilename += ".o";
155        break;
156      case TargetMachine::CGFT_Null:
157        OutputFilename += ".null";
158        break;
159      }
160    }
161  }
162
163  // Decide if we need "binary" output.
164  bool Binary = false;
165  switch (FileType) {
166  default: assert(0 && "Unknown file type");
167  case TargetMachine::CGFT_AssemblyFile:
168    break;
169  case TargetMachine::CGFT_ObjectFile:
170  case TargetMachine::CGFT_Null:
171    Binary = true;
172    break;
173  }
174
175  // Open the file.
176  std::string error;
177  unsigned OpenFlags = 0;
178  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
179  tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
180                                                 OpenFlags);
181  if (!error.empty()) {
182    errs() << error << '\n';
183    delete FDOut;
184    return 0;
185  }
186
187  return FDOut;
188}
189
190// main - Entry point for the llc compiler.
191//
192int main(int argc, char **argv) {
193  sys::PrintStackTraceOnErrorSignal();
194  PrettyStackTraceProgram X(argc, argv);
195
196  // Enable debug stream buffering.
197  EnableDebugBuffering = true;
198
199  LLVMContext &Context = getGlobalContext();
200  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
201
202  // Initialize targets first, so that --version shows registered targets.
203  InitializeAllTargets();
204  InitializeAllMCAsmInfos();
205  InitializeAllMCInstrInfos();
206  InitializeAllMCSubtargetInfos();
207  InitializeAllAsmPrinters();
208  InitializeAllAsmParsers();
209
210  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
211
212  // Load the module to be compiled...
213  SMDiagnostic Err;
214  std::auto_ptr<Module> M;
215
216  M.reset(ParseIRFile(InputFilename, Err, Context));
217  if (M.get() == 0) {
218    Err.Print(argv[0], errs());
219    return 1;
220  }
221  Module &mod = *M.get();
222
223  // If we are supposed to override the target triple, do so now.
224  if (!TargetTriple.empty())
225    mod.setTargetTriple(Triple::normalize(TargetTriple));
226
227  Triple TheTriple(mod.getTargetTriple());
228  if (TheTriple.getTriple().empty())
229    TheTriple.setTriple(sys::getHostTriple());
230
231  // Allocate target machine.  First, check whether the user has explicitly
232  // specified an architecture to compile for. If so we have to look it up by
233  // name, because it might be a backend that has no mapping to a target triple.
234  const Target *TheTarget = 0;
235  if (!MArch.empty()) {
236    for (TargetRegistry::iterator it = TargetRegistry::begin(),
237           ie = TargetRegistry::end(); it != ie; ++it) {
238      if (MArch == it->getName()) {
239        TheTarget = &*it;
240        break;
241      }
242    }
243
244    if (!TheTarget) {
245      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
246      return 1;
247    }
248
249    // Adjust the triple to match (if known), otherwise stick with the
250    // module/host triple.
251    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
252    if (Type != Triple::UnknownArch)
253      TheTriple.setArch(Type);
254  } else {
255    std::string Err;
256    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
257    if (TheTarget == 0) {
258      errs() << argv[0] << ": error auto-selecting target for module '"
259             << Err << "'.  Please use the -march option to explicitly "
260             << "pick a target.\n";
261      return 1;
262    }
263  }
264
265  // Package up features to be passed to target/subtarget
266  std::string FeaturesStr;
267  if (MAttrs.size()) {
268    SubtargetFeatures Features;
269    for (unsigned i = 0; i != MAttrs.size(); ++i)
270      Features.AddFeature(MAttrs[i]);
271    FeaturesStr = Features.getString();
272  }
273
274  std::auto_ptr<TargetMachine>
275    target(TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU,
276                                          FeaturesStr));
277  assert(target.get() && "Could not allocate target machine!");
278  TargetMachine &Target = *target.get();
279
280  if (DisableDotLoc)
281    Target.setMCUseLoc(false);
282
283  if (DisableCFI)
284    Target.setMCUseCFI(false);
285
286  // Disable .loc support for older OS X versions.
287  if (TheTriple.isMacOSX() &&
288      TheTriple.isMacOSXVersionLT(10, 6))
289    Target.setMCUseLoc(false);
290
291  // Figure out where we are going to send the output...
292  OwningPtr<tool_output_file> Out
293    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
294  if (!Out) return 1;
295
296  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
297  switch (OptLevel) {
298  default:
299    errs() << argv[0] << ": invalid optimization level.\n";
300    return 1;
301  case ' ': break;
302  case '0': OLvl = CodeGenOpt::None; break;
303  case '1': OLvl = CodeGenOpt::Less; break;
304  case '2': OLvl = CodeGenOpt::Default; break;
305  case '3': OLvl = CodeGenOpt::Aggressive; break;
306  }
307
308  // Build up all of the passes that we want to do to the module.
309  PassManager PM;
310
311  // Add the target data from the target machine, if it exists, or the module.
312  if (const TargetData *TD = Target.getTargetData())
313    PM.add(new TargetData(*TD));
314  else
315    PM.add(new TargetData(&mod));
316
317  // Override default to generate verbose assembly.
318  Target.setAsmVerbosityDefault(true);
319
320  if (RelaxAll) {
321    if (FileType != TargetMachine::CGFT_ObjectFile)
322      errs() << argv[0]
323             << ": warning: ignoring -mc-relax-all because filetype != obj";
324    else
325      Target.setMCRelaxAll(true);
326  }
327
328  {
329    formatted_raw_ostream FOS(Out->os());
330
331    // Ask the target to add backend passes as necessary.
332    if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
333      errs() << argv[0] << ": target does not support generation of this"
334             << " file type!\n";
335      return 1;
336    }
337
338    // Before executing passes, print the final values of the LLVM options.
339    cl::PrintOptionValues();
340
341    PM.run(mod);
342  }
343
344  // Declare success.
345  Out->keep();
346
347  return 0;
348}
349