Make a couple of command lines static and remove an unnecessary
[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
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Pass.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/PluginLoader.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Target/TargetLibraryInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include <memory>
45 using namespace llvm;
46
47 // General options for llc.  Other pass-specific options are specified
48 // within the corresponding llc passes, and target-specific options
49 // and back-end code generation options are specified with the target machine.
50 //
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
53
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
56
57 static cl::opt<unsigned>
58 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
59                  cl::value_desc("N"),
60                  cl::desc("Repeat compilation N times for timing"));
61
62 static cl::opt<bool>
63 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
64                       cl::desc("Disable integrated assembler"));
65
66 // Determine optimization level.
67 static cl::opt<char>
68 OptLevel("O",
69          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
70                   "(default = '-O2')"),
71          cl::Prefix,
72          cl::ZeroOrMore,
73          cl::init(' '));
74
75 static cl::opt<std::string>
76 TargetTriple("mtriple", cl::desc("Override target triple for module"));
77
78 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
79                               cl::desc("Do not verify input module"));
80
81 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
82                                              cl::desc("Disable simplify-libcalls"));
83
84 static int compileModule(char**, LLVMContext&);
85
86 // GetFileNameRoot - Helper function to get the basename of a filename.
87 static inline std::string
88 GetFileNameRoot(const std::string &InputFilename) {
89   std::string IFN = InputFilename;
90   std::string outputFilename;
91   int Len = IFN.length();
92   if ((Len > 2) &&
93       IFN[Len-3] == '.' &&
94       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
95        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
96     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
97   } else {
98     outputFilename = IFN;
99   }
100   return outputFilename;
101 }
102
103 static tool_output_file *GetOutputStream(const char *TargetName,
104                                          Triple::OSType OS,
105                                          const char *ProgName) {
106   // If we don't yet have an output filename, make one.
107   if (OutputFilename.empty()) {
108     if (InputFilename == "-")
109       OutputFilename = "-";
110     else {
111       OutputFilename = GetFileNameRoot(InputFilename);
112
113       switch (FileType) {
114       case TargetMachine::CGFT_AssemblyFile:
115         if (TargetName[0] == 'c') {
116           if (TargetName[1] == 0)
117             OutputFilename += ".cbe.c";
118           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
119             OutputFilename += ".cpp";
120           else
121             OutputFilename += ".s";
122         } else
123           OutputFilename += ".s";
124         break;
125       case TargetMachine::CGFT_ObjectFile:
126         if (OS == Triple::Win32)
127           OutputFilename += ".obj";
128         else
129           OutputFilename += ".o";
130         break;
131       case TargetMachine::CGFT_Null:
132         OutputFilename += ".null";
133         break;
134       }
135     }
136   }
137
138   // Decide if we need "binary" output.
139   bool Binary = false;
140   switch (FileType) {
141   case TargetMachine::CGFT_AssemblyFile:
142     break;
143   case TargetMachine::CGFT_ObjectFile:
144   case TargetMachine::CGFT_Null:
145     Binary = true;
146     break;
147   }
148
149   // Open the file.
150   std::string error;
151   sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
152   if (!Binary)
153     OpenFlags |= sys::fs::F_Text;
154   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
155                                                  OpenFlags);
156   if (!error.empty()) {
157     errs() << error << '\n';
158     delete FDOut;
159     return nullptr;
160   }
161
162   return FDOut;
163 }
164
165 // main - Entry point for the llc compiler.
166 //
167 int main(int argc, char **argv) {
168   sys::PrintStackTraceOnErrorSignal();
169   PrettyStackTraceProgram X(argc, argv);
170
171   // Enable debug stream buffering.
172   EnableDebugBuffering = true;
173
174   LLVMContext &Context = getGlobalContext();
175   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
176
177   // Initialize targets first, so that --version shows registered targets.
178   InitializeAllTargets();
179   InitializeAllTargetMCs();
180   InitializeAllAsmPrinters();
181   InitializeAllAsmParsers();
182
183   // Initialize codegen and IR passes used by llc so that the -print-after,
184   // -print-before, and -stop-after options work.
185   PassRegistry *Registry = PassRegistry::getPassRegistry();
186   initializeCore(*Registry);
187   initializeCodeGen(*Registry);
188   initializeLoopStrengthReducePass(*Registry);
189   initializeLowerIntrinsicsPass(*Registry);
190   initializeUnreachableBlockElimPass(*Registry);
191
192   // Register the target printer for --version.
193   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
194
195   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
196
197   // Compile the module TimeCompilations times to give better compile time
198   // metrics.
199   for (unsigned I = TimeCompilations; I; --I)
200     if (int RetVal = compileModule(argv, Context))
201       return RetVal;
202   return 0;
203 }
204
205 static int compileModule(char **argv, LLVMContext &Context) {
206   // Load the module to be compiled...
207   SMDiagnostic Err;
208   std::unique_ptr<Module> M;
209   Module *mod = nullptr;
210   Triple TheTriple;
211
212   bool SkipModule = MCPU == "help" ||
213                     (!MAttrs.empty() && MAttrs.front() == "help");
214
215   // If user asked for the 'native' CPU, autodetect here. If autodection fails,
216   // this will set the CPU to an empty string which tells the target to
217   // pick a basic default.
218   if (MCPU == "native")
219     MCPU = sys::getHostCPUName();
220
221   // If user just wants to list available options, skip module loading
222   if (!SkipModule) {
223     M.reset(ParseIRFile(InputFilename, Err, Context));
224     mod = M.get();
225     if (mod == nullptr) {
226       Err.print(argv[0], errs());
227       return 1;
228     }
229
230     // If we are supposed to override the target triple, do so now.
231     if (!TargetTriple.empty())
232       mod->setTargetTriple(Triple::normalize(TargetTriple));
233     TheTriple = Triple(mod->getTargetTriple());
234   } else {
235     TheTriple = Triple(Triple::normalize(TargetTriple));
236   }
237
238   if (TheTriple.getTriple().empty())
239     TheTriple.setTriple(sys::getDefaultTargetTriple());
240
241   // Get the target specific parser.
242   std::string Error;
243   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
244                                                          Error);
245   if (!TheTarget) {
246     errs() << argv[0] << ": " << Error;
247     return 1;
248   }
249
250   // Package up features to be passed to target/subtarget
251   std::string FeaturesStr;
252   if (MAttrs.size()) {
253     SubtargetFeatures Features;
254     for (unsigned i = 0; i != MAttrs.size(); ++i)
255       Features.AddFeature(MAttrs[i]);
256     FeaturesStr = Features.getString();
257   }
258
259   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
260   switch (OptLevel) {
261   default:
262     errs() << argv[0] << ": invalid optimization level.\n";
263     return 1;
264   case ' ': break;
265   case '0': OLvl = CodeGenOpt::None; break;
266   case '1': OLvl = CodeGenOpt::Less; break;
267   case '2': OLvl = CodeGenOpt::Default; break;
268   case '3': OLvl = CodeGenOpt::Aggressive; break;
269   }
270
271   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
272   Options.DisableIntegratedAS = NoIntegratedAssembler;
273
274   // Override default to generate verbose assembly unless we've seen the flag.
275   if (AsmVerbose.getNumOccurrences() == 0)
276     Options.MCOptions.AsmVerbose = true;
277
278   std::unique_ptr<TargetMachine> target(
279       TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
280                                      Options, RelocModel, CMModel, OLvl));
281   assert(target.get() && "Could not allocate target machine!");
282
283   // If we don't have a module then just exit now. We do this down
284   // here since the CPU/Feature help is underneath the target machine
285   // creation.
286   if (SkipModule)
287     return 0;
288
289   assert(mod && "Should have exited if we didn't have a module!");
290   TargetMachine &Target = *target.get();
291
292   if (GenerateSoftFloatCalls)
293     FloatABIForCalls = FloatABI::Soft;
294
295   // Figure out where we are going to send the output.
296   std::unique_ptr<tool_output_file> Out(
297       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
298   if (!Out) return 1;
299
300   // Build up all of the passes that we want to do to the module.
301   PassManager PM;
302
303   // Add an appropriate TargetLibraryInfo pass for the module's triple.
304   TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
305   if (DisableSimplifyLibCalls)
306     TLI->disableAllFunctions();
307   PM.add(TLI);
308
309   // Add the target data from the target machine, if it exists, or the module.
310   if (const DataLayout *DL = Target.getDataLayout())
311     mod->setDataLayout(DL);
312   PM.add(new DataLayoutPass(mod));
313
314   if (RelaxAll.getNumOccurrences() > 0 &&
315       FileType != TargetMachine::CGFT_ObjectFile)
316     errs() << argv[0]
317              << ": warning: ignoring -mc-relax-all because filetype != obj";
318
319   {
320     formatted_raw_ostream FOS(Out->os());
321
322     AnalysisID StartAfterID = nullptr;
323     AnalysisID StopAfterID = nullptr;
324     const PassRegistry *PR = PassRegistry::getPassRegistry();
325     if (!StartAfter.empty()) {
326       const PassInfo *PI = PR->getPassInfo(StartAfter);
327       if (!PI) {
328         errs() << argv[0] << ": start-after pass is not registered.\n";
329         return 1;
330       }
331       StartAfterID = PI->getTypeInfo();
332     }
333     if (!StopAfter.empty()) {
334       const PassInfo *PI = PR->getPassInfo(StopAfter);
335       if (!PI) {
336         errs() << argv[0] << ": stop-after pass is not registered.\n";
337         return 1;
338       }
339       StopAfterID = PI->getTypeInfo();
340     }
341
342     // Ask the target to add backend passes as necessary.
343     if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
344                                    StartAfterID, StopAfterID)) {
345       errs() << argv[0] << ": target does not support generation of this"
346              << " file type!\n";
347       return 1;
348     }
349
350     // Before executing passes, print the final values of the LLVM options.
351     cl::PrintOptionValues();
352
353     PM.run(*mod);
354   }
355
356   // Declare success.
357   Out->keep();
358
359   return 0;
360 }