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