]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/constant.rs
Auto merge of #102340 - JakobDegen:pass-manager-simplification, r=oli-obk
[rust.git] / compiler / rustc_codegen_cranelift / src / constant.rs
1 //! Handling of `static`s, `const`s and promoted allocations
2
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
5 use rustc_middle::mir::interpret::{
6     read_target_uint, AllocId, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, Scalar,
7 };
8 use rustc_span::DUMMY_SP;
9
10 use cranelift_module::*;
11
12 use crate::prelude::*;
13
14 pub(crate) struct ConstantCx {
15     todo: Vec<TodoItem>,
16     done: FxHashSet<DataId>,
17     anon_allocs: FxHashMap<AllocId, DataId>,
18 }
19
20 #[derive(Copy, Clone, Debug)]
21 enum TodoItem {
22     Alloc(AllocId),
23     Static(DefId),
24 }
25
26 impl ConstantCx {
27     pub(crate) fn new() -> Self {
28         ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
29     }
30
31     pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
32         //println!("todo {:?}", self.todo);
33         define_all_allocs(tcx, module, &mut self);
34         //println!("done {:?}", self.done);
35         self.done.clear();
36     }
37 }
38
39 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
40     let mut all_constants_ok = true;
41     for constant in &fx.mir.required_consts {
42         let unevaluated = match fx.monomorphize(constant.literal) {
43             ConstantKind::Ty(_) => unreachable!(),
44             ConstantKind::Unevaluated(uv, _) => uv,
45             ConstantKind::Val(..) => continue,
46         };
47
48         if let Err(err) = fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
49             all_constants_ok = false;
50             match err {
51                 ErrorHandled::Reported(_) | ErrorHandled::Linted => {
52                     fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
53                 }
54                 ErrorHandled::TooGeneric => {
55                     span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
56                 }
57             }
58         }
59     }
60     all_constants_ok
61 }
62
63 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
64     let mut constants_cx = ConstantCx::new();
65     constants_cx.todo.push(TodoItem::Static(def_id));
66     constants_cx.finalize(tcx, module);
67 }
68
69 pub(crate) fn codegen_tls_ref<'tcx>(
70     fx: &mut FunctionCx<'_, '_, 'tcx>,
71     def_id: DefId,
72     layout: TyAndLayout<'tcx>,
73 ) -> CValue<'tcx> {
74     let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
75     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
76     if fx.clif_comments.enabled() {
77         fx.add_comment(local_data_id, format!("tls {:?}", def_id));
78     }
79     let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
80     CValue::by_val(tls_ptr, layout)
81 }
82
83 pub(crate) fn eval_mir_constant<'tcx>(
84     fx: &mut FunctionCx<'_, '_, 'tcx>,
85     constant: &Constant<'tcx>,
86 ) -> (ConstValue<'tcx>, Ty<'tcx>) {
87     let constant_kind = fx.monomorphize(constant.literal);
88     let uv = match constant_kind {
89         ConstantKind::Ty(const_) => match const_.kind() {
90             ty::ConstKind::Unevaluated(uv) => uv.expand(),
91             ty::ConstKind::Value(val) => {
92                 return (fx.tcx.valtree_to_const_val((const_.ty(), val)), const_.ty());
93             }
94             err => span_bug!(
95                 constant.span,
96                 "encountered bad ConstKind after monomorphizing: {:?}",
97                 err
98             ),
99         },
100         ConstantKind::Unevaluated(mir::UnevaluatedConst { def, .. }, _)
101             if fx.tcx.is_static(def.did) =>
102         {
103             span_bug!(constant.span, "MIR constant refers to static");
104         }
105         ConstantKind::Unevaluated(uv, _) => uv,
106         ConstantKind::Val(val, _) => return (val, constant_kind.ty()),
107     };
108
109     (
110         fx.tcx.const_eval_resolve(ty::ParamEnv::reveal_all(), uv, None).unwrap_or_else(|_err| {
111             span_bug!(constant.span, "erroneous constant not captured by required_consts");
112         }),
113         constant_kind.ty(),
114     )
115 }
116
117 pub(crate) fn codegen_constant_operand<'tcx>(
118     fx: &mut FunctionCx<'_, '_, 'tcx>,
119     constant: &Constant<'tcx>,
120 ) -> CValue<'tcx> {
121     let (const_val, ty) = eval_mir_constant(fx, constant);
122
123     codegen_const_value(fx, const_val, ty)
124 }
125
126 pub(crate) fn codegen_const_value<'tcx>(
127     fx: &mut FunctionCx<'_, '_, 'tcx>,
128     const_val: ConstValue<'tcx>,
129     ty: Ty<'tcx>,
130 ) -> CValue<'tcx> {
131     let layout = fx.layout_of(ty);
132     assert!(!layout.is_unsized(), "sized const value");
133
134     if layout.is_zst() {
135         return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
136     }
137
138     match const_val {
139         ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
140         ConstValue::Scalar(x) => match x {
141             Scalar::Int(int) => {
142                 if fx.clif_type(layout.ty).is_some() {
143                     return CValue::const_val(fx, layout, int);
144                 } else {
145                     let raw_val = int.to_bits(int.size()).unwrap();
146                     let val = match int.size().bytes() {
147                         1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
148                         2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
149                         4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
150                         8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
151                         16 => {
152                             let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
153                             let msb =
154                                 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
155                             fx.bcx.ins().iconcat(lsb, msb)
156                         }
157                         _ => unreachable!(),
158                     };
159
160                     let place = CPlace::new_stack_slot(fx, layout);
161                     place.to_ptr().store(fx, val, MemFlags::trusted());
162                     place.to_cvalue(fx)
163                 }
164             }
165             Scalar::Ptr(ptr, _size) => {
166                 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
167                 let base_addr = match fx.tcx.global_alloc(alloc_id) {
168                     GlobalAlloc::Memory(alloc) => {
169                         let data_id = data_id_for_alloc_id(
170                             &mut fx.constants_cx,
171                             fx.module,
172                             alloc_id,
173                             alloc.inner().mutability,
174                         );
175                         let local_data_id =
176                             fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
177                         if fx.clif_comments.enabled() {
178                             fx.add_comment(local_data_id, format!("{:?}", alloc_id));
179                         }
180                         fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
181                     }
182                     GlobalAlloc::Function(instance) => {
183                         let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
184                         let local_func_id =
185                             fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
186                         fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
187                     }
188                     GlobalAlloc::VTable(ty, trait_ref) => {
189                         let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
190                         let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
191                         // FIXME: factor this common code with the `Memory` arm into a function?
192                         let data_id = data_id_for_alloc_id(
193                             &mut fx.constants_cx,
194                             fx.module,
195                             alloc_id,
196                             alloc.inner().mutability,
197                         );
198                         let local_data_id =
199                             fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
200                         fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
201                     }
202                     GlobalAlloc::Static(def_id) => {
203                         assert!(fx.tcx.is_static(def_id));
204                         let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
205                         let local_data_id =
206                             fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
207                         if fx.clif_comments.enabled() {
208                             fx.add_comment(local_data_id, format!("{:?}", def_id));
209                         }
210                         fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
211                     }
212                 };
213                 let val = if offset.bytes() != 0 {
214                     fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
215                 } else {
216                     base_addr
217                 };
218                 CValue::by_val(val, layout)
219             }
220         },
221         ConstValue::ByRef { alloc, offset } => CValue::by_ref(
222             pointer_for_allocation(fx, alloc)
223                 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
224             layout,
225         ),
226         ConstValue::Slice { data, start, end } => {
227             let ptr = pointer_for_allocation(fx, data)
228                 .offset_i64(fx, i64::try_from(start).unwrap())
229                 .get_addr(fx);
230             let len = fx
231                 .bcx
232                 .ins()
233                 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
234             CValue::by_val_pair(ptr, len, layout)
235         }
236     }
237 }
238
239 fn pointer_for_allocation<'tcx>(
240     fx: &mut FunctionCx<'_, '_, 'tcx>,
241     alloc: ConstAllocation<'tcx>,
242 ) -> crate::pointer::Pointer {
243     let alloc_id = fx.tcx.create_memory_alloc(alloc);
244     let data_id = data_id_for_alloc_id(
245         &mut fx.constants_cx,
246         &mut *fx.module,
247         alloc_id,
248         alloc.inner().mutability,
249     );
250
251     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
252     if fx.clif_comments.enabled() {
253         fx.add_comment(local_data_id, format!("{:?}", alloc_id));
254     }
255     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
256     crate::pointer::Pointer::new(global_ptr)
257 }
258
259 pub(crate) fn data_id_for_alloc_id(
260     cx: &mut ConstantCx,
261     module: &mut dyn Module,
262     alloc_id: AllocId,
263     mutability: rustc_hir::Mutability,
264 ) -> DataId {
265     cx.todo.push(TodoItem::Alloc(alloc_id));
266     *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
267         module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
268     })
269 }
270
271 fn data_id_for_static(
272     tcx: TyCtxt<'_>,
273     module: &mut dyn Module,
274     def_id: DefId,
275     definition: bool,
276 ) -> DataId {
277     let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
278     let linkage = if definition {
279         crate::linkage::get_static_linkage(tcx, def_id)
280     } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
281         || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
282     {
283         Linkage::Preemptible
284     } else {
285         Linkage::Import
286     };
287
288     let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
289     let symbol_name = tcx.symbol_name(instance).name;
290     let ty = instance.ty(tcx, ParamEnv::reveal_all());
291     let is_mutable = if tcx.is_mutable_static(def_id) {
292         true
293     } else {
294         !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
295     };
296     let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
297
298     let attrs = tcx.codegen_fn_attrs(def_id);
299
300     let data_id = match module.declare_data(
301         &*symbol_name,
302         linkage,
303         is_mutable,
304         attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
305     ) {
306         Ok(data_id) => data_id,
307         Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
308             "attempt to declare `{symbol_name}` as static, but it was already declared as function"
309         )),
310         Err(err) => Err::<_, _>(err).unwrap(),
311     };
312
313     if rlinkage.is_some() {
314         // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
315         // Declare an internal global `extern_with_linkage_foo` which
316         // is initialized with the address of `foo`.  If `foo` is
317         // discarded during linking (for example, if `foo` has weak
318         // linkage and there are no definitions), then
319         // `extern_with_linkage_foo` will instead be initialized to
320         // zero.
321
322         let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
323         let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
324         let mut data_ctx = DataContext::new();
325         data_ctx.set_align(align);
326         let data = module.declare_data_in_data(data_id, &mut data_ctx);
327         data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
328         data_ctx.write_data_addr(0, data, 0);
329         match module.define_data(ref_data_id, &data_ctx) {
330             // Every time the static is referenced there will be another definition of this global,
331             // so duplicate definitions are expected and allowed.
332             Err(ModuleError::DuplicateDefinition(_)) => {}
333             res => res.unwrap(),
334         }
335         ref_data_id
336     } else {
337         data_id
338     }
339 }
340
341 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
342     while let Some(todo_item) = cx.todo.pop() {
343         let (data_id, alloc, section_name) = match todo_item {
344             TodoItem::Alloc(alloc_id) => {
345                 let alloc = match tcx.global_alloc(alloc_id) {
346                     GlobalAlloc::Memory(alloc) => alloc,
347                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::VTable(..) => {
348                         unreachable!()
349                     }
350                 };
351                 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
352                     module
353                         .declare_anonymous_data(
354                             alloc.inner().mutability == rustc_hir::Mutability::Mut,
355                             false,
356                         )
357                         .unwrap()
358                 });
359                 (data_id, alloc, None)
360             }
361             TodoItem::Static(def_id) => {
362                 //println!("static {:?}", def_id);
363
364                 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
365
366                 let alloc = tcx.eval_static_initializer(def_id).unwrap();
367
368                 let data_id = data_id_for_static(tcx, module, def_id, true);
369                 (data_id, alloc, section_name)
370             }
371         };
372
373         //("data_id {}", data_id);
374         if cx.done.contains(&data_id) {
375             continue;
376         }
377
378         let mut data_ctx = DataContext::new();
379         let alloc = alloc.inner();
380         data_ctx.set_align(alloc.align.bytes());
381
382         if let Some(section_name) = section_name {
383             let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
384                 let section_name = section_name.as_str();
385                 if let Some(names) = section_name.split_once(',') {
386                     names
387                 } else {
388                     tcx.sess.fatal(&format!(
389                         "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
390                         section_name
391                     ));
392                 }
393             } else {
394                 ("", section_name.as_str())
395             };
396             data_ctx.set_segment_section(segment_name, section_name);
397         }
398
399         let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
400         data_ctx.define(bytes.into_boxed_slice());
401
402         for &(offset, alloc_id) in alloc.provenance().iter() {
403             let addend = {
404                 let endianness = tcx.data_layout.endian;
405                 let offset = offset.bytes() as usize;
406                 let ptr_size = tcx.data_layout.pointer_size;
407                 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
408                     offset..offset + ptr_size.bytes() as usize,
409                 );
410                 read_target_uint(endianness, bytes).unwrap()
411             };
412
413             let reloc_target_alloc = tcx.global_alloc(alloc_id);
414             let data_id = match reloc_target_alloc {
415                 GlobalAlloc::Function(instance) => {
416                     assert_eq!(addend, 0);
417                     let func_id =
418                         crate::abi::import_function(tcx, module, instance.polymorphize(tcx));
419                     let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
420                     data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
421                     continue;
422                 }
423                 GlobalAlloc::Memory(target_alloc) => {
424                     data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
425                 }
426                 GlobalAlloc::VTable(ty, trait_ref) => {
427                     let alloc_id = tcx.vtable_allocation((ty, trait_ref));
428                     data_id_for_alloc_id(cx, module, alloc_id, Mutability::Not)
429                 }
430                 GlobalAlloc::Static(def_id) => {
431                     if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
432                     {
433                         tcx.sess.fatal(&format!(
434                             "Allocation {:?} contains reference to TLS value {:?}",
435                             alloc, def_id
436                         ));
437                     }
438
439                     // Don't push a `TodoItem::Static` here, as it will cause statics used by
440                     // multiple crates to be duplicated between them. It isn't necessary anyway,
441                     // as it will get pushed by `codegen_static` when necessary.
442                     data_id_for_static(tcx, module, def_id, false)
443                 }
444             };
445
446             let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
447             data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
448         }
449
450         module.define_data(data_id, &data_ctx).unwrap();
451         cx.done.insert(data_id);
452     }
453
454     assert!(cx.todo.is_empty(), "{:?}", cx.todo);
455 }
456
457 pub(crate) fn mir_operand_get_const_val<'tcx>(
458     fx: &FunctionCx<'_, '_, 'tcx>,
459     operand: &Operand<'tcx>,
460 ) -> Option<ConstValue<'tcx>> {
461     match operand {
462         Operand::Constant(const_) => match fx.monomorphize(const_.literal) {
463             ConstantKind::Ty(const_) => Some(
464                 const_.eval_for_mir(fx.tcx, ParamEnv::reveal_all()).try_to_value(fx.tcx).unwrap(),
465             ),
466             ConstantKind::Val(val, _) => Some(val),
467             ConstantKind::Unevaluated(uv, _) => {
468                 Some(fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), uv, None).unwrap())
469             }
470         },
471         // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
472         // inside a temporary before being passed to the intrinsic requiring the const argument.
473         // This code tries to find a single constant defining definition of the referenced local.
474         Operand::Copy(place) | Operand::Move(place) => {
475             if !place.projection.is_empty() {
476                 return None;
477             }
478             let mut computed_const_val = None;
479             for bb_data in fx.mir.basic_blocks.iter() {
480                 for stmt in &bb_data.statements {
481                     match &stmt.kind {
482                         StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
483                             match &local_and_rvalue.1 {
484                                 Rvalue::Cast(
485                                     CastKind::IntToInt
486                                     | CastKind::FloatToFloat
487                                     | CastKind::FloatToInt
488                                     | CastKind::IntToFloat
489                                     | CastKind::FnPtrToPtr
490                                     | CastKind::PtrToPtr,
491                                     operand,
492                                     ty,
493                                 ) => {
494                                     if computed_const_val.is_some() {
495                                         return None; // local assigned twice
496                                     }
497                                     if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
498                                         return None;
499                                     }
500                                     let const_val = mir_operand_get_const_val(fx, operand)?;
501                                     if fx.layout_of(*ty).size
502                                         != const_val.try_to_scalar_int()?.size()
503                                     {
504                                         return None;
505                                     }
506                                     computed_const_val = Some(const_val);
507                                 }
508                                 Rvalue::Use(operand) => {
509                                     computed_const_val = mir_operand_get_const_val(fx, operand)
510                                 }
511                                 _ => return None,
512                             }
513                         }
514                         StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
515                             if &**stmt_place == place =>
516                         {
517                             return None;
518                         }
519                         StatementKind::Intrinsic(ref intrinsic) => match **intrinsic {
520                             NonDivergingIntrinsic::CopyNonOverlapping(..) => return None,
521                             NonDivergingIntrinsic::Assume(..) => {}
522                         },
523                         // conservative handling
524                         StatementKind::Assign(_)
525                         | StatementKind::FakeRead(_)
526                         | StatementKind::SetDiscriminant { .. }
527                         | StatementKind::Deinit(_)
528                         | StatementKind::StorageLive(_)
529                         | StatementKind::StorageDead(_)
530                         | StatementKind::Retag(_, _)
531                         | StatementKind::AscribeUserType(_, _)
532                         | StatementKind::Coverage(_)
533                         | StatementKind::Nop => {}
534                     }
535                 }
536                 match &bb_data.terminator().kind {
537                     TerminatorKind::Goto { .. }
538                     | TerminatorKind::SwitchInt { .. }
539                     | TerminatorKind::Resume
540                     | TerminatorKind::Abort
541                     | TerminatorKind::Return
542                     | TerminatorKind::Unreachable
543                     | TerminatorKind::Drop { .. }
544                     | TerminatorKind::Assert { .. } => {}
545                     TerminatorKind::DropAndReplace { .. }
546                     | TerminatorKind::Yield { .. }
547                     | TerminatorKind::GeneratorDrop
548                     | TerminatorKind::FalseEdge { .. }
549                     | TerminatorKind::FalseUnwind { .. } => unreachable!(),
550                     TerminatorKind::InlineAsm { .. } => return None,
551                     TerminatorKind::Call { destination, target: Some(_), .. }
552                         if destination == place =>
553                     {
554                         return None;
555                     }
556                     TerminatorKind::Call { .. } => {}
557                 }
558             }
559             computed_const_val
560         }
561     }
562 }