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