lto.cpp 23 KB

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