raw_ostream: Forward declare OpenFlags and include FileSystem.h only where necessary.
[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 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
79                        cl::desc("Do not verify input module"));
80
81 cl::opt<bool>
82 DisableSimplifyLibCalls("disable-simplify-libcalls",
83                         cl::desc("Disable simplify-libcalls"),
84                         cl::init(false));
85
86 static int compileModule(char**, LLVMContext&);
87
88 // GetFileNameRoot - Helper function to get the basename of a filename.
89 static inline std::string
90 GetFileNameRoot(const std::string &InputFilename) {
91   std::string IFN = InputFilename;
92   std::string outputFilename;
93   int Len = IFN.length();
94   if ((Len > 2) &&
95       IFN[Len-3] == '.' &&
96       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
97        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
98     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
99   } else {
100     outputFilename = IFN;
101   }
102   return outputFilename;
103 }
104
105 static tool_output_file *GetOutputStream(const char *TargetName,
106                                          Triple::OSType OS,
107                                          const char *ProgName) {
108   // If we don't yet have an output filename, make one.
109   if (OutputFilename.empty()) {
110     if (InputFilename == "-")
111       OutputFilename = "-";
112     else {
113       OutputFilename = GetFileNameRoot(InputFilename);
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::string error;
153   sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
154   if (!Binary)
155     OpenFlags |= sys::fs::F_Text;
156   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
157                                                  OpenFlags);
158   if (!error.empty()) {
159     errs() << error << '\n';
160     delete FDOut;
161     return nullptr;
162   }
163
164   return FDOut;
165 }
166
167 // main - Entry point for the llc compiler.
168 //
169 int main(int argc, char **argv) {
170   sys::PrintStackTraceOnErrorSignal();
171   PrettyStackTraceProgram X(argc, argv);
172
173   // Enable debug stream buffering.
174   EnableDebugBuffering = true;
175
176   LLVMContext &Context = getGlobalContext();
177   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
178
179   // Initialize targets first, so that --version shows registered targets.
180   InitializeAllTargets();
181   InitializeAllTargetMCs();
182   InitializeAllAsmPrinters();
183   InitializeAllAsmParsers();
184
185   // Initialize codegen and IR passes used by llc so that the -print-after,
186   // -print-before, and -stop-after options work.
187   PassRegistry *Registry = PassRegistry::getPassRegistry();
188   initializeCore(*Registry);
189   initializeCodeGen(*Registry);
190   initializeLoopStrengthReducePass(*Registry);
191   initializeLowerIntrinsicsPass(*Registry);
192   initializeUnreachableBlockElimPass(*Registry);
193
194   // Register the target printer for --version.
195   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
196
197   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
198
199   // Compile the module TimeCompilations times to give better compile time
200   // metrics.
201   for (unsigned I = TimeCompilations; I; --I)
202     if (int RetVal = compileModule(argv, Context))
203       return RetVal;
204   return 0;
205 }
206
207 static int compileModule(char **argv, LLVMContext &Context) {
208   // Load the module to be compiled...
209   SMDiagnostic Err;
210   std::unique_ptr<Module> M;
211   Module *mod = nullptr;
212   Triple TheTriple;
213
214   bool SkipModule = MCPU == "help" ||
215                     (!MAttrs.empty() && MAttrs.front() == "help");
216
217   // If user asked for the 'native' CPU, autodetect here. If autodection fails,
218   // this will set the CPU to an empty string which tells the target to
219   // pick a basic default.
220   if (MCPU == "native")
221     MCPU = sys::getHostCPUName();
222
223   // If user just wants to list available options, skip module loading
224   if (!SkipModule) {
225     M.reset(ParseIRFile(InputFilename, Err, Context));
226     mod = M.get();
227     if (mod == nullptr) {
228       Err.print(argv[0], errs());
229       return 1;
230     }
231
232     // If we are supposed to override the target triple, do so now.
233     if (!TargetTriple.empty())
234       mod->setTargetTriple(Triple::normalize(TargetTriple));
235     TheTriple = Triple(mod->getTargetTriple());
236   } else {
237     TheTriple = Triple(Triple::normalize(TargetTriple));
238   }
239
240   if (TheTriple.getTriple().empty())
241     TheTriple.setTriple(sys::getDefaultTargetTriple());
242
243   // Get the target specific parser.
244   std::string Error;
245   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
246                                                          Error);
247   if (!TheTarget) {
248     errs() << argv[0] << ": " << Error;
249     return 1;
250   }
251
252   // Package up features to be passed to target/subtarget
253   std::string FeaturesStr;
254   if (MAttrs.size()) {
255     SubtargetFeatures Features;
256     for (unsigned i = 0; i != MAttrs.size(); ++i)
257       Features.AddFeature(MAttrs[i]);
258     FeaturesStr = Features.getString();
259   }
260
261   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
262   switch (OptLevel) {
263   default:
264     errs() << argv[0] << ": invalid optimization level.\n";
265     return 1;
266   case ' ': break;
267   case '0': OLvl = CodeGenOpt::None; break;
268   case '1': OLvl = CodeGenOpt::Less; break;
269   case '2': OLvl = CodeGenOpt::Default; break;
270   case '3': OLvl = CodeGenOpt::Aggressive; break;
271   }
272
273   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
274   Options.DisableIntegratedAS = NoIntegratedAssembler;
275
276   std::unique_ptr<TargetMachine> target(
277       TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
278                                      Options, RelocModel, CMModel, OLvl));
279   assert(target.get() && "Could not allocate target machine!");
280   assert(mod && "Should have exited after outputting help!");
281   TargetMachine &Target = *target.get();
282
283   if (DisableCFI)
284     Target.setMCUseCFI(false);
285
286   if (EnableDwarfDirectory)
287     Target.setMCUseDwarfDirectory(true);
288
289   if (GenerateSoftFloatCalls)
290     FloatABIForCalls = FloatABI::Soft;
291
292   // Figure out where we are going to send the output.
293   std::unique_ptr<tool_output_file> Out(
294       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
295   if (!Out) return 1;
296
297   // Build up all of the passes that we want to do to the module.
298   PassManager PM;
299
300   // Add an appropriate TargetLibraryInfo pass for the module's triple.
301   TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
302   if (DisableSimplifyLibCalls)
303     TLI->disableAllFunctions();
304   PM.add(TLI);
305
306   // Add the target data from the target machine, if it exists, or the module.
307   if (const DataLayout *DL = Target.getDataLayout())
308     mod->setDataLayout(DL);
309   PM.add(new DataLayoutPass(mod));
310
311   // Override default to generate verbose assembly.
312   Target.setAsmVerbosityDefault(true);
313
314   if (RelaxAll) {
315     if (FileType != TargetMachine::CGFT_ObjectFile)
316       errs() << argv[0]
317              << ": warning: ignoring -mc-relax-all because filetype != obj";
318     else
319       Target.setMCRelaxAll(true);
320   }
321
322   {
323     formatted_raw_ostream FOS(Out->os());
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, FOS, FileType, NoVerify,
347                                    StartAfterID, 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(*mod);
357   }
358
359   // Declare success.
360   Out->keep();
361
362   return 0;
363 }