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