]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/llvm_util.rs
Formatting
[rust.git] / src / librustc_codegen_llvm / llvm_util.rs
1 use crate::back::write::create_informational_target_machine;
2 use crate::llvm;
3 use syntax_pos::symbol::Symbol;
4 use rustc::session::Session;
5 use rustc::session::config::PrintRequest;
6 use rustc_target::spec::{MergeFunctions, PanicStrategy};
7 use libc::c_int;
8 use std::ffi::CString;
9 use syntax::feature_gate::UnstableFeatures;
10 use syntax::symbol::sym;
11
12 use std::str;
13 use std::slice;
14 use std::sync::atomic::{AtomicBool, Ordering};
15 use std::sync::Once;
16
17 static POISONED: AtomicBool = AtomicBool::new(false);
18 static INIT: Once = Once::new();
19
20 pub(crate) fn init(sess: &Session) {
21     unsafe {
22         // Before we touch LLVM, make sure that multithreading is enabled.
23         INIT.call_once(|| {
24             if llvm::LLVMStartMultithreaded() != 1 {
25                 // use an extra bool to make sure that all future usage of LLVM
26                 // cannot proceed despite the Once not running more than once.
27                 POISONED.store(true, Ordering::SeqCst);
28             }
29
30             configure_llvm(sess);
31         });
32
33         if POISONED.load(Ordering::SeqCst) {
34             bug!("couldn't enable multi-threaded LLVM");
35         }
36     }
37 }
38
39 fn require_inited() {
40     INIT.call_once(|| bug!("llvm is not initialized"));
41     if POISONED.load(Ordering::SeqCst) {
42         bug!("couldn't enable multi-threaded LLVM");
43     }
44 }
45
46 unsafe fn configure_llvm(sess: &Session) {
47     let n_args = sess.opts.cg.llvm_args.len();
48     let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
49     let mut llvm_args = Vec::with_capacity(n_args + 1);
50
51     llvm::LLVMRustInstallFatalErrorHandler();
52
53     {
54         let mut add = |arg: &str| {
55             let s = CString::new(arg).unwrap();
56             llvm_args.push(s.as_ptr());
57             llvm_c_strs.push(s);
58         };
59         add("rustc"); // fake program name
60         if sess.time_llvm_passes() { add("-time-passes"); }
61         if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
62         if sess.opts.debugging_opts.disable_instrumentation_preinliner {
63             add("-disable-preinline");
64         }
65         if get_major_version() >= 8 {
66             match sess.opts.debugging_opts.merge_functions
67                   .unwrap_or(sess.target.target.options.merge_functions) {
68                 MergeFunctions::Disabled |
69                 MergeFunctions::Trampolines => {}
70                 MergeFunctions::Aliases => {
71                     add("-mergefunc-use-aliases");
72                 }
73             }
74         }
75
76         if sess.target.target.target_os == "emscripten" &&
77             sess.panic_strategy() == PanicStrategy::Unwind {
78             add("-enable-emscripten-cxx-exceptions");
79         }
80
81         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
82         // during inlining. Unfortunately these may block other optimizations.
83         add("-preserve-alignment-assumptions-during-inlining=false");
84
85         for arg in &sess.opts.cg.llvm_args {
86             add(&(*arg));
87         }
88     }
89
90     llvm::LLVMInitializePasses();
91
92     ::rustc_llvm::initialize_available_targets();
93
94     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
95                                  llvm_args.as_ptr());
96 }
97
98 // WARNING: the features after applying `to_llvm_feature` must be known
99 // to LLVM or the feature detection code will walk past the end of the feature
100 // array, leading to crashes.
101
102 const ARM_WHITELIST: &[(&str, Option<Symbol>)] = &[
103     ("aclass", Some(sym::arm_target_feature)),
104     ("mclass", Some(sym::arm_target_feature)),
105     ("rclass", Some(sym::arm_target_feature)),
106     ("dsp", Some(sym::arm_target_feature)),
107     ("neon", Some(sym::arm_target_feature)),
108     ("v5te", Some(sym::arm_target_feature)),
109     ("v6", Some(sym::arm_target_feature)),
110     ("v6k", Some(sym::arm_target_feature)),
111     ("v6t2", Some(sym::arm_target_feature)),
112     ("v7", Some(sym::arm_target_feature)),
113     ("v8", Some(sym::arm_target_feature)),
114     ("vfp2", Some(sym::arm_target_feature)),
115     ("vfp3", Some(sym::arm_target_feature)),
116     ("vfp4", Some(sym::arm_target_feature)),
117 ];
118
119 const AARCH64_WHITELIST: &[(&str, Option<Symbol>)] = &[
120     ("fp", Some(sym::aarch64_target_feature)),
121     ("neon", Some(sym::aarch64_target_feature)),
122     ("sve", Some(sym::aarch64_target_feature)),
123     ("crc", Some(sym::aarch64_target_feature)),
124     ("crypto", Some(sym::aarch64_target_feature)),
125     ("ras", Some(sym::aarch64_target_feature)),
126     ("lse", Some(sym::aarch64_target_feature)),
127     ("rdm", Some(sym::aarch64_target_feature)),
128     ("fp16", Some(sym::aarch64_target_feature)),
129     ("rcpc", Some(sym::aarch64_target_feature)),
130     ("dotprod", Some(sym::aarch64_target_feature)),
131     ("v8.1a", Some(sym::aarch64_target_feature)),
132     ("v8.2a", Some(sym::aarch64_target_feature)),
133     ("v8.3a", Some(sym::aarch64_target_feature)),
134 ];
135
136 const X86_WHITELIST: &[(&str, Option<Symbol>)] = &[
137     ("adx", Some(sym::adx_target_feature)),
138     ("aes", None),
139     ("avx", None),
140     ("avx2", None),
141     ("avx512bw", Some(sym::avx512_target_feature)),
142     ("avx512cd", Some(sym::avx512_target_feature)),
143     ("avx512dq", Some(sym::avx512_target_feature)),
144     ("avx512er", Some(sym::avx512_target_feature)),
145     ("avx512f", Some(sym::avx512_target_feature)),
146     ("avx512ifma", Some(sym::avx512_target_feature)),
147     ("avx512pf", Some(sym::avx512_target_feature)),
148     ("avx512vbmi", Some(sym::avx512_target_feature)),
149     ("avx512vl", Some(sym::avx512_target_feature)),
150     ("avx512vpopcntdq", Some(sym::avx512_target_feature)),
151     ("bmi1", None),
152     ("bmi2", None),
153     ("cmpxchg16b", Some(sym::cmpxchg16b_target_feature)),
154     ("f16c", Some(sym::f16c_target_feature)),
155     ("fma", None),
156     ("fxsr", None),
157     ("lzcnt", None),
158     ("mmx", Some(sym::mmx_target_feature)),
159     ("movbe", Some(sym::movbe_target_feature)),
160     ("pclmulqdq", None),
161     ("popcnt", None),
162     ("rdrand", None),
163     ("rdseed", None),
164     ("rtm", Some(sym::rtm_target_feature)),
165     ("sha", None),
166     ("sse", None),
167     ("sse2", None),
168     ("sse3", None),
169     ("sse4.1", None),
170     ("sse4.2", None),
171     ("sse4a", Some(sym::sse4a_target_feature)),
172     ("ssse3", None),
173     ("tbm", Some(sym::tbm_target_feature)),
174     ("xsave", None),
175     ("xsavec", None),
176     ("xsaveopt", None),
177     ("xsaves", None),
178 ];
179
180 const HEXAGON_WHITELIST: &[(&str, Option<Symbol>)] = &[
181     ("hvx", Some(sym::hexagon_target_feature)),
182     ("hvx-length128b", Some(sym::hexagon_target_feature)),
183 ];
184
185 const POWERPC_WHITELIST: &[(&str, Option<Symbol>)] = &[
186     ("altivec", Some(sym::powerpc_target_feature)),
187     ("power8-altivec", Some(sym::powerpc_target_feature)),
188     ("power9-altivec", Some(sym::powerpc_target_feature)),
189     ("power8-vector", Some(sym::powerpc_target_feature)),
190     ("power9-vector", Some(sym::powerpc_target_feature)),
191     ("vsx", Some(sym::powerpc_target_feature)),
192 ];
193
194 const MIPS_WHITELIST: &[(&str, Option<Symbol>)] = &[
195     ("fp64", Some(sym::mips_target_feature)),
196     ("msa", Some(sym::mips_target_feature)),
197 ];
198
199 const WASM_WHITELIST: &[(&str, Option<Symbol>)] = &[
200     ("simd128", Some(sym::wasm_target_feature)),
201     ("atomics", Some(sym::wasm_target_feature)),
202 ];
203
204 /// When rustdoc is running, provide a list of all known features so that all their respective
205 /// primitives may be documented.
206 ///
207 /// IMPORTANT: If you're adding another whitelist to the above lists, make sure to add it to this
208 /// iterator!
209 pub fn all_known_features() -> impl Iterator<Item=(&'static str, Option<Symbol>)> {
210     ARM_WHITELIST.iter().cloned()
211         .chain(AARCH64_WHITELIST.iter().cloned())
212         .chain(X86_WHITELIST.iter().cloned())
213         .chain(HEXAGON_WHITELIST.iter().cloned())
214         .chain(POWERPC_WHITELIST.iter().cloned())
215         .chain(MIPS_WHITELIST.iter().cloned())
216         .chain(WASM_WHITELIST.iter().cloned())
217 }
218
219 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
220     let arch = if sess.target.target.arch == "x86_64" {
221         "x86"
222     } else {
223         &*sess.target.target.arch
224     };
225     match (arch, s) {
226         ("x86", "pclmulqdq") => "pclmul",
227         ("x86", "rdrand") => "rdrnd",
228         ("x86", "bmi1") => "bmi",
229         ("x86", "cmpxchg16b") => "cx16",
230         ("aarch64", "fp") => "fp-armv8",
231         ("aarch64", "fp16") => "fullfp16",
232         (_, s) => s,
233     }
234 }
235
236 pub fn target_features(sess: &Session) -> Vec<Symbol> {
237     let target_machine = create_informational_target_machine(sess, true);
238     target_feature_whitelist(sess)
239         .iter()
240         .filter_map(|&(feature, gate)| {
241             if UnstableFeatures::from_environment().is_nightly_build() || gate.is_none() {
242                 Some(feature)
243             } else {
244                 None
245             }
246         })
247         .filter(|feature| {
248             let llvm_feature = to_llvm_feature(sess, feature);
249             let cstr = CString::new(llvm_feature).unwrap();
250             unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
251         })
252         .map(|feature| Symbol::intern(feature)).collect()
253 }
254
255 pub fn target_feature_whitelist(sess: &Session)
256     -> &'static [(&'static str, Option<Symbol>)]
257 {
258     match &*sess.target.target.arch {
259         "arm" => ARM_WHITELIST,
260         "aarch64" => AARCH64_WHITELIST,
261         "x86" | "x86_64" => X86_WHITELIST,
262         "hexagon" => HEXAGON_WHITELIST,
263         "mips" | "mips64" => MIPS_WHITELIST,
264         "powerpc" | "powerpc64" => POWERPC_WHITELIST,
265         "wasm32" => WASM_WHITELIST,
266         _ => &[],
267     }
268 }
269
270 pub fn print_version() {
271     // Can be called without initializing LLVM
272     unsafe {
273         println!("LLVM version: {}.{}",
274                  llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
275     }
276 }
277
278 pub fn get_major_version() -> u32 {
279     unsafe { llvm::LLVMRustVersionMajor() }
280 }
281
282 pub fn print_passes() {
283     // Can be called without initializing LLVM
284     unsafe { llvm::LLVMRustPrintPasses(); }
285 }
286
287 pub(crate) fn print(req: PrintRequest, sess: &Session) {
288     require_inited();
289     let tm = create_informational_target_machine(sess, true);
290     unsafe {
291         match req {
292             PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
293             PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
294             _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
295         }
296     }
297 }
298
299 pub fn target_cpu(sess: &Session) -> &str {
300     let name = match sess.opts.cg.target_cpu {
301         Some(ref s) => &**s,
302         None => &*sess.target.target.options.cpu
303     };
304     if name != "native" {
305         return name
306     }
307
308     unsafe {
309         let mut len = 0;
310         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
311         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
312     }
313 }