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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

/// Get the nvbit include dir.
///
/// **Note**: This function is intended to be used the build.rs context.
///
/// This can be useful when your crate uses nvbit and requires access to
/// the nvbit header files.
///
/// # Panics
/// When the `DEP_NVBIT_INCLUDE` environment variable is not set.
#[inline]
#[must_use]
pub fn nvbit_include() -> PathBuf {
    PathBuf::from(std::env::var("DEP_NVBIT_INCLUDE").expect("nvbit include path"))
        .canonicalize()
        .expect("canonicalize path")
}

/// Get the cargo output directory.
///
/// **Note**: This function is intended to be used the build.rs context.
///
/// # Panics
/// When the `OUT_DIR` environment variable is not set.
#[inline]
#[must_use]
pub fn output_path() -> PathBuf {
    PathBuf::from(std::env::var("OUT_DIR").expect("cargo out dir"))
        .canonicalize()
        .expect("canonicalize path")
}

/// Get the cargo manifest directory.
///
/// **Note**: This function is intended to be used the build.rs context.
///
/// # Panics
/// When the `CARGO_MANIFEST_DIR` environment variable is not set.
#[inline]
#[must_use]
pub fn manifest_path() -> PathBuf {
    PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("cargo manifest dir"))
        .canonicalize()
        .expect("canonicalize path")
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    Io(#[from] std::io::Error),
    #[error("Command failed")]
    Command(Output),
}

#[derive(Debug, Clone)]
pub struct Build {
    include_directories: Vec<PathBuf>,
    objects: Vec<PathBuf>,
    sources: Vec<PathBuf>,
    instrumentation_sources: Vec<PathBuf>,
    compiler_flags: Vec<String>,
    host_compiler: Option<PathBuf>,
    nvcc_compiler: Option<PathBuf>,
    warnings: bool,
    warnings_as_errors: bool,
}

impl Default for Build {
    fn default() -> Self {
        Self::new()
    }
}

impl Build {
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self {
            include_directories: Vec::new(),
            objects: Vec::new(),
            sources: Vec::new(),
            instrumentation_sources: Vec::new(),
            compiler_flags: Vec::new(),
            host_compiler: None,
            nvcc_compiler: None,
            warnings: false,
            warnings_as_errors: false,
        }
    }

    fn compile_instrumentation_functions(
        &self,
        nvcc_compiler: &Path,
        include_args: &[String],
        compiler_flags: &[&str],
        objects: &mut Vec<PathBuf>,
    ) -> Result<(), Error> {
        for (i, src) in self.instrumentation_sources.iter().enumerate() {
            let default_name = format!("instr_src_{i}");
            let obj = output_path()
                .join(
                    src.file_name()
                        .and_then(OsStr::to_str)
                        .unwrap_or(&default_name),
                )
                .with_extension("o");
            let mut cmd = Command::new(nvcc_compiler);
            if let Some(host_compiler) = &self.host_compiler {
                cmd.args(["-ccbin", &*host_compiler.to_string_lossy()]);
            }
            cmd.args(include_args);
            cmd.args([
                "-maxrregcount=24",
                "-arch=sm_35",
                "-Xptxas",
                "-astoolspatch",
                "--keep-device-functions",
            ])
            .args(compiler_flags)
            .args(&self.compiler_flags)
            .arg("-c")
            .arg(src)
            .arg("-o")
            .arg(&*obj.to_string_lossy());

            println!("cargo:warning={cmd:?}");
            let result = cmd.output()?;
            if !result.status.success() {
                return Err(Error::Command(result));
            }
            objects.push(obj);
        }
        Ok(())
    }

    fn compile_sources(
        &self,
        nvcc_compiler: &Path,
        include_args: &[String],
        compiler_flags: &[&str],
        objects: &mut Vec<PathBuf>,
    ) -> Result<(), Error> {
        for (i, src) in self.sources.iter().enumerate() {
            let default_name = format!("src_{i}");
            let obj = output_path()
                .join(
                    src.file_name()
                        .and_then(OsStr::to_str)
                        .unwrap_or(&default_name),
                )
                .with_extension("o");
            let mut cmd = Command::new(nvcc_compiler);
            if let Some(host_compiler) = &self.host_compiler {
                cmd.args(["-ccbin", &*host_compiler.to_string_lossy()]);
            }
            cmd.args(include_args)
                .args(compiler_flags)
                .args(&self.compiler_flags)
                .args(["-dc", "-c"])
                .arg(src)
                .arg("-o")
                .arg(&*obj.to_string_lossy());
            println!("cargo:warning={cmd:?}");
            let result = cmd.output()?;
            if !result.status.success() {
                return Err(Error::Command(result));
            }
            objects.push(obj);
        }
        Ok(())
    }

    /// Compile and link static library with given name from inputs.
    ///
    /// # Errors
    /// When compilation fails, an error is returned.
    pub fn compile<O: AsRef<str>>(&self, output: O) -> Result<(), Error> {
        let mut objects = self.objects.clone();
        let include_args: Vec<_> = self
            .include_directories
            .iter()
            .map(|d| format!("-I{}", &d.to_string_lossy()))
            .collect();

        let mut compiler_flags = vec!["-arch=sm_35", "-Xcompiler", "-fPIC"];
        if self.warnings {
            compiler_flags.extend(["-Xcompiler", "-Wall"]);
        }
        if self.warnings_as_errors {
            compiler_flags.extend(["-Xcompiler", "-Werror"]);
        }

        let default_nvcc_compiler = PathBuf::from("nvcc");
        let nvcc_compiler = self
            .nvcc_compiler
            .as_ref()
            .unwrap_or(&default_nvcc_compiler);

        // compile instrumentation functions
        self.compile_instrumentation_functions(
            nvcc_compiler,
            &include_args,
            &compiler_flags,
            &mut objects,
        )?;

        // compile sources
        self.compile_sources(nvcc_compiler, &include_args, &compiler_flags, &mut objects)?;

        // link device functions
        let dev_link_obj = output_path().join("dev_link.o");
        let mut cmd = Command::new(nvcc_compiler);
        if let Some(host_compiler) = &self.host_compiler {
            cmd.args(["-ccbin", &*host_compiler.to_string_lossy()]);
        }

        cmd.args(&include_args)
            .args(&compiler_flags)
            .args(&self.compiler_flags)
            .arg("-dlink")
            .args(&objects)
            .arg("-o")
            .arg(&*dev_link_obj.to_string_lossy());
        println!("cargo:warning={cmd:?}");
        let result = cmd.output()?;
        if !result.status.success() {
            return Err(Error::Command(result));
        }
        objects.push(dev_link_obj);

        // link everything together
        let mut cmd = Command::new("ar");
        cmd.args([
            "cru",
            &output_path()
                .join(format!("lib{}.a", output.as_ref()))
                .to_string_lossy(),
        ])
        .args(&objects);
        println!("cargo:warning={cmd:?}");
        let result = cmd.output()?;
        if !result.status.success() {
            return Err(Error::Command(result));
        }

        println!("cargo:rustc-link-search=native={}", output_path().display());
        println!(
            "cargo:rustc-link-lib=static:+whole-archive={}",
            output.as_ref()
        );
        Ok(())
    }

    /// Configures the host compiler to be used to produce output.
    pub fn host_compiler<P: Into<PathBuf>>(&mut self, compiler: P) -> &mut Self {
        self.host_compiler = Some(compiler.into());
        self
    }

    /// Configures the host compiler to be used to produce output.
    pub fn nvcc_compiler<P: Into<PathBuf>>(&mut self, compiler: P) -> &mut Self {
        self.nvcc_compiler = Some(compiler.into());
        self
    }

    pub fn object<P: Into<PathBuf>>(&mut self, obj: P) -> &mut Self {
        self.objects.push(obj.into());
        self
    }

    pub fn objects<P>(&mut self, objects: P) -> &mut Self
    where
        P: IntoIterator,
        P::Item: Into<PathBuf>,
    {
        for obj in objects {
            self.object(obj);
        }
        self
    }

    pub fn instrumentation_source<P: Into<PathBuf>>(&mut self, src: P) -> &mut Self {
        self.instrumentation_sources.push(src.into());
        self
    }

    pub fn instrumentation_sources<P>(&mut self, sources: P) -> &mut Self
    where
        P: IntoIterator,
        P::Item: Into<PathBuf>,
    {
        for src in sources {
            self.instrumentation_source(src);
        }
        self
    }

    pub fn source<P: Into<PathBuf>>(&mut self, dir: P) -> &mut Self {
        self.sources.push(dir.into());
        self
    }

    pub fn sources<P>(&mut self, sources: P) -> &mut Self
    where
        P: IntoIterator,
        P::Item: Into<PathBuf>,
    {
        for src in sources {
            self.source(src);
        }
        self
    }

    /// Add an arbitrary flag to the invocation of nvcc.
    pub fn nvcc_flag<F: Into<String>>(&mut self, flag: F) -> &mut Build {
        self.compiler_flags.push(flag.into());
        self
    }

    /// Add an arbitrary flag to the invocation of the host compiler.
    pub fn host_compiler_flag<F: Into<String>>(&mut self, flag: F) -> &mut Build {
        self.compiler_flags
            .extend(["-Xcompiler".to_string(), flag.into()]);
        self
    }

    /// Add arbitrary flags to the invocation of nvcc.
    pub fn nvcc_flags<I>(&mut self, flags: I) -> &mut Self
    where
        I: IntoIterator,
        I::Item: Into<String>,
    {
        for flag in flags {
            self.nvcc_flag(flag);
        }
        self
    }

    /// Add arbitrary flags to the invocation of the host compiler.
    pub fn host_compiler_flags<I>(&mut self, flags: I) -> &mut Self
    where
        I: IntoIterator,
        I::Item: Into<String>,
    {
        for flag in flags {
            self.host_compiler_flag(flag);
        }
        self
    }

    pub fn include<P: Into<PathBuf>>(&mut self, dir: P) -> &mut Self {
        self.include_directories.push(dir.into());
        self
    }

    pub fn includes<P>(&mut self, dirs: P) -> &mut Self
    where
        P: IntoIterator,
        P::Item: Into<PathBuf>,
    {
        for dir in dirs {
            self.include(dir);
        }
        self
    }

    pub fn warnings(&mut self, enable: bool) -> &mut Self {
        self.warnings = enable;
        self
    }

    pub fn warnings_as_errors(&mut self, enable: bool) -> &mut Self {
        self.warnings_as_errors = enable;
        self
    }
}