]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/llvm_util.rs
Auto merge of #65469 - mati865:libc, r=alexcrichton
[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;
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         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
77         // during inlining. Unfortunately these may block other optimizations.
78         add("-preserve-alignment-assumptions-during-inlining=false");
79
80         for arg in &sess.opts.cg.llvm_args {
81             add(&(*arg));
82         }
83     }
84
85     llvm::LLVMInitializePasses();
86
87     ::rustc_llvm::initialize_available_targets();
88
89     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
90                                  llvm_args.as_ptr());
91 }
92
93 // WARNING: the features after applying `to_llvm_feature` must be known
94 // to LLVM or the feature detection code will walk past the end of the feature
95 // array, leading to crashes.
96
97 const ARM_WHITELIST: &[(&str, Option<Symbol>)] = &[
98     ("aclass", Some(sym::arm_target_feature)),
99     ("mclass", Some(sym::arm_target_feature)),
100     ("rclass", Some(sym::arm_target_feature)),
101     ("dsp", Some(sym::arm_target_feature)),
102     ("neon", Some(sym::arm_target_feature)),
103     ("v5te", Some(sym::arm_target_feature)),
104     ("v6", Some(sym::arm_target_feature)),
105     ("v6k", Some(sym::arm_target_feature)),
106     ("v6t2", Some(sym::arm_target_feature)),
107     ("v7", Some(sym::arm_target_feature)),
108     ("v8", Some(sym::arm_target_feature)),
109     ("vfp2", Some(sym::arm_target_feature)),
110     ("vfp3", Some(sym::arm_target_feature)),
111     ("vfp4", Some(sym::arm_target_feature)),
112 ];
113
114 const AARCH64_WHITELIST: &[(&str, Option<Symbol>)] = &[
115     ("fp", Some(sym::aarch64_target_feature)),
116     ("neon", Some(sym::aarch64_target_feature)),
117     ("sve", Some(sym::aarch64_target_feature)),
118     ("crc", Some(sym::aarch64_target_feature)),
119     ("crypto", Some(sym::aarch64_target_feature)),
120     ("ras", Some(sym::aarch64_target_feature)),
121     ("lse", Some(sym::aarch64_target_feature)),
122     ("rdm", Some(sym::aarch64_target_feature)),
123     ("fp16", Some(sym::aarch64_target_feature)),
124     ("rcpc", Some(sym::aarch64_target_feature)),
125     ("dotprod", Some(sym::aarch64_target_feature)),
126     ("v8.1a", Some(sym::aarch64_target_feature)),
127     ("v8.2a", Some(sym::aarch64_target_feature)),
128     ("v8.3a", Some(sym::aarch64_target_feature)),
129 ];
130
131 const X86_WHITELIST: &[(&str, Option<Symbol>)] = &[
132     ("adx", Some(sym::adx_target_feature)),
133     ("aes", None),
134     ("avx", None),
135     ("avx2", None),
136     ("avx512bw", Some(sym::avx512_target_feature)),
137     ("avx512cd", Some(sym::avx512_target_feature)),
138     ("avx512dq", Some(sym::avx512_target_feature)),
139     ("avx512er", Some(sym::avx512_target_feature)),
140     ("avx512f", Some(sym::avx512_target_feature)),
141     ("avx512ifma", Some(sym::avx512_target_feature)),
142     ("avx512pf", Some(sym::avx512_target_feature)),
143     ("avx512vbmi", Some(sym::avx512_target_feature)),
144     ("avx512vl", Some(sym::avx512_target_feature)),
145     ("avx512vpopcntdq", Some(sym::avx512_target_feature)),
146     ("bmi1", None),
147     ("bmi2", None),
148     ("cmpxchg16b", Some(sym::cmpxchg16b_target_feature)),
149     ("f16c", Some(sym::f16c_target_feature)),
150     ("fma", None),
151     ("fxsr", None),
152     ("lzcnt", None),
153     ("mmx", Some(sym::mmx_target_feature)),
154     ("movbe", Some(sym::movbe_target_feature)),
155     ("pclmulqdq", None),
156     ("popcnt", None),
157     ("rdrand", None),
158     ("rdseed", None),
159     ("rtm", Some(sym::rtm_target_feature)),
160     ("sha", None),
161     ("sse", None),
162     ("sse2", None),
163     ("sse3", None),
164     ("sse4.1", None),
165     ("sse4.2", None),
166     ("sse4a", Some(sym::sse4a_target_feature)),
167     ("ssse3", None),
168     ("tbm", Some(sym::tbm_target_feature)),
169     ("xsave", None),
170     ("xsavec", None),
171     ("xsaveopt", None),
172     ("xsaves", None),
173 ];
174
175 const HEXAGON_WHITELIST: &[(&str, Option<Symbol>)] = &[
176     ("hvx", Some(sym::hexagon_target_feature)),
177     ("hvx-length128b", Some(sym::hexagon_target_feature)),
178 ];
179
180 const POWERPC_WHITELIST: &[(&str, Option<Symbol>)] = &[
181     ("altivec", Some(sym::powerpc_target_feature)),
182     ("power8-altivec", Some(sym::powerpc_target_feature)),
183     ("power9-altivec", Some(sym::powerpc_target_feature)),
184     ("power8-vector", Some(sym::powerpc_target_feature)),
185     ("power9-vector", Some(sym::powerpc_target_feature)),
186     ("vsx", Some(sym::powerpc_target_feature)),
187 ];
188
189 const MIPS_WHITELIST: &[(&str, Option<Symbol>)] = &[
190     ("fp64", Some(sym::mips_target_feature)),
191     ("msa", Some(sym::mips_target_feature)),
192 ];
193
194 const WASM_WHITELIST: &[(&str, Option<Symbol>)] = &[
195     ("simd128", Some(sym::wasm_target_feature)),
196     ("atomics", Some(sym::wasm_target_feature)),
197 ];
198
199 /// When rustdoc is running, provide a list of all known features so that all their respective
200 /// primitives may be documented.
201 ///
202 /// IMPORTANT: If you're adding another whitelist to the above lists, make sure to add it to this
203 /// iterator!
204 pub fn all_known_features() -> impl Iterator<Item=(&'static str, Option<Symbol>)> {
205     ARM_WHITELIST.iter().cloned()
206         .chain(AARCH64_WHITELIST.iter().cloned())
207         .chain(X86_WHITELIST.iter().cloned())
208         .chain(HEXAGON_WHITELIST.iter().cloned())
209         .chain(POWERPC_WHITELIST.iter().cloned())
210         .chain(MIPS_WHITELIST.iter().cloned())
211         .chain(WASM_WHITELIST.iter().cloned())
212 }
213
214 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
215     let arch = if sess.target.target.arch == "x86_64" {
216         "x86"
217     } else {
218         &*sess.target.target.arch
219     };
220     match (arch, s) {
221         ("x86", "pclmulqdq") => "pclmul",
222         ("x86", "rdrand") => "rdrnd",
223         ("x86", "bmi1") => "bmi",
224         ("x86", "cmpxchg16b") => "cx16",
225         ("aarch64", "fp") => "fp-armv8",
226         ("aarch64", "fp16") => "fullfp16",
227         (_, s) => s,
228     }
229 }
230
231 pub fn target_features(sess: &Session) -> Vec<Symbol> {
232     let target_machine = create_informational_target_machine(sess, true);
233     target_feature_whitelist(sess)
234         .iter()
235         .filter_map(|&(feature, gate)| {
236             if UnstableFeatures::from_environment().is_nightly_build() || gate.is_none() {
237                 Some(feature)
238             } else {
239                 None
240             }
241         })
242         .filter(|feature| {
243             let llvm_feature = to_llvm_feature(sess, feature);
244             let cstr = CString::new(llvm_feature).unwrap();
245             unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
246         })
247         .map(|feature| Symbol::intern(feature)).collect()
248 }
249
250 pub fn target_feature_whitelist(sess: &Session)
251     -> &'static [(&'static str, Option<Symbol>)]
252 {
253     match &*sess.target.target.arch {
254         "arm" => ARM_WHITELIST,
255         "aarch64" => AARCH64_WHITELIST,
256         "x86" | "x86_64" => X86_WHITELIST,
257         "hexagon" => HEXAGON_WHITELIST,
258         "mips" | "mips64" => MIPS_WHITELIST,
259         "powerpc" | "powerpc64" => POWERPC_WHITELIST,
260         "wasm32" => WASM_WHITELIST,
261         _ => &[],
262     }
263 }
264
265 pub fn print_version() {
266     // Can be called without initializing LLVM
267     unsafe {
268         println!("LLVM version: {}.{}",
269                  llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
270     }
271 }
272
273 pub fn get_major_version() -> u32 {
274     unsafe { llvm::LLVMRustVersionMajor() }
275 }
276
277 pub fn print_passes() {
278     // Can be called without initializing LLVM
279     unsafe { llvm::LLVMRustPrintPasses(); }
280 }
281
282 pub(crate) fn print(req: PrintRequest, sess: &Session) {
283     require_inited();
284     let tm = create_informational_target_machine(sess, true);
285     unsafe {
286         match req {
287             PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
288             PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
289             _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
290         }
291     }
292 }
293
294 pub fn target_cpu(sess: &Session) -> &str {
295     let name = match sess.opts.cg.target_cpu {
296         Some(ref s) => &**s,
297         None => &*sess.target.target.options.cpu
298     };
299     if name != "native" {
300         return name
301     }
302
303     unsafe {
304         let mut len = 0;
305         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
306         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
307     }
308 }