Commit Graph

204 Commits

Author SHA1 Message Date
Jakub Konka
a8ff51b092 stage2: turn several panics into codegen errors
Add x86_64 backend to behavior.zig test suite.
2022-01-04 02:06:18 +01:00
joachimschmidt557
c710d5eefe stage2 ARM: implement wrap_errunion_err for empty payloads 2022-01-02 15:15:59 -05:00
Andrew Kelley
ae8d6fd7b7 behavior tests: add a "passing for arm backend" section 2022-01-01 14:00:02 -07:00
Luuk de Gram
3de111d993
wasm: Fix loading from pointers to support defer
Previously, the `load` instruction would just pass the pointer to the next instruction
for types that comply to `isByRef`. However, this meant that a defer would directly write
to the reference, rather than a copy. After this commit, we always copy the value.
2022-01-01 16:23:21 +01:00
Luuk de Gram
ad1b040996
wasm: Implement pointer arithmetic and refactoring:
- This implements all pointer arithmetic related instructions such as ptr_add, ptr_sub, ptr_elem_val
- We refactored the code, to use `isByRef` to ensure consistancy.
- Pointers will now be loaded correctly, rather then being passed around.
- The behaviour test for pointers is now passing.
2022-01-01 12:59:43 +01:00
Luuk de Gram
28cfc49c3e
wasm: Implement memCpy and get if behavior tests passing 2022-01-01 12:59:43 +01:00
Luuk de Gram
b9a0401e23
wasm: Implement @ptrToInt and fix indirect function call
- Previously the table index and function type index were switched.
This commit swaps them.
- This also emits the correct indirect function calls count when importing the function table
2022-01-01 12:59:43 +01:00
Luuk de Gram
f644c8b047
wasm: Implement array_to_slice and bug fixes:
- Add method to easily create local for virtual stack
- Ensure function pointers are passed correctly
- Correctly handle slices as return types and values
- Fix wrapping error sets/payloads.
- Handle ptr-like optionals correctly, by using address '0' as null.
- Implement `array_to_slice`
- linker: Always emit a table, so call_indirect inside bodies do not fail if there's no table.
TODO: Only do this when we emit a call_indirect but the relocation cannot be resolved.
2022-01-01 12:59:18 +01:00
Luuk de Gram
29164a31cc
wasm: Pass 'bugs' behavior tests 2022-01-01 12:58:59 +01:00
Luuk de Gram
726ce85c10
wasm: Fix storing error. Pass bool.zig behavior tests 2022-01-01 12:58:12 +01:00
drew
2f53406ad8
CBE; implement airLoad and airStore for arrays (#10452)
Effectively a small continuation of #10152

This allows the for.zig behavior tests to pass. Unfortunately to fully test everything I had to move a lot of behavior tests from array.zig; most of them now pass (sorry @rainbowbismuth!)

I'm also conflicted on how I store constants into arrays because it's kind of stupid; array's can't be re-initialized using the same syntax, so instead of initializing each element, a new array is made which is copied into the destination. This also required that renderValue can't emit string literals for byte arrays given that they need to always have an extra byte for the NULL terminator, meaning that strings are no longer grep-able in the output.
2021-12-30 15:19:12 -05:00
Andrew Kelley
be5130ec53 compiler_rt: move more functions to the stage2 section
also move more already-passing behavior tests to the passing section.
2021-12-29 00:39:25 -07:00
Andrew Kelley
6ed7850972 Sema: fix anytype parameters whose types require comptime 2021-12-27 19:39:28 -07:00
Andrew Kelley
886df772f0 stage2: LLVM backend: fix const packed structs
When doing LLVM const bit shifting we must make sure the integer bit
sizes are wide enough or else LLVM gives us a poison result.
2021-12-27 16:59:26 -07:00
Matthew Hall
4266795743 stage2: make tests/behaviour/void.zig work with c backend
* fix initialisation of void* fields of structs (initialises to 0xaa.. rather than {})
* don't generate struct fields when the field type does not have codegen bits
* in airAlloc generate a void* literal if the element type does not have codegen bits
2021-12-27 14:42:25 -08:00
Andrew Kelley
70894d5c2f AstGen: fix loop result locations
The main problem was that the loop body was treated as an expression
that was one of the peer result values of a loop, when in reality the
loop body is noreturn and only the `break` operands are the result
values of loops.

This was solved by introducing an override that prevents rvalue() from
emitting a store to result location instruction for loop bodies.

An orthogonal change also included in this commit is switching
`elem_val` index expressions to using `coerced_ty` and doing the
coercion to `usize` inside `Sema`, resulting in smaller ZIR (since the
cast becomes implied).

I also changed the break operand expression to use `reachableExpr`,
introducing a new compile error for double break.

This makes a few more behavior tests pass for `while` and `for` loops.
2021-12-27 15:30:31 -07:00
Andrew Kelley
c8fb36b36c stage2: LLVM backend: implement @tagName for enums
Introduced a new AIR instruction: `tag_name`. Reasons to do this
instead of lowering it in Sema to a switch, function call, array
lookup, or if-else tower:
 * Sema is a bottleneck; do less work in Sema whenever possible.
 * If any optimization passes run, and the operand to becomes
   comptime-known, then it could change to have a comptime result
   value instead of lowering to a function or array or something which
   would then have to be garbage-collected.
 * Backends may want to choose to use a function and a switch branch,
   or they may want to use a different strategy.

Codegen for `@tagName` is implemented for the LLVM backend but not any
others yet.

Introduced some new `Type` tags:
 * `const_slice_u8_sentinel_0`
 * `manyptr_const_u8_sentinel_0`

The motivation for this was to make typeof() on the tag_name AIR
instruction non-allocating.

A bunch more enum tests are passing now.
2021-12-27 01:14:50 -07:00
Isaac Freund
7bb6393b59
stage1: implement @prefetch() builtin 2021-12-11 00:29:31 +01:00
Andrew Kelley
38b2d62092 stage1: saturating shl operates using LHS type
Saturating shift left (`<<|`) previously used the `ir_analyze_bin_op_math`
codepath rather than the `ir_analyze_bit_shift` codepath, leading to it
doing peer type resolution (incorrect) instead of using the LHS type as
the number of bits to do the saturating against.

This required implementing SIMD vector support for `@truncate`.

Additionall, this commit adds a compile error for saturating shift left
on a comptime_int.

stage2 does not pass these new behavior tests yet.

closes #10298
2021-12-08 15:25:31 -07:00
Luuk de Gram
9e03cf9489 wasm: Initial behavior tests succeeding
- Correctly load slice value on stack
- Implement WrapErrorUnionErr and payload
- Implement trunc, fix sliceLen and write undefined
- Implement slice as return type and argument

Note: This also fixes a memory leak for inferred error sets, and for usingnamespace
2021-12-05 12:19:01 -08:00
Andrew Kelley
f7cbd92e6c Revert "Merge pull request #10270 from Luukdegram/behaviour-tests"
This reverts commit 725267f7c2, reversing
changes made to 2dae860de3.

This test is failing:

```zig
pub fn main() u8 {
    var e = foo();
    const i = e catch 69;
    return i;
}

fn foo() anyerror!u8 {
    return 5;
}
```

It's returning 69 instead of the expected value 5.
2021-12-04 21:55:50 -07:00
Luuk de Gram
74a5f4d848
wasm: Initial behavior tests succeeding
Note: This also fixes a memory leak for inferred error sets, and for usingnamespace
2021-12-04 21:17:17 +01:00
Andrew Kelley
1e0addcf73 put the passing stage2 behavior tests back
This mostly reverts commit 692c254336.

The test "for loop over pointers to struct, getting field from struct
pointer" is still failing on the CI so that one is not moved over.
2021-11-30 16:15:42 -07:00
Andrew Kelley
692c254336 Revert "I found some more passing behavior tests"
This reverts commit 0a9b4d092f.

Hm, these are all passing for me locally. I'll have to do some
troubleshooting to figure out which one(s) are failing on the CI.
2021-11-30 00:19:37 -07:00
Andrew Kelley
0a9b4d092f I found some more passing behavior tests 2021-11-29 22:36:52 -07:00
Andrew Kelley
17f057c556 stage2: implement @typeName
* stage1: change the `@typeName` of `@TypeOf(undefined)`,
   `@TypeOf(null)`, and `@TypeOf(.foo)` to match stage2.
 * move passing behavior tests to the passing-for-stage2 section.
2021-11-27 00:27:52 -07:00
Andrew Kelley
f0deef1d79 Sema: fix analyzeBlockBody logic
Previously, when a coercion needed to be inserted into a break
instruction, the `br` AIR instruction would be rewritten so that the
block operand was a sub-block that did the coercion. The problem is that
the sub-block itself was never added to the parent block, resulting in
the `br` instruction operand being a bad reference.

Now, the `br` AIR instruction that needs to have coercion instructions
added is replaced with the sub-block itself with type `noreturn`, and
then the sub-block has the coercion instructions and a new `br`
instruction that breaks from the original block.

LLVM backend needed to be fixed to lower `noreturn` blocks without
emitting an unused LLVM basic block.
2021-11-26 23:17:01 -07:00
Scibuild
2e15a404e2 C backend: errors and optionals
* bitcast treats all pointers as pointers
 * correctly unwrapping error unions with pointers
 * equality operators for primitive optional types
2021-11-23 13:46:56 -07:00
Andrew Kelley
e08b6149ab Sema: fix alignment of type-inferred locals 2021-11-22 20:30:20 -07:00
Andrew Kelley
af1a5751d9
Merge pull request #10165 from jmc-88/cbe
CBE: add .optional_single_mut_pointer and .optional_single_const_pointer to Type.childType
2021-11-22 21:36:24 -05:00
Robin Voetter
2b589d71fb stage2: move some tests which are now passing 2021-11-22 04:36:57 +01:00
Daniele Cocca
b3f4abbc5a CBE: mark align.zig and error.zig as passing
Newly passing as of 3794a32d89.
2021-11-17 23:43:19 +00:00
drew
0249344a47 cast -> cast_llvm, cast_c -> cast (doesn't work on LLVM backend) 2021-11-16 16:51:31 -07:00
drew
cf99afc525 add generics behavior test
-airLoad and airStore now properly report an error if they are used with an array, instead of having the C compiler emit a vague error
-airStoreUndefined now works with array types
-structFieldPtr now works with array types, allowing generics' tests to pass
2021-11-16 16:51:31 -07:00
drew
ad4627ea3b small changes + align tests obviously shouldn't have passed 2021-11-16 16:51:31 -07:00
drew
9bf1681990 C backend: basic big ints, fix airPtrToInt, array references, pointer arithmetic UB with NULL, implement airPtrElemPtr/Val, fix redundant indirection/references with arrays
-add additional test cases that were found to be passing
-add basic int128 test cases which previously did not pass but weren't covered
-most test cases in cast.zig now pass
-i128/u128 or smaller int constants can now be rendered
-unsigned int constants are now always suffixed with 'u' to prevent random compile errors
-pointers with a val tag of 'zero' now just emit a 0 constant which coerces to the pointer type and fixes some warnings with ordered comparisons
-pointers with a val tag of 'one' are now casted back to the pointer type
-support pointers with a u64 val
-fix bug where rendering an array's type will emit more indirection than is needed
-render uint128_t/int128_t manually when needed
-implement ptr_add/sub AIR handlers manually so they manually cast to int types which avoids UB if the result or ptr operand is NULL
-implement airPtrElemVal/Ptr
-airAlloc for arrays will not allocate a ref as the local for the array is already a reference/pointer to the array itself
-fix airPtrToInt by casting to the int type
2021-11-16 16:51:31 -07:00
LemonBoy
952d865bd2 stage1: Fix caching of LLVM builtin fns
The cache entry must take into account the fact some functions operate on scalar types and some other on vectors of scalar types.

Fixes #10147
2021-11-16 16:35:56 -05:00
Daniele Cocca
29f531bec9 CBE: memset(..., 0xaa, ...) undefined values
This commit makes airStore() handle undefined values directly instead of
delegating to renderValue(): the call to renderValue() happens too late,
when "dest = " has already been written to the stream, at which point
there's no sane way to initialize e.g. struct values by assignment.

Instead, we make airStore() use memset(dest, 0xaa, sizeof(dest)), which
should transparently handle all types.

Also moves the newly-passing tests to the top of test/behavior.zig.
2021-11-14 22:49:50 -05:00
Emily Bellows
e3d638a49e C backend: while, struct tests, better undefined global handling
1. Function signatures that return a no member struct return void
2. Undefined var decls don't get a value generated for them
3. Don't generate bitcast code if the result isn't used, since
   bitcast is a pure function. Right now struct handling code
   generates some weird unused bitcast AIR, and this optimization
   side steps that issue.
2021-11-08 14:23:55 -05:00
Daniele Cocca
77ffffc7cc
Add more entries to the list of stage1+stage2+CBE passing tests (#10094)
* CBE: mark call.zig tests as passing

* CBE: mark enum.zig tests as passing

* CBE: mark defer.zig tests as passing

* CBE: mark hasdecl.zig tests as passing

* CBE: mark hasfield.zig tests as passing

* CBE: mark ptrcast.zig tests as passing

* CBE: mark bitcast.zig tests as passing

* CBE: mark pub_enum.zig tests as passing

* CBE: mark underscore.zig tests as passing

* CBE: mark usingnamespace.zig tests as passing

* CBE: mark bugs/655.zig tests as passing

* CBE: mark bugs/679.zig tests as passing

* CBE: mark bugs/704.zig tests as passing

* CBE: mark bugs/1486.zig tests as passing

* CBE: mark bugs/2346.zig tests as passing

* CBE: mark bugs/2889.zig tests as passing

* CBE: mark bugs/4560.zig tests as passing

* CBE: mark bugs/4769_a.zig tests as passing

* CBE: mark bugs/4769_b.zig tests as passing

* CBE: mark bugs/6850.zig tests as passing
2021-11-04 14:24:46 -04:00
Emily Bellows
674932e503 C backend: implement ?void, and other zero sized types 2021-11-02 12:45:29 -04:00
Emily Bellows
969bcb6a59 C backend: implement signed trunc 2021-10-30 16:09:55 -04:00
Andrew Kelley
d6067db062 stage2: implement @popCount for non-vectors 2021-10-29 17:49:02 -07:00
Andrew Kelley
98009a2f66 C backend: implement trunc instruction
Note that there is not any test coverage yet for integer
truncation involving non-power-of-two integers.
2021-10-28 17:41:45 -07:00
Andrew Kelley
5479c0f9ac C backend: fix @boolToInt 2021-10-28 17:33:05 -07:00
Andrew Kelley
1c93cf52d8 C backend: fix crash when number of Decls passes a threshold
The ensureUnusedCapacity did not reserve a big enough number. I changed
it to no longer guess the capacity because I saw that the number of
possible items was not determinable ahead of time and this can therefore
avoid allocating more memory than necessary.
2021-10-28 17:23:02 -07:00
Andrew Kelley
c59ee3157f C backend: fix ptrtoint and wrap_errunion_err 2021-10-28 17:05:17 -07:00
Andrew Kelley
9ed955e5ca behavior tests: add "passing for C backend" category 2021-10-28 16:37:12 -07:00
Robin Voetter
7062c8a886 stage2: comptime slice of pointer to hardcoded address 2021-10-25 20:41:15 +02:00
Andrew Kelley
01c1f41520 stage2: slice and alignment fixes
* Fix backend using wrong union field of the slice instruction.
 * LLVM backend properly sets alignment on global variables.
 * Sema: add coercion for *T to *[1]T
 * Sema: pointers to Decls with explicit alignment now have alignment
   metadata in them.
2021-10-22 17:12:12 -07:00
Andrew Kelley
069c83d58c stage2: change @bitCast to always be by-value
After a discussion about language specs, this seems like the best way to
go, because it's simpler to reason about both for humans and compilers.

The `bitcast_result_ptr` ZIR instruction is no longer needed.

This commit also implements writing enums, arrays, and vectors to
virtual memory at compile-time.

This unlocked some more of compiler-rt being able to build, which
in turn unlocks saturating arithmetic behavior tests.

There was also a memory leak in the comptime closure system which is now
fixed.
2021-10-22 15:35:35 -07:00
Andrew Kelley
0a6851cc6d stage2: implement comptime loads through casted pointers 2021-10-21 22:56:11 -07:00
Andrew Kelley
7f70c27e9d stage2: more division support
AIR:
 * div is renamed to div_trunc.
 * Add div_float, div_floor, div_exact.
   - Implemented in Sema and LLVM codegen. C backend has a stub.

Improvements to std.math.big.Int:
 * Add `eqZero` function to `Mutable`.
 * Fix incorrect results for `divFloor`.

Compiler-rt:
 * Add muloti4 to the stage2 section.
2021-10-21 19:05:26 -07:00
Robin Voetter
a3c9bfef30 stage2: truncation
* Also fixes a related case where big int truncate would assume that the
input fits in the output limbs buffer
2021-10-21 20:10:27 -04:00
Andrew Kelley
4cb5fed10b AstGen: make the index variable of inline for a alloc_comptime
Before it was being emitted as an `alloc` which caused inline for loops
to not work correctly.
2021-10-20 15:34:10 -07:00
Matthew Borkowski
79a3dfcfd8 astgen.zig: fix false positive in breakExpr's checking for store_to_block_ptr 2021-10-18 13:18:47 -04:00
Andrew Kelley
7b00bef6bf Sema: resolveTypeFields before accessing type fields 2021-10-17 21:53:59 -07:00
Meghan Denny
0ef2e2520a stage2: implement @hasField
struct and union are kept in stage1 because struct/unionFieldCount are returning zero
2021-10-17 21:42:22 -07:00
Meghan Denny
7d0a74456b alphebetize behavior tests 2021-10-17 21:42:22 -07:00
Andrew Kelley
e9d1e5e533 stage2: LLVM backend: lower constant field/elem ptrs 2021-10-17 17:02:20 -07:00
Andrew Kelley
fdd11f6cee Sema: coercion from error sets to anyerror 2021-10-16 12:41:03 -07:00
Andrew Kelley
82ec56e47e
Merge pull request #9954 from Snektron/shifts
Big int saturating left shift
2021-10-16 15:06:13 -04:00
Meghan Denny
6f30c8c098 elevate more passing tests 2021-10-16 15:04:48 -04:00
Robin Voetter
f6bf24b2f3 stage2: comptime saturating shl 2021-10-16 11:32:05 +02:00
Meghan
1df926b24e stage2: @hasDecl is passing 2021-10-16 04:09:16 -04:00
Andrew Kelley
cacd5366a6 stage2: LLVM backend: implement wrap_optional AIR
and move over some passing tests
2021-10-14 22:16:26 -07:00
Andrew Kelley
55eea3b045 stage2: implement @minimum and @maximum, including vectors
* std.os: take advantage of `@minimum`. It's probably time to
   deprecate `std.min` and `std.max`.
 * New AIR instructions: min and max
 * Introduce SIMD vector support to stage2
 * Add `@Type` support for vectors
 * Sema: add `checkSimdBinOp` which can be re-used for other arithmatic
   operators that want to support vectors.
 * Implement coercion from vectors to arrays.
   - In backends this is handled with bitcast for vector to array,
     however maybe we want to reduce the amount of branching by
     introducing an explicit AIR instruction for it in the future.
 * LLVM backend: implement lowering vector types
 * Sema: Implement `slice.ptr` at comptime
 * Value: improve `numberMin` and `numberMax` to support floats in
   addition to integers, and make them behave properly in the presence
   of NaN.
2021-10-14 21:17:30 -07:00
Andrew Kelley
ed5a5e2293 move behavior tests that are passing for stage2 2021-10-13 21:43:19 -07:00
Andrew Kelley
e851d89113 Sema: implement comptime coerce_result_ptr and alloc
This is progress towards being able to use `builtin.cpu.arch` instead of
the `stage2_arch` workaround. The next blocker is comptime `elemVal`.
2021-10-13 14:16:01 -07:00
Andrew Kelley
6d6cf59847 stage2: support nested structs and arrays and sret
* Add AIR instructions: ret_ptr, ret_load
   - This allows Sema to be blissfully unaware of the backend's decision
     to implement by-val/by-ref semantics for struct/union/array types.
     Backends can lower these simply as alloc, load, ret instructions,
     or they can take advantage of them to use a result pointer.
 * Add AIR instruction: array_elem_val
   - Allows for better codegen for `Sema.elemVal`.
 * Implement calculation of ABI alignment and ABI size for unions.
 * Before appending the following AIR instructions to a block,
   resolveTypeLayout is called on the type:
   - call - return type
   - ret - return type
   - store_ptr - elem type
 * Sema: fix memory leak in `zirArrayInit` and other cleanups to this
   function.
 * x86_64: implement the full x86_64 C ABI according to the spec
 * Type: implement `intInfo` for error sets.
 * Type: implement `intTagType` for tagged unions.

The Zig type tag `Fn` is now used exclusively for function bodies.
Function pointers are modeled as `*const T` where `T` is a `Fn` type.
 * The `call` AIR instruction now allows a function pointer operand as
   well as a function operand.
 * Sema now has a coercion from function body to function pointer.
 * Function type syntax, e.g. `fn()void`, now returns zig tag type of
   Pointer with child Fn, rather than Fn directly.
   - I think this should probably be reverted. Will discuss the lang
     specs before doing this. Idea being that function pointers would
     need to be specified as `*const fn()void` rather than `fn() void`.

LLVM backend:
 * Enable calling the panic handler (previously this just
   emitted `@breakpoint()` since the backend could not handle the panic
   function).
 * Implement sret
 * Introduce `isByRef` and implement it for structs and arrays. Types
   that are `isByRef` are now passed as pointers to functions, and e.g.
   `elem_val` will return a pointer instead of doing a load.
 * Move the function type creating code from `resolveLlvmFunction` to
   `llvmType` where it belongs; now there is only 1 instance of this
   logic instead of two.
 * Add the `nonnull` attribute to non-optional pointer parameters.
 * Fix `resolveGlobalDecl` not using fully-qualified names and not using
   the `decl_map`.
 * Implement `genTypedValue` for pointer-like optionals.
 * Fix memory leak when lowering `block` instruction and OOM occurs.
 * Implement volatile checks where relevant.
2021-10-11 11:39:12 -07:00
Andrew Kelley
78902db68b stage2: fix comptime @bitCast
Before, Sema for comptime `@bitCast` would return the same Value but
change the Type. This gave invalid results because, for example, an
integer Value when the Type is a float would be interpreted numerically,
but `@bitCast` needs it to reinterpret how they would be stored in
memory.

This requires a mechanism to serialize a Value to a byte buffer and
deserialize a Value from a byte buffer.

Not done yet, but needs to happen: comptime dereferencing a pointer
to a Decl needs to perform a comptime bitcast on the loaded value.
Currently the value is silently wrong in the same way that `@bitCast`
was silently wrong before this commit.

The logic in Value for handling readFromMemory for large integers is
only correct for small integers. It needs to be fleshed out for proper
big integers.

As part of this change:
 * std.math.big.Int: initial implementations of readTwosComplement and
   writeTwosComplement. They only support bit_count <= 128 so far and
   panic otherwise.
 * compiler-rt: move the compareXf2 exports over to the stage2 section.
   Even with the improvements in this commit, I'm still seeing test
   failures in the widening behavior tests; more investigation is
   needed.
2021-10-04 23:30:04 -07:00
Andrew Kelley
ac2333ee63 stage2: fix Type max/min int calculation
This was an attempt to move saturating_arithmetic.zig to the "passing
for stage2" section, which did not pan out due to the discovery of 2
prerequisite items that need to be done, but I did make a bug fix along
the way of the calculation of max/min integers.

This commit also simplifies the saturating arithmetic behavior tests to
depend on less of the zig language that is not related to saturating
arithmetic.
2021-10-04 12:23:49 -07:00
Andrew Kelley
c4df9bf56f AstGen: fix while and for with unreachable bodies
Companion commit to 61a53a5875.

This commit also moves over a bunch of behavior test cases to the
passing-for-stage2 section.
2021-10-02 20:15:03 -07:00
Andrew Kelley
1d1f6a0421 move some behavior tests to the "passing for stage2" section 2021-09-29 11:33:22 -07:00
Andrew Kelley
79bc5891c1 stage2: more arithmetic support
* AIR: add `mod` instruction for modulus division
   - Implement for LLVM backend
 * Sema: implement `@mod`, `@rem`, and `%`.
 * Sema: fix comptime switch evaluation
 * Sema: implement comptime shift left
 * Sema: fix the logic inside analyzeArithmetic to handle all the
   nuances between the different mathematical operations.
   - Implement comptime wrapping operations
2021-09-28 16:12:24 -07:00
Martin Wickham
1cc5d4e758
Stage 2: Support inst.func() syntax (#9827)
* Merge call zir instructions to make space for field_call
* Fix bug with comptime known anytype args
* Delete the param_type zir instruction
* Move some passing tests to stage 2
* Implement a.b() function calls
* Add field_call_bind support for call and field builtins
2021-09-28 12:00:35 -05:00
Martin Wickham
a0a847f2e4
Stage2: Implement comptime closures and the This builtin (#9823) 2021-09-23 13:17:06 -04:00
Andrew Kelley
736d14fd5f stage2: fix AstGen for some struct syntaxes
* AstGen: fix not emitting `struct_init_empty` when an explicit type is
   present in struct initialization syntax.
 * AstGen: these two syntaxes now lower to identical ZIR:
   - `var a = A{ .b = c };`
   - `var a = @as(A, .{ .b = c });`
 * Zir: clarify `auto_enum_tag` in the doc comments.
 * LLVM Backend: fix lowering of function return types when the type has
   0 bits.
2021-09-22 21:06:00 -07:00
Andrew Kelley
aecebf38ac stage2: progress towards ability to compile compiler-rt
* prepare compiler-rt to support being compiled by stage2
   - put in a few minor workarounds that will be removed later, such as
     using `builtin.stage2_arch` rather than `builtin.cpu.arch`.
   - only try to export a few symbols for now - we'll move more symbols
     over to the "working in stage2" section as they become functional
     and gain test coverage.
   - use `inline fn` at function declarations rather than `@call` with an
     always_inline modifier at the callsites, to avoid depending on the
     anonymous array literal syntax language feature (for now).
 * AIR: replace floatcast instruction with fptrunc and fpext for
   shortening and widening floating point values, respectively.
 * Introduce a new ZIR instruction, `export_value`, which implements
   `@export` for the case when the thing to be exported is a local
   comptime value that points to a function.
   - AstGen: fix `@export` not properly reporting ambiguous decl
     references.
 * Sema: handle ExportOptions linkage. The value is now available to all
   backends.
   - Implement setting global linkage as appropriate in the LLVM
     backend. I did not yet inspect the LLVM IR, so this still needs to
     be audited. There is already a pending task to make sure the alias
     stuff is working as intended, and this is related.
   - Sema almost handles section, just a tiny bit more code is needed in
     `resolveExportOptions`.
 * Sema: implement float widening and shortening for both `@floatCast`
   and float coercion.
   - Implement the LLVM backend code for this as well.
2021-09-21 23:21:07 -07:00
Andrew Kelley
be71195bba stage2: enable f16 math
There was panic that said TODO add __trunctfhf2 to compiler-rt, but I
checked and that function has been in compiler-rt since April.
2021-09-21 23:21:07 -07:00
Veikka Tuominen
55e7c099ca stage2: various fixes to cImport, sizeOf and types to get tests passing 2021-09-20 20:51:31 -07:00
Andrew Kelley
abc30f7948 stage2: improve handling of 0 bit types
* Sema: zirAtomicLoad handles 0-bit types correctly
 * LLVM backend: when lowering function types, elide parameters
   with 0-bit types.
 * Type: abiSize handles u0/i0 correctly
2021-09-20 16:48:42 -07:00
Andrew Kelley
ab84ba39d0 move behavior test to "passing for stage2" section 2021-09-16 11:21:56 -07:00
Andrew Kelley
264acfdf3c stage2: fix incorrect spelling of AtomicOrder 2021-09-13 22:01:40 -07:00
Andrew Kelley
ca21cad2bf move syntax tests out of behavior tests
parser_test.zig is where the syntax tests go
2021-09-01 17:54:06 -07:00
Andrew Kelley
332eafeb7f stage2: first pass at implementing usingnamespace
Ran into a design flaw here which will need to get solved by having
AstGen annotate ZIR with which instructions are closed over.
2021-09-01 17:54:06 -07:00
travisstaloch
21a5769afe
saturating arithmetic builtins: add, sub, mul, shl (#9619)
- adds 1 simple behavior tests for each
  which does integer and vector ops at
  runtime and comptime
- adds bigint_*_sat() methods for each

- use CreateIntrinsic() which accepts a
  variable number of arguments to pass
  the scale parameter

* update langref
- added case to test/compile_errors.zig given floats

- explain upstream bug in llvm.smul.fix.sat and link to #9643 in langref and commented out test cases

* sat-arithmetic: skip mul tests if arch == .wasm32 because ci is erroring with 'LLVM ERROR: Unable to expand fixed point multiplication' when compiling for wasm32
2021-09-01 14:17:45 -04:00
Martin Wickham
cf75cad899 Add comptime memory tests 2021-08-30 18:50:07 -04:00
Andrew Kelley
0cd361219c stage2: field type expressions support referencing locals
The big change in this commit is making `semaDecl` resolve the fields if
the Decl ends up being a struct or union. It needs to do this while
the `Sema` is still in scope, because it will have the resolved AIR
instructions that the field type expressions possibly reference. We do
this after the decl is populated and set to `complete` so that a `Decl`
may reference itself.

Everything else is fixes and improvements to make the test suite pass
again after making this change.

 * New AIR instruction: `ptr_elem_ptr`
   - Implemented for LLVM backend
 * New Type tag: `type_info` which represents `std.builtin.TypeInfo`. It
   is used by AstGen for the operand type of `@Type`.
 * ZIR instruction `set_float_mode` uses `coerced_ty` to avoid
   superfluous `as` instruction on operand.
 * ZIR instruction `Type` uses `coerced_ty` to properly handle result
   location type of operand.

 * Fix two instances of `enum_nonexhaustive` Value Tag not handled
   properly - it should generally be handled the same as `enum_full`.
 * Fix struct and union field resolution not copying Type and Value
   objects into its Decl arena.
 * Fix enum tag value resolution discarding the ZIR=>AIR instruction map
   for the child Sema, when they still needed to be accessed.
 * Fix `zirResolveInferredAlloc` use-after-free in the AIR instructions
   data array.
 * Fix `elemPtrArray` not respecting const/mutable attribute of pointer
   in the result type.
 * Fix LLVM backend crashing when `updateDeclExports` is called before
   `updateDecl`/`updateFunc` (which is, according to the API, perfectly
   legal for the frontend to do).
 * Fix LLVM backend handling element pointer of pointer-to-array. It
   needed another index in the GEP otherwise LLVM saw the wrong type.
 * Fix LLVM test cases not returning 0 from main, causing test failures.
   Fixes a regression introduced in
   6a5094872f.

 * Implement comptime shift-right.
 * Implement `@Type` for integers and `@TypeInfo` for integers.
 * Implement union initialization syntax.
 * Implement `zirFieldType` for unions.
 * Implement `elemPtrArray` for a runtime-known operand.

 * Make `zirLog2IntType` support RHS of shift being `comptime_int`. In
   this case it returns `comptime_int`.

The motivating test case for this commit was originally:

```zig
test "example" {
    var l: List(10) = undefined;
    l.array[1] = 1;
}

fn List(comptime L: usize) type {
    var T = u8;
    return struct {
        array: [L]T,
    };
}
```

However I changed it to:

```zig
test "example" {
    var l: List = undefined;
    l.array[1] = 1;
}

const List = blk: {
    const T = [10]u8;
    break :blk struct {
        array: T,
    };
};
```

Which ended up being a similar, smaller problem. The former test case
will require a similar solution in the implementation of comptime
function calls - checking if the result of the function call is a struct
or union, and using the child `Sema` before it is destroyed to resolve
the fields.
2021-08-20 15:41:57 -07:00
Robin Voetter
5cd1d42a35
Add mask before truncating dereferenced bit pointers (#9584) 2021-08-19 01:20:50 -04:00
Andrew Kelley
6eecc4af99 stage2 llvm backend: implement const inttoptr 2021-08-12 10:48:54 -07:00
Andrew Kelley
799fedf612 stage2: pass some error union tests
* Value: rename `error_union` to `eu_payload` and clarify the intended
   usage in the doc comments. The way error unions is represented with
   Value is fixed to not have ambiguous values.
 * Fix codegen for error union constants in all the backends.
 * Implement the AIR instructions having to do with error unions in the
   LLVM backend.
2021-08-07 20:34:28 -07:00
Andrew Kelley
f81b2531cb stage2: pass some pointer tests
* New AIR instructions: ptr_add, ptr_sub, ptr_elem_val, ptr_ptr_elem_val
   - See the doc comments for details.
 * Sema: implement runtime pointer arithmetic.
 * Sema: implement elem_val for many-pointers.
 * Sema: support coercion from `*[N:s]T` to `[*]T`.
 * Type: isIndexable handles many-pointers.
2021-08-07 15:46:53 -07:00
Andrew Kelley
259f3458a1 Sema: implement alloc_inferred_comptime 2021-08-07 11:08:08 -07:00
Andrew Kelley
e9e3a29946 stage2: implement generic function memoization
Module has a new field `monomorphed_funcs` which stores the set of
`*Module.Fn` objects which are generic function instantiations.
The hash is based on hashes of comptime values of parameters known to be
comptime based on an explicit comptime keyword or must-be-comptime
type expressions that can be evaluated without performing monomorphization.
This allows function calls to be semantically analyzed cheaply for
generic functions which are already instantiated.

The table is updated with a single `getOrPutAdapted` in the semantic
analysis of `call` instructions, by pre-allocating the `Fn` object and
passing it to the child `Sema`.
2021-08-05 16:37:21 -07:00
Andrew Kelley
6ae0825e7f Sema: implement comptime variables
Sema now properly handles alloc_inferred and alloc_inferred_mut ZIR
instructions inside a comptime execution context. In this case it
creates Decl objects and points to them with the new `decl_ref_mut`
Value Tag. `storePtr` is updated to mutate such Decl types and values.
In this case it destroys the old arena and makes a new one, preventing
memory growth during comptime code execution.

Additionally:

 * Fix `storePtr` to emit a compile error for a pointer comptime-known
   to be undefined.
 * Fix `storePtr` to emit runtime instructions for all the cases that a
   pointer is comptime-known but does not support comptime
   dereferencing, such as `@intToPtr` on a hard-coded address, or an
   extern function.
 * Fix `ret_coerce` not coercing inside inline function call context.
2021-08-01 12:36:04 -07:00
Andrew Kelley
dc88864c97 stage2: implement @boolToInt
This is the first commit in which some behavior tests are passing for
both stage1 and stage2.
2021-07-27 17:08:37 -07:00
Robin Voetter
cdeea3b094 minimum/maximum builtins 2021-07-26 20:41:00 -04:00
Robin Voetter
50a29f7c21 Add @select
@select(
    comptime T: type,
    pred: std.meta.Vector(len, bool),
    a: std.meta.Vector(len, T),
    b: std.meta.Vector(len, T)
) std.meta.Vector(len, T)

Constructs a vector from a & b, based on the values in the predicate vector. For indices where the predicate value is true, the corresponding
element from the a vector is selected, and otherwise from b.
2021-07-26 20:05:48 -04:00
Andrew Kelley
7b8cb881df stage2: improvements towards zig test
* There is now a main_pkg in addition to root_pkg. They are usually the
   same. When using `zig test`, main_pkg is the user's source file and
   root_pkg has the test runner.
 * scanDecl no longer looks for test decls outside the package being
   tested. honoring `--test-filter` is still TODO.
 * test runner main function has a void return value rather than
   `anyerror!void`
 * Sema is improved to generate better AIR for for loops on slices.
 * Sema: fix incorrect capacity calculation in zirBoolBr
 * Sema: add compile errors for trying to use slice fields as an lvalue.
 * Sema: fix type coercion for error unions
 * Sema: fix analyzeVarRef generating garbage AIR
 * C codegen: fix renderValue for error unions with 0 bit payload
 * C codegen: implement function pointer calls
 * CLI: fix usage text

 Adds 4 new AIR instructions:

  * slice_len, slice_ptr: to get the ptr and len fields of a slice.
  * slice_elem_val, ptr_slice_elem_val: to get the element value of
    a slice, and a pointer to a slice.

AstGen gains a new functionality:

 * One of the unused flags of struct decls is now used to indicate
   structs that are known to have non-zero size based on the AST alone.
2021-07-23 22:42:31 -07:00