lto.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. //===-lto.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-c/lto.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/Bitcode/BitcodeReader.h"
  17. #include "llvm/CodeGen/CommandFlags.h"
  18. #include "llvm/IR/DiagnosticInfo.h"
  19. #include "llvm/IR/DiagnosticPrinter.h"
  20. #include "llvm/IR/LLVMContext.h"
  21. #include "llvm/LTO/LTO.h"
  22. #include "llvm/LTO/legacy/LTOCodeGenerator.h"
  23. #include "llvm/LTO/legacy/LTOModule.h"
  24. #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/Support/Signals.h"
  27. #include "llvm/Support/TargetSelect.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace llvm;
  30. static codegen::RegisterCodeGenFlags CGF;
  31. // extra command-line flags needed for LTOCodeGenerator
  32. static cl::opt<char>
  33. OptLevel("O",
  34. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  35. "(default = '-O2')"),
  36. cl::Prefix,
  37. cl::ZeroOrMore,
  38. cl::init('2'));
  39. static cl::opt<bool> EnableFreestanding(
  40. "lto-freestanding", cl::init(false),
  41. cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
  42. #ifdef NDEBUG
  43. static bool VerifyByDefault = false;
  44. #else
  45. static bool VerifyByDefault = true;
  46. #endif
  47. static cl::opt<bool> DisableVerify(
  48. "disable-llvm-verifier", cl::init(!VerifyByDefault),
  49. cl::desc("Don't run the LLVM verifier during the optimization pipeline"));
  50. // Holds most recent error string.
  51. // *** Not thread safe ***
  52. static std::string sLastErrorString;
  53. // Holds the initialization state of the LTO module.
  54. // *** Not thread safe ***
  55. static bool initialized = false;
  56. // Represent the state of parsing command line debug options.
  57. static enum class OptParsingState {
  58. NotParsed, // Initial state.
  59. Early, // After lto_set_debug_options is called.
  60. Done // After maybeParseOptions is called.
  61. } optionParsingState = OptParsingState::NotParsed;
  62. static LLVMContext *LTOContext = nullptr;
  63. struct LTOToolDiagnosticHandler : public DiagnosticHandler {
  64. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  65. if (DI.getSeverity() != DS_Error) {
  66. DiagnosticPrinterRawOStream DP(errs());
  67. DI.print(DP);
  68. errs() << '\n';
  69. return true;
  70. }
  71. sLastErrorString = "";
  72. {
  73. raw_string_ostream Stream(sLastErrorString);
  74. DiagnosticPrinterRawOStream DP(Stream);
  75. DI.print(DP);
  76. }
  77. return true;
  78. }
  79. };
  80. // Initialize the configured targets if they have not been initialized.
  81. static void lto_initialize() {
  82. if (!initialized) {
  83. #ifdef _WIN32
  84. // Dialog box on crash disabling doesn't work across DLL boundaries, so do
  85. // it here.
  86. llvm::sys::DisableSystemDialogsOnCrash();
  87. #endif
  88. InitializeAllTargetInfos();
  89. InitializeAllTargets();
  90. InitializeAllTargetMCs();
  91. InitializeAllAsmParsers();
  92. InitializeAllAsmPrinters();
  93. InitializeAllDisassemblers();
  94. static LLVMContext Context;
  95. LTOContext = &Context;
  96. LTOContext->setDiagnosticHandler(
  97. std::make_unique<LTOToolDiagnosticHandler>(), true);
  98. initialized = true;
  99. }
  100. }
  101. namespace {
  102. static void handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,
  103. const char *Msg, void *) {
  104. sLastErrorString = Msg;
  105. }
  106. // This derived class owns the native object file. This helps implement the
  107. // libLTO API semantics, which require that the code generator owns the object
  108. // file.
  109. struct LibLTOCodeGenerator : LTOCodeGenerator {
  110. LibLTOCodeGenerator() : LTOCodeGenerator(*LTOContext) { init(); }
  111. LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
  112. : LTOCodeGenerator(*Context), OwnedContext(std::move(Context)) {
  113. init();
  114. }
  115. // Reset the module first in case MergedModule is created in OwnedContext.
  116. // Module must be destructed before its context gets destructed.
  117. ~LibLTOCodeGenerator() { resetMergedModule(); }
  118. void init() { setDiagnosticHandler(handleLibLTODiagnostic, nullptr); }
  119. std::unique_ptr<MemoryBuffer> NativeObjectFile;
  120. std::unique_ptr<LLVMContext> OwnedContext;
  121. };
  122. }
  123. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
  124. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ThinLTOCodeGenerator, thinlto_code_gen_t)
  125. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
  126. // Convert the subtarget features into a string to pass to LTOCodeGenerator.
  127. static void lto_add_attrs(lto_code_gen_t cg) {
  128. LTOCodeGenerator *CG = unwrap(cg);
  129. CG->setAttrs(codegen::getMAttrs());
  130. if (OptLevel < '0' || OptLevel > '3')
  131. report_fatal_error("Optimization level must be between 0 and 3");
  132. CG->setOptLevel(OptLevel - '0');
  133. CG->setFreestanding(EnableFreestanding);
  134. CG->setDisableVerify(DisableVerify);
  135. }
  136. extern const char* lto_get_version() {
  137. return LTOCodeGenerator::getVersionString();
  138. }
  139. const char* lto_get_error_message() {
  140. return sLastErrorString.c_str();
  141. }
  142. bool lto_module_is_object_file(const char* path) {
  143. return LTOModule::isBitcodeFile(StringRef(path));
  144. }
  145. bool lto_module_is_object_file_for_target(const char* path,
  146. const char* target_triplet_prefix) {
  147. ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path);
  148. if (!Buffer)
  149. return false;
  150. return LTOModule::isBitcodeForTarget(Buffer->get(),
  151. StringRef(target_triplet_prefix));
  152. }
  153. bool lto_module_has_objc_category(const void *mem, size_t length) {
  154. std::unique_ptr<MemoryBuffer> Buffer(LTOModule::makeBuffer(mem, length));
  155. if (!Buffer)
  156. return false;
  157. LLVMContext Ctx;
  158. ErrorOr<bool> Result = expectedToErrorOrAndEmitErrors(
  159. Ctx, llvm::isBitcodeContainingObjCCategory(*Buffer));
  160. return Result && *Result;
  161. }
  162. bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
  163. return LTOModule::isBitcodeFile(mem, length);
  164. }
  165. bool
  166. lto_module_is_object_file_in_memory_for_target(const void* mem,
  167. size_t length,
  168. const char* target_triplet_prefix) {
  169. std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length));
  170. if (!buffer)
  171. return false;
  172. return LTOModule::isBitcodeForTarget(buffer.get(),
  173. StringRef(target_triplet_prefix));
  174. }
  175. lto_module_t lto_module_create(const char* path) {
  176. lto_initialize();
  177. llvm::TargetOptions Options =
  178. codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  179. ErrorOr<std::unique_ptr<LTOModule>> M =
  180. LTOModule::createFromFile(*LTOContext, StringRef(path), Options);
  181. if (!M)
  182. return nullptr;
  183. return wrap(M->release());
  184. }
  185. lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
  186. lto_initialize();
  187. llvm::TargetOptions Options =
  188. codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  189. ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFile(
  190. *LTOContext, fd, StringRef(path), size, Options);
  191. if (!M)
  192. return nullptr;
  193. return wrap(M->release());
  194. }
  195. lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
  196. size_t file_size,
  197. size_t map_size,
  198. off_t offset) {
  199. lto_initialize();
  200. llvm::TargetOptions Options =
  201. codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  202. ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFileSlice(
  203. *LTOContext, fd, StringRef(path), map_size, offset, Options);
  204. if (!M)
  205. return nullptr;
  206. return wrap(M->release());
  207. }
  208. lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
  209. lto_initialize();
  210. llvm::TargetOptions Options =
  211. codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  212. ErrorOr<std::unique_ptr<LTOModule>> M =
  213. LTOModule::createFromBuffer(*LTOContext, mem, length, Options);
  214. if (!M)
  215. return nullptr;
  216. return wrap(M->release());
  217. }
  218. lto_module_t lto_module_create_from_memory_with_path(const void* mem,
  219. size_t length,
  220. const char *path) {
  221. lto_initialize();
  222. llvm::TargetOptions Options =
  223. codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  224. ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
  225. *LTOContext, mem, length, Options, StringRef(path));
  226. if (!M)
  227. return nullptr;
  228. return wrap(M->release());
  229. }
  230. lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
  231. const char *path) {
  232. lto_initialize();
  233. llvm::TargetOptions Options =
  234. codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  235. // Create a local context. Ownership will be transferred to LTOModule.
  236. std::unique_ptr<LLVMContext> Context = std::make_unique<LLVMContext>();
  237. Context->setDiagnosticHandler(std::make_unique<LTOToolDiagnosticHandler>(),
  238. true);
  239. ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createInLocalContext(
  240. std::move(Context), mem, length, Options, StringRef(path));
  241. if (!M)
  242. return nullptr;
  243. return wrap(M->release());
  244. }
  245. lto_module_t lto_module_create_in_codegen_context(const void *mem,
  246. size_t length,
  247. const char *path,
  248. lto_code_gen_t cg) {
  249. lto_initialize();
  250. llvm::TargetOptions Options =
  251. codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  252. ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
  253. unwrap(cg)->getContext(), mem, length, Options, StringRef(path));
  254. return wrap(M->release());
  255. }
  256. void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
  257. const char* lto_module_get_target_triple(lto_module_t mod) {
  258. return unwrap(mod)->getTargetTriple().c_str();
  259. }
  260. void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
  261. return unwrap(mod)->setTargetTriple(StringRef(triple));
  262. }
  263. unsigned int lto_module_get_num_symbols(lto_module_t mod) {
  264. return unwrap(mod)->getSymbolCount();
  265. }
  266. const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
  267. return unwrap(mod)->getSymbolName(index).data();
  268. }
  269. lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
  270. unsigned int index) {
  271. return unwrap(mod)->getSymbolAttributes(index);
  272. }
  273. const char* lto_module_get_linkeropts(lto_module_t mod) {
  274. return unwrap(mod)->getLinkerOpts().data();
  275. }
  276. lto_bool_t lto_module_get_macho_cputype(lto_module_t mod,
  277. unsigned int *out_cputype,
  278. unsigned int *out_cpusubtype) {
  279. LTOModule *M = unwrap(mod);
  280. Expected<uint32_t> CPUType = M->getMachOCPUType();
  281. if (!CPUType) {
  282. sLastErrorString = toString(CPUType.takeError());
  283. return true;
  284. }
  285. *out_cputype = *CPUType;
  286. Expected<uint32_t> CPUSubType = M->getMachOCPUSubType();
  287. if (!CPUSubType) {
  288. sLastErrorString = toString(CPUSubType.takeError());
  289. return true;
  290. }
  291. *out_cpusubtype = *CPUSubType;
  292. return false;
  293. }
  294. void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
  295. lto_diagnostic_handler_t diag_handler,
  296. void *ctxt) {
  297. unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
  298. }
  299. static lto_code_gen_t createCodeGen(bool InLocalContext) {
  300. lto_initialize();
  301. TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  302. LibLTOCodeGenerator *CodeGen =
  303. InLocalContext ? new LibLTOCodeGenerator(std::make_unique<LLVMContext>())
  304. : new LibLTOCodeGenerator();
  305. CodeGen->setTargetOptions(Options);
  306. return wrap(CodeGen);
  307. }
  308. lto_code_gen_t lto_codegen_create(void) {
  309. return createCodeGen(/* InLocalContext */ false);
  310. }
  311. lto_code_gen_t lto_codegen_create_in_local_context(void) {
  312. return createCodeGen(/* InLocalContext */ true);
  313. }
  314. void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
  315. bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
  316. return !unwrap(cg)->addModule(unwrap(mod));
  317. }
  318. void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
  319. unwrap(cg)->setModule(std::unique_ptr<LTOModule>(unwrap(mod)));
  320. }
  321. bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
  322. unwrap(cg)->setDebugInfo(debug);
  323. return false;
  324. }
  325. bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
  326. switch (model) {
  327. case LTO_CODEGEN_PIC_MODEL_STATIC:
  328. unwrap(cg)->setCodePICModel(Reloc::Static);
  329. return false;
  330. case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
  331. unwrap(cg)->setCodePICModel(Reloc::PIC_);
  332. return false;
  333. case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
  334. unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
  335. return false;
  336. case LTO_CODEGEN_PIC_MODEL_DEFAULT:
  337. unwrap(cg)->setCodePICModel(None);
  338. return false;
  339. }
  340. sLastErrorString = "Unknown PIC model";
  341. return true;
  342. }
  343. void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
  344. return unwrap(cg)->setCpu(cpu);
  345. }
  346. void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
  347. // In here only for backwards compatibility. We use MC now.
  348. }
  349. void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
  350. int nargs) {
  351. // In here only for backwards compatibility. We use MC now.
  352. }
  353. void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
  354. const char *symbol) {
  355. unwrap(cg)->addMustPreserveSymbol(symbol);
  356. }
  357. static void maybeParseOptions(lto_code_gen_t cg) {
  358. if (optionParsingState != OptParsingState::Done) {
  359. // Parse options if any were set by the lto_codegen_debug_options* function.
  360. unwrap(cg)->parseCodeGenDebugOptions();
  361. lto_add_attrs(cg);
  362. optionParsingState = OptParsingState::Done;
  363. }
  364. }
  365. bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
  366. maybeParseOptions(cg);
  367. return !unwrap(cg)->writeMergedModules(path);
  368. }
  369. const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
  370. maybeParseOptions(cg);
  371. LibLTOCodeGenerator *CG = unwrap(cg);
  372. CG->NativeObjectFile = CG->compile();
  373. if (!CG->NativeObjectFile)
  374. return nullptr;
  375. *length = CG->NativeObjectFile->getBufferSize();
  376. return CG->NativeObjectFile->getBufferStart();
  377. }
  378. bool lto_codegen_optimize(lto_code_gen_t cg) {
  379. maybeParseOptions(cg);
  380. return !unwrap(cg)->optimize();
  381. }
  382. const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
  383. maybeParseOptions(cg);
  384. LibLTOCodeGenerator *CG = unwrap(cg);
  385. CG->NativeObjectFile = CG->compileOptimized();
  386. if (!CG->NativeObjectFile)
  387. return nullptr;
  388. *length = CG->NativeObjectFile->getBufferSize();
  389. return CG->NativeObjectFile->getBufferStart();
  390. }
  391. bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
  392. maybeParseOptions(cg);
  393. return !unwrap(cg)->compile_to_file(name);
  394. }
  395. void lto_set_debug_options(const char *const *options, int number) {
  396. assert(optionParsingState == OptParsingState::NotParsed &&
  397. "option processing already happened");
  398. // Need to put each suboption in a null-terminated string before passing to
  399. // parseCommandLineOptions().
  400. std::vector<std::string> Options;
  401. for (int i = 0; i < number; ++i)
  402. Options.push_back(options[i]);
  403. llvm::parseCommandLineOptions(Options);
  404. optionParsingState = OptParsingState::Early;
  405. }
  406. void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
  407. assert(optionParsingState != OptParsingState::Early &&
  408. "early option processing already happened");
  409. SmallVector<StringRef, 4> Options;
  410. for (std::pair<StringRef, StringRef> o = getToken(opt); !o.first.empty();
  411. o = getToken(o.second))
  412. Options.push_back(o.first);
  413. unwrap(cg)->setCodeGenDebugOptions(Options);
  414. }
  415. void lto_codegen_debug_options_array(lto_code_gen_t cg,
  416. const char *const *options, int number) {
  417. assert(optionParsingState != OptParsingState::Early &&
  418. "early option processing already happened");
  419. SmallVector<StringRef, 4> Options;
  420. for (int i = 0; i < number; ++i)
  421. Options.push_back(options[i]);
  422. unwrap(cg)->setCodeGenDebugOptions(makeArrayRef(Options));
  423. }
  424. unsigned int lto_api_version() { return LTO_API_VERSION; }
  425. void lto_codegen_set_should_internalize(lto_code_gen_t cg,
  426. bool ShouldInternalize) {
  427. unwrap(cg)->setShouldInternalize(ShouldInternalize);
  428. }
  429. void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
  430. lto_bool_t ShouldEmbedUselists) {
  431. unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);
  432. }
  433. lto_bool_t lto_module_has_ctor_dtor(lto_module_t mod) {
  434. return unwrap(mod)->hasCtorDtor();
  435. }
  436. // ThinLTO API below
  437. thinlto_code_gen_t thinlto_create_codegen(void) {
  438. lto_initialize();
  439. ThinLTOCodeGenerator *CodeGen = new ThinLTOCodeGenerator();
  440. CodeGen->setTargetOptions(
  441. codegen::InitTargetOptionsFromCodeGenFlags(Triple()));
  442. CodeGen->setFreestanding(EnableFreestanding);
  443. if (OptLevel.getNumOccurrences()) {
  444. if (OptLevel < '0' || OptLevel > '3')
  445. report_fatal_error("Optimization level must be between 0 and 3");
  446. CodeGen->setOptLevel(OptLevel - '0');
  447. switch (OptLevel) {
  448. case '0':
  449. CodeGen->setCodeGenOptLevel(CodeGenOpt::None);
  450. break;
  451. case '1':
  452. CodeGen->setCodeGenOptLevel(CodeGenOpt::Less);
  453. break;
  454. case '2':
  455. CodeGen->setCodeGenOptLevel(CodeGenOpt::Default);
  456. break;
  457. case '3':
  458. CodeGen->setCodeGenOptLevel(CodeGenOpt::Aggressive);
  459. break;
  460. }
  461. }
  462. return wrap(CodeGen);
  463. }
  464. void thinlto_codegen_dispose(thinlto_code_gen_t cg) { delete unwrap(cg); }
  465. void thinlto_codegen_add_module(thinlto_code_gen_t cg, const char *Identifier,
  466. const char *Data, int Length) {
  467. unwrap(cg)->addModule(Identifier, StringRef(Data, Length));
  468. }
  469. void thinlto_codegen_process(thinlto_code_gen_t cg) { unwrap(cg)->run(); }
  470. unsigned int thinlto_module_get_num_objects(thinlto_code_gen_t cg) {
  471. return unwrap(cg)->getProducedBinaries().size();
  472. }
  473. LTOObjectBuffer thinlto_module_get_object(thinlto_code_gen_t cg,
  474. unsigned int index) {
  475. assert(index < unwrap(cg)->getProducedBinaries().size() && "Index overflow");
  476. auto &MemBuffer = unwrap(cg)->getProducedBinaries()[index];
  477. return LTOObjectBuffer{MemBuffer->getBufferStart(),
  478. MemBuffer->getBufferSize()};
  479. }
  480. unsigned int thinlto_module_get_num_object_files(thinlto_code_gen_t cg) {
  481. return unwrap(cg)->getProducedBinaryFiles().size();
  482. }
  483. const char *thinlto_module_get_object_file(thinlto_code_gen_t cg,
  484. unsigned int index) {
  485. assert(index < unwrap(cg)->getProducedBinaryFiles().size() &&
  486. "Index overflow");
  487. return unwrap(cg)->getProducedBinaryFiles()[index].c_str();
  488. }
  489. void thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,
  490. lto_bool_t disable) {
  491. unwrap(cg)->disableCodeGen(disable);
  492. }
  493. void thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,
  494. lto_bool_t CodeGenOnly) {
  495. unwrap(cg)->setCodeGenOnly(CodeGenOnly);
  496. }
  497. void thinlto_debug_options(const char *const *options, int number) {
  498. // if options were requested, set them
  499. if (number && options) {
  500. std::vector<const char *> CodegenArgv(1, "libLTO");
  501. append_range(CodegenArgv, ArrayRef<const char *>(options, number));
  502. cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
  503. }
  504. }
  505. lto_bool_t lto_module_is_thinlto(lto_module_t mod) {
  506. return unwrap(mod)->isThinLTO();
  507. }
  508. void thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,
  509. const char *Name, int Length) {
  510. unwrap(cg)->preserveSymbol(StringRef(Name, Length));
  511. }
  512. void thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,
  513. const char *Name, int Length) {
  514. unwrap(cg)->crossReferenceSymbol(StringRef(Name, Length));
  515. }
  516. void thinlto_codegen_set_cpu(thinlto_code_gen_t cg, const char *cpu) {
  517. return unwrap(cg)->setCpu(cpu);
  518. }
  519. void thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,
  520. const char *cache_dir) {
  521. return unwrap(cg)->setCacheDir(cache_dir);
  522. }
  523. void thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,
  524. int interval) {
  525. return unwrap(cg)->setCachePruningInterval(interval);
  526. }
  527. void thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,
  528. unsigned expiration) {
  529. return unwrap(cg)->setCacheEntryExpiration(expiration);
  530. }
  531. void thinlto_codegen_set_final_cache_size_relative_to_available_space(
  532. thinlto_code_gen_t cg, unsigned Percentage) {
  533. return unwrap(cg)->setMaxCacheSizeRelativeToAvailableSpace(Percentage);
  534. }
  535. void thinlto_codegen_set_cache_size_bytes(
  536. thinlto_code_gen_t cg, unsigned MaxSizeBytes) {
  537. return unwrap(cg)->setCacheMaxSizeBytes(MaxSizeBytes);
  538. }
  539. void thinlto_codegen_set_cache_size_megabytes(
  540. thinlto_code_gen_t cg, unsigned MaxSizeMegabytes) {
  541. uint64_t MaxSizeBytes = MaxSizeMegabytes;
  542. MaxSizeBytes *= 1024 * 1024;
  543. return unwrap(cg)->setCacheMaxSizeBytes(MaxSizeBytes);
  544. }
  545. void thinlto_codegen_set_cache_size_files(
  546. thinlto_code_gen_t cg, unsigned MaxSizeFiles) {
  547. return unwrap(cg)->setCacheMaxSizeFiles(MaxSizeFiles);
  548. }
  549. void thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,
  550. const char *save_temps_dir) {
  551. return unwrap(cg)->setSaveTempsDir(save_temps_dir);
  552. }
  553. void thinlto_set_generated_objects_dir(thinlto_code_gen_t cg,
  554. const char *save_temps_dir) {
  555. unwrap(cg)->setGeneratedObjectsDirectory(save_temps_dir);
  556. }
  557. lto_bool_t thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,
  558. lto_codegen_model model) {
  559. switch (model) {
  560. case LTO_CODEGEN_PIC_MODEL_STATIC:
  561. unwrap(cg)->setCodePICModel(Reloc::Static);
  562. return false;
  563. case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
  564. unwrap(cg)->setCodePICModel(Reloc::PIC_);
  565. return false;
  566. case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
  567. unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
  568. return false;
  569. case LTO_CODEGEN_PIC_MODEL_DEFAULT:
  570. unwrap(cg)->setCodePICModel(None);
  571. return false;
  572. }
  573. sLastErrorString = "Unknown PIC model";
  574. return true;
  575. }
  576. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(lto::InputFile, lto_input_t)
  577. lto_input_t lto_input_create(const void *buffer, size_t buffer_size, const char *path) {
  578. return wrap(LTOModule::createInputFile(buffer, buffer_size, path, sLastErrorString));
  579. }
  580. void lto_input_dispose(lto_input_t input) {
  581. delete unwrap(input);
  582. }
  583. extern unsigned lto_input_get_num_dependent_libraries(lto_input_t input) {
  584. return LTOModule::getDependentLibraryCount(unwrap(input));
  585. }
  586. extern const char *lto_input_get_dependent_library(lto_input_t input,
  587. size_t index,
  588. size_t *size) {
  589. return LTOModule::getDependentLibrary(unwrap(input), index, size);
  590. }
  591. extern const char *const *lto_runtime_lib_symbols_list(size_t *size) {
  592. auto symbols = lto::LTO::getRuntimeLibcallSymbols();
  593. *size = symbols.size();
  594. return symbols.data();
  595. }