1 //===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
13 //===----------------------------------------------------------------------===//
15 #include "llvm-c/lto.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/CommandFlags.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/LTO/LTOCodeGenerator.h"
20 #include "llvm/LTO/LTOModule.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/Signals.h"
23 #include "llvm/Support/TargetSelect.h"
25 // extra command-line flags needed for LTOCodeGenerator
28 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
35 DisableInline("disable-inlining", cl::init(false),
36 cl::desc("Do not run the inliner pass"));
39 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
40 cl::desc("Do not run the GVN load PRE pass"));
43 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
44 cl::desc("Do not run loop or slp vectorization during LTO"));
47 static bool VerifyByDefault = false;
49 static bool VerifyByDefault = true;
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"));
56 // Holds most recent error string.
57 // *** Not thread safe ***
58 static std::string sLastErrorString;
60 // Holds the initialization state of the LTO module.
61 // *** Not thread safe ***
62 static bool initialized = false;
64 // Holds the command-line option parsing state of the LTO module.
65 static bool parsedOptions = false;
67 // Initialize the configured targets if they have not been initialized.
68 static void lto_initialize() {
71 // Dialog box on crash disabling doesn't work across DLL boundaries, so do
73 llvm::sys::DisableSystemDialogsOnCrash();
76 InitializeAllTargetInfos();
77 InitializeAllTargets();
78 InitializeAllTargetMCs();
79 InitializeAllAsmParsers();
80 InitializeAllAsmPrinters();
81 InitializeAllDisassemblers();
88 static void handleLibLTODiagnostic(lto_codegen_diagnostic_severity_t Severity,
89 const char *Msg, void *) {
90 sLastErrorString = Msg;
91 sLastErrorString += "\n";
94 // This derived class owns the native object file. This helps implement the
95 // libLTO API semantics, which require that the code generator owns the object
97 struct LibLTOCodeGenerator : LTOCodeGenerator {
98 LibLTOCodeGenerator() {
99 setDiagnosticHandler(handleLibLTODiagnostic, nullptr); }
100 LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
101 : LTOCodeGenerator(std::move(Context)) {
102 setDiagnosticHandler(handleLibLTODiagnostic, nullptr); }
104 std::unique_ptr<MemoryBuffer> NativeObjectFile;
109 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
110 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
112 // Convert the subtarget features into a string to pass to LTOCodeGenerator.
113 static void lto_add_attrs(lto_code_gen_t cg) {
114 LTOCodeGenerator *CG = unwrap(cg);
117 for (unsigned i = 0; i < MAttrs.size(); ++i) {
120 attrs.append(MAttrs[i]);
123 CG->setAttr(attrs.c_str());
126 if (OptLevel < '0' || OptLevel > '3')
127 report_fatal_error("Optimization level must be between 0 and 3");
128 CG->setOptLevel(OptLevel - '0');
131 extern const char* lto_get_version() {
132 return LTOCodeGenerator::getVersionString();
135 const char* lto_get_error_message() {
136 return sLastErrorString.c_str();
139 bool lto_module_is_object_file(const char* path) {
140 return LTOModule::isBitcodeFile(path);
143 bool lto_module_is_object_file_for_target(const char* path,
144 const char* target_triplet_prefix) {
145 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path);
148 return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix);
151 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
152 return LTOModule::isBitcodeFile(mem, length);
156 lto_module_is_object_file_in_memory_for_target(const void* mem,
158 const char* target_triplet_prefix) {
159 std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length));
162 return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix);
165 lto_module_t lto_module_create(const char* path) {
167 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
168 return wrap(LTOModule::createFromFile(path, Options, sLastErrorString));
171 lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
173 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
175 LTOModule::createFromOpenFile(fd, path, size, Options, sLastErrorString));
178 lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
183 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
184 return wrap(LTOModule::createFromOpenFileSlice(fd, path, map_size, offset,
185 Options, sLastErrorString));
188 lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
190 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
191 return wrap(LTOModule::createFromBuffer(mem, length, Options, sLastErrorString));
194 lto_module_t lto_module_create_from_memory_with_path(const void* mem,
198 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
200 LTOModule::createFromBuffer(mem, length, Options, sLastErrorString, path));
203 lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
206 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
207 return wrap(LTOModule::createInLocalContext(mem, length, Options,
208 sLastErrorString, path));
211 lto_module_t lto_module_create_in_codegen_context(const void *mem,
216 llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
217 return wrap(LTOModule::createInContext(mem, length, Options, sLastErrorString,
218 path, &unwrap(cg)->getContext()));
221 void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
223 const char* lto_module_get_target_triple(lto_module_t mod) {
224 return unwrap(mod)->getTargetTriple().c_str();
227 void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
228 return unwrap(mod)->setTargetTriple(triple);
231 unsigned int lto_module_get_num_symbols(lto_module_t mod) {
232 return unwrap(mod)->getSymbolCount();
235 const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
236 return unwrap(mod)->getSymbolName(index);
239 lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
240 unsigned int index) {
241 return unwrap(mod)->getSymbolAttributes(index);
244 const char* lto_module_get_linkeropts(lto_module_t mod) {
245 return unwrap(mod)->getLinkerOpts();
248 void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
249 lto_diagnostic_handler_t diag_handler,
251 unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
254 static lto_code_gen_t createCodeGen(bool InLocalContext) {
257 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
259 LibLTOCodeGenerator *CodeGen =
260 InLocalContext ? new LibLTOCodeGenerator(make_unique<LLVMContext>())
261 : new LibLTOCodeGenerator();
262 CodeGen->setTargetOptions(Options);
263 return wrap(CodeGen);
266 lto_code_gen_t lto_codegen_create(void) {
267 return createCodeGen(/* InLocalContext */ false);
270 lto_code_gen_t lto_codegen_create_in_local_context(void) {
271 return createCodeGen(/* InLocalContext */ true);
274 void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
276 bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
277 return !unwrap(cg)->addModule(unwrap(mod));
280 void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
281 unwrap(cg)->setModule(std::unique_ptr<LTOModule>(unwrap(mod)));
284 bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
285 unwrap(cg)->setDebugInfo(debug);
289 bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
291 case LTO_CODEGEN_PIC_MODEL_STATIC:
292 unwrap(cg)->setCodePICModel(Reloc::Static);
294 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
295 unwrap(cg)->setCodePICModel(Reloc::PIC_);
297 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
298 unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
300 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
301 unwrap(cg)->setCodePICModel(Reloc::Default);
304 sLastErrorString = "Unknown PIC model";
308 void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
309 return unwrap(cg)->setCpu(cpu);
312 void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
313 // In here only for backwards compatibility. We use MC now.
316 void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
318 // In here only for backwards compatibility. We use MC now.
321 void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
322 const char *symbol) {
323 unwrap(cg)->addMustPreserveSymbol(symbol);
326 static void maybeParseOptions(lto_code_gen_t cg) {
327 if (!parsedOptions) {
328 unwrap(cg)->parseCodeGenDebugOptions();
330 parsedOptions = true;
334 bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
335 maybeParseOptions(cg);
336 return !unwrap(cg)->writeMergedModules(path);
339 const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
340 maybeParseOptions(cg);
341 LibLTOCodeGenerator *CG = unwrap(cg);
342 CG->NativeObjectFile =
343 CG->compile(DisableVerify, DisableInline, DisableGVNLoadPRE,
344 DisableLTOVectorization);
345 if (!CG->NativeObjectFile)
347 *length = CG->NativeObjectFile->getBufferSize();
348 return CG->NativeObjectFile->getBufferStart();
351 bool lto_codegen_optimize(lto_code_gen_t cg) {
352 maybeParseOptions(cg);
353 return !unwrap(cg)->optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
354 DisableLTOVectorization);
357 const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
358 maybeParseOptions(cg);
359 LibLTOCodeGenerator *CG = unwrap(cg);
360 CG->NativeObjectFile = CG->compileOptimized();
361 if (!CG->NativeObjectFile)
363 *length = CG->NativeObjectFile->getBufferSize();
364 return CG->NativeObjectFile->getBufferStart();
367 bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
368 maybeParseOptions(cg);
369 return !unwrap(cg)->compile_to_file(
370 name, DisableVerify, DisableInline, DisableGVNLoadPRE,
371 DisableLTOVectorization);
374 void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
375 unwrap(cg)->setCodeGenDebugOptions(opt);
378 unsigned int lto_api_version() { return LTO_API_VERSION; }
380 void lto_codegen_set_should_internalize(lto_code_gen_t cg,
381 bool ShouldInternalize) {
382 unwrap(cg)->setShouldInternalize(ShouldInternalize);
385 void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
386 lto_bool_t ShouldEmbedUselists) {
387 unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);