Skip to content

Use assume to inform the optimiser about refcount invariants #21418

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 22, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 37 additions & 4 deletions src/liballoc/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ use core::option::Option::{Some, None};
use core::ptr::{self, PtrExt};
use core::result::Result;
use core::result::Result::{Ok, Err};
use core::intrinsics::assume;

use heap::deallocate;

Expand Down Expand Up @@ -905,10 +906,24 @@ trait RcBoxPtr<T> {
fn strong(&self) -> uint { self.inner().strong.get() }

#[inline]
fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
fn inc_strong(&self) {
let strong = self.strong();
// The reference count is always at least one unless we're about to drop the type
// This allows the bulk of the destructor to be omitted in cases where we know that
// the reference count must be > 0.
unsafe { assume(strong > 0); }
self.inner().strong.set(strong + 1);
}

#[inline]
fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
fn dec_strong(&self) {
let strong = self.strong();
// The reference count is always at least one unless we're about to drop the type
// This allows the bulk of the destructor to be omitted in cases where we know that
// the reference count must be > 0
unsafe { assume(strong > 0); }
self.inner().strong.set(strong - 1);
}

#[inline]
fn weak(&self) -> uint { self.inner().weak.get() }
Expand All @@ -922,12 +937,30 @@ trait RcBoxPtr<T> {

impl<T> RcBoxPtr<T> for Rc<T> {
#[inline(always)]
fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
fn inner(&self) -> &RcBox<T> {
unsafe {
// Safe to assume this here, as if it weren't true, we'd be breaking
// the contract anyway.
// This allows the null check to be elided in the destructor if we
// manipulated the reference count in the same function.
assume(!self._ptr.is_null());
&(**self._ptr)
}
}
}

impl<T> RcBoxPtr<T> for Weak<T> {
#[inline(always)]
fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
fn inner(&self) -> &RcBox<T> {
unsafe {
// Safe to assume this here, as if it weren't true, we'd be breaking
// the contract anyway
// This allows the null check to be elided in the destructor if we
// manipulated the reference count in the same function.
assume(!self._ptr.is_null());
&(**self._ptr)
}
}
}

#[cfg(test)]
Expand Down