@@ -358,10 +358,16 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
358358 continue ;
359359 }
360360
361- // Skip statics with explicit #[address_space] attributes
361+ // Handle statics with explicit #[address_space] attributes:
362+ // count #[address_space(constant)] toward the reservation (they
363+ // consume constant memory), skip all others.
362364 let attrs = self . tcx . get_all_attrs ( def_id) ;
363365 let nvvm_attrs = NvvmAttributes :: parse ( self , attrs) ;
364- if nvvm_attrs. addrspace . is_some ( ) {
366+ if let Some ( addr) = nvvm_attrs. addrspace {
367+ if addr == 4 {
368+ let layout = self . layout_of ( ty) ;
369+ reserved += layout. size . bytes ( ) ;
370+ }
365371 continue ;
366372 }
367373
@@ -419,6 +425,34 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
419425
420426 // Priority 1: Explicit #[address_space] attribute always wins
421427 if let Some ( addr) = nvvm_attrs. addrspace {
428+ // Track constant memory usage for #[address_space(constant)] so we
429+ // don't silently exceed the 64KB hardware limit.
430+ if addr == 4 {
431+ let layout = self . layout_of ( ty) ;
432+ let size_bytes = layout. size . bytes ( ) ;
433+ let current_usage = self . constant_memory_usage . get ( ) ;
434+ let new_usage = current_usage + size_bytes;
435+ self . constant_memory_usage . set ( new_usage) ;
436+ self . explicit_constant_memory_placed
437+ . set ( self . explicit_constant_memory_placed . get ( ) + size_bytes) ;
438+
439+ if new_usage > CONSTANT_MEMORY_SIZE_LIMIT_BYTES {
440+ let def_id = instance. def_id ( ) ;
441+ let span = self . tcx . def_span ( def_id) ;
442+ let mut diag = self . tcx . sess . dcx ( ) . struct_span_warn (
443+ span,
444+ format ! (
445+ "constant memory overflow: static `{instance}` ({size_bytes} bytes) \
446+ causes total constant memory usage ({new_usage} bytes) to exceed \
447+ the {CONSTANT_MEMORY_SIZE_LIMIT_BYTES} byte hardware limit",
448+ ) ,
449+ ) ;
450+ diag. span_label ( span, "placed via explicit #[address_space(constant)]" ) ;
451+ diag. note ( "this will likely cause runtime errors" ) ;
452+ diag. help ( "consider moving some statics to global memory" ) ;
453+ diag. emit ( ) ;
454+ }
455+ }
422456 return AddressSpace ( addr as u32 ) ;
423457 }
424458
0 commit comments