5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(bool_to_option)]
9 #![feature(const_cstr_unchecked)]
10 #![feature(crate_visibility_modifier)]
11 #![feature(extern_types)]
12 #![feature(in_band_lifetimes)]
15 #![recursion_limit = "256"]
17 use back
::write
::{create_informational_target_machine, create_target_machine}
;
19 pub use llvm_util
::target_features
;
20 use rustc_ast
::expand
::allocator
::AllocatorKind
;
21 use rustc_codegen_ssa
::back
::lto
::{LtoModuleCodegen, SerializedModule, ThinModule}
;
22 use rustc_codegen_ssa
::back
::write
::{
23 CodegenContext
, FatLTOInput
, ModuleConfig
, TargetMachineFactoryConfig
, TargetMachineFactoryFn
,
25 use rustc_codegen_ssa
::traits
::*;
26 use rustc_codegen_ssa
::ModuleCodegen
;
27 use rustc_codegen_ssa
::{CodegenResults, CompiledModule}
;
28 use rustc_data_structures
::fx
::FxHashMap
;
29 use rustc_errors
::{ErrorReported, FatalError, Handler}
;
30 use rustc_metadata
::EncodedMetadata
;
31 use rustc_middle
::dep_graph
::{WorkProduct, WorkProductId}
;
32 use rustc_middle
::ty
::TyCtxt
;
33 use rustc_session
::config
::{OptLevel, OutputFilenames, PrintRequest}
;
34 use rustc_session
::Session
;
35 use rustc_span
::symbol
::Symbol
;
62 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
63 #[path = "llvm/mod.rs"]
66 pub use super::llvm_
::*;
77 pub struct LlvmCodegenBackend(());
79 struct TimeTraceProfiler
{
83 impl TimeTraceProfiler
{
84 fn new(enabled
: bool
) -> Self {
86 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
88 TimeTraceProfiler { enabled }
92 impl Drop
for TimeTraceProfiler
{
95 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
100 impl ExtraBackendMethods
for LlvmCodegenBackend
{
101 fn new_metadata(&self, tcx
: TyCtxt
<'_
>, mod_name
: &str) -> ModuleLlvm
{
102 ModuleLlvm
::new_metadata(tcx
, mod_name
)
105 fn write_compressed_metadata
<'tcx
>(
108 metadata
: &EncodedMetadata
,
109 llvm_module
: &mut ModuleLlvm
,
111 base
::write_compressed_metadata(tcx
, metadata
, llvm_module
)
113 fn codegen_allocator
<'tcx
>(
116 module_llvm
: &mut ModuleLlvm
,
119 has_alloc_error_handler
: bool
,
121 unsafe { allocator::codegen(tcx, module_llvm, module_name, kind, has_alloc_error_handler) }
123 fn compile_codegen_unit(
127 ) -> (ModuleCodegen
<ModuleLlvm
>, u64) {
128 base
::compile_codegen_unit(tcx
, cgu_name
)
130 fn target_machine_factory(
134 ) -> TargetMachineFactoryFn
<Self> {
135 back
::write
::target_machine_factory(sess
, optlvl
)
137 fn target_cpu
<'b
>(&self, sess
: &'b Session
) -> &'b
str {
138 llvm_util
::target_cpu(sess
)
140 fn tune_cpu
<'b
>(&self, sess
: &'b Session
) -> Option
<&'b
str> {
141 llvm_util
::tune_cpu(sess
)
144 fn spawn_thread
<F
, T
>(time_trace
: bool
, f
: F
) -> std
::thread
::JoinHandle
<T
>
150 std
::thread
::spawn(move || {
151 let _profiler
= TimeTraceProfiler
::new(time_trace
);
156 fn spawn_named_thread
<F
, T
>(
160 ) -> std
::io
::Result
<std
::thread
::JoinHandle
<T
>>
166 std
::thread
::Builder
::new().name(name
).spawn(move || {
167 let _profiler
= TimeTraceProfiler
::new(time_trace
);
173 impl WriteBackendMethods
for LlvmCodegenBackend
{
174 type Module
= ModuleLlvm
;
175 type ModuleBuffer
= back
::lto
::ModuleBuffer
;
176 type Context
= llvm
::Context
;
177 type TargetMachine
= &'
static mut llvm
::TargetMachine
;
178 type ThinData
= back
::lto
::ThinData
;
179 type ThinBuffer
= back
::lto
::ThinBuffer
;
180 fn print_pass_timings(&self) {
182 llvm
::LLVMRustPrintPassTimings();
186 cgcx
: &CodegenContext
<Self>,
187 diag_handler
: &Handler
,
188 modules
: Vec
<ModuleCodegen
<Self::Module
>>,
189 ) -> Result
<ModuleCodegen
<Self::Module
>, FatalError
> {
190 back
::write
::link(cgcx
, diag_handler
, modules
)
193 cgcx
: &CodegenContext
<Self>,
194 modules
: Vec
<FatLTOInput
<Self>>,
195 cached_modules
: Vec
<(SerializedModule
<Self::ModuleBuffer
>, WorkProduct
)>,
196 ) -> Result
<LtoModuleCodegen
<Self>, FatalError
> {
197 back
::lto
::run_fat(cgcx
, modules
, cached_modules
)
200 cgcx
: &CodegenContext
<Self>,
201 modules
: Vec
<(String
, Self::ThinBuffer
)>,
202 cached_modules
: Vec
<(SerializedModule
<Self::ModuleBuffer
>, WorkProduct
)>,
203 ) -> Result
<(Vec
<LtoModuleCodegen
<Self>>, Vec
<WorkProduct
>), FatalError
> {
204 back
::lto
::run_thin(cgcx
, modules
, cached_modules
)
207 cgcx
: &CodegenContext
<Self>,
208 diag_handler
: &Handler
,
209 module
: &ModuleCodegen
<Self::Module
>,
210 config
: &ModuleConfig
,
211 ) -> Result
<(), FatalError
> {
212 back
::write
::optimize(cgcx
, diag_handler
, module
, config
)
214 unsafe fn optimize_thin(
215 cgcx
: &CodegenContext
<Self>,
216 thin
: &mut ThinModule
<Self>,
217 ) -> Result
<ModuleCodegen
<Self::Module
>, FatalError
> {
218 back
::lto
::optimize_thin_module(thin
, cgcx
)
221 cgcx
: &CodegenContext
<Self>,
222 diag_handler
: &Handler
,
223 module
: ModuleCodegen
<Self::Module
>,
224 config
: &ModuleConfig
,
225 ) -> Result
<CompiledModule
, FatalError
> {
226 back
::write
::codegen(cgcx
, diag_handler
, module
, config
)
228 fn prepare_thin(module
: ModuleCodegen
<Self::Module
>) -> (String
, Self::ThinBuffer
) {
229 back
::lto
::prepare_thin(module
)
231 fn serialize_module(module
: ModuleCodegen
<Self::Module
>) -> (String
, Self::ModuleBuffer
) {
232 (module
.name
, back
::lto
::ModuleBuffer
::new(module
.module_llvm
.llmod()))
234 fn run_lto_pass_manager(
235 cgcx
: &CodegenContext
<Self>,
236 module
: &ModuleCodegen
<Self::Module
>,
237 config
: &ModuleConfig
,
239 ) -> Result
<(), FatalError
> {
240 let diag_handler
= cgcx
.create_diag_handler();
241 back
::lto
::run_pass_manager(cgcx
, &diag_handler
, module
, config
, thin
)
245 unsafe impl Send
for LlvmCodegenBackend {}
// Llvm is on a per-thread basis
246 unsafe impl Sync
for LlvmCodegenBackend {}
248 impl LlvmCodegenBackend
{
249 pub fn new() -> Box
<dyn CodegenBackend
> {
250 Box
::new(LlvmCodegenBackend(()))
254 impl CodegenBackend
for LlvmCodegenBackend
{
255 fn init(&self, sess
: &Session
) {
256 llvm_util
::init(sess
); // Make sure llvm is inited
259 fn print(&self, req
: PrintRequest
, sess
: &Session
) {
261 PrintRequest
::RelocationModels
=> {
262 println
!("Available relocation models:");
273 println
!(" {}", name
);
277 PrintRequest
::CodeModels
=> {
278 println
!("Available code models:");
279 for name
in &["tiny", "small", "kernel", "medium", "large"] {
280 println
!(" {}", name
);
284 PrintRequest
::TlsModels
=> {
285 println
!("Available TLS models:");
286 for name
in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
287 println
!(" {}", name
);
291 PrintRequest
::StackProtectorStrategies
=> {
293 r
#"Available stack protector strategies:
295 Generate stack canaries in all functions.
298 Generate stack canaries in a function if it either:
299 - has a local variable of `[T; N]` type, regardless of `T` and `N`
300 - takes the address of a local variable.
302 (Note that a local variable being borrowed is not equivalent to its
303 address being taken: e.g. some borrows may be removed by optimization,
304 while by-value argument passing may be implemented with reference to a
305 local stack variable in the ABI.)
308 Generate stack canaries in functions with:
309 - local variables of `[T; N]` type, where `T` is byte-sized and `N` > 8.
312 Do not generate stack canaries.
316 req
=> llvm_util
::print(req
, sess
),
320 fn print_passes(&self) {
321 llvm_util
::print_passes();
324 fn print_version(&self) {
325 llvm_util
::print_version();
328 fn target_features(&self, sess
: &Session
) -> Vec
<Symbol
> {
329 target_features(sess
)
332 fn codegen_crate
<'tcx
>(
335 metadata
: EncodedMetadata
,
336 need_metadata_module
: bool
,
338 Box
::new(rustc_codegen_ssa
::base
::codegen_crate(
339 LlvmCodegenBackend(()),
341 crate::llvm_util
::target_cpu(tcx
.sess
).to_string(),
343 need_metadata_module
,
349 ongoing_codegen
: Box
<dyn Any
>,
351 ) -> Result
<(CodegenResults
, FxHashMap
<WorkProductId
, WorkProduct
>), ErrorReported
> {
352 let (codegen_results
, work_products
) = ongoing_codegen
353 .downcast
::<rustc_codegen_ssa
::back
::write
::OngoingCodegen
<LlvmCodegenBackend
>>()
354 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
357 sess
.time("llvm_dump_timing_file", || {
358 if sess
.opts
.debugging_opts
.llvm_time_trace
{
359 llvm_util
::time_trace_profiler_finish("llvm_timings.json");
363 Ok((codegen_results
, work_products
))
369 codegen_results
: CodegenResults
,
370 outputs
: &OutputFilenames
,
371 ) -> Result
<(), ErrorReported
> {
372 use crate::back
::archive
::LlvmArchiveBuilder
;
373 use rustc_codegen_ssa
::back
::link
::link_binary
;
375 // Run the linker on any artifacts that resulted from the LLVM run.
376 // This should produce either a finished executable or library.
377 link_binary
::<LlvmArchiveBuilder
<'_
>>(sess
, &codegen_results
, outputs
)
381 pub struct ModuleLlvm
{
382 llcx
: &'
static mut llvm
::Context
,
383 llmod_raw
: *const llvm
::Module
,
384 tm
: &'
static mut llvm
::TargetMachine
,
387 unsafe impl Send
for ModuleLlvm {}
388 unsafe impl Sync
for ModuleLlvm {}
391 fn new(tcx
: TyCtxt
<'_
>, mod_name
: &str) -> Self {
393 let llcx
= llvm
::LLVMRustContextCreate(tcx
.sess
.fewer_names());
394 let llmod_raw
= context
::create_module(tcx
, llcx
, mod_name
) as *const _
;
395 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
399 fn new_metadata(tcx
: TyCtxt
<'_
>, mod_name
: &str) -> Self {
401 let llcx
= llvm
::LLVMRustContextCreate(tcx
.sess
.fewer_names());
402 let llmod_raw
= context
::create_module(tcx
, llcx
, mod_name
) as *const _
;
403 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
408 cgcx
: &CodegenContext
<LlvmCodegenBackend
>,
412 ) -> Result
<Self, FatalError
> {
414 let llcx
= llvm
::LLVMRustContextCreate(cgcx
.fewer_names
);
415 let llmod_raw
= back
::lto
::parse_module(llcx
, name
, buffer
, handler
)?
;
416 let tm_factory_config
= TargetMachineFactoryConfig
::new(cgcx
, name
.to_str().unwrap());
417 let tm
= match (cgcx
.tm_factory
)(tm_factory_config
) {
420 handler
.struct_err(&e
).emit();
421 return Err(FatalError
);
425 Ok(ModuleLlvm { llmod_raw, llcx, tm }
)
429 fn llmod(&self) -> &llvm
::Module
{
430 unsafe { &*self.llmod_raw }
434 impl Drop
for ModuleLlvm
{
437 llvm
::LLVMRustDisposeTargetMachine(&mut *(self.tm
as *mut _
));
438 llvm
::LLVMContextDispose(&mut *(self.llcx
as *mut _
));