llvm-lto2.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. //===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
  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 program takes in a list of bitcode files, links them and performs
  10. // link-time optimization according to the provided symbol resolutions using the
  11. // resolution-based LTO interface, and outputs one or more object files.
  12. //
  13. // This program is intended to eventually replace llvm-lto which uses the legacy
  14. // LTO interface.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Bitcode/BitcodeReader.h"
  18. #include "llvm/CodeGen/CommandFlags.h"
  19. #include "llvm/Config/llvm-config.h"
  20. #include "llvm/IR/DiagnosticPrinter.h"
  21. #include "llvm/LTO/Caching.h"
  22. #include "llvm/LTO/LTO.h"
  23. #include "llvm/Passes/PassPlugin.h"
  24. #include "llvm/Remarks/HotnessThresholdParser.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/FileSystem.h"
  27. #include "llvm/Support/InitLLVM.h"
  28. #include "llvm/Support/PluginLoader.h"
  29. #include "llvm/Support/TargetSelect.h"
  30. #include "llvm/Support/Threading.h"
  31. using namespace llvm;
  32. using namespace lto;
  33. static codegen::RegisterCodeGenFlags CGF;
  34. static cl::opt<char>
  35. OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  36. "(default = '-O2')"),
  37. cl::Prefix, cl::ZeroOrMore, cl::init('2'));
  38. static cl::opt<char> CGOptLevel(
  39. "cg-opt-level",
  40. cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
  41. cl::init('2'));
  42. static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
  43. cl::desc("<input bitcode files>"));
  44. static cl::opt<std::string> OutputFilename("o", cl::Required,
  45. cl::desc("Output filename"),
  46. cl::value_desc("filename"));
  47. static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
  48. cl::value_desc("directory"));
  49. static cl::opt<std::string> OptPipeline("opt-pipeline",
  50. cl::desc("Optimizer Pipeline"),
  51. cl::value_desc("pipeline"));
  52. static cl::opt<std::string> AAPipeline("aa-pipeline",
  53. cl::desc("Alias Analysis Pipeline"),
  54. cl::value_desc("aapipeline"));
  55. static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
  56. static cl::opt<bool>
  57. ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
  58. cl::desc("Write out individual index and "
  59. "import files for the "
  60. "distributed backend case"));
  61. // Default to using all available threads in the system, but using only one
  62. // thread per core (no SMT).
  63. // Use -thinlto-threads=all to use hardware_concurrency() instead, which means
  64. // to use all hardware threads or cores in the system.
  65. static cl::opt<std::string> Threads("thinlto-threads");
  66. static cl::list<std::string> SymbolResolutions(
  67. "r",
  68. cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
  69. "where \"resolution\" is a sequence (which may be empty) of the\n"
  70. "following characters:\n"
  71. " p - prevailing: the linker has chosen this definition of the\n"
  72. " symbol\n"
  73. " l - local: the definition of this symbol is unpreemptable at\n"
  74. " runtime and is known to be in this linkage unit\n"
  75. " x - externally visible: the definition of this symbol is\n"
  76. " visible outside of the LTO unit\n"
  77. "A resolution for each symbol must be specified."),
  78. cl::ZeroOrMore);
  79. static cl::opt<std::string> OverrideTriple(
  80. "override-triple",
  81. cl::desc("Replace target triples in input files with this triple"));
  82. static cl::opt<std::string> DefaultTriple(
  83. "default-triple",
  84. cl::desc(
  85. "Replace unspecified target triples in input files with this triple"));
  86. static cl::opt<bool> RemarksWithHotness(
  87. "pass-remarks-with-hotness",
  88. cl::desc("With PGO, include profile count in optimization remarks"),
  89. cl::Hidden);
  90. cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
  91. RemarksHotnessThreshold(
  92. "pass-remarks-hotness-threshold",
  93. cl::desc("Minimum profile count required for an "
  94. "optimization remark to be output."
  95. " Use 'auto' to apply the threshold from profile summary."),
  96. cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden);
  97. static cl::opt<std::string>
  98. RemarksFilename("pass-remarks-output",
  99. cl::desc("Output filename for pass remarks"),
  100. cl::value_desc("filename"));
  101. static cl::opt<std::string>
  102. RemarksPasses("pass-remarks-filter",
  103. cl::desc("Only record optimization remarks from passes whose "
  104. "names match the given regular expression"),
  105. cl::value_desc("regex"));
  106. static cl::opt<std::string> RemarksFormat(
  107. "pass-remarks-format",
  108. cl::desc("The format used for serializing remarks (default: YAML)"),
  109. cl::value_desc("format"), cl::init("yaml"));
  110. static cl::opt<std::string>
  111. SamplePGOFile("lto-sample-profile-file",
  112. cl::desc("Specify a SamplePGO profile file"));
  113. static cl::opt<std::string>
  114. CSPGOFile("lto-cspgo-profile-file",
  115. cl::desc("Specify a context sensitive PGO profile file"));
  116. static cl::opt<bool>
  117. RunCSIRInstr("lto-cspgo-gen",
  118. cl::desc("Run PGO context sensitive IR instrumentation"),
  119. cl::init(false), cl::Hidden);
  120. static cl::opt<bool>
  121. UseNewPM("use-new-pm",
  122. cl::desc("Run LTO passes using the new pass manager"),
  123. cl::init(LLVM_ENABLE_NEW_PASS_MANAGER), cl::Hidden);
  124. static cl::opt<bool>
  125. DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
  126. cl::desc("Print pass management debugging information"));
  127. static cl::opt<std::string>
  128. StatsFile("stats-file", cl::desc("Filename to write statistics to"));
  129. static cl::list<std::string>
  130. PassPlugins("load-pass-plugin",
  131. cl::desc("Load passes from plugin library"));
  132. static cl::opt<bool> EnableFreestanding(
  133. "lto-freestanding",
  134. cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"),
  135. cl::init(false), cl::Hidden);
  136. static void check(Error E, std::string Msg) {
  137. if (!E)
  138. return;
  139. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  140. errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
  141. });
  142. exit(1);
  143. }
  144. template <typename T> static T check(Expected<T> E, std::string Msg) {
  145. if (E)
  146. return std::move(*E);
  147. check(E.takeError(), Msg);
  148. return T();
  149. }
  150. static void check(std::error_code EC, std::string Msg) {
  151. check(errorCodeToError(EC), Msg);
  152. }
  153. template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
  154. if (E)
  155. return std::move(*E);
  156. check(E.getError(), Msg);
  157. return T();
  158. }
  159. static int usage() {
  160. errs() << "Available subcommands: dump-symtab run\n";
  161. return 1;
  162. }
  163. static int run(int argc, char **argv) {
  164. cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
  165. // FIXME: Workaround PR30396 which means that a symbol can appear
  166. // more than once if it is defined in module-level assembly and
  167. // has a GV declaration. We allow (file, symbol) pairs to have multiple
  168. // resolutions and apply them in the order observed.
  169. std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
  170. CommandLineResolutions;
  171. for (std::string R : SymbolResolutions) {
  172. StringRef Rest = R;
  173. StringRef FileName, SymbolName;
  174. std::tie(FileName, Rest) = Rest.split(',');
  175. if (Rest.empty()) {
  176. llvm::errs() << "invalid resolution: " << R << '\n';
  177. return 1;
  178. }
  179. std::tie(SymbolName, Rest) = Rest.split(',');
  180. SymbolResolution Res;
  181. for (char C : Rest) {
  182. if (C == 'p')
  183. Res.Prevailing = true;
  184. else if (C == 'l')
  185. Res.FinalDefinitionInLinkageUnit = true;
  186. else if (C == 'x')
  187. Res.VisibleToRegularObj = true;
  188. else if (C == 'r')
  189. Res.LinkerRedefined = true;
  190. else {
  191. llvm::errs() << "invalid character " << C << " in resolution: " << R
  192. << '\n';
  193. return 1;
  194. }
  195. }
  196. CommandLineResolutions[{std::string(FileName), std::string(SymbolName)}]
  197. .push_back(Res);
  198. }
  199. std::vector<std::unique_ptr<MemoryBuffer>> MBs;
  200. Config Conf;
  201. Conf.DiagHandler = [](const DiagnosticInfo &DI) {
  202. DiagnosticPrinterRawOStream DP(errs());
  203. DI.print(DP);
  204. errs() << '\n';
  205. if (DI.getSeverity() == DS_Error)
  206. exit(1);
  207. };
  208. Conf.CPU = codegen::getMCPU();
  209. Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  210. Conf.MAttrs = codegen::getMAttrs();
  211. if (auto RM = codegen::getExplicitRelocModel())
  212. Conf.RelocModel = RM.getValue();
  213. Conf.CodeModel = codegen::getExplicitCodeModel();
  214. Conf.DebugPassManager = DebugPassManager;
  215. if (SaveTemps)
  216. check(Conf.addSaveTemps(OutputFilename + "."),
  217. "Config::addSaveTemps failed");
  218. // Optimization remarks.
  219. Conf.RemarksFilename = RemarksFilename;
  220. Conf.RemarksPasses = RemarksPasses;
  221. Conf.RemarksWithHotness = RemarksWithHotness;
  222. Conf.RemarksHotnessThreshold = RemarksHotnessThreshold;
  223. Conf.RemarksFormat = RemarksFormat;
  224. Conf.SampleProfile = SamplePGOFile;
  225. Conf.CSIRProfile = CSPGOFile;
  226. Conf.RunCSIRInstr = RunCSIRInstr;
  227. // Run a custom pipeline, if asked for.
  228. Conf.OptPipeline = OptPipeline;
  229. Conf.AAPipeline = AAPipeline;
  230. Conf.OptLevel = OptLevel - '0';
  231. Conf.UseNewPM = UseNewPM;
  232. Conf.Freestanding = EnableFreestanding;
  233. for (auto &PluginFN : PassPlugins)
  234. Conf.PassPlugins.push_back(PluginFN);
  235. switch (CGOptLevel) {
  236. case '0':
  237. Conf.CGOptLevel = CodeGenOpt::None;
  238. break;
  239. case '1':
  240. Conf.CGOptLevel = CodeGenOpt::Less;
  241. break;
  242. case '2':
  243. Conf.CGOptLevel = CodeGenOpt::Default;
  244. break;
  245. case '3':
  246. Conf.CGOptLevel = CodeGenOpt::Aggressive;
  247. break;
  248. default:
  249. llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
  250. return 1;
  251. }
  252. if (auto FT = codegen::getExplicitFileType())
  253. Conf.CGFileType = FT.getValue();
  254. Conf.OverrideTriple = OverrideTriple;
  255. Conf.DefaultTriple = DefaultTriple;
  256. Conf.StatsFile = StatsFile;
  257. Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
  258. Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
  259. ThinBackend Backend;
  260. if (ThinLTODistributedIndexes)
  261. Backend = createWriteIndexesThinBackend(/* OldPrefix */ "",
  262. /* NewPrefix */ "",
  263. /* ShouldEmitImportsFiles */ true,
  264. /* LinkedObjectsFile */ nullptr,
  265. /* OnWrite */ {});
  266. else
  267. Backend = createInProcessThinBackend(
  268. llvm::heavyweight_hardware_concurrency(Threads));
  269. LTO Lto(std::move(Conf), std::move(Backend));
  270. bool HasErrors = false;
  271. for (std::string F : InputFilenames) {
  272. std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
  273. std::unique_ptr<InputFile> Input =
  274. check(InputFile::create(MB->getMemBufferRef()), F);
  275. std::vector<SymbolResolution> Res;
  276. for (const InputFile::Symbol &Sym : Input->symbols()) {
  277. auto I = CommandLineResolutions.find({F, std::string(Sym.getName())});
  278. // If it isn't found, look for "$", which would have been added
  279. // (followed by a hash) when the symbol was promoted during module
  280. // splitting if it was defined in one part and used in the other.
  281. // Try looking up the symbol name before the "$".
  282. if (I == CommandLineResolutions.end()) {
  283. auto SplitName = Sym.getName().rsplit("$");
  284. I = CommandLineResolutions.find({F, std::string(SplitName.first)});
  285. }
  286. if (I == CommandLineResolutions.end()) {
  287. llvm::errs() << argv[0] << ": missing symbol resolution for " << F
  288. << ',' << Sym.getName() << '\n';
  289. HasErrors = true;
  290. } else {
  291. Res.push_back(I->second.front());
  292. I->second.pop_front();
  293. if (I->second.empty())
  294. CommandLineResolutions.erase(I);
  295. }
  296. }
  297. if (HasErrors)
  298. continue;
  299. MBs.push_back(std::move(MB));
  300. check(Lto.add(std::move(Input), Res), F);
  301. }
  302. if (!CommandLineResolutions.empty()) {
  303. HasErrors = true;
  304. for (auto UnusedRes : CommandLineResolutions)
  305. llvm::errs() << argv[0] << ": unused symbol resolution for "
  306. << UnusedRes.first.first << ',' << UnusedRes.first.second
  307. << '\n';
  308. }
  309. if (HasErrors)
  310. return 1;
  311. auto AddStream =
  312. [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
  313. std::string Path = OutputFilename + "." + utostr(Task);
  314. std::error_code EC;
  315. auto S = std::make_unique<raw_fd_ostream>(Path, EC, sys::fs::OF_None);
  316. check(EC, Path);
  317. return std::make_unique<lto::NativeObjectStream>(std::move(S));
  318. };
  319. auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
  320. *AddStream(Task)->OS << MB->getBuffer();
  321. };
  322. NativeObjectCache Cache;
  323. if (!CacheDir.empty())
  324. Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
  325. check(Lto.run(AddStream, Cache), "LTO::run failed");
  326. return 0;
  327. }
  328. static int dumpSymtab(int argc, char **argv) {
  329. for (StringRef F : make_range(argv + 1, argv + argc)) {
  330. std::unique_ptr<MemoryBuffer> MB =
  331. check(MemoryBuffer::getFile(F), std::string(F));
  332. BitcodeFileContents BFC =
  333. check(getBitcodeFileContents(*MB), std::string(F));
  334. if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
  335. auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
  336. BFC.Symtab.data());
  337. outs() << "version: " << Hdr->Version << '\n';
  338. if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
  339. outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab)
  340. << '\n';
  341. }
  342. std::unique_ptr<InputFile> Input =
  343. check(InputFile::create(MB->getMemBufferRef()), std::string(F));
  344. outs() << "target triple: " << Input->getTargetTriple() << '\n';
  345. Triple TT(Input->getTargetTriple());
  346. outs() << "source filename: " << Input->getSourceFileName() << '\n';
  347. if (TT.isOSBinFormatCOFF())
  348. outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
  349. if (TT.isOSBinFormatELF()) {
  350. outs() << "dependent libraries:";
  351. for (auto L : Input->getDependentLibraries())
  352. outs() << " \"" << L << "\"";
  353. outs() << '\n';
  354. }
  355. std::vector<StringRef> ComdatTable = Input->getComdatTable();
  356. for (const InputFile::Symbol &Sym : Input->symbols()) {
  357. switch (Sym.getVisibility()) {
  358. case GlobalValue::HiddenVisibility:
  359. outs() << 'H';
  360. break;
  361. case GlobalValue::ProtectedVisibility:
  362. outs() << 'P';
  363. break;
  364. case GlobalValue::DefaultVisibility:
  365. outs() << 'D';
  366. break;
  367. }
  368. auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
  369. PrintBool('U', Sym.isUndefined());
  370. PrintBool('C', Sym.isCommon());
  371. PrintBool('W', Sym.isWeak());
  372. PrintBool('I', Sym.isIndirect());
  373. PrintBool('O', Sym.canBeOmittedFromSymbolTable());
  374. PrintBool('T', Sym.isTLS());
  375. PrintBool('X', Sym.isExecutable());
  376. outs() << ' ' << Sym.getName() << '\n';
  377. if (Sym.isCommon())
  378. outs() << " size " << Sym.getCommonSize() << " align "
  379. << Sym.getCommonAlignment() << '\n';
  380. int Comdat = Sym.getComdatIndex();
  381. if (Comdat != -1)
  382. outs() << " comdat " << ComdatTable[Comdat] << '\n';
  383. if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
  384. outs() << " fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
  385. if (!Sym.getSectionName().empty())
  386. outs() << " section " << Sym.getSectionName() << "\n";
  387. }
  388. outs() << '\n';
  389. }
  390. return 0;
  391. }
  392. int main(int argc, char **argv) {
  393. InitLLVM X(argc, argv);
  394. InitializeAllTargets();
  395. InitializeAllTargetMCs();
  396. InitializeAllAsmPrinters();
  397. InitializeAllAsmParsers();
  398. // FIXME: This should use llvm::cl subcommands, but it isn't currently
  399. // possible to pass an argument not associated with a subcommand to a
  400. // subcommand (e.g. -use-new-pm).
  401. if (argc < 2)
  402. return usage();
  403. StringRef Subcommand = argv[1];
  404. // Ensure that argv[0] is correct after adjusting argv/argc.
  405. argv[1] = argv[0];
  406. if (Subcommand == "dump-symtab")
  407. return dumpSymtab(argc - 1, argv + 1);
  408. if (Subcommand == "run")
  409. return run(argc - 1, argv + 1);
  410. return usage();
  411. }