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