1 //! Codegen the completed AST to the LLVM IR.
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.
8 //! Hopefully useful general knowledge about codegen:
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`.
16 use super::{LlvmCodegenBackend, ModuleLlvm};
17 use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
18 use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
22 use crate::builder::Builder;
24 use crate::context::CodegenCx;
26 use rustc::mir::mono::{Linkage, Visibility};
27 use rustc::middle::cstore::{EncodedMetadata};
28 use rustc::ty::TyCtxt;
29 use rustc::middle::exported_symbols;
30 use rustc::session::config::DebugInfo;
31 use rustc_codegen_ssa::mono_item::MonoItemExt;
32 use rustc_data_structures::small_c_str::SmallCStr;
34 use rustc_codegen_ssa::traits::*;
35 use rustc_codegen_ssa::back::write::submit_codegened_module_to_llvm;
37 use std::ffi::CString;
38 use std::time::Instant;
39 use syntax_pos::symbol::InternedString;
40 use rustc::hir::CodegenFnAttrs;
42 use crate::value::Value;
44 pub fn write_compressed_metadata<'a, 'gcx>(
45 tcx: TyCtxt<'a, 'gcx, 'gcx>,
46 metadata: &EncodedMetadata,
47 llvm_module: &mut ModuleLlvm
50 use flate2::Compression;
51 use flate2::write::DeflateEncoder;
53 let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
54 let mut compressed = tcx.metadata_encoding_version();
55 DeflateEncoder::new(&mut compressed, Compression::fast())
56 .write_all(&metadata.raw_data).unwrap();
58 let llmeta = common::bytes_in_context(metadata_llcx, &compressed);
59 let llconst = common::struct_in_context(metadata_llcx, &[llmeta], false);
60 let name = exported_symbols::metadata_symbol_name(tcx);
61 let buf = CString::new(name).unwrap();
62 let llglobal = unsafe {
63 llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr())
66 llvm::LLVMSetInitializer(llglobal, llconst);
67 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
68 let name = SmallCStr::new(section_name);
69 llvm::LLVMSetSection(llglobal, name.as_ptr());
71 // Also generate a .section directive to force no
72 // flags, at least for ELF outputs, so that the
73 // metadata doesn't get loaded into memory.
74 let directive = format!(".section {}", section_name);
75 let directive = CString::new(directive).unwrap();
76 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
80 pub struct ValueIter<'ll> {
81 cur: Option<&'ll Value>,
82 step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
85 impl Iterator for ValueIter<'ll> {
86 type Item = &'ll Value;
88 fn next(&mut self) -> Option<&'ll Value> {
90 if let Some(old) = old {
91 self.cur = unsafe { (self.step)(old) };
97 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
100 cur: llvm::LLVMGetFirstGlobal(llmod),
101 step: llvm::LLVMGetNextGlobal,
106 pub fn compile_codegen_unit(tcx: TyCtxt<'a, 'tcx, 'tcx>, cgu_name: InternedString) {
107 let start_time = Instant::now();
109 let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
110 let (module, _) = tcx.dep_graph.with_task(
115 dep_graph::hash_result,
117 let time_to_codegen = start_time.elapsed();
119 // We assume that the cost to run LLVM on a CGU is proportional to
120 // the time we needed for codegenning it.
121 let cost = time_to_codegen.as_secs() * 1_000_000_000 +
122 time_to_codegen.subsec_nanos() as u64;
124 submit_codegened_module_to_llvm(&LlvmCodegenBackend(()), tcx, module, cost);
126 fn module_codegen<'ll, 'tcx>(
127 tcx: TyCtxt<'ll, 'tcx, 'tcx>,
128 cgu_name: InternedString,
129 ) -> ModuleCodegen<ModuleLlvm> {
130 let cgu = tcx.codegen_unit(cgu_name);
131 // Instantiate monomorphizations without filling out definitions yet...
132 let llvm_module = ModuleLlvm::new(tcx, &cgu_name.as_str());
134 let cx = CodegenCx::new(tcx, cgu, &llvm_module);
135 let mono_items = cx.codegen_unit
136 .items_in_deterministic_order(cx.tcx);
137 for &(mono_item, (linkage, visibility)) in &mono_items {
138 mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility);
141 // ... and now that we have everything pre-defined, fill out those definitions.
142 for &(mono_item, _) in &mono_items {
143 mono_item.define::<Builder<'_, '_, '_>>(&cx);
146 // If this codegen unit contains the main function, also create the
148 maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx);
150 // Run replace-all-uses-with for statics that need it
151 for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
153 let bitcast = llvm::LLVMConstPointerCast(new_g, cx.val_ty(old_g));
154 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
155 llvm::LLVMDeleteGlobal(old_g);
159 // Create the llvm.used variable
160 // This variable has type [N x i8*] and is stored in the llvm.metadata section
161 if !cx.used_statics().borrow().is_empty() {
162 cx.create_used_variable()
165 // Finalize debuginfo
166 if cx.sess().opts.debuginfo != DebugInfo::None {
167 cx.debuginfo_finalize();
172 name: cgu_name.to_string(),
173 module_llvm: llvm_module,
174 kind: ModuleKind::Regular,
179 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
180 let sect = match attrs.link_section {
185 let buf = SmallCStr::new(§.as_str());
186 llvm::LLVMSetSection(llval, buf.as_ptr());
190 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
192 Linkage::External => llvm::Linkage::ExternalLinkage,
193 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
194 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
195 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
196 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
197 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
198 Linkage::Appending => llvm::Linkage::AppendingLinkage,
199 Linkage::Internal => llvm::Linkage::InternalLinkage,
200 Linkage::Private => llvm::Linkage::PrivateLinkage,
201 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
202 Linkage::Common => llvm::Linkage::CommonLinkage,
206 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
208 Visibility::Default => llvm::Visibility::Default,
209 Visibility::Hidden => llvm::Visibility::Hidden,
210 Visibility::Protected => llvm::Visibility::Protected,