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