]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/base.rs
Auto merge of #61300 - indygreg:upgrade-cross-make, r=sanxiyn
[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::{LlvmCodegenBackend, ModuleLlvm};
17 use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
18 use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
19
20 use crate::llvm;
21 use crate::metadata;
22 use crate::builder::Builder;
23 use crate::common;
24 use crate::context::CodegenCx;
25 use crate::monomorphize::partitioning::CodegenUnitExt;
26 use rustc::dep_graph;
27 use rustc::mir::mono::{Linkage, Visibility};
28 use rustc::middle::cstore::{EncodedMetadata};
29 use rustc::ty::TyCtxt;
30 use rustc::middle::exported_symbols;
31 use rustc::session::config::DebugInfo;
32 use rustc_codegen_ssa::mono_item::MonoItemExt;
33 use rustc_data_structures::small_c_str::SmallCStr;
34
35 use rustc_codegen_ssa::traits::*;
36 use rustc_codegen_ssa::back::write::submit_codegened_module_to_llvm;
37
38 use std::ffi::CString;
39 use std::time::Instant;
40 use syntax_pos::symbol::InternedString;
41 use rustc::hir::CodegenFnAttrs;
42
43 use crate::value::Value;
44
45 pub fn write_compressed_metadata<'a, 'gcx>(
46     tcx: TyCtxt<'a, 'gcx, 'gcx>,
47     metadata: &EncodedMetadata,
48     llvm_module: &mut ModuleLlvm
49 ) {
50     use std::io::Write;
51     use flate2::Compression;
52     use flate2::write::DeflateEncoder;
53
54     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
55     let mut compressed = tcx.metadata_encoding_version();
56     DeflateEncoder::new(&mut compressed, Compression::fast())
57         .write_all(&metadata.raw_data).unwrap();
58
59     let llmeta = common::bytes_in_context(metadata_llcx, &compressed);
60     let llconst = common::struct_in_context(metadata_llcx, &[llmeta], false);
61     let name = exported_symbols::metadata_symbol_name(tcx);
62     let buf = CString::new(name).unwrap();
63     let llglobal = unsafe {
64         llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr())
65     };
66     unsafe {
67         llvm::LLVMSetInitializer(llglobal, llconst);
68         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
69         let name = SmallCStr::new(section_name);
70         llvm::LLVMSetSection(llglobal, name.as_ptr());
71
72         // Also generate a .section directive to force no
73         // flags, at least for ELF outputs, so that the
74         // metadata doesn't get loaded into memory.
75         let directive = format!(".section {}", section_name);
76         let directive = CString::new(directive).unwrap();
77         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
78     }
79 }
80
81 pub struct ValueIter<'ll> {
82     cur: Option<&'ll Value>,
83     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
84 }
85
86 impl Iterator for ValueIter<'ll> {
87     type Item = &'ll Value;
88
89     fn next(&mut self) -> Option<&'ll Value> {
90         let old = self.cur;
91         if let Some(old) = old {
92             self.cur = unsafe { (self.step)(old) };
93         }
94         old
95     }
96 }
97
98 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
99     unsafe {
100         ValueIter {
101             cur: llvm::LLVMGetFirstGlobal(llmod),
102             step: llvm::LLVMGetNextGlobal,
103         }
104     }
105 }
106
107 pub fn compile_codegen_unit(tcx: TyCtxt<'a, 'tcx, 'tcx>, cgu_name: InternedString) {
108     let start_time = Instant::now();
109
110     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
111     let (module, _) = tcx.dep_graph.with_task(
112         dep_node,
113         tcx,
114         cgu_name,
115         module_codegen,
116         dep_graph::hash_result,
117     );
118     let time_to_codegen = start_time.elapsed();
119
120     // We assume that the cost to run LLVM on a CGU is proportional to
121     // the time we needed for codegenning it.
122     let cost = time_to_codegen.as_secs() * 1_000_000_000 +
123                time_to_codegen.subsec_nanos() as u64;
124
125     submit_codegened_module_to_llvm(&LlvmCodegenBackend(()), tcx, module, cost);
126
127     fn module_codegen<'ll, 'tcx>(
128         tcx: TyCtxt<'ll, 'tcx, 'tcx>,
129         cgu_name: InternedString,
130     ) -> ModuleCodegen<ModuleLlvm> {
131         let cgu = tcx.codegen_unit(cgu_name);
132         // Instantiate monomorphizations without filling out definitions yet...
133         let llvm_module = ModuleLlvm::new(tcx, &cgu_name.as_str());
134         {
135             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
136             let mono_items = cx.codegen_unit
137                                .items_in_deterministic_order(cx.tcx);
138             for &(mono_item, (linkage, visibility)) in &mono_items {
139                 mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility);
140             }
141
142             // ... and now that we have everything pre-defined, fill out those definitions.
143             for &(mono_item, _) in &mono_items {
144                 mono_item.define::<Builder<'_, '_, '_>>(&cx);
145             }
146
147             // If this codegen unit contains the main function, also create the
148             // wrapper here
149             maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx);
150
151             // Run replace-all-uses-with for statics that need it
152             for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
153                 unsafe {
154                     let bitcast = llvm::LLVMConstPointerCast(new_g, cx.val_ty(old_g));
155                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
156                     llvm::LLVMDeleteGlobal(old_g);
157                 }
158             }
159
160             // Create the llvm.used variable
161             // This variable has type [N x i8*] and is stored in the llvm.metadata section
162             if !cx.used_statics().borrow().is_empty() {
163                 cx.create_used_variable()
164             }
165
166             // Finalize debuginfo
167             if cx.sess().opts.debuginfo != DebugInfo::None {
168                 cx.debuginfo_finalize();
169             }
170         }
171
172         ModuleCodegen {
173             name: cgu_name.to_string(),
174             module_llvm: llvm_module,
175             kind: ModuleKind::Regular,
176         }
177     }
178 }
179
180 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
181     let sect = match attrs.link_section {
182         Some(name) => name,
183         None => return,
184     };
185     unsafe {
186         let buf = SmallCStr::new(&sect.as_str());
187         llvm::LLVMSetSection(llval, buf.as_ptr());
188     }
189 }
190
191 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
192     match linkage {
193         Linkage::External => llvm::Linkage::ExternalLinkage,
194         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
195         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
196         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
197         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
198         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
199         Linkage::Appending => llvm::Linkage::AppendingLinkage,
200         Linkage::Internal => llvm::Linkage::InternalLinkage,
201         Linkage::Private => llvm::Linkage::PrivateLinkage,
202         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
203         Linkage::Common => llvm::Linkage::CommonLinkage,
204     }
205 }
206
207 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
208     match linkage {
209         Visibility::Default => llvm::Visibility::Default,
210         Visibility::Hidden => llvm::Visibility::Hidden,
211         Visibility::Protected => llvm::Visibility::Protected,
212     }
213 }