LTO: Disable extra verify runs in release builds
[oota-llvm.git] / tools / lto / lto.cpp
1 //===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
24
25 // extra command-line flags needed for LTOCodeGenerator
26 static cl::opt<char>
27 OptLevel("O",
28          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
29                   "(default = '-O2')"),
30          cl::Prefix,
31          cl::ZeroOrMore,
32          cl::init('2'));
33
34 static cl::opt<bool>
35 DisableInline("disable-inlining", cl::init(false),
36   cl::desc("Do not run the inliner pass"));
37
38 static cl::opt<bool>
39 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
40   cl::desc("Do not run the GVN load PRE pass"));
41
42 static cl::opt<bool>
43 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
44   cl::desc("Do not run loop or slp vectorization 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 // Holds the command-line option parsing state of the LTO module.
65 static bool parsedOptions = false;
66
67 // Initialize the configured targets if they have not been initialized.
68 static void lto_initialize() {
69   if (!initialized) {
70 #ifdef LLVM_ON_WIN32
71     // Dialog box on crash disabling doesn't work across DLL boundaries, so do
72     // it here.
73     llvm::sys::DisableSystemDialogsOnCrash();
74 #endif
75
76     InitializeAllTargetInfos();
77     InitializeAllTargets();
78     InitializeAllTargetMCs();
79     InitializeAllAsmParsers();
80     InitializeAllAsmPrinters();
81     InitializeAllDisassemblers();
82     initialized = true;
83   }
84 }
85
86 namespace {
87
88 // This derived class owns the native object file. This helps implement the
89 // libLTO API semantics, which require that the code generator owns the object
90 // file.
91 struct LibLTOCodeGenerator : LTOCodeGenerator {
92   LibLTOCodeGenerator() {}
93   LibLTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
94       : LTOCodeGenerator(std::move(Context)) {}
95
96   std::unique_ptr<MemoryBuffer> NativeObjectFile;
97 };
98
99 }
100
101 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LibLTOCodeGenerator, lto_code_gen_t)
102 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t)
103
104 // Convert the subtarget features into a string to pass to LTOCodeGenerator.
105 static void lto_add_attrs(lto_code_gen_t cg) {
106   LTOCodeGenerator *CG = unwrap(cg);
107   if (MAttrs.size()) {
108     std::string attrs;
109     for (unsigned i = 0; i < MAttrs.size(); ++i) {
110       if (i > 0)
111         attrs.append(",");
112       attrs.append(MAttrs[i]);
113     }
114
115     CG->setAttr(attrs.c_str());
116   }
117
118   if (OptLevel < '0' || OptLevel > '3')
119     report_fatal_error("Optimization level must be between 0 and 3");
120   CG->setOptLevel(OptLevel - '0');
121 }
122
123 extern const char* lto_get_version() {
124   return LTOCodeGenerator::getVersionString();
125 }
126
127 const char* lto_get_error_message() {
128   return sLastErrorString.c_str();
129 }
130
131 bool lto_module_is_object_file(const char* path) {
132   return LTOModule::isBitcodeFile(path);
133 }
134
135 bool lto_module_is_object_file_for_target(const char* path,
136                                           const char* target_triplet_prefix) {
137   ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path);
138   if (!Buffer)
139     return false;
140   return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix);
141 }
142
143 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
144   return LTOModule::isBitcodeFile(mem, length);
145 }
146
147 bool
148 lto_module_is_object_file_in_memory_for_target(const void* mem,
149                                             size_t length,
150                                             const char* target_triplet_prefix) {
151   std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length));
152   if (!buffer)
153     return false;
154   return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix);
155 }
156
157 lto_module_t lto_module_create(const char* path) {
158   lto_initialize();
159   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
160   return wrap(LTOModule::createFromFile(path, Options, sLastErrorString));
161 }
162
163 lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
164   lto_initialize();
165   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
166   return wrap(
167       LTOModule::createFromOpenFile(fd, path, size, Options, sLastErrorString));
168 }
169
170 lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path,
171                                                  size_t file_size,
172                                                  size_t map_size,
173                                                  off_t offset) {
174   lto_initialize();
175   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
176   return wrap(LTOModule::createFromOpenFileSlice(fd, path, map_size, offset,
177                                                  Options, sLastErrorString));
178 }
179
180 lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
181   lto_initialize();
182   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
183   return wrap(LTOModule::createFromBuffer(mem, length, Options, sLastErrorString));
184 }
185
186 lto_module_t lto_module_create_from_memory_with_path(const void* mem,
187                                                      size_t length,
188                                                      const char *path) {
189   lto_initialize();
190   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
191   return wrap(
192       LTOModule::createFromBuffer(mem, length, Options, sLastErrorString, path));
193 }
194
195 lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
196                                                 const char *path) {
197   lto_initialize();
198   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
199   return wrap(LTOModule::createInLocalContext(mem, length, Options,
200                                               sLastErrorString, path));
201 }
202
203 lto_module_t lto_module_create_in_codegen_context(const void *mem,
204                                                   size_t length,
205                                                   const char *path,
206                                                   lto_code_gen_t cg) {
207   lto_initialize();
208   llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
209   return wrap(LTOModule::createInContext(mem, length, Options, sLastErrorString,
210                                          path, &unwrap(cg)->getContext()));
211 }
212
213 void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
214
215 const char* lto_module_get_target_triple(lto_module_t mod) {
216   return unwrap(mod)->getTargetTriple().c_str();
217 }
218
219 void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
220   return unwrap(mod)->setTargetTriple(triple);
221 }
222
223 unsigned int lto_module_get_num_symbols(lto_module_t mod) {
224   return unwrap(mod)->getSymbolCount();
225 }
226
227 const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) {
228   return unwrap(mod)->getSymbolName(index);
229 }
230
231 lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
232                                                       unsigned int index) {
233   return unwrap(mod)->getSymbolAttributes(index);
234 }
235
236 const char* lto_module_get_linkeropts(lto_module_t mod) {
237   return unwrap(mod)->getLinkerOpts();
238 }
239
240 void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg,
241                                         lto_diagnostic_handler_t diag_handler,
242                                         void *ctxt) {
243   unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt);
244 }
245
246 static lto_code_gen_t createCodeGen(bool InLocalContext) {
247   lto_initialize();
248
249   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
250
251   LibLTOCodeGenerator *CodeGen =
252       InLocalContext ? new LibLTOCodeGenerator(make_unique<LLVMContext>())
253                      : new LibLTOCodeGenerator();
254   CodeGen->setTargetOptions(Options);
255   return wrap(CodeGen);
256 }
257
258 lto_code_gen_t lto_codegen_create(void) {
259   return createCodeGen(/* InLocalContext */ false);
260 }
261
262 lto_code_gen_t lto_codegen_create_in_local_context(void) {
263   return createCodeGen(/* InLocalContext */ true);
264 }
265
266 void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); }
267
268 bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) {
269   return !unwrap(cg)->addModule(unwrap(mod));
270 }
271
272 void lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod) {
273   unwrap(cg)->setModule(std::unique_ptr<LTOModule>(unwrap(mod)));
274 }
275
276 bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) {
277   unwrap(cg)->setDebugInfo(debug);
278   return false;
279 }
280
281 bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) {
282   switch (model) {
283   case LTO_CODEGEN_PIC_MODEL_STATIC:
284     unwrap(cg)->setCodePICModel(Reloc::Static);
285     return false;
286   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
287     unwrap(cg)->setCodePICModel(Reloc::PIC_);
288     return false;
289   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
290     unwrap(cg)->setCodePICModel(Reloc::DynamicNoPIC);
291     return false;
292   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
293     unwrap(cg)->setCodePICModel(Reloc::Default);
294     return false;
295   }
296   sLastErrorString = "Unknown PIC model";
297   return true;
298 }
299
300 void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) {
301   return unwrap(cg)->setCpu(cpu);
302 }
303
304 void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) {
305   // In here only for backwards compatibility. We use MC now.
306 }
307
308 void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
309                                     int nargs) {
310   // In here only for backwards compatibility. We use MC now.
311 }
312
313 void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
314                                           const char *symbol) {
315   unwrap(cg)->addMustPreserveSymbol(symbol);
316 }
317
318 static void maybeParseOptions(lto_code_gen_t cg) {
319   if (!parsedOptions) {
320     unwrap(cg)->parseCodeGenDebugOptions();
321     lto_add_attrs(cg);
322     parsedOptions = true;
323   }
324 }
325
326 bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) {
327   maybeParseOptions(cg);
328   return !unwrap(cg)->writeMergedModules(path, sLastErrorString);
329 }
330
331 const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) {
332   maybeParseOptions(cg);
333   LibLTOCodeGenerator *CG = unwrap(cg);
334   CG->NativeObjectFile =
335       CG->compile(DisableVerify, DisableInline, DisableGVNLoadPRE,
336                   DisableLTOVectorization, sLastErrorString);
337   if (!CG->NativeObjectFile)
338     return nullptr;
339   *length = CG->NativeObjectFile->getBufferSize();
340   return CG->NativeObjectFile->getBufferStart();
341 }
342
343 bool lto_codegen_optimize(lto_code_gen_t cg) {
344   maybeParseOptions(cg);
345   return !unwrap(cg)->optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
346                                DisableLTOVectorization, sLastErrorString);
347 }
348
349 const void *lto_codegen_compile_optimized(lto_code_gen_t cg, size_t *length) {
350   maybeParseOptions(cg);
351   LibLTOCodeGenerator *CG = unwrap(cg);
352   CG->NativeObjectFile = CG->compileOptimized(sLastErrorString);
353   if (!CG->NativeObjectFile)
354     return nullptr;
355   *length = CG->NativeObjectFile->getBufferSize();
356   return CG->NativeObjectFile->getBufferStart();
357 }
358
359 bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) {
360   maybeParseOptions(cg);
361   return !unwrap(cg)->compile_to_file(
362       name, DisableVerify, DisableInline, DisableGVNLoadPRE,
363       DisableLTOVectorization, sLastErrorString);
364 }
365
366 void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) {
367   unwrap(cg)->setCodeGenDebugOptions(opt);
368 }
369
370 unsigned int lto_api_version() { return LTO_API_VERSION; }
371
372 void lto_codegen_set_should_internalize(lto_code_gen_t cg,
373                                         bool ShouldInternalize) {
374   unwrap(cg)->setShouldInternalize(ShouldInternalize);
375 }
376
377 void lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
378                                            lto_bool_t ShouldEmbedUselists) {
379   unwrap(cg)->setShouldEmbedUselists(ShouldEmbedUselists);
380 }