Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//! PGO (Profile-Guided Optimization) utilities.

use anyhow::Context;
use std::env::consts::EXE_EXTENSION;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use xshell::{Cmd, Shell, cmd};

use crate::flags::PgoTrainingCrate;

/// Decorates `ra_build_cmd` to add PGO instrumentation, and then runs the PGO instrumented
/// Rust Analyzer on itself to gather a PGO profile.
pub(crate) fn gather_pgo_profile<'a>(
    sh: &'a Shell,
    ra_build_cmd: Cmd<'a>,
    target: &str,
    train_crate: PgoTrainingCrate,
) -> anyhow::Result<PathBuf> {
    let pgo_dir = std::path::absolute("rust-analyzer-pgo")?;
    // Clear out any stale profiles
    if pgo_dir.is_dir() {
        std::fs::remove_dir_all(&pgo_dir)?;
    }
    std::fs::create_dir_all(&pgo_dir)?;

    // Figure out a path to `llvm-profdata`
    let target_libdir = cmd!(sh, "rustc --print=target-libdir")
        .read()
        .context("cannot resolve target-libdir from rustc")?;
    let target_bindir = PathBuf::from(target_libdir).parent().unwrap().join("bin");
    let llvm_profdata = target_bindir.join("llvm-profdata").with_extension(EXE_EXTENSION);

    // Build RA with PGO instrumentation
    let cmd_gather =
        ra_build_cmd.env("RUSTFLAGS", format!("-Cprofile-generate={}", pgo_dir.to_str().unwrap()));
    cmd_gather.run().context("cannot build rust-analyzer with PGO instrumentation")?;

    let (train_path, label) = match &train_crate {
        PgoTrainingCrate::RustAnalyzer => (PathBuf::from("."), "itself"),
        PgoTrainingCrate::GitHub(repo) => {
            (download_crate_for_training(sh, &pgo_dir, repo)?, repo.as_str())
        }
    };

    // Run RA either on itself or on a downloaded crate
    eprintln!("Training RA on {label}...");
    cmd!(
        sh,
        "target/{target}/release/rust-analyzer analysis-stats -q --run-all-ide-things {train_path}"
    )
    .run()
    .context("cannot generate PGO profiles")?;

    // Merge profiles into a single file
    let merged_profile = pgo_dir.join("merged.profdata");
    let profile_files = std::fs::read_dir(pgo_dir)?
        .filter_map(|entry| {
            let entry = entry.ok()?;
            if entry.path().extension() == Some(OsStr::new("profraw")) {
                Some(entry.path().to_str().unwrap().to_owned())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    if profile_files.is_empty() {
        anyhow::bail!(
            "rust-analyzer analysis-stats produced no pgo files. This is a bug in rust-analyzer; please file an issue."
        );
    }

    cmd!(sh, "{llvm_profdata} merge {profile_files...} -o {merged_profile}").run().context(
        "cannot merge PGO profiles. Do you have the rustup `llvm-tools` component installed?",
    )?;

    Ok(merged_profile)
}

/// Downloads a crate from GitHub, stores it into `pgo_dir` and returns a path to it.
fn download_crate_for_training(sh: &Shell, pgo_dir: &Path, repo: &str) -> anyhow::Result<PathBuf> {
    let mut it = repo.splitn(2, '@');
    let repo = it.next().unwrap();
    let revision = it.next();

    // FIXME: switch to `--revision` here around 2035 or so
    let revision =
        if let Some(revision) = revision { &["--branch", revision] as &[&str] } else { &[] };

    let normalized_path = repo.replace("/", "-");
    let target_path = pgo_dir.join(normalized_path);
    cmd!(sh, "git clone --depth 1 https://github.com/{repo} {revision...} {target_path}")
        .run()
        .with_context(|| format!("cannot download PGO training crate from {repo}"))?;

    Ok(target_path)
}

/// Helper function to create a build command for rust-analyzer
pub(crate) fn build_command<'a>(
    sh: &'a Shell,
    command: &str,
    target_name: &str,
    features: &[&str],
) -> Cmd<'a> {
    cmd!(
        sh,
        "cargo {command} --manifest-path ./crates/rust-analyzer/Cargo.toml --bin rust-analyzer --target {target_name} {features...} --release"
    )
}

pub(crate) fn apply_pgo_to_cmd<'a>(cmd: Cmd<'a>, profile_path: &Path) -> Cmd<'a> {
    cmd.env("RUSTFLAGS", format!("-Cprofile-use={}", profile_path.to_str().unwrap()))
}
light .kr { color: #FFAD66 } /* Keyword.Reserved */ .highlight .kt { color: #73D0FF } /* Keyword.Type */ .highlight .m { color: #DFBFFF } /* Literal.Number */ .highlight .s { color: #D5FF80 } /* Literal.String */ .highlight .na { color: #FFD173 } /* Name.Attribute */ .highlight .nb { color: #F28779 } /* Name.Builtin */ .highlight .nc { color: #5CCFE6 } /* Name.Class */ .highlight .no { color: #DFBFFF } /* Name.Constant */ .highlight .nd { color: #FFDFB3 } /* Name.Decorator */ .highlight .nf { color: #FFD173 } /* Name.Function */ .highlight .nt { color: #5CCFE6 } /* Name.Tag */ .highlight .ow { color: #F29E74 } /* Operator.Word */ .highlight .w { color: #CCCAC2 } /* Text.Whitespace */ .highlight .mb { color: #DFBFFF } /* Literal.Number.Bin */ .highlight .mf { color: #DFBFFF } /* Literal.Number.Float */ .highlight .mh { color: #DFBFFF } /* Literal.Number.Hex */ .highlight .mi { color: #DFBFFF } /* Literal.Number.Integer */ .highlight .mo { color: #DFBFFF } /* Literal.Number.Oct */ .highlight .sa { color: #D5FF80 } /* Literal.String.Affix */ .highlight .sb { color: #F29E74 } /* Literal.String.Backtick */ .highlight .sc { color: #D5FF80 } /* Literal.String.Char */ .highlight .dl { color: #D5FF80 } /* Literal.String.Delimiter */ .highlight .sd { color: #95E6CB; font-style: italic } /* Literal.String.Doc */ .highlight .s2 { color: #D5FF80 } /* Literal.String.Double */ .highlight .se { color: #D5FF80 } /* Literal.String.Escape */ .highlight .sh { color: #D5FF80 } /* Literal.String.Heredoc */ .highlight .si { color: #D5FF80 } /* Literal.String.Interpol */ .highlight .sx { color: #D5FF80 } /* Literal.String.Other */ .highlight .sr { color: #95E6CB } /* Literal.String.Regex */ .highlight .s1 { color: #D5FF80 } /* Literal.String.Single */ .highlight .ss { color: #D5FF80 } /* Literal.String.Symbol */ .highlight .bp { color: #F28779 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #FFD173 } /* Name.Function.Magic */ .highlight .vi { color: #FFCC66 } /* Name.Variable.Instance */ .highlight .vm { color: #5CCFE6; font-style: italic } /* Name.Variable.Magic */ .highlight .il { color: #DFBFFF } /* Literal.Number.Integer.Long */