LTOCodeGenerator.cpp 23 KB

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