Skip to main content

rustc_codegen_spirv/
lib.rs

1// HACK(eddyb) start of `rustc_codegen_ssa` crate-level attributes (see `build.rs`).
2#![feature(deref_patterns)]
3#![feature(file_buffered)]
4#![feature(negative_impls)]
5#![feature(string_from_utf8_lossy_owned)]
6#![feature(trait_alias)]
7#![feature(try_blocks)]
8#![recursion_limit = "256"]
9// HACK(eddyb) end of `rustc_codegen_ssa` crate-level attributes (see `build.rs`).
10
11//! Welcome to the API documentation for the `rust-gpu` project, this API is
12//! unstable and mainly intended for developing on the project itself. This is
13//! the API documentation for `rustc_codegen_spirv` which is not that useful on
14//! its own. You might also be interested in the following crates. There's also
15//! the [Rust GPU Dev Guide][gpu-dev-guide] which contains more user-level
16//! information on how to use and setup `rust-gpu`.
17//!
18//! - [`spirv-builder`]
19//! - [`spirv-std`]
20//! - [`spirv-tools`]
21//! - [`spirv-tools-sys`]
22//!
23//! [gpu-dev-guide]: https://rust-gpu.github.io/rust-gpu/book
24//! [`spirv-builder`]: https://rust-gpu.github.io/rust-gpu/api/spirv_builder
25//! [`spirv-std`]: https://rust-gpu.github.io/rust-gpu/api/spirv_std
26//! [`spirv-tools`]: https://rust-gpu.github.io/rust-gpu/api/spirv_tools
27//! [`spirv-tools-sys`]: https://rust-gpu.github.io/rust-gpu/api/spirv_tools_sys
28#![feature(rustc_private)]
29// In `rustc_codegen_spirv_disable_pqp_cg_ssa` mode we stop `include!`ing the
30// patched `rustc_codegen_ssa`, so these copied crate-level feature gates can
31// become locally unused even though the default build still needs them.
32#![cfg_attr(rustc_codegen_spirv_disable_pqp_cg_ssa, allow(unused_features))]
33// crate-specific exceptions:
34#![allow(
35    clippy::enum_glob_use,      // pretty useful pattern with some codegen'd enums (e.g. rspirv::spirv::Op)
36    clippy::todo,               // still lots to implement :)
37
38    // FIXME(eddyb) new warnings from 1.83 rustup, apply their suggested changes.
39    mismatched_lifetime_syntaxes,
40)]
41
42// Unfortunately, this will not fail fast when compiling, but rather will wait for
43// rustc_codegen_spirv to be compiled. Putting this in build.rs will solve that problem, however,
44// that creates the much worse problem that then running `cargo check` will cause
45// rustc_codegen_spirv to be *compiled* instead of merely checked, something that takes
46// significantly longer. So, the trade-off between detecting a bad configuration slower for a
47// faster `cargo check` is worth it.
48#[cfg(all(feature = "use-compiled-tools", feature = "use-installed-tools"))]
49compile_error!(
50    "Either \"use-compiled-tools\" (enabled by default) or \"use-installed-tools\" may be enabled."
51);
52
53// HACK(eddyb) `build.rs` copies `rustc_codegen_ssa` (from the `rustc-dev` component)
54// and patches it to produce a "pqp" ("pre-`qptr`-patched") version that maintains
55// compatibility with "legacy" Rust-GPU pointer handling (mainly typed `alloca`s).
56//
57// FIXME(eddyb) get rid of this as soon as it's not needed anymore.
58#[cfg(not(rustc_codegen_spirv_disable_pqp_cg_ssa))]
59include!(concat!(env!("OUT_DIR"), "/pqp_cg_ssa.rs"));
60
61// HACK(eddyb) guide `rustc` to finding the right deps in the sysroot, which
62// (sadly) has to be outside `include!` to have any effect whatsoever.
63// FIXME(eddyb) this only really handles `bitflags`, not `object`.
64#[cfg(not(rustc_codegen_spirv_disable_pqp_cg_ssa))]
65mod _rustc_codegen_ssa_transitive_deps_hack {
66    extern crate rustc_codegen_ssa as _;
67}
68
69// NOTE(eddyb) `mod maybe_pqp_cg_ssa` is defined by the above `include`, when
70// in the (default for now) `pqp_cg_ssa` mode (see `build.rs`).
71#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
72use rustc_codegen_ssa as maybe_pqp_cg_ssa;
73
74// FIXME(eddyb) remove all `#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]`
75// as soon as they're not needed anymore (i.e. using `rustc_codegen_ssa` again).
76#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
77extern crate rustc_abi;
78extern crate rustc_apfloat;
79#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
80extern crate rustc_arena;
81#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
82extern crate rustc_ast;
83#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
84extern crate rustc_attr_parsing;
85#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
86extern crate rustc_codegen_ssa;
87#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
88extern crate rustc_data_structures;
89extern crate rustc_driver;
90#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
91extern crate rustc_errors;
92#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
93extern crate rustc_hashes;
94#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
95extern crate rustc_hir;
96#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
97extern crate rustc_index;
98extern crate rustc_interface;
99#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
100extern crate rustc_metadata;
101#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
102extern crate rustc_middle;
103#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
104extern crate rustc_session;
105#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
106extern crate rustc_span;
107#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
108extern crate rustc_target;
109
110macro_rules! assert_ty_eq {
111    ($codegen_cx:expr, $left:expr, $right:expr) => {
112        assert!(
113            $left == $right,
114            "Expected types to be equal:\n{}\n==\n{}",
115            $codegen_cx.debug_type($left),
116            $codegen_cx.debug_type($right)
117        )
118    };
119}
120
121mod abi;
122mod attr;
123mod builder;
124mod builder_spirv;
125mod codegen_cx;
126mod custom_decorations;
127mod custom_insts;
128mod link;
129mod linker;
130mod naga_transpile;
131mod spirv_type;
132mod spirv_type_constraints;
133mod symbols;
134pub mod target;
135mod target_feature;
136
137use crate::maybe_pqp_cg_ssa::back::write::ThinLtoInput;
138use builder::Builder;
139use codegen_cx::CodegenCx;
140use maybe_pqp_cg_ssa::back::lto::ThinModule;
141use maybe_pqp_cg_ssa::back::write::{
142    CodegenContext, FatLtoInput, ModuleConfig, OngoingCodegen, SharedEmitter,
143    TargetMachineFactoryFn,
144};
145use maybe_pqp_cg_ssa::base::maybe_create_entry_wrapper;
146use maybe_pqp_cg_ssa::mono_item::MonoItemExt;
147use maybe_pqp_cg_ssa::traits::{
148    CodegenBackend, ExtraBackendMethods, ModuleBufferMethods, WriteBackendMethods,
149};
150use maybe_pqp_cg_ssa::{
151    CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind, TargetConfig,
152};
153use rspirv::binary::Assemble;
154use rustc_ast::expand::allocator::AllocatorMethod;
155use rustc_data_structures::fx::FxIndexMap;
156use rustc_data_structures::profiling::SelfProfilerRef;
157use rustc_errors::DiagCtxtHandle;
158use rustc_metadata::EncodedMetadata;
159use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
160use rustc_middle::mono::{MonoItem, MonoItemData};
161use rustc_middle::ty::print::with_no_trimmed_paths;
162use rustc_middle::ty::{InstanceKind, TyCtxt};
163use rustc_session::Session;
164use rustc_session::config::{self, OutputFilenames, OutputType};
165use rustc_span::symbol::Symbol;
166use std::any::Any;
167use std::fs;
168use std::io::Write;
169use std::path::{Path, PathBuf};
170use std::sync::Arc;
171use tracing::error;
172
173fn dump_mir<'tcx>(
174    tcx: TyCtxt<'tcx>,
175    mono_items: &[(MonoItem<'tcx>, MonoItemData)],
176    path: &Path,
177) -> std::io::Result<()> {
178    use rustc_middle::mir::pretty::MirWriter;
179    fs::create_dir_all(path.parent().unwrap())?;
180    let mut file = fs::File::create(path)?;
181    for &(mono_item, _) in mono_items {
182        if let MonoItem::Fn(instance) = mono_item
183            && matches!(instance.def, InstanceKind::Item(_))
184        {
185            let mut w = Vec::new();
186            let writer = MirWriter::new(tcx);
187            writer.write_mir_fn(tcx.instance_mir(instance.def), &mut w)?;
188            file.write_all(w.as_slice())?;
189            writeln!(file)?;
190        }
191    }
192    Ok(())
193}
194
195#[derive(Clone)]
196struct SpirvCodegenBackend;
197
198impl CodegenBackend for SpirvCodegenBackend {
199    fn init(&self, sess: &Session) {
200        // Set up logging/tracing. See https://github.com/Rust-GPU/rust-gpu/issues/192.
201        init_logging(sess);
202    }
203
204    fn target_config(&self, sess: &Session) -> TargetConfig {
205        let cmdline = sess.opts.cg.target_feature.split(',');
206        let cfg = sess.target.options.features.split(',');
207
208        let target_features: Vec<_> = cfg
209            .chain(cmdline)
210            .filter(|l| l.starts_with('+'))
211            .map(|l| &l[1..])
212            .filter(|l| !l.is_empty())
213            .map(Symbol::intern)
214            .collect();
215
216        // HACK(eddyb) this should be a superset of `target_features`,
217        // which *additionally* also includes unstable target features,
218        // but there is no reason to make a distinction for SPIR-V ones.
219        let unstable_target_features = target_features.clone();
220
221        TargetConfig {
222            target_features,
223            unstable_target_features,
224
225            // FIXME(eddyb) support and/or emulate `f16` and `f128`.
226            has_reliable_f16: false,
227            has_reliable_f16_math: false,
228            has_reliable_f128: false,
229            has_reliable_f128_math: false,
230        }
231    }
232
233    fn provide(&self, providers: &mut rustc_middle::util::Providers) {
234        // FIXME(eddyb) this is currently only passed back to us, specifically
235        // into `target_machine_factory` (which is a noop), but it might make
236        // sense to move some of the target feature parsing into here.
237        providers.queries.global_backend_features = |_tcx, ()| vec![];
238
239        crate::abi::provide(providers);
240        crate::attr::provide(&mut providers.queries);
241    }
242
243    fn target_cpu(&self, sess: &Session) -> String {
244        sess.opts
245            .cg
246            .target_cpu
247            .clone()
248            .unwrap_or_else(|| sess.target.cpu.to_string())
249    }
250
251    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
252        Box::new(maybe_pqp_cg_ssa::base::codegen_crate(Self, tcx))
253    }
254
255    fn join_codegen(
256        &self,
257        ongoing_codegen: Box<dyn Any>,
258        sess: &Session,
259        _outputs: &OutputFilenames,
260        crate_info: &CrateInfo,
261    ) -> (CompiledModules, FxIndexMap<WorkProductId, WorkProduct>) {
262        ongoing_codegen
263            .downcast::<OngoingCodegen<Self>>()
264            .expect("Expected OngoingCodegen, found Box<Any>")
265            .join(sess, crate_info)
266    }
267
268    fn link(
269        &self,
270        sess: &Session,
271        compiled_modules: CompiledModules,
272        crate_info: CrateInfo,
273        metadata: EncodedMetadata,
274        outputs: &OutputFilenames,
275    ) {
276        let timer = sess.timer("link_crate");
277        link::link(
278            sess,
279            &compiled_modules,
280            &crate_info,
281            &metadata,
282            outputs,
283            crate_info.local_crate_name.as_str(),
284        );
285        drop(timer);
286    }
287
288    fn name(&self) -> &'static str {
289        "SpirvCodegenBackend"
290    }
291}
292
293struct SpirvModuleBuffer(Vec<u32>);
294
295impl SpirvModuleBuffer {
296    fn as_bytes(&self) -> &[u8] {
297        spirv_tools::binary::from_binary(&self.0)
298    }
299}
300impl ModuleBufferMethods for SpirvModuleBuffer {
301    fn data(&self) -> &[u8] {
302        self.as_bytes()
303    }
304}
305
306impl SpirvCodegenBackend {
307    fn optimize_common(
308        _cgcx: &CodegenContext,
309        module: &mut ModuleCodegen<<Self as WriteBackendMethods>::Module>,
310    ) {
311        // Apply DCE ("dead code elimination") to modules before ever serializing
312        // them as `.spv` files (technically, `.rcgu.o` files inside `.rlib`s),
313        // that will later get linked (potentially many times, esp. if this is
314        // some big upstream library, e.g. `core` itself), and will therefore
315        // benefit from not having to clean up all sorts of unreachable helpers.
316        linker::dce::dce(&mut module.module_llvm);
317
318        // FIXME(eddyb) run as many optimization passes as possible, not just DCE.
319    }
320}
321
322impl WriteBackendMethods for SpirvCodegenBackend {
323    type Module = rspirv::dr::Module;
324    type TargetMachine = ();
325    type ModuleBuffer = SpirvModuleBuffer;
326    type ThinData = ();
327
328    // FIXME(eddyb) reuse the "merge" stage of `crate::linker` for this, or even
329    // consider setting `requires_lto = true` in the target specs and moving the
330    // entirety of `crate::linker` into this stage (lacking diagnostics may be
331    // an issue - it's surprising `CodegenBackend::link` has `Session` at all).
332    fn optimize_and_codegen_fat_lto(
333        _sess: &Session,
334        cgcx: &CodegenContext,
335        _shared_emitter: &SharedEmitter,
336        _tm_factory: TargetMachineFactoryFn<Self>,
337        _exported_symbols_for_lto: &[String],
338        _each_linked_rlib_for_lto: &[PathBuf],
339        _modules: Vec<FatLtoInput<Self>>,
340    ) -> CompiledModule {
341        assert!(
342            cgcx.lto == config::Lto::Fat,
343            "`optimize_and_codegen_fat_lto` should \
344             only be invoked due to `-Clto` (or equivalent)"
345        );
346        unreachable!("Rust-GPU does not support fat LTO")
347    }
348
349    fn run_thin_lto(
350        _cgcx: &CodegenContext,
351        _prof: &SelfProfilerRef,
352        _dcx: DiagCtxtHandle<'_>,
353        _exported_symbols_for_lto: &[String],
354        _each_linked_rlib_for_lto: &[PathBuf],
355        _modules: Vec<ThinLtoInput<Self>>,
356    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
357        // Note(@firestar99): gcc impl this as unreachable as well
358        unreachable!()
359    }
360
361    fn optimize(
362        cgcx: &CodegenContext,
363        _prof: &SelfProfilerRef,
364        _shared_emitter: &SharedEmitter,
365        module: &mut ModuleCodegen<Self::Module>,
366        _config: &ModuleConfig,
367    ) {
368        Self::optimize_common(cgcx, module);
369    }
370
371    fn optimize_and_codegen_thin(
372        cgcx: &CodegenContext,
373        prof: &SelfProfilerRef,
374        shared_emitter: &SharedEmitter,
375        _tm_factory: TargetMachineFactoryFn<Self>,
376        thin_module: ThinModule<Self>,
377    ) -> CompiledModule {
378        // FIXME(eddyb) the inefficiency of Module -> [u8] -> Module roundtrips
379        // comes from upstream and it applies to `rustc_codegen_llvm` as well,
380        // eventually it should be properly addressed (for `ThinLocal` at least).
381        let mut module = ModuleCodegen {
382            module_llvm: link::with_rspirv_loader(|loader| {
383                rspirv::binary::parse_bytes(thin_module.data(), loader)
384            })
385            .unwrap(),
386            name: thin_module.name().to_string(),
387            kind: ModuleKind::Regular,
388            thin_lto_buffer: None,
389        };
390        Self::optimize_common(cgcx, &mut module);
391        Self::codegen(cgcx, prof, shared_emitter, module, &cgcx.module_config)
392    }
393
394    fn codegen(
395        cgcx: &CodegenContext,
396        _prof: &SelfProfilerRef,
397        _shared_emitter: &SharedEmitter,
398        module: ModuleCodegen<Self::Module>,
399        _config: &ModuleConfig,
400    ) -> CompiledModule {
401        let kind = module.kind;
402        let name = module.name;
403        let module_buffer = Self::serialize_module(module.module_llvm, false);
404
405        let path = cgcx
406            .output_filenames
407            .temp_path_for_cgu(OutputType::Object, &name);
408        fs::write(&path, module_buffer.as_bytes()).unwrap();
409
410        CompiledModule {
411            name,
412            kind,
413            object: Some(path),
414            dwarf_object: None,
415            bytecode: None,
416            assembly: None,
417            llvm_ir: None,
418            links_from_incr_cache: vec![],
419        }
420    }
421
422    fn serialize_module(module: Self::Module, _is_thin: bool) -> Self::ModuleBuffer {
423        SpirvModuleBuffer(module.assemble())
424    }
425
426    fn target_machine_factory(
427        &self,
428        _sess: &Session,
429        _opt_level: config::OptLevel,
430        _target_features: &[String],
431    ) -> TargetMachineFactoryFn<Self> {
432        Arc::new(|_, _| ())
433    }
434}
435
436impl ExtraBackendMethods for SpirvCodegenBackend {
437    fn codegen_allocator(&self, _: TyCtxt<'_>, _: &str, _: &[AllocatorMethod]) -> Self::Module {
438        todo!()
439    }
440
441    fn compile_codegen_unit<'tcx>(
442        &self,
443        tcx: TyCtxt<'tcx>,
444        cgu_name: Symbol,
445    ) -> (ModuleCodegen<Self::Module>, u64) {
446        let _timer = tcx
447            .prof
448            .verbose_generic_activity_with_arg("codegen_module", cgu_name.to_string());
449
450        // TODO: Do dep_graph stuff
451        let cgu = tcx.codegen_unit(cgu_name);
452
453        let mut cx = CodegenCx::new(tcx, cgu);
454        let do_codegen = |cx: &mut CodegenCx<'tcx>| {
455            let mono_items = cgu.items_in_deterministic_order(cx.tcx);
456
457            if let Some(dir) = &cx.codegen_args.dump_mir {
458                dump_mir(tcx, mono_items.as_slice(), &dir.join(cgu_name.to_string())).unwrap();
459            }
460
461            for &(mono_item, mono_item_data) in mono_items.iter() {
462                mono_item.predefine::<Builder<'_, '_>>(
463                    cx,
464                    cgu_name.as_str(),
465                    mono_item_data.linkage,
466                    mono_item_data.visibility,
467                );
468            }
469
470            // ... and now that we have everything pre-defined, fill out those definitions.
471            for &(mono_item, mono_item_data) in &mono_items {
472                tracing::trace!(?mono_item, "defining");
473                mono_item.define::<Builder<'_, '_>>(cx, cgu_name.as_str(), mono_item_data);
474            }
475
476            if let Some(_entry) = maybe_create_entry_wrapper::<Builder<'_, '_>>(cx, cgu) {
477                // attributes::sanitize(&cx, SanitizerSet::empty(), entry);
478            }
479        };
480        // HACK(eddyb) mutable access needed for `mono_item.define::<...>(cx, ...)`
481        // but that alone leads to needless cloning and smuggling a mutable borrow
482        // through `DumpModuleOnPanic` (for both its `Drop` impl and `do_codegen`).
483        if let Some(path) = cx.codegen_args.dump_module_on_panic.clone() {
484            let module_dumper = DumpModuleOnPanic {
485                cx: &mut cx,
486                path: &path,
487            };
488            with_no_trimmed_paths!(do_codegen(module_dumper.cx));
489            drop(module_dumper);
490        } else {
491            with_no_trimmed_paths!(do_codegen(&mut cx));
492        }
493
494        (
495            ModuleCodegen {
496                name: cgu_name.to_string(),
497                module_llvm: cx.finalize_module(),
498                kind: ModuleKind::Regular,
499                thin_lto_buffer: None,
500            },
501            0,
502        )
503    }
504}
505
506struct DumpModuleOnPanic<'a, 'cx, 'tcx> {
507    cx: &'cx mut CodegenCx<'tcx>,
508    path: &'a Path,
509}
510
511impl Drop for DumpModuleOnPanic<'_, '_, '_> {
512    fn drop(&mut self) {
513        if std::thread::panicking() {
514            if self.path.has_root() {
515                self.cx.builder.dump_module(self.path);
516            } else {
517                error!("{}", self.cx.builder.dump_module_str());
518            }
519        }
520    }
521}
522
523/// This is the entrypoint for a hot plugged `rustc_codegen_spirv`
524#[unsafe(no_mangle)]
525pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
526    // Tweak rustc's default ICE panic hook, to direct people to `rust-gpu`.
527    rustc_driver::install_ice_hook("https://github.com/rust-gpu/rust-gpu/issues/new", |dcx| {
528        dcx.handle().note(concat!(
529            "`rust-gpu` version `",
530            env!("CARGO_PKG_VERSION"),
531            "`"
532        ));
533    });
534
535    Box::new(SpirvCodegenBackend)
536}
537
538// Set up logging/tracing. See https://github.com/Rust-GPU/rust-gpu/issues/192.
539fn init_logging(sess: &Session) {
540    use std::env::{self, VarError};
541    use std::io::{self, IsTerminal};
542    use tracing_subscriber::layer::SubscriberExt;
543
544    // Set up the default subscriber with optional filtering.
545    let filter = tracing_subscriber::EnvFilter::from_env("RUSTGPU_LOG");
546    #[cfg(not(rustc_codegen_spirv_disable_pqp_cg_ssa))]
547    let filter = filter.add_directive("rustc_codegen_spirv::maybe_pqp_cg_ssa=off".parse().unwrap());
548    let subscriber = tracing_subscriber::Registry::default().with(filter);
549
550    #[derive(Debug, Default)]
551    enum OutputFormat {
552        #[default]
553        Tree,
554        Flat,
555        Json,
556    }
557
558    let output_format = match env::var("RUSTGPU_LOG_FORMAT").as_deref() {
559        Ok("tree") | Err(VarError::NotPresent) => OutputFormat::Tree,
560        Ok("flat") => OutputFormat::Flat,
561        Ok("json") => OutputFormat::Json,
562        Ok(value) => sess.dcx().fatal(format!(
563            "invalid output format value '{value}': expected one of tree, flat, or json",
564        )),
565        Err(VarError::NotUnicode(value)) => sess.dcx().fatal(format!(
566            "invalid output format value '{}': expected one of tree, flat, or json",
567            value.to_string_lossy()
568        )),
569    };
570
571    let subscriber: Box<dyn tracing::Subscriber + Send + Sync> = match output_format {
572        OutputFormat::Tree => {
573            // TODO(@LegNeato): Query dcx color support when rustc exposes it.
574            let color_logs = match env::var("RUSTGPU_LOG_COLOR").as_deref() {
575                Ok("always") => true,
576                Ok("never") => false,
577                Ok("auto") | Err(VarError::NotPresent) => io::stderr().is_terminal(),
578                Ok(value) => sess.dcx().fatal(format!(
579                    "invalid log color value '{value}': expected one of always, never, or auto",
580                )),
581                Err(VarError::NotUnicode(value)) => sess.dcx().fatal(format!(
582                    "invalid log color value '{}': expected one of always, never, or auto",
583                    value.to_string_lossy()
584                )),
585            };
586
587            let tree_layer = tracing_tree::HierarchicalLayer::default()
588                .with_writer(io::stderr)
589                .with_ansi(color_logs)
590                .with_targets(true)
591                .with_wraparound(10)
592                .with_verbose_exit(true)
593                .with_verbose_entry(true)
594                .with_indent_amount(2);
595
596            #[cfg(debug_assertions)]
597            let tree_layer = tree_layer.with_thread_ids(true).with_thread_names(true);
598
599            Box::new(subscriber.with(tree_layer))
600        }
601        OutputFormat::Flat => Box::new(subscriber),
602        OutputFormat::Json => Box::new(subscriber.with(tracing_subscriber::fmt::layer().json())),
603    };
604    tracing::subscriber::set_global_default(subscriber).unwrap();
605}