LTOCodeGenerator.cpp 24 KB

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