rename get_global_alloc to try_get_global_alloc

This commit is contained in:
Ralf Jung 2022-07-17 11:40:34 -04:00
parent da5e4d73f1
commit a10d8e4581
10 changed files with 32 additions and 22 deletions

View File

@ -362,7 +362,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
let (data_id, alloc, section_name) = match todo_item { let (data_id, alloc, section_name) = match todo_item {
TodoItem::Alloc(alloc_id) => { TodoItem::Alloc(alloc_id) => {
//println!("alloc_id {}", alloc_id); //println!("alloc_id {}", alloc_id);
let alloc = match tcx.get_global_alloc(alloc_id).unwrap() { let alloc = match tcx.global_alloc(alloc_id) {
GlobalAlloc::Memory(alloc) => alloc, GlobalAlloc::Memory(alloc) => alloc,
GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::Vtable(..) => { GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::Vtable(..) => {
unreachable!() unreachable!()

View File

@ -369,7 +369,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
// we don't deallocate it. // we don't deallocate it.
let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr)?; let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr)?;
let is_allocated_in_another_const = matches!( let is_allocated_in_another_const = matches!(
ecx.tcx.get_global_alloc(alloc_id), ecx.tcx.try_get_global_alloc(alloc_id),
Some(interpret::GlobalAlloc::Memory(_)) Some(interpret::GlobalAlloc::Memory(_))
); );

View File

@ -138,7 +138,7 @@ pub(crate) fn deref_mir_constant<'tcx>(
let mplace = ecx.deref_operand(&op).unwrap(); let mplace = ecx.deref_operand(&op).unwrap();
if let Some(alloc_id) = mplace.ptr.provenance { if let Some(alloc_id) = mplace.ptr.provenance {
assert_eq!( assert_eq!(
tcx.get_global_alloc(alloc_id).unwrap().unwrap_memory().0.0.mutability, tcx.global_alloc(alloc_id).unwrap_memory().0.0.mutability,
Mutability::Not, Mutability::Not,
"deref_mir_constant cannot be used with mutable allocations as \ "deref_mir_constant cannot be used with mutable allocations as \
that could allow pattern matching to observe mutable statics", that could allow pattern matching to observe mutable statics",

View File

@ -94,7 +94,7 @@ fn intern_shallow<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx, const_eval:
// to validation to error -- it has the much better error messages, pointing out where // to validation to error -- it has the much better error messages, pointing out where
// in the value the dangling reference lies. // in the value the dangling reference lies.
// The `delay_span_bug` ensures that we don't forget such a check in validation. // The `delay_span_bug` ensures that we don't forget such a check in validation.
if tcx.get_global_alloc(alloc_id).is_none() { if tcx.try_get_global_alloc(alloc_id).is_none() {
tcx.sess.delay_span_bug(ecx.tcx.span, "tried to intern dangling pointer"); tcx.sess.delay_span_bug(ecx.tcx.span, "tried to intern dangling pointer");
} }
// treat dangling pointers like other statics // treat dangling pointers like other statics
@ -454,7 +454,7 @@ pub fn intern_const_alloc_recursive<
.sess .sess
.span_err(ecx.tcx.span, "encountered dangling pointer in final constant"); .span_err(ecx.tcx.span, "encountered dangling pointer in final constant");
return Err(reported); return Err(reported);
} else if ecx.tcx.get_global_alloc(alloc_id).is_none() { } else if ecx.tcx.try_get_global_alloc(alloc_id).is_none() {
// We have hit an `AllocId` that is neither in local or global memory and isn't // We have hit an `AllocId` that is neither in local or global memory and isn't
// marked as dangling by local memory. That should be impossible. // marked as dangling by local memory. That should be impossible.
span_bug!(ecx.tcx.span, "encountered unknown alloc id {:?}", alloc_id); span_bug!(ecx.tcx.span, "encountered unknown alloc id {:?}", alloc_id);

View File

@ -161,7 +161,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
) -> InterpResult<'tcx, Pointer<M::Provenance>> { ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
let alloc_id = ptr.provenance; let alloc_id = ptr.provenance;
// We need to handle `extern static`. // We need to handle `extern static`.
match self.tcx.get_global_alloc(alloc_id) { match self.tcx.try_get_global_alloc(alloc_id) {
Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => { Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => {
bug!("global memory cannot point to thread-local static") bug!("global memory cannot point to thread-local static")
} }
@ -289,7 +289,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
let Some((alloc_kind, mut alloc)) = self.memory.alloc_map.remove(&alloc_id) else { let Some((alloc_kind, mut alloc)) = self.memory.alloc_map.remove(&alloc_id) else {
// Deallocating global memory -- always an error // Deallocating global memory -- always an error
return Err(match self.tcx.get_global_alloc(alloc_id) { return Err(match self.tcx.try_get_global_alloc(alloc_id) {
Some(GlobalAlloc::Function(..)) => { Some(GlobalAlloc::Function(..)) => {
err_ub_format!("deallocating {alloc_id:?}, which is a function") err_ub_format!("deallocating {alloc_id:?}, which is a function")
} }
@ -478,7 +478,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
id: AllocId, id: AllocId,
is_write: bool, is_write: bool,
) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::Provenance, M::AllocExtra>>> { ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::Provenance, M::AllocExtra>>> {
let (alloc, def_id) = match self.tcx.get_global_alloc(id) { let (alloc, def_id) = match self.tcx.try_get_global_alloc(id) {
Some(GlobalAlloc::Memory(mem)) => { Some(GlobalAlloc::Memory(mem)) => {
// Memory of a constant or promoted or anonymous memory referenced by a static. // Memory of a constant or promoted or anonymous memory referenced by a static.
(mem, None) (mem, None)
@ -669,7 +669,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
// # Statics // # Statics
// Can't do this in the match argument, we may get cycle errors since the lock would // Can't do this in the match argument, we may get cycle errors since the lock would
// be held throughout the match. // be held throughout the match.
match self.tcx.get_global_alloc(id) { match self.tcx.try_get_global_alloc(id) {
Some(GlobalAlloc::Static(did)) => { Some(GlobalAlloc::Static(did)) => {
assert!(!self.tcx.is_thread_local_static(did)); assert!(!self.tcx.is_thread_local_static(did));
// Use size and align of the type. // Use size and align of the type.
@ -715,7 +715,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
if let Some(extra) = self.memory.extra_fn_ptr_map.get(&id) { if let Some(extra) = self.memory.extra_fn_ptr_map.get(&id) {
Some(FnVal::Other(*extra)) Some(FnVal::Other(*extra))
} else { } else {
match self.tcx.get_global_alloc(id) { match self.tcx.try_get_global_alloc(id) {
Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)), Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)),
_ => None, _ => None,
} }
@ -839,7 +839,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> std::fmt::Debug for DumpAllocs<'a,
} }
None => { None => {
// global alloc // global alloc
match self.ecx.tcx.get_global_alloc(id) { match self.ecx.tcx.try_get_global_alloc(id) {
Some(GlobalAlloc::Memory(alloc)) => { Some(GlobalAlloc::Memory(alloc)) => {
write!(fmt, " (unchanged global, ")?; write!(fmt, " (unchanged global, ")?;
write_allocation_track_relocs( write_allocation_track_relocs(

View File

@ -447,7 +447,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, '
// `!` is a ZST and we want to validate it. // `!` is a ZST and we want to validate it.
if let Ok((alloc_id, _offset, _prov)) = self.ecx.ptr_try_get_alloc_id(place.ptr) { if let Ok((alloc_id, _offset, _prov)) = self.ecx.ptr_try_get_alloc_id(place.ptr) {
// Special handling for pointers to statics (irrespective of their type). // Special handling for pointers to statics (irrespective of their type).
let alloc_kind = self.ecx.tcx.get_global_alloc(alloc_id); let alloc_kind = self.ecx.tcx.try_get_global_alloc(alloc_id);
if let Some(GlobalAlloc::Static(did)) = alloc_kind { if let Some(GlobalAlloc::Static(did)) = alloc_kind {
assert!(!self.ecx.tcx.is_thread_local_static(did)); assert!(!self.ecx.tcx.is_thread_local_static(did));
assert!(self.ecx.tcx.is_static(did)); assert!(self.ecx.tcx.is_static(did));

View File

@ -312,7 +312,9 @@ impl<'s> AllocDecodingSession<'s> {
State::InProgress(TinyList::new_single(self.session_id), alloc_id); State::InProgress(TinyList::new_single(self.session_id), alloc_id);
Some(alloc_id) Some(alloc_id)
} }
AllocDiscriminant::Fn | AllocDiscriminant::Static | AllocDiscriminant::Vtable => { AllocDiscriminant::Fn
| AllocDiscriminant::Static
| AllocDiscriminant::Vtable => {
// Fns and statics cannot be cyclic, and their `AllocId` // Fns and statics cannot be cyclic, and their `AllocId`
// is determined later by interning. // is determined later by interning.
*entry = *entry =
@ -366,7 +368,8 @@ impl<'s> AllocDecodingSession<'s> {
assert!(alloc_id.is_none()); assert!(alloc_id.is_none());
trace!("creating static alloc ID"); trace!("creating static alloc ID");
let ty = <Ty<'_> as Decodable<D>>::decode(decoder); let ty = <Ty<'_> as Decodable<D>>::decode(decoder);
let poly_trait_ref = <Option<ty::PolyExistentialTraitRef<'_>> as Decodable<D>>::decode(decoder); let poly_trait_ref =
<Option<ty::PolyExistentialTraitRef<'_>> as Decodable<D>>::decode(decoder);
trace!("decoded vtable alloc instance: {ty:?}, {poly_trait_ref:?}"); trace!("decoded vtable alloc instance: {ty:?}, {poly_trait_ref:?}");
let alloc_id = decoder.interner().create_vtable_alloc(ty, poly_trait_ref); let alloc_id = decoder.interner().create_vtable_alloc(ty, poly_trait_ref);
alloc_id alloc_id
@ -533,7 +536,11 @@ impl<'tcx> TyCtxt<'tcx> {
} }
/// Generates an `AllocId` for a (symbolic, not-reified) vtable. Will get deduplicated. /// Generates an `AllocId` for a (symbolic, not-reified) vtable. Will get deduplicated.
pub fn create_vtable_alloc(self, ty: Ty<'tcx>, poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>) -> AllocId { pub fn create_vtable_alloc(
self,
ty: Ty<'tcx>,
poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
) -> AllocId {
self.reserve_and_set_dedup(GlobalAlloc::Vtable(ty, poly_trait_ref)) self.reserve_and_set_dedup(GlobalAlloc::Vtable(ty, poly_trait_ref))
} }
@ -554,7 +561,7 @@ impl<'tcx> TyCtxt<'tcx> {
/// This function exists to allow const eval to detect the difference between evaluation- /// This function exists to allow const eval to detect the difference between evaluation-
/// local dangling pointers and allocations in constants/statics. /// local dangling pointers and allocations in constants/statics.
#[inline] #[inline]
pub fn get_global_alloc(self, id: AllocId) -> Option<GlobalAlloc<'tcx>> { pub fn try_get_global_alloc(self, id: AllocId) -> Option<GlobalAlloc<'tcx>> {
self.alloc_map.lock().alloc_map.get(&id).cloned() self.alloc_map.lock().alloc_map.get(&id).cloned()
} }
@ -565,7 +572,7 @@ impl<'tcx> TyCtxt<'tcx> {
/// ids), this function is frequently used throughout rustc, but should not be used within /// ids), this function is frequently used throughout rustc, but should not be used within
/// the miri engine. /// the miri engine.
pub fn global_alloc(self, id: AllocId) -> GlobalAlloc<'tcx> { pub fn global_alloc(self, id: AllocId) -> GlobalAlloc<'tcx> {
match self.get_global_alloc(id) { match self.try_get_global_alloc(id) {
Some(alloc) => alloc, Some(alloc) => alloc,
None => bug!("could not find allocation for {id:?}"), None => bug!("could not find allocation for {id:?}"),
} }

View File

@ -720,12 +720,14 @@ pub fn write_allocations<'tcx>(
write!(w, "{}", display_allocation(tcx, alloc.inner())) write!(w, "{}", display_allocation(tcx, alloc.inner()))
}; };
write!(w, "\n{id:?}")?; write!(w, "\n{id:?}")?;
match tcx.get_global_alloc(id) { match tcx.try_get_global_alloc(id) {
// This can't really happen unless there are bugs, but it doesn't cost us anything to // This can't really happen unless there are bugs, but it doesn't cost us anything to
// gracefully handle it and allow buggy rustc to be debugged via allocation printing. // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
None => write!(w, " (deallocated)")?, None => write!(w, " (deallocated)")?,
Some(GlobalAlloc::Function(inst)) => write!(w, " (fn: {inst})")?, Some(GlobalAlloc::Function(inst)) => write!(w, " (fn: {inst})")?,
Some(GlobalAlloc::Vtable(ty, Some(trait_ref))) => write!(w, " (vtable: impl {trait_ref} for {ty})")?, Some(GlobalAlloc::Vtable(ty, Some(trait_ref))) => {
write!(w, " (vtable: impl {trait_ref} for {ty})")?
}
Some(GlobalAlloc::Vtable(ty, None)) => write!(w, " (vtable: impl ? for {ty})")?, Some(GlobalAlloc::Vtable(ty, None)) => write!(w, " (vtable: impl ? for {ty})")?,
Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => { Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
match tcx.eval_static_initializer(did) { match tcx.eval_static_initializer(did) {

View File

@ -147,7 +147,7 @@ impl<'a> HashStable<StableHashingContext<'a>> for mir::interpret::AllocId {
ty::tls::with_opt(|tcx| { ty::tls::with_opt(|tcx| {
trace!("hashing {:?}", *self); trace!("hashing {:?}", *self);
let tcx = tcx.expect("can't hash AllocIds during hir lowering"); let tcx = tcx.expect("can't hash AllocIds during hir lowering");
tcx.get_global_alloc(*self).hash_stable(hcx, hasher); tcx.try_get_global_alloc(*self).hash_stable(hcx, hasher);
}); });
} }
} }

View File

@ -1269,7 +1269,7 @@ pub trait PrettyPrinter<'tcx>:
if let ty::Array(elem, len) = inner.kind() { if let ty::Array(elem, len) = inner.kind() {
if let ty::Uint(ty::UintTy::U8) = elem.kind() { if let ty::Uint(ty::UintTy::U8) = elem.kind() {
if let ty::ConstKind::Value(ty::ValTree::Leaf(int)) = len.kind() { if let ty::ConstKind::Value(ty::ValTree::Leaf(int)) = len.kind() {
match self.tcx().get_global_alloc(alloc_id) { match self.tcx().try_get_global_alloc(alloc_id) {
Some(GlobalAlloc::Memory(alloc)) => { Some(GlobalAlloc::Memory(alloc)) => {
let len = int.assert_bits(self.tcx().data_layout.pointer_size); let len = int.assert_bits(self.tcx().data_layout.pointer_size);
let range = let range =
@ -1298,7 +1298,8 @@ pub trait PrettyPrinter<'tcx>:
ty::FnPtr(_) => { ty::FnPtr(_) => {
// FIXME: We should probably have a helper method to share code with the "Byte strings" // FIXME: We should probably have a helper method to share code with the "Byte strings"
// printing above (which also has to handle pointers to all sorts of things). // printing above (which also has to handle pointers to all sorts of things).
if let Some(GlobalAlloc::Function(instance)) = self.tcx().get_global_alloc(alloc_id) if let Some(GlobalAlloc::Function(instance)) =
self.tcx().try_get_global_alloc(alloc_id)
{ {
self = self.typed_value( self = self.typed_value(
|this| this.print_value_path(instance.def_id(), instance.substs), |this| this.print_value_path(instance.def_id(), instance.substs),