]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/base.rs
Auto merge of #56462 - Zoxc:query-macro, r=oli-obk
[rust.git] / src / librustc_codegen_llvm / base.rs
1 //! Codegen the completed AST to the LLVM IR.
2 //!
3 //! Some functions here, such as codegen_block and codegen_expr, return a value --
4 //! the result of the codegen to LLVM -- while others, such as codegen_fn
5 //! and mono_item, are called only for the side effect of adding a
6 //! particular definition to the LLVM IR output we're producing.
7 //!
8 //! Hopefully useful general knowledge about codegen:
9 //!
10 //! * There's no way to find out the `Ty` type of a Value. Doing so
11 //!   would be "trying to get the eggs out of an omelette" (credit:
12 //!   pcwalton). You can, instead, find out its `llvm::Type` by calling `val_ty`,
13 //!   but one `llvm::Type` corresponds to many `Ty`s; for instance, `tup(int, int,
14 //!   int)` and `rec(x=int, y=int, z=int)` will have the same `llvm::Type`.
15
16 use super::ModuleLlvm;
17 use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
18 use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
19 use super::LlvmCodegenBackend;
20
21 use crate::llvm;
22 use crate::metadata;
23 use crate::builder::Builder;
24 use crate::common;
25 use crate::context::CodegenCx;
26 use crate::monomorphize::partitioning::CodegenUnitExt;
27 use rustc::dep_graph;
28 use rustc::mir::mono::{Linkage, Visibility, Stats};
29 use rustc::middle::cstore::{EncodedMetadata};
30 use rustc::ty::TyCtxt;
31 use rustc::middle::exported_symbols;
32 use rustc::session::config::{self, DebugInfo};
33 use rustc_codegen_ssa::mono_item::MonoItemExt;
34 use rustc_data_structures::small_c_str::SmallCStr;
35
36 use rustc_codegen_ssa::traits::*;
37 use rustc_codegen_ssa::back::write::submit_codegened_module_to_llvm;
38
39 use std::ffi::CString;
40 use std::time::Instant;
41 use syntax_pos::symbol::InternedString;
42 use rustc::hir::CodegenFnAttrs;
43
44 use crate::value::Value;
45
46
47 pub fn write_metadata<'a, 'gcx>(
48     tcx: TyCtxt<'a, 'gcx, 'gcx>,
49     llvm_module: &mut ModuleLlvm
50 ) -> EncodedMetadata {
51     use std::io::Write;
52     use flate2::Compression;
53     use flate2::write::DeflateEncoder;
54
55     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
56
57     #[derive(PartialEq, Eq, PartialOrd, Ord)]
58     enum MetadataKind {
59         None,
60         Uncompressed,
61         Compressed
62     }
63
64     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
65         match *ty {
66             config::CrateType::Executable |
67             config::CrateType::Staticlib |
68             config::CrateType::Cdylib => MetadataKind::None,
69
70             config::CrateType::Rlib => MetadataKind::Uncompressed,
71
72             config::CrateType::Dylib |
73             config::CrateType::ProcMacro => MetadataKind::Compressed,
74         }
75     }).max().unwrap_or(MetadataKind::None);
76
77     if kind == MetadataKind::None {
78         return EncodedMetadata::new();
79     }
80
81     let metadata = tcx.encode_metadata();
82     if kind == MetadataKind::Uncompressed {
83         return metadata;
84     }
85
86     assert!(kind == MetadataKind::Compressed);
87     let mut compressed = tcx.metadata_encoding_version();
88     DeflateEncoder::new(&mut compressed, Compression::fast())
89         .write_all(&metadata.raw_data).unwrap();
90
91     let llmeta = common::bytes_in_context(metadata_llcx, &compressed);
92     let llconst = common::struct_in_context(metadata_llcx, &[llmeta], false);
93     let name = exported_symbols::metadata_symbol_name(tcx);
94     let buf = CString::new(name).unwrap();
95     let llglobal = unsafe {
96         llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr())
97     };
98     unsafe {
99         llvm::LLVMSetInitializer(llglobal, llconst);
100         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
101         let name = SmallCStr::new(section_name);
102         llvm::LLVMSetSection(llglobal, name.as_ptr());
103
104         // Also generate a .section directive to force no
105         // flags, at least for ELF outputs, so that the
106         // metadata doesn't get loaded into memory.
107         let directive = format!(".section {}", section_name);
108         let directive = CString::new(directive).unwrap();
109         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
110     }
111     return metadata;
112 }
113
114 pub struct ValueIter<'ll> {
115     cur: Option<&'ll Value>,
116     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
117 }
118
119 impl Iterator for ValueIter<'ll> {
120     type Item = &'ll Value;
121
122     fn next(&mut self) -> Option<&'ll Value> {
123         let old = self.cur;
124         if let Some(old) = old {
125             self.cur = unsafe { (self.step)(old) };
126         }
127         old
128     }
129 }
130
131 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
132     unsafe {
133         ValueIter {
134             cur: llvm::LLVMGetFirstGlobal(llmod),
135             step: llvm::LLVMGetNextGlobal,
136         }
137     }
138 }
139
140 pub fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
141                                   cgu_name: InternedString)
142                                   -> Stats {
143     let start_time = Instant::now();
144
145     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
146     let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
147                                                        tcx,
148                                                        cgu_name,
149                                                        module_codegen,
150                                                        dep_graph::hash_result);
151     let time_to_codegen = start_time.elapsed();
152
153     // We assume that the cost to run LLVM on a CGU is proportional to
154     // the time we needed for codegenning it.
155     let cost = time_to_codegen.as_secs() * 1_000_000_000 +
156                time_to_codegen.subsec_nanos() as u64;
157
158     submit_codegened_module_to_llvm(&LlvmCodegenBackend(()), tcx, module, cost);
159     return stats;
160
161     fn module_codegen<'ll, 'tcx>(
162         tcx: TyCtxt<'ll, 'tcx, 'tcx>,
163         cgu_name: InternedString)
164         -> (Stats, ModuleCodegen<ModuleLlvm>)
165     {
166         let backend = LlvmCodegenBackend(());
167         let cgu = tcx.codegen_unit(cgu_name);
168         // Instantiate monomorphizations without filling out definitions yet...
169         let llvm_module = backend.new_metadata(tcx, &cgu_name.as_str());
170         let stats = {
171             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
172             let mono_items = cx.codegen_unit
173                                .items_in_deterministic_order(cx.tcx);
174             for &(mono_item, (linkage, visibility)) in &mono_items {
175                 mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility);
176             }
177
178             // ... and now that we have everything pre-defined, fill out those definitions.
179             for &(mono_item, _) in &mono_items {
180                 mono_item.define::<Builder<'_, '_, '_>>(&cx);
181             }
182
183             // If this codegen unit contains the main function, also create the
184             // wrapper here
185             maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx);
186
187             // Run replace-all-uses-with for statics that need it
188             for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
189                 unsafe {
190                     let bitcast = llvm::LLVMConstPointerCast(new_g, cx.val_ty(old_g));
191                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
192                     llvm::LLVMDeleteGlobal(old_g);
193                 }
194             }
195
196             // Create the llvm.used variable
197             // This variable has type [N x i8*] and is stored in the llvm.metadata section
198             if !cx.used_statics().borrow().is_empty() {
199                 cx.create_used_variable()
200             }
201
202             // Finalize debuginfo
203             if cx.sess().opts.debuginfo != DebugInfo::None {
204                 cx.debuginfo_finalize();
205             }
206
207             cx.consume_stats().into_inner()
208         };
209
210         (stats, ModuleCodegen {
211             name: cgu_name.to_string(),
212             module_llvm: llvm_module,
213             kind: ModuleKind::Regular,
214         })
215     }
216 }
217
218 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
219     let sect = match attrs.link_section {
220         Some(name) => name,
221         None => return,
222     };
223     unsafe {
224         let buf = SmallCStr::new(&sect.as_str());
225         llvm::LLVMSetSection(llval, buf.as_ptr());
226     }
227 }
228
229 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
230     match linkage {
231         Linkage::External => llvm::Linkage::ExternalLinkage,
232         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
233         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
234         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
235         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
236         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
237         Linkage::Appending => llvm::Linkage::AppendingLinkage,
238         Linkage::Internal => llvm::Linkage::InternalLinkage,
239         Linkage::Private => llvm::Linkage::PrivateLinkage,
240         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
241         Linkage::Common => llvm::Linkage::CommonLinkage,
242     }
243 }
244
245 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
246     match linkage {
247         Visibility::Default => llvm::Visibility::Default,
248         Visibility::Hidden => llvm::Visibility::Hidden,
249         Visibility::Protected => llvm::Visibility::Protected,
250     }
251 }