Merge remote-tracking branch 'origin/master' into llvm7

master
Andrew Kelley 2018-04-26 10:55:29 -04:00
commit bbfff46146
89 changed files with 9869 additions and 5263 deletions

View File

@ -1,18 +1,22 @@
sudo: required
services:
- docker
- docker
os:
- linux
- osx
- linux
- osx
dist: trusty
osx_image: xcode8.3
language: cpp
before_install:
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then ci/travis_linux_before_install; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ci/travis_osx_before_install; fi
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then ci/travis_linux_before_install; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ci/travis_osx_before_install; fi
install:
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then ci/travis_linux_install; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ci/travis_osx_install; fi
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then ci/travis_linux_install; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ci/travis_osx_install; fi
script:
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then ci/travis_linux_script; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ci/travis_osx_script; fi
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then ci/travis_linux_script; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ci/travis_osx_script; fi
env:
global:
- secure: QmJ+eLOxj3Irl5SHxt6lQvrj7++1AIz8bYri6RScAQGHQPIztkmbpBjAkpFgYaWPkZ04ROtamFXdS7oHtJHSECesgPoqM/CHIychQkgpDq30+TsFyYbBpDGHY+N6r2WnQTvg+9EuAp6P365us6qFS0D5zQ3P40c56uMbazFu3J4W1HZP+pLWlLjEXaN88ePhHWqNZyvwGMkLpYl3ghcrE9H4vGZQ7jenRW4UmskLEkuhUPJbQiow3Td8arJiRmLVISzWqneqNraLUpGyUVr4F3Rbjzacfoo3r9ZZynhY0mFsEye82x6TMGgH2xsNGkd91zpQuckWUT+pQv/G6FXpnEnjIJSO2Z5WAxXrx6xB1k2HZ17/4NWLF3fJVhdQJm3mS6odeGzUjgGrl1A42evxU+7VbcofEJq1aMiLgU1jUT2pt+pefCwmKJYLpEsSzuyrVxgvskQz0QpC053TAYSNf2Jj6Qhg9YDWyOeemYmDgffTqErF7AYhc6NKH0s0XKkIiNFSxorkEsfG/Ck1o+15slHNmWZXlmXToxDqFkLDoPvfGKg7koU5YTGvci/F9ZKb1juhGLxZbwap/18zN40BqA+Ip2yDBJAKxsIiwSjSIguy6g/Z1I50s0xNGOr36urfRRQX5H+rqr/xCZ63B6WSe6qBcZboWAQMDn8HLS9Xiwc=
- secure: dnb7r5guUeMOX9e7XlPUSZzmga8VW3G9Q1aa7LxEKiTjSnWhu5KpPDe8o1X3Rj6nc5iXDqmBH/C/7eNXPDyXJJWPvpE2YRpGymyUkRaakul0QBKJEaMvwy2SuAfS69CWC+TSzfGRvtSYkdpBhhLvs0h5S819S5jYbCNSCmOKfFucaP5NsHNIZ/I19oIeTPTa0/UnVm7DLFZXZjvbS+czkdyH1DhbT85sLj+XqNTzLePImE68efrjaHnlSy/CzBVJzj55UgD5i9fxNCQWzGWim/SD5xZ0zKtLycSOf6wQN2lCo0lkjw9rDlYz69mM5L9ikfYL9oHDPZnh84oXKglQ5miOHCgqs/qs4439I05lIu8i/EfbFA55YG4NyO3rL9YVOOt5gwiwvJYhDcnkVVzSl0o5bsoZgQfYvPWaIQKNkl3C53zfDQjgqS54CeDzlZpFrQTDQ1RrH8oeVC1gfYAeMabMDadox5rfZmLIN5JTf/F8iD/QdxGcoUvkEENcQgfP9PnubExtexgHGsEmqbm6ORSZ1MkEh2m3fo0f8KE6TbN1UigmcQ8nTkWBHsSmfHnB8HwJQp8mwQmDamXA+Hl3e3w4LOdYkJVlNW1/TTyJJOOvjMQCjF8SJmPHuh+QpqKbSaT9XM/vBhxbIZEufH8kawJKCBBcCNspGMNjhXfNjM0=

View File

@ -498,7 +498,28 @@ set(ZIG_STD_FILES
"math/tan.zig"
"math/tanh.zig"
"math/trunc.zig"
"math/x86_64/sqrt.zig"
"math/complex/abs.zig"
"math/complex/acosh.zig"
"math/complex/acos.zig"
"math/complex/arg.zig"
"math/complex/asinh.zig"
"math/complex/asin.zig"
"math/complex/atanh.zig"
"math/complex/atan.zig"
"math/complex/conj.zig"
"math/complex/cosh.zig"
"math/complex/cos.zig"
"math/complex/exp.zig"
"math/complex/index.zig"
"math/complex/ldexp.zig"
"math/complex/log.zig"
"math/complex/pow.zig"
"math/complex/proj.zig"
"math/complex/sinh.zig"
"math/complex/sin.zig"
"math/complex/sqrt.zig"
"math/complex/tanh.zig"
"math/complex/tan.zig"
"mem.zig"
"net.zig"
"os/child_process.zig"
@ -509,13 +530,17 @@ set(ZIG_STD_FILES
"os/index.zig"
"os/linux/errno.zig"
"os/linux/index.zig"
"os/linux/vdso.zig"
"os/linux/x86_64.zig"
"os/path.zig"
"os/time.zig"
"os/epoch.zig"
"os/windows/error.zig"
"os/windows/index.zig"
"os/windows/util.zig"
"os/zen.zig"
"rand/index.zig"
"rand/ziggurat.zig"
"sort.zig"
"special/bootstrap.zig"
"special/bootstrap_lib.zig"

View File

@ -19,5 +19,5 @@ if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then
echo "secret_key = $AWS_SECRET_ACCESS_KEY" >> ~/.s3cfg
s3cmd put -P $TRAVIS_BUILD_DIR/artifacts/* s3://ziglang.org/builds/
touch empty
s3cmd put -P empty s3://ziglang.org/builds/zig-linux-x86_64-$TRAVIS_BRANCH.tar.xz --add-header=x-amz-website-redirect-location:/builds/$(ls $TRAVIS_BUILD_DIR/artifacts)
s3cmd put -P empty s3://ziglang.org/builds/zig-linux-x86_64-$TRAVIS_BRANCH.tar.xz --add-header="Cache-Control: max-age=0, must-revalidate" --add-header=x-amz-website-redirect-location:/builds/$(ls $TRAVIS_BUILD_DIR/artifacts)
fi

View File

@ -301,6 +301,15 @@ template <class ELFT> void elf::markLive() {
// Follow the graph to mark all live sections.
doGcSections<ELFT>();
// If all references to a DSO happen to be weak, the DSO is removed from
// DT_NEEDED, which creates dangling shared symbols to non-existent DSO.
// We'll replace such symbols with undefined ones to fix it.
for (Symbol *Sym : Symtab->getSymbols())
if (auto *S = dyn_cast<SharedSymbol>(Sym))
if (S->isWeak() && !S->getFile<ELFT>().IsNeeded)
replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_WEAK, S->StOther,
S->Type);
// Report garbage-collected sections.
if (Config->PrintGcSections)
for (InputSectionBase *Sec : InputSections)

View File

@ -749,6 +749,10 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
try build_args.append("--release-fast");
try out.print(" --release-fast");
},
builtin.Mode.ReleaseSmall => {
try build_args.append("--release-small");
try out.print(" --release-small");
},
}
for (code.link_objects) |link_object| {
const name_with_ext = try std.fmt.allocPrint(allocator, "{}{}", link_object, obj_ext);
@ -810,6 +814,10 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
try test_args.append("--release-fast");
try out.print(" --release-fast");
},
builtin.Mode.ReleaseSmall => {
try test_args.append("--release-small");
try out.print(" --release-small");
},
}
if (code.target_windows) {
try test_args.appendSlice([][]const u8{
@ -840,6 +848,10 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
try test_args.append("--release-fast");
try out.print(" --release-fast");
},
builtin.Mode.ReleaseSmall => {
try test_args.append("--release-small");
try out.print(" --release-small");
},
}
const result = try os.ChildProcess.exec(allocator, test_args.toSliceConst(), null, null, max_doc_file_size);
switch (result.term) {
@ -874,6 +886,7 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
builtin.Mode.Debug => {},
builtin.Mode.ReleaseSafe => try test_args.append("--release-safe"),
builtin.Mode.ReleaseFast => try test_args.append("--release-fast"),
builtin.Mode.ReleaseSmall => try test_args.append("--release-small"),
}
const result = try os.ChildProcess.exec(allocator, test_args.toSliceConst(), null, null, max_doc_file_size);
@ -927,6 +940,12 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
try out.print(" --release-fast");
}
},
builtin.Mode.ReleaseSmall => {
try build_args.append("--release-small");
if (!code.is_inline) {
try out.print(" --release-small");
}
},
}
if (maybe_error_match) |error_match| {

View File

@ -3880,6 +3880,25 @@ pub fn main() void {
{#header_open|@ArgType#}
<p>TODO</p>
{#header_close#}
{#header_open|@atomicLoad#}
<pre><code class="zig">@atomicLoad(comptime T: type, ptr: &amp;const T, comptime ordering: builtin.AtomicOrder) -&gt; T</code></pre>
<p>
This builtin function atomically dereferences a pointer and returns the value.
</p>
<p>
<code>T</code> must be a pointer type, a <code>bool</code>,
or an integer whose bit count meets these requirements:
</p>
<ul>
<li>At least 8</li>
<li>At most the same as usize</li>
<li>Power of 2</li>
</ul>
<p>
TODO right now bool is not accepted. Also I think we could make non powers of 2 work fine, maybe
we can remove this restriction
</p>
{#header_close#}
{#header_open|@atomicRmw#}
<pre><code class="zig">@atomicRmw(comptime T: type, ptr: &amp;T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) -&gt; T</code></pre>
<p>
@ -4046,16 +4065,60 @@ comptime {
</p>
{#header_close#}
{#header_open|@cmpxchg#}
<pre><code class="zig">@cmpxchg(ptr: &T, cmp: T, new: T, success_order: AtomicOrder, fail_order: AtomicOrder) -&gt; bool</code></pre>
{#header_open|@cmpxchgStrong#}
<pre><code class="zig">@cmpxchgStrong(comptime T: type, ptr: &T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) -&gt; ?T</code></pre>
<p>
This function performs an atomic compare exchange operation.
This function performs a strong atomic compare exchange operation. It's the equivalent of this code,
except atomic:
</p>
{#code_begin|syntax#}
fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_value: T) ?T {
const old_value = *ptr;
if (old_value == expected_value) {
*ptr = new_value;
return null;
} else {
return old_value;
}
}
{#code_end#}
<p>
If you are using cmpxchg in a loop, {#link|@cmpxchgWeak#} is the better choice, because it can be implemented
more efficiently in machine instructions.
</p>
<p>
<code>AtomicOrder</code> can be found with <code>@import("builtin").AtomicOrder</code>.
</p>
<p><code>@typeOf(ptr).alignment</code> must be <code>&gt;= @sizeOf(T).</code></p>
{#see_also|Compile Variables#}
{#see_also|Compile Variables|cmpxchgWeak#}
{#header_close#}
{#header_open|@cmpxchgWeak#}
<pre><code class="zig">@cmpxchgWeak(comptime T: type, ptr: &T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) -&gt; ?T</code></pre>
<p>
This function performs a weak atomic compare exchange operation. It's the equivalent of this code,
except atomic:
</p>
{#code_begin|syntax#}
fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_value: T) ?T {
const old_value = *ptr;
if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
*ptr = new_value;
return null;
} else {
return old_value;
}
}
{#code_end#}
<p>
If you are using cmpxchg in a loop, the sporadic failure will be no problem, and <code>cmpxchgWeak</code>
is the better choice, because it can be implemented more efficiently in machine instructions.
However if you need a stronger guarantee, use {#link|@cmpxchgStrong#}.
</p>
<p>
<code>AtomicOrder</code> can be found with <code>@import("builtin").AtomicOrder</code>.
</p>
<p><code>@typeOf(ptr).alignment</code> must be <code>&gt;= @sizeOf(T).</code></p>
{#see_also|Compile Variables|cmpxchgStrong#}
{#header_close#}
{#header_open|@compileError#}
<pre><code class="zig">@compileError(comptime msg: []u8)</code></pre>
@ -4349,6 +4412,10 @@ fn add(a: i32, b: i32) i32 { return a + b; }
It does not include functions, variables, or constants.
</p>
{#header_close#}
{#header_open|@field#}
<pre><code class="zig">@field(lhs: var, comptime field_name: []const u8) -&gt; (field)</code></pre>
<p>Preforms field access equivalent to <code>lhs.-&gtfield_name-&lt</code>.</p>
{#header_close#}
{#header_open|@memberType#}
<pre><code class="zig">@memberType(comptime T: type, comptime index: usize) -&gt; type</code></pre>
<p>Returns the field type of a struct or union.</p>
@ -4669,6 +4736,16 @@ pub const FloatMode = enum {
The result is a target-specific compile time constant.
</p>
{#header_close#}
{#header_open|@sqrt#}
<pre><code class="zig">@sqrt(comptime T: type, value: T) -&gt; T</code></pre>
<p>
Performs the square root of a floating point number. Uses a dedicated hardware instruction
when available. Currently only supports f32 and f64 at runtime. f128 at runtime is TODO.
</p>
<p>
This is a low-level intrinsic. Most code can use <code>std.math.sqrt</code> instead.
</p>
{#header_close#}
{#header_open|@subWithOverflow#}
<pre><code class="zig">@subWithOverflow(comptime T: type, a: T, b: T, result: &T) -&gt; bool</code></pre>
<p>
@ -5845,7 +5922,7 @@ Defer(body) = ("defer" | "deferror") body
IfExpression(body) = "if" "(" Expression ")" body option("else" BlockExpression(body))
SuspendExpression(body) = "suspend" option(("|" Symbol "|" body))
SuspendExpression(body) = option(Symbol ":") "suspend" option(("|" Symbol "|" body))
IfErrorExpression(body) = "if" "(" Expression ")" option("|" option("*") Symbol "|") body "else" "|" Symbol "|" BlockExpression(body)
@ -5991,7 +6068,7 @@ hljs.registerLanguage("zig", function(t) {
a = t.IR + "\\s*\\(",
c = {
keyword: "const align var extern stdcallcc nakedcc volatile export pub noalias inline struct packed enum union break return try catch test continue unreachable comptime and or asm defer errdefer if else switch while for fn use bool f32 f64 void type noreturn error i8 u8 i16 u16 i32 u32 i64 u64 isize usize i8w u8w i16w i32w u32w i64w u64w isizew usizew c_short c_ushort c_int c_uint c_long c_ulong c_longlong c_ulonglong",
built_in: "breakpoint returnAddress frameAddress fieldParentPtr setFloatMode IntType OpaqueType compileError compileLog setCold setRuntimeSafety setEvalBranchQuota offsetOf memcpy inlineCall setGlobalLinkage setGlobalSection divTrunc divFloor enumTagName intToPtr ptrToInt panic canImplicitCast ptrCast bitCast rem mod memset sizeOf alignOf alignCast maxValue minValue memberCount memberName memberType typeOf addWithOverflow subWithOverflow mulWithOverflow shlWithOverflow shlExact shrExact cInclude cDefine cUndef ctz clz import cImport errorName embedFile cmpxchg fence divExact truncate atomicRmw",
built_in: "atomicLoad breakpoint returnAddress frameAddress fieldParentPtr setFloatMode IntType OpaqueType compileError compileLog setCold setRuntimeSafety setEvalBranchQuota offsetOf memcpy inlineCall setGlobalLinkage setGlobalSection divTrunc divFloor enumTagName intToPtr ptrToInt panic canImplicitCast ptrCast bitCast rem mod memset sizeOf alignOf alignCast maxValue minValue memberCount memberName memberType typeOf addWithOverflow subWithOverflow mulWithOverflow shlWithOverflow shlExact shrExact cInclude cDefine cUndef ctz clz import cImport errorName embedFile cmpxchgStrong cmpxchgWeak fence divExact truncate atomicRmw sqrt field",
literal: "true false null undefined"
},
n = [e, t.CLCM, t.CBCM, s, r];

284
src-self-hosted/arg.zig Normal file
View File

@ -0,0 +1,284 @@
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const HashMap = std.HashMap;
fn trimStart(slice: []const u8, ch: u8) []const u8 {
var i: usize = 0;
for (slice) |b| {
if (b != '-') break;
i += 1;
}
return slice[i..];
}
fn argInAllowedSet(maybe_set: ?[]const []const u8, arg: []const u8) bool {
if (maybe_set) |set| {
for (set) |possible| {
if (mem.eql(u8, arg, possible)) {
return true;
}
}
return false;
} else {
return true;
}
}
// Modifies the current argument index during iteration
fn readFlagArguments(allocator: &Allocator, args: []const []const u8, required: usize,
allowed_set: ?[]const []const u8, index: &usize) !FlagArg {
switch (required) {
0 => return FlagArg { .None = undefined }, // TODO: Required to force non-tag but value?
1 => {
if (*index + 1 >= args.len) {
return error.MissingFlagArguments;
}
*index += 1;
const arg = args[*index];
if (!argInAllowedSet(allowed_set, arg)) {
return error.ArgumentNotInAllowedSet;
}
return FlagArg { .Single = arg };
},
else => |needed| {
var extra = ArrayList([]const u8).init(allocator);
errdefer extra.deinit();
var j: usize = 0;
while (j < needed) : (j += 1) {
if (*index + 1 >= args.len) {
return error.MissingFlagArguments;
}
*index += 1;
const arg = args[*index];
if (!argInAllowedSet(allowed_set, arg)) {
return error.ArgumentNotInAllowedSet;
}
try extra.append(arg);
}
return FlagArg { .Many = extra };
},
}
}
const HashMapFlags = HashMap([]const u8, FlagArg, std.hash.Fnv1a_32.hash, mem.eql_slice_u8);
// A store for querying found flags and positional arguments.
pub const Args = struct {
flags: HashMapFlags,
positionals: ArrayList([]const u8),
pub fn parse(allocator: &Allocator, comptime spec: []const Flag, args: []const []const u8) !Args {
var parsed = Args {
.flags = HashMapFlags.init(allocator),
.positionals = ArrayList([]const u8).init(allocator),
};
var i: usize = 0;
next: while (i < args.len) : (i += 1) {
const arg = args[i];
if (arg.len != 0 and arg[0] == '-') {
// TODO: hashmap, although the linear scan is okay for small argument sets as is
for (spec) |flag| {
if (mem.eql(u8, arg, flag.name)) {
const flag_name_trimmed = trimStart(flag.name, '-');
const flag_args = readFlagArguments(allocator, args, flag.required, flag.allowed_set, &i) catch |err| {
switch (err) {
error.ArgumentNotInAllowedSet => {
std.debug.warn("argument '{}' is invalid for flag '{}'\n", args[i], arg);
std.debug.warn("allowed options are ");
for (??flag.allowed_set) |possible| {
std.debug.warn("'{}' ", possible);
}
std.debug.warn("\n");
},
error.MissingFlagArguments => {
std.debug.warn("missing argument for flag: {}\n", arg);
},
else => {},
}
return err;
};
if (flag.mergable) {
var prev =
if (parsed.flags.get(flag_name_trimmed)) |entry|
entry.value.Many
else
ArrayList([]const u8).init(allocator);
// MergeN creation disallows 0 length flag entry (doesn't make sense)
switch (flag_args) {
FlagArg.None => unreachable,
FlagArg.Single => |inner| try prev.append(inner),
FlagArg.Many => |inner| try prev.appendSlice(inner.toSliceConst()),
}
_ = try parsed.flags.put(flag_name_trimmed, FlagArg { .Many = prev });
} else {
_ = try parsed.flags.put(flag_name_trimmed, flag_args);
}
continue :next;
}
}
// TODO: Better errors with context, global error state and return is sufficient.
std.debug.warn("could not match flag: {}\n", arg);
return error.UnknownFlag;
} else {
try parsed.positionals.append(arg);
}
}
return parsed;
}
pub fn deinit(self: &Args) void {
self.flags.deinit();
self.positionals.deinit();
}
// e.g. --help
pub fn present(self: &Args, name: []const u8) bool {
return self.flags.contains(name);
}
// e.g. --name value
pub fn single(self: &Args, name: []const u8) ?[]const u8 {
if (self.flags.get(name)) |entry| {
switch (entry.value) {
FlagArg.Single => |inner| { return inner; },
else => @panic("attempted to retrieve flag with wrong type"),
}
} else {
return null;
}
}
// e.g. --names value1 value2 value3
pub fn many(self: &Args, name: []const u8) ?[]const []const u8 {
if (self.flags.get(name)) |entry| {
switch (entry.value) {
FlagArg.Many => |inner| { return inner.toSliceConst(); },
else => @panic("attempted to retrieve flag with wrong type"),
}
} else {
return null;
}
}
};
// Arguments for a flag. e.g. arg1, arg2 in `--command arg1 arg2`.
const FlagArg = union(enum) {
None,
Single: []const u8,
Many: ArrayList([]const u8),
};
// Specification for how a flag should be parsed.
pub const Flag = struct {
name: []const u8,
required: usize,
mergable: bool,
allowed_set: ?[]const []const u8,
pub fn Bool(comptime name: []const u8) Flag {
return ArgN(name, 0);
}
pub fn Arg1(comptime name: []const u8) Flag {
return ArgN(name, 1);
}
pub fn ArgN(comptime name: []const u8, comptime n: usize) Flag {
return Flag {
.name = name,
.required = n,
.mergable = false,
.allowed_set = null,
};
}
pub fn ArgMergeN(comptime name: []const u8, comptime n: usize) Flag {
if (n == 0) {
@compileError("n must be greater than 0");
}
return Flag {
.name = name,
.required = n,
.mergable = true,
.allowed_set = null,
};
}
pub fn Option(comptime name: []const u8, comptime set: []const []const u8) Flag {
return Flag {
.name = name,
.required = 1,
.mergable = false,
.allowed_set = set,
};
}
};
test "parse arguments" {
const spec1 = comptime []const Flag {
Flag.Bool("--help"),
Flag.Bool("--init"),
Flag.Arg1("--build-file"),
Flag.Option("--color", []const []const u8 { "on", "off", "auto" }),
Flag.ArgN("--pkg-begin", 2),
Flag.ArgMergeN("--object", 1),
Flag.ArgN("--library", 1),
};
const cliargs = []const []const u8 {
"build",
"--help",
"pos1",
"--build-file", "build.zig",
"--object", "obj1",
"--object", "obj2",
"--library", "lib1",
"--library", "lib2",
"--color", "on",
"pos2",
};
var args = try Args.parse(std.debug.global_allocator, spec1, cliargs);
debug.assert(args.present("help"));
debug.assert(!args.present("help2"));
debug.assert(!args.present("init"));
debug.assert(mem.eql(u8, ??args.single("build-file"), "build.zig"));
debug.assert(mem.eql(u8, ??args.single("color"), "on"));
const objects = ??args.many("object");
debug.assert(mem.eql(u8, objects[0], "obj1"));
debug.assert(mem.eql(u8, objects[1], "obj2"));
debug.assert(mem.eql(u8, ??args.single("library"), "lib2"));
const pos = args.positionals.toSliceConst();
debug.assert(mem.eql(u8, pos[0], "build"));
debug.assert(mem.eql(u8, pos[1], "pos1"));
debug.assert(mem.eql(u8, pos[2], "pos2"));
}

View File

@ -0,0 +1,57 @@
// Introspection and determination of system libraries needed by zig.
const std = @import("std");
const mem = std.mem;
const os = std.os;
const warn = std.debug.warn;
/// Caller must free result
pub fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) ![]u8 {
const test_zig_dir = try os.path.join(allocator, test_path, "lib", "zig");
errdefer allocator.free(test_zig_dir);
const test_index_file = try os.path.join(allocator, test_zig_dir, "std", "index.zig");
defer allocator.free(test_index_file);
var file = try os.File.openRead(allocator, test_index_file);
file.close();
return test_zig_dir;
}
/// Caller must free result
pub fn findZigLibDir(allocator: &mem.Allocator) ![]u8 {
const self_exe_path = try os.selfExeDirPath(allocator);
defer allocator.free(self_exe_path);
var cur_path: []const u8 = self_exe_path;
while (true) {
const test_dir = os.path.dirname(cur_path);
if (mem.eql(u8, test_dir, cur_path)) {
break;
}
return testZigInstallPrefix(allocator, test_dir) catch |err| {
cur_path = test_dir;
continue;
};
}
return error.FileNotFound;
}
pub fn resolveZigLibDir(allocator: &mem.Allocator) ![]u8 {
return findZigLibDir(allocator) catch |err| {
warn(
\\Unable to find zig lib directory: {}.
\\Reinstall Zig or use --zig-install-prefix.
\\
,
@errorName(err)
);
return error.ZigLibDirNotFound;
};
}

File diff suppressed because it is too large Load Diff

View File

@ -109,6 +109,29 @@ pub const Module = struct {
LlvmIr,
};
pub const CliPkg = struct {
name: []const u8,
path: []const u8,
children: ArrayList(&CliPkg),
parent: ?&CliPkg,
pub fn init(allocator: &mem.Allocator, name: []const u8, path: []const u8, parent: ?&CliPkg) !&CliPkg {
var pkg = try allocator.create(CliPkg);
pkg.name = name;
pkg.path = path;
pkg.children = ArrayList(&CliPkg).init(allocator);
pkg.parent = parent;
return pkg;
}
pub fn deinit(self: &CliPkg) void {
for (self.children.toSliceConst()) |child| {
child.deinit();
}
self.children.deinit();
}
};
pub fn create(allocator: &mem.Allocator, name: []const u8, root_src_path: ?[]const u8, target: &const Target,
kind: Kind, build_mode: builtin.Mode, zig_lib_dir: []const u8, cache_dir: []const u8) !&Module
{

View File

@ -867,6 +867,7 @@ struct AstNodeAwaitExpr {
};
struct AstNodeSuspend {
Buf *name;
AstNode *block;
AstNode *promise_symbol;
};
@ -1291,6 +1292,7 @@ enum BuiltinFnId {
BuiltinFnIdMemberCount,
BuiltinFnIdMemberType,
BuiltinFnIdMemberName,
BuiltinFnIdField,
BuiltinFnIdTypeof,
BuiltinFnIdAddWithOverflow,
BuiltinFnIdSubWithOverflow,
@ -1310,13 +1312,15 @@ enum BuiltinFnId {
BuiltinFnIdReturnAddress,
BuiltinFnIdFrameAddress,
BuiltinFnIdEmbedFile,
BuiltinFnIdCmpExchange,
BuiltinFnIdCmpxchgWeak,
BuiltinFnIdCmpxchgStrong,
BuiltinFnIdFence,
BuiltinFnIdDivExact,
BuiltinFnIdDivTrunc,
BuiltinFnIdDivFloor,
BuiltinFnIdRem,
BuiltinFnIdMod,
BuiltinFnIdSqrt,
BuiltinFnIdTruncate,
BuiltinFnIdIntType,
BuiltinFnIdSetCold,
@ -1346,6 +1350,7 @@ enum BuiltinFnId {
BuiltinFnIdExport,
BuiltinFnIdErrorReturnTrace,
BuiltinFnIdAtomicRmw,
BuiltinFnIdAtomicLoad,
};
struct BuiltinFnEntry {
@ -1413,6 +1418,7 @@ enum ZigLLVMFnId {
ZigLLVMFnIdOverflowArithmetic,
ZigLLVMFnIdFloor,
ZigLLVMFnIdCeil,
ZigLLVMFnIdSqrt,
};
enum AddSubMul {
@ -1433,7 +1439,7 @@ struct ZigLLVMFnKey {
} clz;
struct {
uint32_t bit_count;
} floor_ceil;
} floating;
struct {
AddSubMul add_sub_mul;
uint32_t bit_count;
@ -1454,6 +1460,7 @@ enum BuildMode {
BuildModeDebug,
BuildModeFastRelease,
BuildModeSafeRelease,
BuildModeSmallRelease,
};
enum EmitFileType {
@ -1698,6 +1705,8 @@ struct CodeGen {
ZigList<ZigLLVMDIType **> error_di_types;
ZigList<Buf *> forbidden_libs;
bool no_rosegment_workaround;
};
enum VarLinkage {
@ -1748,6 +1757,7 @@ enum ScopeId {
ScopeIdVarDecl,
ScopeIdCImport,
ScopeIdLoop,
ScopeIdSuspend,
ScopeIdFnDef,
ScopeIdCompTime,
ScopeIdCoroPrelude,
@ -1843,6 +1853,17 @@ struct ScopeLoop {
ZigList<IrBasicBlock *> *incoming_blocks;
};
// This scope is created for a suspend block in order to have labeled
// suspend for breaking out of a suspend and for detecting if a suspend
// block is inside a suspend block.
struct ScopeSuspend {
Scope base;
Buf *name;
IrBasicBlock *resume_block;
bool reported_err;
};
// This scope is created for a comptime expression.
// NodeTypeCompTime, NodeTypeSwitchExpr
struct ScopeCompTime {
@ -2039,12 +2060,14 @@ enum IrInstructionId {
IrInstructionIdCoroPromise,
IrInstructionIdCoroAllocHelper,
IrInstructionIdAtomicRmw,
IrInstructionIdAtomicLoad,
IrInstructionIdPromiseResultType,
IrInstructionIdAwaitBookkeeping,
IrInstructionIdSaveErrRetAddr,
IrInstructionIdAddImplicitReturnType,
IrInstructionIdMergeErrRetTraces,
IrInstructionIdMarkErrRetTracePtr,
IrInstructionIdSqrt,
};
struct IrInstruction {
@ -2201,7 +2224,8 @@ struct IrInstructionFieldPtr {
IrInstruction base;
IrInstruction *container_ptr;
Buf *field_name;
Buf *field_name_buffer;
IrInstruction *field_name_expr;
bool is_const;
};
@ -2520,6 +2544,7 @@ struct IrInstructionEmbedFile {
struct IrInstructionCmpxchg {
IrInstruction base;
IrInstruction *type_value;
IrInstruction *ptr;
IrInstruction *cmp_value;
IrInstruction *new_value;
@ -2527,8 +2552,13 @@ struct IrInstructionCmpxchg {
IrInstruction *failure_order_value;
// if this instruction gets to runtime then we know these values:
TypeTableEntry *type;
AtomicOrder success_order;
AtomicOrder failure_order;
bool is_weak;
LLVMValueRef tmp_ptr;
};
struct IrInstructionFence {
@ -2998,6 +3028,15 @@ struct IrInstructionAtomicRmw {
AtomicOrder resolved_ordering;
};
struct IrInstructionAtomicLoad {
IrInstruction base;
IrInstruction *operand_type;
IrInstruction *ptr;
IrInstruction *ordering;
AtomicOrder resolved_ordering;
};
struct IrInstructionPromiseResultType {
IrInstruction base;
@ -3034,6 +3073,13 @@ struct IrInstructionMarkErrRetTracePtr {
IrInstruction *err_ret_trace_ptr;
};
struct IrInstructionSqrt {
IrInstruction base;
IrInstruction *type;
IrInstruction *op;
};
static const size_t slice_ptr_index = 0;
static const size_t slice_len_index = 1;

View File

@ -156,6 +156,14 @@ ScopeLoop *create_loop_scope(AstNode *node, Scope *parent) {
return scope;
}
ScopeSuspend *create_suspend_scope(AstNode *node, Scope *parent) {
assert(node->type == NodeTypeSuspend);
ScopeSuspend *scope = allocate<ScopeSuspend>(1);
init_scope(&scope->base, ScopeIdSuspend, node, parent);
scope->name = node->data.suspend.name;
return scope;
}
ScopeFnDef *create_fndef_scope(AstNode *node, Scope *parent, FnTableEntry *fn_entry) {
ScopeFnDef *scope = allocate<ScopeFnDef>(1);
init_scope(&scope->base, ScopeIdFnDef, node, parent);
@ -3616,6 +3624,7 @@ FnTableEntry *scope_get_fn_if_root(Scope *scope) {
case ScopeIdVarDecl:
case ScopeIdCImport:
case ScopeIdLoop:
case ScopeIdSuspend:
case ScopeIdCompTime:
case ScopeIdCoroPrelude:
scope = scope->parent;
@ -4297,7 +4306,8 @@ bool handle_is_ptr(TypeTableEntry *type_entry) {
static ZigWindowsSDK *get_windows_sdk(CodeGen *g) {
if (g->win_sdk == nullptr) {
if (os_find_windows_sdk(&g->win_sdk)) {
zig_panic("Unable to determine Windows SDK path.");
fprintf(stderr, "unable to determine windows sdk path\n");
exit(1);
}
}
assert(g->win_sdk != nullptr);
@ -4399,7 +4409,8 @@ void find_libc_include_path(CodeGen *g) {
ZigWindowsSDK *sdk = get_windows_sdk(g);
g->libc_include_dir = buf_alloc();
if (os_get_win32_ucrt_include_path(sdk, g->libc_include_dir)) {
zig_panic("Unable to determine libc include path.");
fprintf(stderr, "Unable to determine libc include path. --libc-include-dir");
exit(1);
}
} else if (g->zig_target.os == OsLinux) {
g->libc_include_dir = get_linux_libc_include_path();
@ -4421,24 +4432,33 @@ void find_libc_lib_path(CodeGen *g) {
if (g->zig_target.os == OsWindows) {
ZigWindowsSDK *sdk = get_windows_sdk(g);
Buf* vc_lib_dir = buf_alloc();
if (os_get_win32_vcruntime_path(vc_lib_dir, g->zig_target.arch.arch)) {
zig_panic("Unable to determine vcruntime path.");
if (g->msvc_lib_dir == nullptr) {
Buf* vc_lib_dir = buf_alloc();
if (os_get_win32_vcruntime_path(vc_lib_dir, g->zig_target.arch.arch)) {
fprintf(stderr, "Unable to determine vcruntime path. --msvc-lib-dir");
exit(1);
}
g->msvc_lib_dir = vc_lib_dir;
}
Buf* ucrt_lib_path = buf_alloc();
if (os_get_win32_ucrt_lib_path(sdk, ucrt_lib_path, g->zig_target.arch.arch)) {
zig_panic("Unable to determine ucrt path.");
if (g->libc_lib_dir == nullptr) {
Buf* ucrt_lib_path = buf_alloc();
if (os_get_win32_ucrt_lib_path(sdk, ucrt_lib_path, g->zig_target.arch.arch)) {
fprintf(stderr, "Unable to determine ucrt path. --libc-lib-dir");
exit(1);
}
g->libc_lib_dir = ucrt_lib_path;
}
Buf* kern_lib_path = buf_alloc();
if (os_get_win32_kern32_path(sdk, kern_lib_path, g->zig_target.arch.arch)) {
zig_panic("Unable to determine kernel32 path.");
if (g->kernel32_lib_dir == nullptr) {
Buf* kern_lib_path = buf_alloc();
if (os_get_win32_kern32_path(sdk, kern_lib_path, g->zig_target.arch.arch)) {
fprintf(stderr, "Unable to determine kernel32 path. --kernel32-lib-dir");
exit(1);
}
g->kernel32_lib_dir = kern_lib_path;
}
g->msvc_lib_dir = vc_lib_dir;
g->libc_lib_dir = ucrt_lib_path;
g->kernel32_lib_dir = kern_lib_path;
} else if (g->zig_target.os == OsLinux) {
g->libc_lib_dir = get_linux_libc_lib_path("crt1.o");
} else {
@ -5801,9 +5821,11 @@ uint32_t zig_llvm_fn_key_hash(ZigLLVMFnKey x) {
case ZigLLVMFnIdClz:
return (uint32_t)(x.data.clz.bit_count) * (uint32_t)2428952817;
case ZigLLVMFnIdFloor:
return (uint32_t)(x.data.floor_ceil.bit_count) * (uint32_t)1899859168;
return (uint32_t)(x.data.floating.bit_count) * (uint32_t)1899859168;
case ZigLLVMFnIdCeil:
return (uint32_t)(x.data.floor_ceil.bit_count) * (uint32_t)1953839089;
return (uint32_t)(x.data.floating.bit_count) * (uint32_t)1953839089;
case ZigLLVMFnIdSqrt:
return (uint32_t)(x.data.floating.bit_count) * (uint32_t)2225366385;
case ZigLLVMFnIdOverflowArithmetic:
return ((uint32_t)(x.data.overflow_arithmetic.bit_count) * 87135777) +
((uint32_t)(x.data.overflow_arithmetic.add_sub_mul) * 31640542) +
@ -5822,7 +5844,8 @@ bool zig_llvm_fn_key_eql(ZigLLVMFnKey a, ZigLLVMFnKey b) {
return a.data.clz.bit_count == b.data.clz.bit_count;
case ZigLLVMFnIdFloor:
case ZigLLVMFnIdCeil:
return a.data.floor_ceil.bit_count == b.data.floor_ceil.bit_count;
case ZigLLVMFnIdSqrt:
return a.data.floating.bit_count == b.data.floating.bit_count;
case ZigLLVMFnIdOverflowArithmetic:
return (a.data.overflow_arithmetic.bit_count == b.data.overflow_arithmetic.bit_count) &&
(a.data.overflow_arithmetic.add_sub_mul == b.data.overflow_arithmetic.add_sub_mul) &&

View File

@ -104,6 +104,7 @@ ScopeDeferExpr *create_defer_expr_scope(AstNode *node, Scope *parent);
Scope *create_var_scope(AstNode *node, Scope *parent, VariableTableEntry *var);
ScopeCImport *create_cimport_scope(AstNode *node, Scope *parent);
ScopeLoop *create_loop_scope(AstNode *node, Scope *parent);
ScopeSuspend *create_suspend_scope(AstNode *node, Scope *parent);
ScopeFnDef *create_fndef_scope(AstNode *node, Scope *parent, FnTableEntry *fn_entry);
ScopeDecls *create_decls_scope(AstNode *node, Scope *parent, TypeTableEntry *container_type, ImportTableEntry *import);
Scope *create_comptime_scope(AstNode *node, Scope *parent);

View File

@ -181,3 +181,7 @@ bool bigfloat_has_fraction(const BigFloat *bigfloat) {
f128M_roundToInt(&bigfloat->value, softfloat_round_minMag, false, &floored);
return !f128M_eq(&floored, &bigfloat->value);
}
void bigfloat_sqrt(BigFloat *dest, const BigFloat *op) {
f128M_sqrt(&op->value, &dest->value);
}

View File

@ -42,6 +42,7 @@ void bigfloat_div_trunc(BigFloat *dest, const BigFloat *op1, const BigFloat *op2
void bigfloat_div_floor(BigFloat *dest, const BigFloat *op1, const BigFloat *op2);
void bigfloat_rem(BigFloat *dest, const BigFloat *op1, const BigFloat *op2);
void bigfloat_mod(BigFloat *dest, const BigFloat *op1, const BigFloat *op2);
void bigfloat_sqrt(BigFloat *dest, const BigFloat *op);
void bigfloat_append_buf(Buf *buf, const BigFloat *op);
Cmp bigfloat_cmp(const BigFloat *op1, const BigFloat *op2);

View File

@ -86,6 +86,11 @@ static void to_twos_complement(BigInt *dest, const BigInt *op, size_t bit_count)
size_t digits_to_copy = bit_count / 64;
size_t leftover_bits = bit_count % 64;
dest->digit_count = digits_to_copy + ((leftover_bits == 0) ? 0 : 1);
if (dest->digit_count == 1 && leftover_bits == 0) {
dest->data.digit = op_digits[0];
if (dest->data.digit == 0) dest->digit_count = 0;
return;
}
dest->data.digits = allocate_nonzero<uint64_t>(dest->digit_count);
for (size_t i = 0; i < digits_to_copy; i += 1) {
uint64_t digit = (i < op->digit_count) ? op_digits[i] : 0;

View File

@ -471,7 +471,7 @@ static LLVMValueRef fn_llvm_value(CodeGen *g, FnTableEntry *fn_table_entry) {
fn_table_entry->llvm_value, buf_ptr(&fn_export->name));
}
}
fn_table_entry->llvm_name = LLVMGetValueName(fn_table_entry->llvm_value);
fn_table_entry->llvm_name = strdup(LLVMGetValueName(fn_table_entry->llvm_value));
switch (fn_table_entry->fn_inline) {
case FnInlineAlways:
@ -516,7 +516,9 @@ static LLVMValueRef fn_llvm_value(CodeGen *g, FnTableEntry *fn_table_entry) {
}
if (fn_table_entry->body_node != nullptr) {
bool want_fn_safety = g->build_mode != BuildModeFastRelease && !fn_table_entry->def_scope->safety_off;
bool want_fn_safety = g->build_mode != BuildModeFastRelease &&
g->build_mode != BuildModeSmallRelease &&
!fn_table_entry->def_scope->safety_off;
if (want_fn_safety) {
if (g->libc_link_lib != nullptr) {
addLLVMFnAttr(fn_table_entry->llvm_value, "sspstrong");
@ -656,6 +658,7 @@ static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) {
}
case ScopeIdDeferExpr:
case ScopeIdLoop:
case ScopeIdSuspend:
case ScopeIdCompTime:
case ScopeIdCoroPrelude:
return get_di_scope(g, scope->parent);
@ -721,12 +724,12 @@ static LLVMValueRef get_int_overflow_fn(CodeGen *g, TypeTableEntry *type_entry,
return fn_val;
}
static LLVMValueRef get_floor_ceil_fn(CodeGen *g, TypeTableEntry *type_entry, ZigLLVMFnId fn_id) {
static LLVMValueRef get_float_fn(CodeGen *g, TypeTableEntry *type_entry, ZigLLVMFnId fn_id) {
assert(type_entry->id == TypeTableEntryIdFloat);
ZigLLVMFnKey key = {};
key.id = fn_id;
key.data.floor_ceil.bit_count = (uint32_t)type_entry->data.floating.bit_count;
key.data.floating.bit_count = (uint32_t)type_entry->data.floating.bit_count;
auto existing_entry = g->llvm_fn_table.maybe_get(key);
if (existing_entry)
@ -737,6 +740,8 @@ static LLVMValueRef get_floor_ceil_fn(CodeGen *g, TypeTableEntry *type_entry, Zi
name = "floor";
} else if (fn_id == ZigLLVMFnIdCeil) {
name = "ceil";
} else if (fn_id == ZigLLVMFnIdSqrt) {
name = "sqrt";
} else {
zig_unreachable();
}
@ -819,7 +824,7 @@ static bool ir_want_fast_math(CodeGen *g, IrInstruction *instruction) {
}
static bool ir_want_runtime_safety(CodeGen *g, IrInstruction *instruction) {
if (g->build_mode == BuildModeFastRelease)
if (g->build_mode == BuildModeFastRelease || g->build_mode == BuildModeSmallRelease)
return false;
// TODO memoize
@ -1867,7 +1872,7 @@ static LLVMValueRef gen_floor(CodeGen *g, LLVMValueRef val, TypeTableEntry *type
if (type_entry->id == TypeTableEntryIdInt)
return val;
LLVMValueRef floor_fn = get_floor_ceil_fn(g, type_entry, ZigLLVMFnIdFloor);
LLVMValueRef floor_fn = get_float_fn(g, type_entry, ZigLLVMFnIdFloor);
return LLVMBuildCall(g->builder, floor_fn, &val, 1, "");
}
@ -1875,7 +1880,7 @@ static LLVMValueRef gen_ceil(CodeGen *g, LLVMValueRef val, TypeTableEntry *type_
if (type_entry->id == TypeTableEntryIdInt)
return val;
LLVMValueRef ceil_fn = get_floor_ceil_fn(g, type_entry, ZigLLVMFnIdCeil);
LLVMValueRef ceil_fn = get_float_fn(g, type_entry, ZigLLVMFnIdCeil);
return LLVMBuildCall(g->builder, ceil_fn, &val, 1, "");
}
@ -3186,10 +3191,12 @@ static LLVMValueRef get_int_builtin_fn(CodeGen *g, TypeTableEntry *int_type, Bui
fn_name = "cttz";
key.id = ZigLLVMFnIdCtz;
key.data.ctz.bit_count = (uint32_t)int_type->data.integral.bit_count;
} else {
} else if (fn_id == BuiltinFnIdClz) {
fn_name = "ctlz";
key.id = ZigLLVMFnIdClz;
key.data.clz.bit_count = (uint32_t)int_type->data.integral.bit_count;
} else {
zig_unreachable();
}
auto existing_entry = g->llvm_fn_table.maybe_get(key);
@ -3491,9 +3498,30 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutable *executable, IrIn
LLVMAtomicOrdering failure_order = to_LLVMAtomicOrdering(instruction->failure_order);
LLVMValueRef result_val = ZigLLVMBuildCmpXchg(g->builder, ptr_val, cmp_val, new_val,
success_order, failure_order);
success_order, failure_order, instruction->is_weak);
return LLVMBuildExtractValue(g->builder, result_val, 1, "");
TypeTableEntry *maybe_type = instruction->base.value.type;
assert(maybe_type->id == TypeTableEntryIdMaybe);
TypeTableEntry *child_type = maybe_type->data.maybe.child_type;
if (type_is_codegen_pointer(child_type)) {
LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, "");
LLVMValueRef success_bit = LLVMBuildExtractValue(g->builder, result_val, 1, "");
return LLVMBuildSelect(g->builder, success_bit, LLVMConstNull(child_type->type_ref), payload_val, "");
}
assert(instruction->tmp_ptr != nullptr);
assert(type_has_bits(instruction->type));
LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, "");
LLVMValueRef val_ptr = LLVMBuildStructGEP(g->builder, instruction->tmp_ptr, maybe_child_index, "");
gen_assign_raw(g, val_ptr, get_pointer_to_type(g, instruction->type, false), payload_val);
LLVMValueRef success_bit = LLVMBuildExtractValue(g->builder, result_val, 1, "");
LLVMValueRef nonnull_bit = LLVMBuildNot(g->builder, success_bit, "");
LLVMValueRef maybe_ptr = LLVMBuildStructGEP(g->builder, instruction->tmp_ptr, maybe_null_index, "");
gen_store_untyped(g, nonnull_bit, maybe_ptr, 0, false);
return instruction->tmp_ptr;
}
static LLVMValueRef ir_render_fence(CodeGen *g, IrExecutable *executable, IrInstructionFence *instruction) {
@ -4296,6 +4324,16 @@ static LLVMValueRef ir_render_atomic_rmw(CodeGen *g, IrExecutable *executable,
return LLVMBuildIntToPtr(g->builder, uncasted_result, operand_type->type_ref, "");
}
static LLVMValueRef ir_render_atomic_load(CodeGen *g, IrExecutable *executable,
IrInstructionAtomicLoad *instruction)
{
LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->resolved_ordering);
LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
LLVMValueRef load_inst = gen_load(g, ptr, instruction->ptr->value.type, "");
LLVMSetOrdering(load_inst, ordering);
return load_inst;
}
static LLVMValueRef ir_render_merge_err_ret_traces(CodeGen *g, IrExecutable *executable,
IrInstructionMergeErrRetTraces *instruction)
{
@ -4317,6 +4355,13 @@ static LLVMValueRef ir_render_mark_err_ret_trace_ptr(CodeGen *g, IrExecutable *e
return nullptr;
}
static LLVMValueRef ir_render_sqrt(CodeGen *g, IrExecutable *executable, IrInstructionSqrt *instruction) {
LLVMValueRef op = ir_llvm_value(g, instruction->op);
assert(instruction->base.value.type->id == TypeTableEntryIdFloat);
LLVMValueRef fn_val = get_float_fn(g, instruction->base.value.type, ZigLLVMFnIdSqrt);
return LLVMBuildCall(g->builder, fn_val, &op, 1, "");
}
static void set_debug_location(CodeGen *g, IrInstruction *instruction) {
AstNode *source_node = instruction->source_node;
Scope *scope = instruction->scope;
@ -4532,12 +4577,16 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable,
return ir_render_coro_alloc_helper(g, executable, (IrInstructionCoroAllocHelper *)instruction);
case IrInstructionIdAtomicRmw:
return ir_render_atomic_rmw(g, executable, (IrInstructionAtomicRmw *)instruction);
case IrInstructionIdAtomicLoad:
return ir_render_atomic_load(g, executable, (IrInstructionAtomicLoad *)instruction);
case IrInstructionIdSaveErrRetAddr:
return ir_render_save_err_ret_addr(g, executable, (IrInstructionSaveErrRetAddr *)instruction);
case IrInstructionIdMergeErrRetTraces:
return ir_render_merge_err_ret_traces(g, executable, (IrInstructionMergeErrRetTraces *)instruction);
case IrInstructionIdMarkErrRetTracePtr:
return ir_render_mark_err_ret_trace_ptr(g, executable, (IrInstructionMarkErrRetTracePtr *)instruction);
case IrInstructionIdSqrt:
return ir_render_sqrt(g, executable, (IrInstructionSqrt *)instruction);
}
zig_unreachable();
}
@ -5476,6 +5525,9 @@ static void do_code_gen(CodeGen *g) {
} else if (instruction->id == IrInstructionIdErrWrapCode) {
IrInstructionErrWrapCode *err_wrap_code_instruction = (IrInstructionErrWrapCode *)instruction;
slot = &err_wrap_code_instruction->tmp_ptr;
} else if (instruction->id == IrInstructionIdCmpxchg) {
IrInstructionCmpxchg *cmpxchg_instruction = (IrInstructionCmpxchg *)instruction;
slot = &cmpxchg_instruction->tmp_ptr;
} else {
zig_unreachable();
}
@ -5637,10 +5689,12 @@ static void do_code_gen(CodeGen *g) {
os_path_join(g->cache_dir, o_basename, output_path);
ensure_cache_dir(g);
bool is_small = g->build_mode == BuildModeSmallRelease;
switch (g->emit_file_type) {
case EmitFileTypeBinary:
if (ZigLLVMTargetMachineEmitToFile(g->target_machine, g->module, buf_ptr(output_path),
ZigLLVM_EmitBinary, &err_msg, g->build_mode == BuildModeDebug))
ZigLLVM_EmitBinary, &err_msg, g->build_mode == BuildModeDebug, is_small))
{
zig_panic("unable to write object file %s: %s", buf_ptr(output_path), err_msg);
}
@ -5650,7 +5704,7 @@ static void do_code_gen(CodeGen *g) {
case EmitFileTypeAssembly:
if (ZigLLVMTargetMachineEmitToFile(g->target_machine, g->module, buf_ptr(output_path),
ZigLLVM_EmitAssembly, &err_msg, g->build_mode == BuildModeDebug))
ZigLLVM_EmitAssembly, &err_msg, g->build_mode == BuildModeDebug, is_small))
{
zig_panic("unable to write assembly file %s: %s", buf_ptr(output_path), err_msg);
}
@ -5659,7 +5713,7 @@ static void do_code_gen(CodeGen *g) {
case EmitFileTypeLLVMIr:
if (ZigLLVMTargetMachineEmitToFile(g->target_machine, g->module, buf_ptr(output_path),
ZigLLVM_EmitLLVMIr, &err_msg, g->build_mode == BuildModeDebug))
ZigLLVM_EmitLLVMIr, &err_msg, g->build_mode == BuildModeDebug, is_small))
{
zig_panic("unable to write llvm-ir file %s: %s", buf_ptr(output_path), err_msg);
}
@ -5985,6 +6039,7 @@ static void define_builtin_fns(CodeGen *g) {
create_builtin_fn(g, BuiltinFnIdMemberCount, "memberCount", 1);
create_builtin_fn(g, BuiltinFnIdMemberType, "memberType", 2);
create_builtin_fn(g, BuiltinFnIdMemberName, "memberName", 2);
create_builtin_fn(g, BuiltinFnIdField, "field", 2);
create_builtin_fn(g, BuiltinFnIdTypeof, "typeOf", 1); // TODO rename to TypeOf
create_builtin_fn(g, BuiltinFnIdAddWithOverflow, "addWithOverflow", 4);
create_builtin_fn(g, BuiltinFnIdSubWithOverflow, "subWithOverflow", 4);
@ -6001,7 +6056,8 @@ static void define_builtin_fns(CodeGen *g) {
create_builtin_fn(g, BuiltinFnIdTypeName, "typeName", 1);
create_builtin_fn(g, BuiltinFnIdCanImplicitCast, "canImplicitCast", 2);
create_builtin_fn(g, BuiltinFnIdEmbedFile, "embedFile", 1);
create_builtin_fn(g, BuiltinFnIdCmpExchange, "cmpxchg", 5);
create_builtin_fn(g, BuiltinFnIdCmpxchgWeak, "cmpxchgWeak", 6);
create_builtin_fn(g, BuiltinFnIdCmpxchgStrong, "cmpxchgStrong", 6);
create_builtin_fn(g, BuiltinFnIdFence, "fence", 1);
create_builtin_fn(g, BuiltinFnIdTruncate, "truncate", 2);
create_builtin_fn(g, BuiltinFnIdCompileErr, "compileError", 1);
@ -6024,6 +6080,7 @@ static void define_builtin_fns(CodeGen *g) {
create_builtin_fn(g, BuiltinFnIdDivFloor, "divFloor", 2);
create_builtin_fn(g, BuiltinFnIdRem, "rem", 2);
create_builtin_fn(g, BuiltinFnIdMod, "mod", 2);
create_builtin_fn(g, BuiltinFnIdSqrt, "sqrt", 2);
create_builtin_fn(g, BuiltinFnIdInlineCall, "inlineCall", SIZE_MAX);
create_builtin_fn(g, BuiltinFnIdNoInlineCall, "noInlineCall", SIZE_MAX);
create_builtin_fn(g, BuiltinFnIdTypeId, "typeId", 1);
@ -6037,6 +6094,7 @@ static void define_builtin_fns(CodeGen *g) {
create_builtin_fn(g, BuiltinFnIdExport, "export", 3);
create_builtin_fn(g, BuiltinFnIdErrorReturnTrace, "errorReturnTrace", 0);
create_builtin_fn(g, BuiltinFnIdAtomicRmw, "atomicRmw", 5);
create_builtin_fn(g, BuiltinFnIdAtomicLoad, "atomicLoad", 3);
}
static const char *bool_to_str(bool b) {
@ -6048,6 +6106,7 @@ static const char *build_mode_to_str(BuildMode build_mode) {
case BuildModeDebug: return "Mode.Debug";
case BuildModeSafeRelease: return "Mode.ReleaseSafe";
case BuildModeFastRelease: return "Mode.ReleaseFast";
case BuildModeSmallRelease: return "Mode.ReleaseSmall";
}
zig_unreachable();
}
@ -6188,6 +6247,7 @@ static void define_builtin_compile_vars(CodeGen *g) {
" Debug,\n"
" ReleaseSafe,\n"
" ReleaseFast,\n"
" ReleaseSmall,\n"
"};\n\n");
}
{
@ -6238,7 +6298,8 @@ static void define_builtin_compile_vars(CodeGen *g) {
int err;
Buf *abs_full_path = buf_alloc();
if ((err = os_path_real(builtin_zig_path, abs_full_path))) {
zig_panic("unable to open '%s': %s", buf_ptr(builtin_zig_path), err_str(err));
fprintf(stderr, "unable to open '%s': %s", buf_ptr(builtin_zig_path), err_str(err));
exit(1);
}
assert(g->root_package);
@ -6358,7 +6419,7 @@ static void init(CodeGen *g) {
}
}
g->have_err_ret_tracing = g->build_mode != BuildModeFastRelease;
g->have_err_ret_tracing = g->build_mode != BuildModeFastRelease && g->build_mode != BuildModeSmallRelease;
define_builtin_fns(g);
define_builtin_compile_vars(g);
@ -6492,12 +6553,14 @@ static void gen_root_source(CodeGen *g) {
Buf *abs_full_path = buf_alloc();
int err;
if ((err = os_path_real(rel_full_path, abs_full_path))) {
zig_panic("unable to open '%s': %s", buf_ptr(rel_full_path), err_str(err));
fprintf(stderr, "unable to open '%s': %s", buf_ptr(rel_full_path), err_str(err));
exit(1);
}
Buf *source_code = buf_alloc();
if ((err = os_fetch_file_path(rel_full_path, source_code, true))) {
zig_panic("unable to open '%s': %s", buf_ptr(rel_full_path), err_str(err));
fprintf(stderr, "unable to open '%s': %s", buf_ptr(rel_full_path), err_str(err));
exit(1);
}
g->root_import = add_source_file(g, g->root_package, abs_full_path, source_code);
@ -7050,4 +7113,3 @@ PackageTableEntry *codegen_create_package(CodeGen *g, const char *root_src_dir,
}
return pkg;
}

File diff suppressed because it is too large Load Diff

View File

@ -358,9 +358,18 @@ static void ir_print_ptr_type_child(IrPrint *irp, IrInstructionPtrTypeChild *ins
}
static void ir_print_field_ptr(IrPrint *irp, IrInstructionFieldPtr *instruction) {
fprintf(irp->f, "fieldptr ");
ir_print_other_instruction(irp, instruction->container_ptr);
fprintf(irp->f, ".%s", buf_ptr(instruction->field_name));
if (instruction->field_name_buffer) {
fprintf(irp->f, "fieldptr ");
ir_print_other_instruction(irp, instruction->container_ptr);
fprintf(irp->f, ".%s", buf_ptr(instruction->field_name_buffer));
} else {
assert(instruction->field_name_expr);
fprintf(irp->f, "@field(");
ir_print_other_instruction(irp, instruction->container_ptr);
fprintf(irp->f, ", ");
ir_print_other_instruction(irp, instruction->field_name_expr);
fprintf(irp->f, ")");
}
}
static void ir_print_struct_field_ptr(IrPrint *irp, IrInstructionStructFieldPtr *instruction) {
@ -1172,6 +1181,24 @@ static void ir_print_atomic_rmw(IrPrint *irp, IrInstructionAtomicRmw *instructio
fprintf(irp->f, ")");
}
static void ir_print_atomic_load(IrPrint *irp, IrInstructionAtomicLoad *instruction) {
fprintf(irp->f, "@atomicLoad(");
if (instruction->operand_type != nullptr) {
ir_print_other_instruction(irp, instruction->operand_type);
} else {
fprintf(irp->f, "[TODO print]");
}
fprintf(irp->f, ",");
ir_print_other_instruction(irp, instruction->ptr);
fprintf(irp->f, ",");
if (instruction->ordering != nullptr) {
ir_print_other_instruction(irp, instruction->ordering);
} else {
fprintf(irp->f, "[TODO print]");
}
fprintf(irp->f, ")");
}
static void ir_print_await_bookkeeping(IrPrint *irp, IrInstructionAwaitBookkeeping *instruction) {
fprintf(irp->f, "@awaitBookkeeping(");
ir_print_other_instruction(irp, instruction->promise_result_type);
@ -1204,6 +1231,18 @@ static void ir_print_mark_err_ret_trace_ptr(IrPrint *irp, IrInstructionMarkErrRe
fprintf(irp->f, ")");
}
static void ir_print_sqrt(IrPrint *irp, IrInstructionSqrt *instruction) {
fprintf(irp->f, "@sqrt(");
if (instruction->type != nullptr) {
ir_print_other_instruction(irp, instruction->type);
} else {
fprintf(irp->f, "null");
}
fprintf(irp->f, ",");
ir_print_other_instruction(irp, instruction->op);
fprintf(irp->f, ")");
}
static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {
ir_print_prefix(irp, instruction);
switch (instruction->id) {
@ -1590,6 +1629,12 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {
case IrInstructionIdMarkErrRetTracePtr:
ir_print_mark_err_ret_trace_ptr(irp, (IrInstructionMarkErrRetTracePtr *)instruction);
break;
case IrInstructionIdSqrt:
ir_print_sqrt(irp, (IrInstructionSqrt *)instruction);
break;
case IrInstructionIdAtomicLoad:
ir_print_atomic_load(irp, (IrInstructionAtomicLoad *)instruction);
break;
}
fprintf(irp->f, "\n");
}

View File

@ -217,6 +217,9 @@ static void construct_linker_job_elf(LinkJob *lj) {
lj->args.append(g->linker_script);
}
if (g->no_rosegment_workaround) {
lj->args.append("--no-rosegment");
}
lj->args.append("--gc-sections");
lj->args.append("-m");

View File

@ -43,6 +43,7 @@ static int usage(const char *arg0) {
" --pkg-end pop current pkg\n"
" --release-fast build with optimizations on and safety off\n"
" --release-safe build with optimizations on and safety on\n"
" --release-small build with size optimizations on and safety off\n"
" --static output will be statically linked\n"
" --strip exclude debug symbols\n"
" --target-arch [name] specify target architecture\n"
@ -54,7 +55,6 @@ static int usage(const char *arg0) {
" --verbose-ir turn on compiler debug output for Zig IR\n"
" --verbose-llvm-ir turn on compiler debug output for LLVM IR\n"
" --verbose-cimport turn on compiler debug output for C imports\n"
" --zig-install-prefix [path] override directory where zig thinks it is installed\n"
" -dirafter [dir] same as -isystem but do it last\n"
" -isystem [dir] add additional search path for other .h files\n"
" -mllvm [arg] additional arguments to forward to LLVM's option processing\n"
@ -74,6 +74,7 @@ static int usage(const char *arg0) {
" -L[dir] alias for --library-path\n"
" -rdynamic add all symbols to the dynamic symbol table\n"
" -rpath [path] add directory to the runtime library search path\n"
" --no-rosegment compromise security to workaround valgrind bug\n"
" -mconsole (windows) --subsystem console to the linker\n"
" -mwindows (windows) --subsystem windows to the linker\n"
" -framework [name] (darwin) link against framework\n"
@ -177,6 +178,7 @@ static int find_zig_lib_dir(Buf *out_path) {
int err;
Buf self_exe_path = BUF_INIT;
buf_resize(&self_exe_path, 0);
if (!(err = os_self_exe_path(&self_exe_path))) {
Buf *cur_path = &self_exe_path;
@ -199,23 +201,14 @@ static int find_zig_lib_dir(Buf *out_path) {
return ErrorFileNotFound;
}
static Buf *resolve_zig_lib_dir(const char *zig_install_prefix_arg) {
static Buf *resolve_zig_lib_dir(void) {
int err;
Buf *result = buf_alloc();
if (zig_install_prefix_arg == nullptr) {
if ((err = find_zig_lib_dir(result))) {
fprintf(stderr, "Unable to find zig lib directory. Reinstall Zig or use --zig-install-prefix.\n");
exit(EXIT_FAILURE);
}
return result;
if ((err = find_zig_lib_dir(result))) {
fprintf(stderr, "Unable to find zig lib directory\n");
exit(EXIT_FAILURE);
}
Buf *zig_lib_dir_buf = buf_create_from_str(zig_install_prefix_arg);
if (test_zig_install_prefix(zig_lib_dir_buf, result)) {
return result;
}
fprintf(stderr, "No Zig installation found at prefix: %s\n", zig_install_prefix_arg);
exit(EXIT_FAILURE);
return result;
}
enum Cmd {
@ -299,7 +292,6 @@ int main(int argc, char **argv) {
const char *libc_include_dir = nullptr;
const char *msvc_lib_dir = nullptr;
const char *kernel32_lib_dir = nullptr;
const char *zig_install_prefix = nullptr;
const char *dynamic_linker = nullptr;
ZigList<const char *> clang_argv = {0};
ZigList<const char *> llvm_argv = {0};
@ -333,6 +325,7 @@ int main(int argc, char **argv) {
ZigList<const char *> test_exec_args = {0};
int comptime_args_end = 0;
int runtime_args_start = argc;
bool no_rosegment_workaround = false;
if (argc >= 2 && strcmp(argv[1], "build") == 0) {
const char *zig_exe_path = arg0;
@ -359,17 +352,12 @@ int main(int argc, char **argv) {
} else if (i + 1 < argc && strcmp(argv[i], "--cache-dir") == 0) {
cache_dir = argv[i + 1];
i += 1;
} else if (i + 1 < argc && strcmp(argv[i], "--zig-install-prefix") == 0) {
args.append(argv[i]);
i += 1;
zig_install_prefix = argv[i];
args.append(zig_install_prefix);
} else {
args.append(argv[i]);
}
}
Buf *zig_lib_dir_buf = resolve_zig_lib_dir(zig_install_prefix);
Buf *zig_lib_dir_buf = resolve_zig_lib_dir();
Buf *zig_std_dir = buf_alloc();
os_path_join(zig_lib_dir_buf, buf_create_from_str("std"), zig_std_dir);
@ -497,6 +485,8 @@ int main(int argc, char **argv) {
build_mode = BuildModeFastRelease;
} else if (strcmp(arg, "--release-safe") == 0) {
build_mode = BuildModeSafeRelease;
} else if (strcmp(arg, "--release-small") == 0) {
build_mode = BuildModeSmallRelease;
} else if (strcmp(arg, "--strip") == 0) {
strip = true;
} else if (strcmp(arg, "--static") == 0) {
@ -519,6 +509,8 @@ int main(int argc, char **argv) {
mconsole = true;
} else if (strcmp(arg, "-rdynamic") == 0) {
rdynamic = true;
} else if (strcmp(arg, "--no-rosegment") == 0) {
no_rosegment_workaround = true;
} else if (strcmp(arg, "--each-lib-rpath") == 0) {
each_lib_rpath = true;
} else if (strcmp(arg, "--enable-timing-info") == 0) {
@ -590,8 +582,6 @@ int main(int argc, char **argv) {
msvc_lib_dir = argv[i];
} else if (strcmp(arg, "--kernel32-lib-dir") == 0) {
kernel32_lib_dir = argv[i];
} else if (strcmp(arg, "--zig-install-prefix") == 0) {
zig_install_prefix = argv[i];
} else if (strcmp(arg, "--dynamic-linker") == 0) {
dynamic_linker = argv[i];
} else if (strcmp(arg, "-isystem") == 0) {
@ -803,7 +793,7 @@ int main(int argc, char **argv) {
full_cache_dir);
}
Buf *zig_lib_dir_buf = resolve_zig_lib_dir(zig_install_prefix);
Buf *zig_lib_dir_buf = resolve_zig_lib_dir();
CodeGen *g = codegen_create(zig_root_source_file, target, out_type, build_mode, zig_lib_dir_buf);
codegen_set_out_name(g, buf_out_name);
@ -858,6 +848,7 @@ int main(int argc, char **argv) {
codegen_set_windows_subsystem(g, mwindows, mconsole);
codegen_set_rdynamic(g, rdynamic);
g->no_rosegment_workaround = no_rosegment_workaround;
if (mmacosx_version_min && mios_version_min) {
fprintf(stderr, "-mmacosx-version-min and -mios-version-min options not allowed together\n");
return EXIT_FAILURE;

View File

@ -1007,6 +1007,7 @@ int os_self_exe_path(Buf *out_path) {
buf_resize(out_path, buf_len(out_path) * 2);
continue;
}
buf_resize(out_path, amt);
return 0;
}
#endif

View File

@ -648,12 +648,30 @@ static AstNode *ast_parse_asm_expr(ParseContext *pc, size_t *token_index, bool m
}
/*
SuspendExpression(body) = "suspend" "|" Symbol "|" body
SuspendExpression(body) = option(Symbol ":") "suspend" option(("|" Symbol "|" body))
*/
static AstNode *ast_parse_suspend_block(ParseContext *pc, size_t *token_index, bool mandatory) {
size_t orig_token_index = *token_index;
Token *suspend_token = &pc->tokens->at(*token_index);
Token *name_token = nullptr;
Token *token = &pc->tokens->at(*token_index);
if (token->id == TokenIdSymbol) {
*token_index += 1;
Token *colon_token = &pc->tokens->at(*token_index);
if (colon_token->id == TokenIdColon) {
*token_index += 1;
name_token = token;
token = &pc->tokens->at(*token_index);
} else if (mandatory) {
ast_expect_token(pc, colon_token, TokenIdColon);
zig_unreachable();
} else {
*token_index = orig_token_index;
return nullptr;
}
}
Token *suspend_token = token;
if (suspend_token->id == TokenIdKeywordSuspend) {
*token_index += 1;
} else if (mandatory) {
@ -675,6 +693,9 @@ static AstNode *ast_parse_suspend_block(ParseContext *pc, size_t *token_index, b
}
AstNode *node = ast_create_node(pc, NodeTypeSuspend, suspend_token);
if (name_token != nullptr) {
node->data.suspend.name = token_buf(name_token);
}
node->data.suspend.promise_symbol = ast_parse_symbol(pc, token_index);
ast_eat_token(pc, token_index, TokenIdBinOr);
node->data.suspend.block = ast_parse_block(pc, token_index, true);

View File

@ -82,7 +82,7 @@ static const bool assertions_on = false;
#endif
bool ZigLLVMTargetMachineEmitToFile(LLVMTargetMachineRef targ_machine_ref, LLVMModuleRef module_ref,
const char *filename, ZigLLVM_EmitOutputType output_type, char **error_message, bool is_debug)
const char *filename, ZigLLVM_EmitOutputType output_type, char **error_message, bool is_debug, bool is_small)
{
std::error_code EC;
raw_fd_ostream dest(filename, EC, sys::fs::F_None);
@ -101,7 +101,7 @@ bool ZigLLVMTargetMachineEmitToFile(LLVMTargetMachineRef targ_machine_ref, LLVMM
return true;
}
PMBuilder->OptLevel = target_machine->getOptLevel();
PMBuilder->SizeLevel = 0;
PMBuilder->SizeLevel = is_small ? 2 : 0;
PMBuilder->DisableTailCalls = is_debug;
PMBuilder->DisableUnitAtATime = is_debug;
@ -780,10 +780,12 @@ static AtomicOrdering mapFromLLVMOrdering(LLVMAtomicOrdering Ordering) {
LLVMValueRef ZigLLVMBuildCmpXchg(LLVMBuilderRef builder, LLVMValueRef ptr, LLVMValueRef cmp,
LLVMValueRef new_val, LLVMAtomicOrdering success_ordering,
LLVMAtomicOrdering failure_ordering)
LLVMAtomicOrdering failure_ordering, bool is_weak)
{
return wrap(unwrap(builder)->CreateAtomicCmpXchg(unwrap(ptr), unwrap(cmp), unwrap(new_val),
mapFromLLVMOrdering(success_ordering), mapFromLLVMOrdering(failure_ordering)));
AtomicCmpXchgInst *inst = unwrap(builder)->CreateAtomicCmpXchg(unwrap(ptr), unwrap(cmp),
unwrap(new_val), mapFromLLVMOrdering(success_ordering), mapFromLLVMOrdering(failure_ordering));
inst->setWeak(is_weak);
return wrap(inst);
}
LLVMValueRef ZigLLVMBuildNSWShl(LLVMBuilderRef builder, LLVMValueRef LHS, LLVMValueRef RHS,

View File

@ -52,7 +52,7 @@ enum ZigLLVM_EmitOutputType {
};
ZIG_EXTERN_C bool ZigLLVMTargetMachineEmitToFile(LLVMTargetMachineRef targ_machine_ref, LLVMModuleRef module_ref,
const char *filename, enum ZigLLVM_EmitOutputType output_type, char **error_message, bool is_debug);
const char *filename, enum ZigLLVM_EmitOutputType output_type, char **error_message, bool is_debug, bool is_small);
ZIG_EXTERN_C LLVMTypeRef ZigLLVMTokenTypeInContext(LLVMContextRef context_ref);
@ -72,7 +72,7 @@ ZIG_EXTERN_C LLVMValueRef ZigLLVMBuildMemSet(LLVMBuilderRef B, LLVMValueRef Ptr,
ZIG_EXTERN_C LLVMValueRef ZigLLVMBuildCmpXchg(LLVMBuilderRef builder, LLVMValueRef ptr, LLVMValueRef cmp,
LLVMValueRef new_val, LLVMAtomicOrdering success_ordering,
LLVMAtomicOrdering failure_ordering);
LLVMAtomicOrdering failure_ordering, bool is_weak);
ZIG_EXTERN_C LLVMValueRef ZigLLVMBuildNSWShl(LLVMBuilderRef builder, LLVMValueRef LHS, LLVMValueRef RHS,
const char *name);

View File

@ -426,15 +426,18 @@ pub const Builder = struct {
const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") ?? false;
const release_fast = self.option(bool, "release-fast", "optimizations on and safety off") ?? false;
const release_small = self.option(bool, "release-small", "size optimizations on and safety off") ?? false;
const mode = if (release_safe and !release_fast)
const mode = if (release_safe and !release_fast and !release_small)
builtin.Mode.ReleaseSafe
else if (release_fast and !release_safe)
else if (release_fast and !release_safe and !release_small)
builtin.Mode.ReleaseFast
else if (!release_fast and !release_safe)
else if (release_small and !release_fast and !release_safe)
builtin.Mode.ReleaseSmall
else if (!release_fast and !release_safe and !release_small)
builtin.Mode.Debug
else x: {
warn("Both -Drelease-safe and -Drelease-fast specified");
warn("Multiple release modes (of -Drelease-safe, -Drelease-fast and -Drelease-small)");
self.markInvalidUserInput();
break :x builtin.Mode.Debug;
};
@ -1229,6 +1232,7 @@ pub const LibExeObjStep = struct {
builtin.Mode.Debug => {},
builtin.Mode.ReleaseSafe => zig_args.append("--release-safe") catch unreachable,
builtin.Mode.ReleaseFast => zig_args.append("--release-fast") catch unreachable,
builtin.Mode.ReleaseSmall => zig_args.append("--release-small") catch unreachable,
}
zig_args.append("--cache-dir") catch unreachable;
@ -1369,7 +1373,7 @@ pub const LibExeObjStep = struct {
args.append("ssp-buffer-size=4") catch unreachable;
}
},
builtin.Mode.ReleaseFast => {
builtin.Mode.ReleaseFast, builtin.Mode.ReleaseSmall => {
args.append("-O2") catch unreachable;
args.append("-fno-stack-protector") catch unreachable;
},
@ -1706,6 +1710,7 @@ pub const TestStep = struct {
builtin.Mode.Debug => {},
builtin.Mode.ReleaseSafe => try zig_args.append("--release-safe"),
builtin.Mode.ReleaseFast => try zig_args.append("--release-fast"),
builtin.Mode.ReleaseSmall => try zig_args.append("--release-small"),
}
switch (self.target) {

View File

@ -3,10 +3,28 @@ pub extern "c" fn _NSGetExecutablePath(buf: &u8, bufsize: &u32) c_int;
pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: &u8, buf_len: usize, basep: &i64) usize;
pub extern "c" fn mach_absolute_time() u64;
pub extern "c" fn mach_timebase_info(tinfo: ?&mach_timebase_info_data) void;
pub use @import("../os/darwin_errno.zig");
pub const _errno = __error;
pub const timeval = extern struct {
tv_sec: isize,
tv_usec: isize,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const mach_timebase_info_data = struct {
numer: u32,
denom: u32,
};
/// Renamed to Stat to not conflict with the stat function.
pub const Stat = extern struct {
dev: i32,

View File

@ -28,6 +28,7 @@ pub extern "c" fn unlink(path: &const u8) c_int;
pub extern "c" fn getcwd(buf: &u8, size: usize) ?&u8;
pub extern "c" fn waitpid(pid: c_int, stat_loc: &c_int, options: c_int) c_int;
pub extern "c" fn fork() c_int;
pub extern "c" fn access(path: &const u8, mode: c_uint) c_int;
pub extern "c" fn pipe(fds: &c_int) c_int;
pub extern "c" fn mkdir(path: &const u8, mode: c_uint) c_int;
pub extern "c" fn symlink(existing: &const u8, new: &const u8) c_int;
@ -40,6 +41,7 @@ pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int;
pub extern "c" fn readlink(noalias path: &const u8, noalias buf: &u8, bufsize: usize) isize;
pub extern "c" fn realpath(noalias file_name: &const u8, noalias resolved_name: &u8) ?&u8;
pub extern "c" fn sigprocmask(how: c_int, noalias set: &const sigset_t, noalias oset: ?&sigset_t) c_int;
pub extern "c" fn gettimeofday(tv: ?&timeval, tz: ?&timezone) c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias oact: ?&Sigaction) c_int;
pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?&timespec) c_int;
pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int;

View File

@ -1,22 +1,17 @@
// Modify the HashFunction variable to the one wanted to test.
//
// NOTE: The throughput measurement may be slightly lower than other measurements since we run
// through our block alignment functions as well. Be aware when comparing against other tests.
//
// ```
// zig build-exe --release-fast --library c throughput_test.zig
// zig build-exe --release-fast throughput_test.zig
// ./throughput_test
// ```
const HashFunction = @import("md5.zig").Md5;
const BytesToHash = 1024 * Mb;
const std = @import("std");
const time = std.os.time;
const Timer = time.Timer;
const HashFunction = @import("md5.zig").Md5;
const c = @cImport({
@cInclude("time.h");
});
const Mb = 1024 * 1024;
const MiB = 1024 * 1024;
const BytesToHash = 1024 * MiB;
pub fn main() !void {
var stdout_file = try std.io.getStdOut();
@ -29,15 +24,15 @@ pub fn main() !void {
var h = HashFunction.init();
var offset: usize = 0;
const start = c.clock();
var timer = try Timer.start();
const start = timer.lap();
while (offset < BytesToHash) : (offset += block.len) {
h.update(block[0..]);
}
const end = c.clock();
const end = timer.read();
const elapsed_s = f64((end - start) * c.CLOCKS_PER_SEC) / 1000000;
const elapsed_s = f64(end - start) / time.ns_per_s;
const throughput = u64(BytesToHash / elapsed_s);
try stdout.print("{}: ", @typeName(HashFunction));
try stdout.print("{} Mb/s\n", throughput);
try stdout.print("{}: {} MiB/s\n", @typeName(HashFunction), throughput / (1 * MiB));
}

View File

@ -38,7 +38,7 @@ pub fn getSelfDebugInfo() !&ElfStackTrace {
if (self_debug_info) |info| {
return info;
} else {
const info = try openSelfDebugInfo(global_allocator);
const info = try openSelfDebugInfo(getDebugInfoAllocator());
self_debug_info = info;
return info;
}
@ -51,7 +51,7 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return;
return;
};
writeCurrentStackTrace(stderr, global_allocator, debug_info, stderr_file.isTty(), start_addr) catch |err| {
writeCurrentStackTrace(stderr, getDebugInfoAllocator(), debug_info, stderr_file.isTty(), start_addr) catch |err| {
stderr.print("Unable to dump stack trace: {}\n", @errorName(err)) catch return;
return;
};
@ -64,7 +64,7 @@ pub fn dumpStackTrace(stack_trace: &const builtin.StackTrace) void {
stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return;
return;
};
writeStackTrace(stack_trace, stderr, global_allocator, debug_info, stderr_file.isTty()) catch |err| {
writeStackTrace(stack_trace, stderr, getDebugInfoAllocator(), debug_info, stderr_file.isTty()) catch |err| {
stderr.print("Unable to dump stack trace: {}\n", @errorName(err)) catch return;
return;
};
@ -592,8 +592,8 @@ fn getString(st: &ElfStackTrace, offset: u64) ![]u8 {
}
fn readAllocBytes(allocator: &mem.Allocator, in_stream: var, size: usize) ![]u8 {
const buf = try global_allocator.alloc(u8, size);
errdefer global_allocator.free(buf);
const buf = try allocator.alloc(u8, size);
errdefer allocator.free(buf);
if ((try in_stream.read(buf)) < size) return error.EndOfFile;
return buf;
}
@ -1126,6 +1126,21 @@ fn readILeb128(in_stream: var) !i64 {
}
}
/// This should only be used in temporary test programs.
pub const global_allocator = &global_fixed_allocator.allocator;
var global_fixed_allocator = std.heap.FixedBufferAllocator.init(global_allocator_mem[0..]);
var global_allocator_mem: [100 * 1024]u8 = undefined;
// TODO make thread safe
var debug_info_allocator: ?&mem.Allocator = null;
var debug_info_direct_allocator: std.heap.DirectAllocator = undefined;
var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined;
fn getDebugInfoAllocator() &mem.Allocator {
if (debug_info_allocator) |a| return a;
debug_info_direct_allocator = std.heap.DirectAllocator.init();
debug_info_arena_allocator = std.heap.ArenaAllocator.init(&debug_info_direct_allocator.allocator);
debug_info_allocator = &debug_info_arena_allocator.allocator;
return &debug_info_arena_allocator.allocator;
}

View File

@ -7,6 +7,246 @@ const mem = std.mem;
const debug = std.debug;
const InStream = std.stream.InStream;
pub const AT_NULL = 0;
pub const AT_IGNORE = 1;
pub const AT_EXECFD = 2;
pub const AT_PHDR = 3;
pub const AT_PHENT = 4;
pub const AT_PHNUM = 5;
pub const AT_PAGESZ = 6;
pub const AT_BASE = 7;
pub const AT_FLAGS = 8;
pub const AT_ENTRY = 9;
pub const AT_NOTELF = 10;
pub const AT_UID = 11;
pub const AT_EUID = 12;
pub const AT_GID = 13;
pub const AT_EGID = 14;
pub const AT_CLKTCK = 17;
pub const AT_PLATFORM = 15;
pub const AT_HWCAP = 16;
pub const AT_FPUCW = 18;
pub const AT_DCACHEBSIZE = 19;
pub const AT_ICACHEBSIZE = 20;
pub const AT_UCACHEBSIZE = 21;
pub const AT_IGNOREPPC = 22;
pub const AT_SECURE = 23;
pub const AT_BASE_PLATFORM = 24;
pub const AT_RANDOM = 25;
pub const AT_HWCAP2 = 26;
pub const AT_EXECFN = 31;
pub const AT_SYSINFO = 32;
pub const AT_SYSINFO_EHDR = 33;
pub const AT_L1I_CACHESHAPE = 34;
pub const AT_L1D_CACHESHAPE = 35;
pub const AT_L2_CACHESHAPE = 36;
pub const AT_L3_CACHESHAPE = 37;
pub const AT_L1I_CACHESIZE = 40;
pub const AT_L1I_CACHEGEOMETRY = 41;
pub const AT_L1D_CACHESIZE = 42;
pub const AT_L1D_CACHEGEOMETRY = 43;
pub const AT_L2_CACHESIZE = 44;
pub const AT_L2_CACHEGEOMETRY = 45;
pub const AT_L3_CACHESIZE = 46;
pub const AT_L3_CACHEGEOMETRY = 47;
pub const DT_NULL = 0;
pub const DT_NEEDED = 1;
pub const DT_PLTRELSZ = 2;
pub const DT_PLTGOT = 3;
pub const DT_HASH = 4;
pub const DT_STRTAB = 5;
pub const DT_SYMTAB = 6;
pub const DT_RELA = 7;
pub const DT_RELASZ = 8;
pub const DT_RELAENT = 9;
pub const DT_STRSZ = 10;
pub const DT_SYMENT = 11;
pub const DT_INIT = 12;
pub const DT_FINI = 13;
pub const DT_SONAME = 14;
pub const DT_RPATH = 15;
pub const DT_SYMBOLIC = 16;
pub const DT_REL = 17;
pub const DT_RELSZ = 18;
pub const DT_RELENT = 19;
pub const DT_PLTREL = 20;
pub const DT_DEBUG = 21;
pub const DT_TEXTREL = 22;
pub const DT_JMPREL = 23;
pub const DT_BIND_NOW = 24;
pub const DT_INIT_ARRAY = 25;
pub const DT_FINI_ARRAY = 26;
pub const DT_INIT_ARRAYSZ = 27;
pub const DT_FINI_ARRAYSZ = 28;
pub const DT_RUNPATH = 29;
pub const DT_FLAGS = 30;
pub const DT_ENCODING = 32;
pub const DT_PREINIT_ARRAY = 32;
pub const DT_PREINIT_ARRAYSZ = 33;
pub const DT_SYMTAB_SHNDX = 34;
pub const DT_NUM = 35;
pub const DT_LOOS = 0x6000000d;
pub const DT_HIOS = 0x6ffff000;
pub const DT_LOPROC = 0x70000000;
pub const DT_HIPROC = 0x7fffffff;
pub const DT_PROCNUM = DT_MIPS_NUM;
pub const DT_VALRNGLO = 0x6ffffd00;
pub const DT_GNU_PRELINKED = 0x6ffffdf5;
pub const DT_GNU_CONFLICTSZ = 0x6ffffdf6;
pub const DT_GNU_LIBLISTSZ = 0x6ffffdf7;
pub const DT_CHECKSUM = 0x6ffffdf8;
pub const DT_PLTPADSZ = 0x6ffffdf9;
pub const DT_MOVEENT = 0x6ffffdfa;
pub const DT_MOVESZ = 0x6ffffdfb;
pub const DT_FEATURE_1 = 0x6ffffdfc;
pub const DT_POSFLAG_1 = 0x6ffffdfd;
pub const DT_SYMINSZ = 0x6ffffdfe;
pub const DT_SYMINENT = 0x6ffffdff;
pub const DT_VALRNGHI = 0x6ffffdff;
pub const DT_VALNUM = 12;
pub const DT_ADDRRNGLO = 0x6ffffe00;
pub const DT_GNU_HASH = 0x6ffffef5;
pub const DT_TLSDESC_PLT = 0x6ffffef6;
pub const DT_TLSDESC_GOT = 0x6ffffef7;
pub const DT_GNU_CONFLICT = 0x6ffffef8;
pub const DT_GNU_LIBLIST = 0x6ffffef9;
pub const DT_CONFIG = 0x6ffffefa;
pub const DT_DEPAUDIT = 0x6ffffefb;
pub const DT_AUDIT = 0x6ffffefc;
pub const DT_PLTPAD = 0x6ffffefd;
pub const DT_MOVETAB = 0x6ffffefe;
pub const DT_SYMINFO = 0x6ffffeff;
pub const DT_ADDRRNGHI = 0x6ffffeff;
pub const DT_ADDRNUM = 11;
pub const DT_VERSYM = 0x6ffffff0;
pub const DT_RELACOUNT = 0x6ffffff9;
pub const DT_RELCOUNT = 0x6ffffffa;
pub const DT_FLAGS_1 = 0x6ffffffb;
pub const DT_VERDEF = 0x6ffffffc;
pub const DT_VERDEFNUM = 0x6ffffffd;
pub const DT_VERNEED = 0x6ffffffe;
pub const DT_VERNEEDNUM = 0x6fffffff;
pub const DT_VERSIONTAGNUM = 16;
pub const DT_AUXILIARY = 0x7ffffffd;
pub const DT_FILTER = 0x7fffffff;
pub const DT_EXTRANUM = 3;
pub const DT_SPARC_REGISTER = 0x70000001;
pub const DT_SPARC_NUM = 2;
pub const DT_MIPS_RLD_VERSION = 0x70000001;
pub const DT_MIPS_TIME_STAMP = 0x70000002;
pub const DT_MIPS_ICHECKSUM = 0x70000003;
pub const DT_MIPS_IVERSION = 0x70000004;
pub const DT_MIPS_FLAGS = 0x70000005;
pub const DT_MIPS_BASE_ADDRESS = 0x70000006;
pub const DT_MIPS_MSYM = 0x70000007;
pub const DT_MIPS_CONFLICT = 0x70000008;
pub const DT_MIPS_LIBLIST = 0x70000009;
pub const DT_MIPS_LOCAL_GOTNO = 0x7000000a;
pub const DT_MIPS_CONFLICTNO = 0x7000000b;
pub const DT_MIPS_LIBLISTNO = 0x70000010;
pub const DT_MIPS_SYMTABNO = 0x70000011;
pub const DT_MIPS_UNREFEXTNO = 0x70000012;
pub const DT_MIPS_GOTSYM = 0x70000013;
pub const DT_MIPS_HIPAGENO = 0x70000014;
pub const DT_MIPS_RLD_MAP = 0x70000016;
pub const DT_MIPS_DELTA_CLASS = 0x70000017;
pub const DT_MIPS_DELTA_CLASS_NO = 0x70000018;
pub const DT_MIPS_DELTA_INSTANCE = 0x70000019;
pub const DT_MIPS_DELTA_INSTANCE_NO = 0x7000001a;
pub const DT_MIPS_DELTA_RELOC = 0x7000001b;
pub const DT_MIPS_DELTA_RELOC_NO = 0x7000001c;
pub const DT_MIPS_DELTA_SYM = 0x7000001d;
pub const DT_MIPS_DELTA_SYM_NO = 0x7000001e;
pub const DT_MIPS_DELTA_CLASSSYM = 0x70000020;
pub const DT_MIPS_DELTA_CLASSSYM_NO = 0x70000021;
pub const DT_MIPS_CXX_FLAGS = 0x70000022;
pub const DT_MIPS_PIXIE_INIT = 0x70000023;
pub const DT_MIPS_SYMBOL_LIB = 0x70000024;
pub const DT_MIPS_LOCALPAGE_GOTIDX = 0x70000025;
pub const DT_MIPS_LOCAL_GOTIDX = 0x70000026;
pub const DT_MIPS_HIDDEN_GOTIDX = 0x70000027;
pub const DT_MIPS_PROTECTED_GOTIDX = 0x70000028;
pub const DT_MIPS_OPTIONS = 0x70000029;
pub const DT_MIPS_INTERFACE = 0x7000002a;
pub const DT_MIPS_DYNSTR_ALIGN = 0x7000002b;
pub const DT_MIPS_INTERFACE_SIZE = 0x7000002c;
pub const DT_MIPS_RLD_TEXT_RESOLVE_ADDR = 0x7000002d;
pub const DT_MIPS_PERF_SUFFIX = 0x7000002e;
pub const DT_MIPS_COMPACT_SIZE = 0x7000002f;
pub const DT_MIPS_GP_VALUE = 0x70000030;
pub const DT_MIPS_AUX_DYNAMIC = 0x70000031;
pub const DT_MIPS_PLTGOT = 0x70000032;
pub const DT_MIPS_RWPLT = 0x70000034;
pub const DT_MIPS_RLD_MAP_REL = 0x70000035;
pub const DT_MIPS_NUM = 0x36;
pub const DT_ALPHA_PLTRO = (DT_LOPROC + 0);
pub const DT_ALPHA_NUM = 1;
pub const DT_PPC_GOT = (DT_LOPROC + 0);
pub const DT_PPC_OPT = (DT_LOPROC + 1);
pub const DT_PPC_NUM = 2;
pub const DT_PPC64_GLINK = (DT_LOPROC + 0);
pub const DT_PPC64_OPD = (DT_LOPROC + 1);
pub const DT_PPC64_OPDSZ = (DT_LOPROC + 2);
pub const DT_PPC64_OPT = (DT_LOPROC + 3);
pub const DT_PPC64_NUM = 4;
pub const DT_IA_64_PLT_RESERVE = (DT_LOPROC + 0);
pub const DT_IA_64_NUM = 1;
pub const DT_NIOS2_GP = 0x70000002;
pub const PT_NULL = 0;
pub const PT_LOAD = 1;
pub const PT_DYNAMIC = 2;
pub const PT_INTERP = 3;
pub const PT_NOTE = 4;
pub const PT_SHLIB = 5;
pub const PT_PHDR = 6;
pub const PT_TLS = 7;
pub const PT_NUM = 8;
pub const PT_LOOS = 0x60000000;
pub const PT_GNU_EH_FRAME = 0x6474e550;
pub const PT_GNU_STACK = 0x6474e551;
pub const PT_GNU_RELRO = 0x6474e552;
pub const PT_LOSUNW = 0x6ffffffa;
pub const PT_SUNWBSS = 0x6ffffffa;
pub const PT_SUNWSTACK = 0x6ffffffb;
pub const PT_HISUNW = 0x6fffffff;
pub const PT_HIOS = 0x6fffffff;
pub const PT_LOPROC = 0x70000000;
pub const PT_HIPROC = 0x7fffffff;
pub const SHT_NULL = 0;
pub const SHT_PROGBITS = 1;
pub const SHT_SYMTAB = 2;
@ -31,6 +271,45 @@ pub const SHT_HIPROC = 0x7fffffff;
pub const SHT_LOUSER = 0x80000000;
pub const SHT_HIUSER = 0xffffffff;
pub const STB_LOCAL = 0;
pub const STB_GLOBAL = 1;
pub const STB_WEAK = 2;
pub const STB_NUM = 3;
pub const STB_LOOS = 10;
pub const STB_GNU_UNIQUE = 10;
pub const STB_HIOS = 12;
pub const STB_LOPROC = 13;
pub const STB_HIPROC = 15;
pub const STB_MIPS_SPLIT_COMMON = 13;
pub const STT_NOTYPE = 0;
pub const STT_OBJECT = 1;
pub const STT_FUNC = 2;
pub const STT_SECTION = 3;
pub const STT_FILE = 4;
pub const STT_COMMON = 5;
pub const STT_TLS = 6;
pub const STT_NUM = 7;
pub const STT_LOOS = 10;
pub const STT_GNU_IFUNC = 10;
pub const STT_HIOS = 12;
pub const STT_LOPROC = 13;
pub const STT_HIPROC = 15;
pub const STT_SPARC_REGISTER = 13;
pub const STT_PARISC_MILLICODE = 13;
pub const STT_HP_OPAQUE = (STT_LOOS + 0x1);
pub const STT_HP_STUB = (STT_LOOS + 0x2);
pub const STT_ARM_TFUNC = STT_LOPROC;
pub const STT_ARM_16BIT = STT_HIPROC;
pub const VER_FLG_BASE = 0x1;
pub const VER_FLG_WEAK = 0x2;
pub const FileType = enum {
Relocatable,
Executable,
@ -266,3 +545,335 @@ pub const Elf = struct {
try elf.in_file.seekTo(elf_section.offset);
}
};
pub const EI_NIDENT = 16;
pub const Elf32_Half = u16;
pub const Elf64_Half = u16;
pub const Elf32_Word = u32;
pub const Elf32_Sword = i32;
pub const Elf64_Word = u32;
pub const Elf64_Sword = i32;
pub const Elf32_Xword = u64;
pub const Elf32_Sxword = i64;
pub const Elf64_Xword = u64;
pub const Elf64_Sxword = i64;
pub const Elf32_Addr = u32;
pub const Elf64_Addr = u64;
pub const Elf32_Off = u32;
pub const Elf64_Off = u64;
pub const Elf32_Section = u16;
pub const Elf64_Section = u16;
pub const Elf32_Versym = Elf32_Half;
pub const Elf64_Versym = Elf64_Half;
pub const Elf32_Ehdr = extern struct {
e_ident: [EI_NIDENT]u8,
e_type: Elf32_Half,
e_machine: Elf32_Half,
e_version: Elf32_Word,
e_entry: Elf32_Addr,
e_phoff: Elf32_Off,
e_shoff: Elf32_Off,
e_flags: Elf32_Word,
e_ehsize: Elf32_Half,
e_phentsize: Elf32_Half,
e_phnum: Elf32_Half,
e_shentsize: Elf32_Half,
e_shnum: Elf32_Half,
e_shstrndx: Elf32_Half,
};
pub const Elf64_Ehdr = extern struct {
e_ident: [EI_NIDENT]u8,
e_type: Elf64_Half,
e_machine: Elf64_Half,
e_version: Elf64_Word,
e_entry: Elf64_Addr,
e_phoff: Elf64_Off,
e_shoff: Elf64_Off,
e_flags: Elf64_Word,
e_ehsize: Elf64_Half,
e_phentsize: Elf64_Half,
e_phnum: Elf64_Half,
e_shentsize: Elf64_Half,
e_shnum: Elf64_Half,
e_shstrndx: Elf64_Half,
};
pub const Elf32_Shdr = extern struct {
sh_name: Elf32_Word,
sh_type: Elf32_Word,
sh_flags: Elf32_Word,
sh_addr: Elf32_Addr,
sh_offset: Elf32_Off,
sh_size: Elf32_Word,
sh_link: Elf32_Word,
sh_info: Elf32_Word,
sh_addralign: Elf32_Word,
sh_entsize: Elf32_Word,
};
pub const Elf64_Shdr = extern struct {
sh_name: Elf64_Word,
sh_type: Elf64_Word,
sh_flags: Elf64_Xword,
sh_addr: Elf64_Addr,
sh_offset: Elf64_Off,
sh_size: Elf64_Xword,
sh_link: Elf64_Word,
sh_info: Elf64_Word,
sh_addralign: Elf64_Xword,
sh_entsize: Elf64_Xword,
};
pub const Elf32_Chdr = extern struct {
ch_type: Elf32_Word,
ch_size: Elf32_Word,
ch_addralign: Elf32_Word,
};
pub const Elf64_Chdr = extern struct {
ch_type: Elf64_Word,
ch_reserved: Elf64_Word,
ch_size: Elf64_Xword,
ch_addralign: Elf64_Xword,
};
pub const Elf32_Sym = extern struct {
st_name: Elf32_Word,
st_value: Elf32_Addr,
st_size: Elf32_Word,
st_info: u8,
st_other: u8,
st_shndx: Elf32_Section,
};
pub const Elf64_Sym = extern struct {
st_name: Elf64_Word,
st_info: u8,
st_other: u8,
st_shndx: Elf64_Section,
st_value: Elf64_Addr,
st_size: Elf64_Xword,
};
pub const Elf32_Syminfo = extern struct {
si_boundto: Elf32_Half,
si_flags: Elf32_Half,
};
pub const Elf64_Syminfo = extern struct {
si_boundto: Elf64_Half,
si_flags: Elf64_Half,
};
pub const Elf32_Rel = extern struct {
r_offset: Elf32_Addr,
r_info: Elf32_Word,
};
pub const Elf64_Rel = extern struct {
r_offset: Elf64_Addr,
r_info: Elf64_Xword,
};
pub const Elf32_Rela = extern struct {
r_offset: Elf32_Addr,
r_info: Elf32_Word,
r_addend: Elf32_Sword,
};
pub const Elf64_Rela = extern struct {
r_offset: Elf64_Addr,
r_info: Elf64_Xword,
r_addend: Elf64_Sxword,
};
pub const Elf32_Phdr = extern struct {
p_type: Elf32_Word,
p_offset: Elf32_Off,
p_vaddr: Elf32_Addr,
p_paddr: Elf32_Addr,
p_filesz: Elf32_Word,
p_memsz: Elf32_Word,
p_flags: Elf32_Word,
p_align: Elf32_Word,
};
pub const Elf64_Phdr = extern struct {
p_type: Elf64_Word,
p_flags: Elf64_Word,
p_offset: Elf64_Off,
p_vaddr: Elf64_Addr,
p_paddr: Elf64_Addr,
p_filesz: Elf64_Xword,
p_memsz: Elf64_Xword,
p_align: Elf64_Xword,
};
pub const Elf32_Dyn = extern struct {
d_tag: Elf32_Sword,
d_un: extern union {
d_val: Elf32_Word,
d_ptr: Elf32_Addr,
},
};
pub const Elf64_Dyn = extern struct {
d_tag: Elf64_Sxword,
d_un: extern union {
d_val: Elf64_Xword,
d_ptr: Elf64_Addr,
},
};
pub const Elf32_Verdef = extern struct {
vd_version: Elf32_Half,
vd_flags: Elf32_Half,
vd_ndx: Elf32_Half,
vd_cnt: Elf32_Half,
vd_hash: Elf32_Word,
vd_aux: Elf32_Word,
vd_next: Elf32_Word,
};
pub const Elf64_Verdef = extern struct {
vd_version: Elf64_Half,
vd_flags: Elf64_Half,
vd_ndx: Elf64_Half,
vd_cnt: Elf64_Half,
vd_hash: Elf64_Word,
vd_aux: Elf64_Word,
vd_next: Elf64_Word,
};
pub const Elf32_Verdaux = extern struct {
vda_name: Elf32_Word,
vda_next: Elf32_Word,
};
pub const Elf64_Verdaux = extern struct {
vda_name: Elf64_Word,
vda_next: Elf64_Word,
};
pub const Elf32_Verneed = extern struct {
vn_version: Elf32_Half,
vn_cnt: Elf32_Half,
vn_file: Elf32_Word,
vn_aux: Elf32_Word,
vn_next: Elf32_Word,
};
pub const Elf64_Verneed = extern struct {
vn_version: Elf64_Half,
vn_cnt: Elf64_Half,
vn_file: Elf64_Word,
vn_aux: Elf64_Word,
vn_next: Elf64_Word,
};
pub const Elf32_Vernaux = extern struct {
vna_hash: Elf32_Word,
vna_flags: Elf32_Half,
vna_other: Elf32_Half,
vna_name: Elf32_Word,
vna_next: Elf32_Word,
};
pub const Elf64_Vernaux = extern struct {
vna_hash: Elf64_Word,
vna_flags: Elf64_Half,
vna_other: Elf64_Half,
vna_name: Elf64_Word,
vna_next: Elf64_Word,
};
pub const Elf32_auxv_t = extern struct {
a_type: u32,
a_un: extern union {
a_val: u32,
},
};
pub const Elf64_auxv_t = extern struct {
a_type: u64,
a_un: extern union {
a_val: u64,
},
};
pub const Elf32_Nhdr = extern struct {
n_namesz: Elf32_Word,
n_descsz: Elf32_Word,
n_type: Elf32_Word,
};
pub const Elf64_Nhdr = extern struct {
n_namesz: Elf64_Word,
n_descsz: Elf64_Word,
n_type: Elf64_Word,
};
pub const Elf32_Move = extern struct {
m_value: Elf32_Xword,
m_info: Elf32_Word,
m_poffset: Elf32_Word,
m_repeat: Elf32_Half,
m_stride: Elf32_Half,
};
pub const Elf64_Move = extern struct {
m_value: Elf64_Xword,
m_info: Elf64_Xword,
m_poffset: Elf64_Xword,
m_repeat: Elf64_Half,
m_stride: Elf64_Half,
};
pub const Elf32_gptab = extern union {
gt_header: extern struct {
gt_current_g_value: Elf32_Word,
gt_unused: Elf32_Word,
},
gt_entry: extern struct {
gt_g_value: Elf32_Word,
gt_bytes: Elf32_Word,
},
};
pub const Elf32_RegInfo = extern struct {
ri_gprmask: Elf32_Word,
ri_cprmask: [4]Elf32_Word,
ri_gp_value: Elf32_Sword,
};
pub const Elf_Options = extern struct {
kind: u8,
size: u8,
@"section": Elf32_Section,
info: Elf32_Word,
};
pub const Elf_Options_Hw = extern struct {
hwp_flags1: Elf32_Word,
hwp_flags2: Elf32_Word,
};
pub const Elf32_Lib = extern struct {
l_name: Elf32_Word,
l_time_stamp: Elf32_Word,
l_checksum: Elf32_Word,
l_version: Elf32_Word,
l_flags: Elf32_Word,
};
pub const Elf64_Lib = extern struct {
l_name: Elf64_Word,
l_time_stamp: Elf64_Word,
l_checksum: Elf64_Word,
l_version: Elf64_Word,
l_flags: Elf64_Word,
};
pub const Elf32_Conflict = Elf32_Addr;
pub const Elf_MIPS_ABIFlags_v0 = extern struct {
version: Elf32_Half,
isa_level: u8,
isa_rev: u8,
gpr_size: u8,
cpr1_size: u8,
cpr2_size: u8,
fp_abi: u8,
isa_ext: Elf32_Word,
ases: Elf32_Word,
flags1: Elf32_Word,
flags2: Elf32_Word,
};
pub const Ehdr = switch(@sizeOf(usize)) {
4 => Elf32_Ehdr,
8 => Elf64_Ehdr,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Phdr = switch(@sizeOf(usize)) {
4 => Elf32_Phdr,
8 => Elf64_Phdr,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Sym = switch(@sizeOf(usize)) {
4 => Elf32_Sym,
8 => Elf64_Sym,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Verdef = switch(@sizeOf(usize)) {
4 => Elf32_Verdef,
8 => Elf64_Verdef,
else => @compileError("expected pointer size of 32 or 64"),
};
pub const Verdaux = switch(@sizeOf(usize)) {
4 => Elf32_Verdaux,
8 => Elf64_Verdaux,
else => @compileError("expected pointer size of 32 or 64"),
};

View File

@ -8,25 +8,25 @@ const errol3 = @import("errol/index.zig").errol3;
const max_int_digits = 65;
const State = enum { // TODO put inside format function and make sure the name and debug info is correct
Start,
OpenBrace,
CloseBrace,
Integer,
IntegerWidth,
Float,
FloatWidth,
Character,
Buf,
BufWidth,
};
/// Renders fmt string with args, calling output with slices of bytes.
/// If `output` returns an error, the error is returned from `format` and
/// `output` is not called again.
pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void,
comptime fmt: []const u8, args: ...) Errors!void
{
const State = enum {
Start,
OpenBrace,
CloseBrace,
Integer,
IntegerWidth,
Float,
FloatWidth,
Character,
Buf,
BufWidth,
};
comptime var start_index = 0;
comptime var state = State.Start;
comptime var next_arg = 0;
@ -86,7 +86,8 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
},
's' => {
state = State.Buf;
},'.' => {
},
'.' => {
state = State.Float;
},
else => @compileError("Unknown format character: " ++ []u8{c}),

View File

@ -79,19 +79,38 @@ pub const DirectAllocator = struct {
switch (builtin.os) {
Os.linux, Os.macosx, Os.ios => {
assert(alignment <= os.page_size);
const p = os.posix;
const addr = p.mmap(null, n, p.PROT_READ|p.PROT_WRITE,
p.MAP_PRIVATE|p.MAP_ANONYMOUS, -1, 0);
if (addr == p.MAP_FAILED) {
return error.OutOfMemory;
}
return @intToPtr(&u8, addr)[0..n];
const alloc_size = if(alignment <= os.page_size) n else n + alignment;
const addr = p.mmap(null, alloc_size, p.PROT_READ|p.PROT_WRITE,
p.MAP_PRIVATE|p.MAP_ANONYMOUS, -1, 0);
if(addr == p.MAP_FAILED) return error.OutOfMemory;
if(alloc_size == n) return @intToPtr(&u8, addr)[0..n];
var aligned_addr = addr & ~usize(alignment - 1);
aligned_addr += alignment;
//We can unmap the unused portions of our mmap, but we must only
// pass munmap bytes that exist outside our allocated pages or it
// will happily eat us too
//Since alignment > page_size, we are by definition on a page boundry
const unused_start = addr;
const unused_len = aligned_addr - 1 - unused_start;
var err = p.munmap(@intToPtr(&u8, unused_start), unused_len);
debug.assert(p.getErrno(err) == 0);
//It is impossible that there is an unoccupied page at the top of our
// mmap.
return @intToPtr(&u8, aligned_addr)[0..n];
},
Os.windows => {
const amt = n + alignment + @sizeOf(usize);
const heap_handle = self.heap_handle ?? blk: {
const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) ?? return error.OutOfMemory;
const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0)
?? return error.OutOfMemory;
self.heap_handle = hh;
break :blk hh;
};
@ -322,6 +341,7 @@ test "DirectAllocator" {
const allocator = &direct_allocator.allocator;
try testAllocator(allocator);
try testAllocatorLargeAlignment(allocator);
}
test "ArenaAllocator" {
@ -332,6 +352,7 @@ test "ArenaAllocator" {
defer arena_allocator.deinit();
try testAllocator(&arena_allocator.allocator);
try testAllocatorLargeAlignment(&arena_allocator.allocator);
}
var test_fixed_buffer_allocator_memory: [30000 * @sizeOf(usize)]u8 = undefined;
@ -339,6 +360,7 @@ test "FixedBufferAllocator" {
var fixed_buffer_allocator = FixedBufferAllocator.init(test_fixed_buffer_allocator_memory[0..]);
try testAllocator(&fixed_buffer_allocator.allocator);
try testAllocatorLargeAlignment(&fixed_buffer_allocator.allocator);
}
fn testAllocator(allocator: &mem.Allocator) !void {
@ -360,3 +382,32 @@ fn testAllocator(allocator: &mem.Allocator) !void {
allocator.free(slice);
}
fn testAllocatorLargeAlignment(allocator: &mem.Allocator) mem.Allocator.Error!void {
//Maybe a platform's page_size is actually the same as or
// very near usize?
if(os.page_size << 2 > @maxValue(usize)) return;
const USizeShift = @IntType(false, std.math.log2(usize.bit_count));
const large_align = u29(os.page_size << 2);
var align_mask: usize = undefined;
_ = @shlWithOverflow(usize, ~usize(0), USizeShift(@ctz(large_align)), &align_mask);
var slice = try allocator.allocFn(allocator, 500, large_align);
debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
slice = try allocator.reallocFn(allocator, slice, 100, large_align);
debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
slice = try allocator.reallocFn(allocator, slice, 5000, large_align);
debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
slice = try allocator.reallocFn(allocator, slice, 10, large_align);
debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
slice = try allocator.reallocFn(allocator, slice, 20000, large_align);
debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
allocator.free(slice);
}

18
std/math/complex/abs.zig Normal file
View File

@ -0,0 +1,18 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn abs(z: var) @typeOf(z.re) {
const T = @typeOf(z.re);
return math.hypot(T, z.re, z.im);
}
const epsilon = 0.0001;
test "complex.cabs" {
const a = Complex(f32).new(5, 3);
const c = abs(a);
debug.assert(math.approxEq(f32, c, 5.83095, epsilon));
}

21
std/math/complex/acos.zig Normal file
View File

@ -0,0 +1,21 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn acos(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const q = cmath.asin(z);
return Complex(T).new(T(math.pi) / 2 - q.re, -q.im);
}
const epsilon = 0.0001;
test "complex.cacos" {
const a = Complex(f32).new(5, 3);
const c = acos(a);
debug.assert(math.approxEq(f32, c.re, 0.546975, epsilon));
debug.assert(math.approxEq(f32, c.im, -2.452914, epsilon));
}

View File

@ -0,0 +1,21 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn acosh(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const q = cmath.acos(z);
return Complex(T).new(-q.im, q.re);
}
const epsilon = 0.0001;
test "complex.cacosh" {
const a = Complex(f32).new(5, 3);
const c = acosh(a);
debug.assert(math.approxEq(f32, c.re, 2.452914, epsilon));
debug.assert(math.approxEq(f32, c.im, 0.546975, epsilon));
}

18
std/math/complex/arg.zig Normal file
View File

@ -0,0 +1,18 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn arg(z: var) @typeOf(z.re) {
const T = @typeOf(z.re);
return math.atan2(T, z.im, z.re);
}
const epsilon = 0.0001;
test "complex.carg" {
const a = Complex(f32).new(5, 3);
const c = arg(a);
debug.assert(math.approxEq(f32, c, 0.540420, epsilon));
}

27
std/math/complex/asin.zig Normal file
View File

@ -0,0 +1,27 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn asin(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const x = z.re;
const y = z.im;
const p = Complex(T).new(1.0 - (x - y) * (x + y), -2.0 * x * y);
const q = Complex(T).new(-y, x);
const r = cmath.log(q.add(cmath.sqrt(p)));
return Complex(T).new(r.im, -r.re);
}
const epsilon = 0.0001;
test "complex.casin" {
const a = Complex(f32).new(5, 3);
const c = asin(a);
debug.assert(math.approxEq(f32, c.re, 1.023822, epsilon));
debug.assert(math.approxEq(f32, c.im, 2.452914, epsilon));
}

View File

@ -0,0 +1,22 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn asinh(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const q = Complex(T).new(-z.im, z.re);
const r = cmath.asin(q);
return Complex(T).new(r.im, -r.re);
}
const epsilon = 0.0001;
test "complex.casinh" {
const a = Complex(f32).new(5, 3);
const c = asinh(a);
debug.assert(math.approxEq(f32, c.re, 2.459831, epsilon));
debug.assert(math.approxEq(f32, c.im, 0.533999, epsilon));
}

130
std/math/complex/atan.zig Normal file
View File

@ -0,0 +1,130 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn atan(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
return switch (T) {
f32 => atan32(z),
f64 => atan64(z),
else => @compileError("atan not implemented for " ++ @typeName(z)),
};
}
fn redupif32(x: f32) f32 {
const DP1 = 3.140625;
const DP2 = 9.67502593994140625e-4;
const DP3 = 1.509957990978376432e-7;
var t = x / math.pi;
if (t >= 0.0) {
t += 0.5;
} else {
t -= 0.5;
}
const u = f32(i32(t));
return ((x - u * DP1) - u * DP2) - t * DP3;
}
fn atan32(z: &const Complex(f32)) Complex(f32) {
const maxnum = 1.0e38;
const x = z.re;
const y = z.im;
if ((x == 0.0) and (y > 1.0)) {
// overflow
return Complex(f32).new(maxnum, maxnum);
}
const x2 = x * x;
var a = 1.0 - x2 - (y * y);
if (a == 0.0) {
// overflow
return Complex(f32).new(maxnum, maxnum);
}
var t = 0.5 * math.atan2(f32, 2.0 * x, a);
var w = redupif32(t);
t = y - 1.0;
a = x2 + t * t;
if (a == 0.0) {
// overflow
return Complex(f32).new(maxnum, maxnum);
}
t = y + 1.0;
a = (x2 + (t * t)) / a;
return Complex(f32).new(w, 0.25 * math.ln(a));
}
fn redupif64(x: f64) f64 {
const DP1 = 3.14159265160560607910;
const DP2 = 1.98418714791870343106e-9;
const DP3 = 1.14423774522196636802e-17;
var t = x / math.pi;
if (t >= 0.0) {
t += 0.5;
} else {
t -= 0.5;
}
const u = f64(i64(t));
return ((x - u * DP1) - u * DP2) - t * DP3;
}
fn atan64(z: &const Complex(f64)) Complex(f64) {
const maxnum = 1.0e308;
const x = z.re;
const y = z.im;
if ((x == 0.0) and (y > 1.0)) {
// overflow
return Complex(f64).new(maxnum, maxnum);
}
const x2 = x * x;
var a = 1.0 - x2 - (y * y);
if (a == 0.0) {
// overflow
return Complex(f64).new(maxnum, maxnum);
}
var t = 0.5 * math.atan2(f64, 2.0 * x, a);
var w = redupif64(t);
t = y - 1.0;
a = x2 + t * t;
if (a == 0.0) {
// overflow
return Complex(f64).new(maxnum, maxnum);
}
t = y + 1.0;
a = (x2 + (t * t)) / a;
return Complex(f64).new(w, 0.25 * math.ln(a));
}
const epsilon = 0.0001;
test "complex.catan32" {
const a = Complex(f32).new(5, 3);
const c = atan(a);
debug.assert(math.approxEq(f32, c.re, 1.423679, epsilon));
debug.assert(math.approxEq(f32, c.im, 0.086569, epsilon));
}
test "complex.catan64" {
const a = Complex(f64).new(5, 3);
const c = atan(a);
debug.assert(math.approxEq(f64, c.re, 1.423679, epsilon));
debug.assert(math.approxEq(f64, c.im, 0.086569, epsilon));
}

View File

@ -0,0 +1,22 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn atanh(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const q = Complex(T).new(-z.im, z.re);
const r = cmath.atan(q);
return Complex(T).new(r.im, -r.re);
}
const epsilon = 0.0001;
test "complex.catanh" {
const a = Complex(f32).new(5, 3);
const c = atanh(a);
debug.assert(math.approxEq(f32, c.re, 0.146947, epsilon));
debug.assert(math.approxEq(f32, c.im, 1.480870, epsilon));
}

17
std/math/complex/conj.zig Normal file
View File

@ -0,0 +1,17 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn conj(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
return Complex(T).new(z.re, -z.im);
}
test "complex.conj" {
const a = Complex(f32).new(5, 3);
const c = a.conjugate();
debug.assert(c.re == 5 and c.im == -3);
}

21
std/math/complex/cos.zig Normal file
View File

@ -0,0 +1,21 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn cos(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const p = Complex(T).new(-z.im, z.re);
return cmath.cosh(p);
}
const epsilon = 0.0001;
test "complex.ccos" {
const a = Complex(f32).new(5, 3);
const c = cos(a);
debug.assert(math.approxEq(f32, c.re, 2.855815, epsilon));
debug.assert(math.approxEq(f32, c.im, 9.606383, epsilon));
}

165
std/math/complex/cosh.zig Normal file
View File

@ -0,0 +1,165 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
const ldexp_cexp = @import("ldexp.zig").ldexp_cexp;
pub fn cosh(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
return switch (T) {
f32 => cosh32(z),
f64 => cosh64(z),
else => @compileError("cosh not implemented for " ++ @typeName(z)),
};
}
fn cosh32(z: &const Complex(f32)) Complex(f32) {
const x = z.re;
const y = z.im;
const hx = @bitCast(u32, x);
const ix = hx & 0x7fffffff;
const hy = @bitCast(u32, y);
const iy = hy & 0x7fffffff;
if (ix < 0x7f800000 and iy < 0x7f800000) {
if (iy == 0) {
return Complex(f32).new(math.cosh(x), y);
}
// small x: normal case
if (ix < 0x41100000) {
return Complex(f32).new(math.cosh(x) * math.cos(y), math.sinh(x) * math.sin(y));
}
// |x|>= 9, so cosh(x) ~= exp(|x|)
if (ix < 0x42b17218) {
// x < 88.7: exp(|x|) won't overflow
const h = math.exp(math.fabs(x)) * 0.5;
return Complex(f32).new(math.copysign(f32, h, x) * math.cos(y), h * math.sin(y));
}
// x < 192.7: scale to avoid overflow
else if (ix < 0x4340b1e7) {
const v = Complex(f32).new(math.fabs(x), y);
const r = ldexp_cexp(v, -1);
return Complex(f32).new(x, y * math.copysign(f32, 1, x));
}
// x >= 192.7: result always overflows
else {
const h = 0x1p127 * x;
return Complex(f32).new(h * h * math.cos(y), h * math.sin(y));
}
}
if (ix == 0 and iy >= 0x7f800000) {
return Complex(f32).new(y - y, math.copysign(f32, 0, x * (y - y)));
}
if (iy == 0 and ix >= 0x7f800000) {
if (hx & 0x7fffff == 0) {
return Complex(f32).new(x * x, math.copysign(f32, 0, x) * y);
}
return Complex(f32).new(x, math.copysign(f32, 0, (x + x) * y));
}
if (ix < 0x7f800000 and iy >= 0x7f800000) {
return Complex(f32).new(y - y, x * (y - y));
}
if (ix >= 0x7f800000 and (hx & 0x7fffff) == 0) {
if (iy >= 0x7f800000) {
return Complex(f32).new(x * x, x * (y - y));
}
return Complex(f32).new((x * x) * math.cos(y), x * math.sin(y));
}
return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y));
}
fn cosh64(z: &const Complex(f64)) Complex(f64) {
const x = z.re;
const y = z.im;
const fx = @bitCast(u64, x);
const hx = u32(fx >> 32);
const lx = @truncate(u32, fx);
const ix = hx & 0x7fffffff;
const fy = @bitCast(u64, y);
const hy = u32(fy >> 32);
const ly = @truncate(u32, fy);
const iy = hy & 0x7fffffff;
// nearly non-exceptional case where x, y are finite
if (ix < 0x7ff00000 and iy < 0x7ff00000) {
if (iy | ly == 0) {
return Complex(f64).new(math.cosh(x), x * y);
}
// small x: normal case
if (ix < 0x40360000) {
return Complex(f64).new(math.cosh(x) * math.cos(y), math.sinh(x) * math.sin(y));
}
// |x|>= 22, so cosh(x) ~= exp(|x|)
if (ix < 0x40862e42) {
// x < 710: exp(|x|) won't overflow
const h = math.exp(math.fabs(x)) * 0.5;
return Complex(f64).new(h * math.cos(y), math.copysign(f64, h, x) * math.sin(y));
}
// x < 1455: scale to avoid overflow
else if (ix < 0x4096bbaa) {
const v = Complex(f64).new(math.fabs(x), y);
const r = ldexp_cexp(v, -1);
return Complex(f64).new(x, y * math.copysign(f64, 1, x));
}
// x >= 1455: result always overflows
else {
const h = 0x1p1023;
return Complex(f64).new(h * h * math.cos(y), h * math.sin(y));
}
}
if (ix | lx == 0 and iy >= 0x7ff00000) {
return Complex(f64).new(y - y, math.copysign(f64, 0, x * (y - y)));
}
if (iy | ly == 0 and ix >= 0x7ff00000) {
if ((hx & 0xfffff) | lx == 0) {
return Complex(f64).new(x * x, math.copysign(f64, 0, x) * y);
}
return Complex(f64).new(x * x, math.copysign(f64, 0, (x + x) * y));
}
if (ix < 0x7ff00000 and iy >= 0x7ff00000) {
return Complex(f64).new(y - y, x * (y - y));
}
if (ix >= 0x7ff00000 and (hx & 0xfffff) | lx == 0) {
if (iy >= 0x7ff00000) {
return Complex(f64).new(x * x, x * (y - y));
}
return Complex(f64).new(x * x * math.cos(y), x * math.sin(y));
}
return Complex(f64).new((x * x) * (y - y), (x + x) * (y - y));
}
const epsilon = 0.0001;
test "complex.ccosh32" {
const a = Complex(f32).new(5, 3);
const c = cosh(a);
debug.assert(math.approxEq(f32, c.re, -73.467300, epsilon));
debug.assert(math.approxEq(f32, c.im, 10.471557, epsilon));
}
test "complex.ccosh64" {
const a = Complex(f64).new(5, 3);
const c = cosh(a);
debug.assert(math.approxEq(f64, c.re, -73.467300, epsilon));
debug.assert(math.approxEq(f64, c.im, 10.471557, epsilon));
}

140
std/math/complex/exp.zig Normal file
View File

@ -0,0 +1,140 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
const ldexp_cexp = @import("ldexp.zig").ldexp_cexp;
pub fn exp(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
return switch (T) {
f32 => exp32(z),
f64 => exp64(z),
else => @compileError("exp not implemented for " ++ @typeName(z)),
};
}
fn exp32(z: &const Complex(f32)) Complex(f32) {
@setFloatMode(this, @import("builtin").FloatMode.Strict);
const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955
const cexp_overflow = 0x43400074; // (max_exp - min_denom_exp) * ln2
const x = z.re;
const y = z.im;
const hy = @bitCast(u32, y) & 0x7fffffff;
// cexp(x + i0) = exp(x) + i0
if (hy == 0) {
return Complex(f32).new(math.exp(x), y);
}
const hx = @bitCast(u32, x);
// cexp(0 + iy) = cos(y) + isin(y)
if ((hx & 0x7fffffff) == 0) {
return Complex(f32).new(math.cos(y), math.sin(y));
}
if (hy >= 0x7f800000) {
// cexp(finite|nan +- i inf|nan) = nan + i nan
if ((hx & 0x7fffffff) != 0x7f800000) {
return Complex(f32).new(y - y, y - y);
}
// cexp(-inf +- i inf|nan) = 0 + i0
else if (hx & 0x80000000 != 0) {
return Complex(f32).new(0, 0);
}
// cexp(+inf +- i inf|nan) = inf + i nan
else {
return Complex(f32).new(x, y - y);
}
}
// 88.7 <= x <= 192 so must scale
if (hx >= exp_overflow and hx <= cexp_overflow) {
return ldexp_cexp(z, 0);
}
// - x < exp_overflow => exp(x) won't overflow (common)
// - x > cexp_overflow, so exp(x) * s overflows for s > 0
// - x = +-inf
// - x = nan
else {
const exp_x = math.exp(x);
return Complex(f32).new(exp_x * math.cos(y), exp_x * math.sin(y));
}
}
fn exp64(z: &const Complex(f64)) Complex(f64) {
const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710
const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2
const x = z.re;
const y = z.im;
const fy = @bitCast(u64, y);
const hy = u32(fy >> 32) & 0x7fffffff;
const ly = @truncate(u32, fy);
// cexp(x + i0) = exp(x) + i0
if (hy | ly == 0) {
return Complex(f64).new(math.exp(x), y);
}
const fx = @bitCast(u64, x);
const hx = u32(fx >> 32);
const lx = @truncate(u32, fx);
// cexp(0 + iy) = cos(y) + isin(y)
if ((hx & 0x7fffffff) | lx == 0) {
return Complex(f64).new(math.cos(y), math.sin(y));
}
if (hy >= 0x7ff00000) {
// cexp(finite|nan +- i inf|nan) = nan + i nan
if (lx != 0 or (hx & 0x7fffffff) != 0x7ff00000) {
return Complex(f64).new(y - y, y - y);
}
// cexp(-inf +- i inf|nan) = 0 + i0
else if (hx & 0x80000000 != 0) {
return Complex(f64).new(0, 0);
}
// cexp(+inf +- i inf|nan) = inf + i nan
else {
return Complex(f64).new(x, y - y);
}
}
// 709.7 <= x <= 1454.3 so must scale
if (hx >= exp_overflow and hx <= cexp_overflow) {
const r = ldexp_cexp(z, 0);
return *r;
}
// - x < exp_overflow => exp(x) won't overflow (common)
// - x > cexp_overflow, so exp(x) * s overflows for s > 0
// - x = +-inf
// - x = nan
else {
const exp_x = math.exp(x);
return Complex(f64).new(exp_x * math.cos(y), exp_x * math.sin(y));
}
}
const epsilon = 0.0001;
test "complex.cexp32" {
const a = Complex(f32).new(5, 3);
const c = exp(a);
debug.assert(math.approxEq(f32, c.re, -146.927917, epsilon));
debug.assert(math.approxEq(f32, c.im, 20.944065, epsilon));
}
test "complex.cexp64" {
const a = Complex(f32).new(5, 3);
const c = exp(a);
debug.assert(math.approxEq(f64, c.re, -146.927917, epsilon));
debug.assert(math.approxEq(f64, c.im, 20.944065, epsilon));
}

171
std/math/complex/index.zig Normal file
View File

@ -0,0 +1,171 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
pub const abs = @import("abs.zig").abs;
pub const acosh = @import("acosh.zig").acosh;
pub const acos = @import("acos.zig").acos;
pub const arg = @import("arg.zig").arg;
pub const asinh = @import("asinh.zig").asinh;
pub const asin = @import("asin.zig").asin;
pub const atanh = @import("atanh.zig").atanh;
pub const atan = @import("atan.zig").atan;
pub const conj = @import("conj.zig").conj;
pub const cosh = @import("cosh.zig").cosh;
pub const cos = @import("cos.zig").cos;
pub const exp = @import("exp.zig").exp;
pub const log = @import("log.zig").log;
pub const pow = @import("pow.zig").pow;
pub const proj = @import("proj.zig").proj;
pub const sinh = @import("sinh.zig").sinh;
pub const sin = @import("sin.zig").sin;
pub const sqrt = @import("sqrt.zig").sqrt;
pub const tanh = @import("tanh.zig").tanh;
pub const tan = @import("tan.zig").tan;
pub fn Complex(comptime T: type) type {
return struct {
const Self = this;
re: T,
im: T,
pub fn new(re: T, im: T) Self {
return Self {
.re = re,
.im = im,
};
}
pub fn add(self: &const Self, other: &const Self) Self {
return Self {
.re = self.re + other.re,
.im = self.im + other.im,
};
}
pub fn sub(self: &const Self, other: &const Self) Self {
return Self {
.re = self.re - other.re,
.im = self.im - other.im,
};
}
pub fn mul(self: &const Self, other: &const Self) Self {
return Self {
.re = self.re * other.re - self.im * other.im,
.im = self.im * other.re + self.re * other.im,
};
}
pub fn div(self: &const Self, other: &const Self) Self {
const re_num = self.re * other.re + self.im * other.im;
const im_num = self.im * other.re - self.re * other.im;
const den = other.re * other.re + other.im * other.im;
return Self {
.re = re_num / den,
.im = im_num / den,
};
}
pub fn conjugate(self: &const Self) Self {
return Self {
.re = self.re,
.im = -self.im,
};
}
pub fn reciprocal(self: &const Self) Self {
const m = self.re * self.re + self.im * self.im;
return Self {
.re = self.re / m,
.im = -self.im / m,
};
}
pub fn magnitude(self: &const Self) T {
return math.sqrt(self.re * self.re + self.im * self.im);
}
};
}
const epsilon = 0.0001;
test "complex.add" {
const a = Complex(f32).new(5, 3);
const b = Complex(f32).new(2, 7);
const c = a.add(b);
debug.assert(c.re == 7 and c.im == 10);
}
test "complex.sub" {
const a = Complex(f32).new(5, 3);
const b = Complex(f32).new(2, 7);
const c = a.sub(b);
debug.assert(c.re == 3 and c.im == -4);
}
test "complex.mul" {
const a = Complex(f32).new(5, 3);
const b = Complex(f32).new(2, 7);
const c = a.mul(b);
debug.assert(c.re == -11 and c.im == 41);
}
test "complex.div" {
const a = Complex(f32).new(5, 3);
const b = Complex(f32).new(2, 7);
const c = a.div(b);
debug.assert(math.approxEq(f32, c.re, f32(31)/53, epsilon) and
math.approxEq(f32, c.im, f32(-29)/53, epsilon));
}
test "complex.conjugate" {
const a = Complex(f32).new(5, 3);
const c = a.conjugate();
debug.assert(c.re == 5 and c.im == -3);
}
test "complex.reciprocal" {
const a = Complex(f32).new(5, 3);
const c = a.reciprocal();
debug.assert(math.approxEq(f32, c.re, f32(5)/34, epsilon) and
math.approxEq(f32, c.im, f32(-3)/34, epsilon));
}
test "complex.magnitude" {
const a = Complex(f32).new(5, 3);
const c = a.magnitude();
debug.assert(math.approxEq(f32, c, 5.83095, epsilon));
}
test "complex.cmath" {
_ = @import("abs.zig");
_ = @import("acosh.zig");
_ = @import("acos.zig");
_ = @import("arg.zig");
_ = @import("asinh.zig");
_ = @import("asin.zig");
_ = @import("atanh.zig");
_ = @import("atan.zig");
_ = @import("conj.zig");
_ = @import("cosh.zig");
_ = @import("cos.zig");
_ = @import("exp.zig");
_ = @import("log.zig");
_ = @import("pow.zig");
_ = @import("proj.zig");
_ = @import("sinh.zig");
_ = @import("sin.zig");
_ = @import("sqrt.zig");
_ = @import("tanh.zig");
_ = @import("tan.zig");
}

View File

@ -0,0 +1,75 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn ldexp_cexp(z: var, expt: i32) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
return switch (T) {
f32 => ldexp_cexp32(z, expt),
f64 => ldexp_cexp64(z, expt),
else => unreachable,
};
}
fn frexp_exp32(x: f32, expt: &i32) f32 {
const k = 235; // reduction constant
const kln2 = 162.88958740; // k * ln2
const exp_x = math.exp(x - kln2);
const hx = @bitCast(u32, exp_x);
*expt = i32(hx >> 23) - (0x7f + 127) + k;
return @bitCast(f32, (hx & 0x7fffff) | ((0x7f + 127) << 23));
}
fn ldexp_cexp32(z: &const Complex(f32), expt: i32) Complex(f32) {
var ex_expt: i32 = undefined;
const exp_x = frexp_exp32(z.re, &ex_expt);
const exptf = expt + ex_expt;
const half_expt1 = @divTrunc(exptf, 2);
const scale1 = @bitCast(f32, (0x7f + half_expt1) << 23);
const half_expt2 = exptf - half_expt1;
const scale2 = @bitCast(f32, (0x7f + half_expt2) << 23);
return Complex(f32).new(
math.cos(z.im) * exp_x * scale1 * scale2,
math.sin(z.im) * exp_x * scale1 * scale2,
);
}
fn frexp_exp64(x: f64, expt: &i32) f64 {
const k = 1799; // reduction constant
const kln2 = 1246.97177782734161156; // k * ln2
const exp_x = math.exp(x - kln2);
const fx = @bitCast(u64, x);
const hx = u32(fx >> 32);
const lx = @truncate(u32, fx);
*expt = i32(hx >> 20) - (0x3ff + 1023) + k;
const high_word = (hx & 0xfffff) | ((0x3ff + 1023) << 20);
return @bitCast(f64, (u64(high_word) << 32) | lx);
}
fn ldexp_cexp64(z: &const Complex(f64), expt: i32) Complex(f64) {
var ex_expt: i32 = undefined;
const exp_x = frexp_exp64(z.re, &ex_expt);
const exptf = i64(expt + ex_expt);
const half_expt1 = @divTrunc(exptf, 2);
const scale1 = @bitCast(f64, (0x3ff + half_expt1) << 20);
const half_expt2 = exptf - half_expt1;
const scale2 = @bitCast(f64, (0x3ff + half_expt2) << 20);
return Complex(f64).new(
math.cos(z.im) * exp_x * scale1 * scale2,
math.sin(z.im) * exp_x * scale1 * scale2,
);
}

23
std/math/complex/log.zig Normal file
View File

@ -0,0 +1,23 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn log(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const r = cmath.abs(z);
const phi = cmath.arg(z);
return Complex(T).new(math.ln(r), phi);
}
const epsilon = 0.0001;
test "complex.clog" {
const a = Complex(f32).new(5, 3);
const c = log(a);
debug.assert(math.approxEq(f32, c.re, 1.763180, epsilon));
debug.assert(math.approxEq(f32, c.im, 0.540419, epsilon));
}

22
std/math/complex/pow.zig Normal file
View File

@ -0,0 +1,22 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn pow(comptime T: type, z: &const T, c: &const T) T {
const p = cmath.log(z);
const q = c.mul(p);
return cmath.exp(q);
}
const epsilon = 0.0001;
test "complex.cpow" {
const a = Complex(f32).new(5, 3);
const b = Complex(f32).new(2.3, -1.3);
const c = pow(Complex(f32), a, b);
debug.assert(math.approxEq(f32, c.re, 58.049110, epsilon));
debug.assert(math.approxEq(f32, c.im, -101.003433, epsilon));
}

24
std/math/complex/proj.zig Normal file
View File

@ -0,0 +1,24 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn proj(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
if (math.isInf(z.re) or math.isInf(z.im)) {
return Complex(T).new(math.inf(T), math.copysign(T, 0, z.re));
}
return Complex(T).new(z.re, z.im);
}
const epsilon = 0.0001;
test "complex.cproj" {
const a = Complex(f32).new(5, 3);
const c = proj(a);
debug.assert(c.re == 5 and c.im == 3);
}

22
std/math/complex/sin.zig Normal file
View File

@ -0,0 +1,22 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn sin(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const p = Complex(T).new(-z.im, z.re);
const q = cmath.sinh(p);
return Complex(T).new(q.im, -q.re);
}
const epsilon = 0.0001;
test "complex.csin" {
const a = Complex(f32).new(5, 3);
const c = sin(a);
debug.assert(math.approxEq(f32, c.re, -9.654126, epsilon));
debug.assert(math.approxEq(f32, c.im, 2.841692, epsilon));
}

164
std/math/complex/sinh.zig Normal file
View File

@ -0,0 +1,164 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
const ldexp_cexp = @import("ldexp.zig").ldexp_cexp;
pub fn sinh(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
return switch (T) {
f32 => sinh32(z),
f64 => sinh64(z),
else => @compileError("tan not implemented for " ++ @typeName(z)),
};
}
fn sinh32(z: &const Complex(f32)) Complex(f32) {
const x = z.re;
const y = z.im;
const hx = @bitCast(u32, x);
const ix = hx & 0x7fffffff;
const hy = @bitCast(u32, y);
const iy = hy & 0x7fffffff;
if (ix < 0x7f800000 and iy < 0x7f800000) {
if (iy == 0) {
return Complex(f32).new(math.sinh(x), y);
}
// small x: normal case
if (ix < 0x41100000) {
return Complex(f32).new(math.sinh(x) * math.cos(y), math.cosh(x) * math.sin(y));
}
// |x|>= 9, so cosh(x) ~= exp(|x|)
if (ix < 0x42b17218) {
// x < 88.7: exp(|x|) won't overflow
const h = math.exp(math.fabs(x)) * 0.5;
return Complex(f32).new(math.copysign(f32, h, x) * math.cos(y), h * math.sin(y));
}
// x < 192.7: scale to avoid overflow
else if (ix < 0x4340b1e7) {
const v = Complex(f32).new(math.fabs(x), y);
const r = ldexp_cexp(v, -1);
return Complex(f32).new(x * math.copysign(f32, 1, x), y);
}
// x >= 192.7: result always overflows
else {
const h = 0x1p127 * x;
return Complex(f32).new(h * math.cos(y), h * h * math.sin(y));
}
}
if (ix == 0 and iy >= 0x7f800000) {
return Complex(f32).new(math.copysign(f32, 0, x * (y - y)), y - y);
}
if (iy == 0 and ix >= 0x7f800000) {
if (hx & 0x7fffff == 0) {
return Complex(f32).new(x, y);
}
return Complex(f32).new(x, math.copysign(f32, 0, y));
}
if (ix < 0x7f800000 and iy >= 0x7f800000) {
return Complex(f32).new(y - y, x * (y - y));
}
if (ix >= 0x7f800000 and (hx & 0x7fffff) == 0) {
if (iy >= 0x7f800000) {
return Complex(f32).new(x * x, x * (y - y));
}
return Complex(f32).new(x * math.cos(y), math.inf_f32 * math.sin(y));
}
return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y));
}
fn sinh64(z: &const Complex(f64)) Complex(f64) {
const x = z.re;
const y = z.im;
const fx = @bitCast(u64, x);
const hx = u32(fx >> 32);
const lx = @truncate(u32, fx);
const ix = hx & 0x7fffffff;
const fy = @bitCast(u64, y);
const hy = u32(fy >> 32);
const ly = @truncate(u32, fy);
const iy = hy & 0x7fffffff;
if (ix < 0x7ff00000 and iy < 0x7ff00000) {
if (iy | ly == 0) {
return Complex(f64).new(math.sinh(x), y);
}
// small x: normal case
if (ix < 0x40360000) {
return Complex(f64).new(math.sinh(x) * math.cos(y), math.cosh(x) * math.sin(y));
}
// |x|>= 22, so cosh(x) ~= exp(|x|)
if (ix < 0x40862e42) {
// x < 710: exp(|x|) won't overflow
const h = math.exp(math.fabs(x)) * 0.5;
return Complex(f64).new(math.copysign(f64, h, x) * math.cos(y), h * math.sin(y));
}
// x < 1455: scale to avoid overflow
else if (ix < 0x4096bbaa) {
const v = Complex(f64).new(math.fabs(x), y);
const r = ldexp_cexp(v, -1);
return Complex(f64).new(x * math.copysign(f64, 1, x), y);
}
// x >= 1455: result always overflows
else {
const h = 0x1p1023 * x;
return Complex(f64).new(h * math.cos(y), h * h * math.sin(y));
}
}
if (ix | lx == 0 and iy >= 0x7ff00000) {
return Complex(f64).new(math.copysign(f64, 0, x * (y - y)), y - y);
}
if (iy | ly == 0 and ix >= 0x7ff00000) {
if ((hx & 0xfffff) | lx == 0) {
return Complex(f64).new(x, y);
}
return Complex(f64).new(x, math.copysign(f64, 0, y));
}
if (ix < 0x7ff00000 and iy >= 0x7ff00000) {
return Complex(f64).new(y - y, x * (y - y));
}
if (ix >= 0x7ff00000 and (hx & 0xfffff) | lx == 0) {
if (iy >= 0x7ff00000) {
return Complex(f64).new(x * x, x * (y - y));
}
return Complex(f64).new(x * math.cos(y), math.inf_f64 * math.sin(y));
}
return Complex(f64).new((x * x) * (y - y), (x + x) * (y - y));
}
const epsilon = 0.0001;
test "complex.csinh32" {
const a = Complex(f32).new(5, 3);
const c = sinh(a);
debug.assert(math.approxEq(f32, c.re, -73.460617, epsilon));
debug.assert(math.approxEq(f32, c.im, 10.472508, epsilon));
}
test "complex.csinh64" {
const a = Complex(f64).new(5, 3);
const c = sinh(a);
debug.assert(math.approxEq(f64, c.re, -73.460617, epsilon));
debug.assert(math.approxEq(f64, c.im, 10.472508, epsilon));
}

133
std/math/complex/sqrt.zig Normal file
View File

@ -0,0 +1,133 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
// TODO when #733 is solved this can be @typeOf(z) instead of Complex(@typeOf(z.re))
pub fn sqrt(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
return switch (T) {
f32 => sqrt32(z),
f64 => sqrt64(z),
else => @compileError("sqrt not implemented for " ++ @typeName(z)),
};
}
fn sqrt32(z: &const Complex(f32)) Complex(f32) {
const x = z.re;
const y = z.im;
if (x == 0 and y == 0) {
return Complex(f32).new(0, y);
}
if (math.isInf(y)) {
return Complex(f32).new(math.inf(f32), y);
}
if (math.isNan(x)) {
// raise invalid if y is not nan
const t = (y - y) / (y - y);
return Complex(f32).new(x, t);
}
if (math.isInf(x)) {
// sqrt(inf + i nan) = inf + nan i
// sqrt(inf + iy) = inf + i0
// sqrt(-inf + i nan) = nan +- inf i
// sqrt(-inf + iy) = 0 + inf i
if (math.signbit(x)) {
return Complex(f32).new(math.fabs(x - y), math.copysign(f32, x, y));
} else {
return Complex(f32).new(x, math.copysign(f32, y - y, y));
}
}
// y = nan special case is handled fine below
// double-precision avoids overflow with correct rounding.
const dx = f64(x);
const dy = f64(y);
if (dx >= 0) {
const t = math.sqrt((dx + math.hypot(f64, dx, dy)) * 0.5);
return Complex(f32).new(f32(t), f32(dy / (2.0 * t)));
} else {
const t = math.sqrt((-dx + math.hypot(f64, dx, dy)) * 0.5);
return Complex(f32).new(f32(math.fabs(y) / (2.0 * t)), f32(math.copysign(f64, t, y)));
}
}
fn sqrt64(z: &const Complex(f64)) Complex(f64) {
// may encounter overflow for im,re >= DBL_MAX / (1 + sqrt(2))
const threshold = 0x1.a827999fcef32p+1022;
var x = z.re;
var y = z.im;
if (x == 0 and y == 0) {
return Complex(f64).new(0, y);
}
if (math.isInf(y)) {
return Complex(f64).new(math.inf(f64), y);
}
if (math.isNan(x)) {
// raise invalid if y is not nan
const t = (y - y) / (y - y);
return Complex(f64).new(x, t);
}
if (math.isInf(x)) {
// sqrt(inf + i nan) = inf + nan i
// sqrt(inf + iy) = inf + i0
// sqrt(-inf + i nan) = nan +- inf i
// sqrt(-inf + iy) = 0 + inf i
if (math.signbit(x)) {
return Complex(f64).new(math.fabs(x - y), math.copysign(f64, x, y));
} else {
return Complex(f64).new(x, math.copysign(f64, y - y, y));
}
}
// y = nan special case is handled fine below
// scale to avoid overflow
var scale = false;
if (math.fabs(x) >= threshold or math.fabs(y) >= threshold) {
x *= 0.25;
y *= 0.25;
scale = true;
}
var result: Complex(f64) = undefined;
if (x >= 0) {
const t = math.sqrt((x + math.hypot(f64, x, y)) * 0.5);
result = Complex(f64).new(t, y / (2.0 * t));
} else {
const t = math.sqrt((-x + math.hypot(f64, x, y)) * 0.5);
result = Complex(f64).new(math.fabs(y) / (2.0 * t), math.copysign(f64, t, y));
}
if (scale) {
result.re *= 2;
result.im *= 2;
}
return result;
}
const epsilon = 0.0001;
test "complex.csqrt32" {
const a = Complex(f32).new(5, 3);
const c = sqrt(a);
debug.assert(math.approxEq(f32, c.re, 2.327117, epsilon));
debug.assert(math.approxEq(f32, c.im, 0.644574, epsilon));
}
test "complex.csqrt64" {
const a = Complex(f64).new(5, 3);
const c = sqrt(a);
debug.assert(math.approxEq(f64, c.re, 2.3271175190399496, epsilon));
debug.assert(math.approxEq(f64, c.im, 0.6445742373246469, epsilon));
}

22
std/math/complex/tan.zig Normal file
View File

@ -0,0 +1,22 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn tan(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const q = Complex(T).new(-z.im, z.re);
const r = cmath.tanh(q);
return Complex(T).new(r.im, -r.re);
}
const epsilon = 0.0001;
test "complex.ctan" {
const a = Complex(f32).new(5, 3);
const c = tan(a);
debug.assert(math.approxEq(f32, c.re, -0.002708233, epsilon));
debug.assert(math.approxEq(f32, c.im, 1.004165, epsilon));
}

111
std/math/complex/tanh.zig Normal file
View File

@ -0,0 +1,111 @@
const std = @import("../../index.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn tanh(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
return switch (T) {
f32 => tanh32(z),
f64 => tanh64(z),
else => @compileError("tan not implemented for " ++ @typeName(z)),
};
}
fn tanh32(z: &const Complex(f32)) Complex(f32) {
const x = z.re;
const y = z.im;
const hx = @bitCast(u32, x);
const ix = hx & 0x7fffffff;
if (ix >= 0x7f800000) {
if (ix & 0x7fffff != 0) {
const r = if (y == 0) y else x * y;
return Complex(f32).new(x, r);
}
const xx = @bitCast(f32, hx - 0x40000000);
const r = if (math.isInf(y)) y else math.sin(y) * math.cos(y);
return Complex(f32).new(xx, math.copysign(f32, 0, r));
}
if (!math.isFinite(y)) {
const r = if (ix != 0) y - y else x;
return Complex(f32).new(r, y - y);
}
// x >= 11
if (ix >= 0x41300000) {
const exp_mx = math.exp(-math.fabs(x));
return Complex(f32).new(math.copysign(f32, 1, x), 4 * math.sin(y) * math.cos(y) * exp_mx * exp_mx);
}
// Kahan's algorithm
const t = math.tan(y);
const beta = 1.0 + t * t;
const s = math.sinh(x);
const rho = math.sqrt(1 + s * s);
const den = 1 + beta * s * s;
return Complex(f32).new((beta * rho * s) / den, t / den);
}
fn tanh64(z: &const Complex(f64)) Complex(f64) {
const x = z.re;
const y = z.im;
const fx = @bitCast(u64, x);
const hx = u32(fx >> 32);
const lx = @truncate(u32, fx);
const ix = hx & 0x7fffffff;
if (ix >= 0x7ff00000) {
if ((ix & 0x7fffff) | lx != 0) {
const r = if (y == 0) y else x * y;
return Complex(f64).new(x, r);
}
const xx = @bitCast(f64, (u64(hx - 0x40000000) << 32) | lx);
const r = if (math.isInf(y)) y else math.sin(y) * math.cos(y);
return Complex(f64).new(xx, math.copysign(f64, 0, r));
}
if (!math.isFinite(y)) {
const r = if (ix != 0) y - y else x;
return Complex(f64).new(r, y - y);
}
// x >= 22
if (ix >= 0x40360000) {
const exp_mx = math.exp(-math.fabs(x));
return Complex(f64).new(math.copysign(f64, 1, x), 4 * math.sin(y) * math.cos(y) * exp_mx * exp_mx);
}
// Kahan's algorithm
const t = math.tan(y);
const beta = 1.0 + t * t;
const s = math.sinh(x);
const rho = math.sqrt(1 + s * s);
const den = 1 + beta * s * s;
return Complex(f64).new((beta * rho * s) / den, t / den);
}
const epsilon = 0.0001;
test "complex.ctanh32" {
const a = Complex(f32).new(5, 3);
const c = tanh(a);
debug.assert(math.approxEq(f32, c.re, 0.999913, epsilon));
debug.assert(math.approxEq(f32, c.im, -0.000025, epsilon));
}
test "complex.ctanh64" {
const a = Complex(f64).new(5, 3);
const c = tanh(a);
debug.assert(math.approxEq(f64, c.re, 0.999913, epsilon));
debug.assert(math.approxEq(f64, c.im, -0.000025, epsilon));
}

View File

@ -6,6 +6,7 @@
const std = @import("../index.zig");
const math = std.math;
const assert = std.debug.assert;
const builtin = @import("builtin");
pub fn exp(x: var) @typeOf(x) {
const T = @typeOf(x);
@ -17,6 +18,8 @@ pub fn exp(x: var) @typeOf(x) {
}
fn exp32(x_: f32) f32 {
@setFloatMode(this, builtin.FloatMode.Strict);
const half = []f32 { 0.5, -0.5 };
const ln2hi = 6.9314575195e-1;
const ln2lo = 1.4286067653e-6;
@ -94,6 +97,8 @@ fn exp32(x_: f32) f32 {
}
fn exp64(x_: f64) f64 {
@setFloatMode(this, builtin.FloatMode.Strict);
const half = []const f64 { 0.5, -0.5 };
const ln2hi: f64 = 6.93147180369123816490e-01;
const ln2lo: f64 = 1.90821492927058770002e-10;

View File

@ -129,6 +129,9 @@ pub const cos = @import("cos.zig").cos;
pub const sin = @import("sin.zig").sin;
pub const tan = @import("tan.zig").tan;
pub const complex = @import("complex/index.zig");
pub const Complex = complex.Complex;
test "math" {
_ = @import("nan.zig");
_ = @import("isnan.zig");
@ -172,6 +175,8 @@ test "math" {
_ = @import("sin.zig");
_ = @import("cos.zig");
_ = @import("tan.zig");
_ = @import("complex/index.zig");
}

View File

@ -89,6 +89,8 @@ pub fn ln_32(x_: f32) f32 {
}
pub fn ln_64(x_: f64) f64 {
@setFloatMode(this, @import("builtin").FloatMode.Strict);
const ln2_hi: f64 = 6.93147180369123816490e-01;
const ln2_lo: f64 = 1.90821492927058770002e-10;
const Lg1: f64 = 6.666666666666735130e-01;

View File

@ -14,26 +14,8 @@ const TypeId = builtin.TypeId;
pub fn sqrt(x: var) (if (@typeId(@typeOf(x)) == TypeId.Int) @IntType(false, @typeOf(x).bit_count / 2) else @typeOf(x)) {
const T = @typeOf(x);
switch (@typeId(T)) {
TypeId.FloatLiteral => {
return T(sqrt64(x));
},
TypeId.Float => {
switch (T) {
f32 => {
switch (builtin.arch) {
builtin.Arch.x86_64 => return @import("x86_64/sqrt.zig").sqrt32(x),
else => return sqrt32(x),
}
},
f64 => {
switch (builtin.arch) {
builtin.Arch.x86_64 => return @import("x86_64/sqrt.zig").sqrt64(x),
else => return sqrt64(x),
}
},
else => @compileError("sqrt not implemented for " ++ @typeName(T)),
}
},
TypeId.FloatLiteral => return T(@sqrt(f64, x)), // TODO upgrade to f128
TypeId.Float => return @sqrt(T, x),
TypeId.IntLiteral => comptime {
if (x > @maxValue(u128)) {
@compileError("sqrt not implemented for comptime_int greater than 128 bits");
@ -43,269 +25,58 @@ pub fn sqrt(x: var) (if (@typeId(@typeOf(x)) == TypeId.Int) @IntType(false, @typ
}
return T(sqrt_int(u128, x));
},
TypeId.Int => {
return sqrt_int(T, x);
},
TypeId.Int => return sqrt_int(T, x),
else => @compileError("sqrt not implemented for " ++ @typeName(T)),
}
}
fn sqrt32(x: f32) f32 {
const tiny: f32 = 1.0e-30;
const sign: i32 = @bitCast(i32, u32(0x80000000));
var ix: i32 = @bitCast(i32, x);
if ((ix & 0x7F800000) == 0x7F800000) {
return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan
}
// zero
if (ix <= 0) {
if (ix & ~sign == 0) {
return x; // sqrt (+-0) = +-0
}
if (ix < 0) {
return math.snan(f32);
}
}
// normalize
var m = ix >> 23;
if (m == 0) {
// subnormal
var i: i32 = 0;
while (ix & 0x00800000 == 0) : (i += 1) {
ix <<= 1;
}
m -= i - 1;
}
m -= 127; // unbias exponent
ix = (ix & 0x007FFFFF) | 0x00800000;
if (m & 1 != 0) { // odd m, double x to even
ix += ix;
}
m >>= 1; // m = [m / 2]
// sqrt(x) bit by bit
ix += ix;
var q: i32 = 0; // q = sqrt(x)
var s: i32 = 0;
var r: i32 = 0x01000000; // r = moving bit right -> left
while (r != 0) {
const t = s + r;
if (t <= ix) {
s = t + r;
ix -= t;
q += r;
}
ix += ix;
r >>= 1;
}
// floating add to find rounding direction
if (ix != 0) {
var z = 1.0 - tiny; // inexact
if (z >= 1.0) {
z = 1.0 + tiny;
if (z > 1.0) {
q += 2;
} else {
if (q & 1 != 0) {
q += 1;
}
}
}
}
ix = (q >> 1) + 0x3f000000;
ix += m << 23;
return @bitCast(f32, ix);
}
// NOTE: The original code is full of implicit signed -> unsigned assumptions and u32 wraparound
// behaviour. Most intermediate i32 values are changed to u32 where appropriate but there are
// potentially some edge cases remaining that are not handled in the same way.
fn sqrt64(x: f64) f64 {
const tiny: f64 = 1.0e-300;
const sign: u32 = 0x80000000;
const u = @bitCast(u64, x);
var ix0 = u32(u >> 32);
var ix1 = u32(u & 0xFFFFFFFF);
// sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = nan
if (ix0 & 0x7FF00000 == 0x7FF00000) {
return x * x + x;
}
// sqrt(+-0) = +-0
if (x == 0.0) {
return x;
}
// sqrt(-ve) = snan
if (ix0 & sign != 0) {
return math.snan(f64);
}
// normalize x
var m = i32(ix0 >> 20);
if (m == 0) {
// subnormal
while (ix0 == 0) {
m -= 21;
ix0 |= ix1 >> 11;
ix1 <<= 21;
}
// subnormal
var i: u32 = 0;
while (ix0 & 0x00100000 == 0) : (i += 1) {
ix0 <<= 1;
}
m -= i32(i) - 1;
ix0 |= ix1 >> u5(32 - i);
ix1 <<= u5(i);
}
// unbias exponent
m -= 1023;
ix0 = (ix0 & 0x000FFFFF) | 0x00100000;
if (m & 1 != 0) {
ix0 += ix0 + (ix1 >> 31);
ix1 = ix1 +% ix1;
}
m >>= 1;
// sqrt(x) bit by bit
ix0 += ix0 + (ix1 >> 31);
ix1 = ix1 +% ix1;
var q: u32 = 0;
var q1: u32 = 0;
var s0: u32 = 0;
var s1: u32 = 0;
var r: u32 = 0x00200000;
var t: u32 = undefined;
var t1: u32 = undefined;
while (r != 0) {
t = s0 +% r;
if (t <= ix0) {
s0 = t + r;
ix0 -= t;
q += r;
}
ix0 = ix0 +% ix0 +% (ix1 >> 31);
ix1 = ix1 +% ix1;
r >>= 1;
}
r = sign;
while (r != 0) {
t = s1 +% r;
t = s0;
if (t < ix0 or (t == ix0 and t1 <= ix1)) {
s1 = t1 +% r;
if (t1 & sign == sign and s1 & sign == 0) {
s0 += 1;
}
ix0 -= t;
if (ix1 < t1) {
ix0 -= 1;
}
ix1 = ix1 -% t1;
q1 += r;
}
ix0 = ix0 +% ix0 +% (ix1 >> 31);
ix1 = ix1 +% ix1;
r >>= 1;
}
// rounding direction
if (ix0 | ix1 != 0) {
var z = 1.0 - tiny; // raise inexact
if (z >= 1.0) {
z = 1.0 + tiny;
if (q1 == 0xFFFFFFFF) {
q1 = 0;
q += 1;
} else if (z > 1.0) {
if (q1 == 0xFFFFFFFE) {
q += 1;
}
q1 += 2;
} else {
q1 += q1 & 1;
}
}
}
ix0 = (q >> 1) + 0x3FE00000;
ix1 = q1 >> 1;
if (q & 1 != 0) {
ix1 |= 0x80000000;
}
// NOTE: musl here appears to rely on signed twos-complement wraparound. +% has the same
// behaviour at least.
var iix0 = i32(ix0);
iix0 = iix0 +% (m << 20);
const uz = (u64(iix0) << 32) | ix1;
return @bitCast(f64, uz);
}
test "math.sqrt" {
assert(sqrt(f32(0.0)) == sqrt32(0.0));
assert(sqrt(f64(0.0)) == sqrt64(0.0));
assert(sqrt(f32(0.0)) == @sqrt(f32, 0.0));
assert(sqrt(f64(0.0)) == @sqrt(f64, 0.0));
}
test "math.sqrt32" {
const epsilon = 0.000001;
assert(sqrt32(0.0) == 0.0);
assert(math.approxEq(f32, sqrt32(2.0), 1.414214, epsilon));
assert(math.approxEq(f32, sqrt32(3.6), 1.897367, epsilon));
assert(sqrt32(4.0) == 2.0);
assert(math.approxEq(f32, sqrt32(7.539840), 2.745877, epsilon));
assert(math.approxEq(f32, sqrt32(19.230934), 4.385309, epsilon));
assert(sqrt32(64.0) == 8.0);
assert(math.approxEq(f32, sqrt32(64.1), 8.006248, epsilon));
assert(math.approxEq(f32, sqrt32(8942.230469), 94.563370, epsilon));
assert(@sqrt(f32, 0.0) == 0.0);
assert(math.approxEq(f32, @sqrt(f32, 2.0), 1.414214, epsilon));
assert(math.approxEq(f32, @sqrt(f32, 3.6), 1.897367, epsilon));
assert(@sqrt(f32, 4.0) == 2.0);
assert(math.approxEq(f32, @sqrt(f32, 7.539840), 2.745877, epsilon));
assert(math.approxEq(f32, @sqrt(f32, 19.230934), 4.385309, epsilon));
assert(@sqrt(f32, 64.0) == 8.0);
assert(math.approxEq(f32, @sqrt(f32, 64.1), 8.006248, epsilon));
assert(math.approxEq(f32, @sqrt(f32, 8942.230469), 94.563370, epsilon));
}
test "math.sqrt64" {
const epsilon = 0.000001;
assert(sqrt64(0.0) == 0.0);
assert(math.approxEq(f64, sqrt64(2.0), 1.414214, epsilon));
assert(math.approxEq(f64, sqrt64(3.6), 1.897367, epsilon));
assert(sqrt64(4.0) == 2.0);
assert(math.approxEq(f64, sqrt64(7.539840), 2.745877, epsilon));
assert(math.approxEq(f64, sqrt64(19.230934), 4.385309, epsilon));
assert(sqrt64(64.0) == 8.0);
assert(math.approxEq(f64, sqrt64(64.1), 8.006248, epsilon));
assert(math.approxEq(f64, sqrt64(8942.230469), 94.563367, epsilon));
assert(@sqrt(f64, 0.0) == 0.0);
assert(math.approxEq(f64, @sqrt(f64, 2.0), 1.414214, epsilon));
assert(math.approxEq(f64, @sqrt(f64, 3.6), 1.897367, epsilon));
assert(@sqrt(f64, 4.0) == 2.0);
assert(math.approxEq(f64, @sqrt(f64, 7.539840), 2.745877, epsilon));
assert(math.approxEq(f64, @sqrt(f64, 19.230934), 4.385309, epsilon));
assert(@sqrt(f64, 64.0) == 8.0);
assert(math.approxEq(f64, @sqrt(f64, 64.1), 8.006248, epsilon));
assert(math.approxEq(f64, @sqrt(f64, 8942.230469), 94.563367, epsilon));
}
test "math.sqrt32.special" {
assert(math.isPositiveInf(sqrt32(math.inf(f32))));
assert(sqrt32(0.0) == 0.0);
assert(sqrt32(-0.0) == -0.0);
assert(math.isNan(sqrt32(-1.0)));
assert(math.isNan(sqrt32(math.nan(f32))));
assert(math.isPositiveInf(@sqrt(f32, math.inf(f32))));
assert(@sqrt(f32, 0.0) == 0.0);
assert(@sqrt(f32, -0.0) == -0.0);
assert(math.isNan(@sqrt(f32, -1.0)));
assert(math.isNan(@sqrt(f32, math.nan(f32))));
}
test "math.sqrt64.special" {
assert(math.isPositiveInf(sqrt64(math.inf(f64))));
assert(sqrt64(0.0) == 0.0);
assert(sqrt64(-0.0) == -0.0);
assert(math.isNan(sqrt64(-1.0)));
assert(math.isNan(sqrt64(math.nan(f64))));
assert(math.isPositiveInf(@sqrt(f64, math.inf(f64))));
assert(@sqrt(f64, 0.0) == 0.0);
assert(@sqrt(f64, -0.0) == -0.0);
assert(math.isNan(@sqrt(f64, -1.0)));
assert(math.isNan(@sqrt(f64, math.nan(f64))));
}
fn sqrt_int(comptime T: type, value: T) @IntType(false, T.bit_count / 2) {

View File

@ -1,15 +0,0 @@
pub fn sqrt32(x: f32) f32 {
return asm (
\\sqrtss %%xmm0, %%xmm0
: [ret] "={xmm0}" (-> f32)
: [x] "{xmm0}" (x)
);
}
pub fn sqrt64(x: f64) f64 {
return asm (
\\sqrtsd %%xmm0, %%xmm0
: [ret] "={xmm0}" (-> f64)
: [x] "{xmm0}" (x)
);
}

View File

@ -11,6 +11,8 @@ pub const Allocator = struct {
/// Allocate byte_count bytes and return them in a slice, with the
/// slice's pointer aligned at least to alignment bytes.
/// The returned newly allocated memory is undefined.
/// `alignment` is guaranteed to be >= 1
/// `alignment` is guaranteed to be a power of 2
allocFn: fn (self: &Allocator, byte_count: usize, alignment: u29) Error![]u8,
/// If `new_byte_count > old_mem.len`:
@ -18,10 +20,12 @@ pub const Allocator = struct {
/// * alignment >= alignment of old_mem.ptr
///
/// If `new_byte_count <= old_mem.len`:
/// * this function must return successfully.
/// * this function must return successfully.
/// * alignment <= alignment of old_mem.ptr
///
/// The returned newly allocated memory is undefined.
/// `alignment` is guaranteed to be >= 1
/// `alignment` is guaranteed to be a power of 2
reallocFn: fn (self: &Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8,
/// Guaranteed: `old_mem.len` is the same as what was returned from `allocFn` or `reallocFn`
@ -170,6 +174,20 @@ pub fn dupe(allocator: &Allocator, comptime T: type, m: []const T) ![]T {
return new_buf;
}
/// Remove values from the beginning of a slice.
pub fn trimLeft(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var begin: usize = 0;
while (begin < slice.len and indexOfScalar(T, values_to_strip, slice[begin]) != null) : (begin += 1) {}
return slice[begin..];
}
/// Remove values from the end of a slice.
pub fn trimRight(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var end: usize = slice.len;
while (end > 0 and indexOfScalar(T, values_to_strip, slice[end - 1]) != null) : (end -= 1) {}
return slice[0..end];
}
/// Remove values from the beginning and end of a slice.
pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var begin: usize = 0;
@ -180,6 +198,8 @@ pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []co
}
test "mem.trim" {
assert(eql(u8, trimLeft(u8, " foo\n ", " \n"), "foo\n "));
assert(eql(u8, trimRight(u8, " foo\n ", " \n"), " foo"));
assert(eql(u8, trim(u8, " foo\n ", " \n"), "foo"));
assert(eql(u8, trim(u8, "foo", " \n"), "foo"));
}
@ -189,6 +209,17 @@ pub fn indexOfScalar(comptime T: type, slice: []const T, value: T) ?usize {
return indexOfScalarPos(T, slice, 0, value);
}
/// Linear search for the last index of a scalar value inside a slice.
pub fn lastIndexOfScalar(comptime T: type, slice: []const T, value: T) ?usize {
var i: usize = slice.len;
while (i != 0) {
i -= 1;
if (slice[i] == value)
return i;
}
return null;
}
pub fn indexOfScalarPos(comptime T: type, slice: []const T, start_index: usize, value: T) ?usize {
var i: usize = start_index;
while (i < slice.len) : (i += 1) {
@ -202,6 +233,18 @@ pub fn indexOfAny(comptime T: type, slice: []const T, values: []const T) ?usize
return indexOfAnyPos(T, slice, 0, values);
}
pub fn lastIndexOfAny(comptime T: type, slice: []const T, values: []const T) ?usize {
var i: usize = slice.len;
while (i != 0) {
i -= 1;
for (values) |value| {
if (slice[i] == value)
return i;
}
}
return null;
}
pub fn indexOfAnyPos(comptime T: type, slice: []const T, start_index: usize, values: []const T) ?usize {
var i: usize = start_index;
while (i < slice.len) : (i += 1) {
@ -217,6 +260,22 @@ pub fn indexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize
return indexOfPos(T, haystack, 0, needle);
}
/// Find the index in a slice of a sub-slice, searching from the end backwards.
/// To start looking at a different index, slice the haystack first.
/// TODO is there even a better algorithm for this?
pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize {
if (needle.len > haystack.len)
return null;
var i: usize = haystack.len - needle.len;
while (true) : (i -= 1) {
if (mem.eql(T, haystack[i..i+needle.len], needle))
return i;
if (i == 0)
return null;
}
}
// TODO boyer-moore algorithm
pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
if (needle.len > haystack.len)
@ -233,9 +292,19 @@ pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, nee
test "mem.indexOf" {
assert(??indexOf(u8, "one two three four", "four") == 14);
assert(??lastIndexOf(u8, "one two three two four", "two") == 14);
assert(indexOf(u8, "one two three four", "gour") == null);
assert(lastIndexOf(u8, "one two three four", "gour") == null);
assert(??indexOf(u8, "foo", "foo") == 0);
assert(??lastIndexOf(u8, "foo", "foo") == 0);
assert(indexOf(u8, "foo", "fool") == null);
assert(lastIndexOf(u8, "foo", "lfoo") == null);
assert(lastIndexOf(u8, "foo", "fool") == null);
assert(??indexOf(u8, "foo foo", "foo") == 0);
assert(??lastIndexOf(u8, "foo foo", "foo") == 4);
assert(??lastIndexOfAny(u8, "boo, cat", "abo") == 6);
assert(??lastIndexOfScalar(u8, "boo", 'o') == 2);
}
/// Reads an integer from memory with size equal to bytes.len.
@ -355,9 +424,24 @@ pub fn startsWith(comptime T: type, haystack: []const T, needle: []const T) bool
return if (needle.len > haystack.len) false else eql(T, haystack[0 .. needle.len], needle);
}
test "mem.startsWith" {
assert(startsWith(u8, "Bob", "Bo"));
assert(!startsWith(u8, "Needle in haystack", "haystack"));
}
pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool {
return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len ..], needle);
}
test "mem.endsWith" {
assert(endsWith(u8, "Needle in haystack", "haystack"));
assert(!endsWith(u8, "Bob", "Bo"));
}
pub const SplitIterator = struct {
buffer: []const u8,
split_bytes: []const u8,
split_bytes: []const u8,
index: usize,
pub fn next(self: &SplitIterator) ?[]const u8 {

View File

@ -41,6 +41,11 @@ pub const SA_64REGSET = 0x0200; /// signal handler with SA_SIGINFO args with 64
pub const O_LARGEFILE = 0x0000;
pub const O_PATH = 0x0000;
pub const F_OK = 0;
pub const X_OK = 1;
pub const W_OK = 2;
pub const R_OK = 4;
pub const O_RDONLY = 0x0000; /// open for reading only
pub const O_WRONLY = 0x0001; /// open for writing only
pub const O_RDWR = 0x0002; /// open for reading and writing
@ -209,6 +214,10 @@ pub fn fork() usize {
return errnoWrap(c.fork());
}
pub fn access(path: &const u8, mode: u32) usize {
return errnoWrap(c.access(path, mode));
}
pub fn pipe(fds: &[2]i32) usize {
comptime assert(i32.bit_count == c_int.bit_count);
return errnoWrap(c.pipe(@ptrCast(&c_int, fds)));
@ -251,6 +260,10 @@ pub fn readlink(noalias path: &const u8, noalias buf_ptr: &u8, buf_len: usize) u
return errnoWrap(c.readlink(path, buf_ptr, buf_len));
}
pub fn gettimeofday(tv: ?&timeval, tz: ?&timezone) usize {
return errnoWrap(c.gettimeofday(tv, tz));
}
pub fn nanosleep(req: &const timespec, rem: ?&timespec) usize {
return errnoWrap(c.nanosleep(req, rem));
}
@ -321,3 +334,11 @@ pub fn sigaddset(set: &sigset_t, signo: u5) void {
fn errnoWrap(value: isize) usize {
return @bitCast(usize, if (value == -1) -isize(*c._errno()) else value);
}
pub const timezone = c.timezone;
pub const timeval = c.timeval;
pub const mach_timebase_info_data = c.mach_timebase_info_data;
pub const mach_absolute_time = c.mach_absolute_time;
pub const mach_timebase_info = c.mach_timebase_info;

26
std/os/epoch.zig Normal file
View File

@ -0,0 +1,26 @@
/// Epoch reference times in terms of their difference from
/// posix epoch in seconds.
pub const posix = 0; //Jan 01, 1970 AD
pub const dos = 315532800; //Jan 01, 1980 AD
pub const ios = 978307200; //Jan 01, 2001 AD
pub const openvms = -3506716800; //Nov 17, 1858 AD
pub const zos = -2208988800; //Jan 01, 1900 AD
pub const windows = -11644473600; //Jan 01, 1601 AD
pub const amiga = 252460800; //Jan 01, 1978 AD
pub const pickos = -63244800; //Dec 31, 1967 AD
pub const gps = 315964800; //Jan 06, 1980 AD
pub const clr = -62135769600; //Jan 01, 0001 AD
pub const unix = posix;
pub const android = posix;
pub const os2 = dos;
pub const bios = dos;
pub const vfat = dos;
pub const ntfs = windows;
pub const ntp = zos;
pub const jbase = pickos;
pub const aros = amiga;
pub const morphos = amiga;
pub const brew = gps;
pub const atsc = gps;
pub const go = clr;

View File

@ -85,6 +85,47 @@ pub const File = struct {
};
}
pub fn access(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) !bool {
const path_with_null = try std.cstr.addNullByte(allocator, path);
defer allocator.free(path_with_null);
if (is_posix) {
// mode is ignored and is always F_OK for now
const result = posix.access(path_with_null.ptr, posix.F_OK);
const err = posix.getErrno(result);
if (err > 0) {
return switch (err) {
posix.EACCES => error.PermissionDenied,
posix.EROFS => error.PermissionDenied,
posix.ELOOP => error.PermissionDenied,
posix.ETXTBSY => error.PermissionDenied,
posix.ENOTDIR => error.NotFound,
posix.ENOENT => error.NotFound,
posix.ENAMETOOLONG => error.NameTooLong,
posix.EINVAL => error.BadMode,
posix.EFAULT => error.BadPathName,
posix.EIO => error.Io,
posix.ENOMEM => error.SystemResources,
else => os.unexpectedErrorPosix(err),
};
}
return true;
} else if (is_windows) {
if (os.windows.PathFileExists(path_with_null.ptr) == os.windows.TRUE) {
return true;
}
const err = windows.GetLastError();
return switch (err) {
windows.ERROR.FILE_NOT_FOUND => error.NotFound,
windows.ERROR.ACCESS_DENIED => error.PermissionDenied,
else => os.unexpectedErrorWindows(err),
};
} else {
@compileError("TODO implement access for this OS");
}
}
/// Upon success, the stream is in an uninitialized state. To continue using it,
/// you must use the open() function.
@ -245,7 +286,9 @@ pub const File = struct {
};
}
return stat.mode;
// TODO: we should be able to cast u16 to ModeError!u32, making this
// explicit cast not necessary
return os.FileMode(stat.mode);
} else if (is_windows) {
return {};
} else {

View File

@ -9,11 +9,10 @@ test "std.os" {
_ = @import("darwin.zig");
_ = @import("darwin_errno.zig");
_ = @import("get_user_id.zig");
_ = @import("linux/errno.zig");
_ = @import("linux/index.zig");
_ = @import("linux/x86_64.zig");
_ = @import("path.zig");
_ = @import("test.zig");
_ = @import("time.zig");
_ = @import("windows/index.zig");
}
@ -32,6 +31,7 @@ pub const net = @import("net.zig");
pub const ChildProcess = @import("child_process.zig").ChildProcess;
pub const path = @import("path.zig");
pub const File = @import("file.zig").File;
pub const time = @import("time.zig");
pub const FileMode = switch (builtin.os) {
Os.windows => void,
@ -478,6 +478,7 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError {
};
}
pub var linux_aux_raw = []usize{0} ** 38;
pub var posix_environ_raw: []&u8 = undefined;
/// Caller must free result when done.
@ -1379,50 +1380,6 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 {
}
}
pub fn sleep(seconds: usize, nanoseconds: usize) void {
switch(builtin.os) {
Os.linux, Os.macosx, Os.ios => {
posixSleep(u63(seconds), u63(nanoseconds));
},
Os.windows => {
const milliseconds = seconds * 1000 + nanoseconds / 1000000;
windows.Sleep(windows.DWORD(milliseconds));
},
else => @compileError("Unsupported OS"),
}
}
const u63 = @IntType(false, 63);
pub fn posixSleep(seconds: u63, nanoseconds: u63) void {
var req = posix.timespec {
.tv_sec = seconds,
.tv_nsec = nanoseconds,
};
var rem: posix.timespec = undefined;
while (true) {
const ret_val = posix.nanosleep(&req, &rem);
const err = posix.getErrno(ret_val);
if (err == 0) return;
switch (err) {
posix.EFAULT => unreachable,
posix.EINVAL => {
// Sometimes Darwin returns EINVAL for no reason.
// We treat it as a spurious wakeup.
return;
},
posix.EINTR => {
req = rem;
continue;
},
else => return,
}
}
}
test "os.sleep" {
sleep(0, 1);
}
pub fn posix_setuid(uid: u32) !void {
const err = posix.getErrno(posix.setuid(uid));
if (err == 0) return;
@ -2384,3 +2341,132 @@ pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void {
posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
}
}
pub const Thread = struct {
pid: i32,
allocator: ?&mem.Allocator,
stack: []u8,
pub fn wait(self: &const Thread) void {
while (true) {
const pid_value = @atomicLoad(i32, &self.pid, builtin.AtomicOrder.SeqCst);
if (pid_value == 0) break;
const rc = linux.futex_wait(@ptrToInt(&self.pid), linux.FUTEX_WAIT, pid_value, null);
switch (linux.getErrno(rc)) {
0 => continue,
posix.EINTR => continue,
posix.EAGAIN => continue,
else => unreachable,
}
}
if (self.allocator) |a| {
a.free(self.stack);
}
}
};
pub const SpawnThreadError = error {
/// A system-imposed limit on the number of threads was encountered.
/// There are a number of limits that may trigger this error:
/// * the RLIMIT_NPROC soft resource limit (set via setrlimit(2)),
/// which limits the number of processes and threads for a real
/// user ID, was reached;
/// * the kernel's system-wide limit on the number of processes and
/// threads, /proc/sys/kernel/threads-max, was reached (see
/// proc(5));
/// * the maximum number of PIDs, /proc/sys/kernel/pid_max, was
/// reached (see proc(5)); or
/// * the PID limit (pids.max) imposed by the cgroup "process num
/// ber" (PIDs) controller was reached.
ThreadQuotaExceeded,
/// The kernel cannot allocate sufficient memory to allocate a task structure
/// for the child, or to copy those parts of the caller's context that need to
/// be copied.
SystemResources,
Unexpected,
};
pub const SpawnThreadAllocatorError = SpawnThreadError || error{OutOfMemory};
/// caller must call wait on the returned thread
/// fn startFn(@typeOf(context)) T
/// where T is u8, noreturn, void, or !void
pub fn spawnThreadAllocator(allocator: &mem.Allocator, context: var, comptime startFn: var) SpawnThreadAllocatorError!&Thread {
// TODO compile-time call graph analysis to determine stack upper bound
// https://github.com/zig-lang/zig/issues/157
const default_stack_size = 8 * 1024 * 1024;
const stack_bytes = try allocator.alloc(u8, default_stack_size);
const thread = try spawnThread(stack_bytes, context, startFn);
thread.allocator = allocator;
return thread;
}
/// stack must be big enough to store one Thread and one @typeOf(context), each with default alignment, at the end
/// fn startFn(@typeOf(context)) T
/// where T is u8, noreturn, void, or !void
/// caller must call wait on the returned thread
pub fn spawnThread(stack: []u8, context: var, comptime startFn: var) SpawnThreadError!&Thread {
const Context = @typeOf(context);
comptime assert(@ArgType(@typeOf(startFn), 0) == Context);
var stack_end: usize = @ptrToInt(stack.ptr) + stack.len;
var arg: usize = undefined;
if (@sizeOf(Context) != 0) {
stack_end -= @sizeOf(Context);
stack_end -= stack_end % @alignOf(Context);
assert(stack_end >= @ptrToInt(stack.ptr));
const context_ptr = @alignCast(@alignOf(Context), @intToPtr(&Context, stack_end));
*context_ptr = context;
arg = stack_end;
}
stack_end -= @sizeOf(Thread);
stack_end -= stack_end % @alignOf(Thread);
assert(stack_end >= @ptrToInt(stack.ptr));
const thread_ptr = @alignCast(@alignOf(Thread), @intToPtr(&Thread, stack_end));
thread_ptr.stack = stack;
thread_ptr.allocator = null;
const threadMain = struct {
extern fn threadMain(ctx_addr: usize) u8 {
if (@sizeOf(Context) == 0) {
return startFn({});
} else {
return startFn(*@intToPtr(&const Context, ctx_addr));
}
}
}.threadMain;
const flags = posix.CLONE_VM | posix.CLONE_FS | posix.CLONE_FILES | posix.CLONE_SIGHAND
| posix.CLONE_THREAD | posix.CLONE_SYSVSEM // | posix.CLONE_SETTLS
| posix.CLONE_PARENT_SETTID | posix.CLONE_CHILD_CLEARTID | posix.CLONE_DETACHED;
const newtls: usize = 0;
const rc = posix.clone(threadMain, stack_end, flags, arg, &thread_ptr.pid, newtls, &thread_ptr.pid);
const err = posix.getErrno(rc);
switch (err) {
0 => return thread_ptr,
posix.EAGAIN => return SpawnThreadError.ThreadQuotaExceeded,
posix.EINVAL => unreachable,
posix.ENOMEM => return SpawnThreadError.SystemResources,
posix.ENOSPC => unreachable,
posix.EPERM => unreachable,
posix.EUSERS => unreachable,
else => return unexpectedErrorPosix(err),
}
}
pub fn posixWait(pid: i32) i32 {
var status: i32 = undefined;
while (true) {
const err = posix.getErrno(posix.waitpid(pid, &status, 0));
switch (err) {
0 => return status,
posix.EINTR => continue,
posix.ECHILD => unreachable, // The process specified does not exist. It would be a race condition to handle this error.
posix.EINVAL => unreachable, // The options argument was invalid
else => unreachable,
}
}
}

View File

@ -1,6 +1,7 @@
const std = @import("../../index.zig");
const assert = std.debug.assert;
const builtin = @import("builtin");
const vdso = @import("vdso.zig");
pub use switch (builtin.arch) {
builtin.Arch.x86_64 => @import("x86_64.zig"),
builtin.Arch.i386 => @import("i386.zig"),
@ -14,6 +15,22 @@ pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const FUTEX_WAIT = 0;
pub const FUTEX_WAKE = 1;
pub const FUTEX_FD = 2;
pub const FUTEX_REQUEUE = 3;
pub const FUTEX_CMP_REQUEUE = 4;
pub const FUTEX_WAKE_OP = 5;
pub const FUTEX_LOCK_PI = 6;
pub const FUTEX_UNLOCK_PI = 7;
pub const FUTEX_TRYLOCK_PI = 8;
pub const FUTEX_WAIT_BITSET = 9;
pub const FUTEX_PRIVATE_FLAG = 128;
pub const FUTEX_CLOCK_REALTIME = 256;
pub const PROT_NONE = 0;
pub const PROT_READ = 1;
pub const PROT_WRITE = 2;
@ -38,6 +55,11 @@ pub const MAP_STACK = 0x20000;
pub const MAP_HUGETLB = 0x40000;
pub const MAP_FILE = 0;
pub const F_OK = 0;
pub const X_OK = 1;
pub const W_OK = 2;
pub const R_OK = 4;
pub const WNOHANG = 1;
pub const WUNTRACED = 2;
pub const WSTOPPED = 2;
@ -647,6 +669,10 @@ pub fn fork() usize {
return syscall0(SYS_fork);
}
pub fn futex_wait(uaddr: usize, futex_op: u32, val: i32, timeout: ?&timespec) usize {
return syscall4(SYS_futex, uaddr, futex_op, @bitCast(u32, val), @ptrToInt(timeout));
}
pub fn getcwd(buf: &u8, size: usize) usize {
return syscall2(SYS_getcwd, @ptrToInt(buf), size);
}
@ -705,6 +731,10 @@ pub fn pread(fd: i32, buf: &u8, count: usize, offset: usize) usize {
return syscall4(SYS_pread, usize(fd), @ptrToInt(buf), count, offset);
}
pub fn access(path: &const u8, mode: u32) usize {
return syscall2(SYS_access, @ptrToInt(path), mode);
}
pub fn pipe(fd: &[2]i32) usize {
return pipe2(fd, 0);
}
@ -737,6 +767,16 @@ pub fn openat(dirfd: i32, path: &const u8, flags: usize, mode: usize) usize {
return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode);
}
/// See also `clone` (from the arch-specific include)
pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: &i32, child_tid: &i32, newtls: usize) usize {
return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls);
}
/// See also `clone` (from the arch-specific include)
pub fn clone2(flags: usize, child_stack_ptr: usize) usize {
return syscall2(SYS_clone, flags, child_stack_ptr);
}
pub fn close(fd: i32) usize {
return syscall1(SYS_close, usize(fd));
}
@ -766,6 +806,45 @@ pub fn waitpid(pid: i32, status: &i32, options: i32) usize {
return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0);
}
pub fn clock_gettime(clk_id: i32, tp: &timespec) usize {
if (VDSO_CGT_SYM.len != 0) {
const f = @atomicLoad(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, builtin.AtomicOrder.Unordered);
if (@ptrToInt(f) != 0) {
const rc = f(clk_id, tp);
switch (rc) {
0, @bitCast(usize, isize(-EINVAL)) => return rc,
else => {},
}
}
}
return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
}
var vdso_clock_gettime = init_vdso_clock_gettime;
extern fn init_vdso_clock_gettime(clk: i32, ts: &timespec) usize {
const addr = vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM);
var f = @intToPtr(@typeOf(init_vdso_clock_gettime), addr);
_ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f,
builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic);
if (@ptrToInt(f) == 0) return @bitCast(usize, isize(-ENOSYS));
return f(clk, ts);
}
pub fn clock_getres(clk_id: i32, tp: &timespec) usize {
return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
}
pub fn clock_settime(clk_id: i32, tp: &const timespec) usize {
return syscall2(SYS_clock_settime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
}
pub fn gettimeofday(tv: &timeval, tz: &timezone) usize {
return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz));
}
pub fn settimeofday(tv: &const timeval, tz: &const timezone) usize {
return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz));
}
pub fn nanosleep(req: &const timespec, rem: ?&timespec) usize {
return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem));
}
@ -1250,9 +1329,7 @@ pub fn capset(hdrp: &cap_user_header_t, datap: &const cap_user_data_t) usize {
return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap));
}
test "import linux test" {
// TODO lazy analysis should prevent this test from being compiled on windows, but
// it is still compiled on windows
test "import" {
if (builtin.os == builtin.Os.linux) {
_ = @import("test.zig");
}

View File

@ -1,4 +1,5 @@
const std = @import("../../index.zig");
const builtin = @import("builtin");
const linux = std.os.linux;
const assert = std.debug.assert;

89
std/os/linux/vdso.zig Normal file
View File

@ -0,0 +1,89 @@
const std = @import("../../index.zig");
const elf = std.elf;
const linux = std.os.linux;
const cstr = std.cstr;
const mem = std.mem;
pub fn lookup(vername: []const u8, name: []const u8) usize {
const vdso_addr = std.os.linux_aux_raw[std.elf.AT_SYSINFO_EHDR];
if (vdso_addr == 0) return 0;
const eh = @intToPtr(&elf.Ehdr, vdso_addr);
var ph_addr: usize = vdso_addr + eh.e_phoff;
const ph = @intToPtr(&elf.Phdr, ph_addr);
var maybe_dynv: ?&usize = null;
var base: usize = @maxValue(usize);
{
var i: usize = 0;
while (i < eh.e_phnum) : ({i += 1; ph_addr += eh.e_phentsize;}) {
const this_ph = @intToPtr(&elf.Phdr, ph_addr);
switch (this_ph.p_type) {
elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr,
elf.PT_DYNAMIC => maybe_dynv = @intToPtr(&usize, vdso_addr + this_ph.p_offset),
else => {},
}
}
}
const dynv = maybe_dynv ?? return 0;
if (base == @maxValue(usize)) return 0;
var maybe_strings: ?&u8 = null;
var maybe_syms: ?&elf.Sym = null;
var maybe_hashtab: ?&linux.Elf_Symndx = null;
var maybe_versym: ?&u16 = null;
var maybe_verdef: ?&elf.Verdef = null;
{
var i: usize = 0;
while (dynv[i] != 0) : (i += 2) {
const p = base + dynv[i + 1];
switch (dynv[i]) {
elf.DT_STRTAB => maybe_strings = @intToPtr(&u8, p),
elf.DT_SYMTAB => maybe_syms = @intToPtr(&elf.Sym, p),
elf.DT_HASH => maybe_hashtab = @intToPtr(&linux.Elf_Symndx, p),
elf.DT_VERSYM => maybe_versym = @intToPtr(&u16, p),
elf.DT_VERDEF => maybe_verdef = @intToPtr(&elf.Verdef, p),
else => {},
}
}
}
const strings = maybe_strings ?? return 0;
const syms = maybe_syms ?? return 0;
const hashtab = maybe_hashtab ?? return 0;
if (maybe_verdef == null) maybe_versym = null;
const OK_TYPES = (1<<elf.STT_NOTYPE | 1<<elf.STT_OBJECT | 1<<elf.STT_FUNC | 1<<elf.STT_COMMON);
const OK_BINDS = (1<<elf.STB_GLOBAL | 1<<elf.STB_WEAK | 1<<elf.STB_GNU_UNIQUE);
var i: usize = 0;
while (i < hashtab[1]) : (i += 1) {
if (0==(u32(1)<<u5(syms[i].st_info&0xf) & OK_TYPES)) continue;
if (0==(u32(1)<<u5(syms[i].st_info>>4) & OK_BINDS)) continue;
if (0==syms[i].st_shndx) continue;
if (!mem.eql(u8, name, cstr.toSliceConst(&strings[syms[i].st_name]))) continue;
if (maybe_versym) |versym| {
if (!checkver(??maybe_verdef, versym[i], vername, strings))
continue;
}
return base + syms[i].st_value;
}
return 0;
}
fn checkver(def_arg: &elf.Verdef, vsym_arg: i32, vername: []const u8, strings: &u8) bool {
var def = def_arg;
const vsym = @bitCast(u32, vsym_arg) & 0x7fff;
while (true) {
if (0==(def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym)
break;
if (def.vd_next == 0)
return false;
def = @intToPtr(&elf.Verdef, @ptrToInt(def) + def.vd_next);
}
const aux = @intToPtr(&elf.Verdaux, @ptrToInt(def ) + def.vd_aux);
return mem.eql(u8, vername, cstr.toSliceConst(&strings[aux.vda_name]));
}

View File

@ -371,6 +371,13 @@ pub const F_GETOWN_EX = 16;
pub const F_GETOWNER_UIDS = 17;
pub const VDSO_USEFUL = true;
pub const VDSO_CGT_SYM = "__vdso_clock_gettime";
pub const VDSO_CGT_VER = "LINUX_2.6";
pub const VDSO_GETCPU_SYM = "__vdso_getcpu";
pub const VDSO_GETCPU_VER = "LINUX_2.6";
pub fn syscall0(number: usize) usize {
return asm volatile ("syscall"
: [ret] "={rax}" (-> usize)
@ -443,6 +450,9 @@ pub fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
: "rcx", "r11");
}
/// This matches the libc clone function.
pub extern fn clone(func: extern fn(arg: usize) u8, stack: usize, flags: usize, arg: usize, ptid: &i32, tls: usize, ctid: &i32) usize;
pub nakedcc fn restore_rt() void {
return asm volatile ("syscall"
:
@ -489,6 +499,16 @@ pub const timespec = extern struct {
tv_nsec: isize,
};
pub const timeval = extern struct {
tv_sec: isize,
tv_usec: isize,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const dirent = extern struct {
d_ino: usize,
d_off: usize,
@ -496,3 +516,4 @@ pub const dirent = extern struct {
d_name: u8, // field address is the address of first byte of name
};
pub const Elf_Symndx = u32;

View File

@ -6,6 +6,8 @@ const io = std.io;
const a = std.debug.global_allocator;
const builtin = @import("builtin");
const AtomicRmwOp = builtin.AtomicRmwOp;
const AtomicOrder = builtin.AtomicOrder;
test "makePath, put some files in it, deleteTree" {
if (builtin.os == builtin.Os.windows) {
@ -23,3 +25,57 @@ test "makePath, put some files in it, deleteTree" {
assert(err == error.PathNotFound);
}
}
test "access file" {
if (builtin.os == builtin.Os.windows) {
return;
}
try os.makePath(a, "os_test_tmp");
if (os.File.access(a, "os_test_tmp/file.txt", os.default_file_mode)) |ok| {
unreachable;
} else |err| {
assert(err == error.NotFound);
}
try io.writeFile(a, "os_test_tmp/file.txt", "");
assert((try os.File.access(a, "os_test_tmp/file.txt", os.default_file_mode)) == true);
try os.deleteTree(a, "os_test_tmp");
}
test "spawn threads" {
if (builtin.os != builtin.Os.linux) {
// TODO implement threads on macos and windows
return;
}
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
var shared_ctx: i32 = 1;
const thread1 = try std.os.spawnThreadAllocator(&direct_allocator.allocator, {}, start1);
const thread4 = try std.os.spawnThreadAllocator(&direct_allocator.allocator, &shared_ctx, start2);
var stack1: [1024]u8 = undefined;
var stack2: [1024]u8 = undefined;
const thread2 = try std.os.spawnThread(stack1[0..], &shared_ctx, start2);
const thread3 = try std.os.spawnThread(stack2[0..], &shared_ctx, start2);
thread1.wait();
thread2.wait();
thread3.wait();
thread4.wait();
assert(shared_ctx == 4);
}
fn start1(ctx: void) u8 {
return 0;
}
fn start2(ctx: &i32) u8 {
_ = @atomicRmw(i32, ctx, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst);
return 0;
}

288
std/os/time.zig Normal file
View File

@ -0,0 +1,288 @@
const std = @import("../index.zig");
const builtin = @import("builtin");
const Os = builtin.Os;
const debug = std.debug;
const windows = std.os.windows;
const linux = std.os.linux;
const darwin = std.os.darwin;
const posix = std.os.posix;
pub const epoch = @import("epoch.zig");
/// Sleep for the specified duration
pub fn sleep(seconds: usize, nanoseconds: usize) void {
switch (builtin.os) {
Os.linux, Os.macosx, Os.ios => {
posixSleep(u63(seconds), u63(nanoseconds));
},
Os.windows => {
const ns_per_ms = ns_per_s / ms_per_s;
const milliseconds = seconds * ms_per_s + nanoseconds / ns_per_ms;
windows.Sleep(windows.DWORD(milliseconds));
},
else => @compileError("Unsupported OS"),
}
}
const u63 = @IntType(false, 63);
pub fn posixSleep(seconds: u63, nanoseconds: u63) void {
var req = posix.timespec {
.tv_sec = seconds,
.tv_nsec = nanoseconds,
};
var rem: posix.timespec = undefined;
while (true) {
const ret_val = posix.nanosleep(&req, &rem);
const err = posix.getErrno(ret_val);
if (err == 0) return;
switch (err) {
posix.EFAULT => unreachable,
posix.EINVAL => {
// Sometimes Darwin returns EINVAL for no reason.
// We treat it as a spurious wakeup.
return;
},
posix.EINTR => {
req = rem;
continue;
},
else => return,
}
}
}
/// Get the posix timestamp, UTC, in seconds
pub fn timestamp() u64 {
return @divFloor(milliTimestamp(), ms_per_s);
}
/// Get the posix timestamp, UTC, in milliseconds
pub const milliTimestamp = switch (builtin.os) {
Os.windows => milliTimestampWindows,
Os.linux => milliTimestampPosix,
Os.macosx, Os.ios => milliTimestampDarwin,
else => @compileError("Unsupported OS"),
};
fn milliTimestampWindows() u64 {
//FileTime has a granularity of 100 nanoseconds
// and uses the NTFS/Windows epoch
var ft: i64 = undefined;
windows.GetSystemTimeAsFileTime(&ft);
const hns_per_ms = (ns_per_s / 100) / ms_per_s;
const epoch_adj = epoch.windows * ms_per_s;
return u64(@divFloor(ft, hns_per_ms) + epoch_adj);
}
fn milliTimestampDarwin() u64 {
//Sources suggest MacOS 10.12 has support for
// posix clock_gettime.
var tv: darwin.timeval = undefined;
var err = darwin.gettimeofday(&tv, null);
debug.assert(err == 0);
const sec_ms = u64(tv.tv_sec) * ms_per_s;
const usec_ms = @divFloor(u64(tv.tv_usec), us_per_s / ms_per_s);
return u64(sec_ms) + u64(usec_ms);
}
fn milliTimestampPosix() u64 {
//From what I can tell there's no reason clock_gettime
// should ever fail for us with CLOCK_REALTIME,
// seccomp aside.
var ts: posix.timespec = undefined;
const err = posix.clock_gettime(posix.CLOCK_REALTIME, &ts);
debug.assert(err == 0);
const sec_ms = u64(ts.tv_sec) * ms_per_s;
const nsec_ms = @divFloor(u64(ts.tv_nsec), ns_per_s / ms_per_s);
return sec_ms + nsec_ms;
}
/// Divisions of a second
pub const ns_per_s = 1000000000;
pub const us_per_s = 1000000;
pub const ms_per_s = 1000;
pub const cs_per_s = 100;
/// Common time divisions
pub const s_per_min = 60;
pub const s_per_hour = s_per_min * 60;
pub const s_per_day = s_per_hour * 24;
pub const s_per_week = s_per_day * 7;
/// A monotonic high-performance timer.
/// Timer.start() must be called to initialize the struct, which captures
/// the counter frequency on windows and darwin, records the resolution,
/// and gives the user an oportunity to check for the existnece of
/// monotonic clocks without forcing them to check for error on each read.
/// .resolution is in nanoseconds on all platforms but .start_time's meaning
/// depends on the OS. On Windows and Darwin it is a hardware counter
/// value that requires calculation to convert to a meaninful unit.
pub const Timer = struct {
//if we used resolution's value when performing the
// performance counter calc on windows/darwin, it would
// be less precise
frequency: switch (builtin.os) {
Os.windows => u64,
Os.macosx, Os.ios => darwin.mach_timebase_info_data,
else => void,
},
resolution: u64,
start_time: u64,
//At some point we may change our minds on RAW, but for now we're
// sticking with posix standard MONOTONIC. For more information, see:
// https://github.com/zig-lang/zig/pull/933
//
//const monotonic_clock_id = switch(builtin.os) {
// Os.linux => linux.CLOCK_MONOTONIC_RAW,
// else => posix.CLOCK_MONOTONIC,
//};
const monotonic_clock_id = posix.CLOCK_MONOTONIC;
/// Initialize the timer structure.
//This gives us an oportunity to grab the counter frequency in windows.
//On Windows: QueryPerformanceCounter will succeed on anything >= XP/2000.
//On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not
// supported, or if the timespec pointer is out of bounds, which should be
// impossible here barring cosmic rays or other such occurances of
// incredibly bad luck.
//On Darwin: This cannot fail, as far as I am able to tell.
const TimerError = error{TimerUnsupported, Unexpected};
pub fn start() TimerError!Timer {
var self: Timer = undefined;
switch (builtin.os) {
Os.windows => {
var freq: i64 = undefined;
var err = windows.QueryPerformanceFrequency(&freq);
if (err == windows.FALSE) return error.TimerUnsupported;
self.frequency = u64(freq);
self.resolution = @divFloor(ns_per_s, self.frequency);
var start_time: i64 = undefined;
err = windows.QueryPerformanceCounter(&start_time);
debug.assert(err != windows.FALSE);
self.start_time = u64(start_time);
},
Os.linux => {
//On Linux, seccomp can do arbitrary things to our ability to call
// syscalls, including return any errno value it wants and
// inconsistently throwing errors. Since we can't account for
// abuses of seccomp in a reasonable way, we'll assume that if
// seccomp is going to block us it will at least do so consistently
var ts: posix.timespec = undefined;
var result = posix.clock_getres(monotonic_clock_id, &ts);
var errno = posix.getErrno(result);
switch (errno) {
0 => {},
posix.EINVAL => return error.TimerUnsupported,
else => return std.os.unexpectedErrorPosix(errno),
}
self.resolution = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec);
result = posix.clock_gettime(monotonic_clock_id, &ts);
errno = posix.getErrno(result);
if (errno != 0) return std.os.unexpectedErrorPosix(errno);
self.start_time = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec);
},
Os.macosx, Os.ios => {
darwin.mach_timebase_info(&self.frequency);
self.resolution = @divFloor(self.frequency.numer, self.frequency.denom);
self.start_time = darwin.mach_absolute_time();
},
else => @compileError("Unsupported OS"),
}
return self;
}
/// Reads the timer value since start or the last reset in nanoseconds
pub fn read(self: &Timer) u64 {
var clock = clockNative() - self.start_time;
return switch (builtin.os) {
Os.windows => @divFloor(clock * ns_per_s, self.frequency),
Os.linux => clock,
Os.macosx, Os.ios => @divFloor(clock * self.frequency.numer, self.frequency.denom),
else => @compileError("Unsupported OS"),
};
}
/// Resets the timer value to 0/now.
pub fn reset(self: &Timer) void
{
self.start_time = clockNative();
}
/// Returns the current value of the timer in nanoseconds, then resets it
pub fn lap(self: &Timer) u64 {
var now = clockNative();
var lap_time = self.read();
self.start_time = now;
return lap_time;
}
const clockNative = switch (builtin.os) {
Os.windows => clockWindows,
Os.linux => clockLinux,
Os.macosx, Os.ios => clockDarwin,
else => @compileError("Unsupported OS"),
};
fn clockWindows() u64 {
var result: i64 = undefined;
var err = windows.QueryPerformanceCounter(&result);
debug.assert(err != windows.FALSE);
return u64(result);
}
fn clockDarwin() u64 {
return darwin.mach_absolute_time();
}
fn clockLinux() u64 {
var ts: posix.timespec = undefined;
var result = posix.clock_gettime(monotonic_clock_id, &ts);
debug.assert(posix.getErrno(result) == 0);
return u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec);
}
};
test "os.time.sleep" {
sleep(0, 1);
}
test "os.time.timestamp" {
const ns_per_ms = (ns_per_s / ms_per_s);
const margin = 50;
const time_0 = milliTimestamp();
sleep(0, ns_per_ms);
const time_1 = milliTimestamp();
const interval = time_1 - time_0;
debug.assert(interval > 0 and interval < margin);
}
test "os.time.Timer" {
const ns_per_ms = (ns_per_s / ms_per_s);
const margin = ns_per_ms * 50;
var timer = try Timer.start();
sleep(0, 10 * ns_per_ms);
const time_0 = timer.read();
debug.assert(time_0 > 0 and time_0 < margin);
const time_1 = timer.lap();
debug.assert(time_1 > time_0);
timer.reset();
debug.assert(timer.read() < time_1);
}

View File

@ -61,6 +61,8 @@ pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA(hFile: HANDLE, lpsz
pub extern "kernel32" stdcallcc fn GetProcessHeap() ?HANDLE;
pub extern "kernel32" stdcallcc fn GetSystemTimeAsFileTime(?&FILETIME) void;
pub extern "kernel32" stdcallcc fn HeapCreate(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T) ?HANDLE;
pub extern "kernel32" stdcallcc fn HeapDestroy(hHeap: HANDLE) BOOL;
pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void, dwBytes: SIZE_T) ?&c_void;
@ -77,6 +79,12 @@ pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem
pub extern "kernel32" stdcallcc fn MoveFileExA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR,
dwFlags: DWORD) BOOL;
pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: &LARGE_INTEGER) BOOL;
pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: &LARGE_INTEGER) BOOL;
pub extern "kernel32" stdcallcc fn PathFileExists(pszPath: ?LPCTSTR) BOOL;
pub extern "kernel32" stdcallcc fn ReadFile(in_hFile: HANDLE, out_lpBuffer: &c_void,
in_nNumberOfBytesToRead: DWORD, out_lpNumberOfBytesRead: &DWORD,
@ -137,6 +145,7 @@ pub const UNICODE = false;
pub const WCHAR = u16;
pub const WORD = u16;
pub const LARGE_INTEGER = i64;
pub const FILETIME = i64;
pub const TRUE = 1;
pub const FALSE = 0;
@ -308,3 +317,7 @@ pub const FILE_END = 2;
pub const HEAP_CREATE_ENABLE_EXECUTE = 0x00040000;
pub const HEAP_GENERATE_EXCEPTIONS = 0x00000004;
pub const HEAP_NO_SERIALIZE = 0x00000001;
test "import" {
_ = @import("util.zig");
}

View File

@ -19,6 +19,7 @@ const builtin = @import("builtin");
const assert = std.debug.assert;
const mem = std.mem;
const math = std.math;
const ziggurat = @import("ziggurat.zig");
// When you need fast unbiased random numbers
pub const DefaultPrng = Xoroshiro128;
@ -109,15 +110,28 @@ pub const Random = struct {
}
}
/// Return a floating point value normally distributed in the range [0, 1].
/// Return a floating point value normally distributed with mean = 0, stddev = 1.
///
/// To use different parameters, use: floatNorm(...) * desiredStddev + desiredMean.
pub fn floatNorm(r: &Random, comptime T: type) T {
// TODO(tiehuis): See https://www.doornik.com/research/ziggurat.pdf
@compileError("floatNorm is unimplemented");
const value = ziggurat.next_f64(r, ziggurat.NormDist);
switch (T) {
f32 => return f32(value),
f64 => return value,
else => @compileError("unknown floating point type"),
}
}
/// Return a exponentially distributed float between (0, @maxValue(f64))
/// Return an exponentially distributed float with a rate parameter of 1.
///
/// To use a different rate parameter, use: floatExp(...) / desiredRate.
pub fn floatExp(r: &Random, comptime T: type) T {
@compileError("floatExp is unimplemented");
const value = ziggurat.next_f64(r, ziggurat.ExpDist);
switch (T) {
f32 => return f32(value),
f64 => return value,
else => @compileError("unknown floating point type"),
}
}
/// Shuffle a slice into a random order.

146
std/rand/ziggurat.zig Normal file
View File

@ -0,0 +1,146 @@
// Implements ZIGNOR [1].
//
// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to Generate Normal Random Samples*]
// (https://www.doornik.com/research/ziggurat.pdf). Nuffield College, Oxford.
//
// rust/rand used as a reference;
//
// NOTE: This seems interesting but reference code is a bit hard to grok:
// https://sbarral.github.io/etf.
const std = @import("../index.zig");
const math = std.math;
const Random = std.rand.Random;
pub fn next_f64(random: &Random, comptime tables: &const ZigTable) f64 {
while (true) {
// We manually construct a float from parts as we can avoid an extra random lookup here by
// using the unused exponent for the lookup table entry.
const bits = random.scalar(u64);
const i = usize(bits & 0xff);
const u = blk: {
if (tables.is_symmetric) {
// Generate a value in the range [2, 4) and scale into [-1, 1)
const repr = ((0x3ff + 1) << 52) | (bits >> 12);
break :blk @bitCast(f64, repr) - 3.0;
} else {
// Generate a value in the range [1, 2) and scale into (0, 1)
const repr = (0x3ff << 52) | (bits >> 12);
break :blk @bitCast(f64, repr) - (1.0 - math.f64_epsilon / 2.0);
}
};
const x = u * tables.x[i];
const test_x = if (tables.is_symmetric) math.fabs(x) else x;
// equivalent to |u| < tables.x[i+1] / tables.x[i] (or u < tables.x[i+1] / tables.x[i])
if (test_x < tables.x[i + 1]) {
return x;
}
if (i == 0) {
return tables.zero_case(random, u);
}
// equivalent to f1 + DRanU() * (f0 - f1) < 1
if (tables.f[i + 1] + (tables.f[i] - tables.f[i + 1]) * random.float(f64) < tables.pdf(x)) {
return x;
}
}
}
pub const ZigTable = struct {
r: f64,
x: [257]f64,
f: [257]f64,
// probability density function used as a fallback
pdf: fn(f64) f64,
// whether the distribution is symmetric
is_symmetric: bool,
// fallback calculation in the case we are in the 0 block
zero_case: fn(&Random, f64) f64,
};
// zigNorInit
fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn(f64) f64,
comptime f_inv: fn(f64) f64, comptime zero_case: fn(&Random, f64) f64) ZigTable {
var tables: ZigTable = undefined;
tables.is_symmetric = is_symmetric;
tables.r = r;
tables.pdf = f;
tables.zero_case = zero_case;
tables.x[0] = v / f(r);
tables.x[1] = r;
for (tables.x[2..256]) |*entry, i| {
const last = tables.x[2 + i - 1];
*entry = f_inv(v / last + f(last));
}
tables.x[256] = 0;
for (tables.f[0..]) |*entry, i| {
*entry = f(tables.x[i]);
}
return tables;
}
// N(0, 1)
pub const NormDist = blk: {
@setEvalBranchQuota(30000);
break :blk ZigTableGen(true, norm_r, norm_v, norm_f, norm_f_inv, norm_zero_case);
};
const norm_r = 3.6541528853610088;
const norm_v = 0.00492867323399;
fn norm_f(x: f64) f64 { return math.exp(-x * x / 2.0); }
fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); }
fn norm_zero_case(random: &Random, u: f64) f64 {
var x: f64 = 1;
var y: f64 = 0;
while (-2.0 * y < x * x) {
x = math.ln(random.float(f64)) / norm_r;
y = math.ln(random.float(f64));
}
if (u < 0) {
return x - norm_r;
} else {
return norm_r - x;
}
}
test "ziggurant normal dist sanity" {
var prng = std.rand.DefaultPrng.init(0);
var i: usize = 0;
while (i < 1000) : (i += 1) {
_ = prng.random.floatNorm(f64);
}
}
// Exp(1)
pub const ExpDist = blk: {
@setEvalBranchQuota(30000);
break :blk ZigTableGen(false, exp_r, exp_v, exp_f, exp_f_inv, exp_zero_case);
};
const exp_r = 7.69711747013104972;
const exp_v = 0.0039496598225815571993;
fn exp_f(x: f64) f64 { return math.exp(-x); }
fn exp_f_inv(y: f64) f64 { return -math.ln(y); }
fn exp_zero_case(random: &Random, _: f64) f64 { return exp_r - math.ln(random.float(f64)); }
test "ziggurant exp dist sanity" {
var prng = std.rand.DefaultPrng.init(0);
var i: usize = 0;
while (i < 1000) : (i += 1) {
_ = prng.random.floatExp(f64);
}
}

View File

@ -48,22 +48,33 @@ extern fn WinMainCRTStartup() noreturn {
fn posixCallMainAndExit() noreturn {
const argc = *argc_ptr;
const argv = @ptrCast(&&u8, &argc_ptr[1]);
const envp = @ptrCast(&?&u8, &argv[argc + 1]);
const envp_nullable = @ptrCast(&?&u8, &argv[argc + 1]);
var envp_count: usize = 0;
while (envp_nullable[envp_count]) |_| : (envp_count += 1) {}
const envp = @ptrCast(&&u8, envp_nullable)[0..envp_count];
if (builtin.os == builtin.Os.linux) {
const auxv = &@ptrCast(&usize, envp.ptr)[envp_count + 1];
var i: usize = 0;
while (auxv[i] != 0) : (i += 2) {
if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i+1];
}
std.debug.assert(std.os.linux_aux_raw[std.elf.AT_PAGESZ] == std.os.page_size);
}
std.os.posix.exit(callMainWithArgs(argc, argv, envp));
}
fn callMainWithArgs(argc: usize, argv: &&u8, envp: &?&u8) u8 {
fn callMainWithArgs(argc: usize, argv: &&u8, envp: []&u8) u8 {
std.os.ArgIteratorPosix.raw = argv[0..argc];
var env_count: usize = 0;
while (envp[env_count] != null) : (env_count += 1) {}
std.os.posix_environ_raw = @ptrCast(&&u8, envp)[0..env_count];
std.os.posix_environ_raw = envp;
return callMain();
}
extern fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) i32 {
return callMainWithArgs(usize(c_argc), c_argv, c_envp);
var env_count: usize = 0;
while (c_envp[env_count] != null) : (env_count += 1) {}
const envp = @ptrCast(&&u8, c_envp)[0..env_count];
return callMainWithArgs(usize(c_argc), c_argv, envp);
}
fn callMain() u8 {

View File

@ -54,14 +54,51 @@ export fn memmove(dest: ?&u8, src: ?&const u8, n: usize) ?&u8 {
}
comptime {
if (builtin.mode != builtin.Mode.ReleaseFast and builtin.os != builtin.Os.windows) {
if (builtin.mode != builtin.Mode.ReleaseFast and
builtin.mode != builtin.Mode.ReleaseSmall and
builtin.os != builtin.Os.windows) {
@export("__stack_chk_fail", __stack_chk_fail, builtin.GlobalLinkage.Strong);
}
if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) {
@export("clone", clone, builtin.GlobalLinkage.Strong);
}
}
extern fn __stack_chk_fail() noreturn {
@panic("stack smashing detected");
}
// TODO we should be able to put this directly in std/linux/x86_64.zig but
// it causes a segfault in release mode. this is a workaround of calling it
// across .o file boundaries. fix comptime @ptrCast of nakedcc functions.
nakedcc fn clone() void {
asm volatile (
\\ xor %%eax,%%eax
\\ mov $56,%%al
\\ mov %%rdi,%%r11
\\ mov %%rdx,%%rdi
\\ mov %%r8,%%rdx
\\ mov %%r9,%%r8
\\ mov 8(%%rsp),%%r10
\\ mov %%r11,%%r9
\\ and $-16,%%rsi
\\ sub $8,%%rsi
\\ mov %%rcx,(%%rsi)
\\ syscall
\\ test %%eax,%%eax
\\ jnz 1f
\\ xor %%ebp,%%ebp
\\ pop %%rdi
\\ call *%%r9
\\ mov %%eax,%%edi
\\ xor %%eax,%%eax
\\ mov $60,%%al
\\ syscall
\\ hlt
\\1: ret
\\
);
}
const math = @import("../math/index.zig");
export fn fmodf(x: f32, y: f32) f32 { return generic_fmod(f32, x, y); }
@ -159,3 +196,212 @@ fn isNan(comptime T: type, bits: T) bool {
unreachable;
}
}
// NOTE: The original code is full of implicit signed -> unsigned assumptions and u32 wraparound
// behaviour. Most intermediate i32 values are changed to u32 where appropriate but there are
// potentially some edge cases remaining that are not handled in the same way.
export fn sqrt(x: f64) f64 {
const tiny: f64 = 1.0e-300;
const sign: u32 = 0x80000000;
const u = @bitCast(u64, x);
var ix0 = u32(u >> 32);
var ix1 = u32(u & 0xFFFFFFFF);
// sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = nan
if (ix0 & 0x7FF00000 == 0x7FF00000) {
return x * x + x;
}
// sqrt(+-0) = +-0
if (x == 0.0) {
return x;
}
// sqrt(-ve) = snan
if (ix0 & sign != 0) {
return math.snan(f64);
}
// normalize x
var m = i32(ix0 >> 20);
if (m == 0) {
// subnormal
while (ix0 == 0) {
m -= 21;
ix0 |= ix1 >> 11;
ix1 <<= 21;
}
// subnormal
var i: u32 = 0;
while (ix0 & 0x00100000 == 0) : (i += 1) {
ix0 <<= 1;
}
m -= i32(i) - 1;
ix0 |= ix1 >> u5(32 - i);
ix1 <<= u5(i);
}
// unbias exponent
m -= 1023;
ix0 = (ix0 & 0x000FFFFF) | 0x00100000;
if (m & 1 != 0) {
ix0 += ix0 + (ix1 >> 31);
ix1 = ix1 +% ix1;
}
m >>= 1;
// sqrt(x) bit by bit
ix0 += ix0 + (ix1 >> 31);
ix1 = ix1 +% ix1;
var q: u32 = 0;
var q1: u32 = 0;
var s0: u32 = 0;
var s1: u32 = 0;
var r: u32 = 0x00200000;
var t: u32 = undefined;
var t1: u32 = undefined;
while (r != 0) {
t = s0 +% r;
if (t <= ix0) {
s0 = t + r;
ix0 -= t;
q += r;
}
ix0 = ix0 +% ix0 +% (ix1 >> 31);
ix1 = ix1 +% ix1;
r >>= 1;
}
r = sign;
while (r != 0) {
t = s1 +% r;
t = s0;
if (t < ix0 or (t == ix0 and t1 <= ix1)) {
s1 = t1 +% r;
if (t1 & sign == sign and s1 & sign == 0) {
s0 += 1;
}
ix0 -= t;
if (ix1 < t1) {
ix0 -= 1;
}
ix1 = ix1 -% t1;
q1 += r;
}
ix0 = ix0 +% ix0 +% (ix1 >> 31);
ix1 = ix1 +% ix1;
r >>= 1;
}
// rounding direction
if (ix0 | ix1 != 0) {
var z = 1.0 - tiny; // raise inexact
if (z >= 1.0) {
z = 1.0 + tiny;
if (q1 == 0xFFFFFFFF) {
q1 = 0;
q += 1;
} else if (z > 1.0) {
if (q1 == 0xFFFFFFFE) {
q += 1;
}
q1 += 2;
} else {
q1 += q1 & 1;
}
}
}
ix0 = (q >> 1) + 0x3FE00000;
ix1 = q1 >> 1;
if (q & 1 != 0) {
ix1 |= 0x80000000;
}
// NOTE: musl here appears to rely on signed twos-complement wraparound. +% has the same
// behaviour at least.
var iix0 = i32(ix0);
iix0 = iix0 +% (m << 20);
const uz = (u64(iix0) << 32) | ix1;
return @bitCast(f64, uz);
}
export fn sqrtf(x: f32) f32 {
const tiny: f32 = 1.0e-30;
const sign: i32 = @bitCast(i32, u32(0x80000000));
var ix: i32 = @bitCast(i32, x);
if ((ix & 0x7F800000) == 0x7F800000) {
return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan
}
// zero
if (ix <= 0) {
if (ix & ~sign == 0) {
return x; // sqrt (+-0) = +-0
}
if (ix < 0) {
return math.snan(f32);
}
}
// normalize
var m = ix >> 23;
if (m == 0) {
// subnormal
var i: i32 = 0;
while (ix & 0x00800000 == 0) : (i += 1) {
ix <<= 1;
}
m -= i - 1;
}
m -= 127; // unbias exponent
ix = (ix & 0x007FFFFF) | 0x00800000;
if (m & 1 != 0) { // odd m, double x to even
ix += ix;
}
m >>= 1; // m = [m / 2]
// sqrt(x) bit by bit
ix += ix;
var q: i32 = 0; // q = sqrt(x)
var s: i32 = 0;
var r: i32 = 0x01000000; // r = moving bit right -> left
while (r != 0) {
const t = s + r;
if (t <= ix) {
s = t + r;
ix -= t;
q += r;
}
ix += ix;
r >>= 1;
}
// floating add to find rounding direction
if (ix != 0) {
var z = 1.0 - tiny; // inexact
if (z >= 1.0) {
z = 1.0 + tiny;
if (z > 1.0) {
q += 2;
} else {
if (q & 1 != 0) {
q += 1;
}
}
}
}
ix = (q >> 1) + 0x3f000000;
ix += m << 23;
return @bitCast(f32, ix);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -12,6 +12,7 @@ comptime {
_ = @import("cases/bugs/655.zig");
_ = @import("cases/bugs/656.zig");
_ = @import("cases/bugs/828.zig");
_ = @import("cases/bugs/920.zig");
_ = @import("cases/cast.zig");
_ = @import("cases/const_slice_child.zig");
_ = @import("cases/coroutines.zig");

View File

@ -1,12 +1,24 @@
const assert = @import("std").debug.assert;
const std = @import("std");
const assert = std.debug.assert;
const builtin = @import("builtin");
const AtomicRmwOp = builtin.AtomicRmwOp;
const AtomicOrder = builtin.AtomicOrder;
test "cmpxchg" {
var x: i32 = 1234;
while (!@cmpxchg(&x, 1234, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) {}
if (@cmpxchgWeak(i32, &x, 99, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
assert(x1 == 1234);
} else {
@panic("cmpxchg should have failed");
}
while (@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
assert(x1 == 1234);
}
assert(x == 5678);
assert(@cmpxchgStrong(i32, &x, 5678, 42, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null);
assert(x == 42);
}
test "fence" {
@ -15,13 +27,45 @@ test "fence" {
x = 5678;
}
test "atomicrmw" {
test "atomicrmw and atomicload" {
var data: u8 = 200;
testAtomicRmw(&data);
assert(data == 42);
testAtomicLoad(&data);
}
fn testAtomicRmw(ptr: &u8) void {
const prev_value = @atomicRmw(u8, ptr, AtomicRmwOp.Xchg, 42, AtomicOrder.SeqCst);
assert(prev_value == 200);
comptime {
var x: i32 = 1234;
const y: i32 = 12345;
assert(@atomicLoad(i32, &x, AtomicOrder.SeqCst) == 1234);
assert(@atomicLoad(i32, &y, AtomicOrder.SeqCst) == 12345);
}
}
fn testAtomicLoad(ptr: &u8) void {
const x = @atomicLoad(u8, ptr, AtomicOrder.SeqCst);
assert(x == 42);
}
test "cmpxchg with ptr" {
var data1: i32 = 1234;
var data2: i32 = 5678;
var data3: i32 = 9101;
var x: &i32 = &data1;
if (@cmpxchgWeak(&i32, &x, &data2, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
assert(x1 == &data1);
} else {
@panic("cmpxchg should have failed");
}
while (@cmpxchgWeak(&i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
assert(x1 == &data1);
}
assert(x == &data3);
assert(@cmpxchgStrong(&i32, &x, &data3, &data2, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null);
assert(x == &data2);
}

60
test/cases/bugs/920.zig Normal file
View File

@ -0,0 +1,60 @@
const std = @import("std");
const math = std.math;
const Random = std.rand.Random;
const ZigTable = struct {
r: f64,
x: [257]f64,
f: [257]f64,
pdf: fn(f64) f64,
is_symmetric: bool,
zero_case: fn(&Random, f64) f64,
};
fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn(f64) f64,
comptime f_inv: fn(f64) f64, comptime zero_case: fn(&Random, f64) f64) ZigTable {
var tables: ZigTable = undefined;
tables.is_symmetric = is_symmetric;
tables.r = r;
tables.pdf = f;
tables.zero_case = zero_case;
tables.x[0] = v / f(r);
tables.x[1] = r;
for (tables.x[2..256]) |*entry, i| {
const last = tables.x[2 + i - 1];
*entry = f_inv(v / last + f(last));
}
tables.x[256] = 0;
for (tables.f[0..]) |*entry, i| {
*entry = f(tables.x[i]);
}
return tables;
}
const norm_r = 3.6541528853610088;
const norm_v = 0.00492867323399;
fn norm_f(x: f64) f64 { return math.exp(-x * x / 2.0); }
fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); }
fn norm_zero_case(random: &Random, u: f64) f64 { return 0.0; }
const NormalDist = blk: {
@setEvalBranchQuota(30000);
break :blk ZigTableGen(true, norm_r, norm_v, norm_f, norm_f_inv, norm_zero_case);
};
test "bug 920 fixed" {
const NormalDist1 = blk: {
break :blk ZigTableGen(true, norm_r, norm_v, norm_f, norm_f_inv, norm_zero_case);
};
for (NormalDist1.f) |_, i| {
std.debug.assert(NormalDist1.f[i] == NormalDist.f[i]);
}
}

View File

@ -224,3 +224,21 @@ async fn printTrace(p: promise->error!void) void {
}
};
}
test "break from suspend" {
var buf: [500]u8 = undefined;
var a = &std.heap.FixedBufferAllocator.init(buf[0..]).allocator;
var my_result: i32 = 1;
const p = try async<a> testBreakFromSuspend(&my_result);
cancel p;
std.debug.assert(my_result == 2);
}
async fn testBreakFromSuspend(my_result: &i32) void {
s: suspend |p| {
break :s;
}
*my_result += 1;
suspend;
*my_result += 1;
}

View File

@ -41,3 +41,14 @@ fn testBreakContInDefer(x: usize) void {
assert(i == 5);
}
}
test "defer and labeled break" {
var i = usize(0);
blk: {
defer i += 1;
break :blk;
}
assert(i == 1);
}

View File

@ -513,3 +513,19 @@ test "array concat of slices gives slice" {
assert(std.mem.eql(u8, c, "aoeuasdf"));
}
}
test "comptime shlWithOverflow" {
const ct_shifted: u64 = comptime amt: {
var amt = u64(0);
_ = @shlWithOverflow(u64, ~u64(0), 16, &amt);
break :amt amt;
};
const rt_shifted: u64 = amt: {
var amt = u64(0);
_ = @shlWithOverflow(u64, ~u64(0), 16, &amt);
break :amt amt;
};
assert(ct_shifted == rt_shifted);
}

View File

@ -104,3 +104,10 @@ test "number literal as an argument" {
fn numberLiteralArg(a: var) void {
assert(a == 3);
}
test "assign inline fn to const variable" {
const a = inlineFn;
a();
}
inline fn inlineFn() void { }

View File

@ -402,3 +402,19 @@ test "comptime float rem int" {
assert(x == 1.0);
}
}
test "@sqrt" {
testSqrt(f64, 12.0);
comptime testSqrt(f64, 12.0);
testSqrt(f32, 13.0);
comptime testSqrt(f32, 13.0);
const x = 14.0;
const y = x * x;
const z = @sqrt(@typeOf(y), y);
comptime assert(z == x);
}
fn testSqrt(comptime T: type, x: T) void {
assert(@sqrt(T, x * x) == x);
}

View File

@ -1,5 +1,6 @@
const assert = @import("std").debug.assert;
const mem = @import("std").mem;
const reflection = this;
test "reflection: array, pointer, nullable, error union type child" {
comptime {
@ -56,7 +57,30 @@ test "reflection: enum member types and names" {
}
test "reflection: @field" {
var f = Foo {
.one = 42,
.two = true,
.three = void{},
};
assert(f.one == f.one);
assert(@field(f, "o" ++ "ne") == f.one);
assert(@field(f, "t" ++ "wo") == f.two);
assert(@field(f, "th" ++ "ree") == f.three);
assert(@field(Foo, "const" ++ "ant") == Foo.constant);
assert(@field(Bar, "O" ++ "ne") == Bar.One);
assert(@field(Bar, "T" ++ "wo") == Bar.Two);
assert(@field(Bar, "Th" ++ "ree") == Bar.Three);
assert(@field(Bar, "F" ++ "our") == Bar.Four);
assert(@field(reflection, "dum" ++ "my")(true, 1, 2) == dummy(true, 1, 2));
@field(f, "o" ++ "ne") = 4;
assert(f.one == 4);
}
const Foo = struct {
const constant = 52;
one: i32,
two: bool,
three: void,

View File

@ -1,6 +1,55 @@
const tests = @import("tests.zig");
pub fn addCases(cases: &tests.CompileErrorContext) void {
cases.add("invalid deref on switch target",
\\comptime {
\\ var tile = Tile.Empty;
\\ switch (*tile) {
\\ Tile.Empty => {},
\\ Tile.Filled => {},
\\ }
\\}
\\const Tile = enum {
\\ Empty,
\\ Filled,
\\};
,
".tmp_source.zig:3:13: error: invalid deref on switch target");
cases.add("invalid field access in comptime",
\\comptime { var x = doesnt_exist.whatever; }
,
".tmp_source.zig:1:20: error: use of undeclared identifier 'doesnt_exist'");
cases.add("suspend inside suspend block",
\\const std = @import("std");
\\
\\export fn entry() void {
\\ var buf: [500]u8 = undefined;
\\ var a = &std.heap.FixedBufferAllocator.init(buf[0..]).allocator;
\\ const p = (async<a> foo()) catch unreachable;
\\ cancel p;
\\}
\\
\\async fn foo() void {
\\ suspend |p| {
\\ suspend |p1| {
\\ }
\\ }
\\}
,
".tmp_source.zig:12:9: error: cannot suspend inside suspend block",
".tmp_source.zig:11:5: note: other suspend block here");
cases.add("assign inline fn to non-comptime var",
\\export fn entry() void {
\\ var a = b;
\\}
\\inline fn b() void { }
,
".tmp_source.zig:2:5: error: functions marked inline must be stored in const or comptime var",
".tmp_source.zig:4:8: note: declared here");
cases.add("wrong type passed to @panic",
\\export fn entry() void {
\\ var e = error.Foo;
@ -1385,17 +1434,17 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
\\const AtomicOrder = @import("builtin").AtomicOrder;
\\export fn f() void {
\\ var x: i32 = 1234;
\\ while (!@cmpxchg(&x, 1234, 5678, AtomicOrder.Monotonic, AtomicOrder.SeqCst)) {}
\\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Monotonic, AtomicOrder.SeqCst)) {}
\\}
, ".tmp_source.zig:4:72: error: failure atomic ordering must be no stricter than success");
, ".tmp_source.zig:4:81: error: failure atomic ordering must be no stricter than success");
cases.add("atomic orderings of cmpxchg - success Monotonic or stricter",
\\const AtomicOrder = @import("builtin").AtomicOrder;
\\export fn f() void {
\\ var x: i32 = 1234;
\\ while (!@cmpxchg(&x, 1234, 5678, AtomicOrder.Unordered, AtomicOrder.Unordered)) {}
\\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Unordered, AtomicOrder.Unordered)) {}
\\}
, ".tmp_source.zig:4:49: error: success atomic ordering must be Monotonic or stricter");
, ".tmp_source.zig:4:58: error: success atomic ordering must be Monotonic or stricter");
cases.add("negation overflow in function evaluation",
\\const y = neg(-128);
@ -2451,11 +2500,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
\\const AtomicOrder = @import("builtin").AtomicOrder;
\\export fn entry() bool {
\\ var x: i32 align(1) = 1234;
\\ while (!@cmpxchg(&x, 1234, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) {}
\\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) {}
\\ return x == 5678;
\\}
,
".tmp_source.zig:4:23: error: expected pointer alignment of at least 4, found 1");
".tmp_source.zig:4:32: error: expected type '&i32', found '&align(1) i32'");
cases.add("wrong size to an array literal",
\\comptime {
@ -2525,10 +2574,10 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
cases.add("wrong types given to atomic order args in cmpxchg",
\\export fn entry() void {
\\ var x: i32 = 1234;
\\ while (!@cmpxchg(&x, 1234, 5678, u32(1234), u32(1234))) {}
\\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, u32(1234), u32(1234))) {}
\\}
,
".tmp_source.zig:3:41: error: expected type 'AtomicOrder', found 'u32'");
".tmp_source.zig:3:50: error: expected type 'AtomicOrder', found 'u32'");
cases.add("wrong types given to @export",
\\extern fn entry() void { }

View File

@ -583,6 +583,7 @@ pub const CompileErrorContext = struct {
Mode.Debug => {},
Mode.ReleaseSafe => zig_args.append("--release-safe") catch unreachable,
Mode.ReleaseFast => zig_args.append("--release-fast") catch unreachable,
Mode.ReleaseSmall => zig_args.append("--release-small") catch unreachable,
}
warn("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name);