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