Skip to content

Commit cbe4449

Browse files
committed
Auto merge of rust-lang#125419 - GuillaumeGomez:add-gcc-to-dist, r=<try>
[bootstrap] Add gcc to dist generation As `@eholk` summarized below: > From my understanding, this change would add libgccjit as an optional component to the Rust distribution. This library is licensed under GPLv2 and currently we do not have any other components under that license so it would be a new license, and one that is generally more restrictive than the other licenses we use. It'll greatly improve the experience for anyone wanting to work on the GCC backend from the compiler. Should help with rust-lang#124172. Will unblock rust-lang#124353. r? `@Kobzol`
2 parents d3a3939 + 7319664 commit cbe4449

File tree

15 files changed

+631
-8
lines changed

15 files changed

+631
-8
lines changed

.gitmodules

+3
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,6 @@
4747
path = src/tools/rustc-perf
4848
url = https://github.com/rust-lang/rustc-perf.git
4949
shallow = true
50+
[submodule "src/gcc"]
51+
path = src/gcc
52+
url = https://github.com/rust-lang/gcc

LICENSES/GCC-exception-3.1.txt

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
GCC RUNTIME LIBRARY EXCEPTION
2+
3+
Version 3.1, 31 March 2009
4+
5+
Copyright © 2009 Free Software Foundation, Inc. <https://fsf.org/>
6+
7+
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
8+
9+
This GCC Runtime Library Exception ("Exception") is an additional permission under section 7 of the GNU General Public License, version 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that bears a notice placed by the copyright holder of the file stating that the file is governed by GPLv3 along with this Exception.
10+
11+
When you use GCC to compile a program, GCC may combine portions of certain GCC header files and runtime libraries with the compiled program. The purpose of this Exception is to allow compilation of non-GPL (including proprietary) programs to use, in this way, the header files and runtime libraries covered by this Exception.
12+
0. Definitions.
13+
14+
A file is an "Independent Module" if it either requires the Runtime Library for execution after a Compilation Process, or makes use of an interface provided by the Runtime Library, but is not otherwise based on the Runtime Library.
15+
16+
"GCC" means a version of the GNU Compiler Collection, with or without modifications, governed by version 3 (or a specified later version) of the GNU General Public License (GPL) with the option of using any subsequent versions published by the FSF.
17+
18+
"GPL-compatible Software" is software whose conditions of propagation, modification and use would permit combination with GCC in accord with the license of GCC.
19+
20+
"Target Code" refers to output from any compiler for a real or virtual target processor architecture, in executable form or suitable for input to an assembler, loader, linker and/or execution phase. Notwithstanding that, Target Code does not include data in any format that is used as a compiler intermediate representation, or used for producing a compiler intermediate representation.
21+
22+
The "Compilation Process" transforms code entirely represented in non-intermediate languages designed for human-written code, and/or in Java Virtual Machine byte code, into Target Code. Thus, for example, use of source code generators and preprocessors need not be considered part of the Compilation Process, since the Compilation Process can be understood as starting with the output of the generators or preprocessors.
23+
24+
A Compilation Process is "Eligible" if it is done using GCC, alone or with other GPL-compatible software, or if it is done without using any work based on GCC. For example, using non-GPL-compatible Software to optimize any GCC intermediate representations would not qualify as an Eligible Compilation Process.
25+
1. Grant of Additional Permission.
26+
27+
You have permission to propagate a work of Target Code formed by combining the Runtime Library with Independent Modules, even if such propagation would otherwise violate the terms of GPLv3, provided that all Target Code was generated by Eligible Compilation Processes. You may then convey such a combination under terms of your choice, consistent with the licensing of the Independent Modules.
28+
2. No Weakening of GCC Copyleft.
29+
30+
The availability of this Exception does not imply any general presumption that third-party software is unaffected by the copyleft requirements of the license of GCC.

LICENSES/GPL-2.0-only.txt

+133
Large diffs are not rendered by default.

LICENSES/GPL-3.0-or-later.txt

+202
Large diffs are not rendered by default.

LICENSES/ISC.txt

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
ISC License
2+
3+
<copyright notice>
4+
5+
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
6+
7+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

rustfmt.toml

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ ignore = [
4545
"src/tools/rust-analyzer",
4646
"src/tools/rustc-perf",
4747
"src/tools/rustfmt",
48+
"src/gcc",
4849

4950
# These are ignored by a standard cargo fmt run.
5051
"compiler/rustc_codegen_cranelift/scripts",

src/bootstrap/src/core/build_steps/dist.rs

+10
Original file line numberDiff line numberDiff line change
@@ -2286,6 +2286,7 @@ impl Step for RustDev {
22862286
tarball.permit_symlinks(true);
22872287

22882288
builder.ensure(crate::core::build_steps::llvm::Llvm { target });
2289+
builder.ensure(crate::core::build_steps::gcc::Gcc { target });
22892290

22902291
let src_bindir = builder.llvm_out(target).join("bin");
22912292
// If updating this, you likely want to change
@@ -2321,6 +2322,15 @@ impl Step for RustDev {
23212322
// just broadly useful to be able to link against the bundled LLVM.
23222323
tarball.add_dir(builder.llvm_out(target).join("include"), "include");
23232324

2325+
let libgccjit_path = builder.gcc_out(target).join("install/lib/libgccjit.so");
2326+
if libgccjit_path.exists() {
2327+
tarball.add_dir(libgccjit_path, "libgccjit.so");
2328+
tarball.add_dir(
2329+
builder.gcc_out(target).join("install/lib/libgccjit.so.0"),
2330+
"libgccjit.so.0",
2331+
);
2332+
}
2333+
23242334
// Copy libLLVM.so to the target lib dir as well, so the RPATH like
23252335
// `$ORIGIN/../lib` can find it. It may also be used as a dependency
23262336
// of `rustc-dev` to support the inherited `-lLLVM` when using the
+224
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
//! Compilation of native dependencies like GCC.
2+
//!
3+
//! Native projects like GCC unfortunately aren't suited just yet for
4+
//! compilation in build scripts that Cargo has. This is because the
5+
//! compilation takes a *very* long time but also because we don't want to
6+
//! compile GCC 3 times as part of a normal bootstrap (we want it cached).
7+
//!
8+
//! GCC and compiler-rt are essentially just wired up to everything else to
9+
//! ensure that they're always in place if needed.
10+
11+
use std::fs;
12+
use std::path::{Path, PathBuf};
13+
use std::sync::OnceLock;
14+
15+
use crate::core::builder::{Builder, RunConfig, ShouldRun, Step};
16+
use crate::core::config::TargetSelection;
17+
use crate::utils::exec::command;
18+
use crate::utils::helpers::{self, t};
19+
use crate::{generate_smart_stamp_hash, Kind};
20+
21+
use super::llvm::HashStamp;
22+
23+
pub struct Meta {
24+
stamp: HashStamp,
25+
out_dir: PathBuf,
26+
install_dir: PathBuf,
27+
root: PathBuf,
28+
}
29+
30+
pub enum GccBuildStatus {
31+
AlreadyBuilt,
32+
ShouldBuild(Meta),
33+
}
34+
35+
/// This returns whether we've already previously built GCC.
36+
///
37+
/// It's used to avoid busting caches during x.py check -- if we've already built
38+
/// GCC, it's fine for us to not try to avoid doing so.
39+
pub fn prebuilt_gcc_config(builder: &Builder<'_>, target: TargetSelection) -> GccBuildStatus {
40+
// If we have gcc submodule initialized already, sync it.
41+
builder.update_existing_submodule(&Path::new("src").join("gcc"));
42+
43+
// FIXME (GuillaumeGomez): To be done once gccjit has been built in the CI.
44+
// builder.config.maybe_download_ci_gcc();
45+
46+
// Initialize the gcc submodule if not initialized already.
47+
builder.update_submodule(&Path::new("src").join("gcc"));
48+
49+
let root = "src/gcc";
50+
let out_dir = builder.gcc_out(target).join("build");
51+
let install_dir = builder.gcc_out(target).join("install");
52+
53+
static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
54+
let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
55+
generate_smart_stamp_hash(
56+
builder,
57+
&builder.config.src.join("src/gcc"),
58+
builder.in_tree_gcc_info.sha().unwrap_or_default(),
59+
)
60+
});
61+
62+
let stamp = out_dir.join("gcc-finished-building");
63+
let stamp = HashStamp::new(stamp, Some(smart_stamp_hash));
64+
65+
if stamp.is_done() {
66+
if stamp.hash.is_none() {
67+
builder.info(
68+
"Could not determine the GCC submodule commit hash. \
69+
Assuming that an GCC rebuild is not necessary.",
70+
);
71+
builder.info(&format!(
72+
"To force GCC to rebuild, remove the file `{}`",
73+
stamp.path.display()
74+
));
75+
}
76+
return GccBuildStatus::AlreadyBuilt;
77+
}
78+
79+
GccBuildStatus::ShouldBuild(Meta { stamp, out_dir, install_dir, root: root.into() })
80+
}
81+
82+
// FIXME (GuillaumeGomez): When gcc-ci-download option is added, uncomment this code.
83+
// /// This retrieves the GCC sha we *want* to use, according to git history.
84+
// pub(crate) fn detect_gcc_sha(config: &Config, is_git: bool) -> String {
85+
// let gcc_sha = if is_git {
86+
// // We proceed in 2 steps. First we get the closest commit that is actually upstream. Then we
87+
// // walk back further to the last bors merge commit that actually changed GCC. The first
88+
// // step will fail on CI because only the `auto` branch exists; we just fall back to `HEAD`
89+
// // in that case.
90+
// let closest_upstream = get_git_merge_base(&config.git_config(), Some(&config.src))
91+
// .unwrap_or_else(|_| "HEAD".into());
92+
// let mut rev_list = config.git();
93+
// rev_list.args(&[
94+
// PathBuf::from("rev-list"),
95+
// format!("--author={}", config.stage0_metadata.config.git_merge_commit_email).into(),
96+
// "-n1".into(),
97+
// "--first-parent".into(),
98+
// closest_upstream.into(),
99+
// "--".into(),
100+
// config.src.join("src/gcc"),
101+
// config.src.join("src/bootstrap/download-ci-gcc-stamp"),
102+
// // the GCC shared object file is named `gcc-12-rust-{version}-nightly`
103+
// config.src.join("src/version"),
104+
// ]);
105+
// output(&mut rev_list).trim().to_owned()
106+
// } else if let Some(info) = channel::read_commit_info_file(&config.src) {
107+
// info.sha.trim().to_owned()
108+
// } else {
109+
// "".to_owned()
110+
// };
111+
112+
// if gcc_sha.is_empty() {
113+
// eprintln!("error: could not find commit hash for downloading GCC");
114+
// eprintln!("HELP: maybe your repository history is too shallow?");
115+
// eprintln!("HELP: consider disabling `download-ci-gcc`");
116+
// eprintln!("HELP: or fetch enough history to include one upstream commit");
117+
// panic!();
118+
// }
119+
120+
// gcc_sha
121+
// }
122+
123+
// /// Returns whether the CI-found GCC is currently usable.
124+
// ///
125+
// /// This checks both the build triple platform to confirm we're usable at all,
126+
// /// and then verifies if the current HEAD matches the detected GCC SHA head,
127+
// /// in which case GCC is indicated as not available.
128+
// pub(crate) fn is_ci_gcc_available(config: &Config, asserts: bool) -> bool {
129+
// let supported_platforms = [
130+
// // tier 1
131+
// ("x86_64-unknown-linux-gnu", true),
132+
// ];
133+
134+
// if !supported_platforms.contains(&(&*config.build.triple, asserts))
135+
// && (asserts || !supported_platforms.contains(&(&*config.build.triple, true)))
136+
// {
137+
// return false;
138+
// }
139+
140+
// if is_ci_gcc_modified(config) {
141+
// eprintln!("Detected GCC as non-available: running in CI and modified GCC in this change");
142+
// return false;
143+
// }
144+
145+
// true
146+
// }
147+
148+
// /// Returns true if we're running in CI with modified GCC (and thus can't download it)
149+
// pub(crate) fn is_ci_gcc_modified(config: &Config) -> bool {
150+
// CiEnv::is_ci() && config.rust_info.is_managed_git_subrepository() && {
151+
// // We assume we have access to git, so it's okay to unconditionally pass
152+
// // `true` here.
153+
// let gcc_sha = detect_gcc_sha(config, true);
154+
// let head_sha = output(config.git().arg("rev-parse").arg("HEAD"));
155+
// let head_sha = head_sha.trim();
156+
// gcc_sha == head_sha
157+
// }
158+
// }
159+
160+
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
161+
pub struct Gcc {
162+
pub target: TargetSelection,
163+
}
164+
165+
impl Step for Gcc {
166+
type Output = bool;
167+
168+
const ONLY_HOSTS: bool = true;
169+
170+
fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
171+
run.path("src/gcc")
172+
}
173+
174+
fn make_run(run: RunConfig<'_>) {
175+
run.builder.ensure(Gcc { target: run.target });
176+
}
177+
178+
/// Compile GCC for `target`.
179+
fn run(self, builder: &Builder<'_>) -> bool {
180+
let target = self.target;
181+
if !target.contains("linux") || !target.contains("x86_64") {
182+
return false;
183+
}
184+
185+
// If GCC has already been built or been downloaded through download-ci-gcc, we avoid
186+
// building it again.
187+
let Meta { stamp, out_dir, install_dir, root } = match prebuilt_gcc_config(builder, target)
188+
{
189+
GccBuildStatus::AlreadyBuilt => return true,
190+
GccBuildStatus::ShouldBuild(m) => m,
191+
};
192+
193+
let _guard = builder.msg_unstaged(Kind::Build, "GCC", target);
194+
t!(stamp.remove());
195+
let _time = helpers::timeit(builder);
196+
t!(fs::create_dir_all(&out_dir));
197+
198+
if builder.config.dry_run() {
199+
return true;
200+
}
201+
202+
builder.run(
203+
command(root.join("configure"))
204+
.current_dir(&out_dir)
205+
.arg("--enable-host-shared")
206+
.arg("--enable-languages=jit")
207+
.arg("--enable-checking=release")
208+
.arg("--disable-bootstrap")
209+
.arg("--disable-multilib")
210+
.arg(format!("--prefix={}", install_dir.display())),
211+
);
212+
builder.run(command("make").current_dir(&out_dir).arg(format!("-j{}", builder.jobs())));
213+
builder.run(command("make").current_dir(&out_dir).arg("install"));
214+
215+
t!(builder.symlink_file(
216+
install_dir.join("lib/libgccjit.so"),
217+
install_dir.join("lib/libgccjit.so.0")
218+
));
219+
220+
t!(stamp.write());
221+
222+
true
223+
}
224+
}

src/bootstrap/src/core/build_steps/llvm.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -1141,17 +1141,17 @@ fn supported_sanitizers(
11411141
}
11421142
}
11431143

1144-
struct HashStamp {
1145-
path: PathBuf,
1146-
hash: Option<Vec<u8>>,
1144+
pub(super) struct HashStamp {
1145+
pub(super) path: PathBuf,
1146+
pub(super) hash: Option<Vec<u8>>,
11471147
}
11481148

11491149
impl HashStamp {
1150-
fn new(path: PathBuf, hash: Option<&str>) -> Self {
1150+
pub(super) fn new(path: PathBuf, hash: Option<&str>) -> Self {
11511151
HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
11521152
}
11531153

1154-
fn is_done(&self) -> bool {
1154+
pub(super) fn is_done(&self) -> bool {
11551155
match fs::read(&self.path) {
11561156
Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
11571157
Err(e) if e.kind() == io::ErrorKind::NotFound => false,
@@ -1161,7 +1161,7 @@ impl HashStamp {
11611161
}
11621162
}
11631163

1164-
fn remove(&self) -> io::Result<()> {
1164+
pub(super) fn remove(&self) -> io::Result<()> {
11651165
match fs::remove_file(&self.path) {
11661166
Ok(()) => Ok(()),
11671167
Err(e) => {
@@ -1174,7 +1174,7 @@ impl HashStamp {
11741174
}
11751175
}
11761176

1177-
fn write(&self) -> io::Result<()> {
1177+
pub(super) fn write(&self) -> io::Result<()> {
11781178
fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
11791179
}
11801180
}

src/bootstrap/src/core/build_steps/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ pub(crate) mod compile;
55
pub(crate) mod dist;
66
pub(crate) mod doc;
77
pub(crate) mod format;
8+
pub(crate) mod gcc;
89
pub(crate) mod install;
910
pub(crate) mod llvm;
1011
pub(crate) mod perf;

src/bootstrap/src/lib.rs

+7
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ pub struct Build {
139139
miri_info: GitInfo,
140140
rustfmt_info: GitInfo,
141141
in_tree_llvm_info: GitInfo,
142+
in_tree_gcc_info: GitInfo,
142143
local_rebuild: bool,
143144
fail_fast: bool,
144145
doc_tests: DocTests,
@@ -307,6 +308,7 @@ impl Build {
307308

308309
// we always try to use git for LLVM builds
309310
let in_tree_llvm_info = GitInfo::new(false, &src.join("src/llvm-project"));
311+
let in_tree_gcc_info = GitInfo::new(false, &src.join("src/gcc"));
310312

311313
let initial_target_libdir_str = if config.dry_run() {
312314
"/dummy/lib/path/to/lib/".to_string()
@@ -392,6 +394,7 @@ impl Build {
392394
miri_info,
393395
rustfmt_info,
394396
in_tree_llvm_info,
397+
in_tree_gcc_info,
395398
cc: RefCell::new(HashMap::new()),
396399
cxx: RefCell::new(HashMap::new()),
397400
ar: RefCell::new(HashMap::new()),
@@ -849,6 +852,10 @@ impl Build {
849852
}
850853
}
851854

855+
fn gcc_out(&self, target: TargetSelection) -> PathBuf {
856+
self.out.join(&*target.triple).join("gcc")
857+
}
858+
852859
fn lld_out(&self, target: TargetSelection) -> PathBuf {
853860
self.out.join(&*target.triple).join("lld")
854861
}

src/gcc

Submodule gcc added at fd3498b

src/tools/tidy/config/black.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ extend-exclude = """(\
1212
src/llvm-project/|\
1313
src/doc/embedded-book/|\
1414
src/tools/rustc-perf/|\
15-
library/backtrace/
15+
library/backtrace/|\
16+
src/gcc/
1617
)"""

0 commit comments

Comments
 (0)