]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/base.rs
Auto merge of #84228 - SkiFire13:fix-84213, r=estebank
[rust.git] / compiler / rustc_codegen_llvm / src / base.rs
1 //! Codegen the MIR to the LLVM IR.
2 //!
3 //! Hopefully useful general knowledge about codegen:
4 //!
5 //! * There's no way to find out the [`Ty`] type of a [`Value`]. Doing so
6 //!   would be "trying to get the eggs out of an omelette" (credit:
7 //!   pcwalton). You can, instead, find out its [`llvm::Type`] by calling [`val_ty`],
8 //!   but one [`llvm::Type`] corresponds to many [`Ty`]s; for instance, `tup(int, int,
9 //!   int)` and `rec(x=int, y=int, z=int)` will have the same [`llvm::Type`].
10 //!
11 //! [`Ty`]: rustc_middle::ty::Ty
12 //! [`val_ty`]: common::val_ty
13
14 use super::ModuleLlvm;
15
16 use crate::attributes;
17 use crate::builder::Builder;
18 use crate::common;
19 use crate::context::CodegenCx;
20 use crate::llvm;
21 use crate::metadata;
22 use crate::value::Value;
23
24 use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
25 use rustc_codegen_ssa::mono_item::MonoItemExt;
26 use rustc_codegen_ssa::traits::*;
27 use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
28 use rustc_data_structures::small_c_str::SmallCStr;
29 use rustc_middle::dep_graph;
30 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
31 use rustc_middle::middle::cstore::EncodedMetadata;
32 use rustc_middle::middle::exported_symbols;
33 use rustc_middle::mir::mono::{Linkage, Visibility};
34 use rustc_middle::ty::TyCtxt;
35 use rustc_session::config::DebugInfo;
36 use rustc_span::symbol::Symbol;
37 use rustc_target::spec::SanitizerSet;
38
39 use std::ffi::CString;
40 use std::time::Instant;
41
42 pub fn write_compressed_metadata<'tcx>(
43     tcx: TyCtxt<'tcx>,
44     metadata: &EncodedMetadata,
45     llvm_module: &mut ModuleLlvm,
46 ) {
47     use snap::write::FrameEncoder;
48     use std::io::Write;
49
50     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
51     let mut compressed = tcx.metadata_encoding_version();
52     FrameEncoder::new(&mut compressed).write_all(&metadata.raw_data).unwrap();
53
54     let llmeta = common::bytes_in_context(metadata_llcx, &compressed);
55     let llconst = common::struct_in_context(metadata_llcx, &[llmeta], false);
56     let name = exported_symbols::metadata_symbol_name(tcx);
57     let buf = CString::new(name).unwrap();
58     let llglobal =
59         unsafe { llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr()) };
60     unsafe {
61         llvm::LLVMSetInitializer(llglobal, llconst);
62         let section_name = metadata::metadata_section_name(&tcx.sess.target);
63         let name = SmallCStr::new(section_name);
64         llvm::LLVMSetSection(llglobal, name.as_ptr());
65
66         // Also generate a .section directive to force no
67         // flags, at least for ELF outputs, so that the
68         // metadata doesn't get loaded into memory.
69         let directive = format!(".section {}", section_name);
70         llvm::LLVMSetModuleInlineAsm2(metadata_llmod, directive.as_ptr().cast(), directive.len())
71     }
72 }
73
74 pub struct ValueIter<'ll> {
75     cur: Option<&'ll Value>,
76     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
77 }
78
79 impl Iterator for ValueIter<'ll> {
80     type Item = &'ll Value;
81
82     fn next(&mut self) -> Option<&'ll Value> {
83         let old = self.cur;
84         if let Some(old) = old {
85             self.cur = unsafe { (self.step)(old) };
86         }
87         old
88     }
89 }
90
91 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
92     unsafe { ValueIter { cur: llvm::LLVMGetFirstGlobal(llmod), step: llvm::LLVMGetNextGlobal } }
93 }
94
95 pub fn compile_codegen_unit(
96     tcx: TyCtxt<'tcx>,
97     cgu_name: Symbol,
98 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
99     let start_time = Instant::now();
100
101     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
102     let (module, _) =
103         tcx.dep_graph.with_task(dep_node, tcx, cgu_name, module_codegen, dep_graph::hash_result);
104     let time_to_codegen = start_time.elapsed();
105
106     // We assume that the cost to run LLVM on a CGU is proportional to
107     // the time we needed for codegenning it.
108     let cost = time_to_codegen.as_nanos() as u64;
109
110     fn module_codegen(tcx: TyCtxt<'_>, cgu_name: Symbol) -> ModuleCodegen<ModuleLlvm> {
111         let cgu = tcx.codegen_unit(cgu_name);
112         let _prof_timer = tcx.prof.generic_activity_with_args(
113             "codegen_module",
114             &[cgu_name.to_string(), cgu.size_estimate().to_string()],
115         );
116         // Instantiate monomorphizations without filling out definitions yet...
117         let llvm_module = ModuleLlvm::new(tcx, &cgu_name.as_str());
118         {
119             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
120             let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx);
121             for &(mono_item, (linkage, visibility)) in &mono_items {
122                 mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility);
123             }
124
125             // ... and now that we have everything pre-defined, fill out those definitions.
126             for &(mono_item, _) in &mono_items {
127                 mono_item.define::<Builder<'_, '_, '_>>(&cx);
128             }
129
130             // If this codegen unit contains the main function, also create the
131             // wrapper here
132             if let Some(entry) = maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx) {
133                 attributes::sanitize(&cx, SanitizerSet::empty(), entry);
134             }
135
136             // Run replace-all-uses-with for statics that need it
137             for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
138                 unsafe {
139                     let bitcast = llvm::LLVMConstPointerCast(new_g, cx.val_ty(old_g));
140                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
141                     llvm::LLVMDeleteGlobal(old_g);
142                 }
143             }
144
145             // Finalize code coverage by injecting the coverage map. Note, the coverage map will
146             // also be added to the `llvm.used` variable, created next.
147             if cx.sess().instrument_coverage() {
148                 cx.coverageinfo_finalize();
149             }
150
151             // Create the llvm.used variable
152             // This variable has type [N x i8*] and is stored in the llvm.metadata section
153             if !cx.used_statics().borrow().is_empty() {
154                 cx.create_used_variable()
155             }
156
157             // Finalize debuginfo
158             if cx.sess().opts.debuginfo != DebugInfo::None {
159                 cx.debuginfo_finalize();
160             }
161         }
162
163         ModuleCodegen {
164             name: cgu_name.to_string(),
165             module_llvm: llvm_module,
166             kind: ModuleKind::Regular,
167         }
168     }
169
170     (module, cost)
171 }
172
173 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
174     let sect = match attrs.link_section {
175         Some(name) => name,
176         None => return,
177     };
178     unsafe {
179         let buf = SmallCStr::new(&sect.as_str());
180         llvm::LLVMSetSection(llval, buf.as_ptr());
181     }
182 }
183
184 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
185     match linkage {
186         Linkage::External => llvm::Linkage::ExternalLinkage,
187         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
188         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
189         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
190         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
191         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
192         Linkage::Appending => llvm::Linkage::AppendingLinkage,
193         Linkage::Internal => llvm::Linkage::InternalLinkage,
194         Linkage::Private => llvm::Linkage::PrivateLinkage,
195         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
196         Linkage::Common => llvm::Linkage::CommonLinkage,
197     }
198 }
199
200 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
201     match linkage {
202         Visibility::Default => llvm::Visibility::Default,
203         Visibility::Hidden => llvm::Visibility::Hidden,
204         Visibility::Protected => llvm::Visibility::Protected,
205     }
206 }