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