]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llc/llc.cpp
Merge llvm, clang, lld and lldb trunk r291274, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/CodeGen/MIRParser/MIRParser.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
54 #include <memory>
55 using namespace llvm;
56
57 // General options for llc.  Other pass-specific options are specified
58 // within the corresponding llc passes, and target-specific options
59 // and back-end code generation options are specified with the target machine.
60 //
61 static cl::opt<std::string>
62 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
63
64 static cl::opt<std::string>
65 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
66
67 static cl::opt<unsigned>
68 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
69                  cl::value_desc("N"),
70                  cl::desc("Repeat compilation N times for timing"));
71
72 static cl::opt<bool>
73 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
74                       cl::desc("Disable integrated assembler"));
75
76 static cl::opt<bool>
77     PreserveComments("preserve-as-comments", cl::Hidden,
78                      cl::desc("Preserve Comments in outputted assembly"),
79                      cl::init(true));
80
81 // Determine optimization level.
82 static cl::opt<char>
83 OptLevel("O",
84          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
85                   "(default = '-O2')"),
86          cl::Prefix,
87          cl::ZeroOrMore,
88          cl::init(' '));
89
90 static cl::opt<std::string>
91 TargetTriple("mtriple", cl::desc("Override target triple for module"));
92
93 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
94                               cl::desc("Do not verify input module"));
95
96 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
97                                              cl::desc("Disable simplify-libcalls"));
98
99 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
100                                     cl::desc("Show encoding in .s output"));
101
102 static cl::opt<bool> EnableDwarfDirectory(
103     "enable-dwarf-directory", cl::Hidden,
104     cl::desc("Use .file directives with an explicit directory."));
105
106 static cl::opt<bool> AsmVerbose("asm-verbose",
107                                 cl::desc("Add comments to directives."),
108                                 cl::init(true));
109
110 static cl::opt<bool>
111     CompileTwice("compile-twice", cl::Hidden,
112                  cl::desc("Run everything twice, re-using the same pass "
113                           "manager and verify the result is the same."),
114                  cl::init(false));
115
116 static cl::opt<bool> DiscardValueNames(
117     "discard-value-names",
118     cl::desc("Discard names from Value (other than GlobalValue)."),
119     cl::init(false), cl::Hidden);
120
121 static cl::opt<std::string> StopBefore("stop-before",
122     cl::desc("Stop compilation before a specific pass"),
123     cl::value_desc("pass-name"), cl::init(""));
124
125 static cl::opt<std::string> StopAfter("stop-after",
126     cl::desc("Stop compilation after a specific pass"),
127     cl::value_desc("pass-name"), cl::init(""));
128
129 static cl::opt<std::string> StartBefore("start-before",
130     cl::desc("Resume compilation before a specific pass"),
131     cl::value_desc("pass-name"), cl::init(""));
132
133 static cl::opt<std::string> StartAfter("start-after",
134     cl::desc("Resume compilation after a specific pass"),
135     cl::value_desc("pass-name"), cl::init(""));
136
137 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
138
139 namespace {
140 static ManagedStatic<std::vector<std::string>> RunPassNames;
141
142 struct RunPassOption {
143   void operator=(const std::string &Val) const {
144     if (Val.empty())
145       return;
146     SmallVector<StringRef, 8> PassNames;
147     StringRef(Val).split(PassNames, ',', -1, false);
148     for (auto PassName : PassNames)
149       RunPassNames->push_back(PassName);
150   }
151 };
152 }
153
154 static RunPassOption RunPassOpt;
155
156 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
157     "run-pass",
158     cl::desc("Run compiler only for specified passes (comma separated list)"),
159     cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
160
161 static int compileModule(char **, LLVMContext &);
162
163 static std::unique_ptr<tool_output_file>
164 GetOutputStream(const char *TargetName, Triple::OSType OS,
165                 const char *ProgName) {
166   // If we don't yet have an output filename, make one.
167   if (OutputFilename.empty()) {
168     if (InputFilename == "-")
169       OutputFilename = "-";
170     else {
171       // If InputFilename ends in .bc or .ll, remove it.
172       StringRef IFN = InputFilename;
173       if (IFN.endswith(".bc") || IFN.endswith(".ll"))
174         OutputFilename = IFN.drop_back(3);
175       else if (IFN.endswith(".mir"))
176         OutputFilename = IFN.drop_back(4);
177       else
178         OutputFilename = IFN;
179
180       switch (FileType) {
181       case TargetMachine::CGFT_AssemblyFile:
182         if (TargetName[0] == 'c') {
183           if (TargetName[1] == 0)
184             OutputFilename += ".cbe.c";
185           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
186             OutputFilename += ".cpp";
187           else
188             OutputFilename += ".s";
189         } else
190           OutputFilename += ".s";
191         break;
192       case TargetMachine::CGFT_ObjectFile:
193         if (OS == Triple::Win32)
194           OutputFilename += ".obj";
195         else
196           OutputFilename += ".o";
197         break;
198       case TargetMachine::CGFT_Null:
199         OutputFilename += ".null";
200         break;
201       }
202     }
203   }
204
205   // Decide if we need "binary" output.
206   bool Binary = false;
207   switch (FileType) {
208   case TargetMachine::CGFT_AssemblyFile:
209     break;
210   case TargetMachine::CGFT_ObjectFile:
211   case TargetMachine::CGFT_Null:
212     Binary = true;
213     break;
214   }
215
216   // Open the file.
217   std::error_code EC;
218   sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
219   if (!Binary)
220     OpenFlags |= sys::fs::F_Text;
221   auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
222                                                    OpenFlags);
223   if (EC) {
224     errs() << EC.message() << '\n';
225     return nullptr;
226   }
227
228   return FDOut;
229 }
230
231 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
232   bool *HasError = static_cast<bool *>(Context);
233   if (DI.getSeverity() == DS_Error)
234     *HasError = true;
235
236   DiagnosticPrinterRawOStream DP(errs());
237   errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
238   DI.print(DP);
239   errs() << "\n";
240 }
241
242 // main - Entry point for the llc compiler.
243 //
244 int main(int argc, char **argv) {
245   sys::PrintStackTraceOnErrorSignal(argv[0]);
246   PrettyStackTraceProgram X(argc, argv);
247
248   // Enable debug stream buffering.
249   EnableDebugBuffering = true;
250
251   LLVMContext Context;
252   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
253
254   // Initialize targets first, so that --version shows registered targets.
255   InitializeAllTargets();
256   InitializeAllTargetMCs();
257   InitializeAllAsmPrinters();
258   InitializeAllAsmParsers();
259
260   // Initialize codegen and IR passes used by llc so that the -print-after,
261   // -print-before, and -stop-after options work.
262   PassRegistry *Registry = PassRegistry::getPassRegistry();
263   initializeCore(*Registry);
264   initializeCodeGen(*Registry);
265   initializeLoopStrengthReducePass(*Registry);
266   initializeLowerIntrinsicsPass(*Registry);
267   initializeCountingFunctionInserterPass(*Registry);
268   initializeUnreachableBlockElimLegacyPassPass(*Registry);
269   initializeConstantHoistingLegacyPassPass(*Registry);
270
271   // Register the target printer for --version.
272   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
273
274   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
275
276   Context.setDiscardValueNames(DiscardValueNames);
277
278   // Set a diagnostic handler that doesn't exit on the first error
279   bool HasError = false;
280   Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
281
282   // Compile the module TimeCompilations times to give better compile time
283   // metrics.
284   for (unsigned I = TimeCompilations; I; --I)
285     if (int RetVal = compileModule(argv, Context))
286       return RetVal;
287   return 0;
288 }
289
290 static bool addPass(PassManagerBase &PM, const char *argv0,
291                     StringRef PassName, TargetPassConfig &TPC) {
292   if (PassName == "none")
293     return false;
294
295   const PassRegistry *PR = PassRegistry::getPassRegistry();
296   const PassInfo *PI = PR->getPassInfo(PassName);
297   if (!PI) {
298     errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
299     return true;
300   }
301
302   Pass *P;
303   if (PI->getTargetMachineCtor())
304     P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>());
305   else if (PI->getNormalCtor())
306     P = PI->getNormalCtor()();
307   else {
308     errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
309     return true;
310   }
311   std::string Banner = std::string("After ") + std::string(P->getPassName());
312   PM.add(P);
313   TPC.printAndVerify(Banner);
314
315   return false;
316 }
317
318 static AnalysisID getPassID(const char *argv0, const char *OptionName,
319                             StringRef PassName) {
320   if (PassName.empty())
321     return nullptr;
322
323   const PassRegistry &PR = *PassRegistry::getPassRegistry();
324   const PassInfo *PI = PR.getPassInfo(PassName);
325   if (!PI) {
326     errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
327     exit(1);
328   }
329   return PI->getTypeInfo();
330 }
331
332 static int compileModule(char **argv, LLVMContext &Context) {
333   // Load the module to be compiled...
334   SMDiagnostic Err;
335   std::unique_ptr<Module> M;
336   std::unique_ptr<MIRParser> MIR;
337   Triple TheTriple;
338
339   bool SkipModule = MCPU == "help" ||
340                     (!MAttrs.empty() && MAttrs.front() == "help");
341
342   // If user just wants to list available options, skip module loading
343   if (!SkipModule) {
344     if (StringRef(InputFilename).endswith_lower(".mir")) {
345       MIR = createMIRParserFromFile(InputFilename, Err, Context);
346       if (MIR)
347         M = MIR->parseLLVMModule();
348     } else
349       M = parseIRFile(InputFilename, Err, Context);
350     if (!M) {
351       Err.print(argv[0], errs());
352       return 1;
353     }
354
355     // Verify module immediately to catch problems before doInitialization() is
356     // called on any passes.
357     if (!NoVerify && verifyModule(*M, &errs())) {
358       errs() << argv[0] << ": " << InputFilename
359              << ": error: input module is broken!\n";
360       return 1;
361     }
362
363     // If we are supposed to override the target triple, do so now.
364     if (!TargetTriple.empty())
365       M->setTargetTriple(Triple::normalize(TargetTriple));
366     TheTriple = Triple(M->getTargetTriple());
367   } else {
368     TheTriple = Triple(Triple::normalize(TargetTriple));
369   }
370
371   if (TheTriple.getTriple().empty())
372     TheTriple.setTriple(sys::getDefaultTargetTriple());
373
374   // Get the target specific parser.
375   std::string Error;
376   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
377                                                          Error);
378   if (!TheTarget) {
379     errs() << argv[0] << ": " << Error;
380     return 1;
381   }
382
383   std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
384
385   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
386   switch (OptLevel) {
387   default:
388     errs() << argv[0] << ": invalid optimization level.\n";
389     return 1;
390   case ' ': break;
391   case '0': OLvl = CodeGenOpt::None; break;
392   case '1': OLvl = CodeGenOpt::Less; break;
393   case '2': OLvl = CodeGenOpt::Default; break;
394   case '3': OLvl = CodeGenOpt::Aggressive; break;
395   }
396
397   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
398   Options.DisableIntegratedAS = NoIntegratedAssembler;
399   Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
400   Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
401   Options.MCOptions.AsmVerbose = AsmVerbose;
402   Options.MCOptions.PreserveAsmComments = PreserveComments;
403   Options.MCOptions.IASSearchPaths = IncludeDirs;
404
405   std::unique_ptr<TargetMachine> Target(
406       TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
407                                      Options, getRelocModel(), CMModel, OLvl));
408
409   assert(Target && "Could not allocate target machine!");
410
411   // If we don't have a module then just exit now. We do this down
412   // here since the CPU/Feature help is underneath the target machine
413   // creation.
414   if (SkipModule)
415     return 0;
416
417   assert(M && "Should have exited if we didn't have a module!");
418   if (FloatABIForCalls != FloatABI::Default)
419     Options.FloatABIType = FloatABIForCalls;
420
421   // Figure out where we are going to send the output.
422   std::unique_ptr<tool_output_file> Out =
423       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
424   if (!Out) return 1;
425
426   // Build up all of the passes that we want to do to the module.
427   legacy::PassManager PM;
428
429   // Add an appropriate TargetLibraryInfo pass for the module's triple.
430   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
431
432   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
433   if (DisableSimplifyLibCalls)
434     TLII.disableAllFunctions();
435   PM.add(new TargetLibraryInfoWrapperPass(TLII));
436
437   // Add the target data from the target machine, if it exists, or the module.
438   M->setDataLayout(Target->createDataLayout());
439
440   // Override function attributes based on CPUStr, FeaturesStr, and command line
441   // flags.
442   setFunctionAttributes(CPUStr, FeaturesStr, *M);
443
444   if (RelaxAll.getNumOccurrences() > 0 &&
445       FileType != TargetMachine::CGFT_ObjectFile)
446     errs() << argv[0]
447              << ": warning: ignoring -mc-relax-all because filetype != obj";
448
449   {
450     raw_pwrite_stream *OS = &Out->os();
451
452     // Manually do the buffering rather than using buffer_ostream,
453     // so we can memcmp the contents in CompileTwice mode
454     SmallVector<char, 0> Buffer;
455     std::unique_ptr<raw_svector_ostream> BOS;
456     if ((FileType != TargetMachine::CGFT_AssemblyFile &&
457          !Out->os().supportsSeeking()) ||
458         CompileTwice) {
459       BOS = make_unique<raw_svector_ostream>(Buffer);
460       OS = BOS.get();
461     }
462
463     if (!RunPassNames->empty()) {
464       if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() ||
465           !StopBefore.empty()) {
466         errs() << argv[0] << ": start-after and/or stop-after passes are "
467                              "redundant when run-pass is specified.\n";
468         return 1;
469       }
470       if (!MIR) {
471         errs() << argv[0] << ": run-pass needs a .mir input.\n";
472         return 1;
473       }
474       LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
475       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
476       PM.add(&TPC);
477       MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
478       MMI->setMachineFunctionInitializer(MIR.get());
479       PM.add(MMI);
480       TPC.printAndVerify("");
481
482       for (const std::string &RunPassName : *RunPassNames) {
483         if (addPass(PM, argv[0], RunPassName, TPC))
484           return 1;
485       }
486       PM.add(createPrintMIRPass(*OS));
487     } else {
488       const char *argv0 = argv[0];
489       AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore);
490       AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter);
491       AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter);
492       AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore);
493
494       if (StartBeforeID && StartAfterID) {
495         errs() << argv[0] << ": -start-before and -start-after specified!\n";
496         return 1;
497       }
498       if (StopBeforeID && StopAfterID) {
499         errs() << argv[0] << ": -stop-before and -stop-after specified!\n";
500         return 1;
501       }
502
503       // Ask the target to add backend passes as necessary.
504       if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
505                                       StartBeforeID, StartAfterID, StopBeforeID,
506                                       StopAfterID, MIR.get())) {
507         errs() << argv[0] << ": target does not support generation of this"
508                << " file type!\n";
509         return 1;
510       }
511     }
512
513     // Before executing passes, print the final values of the LLVM options.
514     cl::PrintOptionValues();
515
516     // If requested, run the pass manager over the same module again,
517     // to catch any bugs due to persistent state in the passes. Note that
518     // opt has the same functionality, so it may be worth abstracting this out
519     // in the future.
520     SmallVector<char, 0> CompileTwiceBuffer;
521     if (CompileTwice) {
522       std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
523       PM.run(*M2);
524       CompileTwiceBuffer = Buffer;
525       Buffer.clear();
526     }
527
528     PM.run(*M);
529
530     auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
531     if (HasError)
532       return 1;
533
534     // Compare the two outputs and make sure they're the same
535     if (CompileTwice) {
536       if (Buffer.size() != CompileTwiceBuffer.size() ||
537           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
538            0)) {
539         errs()
540             << "Running the pass manager twice changed the output.\n"
541                "Writing the result of the second run to the specified output\n"
542                "To generate the one-run comparison binary, just run without\n"
543                "the compile-twice option\n";
544         Out->os() << Buffer;
545         Out->keep();
546         return 1;
547       }
548     }
549
550     if (BOS) {
551       Out->os() << Buffer;
552     }
553   }
554
555   // Declare success.
556   Out->keep();
557
558   return 0;
559 }