]> git.lizzy.rs Git - rust.git/blob - src/librustc_llvm/build.rs
7d01ed556c8ddbee7d76dbdc369c7cb937ab5480
[rust.git] / src / librustc_llvm / build.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 extern crate cc;
12 extern crate build_helper;
13
14 use std::process::Command;
15 use std::env;
16 use std::path::{PathBuf, Path};
17
18 use build_helper::output;
19
20 fn detect_llvm_link() -> (&'static str, &'static str) {
21     // Force the link mode we want, preferring static by default, but
22     // possibly overridden by `configure --enable-llvm-link-shared`.
23     if env::var_os("LLVM_LINK_SHARED").is_some() {
24         ("dylib", "--link-shared")
25     } else {
26         ("static", "--link-static")
27     }
28 }
29
30 fn main() {
31     if env::var_os("RUST_CHECK").is_some() {
32         // If we're just running `check`, there's no need for LLVM to be built.
33         println!("cargo:rerun-if-env-changed=RUST_CHECK");
34         return;
35     }
36
37     let target = env::var("TARGET").expect("TARGET was not set");
38     let llvm_config = env::var_os("LLVM_CONFIG")
39         .map(PathBuf::from)
40         .unwrap_or_else(|| {
41             if let Some(dir) = env::var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
42                 let to_test = dir.parent()
43                     .unwrap()
44                     .parent()
45                     .unwrap()
46                     .join(&target)
47                     .join("llvm/bin/llvm-config");
48                 if Command::new(&to_test).output().is_ok() {
49                     return to_test;
50                 }
51             }
52             PathBuf::from("llvm-config")
53         });
54
55     println!("cargo:rerun-if-changed={}", llvm_config.display());
56     println!("cargo:rerun-if-env-changed=LLVM_CONFIG");
57
58     // Test whether we're cross-compiling LLVM. This is a pretty rare case
59     // currently where we're producing an LLVM for a different platform than
60     // what this build script is currently running on.
61     //
62     // In that case, there's no guarantee that we can actually run the target,
63     // so the build system works around this by giving us the LLVM_CONFIG for
64     // the host platform. This only really works if the host LLVM and target
65     // LLVM are compiled the same way, but for us that's typically the case.
66     //
67     // We *want* detect this cross compiling situation by asking llvm-config
68     // what it's host-target is. If that's not the TARGET, then we're cross
69     // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
70     // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
71     // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
72     // tricks us into thinking we're doing a cross build when we aren't, so
73     // havoc ensues.
74     //
75     // In any case, if we're cross compiling, this generally just means that we
76     // can't trust all the output of llvm-config becaues it might be targeted
77     // for the host rather than the target. As a result a bunch of blocks below
78     // are gated on `if !is_crossed`
79     let target = env::var("TARGET").expect("TARGET was not set");
80     let host = env::var("HOST").expect("HOST was not set");
81     let is_crossed = target != host;
82
83     let mut optional_components =
84         vec!["x86", "arm", "aarch64", "amdgpu", "mips", "powerpc",
85              "systemz", "jsbackend", "webassembly", "msp430", "sparc", "nvptx"];
86
87     let mut version_cmd = Command::new(&llvm_config);
88     version_cmd.arg("--version");
89     let version_output = output(&mut version_cmd);
90     let mut parts = version_output.split('.').take(2)
91         .filter_map(|s| s.parse::<u32>().ok());
92     let (major, _minor) =
93         if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
94             (major, minor)
95         } else {
96             (3, 9)
97         };
98
99     if major > 3 {
100         optional_components.push("hexagon");
101     }
102
103     if major > 6 {
104         optional_components.push("riscv");
105     }
106
107     // FIXME: surely we don't need all these components, right? Stuff like mcjit
108     //        or interpreter the compiler itself never uses.
109     let required_components = &["ipo",
110                                 "bitreader",
111                                 "bitwriter",
112                                 "linker",
113                                 "asmparser",
114                                 "mcjit",
115                                 "lto",
116                                 "interpreter",
117                                 "instrumentation"];
118
119     let components = output(Command::new(&llvm_config).arg("--components"));
120     let mut components = components.split_whitespace().collect::<Vec<_>>();
121     components.retain(|c| optional_components.contains(c) || required_components.contains(c));
122
123     for component in required_components {
124         if !components.contains(component) {
125             panic!("require llvm component {} but wasn't found", component);
126         }
127     }
128
129     for component in components.iter() {
130         println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
131     }
132
133     // Link in our own LLVM shims, compiled with the same flags as LLVM
134     let mut cmd = Command::new(&llvm_config);
135     cmd.arg("--cxxflags");
136     let cxxflags = output(&mut cmd);
137     let mut cfg = cc::Build::new();
138     cfg.warnings(false);
139     for flag in cxxflags.split_whitespace() {
140         // Ignore flags like `-m64` when we're doing a cross build
141         if is_crossed && flag.starts_with("-m") {
142             continue;
143         }
144
145         // -Wdate-time is not supported by the netbsd cross compiler
146         if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
147             continue;
148         }
149
150         cfg.flag(flag);
151     }
152
153     for component in &components {
154         let mut flag = String::from("LLVM_COMPONENT_");
155         flag.push_str(&component.to_uppercase());
156         cfg.define(&flag, None);
157     }
158
159     println!("cargo:rerun-if-changed-env=LLVM_RUSTLLVM");
160     if env::var_os("LLVM_RUSTLLVM").is_some() {
161         cfg.define("LLVM_RUSTLLVM", None);
162     }
163
164     build_helper::rerun_if_changed_anything_in_dir(Path::new("../rustllvm"));
165     cfg.file("../rustllvm/PassWrapper.cpp")
166        .file("../rustllvm/RustWrapper.cpp")
167        .file("../rustllvm/ArchiveWrapper.cpp")
168        .file("../rustllvm/Linker.cpp")
169        .cpp(true)
170        .cpp_link_stdlib(None) // we handle this below
171        .compile("rustllvm");
172
173     let (llvm_kind, llvm_link_arg) = detect_llvm_link();
174
175     // Link in all LLVM libraries, if we're uwring the "wrong" llvm-config then
176     // we don't pick up system libs because unfortunately they're for the host
177     // of llvm-config, not the target that we're attempting to link.
178     let mut cmd = Command::new(&llvm_config);
179     cmd.arg(llvm_link_arg).arg("--libs");
180
181     if !is_crossed {
182         cmd.arg("--system-libs");
183     }
184     cmd.args(&components);
185
186     for lib in output(&mut cmd).split_whitespace() {
187         let name = if lib.starts_with("-l") {
188             &lib[2..]
189         } else if lib.starts_with("-") {
190             &lib[1..]
191         } else if Path::new(lib).exists() {
192             // On MSVC llvm-config will print the full name to libraries, but
193             // we're only interested in the name part
194             let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
195             name.trim_right_matches(".lib")
196         } else if lib.ends_with(".lib") {
197             // Some MSVC libraries just come up with `.lib` tacked on, so chop
198             // that off
199             lib.trim_right_matches(".lib")
200         } else {
201             continue;
202         };
203
204         // Don't need or want this library, but LLVM's CMake build system
205         // doesn't provide a way to disable it, so filter it here even though we
206         // may or may not have built it. We don't reference anything from this
207         // library and it otherwise may just pull in extra dependencies on
208         // libedit which we don't want
209         if name == "LLVMLineEditor" {
210             continue;
211         }
212
213         let kind = if name.starts_with("LLVM") {
214             llvm_kind
215         } else {
216             "dylib"
217         };
218         println!("cargo:rustc-link-lib={}={}", kind, name);
219     }
220
221     // LLVM ldflags
222     //
223     // If we're a cross-compile of LLVM then unfortunately we can't trust these
224     // ldflags (largely where all the LLVM libs are located). Currently just
225     // hack around this by replacing the host triple with the target and pray
226     // that those -L directories are the same!
227     let mut cmd = Command::new(&llvm_config);
228     cmd.arg(llvm_link_arg).arg("--ldflags");
229     for lib in output(&mut cmd).split_whitespace() {
230         if lib.starts_with("-LIBPATH:") {
231             println!("cargo:rustc-link-search=native={}", &lib[9..]);
232         } else if is_crossed {
233             if lib.starts_with("-L") {
234                 println!("cargo:rustc-link-search=native={}",
235                          lib[2..].replace(&host, &target));
236             }
237         } else if lib.starts_with("-l") {
238             println!("cargo:rustc-link-lib={}", &lib[2..]);
239         } else if lib.starts_with("-L") {
240             println!("cargo:rustc-link-search=native={}", &lib[2..]);
241         }
242     }
243
244     let llvm_static_stdcpp = env::var_os("LLVM_STATIC_STDCPP");
245
246     let stdcppname = if target.contains("openbsd") {
247         // llvm-config on OpenBSD doesn't mention stdlib=libc++
248         "c++"
249     } else if target.contains("freebsd") {
250         "c++"
251     } else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
252         // NetBSD uses a separate library when relocation is required
253         "stdc++_pic"
254     } else {
255         "stdc++"
256     };
257
258     // C++ runtime library
259     if !target.contains("msvc") {
260         if let Some(s) = llvm_static_stdcpp {
261             assert!(!cxxflags.contains("stdlib=libc++"));
262             let path = PathBuf::from(s);
263             println!("cargo:rustc-link-search=native={}",
264                      path.parent().unwrap().display());
265             println!("cargo:rustc-link-lib=static={}", stdcppname);
266         } else if cxxflags.contains("stdlib=libc++") {
267             println!("cargo:rustc-link-lib=c++");
268         } else {
269             println!("cargo:rustc-link-lib={}", stdcppname);
270         }
271     }
272
273     // LLVM requires symbols from this library, but apparently they're not printed
274     // during llvm-config?
275     if target.contains("windows-gnu") {
276         println!("cargo:rustc-link-lib=static-nobundle=gcc_s");
277         println!("cargo:rustc-link-lib=static-nobundle=pthread");
278         println!("cargo:rustc-link-lib=dylib=uuid");
279     }
280 }