LTOCodeGenerator.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
  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 file implements the Link Time Optimization library. This library is
  10. // intended to be used by linker to optimize code at link time.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/LTO/legacy/LTOCodeGenerator.h"
  14. #include "llvm/ADT/Statistic.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/Analysis/Passes.h"
  17. #include "llvm/Analysis/TargetLibraryInfo.h"
  18. #include "llvm/Analysis/TargetTransformInfo.h"
  19. #include "llvm/Bitcode/BitcodeWriter.h"
  20. #include "llvm/CodeGen/ParallelCG.h"
  21. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  22. #include "llvm/Config/config.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/DebugInfo.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/DiagnosticInfo.h"
  28. #include "llvm/IR/DiagnosticPrinter.h"
  29. #include "llvm/IR/LLVMContext.h"
  30. #include "llvm/IR/LLVMRemarkStreamer.h"
  31. #include "llvm/IR/LegacyPassManager.h"
  32. #include "llvm/IR/Mangler.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/PassTimingInfo.h"
  35. #include "llvm/IR/Verifier.h"
  36. #include "llvm/InitializePasses.h"
  37. #include "llvm/LTO/LTO.h"
  38. #include "llvm/LTO/LTOBackend.h"
  39. #include "llvm/LTO/legacy/LTOModule.h"
  40. #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
  41. #include "llvm/Linker/Linker.h"
  42. #include "llvm/MC/MCAsmInfo.h"
  43. #include "llvm/MC/MCContext.h"
  44. #include "llvm/MC/SubtargetFeature.h"
  45. #include "llvm/MC/TargetRegistry.h"
  46. #include "llvm/Remarks/HotnessThresholdParser.h"
  47. #include "llvm/Support/CommandLine.h"
  48. #include "llvm/Support/FileSystem.h"
  49. #include "llvm/Support/Host.h"
  50. #include "llvm/Support/MemoryBuffer.h"
  51. #include "llvm/Support/Signals.h"
  52. #include "llvm/Support/TargetSelect.h"
  53. #include "llvm/Support/ToolOutputFile.h"
  54. #include "llvm/Support/YAMLTraits.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. #include "llvm/Target/TargetOptions.h"
  57. #include "llvm/Transforms/IPO.h"
  58. #include "llvm/Transforms/IPO/Internalize.h"
  59. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  60. #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
  61. #include "llvm/Transforms/ObjCARC.h"
  62. #include "llvm/Transforms/Utils/ModuleUtils.h"
  63. #include <system_error>
  64. using namespace llvm;
  65. const char* LTOCodeGenerator::getVersionString() {
  66. #ifdef LLVM_VERSION_INFO
  67. return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
  68. #else
  69. return PACKAGE_NAME " version " PACKAGE_VERSION;
  70. #endif
  71. }
  72. namespace llvm {
  73. cl::opt<bool> LTODiscardValueNames(
  74. "lto-discard-value-names",
  75. cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
  76. #ifdef NDEBUG
  77. cl::init(true),
  78. #else
  79. cl::init(false),
  80. #endif
  81. cl::Hidden);
  82. cl::opt<bool> RemarksWithHotness(
  83. "lto-pass-remarks-with-hotness",
  84. cl::desc("With PGO, include profile count in optimization remarks"),
  85. cl::Hidden);
  86. cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
  87. RemarksHotnessThreshold(
  88. "lto-pass-remarks-hotness-threshold",
  89. cl::desc("Minimum profile count required for an "
  90. "optimization remark to be output."
  91. " Use 'auto' to apply the threshold from profile summary."),
  92. cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden);
  93. cl::opt<std::string>
  94. RemarksFilename("lto-pass-remarks-output",
  95. cl::desc("Output filename for pass remarks"),
  96. cl::value_desc("filename"));
  97. cl::opt<std::string>
  98. RemarksPasses("lto-pass-remarks-filter",
  99. cl::desc("Only record optimization remarks from passes whose "
  100. "names match the given regular expression"),
  101. cl::value_desc("regex"));
  102. cl::opt<std::string> RemarksFormat(
  103. "lto-pass-remarks-format",
  104. cl::desc("The format used for serializing remarks (default: YAML)"),
  105. cl::value_desc("format"), cl::init("yaml"));
  106. cl::opt<std::string> LTOStatsFile(
  107. "lto-stats-file",
  108. cl::desc("Save statistics to the specified file"),
  109. cl::Hidden);
  110. }
  111. LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
  112. : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
  113. TheLinker(new Linker(*MergedModule)) {
  114. Context.setDiscardValueNames(LTODiscardValueNames);
  115. Context.enableDebugTypeODRUniquing();
  116. Config.CodeModel = None;
  117. Config.StatsFile = LTOStatsFile;
  118. Config.PreCodeGenPassesHook = [](legacy::PassManager &PM) {
  119. PM.add(createObjCARCContractPass());
  120. };
  121. }
  122. LTOCodeGenerator::~LTOCodeGenerator() {}
  123. void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
  124. for (const StringRef &Undef : Mod->getAsmUndefinedRefs())
  125. AsmUndefinedRefs.insert(Undef);
  126. }
  127. bool LTOCodeGenerator::addModule(LTOModule *Mod) {
  128. assert(&Mod->getModule().getContext() == &Context &&
  129. "Expected module in same context");
  130. bool ret = TheLinker->linkInModule(Mod->takeModule());
  131. setAsmUndefinedRefs(Mod);
  132. // We've just changed the input, so let's make sure we verify it.
  133. HasVerifiedInput = false;
  134. return !ret;
  135. }
  136. void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
  137. assert(&Mod->getModule().getContext() == &Context &&
  138. "Expected module in same context");
  139. AsmUndefinedRefs.clear();
  140. MergedModule = Mod->takeModule();
  141. TheLinker = std::make_unique<Linker>(*MergedModule);
  142. setAsmUndefinedRefs(&*Mod);
  143. // We've just changed the input, so let's make sure we verify it.
  144. HasVerifiedInput = false;
  145. }
  146. void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
  147. Config.Options = Options;
  148. }
  149. void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
  150. switch (Debug) {
  151. case LTO_DEBUG_MODEL_NONE:
  152. EmitDwarfDebugInfo = false;
  153. return;
  154. case LTO_DEBUG_MODEL_DWARF:
  155. EmitDwarfDebugInfo = true;
  156. return;
  157. }
  158. llvm_unreachable("Unknown debug format!");
  159. }
  160. void LTOCodeGenerator::setOptLevel(unsigned Level) {
  161. Config.OptLevel = Level;
  162. Config.PTO.LoopVectorization = Config.OptLevel > 1;
  163. Config.PTO.SLPVectorization = Config.OptLevel > 1;
  164. switch (Config.OptLevel) {
  165. case 0:
  166. Config.CGOptLevel = CodeGenOpt::None;
  167. return;
  168. case 1:
  169. Config.CGOptLevel = CodeGenOpt::Less;
  170. return;
  171. case 2:
  172. Config.CGOptLevel = CodeGenOpt::Default;
  173. return;
  174. case 3:
  175. Config.CGOptLevel = CodeGenOpt::Aggressive;
  176. return;
  177. }
  178. llvm_unreachable("Unknown optimization level!");
  179. }
  180. bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
  181. if (!determineTarget())
  182. return false;
  183. // We always run the verifier once on the merged module.
  184. verifyMergedModuleOnce();
  185. // mark which symbols can not be internalized
  186. applyScopeRestrictions();
  187. // create output file
  188. std::error_code EC;
  189. ToolOutputFile Out(Path, EC, sys::fs::OF_None);
  190. if (EC) {
  191. std::string ErrMsg = "could not open bitcode file for writing: ";
  192. ErrMsg += Path.str() + ": " + EC.message();
  193. emitError(ErrMsg);
  194. return false;
  195. }
  196. // write bitcode to it
  197. WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
  198. Out.os().close();
  199. if (Out.os().has_error()) {
  200. std::string ErrMsg = "could not write bitcode file: ";
  201. ErrMsg += Path.str() + ": " + Out.os().error().message();
  202. emitError(ErrMsg);
  203. Out.os().clear_error();
  204. return false;
  205. }
  206. Out.keep();
  207. return true;
  208. }
  209. bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
  210. // make unique temp output file to put generated code
  211. SmallString<128> Filename;
  212. auto AddStream = [&](size_t Task) -> std::unique_ptr<CachedFileStream> {
  213. StringRef Extension(Config.CGFileType == CGFT_AssemblyFile ? "s" : "o");
  214. int FD;
  215. std::error_code EC =
  216. sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
  217. if (EC)
  218. emitError(EC.message());
  219. return std::make_unique<CachedFileStream>(
  220. std::make_unique<llvm::raw_fd_ostream>(FD, true));
  221. };
  222. bool genResult = compileOptimized(AddStream, 1);
  223. if (!genResult) {
  224. sys::fs::remove(Twine(Filename));
  225. return false;
  226. }
  227. // If statistics were requested, save them to the specified file or
  228. // print them out after codegen.
  229. if (StatsFile)
  230. PrintStatisticsJSON(StatsFile->os());
  231. else if (AreStatisticsEnabled())
  232. PrintStatistics();
  233. NativeObjectPath = Filename.c_str();
  234. *Name = NativeObjectPath.c_str();
  235. return true;
  236. }
  237. std::unique_ptr<MemoryBuffer>
  238. LTOCodeGenerator::compileOptimized() {
  239. const char *name;
  240. if (!compileOptimizedToFile(&name))
  241. return nullptr;
  242. // read .o file into memory buffer
  243. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFile(
  244. name, /*IsText=*/false, /*RequiresNullTerminator=*/false);
  245. if (std::error_code EC = BufferOrErr.getError()) {
  246. emitError(EC.message());
  247. sys::fs::remove(NativeObjectPath);
  248. return nullptr;
  249. }
  250. // remove temp files
  251. sys::fs::remove(NativeObjectPath);
  252. return std::move(*BufferOrErr);
  253. }
  254. bool LTOCodeGenerator::compile_to_file(const char **Name) {
  255. if (!optimize())
  256. return false;
  257. return compileOptimizedToFile(Name);
  258. }
  259. std::unique_ptr<MemoryBuffer> LTOCodeGenerator::compile() {
  260. if (!optimize())
  261. return nullptr;
  262. return compileOptimized();
  263. }
  264. bool LTOCodeGenerator::determineTarget() {
  265. if (TargetMach)
  266. return true;
  267. TripleStr = MergedModule->getTargetTriple();
  268. if (TripleStr.empty()) {
  269. TripleStr = sys::getDefaultTargetTriple();
  270. MergedModule->setTargetTriple(TripleStr);
  271. }
  272. llvm::Triple Triple(TripleStr);
  273. // create target machine from info for merged modules
  274. std::string ErrMsg;
  275. MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
  276. if (!MArch) {
  277. emitError(ErrMsg);
  278. return false;
  279. }
  280. // Construct LTOModule, hand over ownership of module and target. Use MAttr as
  281. // the default set of features.
  282. SubtargetFeatures Features(join(Config.MAttrs, ""));
  283. Features.getDefaultSubtargetFeatures(Triple);
  284. FeatureStr = Features.getString();
  285. // Set a default CPU for Darwin triples.
  286. if (Config.CPU.empty() && Triple.isOSDarwin()) {
  287. if (Triple.getArch() == llvm::Triple::x86_64)
  288. Config.CPU = "core2";
  289. else if (Triple.getArch() == llvm::Triple::x86)
  290. Config.CPU = "yonah";
  291. else if (Triple.isArm64e())
  292. Config.CPU = "apple-a12";
  293. else if (Triple.getArch() == llvm::Triple::aarch64 ||
  294. Triple.getArch() == llvm::Triple::aarch64_32)
  295. Config.CPU = "cyclone";
  296. }
  297. TargetMach = createTargetMachine();
  298. assert(TargetMach && "Unable to create target machine");
  299. return true;
  300. }
  301. std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
  302. assert(MArch && "MArch is not set!");
  303. return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
  304. TripleStr, Config.CPU, FeatureStr, Config.Options, Config.RelocModel,
  305. None, Config.CGOptLevel));
  306. }
  307. // If a linkonce global is present in the MustPreserveSymbols, we need to make
  308. // sure we honor this. To force the compiler to not drop it, we add it to the
  309. // "llvm.compiler.used" global.
  310. void LTOCodeGenerator::preserveDiscardableGVs(
  311. Module &TheModule,
  312. llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
  313. std::vector<GlobalValue *> Used;
  314. auto mayPreserveGlobal = [&](GlobalValue &GV) {
  315. if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
  316. !mustPreserveGV(GV))
  317. return;
  318. if (GV.hasAvailableExternallyLinkage())
  319. return emitWarning(
  320. (Twine("Linker asked to preserve available_externally global: '") +
  321. GV.getName() + "'").str());
  322. if (GV.hasInternalLinkage())
  323. return emitWarning((Twine("Linker asked to preserve internal global: '") +
  324. GV.getName() + "'").str());
  325. Used.push_back(&GV);
  326. };
  327. for (auto &GV : TheModule)
  328. mayPreserveGlobal(GV);
  329. for (auto &GV : TheModule.globals())
  330. mayPreserveGlobal(GV);
  331. for (auto &GV : TheModule.aliases())
  332. mayPreserveGlobal(GV);
  333. if (Used.empty())
  334. return;
  335. appendToCompilerUsed(TheModule, Used);
  336. }
  337. void LTOCodeGenerator::applyScopeRestrictions() {
  338. if (ScopeRestrictionsDone)
  339. return;
  340. // Declare a callback for the internalize pass that will ask for every
  341. // candidate GlobalValue if it can be internalized or not.
  342. Mangler Mang;
  343. SmallString<64> MangledName;
  344. auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
  345. // Unnamed globals can't be mangled, but they can't be preserved either.
  346. if (!GV.hasName())
  347. return false;
  348. // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
  349. // with the linker supplied name, which on Darwin includes a leading
  350. // underscore.
  351. MangledName.clear();
  352. MangledName.reserve(GV.getName().size() + 1);
  353. Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
  354. return MustPreserveSymbols.count(MangledName);
  355. };
  356. // Preserve linkonce value on linker request
  357. preserveDiscardableGVs(*MergedModule, mustPreserveGV);
  358. if (!ShouldInternalize)
  359. return;
  360. if (ShouldRestoreGlobalsLinkage) {
  361. // Record the linkage type of non-local symbols so they can be restored
  362. // prior
  363. // to module splitting.
  364. auto RecordLinkage = [&](const GlobalValue &GV) {
  365. if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
  366. GV.hasName())
  367. ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
  368. };
  369. for (auto &GV : *MergedModule)
  370. RecordLinkage(GV);
  371. for (auto &GV : MergedModule->globals())
  372. RecordLinkage(GV);
  373. for (auto &GV : MergedModule->aliases())
  374. RecordLinkage(GV);
  375. }
  376. // Update the llvm.compiler_used globals to force preserving libcalls and
  377. // symbols referenced from asm
  378. updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
  379. internalizeModule(*MergedModule, mustPreserveGV);
  380. ScopeRestrictionsDone = true;
  381. }
  382. /// Restore original linkage for symbols that may have been internalized
  383. void LTOCodeGenerator::restoreLinkageForExternals() {
  384. if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
  385. return;
  386. assert(ScopeRestrictionsDone &&
  387. "Cannot externalize without internalization!");
  388. if (ExternalSymbols.empty())
  389. return;
  390. auto externalize = [this](GlobalValue &GV) {
  391. if (!GV.hasLocalLinkage() || !GV.hasName())
  392. return;
  393. auto I = ExternalSymbols.find(GV.getName());
  394. if (I == ExternalSymbols.end())
  395. return;
  396. GV.setLinkage(I->second);
  397. };
  398. llvm::for_each(MergedModule->functions(), externalize);
  399. llvm::for_each(MergedModule->globals(), externalize);
  400. llvm::for_each(MergedModule->aliases(), externalize);
  401. }
  402. void LTOCodeGenerator::verifyMergedModuleOnce() {
  403. // Only run on the first call.
  404. if (HasVerifiedInput)
  405. return;
  406. HasVerifiedInput = true;
  407. bool BrokenDebugInfo = false;
  408. if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
  409. report_fatal_error("Broken module found, compilation aborted!");
  410. if (BrokenDebugInfo) {
  411. emitWarning("Invalid debug info found, debug info will be stripped");
  412. StripDebugInfo(*MergedModule);
  413. }
  414. }
  415. void LTOCodeGenerator::finishOptimizationRemarks() {
  416. if (DiagnosticOutputFile) {
  417. DiagnosticOutputFile->keep();
  418. // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
  419. DiagnosticOutputFile->os().flush();
  420. }
  421. }
  422. /// Optimize merged modules using various IPO passes
  423. bool LTOCodeGenerator::optimize() {
  424. if (!this->determineTarget())
  425. return false;
  426. auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
  427. Context, RemarksFilename, RemarksPasses, RemarksFormat,
  428. RemarksWithHotness, RemarksHotnessThreshold);
  429. if (!DiagFileOrErr) {
  430. errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
  431. report_fatal_error("Can't get an output file for the remarks");
  432. }
  433. DiagnosticOutputFile = std::move(*DiagFileOrErr);
  434. // Setup output file to emit statistics.
  435. auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
  436. if (!StatsFileOrErr) {
  437. errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
  438. report_fatal_error("Can't get an output file for the statistics");
  439. }
  440. StatsFile = std::move(StatsFileOrErr.get());
  441. // Currently there is no support for enabling whole program visibility via a
  442. // linker option in the old LTO API, but this call allows it to be specified
  443. // via the internal option. Must be done before WPD invoked via the optimizer
  444. // pipeline run below.
  445. updateVCallVisibilityInModule(*MergedModule,
  446. /* WholeProgramVisibilityEnabledInLTO */ false,
  447. // FIXME: This needs linker information via a
  448. // TBD new interface.
  449. /* DynamicExportSymbols */ {});
  450. // We always run the verifier once on the merged module, the `DisableVerify`
  451. // parameter only applies to subsequent verify.
  452. verifyMergedModuleOnce();
  453. // Mark which symbols can not be internalized
  454. this->applyScopeRestrictions();
  455. // Write LTOPostLink flag for passes that require all the modules.
  456. MergedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
  457. // Add an appropriate DataLayout instance for this module...
  458. MergedModule->setDataLayout(TargetMach->createDataLayout());
  459. ModuleSummaryIndex CombinedIndex(false);
  460. TargetMach = createTargetMachine();
  461. if (!opt(Config, TargetMach.get(), 0, *MergedModule, /*IsThinLTO=*/false,
  462. /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
  463. /*CmdArgs*/ std::vector<uint8_t>())) {
  464. emitError("LTO middle-end optimizations failed");
  465. return false;
  466. }
  467. return true;
  468. }
  469. bool LTOCodeGenerator::compileOptimized(AddStreamFn AddStream,
  470. unsigned ParallelismLevel) {
  471. if (!this->determineTarget())
  472. return false;
  473. // We always run the verifier once on the merged module. If it has already
  474. // been called in optimize(), this call will return early.
  475. verifyMergedModuleOnce();
  476. // Re-externalize globals that may have been internalized to increase scope
  477. // for splitting
  478. restoreLinkageForExternals();
  479. ModuleSummaryIndex CombinedIndex(false);
  480. Config.CodeGenOnly = true;
  481. Error Err = backend(Config, AddStream, ParallelismLevel, *MergedModule,
  482. CombinedIndex);
  483. assert(!Err && "unexpected code-generation failure");
  484. (void)Err;
  485. // If statistics were requested, save them to the specified file or
  486. // print them out after codegen.
  487. if (StatsFile)
  488. PrintStatisticsJSON(StatsFile->os());
  489. else if (AreStatisticsEnabled())
  490. PrintStatistics();
  491. reportAndResetTimings();
  492. finishOptimizationRemarks();
  493. return true;
  494. }
  495. void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<StringRef> Options) {
  496. for (StringRef Option : Options)
  497. CodegenOptions.push_back(Option.str());
  498. }
  499. void LTOCodeGenerator::parseCodeGenDebugOptions() {
  500. if (!CodegenOptions.empty())
  501. llvm::parseCommandLineOptions(CodegenOptions);
  502. }
  503. void llvm::parseCommandLineOptions(std::vector<std::string> &Options) {
  504. if (!Options.empty()) {
  505. // ParseCommandLineOptions() expects argv[0] to be program name.
  506. std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
  507. for (std::string &Arg : Options)
  508. CodegenArgv.push_back(Arg.c_str());
  509. cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
  510. }
  511. }
  512. void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
  513. // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
  514. lto_codegen_diagnostic_severity_t Severity;
  515. switch (DI.getSeverity()) {
  516. case DS_Error:
  517. Severity = LTO_DS_ERROR;
  518. break;
  519. case DS_Warning:
  520. Severity = LTO_DS_WARNING;
  521. break;
  522. case DS_Remark:
  523. Severity = LTO_DS_REMARK;
  524. break;
  525. case DS_Note:
  526. Severity = LTO_DS_NOTE;
  527. break;
  528. }
  529. // Create the string that will be reported to the external diagnostic handler.
  530. std::string MsgStorage;
  531. raw_string_ostream Stream(MsgStorage);
  532. DiagnosticPrinterRawOStream DP(Stream);
  533. DI.print(DP);
  534. Stream.flush();
  535. // If this method has been called it means someone has set up an external
  536. // diagnostic handler. Assert on that.
  537. assert(DiagHandler && "Invalid diagnostic handler");
  538. (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
  539. }
  540. namespace {
  541. struct LTODiagnosticHandler : public DiagnosticHandler {
  542. LTOCodeGenerator *CodeGenerator;
  543. LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
  544. : CodeGenerator(CodeGenPtr) {}
  545. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  546. CodeGenerator->DiagnosticHandler(DI);
  547. return true;
  548. }
  549. };
  550. }
  551. void
  552. LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
  553. void *Ctxt) {
  554. this->DiagHandler = DiagHandler;
  555. this->DiagContext = Ctxt;
  556. if (!DiagHandler)
  557. return Context.setDiagnosticHandler(nullptr);
  558. // Register the LTOCodeGenerator stub in the LLVMContext to forward the
  559. // diagnostic to the external DiagHandler.
  560. Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this),
  561. true);
  562. }
  563. namespace {
  564. class LTODiagnosticInfo : public DiagnosticInfo {
  565. const Twine &Msg;
  566. public:
  567. LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
  568. : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
  569. void print(DiagnosticPrinter &DP) const override { DP << Msg; }
  570. };
  571. }
  572. void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
  573. if (DiagHandler)
  574. (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
  575. else
  576. Context.diagnose(LTODiagnosticInfo(ErrMsg));
  577. }
  578. void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
  579. if (DiagHandler)
  580. (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
  581. else
  582. Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
  583. }