1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! halide-build is used to compile [Halide](https://github.com/halide/halide) kernels

use std::env;
use std::fs::remove_file;
use std::io;
use std::path::PathBuf;
use std::process::Command;

static CARGO_LINK_SEARCH: &'static str = "cargo:rustc-link-search=native=";
static CARGO_LINK_LIB: &'static str = "cargo:rustc-link-lib=";

/// Link a library, specified by path and name
pub fn link_lib(path: Option<&str>, name: &str) {
    if let Some(path) = path {
        println!("{}{}", CARGO_LINK_SEARCH, path);
    }

    println!("{}{}", CARGO_LINK_LIB, name);
}

/// Link a library, specified by filename
pub fn link<P: AsRef<std::path::Path>>(filename: P) {
    let mut filename = filename.as_ref().to_path_buf();
    let name = filename.file_stem().expect("Invalid filename");
    let s = String::from(name.to_str().expect("Invalid filename"));
    let mut tmp: &str = &s;

    if s.starts_with("lib") {
        tmp = &s[3..]
    }

    if s.ends_with(".a") {
        tmp = &tmp[..tmp.len() - 2];
    } else if s.ends_with(".so") {
        tmp = &tmp[..tmp.len() - 3];
    } else if s.ends_with(".dylib") {
        tmp = &tmp[..tmp.len() - 6];
    }

    filename.pop();
    link_lib(filename.to_str(), tmp);
}

/// Compile a shared library using the C++ compiler
pub fn compile_shared_library(
    compiler: Option<&str>,
    output: &str,
    args: &[&str],
) -> Result<bool, std::io::Error> {
    let cxx = std::env::var("CXX").unwrap_or("c++".to_owned());
    let mut cmd = Command::new(compiler.unwrap_or(&cxx));

    cmd.arg("-std=c++11");
    let res = cmd
        .arg("-shared")
        .arg("-o")
        .arg(output)
        .args(args)
        .status()?;
    Ok(res.success())
}

/// Build stores the required context for building a Halide kernel
#[derive(Debug)]
pub struct Build<'a> {
    /// Path to halide source
    pub halide_path: PathBuf,

    /// Input files
    pub src: Vec<PathBuf>,

    /// Output file
    pub output: PathBuf,

    /// C++ compiler
    pub cxx: Option<&'a str>,

    /// C++ compile time flags
    pub cxxflags: Option<&'a str>,

    /// C++ link time flags
    pub ldflags: Option<&'a str>,

    /// Extra arguments to build step
    pub build_args: Vec<&'a str>,

    /// Extra arguments to run step
    pub run_args: Vec<&'a str>,

    /// Keep executable when finished running
    pub keep: bool,

    /// Include Halide generator header
    pub generator: bool,
}

impl<'a> Build<'a> {
    /// Create a new build with the given halide path and output
    pub fn new<P: AsRef<std::path::Path>, Q: AsRef<std::path::Path>>(
        halide_path: P,
        output: Q,
    ) -> Build<'a> {
        Build {
            halide_path: halide_path.as_ref().to_path_buf(),
            src: vec![],
            output: output.as_ref().to_path_buf(),
            cxx: None,
            cxxflags: None,
            ldflags: None,
            build_args: vec![],
            run_args: vec![],
            keep: false,
            generator: false,
        }
    }

    pub fn source_file(mut self, src: impl AsRef<std::path::Path>) -> Self {
        self.src.push(src.as_ref().to_owned());
        self
    }

    pub fn build_arg(mut self, src: &'a str) -> Self {
        self.build_args.push(src.as_ref());
        self
    }

    pub fn build_args(mut self, src: impl AsRef<[&'a str]>) -> Self {
        self.build_args.extend(src.as_ref());
        self
    }

    pub fn run_arg(mut self, src: &'a str) -> Self {
        self.run_args.push(src.as_ref());
        self
    }

    pub fn run_args(mut self, src: impl AsRef<[&'a str]>) -> Self {
        self.run_args.extend(src.as_ref());
        self
    }

    pub fn ldflags(mut self, flags: &'a str) -> Self {
        self.ldflags = Some(flags);
        self
    }

    pub fn cxxflags(mut self, flags: &'a str) -> Self {
        self.cxxflags = Some(flags);
        self
    }

    pub fn compiler(mut self, name: &'a str) -> Self {
        self.cxx = Some(name);
        self
    }

    pub fn keep(mut self, x: bool) -> Self {
        self.keep = x;
        self
    }

    pub fn generator(mut self, x: bool) -> Self {
        self.generator = x;
        self
    }

    /// Execute the build step
    pub fn build(&self) -> io::Result<bool> {
        let cxx_default = env::var("CXX").unwrap_or("c++".to_string());
        let mut cmd = Command::new(self.cxx.clone().unwrap_or(cxx_default.as_str()));

        cmd.arg("-std=c++11");
        cmd.args(&["-I", &self.halide_path.join("include").to_string_lossy()])
            .args(&["-I", &self.halide_path.join("tools").to_string_lossy()]);

        if let Some(flags) = &self.cxxflags {
            cmd.args(flags.split(" "));
        }

        if self.generator {
            cmd.arg(
                &self
                    .halide_path
                    .join("tools")
                    .join("GenGen.cpp")
                    .to_string_lossy()
                    .as_ref(),
            );
        }

        cmd.args(&self.build_args);

        let tinfo = std::env::var("TERMINFO").unwrap_or_else(|_| "-lncurses".to_string());

        cmd.args(&self.src)
            .args(&["-o", &self.output.to_string_lossy()])
            .args(&[
                "-L",
                &self.halide_path.join("lib").to_string_lossy(),
                "-lHalide",
                "-lpng",
                "-ljpeg",
                "-lpthread",
                &tinfo,
                "-ldl",
                "-lz",
            ]);

        if let Some(flags) = &self.ldflags {
            cmd.args(flags.split(" "));
        }

        cmd.status().map(|status| status.success())
    }

    /// Execute the run step
    pub fn run(&self) -> io::Result<bool> {
        if !self.output.exists() {
            return Ok(false);
        }

        let res = Command::new(&self.output)
            .args(&self.run_args)
            .env("LD_LIBRARY_PATH", self.halide_path.join("lib"))
            .status()
            .map(|status| status.success());

        if !self.keep {
            let _ = remove_file(&self.output);
        }

        res
    }
}

/// Source is used to maintain the Halide source directory
pub struct Source {
    pub halide_path: PathBuf,
    pub repo: String,
    pub branch: String,
    pub make: String,
    pub make_flags: Vec<String>,
}

impl Source {
    /// Download Halide source for the first time
    pub fn download(&self) -> io::Result<bool> {
        Command::new("git")
            .arg("clone")
            .args(&["-b", self.branch.as_str()])
            .arg(&self.repo)
            .arg(&self.halide_path)
            .status()
            .map(|status| status.success())
    }

    /// Update Halide source
    pub fn update(&self) -> io::Result<bool> {
        Command::new("git")
            .current_dir(&self.halide_path)
            .arg("pull")
            .arg("origin")
            .arg(&self.branch)
            .status()
            .map(|status| status.success())
    }

    /// Build Halide source
    pub fn build(&self) -> io::Result<bool> {
        Command::new(&self.make)
            .current_dir(&self.halide_path)
            .args(&self.make_flags)
            .status()
            .map(|status| status.success())
    }
}