Skip to content

Commit

Permalink
Auto merge of #114569 - matthiaskrgr:rollup-p8tcxtz, r=matthiaskrgr
Browse files Browse the repository at this point in the history
Rollup of 8 pull requests

Successful merges:

 - #98935 (Implement `Option::take_if`)
 - #114093 (Add regression test for `echo 'mod unknown;' | rustc -`)
 - #114229 (Nest tests/codegen/sanitizer*.rs tests in sanitizer dir)
 - #114230 (Nest other codegen test topics)
 - #114362 (string.rs: remove "Basic usage" text)
 - #114365 (str.rs: remove "Basic usage" text)
 - #114382 (Add a new `compare_bytes` intrinsic instead of calling `memcmp` directly)
 - #114549 (Style fix and refactor on resolve diagnostics)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Aug 7, 2023
2 parents 9fca8e7 + d804b74 commit 4a71a05
Show file tree
Hide file tree
Showing 86 changed files with 439 additions and 393 deletions.
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1155,6 +1155,20 @@ fn codegen_regular_intrinsic_call<'tcx>(
ret.write_cvalue(fx, CValue::by_val(is_eq_value, ret.layout()));
}

sym::compare_bytes => {
intrinsic_args!(fx, args => (lhs_ptr, rhs_ptr, bytes_val); intrinsic);
let lhs_ptr = lhs_ptr.load_scalar(fx);
let rhs_ptr = rhs_ptr.load_scalar(fx);
let bytes_val = bytes_val.load_scalar(fx);

let params = vec![AbiParam::new(fx.pointer_type); 3];
let returns = vec![AbiParam::new(types::I32)];
let args = &[lhs_ptr, rhs_ptr, bytes_val];
// Here we assume that the `memcmp` provided by the target is a NOP for size 0.
let cmp = fx.lib_call("memcmp", params, returns, args)[0];
ret.write_cvalue(fx, CValue::by_val(cmp, ret.layout()));
}

sym::const_allocate => {
intrinsic_args!(fx, args => (_size, _align); intrinsic);

Expand Down
15 changes: 15 additions & 0 deletions compiler/rustc_codegen_gcc/src/intrinsic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,21 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'a, 'gcc, 'tcx> {
}
}

sym::compare_bytes => {
let a = args[0].immediate();
let b = args[1].immediate();
let n = args[2].immediate();

let void_ptr_type = self.context.new_type::<*const ()>();
let a_ptr = self.bitcast(a, void_ptr_type);
let b_ptr = self.bitcast(b, void_ptr_type);

// Here we assume that the `memcmp` provided by the target is a NOP for size 0.
let builtin = self.context.get_builtin_function("memcmp");
let cmp = self.context.new_call(None, builtin, &[a_ptr, b_ptr, n]);
self.sext(cmp, self.type_ix(32))
}

sym::black_box => {
args[0].val.store(self, result);

Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_codegen_llvm/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -891,7 +891,8 @@ impl<'ll> CodegenCx<'ll, '_> {
ifn!("llvm.prefetch", fn(ptr, t_i32, t_i32, t_i32) -> void);

// This isn't an "LLVM intrinsic", but LLVM's optimization passes
// recognize it like one and we assume it exists in `core::slice::cmp`
// recognize it like one (including turning it into `bcmp` sometimes)
// and we use it to implement intrinsics like `raw_eq` and `compare_bytes`
match self.sess().target.arch.as_ref() {
"avr" | "msp430" => ifn!("memcmp", fn(ptr, ptr, t_isize) -> t_i16),
_ => ifn!("memcmp", fn(ptr, ptr, t_isize) -> t_i32),
Expand Down
10 changes: 10 additions & 0 deletions compiler/rustc_codegen_llvm/src/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,16 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
}
}

sym::compare_bytes => {
// Here we assume that the `memcmp` provided by the target is a NOP for size 0.
let cmp = self.call_intrinsic(
"memcmp",
&[args[0].immediate(), args[1].immediate(), args[2].immediate()],
);
// Some targets have `memcmp` returning `i16`, but the intrinsic is always `i32`.
self.sext(cmp, self.type_ix(32))
}

sym::black_box => {
args[0].val.store(self, result);
let result_val_span = [result.llval];
Expand Down
22 changes: 22 additions & 0 deletions compiler/rustc_const_eval/src/interpret/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
sym::write_bytes => {
self.write_bytes_intrinsic(&args[0], &args[1], &args[2])?;
}
sym::compare_bytes => {
let result = self.compare_bytes_intrinsic(&args[0], &args[1], &args[2])?;
self.write_scalar(result, dest)?;
}
sym::arith_offset => {
let ptr = self.read_pointer(&args[0])?;
let offset_count = self.read_target_isize(&args[1])?;
Expand Down Expand Up @@ -643,6 +647,24 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
self.write_bytes_ptr(dst, bytes)
}

pub(crate) fn compare_bytes_intrinsic(
&mut self,
left: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
right: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
byte_count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
) -> InterpResult<'tcx, Scalar<M::Provenance>> {
let left = self.read_pointer(left)?;
let right = self.read_pointer(right)?;
let n = Size::from_bytes(self.read_target_usize(byte_count)?);

let left_bytes = self.read_bytes_ptr_strip_provenance(left, n)?;
let right_bytes = self.read_bytes_ptr_strip_provenance(right, n)?;

// `Ordering`'s discriminants are -1/0/+1, so casting does the right thing.
let result = Ord::cmp(left_bytes, right_bytes) as i32;
Ok(Scalar::from_i32(result))
}

pub(crate) fn raw_eq_intrinsic(
&mut self,
lhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_hir_analysis/src/check/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,10 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
],
Ty::new_unit(tcx),
),
sym::compare_bytes => {
let byte_ptr = Ty::new_imm_ptr(tcx, tcx.types.u8);
(0, vec![byte_ptr, byte_ptr, tcx.types.usize], tcx.types.i32)
}
sym::write_bytes | sym::volatile_set_memory => (
1,
vec![
Expand Down
73 changes: 35 additions & 38 deletions compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,6 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
}
})
.collect::<Vec<_>>();
let crate_def_id = CRATE_DEF_ID.to_def_id();
// Try to filter out intrinsics candidates, as long as we have
// some other candidates to suggest.
let intrinsic_candidates: Vec<_> = candidates
Expand All @@ -566,8 +565,9 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
.collect();
if candidates.is_empty() {
// Put them back if we have no more candidates to suggest...
candidates.extend(intrinsic_candidates);
candidates = intrinsic_candidates;
}
let crate_def_id = CRATE_DEF_ID.to_def_id();
if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
let mut enum_candidates: Vec<_> = self
.r
Expand Down Expand Up @@ -1180,37 +1180,34 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
/// return the span of whole call and the span for all arguments expect the first one (`self`).
fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
let mut has_self_arg = None;
if let PathSource::Expr(Some(parent)) = source {
match &parent.kind {
ExprKind::Call(_, args) if !args.is_empty() => {
let mut expr_kind = &args[0].kind;
loop {
match expr_kind {
ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
if arg_name.segments[0].ident.name == kw::SelfLower {
let call_span = parent.span;
let tail_args_span = if args.len() > 1 {
Some(Span::new(
args[1].span.lo(),
args.last().unwrap().span.hi(),
call_span.ctxt(),
None,
))
} else {
None
};
has_self_arg = Some((call_span, tail_args_span));
}
break;
if let PathSource::Expr(Some(parent)) = source
&& let ExprKind::Call(_, args) = &parent.kind
&& !args.is_empty() {
let mut expr_kind = &args[0].kind;
loop {
match expr_kind {
ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
if arg_name.segments[0].ident.name == kw::SelfLower {
let call_span = parent.span;
let tail_args_span = if args.len() > 1 {
Some(Span::new(
args[1].span.lo(),
args.last().unwrap().span.hi(),
call_span.ctxt(),
None,
))
} else {
None
};
has_self_arg = Some((call_span, tail_args_span));
}
ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
_ => break,
break;
}
ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
_ => break,
}
}
_ => (),
}
};
}
has_self_arg
}

Expand All @@ -1220,15 +1217,15 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
// where a brace being opened means a block is being started. Look
// ahead for the next text to see if `span` is followed by a `{`.
let sm = self.r.tcx.sess.source_map();
let sp = sm.span_look_ahead(span, None, Some(50));
let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
// In case this could be a struct literal that needs to be surrounded
// by parentheses, find the appropriate span.
let closing_span = sm.span_look_ahead(span, Some("}"), Some(50));
let closing_brace: Option<Span> = sm
.span_to_snippet(closing_span)
.map_or(None, |s| if s == "}" { Some(span.to(closing_span)) } else { None });
(followed_by_brace, closing_brace)
if let Some(followed_brace_span) = sm.span_look_ahead(span, "{", Some(50)) {
// In case this could be a struct literal that needs to be surrounded
// by parentheses, find the appropriate span.
let close_brace_span = sm.span_look_ahead(followed_brace_span, "}", Some(50));
let closing_brace = close_brace_span.map(|sp| span.to(sp));
(true, closing_brace)
} else {
(false, None)
}
}

/// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
Expand Down
15 changes: 6 additions & 9 deletions compiler/rustc_span/src/source_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -973,24 +973,21 @@ impl SourceMap {
Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt(), None)
}

/// Returns a new span to check next none-whitespace character or some specified expected character
/// If `expect` is none, the first span of non-whitespace character is returned.
/// If `expect` presented, the first span of the character `expect` is returned
/// Otherwise, the span reached to limit is returned.
pub fn span_look_ahead(&self, span: Span, expect: Option<&str>, limit: Option<usize>) -> Span {
/// Check whether span is followed by some specified expected string in limit scope
pub fn span_look_ahead(&self, span: Span, expect: &str, limit: Option<usize>) -> Option<Span> {
let mut sp = span;
for _ in 0..limit.unwrap_or(100_usize) {
sp = self.next_point(sp);
if let Ok(ref snippet) = self.span_to_snippet(sp) {
if expect.is_some_and(|es| snippet == es) {
break;
if snippet == expect {
return Some(sp);
}
if expect.is_none() && snippet.chars().any(|c| !c.is_whitespace()) {
if snippet.chars().any(|c| !c.is_whitespace()) {
break;
}
}
}
sp
None
}

/// Finds the width of the character, either before or after the end of provided span,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,7 @@ symbols! {
cold,
collapse_debuginfo,
column,
compare_bytes,
compare_exchange,
compare_exchange_weak,
compile_error,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1429,20 +1429,18 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {

// Issue #109436, we need to add parentheses properly for method calls
// for example, `foo.into()` should be `(&foo).into()`
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(
self.tcx.sess.source_map().span_look_ahead(span, Some("."), Some(50)),
) {
if snippet == "." {
err.multipart_suggestion_verbose(
sugg_msg,
vec![
(span.shrink_to_lo(), format!("({sugg_prefix}")),
(span.shrink_to_hi(), ")".to_string()),
],
Applicability::MaybeIncorrect,
);
return true;
}
if let Some(_) =
self.tcx.sess.source_map().span_look_ahead(span, ".", Some(50))
{
err.multipart_suggestion_verbose(
sugg_msg,
vec![
(span.shrink_to_lo(), format!("({sugg_prefix}")),
(span.shrink_to_hi(), ")".to_string()),
],
Applicability::MaybeIncorrect,
);
return true;
}

// Issue #104961, we need to add parentheses properly for compound expressions
Expand Down
6 changes: 0 additions & 6 deletions library/alloc/src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,6 @@ impl str {
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let s = "this is a string";
/// let boxed_str = s.to_owned().into_boxed_str();
Expand Down Expand Up @@ -487,8 +485,6 @@ impl str {
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let string = String::from("birthday gift");
/// let boxed_str = string.clone().into_boxed_str();
Expand Down Expand Up @@ -602,8 +598,6 @@ impl str {
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let smile_utf8 = Box::new([226, 152, 186]);
/// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
Expand Down
Loading

0 comments on commit 4a71a05

Please sign in to comment.