llc.cpp 13 KB

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