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