Skip to content

Commit dcb4378

Browse files
committed
Auto merge of #44646 - petrochenkov:scompress, r=michaelwoerister
Compress most of spans to 32 bits As described in https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28 Closes #15594 r? @michaelwoerister
2 parents cd93969 + 52251cd commit dcb4378

File tree

6 files changed

+188
-32
lines changed

6 files changed

+188
-32
lines changed

src/librustc/ty/maps/plumbing.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ macro_rules! define_maps {
221221

222222
profq_msg!(tcx,
223223
ProfileQueriesMsg::QueryBegin(
224-
span.clone(),
224+
span.data(),
225225
QueryMsg::$name(profq_key!(tcx, key))
226226
)
227227
);

src/librustc/util/common.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use std::path::Path;
2020
use std::time::{Duration, Instant};
2121

2222
use std::sync::mpsc::{Sender};
23-
use syntax_pos::{Span};
23+
use syntax_pos::{SpanData};
2424
use ty::maps::{QueryMsg};
2525
use dep_graph::{DepNode};
2626

@@ -61,7 +61,8 @@ pub enum ProfileQueriesMsg {
6161
/// end a task
6262
TaskEnd,
6363
/// begin a new query
64-
QueryBegin(Span, QueryMsg),
64+
/// can't use `Span` because queries are sent to other thread
65+
QueryBegin(SpanData, QueryMsg),
6566
/// query is satisfied by using an already-known value for the given key
6667
CacheHit,
6768
/// query requires running a provider; providers may nest, permitting queries to nest.

src/librustc_driver/profile/trace.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
// except according to those terms.
1010

1111
use super::*;
12-
use syntax_pos::Span;
12+
use syntax_pos::SpanData;
1313
use rustc::ty::maps::QueryMsg;
1414
use std::fs::File;
1515
use std::time::{Duration, Instant};
@@ -18,7 +18,7 @@ use rustc::dep_graph::{DepNode};
1818

1919
#[derive(Debug, Clone, Eq, PartialEq)]
2020
pub struct Query {
21-
pub span: Span,
21+
pub span: SpanData,
2222
pub msg: QueryMsg,
2323
}
2424
pub enum Effect {

src/libsyntax_pos/hygiene.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use std::fmt;
2525

2626
/// A SyntaxContext represents a chain of macro expansions (represented by marks).
2727
#[derive(Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
28-
pub struct SyntaxContext(u32);
28+
pub struct SyntaxContext(pub(super) u32);
2929

3030
#[derive(Copy, Clone, Default)]
3131
pub struct SyntaxContextData {

src/libsyntax_pos/lib.rs

+38-26
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,10 @@
2525
#![feature(optin_builtin_traits)]
2626
#![allow(unused_attributes)]
2727
#![feature(specialization)]
28-
#![feature(staged_api)]
2928

3029
use std::borrow::Cow;
3130
use std::cell::{Cell, RefCell};
32-
use std::cmp;
31+
use std::cmp::{self, Ordering};
3332
use std::fmt;
3433
use std::hash::Hasher;
3534
use std::ops::{Add, Sub};
@@ -47,6 +46,9 @@ extern crate serialize as rustc_serialize; // used by deriving
4746
pub mod hygiene;
4847
pub use hygiene::{SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan, CompilerDesugaringKind};
4948

49+
mod span_encoding;
50+
pub use span_encoding::{Span, DUMMY_SP};
51+
5052
pub mod symbol;
5153

5254
pub type FileName = String;
@@ -59,23 +61,33 @@ pub type FileName = String;
5961
/// able to use many of the functions on spans in codemap and you cannot assume
6062
/// that the length of the span = hi - lo; there may be space in the BytePos
6163
/// range between files.
64+
///
65+
/// `SpanData` is public because `Span` uses a thread-local interner and can't be
66+
/// sent to other threads, but some pieces of performance infra run in a separate thread.
67+
/// Using `Span` is generally preferred.
6268
#[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
63-
pub struct Span {
64-
#[unstable(feature = "rustc_private", issue = "27812")]
65-
#[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
69+
pub struct SpanData {
6670
pub lo: BytePos,
67-
#[unstable(feature = "rustc_private", issue = "27812")]
68-
#[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
6971
pub hi: BytePos,
7072
/// Information about where the macro came from, if this piece of
7173
/// code was created by a macro expansion.
72-
#[unstable(feature = "rustc_private", issue = "27812")]
73-
#[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
7474
pub ctxt: SyntaxContext,
7575
}
7676

77-
#[allow(deprecated)]
78-
pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), ctxt: NO_EXPANSION };
77+
// The interner in thread-local, so `Span` shouldn't move between threads.
78+
impl !Send for Span {}
79+
impl !Sync for Span {}
80+
81+
impl PartialOrd for Span {
82+
fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
83+
PartialOrd::partial_cmp(&self.data(), &rhs.data())
84+
}
85+
}
86+
impl Ord for Span {
87+
fn cmp(&self, rhs: &Self) -> Ordering {
88+
Ord::cmp(&self.data(), &rhs.data())
89+
}
90+
}
7991

8092
/// A collection of spans. Spans have two orthogonal attributes:
8193
///
@@ -90,38 +102,32 @@ pub struct MultiSpan {
90102
}
91103

92104
impl Span {
93-
#[allow(deprecated)]
94-
#[inline]
95-
pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
96-
if lo <= hi { Span { lo, hi, ctxt } } else { Span { lo: hi, hi: lo, ctxt } }
97-
}
98-
99-
#[allow(deprecated)]
100105
#[inline]
101106
pub fn lo(self) -> BytePos {
102-
self.lo
107+
self.data().lo
103108
}
104109
#[inline]
105110
pub fn with_lo(self, lo: BytePos) -> Span {
106-
Span::new(lo, self.hi(), self.ctxt())
111+
let base = self.data();
112+
Span::new(lo, base.hi, base.ctxt)
107113
}
108-
#[allow(deprecated)]
109114
#[inline]
110115
pub fn hi(self) -> BytePos {
111-
self.hi
116+
self.data().hi
112117
}
113118
#[inline]
114119
pub fn with_hi(self, hi: BytePos) -> Span {
115-
Span::new(self.lo(), hi, self.ctxt())
120+
let base = self.data();
121+
Span::new(base.lo, hi, base.ctxt)
116122
}
117-
#[allow(deprecated)]
118123
#[inline]
119124
pub fn ctxt(self) -> SyntaxContext {
120-
self.ctxt
125+
self.data().ctxt
121126
}
122127
#[inline]
123128
pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
124-
Span::new(self.lo(), self.hi(), ctxt)
129+
let base = self.data();
130+
Span::new(base.lo, base.hi, ctxt)
125131
}
126132

127133
/// Returns a new span representing just the end-point of this span
@@ -342,6 +348,12 @@ impl fmt::Debug for Span {
342348
}
343349
}
344350

351+
impl fmt::Debug for SpanData {
352+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
353+
SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
354+
}
355+
}
356+
345357
impl MultiSpan {
346358
pub fn new() -> MultiSpan {
347359
MultiSpan {

src/libsyntax_pos/span_encoding.rs

+143
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// Spans are encoded using 1-bit tag and 2 different encoding formats (one for each tag value).
12+
// One format is used for keeping span data inline,
13+
// another contains index into an out-of-line span interner.
14+
// The encoding format for inline spans were obtained by optimizing over crates in rustc/libstd.
15+
// See https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28
16+
17+
use {BytePos, SpanData};
18+
use hygiene::SyntaxContext;
19+
20+
use rustc_data_structures::fx::FxHashMap;
21+
use std::cell::RefCell;
22+
23+
/// A compressed span.
24+
/// Contains either fields of `SpanData` inline if they are small, or index into span interner.
25+
/// The primary goal of `Span` is to be as small as possible and fit into other structures
26+
/// (that's why it uses `packed` as well). Decoding speed is the second priority.
27+
/// See `SpanData` for the info on span fields in decoded representation.
28+
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
29+
#[repr(packed)]
30+
pub struct Span(u32);
31+
32+
/// Dummy span, both position and length are zero, syntax context is zero as well.
33+
/// This span is kept inline and encoded with format 0.
34+
pub const DUMMY_SP: Span = Span(0);
35+
36+
impl Span {
37+
#[inline]
38+
pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
39+
encode(&match lo <= hi {
40+
true => SpanData { lo, hi, ctxt },
41+
false => SpanData { lo: hi, hi: lo, ctxt },
42+
})
43+
}
44+
45+
#[inline]
46+
pub fn data(self) -> SpanData {
47+
decode(self)
48+
}
49+
}
50+
51+
// Tags
52+
const TAG_INLINE: u32 = 0;
53+
const TAG_INTERNED: u32 = 1;
54+
const TAG_MASK: u32 = 1;
55+
56+
// Fields indexes
57+
const BASE_INDEX: usize = 0;
58+
const LEN_INDEX: usize = 1;
59+
const CTXT_INDEX: usize = 2;
60+
61+
// Tag = 0, inline format.
62+
// -----------------------------------
63+
// | base 31:8 | len 7:1 | tag 0:0 |
64+
// -----------------------------------
65+
const INLINE_SIZES: [u32; 3] = [24, 7, 0];
66+
const INLINE_OFFSETS: [u32; 3] = [8, 1, 1];
67+
68+
// Tag = 1, interned format.
69+
// ------------------------
70+
// | index 31:1 | tag 0:0 |
71+
// ------------------------
72+
const INTERNED_INDEX_SIZE: u32 = 31;
73+
const INTERNED_INDEX_OFFSET: u32 = 1;
74+
75+
#[inline]
76+
fn encode(sd: &SpanData) -> Span {
77+
let (base, len, ctxt) = (sd.lo.0, sd.hi.0 - sd.lo.0, sd.ctxt.0);
78+
79+
let val = if (base >> INLINE_SIZES[BASE_INDEX]) == 0 &&
80+
(len >> INLINE_SIZES[LEN_INDEX]) == 0 &&
81+
(ctxt >> INLINE_SIZES[CTXT_INDEX]) == 0 {
82+
(base << INLINE_OFFSETS[BASE_INDEX]) | (len << INLINE_OFFSETS[LEN_INDEX]) |
83+
(ctxt << INLINE_OFFSETS[CTXT_INDEX]) | TAG_INLINE
84+
} else {
85+
let index = with_span_interner(|interner| interner.intern(sd));
86+
(index << INTERNED_INDEX_OFFSET) | TAG_INTERNED
87+
};
88+
Span(val)
89+
}
90+
91+
#[inline]
92+
fn decode(span: Span) -> SpanData {
93+
let val = span.0;
94+
95+
// Extract a field at position `pos` having size `size`.
96+
let extract = |pos: u32, size: u32| {
97+
let mask = ((!0u32) as u64 >> (32 - size)) as u32; // Can't shift u32 by 32
98+
(val >> pos) & mask
99+
};
100+
101+
let (base, len, ctxt) = if val & TAG_MASK == TAG_INLINE {(
102+
extract(INLINE_OFFSETS[BASE_INDEX], INLINE_SIZES[BASE_INDEX]),
103+
extract(INLINE_OFFSETS[LEN_INDEX], INLINE_SIZES[LEN_INDEX]),
104+
extract(INLINE_OFFSETS[CTXT_INDEX], INLINE_SIZES[CTXT_INDEX]),
105+
)} else {
106+
let index = extract(INTERNED_INDEX_OFFSET, INTERNED_INDEX_SIZE);
107+
return with_span_interner(|interner| *interner.get(index));
108+
};
109+
SpanData { lo: BytePos(base), hi: BytePos(base + len), ctxt: SyntaxContext(ctxt) }
110+
}
111+
112+
#[derive(Default)]
113+
struct SpanInterner {
114+
spans: FxHashMap<SpanData, u32>,
115+
span_data: Vec<SpanData>,
116+
}
117+
118+
impl SpanInterner {
119+
fn intern(&mut self, span_data: &SpanData) -> u32 {
120+
if let Some(index) = self.spans.get(span_data) {
121+
return *index;
122+
}
123+
124+
let index = self.spans.len() as u32;
125+
self.span_data.push(*span_data);
126+
self.spans.insert(*span_data, index);
127+
index
128+
}
129+
130+
#[inline]
131+
fn get(&self, index: u32) -> &SpanData {
132+
&self.span_data[index as usize]
133+
}
134+
}
135+
136+
// If an interner exists in TLS, return it. Otherwise, prepare a fresh one.
137+
#[inline]
138+
fn with_span_interner<T, F: FnOnce(&mut SpanInterner) -> T>(f: F) -> T {
139+
thread_local!(static INTERNER: RefCell<SpanInterner> = {
140+
RefCell::new(SpanInterner::default())
141+
});
142+
INTERNER.with(|interner| f(&mut *interner.borrow_mut()))
143+
}

0 commit comments

Comments
 (0)