]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/llvm_util.rs
Auto merge of #83357 - saethlin:vec-reserve-inlining, r=dtolnay
[rust.git] / compiler / rustc_codegen_llvm / src / llvm_util.rs
1 use crate::back::write::create_informational_target_machine;
2 use crate::llvm;
3 use libc::c_int;
4 use rustc_codegen_ssa::target_features::supported_target_features;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_middle::bug;
7 use rustc_session::config::PrintRequest;
8 use rustc_session::Session;
9 use rustc_span::symbol::Symbol;
10 use rustc_target::spec::{MergeFunctions, PanicStrategy};
11 use std::ffi::{CStr, CString};
12
13 use std::slice;
14 use std::str;
15 use std::sync::atomic::{AtomicBool, Ordering};
16 use std::sync::Once;
17
18 static POISONED: AtomicBool = AtomicBool::new(false);
19 static INIT: Once = Once::new();
20
21 pub(crate) fn init(sess: &Session) {
22     unsafe {
23         // Before we touch LLVM, make sure that multithreading is enabled.
24         INIT.call_once(|| {
25             if llvm::LLVMStartMultithreaded() != 1 {
26                 // use an extra bool to make sure that all future usage of LLVM
27                 // cannot proceed despite the Once not running more than once.
28                 POISONED.store(true, Ordering::SeqCst);
29             }
30
31             configure_llvm(sess);
32         });
33
34         if POISONED.load(Ordering::SeqCst) {
35             bug!("couldn't enable multi-threaded LLVM");
36         }
37     }
38 }
39
40 fn require_inited() {
41     INIT.call_once(|| bug!("llvm is not initialized"));
42     if POISONED.load(Ordering::SeqCst) {
43         bug!("couldn't enable multi-threaded LLVM");
44     }
45 }
46
47 unsafe fn configure_llvm(sess: &Session) {
48     let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
49     let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
50     let mut llvm_args = Vec::with_capacity(n_args + 1);
51
52     llvm::LLVMRustInstallFatalErrorHandler();
53
54     fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
55         full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
56     }
57
58     let cg_opts = sess.opts.cg.llvm_args.iter();
59     let tg_opts = sess.target.llvm_args.iter();
60     let sess_args = cg_opts.chain(tg_opts);
61
62     let user_specified_args: FxHashSet<_> =
63         sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
64
65     {
66         // This adds the given argument to LLVM. Unless `force` is true
67         // user specified arguments are *not* overridden.
68         let mut add = |arg: &str, force: bool| {
69             if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
70                 let s = CString::new(arg).unwrap();
71                 llvm_args.push(s.as_ptr());
72                 llvm_c_strs.push(s);
73             }
74         };
75         // Set the llvm "program name" to make usage and invalid argument messages more clear.
76         add("rustc -Cllvm-args=\"...\" with", true);
77         if sess.time_llvm_passes() {
78             add("-time-passes", false);
79         }
80         if sess.print_llvm_passes() {
81             add("-debug-pass=Structure", false);
82         }
83         if !sess.opts.debugging_opts.no_generate_arange_section {
84             add("-generate-arange-section", false);
85         }
86         match sess.opts.debugging_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
87             MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
88             MergeFunctions::Aliases => {
89                 add("-mergefunc-use-aliases", false);
90             }
91         }
92
93         if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
94             add("-enable-emscripten-cxx-exceptions", false);
95         }
96
97         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
98         // during inlining. Unfortunately these may block other optimizations.
99         add("-preserve-alignment-assumptions-during-inlining=false", false);
100
101         // Use non-zero `import-instr-limit` multiplier for cold callsites.
102         add("-import-cold-multiplier=0.1", false);
103
104         for arg in sess_args {
105             add(&(*arg), true);
106         }
107     }
108
109     if sess.opts.debugging_opts.llvm_time_trace {
110         // time-trace is not thread safe and running it in parallel will cause seg faults.
111         if !sess.opts.debugging_opts.no_parallel_llvm {
112             bug!("`-Z llvm-time-trace` requires `-Z no-parallel-llvm")
113         }
114
115         llvm::LLVMTimeTraceProfilerInitialize();
116     }
117
118     llvm::LLVMInitializePasses();
119
120     rustc_llvm::initialize_available_targets();
121
122     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
123 }
124
125 pub fn time_trace_profiler_finish(file_name: &str) {
126     unsafe {
127         let file_name = CString::new(file_name).unwrap();
128         llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
129     }
130 }
131
132 // WARNING: the features after applying `to_llvm_feature` must be known
133 // to LLVM or the feature detection code will walk past the end of the feature
134 // array, leading to crashes.
135 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
136 // where the * matches the architecture's name
137 // Beware to not use the llvm github project for this, but check the git submodule
138 // found in src/llvm-project
139 // Though note that Rust can also be build with an external precompiled version of LLVM
140 // which might lead to failures if the oldest tested / supported LLVM version
141 // doesn't yet support the relevant intrinsics
142 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
143     let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
144     match (arch, s) {
145         ("x86", "pclmulqdq") => "pclmul",
146         ("x86", "rdrand") => "rdrnd",
147         ("x86", "bmi1") => "bmi",
148         ("x86", "cmpxchg16b") => "cx16",
149         ("x86", "avx512vaes") => "vaes",
150         ("x86", "avx512gfni") => "gfni",
151         ("x86", "avx512vpclmulqdq") => "vpclmulqdq",
152         ("aarch64", "fp") => "fp-armv8",
153         ("aarch64", "fp16") => "fullfp16",
154         (_, s) => s,
155     }
156 }
157
158 pub fn target_features(sess: &Session) -> Vec<Symbol> {
159     let target_machine = create_informational_target_machine(sess);
160     supported_target_features(sess)
161         .iter()
162         .filter_map(
163             |&(feature, gate)| {
164                 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
165             },
166         )
167         .filter(|feature| {
168             let llvm_feature = to_llvm_feature(sess, feature);
169             let cstr = CString::new(llvm_feature).unwrap();
170             unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
171         })
172         .map(|feature| Symbol::intern(feature))
173         .collect()
174 }
175
176 pub fn print_version() {
177     let (major, minor, patch) = get_version();
178     println!("LLVM version: {}.{}.{}", major, minor, patch);
179 }
180
181 pub fn get_version() -> (u32, u32, u32) {
182     // Can be called without initializing LLVM
183     unsafe {
184         (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
185     }
186 }
187
188 pub fn print_passes() {
189     // Can be called without initializing LLVM
190     unsafe {
191         llvm::LLVMRustPrintPasses();
192     }
193 }
194
195 pub(crate) fn print(req: PrintRequest, sess: &Session) {
196     require_inited();
197     let tm = create_informational_target_machine(sess);
198     unsafe {
199         match req {
200             PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
201             PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
202             _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
203         }
204     }
205 }
206
207 fn handle_native(name: &str) -> &str {
208     if name != "native" {
209         return name;
210     }
211
212     unsafe {
213         let mut len = 0;
214         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
215         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
216     }
217 }
218
219 pub fn target_cpu(sess: &Session) -> &str {
220     let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
221     handle_native(name)
222 }
223
224 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
225 /// `--target` and similar).
226 // FIXME(nagisa): Cache the output of this somehow? Maybe make this a query? We're calling this
227 // for every function that has `#[target_feature]` on it. The global features won't change between
228 // the functions; only crates, maybe…
229 pub fn llvm_global_features(sess: &Session) -> Vec<String> {
230     // FIXME(nagisa): this should definitely be available more centrally and to other codegen backends.
231     /// These features control behaviour of rustc rather than llvm.
232     const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
233
234     // Features that come earlier are overriden by conflicting features later in the string.
235     // Typically we'll want more explicit settings to override the implicit ones, so:
236     //
237     // * Features from -Ctarget-cpu=*; are overriden by [^1]
238     // * Features implied by --target; are overriden by
239     // * Features from -Ctarget-feature; are overriden by
240     // * function specific features.
241     //
242     // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
243     // through LLVM TargetMachine implementation.
244     //
245     // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
246     // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
247     // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
248     // the host target are overriden by `-Ctarget-cpu=*`. On the other hand, what about when both
249     // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
250     // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
251     // should be taken in cases like these.
252     let mut features = vec![];
253
254     // -Ctarget-cpu=native
255     match sess.opts.cg.target_cpu {
256         Some(ref s) if s == "native" => {
257             let features_string = unsafe {
258                 let ptr = llvm::LLVMGetHostCPUFeatures();
259                 let features_string = if !ptr.is_null() {
260                     CStr::from_ptr(ptr)
261                         .to_str()
262                         .unwrap_or_else(|e| {
263                             bug!("LLVM returned a non-utf8 features string: {}", e);
264                         })
265                         .to_owned()
266                 } else {
267                     bug!("could not allocate host CPU features, LLVM returned a `null` string");
268                 };
269
270                 llvm::LLVMDisposeMessage(ptr);
271
272                 features_string
273             };
274             features.extend(features_string.split(",").map(String::from));
275         }
276         Some(_) | None => {}
277     };
278
279     // Features implied by an implicit or explicit `--target`.
280     features.extend(
281         sess.target
282             .features
283             .split(',')
284             .filter(|f| !f.is_empty() && !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)))
285             .map(String::from),
286     );
287
288     // -Ctarget-features
289     features.extend(
290         sess.opts
291             .cg
292             .target_feature
293             .split(',')
294             .filter(|f| !f.is_empty() && !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)))
295             .map(String::from),
296     );
297
298     features
299 }
300
301 pub fn tune_cpu(sess: &Session) -> Option<&str> {
302     let name = sess.opts.debugging_opts.tune_cpu.as_ref()?;
303     Some(handle_native(name))
304 }