1#![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#![feature(rustc_private)]
29#![cfg_attr(rustc_codegen_spirv_disable_pqp_cg_ssa, allow(unused_features))]
33#![allow(
35 clippy::enum_glob_use, clippy::todo, mismatched_lifetime_syntaxes,
40)]
41
42#[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#[cfg(not(rustc_codegen_spirv_disable_pqp_cg_ssa))]
59include!(concat!(env!("OUT_DIR"), "/pqp_cg_ssa.rs"));
60
61#[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#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
72use rustc_codegen_ssa as maybe_pqp_cg_ssa;
73
74#[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 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 let unstable_target_features = target_features.clone();
220
221 TargetConfig {
222 target_features,
223 unstable_target_features,
224
225 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 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 linker::dce::dce(&mut module.module_llvm);
317
318 }
320}
321
322impl WriteBackendMethods for SpirvCodegenBackend {
323 type Module = rspirv::dr::Module;
324 type TargetMachine = ();
325 type ModuleBuffer = SpirvModuleBuffer;
326 type ThinData = ();
327
328 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 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 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 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 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 }
479 };
480 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#[unsafe(no_mangle)]
525pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
526 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
538fn init_logging(sess: &Session) {
540 use std::env::{self, VarError};
541 use std::io::{self, IsTerminal};
542 use tracing_subscriber::layer::SubscriberExt;
543
544 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 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}