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