llc.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is the llc code generator driver. It provides a convenient
  10. // command-line interface for generating native assembly-language code
  11. // or C code, given LLVM bitcode.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/ScopeExit.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/CodeGen/MachineFunctionPass.h"
  23. #include "llvm/CodeGen/MachineModuleInfo.h"
  24. #include "llvm/CodeGen/TargetPassConfig.h"
  25. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  26. #include "llvm/IR/AutoUpgrade.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/LLVMRemarkStreamer.h"
  33. #include "llvm/IR/LegacyPassManager.h"
  34. #include "llvm/IR/Module.h"
  35. #include "llvm/IR/Verifier.h"
  36. #include "llvm/IRReader/IRReader.h"
  37. #include "llvm/InitializePasses.h"
  38. #include "llvm/MC/SubtargetFeature.h"
  39. #include "llvm/MC/TargetRegistry.h"
  40. #include "llvm/Pass.h"
  41. #include "llvm/Remarks/HotnessThresholdParser.h"
  42. #include "llvm/Support/CommandLine.h"
  43. #include "llvm/Support/Debug.h"
  44. #include "llvm/Support/FileSystem.h"
  45. #include "llvm/Support/FormattedStream.h"
  46. #include "llvm/Support/Host.h"
  47. #include "llvm/Support/InitLLVM.h"
  48. #include "llvm/Support/ManagedStatic.h"
  49. #include "llvm/Support/PluginLoader.h"
  50. #include "llvm/Support/SourceMgr.h"
  51. #include "llvm/Support/TargetSelect.h"
  52. #include "llvm/Support/TimeProfiler.h"
  53. #include "llvm/Support/ToolOutputFile.h"
  54. #include "llvm/Support/WithColor.h"
  55. #include "llvm/Target/TargetLoweringObjectFile.h"
  56. #include "llvm/Target/TargetMachine.h"
  57. #include "llvm/Transforms/Utils/Cloning.h"
  58. #include <memory>
  59. using namespace llvm;
  60. static codegen::RegisterCodeGenFlags CGF;
  61. // General options for llc. Other pass-specific options are specified
  62. // within the corresponding llc passes, and target-specific options
  63. // and back-end code generation options are specified with the target machine.
  64. //
  65. static cl::opt<std::string>
  66. InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
  67. static cl::opt<std::string>
  68. InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
  69. static cl::opt<std::string>
  70. OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
  71. static cl::opt<std::string>
  72. SplitDwarfOutputFile("split-dwarf-output",
  73. cl::desc(".dwo output filename"),
  74. cl::value_desc("filename"));
  75. static cl::opt<unsigned>
  76. TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
  77. cl::value_desc("N"),
  78. cl::desc("Repeat compilation N times for timing"));
  79. static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
  80. static cl::opt<unsigned> TimeTraceGranularity(
  81. "time-trace-granularity",
  82. cl::desc(
  83. "Minimum time granularity (in microseconds) traced by time profiler"),
  84. cl::init(500), cl::Hidden);
  85. static cl::opt<std::string>
  86. TimeTraceFile("time-trace-file",
  87. cl::desc("Specify time trace file destination"),
  88. cl::value_desc("filename"));
  89. static cl::opt<std::string>
  90. BinutilsVersion("binutils-version", cl::Hidden,
  91. cl::desc("Produced object files can use all ELF features "
  92. "supported by this binutils version and newer."
  93. "If -no-integrated-as is specified, the generated "
  94. "assembly will consider GNU as support."
  95. "'none' means that all ELF features can be used, "
  96. "regardless of binutils support"));
  97. static cl::opt<bool>
  98. NoIntegratedAssembler("no-integrated-as", cl::Hidden,
  99. cl::desc("Disable integrated assembler"));
  100. static cl::opt<bool>
  101. PreserveComments("preserve-as-comments", cl::Hidden,
  102. cl::desc("Preserve Comments in outputted assembly"),
  103. cl::init(true));
  104. // Determine optimization level.
  105. static cl::opt<char>
  106. OptLevel("O",
  107. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  108. "(default = '-O2')"),
  109. cl::Prefix,
  110. cl::ZeroOrMore,
  111. cl::init(' '));
  112. static cl::opt<std::string>
  113. TargetTriple("mtriple", cl::desc("Override target triple for module"));
  114. static cl::opt<std::string> SplitDwarfFile(
  115. "split-dwarf-file",
  116. cl::desc(
  117. "Specify the name of the .dwo file to encode in the DWARF output"));
  118. static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
  119. cl::desc("Do not verify input module"));
  120. static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
  121. cl::desc("Disable simplify-libcalls"));
  122. static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
  123. cl::desc("Show encoding in .s output"));
  124. static cl::opt<bool>
  125. DwarfDirectory("dwarf-directory", cl::Hidden,
  126. cl::desc("Use .file directives with an explicit directory"),
  127. cl::init(true));
  128. static cl::opt<bool> AsmVerbose("asm-verbose",
  129. cl::desc("Add comments to directives."),
  130. cl::init(true));
  131. static cl::opt<bool>
  132. CompileTwice("compile-twice", cl::Hidden,
  133. cl::desc("Run everything twice, re-using the same pass "
  134. "manager and verify the result is the same."),
  135. cl::init(false));
  136. static cl::opt<bool> DiscardValueNames(
  137. "discard-value-names",
  138. cl::desc("Discard names from Value (other than GlobalValue)."),
  139. cl::init(false), cl::Hidden);
  140. static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
  141. static cl::opt<bool> RemarksWithHotness(
  142. "pass-remarks-with-hotness",
  143. cl::desc("With PGO, include profile count in optimization remarks"),
  144. cl::Hidden);
  145. static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
  146. RemarksHotnessThreshold(
  147. "pass-remarks-hotness-threshold",
  148. cl::desc("Minimum profile count required for "
  149. "an optimization remark to be output. "
  150. "Use 'auto' to apply the threshold from profile summary."),
  151. cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
  152. static cl::opt<std::string>
  153. RemarksFilename("pass-remarks-output",
  154. cl::desc("Output filename for pass remarks"),
  155. cl::value_desc("filename"));
  156. static cl::opt<std::string>
  157. RemarksPasses("pass-remarks-filter",
  158. cl::desc("Only record optimization remarks from passes whose "
  159. "names match the given regular expression"),
  160. cl::value_desc("regex"));
  161. static cl::opt<std::string> RemarksFormat(
  162. "pass-remarks-format",
  163. cl::desc("The format used for serializing remarks (default: YAML)"),
  164. cl::value_desc("format"), cl::init("yaml"));
  165. namespace {
  166. static ManagedStatic<std::vector<std::string>> RunPassNames;
  167. struct RunPassOption {
  168. void operator=(const std::string &Val) const {
  169. if (Val.empty())
  170. return;
  171. SmallVector<StringRef, 8> PassNames;
  172. StringRef(Val).split(PassNames, ',', -1, false);
  173. for (auto PassName : PassNames)
  174. RunPassNames->push_back(std::string(PassName));
  175. }
  176. };
  177. }
  178. static RunPassOption RunPassOpt;
  179. static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
  180. "run-pass",
  181. cl::desc("Run compiler only for specified passes (comma separated list)"),
  182. cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
  183. static int compileModule(char **, LLVMContext &);
  184. [[noreturn]] static void reportError(Twine Msg, StringRef Filename = "") {
  185. SmallString<256> Prefix;
  186. if (!Filename.empty()) {
  187. if (Filename == "-")
  188. Filename = "<stdin>";
  189. ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
  190. }
  191. WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
  192. exit(1);
  193. }
  194. [[noreturn]] static void reportError(Error Err, StringRef Filename) {
  195. assert(Err);
  196. handleAllErrors(createFileError(Filename, std::move(Err)),
  197. [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
  198. llvm_unreachable("reportError() should not return");
  199. }
  200. static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
  201. Triple::OSType OS,
  202. const char *ProgName) {
  203. // If we don't yet have an output filename, make one.
  204. if (OutputFilename.empty()) {
  205. if (InputFilename == "-")
  206. OutputFilename = "-";
  207. else {
  208. // If InputFilename ends in .bc or .ll, remove it.
  209. StringRef IFN = InputFilename;
  210. if (IFN.endswith(".bc") || IFN.endswith(".ll"))
  211. OutputFilename = std::string(IFN.drop_back(3));
  212. else if (IFN.endswith(".mir"))
  213. OutputFilename = std::string(IFN.drop_back(4));
  214. else
  215. OutputFilename = std::string(IFN);
  216. switch (codegen::getFileType()) {
  217. case CGFT_AssemblyFile:
  218. if (TargetName[0] == 'c') {
  219. if (TargetName[1] == 0)
  220. OutputFilename += ".cbe.c";
  221. else if (TargetName[1] == 'p' && TargetName[2] == 'p')
  222. OutputFilename += ".cpp";
  223. else
  224. OutputFilename += ".s";
  225. } else
  226. OutputFilename += ".s";
  227. break;
  228. case CGFT_ObjectFile:
  229. if (OS == Triple::Win32)
  230. OutputFilename += ".obj";
  231. else
  232. OutputFilename += ".o";
  233. break;
  234. case CGFT_Null:
  235. OutputFilename = "-";
  236. break;
  237. }
  238. }
  239. }
  240. // Decide if we need "binary" output.
  241. bool Binary = false;
  242. switch (codegen::getFileType()) {
  243. case CGFT_AssemblyFile:
  244. break;
  245. case CGFT_ObjectFile:
  246. case CGFT_Null:
  247. Binary = true;
  248. break;
  249. }
  250. // Open the file.
  251. std::error_code EC;
  252. sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
  253. if (!Binary)
  254. OpenFlags |= sys::fs::OF_TextWithCRLF;
  255. auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
  256. if (EC) {
  257. reportError(EC.message());
  258. return nullptr;
  259. }
  260. return FDOut;
  261. }
  262. struct LLCDiagnosticHandler : public DiagnosticHandler {
  263. bool *HasError;
  264. LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
  265. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  266. if (DI.getKind() == llvm::DK_SrcMgr) {
  267. const auto &DISM = cast<DiagnosticInfoSrcMgr>(DI);
  268. const SMDiagnostic &SMD = DISM.getSMDiag();
  269. if (SMD.getKind() == SourceMgr::DK_Error)
  270. *HasError = true;
  271. SMD.print(nullptr, errs());
  272. // For testing purposes, we print the LocCookie here.
  273. if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
  274. WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
  275. return true;
  276. }
  277. if (DI.getSeverity() == DS_Error)
  278. *HasError = true;
  279. if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
  280. if (!Remark->isEnabled())
  281. return true;
  282. DiagnosticPrinterRawOStream DP(errs());
  283. errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
  284. DI.print(DP);
  285. errs() << "\n";
  286. return true;
  287. }
  288. };
  289. // main - Entry point for the llc compiler.
  290. //
  291. int main(int argc, char **argv) {
  292. InitLLVM X(argc, argv);
  293. // Enable debug stream buffering.
  294. EnableDebugBuffering = true;
  295. // Initialize targets first, so that --version shows registered targets.
  296. InitializeAllTargets();
  297. InitializeAllTargetMCs();
  298. InitializeAllAsmPrinters();
  299. InitializeAllAsmParsers();
  300. // Initialize codegen and IR passes used by llc so that the -print-after,
  301. // -print-before, and -stop-after options work.
  302. PassRegistry *Registry = PassRegistry::getPassRegistry();
  303. initializeCore(*Registry);
  304. initializeCodeGen(*Registry);
  305. initializeLoopStrengthReducePass(*Registry);
  306. initializeLowerIntrinsicsPass(*Registry);
  307. initializeEntryExitInstrumenterPass(*Registry);
  308. initializePostInlineEntryExitInstrumenterPass(*Registry);
  309. initializeUnreachableBlockElimLegacyPassPass(*Registry);
  310. initializeConstantHoistingLegacyPassPass(*Registry);
  311. initializeScalarOpts(*Registry);
  312. initializeVectorization(*Registry);
  313. initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
  314. initializeExpandReductionsPass(*Registry);
  315. initializeExpandVectorPredicationPass(*Registry);
  316. initializeHardwareLoopsPass(*Registry);
  317. initializeTransformUtils(*Registry);
  318. initializeReplaceWithVeclibLegacyPass(*Registry);
  319. // Initialize debugging passes.
  320. initializeScavengerTestPass(*Registry);
  321. // Register the target printer for --version.
  322. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  323. cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
  324. if (TimeTrace)
  325. timeTraceProfilerInitialize(TimeTraceGranularity, argv[0]);
  326. auto TimeTraceScopeExit = make_scope_exit([]() {
  327. if (TimeTrace) {
  328. if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
  329. handleAllErrors(std::move(E), [&](const StringError &SE) {
  330. errs() << SE.getMessage() << "\n";
  331. });
  332. return;
  333. }
  334. timeTraceProfilerCleanup();
  335. }
  336. });
  337. LLVMContext Context;
  338. Context.setDiscardValueNames(DiscardValueNames);
  339. // Set a diagnostic handler that doesn't exit on the first error
  340. bool HasError = false;
  341. Context.setDiagnosticHandler(
  342. std::make_unique<LLCDiagnosticHandler>(&HasError));
  343. Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
  344. setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
  345. RemarksFormat, RemarksWithHotness,
  346. RemarksHotnessThreshold);
  347. if (Error E = RemarksFileOrErr.takeError())
  348. reportError(std::move(E), RemarksFilename);
  349. std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
  350. if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
  351. reportError("input language must be '', 'IR' or 'MIR'");
  352. // Compile the module TimeCompilations times to give better compile time
  353. // metrics.
  354. for (unsigned I = TimeCompilations; I; --I)
  355. if (int RetVal = compileModule(argv, Context))
  356. return RetVal;
  357. if (RemarksFile)
  358. RemarksFile->keep();
  359. return 0;
  360. }
  361. static bool addPass(PassManagerBase &PM, const char *argv0,
  362. StringRef PassName, TargetPassConfig &TPC) {
  363. if (PassName == "none")
  364. return false;
  365. const PassRegistry *PR = PassRegistry::getPassRegistry();
  366. const PassInfo *PI = PR->getPassInfo(PassName);
  367. if (!PI) {
  368. WithColor::error(errs(), argv0)
  369. << "run-pass " << PassName << " is not registered.\n";
  370. return true;
  371. }
  372. Pass *P;
  373. if (PI->getNormalCtor())
  374. P = PI->getNormalCtor()();
  375. else {
  376. WithColor::error(errs(), argv0)
  377. << "cannot create pass: " << PI->getPassName() << "\n";
  378. return true;
  379. }
  380. std::string Banner = std::string("After ") + std::string(P->getPassName());
  381. TPC.addMachinePrePasses();
  382. PM.add(P);
  383. TPC.addMachinePostPasses(Banner);
  384. return false;
  385. }
  386. static int compileModule(char **argv, LLVMContext &Context) {
  387. // Load the module to be compiled...
  388. SMDiagnostic Err;
  389. std::unique_ptr<Module> M;
  390. std::unique_ptr<MIRParser> MIR;
  391. Triple TheTriple;
  392. std::string CPUStr = codegen::getCPUStr(),
  393. FeaturesStr = codegen::getFeaturesStr();
  394. // Set attributes on functions as loaded from MIR from command line arguments.
  395. auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
  396. codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
  397. };
  398. auto MAttrs = codegen::getMAttrs();
  399. bool SkipModule = codegen::getMCPU() == "help" ||
  400. (!MAttrs.empty() && MAttrs.front() == "help");
  401. CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  402. switch (OptLevel) {
  403. default:
  404. WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
  405. return 1;
  406. case ' ': break;
  407. case '0': OLvl = CodeGenOpt::None; break;
  408. case '1': OLvl = CodeGenOpt::Less; break;
  409. case '2': OLvl = CodeGenOpt::Default; break;
  410. case '3': OLvl = CodeGenOpt::Aggressive; break;
  411. }
  412. // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
  413. // use that to indicate the MC default.
  414. if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
  415. StringRef V = BinutilsVersion.getValue();
  416. unsigned Num;
  417. if (V.consumeInteger(10, Num) || Num == 0 ||
  418. !(V.empty() ||
  419. (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
  420. WithColor::error(errs(), argv[0])
  421. << "invalid -binutils-version, accepting 'none' or major.minor\n";
  422. return 1;
  423. }
  424. }
  425. TargetOptions Options;
  426. auto InitializeOptions = [&](const Triple &TheTriple) {
  427. Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
  428. Options.BinutilsVersion =
  429. TargetMachine::parseBinutilsVersion(BinutilsVersion);
  430. Options.DisableIntegratedAS = NoIntegratedAssembler;
  431. Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
  432. Options.MCOptions.MCUseDwarfDirectory = DwarfDirectory;
  433. Options.MCOptions.AsmVerbose = AsmVerbose;
  434. Options.MCOptions.PreserveAsmComments = PreserveComments;
  435. Options.MCOptions.IASSearchPaths = IncludeDirs;
  436. Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
  437. };
  438. Optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
  439. const Target *TheTarget = nullptr;
  440. std::unique_ptr<TargetMachine> Target;
  441. // If user just wants to list available options, skip module loading
  442. if (!SkipModule) {
  443. auto SetDataLayout =
  444. [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> {
  445. // If we are supposed to override the target triple, do so now.
  446. std::string IRTargetTriple = DataLayoutTargetTriple.str();
  447. if (!TargetTriple.empty())
  448. IRTargetTriple = Triple::normalize(TargetTriple);
  449. TheTriple = Triple(IRTargetTriple);
  450. if (TheTriple.getTriple().empty())
  451. TheTriple.setTriple(sys::getDefaultTargetTriple());
  452. std::string Error;
  453. TheTarget =
  454. TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
  455. if (!TheTarget) {
  456. WithColor::error(errs(), argv[0]) << Error;
  457. exit(1);
  458. }
  459. // On AIX, setting the relocation model to anything other than PIC is
  460. // considered a user error.
  461. if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_)
  462. reportError("invalid relocation model, AIX only supports PIC",
  463. InputFilename);
  464. InitializeOptions(TheTriple);
  465. Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
  466. TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
  467. codegen::getExplicitCodeModel(), OLvl));
  468. assert(Target && "Could not allocate target machine!");
  469. return Target->createDataLayout().getStringRepresentation();
  470. };
  471. if (InputLanguage == "mir" ||
  472. (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
  473. MIR = createMIRParserFromFile(InputFilename, Err, Context,
  474. setMIRFunctionAttributes);
  475. if (MIR)
  476. M = MIR->parseIRModule(SetDataLayout);
  477. } else {
  478. M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
  479. }
  480. if (!M) {
  481. Err.print(argv[0], WithColor::error(errs(), argv[0]));
  482. return 1;
  483. }
  484. if (!TargetTriple.empty())
  485. M->setTargetTriple(Triple::normalize(TargetTriple));
  486. } else {
  487. TheTriple = Triple(Triple::normalize(TargetTriple));
  488. if (TheTriple.getTriple().empty())
  489. TheTriple.setTriple(sys::getDefaultTargetTriple());
  490. // Get the target specific parser.
  491. std::string Error;
  492. TheTarget =
  493. TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
  494. if (!TheTarget) {
  495. WithColor::error(errs(), argv[0]) << Error;
  496. return 1;
  497. }
  498. // On AIX, setting the relocation model to anything other than PIC is
  499. // considered a user error.
  500. if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) {
  501. WithColor::error(errs(), argv[0])
  502. << "invalid relocation model, AIX only supports PIC.\n";
  503. return 1;
  504. }
  505. InitializeOptions(TheTriple);
  506. Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
  507. TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
  508. codegen::getExplicitCodeModel(), OLvl));
  509. assert(Target && "Could not allocate target machine!");
  510. // If we don't have a module then just exit now. We do this down
  511. // here since the CPU/Feature help is underneath the target machine
  512. // creation.
  513. return 0;
  514. }
  515. assert(M && "Should have exited if we didn't have a module!");
  516. if (codegen::getFloatABIForCalls() != FloatABI::Default)
  517. Options.FloatABIType = codegen::getFloatABIForCalls();
  518. // Figure out where we are going to send the output.
  519. std::unique_ptr<ToolOutputFile> Out =
  520. GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
  521. if (!Out) return 1;
  522. // Ensure the filename is passed down to CodeViewDebug.
  523. Target->Options.ObjectFilenameForDebug = Out->outputFilename();
  524. std::unique_ptr<ToolOutputFile> DwoOut;
  525. if (!SplitDwarfOutputFile.empty()) {
  526. std::error_code EC;
  527. DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
  528. sys::fs::OF_None);
  529. if (EC)
  530. reportError(EC.message(), SplitDwarfOutputFile);
  531. }
  532. // Build up all of the passes that we want to do to the module.
  533. legacy::PassManager PM;
  534. // Add an appropriate TargetLibraryInfo pass for the module's triple.
  535. TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
  536. // The -disable-simplify-libcalls flag actually disables all builtin optzns.
  537. if (DisableSimplifyLibCalls)
  538. TLII.disableAllFunctions();
  539. PM.add(new TargetLibraryInfoWrapperPass(TLII));
  540. // Verify module immediately to catch problems before doInitialization() is
  541. // called on any passes.
  542. if (!NoVerify && verifyModule(*M, &errs()))
  543. reportError("input module cannot be verified", InputFilename);
  544. // Override function attributes based on CPUStr, FeaturesStr, and command line
  545. // flags.
  546. codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
  547. if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile)
  548. WithColor::warning(errs(), argv[0])
  549. << ": warning: ignoring -mc-relax-all because filetype != obj";
  550. {
  551. raw_pwrite_stream *OS = &Out->os();
  552. // Manually do the buffering rather than using buffer_ostream,
  553. // so we can memcmp the contents in CompileTwice mode
  554. SmallVector<char, 0> Buffer;
  555. std::unique_ptr<raw_svector_ostream> BOS;
  556. if ((codegen::getFileType() != CGFT_AssemblyFile &&
  557. !Out->os().supportsSeeking()) ||
  558. CompileTwice) {
  559. BOS = std::make_unique<raw_svector_ostream>(Buffer);
  560. OS = BOS.get();
  561. }
  562. const char *argv0 = argv[0];
  563. LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
  564. MachineModuleInfoWrapperPass *MMIWP =
  565. new MachineModuleInfoWrapperPass(&LLVMTM);
  566. // Construct a custom pass pipeline that starts after instruction
  567. // selection.
  568. if (!RunPassNames->empty()) {
  569. if (!MIR) {
  570. WithColor::warning(errs(), argv[0])
  571. << "run-pass is for .mir file only.\n";
  572. return 1;
  573. }
  574. TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
  575. if (TPC.hasLimitedCodeGenPipeline()) {
  576. WithColor::warning(errs(), argv[0])
  577. << "run-pass cannot be used with "
  578. << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
  579. return 1;
  580. }
  581. TPC.setDisableVerify(NoVerify);
  582. PM.add(&TPC);
  583. PM.add(MMIWP);
  584. TPC.printAndVerify("");
  585. for (const std::string &RunPassName : *RunPassNames) {
  586. if (addPass(PM, argv0, RunPassName, TPC))
  587. return 1;
  588. }
  589. TPC.setInitialized();
  590. PM.add(createPrintMIRPass(*OS));
  591. PM.add(createFreeMachineFunctionPass());
  592. } else if (Target->addPassesToEmitFile(
  593. PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
  594. codegen::getFileType(), NoVerify, MMIWP)) {
  595. reportError("target does not support generation of this file type");
  596. }
  597. const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
  598. ->Initialize(MMIWP->getMMI().getContext(), *Target);
  599. if (MIR) {
  600. assert(MMIWP && "Forgot to create MMIWP?");
  601. if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
  602. return 1;
  603. }
  604. // Before executing passes, print the final values of the LLVM options.
  605. cl::PrintOptionValues();
  606. // If requested, run the pass manager over the same module again,
  607. // to catch any bugs due to persistent state in the passes. Note that
  608. // opt has the same functionality, so it may be worth abstracting this out
  609. // in the future.
  610. SmallVector<char, 0> CompileTwiceBuffer;
  611. if (CompileTwice) {
  612. std::unique_ptr<Module> M2(llvm::CloneModule(*M));
  613. PM.run(*M2);
  614. CompileTwiceBuffer = Buffer;
  615. Buffer.clear();
  616. }
  617. PM.run(*M);
  618. auto HasError =
  619. ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
  620. if (*HasError)
  621. return 1;
  622. // Compare the two outputs and make sure they're the same
  623. if (CompileTwice) {
  624. if (Buffer.size() != CompileTwiceBuffer.size() ||
  625. (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
  626. 0)) {
  627. errs()
  628. << "Running the pass manager twice changed the output.\n"
  629. "Writing the result of the second run to the specified output\n"
  630. "To generate the one-run comparison binary, just run without\n"
  631. "the compile-twice option\n";
  632. Out->os() << Buffer;
  633. Out->keep();
  634. return 1;
  635. }
  636. }
  637. if (BOS) {
  638. Out->os() << Buffer;
  639. }
  640. }
  641. // Declare success.
  642. Out->keep();
  643. if (DwoOut)
  644. DwoOut->keep();
  645. return 0;
  646. }