Verifier: Call verifyModule() from llc and opt
[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 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 = parseIRFile(InputFilename, Err, Context);
224     if (!M) {
225       Err.print(argv[0], errs());
226       return 1;
227     }
228
229     // Verify module immediately to catch problems before doInitialization() is
230     // called on any passes.
231     if (!NoVerify && verifyModule(*M, &errs())) {
232       errs() << argv[0] << ": " << InputFilename
233              << ": error: does not verify\n";
234       return 1;
235     }
236
237     // If we are supposed to override the target triple, do so now.
238     if (!TargetTriple.empty())
239       M->setTargetTriple(Triple::normalize(TargetTriple));
240     TheTriple = Triple(M->getTargetTriple());
241   } else {
242     TheTriple = Triple(Triple::normalize(TargetTriple));
243   }
244
245   if (TheTriple.getTriple().empty())
246     TheTriple.setTriple(sys::getDefaultTargetTriple());
247
248   // Get the target specific parser.
249   std::string Error;
250   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
251                                                          Error);
252   if (!TheTarget) {
253     errs() << argv[0] << ": " << Error;
254     return 1;
255   }
256
257   // Package up features to be passed to target/subtarget
258   std::string FeaturesStr;
259   if (MAttrs.size()) {
260     SubtargetFeatures Features;
261     for (unsigned i = 0; i != MAttrs.size(); ++i)
262       Features.AddFeature(MAttrs[i]);
263     FeaturesStr = Features.getString();
264   }
265
266   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
267   switch (OptLevel) {
268   default:
269     errs() << argv[0] << ": invalid optimization level.\n";
270     return 1;
271   case ' ': break;
272   case '0': OLvl = CodeGenOpt::None; break;
273   case '1': OLvl = CodeGenOpt::Less; break;
274   case '2': OLvl = CodeGenOpt::Default; break;
275   case '3': OLvl = CodeGenOpt::Aggressive; break;
276   }
277
278   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
279   Options.DisableIntegratedAS = NoIntegratedAssembler;
280   Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
281   Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
282   Options.MCOptions.AsmVerbose = AsmVerbose;
283
284   std::unique_ptr<TargetMachine> Target(
285       TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
286                                      Options, RelocModel, CMModel, OLvl));
287   assert(Target && "Could not allocate target machine!");
288
289   // If we don't have a module then just exit now. We do this down
290   // here since the CPU/Feature help is underneath the target machine
291   // creation.
292   if (SkipModule)
293     return 0;
294
295   assert(M && "Should have exited if we didn't have a module!");
296
297   if (GenerateSoftFloatCalls)
298     FloatABIForCalls = FloatABI::Soft;
299
300   // Figure out where we are going to send the output.
301   std::unique_ptr<tool_output_file> Out =
302       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
303   if (!Out) return 1;
304
305   // Build up all of the passes that we want to do to the module.
306   legacy::PassManager PM;
307
308   // Add an appropriate TargetLibraryInfo pass for the module's triple.
309   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
310
311   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
312   if (DisableSimplifyLibCalls)
313     TLII.disableAllFunctions();
314   PM.add(new TargetLibraryInfoWrapperPass(TLII));
315
316   // Add the target data from the target machine, if it exists, or the module.
317   if (const DataLayout *DL = Target->getDataLayout())
318     M->setDataLayout(*DL);
319
320   if (RelaxAll.getNumOccurrences() > 0 &&
321       FileType != TargetMachine::CGFT_ObjectFile)
322     errs() << argv[0]
323              << ": warning: ignoring -mc-relax-all because filetype != obj";
324
325   {
326     formatted_raw_ostream FOS(Out->os());
327
328     AnalysisID StartAfterID = nullptr;
329     AnalysisID StopAfterID = nullptr;
330     const PassRegistry *PR = PassRegistry::getPassRegistry();
331     if (!StartAfter.empty()) {
332       const PassInfo *PI = PR->getPassInfo(StartAfter);
333       if (!PI) {
334         errs() << argv[0] << ": start-after pass is not registered.\n";
335         return 1;
336       }
337       StartAfterID = PI->getTypeInfo();
338     }
339     if (!StopAfter.empty()) {
340       const PassInfo *PI = PR->getPassInfo(StopAfter);
341       if (!PI) {
342         errs() << argv[0] << ": stop-after pass is not registered.\n";
343         return 1;
344       }
345       StopAfterID = PI->getTypeInfo();
346     }
347
348     // Ask the target to add backend passes as necessary.
349     if (Target->addPassesToEmitFile(PM, FOS, FileType, NoVerify,
350                                     StartAfterID, StopAfterID)) {
351       errs() << argv[0] << ": target does not support generation of this"
352              << " file type!\n";
353       return 1;
354     }
355
356     // Before executing passes, print the final values of the LLVM options.
357     cl::PrintOptionValues();
358
359     PM.run(*M);
360   }
361
362   // Declare success.
363   Out->keep();
364
365   return 0;
366 }