]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/back/write.rs
Auto merge of #58741 - varkor:lang-lib-feature-shared-name, r=alexreg
[rust.git] / src / librustc_codegen_llvm / back / write.rs
1 use crate::attributes;
2 use crate::back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
3 use crate::back::lto::ThinBuffer;
4 use crate::base;
5 use crate::consts;
6 use crate::time_graph::Timeline;
7 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
8 use crate::llvm_util;
9 use crate::ModuleLlvm;
10 use crate::type_::Type;
11 use crate::context::{is_pie_binary, get_reloc_model};
12 use crate::common;
13 use crate::LlvmCodegenBackend;
14 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, run_assembler};
15 use rustc_codegen_ssa::traits::*;
16 use rustc::hir::def_id::LOCAL_CRATE;
17 use rustc::session::config::{self, OutputType, Passes, Lto};
18 use rustc::session::Session;
19 use rustc::ty::TyCtxt;
20 use rustc_codegen_ssa::{ModuleCodegen, CompiledModule};
21 use rustc::util::common::time_ext;
22 use rustc_fs_util::{path_to_c_string, link_or_copy};
23 use rustc_data_structures::small_c_str::SmallCStr;
24 use errors::{Handler, FatalError};
25
26 use std::ffi::{CString, CStr};
27 use std::fs;
28 use std::io::{self, Write};
29 use std::path::Path;
30 use std::str;
31 use std::sync::Arc;
32 use std::slice;
33 use libc::{c_uint, c_void, c_char, size_t};
34
35 pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [
36     ("pic", llvm::RelocMode::PIC),
37     ("static", llvm::RelocMode::Static),
38     ("default", llvm::RelocMode::Default),
39     ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
40     ("ropi", llvm::RelocMode::ROPI),
41     ("rwpi", llvm::RelocMode::RWPI),
42     ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
43 ];
44
45 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
46     ("small", llvm::CodeModel::Small),
47     ("kernel", llvm::CodeModel::Kernel),
48     ("medium", llvm::CodeModel::Medium),
49     ("large", llvm::CodeModel::Large),
50 ];
51
52 pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [
53     ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
54     ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
55     ("initial-exec", llvm::ThreadLocalMode::InitialExec),
56     ("local-exec", llvm::ThreadLocalMode::LocalExec),
57 ];
58
59 pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError {
60     match llvm::last_error() {
61         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
62         None => handler.fatal(&msg),
63     }
64 }
65
66 pub fn write_output_file(
67         handler: &errors::Handler,
68         target: &'ll llvm::TargetMachine,
69         pm: &llvm::PassManager<'ll>,
70         m: &'ll llvm::Module,
71         output: &Path,
72         file_type: llvm::FileType) -> Result<(), FatalError> {
73     unsafe {
74         let output_c = path_to_c_string(output);
75         let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
76         if result.into_result().is_err() {
77             let msg = format!("could not write output to {}", output.display());
78             Err(llvm_err(handler, &msg))
79         } else {
80             Ok(())
81         }
82     }
83 }
84
85 pub fn create_target_machine(
86     tcx: TyCtxt<'_, '_, '_>,
87     find_features: bool,
88 ) -> &'static mut llvm::TargetMachine {
89     target_machine_factory(tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)()
90         .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise() )
91 }
92
93 pub fn create_informational_target_machine(
94     sess: &Session,
95     find_features: bool,
96 ) -> &'static mut llvm::TargetMachine {
97     target_machine_factory(sess, config::OptLevel::No, find_features)().unwrap_or_else(|err| {
98         llvm_err(sess.diagnostic(), &err).raise()
99     })
100 }
101
102
103 pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize)
104 {
105     use self::config::OptLevel::*;
106     match cfg {
107         No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
108         Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
109         Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
110         Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
111         Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
112         SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
113     }
114 }
115
116 // If find_features is true this won't access `sess.crate_types` by assuming
117 // that `is_pie_binary` is false. When we discover LLVM target features
118 // `sess.crate_types` is uninitialized so we cannot access it.
119 pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_features: bool)
120     -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
121 {
122     let reloc_model = get_reloc_model(sess);
123
124     let (opt_level, _) = to_llvm_opt_settings(optlvl);
125     let use_softfp = sess.opts.cg.soft_float;
126
127     let ffunction_sections = sess.target.target.options.function_sections;
128     let fdata_sections = ffunction_sections;
129
130     let code_model_arg = sess.opts.cg.code_model.as_ref().or(
131         sess.target.target.options.code_model.as_ref(),
132     );
133
134     let code_model = match code_model_arg {
135         Some(s) => {
136             match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
137                 Some(x) => x.1,
138                 _ => {
139                     sess.err(&format!("{:?} is not a valid code model",
140                                       code_model_arg));
141                     sess.abort_if_errors();
142                     bug!();
143                 }
144             }
145         }
146         None => llvm::CodeModel::None,
147     };
148
149     let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
150     let mut singlethread = sess.target.target.options.singlethread;
151
152     // On the wasm target once the `atomics` feature is enabled that means that
153     // we're no longer single-threaded, or otherwise we don't want LLVM to
154     // lower atomic operations to single-threaded operations.
155     if singlethread &&
156         sess.target.target.llvm_target.contains("wasm32") &&
157         features.iter().any(|s| *s == "+atomics")
158     {
159         singlethread = false;
160     }
161
162     let triple = SmallCStr::new(&sess.target.target.llvm_target);
163     let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
164     let features = features.join(",");
165     let features = CString::new(features).unwrap();
166     let is_pie_binary = !find_features && is_pie_binary(sess);
167     let trap_unreachable = sess.target.target.options.trap_unreachable;
168     let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
169
170     let asm_comments = sess.asm_comments();
171
172     Arc::new(move || {
173         let tm = unsafe {
174             llvm::LLVMRustCreateTargetMachine(
175                 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
176                 code_model,
177                 reloc_model,
178                 opt_level,
179                 use_softfp,
180                 is_pie_binary,
181                 ffunction_sections,
182                 fdata_sections,
183                 trap_unreachable,
184                 singlethread,
185                 asm_comments,
186                 emit_stack_size_section,
187             )
188         };
189
190         tm.ok_or_else(|| {
191             format!("Could not create LLVM TargetMachine for triple: {}",
192                     triple.to_str().unwrap())
193         })
194     })
195 }
196
197 pub(crate) fn save_temp_bitcode(
198     cgcx: &CodegenContext<LlvmCodegenBackend>,
199     module: &ModuleCodegen<ModuleLlvm>,
200     name: &str
201 ) {
202     if !cgcx.save_temps {
203         return
204     }
205     unsafe {
206         let ext = format!("{}.bc", name);
207         let cgu = Some(&module.name[..]);
208         let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
209         let cstr = path_to_c_string(&path);
210         let llmod = module.module_llvm.llmod();
211         llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
212     }
213 }
214
215 pub struct DiagnosticHandlers<'a> {
216     data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
217     llcx: &'a llvm::Context,
218 }
219
220 impl<'a> DiagnosticHandlers<'a> {
221     pub fn new(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
222                handler: &'a Handler,
223                llcx: &'a llvm::Context) -> Self {
224         let data = Box::into_raw(Box::new((cgcx, handler)));
225         unsafe {
226             llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
227             llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
228         }
229         DiagnosticHandlers { data, llcx }
230     }
231 }
232
233 impl<'a> Drop for DiagnosticHandlers<'a> {
234     fn drop(&mut self) {
235         use std::ptr::null_mut;
236         unsafe {
237             llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
238             llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
239             drop(Box::from_raw(self.data));
240         }
241     }
242 }
243
244 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
245                                                msg: &'b str,
246                                                cookie: c_uint) {
247     cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
248 }
249
250 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
251                                         user: *const c_void,
252                                         cookie: c_uint) {
253     if user.is_null() {
254         return
255     }
256     let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
257
258     let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
259         .expect("non-UTF8 SMDiagnostic");
260
261     report_inline_asm(cgcx, &msg, cookie);
262 }
263
264 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
265     if user.is_null() {
266         return
267     }
268     let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
269
270     match llvm::diagnostic::Diagnostic::unpack(info) {
271         llvm::diagnostic::InlineAsm(inline) => {
272             report_inline_asm(cgcx,
273                               &llvm::twine_to_string(inline.message),
274                               inline.cookie);
275         }
276
277         llvm::diagnostic::Optimization(opt) => {
278             let enabled = match cgcx.remark {
279                 Passes::All => true,
280                 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
281             };
282
283             if enabled {
284                 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
285                                                 opt.kind.describe(),
286                                                 opt.pass_name,
287                                                 opt.filename,
288                                                 opt.line,
289                                                 opt.column,
290                                                 opt.message));
291             }
292         }
293         llvm::diagnostic::PGO(diagnostic_ref) |
294         llvm::diagnostic::Linker(diagnostic_ref) => {
295             let msg = llvm::build_string(|s| {
296                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
297             }).expect("non-UTF8 diagnostic");
298             diag_handler.warn(&msg);
299         }
300         llvm::diagnostic::UnknownDiagnostic(..) => {},
301     }
302 }
303
304 // Unsafe due to LLVM calls.
305 pub(crate) unsafe fn optimize(cgcx: &CodegenContext<LlvmCodegenBackend>,
306                    diag_handler: &Handler,
307                    module: &ModuleCodegen<ModuleLlvm>,
308                    config: &ModuleConfig,
309                    timeline: &mut Timeline)
310     -> Result<(), FatalError>
311 {
312     let llmod = module.module_llvm.llmod();
313     let llcx = &*module.module_llvm.llcx;
314     let tm = &*module.module_llvm.tm;
315     let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
316
317     let module_name = module.name.clone();
318     let module_name = Some(&module_name[..]);
319
320     if config.emit_no_opt_bc {
321         let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
322         let out = path_to_c_string(&out);
323         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
324     }
325
326     if config.opt_level.is_some() {
327         // Create the two optimizing pass managers. These mirror what clang
328         // does, and are by populated by LLVM's default PassManagerBuilder.
329         // Each manager has a different set of passes, but they also share
330         // some common passes.
331         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
332         let mpm = llvm::LLVMCreatePassManager();
333
334         {
335             // If we're verifying or linting, add them to the function pass
336             // manager.
337             let addpass = |pass_name: &str| {
338                 let pass_name = SmallCStr::new(pass_name);
339                 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
340                     Some(pass) => pass,
341                     None => return false,
342                 };
343                 let pass_manager = match llvm::LLVMRustPassKind(pass) {
344                     llvm::PassKind::Function => &*fpm,
345                     llvm::PassKind::Module => &*mpm,
346                     llvm::PassKind::Other => {
347                         diag_handler.err("Encountered LLVM pass kind we can't handle");
348                         return true
349                     },
350                 };
351                 llvm::LLVMRustAddPass(pass_manager, pass);
352                 true
353             };
354
355             if config.verify_llvm_ir { assert!(addpass("verify")); }
356
357             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
358             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
359             // we'll get errors in LLVM.
360             let using_thin_buffers = config.bitcode_needed();
361             let mut have_name_anon_globals_pass = false;
362             if !config.no_prepopulate_passes {
363                 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
364                 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
365                 let opt_level = config.opt_level.map(|x| to_llvm_opt_settings(x).0)
366                     .unwrap_or(llvm::CodeGenOptLevel::None);
367                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
368                     (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
369                 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
370                     llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
371                     llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
372                 });
373
374                 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
375                 if using_thin_buffers && !prepare_for_thin_lto {
376                     assert!(addpass("name-anon-globals"));
377                     have_name_anon_globals_pass = true;
378                 }
379             }
380
381             for pass in &config.passes {
382                 if !addpass(pass) {
383                     diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
384                 }
385                 if pass == "name-anon-globals" {
386                     have_name_anon_globals_pass = true;
387                 }
388             }
389
390             for pass in &cgcx.plugin_passes {
391                 if !addpass(pass) {
392                     diag_handler.err(&format!("a plugin asked for LLVM pass \
393                                                `{}` but LLVM does not \
394                                                recognize it", pass));
395                 }
396                 if pass == "name-anon-globals" {
397                     have_name_anon_globals_pass = true;
398                 }
399             }
400
401             if using_thin_buffers && !have_name_anon_globals_pass {
402                 // As described above, this will probably cause an error in LLVM
403                 if config.no_prepopulate_passes {
404                     diag_handler.err("The current compilation is going to use thin LTO buffers \
405                                       without running LLVM's NameAnonGlobals pass. \
406                                       This will likely cause errors in LLVM. Consider adding \
407                                       -C passes=name-anon-globals to the compiler command line.");
408                 } else {
409                     bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
410                           This will likely cause errors in LLVM and should never happen.");
411                 }
412             }
413         }
414
415         diag_handler.abort_if_errors();
416
417         // Finally, run the actual optimization passes
418         time_ext(config.time_passes,
419                  None,
420                  &format!("llvm function passes [{}]", module_name.unwrap()),
421                  || {
422             llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
423         });
424         timeline.record("fpm");
425         time_ext(config.time_passes,
426                  None,
427                  &format!("llvm module passes [{}]", module_name.unwrap()),
428                  || {
429             llvm::LLVMRunPassManager(mpm, llmod)
430         });
431
432         // Deallocate managers that we're now done with
433         llvm::LLVMDisposePassManager(fpm);
434         llvm::LLVMDisposePassManager(mpm);
435     }
436     Ok(())
437 }
438
439 pub(crate) unsafe fn codegen(cgcx: &CodegenContext<LlvmCodegenBackend>,
440                   diag_handler: &Handler,
441                   module: ModuleCodegen<ModuleLlvm>,
442                   config: &ModuleConfig,
443                   timeline: &mut Timeline)
444     -> Result<CompiledModule, FatalError>
445 {
446     timeline.record("codegen");
447     {
448         let llmod = module.module_llvm.llmod();
449         let llcx = &*module.module_llvm.llcx;
450         let tm = &*module.module_llvm.tm;
451         let module_name = module.name.clone();
452         let module_name = Some(&module_name[..]);
453         let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
454
455         if cgcx.msvc_imps_needed {
456             create_msvc_imps(cgcx, llcx, llmod);
457         }
458
459         // A codegen-specific pass manager is used to generate object
460         // files for an LLVM module.
461         //
462         // Apparently each of these pass managers is a one-shot kind of
463         // thing, so we create a new one for each type of output. The
464         // pass manager passed to the closure should be ensured to not
465         // escape the closure itself, and the manager should only be
466         // used once.
467         unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
468                                           llmod: &'ll llvm::Module,
469                                           no_builtins: bool,
470                                           f: F) -> R
471             where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
472         {
473             let cpm = llvm::LLVMCreatePassManager();
474             llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
475             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
476             f(cpm)
477         }
478
479         // If we don't have the integrated assembler, then we need to emit asm
480         // from LLVM and use `gcc` to create the object file.
481         let asm_to_obj = config.emit_obj && config.no_integrated_as;
482
483         // Change what we write and cleanup based on whether obj files are
484         // just llvm bitcode. In that case write bitcode, and possibly
485         // delete the bitcode if it wasn't requested. Don't generate the
486         // machine code, instead copy the .o file from the .bc
487         let write_bc = config.emit_bc || config.obj_is_bitcode;
488         let rm_bc = !config.emit_bc && config.obj_is_bitcode;
489         let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
490         let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
491
492         let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
493         let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
494
495
496         if write_bc || config.emit_bc_compressed || config.embed_bitcode {
497             let thin = ThinBuffer::new(llmod);
498             let data = thin.data();
499             timeline.record("make-bc");
500
501             if write_bc {
502                 if let Err(e) = fs::write(&bc_out, data) {
503                     diag_handler.err(&format!("failed to write bytecode: {}", e));
504                 }
505                 timeline.record("write-bc");
506             }
507
508             if config.embed_bitcode {
509                 embed_bitcode(cgcx, llcx, llmod, Some(data));
510                 timeline.record("embed-bc");
511             }
512
513             if config.emit_bc_compressed {
514                 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
515                 let data = bytecode::encode(&module.name, data);
516                 if let Err(e) = fs::write(&dst, data) {
517                     diag_handler.err(&format!("failed to write bytecode: {}", e));
518                 }
519                 timeline.record("compress-bc");
520             }
521         } else if config.embed_bitcode_marker {
522             embed_bitcode(cgcx, llcx, llmod, None);
523         }
524
525         time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
526             || -> Result<(), FatalError> {
527             if config.emit_ir {
528                 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
529                 let out = path_to_c_string(&out);
530
531                 extern "C" fn demangle_callback(input_ptr: *const c_char,
532                                                 input_len: size_t,
533                                                 output_ptr: *mut c_char,
534                                                 output_len: size_t) -> size_t {
535                     let input = unsafe {
536                         slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
537                     };
538
539                     let input = match str::from_utf8(input) {
540                         Ok(s) => s,
541                         Err(_) => return 0,
542                     };
543
544                     let output = unsafe {
545                         slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
546                     };
547                     let mut cursor = io::Cursor::new(output);
548
549                     let demangled = match rustc_demangle::try_demangle(input) {
550                         Ok(d) => d,
551                         Err(_) => return 0,
552                     };
553
554                     if let Err(_) = write!(cursor, "{:#}", demangled) {
555                         // Possible only if provided buffer is not big enough
556                         return 0;
557                     }
558
559                     cursor.position() as size_t
560                 }
561
562                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
563                     llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
564                     llvm::LLVMDisposePassManager(cpm);
565                 });
566                 timeline.record("ir");
567             }
568
569             if config.emit_asm || asm_to_obj {
570                 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
571
572                 // We can't use the same module for asm and binary output, because that triggers
573                 // various errors like invalid IR or broken binaries, so we might have to clone the
574                 // module to produce the asm output
575                 let llmod = if config.emit_obj {
576                     llvm::LLVMCloneModule(llmod)
577                 } else {
578                     llmod
579                 };
580                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
581                     write_output_file(diag_handler, tm, cpm, llmod, &path,
582                                       llvm::FileType::AssemblyFile)
583                 })?;
584                 timeline.record("asm");
585             }
586
587             if write_obj {
588                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
589                     write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
590                                       llvm::FileType::ObjectFile)
591                 })?;
592                 timeline.record("obj");
593             } else if asm_to_obj {
594                 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
595                 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
596                 timeline.record("asm_to_obj");
597
598                 if !config.emit_asm && !cgcx.save_temps {
599                     drop(fs::remove_file(&assembly));
600                 }
601             }
602
603             Ok(())
604         })?;
605
606         if copy_bc_to_obj {
607             debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
608             if let Err(e) = link_or_copy(&bc_out, &obj_out) {
609                 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
610             }
611         }
612
613         if rm_bc {
614             debug!("removing_bitcode {:?}", bc_out);
615             if let Err(e) = fs::remove_file(&bc_out) {
616                 diag_handler.err(&format!("failed to remove bitcode: {}", e));
617             }
618         }
619
620         drop(handlers);
621     }
622     Ok(module.into_compiled_module(config.emit_obj,
623                                    config.emit_bc,
624                                    config.emit_bc_compressed,
625                                    &cgcx.output_filenames))
626 }
627
628 /// Embed the bitcode of an LLVM module in the LLVM module itself.
629 ///
630 /// This is done primarily for iOS where it appears to be standard to compile C
631 /// code at least with `-fembed-bitcode` which creates two sections in the
632 /// executable:
633 ///
634 /// * __LLVM,__bitcode
635 /// * __LLVM,__cmdline
636 ///
637 /// It appears *both* of these sections are necessary to get the linker to
638 /// recognize what's going on. For us though we just always throw in an empty
639 /// cmdline section.
640 ///
641 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
642 /// embed an empty section.
643 ///
644 /// Basically all of this is us attempting to follow in the footsteps of clang
645 /// on iOS. See #35968 for lots more info.
646 unsafe fn embed_bitcode(cgcx: &CodegenContext<LlvmCodegenBackend>,
647                         llcx: &llvm::Context,
648                         llmod: &llvm::Module,
649                         bitcode: Option<&[u8]>) {
650     let llconst = common::bytes_in_context(llcx, bitcode.unwrap_or(&[]));
651     let llglobal = llvm::LLVMAddGlobal(
652         llmod,
653         common::val_ty(llconst),
654         "rustc.embedded.module\0".as_ptr() as *const _,
655     );
656     llvm::LLVMSetInitializer(llglobal, llconst);
657
658     let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
659                    cgcx.opts.target_triple.triple().contains("-darwin");
660
661     let section = if is_apple {
662         "__LLVM,__bitcode\0"
663     } else {
664         ".llvmbc\0"
665     };
666     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
667     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
668     llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
669
670     let llconst = common::bytes_in_context(llcx, &[]);
671     let llglobal = llvm::LLVMAddGlobal(
672         llmod,
673         common::val_ty(llconst),
674         "rustc.embedded.cmdline\0".as_ptr() as *const _,
675     );
676     llvm::LLVMSetInitializer(llglobal, llconst);
677     let section = if  is_apple {
678         "__LLVM,__cmdline\0"
679     } else {
680         ".llvmcmd\0"
681     };
682     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
683     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
684 }
685
686 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
687                             config: &ModuleConfig,
688                             opt_level: llvm::CodeGenOptLevel,
689                             prepare_for_thin_lto: bool,
690                             f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
691     use std::ptr;
692
693     // Create the PassManagerBuilder for LLVM. We configure it with
694     // reasonable defaults and prepare it to actually populate the pass
695     // manager.
696     let builder = llvm::LLVMPassManagerBuilderCreate();
697     let opt_size = config.opt_size.map(|x| to_llvm_opt_settings(x).1)
698         .unwrap_or(llvm::CodeGenOptSizeNone);
699     let inline_threshold = config.inline_threshold;
700
701     let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
702         let s = if s.is_empty() { "default_%m.profraw" } else { s };
703         CString::new(s.as_bytes()).unwrap()
704     });
705
706     let pgo_use_path = if config.pgo_use.is_empty() {
707         None
708     } else {
709         Some(CString::new(config.pgo_use.as_bytes()).unwrap())
710     };
711
712     llvm::LLVMRustConfigurePassManagerBuilder(
713         builder,
714         opt_level,
715         config.merge_functions,
716         config.vectorize_slp,
717         config.vectorize_loop,
718         prepare_for_thin_lto,
719         pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
720         pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
721     );
722
723     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
724
725     if opt_size != llvm::CodeGenOptSizeNone {
726         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
727     }
728
729     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
730
731     // Here we match what clang does (kinda). For O0 we only inline
732     // always-inline functions (but don't add lifetime intrinsics), at O1 we
733     // inline with lifetime intrinsics, and O2+ we add an inliner with a
734     // thresholds copied from clang.
735     match (opt_level, opt_size, inline_threshold) {
736         (.., Some(t)) => {
737             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
738         }
739         (llvm::CodeGenOptLevel::Aggressive, ..) => {
740             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
741         }
742         (_, llvm::CodeGenOptSizeDefault, _) => {
743             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
744         }
745         (_, llvm::CodeGenOptSizeAggressive, _) => {
746             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
747         }
748         (llvm::CodeGenOptLevel::None, ..) => {
749             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
750         }
751         (llvm::CodeGenOptLevel::Less, ..) => {
752             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
753         }
754         (llvm::CodeGenOptLevel::Default, ..) => {
755             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
756         }
757         (llvm::CodeGenOptLevel::Other, ..) => {
758             bug!("CodeGenOptLevel::Other selected")
759         }
760     }
761
762     f(builder);
763     llvm::LLVMPassManagerBuilderDispose(builder);
764 }
765
766 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
767 // This is required to satisfy `dllimport` references to static data in .rlibs
768 // when using MSVC linker.  We do this only for data, as linker can fix up
769 // code references on its own.
770 // See #26591, #27438
771 fn create_msvc_imps(
772     cgcx: &CodegenContext<LlvmCodegenBackend>,
773     llcx: &llvm::Context,
774     llmod: &llvm::Module
775 ) {
776     if !cgcx.msvc_imps_needed {
777         return
778     }
779     // The x86 ABI seems to require that leading underscores are added to symbol
780     // names, so we need an extra underscore on 32-bit. There's also a leading
781     // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
782     // underscores added in front).
783     let prefix = if cgcx.target_pointer_width == "32" {
784         "\x01__imp__"
785     } else {
786         "\x01__imp_"
787     };
788     unsafe {
789         let i8p_ty = Type::i8p_llcx(llcx);
790         let globals = base::iter_globals(llmod)
791             .filter(|&val| {
792                 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
793                     llvm::LLVMIsDeclaration(val) == 0
794             })
795             .map(move |val| {
796                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
797                 let mut imp_name = prefix.as_bytes().to_vec();
798                 imp_name.extend(name.to_bytes());
799                 let imp_name = CString::new(imp_name).unwrap();
800                 (imp_name, val)
801             })
802             .collect::<Vec<_>>();
803         for (imp_name, val) in globals {
804             let imp = llvm::LLVMAddGlobal(llmod,
805                                           i8p_ty,
806                                           imp_name.as_ptr() as *const _);
807             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
808             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
809         }
810     }
811 }