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