Skip to content

Commit 29b7717

Browse files
committed
Auto merge of #147162 - matthiaskrgr:rollup-4bv1xzb, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #146937 (std: implement `hostname`) - #147040 (mbe: macro_check: Fix function comments referencing non-existent parameters) - #147131 (Use MirPatch in simplify_branches.) - #147133 (Remove one loop in `extract_cfg_from_attrs`) - #147150 (Emit allocator attributes for allocator shim) r? `@ghost` `@rustbot` modify labels: rollup
2 parents dc2c356 + 3799799 commit 29b7717

File tree

17 files changed

+296
-112
lines changed

17 files changed

+296
-112
lines changed

compiler/rustc_codegen_llvm/src/allocator.rs

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@ use rustc_ast::expand::allocator::{
55
};
66
use rustc_codegen_ssa::traits::BaseTypeCodegenMethods as _;
77
use rustc_middle::bug;
8-
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
8+
use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
99
use rustc_middle::ty::TyCtxt;
1010
use rustc_session::config::{DebugInfo, OomStrategy};
11+
use rustc_span::sym;
1112
use rustc_symbol_mangling::mangle_internal_symbol;
1213

1314
use crate::attributes::llfn_attrs_from_instance;
@@ -59,7 +60,26 @@ pub(crate) unsafe fn codegen(
5960
let from_name = mangle_internal_symbol(tcx, &global_fn_name(method.name));
6061
let to_name = mangle_internal_symbol(tcx, &default_fn_name(method.name));
6162

62-
create_wrapper_function(tcx, &cx, &from_name, Some(&to_name), &args, output, false);
63+
let alloc_attr_flag = match method.name {
64+
sym::alloc => CodegenFnAttrFlags::ALLOCATOR,
65+
sym::dealloc => CodegenFnAttrFlags::DEALLOCATOR,
66+
sym::realloc => CodegenFnAttrFlags::REALLOCATOR,
67+
sym::alloc_zeroed => CodegenFnAttrFlags::ALLOCATOR_ZEROED,
68+
_ => unreachable!("Unknown allocator method!"),
69+
};
70+
71+
let mut attrs = CodegenFnAttrs::new();
72+
attrs.flags |= alloc_attr_flag;
73+
create_wrapper_function(
74+
tcx,
75+
&cx,
76+
&from_name,
77+
Some(&to_name),
78+
&args,
79+
output,
80+
false,
81+
&attrs,
82+
);
6383
}
6484
}
6585

@@ -72,6 +92,7 @@ pub(crate) unsafe fn codegen(
7292
&[usize, usize], // size, align
7393
None,
7494
true,
95+
&CodegenFnAttrs::new(),
7596
);
7697

7798
unsafe {
@@ -93,6 +114,7 @@ pub(crate) unsafe fn codegen(
93114
&[],
94115
None,
95116
false,
117+
&CodegenFnAttrs::new(),
96118
);
97119
}
98120

@@ -139,6 +161,7 @@ fn create_wrapper_function(
139161
args: &[&Type],
140162
output: Option<&Type>,
141163
no_return: bool,
164+
attrs: &CodegenFnAttrs,
142165
) {
143166
let ty = cx.type_func(args, output.unwrap_or_else(|| cx.type_void()));
144167
let llfn = declare_simple_fn(
@@ -150,8 +173,7 @@ fn create_wrapper_function(
150173
ty,
151174
);
152175

153-
let attrs = CodegenFnAttrs::new();
154-
llfn_attrs_from_instance(cx, tcx, llfn, &attrs, None);
176+
llfn_attrs_from_instance(cx, tcx, llfn, attrs, None);
155177

156178
let no_return = if no_return {
157179
// -> ! DIFlagNoReturn

compiler/rustc_expand/src/mbe/macro_check.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -210,8 +210,7 @@ pub(super) fn check_meta_variables(
210210
guar.map_or(Ok(()), Err)
211211
}
212212

213-
/// Checks `lhs` as part of the LHS of a macro definition, extends `binders` with new binders, and
214-
/// sets `valid` to false in case of errors.
213+
/// Checks `lhs` as part of the LHS of a macro definition.
215214
///
216215
/// Arguments:
217216
/// - `psess` is used to emit diagnostics and lints
@@ -306,8 +305,7 @@ fn get_binder_info<'a>(
306305
binders.get(&name).or_else(|| macros.find_map(|state| state.binders.get(&name)))
307306
}
308307

309-
/// Checks `rhs` as part of the RHS of a macro definition and sets `valid` to false in case of
310-
/// errors.
308+
/// Checks `rhs` as part of the RHS of a macro definition.
311309
///
312310
/// Arguments:
313311
/// - `psess` is used to emit diagnostics and lints
@@ -372,7 +370,7 @@ enum NestedMacroState {
372370
}
373371

374372
/// Checks `tts` as part of the RHS of a macro definition, tries to recognize nested macro
375-
/// definitions, and sets `valid` to false in case of errors.
373+
/// definitions.
376374
///
377375
/// Arguments:
378376
/// - `psess` is used to emit diagnostics and lints
@@ -491,8 +489,7 @@ fn check_nested_occurrences(
491489
}
492490
}
493491

494-
/// Checks the body of nested macro, returns where the check stopped, and sets `valid` to false in
495-
/// case of errors.
492+
/// Checks the body of nested macro, returns where the check stopped.
496493
///
497494
/// The token trees are checked as long as they look like a list of (LHS) => {RHS} token trees. This
498495
/// check is a best-effort to detect a macro definition. It returns the position in `tts` where we

compiler/rustc_mir_transform/src/patch.rs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ use tracing::debug;
1111
/// once with `apply`. This is useful for MIR transformation passes.
1212
pub(crate) struct MirPatch<'tcx> {
1313
term_patch_map: FxHashMap<BasicBlock, TerminatorKind<'tcx>>,
14+
/// Set of statements that should be replaced by `Nop`.
15+
nop_statements: Vec<Location>,
1416
new_blocks: Vec<BasicBlockData<'tcx>>,
1517
new_statements: Vec<(Location, StatementKind<'tcx>)>,
1618
new_locals: Vec<LocalDecl<'tcx>>,
@@ -33,6 +35,7 @@ impl<'tcx> MirPatch<'tcx> {
3335
pub(crate) fn new(body: &Body<'tcx>) -> Self {
3436
let mut result = MirPatch {
3537
term_patch_map: Default::default(),
38+
nop_statements: vec![],
3639
new_blocks: vec![],
3740
new_statements: vec![],
3841
new_locals: vec![],
@@ -212,6 +215,15 @@ impl<'tcx> MirPatch<'tcx> {
212215
self.term_patch_map.insert(block, new);
213216
}
214217

218+
/// Mark given statement to be replaced by a `Nop`.
219+
///
220+
/// This method only works on statements from the initial body, and cannot be used to remove
221+
/// statements from `add_statement` or `add_assign`.
222+
#[tracing::instrument(level = "debug", skip(self))]
223+
pub(crate) fn nop_statement(&mut self, loc: Location) {
224+
self.nop_statements.push(loc);
225+
}
226+
215227
/// Queues the insertion of a statement at a given location. The statement
216228
/// currently at that location, and all statements that follow, are shifted
217229
/// down. If multiple statements are queued for addition at the same
@@ -257,11 +269,8 @@ impl<'tcx> MirPatch<'tcx> {
257269
bbs.extend(self.new_blocks);
258270
body.local_decls.extend(self.new_locals);
259271

260-
// The order in which we patch terminators does not change the result.
261-
#[allow(rustc::potential_query_instability)]
262-
for (src, patch) in self.term_patch_map {
263-
debug!("MirPatch: patching block {:?}", src);
264-
bbs[src].terminator_mut().kind = patch;
272+
for loc in self.nop_statements {
273+
bbs[loc.block].statements[loc.statement_index].make_nop();
265274
}
266275

267276
let mut new_statements = self.new_statements;
@@ -285,6 +294,17 @@ impl<'tcx> MirPatch<'tcx> {
285294
.insert(loc.statement_index, Statement::new(source_info, stmt));
286295
delta += 1;
287296
}
297+
298+
// The order in which we patch terminators does not change the result.
299+
#[allow(rustc::potential_query_instability)]
300+
for (src, patch) in self.term_patch_map {
301+
debug!("MirPatch: patching block {:?}", src);
302+
let bb = &mut bbs[src];
303+
if let TerminatorKind::Unreachable = patch {
304+
bb.statements.clear();
305+
}
306+
bb.terminator_mut().kind = patch;
307+
}
288308
}
289309

290310
fn source_info_for_index(data: &BasicBlockData<'_>, loc: Location) -> SourceInfo {

compiler/rustc_mir_transform/src/simplify_branches.rs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ use rustc_middle::mir::*;
22
use rustc_middle::ty::TyCtxt;
33
use tracing::trace;
44

5+
use crate::patch::MirPatch;
6+
57
pub(super) enum SimplifyConstCondition {
68
AfterConstProp,
79
Final,
@@ -19,26 +21,27 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyConstCondition {
1921
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
2022
trace!("Running SimplifyConstCondition on {:?}", body.source);
2123
let typing_env = body.typing_env(tcx);
22-
'blocks: for block in body.basic_blocks_mut() {
23-
for stmt in block.statements.iter_mut() {
24+
let mut patch = MirPatch::new(body);
25+
26+
'blocks: for (bb, block) in body.basic_blocks.iter_enumerated() {
27+
for (statement_index, stmt) in block.statements.iter().enumerate() {
2428
// Simplify `assume` of a known value: either a NOP or unreachable.
2529
if let StatementKind::Intrinsic(box ref intrinsic) = stmt.kind
2630
&& let NonDivergingIntrinsic::Assume(discr) = intrinsic
2731
&& let Operand::Constant(c) = discr
2832
&& let Some(constant) = c.const_.try_eval_bool(tcx, typing_env)
2933
{
3034
if constant {
31-
stmt.make_nop();
35+
patch.nop_statement(Location { block: bb, statement_index });
3236
} else {
33-
block.statements.clear();
34-
block.terminator_mut().kind = TerminatorKind::Unreachable;
37+
patch.patch_terminator(bb, TerminatorKind::Unreachable);
3538
continue 'blocks;
3639
}
3740
}
3841
}
3942

40-
let terminator = block.terminator_mut();
41-
terminator.kind = match terminator.kind {
43+
let terminator = block.terminator();
44+
let terminator = match terminator.kind {
4245
TerminatorKind::SwitchInt {
4346
discr: Operand::Constant(ref c), ref targets, ..
4447
} => {
@@ -58,7 +61,9 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyConstCondition {
5861
},
5962
_ => continue,
6063
};
64+
patch.patch_terminator(bb, terminator);
6165
}
66+
patch.apply(body);
6267
}
6368

6469
fn is_required(&self) -> bool {

library/std/src/net/hostname.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use crate::ffi::OsString;
2+
3+
/// Returns the system hostname.
4+
///
5+
/// This can error out in platform-specific error cases;
6+
/// for example, uefi and wasm, where hostnames aren't
7+
/// supported.
8+
///
9+
/// # Underlying system calls
10+
///
11+
/// | Platform | System call |
12+
/// |----------|---------------------------------------------------------------------------------------------------------|
13+
/// | UNIX | [`gethostname`](https://www.man7.org/linux/man-pages/man2/gethostname.2.html) |
14+
/// | Windows | [`GetHostNameW`](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-gethostnamew) |
15+
///
16+
/// Note that platform-specific behavior [may change in the future][changes].
17+
///
18+
/// [changes]: crate::io#platform-specific-behavior
19+
#[unstable(feature = "gethostname", issue = "135142")]
20+
pub fn hostname() -> crate::io::Result<OsString> {
21+
crate::sys::net::hostname()
22+
}

library/std/src/net/mod.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
//! Networking primitives for TCP/UDP communication.
22
//!
33
//! This module provides networking functionality for the Transmission Control and User
4-
//! Datagram Protocols, as well as types for IP and socket addresses.
4+
//! Datagram Protocols, as well as types for IP and socket addresses and functions related
5+
//! to network properties.
56
//!
67
//! # Organization
78
//!
@@ -24,6 +25,8 @@
2425
#[stable(feature = "rust1", since = "1.0.0")]
2526
pub use core::net::AddrParseError;
2627

28+
#[unstable(feature = "gethostname", issue = "135142")]
29+
pub use self::hostname::hostname;
2730
#[stable(feature = "rust1", since = "1.0.0")]
2831
pub use self::ip_addr::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};
2932
#[stable(feature = "rust1", since = "1.0.0")]
@@ -35,6 +38,7 @@ pub use self::tcp::{Incoming, TcpListener, TcpStream};
3538
#[stable(feature = "rust1", since = "1.0.0")]
3639
pub use self::udp::UdpSocket;
3740

41+
mod hostname;
3842
mod ip_addr;
3943
mod socket_addr;
4044
mod tcp;

library/std/src/sys/net/connection/socket/windows.rs

Lines changed: 3 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@ use crate::net::{Shutdown, SocketAddr};
88
use crate::os::windows::io::{
99
AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket,
1010
};
11-
use crate::sync::atomic::Atomic;
12-
use crate::sync::atomic::Ordering::{AcqRel, Relaxed};
1311
use crate::sys::c;
12+
use crate::sys::pal::winsock::last_error;
1413
use crate::sys_common::{AsInner, FromInner, IntoInner};
1514
use crate::time::Duration;
1615
use crate::{cmp, mem, ptr, sys};
@@ -112,84 +111,11 @@ pub(super) mod netc {
112111
}
113112
}
114113

114+
pub use crate::sys::pal::winsock::{cleanup, cvt, cvt_gai, cvt_r, startup as init};
115+
115116
#[expect(missing_debug_implementations)]
116117
pub struct Socket(OwnedSocket);
117118

118-
static WSA_INITIALIZED: Atomic<bool> = Atomic::<bool>::new(false);
119-
120-
/// Checks whether the Windows socket interface has been started already, and
121-
/// if not, starts it.
122-
#[inline]
123-
pub fn init() {
124-
if !WSA_INITIALIZED.load(Relaxed) {
125-
wsa_startup();
126-
}
127-
}
128-
129-
#[cold]
130-
fn wsa_startup() {
131-
unsafe {
132-
let mut data: c::WSADATA = mem::zeroed();
133-
let ret = c::WSAStartup(
134-
0x202, // version 2.2
135-
&mut data,
136-
);
137-
assert_eq!(ret, 0);
138-
if WSA_INITIALIZED.swap(true, AcqRel) {
139-
// If another thread raced with us and called WSAStartup first then call
140-
// WSACleanup so it's as though WSAStartup was only called once.
141-
c::WSACleanup();
142-
}
143-
}
144-
}
145-
146-
pub fn cleanup() {
147-
// We don't need to call WSACleanup here because exiting the process will cause
148-
// the OS to clean everything for us, which is faster than doing it manually.
149-
// See #141799.
150-
}
151-
152-
/// Returns the last error from the Windows socket interface.
153-
fn last_error() -> io::Error {
154-
io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
155-
}
156-
157-
#[doc(hidden)]
158-
pub trait IsMinusOne {
159-
fn is_minus_one(&self) -> bool;
160-
}
161-
162-
macro_rules! impl_is_minus_one {
163-
($($t:ident)*) => ($(impl IsMinusOne for $t {
164-
fn is_minus_one(&self) -> bool {
165-
*self == -1
166-
}
167-
})*)
168-
}
169-
170-
impl_is_minus_one! { i8 i16 i32 i64 isize }
171-
172-
/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
173-
/// and if so, returns the last error from the Windows socket interface. This
174-
/// function must be called before another call to the socket API is made.
175-
pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
176-
if t.is_minus_one() { Err(last_error()) } else { Ok(t) }
177-
}
178-
179-
/// A variant of `cvt` for `getaddrinfo` which return 0 for a success.
180-
pub fn cvt_gai(err: c_int) -> io::Result<()> {
181-
if err == 0 { Ok(()) } else { Err(last_error()) }
182-
}
183-
184-
/// Just to provide the same interface as sys/pal/unix/net.rs
185-
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
186-
where
187-
T: IsMinusOne,
188-
F: FnMut() -> T,
189-
{
190-
cvt(f())
191-
}
192-
193119
impl Socket {
194120
pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
195121
let family = match *addr {
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
cfg_select! {
2+
target_family = "unix" => {
3+
mod unix;
4+
pub use unix::hostname;
5+
}
6+
target_os = "windows" => {
7+
mod windows;
8+
pub use windows::hostname;
9+
}
10+
_ => {
11+
mod unsupported;
12+
pub use unsupported::hostname;
13+
}
14+
}

0 commit comments

Comments
 (0)