xref: /llvm-project-15.0.7/llvm/tools/lto/lto.cpp (revision d86a206f)
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 
31 using namespace llvm;
32 
33 static codegen::RegisterCodeGenFlags CGF;
34 
35 // extra command-line flags needed for LTOCodeGenerator
36 static cl::opt<char>
37     OptLevel("O",
38              cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
39                       "(default = '-O2')"),
40              cl::Prefix, cl::init('2'));
41 
42 static cl::opt<bool> EnableFreestanding(
43     "lto-freestanding", cl::init(false),
44     cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
45 
46 #ifdef NDEBUG
47 static bool VerifyByDefault = false;
48 #else
49 static bool VerifyByDefault = true;
50 #endif
51 
52 static cl::opt<bool> DisableVerify(
53     "disable-llvm-verifier", cl::init(!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 ***
58 static std::string sLastErrorString;
59 
60 // Holds the initialization state of the LTO module.
61 // *** Not thread safe ***
62 static bool initialized = false;
63 
64 // Represent the state of parsing command line debug options.
65 static 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 
71 static LLVMContext *LTOContext = nullptr;
72 
73 struct LTOToolDiagnosticHandler : public DiagnosticHandler {
handleDiagnosticsLTOToolDiagnosticHandler74   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.
lto_initialize()92 static 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         std::make_unique<LTOToolDiagnosticHandler>(), true);
111     initialized = true;
112   }
113 }
114 
115 namespace {
116 
handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,const char * Msg,void *)117 static 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.
125 struct LibLTOCodeGenerator : LTOCodeGenerator {
LibLTOCodeGenerator__anond18e8ca70111::LibLTOCodeGenerator126   LibLTOCodeGenerator() : LTOCodeGenerator(*LTOContext) { init(); }
LibLTOCodeGenerator__anond18e8ca70111::LibLTOCodeGenerator127   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.
~LibLTOCodeGenerator__anond18e8ca70111::LibLTOCodeGenerator134   ~LibLTOCodeGenerator() { resetMergedModule(); }
135 
init__anond18e8ca70111::LibLTOCodeGenerator136   void init() { setDiagnosticHandler(handleLibLTODiagnostic, nullptr); }
137 
138   std::unique_ptr<MemoryBuffer> NativeObjectFile;
139   std::unique_ptr<LLVMContext> OwnedContext;
140 };
141 
142 }
143 
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator,lto_code_gen_t)144 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
145 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ThinLTOCodeGenerator, thinlto_code_gen_t)
146 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
147 
148 // Convert the subtarget features into a string to pass to LTOCodeGenerator.
149 static void lto_add_attrs(lto_code_gen_t cg) {
150   LTOCodeGenerator *CG = unwrap(cg);
151   CG->setAttrs(codegen::getMAttrs());
152 
153   if (OptLevel < '0' || OptLevel > '3')
154     report_fatal_error("Optimization level must be between 0 and 3");
155   CG->setOptLevel(OptLevel - '0');
156   CG->setFreestanding(EnableFreestanding);
157   CG->setDisableVerify(DisableVerify);
158 }
159 
lto_get_version()160 extern const char* lto_get_version() {
161   return LTOCodeGenerator::getVersionString();
162 }
163 
lto_get_error_message()164 const char* lto_get_error_message() {
165   return sLastErrorString.c_str();
166 }
167 
lto_module_is_object_file(const char * path)168 bool lto_module_is_object_file(const char* path) {
169   return LTOModule::isBitcodeFile(StringRef(path));
170 }
171 
lto_module_is_object_file_for_target(const char * path,const char * target_triplet_prefix)172 bool 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(path);
175   if (!Buffer)
176     return false;
177   return LTOModule::isBitcodeForTarget(Buffer->get(),
178                                        StringRef(target_triplet_prefix));
179 }
180 
lto_module_has_objc_category(const void * mem,size_t length)181 bool 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, llvm::isBitcodeContainingObjCCategory(*Buffer));
188   return Result && *Result;
189 }
190 
lto_module_is_object_file_in_memory(const void * mem,size_t length)191 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
192   return LTOModule::isBitcodeFile(mem, length);
193 }
194 
195 bool
lto_module_is_object_file_in_memory_for_target(const void * mem,size_t length,const char * target_triplet_prefix)196 lto_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(buffer.get(),
203                                        StringRef(target_triplet_prefix));
204 }
205 
lto_module_create(const char * path)206 lto_module_t lto_module_create(const char* path) {
207   lto_initialize();
208   llvm::TargetOptions Options =
209       codegen::InitTargetOptionsFromCodeGenFlags(Triple());
210   ErrorOr<std::unique_ptr<LTOModule>> M =
211       LTOModule::createFromFile(*LTOContext, StringRef(path), Options);
212   if (!M)
213     return nullptr;
214   return wrap(M->release());
215 }
216 
lto_module_create_from_fd(int fd,const char * path,size_t size)217 lto_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(Triple());
221   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFile(
222       *LTOContext, fd, StringRef(path), size, Options);
223   if (!M)
224     return nullptr;
225   return wrap(M->release());
226 }
227 
lto_module_create_from_fd_at_offset(int fd,const char * path,size_t file_size,size_t map_size,off_t offset)228 lto_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(Triple());
235   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromOpenFileSlice(
236       *LTOContext, fd, StringRef(path), map_size, offset, Options);
237   if (!M)
238     return nullptr;
239   return wrap(M->release());
240 }
241 
lto_module_create_from_memory(const void * mem,size_t length)242 lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
243   lto_initialize();
244   llvm::TargetOptions Options =
245       codegen::InitTargetOptionsFromCodeGenFlags(Triple());
246   ErrorOr<std::unique_ptr<LTOModule>> M =
247       LTOModule::createFromBuffer(*LTOContext, mem, length, Options);
248   if (!M)
249     return nullptr;
250   return wrap(M->release());
251 }
252 
lto_module_create_from_memory_with_path(const void * mem,size_t length,const char * path)253 lto_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(Triple());
259   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
260       *LTOContext, mem, length, Options, StringRef(path));
261   if (!M)
262     return nullptr;
263   return wrap(M->release());
264 }
265 
lto_module_create_in_local_context(const void * mem,size_t length,const char * path)266 lto_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(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(std::make_unique<LTOToolDiagnosticHandler>(),
275                                 true);
276 
277   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createInLocalContext(
278       std::move(Context), mem, length, Options, StringRef(path));
279   if (!M)
280     return nullptr;
281   return wrap(M->release());
282 }
283 
lto_module_create_in_codegen_context(const void * mem,size_t length,const char * path,lto_code_gen_t cg)284 lto_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(Triple());
291   ErrorOr<std::unique_ptr<LTOModule>> M = LTOModule::createFromBuffer(
292       unwrap(cg)->getContext(), mem, length, Options, StringRef(path));
293   return wrap(M->release());
294 }
295 
lto_module_dispose(lto_module_t mod)296 void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
297 
lto_module_get_target_triple(lto_module_t mod)298 const char* lto_module_get_target_triple(lto_module_t mod) {
299   return unwrap(mod)->getTargetTriple().c_str();
300 }
301 
lto_module_set_target_triple(lto_module_t mod,const char * triple)302 void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
303   return unwrap(mod)->setTargetTriple(StringRef(triple));
304 }
305 
lto_module_get_num_symbols(lto_module_t mod)306 unsigned int lto_module_get_num_symbols(lto_module_t mod) {
307   return unwrap(mod)->getSymbolCount();
308 }
309 
lto_module_get_symbol_name(lto_module_t mod,unsigned int index)310 const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
311   return unwrap(mod)->getSymbolName(index).data();
312 }
313 
lto_module_get_symbol_attribute(lto_module_t mod,unsigned int index)314 lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
315                                                       unsigned int index) {
316   return unwrap(mod)->getSymbolAttributes(index);
317 }
318 
lto_module_get_linkeropts(lto_module_t mod)319 const char* lto_module_get_linkeropts(lto_module_t mod) {
320   return unwrap(mod)->getLinkerOpts().data();
321 }
322 
lto_module_get_macho_cputype(lto_module_t mod,unsigned int * out_cputype,unsigned int * out_cpusubtype)323 lto_bool_t lto_module_get_macho_cputype(lto_module_t mod,
324                                         unsigned int *out_cputype,
325                                         unsigned int *out_cpusubtype) {
326   LTOModule *M = unwrap(mod);
327   Expected<uint32_t> CPUType = M->getMachOCPUType();
328   if (!CPUType) {
329     sLastErrorString = toString(CPUType.takeError());
330     return true;
331   }
332   *out_cputype = *CPUType;
333 
334   Expected<uint32_t> CPUSubType = M->getMachOCPUSubType();
335   if (!CPUSubType) {
336     sLastErrorString = toString(CPUSubType.takeError());
337     return true;
338   }
339   *out_cpusubtype = *CPUSubType;
340 
341   return false;
342 }
343 
lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,lto_diagnostic_handler_t diag_handler,void * ctxt)344 void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
345                                         lto_diagnostic_handler_t diag_handler,
346                                         void *ctxt) {
347   unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
348 }
349 
createCodeGen(bool InLocalContext)350 static lto_code_gen_t createCodeGen(bool InLocalContext) {
351   lto_initialize();
352 
353   TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
354 
355   LibLTOCodeGenerator *CodeGen =
356       InLocalContext ? new LibLTOCodeGenerator(std::make_unique<LLVMContext>())
357                      : new LibLTOCodeGenerator();
358   CodeGen->setTargetOptions(Options);
359   return wrap(CodeGen);
360 }
361 
lto_codegen_create(void)362 lto_code_gen_t lto_codegen_create(void) {
363   return createCodeGen(/* InLocalContext */ false);
364 }
365 
lto_codegen_create_in_local_context(void)366 lto_code_gen_t lto_codegen_create_in_local_context(void) {
367   return createCodeGen(/* InLocalContext */ true);
368 }
369 
lto_codegen_dispose(lto_code_gen_t cg)370 void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
371 
lto_codegen_add_module(lto_code_gen_t cg,lto_module_t mod)372 bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
373   return !unwrap(cg)->addModule(unwrap(mod));
374 }
375 
lto_codegen_set_module(lto_code_gen_t cg,lto_module_t mod)376 void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
377   unwrap(cg)->setModule(std::unique_ptr<LTOModule>(unwrap(mod)));
378 }
379 
lto_codegen_set_debug_model(lto_code_gen_t cg,lto_debug_model debug)380 bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
381   unwrap(cg)->setDebugInfo(debug);
382   return false;
383 }
384 
lto_codegen_set_pic_model(lto_code_gen_t cg,lto_codegen_model model)385 bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
386   switch (model) {
387   case LTO_CODEGEN_PIC_MODEL_STATIC:
388     unwrap(cg)->setCodePICModel(Reloc::Static);
389     return false;
390   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
391     unwrap(cg)->setCodePICModel(Reloc::PIC_);
392     return false;
393   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
394     unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
395     return false;
396   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
397     unwrap(cg)->setCodePICModel(None);
398     return false;
399   }
400   sLastErrorString = "Unknown PIC model";
401   return true;
402 }
403 
lto_codegen_set_cpu(lto_code_gen_t cg,const char * cpu)404 void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
405   return unwrap(cg)->setCpu(cpu);
406 }
407 
lto_codegen_set_assembler_path(lto_code_gen_t cg,const char * path)408 void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
409   // In here only for backwards compatibility. We use MC now.
410 }
411 
lto_codegen_set_assembler_args(lto_code_gen_t cg,const char ** args,int nargs)412 void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
413                                     int nargs) {
414   // In here only for backwards compatibility. We use MC now.
415 }
416 
lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,const char * symbol)417 void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
418                                           const char *symbol) {
419   unwrap(cg)->addMustPreserveSymbol(symbol);
420 }
421 
maybeParseOptions(lto_code_gen_t cg)422 static void maybeParseOptions(lto_code_gen_t cg) {
423   if (optionParsingState != OptParsingState::Done) {
424     // Parse options if any were set by the lto_codegen_debug_options* function.
425     unwrap(cg)->parseCodeGenDebugOptions();
426     lto_add_attrs(cg);
427     optionParsingState = OptParsingState::Done;
428   }
429 }
430 
lto_codegen_write_merged_modules(lto_code_gen_t cg,const char * path)431 bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
432   maybeParseOptions(cg);
433   return !unwrap(cg)->writeMergedModules(path);
434 }
435 
lto_codegen_compile(lto_code_gen_t cg,size_t * length)436 const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
437   maybeParseOptions(cg);
438   LibLTOCodeGenerator *CG = unwrap(cg);
439   CG->NativeObjectFile = CG->compile();
440   if (!CG->NativeObjectFile)
441     return nullptr;
442   *length = CG->NativeObjectFile->getBufferSize();
443   return CG->NativeObjectFile->getBufferStart();
444 }
445 
lto_codegen_optimize(lto_code_gen_t cg)446 bool lto_codegen_optimize(lto_code_gen_t cg) {
447   maybeParseOptions(cg);
448   return !unwrap(cg)->optimize();
449 }
450 
lto_codegen_compile_optimized(lto_code_gen_t cg,size_t * length)451 const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
452   maybeParseOptions(cg);
453   LibLTOCodeGenerator *CG = unwrap(cg);
454   CG->NativeObjectFile = CG->compileOptimized();
455   if (!CG->NativeObjectFile)
456     return nullptr;
457   *length = CG->NativeObjectFile->getBufferSize();
458   return CG->NativeObjectFile->getBufferStart();
459 }
460 
lto_codegen_compile_to_file(lto_code_gen_t cg,const char ** name)461 bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
462   maybeParseOptions(cg);
463   return !unwrap(cg)->compile_to_file(name);
464 }
465 
lto_set_debug_options(const char * const * options,int number)466 void lto_set_debug_options(const char *const *options, int number) {
467   assert(optionParsingState == OptParsingState::NotParsed &&
468          "option processing already happened");
469   // Need to put each suboption in a null-terminated string before passing to
470   // parseCommandLineOptions().
471   std::vector<std::string> Options;
472   for (int i = 0; i < number; ++i)
473     Options.push_back(options[i]);
474 
475   llvm::parseCommandLineOptions(Options);
476   optionParsingState = OptParsingState::Early;
477 }
478 
lto_codegen_debug_options(lto_code_gen_t cg,const char * opt)479 void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
480   assert(optionParsingState != OptParsingState::Early &&
481          "early option processing already happened");
482   SmallVector<StringRef, 4> Options;
483   for (std::pair<StringRef, StringRef> o = getToken(opt); !o.first.empty();
484        o = getToken(o.second))
485     Options.push_back(o.first);
486 
487   unwrap(cg)->setCodeGenDebugOptions(Options);
488 }
489 
lto_codegen_debug_options_array(lto_code_gen_t cg,const char * const * options,int number)490 void lto_codegen_debug_options_array(lto_code_gen_t cg,
491                                      const char *const *options, int number) {
492   assert(optionParsingState != OptParsingState::Early &&
493          "early option processing already happened");
494   SmallVector<StringRef, 4> Options;
495   for (int i = 0; i < number; ++i)
496     Options.push_back(options[i]);
497   unwrap(cg)->setCodeGenDebugOptions(makeArrayRef(Options));
498 }
499 
lto_api_version()500 unsigned int lto_api_version() { return LTO_API_VERSION; }
501 
lto_codegen_set_should_internalize(lto_code_gen_t cg,bool ShouldInternalize)502 void lto_codegen_set_should_internalize(lto_code_gen_t cg,
503                                         bool ShouldInternalize) {
504   unwrap(cg)->setShouldInternalize(ShouldInternalize);
505 }
506 
lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,lto_bool_t ShouldEmbedUselists)507 void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
508                                            lto_bool_t ShouldEmbedUselists) {
509   unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);
510 }
511 
lto_module_has_ctor_dtor(lto_module_t mod)512 lto_bool_t lto_module_has_ctor_dtor(lto_module_t mod) {
513   return unwrap(mod)->hasCtorDtor();
514 }
515 
516 // ThinLTO API below
517 
thinlto_create_codegen(void)518 thinlto_code_gen_t thinlto_create_codegen(void) {
519   lto_initialize();
520   ThinLTOCodeGenerator *CodeGen = new ThinLTOCodeGenerator();
521   CodeGen->setTargetOptions(
522       codegen::InitTargetOptionsFromCodeGenFlags(Triple()));
523   CodeGen->setFreestanding(EnableFreestanding);
524 
525   if (OptLevel.getNumOccurrences()) {
526     if (OptLevel < '0' || OptLevel > '3')
527       report_fatal_error("Optimization level must be between 0 and 3");
528     CodeGen->setOptLevel(OptLevel - '0');
529     switch (OptLevel) {
530     case '0':
531       CodeGen->setCodeGenOptLevel(CodeGenOpt::None);
532       break;
533     case '1':
534       CodeGen->setCodeGenOptLevel(CodeGenOpt::Less);
535       break;
536     case '2':
537       CodeGen->setCodeGenOptLevel(CodeGenOpt::Default);
538       break;
539     case '3':
540       CodeGen->setCodeGenOptLevel(CodeGenOpt::Aggressive);
541       break;
542     }
543   }
544   return wrap(CodeGen);
545 }
546 
thinlto_codegen_dispose(thinlto_code_gen_t cg)547 void thinlto_codegen_dispose(thinlto_code_gen_t cg) { delete unwrap(cg); }
548 
thinlto_codegen_add_module(thinlto_code_gen_t cg,const char * Identifier,const char * Data,int Length)549 void thinlto_codegen_add_module(thinlto_code_gen_t cg, const char *Identifier,
550                                 const char *Data, int Length) {
551   unwrap(cg)->addModule(Identifier, StringRef(Data, Length));
552 }
553 
thinlto_codegen_process(thinlto_code_gen_t cg)554 void thinlto_codegen_process(thinlto_code_gen_t cg) { unwrap(cg)->run(); }
555 
thinlto_module_get_num_objects(thinlto_code_gen_t cg)556 unsigned int thinlto_module_get_num_objects(thinlto_code_gen_t cg) {
557   return unwrap(cg)->getProducedBinaries().size();
558 }
thinlto_module_get_object(thinlto_code_gen_t cg,unsigned int index)559 LTOObjectBuffer thinlto_module_get_object(thinlto_code_gen_t cg,
560                                           unsigned int index) {
561   assert(index < unwrap(cg)->getProducedBinaries().size() && "Index overflow");
562   auto &MemBuffer = unwrap(cg)->getProducedBinaries()[index];
563   return LTOObjectBuffer{MemBuffer->getBufferStart(),
564                          MemBuffer->getBufferSize()};
565 }
566 
thinlto_module_get_num_object_files(thinlto_code_gen_t cg)567 unsigned int thinlto_module_get_num_object_files(thinlto_code_gen_t cg) {
568   return unwrap(cg)->getProducedBinaryFiles().size();
569 }
thinlto_module_get_object_file(thinlto_code_gen_t cg,unsigned int index)570 const char *thinlto_module_get_object_file(thinlto_code_gen_t cg,
571                                            unsigned int index) {
572   assert(index < unwrap(cg)->getProducedBinaryFiles().size() &&
573          "Index overflow");
574   return unwrap(cg)->getProducedBinaryFiles()[index].c_str();
575 }
576 
thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,lto_bool_t disable)577 void thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,
578                                      lto_bool_t disable) {
579   unwrap(cg)->disableCodeGen(disable);
580 }
581 
thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,lto_bool_t CodeGenOnly)582 void thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,
583                                       lto_bool_t CodeGenOnly) {
584   unwrap(cg)->setCodeGenOnly(CodeGenOnly);
585 }
586 
thinlto_debug_options(const char * const * options,int number)587 void thinlto_debug_options(const char *const *options, int number) {
588   // if options were requested, set them
589   if (number && options) {
590     std::vector<const char *> CodegenArgv(1, "libLTO");
591     append_range(CodegenArgv, ArrayRef<const char *>(options, number));
592     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
593   }
594 }
595 
lto_module_is_thinlto(lto_module_t mod)596 lto_bool_t lto_module_is_thinlto(lto_module_t mod) {
597   return unwrap(mod)->isThinLTO();
598 }
599 
thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,const char * Name,int Length)600 void thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,
601                                               const char *Name, int Length) {
602   unwrap(cg)->preserveSymbol(StringRef(Name, Length));
603 }
604 
thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,const char * Name,int Length)605 void thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,
606                                                  const char *Name, int Length) {
607   unwrap(cg)->crossReferenceSymbol(StringRef(Name, Length));
608 }
609 
thinlto_codegen_set_cpu(thinlto_code_gen_t cg,const char * cpu)610 void thinlto_codegen_set_cpu(thinlto_code_gen_t cg, const char *cpu) {
611   return unwrap(cg)->setCpu(cpu);
612 }
613 
thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,const char * cache_dir)614 void thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,
615                                    const char *cache_dir) {
616   return unwrap(cg)->setCacheDir(cache_dir);
617 }
618 
thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,int interval)619 void thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,
620                                                 int interval) {
621   return unwrap(cg)->setCachePruningInterval(interval);
622 }
623 
thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,unsigned expiration)624 void thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,
625                                                 unsigned expiration) {
626   return unwrap(cg)->setCacheEntryExpiration(expiration);
627 }
628 
thinlto_codegen_set_final_cache_size_relative_to_available_space(thinlto_code_gen_t cg,unsigned Percentage)629 void thinlto_codegen_set_final_cache_size_relative_to_available_space(
630     thinlto_code_gen_t cg, unsigned Percentage) {
631   return unwrap(cg)->setMaxCacheSizeRelativeToAvailableSpace(Percentage);
632 }
633 
thinlto_codegen_set_cache_size_bytes(thinlto_code_gen_t cg,unsigned MaxSizeBytes)634 void thinlto_codegen_set_cache_size_bytes(
635     thinlto_code_gen_t cg, unsigned MaxSizeBytes) {
636   return unwrap(cg)->setCacheMaxSizeBytes(MaxSizeBytes);
637 }
638 
thinlto_codegen_set_cache_size_megabytes(thinlto_code_gen_t cg,unsigned MaxSizeMegabytes)639 void thinlto_codegen_set_cache_size_megabytes(
640     thinlto_code_gen_t cg, unsigned MaxSizeMegabytes) {
641   uint64_t MaxSizeBytes = MaxSizeMegabytes;
642   MaxSizeBytes *= 1024 * 1024;
643   return unwrap(cg)->setCacheMaxSizeBytes(MaxSizeBytes);
644 }
645 
thinlto_codegen_set_cache_size_files(thinlto_code_gen_t cg,unsigned MaxSizeFiles)646 void thinlto_codegen_set_cache_size_files(
647     thinlto_code_gen_t cg, unsigned MaxSizeFiles) {
648   return unwrap(cg)->setCacheMaxSizeFiles(MaxSizeFiles);
649 }
650 
thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,const char * save_temps_dir)651 void thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,
652                                        const char *save_temps_dir) {
653   return unwrap(cg)->setSaveTempsDir(save_temps_dir);
654 }
655 
thinlto_set_generated_objects_dir(thinlto_code_gen_t cg,const char * save_temps_dir)656 void thinlto_set_generated_objects_dir(thinlto_code_gen_t cg,
657                                        const char *save_temps_dir) {
658   unwrap(cg)->setGeneratedObjectsDirectory(save_temps_dir);
659 }
660 
thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,lto_codegen_model model)661 lto_bool_t thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,
662                                          lto_codegen_model model) {
663   switch (model) {
664   case LTO_CODEGEN_PIC_MODEL_STATIC:
665     unwrap(cg)->setCodePICModel(Reloc::Static);
666     return false;
667   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
668     unwrap(cg)->setCodePICModel(Reloc::PIC_);
669     return false;
670   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
671     unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
672     return false;
673   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
674     unwrap(cg)->setCodePICModel(None);
675     return false;
676   }
677   sLastErrorString = "Unknown PIC model";
678   return true;
679 }
680 
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(lto::InputFile,lto_input_t)681 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(lto::InputFile, lto_input_t)
682 
683 lto_input_t lto_input_create(const void *buffer, size_t buffer_size, const char *path) {
684   return wrap(LTOModule::createInputFile(buffer, buffer_size, path, sLastErrorString));
685 }
686 
lto_input_dispose(lto_input_t input)687 void lto_input_dispose(lto_input_t input) {
688   delete unwrap(input);
689 }
690 
lto_input_get_num_dependent_libraries(lto_input_t input)691 extern unsigned lto_input_get_num_dependent_libraries(lto_input_t input) {
692   return LTOModule::getDependentLibraryCount(unwrap(input));
693 }
694 
lto_input_get_dependent_library(lto_input_t input,size_t index,size_t * size)695 extern const char *lto_input_get_dependent_library(lto_input_t input,
696                                                    size_t index,
697                                                    size_t *size) {
698   return LTOModule::getDependentLibrary(unwrap(input), index, size);
699 }
700 
lto_runtime_lib_symbols_list(size_t * size)701 extern const char *const *lto_runtime_lib_symbols_list(size_t *size) {
702   auto symbols = lto::LTO::getRuntimeLibcallSymbols();
703   *size = symbols.size();
704   return symbols.data();
705 }
706