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