summaryrefslogtreecommitdiff
path: root/src/build/MetallibStep.zig
blob: 12adf3edb4cf7d98aa23659227f8fe3420549884 (plain)
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
/// A zig build step that compiles a set of ".metal" files into a
/// ".metallib" file.
const MetallibStep = @This();

const std = @import("std");
const Step = std.Build.Step;
const RunStep = std.Build.Step.Run;
const LazyPath = std.Build.LazyPath;

pub const Options = struct {
    /// The name of the xcframework to create.
    name: []const u8,

    /// The OS being targeted
    target: std.Build.ResolvedTarget,

    /// The Metal source files.
    sources: []const LazyPath,
};

step: *Step,
output: LazyPath,

pub fn create(b: *std.Build, opts: Options) ?*MetallibStep {
    const self = b.allocator.create(MetallibStep) catch @panic("OOM");

    const sdk = switch (opts.target.result.os.tag) {
        .macos => "macosx",
        .ios => "iphoneos",
        else => return null,
    };

    const min_version = if (opts.target.query.os_version_min) |v|
        b.fmt("{}", .{v.semver})
    else switch (opts.target.result.os.tag) {
        .macos => "10.14",
        .ios => "11.0",
        else => unreachable,
    };

    const run_ir = RunStep.create(
        b,
        b.fmt("metal {s}", .{opts.name}),
    );
    run_ir.addArgs(&.{ "/usr/bin/xcrun", "-sdk", sdk, "metal", "-o" });
    const output_ir = run_ir.addOutputFileArg(b.fmt("{s}.ir", .{opts.name}));
    run_ir.addArgs(&.{"-c"});
    for (opts.sources) |source| run_ir.addFileArg(source);
    switch (opts.target.result.os.tag) {
        .ios => run_ir.addArgs(&.{b.fmt(
            "-mios-version-min={s}",
            .{min_version},
        )}),
        .macos => run_ir.addArgs(&.{b.fmt(
            "-mmacos-version-min={s}",
            .{min_version},
        )}),
        else => {},
    }

    const run_lib = RunStep.create(
        b,
        b.fmt("metallib {s}", .{opts.name}),
    );
    run_lib.addArgs(&.{ "/usr/bin/xcrun", "-sdk", sdk, "metallib", "-o" });
    const output_lib = run_lib.addOutputFileArg(b.fmt("{s}.metallib", .{opts.name}));
    run_lib.addFileArg(output_ir);
    run_lib.step.dependOn(&run_ir.step);

    self.* = .{
        .step = &run_lib.step,
        .output = output_lib,
    };

    return self;
}