4736 Commits

Author SHA1 Message Date
Andrew Kelley
0c1701768d Release 0.10.0 2022-10-31 10:24:38 -07:00
Cody Tapscott
049e6025f2 stage2: Add explicit type qualifier to workaround #13366
Depending on how #13366 is resolved, this code should arguably have
been rejected with a compile error in the first place.
2022-10-31 13:13:11 -04:00
Cody Tapscott
6f2408aab8 link/MachO: Avoid depending on host PATH_MAX
Repeat of a4eb221b9 for the newly-synchronized zld code.

Restores ability to compile Zig for WASI.
2022-10-31 13:12:37 -04:00
Andrew Kelley
d02242661e std.heap: make wasm32 PageAllocator handle large allocation
When a number of bytes to be allocated is so great that alignForward()
is not possible, return `error.OutOfMemory`.

Companion commit to 3f3003097c.
2022-10-30 19:28:26 -07:00
Andrew Kelley
ef761c2cbc Merge pull request #13360 from topolarity/comptime-bool-binops
Make `x and false` and `x or true` comptime-known
2022-10-30 22:11:44 -04:00
Andrew Kelley
6d999abba0 mingw-w64: add gdiplus def files
closes #13192
2022-10-30 19:04:00 -07:00
Andrew Kelley
d4f668b241 Merge pull request #13361 from jacobly0/while-cont-scope
AstGen: avoid access to capture defined in an inner scope from a continue expression
2022-10-30 21:44:07 -04:00
Andrew Kelley
3e126102b7 compiler_rt: fix gnu_f16_abi for i386-windows
closes #13333
2022-10-30 18:42:59 -07:00
Andrew Kelley
30b8b29f88 re-apply "Fix C include files not being in whole cache (#11365)"
This reverts commit 06310e3d4e, reapplying
commit a430630002.

I deeply apologize to @moosichu and those affected by this bug. The
original fix was actually fine. When I reverted it, I misremembered
how the Cache API works. I thought the fix was going to introduce
nondeterminism into the hash, but I forgot that the order of files in
the manifest doesn't actually matter when checking for a cache hit.

Actually, it does matter a little bit. This fix has a subtle downside
which is that it does introduce the possibility of false negatives when
checking for cache hits of 2+ iterations ago. For example, if the code
goes from "foo", to "bar", and then back to "foo", it may look like a
cache miss when it should have been a hit because 2 iterations ago the
code was the same. However, this is an uncommon use case, and all it
does is cause a bit of wasted time and disk space. That said, my
suggestion from earlier still applies and would be a nice follow-up
enhancement to this fix:

The proper solution to this is to, in whole cache mode, append the hash
inputs to some data structure, and then after the compilation is
complete, do some kind of sorting on the hash inputs so that they will
be the same order every time, then apply them in sequence. No lock on
the Cache object is needed for this scheme.

closes #11063
2022-10-30 17:04:09 -07:00
Andrew Kelley
a5c96c49d0 langref: mention void{} and empty blocks
closes #11112
closes #12496
2022-10-30 16:33:22 -07:00
Andrew Kelley
3f3003097c std.heap.PageAllocator: add check for large allocation
Instead of making the memory alignment functions more complicated, I
added more API documentation for their existing semantics.

closes #12118
closes #12135
2022-10-30 16:10:20 -07:00
Andrew Kelley
9b54c9dee8 zig test: forward target CLI args to zig run when using -ofmt=c
Previously, if you used `zig test -ofmt=c -target foobar` then Zig would
try to compile the generated C code with the native target instead of
"foobar".

With this change, `--test-cmd` with e.g. QEMU still won't work, but at
least the binary will get compiled for the correct target.
2022-10-30 15:44:58 -07:00
Jacob Young
a77d89afe3 behavior: enable fixed cbe tests 2022-10-30 15:38:50 -04:00
Jacob Young
01d76d419e Sema: avoid comptime null unwrap
This avoids a crash analyzing check_comptime_control_flow.
2022-10-30 15:38:46 -04:00
Cody Tapscott
ca332f57f7 stage2: Make x and false/x or true comptime-known
Same as preceding change, but for stage2.
2022-10-30 12:38:08 -07:00
Jacob Young
5c3a486639 AstGen: avoid accessing value from inner scope
While continue expressions can access the capture, so ensure that it is
unwrapped in an outer scope.
2022-10-30 15:25:58 -04:00
Cody Tapscott
2f732deb3d stage1: Make x and false/x or true comptime-known
We need to be careful to respect side-effects/branching in these
cases, but otherwise this behaves very similarly to multiplication.
`lhs and rhs == false` if either lhs or rhs is comptime-known `false`,
just like `lhs * rhs == 0` if either lhs or rhs is comptime-known to
be zero.

Similar reasoning applies to `lhs or rhs`.
2022-10-30 12:21:37 -07:00
Andrew Kelley
8caed48460 Merge branch 'ci-enable-aarch64-linux' 2022-10-30 12:09:40 -07:00
Nameless
40e84a27d6 change uefi packed structs to new integer backed syntax (#13173)
* std.os.uefi: integer backed structs, add tests to catch regressions

device_path_protocol now uses extern structs with align(1) fields because
the transition to integer backed packed struct broke alignment

added comptime asserts that device_path_protocol structs do not violate
alignment and size specifications
2022-10-30 15:08:32 -04:00
Loris Cro
1696434063 Merge pull request #13300 from jcalabro/master
Better Autodoc Src File Links
2022-10-30 17:20:57 +01:00
Loris Cro
d4487b6a2e autodoc: update to new func zir body structure
this is a hack meant to restore functionality for the upcoming release,
a proper analysis of the new zir structure is required to make a robust
change.
2022-10-30 17:17:34 +01:00
Jakub Konka
2b25d3c333 Merge pull request #13356 from ziglang/macho-no-dupe
macho: fix performance regression for x86_64 and -dead_strip
2022-10-30 16:38:28 +01:00
Andrew Kelley
17df35025b CI: disable failing C backend test
See #13357
2022-10-30 03:21:18 -07:00
Jakub Konka
9b0c555db4 macho: fix regression in dead strip for x86_64
Correctly handle calculating encompassing atoms for local
relocations (`r_extern == 0`).
2022-10-30 10:49:00 +01:00
Jakub Konka
27bcd4ec79 macho: do not unnecessarily dupe sym names in resolver 2022-10-30 10:12:25 +01:00
Andrew Kelley
5339cac2ef std: re-enable auto hash test
It was temporarily disabled due to a self-hosted compiler
miscompilation.

closes #12178
2022-10-30 01:09:31 -07:00
Andrew Kelley
fbd1390f80 CI: drone: shuffle some tests around
We have to balance the timings to end up below the two hour mark.
2022-10-29 23:10:49 -07:00
Andrew Kelley
c8f1ea46b5 ci: enable aarch64-linux test coverage
closes #12689
2022-10-29 23:07:16 -07:00
Andrew Kelley
209a0d2a83 Merge pull request #13153 from squeek502/iterator-filename-limits
Windows: Fix Iterator name buffer size not handling all possible file name components
2022-10-29 23:50:37 -04:00
Andrew Kelley
5f5a20ebaf Merge pull request #13093 from jacobly0/backend-fixes
C backend fixes
2022-10-29 23:06:59 -04:00
Evin Yulo
09a96cdfce Fix #12822: Clarify langref about the behavior of undefined 2022-10-29 17:55:06 -04:00
kkHAIKE
949cca9f2a Allocator: fix len_align calc in large type size case 2022-10-29 17:53:56 -04:00
Andrew Kelley
28dc208f65 Merge pull request #13082 from g-w1/unnamed-decls-and-relocs-p9
Plan9: Fix The Backend
2022-10-29 17:45:00 -04:00
Ryan Liptak
db80225a97 fs: Some NAME_MAX/MAX_NAME_BYTES improvements 2022-10-29 14:30:46 -07:00
Ryan Liptak
348f73502e Make MAX_NAME_BYTES on WASI equivalent to the max of the other platforms
Make the test use the minimum length and set MAX_NAME_BYTES to the maximum so that:
- the test will work on any host platform
- *and* the MAX_NAME_BYTES will be able to hold the max file name component on any host platform
2022-10-29 14:30:46 -07:00
Ryan Liptak
c5d23161fc Set wasi MAX_NAME_BYTES to minimum of the rest of the supported platforms
This is a slightly weird situation, because the 'real' value may depend on the host platform that the WASI is being executed on.
2022-10-29 14:30:45 -07:00
Ryan Liptak
dd0962d5ea Add wasi branch to MAX_NAME_BYTES 2022-10-29 14:30:45 -07:00
Ryan Liptak
c6ff1a7160 Windows: Fix iterator name buffer size not handling all possible file name components
Each u16 within a file name component can be encoded as up to 3 UTF-8 bytes, so we need to use MAX_NAME_BYTES to account for all possible UTF-8 encoded names.

Fixes #8268
2022-10-29 14:30:44 -07:00
Ryan Liptak
33fdc43714 std.fs: Add MAX_NAME_BYTES
Also add some NAME_MAX or equivalent definitions where necessary
2022-10-29 14:30:43 -07:00
Jacob Young
4364f51476 cbe: finish partial zig_noreturn rewrite 2022-10-29 16:54:50 -04:00
Andrew Kelley
e036cc48d5 Merge pull request #13342 from ziglang/fix-glibc-race
glibc: fix race condition when building stubs
2022-10-29 16:16:57 -04:00
fn ⌃ ⌥
a70c86e661 Fix deprecation docs for isAlpha and isCntrl 2022-10-29 15:22:05 -04:00
Andrew Kelley
3e926d868e CI: update freebsd tarball 2022-10-29 12:15:47 -07:00
Andrew Kelley
4cfeb9a541 glibc: fix race condition when building stubs
Before, the code for building glibc stubs used a special case of the
Cache API that did not add any file inputs, and did not use
writeManifest(). This is not really how the Cache API is designed to
work and it shows because there was a race condition.

This commit adds as an input file the abilists file that comes with
Zig's installation, which has the added benefit of making glibc stub
caching properly detect cache invalidation when the user decides to
overwrite their abilists file. This harmonizes with the rest of how Zig
works, which intentionally allows you to hack the installation files and
have it behave properly with the cache system.

Finally, because of having any file inputs, the normal API flow of the
Cache system can be used, eliminating the one place that used the Cache
API in a special way. In other words, it uses writeManifest() now and
properly obeys the cache hit/miss semantics.

closes #13160
2022-10-29 12:15:47 -07:00
Jacob Young
48a2783969 cbe: implement optional slice representation change 2022-10-29 05:58:41 -04:00
Andrew Kelley
20925b2f5c Merge pull request #13272 from topolarity/sha2-intrinsics
crypto.sha2: Use intrinsics for SHA-256 on x86-64 and AArch64
2022-10-29 03:31:42 -04:00
Andrew Kelley
c36eb4ede9 Merge pull request #13221 from topolarity/packed-mem
Introduce `std.mem.readPackedInt` and improve bitcasting of packed memory layouts
2022-10-28 21:15:16 -04:00
Zhora Trush
c66d3f6bf6 Enhance indexOfIgnoreCase with Boyer-Moore-Horspool algorithm 2022-10-28 20:29:41 -04:00
Cody Tapscott
67fa3262b1 std.crypto: Use featureSetHas to gate intrinsics
This also fixes a bug where the feature gating was not taking
effect at comptime due to https://github.com/ziglang/zig/issues/6768
2022-10-28 17:17:08 -07:00
Andrew Kelley
84e0c148b1 CLI: report error when -fstage1 requested but not available 2022-10-28 15:30:04 -07:00
Cody Tapscott
f9fe548e41 std.crypto: Add isComptime guard around intrinsics
Comptime code can't execute assembly code, so we need some way to
force comptime code to use the generic path. This should be replaced
with whatever is implemented for #868, when that day comes.

I am seeing that the result for the hash is incorrect in stage1 and
crashes stage2, so presumably this never worked correctly. I will follow
up on that soon.
2022-10-28 15:21:10 -07:00
Cody Tapscott
4c1f71e866 std.crypto: Optimize SHA-256 intrinsics for AMD x86-64
This gets us most of the way back to the performance I had when
I was using the LLVM intrinsics:
  - Intel Intel(R) Core(TM) i7-1068NG7 CPU @ 2.30GHz:
       190.67 MB/s (w/o intrinsics) -> 1285.08 MB/s
  - AMD EPYC 7763 (VM) @ 2.45 GHz:
       240.09 MB/s (w/o intrinsics) -> 1360.78 MB/s
  - Apple M1:
       216.96 MB/s (w/o intrinsics) -> 2133.69 MB/s

Minor changes to this source can swing performance from 400 MB/s to
1400 MB/s or... 20 MB/s, depending on how it interacts with the
optimizer. I have a sneaking suspicion that despite LLVM inheriting
GCC's extremely strict inline assembly semantics, its passes are
rather skittish around inline assembly (and almost certainly, its
instruction cost models can assume nothing)
2022-10-28 15:21:10 -07:00
Cody Tapscott
ee241c47ee std.crypto: SHA-256 Properly gate comptime conditional
This feature detection must be done at comptime so that we avoid
generating invalid ASM for the target.
2022-10-28 15:21:10 -07:00
Cody Tapscott
10edb6d352 crypto.sha2: Use intrinsics for SHA-256 on x86-64 and AArch64
There's probably plenty of room to optimize these further in the
future, but for the moment this gives ~3x improvement on Intel
x86-64 processors, ~5x on AMD, and ~10x on M1 Macs.

These extensions are very new - Most processors prior to 2020 do
not support them.

AVX-512 is a slightly older alternative that we could use on Intel
for a much bigger performance bump, but it's been fused off on
Intel's latest hybrid architectures and it relies on computing
independent SHA hashes in parallel. In contrast, these SHA intrinsics
provide the usual single-threaded, single-stream interface, and should
continue working on new processors.

AArch64 also has SHA-512 intrinsics that we could take advantage
of in the future
2022-10-28 15:21:10 -07:00
Evan Haas
c616141241 translate-c: Better support for division in macros
Perform C-style arithmetic conversions on operands to division operator
in macros

Closes #13162
2022-10-28 17:59:32 -04:00
Cody Tapscott
40b7792a4c Enable bitcast test now that #13214 is resolved. 2022-10-28 12:41:15 -07:00
Veikka Tuominen
bd32206b44 Merge pull request #13322 from Vexu/comptime-reason
Further enhance explanation of why expression is evaluated at comptime
2022-10-28 20:15:13 +02:00
Cody Tapscott
03ed0a59e3 std.mem: Skip read/writePackedInt test on WASM32/64 2022-10-28 08:41:04 -07:00
Cody Tapscott
9d0a4b60e1 Value: Add @intCast in writeToPackedMemory for 32-bit targets 2022-10-28 08:41:04 -07:00
Cody Tapscott
3295fee911 stage2: Use mem.readPackedInt etc. for packed bitcasts
Packed memory has a well-defined layout that doesn't require
conversion from an integer to read from. Let's use it :-)

This change means that for bitcasting to/from a packed value that
is N layers deep, we no longer have to create N temporary big-ints
and perform N copies.

Other miscellaneous improvements:
  - Adds support for casting to packed enums and vectors
  - Fixes bitcasting to/from vectors outside of a packed struct
  - Adds a fast path for bitcasting <= u/i64
  - Fixes bug when bitcasting f80 which would clear following fields

This also changes the bitcast memory layout of exotic integers on
big-endian systems to match what's empirically observed on our targets.
Technically, this layout is not guaranteed by LLVM so we should probably
ban bitcasts that reveal these padding bits, but for now this is an
improvement.
2022-10-28 08:41:04 -07:00
Cody Tapscott
c639c22544 std.mem: Add readPackedInt, writePackedInt, etc.
These utility functions allow reading from (stage2) packed memory at
runtime-known offsets.
2022-10-28 08:41:04 -07:00
Frank Denis
f28e4e03ee std.sign.ecdsa: add support for incremental signatures (#13332)
Similar to what was done for EdDSA, allow incremental creation
and verification of ECDSA signatures.

Doing so for ECDSA is trivial, and can be useful for TLS as well
as the future package manager.
2022-10-28 16:25:37 +02:00
Ali Chraghi
d6943f87f9 NativeTargetInfo: remove unused error 2022-10-28 13:58:28 +02:00
Veikka Tuominen
6fc71835c3 value: properly hash null_value pointer
Closes #13325
2022-10-28 13:31:16 +03:00
Veikka Tuominen
c3b85e4e2f Sema: further enhance explanation of why expr is evaluated at comptime 2022-10-28 13:31:16 +03:00
Andrew Kelley
c389f8800b Merge pull request #13290 from Vexu/generic-deletion-mitigation
Mitigate generic deletion bug
2022-10-28 01:04:00 -04:00
Andrew Kelley
23878aec4a CI: azure: fix upload script
Partial revert of changes made in
398a3aae40, fixes regression.
2022-10-27 20:57:21 -07:00
Andrew Kelley
1f4f8d34a1 compiler_rt: fix memcmp wrong for some inputs
See the new test case - this fails in the previous implementation.

See #13303
2022-10-27 22:11:20 -04:00
Andrew Kelley
2991e4a454 Merge pull request #13288 from Vexu/opt-slice
Optimize size of optional slices (+ some fixes)
2022-10-27 22:09:17 -04:00
InKryption
bc72ae5e4e Sema: Prevent coercion from tuple pointer to mutable slice.
Also fix some stdlib code affected by this.

Co-authored by: topolarity <topolarity@tapscott.me>
2022-10-27 22:00:47 -04:00
Andrew Kelley
1d1c7ae5de Merge pull request #13257 from topolarity/ctype-fixes
stage 2: Update `CType` size/alignment
2022-10-27 21:15:22 -04:00
Veikka Tuominen
d03c47bf85 Sema: use runtime_value instead of creating allocs 2022-10-27 21:08:25 -04:00
Eric Joldasov
398a3aae40 CI: make directory structure in releases consistent 2022-10-27 20:53:11 -04:00
daurnimator
f2401a0756 Add sockaddr_vm for vSocckets on Linux 2022-10-27 20:51:35 -04:00
daurnimator
c0c8ee5ae9 Add reboot syscall
Only linux for now
2022-10-27 20:39:35 -04:00
Andrew Kelley
0b99e5e4c4 build: rename the "skip lib files" option
* Old cmake option: `-DZIG_SKIP_INSTALL_LIB_FILES=ON`
 * New cmake option: `-DZIG_NO_LIB=ON`
 * Old build.zig option: `-Dskip-install-lib-files`
 * New build.zig option: `-Dno-lib`

Motivation is making build commands easier to type.
2022-10-27 15:18:00 -07:00
Andrew Kelley
f4f4e33885 github: simplify bug issue template 2022-10-27 12:32:32 -07:00
Frank Denis
9c0d975a09 Revamp the ed25519 API (#13309) 2022-10-27 19:07:42 +02:00
Veikka Tuominen
648d34d8ea Sema: coerce zero-bit generic args are coerced properly
Closes #13307
2022-10-27 13:40:20 +03:00
Andrew Kelley
710e2e7f10 libcxx: only pass -DHAVE___CXA_THREAD_ATEXIT_IMPL for glibc
This definition communicates to libcxxabi that the libc will provide the
`__cxa_thread_atexit_impl` symbol. This is true for glibc but not
true for other libcs, such as musl.
2022-10-27 01:03:11 -04:00
Andrew Kelley
0b72965dbf build: update Tracy integration
* Update for v0.9
 * Enable the memory and callstack integrations by default
2022-10-26 18:17:49 -07:00
Andrew Kelley
7d0dc2fd75 docgen: fix not escaping html in shell samples 2022-10-26 16:48:50 -07:00
Veikka Tuominen
b937a04560 Sema: check coerceInMemoryAllowed earlier in resolvePeerTypes
Closes #13310
2022-10-27 01:31:18 +03:00
Veikka Tuominen
f3a3fb3d88 llvm: pass optional slices like regular slices 2022-10-27 01:31:18 +03:00
Veikka Tuominen
595ccecd88 llvm: do not return undefined pointers from array_to_slice 2022-10-27 01:31:18 +03:00
Veikka Tuominen
5b79f42dc5 std.mem.Allocator: do not return undefined pointers 2022-10-27 01:31:18 +03:00
Veikka Tuominen
d9fe5ba7f8 Sema: add error for too big packed struct 2022-10-27 01:31:18 +03:00
Veikka Tuominen
9dcfc829e6 Sema: fix some edge cases with error return traces and typeof blocks
Closes #13293
2022-10-27 01:31:18 +03:00
Veikka Tuominen
4ac8ec4c5c AstGen: fix refing inferred allocs
Closes  #13285
2022-10-27 01:31:18 +03:00
Veikka Tuominen
4fc944dde8 translate-c: fix redefinition of label on left recursive comma operator
Closes #13239
2022-10-27 01:31:18 +03:00
Veikka Tuominen
d773b7e71f translate-c: cleanup unused parameters 2022-10-27 01:31:18 +03:00
Veikka Tuominen
78a7bb108a llvm: handle namespace like packed structs
Closes #13159
Closes #13188
2022-10-27 01:31:18 +03:00
Veikka Tuominen
dd437ae399 stage2: optimize size of optional slices 2022-10-27 01:31:17 +03:00
Veikka Tuominen
b12a5cea75 remove test case triggering generic deletion bug
This test should be restored once the underlying issue is resolved (with the typo fixed).
2022-10-27 01:31:05 +03:00
Veikka Tuominen
db799ae628 Module: mitigate generic deletion bug 2022-10-27 01:31:05 +03:00
Hadrien Dorio
9db293492b make a .rsp file for zig clang
same as std.build.LibExeObjStep.make() for `zig build-exe`
closes #12419
2022-10-26 23:50:51 +02:00
Luuk de Gram
875e98a57d Merge pull request #13287 from Luukdegram/wasm-features
wasm-linker: feature compatibility validation
2022-10-26 14:04:16 +02:00
Jakub Konka
d42a719e8f Merge pull request #13299 from ziglang/darwin-autumn-cleaning
Darwin autumn cleaning: x86_64-macos.13 and aarch64-macos.13 support
2022-10-26 13:56:02 +02:00
Naoki MATSUMOTO
cd4865d88c std.crypto.sign.ecdsa: accepts unusual parameters like EcdsaP384Sha256 (#13302)
This commit accepts unusual parameters like EcdsaP384Sha256.
Some certifictes(below certs are in /etc/ssl/certs/ca-certificates.crt on Ubuntu 22.04) use EcdsaP384Sha256 to sign itself.
- Subject: C=GR, L=Athens, O=Hellenic Academic and Research Institutions Cert. Authority, CN=Hellenic Academic and Research Institutions ECC RootCA 2015
- Subject: C=US, ST=Texas, L=Houston, O=SSL Corporation, CN=SSL.com EV Root Certification Authority ECC
- Subject: C=US, ST=Texas, L=Houston, O=SSL Corporation, CN=SSL.com Root Certification Authority ECC

In verify(), hash array `h` is allocated to be larger than the scalar.encoded_length.
The array is regarded as big-endian.
Hash values are filled in the back of the array and the rest bytes in front are filled with zero.

In sign(), the hash array is allocated and filled as same as verify().
In deterministicScalar(), hash bytes are insufficient to generate `k`
To generate `k` without narrowing its value range,
this commit uses algorithm stage h. in  "Section 3.2 Generation of k" in RFC6979.
2022-10-26 13:18:06 +02:00
Jakub Konka
453a2d2fad darwin: remove 10.15.7 as available libc from src/target.zig 2022-10-26 08:53:33 +02:00
Frank Denis
22b71b1376 crypto/bcrypt: don't reimplement base64, just use a custom alphabet
Now that std.base64 supports everything bcrypt needs to encode its
parameters, we don't need to include another implementation.
2022-10-25 21:52:03 -07:00
Andrew Kelley
e490d9e517 CI: update drone and zinc tarballs 2022-10-25 19:22:34 -07:00
Andrew Kelley
8fc7b4d140 CMake: handle zstd the same as zlib
This is a new dependency of LLVM 15.
2022-10-25 18:29:39 -07:00
Andrew Kelley
0010288dae CI: update macos and windows tarballs 2022-10-25 17:16:36 -07:00
Jakub Konka
73c2e91a0d build: include -lzstd in the linker line when building Zig 2022-10-25 23:55:58 +02:00
Luuk de Gram
c0710b0c42 use fixed-size arrays for feature lists
Considering all possible features are known by the linker during
compile-time, we can create arrays on the stack instead of
dynamically allocating hash maps. We use a simple bitset to determine
whether a feature is enabled or not, and from which object file
it originates. This allows us to make feature validation slightly
faster and use less runtime memory.
In the future this could be enhanced further by having a single
array instead with a more sophisticated bitset.
2022-10-25 21:16:51 +02:00
Luuk de Gram
3d1d19f387 wasm-linker: seperate linker -and cpu features
The list of features a Wasm object/binary file can emit can differ
from the list of cpu features. The reason for this is because the
"target_features" section also contains linker features. An example
of this is the "shared-mem" feature, which is a feature for the linker
and not that of the cpu target as defined by LLVM.
2022-10-25 20:48:09 +02:00
Luuk de Gram
2f41109cc4 test/link: add Wasm linker tests for features
Adds a test for inferring features based on a different object file.
Also provides a test case where cpu features are explicitly set on
a library where the end result will output said target features.
2022-10-25 20:48:08 +02:00
Luuk de Gram
b14f605dd7 CheckObjectStep: parse and dump target_features
When an object file or binary contains the target_features section
we can now parse and then dump its contents in string format so
we can use them in our linker tests to verify the features section.
2022-10-25 20:48:08 +02:00
Luuk de Gram
777bcbf968 wasm-linker: emit target_features section
When the result is not being stripped, we emit the `target_features`
section based on all the used features. This includes features
inferred from linked object files.
Considering we know all possible features upfront, we can use an
array and therefore do not have to dynamically allocate memory.
Using this trick we can also easily order all features based
the same ordering as found in `std.Target.wasm` which is the same
ordering used by LLVM and the like.
2022-10-25 20:48:08 +02:00
Luuk de Gram
85b669d497 wasm-linker: validate feature compatibility
Verifies disallowed and used/required features. After verifying,
all errors will be emit to notify the user about incompatible
features. When the user did not define any featureset, we infer
the features from the linked objects instead.
2022-10-25 20:48:05 +02:00
Jakub Konka
304eb54169 darwin: update macOS libc headers
Add aarch64-macos.13 and x86_64-macos.13 libc headers, and remove
x86_64-macos.10 headers.
2022-10-25 20:37:26 +02:00
Jakub Konka
cf2ac99f84 darwin: remove libSystem.10.tbd 2022-10-25 20:37:26 +02:00
Jakub Konka
43dbebdd8d darwin: add libSystem.13.tbd 2022-10-25 20:31:48 +02:00
Jakub Konka
2d03f38988 darwin: bump minimum supported version to 11.7.1
Drop Catalina support.
2022-10-25 20:31:48 +02:00
Jakub Konka
98285b17b3 darwin: bump max macOS version to 13.0 2022-10-25 20:31:31 +02:00
Jacob Young
55c5da1b20 fmt: fix f80 hex formatting
These ifs were missing a case for f80 which should have shifted by one,
but we can just compute the correct value instead.  Also, we want the
fractional bits to be a multiple of four, not the mantissa bits, since
the mantissa could have a leading one which we want to be separated.
2022-10-25 09:04:04 -07:00
jcalabro
f027f163cd better source file links 2022-10-25 10:36:47 -04:00
Jacob Young
e20d2b3151 cbe: fix floating point builtins 2022-10-25 07:02:06 -04:00
Jacob Young
3d22327b23 cbe: enable test fixed by #13296 2022-10-25 05:43:00 -04:00
Jacob Young
94425fe46e cbe: improve floating point type support 2022-10-25 05:22:55 -04:00
Jacob Young
6021edd7ce cbe: add support for all float literals types 2022-10-25 05:22:55 -04:00
Jacob Young
54326cc554 cbe: implement field_parent_ptr 2022-10-25 05:11:29 -04:00
Jacob Young
361035fe7a cbe: implement cmp_lt_errors_len 2022-10-25 05:11:29 -04:00
Jacob Young
e470cf361f cbe: update test cases 2022-10-25 05:11:29 -04:00
Jacob Young
ab468d57e3 cbe: implement packed structs
Sometimes you have to break a test to make progress :)
2022-10-25 05:11:29 -04:00
Jacob Young
15df64ade8 std: add cbe hacks to more targets
These are needed because clang doesn't support anything in naked
functions, not even assembly register inputs.
2022-10-25 05:11:29 -04:00
Jacob Young
1bab854868 cbe: implement 128-bit and fix smaller integer builtins 2022-10-25 05:11:29 -04:00
Jacob Young
65a48df532 cbe: fix globals that reference functions
Global constant initializers can reference functions, so forward declare
the constants and initialize them later with the function definitions,
which guarantees that they appear after all declarations.
2022-10-25 05:11:29 -04:00
Jacob Young
8b6a3ba74e cbe: fix typedef declaration order 2022-10-25 05:11:29 -04:00
Jacob Young
3d90ee50ff cbe: allow immediate and register asm constraints in naked functions 2022-10-25 05:11:29 -04:00
Jacob Young
4fdac5f1c9 cbe: fix C syntax when rendering initializers 2022-10-25 05:11:29 -04:00
Jacob Young
4765294ca4 cbe: get enough things working to support basic programs
* Enable advanced start support.
 * Enable advanced test_runner support.
 * Zig Language Reference's Hello World now works.
2022-10-25 05:11:29 -04:00
Jacob Young
912b84bbad cbe: fix atomics 2022-10-25 05:11:29 -04:00
Jacob Young
6921b0a850 cbe: implement some float ops 2022-10-25 05:11:29 -04:00
Jacob Young
b48417aed2 cbe: misc fixes 2022-10-25 05:11:29 -04:00
Jacob Young
1dd4a6102f cbe: implement global assembly 2022-10-25 05:11:29 -04:00
Jacob Young
e8bda9eb3a cbe: implement ptr slice ptr 2022-10-25 05:11:29 -04:00
Jacob Young
87d432328e cbe: implement aggregate_init of struct 2022-10-25 05:11:29 -04:00
Jacob Young
feb8f81cd9 cbe: canonicalize types that have the same C type when emitting typedefs 2022-10-25 05:11:29 -04:00
Jacob Young
5eafc10bf4 cbe: fix global access fix 2022-10-25 05:11:29 -04:00
Jacob Young
c126a1018e cbe: implement more asm features 2022-10-25 05:11:28 -04:00
Jacob Young
a12535f501 cbe: fix global access 2022-10-25 05:11:28 -04:00
Jacob Young
f399dd107a cbe: implement tag name 2022-10-25 05:11:28 -04:00
Jacob Young
40b5bb7161 cbe: fix loads and stores of 0-bit types 2022-10-25 05:11:28 -04:00
Jacob Young
962f33ee11 cbe: implement airUnionInit 2022-10-25 05:11:28 -04:00
Jacob Young
6a4266d62a cbe: fix infinite recursion on recursive types 2022-10-25 05:11:28 -04:00
Jacob Young
7c9a9a0fd4 cbe: cleanup code and fix cases test breakage 2022-10-25 05:11:28 -04:00
Jacob Young
525dcaecba behavior: enable stage2_c tests that are currently passing
Also fix C warnings triggered by these tests.
2022-10-25 05:11:28 -04:00
Jacob Young
45c667eb21 behavior: fix redefined exports 2022-10-25 05:11:28 -04:00
Jacob Young
e875530f8f c: improve lowering of undef values
All remaining behavior test -Wall -Wextra warnings are unused (but set)
warnings.
2022-10-25 05:11:28 -04:00
Jacob Young
5ae3ac9c43 c: fix redefinition of typedef warnings
Closes #11651
2022-10-25 05:11:28 -04:00
Jacob Young
f81651932a c: hacks to fix incompatible redeclaration of library function warnings 2022-10-25 05:11:28 -04:00
Jacob Young
f8a8197caa c: fix incompatible pointer types warning 2022-10-25 05:11:28 -04:00
Jacob Young
3b501b2d81 c: cast NULL in advance to avoid comparison warnings 2022-10-25 05:11:28 -04:00
Jacob Young
497329622a c: fix nonscalar type cast warning 2022-10-25 05:11:28 -04:00
Jacob Young
72e2fc4c73 c: fix stage1 compatibility 2022-10-25 05:11:28 -04:00
Jacob Young
0092f6ed88 c: fix int literal warnings 2022-10-25 05:11:28 -04:00
Jacob Young
61bf43d790 c: fix switch on bool warning 2022-10-25 05:11:28 -04:00
Jacob Young
da939b032e c: fix empty container warnings 2022-10-25 05:11:28 -04:00
Jacob Young
6f3654ad69 c: implement @errorName 2022-10-25 05:11:28 -04:00
Jacob Young
c8d0e71de6 c: fix mangling of error names
Closes #12751
2022-10-25 05:11:28 -04:00
Jacob Young
ab024d3524 c: fix undefined tests in ReleaseSafe 2022-10-25 05:11:28 -04:00
Jacob Young
458233a684 fmt: fix f80 hex formatting
These ifs were missing a case for f80 which should have shifted by one,
but we can just compute the correct value instead.  Also, we want the
fractional bits to be a multiple of four, not the mantissa bits, since
the mantissa could have a leading one which we want to be separated.
2022-10-25 05:06:54 -04:00
Andrew Kelley
b3cd38ea4a link: add an explicit error set for flush() and flushModule()
This makes it easier to understand how control flow should happen in
various cases; already just by doing this it is revealed that
UndefinedSymbol and UndefinedSymbolReference should be merged, and that
MissingMainEntrypoint should be removed in favor of the ErrorFlags
mechanism thath we already have for missing the main entrypoint.

The main motivation for this change, however, is preventing a compile
error when there is conditional compilation inside linker
implementations, causing the flush() error set to depend on compilation
options. With this change, the error set is fixed, and, notably, the
`-Donly-c` flag no longer has compilation errors due to this error set.
2022-10-24 23:30:57 -07:00
Jacob G-W
5aef54cbc8 additional fixes for Plan9
with this, the tests should pass
2022-10-24 17:01:26 -04:00
Jacob G-W
c6fb798740 Revert "remove plan9 test coverage": Plan9 now works :^)
This reverts commit 67db2b85b7.
2022-10-24 16:53:12 -04:00
Jacob G-W
6cba18fe60 Add relocations to the plan9 backend 2022-10-24 16:53:12 -04:00
Jacob G-W
5cf3d10e35 Plan9: deal with unnamed decls
Hello World works again!
2022-10-24 16:53:12 -04:00
Cody Tapscott
4ecc384f99 Fix long double on x86_64-windows
The larger alignment on this platform means that long double reports
a sizeof 16 bytes, but it's underlying size is really just the 10
bytes of `f80`

C doesn't give us a way to see the "underlying" size of a type, so
this has to be caught by hand or by monitoring runtime memory. Luckily,
x86 and x86-64 are the only platforms that seem to use a non-power-of-two
type like this.
2022-10-23 23:18:50 -07:00
Andrew Kelley
4f04759c87 build: add -Donly-c option
This option can be used to produce a C backend build of the self-hosted
compiler, which only has the C backend enabled. Once the C backend is
capable of self-hosting, this will be a way for us to replace our stage1
codebase with a C backend build of self-hosted, which we can then use
for bootstrapping. See #5246 for more details.

Using this option right now results in a crash because the C backend is
not yet passing all the behavior tests.
2022-10-23 20:05:12 -07:00
Jakub Konka
828735ac03 macho: handle majority of DW_FORM_ values for DWARF4 in the linker 2022-10-23 21:53:36 +02:00
Andrew Kelley
04472af328 Merge pull request #13251 from Vexu/c-abi
implement ARM C ABI, separate C ABI tests from standalone tests
2022-10-23 12:16:58 -07:00
Andrew Kelley
a3033c7bd9 Merge pull request #13267 from ziglang/macho-threaded-sha256
link.MachO: multi-thread first round of sha256 hashing
2022-10-23 11:35:03 -07:00
Jakub Konka
2f37278540 macho: temp hash buffer has to live as long as pread error resolution 2022-10-23 10:15:42 +02:00
Jakub Konka
1bbafbc65f macho: increment temp buffer when calculating hashes 2022-10-23 09:58:47 +02:00
Andrew Kelley
0ae60f7236 CMake: detect use of CMAKE_PREFIX_PATH env var
CMake recognizes the CMAKE_PREFIX_PATH environment variable for some
things, and also the CMAKE_PREFIX_PATH cache variable for other things.
However, it does not relate these two things, i.e. if the environment
variable is set, CMake does not populate the cache variable in a
corresponding manner. Some package systems, such as Homebrew, set the
environment variable but not the cache variable. Furthermore, the
environment variable follows the system path separator, such as ':' on
POSIX and ';' on Windows, but the cache variable follows CMake's array
behavior, i.e. always ';' for a separator.

Closes #13242
2022-10-22 20:30:08 -07:00
Andrew Kelley
f82a82f889 Revert "fix CI failures with commit "ci: make directory structure in releases consistent""
This reverts commit 54c8861bc4.

This caused CI failure.
2022-10-22 20:29:24 -07:00
Cody Tapscott
c96f85852e CType: Add preferredAlignment
This value corresponds to clang/gcc's `__alignof` (rather than
`_Alignof` which reports the minimum alignment). We don't use this
information yet, but it might be useful for implementing ABIs so it
is included here.
2022-10-22 17:25:02 -07:00
Cody Tapscott
c50f33b111 compiler_rt: Always export "standard" symbol names
The Zig LLVM backend emits calls to softfloat methods with the "standard
compiler-rt" names. Rather than add complexity to the backend and
have to synchronize the naming scheme across all targets, the simplest
fix is just to export these symbols under both the "standard" and the
platform-specific naming convention.
2022-10-22 17:19:33 -07:00
Eric Joldasov
54c8861bc4 fix CI failures with commit "ci: make directory structure in releases consistent" 2022-10-22 16:43:35 -07:00
Andrew Kelley
4a2f1e748e link.MachO: multi-thread first round of sha256 hashing
when computing the adhoc code signature
2022-10-22 16:03:59 -07:00
Veikka Tuominen
f2a7aba586 x86_64 llvm: correct lowering of ptr sized float struct
Closes #13211
2022-10-22 22:00:59 +03:00
Andrew Kelley
e67c756b91 Merge pull request #13260 from ziglang/zld-sync
macho: faster and more memory efficient linker
2022-10-22 10:14:46 -07:00
Veikka Tuominen
be10f95994 ARM C ABI: workaround i128 issues 2022-10-22 19:32:56 +03:00
Jan Philipp Hafer
776f7de967 update compiler_rt README and prettify it
This documents status of routines and adds the next work item
"Decimal float library routines", which are only recommended for
binary data. Complete absence of tests is also documented.
This does not document the various aliases, e.g. those for ARM.

Missing Integer library routines:
- __addvsi3
- __addvdi3
- __addvti3
- __addvdi3
- __addvti3
- __subvsi3
- __subvdi3
- __subvti3
- __subvdi3
- __subvti3
- __mulvsi3
- __mulvdi3
- __mulvti3
- __mulvdi3
- __mulvti3

Missing floating library routines:
- __powisf2
- __powidf2
- __powitf2
- __powixf2

Missing routines for symbol-level compatibility to gcc:
- __ashlsi3
- __ashrsi3
- __lshrsi3
2022-10-22 09:23:50 -07:00
Andrew Kelley
10b8c4d8f0 CI: drone: skip some ReleaseFast and ReleaseSmall std lib tests
Follow-up commit to b9103bd514.
2022-10-22 09:19:05 -07:00
Luuk de Gram
cdf7e7dba9 fix: correctly import memcmp.zig in compiler-rt
cmp.zig was accidently being referenced twice, rather than importing
memcmp.zig. This means that its symbols were also not included in
the generated compiler-rt output.
2022-10-22 16:56:33 +02:00
Jakub Konka
593b75b109 macho: some docs 2022-10-22 14:53:53 +02:00
Veikka Tuominen
3f41979061 replace some panics with try in C ABI tests 2022-10-22 14:52:26 +03:00
Veikka Tuominen
5e0b4836a1 stage2: implement RISCV C ABI 2022-10-22 14:52:26 +03:00
Veikka Tuominen
8fa91939a8 build.zig: separate C ABI tests from standalone tests 2022-10-22 11:31:41 +03:00
Veikka Tuominen
12a2ccfb45 make C ABI tests compile on powerpc 2022-10-22 11:31:41 +03:00
Veikka Tuominen
031c768cc8 add C ABI tests for simd vectors 2022-10-22 11:31:41 +03:00
Jakub Konka
086cee844a macho: refactor dead code stripping conditions
1. If an object file was not compiled with `MH_SUBSECTIONS_VIA_SYMBOLS`
   such a hand-written ASM on x86_64, treat the entire object file as
   not suitable for dead code stripping aka a GC root.
2. If there are non-extern relocs within a section, treat the entire
   section as a root, at least temporarily until we work out the exact
   conditions for marking the atoms live.
2022-10-22 07:59:24 +02:00
Jakub Konka
0cc4d54781 macho: do not skip over SUBTRACTOR reloc when dead stripping 2022-10-22 07:59:24 +02:00
Jakub Konka
f8cbe29a17 macho: fix incorrect lookup of symbols when calculating subtractors 2022-10-22 07:59:24 +02:00
Jakub Konka
93cc5496e1 macho: rewrite movq to leaq when TLV is not external pointer 2022-10-22 07:59:24 +02:00
Jakub Konka
5823f19c5e macho: gracefully handle uninitialized symtabs in objects 2022-10-22 07:59:24 +02:00
Jakub Konka
2c2ff4558f macho: fix handling of lack of subsections and tracking of inner symbols 2022-10-22 07:59:24 +02:00
Jakub Konka
5edb8e0b8f macho: relax SUBTRACTOR assumption it not being a defined global 2022-10-22 07:59:23 +02:00
Jakub Konka
bc1e714de6 macho: revert changes to file descriptors mgmt 2022-10-22 07:59:23 +02:00
Jakub Konka
15f1e6a60c macho: fix silly error where we would incorrectly skip a valid binding 2022-10-22 07:59:23 +02:00
Jakub Konka
c15e03ac79 macho: fix bug in incorrectly splicing nodes in trie 2022-10-22 07:59:23 +02:00
Jakub Konka
5b9eaf2938 macho: do not assume __la_symbol_ptr was created 2022-10-22 07:59:23 +02:00
Jakub Konka
33d1942f27 macho: always create __TEXT segment 2022-10-22 07:59:23 +02:00
Jakub Konka
e70adc7f1a macho: skip parsing __eh_frame until we know how to handle it 2022-10-22 07:59:23 +02:00
Jakub Konka
baceaf65f2 macho: fix incorrectly erroring out with multiple sym definition 2022-10-22 07:59:23 +02:00
Jakub Konka
a32bc0e39c macho: fix 32bit build 2022-10-22 07:59:23 +02:00
Jakub Konka
04a590a171 macho: remove unused nlist flags 2022-10-22 07:59:23 +02:00
Jakub Konka
d57639a308 macho: upstream rewritten traditional linker, zld
kubkon/zld gitrev 5733ed87abe2f07e1330c3232a252e9defec638a
2022-10-22 07:59:23 +02:00
Andrew Kelley
09236d29b7 Merge pull request #12837 from topolarity/err-ret-trace-improvements-1923
stage2: Pop error trace frames for handled errors (#1923)
2022-10-21 20:24:37 -07:00
Cody Tapscott
94945864b9 Type.zig: Add nvcl/cuda CType definitions 2022-10-21 20:16:00 -07:00
Andrew Kelley
b9103bd514 CI: drone: skip ReleaseSafe std lib tests that link libc
To save a little bit of time and keep under the 2 hour mark.
2022-10-21 19:28:46 -07:00
Cody Tapscott
f0e66ac4d0 std.Target: Remove longDoubleIs
This function is redundant with CType.sizeInBits(), and until the
previous commit they disagreed about the correct long double type
for several targets. Although they're all synced up now, it's much
simpler just to have a single source of truth.
2022-10-21 19:20:58 -07:00
Cody Tapscott
ddbdb83c86 stage 2: Update C types' size/alignment
These updates were made by testing against the `sizeof/_Alignof` reported
by Clang for all supported arch-OS-ABI combinations and correcting any
discrepancies.

This is bound to have a few errors (the recent long double fix for i386
Android is one example), but Clang is certainly not a bad place to start,
especially for our most popular targets.
2022-10-21 19:11:47 -07:00
Louis Pearson
8d4778b4f9 Support compiling for the android NDK (#13245) 2022-10-21 18:32:56 -04:00
Andrew Kelley
3b2f0c3eee Revert "ci: make directory structure in releases consistent"
This reverts commit 28054d96f0.

This caused CI failures.
2022-10-21 13:18:37 -07:00
Cody Tapscott
c36a2c27a5 Change how Block propagates (error return) trace index
Instead of adding 3 fields to every `Block`, this adds just one. The
function-level information is saved in the `Sema` struct instead,
which is created/copied more rarely.
2022-10-21 12:46:46 -07:00
Cody Tapscott
74b9cbd895 stage2: Skip test exposing #13175
This PR (#12873) in combination with this particular test exposed
a pre-existing bug (#13175).

This means that the test for #13038 has regressed
2022-10-21 12:40:33 -07:00
Cody Tapscott
a4523a2d4a builtin.zig: Do not overwrite error frames when trace full
Previously, we'd overwrite the errors in a circular buffer. Now that
error return traces are intended to follow a stack discipline, we no
longer have to support the index rolling over. By treating the trace
like a saturating stack, any pop/restore code still behaves correctly
past-the-end of the trace.

As a bonus, this adds a small blurb to let the user know when the trace
saturated and x number of frames were dropped.
2022-10-21 12:40:33 -07:00
Cody Tapscott
d060cbbec7 stage2: Keep error return traces alive when storing to const
This change extends the "lifetime" of the error return trace associated
with an error to continue throughout the block of a `const` variable
that it is assigned to.

This is necessary to support patterns like this one in test_runner.zig:
```zig
const result = foo();
if (result) |_| {
    // ... success logic
} else |err| {
    // `foo()` should be included in the error trace here
    return error.TestFailed;
}
```

To make this happen, the majority of the error return trace popping logic
needed to move into Sema, since `const x = foo();` cannot be examined
syntactically to determine whether it modifies the error return trace. We
also have to make sure not to delete pertinent block information before it
makes it to Sema, so that Sema can pop/restore around blocks correctly.

* Why do this only for `const` and not `var`? *

There is room to relax things for `var`, but only a little bit. We could
do the same thing we do for const and keep the error trace alive for the
remainder of the block where the *assignment* happens. Any wider scope
would violate the stack discipline for traces, so it's not viable.

In the end, I decided the most consistent behavior for the user is just
to kill all error return traces assigned to a mutable `var`.
2022-10-21 12:40:29 -07:00
Cody Tapscott
597ead5318 stage2: Fix usage of getError()
Despite the old doc-comment, this function cannot be valid for all types
since it operates with only a value and Error (Union) types have
overlapping Value representations with other Types.
2022-10-21 11:22:49 -07:00
Cody Tapscott
b529d8e48f stage2: Propagate error return trace into fn call
This change extends the "lifetime" of the error return trace associated
with an error to include the duration of a function call it is passed
to.

This means that if a function returns an error, its return trace will
include the error return trace for any error inputs. This is needed to
support `testing.expectError` and similar functions.

If a function returns a non-error, we have to clean up any error return
traces created by error-able call arguments.
2022-10-21 11:22:49 -07:00
Cody Tapscott
77720e30aa Re-factor: Change AstGen.ResultLoc to be a struct
This re-factor is intended to make it easier to track what kind of
operator/expression consumes a result location, without overloading the
ResultLoc union for this purpose.

This is used in the following commit to keep track of initializer
expressions of `const` variables to avoid popping error traces
pre-maturely. Hopefully this will also be useful for implementing
RLS temporaries in the future.
2022-10-21 11:22:46 -07:00
Cody Tapscott
724d753638 stage2: Add .save_err_return_trace_index AIR op
This is encoded as a primitive AIR instruction to resolve one corner
case: A function may include a `catch { ... }` or `else |err| { ... }`
block but not call any errorable fn. In that case, there is no error
return trace to save the index of and codegen needs to avoid
interacting with the non-existing error trace.

By using a primitive AIR op, we can depend on Liveness to mark this
unused in this corner case.
2022-10-21 10:44:20 -07:00
Cody Tapscott
3007fdde45 stage2: Pop error trace when storing error to var/const
In order to enforce a strict stack discipline for error return traces,
we cannot track error return traces that are stored in variables:

  ```zig
  const x = errorable(); // errorable()'s error return trace is killed here

  // v-- error trace starts here instead
  return x catch error.UnknownError;
  ```

In order to propagate error return traces, function calls need to be passed
directly to an error-handling expression (`if`, `catch`, `try` or `return`):

  ```zig
  // When passed directly to `catch`, the return trace is propagated
  return errorable() catch error.UnknownError;

  // Using a break also works
  return blk: {
      // code here
      break :blk errorable();
  } catch error.UnknownError;
  ```

Why do we need this restriction? Without it, multiple errors can co-exist
with their own error traces. Handling that situation correctly means either:
  a. Dynamically allocating trace memory and tracking lifetimes, OR
  b. Allowing the production of one error to interfere with the trace of another
     (which is the current status quo)

This is piece (3/3) of https://github.com/ziglang/zig/issues/1923#issuecomment-1218495574
2022-10-21 10:44:20 -07:00
Cody Tapscott
0c3a50fe1c stage2: Do not pop error trace if result is an error
This allows for errors to be "re-thrown" by yielding any error as the
result of a catch block. For example:

```zig
fn errorable() !void {
    return error.FallingOutOfPlane;
}

fn foo(have_parachute: bool) !void {
    return errorable() catch |err| b: {
        if (have_parachute) {
            // error trace will include the call to errorable()
            break :b error.NoParachute;
        } else {
            return;
        }
    };
}

pub fn main() !void {
    // Anything that returns a non-error does not pollute the error trace.
    try foo(true);

    // This error trace will still include errorable(), whose error was "re-thrown" by foo()
    try foo(false);
}
```

This is piece (2/3) of https://github.com/ziglang/zig/issues/1923#issuecomment-1218495574
2022-10-21 10:44:19 -07:00
Cody Tapscott
eda3eb1561 stage2: "Pop" error trace for break/return within catch
This implement trace "popping" for correctly handled errors within
`catch { ... }` and `else { ... }` blocks.

When breaking from these blocks with any non-error, we pop the error
trace frames corresponding to the operand. When breaking with an error,
we preserve the frames so that error traces "chain" together as usual.

```zig
fn foo(cond1: bool, cond2: bool) !void {
    bar() catch {
    	if (cond1) {
	    // If baz() result is a non-error, pop the error trace frames from bar()
	    // If baz() result is an error, leave the bar() frames on the error trace
            return baz();
	} else if (cond2) {
	    // If we break/return an error, then leave the error frames from bar() on the error trace
	    return error.Foo;
	}
    };

    // An error returned from here does not include bar()'s error frames in the trace
    return error.Bar;
}
```

Notice that if foo() does not return an error it, it leaves no extra
frames on the error trace.

This is piece (1/3) of https://github.com/ziglang/zig/issues/1923#issuecomment-1218495574
2022-10-21 10:43:42 -07:00
Veikka Tuominen
5316a00a18 stage2: properly reset error return trace index 2022-10-21 10:43:42 -07:00
Veikka Tuominen
3981250b84 aarch64 C ABI: return union instead of array of two enums
The result is much cleaner and the second element was unused most of the time.
2022-10-21 20:30:45 +03:00
Eric Joldasov
28054d96f0 ci: make directory structure in releases consistent 2022-10-21 12:51:04 -04:00
Veikka Tuominen
9ae78a5890 stage2: implement ARM C ABI
Six new passing tests and the previously incorrectly passing
complex tests are now skipped.
2022-10-21 18:07:11 +03:00
Veikka Tuominen
7622078127 aarc64 C ABI: fix handling of packed structs and unions
* Packed unions were not handled at all previously.
* Packed unions and structs are integers so their floats should not be counted.
2022-10-21 17:51:54 +03:00
David Gonzalez Martin
680d3cd1fc UEFI: Querying memory map size with no allocation
This makes possible to query the memory map size from EFI firmware
without making any allocation beforehand. This makes possible to be
precise about the size of the allocation which will own a copy of
the memory map from the UEFI application.
2022-10-21 12:17:41 +02:00
Veikka Tuominen
972c39e2c0 Merge pull request #13219 from Vexu/stage2-fixes
Stage2 bug fixes
2022-10-21 12:11:49 +02:00
Joachim Schmidt
41575b1f55 Merge pull request #13236 from joachimschmidt557/stage2-aarch64
stage2 AArch64: move to new allocRegs mechanism
2022-10-21 09:17:56 +02:00
Andrew Kelley
0f00766661 Revert "add std.debug.todo"
This reverts commit 80ac022c46.

I changed my mind on this one, sorry. I don't think this belongs in the
standard library.
2022-10-20 18:34:40 -07:00
Veikka Tuominen
2609e33ab0 make C ABI tests compile on arm, mips and riscv
x86_64      24/25
x86         15/25
aarch64     25/25 - all
arm         18/25
mips        10/24
riscv64     13/25
wasm32      25/25 - all
2022-10-20 20:11:12 +03:00
Veikka Tuominen
646d927c79 stage2: fix handling of aarch64 C ABI float array like structs
Closes #11702
Closes #13125
2022-10-20 20:11:12 +03:00
Veikka Tuominen
07b6173cb8 delete failing recursive test
Don't forget to add these back when solving #12973
2022-10-20 20:11:12 +03:00
Veikka Tuominen
7e946bc790 make C ABI tests compile on i386 2022-10-20 20:11:12 +03:00
Veikka Tuominen
51491186cb stage2: fix x86_64 C ABI of struct with array member
Closes #12185
2022-10-20 20:11:12 +03:00
Veikka Tuominen
ce95cc170b Value: handle runtime_int in hashPtr
Closes #12702
2022-10-20 20:11:12 +03:00
Veikka Tuominen
9a52abf3b4 Sema: add missing calls to wip_captures.finalize
Closes #13171
2022-10-20 20:11:12 +03:00
Veikka Tuominen
3b60a6de2f Sema: fix using runtime instructions inside typeof in comptime only blocks
Closes #13210
Follow up to 3ccd4907fb
2022-10-20 20:11:12 +03:00
Veikka Tuominen
c95a34b68f stage2: improve source location of assignment 2022-10-20 20:11:00 +03:00
Veikka Tuominen
34e4b07d0c Sema: allow runtime only instructions to be emitted in outside functions
It is possible to get comptime-known values from runtime-known values
for example the length of array. Allowing runtime only instructions to
be emitted outside function bodies allows these operations to happen.
In places where comptime-known values are required we have other methods
to ensure that and they usually result in more specific compile errors too.

Closes #12240
2022-10-20 20:11:00 +03:00
Veikka Tuominen
13897be0ab Type: bitSizeOf non-packed structs should include padding
Closes #13214
2022-10-20 20:11:00 +03:00
Andrew Kelley
5b9c8d1d6f add m68k target CPU features 2022-10-20 09:21:06 -07:00
joachimschmidt557
67941926b2 stage2 AArch64: Remove remaining legacy binOp code 2022-10-20 16:14:52 +02:00
joachimschmidt557
dd62d5941e stage2 AArch64: move remaining operations out of binOp 2022-10-20 16:14:52 +02:00
joachimschmidt557
3800bb538a stage2 AArch64: mov mul,div,mod to new allocRegs mechanism 2022-10-20 16:14:52 +02:00
joachimschmidt557
ea7a60116d stage2 AArch64: move add+sub to new allocRegs mechanism 2022-10-20 16:14:52 +02:00
joachimschmidt557
d8fddb535c stage2 AArch64: move cmp to new allocRegs mechanism
Remove cmp from binOp in the process
2022-10-20 16:14:52 +02:00
joachimschmidt557
5838fe89c1 stage2 AArch64: introduce ldr_ptr_stack Mir instruction 2022-10-20 16:14:52 +02:00
joachimschmidt557
230bafa1ab stage2 AArch64: simplify allocMem 2022-10-20 16:14:52 +02:00
joachimschmidt557
151e15e444 stage2 AArch64: merge floating-point registers into Register enum 2022-10-20 16:14:50 +02:00
Matheus C. França
b41b35f578 crypto/benchmark - replace testing allocator
Fix error: Cannot use testing allocator outside of test block
2022-10-20 14:04:59 +03:00
yujiri8
a99d465f62 Fix #12091: Error message with TERM=dumb is missing info 2022-10-20 13:57:57 +03:00
Andrew Kelley
a4eb221b9e link/MachO: avoid depending on host PATH_MAX
closes #13229

Restores ability to compile zig for WASI
2022-10-19 12:20:42 -07:00
LordMZTE
3f577f06a0 build: added unwind_tables to LibExeObjStep 2022-10-19 13:24:06 -04:00
Andrew Kelley
8a344fab39 Merge pull request #13036 from BratishkaErik/fix-installing 2022-10-19 09:34:35 -04:00
Luuk de Gram
7d6596e979 Merge pull request #13218 from Luukdegram/fix-emulatable-step
std: CheckObject - correctly depend on its own step when creating an EmulatableRunStep
2022-10-19 08:36:14 +02:00
Andrew Kelley
1952dd6437 Revert recent std.Progress implementation changes
I have noticed this causing my terminal to stop accepting input
sometimes. The previous implementation with all of its flaws was better
in the sense that it never caused this to happen.

This commit has multiple reverts in it:

Revert "Merge pull request #13148 from r00ster91/progressfollowup"

This reverts commit cb257d59f9, reversing
changes made to f5f28e0d2c.

Revert "`std.Progress`: fix inaccurate line truncation and use optimal
max terminal width (#12079)"

This reverts commit cd3d8f3a4e.
2022-10-18 18:53:44 -07:00
Andrew Kelley
cb635e084b stage2: better handling of CacheMode.whole on Windows
Windows gives AccessDenied if you delete a directory which contains open
file handles. This could be triggered when using CacheMode.whole when
cross compiling macho test binaries.
2022-10-18 16:52:43 -07:00
Andrew Kelley
9ee4530b9b std.os.windows.OpenFile: handle INVALID_HANDLE ntstatus 2022-10-18 16:52:43 -07:00
Andrew Kelley
c7772dd694 std.zig.system.NativePaths: avoid calling std.os.getenv on Windows 2022-10-18 16:52:43 -07:00
Andrew Kelley
caddbbc315 build: avoid compiling self-hosted twice
build.zig: add a 'compile' step to compile the self-hosted compiler
without installing it.
Compilation: set cache mode to whole when using the LLVM backend and
--enable-cache is passed.

This makes `zig build` act the same as it does with stage1. Upside is
that a second invocation of `zig build` on an unmodified source tree
will avoid redoing the compilation again. Downside is that it will
proliferate more garbage in the project-local cache (same as stage1).

This can eventually be fixed when Zig's incremental compilation is more
robust; we can go back to having LLVM use CacheMode.incremental and rely
on it detecting no changes and avoiding doing the flush() step.
2022-10-18 16:52:43 -07:00
Eric Joldasov
1013212697 cmake: separate installing and building (again) 2022-10-18 16:52:43 -07:00
Veikka Tuominen
4aaff75c81 Sema: resolve tuple default values before hashing
Closes #12488
2022-10-19 01:38:19 +03:00
Veikka Tuominen
6582896ee0 Sema: remove unresolved inferred allocs
Closes #2557
2022-10-19 01:38:19 +03:00
Veikka Tuominen
4e134f6dcb Sema: respect inline call semantics
If an argument is comptime-known but shouldn't be create an alloc
to store it in to get a runtime-known value.
2022-10-19 01:38:18 +03:00
Andrew Kelley
14c173b200 ci: windows: update tarball
This has the `@max`/`@maximum`, `@min`/`@minimum` update.
2022-10-18 15:30:44 -07:00
Andrew Kelley
4f9345d20b Revert "adding static and dynamic ZigEquivalent
enums so that we can branch to set `link_mode` properly when we iterate
over the clang arguments. also replaced `dynamic` flag in
clang_options_data.zig with proper definition similarly to `static`."

This reverts commit 6af0eeb58d.

This change needs more careful consideration. It regressed
zig-bootstrap due to cmake passing `-static -lkernel32` and zig failing
with error.UnableToStaticLink.

See https://github.com/ziglang/zig-bootstrap/issues/134
2022-10-18 14:16:07 -07:00
Andrew Kelley
b120c819db Merge pull request #13055 from alichraghi/m2m
all: rename `@maximum` to `@max` and `@minimum` to `@min`
2022-10-18 14:42:55 -04:00
Andrew Kelley
4962f36b0f synchronize target CPU features with LLVM 15.0.3 2022-10-18 10:18:09 -07:00
Andrew Kelley
7c7d9e13d7 Sema: fix runtime int to enum with one possible value 2022-10-18 10:18:09 -07:00
Andrew Kelley
d0a5ad0e4c update libcxx to LLVM 15.0.3 2022-10-18 10:18:09 -07:00
fd10baf748 os.copy_file_range: save a syscall for most operations
Currenty copy_file_range always uses at least two syscalls:

1. As many as it needs to do the initial copy (always 1 during my
   testing)
2. The last one is always when offset is the size of the file.

The second syscall is used to detect the terminating condition. However,
because we do a stat for other reasons, we know the size of the file,
and we can skip the syscall.

Sparse files: since copy_file_range expands holes of sparse files, I
conclude that this layer was not intended to work with sparse files. In
other words, this commit does not make it worse for sparse file society.

Test program
------------

    const std = @import("std");

    pub fn main() !void {
        const arg1 = std.mem.span(std.os.argv[1]);
        const arg2 = std.mem.span(std.os.argv[2]);
        try std.fs.cwd().copyFile(arg1, std.fs.cwd(), arg2, .{});
    }

Test output (current master)
----------------------------

Observe two `copy_file_range` syscalls: one with 209 bytes, one with
zero:

    $ zig build-exe cp.zig
    $ strace ./cp ./cp.zig ./cp2.zig |& grep copy_file_range
    copy_file_range(3, [0], 5, [0], 4294967295, 0) = 209
    copy_file_range(3, [209], 5, [209], 4294967295, 0) = 0
    $

Test output (this diff)
-----------------------

Observe a single `copy_file_range` syscall with 209 bytes:

    $ /code/zig/build/zig build-exe cp.zig
    $ strace ./cp ./cp.zig ./cp2.zig |& grep copy_file_range
    copy_file_range(3, [0], 5, [0], 4294967295, 0) = 209
    $
2022-10-18 12:57:21 -04:00
Motiejus Jakštys
5ec76cf5c8 [elf] main.zig: add -z nocopyreloc
I did not fully wire it up in main.zig when I originally implemented
`-z nocopyreloc` in #11679 (440f5249f1a). Finish it.

If we strictly follow the rules, we should bump the cache has version,
since the field was technically added only now. But since nobody
complained thus far, I don't think many users care that much about it
and we can omit it.
2022-10-18 12:55:31 -04:00
Loris Cro
787788996f Merge pull request #13120 from jcalabro/master
Add [src] links to function decls in autodocs
2022-10-18 17:51:40 +02:00
Luuk de Gram
c0fe135ff3 test/link: remove redundant dependOn statements
`runAndCompare` will already depend on the `CheckObject` step itself
so it's not needed to also have the test step depend on the
check object step.
2022-10-18 17:20:08 +02:00
Luuk de Gram
10b56b21d4 CheckObjectStep: correctly depend on its own step
When creating an `EmulatableRunStep`, it now correctly depends
on its own step rather than only the executable that was created.
This means we do not need to add extra `dependOn` statements on
both the emulatable step as well as the check object step.
2022-10-18 17:15:58 +02:00
Jacob Young
687a7d38a0 value: implement Value.eqlAdvanced on slices
* Support comparison between implicitly casted array pointer and slice.
 * Support comparison between slices with different value tags.

Closes #12700
2022-10-18 14:16:39 +02:00
Veikka Tuominen
71e0ab4ec7 zig fmt: rewrite @maximum and @minimum 2022-10-18 14:16:24 +03:00
Ali Chraghi
ca27055cda all: rename @maximum to @max and @minimum to @min 2022-10-18 14:15:16 +03:00
GethDW
edc842ff18 stage2: implement packedStuctToInt for more types 2022-10-18 14:05:48 +03:00
Meghan
759f72fcfe std.debug: define error set in DebugInfo.lookupModuleDl 2022-10-18 13:03:49 +02:00
Xavier Bouchoux
23e212a9d0 std: check for overflow in dumpStackTraceFromBase
same change as [68e26a2cee] "std: check for overflow in writeCurrentStackTrace"

On arm64 macOS, the address of the last frame is 0x0 rather than
a positive value like 0x1 on x86_64 macOS, therefore, we overflow
an integer trying to subtract 1 when printing the stack trace. This
patch fixes it by first checking for this condition before trying
to subtract 1.

Same behaviour on i386-windows-msvc.

Note that we do not need to signal the `SignalIterator` about this
as it will correctly detect this condition on the subsequent iteration
and return `null`, thus terminating the loop.
2022-10-18 13:03:22 +02:00
jacobly0
bd0dd225e8 Sema: implement linksection on functions
* Sema: implement linksection on functions

 * Implement function linksection in Sema.
 * Don't clobber function linksection/align/addrspace in Sema.
 * Fix copy-paste typo in tests.
 * Add a bunch of missing test_step.dependOn.
 * Fix checkInSymtab match.

Closes #12546
2022-10-18 14:02:10 +03:00
jumpnbrownweasel
71f8762959 Fix for #13163: DefaultRwLock accumulates write-waiters, eventually fails to write lock (#13180)
* Fix for: DefaultRwLock accumulates write-waiters, eventually fails to write lock #13163

* Comment out debug.print at the end of the last test.

* Code formatting

* - use equality test after lock/unlock rather than peeking into internals.
  however, this is still implementation specific and only done for
  DefaultRwLock.
- add num_reads maximum to ensure that reader threads stop if writer threads are
  starved
- use relaxed orderings for the read atomic counter
- don't check at the end for non-zero read ops, since the reader threads may
  only run once if they are starved

* More review changes
- Monotonic is sufficient for incrementing the reads counter
2022-10-17 18:15:15 -05:00
Andrew Kelley
ce3ffa5e1b Merge pull request #11747 from Luukdegram/compiler-rt
compiler_rt: Move mem implementations from c.zig
2022-10-17 18:12:22 -04:00
Yujiri
8aa21ade8c add tcdrain on linux 2022-10-17 18:01:05 -04:00
Andrew Kelley
a1486e1e1e stage2: allow comptime expressions for inline asm
It is not yet determined whether the Zig language will land on
text-based string concatenation for inline assembly, as Zig 0.9.1
allows, and as this commit allows, or whether it will introduce a new
assembly syntax more integrated with the rest of the language. Until
this decision is made, this commit relaxes the restriction which was
preventing inline assembly expressions from using comptime expressions
for the assembly source code.
2022-10-17 16:31:23 -04:00
Veikka Tuominen
be9a4a1f97 Sema: handle noreturn in boolBr
Closes #13112
2022-10-17 18:53:15 +03:00
Jacob Young
1e963053d0 tools: add lldb stage2 pretty printers
* Fix untagged struct names in debug info for llvm.
 * Factor out common stage2 pretty printer data.
 * Add lldb version of stage2 pretty printers.
2022-10-17 07:55:28 -04:00
Andrew Kelley
c010767311 Merge pull request #13193 from Luukdegram/wasm-locals
stage2: Wasm - Integrate lifeness analysis for locals reusal
2022-10-17 07:51:07 -04:00
Jacob Young
1e0f74a9e6 emutls: add const to default_value field
Commit f14cc75 accidentally added a const when grepping for assignments
to `std.builtin.Type.StructField.default_value`, however when looking
into it further, I noticed that even though this default_value field is
emitted into the .data section, the value it points to is actually
emitted into the .rodata section, so it seems correct to use const here.
2022-10-17 07:50:01 -04:00
Naoki MATSUMOTO
059e397ffc std.os: handle error.UnreachableAddress in send() 2022-10-17 13:10:23 +02:00
Evin Yulo
f36aee93cc Give better error message for --name with folder separator 2022-10-17 13:06:06 +02:00
Jens Goldberg
1459231624 fix setsockopt returning ENODEV 2022-10-17 12:55:12 +02:00
Ali Chraghi
5127dae7a2 std.os: fix execv* doc comment 2022-10-16 11:38:22 -04:00
dan
ca1c185eb6 std.zig: search include dir and lib dir from environment variables (#13145)
* minor fix based on feedback from @marler8997

Co-authored-by: dan <i@dan.games>
2022-10-16 11:37:35 -04:00
bfredl
c750d95417 os.linux: some fixes to BPF module
- For ALU operations, src should be allowed to be an explicit Reg.
- Expose AluOp and JmpOp as public types.
  This makes code generation using BPF as a backend easier,
  as AluOp and JmpOp can be used directly as part of an IR
2022-10-16 11:36:11 -04:00
Evin Yulo
b346d48572 Simplify code in std.meta.isTag 2022-10-16 11:35:27 -04:00
Meghan
c37b40248c stage2: remove --verbose-mir from help menu
removed in 5f97652da8
2022-10-16 11:35:06 -04:00
Luuk de Gram
0aa23fe8b7 wasm: rename 'self' to more explanatory name
'Self' isn't a very good name to describe what it does.
This commit changes the type name into `CodeGen` and the parameter
to `func` as we're generating code for a function.
With this change, the backend's coding style is in line with the
self-hosted Wasm-linker.
2022-10-16 15:54:56 +02:00
Luuk de Gram
ff1cab037c wasm: re-use operands
When we return an operand directly as a result, we must call
`reuseOperand`. This commit ensures it's done for all currently-
implemented AIR instructions.
2022-10-16 15:54:17 +02:00
Luuk de Gram
273b8e20ca wasm: allow merging single branches
Rather than accepting a canonical branch and a target branch
we allow to directly merge a branch into the parent branch.
This is possible as there's no overlapping and we have infinite
registers to our availability. This makes merging a lot simpler.
2022-10-16 15:54:17 +02:00
Luuk de Gram
6fcd72355c wasm: correctly get the type of a local for free
When determining the type of a local (read: register), we would
previously subtract the stack locals also. However, this locals
are also within the same `locals` list, meaning the type of the
local we were retrieving was off by 2. This could create a validation
error when we re-use a local of a different type.
2022-10-16 15:54:17 +02:00
Luuk de Gram
e62bb1d689 wasm: implement branching
Upon a branch, we only allow locals to be freed which were allocated
within the same branch as where they die. This ensures that when two
or more branches target the same operand we do not try to free
it more than once. This does however not implement freeing the local
upon branch merging yet.
2022-10-16 15:54:16 +02:00
Luuk de Gram
576bb3f0a9 wasm: de -and increment reference count locals
When reusing an operand it increases the reference count, then when
an operand dies it will only decrease the reference count. When
this reaches 0, the local will be virtually freed, meaning it can be
re-used for a new local.
2022-10-16 15:54:16 +02:00
Luuk de Gram
b17c8c5424 wasm: reference count locals
By reference counting the locals, we can ensure that when we free
a local, no local will be reused while it still has references pointing
to it. This prevents misscompilations. The compiler will also panic if
we free a local more than we reference it, introducing extra safety to
ensure they match up.
2022-10-16 15:54:16 +02:00
Luuk de Gram
b9b20b14ea wasm: use liveness analysis for locals
This hooks reusal of locals into liveness analysis.
Meaning that when an operand dies, and is a local,
it will automatically be freed so it can be re-used
when a new local is required. The result of this, is
a lower allocation required for locals. Having less
locals means smaller binary size, as well as faster
compilation speed when loaded by the runtime.
2022-10-16 15:54:16 +02:00
Isaac Yonemoto
99c3578f69 adds isTag function to std.meta (#11895) 2022-10-15 14:32:05 -04:00
Andrew Kelley
c0d7f64036 Merge pull request #12448 from r00ster91/ultimateascii
std.ascii: rename functions and other improvements
2022-10-15 14:28:33 -04:00
Jacob Young
f9192adaba llvm: fix lowering of non-byte-aligned field pointers
* When a field starts at some bit offset within a byte you need to load
   starting from that byte and shift, not starting from the next byte,
   so a rounded-down divide is required here, not a rounded-up one.
 * Remove paragraph from doc that no longer relates to anything.

Closes #12363
2022-10-15 14:19:40 -04:00
Jacob Young
c7f9833238 Module: fix early exit conditions during compilation
* `--verbose-llvm-ir` should trigger analysis and codegen
 * `-femit-asm` etc should trigger codegen even with `-fno-emit-bin`

Closes #12588
2022-10-15 14:18:35 -04:00
Jacob Young
cb0e22db4e llvm: fix lowering of runtime refs to comptime-only decls
When we want a runtime pointer to a zero-bit value we use an undef
pointer, but what if we want a runtime pointer to a comptime-only value?
Normally, if `T` is a comptime-only type such as `*const comptime_int`,
then `*const T` would also be a comptime-only type, so anything
referencing a comptime-only value is usually also comptime-only, and
therefore not emitted to the executable.

However, what if instead we have a `*const anyopaque` pointing to a
comptime-only value?  Certainly, `*const anyopaque` is a runtime type,
and so we need some runtime value to store, even when it happens to be
pointing to a comptime-only value.  In this case we want to do the same
thing as we do when pointing to a zero-bit value, so we use
`hasRuntimeBits` to handle both cases instead of ignoring comptime.

Closes #12025
2022-10-15 14:17:25 -04:00
Andrew Kelley
feab1ebe1b Merge pull request #12878 from gwenzek/ptx
Update Nvptx backend for Zig 0.10
2022-10-15 13:53:04 -04:00
Andrew Kelley
c289794f0d nvptx: add TODO comment regarding abuse of llvm builtins 2022-10-15 10:50:02 -07:00
Guillaume Wenzek
24c749473a implement os.abort and panic for cuda 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
419855c475 fix test 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
ac1f17f63f disable sema.addConstant 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
b425d88737 re-enable nvptx tests 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
577f0aa54b addrSpaceCastIsValid nvptx 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
aad983cf40 sanitize qualified name for nvptx backend 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
92a857b76c debug 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
004fca2c64 restore comp when leaving flushModule 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
b3dc80a1e3 disable debug info for ptx<7.5 2022-10-15 10:39:19 -07:00
Guillaume Wenzek
85c6b0f0bc allow ptx kernel export 2022-10-15 10:39:19 -07:00
Andrew Kelley
65f860bef7 Merge pull request #12879 from Snektron/amdgpu-improvements
Amdgpu improvements
2022-10-15 13:36:43 -04:00
Andrew Kelley
66d6183001 Merge branch 'amdgpu-improvements' of https://github.com/Snektron/zig into Snektron-amdgpu-improvements 2022-10-15 10:36:10 -07:00
Andrew Kelley
1087e67762 Merge pull request #13108 from topolarity/llvm-lib-dir
build.zig: Forward LLVM lib/include dirs from CMake
2022-10-15 12:36:38 -04:00
Andrew Kelley
16cc65242f Merge pull request #12918 from jacobly0/math-cast-comptime-int
std.math: fix behavior relating to comptime_int arguments
2022-10-15 12:11:55 -04:00
Jacob Young
400319872b llvm: fix bug lowering aggregate_init with a byref sentinel
Closes #12972
2022-10-15 11:12:04 -04:00
xEgoist
ae39e7867d Added os check for std.fs.setAsCwd() to work with windows
Due to the unavailability of fchdir in Windows, a call for setting the
CWD needs to either call chdir with the path string or call
SetCurrentDirectory.
Either way, since we are dealing with a Handle in Windows, a call for
GetFinalPathNameByHandle is necessary for getting the file path first.
2022-10-15 11:05:15 -04:00
Andrew Kelley
b4e3424594 Merge pull request #13100 from topolarity/powerpc64le
stage2: Fix softfloat support for PPC64(LE)
2022-10-15 10:05:00 -04:00
Luuk de Gram
74108bb9c0 test/link: fix Wasm archive test
As memcpy is now part of compiler-rt, we no longer expect
any imports in the binary.
2022-10-15 07:02:38 -07:00
Luuk de Gram
f5edaa96dd compiler_rt: Move mem implementations from c.zig
This moves functions that LLVM generates calls to,
to the compiler_rt implementation itself, rather than c.zig.
This is a prerequisite for native backends to link with compiler-rt.
This also allows native backends to generate calls to `memcpy` and the like.
2022-10-15 07:02:38 -07:00
Cody Tapscott
a168893e00 stage1: Fix ppcle long double size
Resolves #13110
2022-10-14 13:35:10 -07:00
Ryan Liptak
8bb2e96ac3 std.os.windows: Change HKEY to *opaque {}
The definition of HKEY__ as a struct with an unused int field is only the case in the Windows headers when `STRICT` is defined. From https://learn.microsoft.com/en-us/windows/win32/winprog/enabling-strict:

> When STRICT is defined, data type definitions change as follows:
>
> -  Specific handle types are defined to be mutually exclusive; for example, you will not be able to pass an HWND where an HDC type argument is required. Without STRICT, all handles are defined as HANDLE, so the compiler does not prevent you from using one type of handle where another type is expected.

Zig's `opaque {}` already gives this benefit to us, so the usage of a struct with an unused field is unnecessary, and it was causing HKEY to have an alignment of 4, which is a problem because there are HKEY constants like HKEY_LOCAL_MACHINE (0x80000002) that are not 4-byte aligned. Without this change, the compiler would not allow something like HKEY_LOCAL_MACHINE to be defined since it enforces pointer alignment.
2022-10-14 15:23:13 -04:00
Evan Haas
e4e1c21e1f i386 ABI: Fix some sizes and alignments
This makes the following changes for i386:

long long and unsigned long long have 4 byte alignment on non-Windows

f64 (double) has 4-byte alignment on non-Windows

long double is 80 bits and has 4 byte alignment on mingw

long double on android is 64 bits, not 80: https://www.uclibc.org/docs/psABI-i386.pdf

Fixes #12453
Fixes #12987
2022-10-14 15:22:00 -04:00
Ryan Liptak
c8da03a0e1 Fix compile error in Dir.deleteTreeMinStackSize and add test
Follow up to #13073
2022-10-14 14:48:23 -04:00
Jacob Young
9b45dc1608 stage2: fix emitting asm and bin at the same time
This logic is copied from stage1.

Fixes #12800
2022-10-14 14:46:50 -04:00
Andrew Kelley
cb257d59f9 Merge pull request #13148 from r00ster91/progressfollowup
fix(std.Progress): some follow-ups
2022-10-14 14:43:34 -04:00
r00ster91
ab4e696e1f fix: handle larger window sizes more robustly
We should now be able to handle virtually any window size gracefully.
2022-10-14 09:38:09 +02:00
Cody Tapscott
34863224c3 Re-enable mulAdd f128 tests on i386-linux 2022-10-13 12:53:30 -07:00
Cody Tapscott
1e278131e3 Re-enable @mulAdd f128 tests on aarch64-darwin
Closes #9900
2022-10-13 12:53:29 -07:00
Cody Tapscott
f035437b5d Re-enable Vector f16 tests on Windows
Closes #4952
2022-10-13 12:53:20 -07:00
Cody Tapscott
b8c587eb40 tests: Enable PPC64LE as a test target 2022-10-13 12:53:20 -07:00
Cody Tapscott
46fb730712 stage2: Use softfloat for f16 on MIPS targets 2022-10-13 12:53:20 -07:00
Cody Tapscott
db9058e41a Disable llvm.prefetch for PowerPC
This instruction is not supported on this backend, so should
just be a noop.
2022-10-13 12:53:20 -07:00
Cody Tapscott
6e6ae8886e stage1: Add softfloat support for @reduce 2022-10-13 12:53:20 -07:00
Cody Tapscott
f0d12dd82b stage2: Add softfloat support for @reduce 2022-10-13 12:53:20 -07:00
Cody Tapscott
b992ea1b07 stage1: Rely on softfloat for f16 on non-arm targets 2022-10-13 12:53:20 -07:00
Cody Tapscott
37c6fcafa2 stage2 LLVM: Correct long double for WASM
Also, f16 is not supported on this backend.
2022-10-13 12:53:20 -07:00
Cody Tapscott
0d533433e2 compiler_rt: Add missing f16 functions
This change also exposes some of the existing functions under both the
PPC-style names symbols and the compiler-rt-style names, since Zig
currently lowers softfloat calls to the latter.
2022-10-13 12:53:20 -07:00
Cody Tapscott
aedafb20cf stage2: Fix softfloat support for PPC64(LE)
Stage 2's softfloat support still had a couple of gaps, which were
preventing us from lowering `f16` on this target. With any luck,
this is enough to get PPC64 working as a Tier 2 target again.
2022-10-13 12:53:20 -07:00
Cody Tapscott
83e2d3fb37 stage1: Skip new tests that never passed in stage1
This gets the behavior tests passing for stage1 again.
2022-10-13 12:53:20 -07:00
r00ster91
4ae8717fb3 test: uncomment print
For general output testing, this shouldn't always be required and is only sometimes useful.
2022-10-13 16:06:51 +02:00
r00ster91
cbe6872518 refactor: max_width calculation
I think this may be helpful in the future when we might want to calculate this again at some other point.
It also makes it more clear that the other two functions below it are only required for this calculation.
2022-10-13 16:06:51 +02:00
r00ster91
e484e75969 docs: add notes 2022-10-13 16:06:46 +02:00
Jacob Young
f5f28e0d2c io_uring: ignore SOCK_NONEMPTY for reproducible tests
Fixes #12670
2022-10-13 14:58:06 +02:00
Ali Chraghi
0eb3b8fa44 std.SegmentedList: fix compilation error 2022-10-13 13:57:20 +02:00
Bill Nagel
ea23217751 enable event loop for ios, tvos, and watchos 2022-10-13 13:33:45 +02:00
Ali Chraghi
fb366f3cd4 std.c: fix incorrect return types
Closes #12964
2022-10-13 13:21:19 +02:00
cod1r
6af0eeb58d adding static and dynamic ZigEquivalent enums so that we can branch to set link_mode properly when we iterate over the clang arguments. also replaced dynamic flag in clang_options_data.zig with proper definition similarly to static. 2022-10-13 13:12:17 +02:00
kkHAIKE
d987bf859e Sema: add float128IntPartToBigInt to fix compare comptime float with int 2022-10-13 13:11:13 +02:00
Marijn Stollenga
3a9344d8fc Return invalid argument in sendto instead of unreachable, since this can happen with user-side errors 2022-10-13 13:10:29 +02:00
zooster
cd3d8f3a4e std.Progress: fix inaccurate line truncation and use optimal max terminal width (#12079)
* prep: output_buffer -> output_buffer_slice

* fix: truncate lines accurately

Currently, the code assumes a terminal width of 100.

If we look at what's printed for the last test:
```
Test [1/1] test "basic functionality"... [101/100] this is a really long name designed to activate the truncation code. let's fi...
```
No, it does not really work because the relevant part here is `"[101/100] this is a really long name designed to activate the truncation code. let's fi... "`,
which is 90 characters, but we expect 100 because that's the width that is assumed.
The reason is that it also measures **unprintable characters** (escape sequences) at least non-Windows systems.
With this commit the output is now:
```
Test [1/1] test "basic functionality"... [101/100] this is a really long name designed to activate the truncation code. let's find out if...
```
Of which `"[101/100] this is a really long name designed to activate the truncation code. let's find out if... "`
is the actual output of *our* `std.Progress` (remember that `zig test` has an `std.Progress` and our test itself does).
The length of that string is 100. Now the length is consistent with Windows where we don't use escape sequences. This issue was only present on non-Windows systems.

* feat: decide optimal maximum width

This is done by 1. getting the current terminal width and 2. subtracting that by the current cursor column. This accounts for previous output from someone else.

* test: add more tests

They make it easier to see how the progress line is printed in different cases.

* style: fix typo and improve docs

It also expands an acronym used as a variable name. It confused me.

* cleanup: import std.time

* test: add test

* fix: limit termios usage to Linux only for now

* fix: missing cast on Windows

* test: try to debug failure

* fix: fix off-by-one and disable tests

* docs: make comment clearer

* fix: more durability

* fix(getTerminalWidth): change order
2022-10-13 06:39:24 -04:00
Jacob Young
02d7292a8c build.zig: Forward LLVM lib/include dirs from CMake
Previously, you might obtain `-lLLVM-15` from the CMake configuration,
but we might not be able to locate the library if it's not in your
system library path.
2022-10-12 18:11:46 -04:00
Cody Tapscott
50a6dc8496 build.zig: Parse CMAKE_PREFIX_PATH with multiple entries
CMAKE_PREFIX_PATH is a semicolon separated list.
2022-10-12 12:01:44 -07:00
Robin Voetter
9ff60e356e typo 2022-10-12 20:38:43 +02:00
Robin Voetter
e90a42a808 stage2: improve globals with address spaces a little 2022-10-12 20:36:15 +02:00
Robin Voetter
ad74773959 make addrSpaceCast work with optionals; forbid ptrCast'ing address spaces 2022-10-12 20:36:15 +02:00
Robin Voetter
aa20295d24 compiler_rt: apply protty suggestions 2022-10-12 20:36:15 +02:00
Robin Voetter
86f40d3ff6 zig_libc: do not call abort() on amdgpu 2022-10-12 20:36:15 +02:00
Robin Voetter
9006cd9d09 compiler_rt: cmpxchg-based atomic fetch/exchange for small types
Some architectures (AMDGPU) do not support atomic exchange/fetch for
small types (for AMDGPU: 8- and 16-bit ints). For these types
atomic fetch and atomic exchange needs to be implemeted using atomic
operations on a wider type using cmpxchg.
2022-10-12 20:36:14 +02:00
Robin Voetter
8894d1c45e stage2: f128 improvements for targets that do not support it 2022-10-12 20:36:14 +02:00
Robin Voetter
76ad9cb10e backport @addrSpaceCast to stage 1 2022-10-12 20:36:14 +02:00
Robin Voetter
fb9a7dad17 add @addrSpaceCast to langref 2022-10-12 20:36:14 +02:00
Robin Voetter
9f14681473 stage2: check address space cast validity 2022-10-12 20:36:14 +02:00
Robin Voetter
5d429b03e3 stage2: add @addrSpaceCast builtin 2022-10-12 20:36:12 +02:00
Robin Voetter
5f3b91437f stage2: improve addrspace handling
This commit changes the way Zig is intended to deal with variable
declaration for exotic targets. Where previously the idea was to
enfore local/global variables to be placed into their respective
address spaces, depending on the target, this is now fixed to the
generic address space.

To facilitate this for targets where local variables _must_ be
generated into a specific address space (ex. amdgcn where locals
must be generated into the private address space), the variable
allocations (alloca) are generated into the right address space
and then addrspace-casted back to the generic address space. While this
could be less efficient in theory, LLVM will hopefull deal with figuring
out the actual correct address space for a pointer for us. HIP seems to
do the same thing in this regard.

Global variables are handled in a similar way.
2022-10-12 20:34:42 +02:00
Robin Voetter
3392de87dc allow global/local/shared address spaces on amdgcn 2022-10-12 20:34:41 +02:00
Robin Voetter
5859d8458f big int: make Mutable.normalize const 2022-10-12 20:34:41 +02:00
Robin Voetter
d638b2e29f stage 2: grammar 2022-10-12 20:34:41 +02:00
Robin Voetter
6b69dcfdd2 amdgpu: add AmdgpuKernel calling convention 2022-10-12 20:34:41 +02:00
Robin Voetter
5dd3d17c20 amdgpu: add amdhsa/amdpal ctype abi sizes 2022-10-12 20:34:40 +02:00
Michael Dusan
0b47e69b7c improve header searchlist handling in build, main
build.zig:
- use "-I" instead of "-isystem" for `b.addSearchPrefix()`

main.zig:
- silently ignore superfluous search dirs
- warn when a dir is added to multiple searchlists
- consolidate "expected paramter after {s}" fatal error messages
- rename command-line switch `-dirafter` → `-idirafter`

closes #12888
2022-10-12 13:50:25 -04:00
Andrew Kelley
c23b3e6fd9 Merge pull request #13073 from squeek502/fs-delete-tree-2
`fs.Dir.deleteTree`: Optimize for non-deeply-nested directories
2022-10-12 13:37:06 -04:00
Veikka Tuominen
260b0ff7c5 Sema: add reference trace before checking for cached value
Closes #13143
2022-10-12 18:57:31 +03:00
Veikka Tuominen
3a8777a8bb fix hyphenation in test case
Follow up to 51d9db8569
2022-10-12 16:10:57 +03:00
Jacob Young
e78d7704a4 math.big.int: document the purpose of limb_len in scalar methods
Ideally this duplicated code could be factored out into a function, but
there doesn't seem to be any way in the Zig type system to represent an
argument to a function called at comptime that is only needed if it is
comptime-known.  Instead, we document what is going on in an adjacent
comment in case it gets copy-pasted into new methods in the future.
2022-10-12 08:56:13 -04:00
Jacob Young
38ee512a25 math.big.int: add calcLimbLen doc comment note
When trying to allocate memory for functions like `Managed.init` and
`Managed.set` on the stack, a comptime-known allocation size is desired.
The doc comments for these functions indicate that `calcLimbLen` can be
used to determine how many limbs to allocate, but if `value` is not
comptime-known, then neither is `calcLimbLen(value)`.  However, an upper
bound on the allocation size is still computable at comptime in this
case, so this note documents an expression that can be used, rather than
trying to add it to every doc comment that mentions `calcLimbLen`.
2022-10-12 08:18:47 -04:00
jacobly0
562ac8be48 codegen: add support for lowering .field_ptr on a slice
Closes #13068
2022-10-12 12:40:59 +03:00
Andrew Kelley
b47e54ed3f CI: windows: update tarball
Needed due to the --strip/-fstrip breaking changes.
2022-10-12 02:34:26 -07:00
kcbanner
28b7fa1d13 msvc: fixup compiler arg generation, as /O2 is incompatible with /RTC1 2022-10-12 05:31:48 -04:00
Andrew Kelley
d08191e146 Merge pull request #12897 from r00ster91/uefi
std.os.uefi: fix some mistakes
2022-10-12 05:28:13 -04:00
Andrew Kelley
7ce1ee1bce Merge pull request #13081 from r00ster91/docs
fix(text): hyphenation and other fixes
2022-10-12 05:26:11 -04:00
Ryan Liptak
bec40a89c2 Windows: Fix stage1.zig's main failing to receive non-ASCII args
Closes #10506
2022-10-12 05:21:48 -04:00
Luuk de Gram
1f196b9e2f stage2: implement exporting using field access (#13136)
This implements `@export(a.b, .{..});` in semantic analysis,
allowing users to directly export a variable from a namespace.

* add test case for exporting using field access
2022-10-12 04:38:07 -04:00
Gaëtan
62258555b6 Make CompressorOptions public 2022-10-12 04:04:43 -04:00
Andrew Kelley
a3c9c154b4 Merge pull request #13089 from ziglang/update-mingw 2022-10-12 03:17:52 -04:00
Jacob Young
2fe5bdb9ed big.int: rewrite confusing code in an equivalent but less confusing way 2022-10-11 19:57:13 -04:00
Jacob Young
5c49341f09 big.int: add support for non-comptime scalars 2022-10-11 19:51:03 -04:00
Jacob Young
7a89eebfc6 std.math: add support to cast for a comptime_int argument
This allows converting a comptime_int to an optional integer type, which
either behaves the same as an implicit cast or produces null if the
argument is outside the range of the destination type.
2022-10-11 19:51:03 -04:00
Cody Tapscott
e6ebdcb82e stage2 LLVM: Use a packed aggregate for union payload init
Without the packed qualifier, the type layout that we use to
initialize doesn't match the correct layout of the underlying
storage, causing corrupted data and past-the-end writes.
2022-10-11 15:42:01 -04:00
Luuk de Gram
8635c18e40 test/link: don't strip producers section for wasm
When testing the Wasm linker for the producers section
we do not ever want to strip the binary as this will remove
the producers section in release-small.

This fixes the CI errors by d086b371f0
2022-10-11 21:27:09 +02:00
GethDW
01b9fa2c25 std: fix memory leak on OutOfMemory error in math.big.int and math.big.rationa 2022-10-11 20:12:03 +03:00
Veikka Tuominen
a72b584c76 Merge pull request #13126 from tau-dev/master
translate-c: Fix function pointers, add cast to subscripts in macros
2022-10-11 19:04:44 +02:00
Ali Chraghi
d086b371f0 Compilation: strip debug info from ReleaseSmall by default 2022-10-11 17:51:25 +02:00
mllken
42a3b60c33 io_uring: allow for nullable arguments 2022-10-11 17:49:30 +02:00
r00ster91
697e22caa4 fix: resolve data race in std.Progress.maybeRefresh()
It seems we can simply lock the update mutex a little earlier.
2022-10-11 17:46:39 +02:00
Eric Milliken
0b7b4b7e97 std: add linux support for packet sockaddr 2022-10-11 18:46:24 +03:00
Andrew Kelley
c3d67c5c4e Merge pull request #13117 from topolarity/compiler-rt-cmul
compiler-rt: Implement complex multiply/division
2022-10-11 05:51:47 -04:00
Andrew Kelley
b020d83265 mingw-w64: pass -D__USE_MINGW_ANSI_STDIO=0 for crt files
Thanks to Martin Storsjö for explaining this to me on IRC:

__USE_MINGW_ANSI_STDIO redirects stdio functions towards mingw-w64
reimplementations of them (since msvcrt.dll lacks lots of things). For
x86 with "long double", this is also needed to get long doubles
formatted properly. It's enabled by default by headers when building in
C99 mode, unless you're targeting UCRT. The headers normally enable this
automatically - or you can request it enabled with
-D__USE_MINGW_ANSI_STDIO=1. However, the mingw-w64-crt files are
expected to be built with this explicitly turned off. Since there's a
half dozen various ways of configuring the CRT and various features, the
mingw-w64-crt files specifically need to be built in a very hardcoded
configuration, which is different from how end user source files are
compiled.

This commit removes a patch that we were carrying previously.

See #7356
2022-10-11 01:59:39 -07:00
Andrew Kelley
3108b8010e CI: windows: update tarball 2022-10-11 01:51:49 -07:00
Andrew Kelley
85f4e579d8 stage2: update mingw-w64 build logic to v10.0.0 2022-10-11 01:05:42 -07:00
Andrew Kelley
e4ed8c3f37 update mingw-w64 crt files to v10.0.0 2022-10-11 01:05:42 -07:00
Andrew Kelley
e52931e50f update mingw-w64 headers to v10.0.0 2022-10-11 01:05:42 -07:00
Tau
85b105d4f9 Update translate-c tests 2022-10-11 00:43:53 +02:00
Veikka Tuominen
b316c25cc6 Merge pull request #13075 from Vexu/stage2-fixes
Stage2 misc fixes
2022-10-10 23:27:17 +02:00
Veikka Tuominen
1f8ae10a38 Merge pull request #13091 from Vexu/small-proposals
Implement some small proposals
2022-10-10 23:26:56 +02:00
Rekai Nyangadzayi Musuka
dacdc95ea2 std/math.zig: use previous rotate code with non-power-of-two integers 2022-10-11 00:22:35 +03:00
Tau
770a1aa967 translate-c: fix #5305 2022-10-10 22:50:22 +02:00
Tau
6be16eeae9 translate-c: fix the remaining function pointer issues 2022-10-10 22:30:33 +02:00
Tau
2ca503ec05 translate-c: Fix #12263 2022-10-10 22:29:56 +02:00
Eric Joldasov
02fff6fd01 Fix building with Clang 16
Related:
https://archives.gentoo.org/gentoo-dev/message/dd9f2d3082b8b6f8dfbccb0639e6e240
2022-10-10 02:31:09 -04:00
Cody Tapscott
a06185f362 C ABI: Add tests for complex float/double support
These tests will be failing on many platforms until #8465 is resolved.

Luckily, the particular function signature used for __divXc3 and __mulXc3
seems to be OK on x86-64.
2022-10-09 23:24:29 -07:00
Cody Tapscott
879fb0c57c Manually construct denormal constants in tests
Constructing these at runtime can cause them to be flushed to zero,
which was triggering a CI failure for Windows.
2022-10-09 20:29:30 -07:00
jcalabro
c8ca47dae7 add [src] links to function decls in autodocs 2022-10-09 20:47:28 -04:00
Cody Tapscott
c9ecf7b920 compiler_rt: Fix extendf_f80 bug
Zig should probably perform this cast automatically (w/ safety).
Integer shifts are a real pain otherwise.

Adds some test coverage, too.
2022-10-09 13:42:39 -07:00
Cody Tapscott
05915b85dd compiler-rt: Implement mulXc3 and divXc3 functions
These are the standard complex multiplication/division functions
required by the C standard (Annex G).

Don't get me started on the standard's handling of complex-infinity...
2022-10-09 11:09:41 -07:00
Cody Tapscott
eac1e613be compiler_rt: Re-implement ldexp/ilogb using bit-ops
This re-write was needed to fix deficiencies in the existing ldexp,
which was failing to compute correct results for both f16 and f80.

It would be nice to add a fast multiplication-based fallback in the
future for targets that have a hardware FPU, but this implementation
should be much faster than the existing for targets without one.
2022-10-09 11:09:02 -07:00
Cody Tapscott
350a88ddf4 build.zig: Forward LLVM lib/include dirs from CMake
Previously, you might obtain `-lLLVM-15` from the CMake configuration,
but we might not be able to locate the library if it's not in your
system library path.
2022-10-08 13:18:14 -07:00
Luuk de Gram
7f508480f4 wasm-linker: convert relocation addend to i32
Addends in relocations are signed integers as theoretically it could
be a negative number. As Atom's offsets are relative to their parent
section, the relocation value should still result in a postive number.
For this reason, the final result is stored as an unsigned integer.

Also, rather than using `null` for relocations that do not support
addends. We set the value to 0 for those that do not support addends,
and have to call `addendIsPresent` to determine if an addend exists
or not. This means each Relocation costs 4 bytes less than before,
saving memory while linking.
2022-10-08 17:23:13 +02:00
Veikka Tuominen
3ccd4907fb Sema: add error for capturing a runtime value outside of function scope
Closes #13104
2022-10-08 16:58:54 +03:00
Veikka Tuominen
b5c0a797a7 Sema: inline switch capture needs to be set when switch operand is comptime known 2022-10-08 16:58:52 +03:00
Veikka Tuominen
1500b9ddc3 Sema: restore sema.src after inline call
Closes #13099
2022-10-08 16:58:26 +03:00
Luuk de Gram
fa9327ac05 Merge pull request #13054 from Luukdegram/wasm-producer
wasm-linker: generate 'producers' section
2022-10-08 15:36:15 +02:00
Luuk de Gram
fda75f53fa test/link: Add linker test for producers section
This also turns off non-debug modes for the bss linker tests for
Wasm. This is done as it's not required to guarantee to zero out
the bss section for non-debug modes.
2022-10-08 09:43:40 +02:00
Luuk de Gram
3beef5a94f CheckObjectStep: parsing and dumping producers 2022-10-08 09:43:40 +02:00
Luuk de Gram
43b55ea9f4 wasm-linker: generate 'producers' section
The `producers` section contains meta data of the binary and/or
object file. It *can* contain the source language, the tool it
was processed by, and/or the SDK that was used to produce the file.

For now, we always set the language and processed-by fields to Zig.
In the future we will parse linked object files to detect their
producers sections and append (if different) their language, SDK
and processed-by fields.
2022-10-08 09:43:35 +02:00
r00ster91
47e72132e2 fix: wrong amount of arguments passed to function
I don't know why that one argument was discarded. Is there a reason? It failed to compile.
2022-10-07 19:33:29 +02:00
r00ster91
a56a51e48f fix: wrong return type for _poll
See page 1055 of <https://uefi.org/sites/default/files/resources/UEFI_Spec_2_3_1.pdf>.
2022-10-07 19:33:29 +02:00
r00ster91
4440391d81 fix: wrap function pointers in std.meta.FnPtr 2022-10-07 19:33:29 +02:00
Veikka Tuominen
4a6cc1c602 Sema: allow equality comparisons between error unions and error sets
Closes #1302
2022-10-07 11:04:02 +03:00
Veikka Tuominen
2315e1b410 safety: add safety check for hitting else branch on a corrupt enum value
Closes #7053
2022-10-07 11:04:02 +03:00
Veikka Tuominen
29ae6515f3 AstGen: use 'shadows' instead of 'redeclaration' when names are in different scopes
Closes #8532
2022-10-07 11:04:02 +03:00
Ali Chraghi
11dce78944 std.http: fix typo 2022-10-06 21:22:20 +03:00
Ali Chraghi
6672921e32 Sema: fix error location when casting pointer to slice
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-10-06 21:18:01 +03:00
Veikka Tuominen
dffce98045 Sema: disallow using stage1 fn ptrs in extern contexts
Closes #13022
2022-10-06 20:09:45 +03:00
Veikka Tuominen
446deb31a8 Sema: validate bitSizeOf operand type
Closes #13080
2022-10-06 20:09:45 +03:00
Veikka Tuominen
775e055b59 Sema: generic function instantiation inherits parent's branch quota
Closes #12624
2022-10-06 20:09:45 +03:00
Veikka Tuominen
94039d66ed Sema: disallow fieldParentPtr and offsetOf on comptime fields
Comptime fields are tied to the type and behave more like declarations
so these operations cannot return anything useful for them.
2022-10-06 20:09:45 +03:00
Veikka Tuominen
cc89908e82 Sema: do not emit is(_non)_null for invalid types
Closes  #13024
2022-10-06 15:39:06 +03:00
Veikka Tuominen
0b1dd845d9 stage2: add error for non-void error union payload being ignored
See https://github.com/ziglang/zig/pull/6060#discussion_r471032912
2022-10-06 15:39:06 +03:00
Veikka Tuominen
b626977f45 Sema: create sub block for inline loops
Closes #13038
2022-10-06 15:39:06 +03:00
Ryan Liptak
1468eb12f3 std.fs.deleteTree: Unify how the initial sub_path is treated between deleteTree/deleteTreeMinStackSize 2022-10-05 20:08:53 -07:00
Ryan Liptak
063c5f43e9 fs.Dir.deleteTree: Fix FileBusy errors on Windows
Windows requires the directory handle to be closed before attempting to delete the directory, so now we do that and then re-open it if we need to retry (from getting DirNotEmpty when trying to delete).
2022-10-05 19:58:36 -07:00
Ryan Liptak
db0829c15a fs.Dir.deleteTree: Fix some handling of NotDir error in deleteFile calls
We don't control sub_path so it may contain directory components; therefore, NotDir is a potential error when acting on sub_path.
2022-10-05 19:51:43 -07:00
Ryan Liptak
34f180901e fs: deleteTreeFallback -> deleteTreeMinStackSize and make it pub 2022-10-05 16:15:25 -07:00
Ryan Liptak
39f192d54e fs: Reduce IterableDir.Iterator buf size to 1024
This was sized large so that `getdents` (and other platforms' equivalents) could provide large amounts of entries per syscall, but some benchmarking seems to indicate that the larger 8192 sizing doesn't actually lead to performance gains outside of edge cases like extremely large amounts of entries within a single directory (e.g. 25,000 files in one directory), and even then the gains are minimal ('./walk-8192 dir-with-tons-of-entries' ran 1.02 ± 0.34 times faster than './walk-1024 dir-with-tons-of-entries').

Note: Sizes 1024 and 2048 had similar performance characteristics, so the smaller of the two was chosen.
2022-10-05 16:05:02 -07:00
r00ster91
8e2aaf6aed fix(text): hyphenate "runtime" adjectives 2022-10-05 21:33:42 +02:00
r00ster91
51d9db8569 fix(text): hyphenate "comptime" adjectives 2022-10-05 21:19:30 +02:00
r00ster91
654e0b6679 fix(text): hyphenation and other fixes 2022-10-05 21:19:10 +02:00
Veikka Tuominen
ba4aa12098 Sema: use correct value when @ptrCast operand is comptime known
Closes #13034
2022-10-05 17:26:29 +03:00
Veikka Tuominen
40578656e8 Zir: handle ranges in getMultiProng
Closes #12890
2022-10-05 17:26:29 +03:00
Veikka Tuominen
c0350cf87e Sema: avoid passing undefined as reason to failWithNeededComptime
Closes #13046
2022-10-05 17:26:29 +03:00
Andrew Kelley
3234e8de3a Merge pull request #13071 from ziglang/resolve-cache-files
stage2: resolve file before putting them into cache
2022-10-05 09:41:03 -04:00
Veikka Tuominen
e563af1329 Merge pull request #12745 from Techcable/translate-c/packed-struct-implies-align1
translate-c: Translate clang packed struct C into Zig extern struct with align(1)
2022-10-05 15:35:11 +03:00
Ryan Liptak
274d19575e fs: Optimize Dir.deleteTree for non-deeply-nested directories
`deleteTree` now uses a stack-allocated stack for the first 16 nested directories, and then falls back to the previous implementation (which only keeps 1 directory open at a time) when it runs out of room in its stack. This allows the function to perform as well as a recursive implementation for most use-cases without needing allocation or introducing the possibility of stack overflow.
2022-10-05 03:27:25 -07:00
Ryan Liptak
e9889cd25f fs: Add IterableDir.Iterator.reset 2022-10-05 03:26:13 -07:00
Ryan Liptak
8cec8f6ddd fs.Dir.deleteTree: Reduce the number of failing deleteFile calls
There are two parts to this:

1. The deleteFile call on the sub_path has been moved outside the loop, since if the first call fails with `IsDir` then it's very likely that all the subsequent calls will do the same. Instead, if the `openIterableDir` call ever hits `NotDir` after the `deleteFile` hit `IsDir`, then we assume that the tree was deleted at some point and can consider the deleteTree a success.

2. Inside the `dir_it.next()` loop, we look at entry.kind and only try doing the relevant (deleteFile/openIterableDir) operation, but always fall back to the other if we get the relevant error (NotDir/IsDir).
2022-10-05 03:26:13 -07:00
Andrew Kelley
f374ea2cd1 build: add -Dsanitize-thread option 2022-10-05 03:22:10 -07:00
Ryan Liptak
5059384b57 Introduce IterableDir.iterateAssumeFirstIteration
This allows for avoiding an unnecessary lseek (or equivalent) call in places where it can be known that the fd has not had its cursor modified yet.
2022-10-05 02:20:13 -07:00
Ryan Liptak
6ac0d2d9d6 Fix all std lib tests being run for any file within the std package
Before this commit:

```
$ zig test lib/std/fs/test.zig --main-pkg-path lib/std --zig-lib-dir lib
2170 passed; 37 skipped; 0 failed.
```

After this commit:

```
$ zig test lib/std/fs/test.zig --main-pkg-path lib/std --zig-lib-dir lib
All 45 tests passed.
```

This matches stage1 behavior:

```
$ zig test -fstage1 lib/std/fs/test.zig --main-pkg-path lib/std --zig-lib-dir lib
All 45 tests passed.
```

All tests are still run if `zig test` is run directly on `lib/std/std.zig`:

```
$ zig test lib/std/std.zig --main-pkg-path lib/std --zig-lib-dir lib
2170 passed; 37 skipped; 0 failed.
```

`zig build test-std` is unaffected by this change.

Closes #12926
2022-10-05 04:21:16 -04:00
Andrew Kelley
6152f043c0 stage2: resolve file before putting them into cache
This was an accidental misuse of the Cache API which intends to call
resolve on all file paths going into it. This one callsite was failing
to do that; fixed now.

Fixes relative file paths from making it into the global cache manifest.

See #13050
2022-10-05 00:42:08 -07:00
Andrew Kelley
f4c6e5d94e CLI: better error message for bad input path
Previously it just said `error: NotDir` but now it says
`error: unable to open '<path>': NotDir`.
2022-10-05 00:41:17 -07:00
Andrew Kelley
ff534d2267 Merge pull request #12979 from Vexu/inline-switch
Implement inline switch cases
2022-10-03 23:43:09 -04:00
GethDW
9d5462dcb5 std: fix memory leak in ArrayHashMap (#13001) 2022-10-03 22:57:53 -04:00
Luuk de Gram
8bbb022500 std: WASI - update to latest snapshot preview 1
This implements the new addition to the API: `sock_accept`.
Reference commit of WASI spec:
0ba0c5e2e37625ca5a6d3e4255a998dfaa3efc52

For full details:
0ba0c5e2e3

For entire spec at this commit:
0ba0c5e2e3/phases/snapshot/docs.md
2022-10-03 22:48:57 -04:00
Jacob Young
0d92c2ca5b stage2: add support for assembly debug info
Pulls out the -g cc flag addition to the common area so that it is also
applied to assembly files.
2022-10-03 22:48:26 -04:00
Andrew Kelley
54eb0f2daa Merge pull request #13032 from jacobly0/br-on-undef-val
stage2: fix branches on undefined values
2022-10-03 22:46:22 -04:00
zooster
8eb96c32e3 docs(langref): fix outdated example 2022-10-03 22:41:48 -04:00
Jacob Young
38bd2bbcf2 stage2: fix C ABI for bool
This fixes a miscompilation compiling debug zig with release stage3 zig.
2022-10-03 22:41:07 -04:00
Jacob Young
9cad44770a test/standalone: remove unneeded FnPtr
The behavior of this test is not affected by an extra level of
indirection.
2022-10-03 10:28:30 -04:00
Jacob Young
9d8cdb855b Sema: fix function paramater count mismatch note
expected type 'fn() void', found 'fn(i32) void'
function with 0 parameters cannot cast into a function with 0 parameters
  =>
expected type 'fn() void', found 'fn(i32) void'
function with 1 parameters cannot cast into a function with 0 parameters
2022-10-03 13:06:49 +03:00
zooster
db5562deb0 std.os.windows: fix HANDLER_ROUTINE callconv 2022-10-03 13:05:38 +03:00
Julian
32d755beb8 Sema: require reified packed struct fields to have zero alignment 2022-10-03 13:05:12 +03:00
alex
2eb0909206 std.ChildProcess: correct fn getUserInfo pkg in setUserName
17b0166e moved getUserInfo from std.os to std.process
but ChildProcess.setUserName never updated the pkg name.
2022-10-03 12:59:47 +03:00
Techcable
a560af9656 translate-c: Add tests for packed unions
Was missing test coverage before this (although it was suppored)
2022-10-01 15:22:26 -07:00
Techcable
5b689d389f translate-c: packed struct implies align(1) on every field
Superceeds PR #12735 (now supporting all packed structs in GNU C)
Fixes issue #12733

This stops translating C packed struct as a Zig packed struct.
Instead use a regular `extern struct` with `align(1)`.

This is because (as @Vexu explained) Zig packed structs are really just integers (not structs).

Alignment issue is more complicated. I think @ifreund was the
first to notice it in his comment on PR #12735

Justification of my interpretion of the C(lang) behavior
comes from a careful reading of the GCC docs for type & variable attributes:

(clang emulates gnu's packed attribute here)

The final line of the documentation for __attribute__ ((aligned)) [on types] says:

> When used on a struct, or struct member, *the aligned attribute can only increase the alignment*; in order to decrease it, the packed attribute must be specified as well.

This implies that GCC uses the `packed` attribute for alignment purposes
in addition to eliminating padding.

The documentation for __attribute__((packed)) [on types], states:

> This attribute, attached to a struct, union, or C++ class type definition, specifies that each of its members (other than zero-width bit-fields) is placed to minimize the memory required. **This is equivalent to specifying the packed attribute on each of the members**.

The key is resolving this indirection, and looking at the documentation
for __attribute__((packed)) [on fields (wierdly under "variables" section)]:

> The packed attribute specifies that a **structure member should have the smallest possible alignment** — one bit for a bit-field and one byte otherwise, unless a larger value is specified with the aligned attribute. The attribute does not apply to non-member objects.

Furthermore, alignment is the only effect of the packed attribute mentioned in the GCC docs (for "common" architecture).
Based on this, it seems safe to completely substitute C 'packed' with Zig 'align(1)'.
Target-specific or undocumented behavior potentially changes this.

Unfortunately, the current implementation of `translate-c` translates as
`packed struct` without alignment info.

Because Zig packed structs are really integers (as mentioned above),
they are the wrong interpretation and we should be using 'extern struct'.

Running `translate-c` on the following code:

```c
struct foo {
    char a;
    int b;
} __attribute__((packed));

struct bar {
    char a;
    int b;
    short c;
    __attribute__((aligned(8))) long d;
} __attribute__((packed));
```

Previously used a 'packed struct' (which was not FFI-safe on stage1).

After applying this change, the translated structures have align(1)
explicitly applied to all of their fields AS EXPECTED (unless explicitly overriden).
This makes Zig behavior for `tranlsate-c` consistent with clang/GCC.

Here is the newly produced (correct) output for the above example:

```zig
pub const struct_foo = extern struct {
    a: u8 align(1),
    b: c_int align(1),
};
pub const struct_bar = extern struct {
    a: u8 align(1),
    b: c_int align(1),
    c: c_short align(1),
    d: c_long align(8),
};
```

Also note for reference: Since the last stable release (0.9.1),
there was a change in the language spec
related to the alignment of packed structures.

The docs for Zig 0.9.1 read:
> Packed structs have 1-byte alignment.

So the old behavior of translate-c (not specifying any alignment) was possibly correct back then.

However the current docs read:

> Packed structs have the same alignment as their backing integer

Suggsestive both to the change to an integer-backed representation
which is incompatible with C's notation.
2022-10-01 15:22:10 -07:00
Jacob Young
272e31227c llvm: add assert to reliably catch undefined value use
This assert makes it possible to detect a regression of #13030 in the
future without relying on undefined value tracking.
2022-10-01 09:03:28 -04:00
Jacob Young
b7bd44a654 Sema: ensure builtin.StackTrace fields are analyzed
When encountering a fn type that returns an error (union), a backend
that supports error return tracing will want the StackTrace struct and
its fields to be analyzed.
2022-10-01 08:09:43 -04:00
zooster
91b05ad473 std.math: allow comptime_float for radiansToDegrees and degreesToRadians
And some other minor things.
2022-10-01 13:46:20 +03:00
Jacob Young
8b66443d50 llvm: avoid undefined values by ensuring the StackTrace decl is analyzed
The test builds an object file to prevent StackTrace from already having
been analyzed by other code.

Fixes #13030
2022-10-01 04:02:09 -04:00
Jacob Young
d9490a4340 Sema: avoid undefined fields in file struct decls
Fixes original comment of #12399
2022-10-01 04:02:00 -04:00
Andrew Kelley
34835bbbcf Merge pull request #13010 from Vexu/stage2-fixes
fix stack trace line numbers
2022-09-30 00:14:55 -04:00
Veikka Tuominen
2a4e89e0c9 Type: correctly handle ABI align strat for optionals and error unions
Closes #12984
2022-09-30 00:46:45 +03:00
Veikka Tuominen
3122601242 AstGen: do not set decl_line for containers
Previously AstGen would set decl_line for containers so that
declarations inside them would be relative to the start of the
container but Sema was not aware of the line offset of the container
and would make them relative to the containers parent decl which
would then break for generic structs.

In the future when working on incremental compilation it will likely
be better to communicate the line delta to Sema but for now this
is a simpler fix that correctly handles the non-incremental case.

Closes #12725
Closes #12818
2022-09-30 00:09:24 +03:00
Veikka Tuominen
b3c6d774d2 stage2: improve error message for missing member in file root struct
* the root struct decl name is fully qualified
  this prevents error messages containing 'main.main'
* avoid declared here note when file struct is missing a member
  It always points at the start of the file which might contain another
  container misleading the user.
2022-09-30 00:09:24 +03:00
Veikka Tuominen
409cf4aeb8 Sema: use correct ptr ty to check for attributes of slice field ptr
Closes #12870
Closes #13006
2022-09-30 00:09:24 +03:00
r00ster91
f6312e4b69 docs: minor improvements
Just some minor improvements when passing by.
2022-09-29 21:40:25 +02:00
r00ster91
fda0b2c372 fix(std.testing.refAllDeclsRecursive): silently return if !builtin.is_test 2022-09-29 21:40:25 +02:00
ominitay
295451dfe5 std: Replace use of stage1 function pointers 2022-09-29 21:45:30 +03:00
Chris Boesch
9c99a88796 std.math: add "Greatest common divisor" (gcd) 2022-09-29 21:42:56 +03:00
Jakub Konka
36d2a55037 ci: update windows tarball 2022-09-29 18:43:16 +02:00
zooster
12896d36cb std.builtin: un-pub testVersionParse() 2022-09-29 14:47:41 +03:00
Igor Anić
9f6f460124 Sema: improve source location in errors
resolves #12793
2022-09-29 14:45:08 +03:00
kkHAIKE
317cb629fb Sema: fix resolveInferredErrorSet panic when generic inline function 2022-09-29 14:44:37 +03:00
Lee Cannon
8d288a5fa7 Fix Step.cast for OptionsStep and CheckObjectStep 2022-09-29 14:41:39 +03:00
Jacob Young
5e0d8a435e testing: fix copy paste typo 2022-09-29 14:39:10 +03:00
Techatrix
9a2f17f9f9 Docs: clarify unreachable for ReleaseSmall 2022-09-28 13:30:55 +03:00
Evin Yulo
779c2daa19 Remove outdated comment 2022-09-28 13:00:00 +03:00
Jacob G-W
0a064eae99 stage2: detect duplicate enum values
Closes #12805
2022-09-28 12:48:54 +03:00
Cody Tapscott
e165b8b223 stage2: Fix multiple_llvm_int parameter passing
Small iteration oopsie

We could really use some more comprehensive C ABI tests.
2022-09-28 12:48:28 +03:00
Silver
f3a1b5c481 std/meta: make FieldEnum(T) == Tag(T) for tagged unions when values match field indices 2022-09-27 18:42:20 +03:00
InKryption
c75e8f3616 Sema: check that reified enum field values fits tag type. 2022-09-27 18:38:37 +03:00
Veikka Tuominen
c673e6a48a Sema: avoid passing .unneeded to safetyPanic 2022-09-27 18:35:32 +03:00
Veikka Tuominen
17eea918ae langref: document inline switch 2022-09-27 18:33:23 +03:00
Veikka Tuominen
d4917957ef Sema: add better source location for inline prong backwards branch limit 2022-09-27 18:33:23 +03:00
Veikka Tuominen
509bb82b20 Sema: refactor common code to its own function 2022-09-27 18:33:23 +03:00
Veikka Tuominen
83fa216c8d Sema: implement inline else for ints 2022-09-27 18:33:23 +03:00
Veikka Tuominen
950a0e2405 Sema: implement inline else for errors enums and bools 2022-09-27 18:33:23 +03:00
Veikka Tuominen
0e77259f44 add inline switch union tag captures 2022-09-27 18:33:23 +03:00
Veikka Tuominen
5baaf90e3c Sema: implement non-special inline switch prongs 2022-09-27 18:33:23 +03:00
Veikka Tuominen
cccc4c3827 AstGen: analyze inline switch cases 2022-09-27 18:05:08 +03:00
Veikka Tuominen
07a7c2f7c8 stage2: remove redundant is_ref flag from SwitchBlock.Bits 2022-09-27 18:05:08 +03:00
Veikka Tuominen
b4d81857f3 stage1+2: parse inline switch cases 2022-09-27 18:05:08 +03:00
Jacob Young
c1493635fb fmt: ignore non-files 2022-09-27 13:25:19 +03:00
kkHAIKE
ba5cbea0c3 Sema: fix segfault when union init with empty field 2022-09-27 13:23:51 +03:00
Zhora Trush
f7f15e99c4 Fix minor langref typos 2022-09-27 13:22:57 +03:00
Jacob Young
e915b905e0 use @ptrCast to assigned generic type to default_value
If the type happens to be a pointer, then the double pointer will not
coerce implicitly.
2022-09-27 13:21:01 +03:00
Lee Cannon
38a50f819c make runPkgConfig pub 2022-09-27 13:20:32 +03:00
Jakub Konka
9c2fb6e186 Merge pull request #12959 from kcbanner/fix_uwtable
llvm: fix missing unwind info (wrong uwtable attribute value)
2022-09-26 23:05:39 +02:00
Luuk de Gram
9cd521a24f zig fmt 2022-09-26 19:54:35 +02:00
Loris Cro
37cfe3dfd2 Merge pull request #12976 from der-teufel-programming/master
autodoc: Added `.html` to generated source view file names
2022-09-26 18:00:36 +02:00
Der Teufel
55a9db4c9d autodoc: Added .html to generated source view file names 2022-09-26 15:46:01 +02:00
Veikka Tuominen
8849792789 Merge pull request #12951 from schmee/fix-add-field-err-note-oob
sema: load the correct AST in addFieldErrNote
2022-09-26 13:58:55 +03:00
John Schmidt
b6bda5183e sema: load the correct AST in failWithInvalidComptimeFieldStore
The container we want to get the fields from might not be declared in the
same file as the block we are analyzing, so we should get the AST from
the decl's file instead.
2022-09-26 08:56:34 +02:00
John Schmidt
6cc2b26163 sema: load the correct AST in addFieldErrNote
The enum we want to get the fields from might not be declared in the
same file as the block we are analyzing, so we should get the AST from
the decl's file instead.

Closes #12950.
2022-09-25 10:28:48 +02:00
Andrew Kelley
6d7b0690a0 Merge pull request #12942 from Vexu/stage2-fixes
misc stage2 fixes
2022-09-25 03:31:57 -04:00
kcbanner
1cc890e5c3 llvm: update uwtable value for stage1 2022-09-25 02:39:00 -04:00
kcbanner
328f75c985 llvm: fix uwtable attribute value 2022-09-25 01:52:40 -04:00
Veikka Tuominen
c4400e8aa5 AstGen: reset anon_name_strategy for sub expressions
Closes  #12910
2022-09-24 16:30:37 +03:00
Veikka Tuominen
8e4d0ae4f5 Sema: avoid generic parameter error in nested function type
Related to cd1833044a
Closes #12945
2022-09-24 15:15:36 +03:00
Veikka Tuominen
3a5148112d Sema: avoid using pointerDecl when dealing with slices
Closes #12885
2022-09-24 14:43:03 +03:00
Veikka Tuominen
fdf4c875ff llvm: avoid crash on duplicate asm input/output name 2022-09-24 14:43:03 +03:00
Veikka Tuominen
3525b8778e Sema: properly handle generic struct as parameter type
Closes #12907
2022-09-24 14:43:03 +03:00
Veikka Tuominen
ede3798485 Sema: resolve struct layout in zirStructInit
Closes #12911
2022-09-23 17:39:21 +03:00
Veikka Tuominen
581df942e1 Sema: correct sentinel check on implicit cast from array ptr
Closes #12938
2022-09-23 17:39:06 +03:00
Veikka Tuominen
3de5c3b503 Sema: check for slices in packed and extern type validation
Closes #12930
2022-09-23 17:39:06 +03:00
Veikka Tuominen
8d1fdfc8ed Sema: preserve volatileness when constructing field pointers
Closes #12928
2022-09-23 17:39:06 +03:00
Sage Hane
cae76d8293 langref: fix minor format error 2022-09-23 15:58:46 +02:00
Bill Nagel
eeeda53423 add missing darwin types 2022-09-23 12:25:40 +03:00
ノYuh
eaaaceaf3c make fmt.formatAsciiChar respect options parameter 2022-09-23 12:20:38 +03:00
noiryuh
0be46866fe use std.ascii instead of defining ascii functions in std.fs.path 2022-09-23 12:19:09 +03:00
John Simon
246a39c10e langref: remove uses of old function pointer syntax 2022-09-23 12:08:30 +03:00
Evin Yulo
dab5bb9247 Fix docstring for std.fs.path.extension 2022-09-22 20:13:09 -04:00
Andrew Kelley
0e4b04672c CI: remove --fail-with-body option
I observed this error:

```
curl: option --fail-with-body: is unknown
```
2022-09-21 22:22:41 -07:00
Andrew Kelley
5dce9368d6 CI: update sourcehut oauth token
it expired after one year
2022-09-21 20:34:17 -07:00
Andrew Kelley
99b954b9ce LLVM: remove purposeless const qualifiers
These const qualifiers on pointers to opaque types do not serve any
purpose. If anything they are misleading since the underlying pointers
very likely point to objects that are in fact mutated.

This commit does not change any behavior.
2022-09-21 13:27:23 -07:00
kkHAIKE
4961044ce8 AstGen: store void to ptr result loc when there is no else branch 2022-09-21 20:21:02 +03:00
kkHAIKE
183127733c AstGen: make loop body's ResultLoc .none
Fixes #12555
Fixes #12551
Fixes #12455
2022-09-21 20:20:05 +03:00
Ali Chraghi
0799e98562 std: update NativeTargetInfo.detect doc comments
`detect` doesn't take allocator anymore
2022-09-21 20:14:39 +03:00
Jacob Young
14f4c73191 sema: fix typo 2022-09-21 11:29:20 +02:00
Andrew Kelley
85e3204344 stage2: free up 2 ZIR tags
cmpxchg_weak and cmpxchg_strong are not very common; demote them to
extended operations to make some headroom.

This commit does not change any behavior, only memory layout of the
compiler.
2022-09-21 03:54:37 -04:00
Andrew Kelley
902f6db67b Merge pull request #12889 from ziglang/unwrap-error-switch
safety: show error return trace when unwrapping error in switch
2022-09-21 02:56:21 -04:00
Andrew Kelley
d7d21672b8 CI: update windows tarball 2022-09-20 19:05:00 -07:00
Veikka Tuominen
694fab4848 std: add return address parameter to panic fn 2022-09-20 19:05:00 -07:00
Veikka Tuominen
8f2e82dbf6 safety: show error return trace when unwrapping error in switch 2022-09-20 19:05:00 -07:00
Andrew Kelley
62ecc154d9 Merge pull request #12904 from Vexu/ptrcast
stage2: pointer casting fixes and improvements
2022-09-20 22:02:36 -04:00
Meghan
521c753fda std: fix os.linux.S function signatures to use mode_t 2022-09-20 17:54:32 -04:00
Joachim Schmidt
1f50810733 Merge pull request #12912 from joachimschmidt557/stage2-arm
stage2 ARM: minor fixes
2022-09-20 21:51:02 +02:00
joachimschmidt557
f014de6456 stage2 ARM: fix debug info for arguments passed in registers 2022-09-20 17:14:31 +02:00
joachimschmidt557
258b058eec stage2 ARM: make sub_sp_scratch MIR instruction use r4
r0 is used for argument passing, so this register is not available as
a scratch register upon function entry.
2022-09-20 17:14:27 +02:00
Veikka Tuominen
eef6539049 Sema: handle Value.slice in beginComptimePtrLoad 2022-09-20 00:50:13 +03:00
Veikka Tuominen
3e80aa9079 Sema: validate @alignOf type 2022-09-20 00:50:13 +03:00
Veikka Tuominen
540130650f Sema: pass calculated offset to elemPtrType in elemPtrSlice 2022-09-20 00:50:13 +03:00
Veikka Tuominen
541b3e3a31 Sema: check pointer qualifiers before implicit cast
Closes #12881
2022-09-20 00:50:13 +03:00
Motiejus Jakštys
4521456f66 zig cc: emit to a.out if outpath is unspecified
If `-o` is not specified for `zig cc` for linking, it should emit the
`a.out` (or equivalent) to the current directory. So then this:

    $ zig cc test.c

Should result in `./a.out`.

If directory is omitted from `Compilation.EmitLoc`, it will default to
the cache directory later in the compilation chain, which will result
in `a.out` missing in the current directory.

If we specify the directory to `Compilation.EmitLoc`, it will be
handled, allegedly, correctly.

Fixes #12858
2022-09-19 15:05:37 -04:00
Veikka Tuominen
fb91483e48 Sema: do not use coerceCompatiblePtr for ptrCast 2022-09-19 18:34:53 +03:00
Veikka Tuominen
e584558bd8 Sema: do not use coerceCompatiblePtr for alignCast
Closes  #12902
2022-09-19 18:34:52 +03:00
Jakub Konka
e42f83825f Merge pull request #12893 from ziglang/macho-relocs-cleanup
macho: rewrite incremental linker, and init splitting of linking contexts
2022-09-18 23:19:33 +02:00
Loris Cro
2698cb346a autodoc: don't collect tests, usingnamespace and comptime blocks
Previously we were collecting as autodoc decls everything that was a ZIR
decl in a rather naive way. Now we only collect decltests as part of the
data relative to the decl they refer to, and ignore everything else.
2022-09-18 20:00:44 +02:00
Jakub Konka
4474f8dd6e macho: cleanup how we collect dyld data in incremental linker 2022-09-18 15:13:45 +02:00
Jakub Konka
f4706c23e9 macho: fix after sync with master 2022-09-18 11:01:29 +02:00
Jakub Konka
372acb8350 macho: ensure we extend section size when updating last atom 2022-09-18 10:00:04 +02:00
Jakub Konka
275abf7c57 macho: fix overlapping segments in file offset 2022-09-18 10:00:04 +02:00
Jakub Konka
66942cbc1a macho: make sure both vmsize and filesize for segments match always 2022-09-18 10:00:04 +02:00
Jakub Konka
2c971f0085 fix code formatting 2022-09-18 10:00:04 +02:00
Jakub Konka
e35a16c7e0 macho: make sure both vmsize and filesize for segments match 2022-09-18 10:00:04 +02:00
Jakub Konka
7f7669a09e macho: fix building on 32bit targets 2022-09-18 10:00:04 +02:00
Jakub Konka
dc6480dba5 macho: allow for add and ldr when resolving GOT_LOAD_* relocs 2022-09-18 10:00:04 +02:00
Jakub Konka
618c7a3546 macho: add logic for expanding segments in memory 2022-09-18 10:00:04 +02:00
Jakub Konka
e601969244 macho: rewrite how we allocate space in incremental context 2022-09-18 10:00:04 +02:00
Jakub Konka
79ab46ec91 macho: start separating linking contexts 2022-09-18 10:00:04 +02:00
Jakub Konka
53bd7bd044 macho: move to incremental writes and global relocs for incremental 2022-09-18 10:00:04 +02:00
Jakub Konka
34f9360ea2 macho: do not call populateMissingMetadata in full link mode 2022-09-18 10:00:04 +02:00
Jakub Konka
e5da251635 macho: clean up use of section ids 2022-09-18 10:00:04 +02:00
Jakub Konka
05d0c42894 macho: move main driver loop for one-shot into standalone zld module 2022-09-18 10:00:03 +02:00
Jakub Konka
26af8d254a macho: separate in structure and logic incremental relocs and file relocs 2022-09-18 10:00:03 +02:00
Jakub Konka
54854e2ab8 add removed expected stdout comparison in link test 2022-09-18 09:28:46 +02:00
Jakub Konka
0030e72d53 use EmulatableRunStep for newly added macho link test
Reverts 75e9a8c7fa
2022-09-18 09:22:49 +02:00
Andrew Kelley
75e9a8c7fa skip macho link test execution on non-macOS
2c3d87b168 introduced a new test that
passes on macOS but fails on other operating systems. This commit makes
it only run on macOS.
2022-09-17 21:33:19 -07:00
Jakub Konka
437ddcce7a test-cases: remove removed "note: referenced here" note from the error 2022-09-17 23:38:40 +02:00
Jakub Konka
0f1fbbfdfb ci: azure: macos: use updated release tarball 2022-09-17 23:11:58 +02:00
Jakub Konka
2c3d87b168 macho: test empty translation units 2022-09-17 18:43:24 +02:00
Jakub Konka
5391541f11 macho: do not assume every object has a symtab
For example, building stage2 requires an empty `empty.cc` source file
compiling which generates a valid translation unit with no symtab/strtab.
In this case, we cannot simply assume that every translation unit will
have a valid symtab; instead, we cautiously default the input symtab
and strtab fields to optional `null` to signal symtab's presence or its lack of.
In case the symtab is not present, we catch this fact when splitting
input sections into subsections and create a synthetic symbol per every
suitable section.
2022-09-17 18:42:47 +02:00
billzez
dfcadd22bb fix android definition of pthread_rwlock_t (#12830) 2022-09-16 20:20:24 -05:00
Veikka Tuominen
b2aedb0709 Merge pull request #12796 from Vexu/referenced-by-v2
stage2: add referenced by trace to compile errors attempt #2 (+ some fixes)
2022-09-16 23:49:00 +03:00
Andrew Kelley
8edd7219c0 Sema: improve source location after as_node is used
+2 more passing compile error tests
2022-09-16 14:47:17 -04:00
Andrew Kelley
d3d24874c9 std: remove deprecated API for the upcoming release
See #3811
2022-09-16 14:46:53 -04:00
cod1r
7b32aacbaf fix ChildProcess crash when PATH is empty. 2022-09-15 22:54:17 -04:00
Andrew Kelley
2be72c719e ci: azure: macos: use an unstripped debug zig tarball
Hopefully will give us some insight into the spurious failures.

Follow-up from afba53f0f1.
2022-09-15 13:56:18 -07:00
Andrew Kelley
9f4408d68b organize some compile error tests
Many of these tests check for the incorrect behavior of stage1 whereas
self-hosted correctly does not emit an error, so they are simply
deleted.

The remaining number of test cases within the stage1/ subdirectory is
reduced from 143 to 103.
2022-09-15 14:40:45 -04:00
Andrew Kelley
afba53f0f1 CI: swap out azure macos tarball for unstripped ReleaseSafe
Hopefully will give us some insight into the spurious failures.
2022-09-14 19:16:02 -07:00
Eric Joldasov
a86c7b13a3 docgen: add f80 to builtin types 2022-09-14 20:08:34 -04:00
Stephen Gregoratto
7ccb94fac8 Audit FreeBSD structs to match header files/ABI
The big outliers were `Stat` and `mcontext_t`. Also adds doc-comments
from the headers where possible.
2022-09-14 20:05:54 -04:00
alichraghi
8c9f468fdd std.ArrayList.ensureTotalCapacity: optimize and fix integer overflow
Fixes #12099
2022-09-14 20:05:15 -04:00
Andrew Kelley
78cd7b57ef Merge pull request #12206 from koachan/sparc64-codegen
stage2: sparc64: Another batch of Air lowerings, bugfixes, etc.
2022-09-14 20:00:38 -04:00
Koakuma
86dc982e74 stage2: sparc64: Implement airSlicePtr 2022-09-14 16:58:13 -07:00
Koakuma
ed546a7aad stage2: sparc64: Add placeholder for some Air instructions
airAddSat airSubSat airMulSat airShlSat airUnaryMath airPopcount airPrefetch
airPtrElemVal airOptionalPayload airOptionalPayloadPtr airOptionalPayloadPtrSet
2022-09-14 16:58:13 -07:00
Koakuma
0910cb6fcb stage2: sparc64: Skip compile-failing tests for now 2022-09-14 16:58:12 -07:00
Koakuma
0e1c68d90a stage2: sparc64: Don't track condition_flags_inst in checked binOps
This stops the emission of spurious CCR spills.
2022-09-14 16:57:31 -07:00
Koakuma
0464512f2e stage2: sparc64: Implement airShlWithOverflow 2022-09-14 16:57:31 -07:00
Koakuma
de17fe66a5 stage2: sparc64: Tidy up binOp and enable more operations
sub, mul, addwrap, subwrap, mulwrap, shr, shr_exact
2022-09-14 16:57:31 -07:00
Koakuma
ab3d3b260b stage2: sparc64: Add airClz/airCtz placeholder 2022-09-14 16:57:31 -07:00
Koakuma
b9897c3b84 stage2: sparc64: Implement airMulOverflow for <= 32 bits 2022-09-14 16:57:31 -07:00
Koakuma
844d3a5a74 stage2: sparc64: Fix SPARCv9 shift opcodes encoding 2022-09-14 16:57:31 -07:00
Koakuma
2263bba6cd stage2: sparc64: Skip Sema-failing tests for now 2022-09-14 16:57:31 -07:00
Koakuma
61265fba04 stage2: sparc64: Implement airBinop for bool_and/or 2022-09-14 16:57:31 -07:00
Koakuma
4fc6df9f62 stage2: sparc64: Implement airTagName 2022-09-14 16:57:31 -07:00
Koakuma
f01867f78e stage2: sparc64: Implement airWrapOptional 2022-09-14 16:57:31 -07:00
Koakuma
b6307144c0 stage2: sparc64: Implement airPtrToInt 2022-09-14 16:57:31 -07:00
Koakuma
2c9ab03b0b stage2: sparc64: Add airCmpLtErrorsLen placeholder 2022-09-14 16:57:31 -07:00
Koakuma
5b0134e3ed stage2: sparc64: Change branch_link Mir field definition 2022-09-14 16:57:31 -07:00
Koakuma
64b61f0740 stage2: sparc64: Add airFloatToInt & airIntToFloat placeholder 2022-09-14 16:57:31 -07:00
Andrew Kelley
17596c79a9 stage2: fix compile error merge conflict
3250b20cea had a silent merge conflict
with master branch; fixed now.
2022-09-14 16:41:53 -07:00
Jan Philipp Hafer
8cab0762d8 place zig-cache directory next to build.zig
* search upwards, if no build.zig is found
* if this fails or any error occurs, fallback to global zig-cache

Closes #11672
2022-09-14 19:39:25 -04:00
Manlio Perillo
3250b20cea src/print_env: print the native target
Add the native target triple to the zig env command output.

The target triple is formatted the same way as it is done in the
zig targets command.
2022-09-14 19:28:47 -04:00
Andrew Kelley
1d041d3a10 Merge pull request #11664 from vincenzopalazzo/macros/docs
docs: add missed docs for some language feature like `defer` and `errdefer`
2022-09-14 19:26:28 -04:00
Andrew Kelley
0931dda9a9 Merge pull request #11663 from matu3ba/utf16
std.unicode: add utf16 byte length and codepoints counting routines
2022-09-14 19:25:15 -04:00
Andrew Kelley
d7a0fe67b3 disable spuriously failing test on Windows
See tracking issue #12844
2022-09-14 16:12:55 -07:00
Andrew Kelley
d834b18011 Merge pull request #11633 from SpexGuy
Remove `std.testing.zig_exe_path` in favor of `ZIG_EXE` environment variable
2022-09-14 18:02:21 -04:00
Andrew Kelley
85b10eb07c ZIG_EXE envirnoment variable instead of testing build options
No longer introduce build options for tests. Instead, ZIG_EXE
environment variable is added to any invocation of `zig run` or `zig
test`.

The end result of this branch is the same: there is no longer a
mandatory positional command line argument when invoking zig test
binaries directly.
2022-09-14 14:56:45 -07:00
Veikka Tuominen
31daea74d2 stage2: implement referenced by trace for error messages
Closes #7668
Closes #12141
2022-09-15 00:50:18 +03:00
Veikka Tuominen
5e4483fff8 Sema: handle comptime fields in field call bind
Closes #12801
2022-09-15 00:50:18 +03:00
Veikka Tuominen
5e37da6ade Sema: check_comptime_control_flow needs to check runtime_index 2022-09-15 00:50:18 +03:00
Veikka Tuominen
bf4a3df9a9 Sema: allow runtime break from inline loop
Closes #12787
2022-09-15 00:48:47 +03:00
Veikka Tuominen
002260c274 Sema: copy runtime_index & friends when making child blocks 2022-09-15 00:48:47 +03:00
Veikka Tuominen
6f6b14621d value: hash extern functions
Closes #12766
2022-09-15 00:48:47 +03:00
Veikka Tuominen
930f904aaa Sema: resolve lazy align in reifyStruct
Closes #12786
2022-09-15 00:48:47 +03:00
Veikka Tuominen
de24cea2cf Sema: handle empty_struct_value in beginComptimePtrMutation
Closes #12794
2022-09-15 00:48:47 +03:00
Martin Wickham
5523e2061b Move std.testing.zig_exe_path into build options 2022-09-14 14:42:58 -07:00
Andrew Kelley
61aaef0b07 std: re-enable test case for fixed bug
The miscompilation in question has been fixed upstream in LLVM 14.

closes #9879
2022-09-13 18:36:39 -07:00
Andrew Kelley
68f2d6cb24 std: remove workaround for fixed bug
The miscompilation in question has been fixed upstream in LLVM 13.

closes #8117
2022-09-13 18:20:18 -07:00
Andrew Kelley
0a89624d59 stage2: support being built in ReleaseSafe mode 2022-09-13 18:08:59 -07:00
Veikka Tuominen
349d78a443 validate number literals in AstGen 2022-09-13 20:26:04 -04:00
Andrew Kelley
716d9237cb Merge remote-tracking branch 'origin/llvm15'
Upgrade to LLVM 15
2022-09-13 15:39:19 -07:00
Andrew Kelley
fda6d44778 zig cc: do not enable the cache for link operations
This commit makes `zig cc` match the equivalent behavior of
`zig build-exe` with regards to caching. That is - it will cache
individual .c to .o compilations (with the usual exceptions), but will
always repeat the linking process so that incremental linking has a
chance to happen.

Perhaps a future enhancement will provide a way to get the old behavior,
but I suspect this new behavior will be preferred by everyone, because
it is closer to what C compilers do. Note that the old behavior can be
obtained by switching to `zig build-exe` instead of `zig cc` and using
the `--enable-cache` parameter.

Closes #12317
2022-09-13 14:10:13 -07:00
Andrew Kelley
0a4cfb81bc Merge remote-tracking branch 'origin/master' into llvm15 2022-09-13 13:50:25 -07:00
Andrew Kelley
f9859c102d fix libc++ exceptions for musl targets
This reverts commit d31be31267.

The problem was happening due to an LLVM bug exposed by having LTO
enabled for libunwind. The simple workaround is to disable LTO for
libunwind. It can be re-enabled in the future when the upstream bug
is fixed.

See #12828
2022-09-13 11:38:14 -07:00
Andrew Kelley
c25ce5bba0 Merge pull request #12820 from ziglang/pointless-discard-error
introduce compile error for pointless discards
2022-09-13 13:01:42 -04:00
Andrew Kelley
b2e94de358 add compile error test for pointless discards 2022-09-13 10:01:17 -07:00
Luuk de Gram
be94487029 Merge pull request #12823 from Luukdegram/wasm-linker
wasm-linker: misc improvements & cleanups
2022-09-13 17:42:51 +02:00
Andrew Kelley
cdb40936bd properly annotate nullability of ZigLLVMCreateDebugForwardDeclType
This bug manifested as a segfault in stage1 when calling this function.
The C++ code looks like this:

```c++
entry->llvm_di_type = ZigLLVMCreateDebugForwardDeclType(g->dbuilder,
    ZigLLVMTag_DW_structure_type(), full_name,
    import ? ZigLLVMFileToScope(import->data.structure.root_struct->di_file) : nullptr,
    import ? import->data.structure.root_struct->di_file : nullptr,
    line);
```

There is actually no problem here - what happened is that because
cross-language LTO was enabled between zig and c++ code, and because
Zig annotated the file parameter (3rd line) as being non-null, the C++
code assumed that parameter could not be null, and eagerly dereferenced
`import->...`, causing a segfault, since it was null.

I verified that this commit fixed the problem and I also verified this
hypothesis by disabling LTO and noticing that it indeed avoided the
problem.
2022-09-13 03:09:29 -07:00
Andrew Kelley
ebd082d3f6 remove pointless discards in test cases 2022-09-13 02:04:20 -07:00
Andrew Kelley
bec70a1a39 stage2: remove pointless discards from source code
Good riddance!
2022-09-13 02:04:20 -07:00
Andrew Kelley
f8a9bc57ce translate-c: lower discards differently
This makes translate-c lower discards as `_ = @TypeOf(foo);` to avoid
tripping the "pointless discard" error.

Ideally, translate-c would avoid emitting pointless discards, in which
case this commit can be reverted, however, that is a separate
enhancement.
2022-09-13 02:04:20 -07:00
Andrew Kelley
d31be31267 disable failing c++ test
See tracking issue #12828
2022-09-12 23:16:57 -07:00
Andrew Kelley
87819dba27 libunwind: compile with -std=c11
I noticed that the upstream cmake script does this now.
2022-09-12 23:16:38 -07:00
Andrew Kelley
7a941391d8 universal-libc: fix strncmp tests
The specification for this function is that it returns a positive value,
zero, or negative value, not that it returns the difference between
ascii values.
2022-09-12 22:32:15 -07:00
Andrew Kelley
78729c4939 update CI tarballs with libcxx fix
The main reason to update the CI tarballs is
f79824f946 which fixes an issue that
caused the CI to fail on all targets.
2022-09-12 21:25:49 -07:00
Andrew Kelley
2434cb6f06 cmake: add -Dversion-string flag to zig build command 2022-09-12 20:13:00 -07:00
Andrew Kelley
188902a710 Sema: introduce Type.ptrAlignmentAdvanced
I'm not sure why the other commits in this branch caused this fix to be
necessary. Also, there seems to be more fixes necessary before tests
will pass.
2022-09-12 18:13:24 -07:00
Andrew Kelley
f16855b9d7 remove pointless discards 2022-09-12 18:13:24 -07:00
Andrew Kelley
011663eea5 Merge remote-tracking branch 'origin/master' into llvm15 2022-09-12 16:11:18 -07:00
Andrew Kelley
01e89fec71 disable LLVM 15 regressed behavior test: "vector @splat"
See #12827
2022-09-12 16:02:31 -07:00
Andrew Kelley
f79824f946 libcxx: define _LIBCPP_ABI_VERSION and _LIBCPP_ABI_NAMESPACE
The changes from https://reviews.llvm.org/D119173 mean that __config no
longer defaults the libc++ ABI to 1, relying on external configuration.
This means Zig must provide the external configuration.

This fixes static libraries built with zig with -lc++ to have the
standard __1 namespace prefix, which had previously regressed in the
llvm15 branch.
2022-09-12 15:56:31 -07:00
Andrew Kelley
6e3bbba951 update CI tarballs for LLVM 15 2022-09-12 13:03:10 -07:00
Luuk de Gram
3edf8c7a6c wasm-linker: reset file pointer for incremental
On each invocation of `flush()` the file pointer is moved.
This means that rather than overwriting the binary file,
we're appending to the file. With this commit, we're resetting
said pointer to '0' and overwrite the existing binary in incremental
mode.
2022-09-12 21:35:28 +02:00
Luuk de Gram
61f317e386 wasm-linker: rename self to descriptive name 2022-09-12 21:19:16 +02:00
Luuk de Gram
6dbf5f1d86 wasm-linker: write to file at once
Rather than writing to the file using a writer, we now first write to
an arraylist and store the binary in memory. Once the full binary
data was written, we write all data to disk at once. This reduces
the amount of syscalls tremendously, increasing the performance of
the linker in exchange for increased memory usage during flush.
2022-09-12 21:19:16 +02:00
Luuk de Gram
a01b1448e2 wasm-linker: write magic bytes only on success
By writing them at the very end, we can easily detect
where the writing of the binary went wrong as tools will
indicate the missing of the magic bytes.
2022-09-12 21:19:13 +02:00
Veikka Tuominen
e323cf1264 stage2: change how defers are stored in Zir
Storing defers this way has the benefits that the defer doesn't get
analyzed multiple times in AstGen, it takes up less space, and it
makes Sema aware of defers allowing for 'unreachable else prong'
error on error sets in generic code.

The disadvantage is that it is a bit more complex and errdefers with
payloads now emit a placeholder instruction (but those are rare).

Sema.zig before:
  Total ZIR bytes:    3.7794370651245117MiB
  Instructions:       238996 (2.051319122314453MiB)
  String Table Bytes: 89.2802734375KiB
  Extra Data Items:   430144 (1.640869140625MiB)
Sema.zig after:
  Total ZIR bytes:    3.3344192504882812MiB
  Instructions:       211829 (1.8181428909301758MiB)
  String Table Bytes: 89.2802734375KiB
  Extra Data Items:   374611 (1.4290275573730469MiB)
2022-09-12 01:52:44 -04:00
Andrew Kelley
ab3ac291ac Merge remote-tracking branch 'origin/master' into llvm15 2022-09-11 20:26:53 -07:00
Shane Kennedy
c97d64b677 chore: Remove unused constants 2022-09-11 23:18:43 -04:00
Andrew Kelley
349df40d14 Merge pull request #12814 from ziglang/native-libc-integration
stage2: no condition on system libs to link native libc
2022-09-11 23:12:50 -04:00
Andrew Kelley
65bea514ae Compilation: handle system C compiler not found
When linking libc and compiling natively, Zig tries to integrate with
the system C compiler. However, this caused Zig to fail when no system C
compiler is installed, despite the fact that Zig is perfectly capable of
compiling & linking libc without one.

This commit makes Zig fall back to using its own ability to provide libc
in the case that no C compiler is installed. For glibc, it means
sometimes getting the warning "zig cannot build new glibc version abc,
providing instead xyz".

Ideally, Zig would do some more validation about the system libraries
being linked against, and report an error in case it could not provide
the exact correct libc version of the system libraries (or that the
system libraries themselves conflict with each other), however, I think
it is fair to call that a separate enhancement.
2022-09-11 16:37:03 -07:00
Loris Cro
60678f5baf autodoc: fix regression in frontend rendering of values 2022-09-11 23:45:18 +02:00
Andrew Kelley
aec0e595f2 stage2: no condition on system libs to link native libc
Before, Zig tried to use its own libc files (e.g. glibc) when there were
no system libs being linked. This prevented building against native
glibc on systems that have newer glibc than the ones Zig provides.

Closes #12797
2022-09-11 13:39:58 -07:00
Loris Cro
2a96f80d03 autodoc: reduce json payload size
this commit removes whitespace and changes Decl, AstNode and Type to be
json arrays instead of json objects. This change reduces json payload
size for the stdlib from 25mb to < 10mb.
2022-09-11 21:35:01 +02:00
Loris Cro
81939a4939 autodoc: remove unnecessary string copy 2022-09-10 17:31:42 +02:00
Jakub Konka
4fd4c733d4 x86_64: pass more behavior tests 2022-09-10 09:23:26 +02:00
Jakub Konka
5778077f9f Merge pull request #12799 from joachimschmidt557/stage2-arm
stage2 ARM: introduce allocRegs mechanism and other improvements
2022-09-10 09:13:08 +02:00
Jakub Konka
69da56b36c Merge pull request #12802 from ziglang/macho-refactor
Self-hosted backends and linkers refactor: x86_64 + aarch64 + macho + coff
2022-09-10 09:07:07 +02:00
Jakub Konka
a1b8545265 coff: remove unused function 2022-09-10 00:59:46 +02:00
Jakub Konka
0824808444 macho: refactor direct use of locals container in favour of helpers 2022-09-10 00:58:16 +02:00
Jakub Konka
485d8819b3 aarch64: update codegen to using a global index rather than local index 2022-09-10 00:57:54 +02:00
Jacob Young
5b9c5191ab type: print comptime on fn type params
This avoids the following confusing error message:

    error: expected type 'fn(i32, i32) void', found 'fn(i32, i32) void'
2022-09-10 01:55:52 +03:00
Evan Haas
8e631ee3e7 translate-c: Escape non-ASCII characters that appear in macros
Macro definitions are simply a slice of bytes, which may not be
UTF-8 encoded. If they are not UTF-8 encoded, escape non-printable
and non-ASCII characters as `\xNN`.

Fixes #12784
2022-09-10 01:50:17 +03:00
Jakub Konka
fc5a6e0e32 x86_64: combine got_load, direct_load and imports_load into linker_load MCV 2022-09-10 00:18:39 +02:00
Jakub Konka
d8f2103545 macho+coff: return index into global table from getGlobalSymbol 2022-09-09 23:30:31 +02:00
Jakub Konka
bac065c7cf coff: use global accessor abstractions from MachO 2022-09-09 22:29:50 +02:00
Jakub Konka
8d44e03161 macho: use globals free list like in COFF linker 2022-09-09 22:10:27 +02:00
joachimschmidt557
94499898e5 stage2 ARM: implement basic array_elem_val 2022-09-09 20:26:04 +02:00
Andrew Kelley
37cdb5dbf9 Merge remote-tracking branch 'origin/master' into llvm15 2022-09-09 10:26:17 -07:00
joachimschmidt557
b976997e16 stage2 ARM: implement ptr_elem_val 2022-09-09 19:17:18 +02:00
joachimschmidt557
a0a7d15142 stage2 ARM: support larger function stacks
This is done by introducing a new Mir pseudo-instruction
2022-09-09 19:17:18 +02:00
joachimschmidt557
3794f2c493 stage2 ARM: implement struct_field_val for registers 2022-09-09 19:17:18 +02:00
joachimschmidt557
25729d6155 stage2 ARM: fix multiple uses of reuseOperand
- add missing checks whether destination fits into the operand
- remove reuseOperand invocations from airIsNullPtr and similar
  functions as we need to load the operands into temporary locations
2022-09-09 19:17:18 +02:00
joachimschmidt557
261fec8036 stage2 ARM: amend implementation of various AIR instructions
- unwrap_errunion_err for registers
- unwrap_errunion_payload for registers
- ptr_slice_len_ptr for all MCValues
- ptr_slice_ptr_ptr for all MCValues
2022-09-09 19:17:17 +02:00
joachimschmidt557
e2b029e2c8 stage2 ARM: implement field_parent_ptr 2022-09-09 19:17:17 +02:00
joachimschmidt557
481bd4761a stage2 ARM: remove remaining uses of binOp{Register,Immediate} 2022-09-09 19:17:17 +02:00
joachimschmidt557
95b8a5f157 stage2 ARM: extract remaining operations out of binOp 2022-09-09 19:17:17 +02:00
joachimschmidt557
fdb2c80bdc stage2 ARM: extract mul, div, and mod out of binOp 2022-09-09 19:17:17 +02:00
joachimschmidt557
ed4be06883 stage2 ARM: extract add+sub from binOp
This commit also lays the groundwork for further extractions from
binOp.
2022-09-09 19:17:17 +02:00
joachimschmidt557
86dd123392 stage2 ARM: move cmp to new allocReg mechanism; remove from binOp 2022-09-09 19:17:17 +02:00
joachimschmidt557
0414ef591a stage2 ARM: introduce allocRegs
This new register allocation mechanism which is designed to be more
generic and flexible will replace binOp.
2022-09-09 19:17:16 +02:00
joachimschmidt557
28cc363947 stage2 ARM: improve Mir representation of mov and cmp 2022-09-09 19:17:13 +02:00
Andrew Kelley
9e070b653c Merge pull request #12788 from ziglang/detect-native-glibc
std.zig.system.NativeTargetInfo: improve glibc version and dynamic linker detection
2022-09-09 12:28:25 -04:00
Andrew Kelley
68e61bbc0c std.zig.system.NativeTargetInfo: more headroom for libc.so.6 .dynstr 2022-09-09 09:27:02 -07:00
Yusuf Bham
c9f145a50b std.os.uefi: mark BlockIoProtocol and EfiBlockMedia as public 2022-09-09 16:48:54 +03:00
Jakub Konka
56b96cd61b Merge pull request #12772 from ziglang/coff-basic-imports
coff: implement enough of the incremental linker to pass behavior and incremental tests on Windows
2022-09-09 13:08:58 +02:00
Andrew Kelley
c7d6048081 std.zig.system.NativeTargetInfo: add fallback check
After failing to find RUNPATH in the ELF of /usr/bin/env, not finding
the answer in a symlink of the dynamic interpreter, and not finding
libc.so.6 in the same directory as the dynamic interpreter, Zig will
check `/lib/$triple`.

This fixes incorrect native glibc version detected on Debian bookworm.
2022-09-09 00:07:02 -07:00
Jakub Konka
5006fb6846 macho: fix compilation for 32bit targets 2022-09-09 08:30:27 +02:00
Andrew Kelley
9f40f34501 std.zig.system.NativeTargetInfo: restore symlink logic
This is a partial revert of the previous commit, fixing a regression on
Debian. However, the commit additionally improves the
detectAbiAndDynamicLinker function to read more than 1 byte at a time
when detecting a shebang line.
2022-09-08 20:52:49 -07:00
Andrew Kelley
c668396941 std.zig.system.NativeTargetInfo: handle missing DT_RUNPATH
This commit removes the check that takes advantage of when the dynamic
linker is a symlink. Instead, it falls back on the same directory as the
dynamic linker as a de facto runpath. Empirically, this gives correct
results on Gentoo and NixOS.

Unfortunately it is still falling short for Debian, which has libc.so.6
in a different directory as the dynamic linker.
2022-09-08 20:52:49 -07:00
Andrew Kelley
1b6fa1965a stage2: fix building for 32-bit targets 2022-09-08 20:52:49 -07:00
Andrew Kelley
3ee01c14ee std.zig.system.NativeTargetInfo: detection ignores self exe
Before, native glibc and dynamic linker detection attempted to use the
executable's own binary if it was dynamically linked to answer both the
C ABI question and the dynamic linker question. However, this could be
problematic on a system that uses a RUNPATH for the compiler binary,
locking it to an older glibc version, while system binaries such as
/usr/bin/env use a newer glibc version. The problem is that libc.so.6
glibc version will match that of the system while the dynamic linker
will match that of the compiler binary. Executables with these versions
mismatching will fail to run.

Therefore, this commit changes the logic to be the same regardless of
whether the compiler binary is dynamically or statically linked. It
inspects `/usr/bin/env` as an ELF file to find the answer to these
questions, or if there is a shebang line, then it chases the referenced
file recursively. If that does not provide the answer, then the function
falls back to defaults.

This commit also solves a TODO to remove an Allocator parameter to the
detect() function.
2022-09-08 20:52:49 -07:00
Andrew Kelley
fa940bafa2 std.zig.system.NativeTargetInfo: improve glibc version detection
Previously, this code would fail to detect glibc version because it
relied on libc.so.6 being a symlink which revealed the answer. On modern
distros, this is no longer the case.

This new strategy finds the path to libc.so.6 from /usr/bin/env, then
inspects the .dynstr section of libc.so.6, looking for symbols that
start with "GLIBC_2.". It then parses those as semantic versions and
takes the maximum value as the system-native glibc version.

closes #6469
   see #11137
closes #12567
2022-09-08 20:52:49 -07:00
a833bdcd7e [ld] add --print-* for diagnostics
This adds the following for passthrough to lld:
- `--print-gc-sections`
- `--print-icf-sections`
- `--print-map`

I am not adding these to the cache manifest, since it does not change
the produced artifacts.

Tested with an example from #11398: it successfully prints the resulting
map and the GC'd sections.
2022-09-08 22:30:32 -04:00
Jakub Konka
8378cde743 macho: prefill any space between __DATA and __LINKEDIT with 0s if required
If there are zerofill sections, the loader may copy the contents of
the physical space in file directly into memory and attach that to
the zerofill section. This is a performance optimisation in the loader
but requires us, the linker, to properly zero-out any space between
__DATA and __LINKEDIT segments in file. This is of course completely
skipped if there are no zerofill sections present.
2022-09-09 00:01:22 +02:00
Luuk de Gram
ab4b26d8a6 Merge pull request #12770 from Luukdegram/wasm-dwarf
wasm-linker: implement linking debug-information
2022-09-08 16:57:23 +02:00
Veikka Tuominen
6a62a15ecd Merge pull request #12773 from Vexu/stage2-fixes
Sema: fix UAF in zirClosureGet
2022-09-08 16:43:54 +03:00
Jakub Konka
0ae2ea671b wasm: temporarily save curr file pointer before pwriting on Win
This is a temporary workaround to an unclear platform-dependence
behavior we have in libstd for `std.fs.File` abstraction. See
https://github.com/ziglang/zig/issues/12783 for more information.
2022-09-08 14:29:54 +02:00
Veikka Tuominen
c7e45aebaf llvm: handle pointers in packed structs in more places
Closes #12776
2022-09-08 12:51:40 +03:00
Martin Stuurwold
a7661f115d NativeTargetInfo.zig: fix typo 2022-09-08 01:53:32 -04:00
Veikka Tuominen
44b9a1d031 translate-c: use correct name for failDecl
Closes #12737
2022-09-08 01:00:19 +03:00
Veikka Tuominen
99826a2ba8 Sema: fix UAF in zirClosureGet
Previously if a decl failed its capture scope would be deallocated and
set to undefined which would then lead to invalid dereference in
`zirClosureGet`. To avoid this set the capture scope to a special
failed state and fail the current decl with dependency failure if
the failed state is encountered in `zirClosureGet`.

Closes #12433
Closes #12530
Closes #12593
2022-09-08 00:37:11 +03:00
Veikka Tuominen
37afab2add Sema: preserve alignment of const decl pointers
Closes #12769
2022-09-08 00:37:11 +03:00
Veikka Tuominen
0fa80e66b7 Sema: correct types in @memset and @memcpy
Closes #12750
2022-09-08 00:37:11 +03:00
Jakub Konka
b98b3252be revert part of 945111ae92 2022-09-07 23:18:57 +02:00
Jakub Konka
0e152b76ac tests: force LLD off for stage2 backends until auto-select deems worthy 2022-09-07 23:16:42 +02:00
Jakub Konka
c4d297b1af test-cases: add missing incremental x86_64-windows test cases 2022-09-07 22:42:59 +02:00
Jakub Konka
a226aef36c test-cases: enable stage2 tests on Windows 2022-09-07 22:42:59 +02:00
Jakub Konka
678e07b924 macho+wasm: unify and clean up closing file handles 2022-09-07 22:42:59 +02:00
Jakub Konka
639237c7b4 macho: set file instance in linkOneShot only if not already set 2022-09-07 22:42:59 +02:00
Jakub Konka
8ef1c62f2e macho: properly close file handles owned by the linker in deinit() 2022-09-07 22:42:59 +02:00
Jakub Konka
215fce8c51 coff: fix tracking of got and import entries; free relocs in update* fns 2022-09-07 22:42:59 +02:00
Jakub Konka
99c2cb72e8 coff: track globals in contiguous array to allow for tombstones 2022-09-07 22:42:59 +02:00
Jakub Konka
f3e4e44a2b coff: fix memory leak in incorrectly disposing of globals table 2022-09-07 22:42:58 +02:00
Jakub Konka
945111ae92 enable testing of x86_64-windows-gnu using self-hosted backend and linker 2022-09-07 22:42:58 +02:00
Jakub Konka
7b8cc599d9 coff: use more generous initial memory sizes for sections 2022-09-07 22:42:58 +02:00
Jakub Konka
16ca47b9b8 coff: remove redundant bits and clean up 2022-09-07 22:42:58 +02:00
Jakub Konka
2b373b0579 coff: grow section in virtual address space when required 2022-09-07 22:42:58 +02:00
Jakub Konka
9116e0f746 coff: find new file space for a section (file offsets) 2022-09-07 22:42:58 +02:00
Jakub Konka
79e51c5e4b coff: differentiate between file space and VM space for alloc 2022-09-07 22:42:58 +02:00
Jakub Konka
08f6546c84 coff: create a helper for allocating sections 2022-09-07 22:42:58 +02:00
Jakub Konka
f1bdf3f62f coff: fix writing strtab to PE image file 2022-09-07 22:42:57 +02:00
Jakub Konka
467d69c68a x86_64: fix SystemV calling convention 2022-09-07 22:42:57 +02:00
Jakub Konka
56a131d27a test-cases: fix compiler error locations for hello world with updates 2022-09-07 22:42:57 +02:00
Jakub Konka
66bad3eaaf coff: mark relocations dirty when target atoms change 2022-09-07 22:42:57 +02:00
Jakub Konka
1e2a2d6fad coff: fix bug in lowerUnnamedConst 2022-09-07 22:42:57 +02:00
Jakub Konka
423f424c27 libstd: use windows.GetStdHandle() with stage2_x86_64 backend for now 2022-09-07 22:42:57 +02:00
Jakub Konka
e0167ae0e3 x86_64: allow for any index register in complex SIB encodings
This relieves register pressure, and reduce generated code size
(since now we can use the same index register for both `mov_scale_src`
and `mov_scale_dst` MIR instructions).

Fix lowering of ModRM + SIB encodings where index register is extended
- previously, we would carelessly ignore the fact generating incorrect
encodings.
2022-09-07 22:42:57 +02:00
Jakub Konka
619d82234e x86_64: clean up return registers for unspecified cc 2022-09-07 22:42:57 +02:00
Jakub Konka
28f525baa4 x86_64: handle ptr_stack_offset for blocks 2022-09-07 22:42:56 +02:00
Jakub Konka
1d57b347e9 x86_64: clean up logging 2022-09-07 22:42:56 +02:00
Jakub Konka
b9c31a8703 x86_64: refactor cond_br with canonicaliseBranches helper 2022-09-07 22:42:56 +02:00
Jakub Konka
c0e288c782 x86_64: implement canonicalising branches in switch expression 2022-09-07 22:42:56 +02:00
Jakub Konka
3a4c69c018 x86_64: implement Windows x64 calling convention 2022-09-07 22:42:56 +02:00
Jakub Konka
38573fed0b coff: fix runtime traps 2022-09-07 22:42:56 +02:00
Jakub Konka
49b1716064 coff: implement lowering unnamed consts 2022-09-07 22:42:56 +02:00
Jakub Konka
a19e6adbf9 x86_64: add support for Win64/C calling convention 2022-09-07 22:42:56 +02:00
Jakub Konka
aac4c1d3b2 coff: fix contents of IAT, and ensure codegen loads addr into reg
As far as I can see, unlike with MachO, we don't have any stubs
helper routines available and need to load a bound pointer into
a register to then call it.
2022-09-07 22:42:55 +02:00
Jakub Konka
0ebeb58d91 coff: populate import address table dir 2022-09-07 22:42:55 +02:00
Jakub Konka
1ab149c5fc coff: create import atoms and matching bindings 2022-09-07 22:42:55 +02:00
Jakub Konka
51fba37af7 coff: add relocation for call_extern 2022-09-07 22:42:55 +02:00
Jakub Konka
a35f156cf6 coff: re-enable default entrypoint for Windows 2022-09-07 22:42:55 +02:00
Jakub Konka
11d14a23a3 win-ci: add missing ZIGPREFIXPATH variable def 2022-09-07 22:21:12 +02:00
Luuk de Gram
a8d137d05a wasm-linker: support incremental debug info
Although the wasm-linker previously already supported
debug information in incremental-mode, this was no longer
working as-is with the addition of supporting object-file-parsed
debug information. This commit implements the Zig-created debug information
structure from scratch which is a lot more robust and also allows
being linked with debug information from other object files.
2022-09-07 18:59:36 +02:00
Luuk de Gram
971327d6e0 wasm: fix memory leak 2022-09-07 18:53:16 +02:00
Luuk de Gram
f2c8d09c4f wasm-linker: Mix Zig -and Object debug atoms
When linking a Zig-compilation with an object file,
we allow mixing the debug atoms to make sure debug
information is preserved from object files. By default,
we now always initialize all debug sections if the `strip` flag
is unset.

This also fixes relocations for debug information as previously
the offset of an atom wasn't calculated, and neither was the code
size itself which meant that debug lines were off and file names
from other object files were missing.
2022-09-07 18:53:16 +02:00
Luuk de Gram
b2718e213e wasm-linker: use Atoms for zig debug info
Previously we used single arraylists for each debug section for debug
information that was generated from Zig code. (e.i. `Module` is available).
This information is now stored in Atoms, similarly to debug information
from object files. This will allow us to link them together and resolve
debug relocations.
2022-09-07 18:53:16 +02:00
Luuk de Gram
46c932a2c9 wasm-linker: perform debug relocations
This correctly performs a relocation for debug sections.
The result is that the wasm-linker can now correctly create
a binary from object files while preserving all debug information.
2022-09-07 18:53:16 +02:00
Luuk de Gram
c347751338 wasm-linker: write debug sections from objects
We now link relocatable debug sections with the correct
section symbol and then allocate and resolve the debug atoms
before writing them into the final binary.

Although this does perform the relocation, the actual relocations
are not done correctly yet.
2022-09-07 18:53:16 +02:00
Luuk de Gram
f060edb0f3 wasm-linker: create atoms from debug sections 2022-09-07 18:53:16 +02:00
Luuk de Gram
9a92f3d290 wasm/Object: parse debug sections into reloc data
Rather than storing the name of a debug section into the structure
`RelocatableData`, we use the `index` field as an offset into the
debug names table. This means we do not have to store an extra 16 bytes
for non-debug sections which can be massive for object files where each
data symbol has its own data section. The name of a debug section
can then be retrieved again when needed by using the offset and
then reading until the 0-delimiter.
2022-09-07 18:53:12 +02:00
Dan Ellis Echavarria
924679abc4 std.simd: change T to u16
The `element_bit_size` would break if `T` was signed due to `ceilPowerOfTwo` only working on unsigned numbers.
2022-09-07 15:22:30 +03:00
bfredl
e02b9f458d build-exe: allow combination of -fno-emit-bin and --verbose-air
Currently, `zig build-exe -fno-emit-bin --verbose-air src/main.zig`
results in no output at all. With this refactor, it dumps AIR
and then exits without invoking LLVM, as expected
2022-09-07 14:53:31 +03:00
Evan Haas
e283a40d17 translate-c: convert tabs to \t in object-like macro string literals
Closes #12549
2022-09-07 14:46:58 +03:00
Andrew Kelley
b7900de168 Merge remote-tracking branch 'origin/master' into llvm15 2022-09-06 19:45:02 -07:00
Loris Cro
e2bb92b2e2 Merge pull request #12736 from alichraghi/patch-2
autodoc: fix highlighted line in light mode
2022-09-05 17:37:12 +02:00
Loris Cro
201dca323e autodoc: improve rendering of long fn signatures 2022-09-05 17:26:59 +02:00
Loris Cro
3deb33fffa Merge pull request #12738 from der-teufel-programming/autodoc-opaque-types
autodoc: Opaque now handled like other container types
2022-09-04 22:51:03 +02:00
Der Teufel
b8001335c4 autodoc: Opaque now handled like other container types 2022-09-04 22:47:58 +02:00
Loris Cro
dbd60e3d29 autodoc: add support for doc tests 2022-09-04 22:45:57 +02:00
Veikka Tuominen
9ce841a0f0 stage2 llvm: implement aarch64 C ABI
... at least enough to pass all the current tests.
2022-09-04 18:46:56 +03:00
Yujiri
ae3a5ff7f9 Fix #12440: std.math.big.Rational order/orderAbs 2022-09-04 18:45:20 +03:00
riChar
349cf54b32 llvm: fix the type parameter of GlobalAlias
Closes 12680
2022-09-04 18:44:45 +03:00
Ali Chraghi
5b3ca4bb53 autodoc: fix highlighted line in light mode 2022-09-04 14:13:47 +04:30
Veikka Tuominen
b7d5582ded Merge pull request #12723 from Vexu/stage2-fixes
Stage2 fixes
2022-09-03 15:48:28 +03:00
Veikka Tuominen
c7884af063 translate-c: do not translate packed C structs as packed Zig structs in stage2
Zig's integer backed packed structs are not compatible with C's packed structs.
2022-09-03 03:42:42 +03:00
Veikka Tuominen
0f61d1f0df stage2 llvm: improve handling of i128 on Windows C ABI 2022-09-03 03:42:42 +03:00
Veikka Tuominen
b83c037f9f Sema: only ABI sized packed structs are extern compatible 2022-09-03 01:04:46 +03:00
yujiri8
10e11b60e5 zig fmt: don't delete container doc comments
Fixes #12617
2022-09-02 20:12:20 +02:00
Veikka Tuominen
6aee07c144 Sema: remove unused src param from typeRequiresComptime 2022-09-02 19:49:11 +03:00
Loris Cro
4a08c6dd51 autodoc: fix stage2 compile error 2022-09-02 18:13:17 +02:00
Loris Cro
e72a8ed5a1 autodoc: fix merge mistake 2022-09-02 17:59:37 +02:00
Loris Cro
907c60aaa7 Merge pull request #12705 from der-teufel-programming/autodoc-big-int
Autodoc big_int
2022-09-02 17:48:17 +02:00
Loris Cro
a77d7b740f autodoc: simplify int_big json stringify procedure 2022-09-02 17:47:04 +02:00
Loris Cro
70b96169ae Merge pull request #12709 from der-teufel-programming/autodoc-compare-operators
autodoc: Compare operators
2022-09-02 17:38:00 +02:00
Loris Cro
0b11d8ec4d codeowners: mark myself as the codeowner of /src/autodoc/ 2022-09-02 17:35:41 +02:00
Loris Cro
081d5a9690 autodoc: correct line number implementation
we also correctly take advantage of the starting byte offset of the
parent decl when calling `tree.tokenLocation()`!
2022-09-02 17:28:12 +02:00
Veikka Tuominen
f281f3d10e Sema: improve behavior of comptime_int backed enums 2022-09-02 17:57:11 +03:00
Veikka Tuominen
a9cdacff95 Sema: add error for enum tag value overflow
Closes #12291
2022-09-02 17:57:11 +03:00
Veikka Tuominen
7a51e0befe Sema: fix noalias coercion error message
Closes #11769
2022-09-02 17:57:11 +03:00
Veikka Tuominen
1c4c68e6ba AstGen: use reachableExpr for try operand
Closes #12248
2022-09-02 17:57:10 +03:00
Veikka Tuominen
db54cd247d Sema: do not emit dbg_inline_end after NoReturn
Closes #12698
2022-09-02 17:57:10 +03:00
Veikka Tuominen
8b58dab78b Sema: resolve lazy value before intToFloat
Closes #12698
2022-09-02 17:57:10 +03:00
Veikka Tuominen
7a8d9af4a9 stage2 llvm: correct handling of zero-bit types in unionFieldPtr
Pointers to zero-bit types are not zero-bit types so the function should
return something.
Closes #12716
2022-09-02 17:57:10 +03:00
Veikka Tuominen
4462d08224 stage2 llvm: fix passing packed structs to callconv(.C) functions
Closes #12704
2022-09-02 17:57:10 +03:00
Loris Cro
5581b60393 Merge pull request #12724 from alichraghi/patch-2
autodoc: highlight target line
2022-09-02 16:49:56 +02:00
Ali Chraghi
30e85c9c80 autodoc: highlight target line 2022-09-02 19:11:34 +04:30
riChar
f7784a081f stage2: fix panic when the dependency is missing 2022-09-02 12:53:48 +03:00
riChar
0d96f1f4fb zig fmt: remove trailing comma at the end of assembly clobber 2022-09-02 12:52:33 +03:00
Der Teufel
4c033eb35c autodoc: int_big cleanup 2022-09-02 11:01:46 +02:00
Der Teufel
0d3c6b7aa8 autodoc: Added int_big support 2022-09-02 11:01:46 +02:00
John Schmidt
36f4f32fad Add AFNOSUPPORT error to bind (#12560) 2022-09-01 15:13:07 -05:00
Andrew Kelley
7c91a6fe48 CI: fix CLI usage of s3cmd regarding mime types for autodocs 2022-09-01 12:57:06 -07:00
Der Teufel
3bbf08e98a autodoc: Compare operators 2022-09-01 15:17:14 +02:00
Veikka Tuominen
2cd3989cb3 Sema: add more validation to coerceVarArgParam
Closes #12706
2022-09-01 13:16:33 +03:00
Jason Ho
2b92c5a23e langref: tweak description of []T (#12319)
saying []T is a pointer is confusing because zig docs say there are two types of pointers (*T and [*]T). It is more clear to say that []T is a slice type which contains a [*]T pointer and a length.

Co-authored-by: Philipp Lühmann <47984692+luehmann@users.noreply.github.com>
2022-08-31 21:53:00 -04:00
Andrew Kelley
7a733b9385 CI: macos: skip non native
We already test cross compiling on x86_64-linux; no need to additionally
test it in the macOS script.
2022-08-31 16:07:08 -07:00
Andrew Kelley
77f31ebbbe CI: fix content type of autodocs source listings 2022-08-31 15:27:09 -07:00
Andrew Kelley
368a20a051 CI: include source listings for autodocs 2022-08-31 14:22:01 -07:00
Andrew Kelley
c5f1b3224f CI: update_download_page: change docs deployment
The original impetus for making a change here was a typo in --add-header
causing the script to fail. However, upon inspection, I was alarmed that
we were making a --recursive upload to the *root directory* of
ziglang.org. This could result in garbage files being uploaded to the
website, or important files being overwritten. As I addressed this concern,
I decided to take on file compression as well.

Removed compression prior to sending to S3. I am vetoing pre-compressing
objects for the following reasons:
 * It prevents clients from working which do not support gzip encoding.
 * It breaks a premise that objects on S3 are stored 1-to-1 with what is
   on disk.
 * It prevents Cloudflare from using a more efficient encoding, such as
   brotli, which they have started doing recently.

These systems such as Cloudflare or Fastly already do compression on
the fly, and we should interop with these systems instead of fighting them.

Cloudfront has an arbitrary limit of 9.5 MiB for auto-compression. I looked
and did not see a way to increase this limit. The data.js file is currently
16 MiB. In order to fix this problem, we need to do one of the following things:

 * Reduce the size of data.js to less than 9.5 MiB.
 * Figure out how to adjust the Cloudfront settings to increase the max size
   for auto-compressed objects.
 * Migrate to Fastly. Fastly appears to not have this limitation. Note
   that we already plan to migrate to Fastly for the website.
2022-08-31 13:15:42 -07:00
Andrew Kelley
9a0cb34c73 CI: namespace manifest json files to avoid clobbering 2022-08-31 13:15:21 -07:00
Andrew Kelley
36ad0abd7a CI: drone: avoid notify_lavahut task for PRs 2022-08-31 13:14:51 -07:00
Jakub Konka
540d8cd809 coff: add import table definitions 2022-08-31 19:30:51 +02:00
Veikka Tuominen
26e9839132 disable test for non-llvm backends
Follow up to fdb8870852
2022-08-31 16:46:51 +03:00
Hashi364
973b440561 Using comptime level.asText() in log example
Some recent change makes slice concatenation runtime (merge #12368), so the example needs to be explicitly made comptime.
2022-08-31 16:01:35 +03:00
Evan Haas
fdb8870852 translate-c: promote large integer macros to unsigned long long if necessary
Closes #10793

Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-08-31 15:52:53 +03:00
Jakub Konka
b45387f20e coff: write base relocations for the dynamic linker
This means we can request ASLR on by default as other COFF linkers
do. Currently, we write the base relocations in bulk, however,
given that there is a mechanism for padding in place in PE/COFF
I believe there might be room for making it an incremental operation
(write base relocation whenever we add/update a pointer that would
require it).
2022-08-31 14:39:35 +02:00
Luuk de Gram
4ba0ad295f Merge pull request #12687 from Luukdegram/wasm-extern-globals
wasm-linker: implement non-function extern variables
2022-08-31 13:44:06 +02:00
Andrew Kelley
9f9e51eb11 CI: drone: disable failing tests
See tracking issue #12689
2022-08-30 22:55:30 -07:00
biexelar
59e33b447b std.Thread: fix freeAndExit on x86_64-linux (#12693)
Previously, this function used incorrect registers for the munmap syscall, leading to detached threads not cleaning up.

closes #12690

Co-authored-by: bxlr <biexelar@diroot.org>
2022-08-30 22:31:47 -04:00
Andrew Kelley
20145016ac Merge remote-tracking branch 'origin/master' into llvm15 2022-08-30 19:12:05 -07:00
Andrew Kelley
ea4ef832e3 fix llvm 15 translate-c regressions
by inserting explicit casts.

closes #12682
2022-08-30 19:11:31 -07:00
Andrew Kelley
56cfa8f22f Sema: prevent access of undefined fields
When instantiating a generic function, there is a period of time where
the function is inserted into monomorphed_funcs map, but is not yet
initialized. Despite semantic analysis being single-threaded, generic
function instantiation can happen recursively, meaning that the hash
and equality functions for monomorphed_funcs entries are potentially
invoked for an uninitialized function.

This problem was mitigated by pre-setting the hash field on the newly
allocated function, however it did not solve the problem for hash
collisions in which case the equality function would be invoked. That it
was solved for hash() but not eql() explains why the problem was
difficult to observe. I tested this patch by temporarily sabotaging the
hash and making it always return 0.

This fix is centered on adding a new field to Module.Fn which is the one
checked by eql() and is populated pre-initialization.

closes #12643
2022-08-30 18:34:08 -07:00
Andrew Kelley
35e0ff7c36 CI: drone: disable failing tests
See tracking issue #12689
2022-08-30 15:01:05 -07:00
Andrew Kelley
fb81ba8762 LLVM: fix extern functions missing attributes
Extern functions were missing attributes such as "readonly" on
non-optional pointers, and "byval" which is required to match C ABI.

Follow-up from bf28765a97.

closes #12683
2022-08-30 14:45:03 -07:00
Jakub Konka
d3eaabd285 coff: add base relocation related types 2022-08-30 23:07:28 +02:00
Andrew Kelley
1e21876de2 Merge remote-tracking branch 'origin/master' into llvm15 2022-08-30 13:02:43 -07:00
Andrew Kelley
f559ea95b1 Merge pull request #12686 from Vexu/stage2-fixes
Stage2 fixes
2022-08-30 15:55:05 -04:00
Andrew Kelley
7377dce368 avoid exposing supportsTailCall in the standard library
This is problematic because in practice it depends on whether the
compiler backend supports it too, as evidenced by the TODO comment about
LLVM not supporting some architectures that in fact do support tail
calls.

Instead this logic is organized strategically in src/target.zig, part of
the internal compiler source code, and the behavior tests in question
duplicate some logic for deciding whether to proceed with the test.

The proper place to expose this flag is in `@import("builtin")` - the
generated source file - so that third party compilers can advertise
whether they support tail calls.
2022-08-30 12:50:15 -07:00
Veikka Tuominen
65d3723968 Sema: check that target supports tail calls 2022-08-30 12:22:07 -07:00
Veikka Tuominen
c558de6655 stage2 llvm: use tag value instead of field index in airUnionInit
Closes #12656
2022-08-30 12:22:07 -07:00
Veikka Tuominen
d3b4b2edf1 Sema: shift of comptime int with runtime value
Closes #12290
2022-08-30 12:22:07 -07:00
Veikka Tuominen
01d19a8d3c Sema: do not emit generic poison for non generic parameters
Closes #12679
2022-08-30 12:22:07 -07:00
Veikka Tuominen
67a44211f7 Sema: improve handling of always_tail call modifier
Closes #4301
Closes #5692
Closes #6281
Closes #10786
Closes #11149
Closes #11776
2022-08-30 12:22:07 -07:00
Andrew Kelley
0a42602418 CI: drone: disable failing tests
See tracking issue #12689
2022-08-30 12:02:26 -07:00
Luuk de Gram
8627858bbc test/link: add test for extern resolution
Adds a linker tests to verify extern/undefined symbols
representing non-functions are being resolved correctly.
2022-08-30 18:32:08 +02:00
Luuk de Gram
4f72ac265a wasm: create relocations for extern decls
This also fixes performing relocations for data symbols
of which the target symbol exists in an external object file.
We do this by checking if the target symbol was discarded,
and if so: get the new location so that we can find the
corresponding atom that belongs to said new location. Previously
it would always assume the symbol would live in the same file
as the atom/symbol that is doing the relocation.
2022-08-30 16:38:55 +02:00
Luuk de Gram
414fcea162 link/Wasm: handle extern variables
Generate symbols for extern variables and try to resolve them.
Unresolved 'data' symbols generate an error as they cannot be
exported from the Wasm runtime into a Wasm module. This means,
they can only be resolved by other object files such as from other
Zig or C code compiled to Wasm.
2022-08-30 16:38:51 +02:00
Jakub Konka
aa5568beb6 coff: move Symtab and Strtab out of coff.Coff
This should ease interfacing with different std.coff functionalities.
2022-08-30 15:51:49 +02:00
Jakub Konka
7ef0c9d298 Merge pull request #12677 from ziglang/coff-linker
coff: initial rewrite of the COFF/PE linker
2022-08-30 14:29:41 +02:00
Jakub Konka
b64e4c5bf2 fix aarch64-macos CI build script 2022-08-30 14:29:06 +02:00
Jakub Konka
69d6931be7 Merge pull request #12662 from wsengir/coff-fix
coff: fix reading COFF header offset
2022-08-30 12:26:35 +02:00
Veikka Tuominen
e6be6d9768 std.rand: make weightedIndex proportions param a const slice
The function does not mutate the proportions and the signature should reflect that.
2022-08-30 13:02:17 +03:00
Jakub Konka
e57fbe8069 test-cases: fix compiler error locations for hello world with updates 2022-08-30 11:01:08 +02:00
Jakub Konka
241e1ac030 cmake: add runaway Coff/Object.zig path 2022-08-30 10:42:21 +02:00
Jakub Konka
601f2147e0 coff: cleanup relocations; remove COFF support from other backends
Given that COFF will want to support PIC from ground-up, there is no
point in leaving outdated code for COFF in other backends such as
arm or aarch64. Instead, when we are ready to look into those, we
can start figuring out what to add and where.
2022-08-30 10:42:21 +02:00
Jakub Konka
ebdb286736 coff: commit missing Object.zig placeholder 2022-08-30 10:42:21 +02:00
Jakub Konka
f0d4ce4494 coff: add basic handling of GOT PC relative indirection 2022-08-30 10:42:21 +02:00
Jakub Konka
db1a3bb0e7 coff: fallback to _start as default entry point for now
This is not technically correct, but given that we are not yet able
to link against the CRT, it's a good default until then.

Add basic logging of generated symbol table in the linker.
2022-08-30 10:42:21 +02:00
Jakub Konka
b4e3b87a52 coff: ...and lift-off! 2022-08-30 10:42:21 +02:00
Jakub Konka
30baba899c coff: add missing bits required for minimal PE example 2022-08-30 10:42:21 +02:00
Jakub Konka
e5b8a1ac27 coff: allocate and write atoms to file 2022-08-30 10:42:21 +02:00
Jakub Konka
2a994ba4a7 coff: populate missing section metadata 2022-08-30 10:42:21 +02:00
Jakub Konka
f36029a385 coff: add helpers for setting section/symbol names 2022-08-30 10:42:21 +02:00
Jakub Konka
ff0abad2a9 coff: allow for strtab in final PE image
I believe this is going to be vital for section headers having names
that require the use of a string table.
2022-08-30 10:42:21 +02:00
Jakub Konka
3aa99f45b8 coff: initial implementation of incremental file allocs 2022-08-30 10:42:21 +02:00
Jakub Konka
da00e6dd59 coff: always write all data directory headers to file
Maximum number is always 16, and this also unbreaks `dumpbin.exe`
run on a simple section-less PE image created with our linker.
2022-08-30 10:42:21 +02:00
Jakub Konka
9fc6933418 coff: write data directory and section headers to file 2022-08-30 10:42:21 +02:00
Jakub Konka
93127a615b coff: set some defaults for PE headers 2022-08-30 10:42:21 +02:00
Jakub Konka
ed481e3837 coff: write headers to file 2022-08-30 10:42:21 +02:00
Jakub Konka
90b3599c68 coff: reorganize the linker 2022-08-30 10:42:21 +02:00
Jakub Konka
580bfe01c8 coff: fix after rebase 2022-08-30 10:42:21 +02:00
Jakub Konka
3c10221030 coff: move header writing logic into flush 2022-08-30 10:42:21 +02:00
Jakub Konka
06371950cf start: allow for explicitly defined entry point for Win 2022-08-30 10:42:21 +02:00
Andrew Kelley
527055a821 CI: use absolute path for zig lib dir
Workaround for #12685
2022-08-30 00:33:21 -07:00
Andrew Kelley
75d5a4b9a2 CI: pass explicit zig lib dir in lots of places
see #12684 for motivation
2022-08-29 23:37:31 -07:00
Andrew Kelley
6f9b7c8cee make 'zig build' respect ZIG_LIB_DIR
follow-up to 56bdd0127f
2022-08-29 23:35:07 -07:00
Andrew Kelley
1cb8065a52 skip new behavior tests that do not pass for stage1 2022-08-29 22:58:24 -07:00
Andrew Kelley
3c506c8aaa disable tests failing due to LLVM 15 regressions 2022-08-29 22:58:24 -07:00
Meghan
56bdd0127f implement cache environment variables for zig build 2022-08-29 22:26:41 -04:00
Andrew Kelley
bf28765a97 LLVM: upgrade byval attr code to LLVM 15 opaque pointers
Follow-up from 74673b7f69.
2022-08-29 18:19:39 -07:00
Luuk de Gram
fffece1533 wasm-lld: set stack size to 1MB by default
Regardless of the build mode (build-exe, build-lib), always
set the default stack size to 1MB. Previously, this was only
done when using build-exe, making the inconsistancy confusing.
The user can still override this behavior by providing the
`--stack <size>` flag.
2022-08-29 18:23:14 -04:00
Andrew Kelley
d2d42cf7ba Merge pull request #12641 from Luukdegram/wasm-c-types
stage2: fix size of c_longdouble for Wasm target
2022-08-29 18:21:38 -04:00
Andrew Kelley
f52ee1607a Merge remote-tracking branch 'origin/master' into llvm15 2022-08-29 15:19:19 -07:00
Andrew Kelley
d841d2c27e update C headers to LLVM 15 rc3 2022-08-29 15:14:58 -07:00
Andrew Kelley
e6ccc93aac update libcxx to LLVM 15 rc3 2022-08-29 15:12:46 -07:00
Andrew Kelley
b5dc8b67bc LLVM: update merged master branch code to opaque pointers 2022-08-29 15:00:31 -07:00
Andrew Kelley
e8edc4cf83 link: add force_undefined_symbols to cache hash
Follow-up for d5233ee85c.
2022-08-29 14:52:18 -07:00
Andrew Kelley
de7270028d Merge remote-tracking branch 'origin/master' into llvm15 2022-08-29 14:10:59 -07:00
Andrew Kelley
e69973bedd Merge pull request #12508 from ziglang/cmake-stage3
cmake: build stage3 by default
2022-08-29 16:52:36 -04:00
Andrew Kelley
9cca6728e5 Merge pull request #12663 from Vexu/stage2-fixes
Stage2 fixes
2022-08-29 16:46:51 -04:00
Veikka Tuominen
a4b52ccd9f Sema: fix access of inactive union field when enum and union fields are in different order
Closes #12667
2022-08-29 13:45:37 -07:00
Andrew Kelley
532cfb65e0 CI: rework to account for new cmake behavior
* CMakeLists: pass `-Dstrip` for release zig builds
 * pass -target and -mcpu to zig1. works around llvm on freebsd
   incorrectly detecting "freestanding" instead of "freebsd" for the
   native OS.
 * ci.ziglang.org is now responsible for creating aarch64-macos tarballs
   rather than Azure.
2022-08-28 17:07:21 -07:00
Andrew Kelley
aee53e2ffd CMake: add dummy install command
This makes it so that `ninja install` will work as expected.
2022-08-28 17:07:21 -07:00
Andrew Kelley
3d9b6cfcc9 stage2: add an explicit padding field to avoid Valgrind warning
Adds a `unused: u32 = 0` field to `Zir.Header`.

We could leave this as padding, however it triggers a Valgrind warning because
we read and write undefined bytes to the file system. This is harmless, but
it's essentially free to have a zero field here and makes the warning go away,
making it more likely that following Valgrind warnings will be taken seriously.
2022-08-28 17:07:21 -07:00
Andrew Kelley
56129d26eb cmake: build stage3 by default
This is a simplification of the cmake build script which introduces a
new "stage3" target that is built by default, which builds and installs
a stage3 zig.

It greatly simplifies the build instructions for Zig, making it conform
to the regular cmake routine, while still producing a stage3 artifact.
2022-08-28 17:07:21 -07:00
Luuk de Gram
1eb22e7ad6 wasm: skip unimplemented behavior test
Since now the size of a c_longdouble is correctly 16 bytes,
the test is no longer passing. It was previously accidentally passing
due to incorrect sizing and it not being larger than the size
of a f64.

disable long_double test for windows
2022-08-28 17:50:07 +02:00
William Sengir
91b9f295d3 coff: publicize and flesh out more image constants 2022-08-28 06:20:18 -07:00
Veikka Tuominen
15cc4514e0 Sema: add missing calls to resolveStructLayout
Closes #12645
2022-08-28 15:41:21 +03:00
Veikka Tuominen
e2dc77ab62 Sema: correct one possible value for tuples
Closes #12376
2022-08-28 15:41:21 +03:00
Veikka Tuominen
776caaf999 Sema: fix handling of non-standard int types in empty non-exhaustive enums
Closes #12649
2022-08-28 15:41:21 +03:00
Veikka Tuominen
6aead18ab3 add error tests for now correctly behaving cases
Closes #6377
2022-08-28 15:41:21 +03:00
Veikka Tuominen
1401890ed5 Sema: add error for switch on slice
Closes #12651
2022-08-28 15:41:21 +03:00
Veikka Tuominen
fc213e2d61 AstGen: add error for named function type
Closes #12660
2022-08-28 15:41:21 +03:00
Justin Whear
5bb8c03697 std.random: add weightedIndex function
`weightedIndex` picks from a selection of weighted indices.
2022-08-28 14:19:51 +03:00
William Sengir
3860e664c5 coff: fix reading COFF header offset 2022-08-28 03:10:39 -07:00
Loris Cro
0f27836c21 ci: fix wrong path when deploying stdlib docs 2022-08-28 01:20:38 +02:00
Loris Cro
e0103704c5 autodoc: better line counting for decls 2022-08-27 22:48:18 +02:00
Henrique Dante de Almeida
ee12264387 docs: Remove mention of type inference on anytype struct fields
It was removed from the language.
2022-08-27 20:34:13 +02:00
antlilja
ae8d26a6a0 Sema: add error for non-comptime param in comptime func
Adds error for taking a non comptime parameter in a function returning a
comptime-only type but not when that type is dependent on a parameter.

Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-08-27 11:17:48 +03:00
David Gonzalez Martin
da95da438e Add behavior test coverage for nested packed struct field access
Closes #3091
2022-08-26 21:43:38 -04:00
Luuk de Gram
91dba79c48 wasm: fix abi size of c_longdouble
According to https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md
the size of c's long double is 16 bytes for Wasm, rather than 8 bytes
which was the value previously in the compiler. This ensures
we not only pass the correct value, but also creates the correct
function signature needed to pass the Wasm validator.

This also adds an additional test case in c_abi tests.
2022-08-26 21:01:05 +02:00
Sébastien Marie
8bcb962ada openbsd: fix sigcontext struct and avoid defining fxsave64
`sc_fpstate` member of `struct sigcontext` is a `struct fxsave64 *`.
use *anyopaque to represent it.

avoid to defining `fxsave64` as it is a packed struct with some arrays.
2022-08-26 17:30:07 +02:00
Loris Cro
2e0ff6c700 Merge pull request #12600 from ominitay/autodocs-errorset
autodocs: improve error set rendering
2022-08-26 16:36:06 +02:00
Loris Cro
a69a16c6bd Merge pull request #12601 from ominitay/autodocs-shortdesc
autodocs: improve first-line descriptions
2022-08-26 16:35:00 +02:00
Jakub Konka
02e6960966 coff: do not pull in std.log into coff.zig definitions 2022-08-26 16:14:44 +02:00
9038528187 copy_file_range: fix zigification of TXTBSY
From `copy_file_range(2)` errors:

    ETXTBSY
           Either fd_in or fd_out refers to an active swap file.

Same error will be used in the upcoming `ioctl_ficlonerange(2)`:

    ETXTBSY
           One of the files is a swap file.  Swap files cannot share storage.
2022-08-26 15:36:40 +03:00
martinhath
3fa5415253 Sema: ensure resolveTypeFields is called for optional and error union types
We call `sema.resolveTypeFields` in order to get the fields of structs
and unions inserted into their data structures. If it isn't called, it
can happen that the fields of a type is queried before those fields are
inserted into (for instance) `Module.Union.fields`, which would result in
a wrong 'no field named' error.

Fixes: #12486
2022-08-26 11:37:17 +03:00
Evan Haas
bcaa9df5b4 translate-c: Don't add self-defined macros to global name table
A self-defined macro is one of the form `#define FOO FOO`

Those types of macros have never been translated; this change will cause
any macros which refer to them to be translated as `@compileError` instead
of referring to a non-existent identifier.

Closes #12471
2022-08-26 11:24:57 +03:00
David Gonzalez Martin
d6bb9af18d stage2: Reference to void constants
Closes #7567
2022-08-26 00:00:22 -04:00
Andrew Kelley
aa4544963c Merge pull request #12629 from motiejus/libresolv-abilists
glibc/abilists: add libresolv stubs
2022-08-25 23:33:59 -04:00
Andrew Kelley
d2ad8afff4 LLVM: fix missing alignment on wrapping instructions
Previously, when lowering AIR instructions `wrap_errunion_payload`,
`wrap_errunion_err`, and `wrap_optional`, the LLVM backend would create
an alloca instruction to store the result, but did not set the alignment
on it. This caused UB which went undetected for a long time until we
started enabling the stack protector.

Closes #12594
Unblocks #12508
Inspires #12634

Tests passed locally:
 * test-behavior
 * test-cases
2022-08-25 16:15:48 -07:00
Andrew Kelley
9d231c4991 CI: drone: reduce duration of the bottleneck
Empirically, the ReleaseSmall std lib tsets take about 55 minutes on the
CI, and is the bottleneck causing timeouts. So this commit disables full
coverage in favor of running a smaller set of ReleaseSmall std lib tests.
2022-08-25 15:23:01 -07:00
Jakub Konka
d5233ee85c add ability to pass force undefined symbols to the linker
This commit enables `-u <symbol>` for ELF and `-include:<symbol>` for
COFF linkers for use internally. This means we do not expose these
flags to the users just yet, however, we make use of them internally
whenever required. One such use case is forcing inclusion of
`_tls_index` when linking for Windows with mingw and LTO and dead
code stripping enabled. This ensures we add `_tls_index` to the symbol
resolver as an undefined symbol and force the linker to include an atom
that provides it marking it a dead-code-stripping root - meaning it will
not be garbage collected by the linker no matter what.
2022-08-25 16:23:01 -04:00
Jakub Konka
ba346ecfe9 run_translated_c: disable failing test on Windows
ziglang/zig#12630
2022-08-25 17:01:49 +02:00
Motiejus Jakštys
29e90efbb1 src/glibc: remove redundant Arch
abilists now use Zig's arch, no need for a separate one.
2022-08-25 16:46:32 +03:00
Motiejus Jakštys
ea785f70ef glibc/abilists: add libresolv stubs
Generated with https://github.com/ziglang/glibc-abi-tool/pull/2

Fixes #12628
2022-08-25 16:36:10 +03:00
Veikka Tuominen
4405188cf7 Sema: ignore comptime params in partial func type check
This fixes a bug exposed by cd1833044a
where a function type would be converted to generic_poison even after
being instantiated due to containing comptime only types.

This could also be fixed by just checking `is_generic_instantiation`
but this way also provides better type names.

Closes #12625
2022-08-25 16:29:23 +03:00
Andrew Kelley
3a7ea0b65e fix order of CLI args passed to clang
Commit eb3f7d2f37 changed the order of CLI
args passed to clang, making object-specific "extra flags" passed first.
However, these are supposed to be able to override other flags, and this
behavior is exploited by workarounds in mingw.zig to disable LTO.

This commit rectifies the situation by moving extra flags back to being
passed after the call to addCCArgs().
2022-08-25 03:10:41 -07:00
Andrew Kelley
7453f56e67 stage2: explicitly tagged enums no longer have one possible value
Previously, Zig had inconsistent semantics for an enum like this:

`enum(u8){zero = 0}`

Although in theory this can only hold one possible value, the tag
`zero`, Zig no longer will treat the type this way. It will do loads and
stores, as if the type has runtime bits.

Closes #12619

Tests passed locally:
 * test-behavior
 * test-cases
2022-08-24 22:20:31 -07:00
Andrew Kelley
af19909b9c stage2: fix generic function cleanup
When removing generic function instantiations from monomorphed_funcs, we
need to first make sure the function is generic, otherwise the hash map
tries to access the `hash` field of the function which is undefined.

closes #12614
2022-08-24 16:47:58 -07:00
Andrew Kelley
f4980a4800 CI: windows: update tarball
needed because of some changes to std.dwarf
2022-08-24 16:18:42 -07:00
Andrew Kelley
a9af472728 Compilation: move comptime condition first
Avoids compile error on Windows due to not having execv capabilities.

Fixup for eb3f7d2f37.

See #6768
2022-08-24 15:19:31 -07:00
Jonas Gollenz
07afd5bdba docs: remove confusion about align[For|Back]ward 2022-08-24 17:18:29 -04:00
max
d8e22fcb20 fix coff.zig with const qualifier convert problem 2022-08-24 22:49:47 +02:00
Sébastien Marie
397099b7ee pthread_key_create: make it build with stage2 2022-08-24 16:35:01 -04:00
Loris Cro
eb3f7d2f37 compilation: avoid pointless caching
When the entire purpose of this compilation is to perform a single zig
cc operation we could "tail call" clang by doing an execve, and any use
of the caching system would actually be problematic since the user is
presumably doing their own caching by using dep file flags.

Fixes #12317
2022-08-24 16:33:01 -04:00
Andrew Kelley
7a881435ed Merge pull request #12623 from Vexu/stage2-fixes
Stage2 fixes
2022-08-24 15:59:46 -04:00
Andrew Kelley
2a96209c40 Merge pull request #12574 from Vexu/remove-bit-op-type-param
stage2+stage1: remove type parameter from bit builtins
2022-08-24 15:57:44 -04:00
Andrew Kelley
80b8294bcc test-stack-traces: restore test coverage
reverts 1ce71c86bf
2022-08-24 12:57:31 -07:00
Andrew Kelley
40c9b13608 CI: x86_64-linux: update tarball
I thought this would be needed for dwarf 4 but I think it's not actually
needed. Anyway the tarball is fresher, might as well use it.
2022-08-24 12:57:31 -07:00
Felix "xq" Queißner
b466f8c817 Enables std.build.TranslateCStep to use stage1/stage2 selectively. Unbreaks projects using stage1 and manual TranslateC 2022-08-24 15:41:27 -04:00
Veikka Tuominen
69a3c4e279 Sema: correctly reset inst_map for analyzeInlineCallArg
Closes #12622
2022-08-24 21:31:02 +03:00
Veikka Tuominen
f49dff64c6 Sema: check one possible value earlier in zirValidateArrayInit
Closes #12566
2022-08-24 21:31:02 +03:00
Veikka Tuominen
1d0b729f28 Sema: fix crash on slice of non-array type
Closes #12621
2022-08-24 21:31:02 +03:00
Veikka Tuominen
cd1833044a Sema: do not construct nested partial function types
Closes #12616
2022-08-24 21:31:02 +03:00
Will Hawkins
5fd5950c92 Doc: Add hyphenation for top-level doc 2022-08-24 20:00:46 +03:00
Veikka Tuominen
d515d37934 AstGen: make root decls relative to beginning of file
Closes #12610
2022-08-24 15:26:49 +03:00
Veikka Tuominen
38215ccc3e stage2: handle int_u64 in elemValueAdvanced
Closes #12599
2022-08-24 15:04:31 +03:00
Felix "xq" Queißner
5696cc8ab6 Adds std.meta.FnPtr for easier stage1/stage2 compatibility 2022-08-24 03:13:44 -04:00
Andrew Kelley
5db80a051f Revert "std.os: add INVALID_SOCKET (#12081)"
This reverts commit 0f01e812ff.

This does not belong in `std.posix`, and it is already provided at
`std.os.windows.ws2_32.INVALID_SOCKET`.

See related issue #5019.
2022-08-23 21:30:23 -07:00
Andrew Kelley
a31b449b55 make LLVM and Clang emit DWARF 4 instead of 5
This reverts 6d679eb2bc and additionally
changes the command line parameters passed to Clang to match.

Clang 14 defaults to DWARFv5 which is an interesting choice. v5 has been
out for 5 years and yet Valgrind does not support it, and apparently
neither does either GDB or LLD, I haven't determined which, but I wasn't
able to use GDB to debug my LLVM-emitted dwarf 5 zig code that was linked
with LLD.

A couple years ago when I was working on the self-hosted ELF linker, I
emitted DWARFv5 but then downgraded to v4 when I realized that third
party tools were stuck in the past. Years later, they still are.

Hopefully, Clang 14's bold move will inspire third party tools to get
their shit together, however, in the meantime, everything's broken, so
we're passing `-gdwarf-4` to clang and instructing LLVM to emit DWARFv4.

Note that Zig's std.debug code *does* support DWARFv5 already as of a
previous commit that I made today.
2022-08-23 21:24:03 -07:00
Andrew Kelley
60722261fa std.debug: DWARFv5 fixes
handle str_offsets_base and addr_base correctly.
handle data16
fix compilation on 32-bit hosts
remove stray debug print statement

closes #12120
2022-08-23 21:11:02 -07:00
yyny
0f01e812ff std.os: add INVALID_SOCKET (#12081)
This constant returns an invalid `socket_t` that can be used as a sentinel
value.
2022-08-23 19:44:42 -05:00
Jakub Konka
d852894dcf skip failing compiler-rt divxf3 tests on Windows 2022-08-23 22:59:11 +02:00
Jakub Konka
abfe21a4fe skip failing f80 behavior tests on Windows 2022-08-23 22:43:19 +02:00
Jakub Konka
f907f74282 coff: fix compile errors in std.debug 2022-08-23 22:01:05 +02:00
Jakub Konka
cf9f6fd7f0 macho: fix compile errors in std.debug 2022-08-23 22:01:05 +02:00
ominitay
b63667dda3 autodocs: improve first-line descriptions 2022-08-23 19:26:54 +01:00
ominitay
e0f8198c2f autodocs: improve error set rendering 2022-08-23 18:08:50 +01:00
Loris Cro
c8d04fea15 Merge pull request #12598 from ziglang/autodoc-anonstruct-wip
Autodoc: anon_init_struct support
2022-08-23 18:50:36 +02:00
Loris Cro
b32e5a14ce autodoc: handle self-referential call+field_type instructions 2022-08-23 18:45:22 +02:00
Loris Cro
0482e8ba9d autodoc: initial support for struct_init_anon 2022-08-23 18:37:29 +02:00
Loris Cro
583175dc1d ci: upload rendered source listings in stdlib docs 2022-08-23 15:59:35 +02:00
Loris Cro
102a6e9e9c Merge pull request #12481 from alichraghi/patch-1
docs: add padding between functions list
2022-08-23 15:48:35 +02:00
Loris Cro
13e502b89b Merge pull request #12502 from squeek502/autodoc-fields-light-mode
autodoc: Fix border color around field docs in light mode
2022-08-23 15:48:01 +02:00
Loris Cro
d635dcacbf Merge pull request #12542 from der-teufel-programming/compileError-input
autodoc: show compileErrors correctly
2022-08-23 15:46:26 +02:00
Loris Cro
8c27e7ed91 Merge pull request #12583 from der-teufel-programming/autodoc-error-set
autodoc: error sets now display all their members
2022-08-23 15:44:13 +02:00
Andrew Kelley
1ce71c86bf std.debug: implement support for DWARFv5 2022-08-23 00:28:45 -07:00
Jakub Konka
c84e5ee878 coff: improve default COFF/PE object parser
We now do not allocate memory for headers and other metadata unless
requested by the caller. Instead, we read-in the entire contents
of the image into memory and operate on pointers and casts wherever
possible. I have a left a TODO to hook up Windows' memory-mapped API
here in-place of standard `readToEndAlloc` which should be more memory
proof on memory constrained hosts.

This commit also supplements our `std.coff` with a lot missing basic
extern structs required to make our COFF linker.
2022-08-23 08:55:04 +02:00
Der Teufel
970268d1f5 autodoc: error sets now display all their members 2022-08-23 08:35:13 +02:00
Andrew Kelley
9043e665a5 add behavior test for copying array of vectors
closes #12026
2022-08-22 18:37:42 -07:00
Ryan Liptak
95c43e20b4 Windows: Fix incorrect output when .pdb file is not found during stack trace
This `pdb.Pdb.init` call can return `error.FileNotFound`, which was previously resulting in:

    Unable to print stack trace: FileNotFound

which also aborts the stack trace printing (so any deeper stack traces are not printed).

It makes more sense to treat it as `MissingDebugInfo` which then gets printed as:

    ???:?:?: 0x7fffa8817033 in ??? (???)

and allows the stack trace to continue printing.

Note: locally, the error.FileNotFound was being triggered for me when looking for kernel32.pdb and ntdll.pdb
2022-08-22 20:51:55 -04:00
Keith Chambers
96737ef499 Dwarf: Added stroffsetsptr support (#12270)
* Added support for stroffsetsptr class in Dwarf stdlib

* Proper initializion of debug_str_offsets in DwarfInfo

* Added missing null initializer to DwarfInfo in Macho

* Added missing is_64 field to getAttrString in DwarfInfo

* Fixed formatting

* Added missing is_64 param to getAttrString

* Added required cast to usize

* Adding missing .debug_str_offsets initialization

* getAttrString now uses the str_offsets_base attr
2022-08-22 20:50:06 -04:00
Andrew Kelley
6d679eb2bc LLVM: update to DWARF version 5
clang-14 uses DWARF 5 as the default. Let's join them.
2022-08-22 16:57:18 -07:00
Andrew Kelley
5d2e9a1244 test harness: don't skip tests
The meaning of this "skip_stage2" flag was intended to mean the
self-hosted backends, not the stage2 frontend. Sorry for the confusion.

closes #12541
2022-08-22 19:50:32 -04:00
Andrew Kelley
dae7aeb337 llvm: add valgrind client request integration for x86_64
closes #12500
2022-08-22 16:04:07 -07:00
Andrew Kelley
7b14d614d9 CI: update windows tarball 2022-08-22 15:55:38 -07:00
Andrew Kelley
ecdd4a9fe8 build system: add flag for -fstack-protector 2022-08-22 15:11:34 -07:00
Andrew Kelley
c955379504 Revert "test_runner: workaround #1923, isolating error traces in tests"
This reverts commit 1a32f2a7f4.

Sorry, this workaround is not welcome. Instead, please solve the actual
issue by doing the accepted behavior in the compiler itself:

> in a catch or else (handling a returned error), if the block does not
> try or return error.xyz, set the index to 0

This also applies to if statements, such as the one that test runner is
doing just above this hack.
2022-08-22 11:46:54 -07:00
Techcable
1a32f2a7f4 test_runner: workaround #1923, isolating error traces in tests
Essentially #1923 means "caught" errors still show up in error return traces.
The correct fix would require the compiler to fix this, but that could affect performance.

For now, simply workaround this issue by clearing the return traces
between tests.

This means that "caught" errors in one test will not show up in the
error traces of other tests.
2022-08-22 14:38:03 +03:00
Veikka Tuominen
8667d6d61e Merge pull request #12563 from Vexu/stage2-fixes
Stage2 fixes
2022-08-22 14:32:31 +03:00
Veikka Tuominen
5404dcdfd8 Sema: fix fieldCallBind on tuples and anon structs
Closes #12573
2022-08-22 14:31:58 +03:00
InKryption
f1999712b0 std.io.Reader: bounded array functions
* Add readIntoBoundedBytes
 * Add readBoundedBytes
2022-08-22 14:07:22 +03:00
Shane Kennedy
cd5a9ba1f4 lagnref: add signed integer repr documentation
Closes #11103
2022-08-22 13:57:51 +03:00
Justas Zabulionis
24d718e7eb std.valgrind.callgrind: fix string type
Fixes the error when using std.vallgrind.callgrind:
error: expected type '[2]u8', found '*const [2:0]u8'
2022-08-22 13:55:00 +03:00
Veikka Tuominen
62ff8871ed stage2+stage1: remove type parameter from bit builtins
Closes #12529
Closes #12511
Closes #6835
2022-08-22 11:19:20 +03:00
Veikka Tuominen
560baf67ce Sema: fix implicit cast from extern fn to fn ptr
Closes #12570
2022-08-22 11:16:36 +03:00
Veikka Tuominen
b0bcd4add2 Sema: allow optional pointers in packed structs
Closes #12572
2022-08-22 11:16:36 +03:00
Veikka Tuominen
74c7782c60 Sema: make orelse with C pointers behave like stage1 for now
Closes #12537
2022-08-22 11:16:36 +03:00
Veikka Tuominen
c1afe57d70 Sema: resolve lazy values in resolveMaybeUndefValIntable
Closes #12512
Closes #12513
2022-08-22 11:16:36 +03:00
Veikka Tuominen
b55a5007fa Sema: fix parameter of type 'T' must be comptime error
Closes #12519
Closes #12505
2022-08-22 11:16:36 +03:00
Veikka Tuominen
b2f02a820f Sema: check for astgen failures in semaStructFields
The struct might be a top level struct in which case it might not have Zir.

Closes #12548
2022-08-22 11:16:36 +03:00
Jakub Konka
6c020cdb76 Merge pull request #12557 from Luukdegram/wasm-archive
wasm-linker: Improve archive linking
2022-08-22 08:38:41 +02:00
John Schmidt
9cf667a21b Enable unexpectedErrno error tracing for stage2 LLVM
Stage2 seems to be able to handle this now.
2022-08-21 23:41:01 +03:00
Luuk de Gram
d4c56804df std: fix EmulatableRunStep
Fixes a compilation error when using the `EmulatableRunStep`
that is being generated from a step directly using `runEmulatable`.
2022-08-21 16:42:11 +02:00
Veikka Tuominen
02070ae26b Merge pull request #12499 from Vexu/explain-why-called-at-comptime
stage2: add note about function call being comptime because of comptime only return type
2022-08-21 17:27:52 +03:00
Veikka Tuominen
20d0018d79 Sema: ignore dbg_block instructions when checking for comptimeness
Closes #12514
2022-08-21 12:53:19 +03:00
Veikka Tuominen
d48af541c7 Sema: handle union and enum field order being different
Closes #12543
2022-08-21 12:51:40 +03:00
Veikka Tuominen
e8102d8738 Sema: add note about function call being comptime because of comptime only return type 2022-08-21 12:24:48 +03:00
Der Teufel
76c9ee9b30 autodoc: Fixed compileError case in exprName 2022-08-21 06:32:26 +02:00
Der Teufel
a022157956 autodoc: compileError now uses index into exprs instead of a []const u8 2022-08-21 05:29:39 +02:00
Jakub Konka
4a98385b0a macho: do not leave file descriptors open if unused
This manifested in different `AccessDenied` errors on Windows when
trying to do an atomic file copying in the compiler/linker.
2022-08-20 19:41:23 +02:00
Luuk de Gram
7fe2a3d104 test/link: add wasm linker-test for archives
Adds a test case that will pull-in compiler-rt symbols,
and therefore link with the compiler-rt archive file.
2022-08-20 15:46:39 +02:00
Luuk de Gram
1544625df3 wasm/Object: parse using the correct file size
When an object file is being parsed from within an archive
file, we provide the object file size to ensure we do not
read past the object file. This is because follow up object
files can exist there, as well as an LF character to notate
the end of the file was reached. Such a character is invalid
within the object file.

This also fixes a bug in getting the function/global type
for defined globals/functions from object files as it was missing
the substraction with the import count of the respective type.
2022-08-20 14:50:11 +02:00
Luuk de Gram
aca911ca18 wasm/archive: correctly parse long file names
Wasm archive files are encoded the same way as GNU.
This means that the header notates the character index within
the long file name list rather than the length of the name.
The entire name is then delimited by an LF character (0x0a).

This also makes a cosmetic update to remove the `self` name,
and rather label it as `archive` instead.
2022-08-20 14:50:08 +02:00
Ryan Liptak
9740bb2423 autodoc: Fix border color around field docs in light mode
Follow up to https://github.com/ziglang/zig/pull/12305
2022-08-19 19:06:01 -07:00
Andrew Kelley
e5e6eb9831 Merge pull request #12368 from ziglang/stage3-default
make self-hosted the default compiler
2022-08-19 20:26:46 -04:00
Andrew Kelley
b75eeae595 CI: x86_64-linux: avoid cmake ZIG_EXECUTABLE hack
empirically this avoids a segfault on the CI.
2022-08-19 17:24:23 -07:00
Andrew Kelley
e78e9f33c0 CI: update x86_64-linux tarball 2022-08-19 16:45:16 -07:00
Andrew Kelley
3ce8060818 CI: update windows tarball 2022-08-19 16:45:16 -07:00
Andrew Kelley
4a27d2aac6 std.os.linux.bpf: fix compile error 2022-08-19 16:45:16 -07:00
Andrew Kelley
a85f41ec2c test-stack-traces: relax parsing rules
* accept forward and backward slashes in file paths
 * strip multiple extensions; e.g. if the basename is "test.exe.obj"
   then it strips to "test".
2022-08-19 16:45:16 -07:00
Jakub Konka
10b95d89f8 coff: change improperly used packed struct into extern struct 2022-08-19 16:45:16 -07:00
Andrew Kelley
437311756d LLVM: add DLL export attribute
This was present in stage1 but missing from self-hosted.
2022-08-19 16:45:16 -07:00
Andrew Kelley
35f62bc7ae CI: windows: don't create build directory
Simplify the script by not creating an unnecessary build directory and
then changing directories to and from it.
2022-08-19 16:45:16 -07:00
Andrew Kelley
c4466496ff build: hook up -Dskip-stage2-tests and remove test-toolchain 2022-08-19 16:45:16 -07:00
Andrew Kelley
5be2e8f941 CI: update windows tarball
This includes a few recent bug fixes which may solve the Windows CI
failure.
2022-08-19 16:45:16 -07:00
Andrew Kelley
445b33cfc0 fix std.os.windows.PathSpace.span
it was returning a pointer to a parameter.
2022-08-19 16:45:16 -07:00
Andrew Kelley
28e95b3240 CI: drone: simplify
Instead of a switch in a bash file we just properly name
the pipeline steps.

Also use zig build to produce the release artifact.
2022-08-19 16:45:15 -07:00
Andrew Kelley
5b486b1851 CI: use zig build to produce release artifact
For both macOS and FreeBSD.
2022-08-19 16:45:15 -07:00
Andrew Kelley
a8f86291d2 CI: update freebsd tarball
This updates to a stage3 freebsd tarball.
2022-08-19 16:45:15 -07:00
Andrew Kelley
7cf6930e24 CI: macos: set release mode for zig and simplify 2022-08-19 16:45:15 -07:00
Andrew Kelley
9f43ebd6ef CI: windows: build stage3 directly from dev kit 2022-08-19 16:45:15 -07:00
Andrew Kelley
d75d40dfdf build: make docs a separate step than test 2022-08-19 16:45:15 -07:00
Andrew Kelley
7346600517 CI: avoid concurrent jobs tripping over each other 2022-08-19 16:45:15 -07:00
Andrew Kelley
e3ccea70dd CI: isolate zig-cache for parallel debug/release builds 2022-08-19 16:45:15 -07:00
Andrew Kelley
09ec9b0315 langref: update to new error message 2022-08-19 16:45:15 -07:00
Andrew Kelley
a73b3a0d70 CI: simplify x86 linux test instructions 2022-08-19 16:45:15 -07:00
Andrew Kelley
06c42a0c68 CI: test both stage3-debug and stage3-release on x86-linux 2022-08-19 16:45:15 -07:00
Andrew Kelley
507aae4a1a make self-hosted the default compiler
stage1 is available behind the -fstage1 flag.

closes #89
2022-08-19 16:45:15 -07:00
Andrew Kelley
73bbd1069a build: remove the option to omit stage2 2022-08-19 16:45:15 -07:00
r00ster91
39f43fea8d fix: fix off-by-one for leading zeroes 2022-08-20 01:45:34 +03:00
Andrew Kelley
be2bd5848a Merge pull request #12472 from ziglang/stage2-stack-protector
stage2: implement stack protectors
2022-08-19 06:41:34 -04:00
Andrew Kelley
fdb934a157 stage2: disable stack-protector on wasm, matching stage1
The CI gave me: unknown import: `env::__stack_chk_fail` has not been
defined
2022-08-19 03:41:13 -07:00
Andrew Kelley
d6ba66e50d Sema: avoid false positive error for linking libc
when extern c functions are called.
2022-08-19 03:41:13 -07:00
Andrew Kelley
c0b7f20893 stage2: implement stack protectors
This is one of the final remaining TODOs for the LLVM backend.
2022-08-19 03:41:13 -07:00
Andrew Kelley
2ccaa5414b Merge pull request #12145 from ziglang/fixes
More ABI size and alignment fixes
2022-08-19 04:56:08 -04:00
Andrew Kelley
150786e83c test harness: fix handling of object format
Follow-up to b975f7a56f.
2022-08-18 22:02:55 -07:00
Andrew Kelley
5e989fcb67 stage2: pointers to comptime-only types are comptime-only
This is a partial revert of c5ba941b77.
2022-08-18 22:02:10 -07:00
Andrew Kelley
cee82c7ce4 improved ABI alignment/size for >= 128-bit integers
* riscv64: adjust alignment and size of 128-bit integers.
 * take ofmt=c into account for ABI alignment of 128-bit integers and
   structs.
 * Type: make packed struct support intInfo
 * fix f80 alignment for i386-windows-msvc
2022-08-18 20:34:36 -07:00
Andrew Kelley
b975f7a56f std.Target gains ObjectFormat field 2022-08-18 18:58:28 -07:00
Andrew Kelley
517eb73b23 LLVM: disable the ABI size safety check
There still more instances of this check being tripped during behavior
tests that we need to fix before we can enable this.
2022-08-18 17:11:34 -07:00
Andrew Kelley
4552ccb685 stage2: make @Vector ABI size agree with LLVM 2022-08-18 17:11:34 -07:00
Andrew Kelley
6e313eb110 stage2: agree with LLVM that @alignOf(u128) is 8
on x86_64 and similar targets.
2022-08-18 17:11:32 -07:00
Andrew Kelley
c5ba941b77 stage2: all pointers have runtime bits 2022-08-18 16:02:29 -07:00
Ben Fiedler
7d674d5fb6 build: Allow comptime_int in OptionsStep.addOption 2022-08-18 23:00:44 +02:00
Jakub Konka
b12992cb01 macho: do not open file handle when building static archive
Firstly, opening a file handle is not really needed since we won't even
use it, and secondly, this can cause AccessDenied errors on Windows
when trying to move a directory from zig-cache/tmp/ to zig-cache/o/
since, without POSIX semantics, it is illegal to move directories
with open handles to any of its resources.
2022-08-18 15:54:09 -04:00
Ali Chraghi
51b2aa1643 docs: add padding between functions list 2022-08-18 22:02:02 +04:30
Sage Hane
f6459721e5 std.build: Fix typo in LibExeObjStep.runEmulatable's assertion 2022-08-18 20:08:25 +03:00
Eric Joldasov
b97ae88898 std.zig.system.NativeTargetInfo: look for a shebang line in /usr/bin/env, if any 2022-08-18 19:57:50 +03:00
zooster
4055e6055b AstGen: disallow leading zeroes in int literals and int types
This makes `0123` and `u0123` etc. illegal.

I'm now confident that this is a good change because
I actually caught two C header translation mistakes in `haiku.zig` with this.
Clearly, `0123` being octal in C (TIL) can cause confusion, and we make this easier to read by
requiring `0o` as the prefix and now also disallowing leading zeroes in integers.

For consistency and because it looks weird, we disallow it for integer types too (e.g. `u0123`).

Fixes #11963
Fixes #12417
2022-08-18 19:54:51 +03:00
Loris Cro
2523b443a4 Merge pull request #12477 from der-teufel-programming/master
Autodoc: HTML files generation
2022-08-18 18:05:11 +02:00
Loris Cro
53e971226d autodoc: minor pr cleanup 2022-08-18 18:02:19 +02:00
Veikka Tuominen
b038dba06b Merge pull request #12462 from Vexu/stage2-noreturn
Stage2: improve behavior of noreturn
2022-08-18 17:18:57 +03:00
Der Teufel
51a4861a08 Fixed Docgen.zig formatting 2022-08-18 15:44:42 +02:00
Der Teufel
f0bfdf9766 Fixed stage1 compilation error 2022-08-18 15:33:56 +02:00
Luuk de Gram
4f2143becc link/Wasm: improve symbol resolution
This adds additional checks during symbol resolution:
- Ensures function signatures match when a symbol will be replaced.
- Ensures global types match when the symbol is being replaced.
- When both symbols are undefined, ensures they have a matching module name.

Those changes ensure the result will pass the validator when
the runtime compiles the Wasm module.

Additionally, this also slightly changes the behavior when both
the existing symbol and new symbol are both defined. Rather than
always resulting in a collision, it only results in a collision
when both are also weak. Else, the non-weak symbol will be picked.
2022-08-18 14:17:01 +02:00
Luuk de Gram
63c25cc1cc wasm: fix callInstrinsic return value
Rather than storing it in a local and returning that,
we now keep this on the stack as all internal functions
expect it to be on the stack already and therefore were
generating extra `local.set` instructions.
2022-08-18 14:17:01 +02:00
der-teufel-programming
3ed9cdc1cc Merge branch 'ziglang:master' into master 2022-08-18 14:10:47 +02:00
Der Teufel
656b9429d0 autodoc: An attempt at generating HTML files from all imported source
files. Files generated from the standard library could be considered
for placing with main.js and index.html in lib/docs. Paths should
reflect packages in the future.
2022-08-18 14:03:42 +02:00
Andrew Kelley
df507edffe Merge pull request #12461 from ziglang/fix-12421
Fixes link-tests and `atomicSymLink` on Windows
2022-08-18 00:50:14 -04:00
Techatrix
79757f233d fix memory leak in NativePaths.zig 2022-08-17 19:05:39 -04:00
Jakub Konka
b6ce0cce69 windows-ci: pass -Domit-stage2 to test-toolchain 2022-08-17 23:13:58 +02:00
Jakub Konka
515ee5b2fa libstd: do not follow symlinks in renameatW
This correctly mimicks POSIX behavior.
2022-08-17 23:13:58 +02:00
Jakub Konka
9b595dd55f link-test: refactor and reorg
Move common tests by target file format (Wasm, MachO) into helper
functions in `link.zig`, and sort alphabetically within for easier
tracking versus file organization on disk.
2022-08-17 23:13:49 +02:00
Andrew Kelley
7f0642b5d3 Merge pull request #12397 from martinhath/issue-12364
Sema: error on ambiguous coercion of comptime float and ints
2022-08-17 17:10:08 -04:00
Andrew Kelley
2cccd14491 fix typo in compile error message 2022-08-17 14:09:42 -07:00
Veikka Tuominen
59b6483d63 add test 2022-08-17 14:09:42 -07:00
Martin Hafskjold Thoresen
07f64a2e13 Sema: error on ambiguous coercion of comptime float and ints
The following, from the documentation as of the time of writing, illustrates
the problem:

```zig
// Compile time coercion of float to int
test "implicit cast to comptime_int" {
    var f: f32 = 54.0 / 5;
    _ = f;
}
```

It is not clear how to unify the types of 54.0 and 5 to perform the
division. We can either

 - cast 54.0 to comptime_int resulting in @as(comptime_int, 10), which is
   casted to @as(f32, 10), or
 - cast 5 to comptime_float resulting in @as(comptime_float, 10.8), which
   is casted to @as(f32, 10.8)

Since the two resulting values are different, a compiler error is appropriate.

If we know that casting to either type will result in the same value we
don't need to error.  For instance, 10.0 / 2 is okay, as is 10 / 2.0.

Fixes: #12364
2022-08-17 14:09:09 -07:00
Jakub Konka
070282a96e libstd: fix off-by-one error in def of ProcSym in pdb
Make sure `ProcSym` includes a single element byte-array which delimits
the start of the symbol's name as part of its definition. This makes
the code more elegant in that accessing the name is equivalent to taking
the address of this one element array.
2022-08-17 16:36:02 -04:00
Veikka Tuominen
233049503a Sema: allow empty enums and unions 2022-08-17 23:03:04 +03:00
Andrew Kelley
c764640e92 Sema: fix generics with struct literal coerced to tagged union
The `Value.eql` function has to test for value equality *as-if* the lhs
value parameter is coerced into the type of the rhs. For tagged unions,
there was a problematic case when the lhs was an anonymous struct,
because in such case the value is empty_struct_value and the type
contains all the value information. But the only type available in the
function was the rhs type.

So the fix involved making `Value.eqlAdvanced` also accept the lhs type,
and then enhancing the logic to handle the case of the `.anon_struct` tag.

closes #12418

Tests run locally:
 * test-behavior
 * test-cases
2022-08-17 13:02:57 -07:00
Veikka Tuominen
c3d5428cba Sema: properly handle noreturn fields in unions 2022-08-17 22:07:48 +03:00
r00ster91
4ea3a9ba9f fix: comments 2022-08-17 20:08:13 +02:00
r00ster91
37880f2385 api: deprecate lowercase control_code consts 2022-08-17 20:07:58 +02:00
Veikka Tuominen
b0a55e1b3b Sema: make noreturn error union behave correctly 2022-08-17 20:10:18 +03:00
Veikka Tuominen
db0f372da8 Sema: make optional noreturn behave correctly 2022-08-17 20:10:18 +03:00
Jakub Konka
d84282174c link-test: move tls test to macho/tls
This test was always really testing correct behavior of our in-house
MachO linker to begin with.
2022-08-17 09:00:26 +02:00
Andrew Kelley
a12abc6d6c Merge pull request #12456 from Vexu/stage2
Stage2 namespacing fixes
2022-08-16 19:57:22 -04:00
r00ster91
298062897d docs: fixes and improvements 2022-08-16 21:37:02 +02:00
Andrew Kelley
9d85335de9 Merge pull request #12427 from r00ster91/nicelexer
tokenizer: cleanups
2022-08-16 14:08:31 -04:00
Veikka Tuominen
9d4561ef00 AstGen: detect declarations shadowing locals
Closes #9355
2022-08-16 20:35:03 +03:00
Loris Cro
6e794938b8 Merge pull request #12374 from vesim987/autodoc-links
autodoc: links to source code
2022-08-16 16:52:55 +02:00
Loris Cro
7f7d58ee89 Merge branch 'master' into autodoc-links 2022-08-16 16:52:26 +02:00
Loris Cro
5929da37a1 autodoc: absolute line numbers in decl [src] links 2022-08-16 16:51:32 +02:00
Loris Cro
0a0b3dda03 autodoc: remove reference to github, replace with placeholder link 2022-08-16 16:19:54 +02:00
Veikka Tuominen
c17793b487 Sema: ignore current declaration in ambiguous reference error
Closes #12429
2022-08-16 16:37:27 +03:00
r00ster91
83909651ea test: simplify testTokenize
What this does is already done by `expectEqual`.
Now the trace seems to be shorter and more concise so the errors should be easier to read now.
2022-08-16 00:20:19 +02:00
r00ster91
5490688d65 refactor: use std.ascii functions 2022-08-16 00:20:19 +02:00
r00ster91
e3b3eab840 test(names): some renamings 2022-08-16 00:20:19 +02:00
r00ster91
f07cba10a3 test(names): remove unnecessary "tokenizer - " prefix 2022-08-16 00:20:19 +02:00
Loris Cro
b3922289be Zir: add missing support for packed ints in declIterator 2022-08-15 21:57:33 +02:00
Loris Cro
aefb091973 Merge pull request #12445 from r00ster91/noresults
autodoc: better No Results Found page and other improvements
2022-08-15 20:50:34 +02:00
Loris Cro
95573dbeeb ci: add gzip compression to stdlib docs & langref 2022-08-15 20:44:30 +02:00
sin-ack
a9c4dc84f4 Sema: Revert sema.err to null if the Decl already has an error
Previously we would assign the error message to Sema and then never
clear it even when destroying the error message, which caused memory
corruption.

Closes #12437
2022-08-15 11:34:12 +03:00
Veikka Tuominen
40eac90280 Merge pull request #12416 from Vexu/stage2-safety
Stage2 error set safety improvements
2022-08-15 11:32:26 +03:00
LeRoyce Pearson
cb901e578c stage2: add compile errors for comptime @shrExact and @divExact failures 2022-08-15 11:28:42 +03:00
Ryan Liptak
764cf4e53f std.fs: Fix WalkerEntry.dir not always being the containing dir
Before this commit, the modified test would fail with `FileNotFound` because the `entry.dir` would be for the entry itself rather than the containing dir of the entry. That is, if you were walking a tree of `a/b`, then (previously) the entry for `b` would incorrectly have an `entry.dir` for `b` rather than `a`.
2022-08-15 11:25:51 +03:00
Yujiri
2279f27e0f Fix #12423: auto_hash not hashing arrays of slices uniquely 2022-08-14 23:12:48 +03:00
r00ster91
ee97fbc199 api: deprecate isPunct too
See https://github.com/ziglang/zig/issues/8419#issuecomment-843719898
2022-08-14 22:04:13 +02:00
r00ster91
846dbf2745 docs: remove some hyphens 2022-08-14 21:49:21 +02:00
r00ster91
8890190857 fix: add missing 'o' 2022-08-14 21:46:26 +02:00
r00ster91
028134055c fix: remove outdated TODO
It was supposed to be removed: 490654c332 (r47643278)
2022-08-14 21:43:40 +02:00
r00ster91
9b79c6ae52 test: update and add more tests 2022-08-14 21:42:24 +02:00
r00ster91
d130d09e2b docs: add more docs
And improve some existing docs.
2022-08-14 21:39:53 +02:00
r00ster91
02893d80cf api: rename and deprecate a bunch of functions
`isAlNum` and `isAlpha`:
1. I think these names are a bit cryptic.
2. `isAlpha` is a bit ambiguous: is it alpha*numeric* or alpha*betic*?
   This is why I renamed `isAlpha` to `isAlphabetic`.
3. For consistency and because `isAlNum` looks weird, I renamed it to `isAlphanumeric`.

`isCntrl`:
1. It's cryptic and hard to find when you look for it.
2. We don't save a lot of space writing it this way.
3. It's closer to the name of the `control_code` struct.

`isSpace`:
1. The name is ambiguous and misleading.

`spaces`:
1. Ditto

`isXDigit`:
1. The name is extremely cryptic.
2. The function is very hard to find by its name.
2022-08-14 21:34:59 +02:00
r00ster91
d178df773a api: deprecate isBlank and isGraph.
I think `isBlank` and `isWhitespace` are quite confusable.
What `isBlank` does is so simple that you can just do the `c == ' ' or c == '\t'`
check yourself but in a lot of cases you don't even want that.
`std.ascii` can't really know what you think "blank" means.
That's why I think it's better to remove it.
And again, it seems ambiguous considering that we have `isWhitespace`.

Next, it also deprecates `isGraph`.
It's the same as `isPrint(c) and c != ' '`, which I find confusing.
When something is printable, you can say it also has a *graph*ical representation.
Removing `isGraph` solves this possible confusion.
2022-08-14 21:13:46 +02:00
r00ster91
93ca0c4a5e fix: off-by-one in isCntrl
0x1F (`control_code.us`) itself is also a control code.
2022-08-14 21:05:37 +02:00
r00ster91
aa0b93e875 feat: new control_code
It lowercases all constants and documents them.
2022-08-14 21:03:57 +02:00
r00ster91
78bb29d1dc fix: scroll page to very top when S is pressed
Credits go to @rudedogg
2022-08-14 19:19:44 +02:00
r00ster91
af20dfae60 bug: add TODO 2022-08-14 12:20:26 +02:00
r00ster91
e5379e5027 docs: add comment 2022-08-14 12:18:08 +02:00
r00ster91
2723d8e6e2 style: format
Some formatting, apparently.
2022-08-14 11:54:51 +02:00
r00ster91
8f6f4bc7ca feat: make modal more restrictive and more Esc freedom
This makes it so that you can no longer interact with the search bar
or the results or anything while the modal is open. That's why it's a "modal" and not a "dialog".

It also makes it so that you can now always press Esc to return to the results or the main page.
Previously this was only possible when the search field was active.
2022-08-14 11:54:51 +02:00
r00ster91
9900413eb1 feat: indent keyboard shortcuts
This indents the keyboard shortcuts related to the S key because you can only
use these keyboard shortcuts after you pressed S (when the search field is focused).
This is a visual hint.
2022-08-14 11:54:51 +02:00
r00ster91
e1eaa1f7d6 fix: var(--mono) used for font-size 2022-08-14 11:54:51 +02:00
r00ster91
dc5174440c feat: better No Results Found page
This adds some helpful links to the page and makes it look nicer by using <kbd> etc.
2022-08-14 11:54:51 +02:00
Joachim Schmidt
d2342370fe Merge pull request #12438 from joachimschmidt557/stage2-arm
stage2 ARM: misc improvements
2022-08-13 20:32:18 +00:00
joachimschmidt557
c9d9fd53a6 stage2 ARM: add inline memcpy to genSetStack 2022-08-13 17:00:03 +02:00
joachimschmidt557
91969ad908 stage2 ARM: Fix tracking of function return values 2022-08-13 17:00:03 +02:00
joachimschmidt557
4c5156544b stage2 ARM: pass stack arguments in opposite order
Earlier arguments have a smaller address (i.e. towards the bottom of
the stack)
2022-08-13 17:00:00 +02:00
Cody Tapscott
7e07f3d4f9 stage2 astgen: Use rl semantics for @Type
Resolves #12430.
2022-08-13 09:22:25 +03:00
Jakub Konka
bfe8a4d9f6 Merge pull request #12425 from ziglang/dwarf-fixes
x86: fix generating debug info for variables
2022-08-12 21:48:34 +02:00
Jakub Konka
aeaffd42f6 x86: fix generating debug info for variables
Add handling for these additional `MCValue`s:
* `.immediate` - lower to `DW.OP.consts` or `DW.OP.constu` depending
  on signedness followed by popping off the DWARF stack with
  `DW.OP.stack_value`
* `.undef` - lower to `DW.OP.implicit_value`
* `.none` - lower to `DW.OP.lit0` followed by popping off the DWARF
  stack with `DW.OP.stack_value`

For any remaining unhandled case, we generate `DW.OP.nop` in order
not to mess up remaining DWARF info.
2022-08-12 12:05:34 +02:00
Jakub Konka
f2f1bb7cb6 macho: update __DWARF sections before and after writing out __LINKEDIT 2022-08-12 11:50:39 +02:00
martinhath
92568a0097 Sema: add error for signed integer division
stage1 error reads

error: division with 'i32' and 'comptime_int': signed integers must use @divTrunc, @divFloor, or @divExact

Fixes: #12339
2022-08-12 11:45:11 +03:00
Veikka Tuominen
09f273136c stage2: check for zero in @intToError safety 2022-08-12 11:41:09 +03:00
Veikka Tuominen
7c9979a02e stage2: generate a switch for @errSetCast safety 2022-08-12 11:40:37 +03:00
Andrew Kelley
fa50e179f7 Merge pull request #12381 from hdorio/12380-fix-reporting-success
ci: windows: stop when exe exits with an error
2022-08-12 03:51:09 -04:00
Luuk de Gram
645c396d02 Merge pull request #12394 from Luukdegram/wasm-reuse-locals
stage2: wasm - reuse (temporary) locals
2022-08-12 08:07:09 +02:00
Andrew Kelley
5e42b0821a disable failing stack traces tests on windows
See tracking issue #12422
2022-08-11 19:19:23 -07:00
Andrew Kelley
486626beb7 disable failing link tests on windows
See tracking issue #12421
2022-08-11 17:53:15 -07:00
Andrew Kelley
23a227a073 disable failing standalone test: issue_11595
See tracking issue #12419
2022-08-11 17:53:12 -07:00
Andrew Kelley
dba758da18 disable failing C backend behavior test on Windows
See tracking issue #12415
2022-08-11 12:56:46 -07:00
Andrew Kelley
64307c2821 CI: update windows tarball 2022-08-11 12:48:11 -07:00
Hadrien Dorio
bcc6cdc4fb ci: azure: stop when exe exits with an error 2022-08-11 12:48:11 -07:00
Andrew Kelley
e67a43a673 Merge pull request #12410 from ifreund/sig-err-dfl-ign-fix
std: fix definition of SIG_IGN, SIG_DFL, etc.
2022-08-11 15:05:07 -04:00
LordMZTE
bbcc26a9b6 fix error message when providing slice to std.hash.autoHash 2022-08-11 21:44:33 +03:00
Andrew Kelley
a82d7c2063 std: add missing error to windows.WriteFile
I encountered this error today when testing the self-hosted compiler on
Windows.
2022-08-11 06:22:05 -04:00
Andrew Kelley
44a6172edb Merge pull request #12405 from ziglang/macho-aligned-ptrs
link.MachO: use accurate alignment attribute on pointers
2022-08-11 06:19:10 -04:00
Isaac Freund
b78f3bf1f1 std: fix definition of SIG_IGN, SIG_DFL, etc.
POSIX specifies that the sa_handler field of the sigaction struct may
be set to SIG_IGN or SIG_DFL. However, the current constants in the
standard library use the function pointer signature corresponding to
the sa_sigaction field instead.

This may not cause issues in practice because the fields usually occupy
the same memory in a union, but this isn't required by POSIX and there
may be systems we do not yet support that do this differently.

Fixing this also makes the Zig interface less confusing to use after
reading the man page.
2022-08-11 12:09:34 +02:00
Luuk de Gram
b42ba7c3d4 wasm: free unused locals
When a local is no longer referenced or used, free it
so the local can be re-used by another instruction.
This means we generate less locals. Freeing this local
is a manual action and must only be used on temporaries
or where we are sure the local is not referenced by a
different AIR instruction, as that creates UB.

We now also no longer store a `WValue` when its tag is set to `none`
as those may never be referenced by any AIR instruction.
An assertion is done to make sure we never store a reference to a
`stack` value in our resolved instructions.
2022-08-11 11:08:01 +02:00
Luuk de Gram
a5e4fd7ef6 wasm: keep load values on the stack
We internally use a lot of `load`'s that used to put
the result in a newly created local. For instance, when is considered
byRef or when we need a specific field/element/bytes from a larger type.
However, sometimes we want to directly use this value and then forget about
it, which means storing it in a local first is wasted instructions as well
as wasted locals that shouldn't be generated in the first place.
With this change it's explicit and requires the usage of `toLocal`.
2022-08-11 11:08:00 +02:00
Luuk de Gram
3cd0cd12a0 wasm: leave signedAbsValue values on the stack 2022-08-11 11:08:00 +02:00
Luuk de Gram
cde16f61eb wasm: wrapOperand - leave value on the stack
This also does it for `wrapBinOp` which internally uses the already
refactored `binOp` and `wrapOperand` heavily simplifying this
function and not duplicate the logic from `binOp`
2022-08-11 11:08:00 +02:00
Luuk de Gram
699bc6171d wasm: Keep intcast values on stack 2022-08-11 11:08:00 +02:00
Luuk de Gram
305b113a53 wasm: keep result of cmp on the stack
By keeping the result on the stack, we prevent codegen
from generating unneccesary locals when we have subsequent instructions
that do not have to be re-used.
2022-08-11 11:08:00 +02:00
Luuk de Gram
cc6f2b67c6 wasm: binOp leave value on stack
Rather than always creating a new local and storing the result of
a binary operation into said local, we now leave it on top of the stack.
This allows for better codegen as we need less instructions, as well
as less total amount of locals.
2022-08-11 11:08:00 +02:00
Luuk de Gram
7e6dbd6398 wasm: Use free-lists for unused locals
When a local is no longer needed (for instance, it was used as
a temporary during arithmetic), it can be appended to one of
the typed freelists. This allows us to re-use locals and therefore
require less locals, reducing the binary size, as well as runtime
initialization.
2022-08-11 11:07:56 +02:00
Isaac Freund
7d6a7f513b std: Don't pass undefined memory to the kernel in os.abort() 2022-08-11 11:05:53 +02:00
Andrew Kelley
9f1f60fd43 test-cases: remove multi-threading
This effectively reverts 22690efcc2,
re-opening #11818.

This had the following problems:
 * Buggy on some targets (macOS, Windows)
 * Messy output to the terminal

These problems need to be solved before moving forward with this.
2022-08-11 00:46:44 -07:00
Andrew Kelley
933436dc52 stage2: remove destroyed functions from maps
This is likely the cause of the flaky test failures in master branch.
Since we have some test coverage for incremental compilation, it's not
OK to leave proper memory management of Fn objects as "TODO".
2022-08-10 23:23:30 -07:00
Andrew Kelley
fa620ef710 link.MachO: use accurate alignment attribute on pointers
Also adds a new method to ArrayList: appendUnalignedSlice
2022-08-10 22:28:05 -07:00
Andrew Kelley
cc56400e62 Revert "macho: allow unaligned offsets in object files"
This reverts commit 45c444ff18.
2022-08-10 22:27:59 -07:00
Veikka Tuominen
74673b7f69 stage2 llvm: implement more C ABI 2022-08-10 20:52:36 -04:00
Andrew Kelley
4d7f5a1917 stage2: fix crash with comptime vector reduce 2022-08-10 16:45:29 -07:00
Andrew Kelley
3c4e9b5983 disable failing behavior test
See #12360
2022-08-10 16:43:47 -07:00
Andrew Kelley
d267f0f968 LLVM: respect linksection for exported variables 2022-08-10 16:43:30 -07:00
Andrew Kelley
e8d02c5b90 add ZIG_GLOBAL_CACHE_DIR env var 2022-08-10 16:43:25 -07:00
Andrew Kelley
9656ec271c better default for use_stage1 when -ofmt=c is provided 2022-08-10 16:24:04 -07:00
Andrew Kelley
173952f4b8 disable failing behavior test
see tracking issue #12396
2022-08-10 16:13:59 -07:00
Andrew Kelley
e0178890ba Merge pull request #12379 from ifreund/packed-struct-explicit-backing-int
stage2: Implement explicit backing integers for packed structs
2022-08-10 19:13:29 -04:00
Jakub Konka
45c444ff18 macho: allow unaligned offsets in object files 2022-08-10 18:45:46 -04:00
InKryption
e218b7ea0c stage2: add compile error for invalid null/undefined pointer cast 2022-08-10 16:39:46 -04:00
LeRoyce Pearson
0e118ed0ac stage2: add compile error for shlExact overflow
- moves a stage1 test case and makes it target `llvm` backend instead
  of `stage1` backend
2022-08-10 16:14:30 -04:00
zooster
8fd20a5eb0 fix: disallow newline in char literal 2022-08-10 16:13:56 -04:00
Veikka Tuominen
40447b25e8 Sema: fix expansion of repeated value
Closes #12386
2022-08-10 15:18:09 -04:00
Isaac Freund
0d32b73078 stage2: Implement explicit backing integers for packed structs
Now the backing integer of a packed struct type may be explicitly
specified with e.g. `packed struct(u32) { ... }`.
2022-08-10 19:54:45 +02:00
Isaac Freund
bb1c3e8b7e stage2: Handle lazy values for the % operator 2022-08-10 14:48:27 +02:00
Andrew Kelley
49a270b203 Merge pull request #12356 from Vexu/stage2-call
stage2: generate call arguments in separate blocks
2022-08-09 23:11:36 -04:00
Veikka Tuominen
b757a96d5c Sema: add declared here note to function call errors 2022-08-09 23:37:26 +03:00
Veikka Tuominen
0778490283 AutoDoc: update to Zir call inst changes 2022-08-09 19:26:40 +03:00
Veikka Tuominen
19af4b5cad std: add workaround for stage2 bug 2022-08-09 16:19:55 +03:00
Veikka Tuominen
0fd90749d1 stage2: generate call arguments in separate blocks 2022-08-09 16:19:55 +03:00
Andrew Kelley
85a3f9b054 Merge pull request #12383 from ziglang/stage2-stack-traces
several improvements to error return tracing in the self-hosted compiler
2022-08-09 02:11:58 -07:00
Veikka Tuominen
c76b5c1a31 stage2: correct node offset of nested declarations 2022-08-09 11:59:10 +03:00
Andrew Kelley
feb90f6ed4 AstGen: emit debug stmt for try
This improves the following test case:

```zig
pub fn main() !void {
    try foo();
}

fn foo() !void {
    return error.Bad;
}
```

The error return trace now points to the `try` token instead of pointing
to the foo() function call, matching stage1.

Closes #12308.
2022-08-08 21:12:04 -07:00
Andrew Kelley
0648177ed7 AstGen: avoid multiple dbg_stmt instructions in a row
This is purely an optimization to emit fewer ZIR instructions.
2022-08-08 20:43:05 -07:00
Andrew Kelley
3389890709 stage2: error return tracing handles ret better
Sema: insert an error return trace frame when appropriate when analyzing
ret_load. Also optimize the instructions to avoid an unnecessary block
sent to the backends.

AstGen: always emit a dbg_stmt for return expressions, in between the
defer instructions and the return instruction.

This improves the following test case:

```zig
pub fn main() !void {
    return foo();
}

fn foo() !void {
    return error.Bad;
}
```

The error return trace now points to the return token instead of
pointing to the foo() function call, matching stage1.
2022-08-08 20:43:05 -07:00
Andrew Kelley
1a500b9699 Sema: avoid error return traces when possible
stage2 was adding bogus error return trace frames when an error was not
being returned. This commit makes several improvements:

 * Make a runtime check if necessary to only emit a frame into the error
   return trace when an actual error is returned.
 * Use the `analyzeIsNonErrComptimeOnly` machinery to avoid runtime
   checks when it is compile-time-known that the value is an error, or a
   non-error.
 * Make std.builtin.returnError take a non-optional stack trace pointer.

closes #12174
2022-08-08 19:16:21 -07:00
Veikka Tuominen
d769fd0102 stage2: pass anon name strategy to reify 2022-08-08 18:28:39 -07:00
Andrew Kelley
3afc4dff30 Merge pull request #12369 from ziglang/zig-cc-m-flag
cc: add support for -M flag
2022-08-08 18:26:26 -07:00
Ryotaro "Justin" Kimura
50b36e84fa std: fix BoundedArray test checking wrong condition (#12372) 2022-08-08 18:13:35 -04:00
Maciej 'vesim' Kuliński
a0a1178694 autodoc: links to source code 2022-08-08 21:42:38 +02:00
Loris Cro
1db99b08e2 Merge pull request #12347 from r00ster91/nicedocs
autodoc: various improvements
2022-08-08 18:31:01 +02:00
r00ster91
ff6d2e632f fix: cleanup recent changes 2022-08-08 18:14:26 +02:00
Jakub Konka
a0ec07fdec cc: add support for -M flag 2022-08-08 14:26:10 +02:00
Jakub Konka
80c9d3f3b1 update update_clang_options.zig to latest formatting changes 2022-08-08 14:25:45 +02:00
Andrew Kelley
396eb730e5 Merge pull request #12228 from nektro/stage2-arch
remove 'builtin.stage2_arch', Sema is smart enough now
2022-08-07 19:37:05 -07:00
Andrew Kelley
ec7f713147 delete failing RISC-V test
this backend needs to get further along before it deserves test
coverage.
2022-08-07 16:07:25 -07:00
Andrew Kelley
11c715cd5a remove brittle test case
see #12358
2022-08-07 16:07:21 -07:00
Meghan Denny
0879cbeed2 remove 'builtin.stage2_arch', Sema is smart enough now 2022-08-07 16:07:08 -07:00
Jakub Konka
ae16c1d083 std: use std.macho.LoadCommandIterator for MachO parsing in std.debug 2022-08-06 23:14:54 -07:00
Andrew Kelley
b3d463c9e6 Merge pull request #12337 from Vexu/stage2-safety
Stage2: implement remaining runtime safety checks
2022-08-06 14:59:10 -07:00
Veikka Tuominen
3e2defd36c stage2: add a helpful error for when async is used 2022-08-06 14:51:20 -07:00
joachimschmidt557
b300eecb9d stage2 DWARF: fix size and offset in slices
Previously, `@sizeOf(usize)` was used, however, the pointer size of
the host may differ from the target when cross-compiling.
2022-08-06 14:44:05 -07:00
Veikka Tuominen
bd21f499dc Type: adjust C type sizes 2022-08-06 14:42:05 -07:00
zooster
3debd6b732 Merge branch 'master' into nicedocs 2022-08-06 19:32:42 +02:00
Loris Cro
94662591d6 ci: upload langref and stdlib docs directly to s3
previously we were delegating that job to the website CI but it caused
the website repo to bloat, so now we only commit releases.json
2022-08-06 18:12:21 +02:00
Loris Cro
cb7c912a1b autodoc: use location.replace to avoid history spam when searching 2022-08-06 17:29:39 +02:00
Loris Cro
9fc6990052 autodoc: re-introduce search result limits 2022-08-06 17:29:13 +02:00
Loris Cro
059713478a Merge pull request #12343 from rudedogg/master
autodoc: only modify the DOM once to display the search results
2022-08-06 16:43:25 +02:00
r00ster91
943f4eb515 fix: use brighter bg color for help modal in light mode
You can see this issue in the video.
2022-08-06 16:07:32 +02:00
r00ster91
60b04b0988 style: some more formatting 2022-08-06 16:01:43 +02:00
r00ster91
2f5afe1194 let -> const for dom elements
These should never be reassigned.
2022-08-06 15:53:20 +02:00
r00ster91
e921dd1136 style: missing semi 2022-08-06 15:38:32 +02:00
r00ster91
beba29c24f feat: make shadow of <kbd>s look nicer 2022-08-06 15:34:38 +02:00
r00ster91
ee72868f92 style: format
This is mostly manually formatted. I couldn't find a good HTML formatter for this file.
It also converts a bunch of tabs to spaces.
2022-08-06 15:34:00 +02:00
r00ster91
2f0abe63d4 fix: disable search bar before loading
This fixes the new search placeholder not disappearing if you type before
it finished loading, and maybe some other things.
2022-08-06 15:16:27 +02:00
r00ster91
df8cfb1273 feat: new search placeholder
This new search placeholder looks much nicer because it allows HTML inside it which
the `placeholder` attribute on `<input>`s doesn't allow.
I tested it for all kinds of cases and it seems to work pretty well.
2022-08-06 15:15:59 +02:00
r00ster91
6354851909 fix: "dialog" -> "modal"
"Dialog" is the incorrect term here because a dialog is a separate window that still lets you use the app
but a modal is a window where you can't continue using the app until you close it.
2022-08-06 15:05:58 +02:00
r00ster91
4ef567ba41 feat: make help modal disappear if you click outside it 2022-08-06 15:01:55 +02:00
Veikka Tuominen
75275a1514 Sema: do not emit pointer safety checks for pointers to zero-bit types 2022-08-06 15:22:14 +03:00
Anton Lilja
86d9c3de2b Sema: fix infinite recursion in explainWhyTypeIsComptime
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-08-06 14:17:09 +03:00
Andrew Kelley
5c9826630d Sema: elide safety of modulus and remainder division sometimes
Piggybacking on 40f8f0134f, remainder
division, modulus, and `%` syntax no longer emit safety checks for a
comptime-known denominator.
2022-08-05 21:13:18 -07:00
Austin Rude
7afe7de4f0 autodoc: only modify the DOM once to display the search results 2022-08-05 21:47:36 -06:00
Andrew Kelley
7c9a8ecc2a stage1: another LLVM opaque pointers fix 2022-08-05 18:59:46 -07:00
Andrew Kelley
40babaa537 Merge pull request #12338 from joachimschmidt557/stage2-aarch64
stage2 AArch64: fixes for removing builtin.stage2_arch
2022-08-05 16:56:27 -07:00
Loris Cro
ab6b53a259 Merge pull request #12340 from rudedogg/master
autodoc: Run through prettier formatter with default settings
2022-08-06 00:24:32 +02:00
Austin Rude
e02f51762f autodoc: Run through prettier formatter with default settings 2022-08-05 16:01:57 -06:00
Veikka Tuominen
0daa77bd63 stage2 cbe: correct airIsNull ptr operand check 2022-08-05 22:13:58 +03:00
Veikka Tuominen
f46d7304b1 stage2: add runtime safety for invalid enum values 2022-08-05 22:13:58 +03:00
Veikka Tuominen
19d5ffc710 Sema: add safety check for non-power-of-two shift amounts 2022-08-05 22:13:58 +03:00
Veikka Tuominen
9116e26c1f Sema: add null check for implicit casts 2022-08-05 22:13:58 +03:00
Veikka Tuominen
5605f6e0e3 Sema: account for sentinel in bounds check 2022-08-05 22:13:57 +03:00
Veikka Tuominen
6aa438f065 Sema: add null pointer slice safety check when len is comptime known 2022-08-05 22:13:57 +03:00
Veikka Tuominen
eec2978fac Sema: better safety check on switch on corrupt value 2022-08-05 22:13:57 +03:00
joachimschmidt557
f46c80b267 stage2 AArch64: improve correctness of register aliases
Also implements ptr_elem_ptr
2022-08-05 20:30:52 +02:00
joachimschmidt557
508b90fcfa stage2 AArch64: implement basic integer rem/mod 2022-08-05 20:30:52 +02:00
joachimschmidt557
8b24c783c5 stage2 AArch64: implement basic integer division 2022-08-05 20:30:51 +02:00
joachimschmidt557
dcb236acf4 stage2 AArch64: memcpy support in store and more complete intcast 2022-08-05 20:30:51 +02:00
joachimschmidt557
02738228f2 stage2 AArch64: support returning values by reference
also adds some more support for slices passed as stack arguments
2022-08-05 20:30:51 +02:00
joachimschmidt557
65b3c27f24 stage2 AArch64: all arguments passed via stack from now on
Only in the Undefined calling convention, not in other calling
conventions
2022-08-05 20:30:51 +02:00
joachimschmidt557
cf3aaceed9 stage2 AArch64: introduce MCValue.stack_argument_offset
This new MCValue union member shares the same semantics as the MCValue
type of the same name in the ARM backend.
2022-08-05 20:30:51 +02:00
joachimschmidt557
423bef4dfc stage2 AArch64: Fix struct_field_val for register_with_overflow
Now mirrors the behavior of the native ARM backend
2022-08-05 20:30:47 +02:00
N00byEdge
18440cb239 std.mem.zeroes: Zero sized structs with uninitialized members (#12246)
`std.mem.zeroes(struct{handle: void})` Failed with the following error before:
```
/nix/store/l6v4359wc9xrxxmvvp3rynsb5s3d78xf-zig-0.9.1/lib/zig/std/mem.zig:270:42: error: missing field: 'handle'
            if (@sizeOf(T) == 0) return T{};
                                         ^
```
2022-08-05 15:47:52 +03:00
Allan Regush
44c321c05e std.enums: make directEnumArrayLen public 2022-08-05 15:41:03 +03:00
Felix "xq" Queißner
263b5933d2 Makes std.meta.Tuple and std.meta.ArgsTuple generate a unique type instead of generating one per invocation. 2022-08-05 15:39:53 +03:00
Meredith Oleander
fd3415ad5e translate-c: fix alignment in pointer casts 2022-08-05 15:38:48 +03:00
Stephen Gregoratto
b3950d4a88 Update Linux syscall list for 5.19
New changes: memfd_secret implemented for RISC-V.
2022-08-05 15:36:32 +03:00
Veikka Tuominen
42ade6a114 Merge pull request #12300 from antlilja/getParamName
Replace param_names and anytype_args fields inside of Fn with functions
2022-08-05 15:29:59 +03:00
Andrew Kelley
e1dbb70bef Merge remote-tracking branch 'origin/master' into llvm15 2022-08-05 00:33:50 -07:00
Andrew Kelley
2f635c3ce9 update libunwind to LLVM 15
release/15.x commit 134fd359a5d884f16662a9edd22ab24feeb1498c
2022-08-04 18:09:10 -07:00
Andrew Kelley
c0d9578a84 update libcxxabi to LLVM 15
release/15.x commit 134fd359a5d884f16662a9edd22ab24feeb1498c
2022-08-04 18:02:01 -07:00
Andrew Kelley
8278eb8837 update libcxx to LLVM 15
release/15.x commit 134fd359a5d884f16662a9edd22ab24feeb1498c
2022-08-04 17:53:05 -07:00
Andrew Kelley
ac5c6b6061 stage2 LLVM backend: opaque pointer fixes 2022-08-04 17:32:46 -07:00
Loris Cro
259f407160 init-exe template: align cli tests to new template 2022-08-05 00:42:53 +02:00
Loris Cro
7ffba492a5 autodoc: fix inconsistency when indexing generic types for search
closes #12334
2022-08-05 00:11:32 +02:00
Andrew Kelley
169ad1aac7 compiler_rt: update ABI for x86 float16 functions
See https://github.com/llvm/llvm-project/issues/56854 for more details.
2022-08-04 14:55:35 -07:00
Loris Cro
55ec2148fd autodoc: fix analysis of function return types 2022-08-04 23:24:18 +02:00
Andrew Kelley
ba70eee8bb Merge remote-tracking branch 'origin/master' into llvm15 2022-08-04 14:24:00 -07:00
Loris Cro
616f65df75 init-exe template: add flushing to the buffered writer 2022-08-04 21:12:42 +02:00
Loris Cro
cbac7a0194 init-exe template: small improvements 2022-08-04 20:27:46 +02:00
Loris Cro
fb0b9f05b3 new init-exe template
- removed an unnecessary (and confusing) `anyerror` fronm the function
  signature of `main`
- replaced the call to std.log with two prints: one to stderr and one to
  stdout
- replaced the test code with a better example
2022-08-04 20:10:43 +02:00
Jakub Konka
4a4f3c50ce Merge pull request #12320 from ziglang/macho-zld-sync 2022-08-03 22:02:50 -07:00
Andrew Kelley
e483336ba4 Merge pull request #12318 from Vexu/stage2-compile-errors
Stage2: misc compile error improvements
2022-08-03 20:13:07 -07:00
Andrew Kelley
a3045b8abb LLVM backends: more LLVM 15 fixes
uwtable now needs a "sync" or "async" parameter.

more opaque pointer fixes
2022-08-03 16:42:27 -07:00
Andrew Kelley
7e43904508 stage1: more LLVM15 opaque pointers fixes 2022-08-03 14:48:08 -07:00
Andrew Kelley
900f969cb3 link: LLD 15 requires two dashes on --error-limit 2022-08-03 14:19:35 -07:00
Jakub Konka
007eb3bd71 macho: fix some TODOs 2022-08-03 21:26:52 +02:00
Jakub Konka
2c8fc3b597 macho: add missing u64 to usize casts
Fixes 32bit builds.
2022-08-03 21:19:41 +02:00
Jakub Konka
90e3268270 macho: do not preempt segment headers; do it when commiting to file
This way, tracking segment-to-section mapping becomes a lot easier
since it's effectively just start index plus number of sections
defined within the segment. If a section becomes empty however
care needs to be taken to remove the header upon committing to the
final binary.
2022-08-03 21:19:41 +02:00
Jakub Konka
421d3e8d28 macho: add missing align cast in LoadCommandIterator 2022-08-03 21:19:41 +02:00
Jakub Konka
1e710396d4 macho: fix linking in incremental context
Fix incorrect writing of symtab and strtab in dSYM bundle in incremental
context.

Fix incorrectly navigating unnamed consts (freeing) in incremental context.
This is currently hard-coded to require all consts to land in `__TEXT,__const`,
which is wrong and needs a rewrite.
2022-08-03 21:19:41 +02:00
Jakub Konka
7bba3d330a macho: cleanup output section selection logic
Cache only section indexes used by the linker for synthetic sections
and/or incremental codepath.
2022-08-03 21:19:41 +02:00
Jakub Konka
bb532584bc macho: update how we insert output sections
Instead of generating sections upfront, allow generation by scanning
the object files for input -> output sections mapping. Next, always
strive to keep output sections in the final container sorted as they
appear in the final binary. This makes the linker less messy wrt
handling of output sections sort order for dyld/macOS not to complain.
There's still more work to be done for incremental context though
to make this work but looks promising already.
2022-08-03 21:19:41 +02:00
Jakub Konka
f26d5ee7ea macho: sync with zld
gitrev a2c32e972f8c5adfcda8ed2d99379ae868f59c24

a2c32e972f
2022-08-03 21:19:41 +02:00
Loris Cro
4c750016eb autodoc: inferred error unions in function return values 2022-08-03 17:21:56 +02:00
Loris Cro
ecccf1f91f Add codeowners file for automated PR assignment
Added myself for Autodoc related files.
2022-08-03 16:26:53 +02:00
Loris Cro
dd8ca27979 Merge pull request #12323 from ziglang/autodoc-issue-template
Update issue templates
2022-08-03 16:20:59 +02:00
Loris Cro
c85bdbffa9 Update issue templates 2022-08-03 16:20:27 +02:00
Veikka Tuominen
4ab60dc18b Sema: add error for dependency loops 2022-08-03 17:10:39 +03:00
Veikka Tuominen
b79929b2ea AstGen: better source location for if/while condition unwrapping 2022-08-03 16:45:33 +03:00
Veikka Tuominen
d1d24b426d AstGen: check loop bodies and else branches for unused result 2022-08-03 16:45:33 +03:00
Veikka Tuominen
aa78ebaf95 Sema: improve circular dependency errors 2022-08-03 16:45:33 +03:00
Veikka Tuominen
797ded47f0 Sema: move last error message from Inlining to Sema 2022-08-03 16:45:33 +03:00
Veikka Tuominen
02112f8836 AstGen: add error for break/continue out of defer expression 2022-08-03 16:45:33 +03:00
Veikka Tuominen
6547c3887e Sema: add error for closure capture at runtime 2022-08-03 16:45:33 +03:00
Frank Denis
fa321a07cd crypto.sign.ed25519: include a context string in blind key signatures (#12316)
The next revision of the specification is going to include a context
string in the way blinded scalars are computed.

See:
https://github.com/cfrg/draft-irtf-cfrg-signature-key-blinding/issues/30#issuecomment-1180516152
https://github.com/cfrg/draft-irtf-cfrg-signature-key-blinding/pull/37
2022-08-03 15:25:15 +02:00
Andrew Kelley
d631bfe060 update clang CLI options to LLVM 15 2022-08-02 19:43:38 -07:00
Andrew Kelley
c75226d033 update target CPU features for LLVM 15 2022-08-02 19:22:09 -07:00
Andrew Kelley
5043369e14 stage1: fix a few more LLVM 15 opaque pointer bugs 2022-08-02 18:06:21 -07:00
Andrew Kelley
c8e20758f6 add missing declaration to zig_clang.h 2022-08-02 17:22:23 -07:00
Andrew Kelley
affe52b590 compiler_rt: use standard f16 function names on x86
LLVM 15 started generating calls to the standard name now.
2022-08-02 17:22:23 -07:00
Andrew Kelley
dfecd819ce build: add new clang libraries for LLVM 15 upgrade 2022-08-02 17:22:16 -07:00
Andrew Kelley
129bd4e9c3 update LLVM library list to LLVM 15 2022-08-02 16:57:32 -07:00
Andrew Kelley
30b98d3973 more LLVM backend fixes
more carnage from opaque pointers API
2022-08-02 16:48:58 -07:00
Loris Cro
447a4cc115 autodoc: fix off-by-1 error in analysis of pointer types 2022-08-02 17:49:36 +02:00
Loris Cro
c5afefec42 autodoc: fix autodoc analysis for @typeInfo
We were previously erroneously saving it as a `@TypeOf`.
2022-08-02 17:49:36 +02:00
Loris Cro
622714b76b autodoc: fix frontend crash while rendering std.mem
Previously we expected to only find decl refs in a `foo.bar.baz`
type of expression. This would crash when trying to render something
like `@typeInfo(T).Int.bits`. We now properly account for builtins
and other components.
2022-08-02 17:49:36 +02:00
Veikka Tuominen
14f0b70570 Sema: add safety for sentinel slice 2022-08-02 18:34:30 +03:00
Veikka Tuominen
292906fb23 Sema: fix reify Fn alignment and args 2022-08-02 18:33:03 +03:00
Veikka Tuominen
4831c1c65f Merge pull request #12277 from Vexu/stage2-compile-errors
Stage2: validate packed struct field types
2022-08-02 18:32:44 +03:00
Loris Cro
2375658da9 Merge pull request #12276 from r00ster91/shortdesc
autodoc: better short description algorithm
2022-08-02 16:32:08 +02:00
Loris Cro
9ba2377d64 Merge pull request #12305 from squeek502/autodoc-field-doc-borders
autodoc: Add borders to field docs to make it clear which field they are associated with
2022-08-02 16:30:12 +02:00
Andrew Kelley
99318e7a95 LLVM backend fixes
Fixing assertions hit after upgrading to opaque pointers API.
2022-08-02 00:04:38 -07:00
Andrew Kelley
44f833129c LLVM backends: work around poorly designed C API
As part of the Opaque Pointers upgrade documentation, LLVM says that the
function LLVMGetGEPSourceElementType() can be used to obtain element
type information in lieu of LLVMGetElementType(), however, this function
actually returns the struct type, not the field type. The GEP
instruction does store the information we need, however, this is not
exposed in the C API. It seems like they accidentally exposed the wrong
field, because one would never need the struct type since one must
already pass it directly to the GEP instruction, so one will always have
it handy, whereas one will usually not have the field type handy.
2022-08-01 23:26:36 -07:00
Andrew Kelley
9e4091200e stage1: avoid using LLVMGetElementType 2022-08-01 23:00:57 -07:00
Andrew Kelley
aa79cc10aa fix bugs from previous two commits 2022-08-01 22:41:45 -07:00
Andrew Kelley
bc2aaf18c8 stage2: LLVM lowering to opaque pointers API 2022-08-01 20:55:17 -07:00
Andrew Kelley
0f793840ae stage1: LLVM lowering to opaque pointers API 2022-08-01 18:16:52 -07:00
Veikka Tuominen
e47706f344 Sema: validate packed struct field types 2022-08-01 23:59:40 +03:00
Veikka Tuominen
f1768b40b2 stage2: better source location for var decls 2022-08-01 23:37:01 +03:00
Veikka Tuominen
57f9405a8f Sema: validate bitcast operand type 2022-08-01 23:37:01 +03:00
Ryan Liptak
e7b6a18331 std.fs: Split Iterator.next on Linux and WASI to allow for handling platform-specific errors
Follow up to #12226, implements the compromise detailed in https://github.com/ziglang/zig/issues/12211#issuecomment-1196011590
2022-08-01 19:38:05 +03:00
antlilja
ab3b614a33 Removed anytype_args field from Fn
anytype_args field was replaced with isAnytypeParam function.
2022-08-01 14:51:54 +02:00
antlilja
cd8070f94f Removed param_names from Fn inside Module.zig
Removed the copy of param_names inside of Fn and changed to
implementation of getParamName to fetch to parameter name from the ZIR.
The signature of getParamName was also changed to take an additional
*Module argument.
2022-08-01 14:51:50 +02:00
Andrew Kelley
70d3912390 update Target, CPU, OS, ABI, etc. to LLVM 15 2022-07-31 18:10:28 -07:00
Andrew Kelley
d46446e4df Merge remote-tracking branch 'origin/master' into llvm15 2022-07-31 15:55:44 -07:00
Ikko Ashimine
ff125db53d wasm: fix typo in CodeGen.zig
occured -> occurred
2022-07-31 13:00:37 -07:00
Ryan Liptak
1a1b7a3afd Linux: Add IN_MASK_CREATE and corresponding error handling in inotify_add_watch
From https://man7.org/linux/man-pages/man7/inotify.7.html

> **IN_MASK_CREATE** (since Linux 4.18)
>
> Watch pathname only if it does not already have a watch associated with it; the error EEXIST results if pathname is already being watched.
2022-07-31 13:00:16 -07:00
Cody Tapscott
075f93fa10 stage2 LLVM: Pass inline assembly outputs directly when not targeting memory
This change provides a basic implementation of #2349 for stage2. There's
still quite a lot of work before this logic is as complete as what's in
Clang (b364535304/clang/lib/CodeGen/CGStmt.cpp (L2304-L2795)),
particularly considering the diversity of constraints across targets.

It's probably not worth doing the complete work until there's a clearer
picture for constraints in Zig's future dedicated ASM syntax, but at
least this gives us a small improvement for now.

As a bonus, this also fixes a bug with how we were handling `_`
identifiers.
2022-07-31 12:59:19 -07:00
Andrew Kelley
1ab15b6c9c Merge pull request #12289 from Vexu/stage2
Stage2: reify functions + fixes
2022-07-31 12:57:53 -07:00
sin-ack
b35490c217 cmake: Print all LLVM config errors instead of just the last one
If you have multiple llvm-config executables in your path, and all of
them cause failures, then only the last failure will be printed. This
can cause confusion when the multiple llvm-config executables are from
different major LLVM versions, i.e. LLVM 13 and 14, which might mask an
error that happened on the LLVM 14 llvm-config with an unrelated error.

This commit makes it so that all errors are collected into a list and
printed all at once; this way, you can see how each llvm-config
executable failed to configure properly. Note that the failures still
won't be printed if a successful configuration is found.
2022-07-31 12:56:00 -07:00
Ryan Liptak
921ba6cad4 autodoc: Add borders to field docs to make it clear which field they are associated with 2022-07-30 17:26:29 -07:00
Cody Tapscott
c0a1b4fa46 stage2: Fix AIR printing
Packed structs never have comptime fields, and a slice might actually be
backed by a variable, which we need to catch before iterating its
elements.
2022-07-30 12:36:11 -07:00
Evan Haas
8632e4fc7b translate-c: use correct number of initializers for vectors
Fixes #12264
2022-07-30 13:24:03 +03:00
Veikka Tuominen
02dc073260 Sema: check comptime slice sentinel 2022-07-30 11:07:37 +03:00
Andrew Kelley
3cf8f283d3 Merge pull request #12085 from topolarity/dyn-link-libcpp
Dynamically link `libc++` if integrating with system LLVM
2022-07-29 14:18:32 -07:00
Veikka Tuominen
d26d696ee0 parser: require expression after colon in slice expr 2022-07-30 00:18:08 +03:00
Veikka Tuominen
4758752e5d Sema: implement coercion from tuples to tuples
Closes #12242
2022-07-30 00:18:08 +03:00
Veikka Tuominen
17622b9db1 Sema: implement @Type for functions
Closes #12280
2022-07-30 00:18:08 +03:00
Veikka Tuominen
f43ea43ac9 stage2: fix hashing of struct values
Closes #12279
2022-07-30 00:17:49 +03:00
Cody Tapscott
4fc2acdaa4 build.zig: Emit warning if "config.h" cannot be found
We now warn the user if config.h could not be located.

This also updates the search to stop early upon encountering a
`.git` directory, so that we avoid recursing outside of the zig
source if possible.
2022-07-29 11:38:58 -07:00
Wei Fu
b3d0694fc5 stage1: remove deadcode ast_print
Fixes: 2a990d696 ("stage1: rework tokenizer to match stage2")
Fixes: b6354ddd5 ("move AST rendering code to separate file")

Signed-off-by: Wei Fu <fuweid89@gmail.com>
2022-07-29 11:28:39 -07:00
Andrew Kelley
64dc1b05d6 Merge pull request #12286 from ziglang/division-safety
Division safety improvements
2022-07-29 11:03:27 -07:00
Andrew Kelley
932d1f785e CI: -Denable-llvm for test-cases
This requires using -Dstatic-llvm and setting the search prefix and the
target, just like it is required for building stage2 and stage3. This
prevents Zig from trying to integrate with the system, which would
trigger an error due to the `cc` command not being installed.

closes #12144
2022-07-29 11:03:12 -07:00
Andrew Kelley
a7a6f38eeb Sema: fix runtime safety for integer overflow with vectors 2022-07-29 11:03:12 -07:00
Cody Tapscott
58540f968a ELF: Scan for dylibs-as-objects when adding rpaths
Shared libraries can be provided on the command line as if they were
objects, as a path to the ".so" file. The "each-lib-rpath" functionality
was ignoring these shared libraries accidentally, causing missing rpaths
in the output executable.
2022-07-29 09:44:45 -07:00
Andrew Kelley
1b1c70ce38 disable failing incremental compilation test case
see #12288

now `zig build test-cases -Denable-llvm` passes locally for me.
2022-07-29 02:35:06 -07:00
Andrew Kelley
daac39364a fix compile error test case note column number 2022-07-29 02:35:06 -07:00
Andrew Kelley
40f8f0134f Sema: enhance div_trunc, div_exact, div_floor
* No longer emit div_exact AIR instruction that can produce a
   remainder, invoking undefined behavior.
 * div_trunc, div_exact, div_floor are extracted from analyzeArithmetic
   and directly handled similarly to div_trunc, integrating them with
   integer overflow safety checking.
 * Also they no longer emit divide-by-zero safety checking when RHS
   is comptime known to be non-zero.
2022-07-29 02:35:06 -07:00
Andrew Kelley
1fc24e8d80 Sema: enhance div instruction analysis
Concrete improvements:
 * Added safety for integer overflow (-MAX_INT/-1)
 * Omit division by zero safety check when RHS is comptime known to
   be non-zero.
 * Avoid emitting `_optimized` variants of AIR instructions for integers
   (this suffix is intended to be used for floats only).

Subjective changes: I extracted the div logic out from analyzeArithmetic
in order to reduce the amount of branches - not for performance reasons
but for code clarity. It is more lines of code however, and some logic
is duplicated.
2022-07-29 02:35:06 -07:00
Andrew Kelley
a482517357 std.debug: default signal handler also handles SIGFPE 2022-07-29 02:35:06 -07:00
Veikka Tuominen
fdaf9c40d6 stage2: handle tuple init edge cases 2022-07-29 10:12:36 +03:00
Veikka Tuominen
9e0a930ce3 stage2: add error for comptime control flow in runtime block 2022-07-29 10:08:35 +03:00
Meghan Denny
b5861193e0 std: rename std.Target.systemz to .s390x 2022-07-28 23:22:44 -07:00
Cody Tapscott
f1feb1369b Dynamically link libc++, if integrating with system LLVM
This ensures that the zigcpp clang driver and LLVM are using the
same copy of libc++. See prior commit for more details.
2022-07-28 22:21:24 -07:00
Cody Tapscott
b0525344a2 Add check to verify libc++ is shared by LLVM/Clang
This check is needed because if static/dynamic linking is mixed incorrectly,
it's possible for Clang and LLVM to end up with duplicate "copies" of libc++.

This is not benign: Static variables are not shared, so equality comparisons
that depend on pointers to static variables will fail. One such failure is
std::generic_category(), which causes POSIX error codes to compare as unequal
when passed between LLVM and Clang.

I believe this is the cause of https://github.com/ziglang/zig/issues/11168

In order to avoid affecting build times when Zig is repeatedly invoked,
we only enable this check for "zig env" and "zig version"
2022-07-28 22:21:24 -07:00
Andrew Kelley
e6b3eae490 Merge pull request #11867 from nektro/patch-2
stage2: ensure builtin packages are always available
2022-07-28 15:20:49 -07:00
Veikka Tuominen
ece1d1daf4 CLI: add error for duplicate package 2022-07-28 15:20:01 -07:00
Meghan
02acde99a1 stage2: ensure 'std', 'builtin', and 'root' is always available to @import 2022-07-28 15:19:17 -07:00
joachimschmidt557
0fc79d602b stage2 ARM: more support for switch statements 2022-07-28 20:44:32 +00:00
r00ster91
2c7387aef5 autodoc: better short description algorithm 2022-07-28 21:37:36 +02:00
Andrew Kelley
d3389eadf4 update C headers to LLVM 15
release/15.x 37007475ca1b345b4c5d340e228bcd7a62732d81
2022-07-28 11:54:23 -07:00
Andrew Kelley
adb4a95302 update to LLVM 15
release/15.x 37007475ca1b345b4c5d340e228bcd7a62732d81
2022-07-28 11:53:25 -07:00
Loris Cro
e863292fe2 autodoc: no whitespace in json output for release builds
With this change, stdlib autodocs go from 24mb to 16mb (-8mb).
2022-07-28 15:08:58 +02:00
Andrew Kelley
c650ccfca7 Merge pull request #12265 from ziglang/stage3-run-translated-c
CI: test-run-translated-c with stage3
2022-07-27 22:04:00 -07:00
Andrew Kelley
3ccb6a0cd4 CI: run test-run-translated-c tests with stage3 2022-07-27 17:56:59 -07:00
Andrew Kelley
3ba7098a17 LLVM: fix returning extern union with C callconv 2022-07-27 17:56:15 -07:00
Andrew Kelley
6a4df2778e AstGen: fix ref instruction injection for functions
For the expressions regarding return type, alignment,
parameter type, etc.
2022-07-27 16:19:23 -07:00
Andrew Kelley
401abd793d run-translated-c: disable two failing tests
Issues reported:
 * #12263
 * #12264
2022-07-27 16:19:23 -07:00
Andrew Kelley
f880af369d LLVM: fix lowering byte-aligned packed struct field pointers 2022-07-27 16:19:23 -07:00
Andrew Kelley
dfc7493dcb Merge pull request #12256 from Vexu/stage2
stage2 typeInfo UAF fix + more
2022-07-27 16:11:07 -07:00
Andrew Kelley
90f23e131e Merge pull request #12252 from ziglang/stage3-test-cases
CI: run test-cases with stage3
2022-07-27 10:27:12 -07:00
Andrew Kelley
0527b441ae move zig.h to become an installation file
Now instead of zig.h being baked into the compiler binary, it is a
header file distributed along with all the other header files
distributed with Zig.

Closes #11643
2022-07-27 10:26:45 -07:00
Veikka Tuominen
793db63746 Sema: copy fn param ty in zirTypeInfo
Closes #12247
2022-07-27 18:27:17 +03:00
LordMZTE
c6f5832bb6 Module: fix inverted condition 2022-07-27 18:17:07 +03:00
LordMZTE
8c4896fb3a Module: use path.isSep
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-07-27 18:17:07 +03:00
LordMZTE
1110eafe9b Module: fix error message importing file starting with root path 2022-07-27 18:17:07 +03:00
r00ster91
baafb8a491 std.fmt: add more invalid format string errors 2022-07-27 18:07:53 +03:00
r00ster91
4ef7d85810 std.fmt: lowercase compile errors
`compileError\("([A-Z])` and `compileError\("\L\1`. It's pretty convenient.
2022-07-27 18:07:53 +03:00
Veikka Tuominen
3818d63dd8 Sema: resolve pointee type in zirReify
Closes #12223
2022-07-27 17:11:46 +03:00
Veikka Tuominen
e4a36a4cec AstGen: add dbg_stmts for unreachable and @panic
Closes #12249
2022-07-27 17:11:46 +03:00
Evan Haas
7ba1f9bfb5 translate-c: take address of functions before passing them to @ptrToInt
Fixes #12194
2022-07-27 14:03:08 +03:00
Andrew Kelley
20c230cda9 test-cases harness: annotate an optional type
Not sure why this is needed by the CI; it's not needed locally. This is
a mystery that will have to wait for another day.
2022-07-27 02:13:01 -07:00
Andrew Kelley
ffac6a1b9f CI: run test-link with stage3 2022-07-26 20:23:33 -07:00
Andrew Kelley
3de9ffa84d CI: run test-cases with stage3
See #12144 for why I did not `-Denable-llvm` yet.
2022-07-26 20:15:57 -07:00
Andrew Kelley
bdaa915a02 test-cases: remove failing test
This causes a stack overflow in a debug build of stage3 unfortunately. I
will open an issue to track this test coverage, which we absolutely
should get working - users of the compiler should get a compile error,
not a segfault if they hit the default branch quota from abusing
recursive inline functions.

Note that the problem does not occur in a release build of stage3
which has significantly reduced stack usage.

On Linux, I tried bumping up the stack size from 32 MiB to 64 MiB and it
did not solve the problem. I'm not sure why not. It seems like it should
be fine.

Note that we also have a problem of running test-cases in multi-threaded
mode which is currently the default. Currently Zig threads are spawned
with 16 MiB stack space.
2022-07-26 20:12:40 -07:00
Andrew Kelley
acf1aa10c2 test-cases harness: refresh just before update()
This makes it so that in a -Dsingle-threaded build of test-cases, if a
crash happens, the test case name will be printed just before the stderr
of the crash.
2022-07-26 20:11:52 -07:00
Andrew Kelley
4e53249d76 test-cases harness: improve stage2 compatibility
* proper skip_stage1 mechanism that doesn't get side-stepped with
   manually added test cases.
 * avoid runtime-known function pointers.
 * check for type equality more simply without checking the type name.
2022-07-26 20:09:48 -07:00
Andrew Kelley
ea3db3274d link: avoid passing bad ptrs to pwritev
At least on Linux, the pwritev syscall checks the pointer and returns
EFAULT before it checks if the length is nonzero.

Perhaps this should be fixed in the standard library, however, these are
still improvements since they make the kernel do less work within the
syscall.
2022-07-26 20:05:54 -07:00
Andrew Kelley
0bc4726e00 LLVM: add probe-stack function attribute 2022-07-26 20:05:06 -07:00
Andrew Kelley
a127693f95 start code: enable segfault handler for stage2 2022-07-26 20:04:24 -07:00
Andrew Kelley
c8c798685f Merge pull request #12244 from Vexu/stage2
Minor stage2 fixes
2022-07-26 17:41:26 -07:00
Andrew Kelley
e2d4709779 C ABI tests no longer apply to only stage1 2022-07-26 14:51:45 -07:00
Veikka Tuominen
d6e3988fe8 Sema: better error when coercing error sets 2022-07-26 23:29:54 +03:00
Andrew Kelley
f50c98a75a test-cases harness: test all updates
even if some are "run" on foreign hosts.

closes #12193
2022-07-26 13:28:46 -07:00
Andrew Kelley
7a09bce232 Merge pull request #12136 from topolarity/llvm-config-rework
CMake: Improve usage of `llvm-config` (esp. for consistent static/shared linking)
2022-07-26 11:41:00 -07:00
Andrew Kelley
0ffcf19e3d Merge pull request #12237 from Vexu/stage2-compile-errors
Stage2 improve errors for builtin function options structs
2022-07-26 11:26:35 -07:00
InKryption
a0d3a87ce1 std.fmt: require specifier for unwrapping ?T and E!T 2022-07-26 11:25:49 -07:00
Veikka Tuominen
7862ab9f41 Sema: disable "unreachable else prong" error for error sets for now
Closes #11798
2022-07-26 16:40:24 +03:00
Veikka Tuominen
5d99e5ecd4 Sema: improve expression value ignored error
Closes #4483
2022-07-26 16:40:24 +03:00
Veikka Tuominen
3d18c8c130 Sema: resolve lazy values for compile log
Close #12204
2022-07-26 16:40:24 +03:00
Veikka Tuominen
d78532f462 Sema: give comptime_field_ptr priority over field_ptr in tuples
Closes #11983
2022-07-26 16:40:24 +03:00
r00ster
1a16b7214d std.mem: add reset to SplitBackwardsIterator and SplitIterator 2022-07-26 14:26:46 +03:00
Veikka Tuominen
a463dc7d6c AstGen: disable null bytes and empty stings in some places
Namely:
 * test names
 * identifiers
 * library names
 * import strings
2022-07-26 12:14:59 +03:00
Veikka Tuominen
2f54129087 parser: add error for doc comment attached to comptime or test blocks 2022-07-26 12:14:59 +03:00
Veikka Tuominen
825fc654b6 Sema: better source location for builtin options 2022-07-26 12:14:59 +03:00
Veikka Tuominen
28478a4bac Module: improve handling of errors in @call arguments 2022-07-26 12:14:59 +03:00
Jakub Konka
20ea44ef10 macho: fix memory leak and refactor Target usage 2022-07-25 22:46:43 -07:00
r00ster
cff5d9c805 std.mem: add first method to SplitIterator and SplitBackwardsIterator 2022-07-25 22:04:30 +03:00
Veikka Tuominen
2f34d06d01 Sema: analyzeInlineCallArg needs a block for the arg and the param 2022-07-25 22:04:08 +03:00
Cody Tapscott
abc1ae538f CMake: Search for Clang in CMAKE_LIBRARY_PATH, CMAKE_PREFIX_PATH, and CMAKE_FRAMEWORK_PATH
On some systems (esp. systems that use unique hashed file-paths for
library-versions like Nix), we can't expect LLVM and Clang to share
lib/bin directories.

The best we can do is find the matching clang libraries in the
CMAKE_LIBRARY_PATH provided by the environment
2022-07-25 10:38:52 -07:00
VÖRÖSKŐI András
370793a36b PriorityDequeue: use compareFn in update() method 2022-07-25 18:12:32 +03:00
Luuk de Gram
9a3dacc00e Merge pull request #12188 from Luukdegram/llvm-wasm-c-abi
stage2: llvm - Implement C ABI when targetting wasm32
2022-07-25 16:12:36 +02:00
Ryan Liptak
75e5b38410 std.fs: End iteration on Linux/WASI during Iterator.next when hitting ENOENT
`getdents` on Linux can return `ENOENT` if the directory referred to by the fd is deleted during iteration. Returning null when this happens makes sense because:

- `ENOENT` is specific to the Linux implementation of `getdents`
- On other platforms like FreeBSD, `getdents` returns `0` in this scenario, which is functionally equivalent to the `.NOENT => return null` handling on Linux
- In all the usage sites of `Iterator.next` throughout the standard library, translating `ENOENT` returned from `next` as null was the best way to handle it, so the use-case for handling the exact `ENOENT` scenario specifically may not exist to a relevant extent

Previously, ENOENT being returned would trigger `os.unexpectedErrno`.

Closes #12211
2022-07-25 16:14:25 +03:00
r00ster
8f3ab96b0e std.testing: make the caret indicator line more helpful 2022-07-25 15:51:22 +03:00
Andrew Kelley
0d120fcb89 Merge pull request #12225 from ziglang/ci-stage3-standalone
CI stage3 test coverage for test-standalone and test-cli
2022-07-25 00:46:56 -07:00
Luuk de Gram
a7417f7839 wasm: Enable C-ABI tests for self-hosted compiler 2022-07-25 06:34:00 +02:00
Luuk de Gram
6b4d4c70fd wasm: Only allow lowering C-ABI compatible types 2022-07-25 06:34:00 +02:00
Luuk de Gram
200b2e4ee1 llvm: correctly lower c-abi for Wasm target
When lowering the return type for Wasm if the calling convention is `C`,
it now correctly lower it according to what clang does as specified in:
https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md

This makes use of the same logic as the Wasm backend, ensuring the
generated code does not diverge in function signatures.

When passing arguments accross the C-ABI for the Wasm target,
we want slightly different behavior than x86_64.
For instance: a struct with multiple fields must always be passed
by reference, even if its ABI size fits in a single integer.
However, we do pass larger integers such as 128bit by value,
which LLVM will correctly lower to use double arguments instead.
2022-07-25 06:34:00 +02:00
Luuk de Gram
bf28a47cf2 wasm: pass correct abi-size for scalar values
When returning an aggregate type that contains a scalar value (nested),
its abi-size is passed by bits, rather than bytes to `buildOpcode`.
2022-07-25 06:33:56 +02:00
Luuk de Gram
7c13bdb1c9 Merge pull request #12059 from Luukdegram/linker-tests-run-step
Implement EmulatableRunStep for linker tests
2022-07-25 06:33:01 +02:00
Andrew Kelley
546c75ca46 LLVM: notice the soft_float CPU feature
when deciding whether to lower to x86_fp80 instructions, or softfloat
instructions.

Closes #10847
Closes #12090
2022-07-24 17:10:08 -07:00
Andrew Kelley
93ae386f56 stage2: don't skip liveness or codegen if -femit-asm is supplied
Fixes Godbolt's CLI usage of Zig.
2022-07-24 15:02:05 -07:00
Andrew Kelley
be294e3744 CI stage3 test coverage for test-standalone 2022-07-24 15:02:05 -07:00
Ryan Liptak
4624c81899 std.fs: Fix Walker closing the initial directory when not fully iterated
This is a fix for a regression caused by 61c5d8f8f1

Closes #12209
2022-07-24 12:00:14 -07:00
Andrew Kelley
934573fc5d Revert "std.fmt: require specifier for unwrapping ?T and E!T."
This reverts commit 7cbd586ace.

This is causing a fail to build from source:

```
./lib/std/fmt.zig:492:17: error: cannot format optional without a specifier (i.e. {?} or {any})
                @compileError("cannot format optional without a specifier (i.e. {?} or {any})");
                ^
./src/link/MachO/Atom.zig:544:26: note: called from here
                log.debug("  RELA({s}) @ {x} => %{d} in object({d})", .{
                         ^
```

I looked at the code to fix it but none of those args are optionals.
2022-07-24 11:50:10 -07:00
Lewis Gaul
a08b0fa706 Fix indexing in the test runner's log formatting 2022-07-24 12:08:02 +03:00
InKryption
7cbd586ace std.fmt: require specifier for unwrapping ?T and E!T.
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-07-24 12:01:56 +03:00
Ali Chraghi
0b4a3ec950 std: compile error on invalid testing allocator usage 2022-07-24 11:57:00 +03:00
Meghan
dea437edfb stage2: implement noinline fn 2022-07-24 11:56:33 +03:00
Andreas Reischuck
903bed931d report better error for package not found in stage2 2022-07-24 11:55:37 +03:00
Jonathan Marler
f598234ee8 std.json: expose encodeJsonString and encodeJsonStringChars
Expose 2 functions from std.json.  These functions take a slice of bytes
and forward them to a given writer as a JSON encoded string.

The use case I have for this is in a custom JsonStringWriter.  This writer
takes data and automatically encodes it as JSON string characters and
forwards it to an underlying writer.  I use this JsonStringWriter in
combination with std.fmt.format to go directly from a format string/arg
pair to JSON.  This way I don't have to format my string into a separate
buffer first and encode it afterwards, which avoids the need to create
a temporary buffer to hold the unencoded but formatted string.
2022-07-24 11:51:59 +03:00
Andrew Kelley
a2ab9e36fa Merge pull request #12143 from Vexu/stage2-safety
Stage2 runtime safety progress
2022-07-23 20:09:24 -07:00
Andrew Kelley
9964324856 disable flaky behavior test
see #12208
2022-07-23 20:03:50 -07:00
Cody Tapscott
5337934bcd CMake: Add ZIG_LLVM_LINK_MODE to config.h
This is currently unused, but it will be needed soon so that we can
avoid linking static libc++ if LLVM/Clang is configured as a shared
library.
2022-07-23 09:03:19 -07:00
Cody Tapscott
4113a790b0 CMake: Search more permissively for LLD
This change relaxes the restriction added in the prior commit that LLD
should be alongside LLVM.

This also leaves unresolved the issue of making sure the link mode
(static or shared) of LLD matches that of LLVM/Clang. That would be an
unfortunate restriction, since LLD seems to be provided only as a static
lib on some distros.
2022-07-23 08:55:56 -07:00
Cody Tapscott
3f640ef3d2 CMake: Improve usage of llvm-config, esp. for consistent linking
This commit reworks the LLVM/Clang/LLD discovery process for CMake. The
biggest changes are that:
  1. We search for LLVM from most preferred directory to least, skipping
     any `llvm-config` that is the wrong version, or that doesn't
     support the requested link mode ("static" or "shared").
  2. `ZIG_PREFER_CLANG_CPP_DYLIB` has been renamed to `ZIG_SHARED_LLVM`,
     to better align with `ZIG_STATIC_LLVM`.
  3. We only search for LLVM in the same directory alongside LLVM.
  4. LLVM's link mode is forwarded to Clang, so that we can look for the
     appropriate shared/static libraries.
  5. We use `--link-static` when querying `--system-libs` from llvm-config,
     so that this will include libz and other dependencies for
     statically linking LLD
2022-07-23 08:52:30 -07:00
Luuk de Gram
72c0cebe5c test/link/macho: use EmulationStep for dead_strip 2022-07-23 17:27:47 +02:00
Vincent Rischmann
d99c32c2e1 io_uring: add new flags and opcodes 2022-07-23 17:21:17 +03:00
Veikka Tuominen
baf516218e Sema: don't add union field access safety check for single field unions 2022-07-23 15:40:12 +03:00
Veikka Tuominen
2436dd2c1b Sema: validate duplicate fields in anon structs 2022-07-23 15:40:12 +03:00
Veikka Tuominen
5b29275240 Sema: add some more 'declared here' notes 2022-07-23 15:40:12 +03:00
Veikka Tuominen
881c0cb20b Sema: add default value here note to invalid comptime field store error 2022-07-23 15:40:12 +03:00
Veikka Tuominen
15dddfd84d AstGen: make comptime fields in packed and extern structs compile errors 2022-07-23 15:40:12 +03:00
Veikka Tuominen
0ef4cc738b Sema: check for zero length slices in @alignCast safety 2022-07-23 15:40:12 +03:00
Veikka Tuominen
d75fa86d70 stage2: implement @setFloatMode 2022-07-23 15:40:12 +03:00
Veikka Tuominen
585c160c20 Sema: handle store to comptime field when ResultLoc == .none 2022-07-23 15:40:12 +03:00
Veikka Tuominen
9465906775 Sema: return .comptime_field_ptrs for tuples 2022-07-23 15:40:12 +03:00
Veikka Tuominen
cf87026e52 Sema: @alignCast safety 2022-07-23 15:40:11 +03:00
Veikka Tuominen
711b656773 Sema: @floatToInt safety 2022-07-23 15:40:11 +03:00
Veikka Tuominen
ff7ec4efb5 Sema: bad union field access safety 2022-07-23 15:40:11 +03:00
Veikka Tuominen
55fe34100f Sema: exact division safety 2022-07-23 15:40:11 +03:00
Veikka Tuominen
76d099950a Sema: cast negative to unsigned safety 2022-07-23 15:40:11 +03:00
Veikka Tuominen
0782586b15 Sema: divide by zero safety 2022-07-23 15:40:11 +03:00
Veikka Tuominen
9f10dfcb54 Sema: implement shr_exact runtime safety 2022-07-23 15:40:11 +03:00
Veikka Tuominen
4d20d6874c move passing safety tests to stage2 2022-07-23 15:40:11 +03:00
Veikka Tuominen
72c60acd5d Revert "std.mem.Allocator: add alignedCreate"
This reverts commit 5647a73fea.
2022-07-23 15:30:12 +03:00
viri
b728e6aa00 stage1: don't lowercaseify lib names 2022-07-23 15:04:02 +03:00
Yujiri
6b9f609bd0 Fix #6944: referencing type info alignment causes error in unrelated function 2022-07-23 14:26:52 +03:00
devins2518
5647a73fea std.mem.Allocator: add alignedCreate 2022-07-23 14:22:35 +03:00
InKryption
9555b84ab4 langref: clarify permitted @bitCast usage.
The current phrasing is vague; it is unclear whether it is demonstrating an example of the type of permitted behavior, from which the rule set must be extrapolated, or it is stating that this restriction only applies to the relationship between integers and bare structs.
2022-07-23 14:20:29 +03:00
Allan Regush
9734e643fb docs: Pointer Arithmetic 2022-07-23 13:57:40 +03:00
Veikka Touminen
819c868bbf std.net.getAddressList: fix segfault on bad hostname
Fixes #12065
2022-07-23 13:54:24 +03:00
ominitay
889efddd1a std.json: Fix parsing of large numbers
Numbers greater than about 2^53 are encoded as strings in JSON.
std.json.parseInternal previously errored out in this condition.
2022-07-23 13:52:16 +03:00
Luuk de Gram
2429c3d73c Share logic between EmulatableRunStep & RunStep 2022-07-23 10:08:53 +02:00
Luuk de Gram
34b786fb0f enable link-test on linux CI 2022-07-23 10:08:51 +02:00
Luuk de Gram
4776065036 Use EmulatableRunStep for MachO linker tests 2022-07-23 10:03:51 +02:00
Luuk de Gram
735b6eefe9 rename:RunCompareStep -> EmulatableRunStep
Renamed to better convery the intention of the step
2022-07-23 10:03:51 +02:00
Luuk de Gram
0dc3a0180b show/hide warning for incompatible warnings
Implements running and verifying the expected output when a binary is run.
Also adds warnings when a binary is skipped because of incompatibility.
This warning can be hidden by either setting the option manually through build.zig,
or by providing the option `-Dhide_foreign_warnings`.
2022-07-23 10:03:51 +02:00
Luuk de Gram
fd26c12469 RunCompareStep: implement new step
This creates a new step that can run foreign binaries when
emulation is enabled using options such as `enable_qemu`.
When an incompatible binary is found, the binary will not be executed.
This differs from `RunStep` which will always execute a binary,
regardless of the compatibility.

This is useful for usecases where the user wishes to allow for running the
binary on any supported platform either natively or through emulation,
but not generate an error when met with an incompatibility.
The above is useful when creating test cases that rely on running the binary
and optionally verifying its output.

The addition of this Step was generated by the need for our linker tests.
For that reason, a handy function was created on `CheckObjectStep` to ease
the setup for that.
2022-07-23 10:03:46 +02:00
Jakub Konka
a8bfddfaea Merge pull request #12140 from ziglang/macho-gc-sections
macho: add support for `-dead_strip` (GC sections) and simplify symbol resolution
2022-07-23 00:01:09 -07:00
Andrew Kelley
a035d75a17 Autodoc: update to new ZIR
Fixes a merge conflict with 8e75ba653b
which removed ptr_type_simple and added overflow_arithmetic_ptr.
2022-07-22 21:24:19 -07:00
Andrew Kelley
7502e490cb Merge pull request #12173 from ziglang/autodocs-rebased
New Autodocs!
2022-07-22 20:56:59 -07:00
Andrew Kelley
f591936480 Merge pull request #12198 from Vexu/stage2
Sema: fix loading and storing of optional pointers represented as pointers
2022-07-22 20:47:40 -07:00
Jakub Konka
cf6cfc830d macho: fix use-after-move in placeDecl
Previously, we would get a pointer to a slot in the symbol table,
apply changes to the symbol, and return the pointer. This however
didn't take into account that the symbol table may be moved in memory
in-between the modification and return from the function (`fn placeDecl`).
Prior to my rewrite, this was not possible within the body of the said
function. However, my rewrite revamped how we allocate GOT atoms and
their matching symtab indexes, which now may cause a move in memory
of the container.
2022-07-23 00:13:34 +02:00
Jakub Konka
eb1b2f5c58 macos: add /usr/local/* paths conditional on macOS major version
`/usr/local/include`, `/usr/local/lib` and `/Library/Frameworks`
have been deprecated since approximately macOS 11, and so to avoid
redundant and misinformed warning messages generated by the linker,
add those dirs only when natively targeting macOS 10.x.x or below.
2022-07-22 14:11:23 -07:00
Jakub Konka
600348283f macho: include __StaticInit input sections as GC roots 2022-07-22 21:19:33 +02:00
Andrew Kelley
5dd59a5423 Merge pull request #12191 from ziglang/underaligned-fields
LLVM: fix lowering of structs with underaligned fields
2022-07-22 11:58:50 -07:00
Veikka Tuominen
423a19fa60 Sema: add error for dereferencing invalid payload ptr at comptime 2022-07-22 21:10:50 +03:00
Veikka Tuominen
03b1fbe50d stage2: fix airIsErr when is_ptr == true 2022-07-22 21:07:55 +03:00
Veikka Tuominen
1f748fe426 Sema: fix mutation of optional ptr represented as regular ptr 2022-07-22 19:50:11 +03:00
VÖRÖSKŐI András
d925d19cfc PriorityQueue: use compareFn in update()
update() calls mem.indexOfScalar() which uses `==` for comparing items,
which fails when the operator is not supported.
As PirorityQueue needs a comparing function anyway we can use `.eq` results
to identify matching objects.

closes #9918
2022-07-22 19:25:38 +03:00
Dan Ellis Echavarria
d1d892c83c SIMD size suggestions: suggestions code now compiles, added more
architectures
The idea behind this is using the register capabilities in safe amounts,
 there is still some consideration to be done.
+ Fixed compile error using std.Target.<arch>.featureSetHas
+ X86 MMX and "3DNOW" 64 bits register usage considered for vector size
+ Added ARM Neon recommened usage of 128 bits (The size of the register)
+ Added AARCH64 Neon and SVE for 128 bits. SVE could use in theory up to
  2048 bits, but found only evidence of functional 512 bits on a super
       computer, decided on using 128 bits as a safety
+ Added Altivec recommendation of using the 128 bits long register
+ Using MIPS msa 2x64bits capabilities, usage of 64 bits registers for MDMX
  systems, need testing on how using bigger values affect performance
+ Using V extension on RISC-V, which is extendable via instructions, decided on 128 bits
  as a value to not use all registers
+ in SPARC the 64 bits registers are used, a max of 32 registers
  are to be used for configurable simd instructions, decided on using
the size of the register, need testing on performance hit on using a
bigger sized register vector size
2022-07-22 18:58:43 +03:00
Jakub Konka
f8458a549b macho: dead_strip defaults: off for debug, on for release 2022-07-22 16:58:21 +02:00
Jakub Konka
0901e4805c macho: fix zig cc and c++ using stage2 llvm 2022-07-22 16:58:21 +02:00
Jakub Konka
ca74656685 macho: move GC code into dead_strip.zig module
Implement marking live atoms that reference other live atoms if
required by the compiler (via section attribute).
2022-07-22 16:58:21 +02:00
Jakub Konka
7345976261 macho: sort subsection symbols by seniority 2022-07-22 16:58:21 +02:00
Jakub Konka
39df241df4 macho: do not GC local symbols unless reference dead symbols
If a local references another local, we keep it. If it doesn't
reference anything, we keep it. Otherwise, we dead strip it.
2022-07-22 16:58:21 +02:00
Jakub Konka
a089a6dc4f macho: parse data-in-code when writing LINKEDIT segment 2022-07-22 16:58:21 +02:00
Jakub Konka
2c184f9a5f link-tests: add checkNotPresent and add -dead_strip smoke test
`checkNotPresent` is the inverse of `checkNext` - if the phrase is
found in the output, then it fails the test.
2022-07-22 16:58:21 +02:00
Jakub Konka
2dfc78dc03 macho: limit export info to entrypoint and mh symbol when executable 2022-07-22 16:58:21 +02:00
Jakub Konka
0f1b5d45bc macho: mark __mh_execute_header as ref'd dynamically 2022-07-22 16:58:21 +02:00
Jakub Konka
0da8ba816a macho: do not store stabs; generate on-the-fly instead 2022-07-22 16:58:21 +02:00
Jakub Konka
41b91442f4 macho: improve logs for dyld info 2022-07-22 16:58:21 +02:00
Jakub Konka
4658d857de macho: fix caching linker line in incremental setting 2022-07-22 16:58:20 +02:00
Jakub Konka
b380ed6a72 macho: deallocate globals keys 2022-07-22 16:58:20 +02:00
Jakub Konka
817939d20a macho: don't store GC roots globally
Instead, if dead-strip was requested, create a temp container and
pass it around.
2022-07-22 16:58:20 +02:00
Jakub Konka
61b4119a7d macho: link atom starting section by orig section id
In x86_64 relocs, it can so happen that the compiler
refers to the same atom by both the actual assigned symbol
and the start of the section. In this case, we need to
link the two together so add an alias.
2022-07-22 16:58:20 +02:00
Jakub Konka
35a5a4a0e4 macho: fix marking sections for pruning in GC 2022-07-22 16:58:20 +02:00
Jakub Konka
d80fcc8a0b macho: rework symbol handling for incremental stage2 builds 2022-07-22 16:58:20 +02:00
Jakub Konka
eeb6d8f045 macho: fix compilation issues on 32bit hosts 2022-07-22 16:58:20 +02:00
Jakub Konka
9eb7e5182b macho: rework symbol handling to match zld/ELF
Now, each object file will store a mutable table of symbols that it
defines. Upon symbol resolution between object files, the symbol
will be updated with a globally allocated section ordinal and address
in virtual memory. If the object defines a globally available symbol,
its location only (comprising of the symbol index and object index)
will be stored in the globals map for easy access when relocating, etc.
This approach cleans up the symbol management significantly, and matches
the status quo used in zld/ELF.

Additionally, this makes scoping symbol stabs easier too as they are
now naturally contained within each object file.
2022-07-22 16:58:20 +02:00
Jakub Konka
843701d0fe macho: remove unused fields from Atom 2022-07-22 16:58:20 +02:00
Jakub Konka
03feea0fb2 macho: split section into subsections if requested and/or possible 2022-07-22 16:58:20 +02:00
Jakub Konka
d042b88c11 macho: put parsing into an atom into a helper 2022-07-22 16:58:20 +02:00
Jakub Konka
b81c48d985 macho: read the entire file contents into memory at once 2022-07-22 16:58:20 +02:00
Jakub Konka
7ec9a4f382 cli: support --gc-sections and --no-gc-sections for Zig sources 2022-07-22 16:58:20 +02:00
Jakub Konka
44ee42c6bc cli: parse -dead_strip MachO linker flag 2022-07-22 16:58:20 +02:00
Veikka Tuominen
c619371ec1 Sema: fix loading and storing of optional pointers represented as pointers 2022-07-22 17:03:42 +03:00
Veikka Tuominen
393d59bb72 Sema: allow C pointers in fieldCallBind 2022-07-22 17:03:42 +03:00
Veikka Tuominen
8a488fcdb8 Sema: validate empty array init 2022-07-22 17:03:42 +03:00
Veikka Tuominen
47de73980e Sema: use resolveMaybeUndefValIntable in zirIntToPtr 2022-07-22 17:03:42 +03:00
Veikka Tuominen
8e75ba653b Merge pull request #12117 from Vexu/stage2-compile-errors
Stage2: explain why value must be comptime known
2022-07-22 13:07:32 +03:00
Andrew Kelley
5cd1ccf4b9 CI: stage3 coverage for test-translate-c 2022-07-21 22:52:08 -07:00
Andrew Kelley
046a4d084b update test-translate-c cases to stage2 2022-07-21 22:51:17 -07:00
Andrew Kelley
3114978389 update standalone test cases for stage2 2022-07-21 22:51:17 -07:00
Andrew Kelley
46a06074eb tests: remove superfluous newlines from logs 2022-07-21 22:51:17 -07:00
Andrew Kelley
f550c29c4e LLVM: fix lowering of structs with underaligned fields
When lowering a struct type to an LLVM struct type, keep track of
whether there are any underaligned fields. If so, then make it a packed
llvm struct. This works because we already insert manual padding bytes
regardless.

We could unconditionally use an LLVM packed struct; the reason we bother
checking for underaligned fields is that it is a conservative choice, in
case LLVM handles packed structs less optimally. A future improvement
could simplify this code by unconditionally using packed LLVM structs
and then make sure measure perf is unaffected.

closes #12190
2022-07-21 22:51:17 -07:00
Andrew Kelley
b749487f48 add new compile error note to old test case 2022-07-21 22:05:46 -07:00
Andrew Kelley
25f3be32db Sema: fix fn pointer align disagrees with fn align error
Check the specified function alignment rather than the effective
function alignment.
2022-07-21 15:19:56 -07:00
Andrew Kelley
fc6e111b76 Sema: improve compile error for bad function alignment
* Integrate more declaratively with src/target.zig
 * Only trigger the check when a function body is found, do not trigger
   for function types.
2022-07-21 13:55:29 -07:00
Andrew Kelley
b946934576 build.zig: 32 MiB stack size
This gives more headroom for comptime recursion, especially for debug
builds of Zig.
2022-07-21 12:23:33 -07:00
Andrew Kelley
644baa0f5b constrain target/backend of new test cases
avoids testing stuff that doesn't work yet.
2022-07-21 12:21:30 -07:00
Veikka Tuominen
794beafb9c Sema: validate extern struct field types earlier
`validateExternType` does not require the type to be resolved so we can
check it earlier. Only doing it in `resolveTypeFully` lead to worse or
missing compile errors.
2022-07-21 12:21:30 -07:00
Veikka Tuominen
821e4063f9 Sema: better source location for function call args 2022-07-21 12:21:30 -07:00
Veikka Tuominen
79ef0cdf30 Sema: better function parameter source location 2022-07-21 12:21:30 -07:00
Veikka Tuominen
83b2d2cd3e Sema: better source location for incompatible capture group 2022-07-21 12:21:30 -07:00
Veikka Tuominen
9fb8d21a01 AstGen: add error for fields in opaque types 2022-07-21 12:21:30 -07:00
Veikka Tuominen
1705a21f80 Sema: more union and enum tag type validation 2022-07-21 12:21:30 -07:00
Veikka Tuominen
8feb398760 Sema: validate function parameter types and return type 2022-07-21 12:21:30 -07:00
Veikka Tuominen
d851b24180 Sema: validate function pointer alignment 2022-07-21 12:21:30 -07:00
Veikka Tuominen
76e7959a90 Sema: explain why comptime is needed 2022-07-21 12:21:30 -07:00
Veikka Tuominen
195c3cd89f fix errors in tests not tested locally or on CI 2022-07-21 12:21:30 -07:00
Veikka Tuominen
d729173204 stage2: better pointer source location 2022-07-21 12:21:30 -07:00
Veikka Tuominen
29815fe9de Sema: disallow 'align' on functions on wasm 2022-07-21 12:21:30 -07:00
Veikka Tuominen
62120e3d0e Sema: fix non-exhaustive union switch checks 2022-07-21 12:21:30 -07:00
zc
460211431f complete the drone pipeline runner type and platform os 2022-07-21 11:17:35 -07:00
Yujiri
b8bf5de75a Fix #9184: fmtIntSizeDec/fmtIntSizeBin support FormatOptions 2022-07-21 18:41:21 +03:00
Loris Cro
92966088c2 autodoc: cleanup file-related operations 2022-07-21 16:31:45 +02:00
Loris Cro
d74a49456d autodoc: use already open handles to output docs artifacts 2022-07-21 14:17:25 +02:00
Andrew Kelley
e054877466 CI: stage3 covers test-universal-libc and builds stage1 2022-07-20 23:28:30 -07:00
Andrew Kelley
ca3adb83b7 Merge pull request #12111 from ziglang/ci-stage3
CI: increase stage3 test coverage
2022-07-20 17:07:19 -07:00
Andrew Kelley
5b7e332b28 disable new behavior test in stage1
I regressed this in 379beceffd1b0a0b0d8f3163dc02eba1e53ffa39; sorry
about that.
2022-07-20 16:17:33 -07:00
fd9b55a640 build.zig: teach --compress-debug-sections
Now that #11863 is landed, let's expose it to the zig programs that
build stuff via `build.zig`. "Benchmarks" with [turbonss](https://git.sr.ht/~motiejus/turbonss):

Built with:

    $ zig build -Dtarget=x86_64-linux-gnu.2.19 -Dcpu=x86_64_v3 -Drelease-small=true

*Debug, uncompressed*

    174K turbonss-analyze
    161K turbonss-getent
    1.2M turbonss-unix2db
    448K libnss_turbo.so.2.0.0

*Debug, compressed*

     78K turbonss-analyze
     86K turbonss-getent
    572K turbonss-unix2db
    190K libnss_turbo.so.2.0.0

*Stripped, for completeness*

     17K turbonss-analyze
     20K turbonss-getent
    197K turbonss-unix2db
     26K libnss_turbo.so.2.0.0
2022-07-20 18:26:17 -04:00
Andrew Kelley
c1f3aca602 Merge pull request #12177 from Vexu/packed-ptr
stage2 llvm: fix handling of pointer fields in packed structs
2022-07-20 18:22:25 -04:00
Andrew Kelley
379beceffd improve test case from previous commit
Now it checks that the code is correctly compiled rather than only checking
that it does not crash the compiler.
2022-07-20 15:21:24 -07:00
Andrew Kelley
21064d9144 disable std lib test failing with self-hosted ReleaseSafe
I opened a corresponding issue #12178 which has the 0.10.0 milestone, so
this must be fixed before we release.
2022-07-20 12:50:58 -07:00
Andrew Kelley
1ec50613bf CI: increase stage3 test coverage
* Use a debug build of stage3 instead of a debug build of stage2 for
   our self-hosted compiler test coverage.
 * Move coverage from stage1 to stage3 for:
   - building self-hosted without LLVM
   - building self-hosted for 32-bit arm
   - test-compiler-rt
   - test-behavior
   - test-std
   - test-compare-output
   - test-asm-link
   - test-fmt
2022-07-20 12:27:03 -07:00
Andrew Kelley
08f3c7960a build.zig: remove deleted .cpp file 2022-07-20 11:10:46 -07:00
Veikka Tuominen
d41dd499a9 stage2 llvm: fix handling of pointer fields in packed structs 2022-07-20 17:07:12 +03:00
Cody Tapscott
de62bd0647 macho: Pass sections by pointer when slicing names
We were accidentally returning a pointer to stack memory, because these
arguments were passed by value. It's just an accident that stage 1 was
passing these by reference, so things were alright until stage 3.
2022-07-20 03:45:29 -04:00
Loris Cro
268edce862 Autodoc: fix int expr size for 32bit targets 2022-07-20 08:34:05 +02:00
Andrew Kelley
42b2fb4c5d Autodoc: stage2 miscompilation workaround
There is no issue open for this yet; I will file one after pushing this
commit.
2022-07-19 19:55:12 -07:00
Andrew Kelley
aa1a06bf9b Autodoc: small polish on the html 2022-07-19 19:10:12 -07:00
Loris Cro
572f9a5602 Autodoc: add warning banner to html 2022-07-19 19:10:12 -07:00
Andrew Kelley
7d636f0f9d delete the stage1 implementation of autodoc 2022-07-19 19:10:12 -07:00
Andrew Kelley
8df1b91d17 Autodoc: clean up debug printing
use std.log.scoped
2022-07-19 19:10:12 -07:00
Andrew Kelley
e5d21e10bc Autodoc: skip docs when compile errors occur 2022-07-19 19:10:12 -07:00
Andrew Kelley
84adbeb077 Autodoc: update to new array_type ZIR 2022-07-19 19:10:12 -07:00
Andrew Kelley
22d61faf17 Autodoc: update to new ZIR encoding
* error_to_int, int_to_error moved to extended
 * struct field encodings are different
2022-07-19 19:10:12 -07:00
Loris Cro
ad7bc57919 autodoc: fix rendering of function arguments 2022-07-19 19:10:12 -07:00
Loris Cro
8ec34eb046 autodoc: handle result location instructions 2022-07-19 19:10:12 -07:00
Loris Cro
947eff6e39 autodoc: handle special case of autodoc for std 2022-07-19 19:10:12 -07:00
Loris Cro
54fe5ea4f3 autodoc: add support for new func-related Zir 2022-07-19 19:10:12 -07:00
Vallahor
fed9dcff24 autodoc: @as behavior in js 2022-07-19 19:10:12 -07:00
Vallahor
341431b15c autodoc: handling more values sections 2022-07-19 19:10:12 -07:00
Loris Cro
24a79426ec autodoc: update array analysis to new Zir 2022-07-19 19:10:12 -07:00
Vallahor
866bbb2e7a autodoc: fiedRef type rendering 2022-07-19 19:10:12 -07:00
Vallahor
e7476fd81c autodoc: handling refPath and fieldRef 2022-07-19 19:10:12 -07:00
Vallahor
81147dd101 autodoc: initial work in opaque_decl 2022-07-19 19:10:12 -07:00
Loris Cro
dd4bd55ef6 autodoc: rework json printing code
We're now using `std.json.writeStream`, which makes our prints correct
in terms of escapes and also reduces the amount of json-related code.
Unfortunately, we have to mess around with the json stream writer state
whenever we end up using `std.json.stringify` for convenience.
2022-07-19 19:10:12 -07:00
Loris Cro
45e3b1a23d autodoc: remove type annotations from main.js 2022-07-19 19:10:12 -07:00
Vallahor
02bd5fe93a autodoc: experiment get line info 2022-07-19 19:10:12 -07:00
Loris Cro
cd357fc767 autodoc: fix package issue when analyzing stdlib 2022-07-19 19:10:12 -07:00
Loris Cro
d2baf404a5 autodoc: enabled packages 2022-07-19 19:10:12 -07:00
Loris Cro
a5e7b0e4db autodoc: restore support for zig version + cleanup & init work to fix packages 2022-07-19 19:10:12 -07:00
Vallahor
20b861d805 autodoc: fixing a bug in builtin functions when the typeRef is null 2022-07-19 19:10:12 -07:00
Vallahor
f189e46b8e autodoc: add some tags 2022-07-19 19:10:12 -07:00
Vallahor
f13db1ce18 autodoc: add cmpxchg_strong/weak 2022-07-19 19:10:12 -07:00
Vallahor
4530b446b1 autodoc: @check array_cat and array_mul 2022-07-19 19:10:12 -07:00
Vallahor
5e52666c83 autodoc: add some builtin functions and float128 2022-07-19 19:10:12 -07:00
Vallahor
9613aca417 autodoc: refactoring binOp 2022-07-19 19:10:12 -07:00
Loris Cro
918475e2e2 autodoc: new design for function list 2022-07-19 19:10:12 -07:00
Loris Cro
06ee275295 autodoc: fix crash when handling siwtch_block instructions 2022-07-19 19:10:12 -07:00
Vallahor
dd9a018185 fix: slice_start, slice_end and slice_sentinel typeRef are now showing the slice type 2022-07-19 19:10:12 -07:00
Vallahor
1f5df0e034 add: slice_start, slice_end and slice_sentinel 2022-07-19 19:10:12 -07:00
Vallahor
b9fa91002e add: builtins functions 2022-07-19 19:10:12 -07:00
Vallahor
a0ec87be71 add: merge_error_sets and @alignOf() need a checkin to confirm it's fully work 2022-07-19 19:10:12 -07:00
Loris Cro
d858f26139 autodoc: fixes to generic fn support plus linking support 2022-07-19 19:10:12 -07:00
Loris Cro
413cfd4066 autodoc: init generic function support 2022-07-19 19:10:12 -07:00
Loris Cro
51647c305e autodoc: add buffering to the json writer 2022-07-19 19:10:12 -07:00
Vallahor
f07534069d WIP: switch_block tag 2022-07-19 19:10:12 -07:00
Vallahor
9be9e4d02c add: @enumToInt() WIP 2022-07-19 19:10:12 -07:00
Vallahor
5fcf0b0565 add: handling @bitSizeOf() need to check why not working correctly with align() 2022-07-19 19:10:12 -07:00
Vallahor
a529d747c9 add: binOp @alignCast and bit_or 2022-07-19 19:10:12 -07:00
Vallahor
f59bb65ff5 add: handling @bitCast as binOp 2022-07-19 19:10:12 -07:00
Vallahor
8e835fd3a2 add: handling binOp div 2022-07-19 19:10:12 -07:00
Vallahor
d5d27f245b issue: reminder to fix array_init 2022-07-19 19:10:12 -07:00
Vallahor
1213123ad0 fix: *.{} array are now printed as type *[]comptime 2022-07-19 19:10:12 -07:00
Vallahor
d23ccdb8d9 fix: "match failure" in c.zig file @check other files and handling floats and undefined values in js 2022-07-19 19:10:12 -07:00
Vallahor
462f751902 binOp now showing better it's need a better struture, right now it's has a hack one 2022-07-19 19:10:11 -07:00
Vallahor
9f6bdc4bbe add: binOp WIP 2022-07-19 19:10:11 -07:00
Vallahor
c0c9925255 fix: apparently doing this the @as problem is solved @check 2022-07-19 19:10:11 -07:00
Vallahor
d55761f07e fix: print align() in pointers 2022-07-19 19:10:11 -07:00
Vallahor
b96bd33f55 add: handling to extra information in ptr_type 2022-07-19 19:10:11 -07:00
Vallahor
b823f01141 add: extra information in extendedFn 2022-07-19 19:10:11 -07:00
Vallahor
927f087a40 fix: calling convention 2022-07-19 19:10:11 -07:00
Vallahor
0e5a2bbd63 fix: NoReturn and WIP in calling_conventions 2022-07-19 19:10:11 -07:00
Vallahor
ec8d29ff25 fix: anyopaque_type. it was showing *[1]anyopaque now *anyopaque 2022-07-19 19:10:11 -07:00
Vallahor
2809b01b2f add: noreturn keyword at end of the fn decl 2022-07-19 19:10:11 -07:00
Vallahor
a3f44b0d21 fixes: @check 2022-07-19 19:10:11 -07:00
Vallahor
11eb11d7d6 fix: slices 2022-07-19 19:10:11 -07:00
Vallahor
f04f23a3aa add: extern, callconv and return errors 2022-07-19 19:10:11 -07:00
Vallahor
76e934dba8 fix: comptime not showing in all anytype params anymore. add: pointer flags 2022-07-19 19:10:11 -07:00
Vallahor
c449788b11 fix: typeOf_peer working in all cases 2022-07-19 19:10:11 -07:00
Vallahor
4bd359a849 add: handling typeof_peer 2022-07-19 19:10:11 -07:00
Vallahor
1792842808 fix: typeOf "match failed" with a call after @TypeOf() 2022-07-19 19:10:11 -07:00
Vallahor
270e2c18bf fix: @TypeOf() now rendering 2022-07-19 19:10:11 -07:00
Vallahor
e1d55385ff add: typeof_builtin (not fully implemented) 2022-07-19 19:10:11 -07:00
Vallahor
1a4d00d832 add: handling some anytype cases 2022-07-19 19:10:11 -07:00
Vallahor
cadee07ef4 fix: paths working on windows 2022-07-19 19:10:11 -07:00
Vallahor
7b11c23da6 fix: comptimeExpr working with generated data 2022-07-19 19:10:11 -07:00
Vallahor
4da1f1fb32 add: handling comptimeExpr in js 2022-07-19 19:10:11 -07:00
Vallahor
2a3fb341aa fix: handling more types of sentinels. now can be structs too 2022-07-19 19:10:11 -07:00
Loris Cro
d707cd6e6d autodoc: improve decl categorization and fix enumliteral arrays/ptrs 2022-07-19 19:10:11 -07:00
Vallahor
bde1caa4ce fix: array_init_anon know working 2022-07-19 19:10:11 -07:00
Vallahor
21fd4a7a8b fix: printing const in types and fn decl and sentinel in strings 2022-07-19 19:10:11 -07:00
Vallahor
019fd45617 fix: sentinel working with types and in fn decls 2022-07-19 19:10:11 -07:00
Vallahor
5b20b1f2a7 add: array init refs 2022-07-19 19:10:11 -07:00
Vallahor
646079c968 add: rendering sentinel in js and some fixes in autodoc 2022-07-19 19:10:11 -07:00
Vallahor
5a4005323f add: sentiel 2022-07-19 19:10:11 -07:00
Loris Cro
aa545dbd1e autodoc: improve frontend rendering 2022-07-19 19:10:11 -07:00
Loris Cro
cf685c1132 autodoc: collect type information for some expressions 2022-07-19 19:10:11 -07:00
Loris Cro
0339e1c7d4 update to new code from master branch 2022-07-19 19:10:11 -07:00
Loris Cro
ae4b5c29b2 autodoc: fix final js type error 2022-07-19 19:10:11 -07:00
Loris Cro
cc71003cfc autodoc: improved rendering container fields and fixed rendering of func
args
2022-07-19 19:10:11 -07:00
Loris Cro
d85259989e autodoc: var 2 let in main.js 2022-07-19 19:10:11 -07:00
Loris Cro
67da1b8c88 autodoc: fixed all type errors in main.js 2022-07-19 19:10:11 -07:00
Loris Cro
80f9490e06 autodoc: more js type fixes 2022-07-19 19:10:11 -07:00
Loris Cro
919b8e400c autodoc: more typechecking in main.js 2022-07-19 19:10:11 -07:00
Loris Cro
72e5b4fb74 autodoc: improve type checking in main.js 2022-07-19 19:10:11 -07:00
Loris Cro
64feb222b5 autodoc: make links respect internal docs mode 2022-07-19 19:10:11 -07:00
Loris Cro
53fa75c852 autodoc: improved frontend rendering 2022-07-19 19:10:11 -07:00
Loris Cro
36c4b1aac9 autodoc: improve rendering and add "show priv decls" checkbox 2022-07-19 19:10:11 -07:00
Loris Cro
df3074aa98 autodoc: fix offset math for decls and change TODOs from panics to just
prints
2022-07-19 19:10:11 -07:00
Reece Van Atta
5f0ab34cc5 autodoc: add type comments to main.js file 2022-07-19 19:10:11 -07:00
Reece Van Atta
9cd9a390ae autodoc: add typedef to zigAnalysis file, just in case 2022-07-19 19:10:11 -07:00
ABuffSeagull
e39d1ae78f autodoc: fix missing variable declaration for strict mode 2022-07-19 19:10:11 -07:00
Loris Cro
40a2844c30 autodoc: decl paths become ref paths
originally I thought `foo.bar.baz` was a path of decls, but turns out
other language constructs require to make this model more general.
originally a decl path was an array of decl indexes, now it's an array
of `WalkResult`s
2022-07-19 19:10:11 -07:00
Loris Cro
63be9e65ed autodoc: added support for error sets and extended functions 2022-07-19 19:10:11 -07:00
Loris Cro
67f1d2b967 autodoc: add basic support for more builtin 2022-07-19 19:10:11 -07:00
Loris Cro
ec7f4d1faa autodoc: add support for anytype and improve semantics for array length 2022-07-19 19:10:11 -07:00
Loris Cro
d745dde54f autodoc: improve comments 2022-07-19 19:10:11 -07:00
Loris Cro
4f949163a5 autodoc: add support for enum literals 2022-07-19 19:10:11 -07:00
Loris Cro
056ba8e57c autodoc: add support for @This and improve call support in decl paths 2022-07-19 19:10:11 -07:00
Loris Cro
3eb90a110f autodoc: add support for pointers and comptime expressions in decl paths 2022-07-19 19:10:11 -07:00
Loris Cro
03d3929232 autodoc: add simplified support for tests 2022-07-19 19:10:11 -07:00
Loris Cro
1e2cd421b9 autodoc: add support for array decls 2022-07-19 19:10:11 -07:00
Loris Cro
eced8c065d autodoc: add support for solving decl paths depending on other
decl paths
2022-07-19 19:10:11 -07:00
Loris Cro
8bb529b395 autodoc: add support for generic functions & generic function calls 2022-07-19 19:10:11 -07:00
Loris Cro
195231b212 autodoc: add support for non-generic function calls 2022-07-19 19:10:11 -07:00
Loris Cro
028c8a3c91 autodoc: added support for same-file lazy resolution of decl paths 2022-07-19 19:10:11 -07:00
Loris Cro
580e633777 autodoc: added support for non-lazy decl paths 2022-07-19 19:10:11 -07:00
Loris Cro
253e7e112e autodoc: add frontend support for optionals & generic cleanup 2022-07-19 19:10:11 -07:00
Loris Cro
fbf0d0bee9 autodoc: fix decltest offset errors
while it would be preferable to not save decltests as first-class decls
(and just embed their information inside the decl they refer), adding
logic to skip them complicates the code too much so we should consider
this an optimization for the future.
2022-07-19 19:10:11 -07:00
Jacob G-W
a0ff7c8078 add decltests to the autodoc backend 2022-07-19 19:10:11 -07:00
Loris Cro
5d4c88c741 autodoc: added basic support for unresolved comptime expressions 2022-07-19 19:10:11 -07:00
Loris Cro
ee16eddecf autodoc: added basic support for @import 2022-07-19 19:10:11 -07:00
Loris Cro
4a868fa2be autodoc: escape html in decl ref names 2022-07-19 19:10:11 -07:00
Loris Cro
564d6c4960 autodocs: improve function rendering 2022-07-19 19:10:10 -07:00
Loris Cro
b296f5ac02 autodocs: added basic support for functions 2022-07-19 19:10:10 -07:00
Loris Cro
5a31126d89 autodocs: output data support for more types 2022-07-19 19:10:10 -07:00
Loris Cro
ef5a2e8d6f autodocs: added basic support for unions 2022-07-19 19:10:10 -07:00
Loris Cro
a04045c709 autodocs: fix rendering of non-type decls 2022-07-19 19:10:10 -07:00
Loris Cro
ce40f34cbc autodocs: added support for some non-type values 2022-07-19 19:10:10 -07:00
Loris Cro
29771440b2 autodocs: add support for int values 2022-07-19 19:10:10 -07:00
Loris Cro
0135d22716 autodocs: add support for indirect decl references 2022-07-19 19:10:10 -07:00
Loris Cro
38281c8ed4 autodoc: add declval support to docs js 2022-07-19 19:10:10 -07:00
Loris Cro
75d39a97a2 autodocs: fix merge conflict 2022-07-19 19:10:10 -07:00
Loris Cro
07ed8886b5 autodocs: refactoring: moved some fn arguments inside of self 2022-07-19 19:10:10 -07:00
Jacob G-W
9ad9664ea8 autdoc: install artifacts 2022-07-19 19:10:10 -07:00
Loris Cro
2dcaed743f autodocs: add support for block_inline 2022-07-19 19:10:10 -07:00
Jacob G-W
66a46888bb autodoc: generate WalkResults for ref types 2022-07-19 19:10:10 -07:00
Jacob G-W
025337a78d autodoc: don't hardcode file name 2022-07-19 19:10:10 -07:00
Loris Cro
652e13e7c0 autodoc: init work 2022-07-19 19:10:10 -07:00
Andrew Kelley
0efc6a35be Sema: fix enum value without tag name used as switch item
Previously stage2 would report a false positive compile error saying there
was no tag for this value.
2022-07-19 18:39:48 -07:00
Andrew Kelley
1d5f865cfa Sema: fix runtime instructions omitted
in the presence of comptime control flow.

fixes #12171
2022-07-19 17:45:38 -07:00
Andrew Kelley
046df9b7d0 Merge pull request #12131 from hnakamur/fix_big_int_Managed_mul_sqr_capacity_too_large
Fix std.math.big.int.Managed capacity after mul and sqr
2022-07-19 18:54:30 -04:00
Andrew Kelley
6fab6c3e46 Merge pull request #12164 from ziglang/llvm-opt-byref
LLVM: lower optional types as byref=true
2022-07-19 14:50:03 -04:00
Andrew Kelley
fe8c3ffeb1 LLVM: change commentary on isByRef
This branch originally started out as a potential workaround to
address #11450. It did not solve that problem, however, it did end
up fixing #11498!
2022-07-19 11:31:37 -07:00
Andrew Kelley
74fb65fb42 LLVM: lower all error unions as byref=true
Same reasoning as previous commit.
2022-07-19 11:26:19 -07:00
Andrew Kelley
bab570a225 LLVM: lower all structs as byref=true
Same reasoning as previous commit.
2022-07-19 11:26:18 -07:00
Andrew Kelley
65bc4d915d LLVM: lower optional types as byref=true
This is a possible workaround for
https://github.com/llvm/llvm-project/issues/56585

On my computer it makes stage3-release go from false positive
compilation errors on the behavior tests to "segmentation fault".
Is this forwards progress or backwards progress? I have no idea.

See #11450
2022-07-19 11:22:48 -07:00
LeRoyce Pearson
c26d9f6287 Read dynstr starting at rpath offset
Since we know the offset, we may as well read starting there. Still expects
rpath to fit in 4096 bytes; that might be worth fixing in the future.

Fixes issue #12112
2022-07-19 14:01:35 -04:00
Cody Tapscott
b93a38860d stage2: Change optional non-null field to i8
This is a workaround for https://github.com/llvm/llvm-project/issues/56585
which causes writes to i1 in memory to be optimized to an incorrect value.
Unfortunately, this does not save users from running into this bug with u1
in their own types.

However, this does seem to be enough to get the behavior tests working.
This resolves #11450 on my machine.
2022-07-19 13:33:41 -04:00
Veikka Tuominen
0e26c61499 std.fs: remove accidental comptime block 2022-07-17 11:54:13 +03:00
Veikka Tuominen
fcaeca5b0a std.fs: add Iterable versions of openDirAbsolute*
Follow up to 262f4c7b3a
2022-07-17 11:52:30 +03:00
Andrew Kelley
a39c51c6a4 Sema: fix UAF in coerceInMemoryAllowed 2022-07-16 13:48:12 -07:00
Vincent Rischmann
47c58cba59 Fix io_uring tests (#12134)
* io_uring: fix the timeout_remove test

The test does a IORING_OP_TIMEOUT followed with a IORING_OP_TIMEOUT_REMOVE
and assumed we would get the CQEs in the same order.

Linux v5.18 changed how this works and we now get them in the reverse order.

The documentation doesn't explicitly say which CQE we should get first
so just make the test work with both cases.

* io_uring: fix the remove_buffers test

The original test was buggy but accidentally worked with kernels < 5.18

The test assumed that IORING_OP_REMOVE_BUFFERS removed from the start of
but in fact the documentation doesn't specify which buffer is removed,
only that a certain number of buffers are removed.

Starting with the kernel 5.18 the check for the `used_buffer_id` fails.
Turns out that previous kernels removed buffers in such a way that the
remaining buffer for this read would always be 0, however this isn't
true anymore.

Instead of checking a specific value just check that the `used_buffer_id`
corresponds to a valid ID.
2022-07-16 10:05:11 -05:00
alichraghi
9c66fdadc7 std.testing: add refAllDeclsRecursive function 2022-07-16 12:33:25 +03:00
Ryan Liptak
43770c0103 Fix checkAllAllocationFailures being too strict when checking arg types
Before this would fail to compile:

```
fn testFn(alloc: std.mem.Allocator, arr: []const u8) !void {
    _ = alloc;
    _ = arr;
}

test "checkAll" {
    var arr = [_]u8{ 1, 2, 3 };
    try std.testing.checkAllAllocationFailures(std.testing.allocator, testFn, .{arr[0..]});
}
```

with the error `error: Unexpected type for extra argument at index 0: expected []const u8, found *[3]u8`

By removing this strict equality check, we allow the type checking to be done during the `@field(args, arg_i_str) = @field(extra_args, field.name);` instead, which then allows for things like type coercion to work, but still will give a compile error if the types are incorrect. So, after this change, the above succeeds (because `*[3]u8` can be coerced to `[]const u8`).

The new compile error when providing an incorrect type that can't be coerced looks like this:

```
zig/lib/std/testing.zig:639:35: error: expected type '[]const u8', found '*[3]u32'
        @field(args, arg_i_str) = @field(extra_args, field.name);
                                  ^
```
2022-07-16 12:32:20 +03:00
Veikka Tuominen
b2486fbc5e Merge pull request #12121 from Vexu/span
Stage2 point to error location using spans
2022-07-16 12:22:53 +03:00
Veikka Tuominen
da94227f78 Merge pull request #12060 from Vexu/IterableDir
std.fs: split `Dir` into `IterableDir`
2022-07-16 12:18:21 +03:00
r00ster91
8f943b3d33 style: add missing comma
This is really minor but the issue this fixes is that if you copy-paste this output of `--show-builtin` into your `build.zig` for example then the formatter will format
```
pub const os = std.Target.Os{
    .tag = .freestanding,
    .version_range = .{ .none = {} }
};
```
to
```
pub const os = std.Target.Os{ .tag = .freestanding, .version_range = .{ .none = {} } };
```
which doesn't match the output.
With this comma, the output will stay the way it is after a `zig fmt`.
2022-07-16 09:03:04 +00:00
Hiroaki Nakamura
3e667fd292 Use Managed.len in sub, divFloor, and divTrunc too 2022-07-16 11:46:13 +09:00
Hiroaki Nakamura
0cee8372cf Use Managed.len() instead of Managed.toConst().limbs.len 2022-07-16 08:14:16 +09:00
Andrew Kelley
e867127a6c Merge pull request #12127 from ziglang/llvm-abi-size
Audit LLVM ABI size
2022-07-15 14:48:21 -04:00
Hiroaki Nakamura
d63604b116 Fix std.math.big.int.Managed capacity after mul and sqr 2022-07-16 00:08:55 +09:00
Luuk de Gram
6ba2fb3db7 zig cc: support -Wl,--export=<symbol> 2022-07-15 16:59:23 +02:00
Jakub Konka
e3c8ba2dc5 ci: bump macOS image on Github Actions to macos-11
The currently used image is getting deprecated and every user is advised
to switch to either macos-11 or macos-12. The link to upstream
issue/notification:

https://github.com/actions/virtual-environments/issues/5583
2022-07-15 07:56:21 -07:00
Veikka Tuominen
cf207df592 Module: improve source spans for initializers and var types
```zig
const U = union { foo: u32, bar: u32 };
test {
    var a = U{ .foo = 1213, .bar = 1123 };
    _ = a;
}
test {
    var a: (123 + 5238094) = 0;
    _ = a;
}
```

before:
```
:30: note: additional initializer here
    var a = U{ .foo = 1213, .bar = 1123 };
                             ^~~
:12: error: expected type 'type', found 'comptime_int'
    var a: (123 + 5238094) = 0;
           ^
```
after:
```
:30: note: additional initializer here
    var a = U{ .foo = 1213, .bar = 1123 };
                            ~^~~~~~~~~~
:12: error: expected type 'type', found 'comptime_int'
    var a: (123 + 5238094) = 0;
           ^~~~~~~~~~~~~~~
```
2022-07-15 16:06:16 +03:00
Veikka Tuominen
1463144fc8 Compilation: point caret in error message at the main token 2022-07-15 15:11:43 +03:00
Veikka Tuominen
262f4c7b3a std.fs: remove OpenDirOptions.iterate 2022-07-15 14:39:21 +03:00
Veikka Tuominen
2b67f56c35 std.fs: split Dir into IterableDir
Also adds safety check for attempting to iterate directory not opened with `iterate = true`.
2022-07-15 13:04:21 +03:00
Yujiri
577f9fdbae doc/langref: clarify behavior of slicing with constant indexes
Fixes #11219.
2022-07-15 10:17:22 +03:00
Kim SHrier
397e6547a9 add FreeBSD support to std.os.getFdPath
This implementation uses the F_KINFO fcntl command added in FreeBSD
13 release. FreeBSD 12 users get a compile error.

Co-authored-by: Stephen Gregoratto <dev@sgregoratto.me>
2022-07-15 10:16:31 +03:00
Andrew Kelley
9329b93b88 LLVM: disable the ABI size safety check
There are many more instances of this check being tripped that we need
to fix before we can enable this.
2022-07-14 23:26:32 -07:00
Andrew Kelley
040cb585e8 LLVM: fix ABI size of optional and error union types
Previously, the Zig ABI size and LLVM ABI size of these types disagreed
sometimes. This code also corrects the logging messages to not trigger
LLVM assertions.
2022-07-14 23:24:57 -07:00
Andrew Kelley
8c14d170b5 Revert "stage2 llvm: Use unpacked struct for unions and arrays"
This reverts commit 2eaef84ebe.

Here is a motivating example:

```zig
const E = union(enum) {
    A: [9]u8,
    B: u64,
};
```

```llvm
%test2.E = type { { i64, [1 x i8] }, i1, [6 x i8] }
```

```
error(codegen): when lowering test2.E, Zig ABI size = 16 but LLVM ABI size = 24
```
2022-07-14 22:26:11 -07:00
Andrew Kelley
9c136be78f LLVM: add padding to optional types when lowering
If the LLVM ABI size does not agree with the Zig ABI size.
2022-07-14 22:26:11 -07:00
Andrew Kelley
070e3ea37d LLVM: insert debug logging when LLVM ABI size is wrong 2022-07-14 22:26:11 -07:00
Andrew Kelley
4c7fe74b2c Merge pull request #12124 from ziglang/stage2-coerce-result-ptr
Sema: fix coerce_result_ptr in case of inferred result type
2022-07-15 01:06:05 -04:00
Cody Tapscott
dd70336f3a CMake: Use NAMES_PER_DIR in all lookups
CMake has a surprising default behavior where looking up a library by
multiple names gives the name order higher priority than the directory
search order.

For example, if your system provides "llvm-config-14" and
CMAKE_PREFIX_PATH includes "llvm-config", CMake will always end up
choosing the system-provided llvm-config-14.

This change add NAMES_PER_DIR to request the more sensible behavior:
directory search order has higher priority than name order, so
CMAKE_PREFIX_PATH always wins over system-provided tools/libraries.
2022-07-14 22:18:10 -04:00
Andrew Kelley
04572f6e34 Sema: fix coerceResultPtr
It did not handle properly when the dummy operand was a comptime_int; it
was crashing in coerce because comptime_int is supposed to be
comptime-known. So when calling coerceResultPtr, we pass the actual
operand, not a dummy operand, which means it will have the proper
comptime value when necessary.
2022-07-14 18:11:46 -07:00
Andrew Kelley
d7711ec953 print_zir: fix wrong union tag for validate_deref
closes #12125
2022-07-14 17:16:07 -07:00
Andrew Kelley
667ad9250f Sema: fix coerce_result_ptr in case of inferred result type
Previously, the logic for analyzing coerce_result_ptr would generate
invalid bitcast instructions which did not include coercion logic, such
as optional wrapping, resulting in miscompilations.

Now, the logic of resolve_inferred_alloc goes back over all the
placeholders inserted by coerce_result_ptr, and replaces them with logic
doing the proper coercions.

Closes #12045
2022-07-14 16:48:44 -07:00
Veikka Tuominen
b5a838247b stage2: point to error location using spans 2022-07-14 22:18:58 +03:00
Bill Nagel
a455927150 handle HOSTUNREACH for blocking and non-blocking connects 2022-07-14 12:51:40 +03:00
Andrew Kelley
1653a9b259 Merge pull request #12098 from ziglang/llvm-riscv64
LLVM: implement signext/zeroext attributes
2022-07-13 19:15:19 -04:00
Andrew Kelley
fad95741db AstGen: fix loop control flow applying to wrong loop
In the case of 'continue' or 'break' inside the 'else' block of a
'while' or 'for' loop.

Closes #12109
2022-07-13 16:10:41 -07:00
Andrew Kelley
92bc3cbe27 stage2: fix comptime bitcast involving f80
* Sema: implement comptime bitcast of f80 with integer-like types
  bitwise rather than taking a round trip through memory layout.
* Type: introduce `isAbiInt`.
* Value: comptime memory write of f80 writes 0 bytes for padding
  instead of leaving the memory uninitialized.
* Value: floatReadFromMemory has a more general implementation, checking
  the endianness rather than checking for specific architectures.

This fixes behavior test failures occurring on MIPS.
2022-07-13 13:14:37 -07:00
Andrew Kelley
35e7011124 LLVM: implement signext/zeroext attributes
For calling convention ABI purposes, integer attributes and return
values need to have an LLVM attribute signext or zeroext added
sometimes. This commit implements that logic.

It also implements a proof-of-concept of moving the F16T type from
being a compiler_rt hack to being how the compiler lowers f16 in
functions that need to match certain calling conventions.

Closes #12054
2022-07-13 11:14:46 -07:00
Andrew Kelley
efe34243c6 std.math: add inline to some functions
These functions semantically benefit from being inline; it makes sense
that `isInf(x)` where `x` is comptime-known should have a
comptime-known result.
2022-07-13 11:14:46 -07:00
Joachim Schmidt
1fee9eac8b Merge pull request #12095 from joachimschmidt557/stage2-arm
stage2 ARM: add integer div+mod with constant power-of-twos
2022-07-13 10:54:27 +02:00
Andrew Kelley
4a28c1d5c3 stage2: lower each struct field type, align, init separately
Previously, struct types, alignment values, and initialization
expressions were all lowered into the same ZIR body, which caused false
positive "depends on itself" errors when the initialization expression
depended on the size of the struct.

This also uses ResultLoc.coerced_ty for struct field alignment and
initialization values. The resulting ZIR encoding ends up being roughly
the same, neither smaller nor larger than previously.

Closes #12029
2022-07-13 02:38:13 -04:00
Andrew Kelley
3708e26f4b Merge pull request #12084 from ziglang/stage2-std
stage2 bug fixes
2022-07-12 22:00:55 -04:00
Andrew Kelley
6ab5219e34 std: update test cases to reflect new packed struct semantics 2022-07-12 18:38:11 -07:00
Andrew Kelley
8324a93f2e LLVM: always add some clobbers for some architectures
For some targets, Clang unconditionally adds some clobbers to all inline assembly.
While this is probably not strictly necessary, if we don't follow Clang's lead
here then we may risk tripping LLVM bugs since anything not used by Clang tends
to be buggy and regress often.
2022-07-12 18:38:11 -07:00
Andrew Kelley
0d164f9a25 LLVM: broaden aarch64-windows f16 debug variable workaround
LLVM does not properly handle debug info for f16 on the aarch64-windows
target, causing "fatal error: unknown codeview register H1". The
previous workaround checked only for f16 but was still vulnerable if a
type was a byval struct or tuple which had an f16 field in it.

Now I have filed an upstream issue (see
https://github.com/llvm/llvm-project/issues/56484) and broadened the
workaround to always skip debug values for this target.
2022-07-12 18:38:11 -07:00
Andrew Kelley
d789c68717 zig_llvm: include Debug Info Version even for CodeView
I mistakenly thought this was supposed to only be present for Dwarf.
2022-07-12 18:38:11 -07:00
Andrew Kelley
56f2e5c5bc Sema: fix double-free on compile errors
when instantiating a generic function and an error occurs in the
function prototype.
2022-07-12 18:38:11 -07:00
Cody Tapscott
2eaef84ebe stage2 llvm: Use unpacked struct for unions and arrays
Our lowerings for various LLVM types assume that we can anticipate the
alignment/layout that LLVM will generate. Among other things, this
requires that we keep the alignment of our lowered LLVM types
synchronized with their expected alignment in Zig.

 - Arrays were using packed struct types, which is seems to be
   incorrect since array elements are supposed to be self-aligned.

 - Unions were using packed struct types for their payload, which causes
   layout divergence between what stage2 expects and what LLVM generates

Consider this lowered union type:
```llvm
%Value = type { <{ i64, [8 x i8] }>, i1, [7 x i8] } ; 24 bytes, align(1)
%ErrorUnion = type { %Value, i16 } ; 26 bytes, align(2)
```

Zig expects Value to be align(8) and, by extension, for ErrorUnion to be
size 32.
2022-07-12 21:34:20 -04:00
joachimschmidt557
f89ace4d04 stage2 ARM: add integer modulo with constant power-of-two rhs 2022-07-12 23:22:15 +02:00
joachimschmidt557
47d1874218 stage2 ARM: implement division by constant int power-of-two divisors 2022-07-12 22:43:55 +02:00
Veikka Tuominen
7090f0471c Merge pull request #12083 from Vexu/c-container-err
parser: add helpful error for C style container declarations
2022-07-12 19:37:02 +03:00
Luuk de Gram
8033767082 wasm-linker: Implement linker tests (#12006)
* test/link: initial wasm support

This adds basic parsing and dumping of wasm section so they
can be tested using the new linker-test infrastructure.

* test/link: all wasm sections parsing and dumping

We now parse and dump all sections for the wasm binary format.
Currently, this only dumps the name of a custom section.
Later this should also dump symbol table, name, linking metadata and relocations.
All of those live within the custom sections.

* Add wasm linker test

This also fixes a parser mistake in reading the flags.

* test/link: implement linker tests wasm & fixes

Adds several test cases to test the wasm self-hosted linker.
This also introduces fixes that were caught during the implementation
of those tests.

* test-runner: obey omit_stage2 for standalone

When a standalone test requires stage2, but stage2 is omit
from the compiler, such test case will not be included as part
of the test suite that is being ran. This is to support CI's
where we omit stage2 to lower the memory usage.
2022-07-12 14:36:33 +02:00
Veikka Tuominen
2a3f3766a4 stage2: handle parser notes in a more general way 2022-07-12 12:50:59 +03:00
Veikka Tuominen
5d22204d2d parser: add helpful error for C style container declarations
```zig
// a.zig
struct Foo {
    a: u32,
};
```

before:
```
a.zig:1:1: error: expected test, comptime, var decl, or container field, found 'struct'
struct Foo {
^
```
after:
```
a.zig:1:8: error: 'struct Foo' is invalid
struct Foo {
       ^
a.zig:1:8: note: to declare a container do 'const Foo = struct'
struct Foo {
       ^
```
2022-07-12 12:50:59 +03:00
Andrew Kelley
7d2e142679 Merge pull request #12044 from Vexu/stage2-compile-errors
Sema: add detailed error notes to `coerceInMemoryAllowed`
2022-07-11 20:45:27 -04:00
Andrew Kelley
dc815e5e8f Merge pull request #12075 from Vexu/stage2-validate-extern
Stage2 validate extern types
2022-07-11 20:25:35 -04:00
Andrew Kelley
8b3f15f218 Merge pull request #11863 from motiejus/compress-debug-sections
ELF: understand --compress-debug-sections
2022-07-11 17:23:02 -04:00
Andrew Kelley
2b99182e25 stage2: cleanups to --compress-debug-sections
* make the setting in the linker backend be non-optional; by this time
   all defaults are supposed to be resolved.
 * integrate with `zig cc`
 * change the CLI parsing to match C compiler parsing, allowing
   `--compress-debug-sections` alone to choose a default encoding of
   zlib.
2022-07-11 14:18:56 -07:00
r00ster91
da75eb0d79 Compilation: indent multiline error messages properly
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-07-12 00:10:39 +03:00
1f410b500c ELF: understand -Wl,--compress-debug-sections
This argument is both a compiler and a linker flag. The linker flag was
not understood; now it is. Go likes to use it as a linker flag.

Tested with sqlite3. The size difference is significant, and I confirmed
gdb understands both binaries.

zlib: 3.66MB
------------

    CC="zig cc"
    CFLAGS="-Wl,--compress-debug-sections=zlib -O2"
    ./configure --disable-tcl
    make

        FILE SIZE        VM SIZE
     --------------  --------------
      39.1%  1.43Mi  88.4%  1.43Mi    .text
      19.6%   734Ki   0.0%       0    .debug_info
      16.4%   613Ki   0.0%       0    .debug_loc
      13.1%   492Ki   0.0%       0    .debug_line
       4.2%   157Ki   9.5%   157Ki    .rodata
       2.3%  87.6Ki   0.0%       0    .debug_ranges
       1.5%  56.2Ki   0.0%       0    .symtab
       1.1%  40.2Ki   0.0%       0    .strtab
       1.0%  38.2Ki   0.0%       0    .debug_str
       0.7%  26.2Ki   0.0%       0    .debug_frame
       0.4%  15.3Ki   0.9%  15.3Ki    .data
       0.1%  4.71Ki   0.3%  4.71Ki    .dynsym
       0.1%  3.65Ki   0.2%  3.26Ki    [16 Others]
       0.1%  2.55Ki   0.2%  2.55Ki    .rela.plt
       0.1%  2.12Ki   0.0%       0    [ELF Section Headers]
       0.0%       0   0.1%  2.02Ki    .bss
       0.0%  1.84Ki   0.1%  1.84Ki    .dynstr
       0.0%  1.72Ki   0.1%  1.72Ki    .plt
       0.0%  1.58Ki   0.1%  1.58Ki    .hash
       0.0%  1.17Ki   0.0%       0    .debug_abbrev
       0.0%  1.01Ki   0.1%  1.01Ki    .rela.dyn
     100.0%  3.66Mi 100.0%  1.62Mi    TOTAL

none: 8.56MB
------------

    CC="zig cc" CFLAGS="-O2" ./configure --disable-tcl
    make

        FILE SIZE        VM SIZE
     --------------  --------------
      41.1%  3.52Mi   0.0%       0    .debug_loc
      18.5%  1.59Mi   0.0%       0    .debug_info
      16.7%  1.43Mi  88.4%  1.43Mi    .text
      11.8%  1.01Mi   0.0%       0    .debug_line
       5.9%   515Ki   0.0%       0    .debug_ranges
       1.8%   157Ki   9.5%   157Ki    .rodata
       1.3%   118Ki   0.0%       0    .debug_frame
       1.3%   110Ki   0.0%       0    .debug_str
       0.6%  56.2Ki   0.0%       0    .symtab
       0.5%  40.2Ki   0.0%       0    .strtab
       0.2%  15.3Ki   0.9%  15.3Ki    .data
       0.1%  4.71Ki   0.3%  4.71Ki    .dynsym
       0.0%  3.64Ki   0.2%  3.26Ki    [16 Others]
       0.0%  2.98Ki   0.0%       0    .debug_abbrev
       0.0%  2.55Ki   0.2%  2.55Ki    .rela.plt
       0.0%  2.12Ki   0.0%       0    [ELF Section Headers]
       0.0%       0   0.1%  2.02Ki    .bss
       0.0%  1.84Ki   0.1%  1.84Ki    .dynstr
       0.0%  1.72Ki   0.1%  1.72Ki    .plt
       0.0%  1.58Ki   0.1%  1.58Ki    .hash
       0.0%  1.01Ki   0.1%  1.01Ki    .rela.dyn
     100.0%  8.56Mi 100.0%  1.62Mi    TOTAL
2022-07-11 13:55:29 -07:00
Veikka Tuominen
122c76a167 Sema: allow void as an extern union field & fix invalid extern unions 2022-07-11 20:30:16 +03:00
Ikko Ashimine
ade9bd9287 stage1: fix typo in analyze.cpp (#12077)
accomodate -> accommodate
2022-07-11 18:30:28 +02:00
Veikka Tuominen
d00da05ecb Sema: validate extern types 2022-07-11 18:47:29 +03:00
Veikka Tuominen
3ceb27c840 Sema: better explanation why opaque types require comptime 2022-07-11 18:47:29 +03:00
Veikka Tuominen
20d4f7213d Sema: add notes about function return type 2022-07-11 17:55:19 +03:00
frmdstryr
3e2e6c108a std.math: add degreesToRadians and radiansToDegrees 2022-07-11 16:40:05 +03:00
Veikka Tuominen
c9e1360cdb Sema: add "cannot convert to payload type" error notes 2022-07-11 14:17:22 +03:00
Veikka Tuominen
2a41b1449b Compilation: do not repeat AstGen error source line for notes 2022-07-11 14:16:42 +03:00
Veikka Tuominen
0370006c1f Sema: only add note about int mismatch if not coercible
`unsigned 64-bit int cannot represent all possible unsigned 63-bit values`
is nonsensical.
2022-07-11 11:59:26 +03:00
Mikko Kaihlavirta
6f55b294f6 use std.log for logging 2022-07-11 11:18:52 +03:00
Duncan Holm
4bbc95b219 std.fmt: clarify the description of placeholders in Format Strings
Those 6 sets of square brackets are just a typographical aid used in this doc-comment, and must not actually be written by the user in their own format string... except for in one case where they must

* Avoid the implication that the numeric index is 1-based rather than 0-based
2022-07-11 11:16:28 +03:00
Andrew Kelley
76c89a3de9 Merge pull request #12071 from topolarity/windows-abi-change
compiler_rt: Update Windows ABI for float<->int conversion routines
2022-07-10 23:53:14 -04:00
Cody Tapscott
2b5215436c stage2: Lower libcalls on Windows x86-64 correctly
This change is the Zig counterpart to https://reviews.llvm.org/D110413

Same as the prior commit, but for stage2
2022-07-10 20:52:29 -07:00
Cody Tapscott
d182e2ebda stage1: Lower libcalls on Windows x86-64 correctly
This change is the Zig counterpart to https://reviews.llvm.org/D110413

Since we lower some libcalls directly (just like clang does), we need to
make sure that the ABI we call with matches the ABI of the compiler-rt
we are providing (and also the ABI expected by LLVM).

While I was at it, I noticed some flawed vector handling in the binary
soft float ops in stage 1, so I shored up the logic a bit and expanded
an existing test to cover the missing functionality.
2022-07-10 20:52:28 -07:00
Cody Tapscott
bb8971150c compiler_rt: Slightly re-factor exports for Windows x86-64
This is just a cosmetic change. The goal is to keep the export logic
relatively flat and centralized.
2022-07-10 20:51:34 -07:00
Cody Tapscott
680419c407 compiler_rt: Update Windows ABI for float<->int conversion routines
Starting with LLVM 14, the Libcalls to these functions are now lowered
using a Vec(2, u64) instead of the standard ABI for i128 integers, so
our compiler-rt implementation needs to be updated to expose the same
ABI on Windows.
2022-07-10 20:51:34 -07:00
Frank Denis
f3333a56e8 stage1/codegen: replace sprintf() with snprintf()
Calling sprintf() is now triggering an error on Xcode 14.

Using snprintf() is generally not a bad idea anyway.
2022-07-10 22:59:25 -04:00
Veikka Tuominen
e644a2ab6a Compilation: do not repeat same source line for notes 2022-07-10 23:47:56 +03:00
Veikka Tuominen
34fe2b4f4b Sema: prefer original error message in coerce 2022-07-10 23:47:56 +03:00
Veikka Tuominen
b9f01bc394 Sema: add detailed error notes to coerceInMemoryAllowed 2022-07-10 23:15:17 +03:00
BratishkaErik
b9ed072278 CMakeLists.txt: set LLVM minimal version to 14 2022-07-10 15:43:01 -04:00
Andrew Kelley
b88151e0e1 Merge pull request #12001 from ziglang/llvm14
Upgrade to LLVM 14
2022-07-10 03:06:05 -04:00
Andrew Kelley
f9bf488926 two more regressed test cases; same cause as last two commits 2022-07-09 17:35:14 -07:00
Andrew Kelley
31281a7d14 disable regressed math.sign test case
see #12012
2022-07-09 15:43:33 -07:00
Andrew Kelley
321fec1aa6 disable regressed float formatting test case
See #12063
2022-07-09 15:34:34 -07:00
Andrew Kelley
4d10fbef10 windows_com: add missing __CRT_UUID_DECL() for IEnumSetupInstances
This is intended to fix this error:

lld-link: error: undefined symbol: _GUID const& __mingw_uuidof<IEnumSetupInstances>()
>>> referenced by D:\a\1\s\src\windows_com.hpp:898
>>>               D:\a\1\s\zig-cache\o\a5030d467932f0ce2f6511feb7d6af12\windows_sdk.obj:(__IEnumSetupInstances_IID_getter())

Thank you to Martin Storsjö for suggesting the fix.
2022-07-09 14:04:38 -07:00
Andrew Kelley
e0d5ae75af these riscv64 behavior tests work for stage1 but not stage2 2022-07-09 12:48:59 -07:00
Veikka Tuominen
3f11d1d56d Merge pull request #12050 from topolarity/anon-struct-init
stage2: Support initializing anonymous struct type
2022-07-09 18:30:07 +03:00
r00ster91
13d58258a8 std.log: deduplicate switch 2022-07-09 15:19:03 +03:00
Veikka Tuominen
5b36b0ed0c Sema: use tupleFieldIndex 2022-07-09 14:41:47 +03:00
Yusuke Tanaka
f1da93af3c Remove outdated TODO comment (#12053) 2022-07-09 13:05:41 +02:00
Andrew Kelley
a1c56ffd5a disable regressed translate-c test case on freebsd
see #12055
2022-07-08 23:17:41 -07:00
Andrew Kelley
f976758855 disable failing riscv64 tests from LLVM 14 upgrade
See #12054
2022-07-08 23:11:03 -07:00
Andrew Kelley
3e864c86da CI: azure: update build.zig for LLVM 14 2022-07-08 23:02:38 -07:00
Andrew Kelley
aade8856ee CI: update scripts to stage1 LLVM 14 tarballs
The previous tarballs were stage3 which is not quite ready for primetime
yet.
2022-07-08 21:28:06 -07:00
Cody Tapscott
c830606bbe stage2: Support @fieldParentPtr for tuples and anon structs 2022-07-08 19:52:23 -07:00
Cody Tapscott
51a8f52e6c stage2: Support @offsetOf for tuples and anon structs 2022-07-08 19:51:35 -07:00
Cody Tapscott
2fff25fd22 stage2: Support initializing anonymous struct type
This commit adds support for initializing `.anon_struct` types. There
is also some follow-up work to do for both tuples and structs regarding
comptime fields, so this also adds some tests to keep track of that
work.
2022-07-08 19:50:28 -07:00
Frank Denis
6f0807f50f crypto.sign.ed25519: add support for blind key signatures (#11868)
Key blinding allows public keys to be augmented with a secret
scalar, making multiple signatures from the same signer unlinkable.

https://datatracker.ietf.org/doc/draft-dew-cfrg-signature-key-blinding/

This is required by privacy-preserving applications such as Tor
onion services and the PrivacyPass protocol.
2022-07-08 13:21:37 +02:00
Cody Tapscott
33a39c4b2b stage2: Fix panic when printing AIR for tuple/anon struct types 2022-07-08 10:19:17 +03:00
Andrew Kelley
bdf3fa12fa CI: update scripts to new LLVM 14 tarballs 2022-07-07 20:47:58 -07:00
Andrew Kelley
8e492f7d47 compiler_rt: enable __clear_cache for stage2 2022-07-07 20:47:43 -07:00
Andrew Kelley
6a3a0fe7ae Merge remote-tracking branch 'origin/master' into llvm14 2022-07-07 18:25:01 -07:00
Andrew Kelley
3a03872af7 LLVM: more robust implementation of C ABI for multiple_llvm_ints
The previous code here was potentially more optimal for some cases,
however, I never tested the perf, so it might not actually matter. This
code handles more cases. We can go back and re-evaluate that other
implementation if it seems worthwhile in the future.
2022-07-07 18:24:34 -07:00
Andrew Kelley
8d6011361f LLVM: handle byref combined with multiple_llvm_ints 2022-07-07 18:24:34 -07:00
Andrew Kelley
e5e9e5a7aa std.builtin.returnError: disable runtime safety 2022-07-07 18:24:34 -07:00
Cody Tapscott
cbc85f4516 stage1: Fix seg-fault when slicing string literal with sentinel 2022-07-08 02:14:38 +03:00
VÖRÖSKŐI András
75c33ba85e Sema: add a note about @setEvalBranchQuota() when branch quota is exceeded
closes #11996
2022-07-08 02:13:33 +03:00
Andrew Kelley
8e07b0c4b9 Merge remote-tracking branch 'origin/master' into llvm14 2022-07-07 14:01:54 -07:00
Andrew Kelley
e0b9200492 llvm c++ wrapper: fix argument index calculations 2022-07-07 13:56:46 -07:00
Andrew Kelley
1b9a9ee4ba langref: disable an example that regressed from LLVM 14 2022-07-07 12:19:48 -07:00
Andrew Kelley
0c78ece1c9 Merge pull request #12016 from Vexu/stage2-compile-errors
Stage2 compile error improvements
2022-07-07 14:52:28 -04:00
r00ster91
6f17be063d std.log: give friendly error to freestanding users 2022-07-07 21:40:31 +03:00
emma
81bbefe9b8 AstGen: fix catch payoad not checking for shadowing 2022-07-07 21:38:32 +03:00
Veikka Tuominen
5007f727e5 stage2: move C pointer allowzero error to AstGen 2022-07-07 10:50:06 +03:00
Veikka Tuominen
b5ac2b4330 Sema: improve array source location 2022-07-07 10:50:06 +03:00
Veikka Tuominen
27ee414159 Sema: improve slice source locations 2022-07-07 10:50:06 +03:00
Veikka Tuominen
2ca752ea1a Module: add .node_offset_un_op 2022-07-07 10:50:06 +03:00
Veikka Tuominen
89cef9f5f7 stage2: make line field of @src runtime known 2022-07-07 10:50:06 +03:00
Veikka Tuominen
226994cd7e Sema: misc error message fixes 2022-07-07 10:50:06 +03:00
Veikka Tuominen
c07c2d68c7 Sema: more runtime indexing comptime value checks 2022-07-07 10:50:06 +03:00
Veikka Tuominen
1569b9c165 Sema: validate pointer types 2022-07-07 10:50:05 +03:00
Veikka Tuominen
299836dbd9 Sema: panic at comptime + misc error message improvements 2022-07-07 10:50:05 +03:00
Veikka Tuominen
252388eb28 AstGen: move error_to_int, int_to_error and select to extended 2022-07-07 10:45:45 +03:00
Andrew Kelley
e5549de0de Merge remote-tracking branch 'origin/master' into llvm14 2022-07-07 00:06:11 -07:00
Andrew Kelley
c9006d9479 std.json: move tests to json/test.zig file
This accomplishes two things:
 * Works around #8442 by putting stage1-specific logic in to disable all
   the std.json tests.
 * Slightly reduces installation size of zig since std lib files ending
   in "test.zig" are excluded from being installed.
2022-07-07 00:05:21 -07:00
Andrew Kelley
f0fde1d9c2 std.leb128: disable regressed test due to LLVM 14
See #12031
2022-07-06 20:12:00 -07:00
Riccardo Binetti
0101a5f75e Sema: accept thumb and thumbeb with ARM calling conventions
Commit 3014a0d5f1 added calling convention
validation, but left out thumb and thumbeb from the archs that can use the
ARM-specific calling conventions. This plus
a8a7f15106 made compilation fail for thumb
targets.
2022-07-06 21:02:30 -04:00
Andrew Kelley
1b610d7853 Merge remote-tracking branch 'origin/master' into llvm14 2022-07-06 17:55:05 -07:00
Andrew Kelley
f3069f51aa Sema: fix type resolution during generic function instantiation
Found when trying to compile the std lib tests for x86_64-macos.
2022-07-06 17:00:17 -07:00
Andrew Kelley
18950e865e std.fmt.parse_float: disable failing aarch64 test from LLVM 14
See #12027
2022-07-06 16:23:42 -07:00
Andrew Kelley
222ea6992d std: disable aarch64 tests that regressed from LLVM 14
See #12012
2022-07-06 15:57:36 -07:00
Andrew Kelley
4e002dde69 std: disable tests tripping LLVM assertions
see #12012
2022-07-06 15:45:53 -07:00
Andrew Kelley
c061b3a572 disable more standalone tests
these are tripping LLVM 13 assertions.

See #12015
See #12022
2022-07-06 15:10:41 -07:00
Andrew Kelley
6164801efb update install_raw_hex test case
LLVM 14 optimizes differently, so it's reasonable to have there be a
binary difference here.
2022-07-06 11:52:21 -07:00
Andrew Kelley
fa40bddf27 Merge remote-tracking branch 'origin/master' into llvm14 2022-07-06 02:40:05 -07:00
Andrew Kelley
aab1284e10 disable failing standalone test - tools/gen_spirv_spec.zig
Because it is tripping an LLVM 13 assertion.

See #12015
2022-07-06 02:39:28 -07:00
Andrew Kelley
38e3063296 compiler_rt: RISC-V does not want gnu_f16_abi 2022-07-06 02:29:54 -07:00
Frank Denis
38096960fb crypto.sign.ecdsa: fix toCompressedSec1()/toUnompressedSec1() (#12009)
The Ecdsa.PublicKey type is not a direct alias for a curve element.

So, use the inner field containing the curve element for serialization.
2022-07-06 08:30:43 +02:00
Andrew Kelley
683ace7472 Merge remote-tracking branch 'origin/master' into llvm14 2022-07-05 21:56:55 -07:00
Andrew Kelley
6279a1d684 std: align some function pointers 2022-07-05 21:54:24 -07:00
Andrew Kelley
c34392b24e std.os.linux.io_uring: work around LLVM bug
See #12014
2022-07-05 21:54:05 -07:00
Andrew Kelley
d8fc8d0118 compiler_rt: work around LLVM optimizing __muloti4 to call itself
This is a workaround for
https://github.com/llvm/llvm-project/issues/56403
2022-07-05 21:28:39 -07:00
Andrew Kelley
558ad19095 disable regressed behavior tests from llvm 14
See #12012
See #12013
2022-07-05 18:50:03 -07:00
Andrew Kelley
9a5c7b4b4d Merge remote-tracking branch 'origin/master' into llvm14 2022-07-05 16:24:18 -07:00
Andrew Kelley
f639cb33a9 fix expected error messages in test cases 2022-07-05 16:22:53 -07:00
Andrew Kelley
844b77e3bc remove sparc64 test case which is tripping llvm assertion
See #12011
2022-07-05 16:22:53 -07:00
Andrew Kelley
e8ce1728e9 disable regressed wasm32 behavior tests from LLVM 14 2022-07-05 15:46:12 -07:00
Andrew Kelley
fc7c0e07be stage2: propagate use_stage1 to sub-compilation
This makes it so that -fno-stage1 also affects compiler-rt for example.
2022-07-05 15:45:48 -07:00
Andrew Kelley
388520a40b fix behavior test which was relying on UB 2022-07-05 15:22:19 -07:00
Andrew Kelley
2ee864ca5e CLI: add support for -fno-builtin 2022-07-05 15:21:20 -07:00
Andrew Kelley
927e59d053 CI: fix wrong macos tarball 2022-07-05 15:20:12 -07:00
Jonathan Marler
93ac87c1bd Mark fstype argument to mount as optional
The fstype argument to the mount system call can be null.  To see an
example run "strace -e trace=mount unshare -m":

```
mount("none", "/", NULL, MS_REC|MS_PRIVATE, NULL) = 0
...
```
2022-07-05 15:04:31 -04:00
Cody Tapscott
86570b3e2c stage2: Fix corrupted Type when de-referencing field pointer 2022-07-05 15:02:13 -04:00
Andrew Kelley
bcfc4f0ceb CI: update tarballs to LLVM 14 2022-07-04 20:12:44 -07:00
Andrew Kelley
fbd6c88321 Merge remote-tracking branch 'origin/master' into llvm14 2022-07-04 17:22:36 -07:00
Andrew Kelley
6fc9f6c5f6 link.Coff: notice special windows symbols
in order to have a better default for subsystem. This brings stage2
behavior on par with stage1.
2022-07-04 17:20:01 -07:00
Andrew Kelley
afe6e69e4c std.Thread: fix mutable ref of temporary
The previous code is a compile error in stage2 as well as the
upcoming lang spec.
2022-07-04 16:53:41 -07:00
Andrew Kelley
9ecc47cd7c Sema: fix intFitsInType implementation
The function did not handle comptime_int in the case of lazy_align or
lazy_size.
2022-07-04 16:52:34 -07:00
Andrew Kelley
eba8892b84 Sema: resolve lazy value before hashing it for generic fn 2022-07-04 16:44:41 -07:00
Andrew Kelley
ecb4293afe stage2: disable unit tests when building with stage1
They trip LLVM assertions and spirv is not needed to bootstrap. Not
important for these tests to pass with stage1.
2022-07-04 16:20:33 -07:00
Andrew Kelley
f59bd2be53 Merge remote-tracking branch 'origin/master' into llvm14 2022-07-04 14:07:08 -07:00
Andrew Kelley
d65e248ed1 stage2: ELF: improve error reporting when libc is missing
Future improvement: make plain error notes actually render as notes
rather than errors, but keep them as errors for the case of
sub-compilation errors, e.g. when compiler-rt has compilation errors.
2022-07-04 14:06:20 -07:00
Andrew Kelley
9c5056788f std: update bsd bits to new fn ptr semantics 2022-07-04 13:02:30 -07:00
Andrew Kelley
e3274067f8 update macOS libc headers
notably this adds copyfile.h

fetch-them-macos-headers rev 900567517197df46e98006c53023fa10cb986004
2022-07-04 12:14:48 -07:00
Veikka Tuominen
050fef3c23 translate-c: do not try to get rid of do while loop
It might contain breaks and continues.

Closes #11994
2022-07-04 21:56:54 +03:00
Andrew Kelley
6db190cf70 Merge remote-tracking branch 'origin/master' into llvm14 2022-07-03 22:27:21 -07:00
Andrew Kelley
314ce5465d std: better definition for std.os.linux.epoll_event
The previous definition depends on a non-lang-spec-compliant memory
layout for packed structs, which happens to trigger #11989 in stage2.

This commit changes the struct to be an extern struct with an
align(4) field. However, stage1 cannot handle this, so conditional
compilation logic is used to select different struct definitions
depending on stage1 vs stage2.

This works around #11989 but does not solve the underlying problem -
putting an extern union inside a packed struct will still trigger the
assert.

After this, both stage1 and stage2 std lib tests run assertion-clean
with a debug LLVM 13.
2022-07-03 22:18:05 -07:00
Andrew Kelley
fdc24e6608 stage1: fix vectors of small int and bool tripping LLVM assertion
stage2 already has this fixed; debug info is given size in bits rather
than ABI size (bytes) multiplied by 8.

closes #11587
2022-07-03 21:08:47 -07:00
Andrew Kelley
15bdba410a update build scripts to LLD and LLVM 14 libraries 2022-07-03 18:41:43 -07:00
Andrew Kelley
d588f88b1a update C headers to LLVM 14.0.6 2022-07-03 15:58:39 -07:00
Andrew Kelley
cbdd21cd9a std: disable tests regressed from LLVM 14 2022-07-03 15:39:39 -07:00
Andrew Kelley
b698168664 stage2: update vector alignment logic
This follows LLVM14's lead on vector alignment, which computes byte
count based on the length premultiplied by bits.

This commit also disables behavior tests regressed by LLVM 14, only for
stage1. stage2 fortunately does not trip the regression.
2022-07-03 13:33:09 -07:00
Andrew Kelley
15f111a085 LLVM: update lowering of saturating shift-left
LLVM 14 makes it so that a RHS of saturating shift left produces a
poison value if the value is greater than the number of bits of the LHS.
Zig now emits code that will check if this is the case and select a
saturated LHS value in such case, matching Zig semantics.
2022-07-03 13:07:23 -07:00
Andrew Kelley
b1873f2074 LLVM: update inline asm to LLVM14 semantics
This is the equivalent of d19290e603
applied to stage2 instead of stage1.
2022-07-03 11:37:31 -07:00
Jakub Konka
5735ce39ae clang: parse --verbose flag as -v 2022-07-03 09:43:01 +02:00
Andrew Kelley
fcf77e06ea libcxx: add additional include directory
It appears that libcxx files now want to additionally include based
from the src/ directory.
2022-07-02 20:41:47 -07:00
Andrew Kelley
48136c11d1 libcxx: do not include __config_site
This file contains build configuration options which zig instead
provides via command line flags.
2022-07-02 20:40:59 -07:00
Andrew Kelley
f5b4b5d4cb std.zig.fmtId: revert recent changes
integer types are valid ids; we need different logic inside the
update_cpu_features tool, not to change the fmtId function.
2022-07-01 23:46:07 -07:00
Andrew Kelley
c8a00c4b02 update clang command line options to LLVM 14 2022-07-01 22:36:51 -07:00
Andrew Kelley
3ab5912eee LLD: the driver functions now return "false" to mean "error" 2022-07-01 22:13:30 -07:00
Andrew Kelley
ae0b0729fc LLD: there are fewer libraries to link against now 2022-07-01 22:13:12 -07:00
Andrew Kelley
d55d98919d update CPU features to LLVM 14
Notable changes:

`_i386`, `_i486`, and `_i686` are renamed to `i386`, `i486`,
and `i686` respectively. `std.zig.fmtId` is enhanced to support
formatting `i386` as `@"i386"`.

Some CPU features which are actually CPU models have been
properly flattened, such as `apple_a12`, `apple_a13`, `apple_a7`,
`cortex_a78c`, `exynos_m4`, `neoverse_e1`, `neoverse_n1`,
`neoverse_n2`, `neoverse_v1`.

Some CPU features have been added and some have been removed, following
LLVM's lead.

CSky CPU features support is added.
2022-07-01 21:35:19 -07:00
Andrew Kelley
d19290e603 stage1: update inline asm outputs to LLVM 14
LLVM pointers are transitioning to no longer have types, however, inline
assembly inputs and outputs which accept pointers need to know the
element type. So, inline assembly must be upgraded to add
elementtype(<ty>) annotations.
2022-07-01 20:11:06 -07:00
Andrew Kelley
1fa4a58d2c stage1: update to LLVM 14 API 2022-07-01 19:19:13 -07:00
Andrew Kelley
41a0b81731 CMake: disable deprecated function warnings
LLVM 14 deprecated a bunch of C API functions in preparation for opaque
pointer changes. However, they did not actually implement opaque pointer
semantics, so the deprecations are largely masturbatory. I have nothing
against masturbation, I am just busy trying to get the self hosted
compiler done for 0.10.0, so we will come back to this later.
2022-07-01 19:17:09 -07:00
Andrew Kelley
ceb3819c42 update libunwind to llvm 14.0.6 2022-07-01 16:39:31 -07:00
Andrew Kelley
aa964bd555 update libcxxabi to llvm 14.0.6 2022-07-01 16:39:29 -07:00
Andrew Kelley
bd680139d0 update libcxx to llvm 14.0.6 2022-07-01 16:31:47 -07:00
Andrew Kelley
c89dd15e1b Merge remote-tracking branch 'origin/master' into llvm14 2022-07-01 15:52:54 -07:00
Andrew Kelley
2360f8c490 Merge pull request #11974 from ziglang/fixfixfix
stage2 fixes
2022-07-01 17:29:31 -04:00
Andrew Kelley
7e2eb1326b Merge pull request #11973 from Vexu/stage2-compile-errors
more stage2 compile error fixes
2022-07-01 17:29:18 -04:00
Jakub Konka
b79884eaf0 macho: implement pruning of unused segments and sections
This is a prelude to a more elaborate work which will implement
`-dead_strip` flag - garbage collection of unreachable atoms. Here,
when sorting sections, we also check that the section is actually
populated with some atoms, and if not, we exclude it from the final
linked image. This can happen when we do not import any symbols
from dynamic libraries in which case we will not be populating
the stubs sections or the GOT table, implying we can skip allocating
those sections. Furthermore, we also make a check that a segment
is actually occupied too, with the exception of `__TEXT` segment
which is non-optional given that it wraps the header and load commands
and thus is required by the `dyld` to perform dynamic linking, and
`__PAGEZERO` which is generally non-optional when the linked image
is an executable. For any other segment, if its section count is
zero, we mark it as dead and skip allocating it and generating
a load command for it.

This commit also includes some minor improvements to the linker such
as refactoring of the segment allocating codepaths, skipping
`__PAGEZERO` generation for dylibs, and skipping generation of zero-sized
atoms for special symbols such as `__mh_execute_header` and `___dso_handle`.
These special symbols are only allocated local and global symbol pair
and their VM addresses is set to the start of the `__TEXT` segment,
but no `Atom` is created, as it's not necessary given that they never
carry any machine code.

Finally, we now always force-link against `libSystem` which turns out
to be required for `dyld` to properly handle `LC_MAIN` load command
on older macOS versions such as 10.15.7.
2022-07-01 22:05:22 +02:00
Frank Denis
ee01dd4032 crypto: add the Xoodoo permutation, prepare for Gimli deprecation (#11866)
Gimli was a game changer. A permutation that is large enough to be
used in sponge-like constructions, yet small enough to be compact
to implement and fast on a wide range of platforms.

And Gimli being part of the Zig standard library was awesome.

But since then, Gimli entered the NIST Lightweight Cryptography
Competition, competing againt other candidates sharing a similar set
of properties.

Unfortunately, Gimli didn't pass the 3rd round.

There are no practical attacks against Gimli when used correctly, but
NIST's decision means that Gimli is unlikely to ever get any traction.

So, maybe the time has come to move Gimli from the standard library
to another repository.

We shouldn't do it without providing an alternative, though.
And the best candidate for this is probably Xoodoo.

Xoodoo is the core function of Xoodyak, one of the finalists of the
NIST LWC competition, and the most direct competitor to Gimli. It is
also a 384-bit permutation, so it can easily be used everywhere Gimli
was used with no parameter changes.

It is the building block of Xoodyak (for actual encryption and hashing)
as well as Charm, that some Zig applications are already using.

Like Gimli that it was heavily inspired from, it is compact and
suitable for constrained environments.

This change adds the Xoodoo permutation to std.crypto.core.

The set of public functions includes everything required to later
implement existing Xoodoo-based constructions.

In order to prepare for the Gimli deprecation, the default
CSPRNG was changed to a Xoodoo-based that works exactly the same way.
2022-07-01 13:18:08 +02:00
Frank Denis
48fd92365a std.crypto.hash: allow creating hash functions from compositions (#11965)
A hash function cascade was a common way to avoid length-extension
attacks with traditional hash functions such as the SHA-2 family.

Add `std.crypto.hash.composition` to do exactly that using arbitrary
hash functions, and pre-define the common SHA2-based ones.

With this, we can now sign and verify Bitcoin signatures in pure Zig.
2022-07-01 11:37:41 +02:00
Veikka Tuominen
2029601cb2 AstGen: use elem_{ptr,val}_node for array access syntax 2022-07-01 10:22:26 +03:00
Veikka Tuominen
a6bf8c2593 Sema: add more validation to zirFieldParentPtr 2022-07-01 10:22:25 +03:00
Veikka Tuominen
e6ebf56dd6 Sema: validate @intToEnum int operand type 2022-07-01 10:22:25 +03:00
Veikka Tuominen
ae7b32eb62 Sema: validate deref operator type and value 2022-07-01 10:22:25 +03:00
Veikka Tuominen
3c73f71177 Sema: prefer func.onwer_decl for compilelog src 2022-07-01 10:22:25 +03:00
Veikka Tuominen
3014a0d5f1 Sema: validate callconv 2022-07-01 10:22:25 +03:00
Veikka Tuominen
6d24c40b6e Sema: improve bitcast to enum error 2022-07-01 09:29:13 +03:00
Andrew Kelley
095e24e537 stage2: implement alignment calculation of vectors
closes #11856
2022-06-30 19:39:41 -07:00
Andrew Kelley
d3542be875 LLVM: be sure to never pass align(0) attribute
This can happen with pointers to zero-bit types.

This commit fixes an LLVM assertion being tripped.
2022-06-30 18:33:02 -07:00
Andrew Kelley
c030ec1884 LLVM: use unnamed struct llvm type for unions when necessary
The constant value lowering for unions was missing a check for whether
the payload was itself an unnamed struct. Lowerings of other types
already handle this case.

closes #11971
2022-06-30 18:33:02 -07:00
Andrew Kelley
67db2b85b7 remove plan9 test coverage
This regressed; the plan9 linker code is crashing when trying to build
compiler-rt and we have no active plan9 maintainers involved in the Zig
project. Anyone is welcome to come over and take the role; however, it's
not one of the tier 1, 2, or 3 targets, so we will not be blocking
progress towards 1.0 on plan9.
2022-06-30 18:33:02 -07:00
Andrew Kelley
152462e2e1 stage2: object format affects whether LLVM can be used 2022-06-30 18:33:02 -07:00
Andrew Kelley
902dc8c721 CI: update freebsd pkg install command 2022-06-30 17:57:00 -07:00
Andrew Kelley
1951051e3d Merge pull request #11942 from Vexu/stage2-compile-errors
Move passing stage1 compile error tests to stage2
2022-06-30 18:39:46 -04:00
Andrew Kelley
77a334451f Merge pull request #11967 from ziglang/runtime-float-negation
stage2: lower float negation explicitly + modify hash/eql logic for floats
2022-06-30 17:34:05 -04:00
Mikko Kaihlavirta
be18459c81 std.event: use .{} to initiate Lock to unlocked state
Co-authored-by: Mikko Kaihlavirta <kaihlavirta@gmail.com>
2022-07-01 00:09:36 +03:00
Andrew Kelley
b3b96b5e28 LLVM: lower float negation with xor a constant
Rather than a compiler-rt call in the case that LLVM does not support
lowering the fneg instruction.
2022-06-30 11:48:37 -07:00
Veikka Tuominen
4cde6dd109 adjust tests that didn't pass CI 2022-06-30 21:47:26 +03:00
Veikka Tuominen
4f200eda9f stage2 llvm: ensure @tagName functions are unique 2022-06-30 21:47:25 +03:00
Veikka Tuominen
90ae37cc00 tests: move compile errors not planned for stage2 2022-06-30 09:57:38 +02:00
Veikka Tuominen
cc3336c784 Sema: add source location to coerce result ptr, fix negation error 2022-06-30 09:57:38 +02:00
Veikka Tuominen
979910dc38 Sema: validate shift amounts and switch ranges 2022-06-30 09:57:38 +02:00
Veikka Tuominen
6cadac18b8 Sema: improve auto generated union enum name 2022-06-30 09:57:38 +02:00
Veikka Tuominen
2e7dc5e151 Sema: improve vector overflow errors 2022-06-30 09:57:38 +02:00
Veikka Tuominen
03b356e34a Sema: improve @call errors 2022-06-30 09:57:38 +02:00
Veikka Tuominen
3204d00a5e move passing stage1 compile error tests to stage2 2022-06-30 09:57:38 +02:00
Andrew Kelley
c8531faaf5 stage2: hash/eql of fixed-size floats use bit pattern
Zig guarantees the memory layout of f16, f32, f64, f80, and f128 which
means for generic function purposes, values of these types need to be
compared on the basis of their bits in memory. This means nan-packing
can be used with generic functions, for example.

For comptime_float, the sign is observable, whether it is nan is
observable, but not any more kinds of bit patterns are observable.

This fixes the std.fmt tests that check printing "-nan".
2022-06-30 00:54:03 -07:00
Andrew Kelley
6bc6e47b15 stage2: lower float negation explicitly
Rather than lowering float negation as `0.0 - x`.

 * Add AIR instruction for float negation.
 * Add compiler-rt functions for f128, f80 negation

closes #11853
2022-06-30 00:02:00 -07:00
Andrew Kelley
c248af3bdc LLVM: fix lowering of untagged union types
The LLVM backend was calculating the amount of padding solely based
on the payload size. However, in the case where there is no union
tag, this fails to take into account alignment.

Closes #11857
2022-06-30 02:43:05 -04:00
Andrew Kelley
54454fd010 std.math.big.int: breaking API changes to prevent UAF
Many of the Managed methods accepted by-val parameters which could
reference Limb slices that became invalid memory after any
ensureCapacity calls. Now, Managed methods accept `*const Managed`
parameters so that if the function allows aliasing and the
ensure-capacity call resizes the Limb slice, it also affects the
aliased parameters, avoiding use-after-free bugs.

This is a breaking change that reduces the requirement for callsites to
manually make the ensure-capacity changes prior to calling many of the
Managed methods.

Closes #11897
2022-06-29 22:06:27 -04:00
Veikka Tuominen
8f2f0d8f08 Merge pull request #11962 from LordMZTE/fix/cast-or-call-parens
translate-c: fix cast or call macro with parenthesis
2022-06-29 21:36:13 +03:00
Andrew Kelley
98681b2da0 Merge pull request #11958 from ziglang/store-to-inferred-ptr
stage2: fix miscompilations for peer expressions any time they needed coercions to runtime types
2022-06-29 14:26:23 -04:00
Jakub Konka
7cc4176448 clang: add Zig equivalent for -headerpad_max_install_names cli flag 2022-06-29 17:21:32 +02:00
Jakub Konka
59359b2547 aarch64: add airRetLoad for register mcv 2022-06-29 17:19:49 +02:00
LordMZTE
b4ecc02471 translate-c: fix token pasting operator without parens 2022-06-29 16:59:18 +02:00
LordMZTE
7b32062775 translate-c: fix cast or call macro with parenthesis 2022-06-29 16:03:29 +02:00
Frank Denis
234ccb4a50 std.crypto.ecc: add support for the secp256k1 curve (#11880)
std.crypto.ecc: add support for the secp256k1 curve

Usage of the secp256k1 elliptic curve recently grew exponentially,
since this is the curve used by Bitcoin and other popular blockchains
such as Ethereum.

With this, Zig has support for all the widely deployed elliptic curves
today.
2022-06-29 15:11:33 +02:00
May B
ea13437ac5 std.json: Support disabling indent (#11823)
Newline Delimited JSON (ndjson) expect compact json without newline inside its content
Add None to StringfyOptions.indent and move newline writeByte inside StringfyOptions.outputIndent
2022-06-29 11:53:01 +02:00
4a6b70fbd1 mem: add splitBackwards (#11908)
* mem: refactor tests of split()

- add a few cases for .rest()
- use expectEqualSlices()

* mem: add splitBackwards

Over the last couple of weeks weeks I needed to iterate over a
collection backwards at least twice. Do we want to have this in stdlib?
If yes, click "Merge" and start using today! Free shipping and returns
(before 1.0).

Why is this useful?
-------------------

I need this for building an error wrapper: errors are added in the
wrapper from "lowest" level to "highest" level, and then printed in
reverse order. Imagine `UpdateUsers` call, which needs to return
`error.InvalidInput` and a wrappable error context. In Go we would add a
context to the error when returning it:

    // if update_user fails, add context on which user we are operating
    if err := update_user(user); err != nil {
        return fmt.Errorf("user id=%d: %w", user.id, err)
    }

Since Zig cannot pass anything else than u16 with an error (#2647), I
will pass a `err_ctx: *Err`, to the callers, where they can, besides
returning an error, augment it with auxiliary data. `Err` is a
preallocated array that can add zero-byte-separated strings. For a
concrete example, imagine such a call graph:

    update_user(User, *Err) error{InvalidInput}!<...>
      validate_user([]const u8, *Err) error{InvalidInput}!<...>

Where `validate_user` would like, besides only the error, signal the
invalid field. And `update_user`, besides the error, would signal the
offending user id.

We also don't want the low-level functions to know in which context they
are operating to construct a meaningful error message: if validation
fails, they append their "context" to the buffer. To translate/augment
the Go example above:

    pub fn validate_user(err_ctx: *Err, user: User) error{InvalidInput}!void {
        const name = user.name;
        if (!ascii.isAlpha(name)) {
            err_ctx.print("name '{s}' must be ascii-letters only", .{name});
            return error.InvalidInput;
        }
        <...>
    }

    // update_user validates each user and does something with it.
    pub fn update_user(err_ctx: *Err, user: User) error{InvalidInput}!void {
        // validate the user before updating it
        validate_user(user) catch {
            err_ctx.print("user id={d}", .{user.id});
            return error.InvalidInput;
        };
        <...>
    }

Then the top-level function (in my case, CLI) will read the buffer
backwards (splitting on `"\x00"`) and print:

    user id=123: name 'Žvangalas' must be ascii-letters only

To read that buffer backwards, dear readers of this commit message, I
need `mem.splitBackwards`.
2022-06-29 08:23:09 +02:00
Jakub Konka
bb3e1bcf31 Merge pull request #11954 from ziglang/fixes-weak-l
macho: weak libraries and frameworks fixes
2022-06-29 07:56:21 +02:00
Frank Denis
41533fa6a1 std/crypto/{25519,pcurves}: make the scalar field order public (#11955)
For 25519, it's very likely that applications would ever need the
serialized representation. Expose the value as an integer as in
other curves. Rename the internal representation from `field_size`
to `field_order` for consistency.

Also fix a common typo in `scalar.sub()`.
2022-06-29 07:44:43 +02:00
Frank Denis
b2e4dda001 std.crypto.{p256,p384}: process the top nibble in mulDoubleBasePublic (#11956)
Unlike curve25519 where the scalar size is not large enough to fill
the top nibble, this can definitely be the case for p256 and p384.
2022-06-29 07:43:49 +02:00
Andrew Kelley
c3ae909e93 Revert "AstGen: preserve inferred ptr result loc for breaks"
This reverts commit 8bf3e1f8d0, which
introduced miscompilations for peer expressions any time they needed
coercions to runtime types.

I opened #11957 as a proposal to accomplish the goal of the reverted
commit.

Closes #11898
2022-06-28 18:38:25 -07:00
Andrew Kelley
a058696df2 print_zir: fix unreachable missing end paren 2022-06-28 17:25:26 -07:00
Andrew Kelley
6c51c8e131 Sema: fix not propagating want_safety in zirBlock
Before this commit, `@setRuntimeSafety()` has no effect inside an if
expression.
2022-06-28 16:36:11 -07:00
Andrew Kelley
304a58a251 TypedValue: fix print function
for optional_payload_ptr and eu_payload_ptr
2022-06-28 16:35:34 -07:00
Ben Fiedler
76546b3f8e std.mem: add peek() to TokenIterator(T) 2022-06-28 21:45:02 +02:00
Philipp Lühmann
bb2929ba08 zig fmt: fix idempotency with newlines surrounding doc comment
Fixes: https://github.com/ziglang/zig/issues/11802
2022-06-28 21:38:28 +02:00
Jakub Konka
c2c1998269 clang: update cmdline options to include weak libs and frameworks
Clang accepts `-weak-lx`, `-weak_library x` and `-weak_framework x`.
2022-06-28 21:16:23 +02:00
Jakub Konka
c02dc17618 link: cache weak libraries 2022-06-28 20:52:31 +02:00
Andrew Kelley
8974cee5a1 Merge pull request #11919 from squeek502/failing-allocator-stacktrace
Add stack trace capturing to `FailingAllocator` and use it to improve `checkAllAllocationFailures`
2022-06-28 14:44:00 -04:00
Jakub Konka
9e8298b864 Merge pull request #11950 from ziglang/macho-weak-libs-frameworks
macho: fully implement `-weak-lx` and `-weak_framework x` flags
2022-06-28 20:29:20 +02:00
Shupei Fan
ca3c4ff2d0 zig0: handle baseline cpu features for rv64 2022-06-28 14:22:13 -04:00
Ken Micklas
22490892fa Pass -O0 rather than -Og to Clang for Debug builds 2022-06-28 14:16:22 -04:00
Andrew Kelley
aa1f9556d0 Merge pull request #11952 from ziglang/test-harness-improvements
Test harness improvements
2022-06-28 14:15:30 -04:00
Jakub Konka
914e2d4c99 test: fix spurious whitespace in nested_blocks test 2022-06-28 13:28:09 +02:00
Jakub Konka
6420e9350c test: return error on unknown config value 2022-06-28 13:28:05 +02:00
Jakub Konka
5834a608fc link-tests: do not save global extracted var unless a match
Improve testing MachO binaries by verbose printing of the symtab
which includes segment,section names for defined symbols, and
import (dylib) name for imports.
2022-06-28 10:23:25 +02:00
Jakub Konka
075f5bc5ff link-tests: test -weak-lx and -weak_framework x 2022-06-28 09:22:04 +02:00
Jakub Konka
20bd722464 build: handle weakly imported libs and frameworks 2022-06-28 09:19:01 +02:00
Jakub Konka
cd5dcfbf41 macho: annotate weak imports when linking with weak lib/framework 2022-06-28 09:19:01 +02:00
Jakub Konka
f353b59efa macho: discriminate between normal and weak dylibs
Parse `-weak-lx` and `-weak_framework x` in the CLI.
2022-06-28 09:18:54 +02:00
Andrew Kelley
975a660807 Merge pull request #11945 from ziglang/stage2-std
stage2 fixes towards standard library tests passing
2022-06-28 01:34:46 -04:00
Jakub Konka
1188415f4c cli: typo --needed_library should be -needed_library on macos 2022-06-28 07:30:13 +02:00
Jakub Konka
d4623a8a07 Merge pull request #11941 from ziglang/macho-stripping-dylibs
macho: handle `-dead_strip_dylibs`, `-needed-lx` and `-needed_framework x` flags
2022-06-28 07:22:19 +02:00
Andrew Kelley
a71d00a4d5 std.crypto.25519.field: avoid excessive inlining
This valid zig code produces reasonable LLVM IR, however, on the
wasm32-wasi target, when using the wasmtime runtime, the number of
locals of the `isSquare` function exceeds 50000, causing wasmtime
to refuse to execute the binary.

The `inline` keyword in Zig is intended to be used only where it is
semantically necessary; not as an optimization hint. Otherwise, this may
produce unwanted binary bloat for the -OReleaseSmall use case.

In the future, it is possible that we may end up with both `inline`
keyword, which operates as it does in status quo, and additionally
`callconv(.inline_hint)` which has no semantic impact, but may be
observed by optimization passes.

In this commit, I also cleaned up `isSquare` by eliminating an
unnecessary mutable variable, replacing it with several local constants.

Closes #11947.
2022-06-27 19:11:55 -07:00
Andrew Kelley
0b8bd9b2b4 std.os.linux.clone: upgrade to stage2 fn ptr semantics 2022-06-27 18:27:06 -07:00
Andrew Kelley
df1f401cf0 std.x.os.net: make error set consistent across targets 2022-06-27 18:26:50 -07:00
Andrew Kelley
3c1daf951c LLVM: fix invalid IR on @returnAddress of wasm/bpf
see #11946
2022-06-27 17:12:45 -07:00
Andrew Kelley
8d8a5f9733 LLVM: support calls to varargs functions
closes #11944
2022-06-27 16:02:41 -07:00
Andrew Kelley
3b19869853 Sema: honor the --test-filter flag 2022-06-27 14:31:54 -07:00
Jakub Konka
0dd28920da macho: implement and handle -needed-* and -needed_* family of flags
MachO linker now handles `-needed-l<name>`, `-needed_library=<name>`
and `-needed_framework=<name>`. While on macOS `-l` is equivalent
to `-needed-l`, and `-framework` to `-needed_framework`, it can be
used to the same effect as on Linux if combined with `-dead_strip_dylibs`.

This commit also adds handling for `-needed_library` which is macOS
specific flag only (in addition to `-needed-l`).

Finally, in order to leverage new linker testing harness, this commit
added ability to specify lowering to those flags via `build.zig`:
`linkSystemLibraryNeeded` (and related), and `linkFrameworkNeeded`.
2022-06-27 19:53:38 +02:00
Jakub Konka
efc5c97bff macho: implement -dead_strip_dylibs linker flag 2022-06-27 19:53:38 +02:00
Ryan Liptak
a76775b50a Fix stack traces with non-null first_address on Windows
Before this commit, the passed in length would always be given to the RtlCaptureStackBackTrace call. Now we always give the length of the actual buffer we're using (the addr_buf_stack size of 32 or the passed in length if it's larger than 32; this matches what the doc comment says the function was meant to be doing as well).

This was causing empty stack traces for things like the GeneralPurposeAllocator leak checking.

Fixes #6687
2022-06-27 20:00:39 +03:00
Pierre Curto
76f8328277 doc: update std.builtin.TypeInfo to std.builtin.Type 2022-06-27 19:48:52 +03:00
Ryan Liptak
22720981ea Move sys_can_stack_trace from GPA to std.debug so that it can be re-used as needed 2022-06-25 21:27:56 -07:00
Jakub Konka
08459ff1c2 Merge pull request #11933 from Luukdegram/wasm-link-bss
stage2: wasm-linker - Place decls in the correct segment and order segments
2022-06-25 22:51:06 +02:00
joachimschmidt557
960c142060 stage2 ARM: implement basic intCast and error union wrapping 2022-06-25 21:16:51 +02:00
Jakub Konka
76b28ed452 Merge pull request #11929 from ziglang/headerpad_max_install_names
macho: handle `-headerpad` and `-headerpad_max_install_names`
2022-06-25 21:15:59 +02:00
Luuk de Gram
140bac6395 link/wasm: Sort data segments
We now ensure the "bss" section is last, which allows us to not
emit this section and let the runtime initialize the memory with 0's instead.
This allows for smaller binaries.
The order of the other segments is arbitrary and does not matter, this may
change in the future.
2022-06-25 18:36:56 +02:00
Jakub Konka
589bf67635 macho: implement -headerpad_max_install_names 2022-06-25 18:04:40 +02:00
Jakub Konka
a6fbdfabb9 link-tests: add -headerpad_size test scenario 2022-06-25 17:59:09 +02:00
Jakub Konka
8c1feef4cd macho: implement -headerpad_size option
Includes both traditiona and incremental codepaths with one caveat that
in incremental case, the requested size cannot be smaller than the
default padding size due to prealloc required due to incremental nature
of linking.

Also parse `-headerpad_max_install_names`, however, not actionable just yet -
missing implementation.
2022-06-25 17:59:08 +02:00
Jakub Konka
f91503e577 link-tests: defer parsing of the RPN program until running the action 2022-06-25 17:56:03 +02:00
Jakub Konka
0078d36ff3 Merge pull request #11917 from motiejus/wl-search-paths
macho: implement `-search_paths_first` and `-search_dylibs_first`
2022-06-25 17:55:26 +02:00
Jakub Konka
8f00bc9d23 link-tests: put macho search strategy tests into one test case 2022-06-25 10:57:56 +02:00
Jakub Konka
dfdb807543 cache setting macho search strategy flags 2022-06-25 10:50:00 +02:00
Jakub Konka
24821dd17f link-tests: test -search_paths_first and -search_dylibs_first macho flags 2022-06-24 22:07:51 +02:00
Jakub Konka
eadac47631 cli: let the linker resolve libs into dynamic and static
Unlike targeting ELF-based OSes such as Linux, resolving system libs
on Darwin should follow one of two strategies: `-search_paths_first`
or `-search_dylibs_first` and hence we defer always forcing linking
a static library to the linker.
2022-06-24 22:02:19 +02:00
Luuk de Gram
e32a5ba78b link/wasm: Put decls into the correct segments
Decls will now be put into their respective segment.
e.g. a constant decl will be inserted into the "rodata" segment,
whereas an uninitialized decl will be put in the "bss" segment instead.
2022-06-24 22:01:41 +02:00
Jakub Konka
b60938eefd macho: verbose print all input linker args verbatim 2022-06-24 22:01:29 +02:00
Jakub Konka
905a18849f Merge pull request #11923 from koachan/sparc64-codegen
stage2: sparc64: Another batch of new Air lowerings, improvements, and fixes
2022-06-24 20:29:21 +02:00
Jakub Konka
0df7ed79d3 macho: implement -search_dylibs_first linker option 2022-06-24 20:25:16 +02:00
d589047e80 zld: ignore -search_paths_first
Ignore MachO-specific flag -search_paths_first, since it is the default
in zld and ld64.

Also see Jakub's comment[1]:

    Changing topic slightly, @motiejus dunno if you noticed, with this
    change building arm64 Zig binary fails on macos - it complains about
    unknown -search_paths_first flag. This one is an easy fix: we should
    ignore it since this is the default behaviour in both ld64 and zld.

[1]: https://github.com/ziglang/zig/pull/11906#issuecomment-1163545849
2022-06-24 19:03:15 +02:00
Koakuma
672d6df429 stage2: sparc64: Skip Sema-failing tests for now 2022-06-24 21:19:33 +07:00
Koakuma
ad176b319d stage2: sparc64: Implement SPARCv9 movr 2022-06-24 21:19:33 +07:00
Koakuma
65c5ef52e9 stage2: sparc64: Implement airRem, airMod, and SPARCv9 s/udivx 2022-06-24 21:19:33 +07:00
Koakuma
27adee3f12 stage2: sparc64: Implement airErrUnionPayloadPtrSet 2022-06-24 21:19:33 +07:00
Koakuma
84a57987c7 stage2: sparc64: Implement airAggregateInit 2022-06-24 21:19:33 +07:00
Koakuma
dd57729299 stage2: sparc64: Update BigTomb implementation to use Liveness
Change BigTomb implementation to call to Liveness' implementation
rather than implementing feed() in itself.
This is modelled after the AArch64 backend.
2022-06-24 21:19:33 +07:00
Koakuma
e2cb25358e stage2: sparc64: Implement airCall with BigTomb use for return 2022-06-24 21:19:33 +07:00
Koakuma
26b63b022f stage2: sparc64: Add airMemset placeholder 2022-06-24 21:19:33 +07:00
Koakuma
4fd0500bb5 stage2: sparc64: Implement airBoolToInt 2022-06-24 21:19:33 +07:00
Koakuma
837cd0d8af stage2: sparc64: Fix airNot comments/error messages 2022-06-24 21:19:33 +07:00
Koakuma
be6718b796 stage2: sparc64: Implement airIsNull/airIsNonNull 2022-06-24 21:19:33 +07:00
Koakuma
4d15284c3c stage2: sparc64: Implement SPARCv9 shifts 2022-06-24 21:19:33 +07:00
Koakuma
513ab4eb56 stage2: sparc64: Implement airIntCast basics 2022-06-24 21:19:33 +07:00
Koakuma
36bfe4b7ef stage2: sparc64: Implement airFence + SPARCv9 membar 2022-06-24 21:19:33 +07:00
Koakuma
18d61d691c stage2: sparc64: Implement airArrayElemVal 2022-06-24 21:19:33 +07:00
Koakuma
672cd2f02f stage2: sparc64: Implement SPARCv9 and 2022-06-24 21:19:33 +07:00
Koakuma
6218d70d09 stage2: sparc64: Implement airBinOp for and, or, and xor 2022-06-24 21:19:33 +07:00
Koakuma
921f776224 stage2: sparc64: Implement airTry 2022-06-24 21:19:27 +07:00
Koakuma
40590c8bf9 stage2: sparc64: Save registers before calling another function 2022-06-24 21:08:41 +07:00
Koakuma
5c8612642b stage2: sparc64: Use official encoding for not rs2, rs1 2022-06-24 21:08:41 +07:00
Koakuma
e7fde5f64e stage2: sparc64: Introduce condition_register MCValue type
Introduce condition_register MCValue type for future uses with BPr/MOVr
(mostly when needing to compare a signed value with zero)
2022-06-24 21:08:41 +07:00
Koakuma
accc3bad63 stage2: sparc64: Move conditional branch emission out of airCondBr 2022-06-24 21:08:41 +07:00
Koakuma
8b3f7d2ad8 stage2: sparc64: Merge the compare_flag structs into condition_flags
This follows the design in the aarch64 backend (commit
61844b6bd4).
2022-06-24 21:08:40 +07:00
Luuk de Gram
7c87f9c828 link:clarification & enable MachO getGlobalSymbol
This adds clarification to the getGlobalSymbol doc comments,
as well as renames the `addExternFn` function for MachO to `getGlobalSymbol`.
This function will now be called from 'src/link.zig' as well.

Finally, this also enables compiling zig's libc using LLVM even though
the `fno-LLVM` flag is given.
2022-06-24 08:12:17 +02:00
Luuk de Gram
3868864695 Revert "wasm: Enable f16 behavior tests"
This reverts commit 3c34c9f13c67ff1716a9531e87d23a6dad12b45e.
2022-06-24 08:12:17 +02:00
Luuk de Gram
6ae898b244 wasm: more f16 support and cleanup of intrinsics
`genFunctype` now accepts calling convention, param types, and return type
as part of its function signature rather than `fnData`. This means
we no longer have to create a dummy for our intrinsic call abstraction.
This also adds support for f16 division and builtins such as `@ceil` & more.
2022-06-24 08:12:17 +02:00
Luuk de Gram
ba37bc81e9 wasm: Enable f16 behavior tests 2022-06-24 08:12:17 +02:00
Luuk de Gram
a6747d328c stage2: Enable compiler-rt when LLVM is existant
Rather than checking if the user wants to use LLVM for the current compilation,
check for the existance of LLVM as part of the compiler. This is temporarily,
until other backends gain the ability to compiler LLVM themselves.
This means that when a user passed `-fno-LLVM` we will use the native
backend for the user's code, but use LLVM for compiler-rt.

This also fixes emitting names for symbols in the Wasm linker,
by deduplicating symbol names when multiple symbols point the same object.
2022-06-24 08:12:17 +02:00
Luuk de Gram
9015efe405 wasm: Implement @mulAdd for f16
Implements `@mulAdd` for floats with bitsize 16, where it generates
a call into compiler-rt's `fmaf` function. Note that arguments
for fmaf are different in order than `@mulAdd`.
2022-06-24 08:12:17 +02:00
Luuk de Gram
5ebaf49ebb wasm: Implement basic f16 support
This implements binary operations and comparisons
for floats with bitsize 16. It does this by calling into
compiler-rt to first extend the float to 32 bits, perform the operation,
and then finally truncate back to 16 bits. When loading and storing the f16,
we do this as an unsigned 16bit integer.
2022-06-24 08:12:17 +02:00
Luuk de Gram
241180216f wasm-linker: Parse object file from the archive
Rather than finding the original object file, we seekTo to the
object file's position within the archive file, and from there open
a new file handle. This file handle is passed to the `Object` parser
which will create the object.
2022-06-24 08:12:17 +02:00
Luuk de Gram
c9f929a18b fix memory leaks 2022-06-24 08:12:17 +02:00
Luuk de Gram
16daf3f3bc wasm-link: Discard old symbols correctly
When a new symbol is resolved to an existing symbol where
it doesn't overwrite the existing symbol, we now add this symbol
to the discarded list. This is required so when any relocation points
to the symbol, we can retrieve the correct symbol it's resolved by instead.
2022-06-24 08:12:17 +02:00
Luuk de Gram
1a3f58f5e5 wasm-linker: Correctly resolve function type
When performing relocations for a type index,
we first check if the target symbol is undefined. In which case,
we will obtain the type from the `import` rather than look into the
`functions` table.
2022-06-24 08:12:17 +02:00
Luuk de Gram
cb28fc2e63 wasm-linker: Resolve symbols from archives
Lazily load object files by default, and only load the object file
when an unresolved symbol has been found within an archive.
2022-06-24 08:12:17 +02:00
Luuk de Gram
0606fbbc4b wasm-linker: Implement Archive parsing
This implements a very basic archive file parser that validates
the magic bytes, and then parses the symbol table and stores
the symbol and their position.
2022-06-24 08:12:17 +02:00
Luuk de Gram
4d3715d89f wasm-linker: de-duplicate functions+atom sorting
Multiple symbols can point to the same function, this means that when we loop over
the symbol list, we must deduplicate those functions being added twice.
Additionaly, we must also ensure that when we append a new type and set the type
index on a function, we must not do this again for the same function.

This commit also implements sorting of code atoms to ensure their order matches
the order of the function section to ensure the function signature matches
that of the function body.
2022-06-24 08:12:17 +02:00
Luuk de Gram
8d03e4fc6b link: Implement API to get global symbol index 2022-06-24 08:12:17 +02:00
Luuk de Gram
359b61aec3 wasm: Create compiler-rt symbols and lowering
Implements the creation of an undefined symbol for a compiler-rt intrinsic.
Also implements the building of the function call to said compiler-rt intrinsic.
2022-06-24 08:12:17 +02:00
Ryan Liptak
19d7f4dd82 FailingAllocator: Only capture the stack trace of the first induced allocation failure
This is a precaution to avoid confusing stack traces on the off chance that FailingAllocator continues to try to allocate after the first failure.
2022-06-23 17:27:55 -07:00
Ryan Liptak
c321b2f2a0 checkAllAllocationFailures: add possibility of SwallowedOutOfMemoryError (split from NondeterministicMemoryUsage)
Inducing failure but not getting OutOfMemory back is not as much of a problem as never inducing failure when it was expected to be induced, so treating them differently and allowing them to be handled differently by the caller is useful.

For example, the current implementation of `std.HashMapUnmanaged.getOrPutContextAdapted` always tries to grow and then recovers from OutOfMemory by attempting a lookup of an existing key. If this function is used (i.e. from `std.BufMap.putMove`) with `checkAllAllocationFailures`, then we'd have previously triggered `error.NondeterministicMemoryUsage`, but the real cause is that `OutOfMemory` is being recovered from and so the error is being swallowed. The new error allows us to both understand what's happening easier and to catch it and ignore it if we're okay with the code we're testing handling `error.OutOfMemory` without always bubbling it up.
2022-06-23 17:20:24 -07:00
Ryan Liptak
def304a9a5 Integrate FailingAllocator stack trace with testing.checkAllAllocationFailures 2022-06-23 17:02:29 -07:00
Ryan Liptak
819e0e83d3 Add stack trace capturing to FailingAllocator 2022-06-23 17:01:56 -07:00
Jakub Konka
291c08f7b0 Merge pull request #11910 from ziglang/linker-tests 2022-06-24 00:02:12 +02:00
FlandreScarlet
87d8cb19e4 std.debug: fix ConfigurableTrace.dump OOB
The for-loop in dump() would index out of bounds if `t.index` is greater
than size, because `end` is the maximum of `t.index` and `size` rather than the
minimum.
2022-06-23 15:07:08 +03:00
Jakub Konka
03ddb42b8b link-tests: rename check() to checkStart()
Do not hardcode the symtab label; instead allow each parser to define
its own.

Check for missing extractor value in the matcher when matching `{}`.
2022-06-23 13:16:03 +02:00
Jakub Konka
6e04c2faab link-tests: fix parsing symtab for macho 2022-06-23 13:16:03 +02:00
Jakub Konka
4497e422f0 macho: fix aligning linkedit sections
Align by file offsets and not file size.
2022-06-23 13:16:00 +02:00
Jakub Konka
ab8a670a57 link-tests: enable on macos CI host only for now 2022-06-22 23:04:47 +02:00
Jakub Konka
e6c012c743 link-tests: add better docs 2022-06-22 22:40:05 +02:00
Jakub Konka
51f2442fc4 link-tests: clean up error messages in case of failure 2022-06-22 22:24:52 +02:00
Jakub Konka
ba768614ac link-tests: frameworks example can test for libobjc autolink in safety modes 2022-06-22 18:51:35 +02:00
Jakub Konka
b35e434cae link-tests: clean up linker testing harness 2022-06-22 18:34:39 +02:00
frmdstryr
6de0c622ff Add missing adddf3
```
LLD Link... ld.lld: error: undefined symbol: __aeabi_dadd
>>> referenced by errol.zig:366 (/home/usr/projects/zig/build/lib/zig/std/fmt/errol.zig:366)
```
2022-06-22 14:32:52 +02:00
Jakub Konka
211de9b63b link-tests: fix dumping of LOAD_DYLIB: name instead of path field 2022-06-22 10:40:10 +02:00
Jakub Konka
23a63f4ce4 link-tests: rename CheckMachOStep to CheckObjectStep and accept obj format 2022-06-22 10:27:51 +02:00
Jakub Konka
b5601a2da6 link-tests: extract values into variables
We can then collect multiple variables (currently assumed always
in global scope) and run a comparison with some very basic
arithmetic on the values.
2022-06-22 00:49:22 +02:00
Jakub Konka
3bb4d65b2f link-tests: move macho tests to subfolder
Handle `-e` option in MachO linker allowing the user to set a custom
entrypoint address.
2022-06-21 23:01:09 +02:00
Jakub Konka
937464f398 link-tests: dump metadata to string and grep results
This approach is more inline with what LLVM/LLD does for testing
of their output, and seems to be more generic and easier to extend
than implementing a lot of repetitive and nontrivial comparison
logic when working directly on structures.
2022-06-21 22:19:57 +02:00
Jakub Konka
5fbdfb3f34 link-tests: add CheckMachOStep
CheckMachOStep specialises CheckFileStep into directed (surgical)
MachO file fuzzy searches. This will be the building block for
comprehensive MachO linker tests.
2022-06-21 15:44:24 +02:00
Veikka Tuominen
d980c6a38d Merge pull request #11899 from Vexu/stage2
Stage2: fixes for std tests
2022-06-21 13:56:38 +03:00
Jonathan Marler
ca98625789 std.os.execvpe: fix buffer overflow
The NameTooLong check isn't taking the sentinel 0 into account which
would result in a buffer overflow on the stack.
2022-06-21 11:21:45 +02:00
Jakub Konka
2d09540a63 link-tests: test pagezero_size option for macho 2022-06-20 18:25:20 +02:00
Jakub Konka
6e56a8df20 link-tests: CheckFileStep to do grep test on the binary 2022-06-20 17:59:17 +02:00
Jakub Konka
38edef35bf test: introduce link(er) tests - builds on standalone tests 2022-06-20 17:59:17 +02:00
Jakub Konka
74ed7c1f09 Merge pull request #11875 from motiejus/pagezero-size
[MachO] add -pagezero_size
2022-06-20 17:51:20 +02:00
Veikka Tuominen
d0d5052b39 std.fmt: update test to stage2 fn pointer semantics 2022-06-20 16:12:40 +03:00
Jakub Konka
8752db3285 macho: -pagezero_size is always in hex
This matches the behavior of other linkers out there including
`ld64` and `lld`.
2022-06-20 14:26:59 +02:00
Veikka Tuominen
38a1222c87 std.crypto: fix invalid pass by value 2022-06-20 15:11:22 +03:00
Jakub Konka
753e2b8639 macho: verbose print pagezero size if specified 2022-06-20 13:52:39 +02:00
Jakub Konka
ea9b7a0626 macho: round down pagezero size to page size
If page aligned requested pagezero size is 0, skip generating
__PAGEZERO segment.

Add misc improvements to the pipeline, and correctly transfer the
requested __PAGEZERO size to the linker.
2022-06-20 13:39:33 +02:00
98138ba78c [MachO] add -pagezero_size
Pass `-pagezero_size` to the MachO linker. This is the final
"unsupported linker arg" that I could chase that CGo uses. After this
and #11874 we may be able to fail on an "unsupported linker arg" instead
of emiting a warning.

Test case:

    zig=/code/zig/build/zig
    CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 CC="$zig cc -target x86_64-macos" CXX="$zig c++ -target x86_64-macos" go build -a -ldflags "-s -w" cgo.go

I compiled a trivial CGo program and executed it on an amd64 Darwin
host.

To be honest, I am not entirely sure what this is doing. This feels
right after reading what this argument does in LLVM sources, but I am by
no means qualified to make MachO pull requests. Will take feedback.
2022-06-20 13:39:33 +02:00
Jakub Konka
a97a39bea6 Merge pull request #11893 from Luukdegram/wasm-sat
stage2: wasm - saturating arithmetic
2022-06-20 08:48:46 +02:00
Jakub Konka
74442f3503 Merge pull request #11847 from ziglang/better-libcompiler_rt 2022-06-20 00:26:39 +02:00
Jakub Konka
1d4dbf8d3c macos: run test-cases single threaded in the CI 2022-06-19 21:08:53 +02:00
Luuk de Gram
4957c7cbbd wasm: enable passing behavior tests
This also splits the test cases for addition and subtraction as the wasm
backend does not yet provide support for 128bit saturating arithmetic.
2022-06-19 17:27:56 +02:00
Luuk de Gram
a50147bfff wasm: fixes for signed saturation 2022-06-19 17:26:44 +02:00
Luuk de Gram
05600a6d84 wasm: saturating shift-left for signed integers 2022-06-19 15:50:03 +02:00
Jakub Konka
b4f2c0dcb9 compiler-rt: fix logic for choosing __gnu_{f2h,h2f}_ieee
Similar to wasm32-wasi-musl, Apple targets also want standard
symbol names.
2022-06-19 15:12:08 +02:00
Luuk de Gram
53831442ef wasm: saturating shift-left for unsigned integers 2022-06-19 14:30:17 +02:00
Luuk de Gram
ce5d934f5f wasm: saturating add and sub for signed integers 2022-06-19 14:30:17 +02:00
Luuk de Gram
fcd4280a8c wasm: implement saturating add, sub for unsigned
Implements +| and -| for unsigned integers <= 64 bits.
2022-06-19 14:30:13 +02:00
Jakub Konka
091238254e macho: return from flushModule if building object for static lib 2022-06-18 22:55:55 +02:00
Veikka Tuominen
8f9b31af92 value: handle slices in canMutateComptimeVarState 2022-06-18 20:04:49 +03:00
Andrew Kelley
30ef033693 compiler-rt: fix logic for choosing __gnu_{f2h,h2f}_ieee
wasm32-wasi-musl wants the standard symbol names however Linux requires
the `__gnu_*` flavors. I did not find any authoritative source on what
decides which symbol flavors to use. If we run into more trouble in the
future we can go back to having both.
2022-06-17 20:25:17 -07:00
Andrew Kelley
e4092d4442 stage2: rip out multi-compilation-unit compiler-rt
After doing performance testing, it seems that multi-compilation-unit
compiler-rt did not bring the performance improvements that we expected
it to. The idea is that it makes linking faster, however, it incurred a
cost in the frontend that was not offset by any gains in linking.

Furthermore, the single-object compiler-rt (with -ffunction-sections and
--gc-sections) ends up being fewer bytes on disk and so it's actually
the same or faster linking speed than the multi-compilation-unit
version.

So we are planning to keep using single-compilation-unit compiler-rt for
the foreseeable future, but may experiment with this again in the
future, in which case this commit can be reverted.
2022-06-17 18:34:11 -07:00
Andrew Kelley
2064d86298 update CMakeLists.txt source files 2022-06-17 18:24:57 -07:00
Andrew Kelley
ebab5288c3 compiler-rt: fix aeabi logic
Before, compiler-rt would have the wrong symbols for ARM targets.
2022-06-17 18:22:35 -07:00
Andrew Kelley
0556a2ba53 compiler-rt: finish cleanups
Finishes cleanups that I started in other commits in this branch.

 * Use common.linkage for all exports instead of redoing the logic in
   each file.
 * Remove pointless `@setRuntimeSafety` calls.
 * Avoid redundantly exporting multiple versions of functions. For
   example, if PPC wants `ceilf128` then don't also export `ceilq`;
   similarly if ARM wants `__aeabi_ddiv` then don't also export
   `__divdf3`.
 * Use `inline` for helper functions instead of making inline calls at
   callsites.
2022-06-17 18:10:00 -07:00
Andrew Kelley
3efc229bbf compiler-rt: musl ABI also needs __gnu_f2h_ieee etc 2022-06-17 16:42:50 -07:00
Andrew Kelley
bcf3a7d600 compiler-rt: gedf2 and gesf2 2022-06-17 16:40:25 -07:00
Andrew Kelley
e798a3a779 compiler-rt: disable separate compilation units 2022-06-17 16:38:59 -07:00
Andrew Kelley
5cd548e530 Compilation: multi-thread compiler-rt
compiler_rt_lib and compiler_rt_obj are extracted from the generic
JobQueue into simple boolean flags, and then handled explicitly inside
performAllTheWork().

Introduced generic handling of allocation failure and made
setMiscFailure not return a possible error.

Building the compiler-rt static library now takes advantage of
Compilation's ThreadPool. This introduced a problem, however, because
now each of the object files of compiler-rt all perform AstGen for the
full standard library and compiler-rt files. Even though all of them end
up being cache hits except for the first ones, this is wasteful - O(N*M)
where N is number of compilation units inside compiler-rt and M is the
number of .zig files in the standard library and compiler-rt combined.

More importantly, however, it causes a deadlock, because each thread
interacts with a file system lock for doing AstGen on files, and threads
end up waiting for each other. This will need to be handled with a
process-level file caching system, or some other creative solution.
2022-06-17 16:38:59 -07:00
Andrew Kelley
b4f3e69342 update CMakeLists.txt source file list 2022-06-17 16:38:59 -07:00
Andrew Kelley
fcebdbe25d compiler-rt: no more -ffunction-sections 2022-06-17 16:38:59 -07:00
Andrew Kelley
bbc6103398 compiler-rt: fix tests 2022-06-17 16:38:59 -07:00
Andrew Kelley
453243d9e0 compiler-rt: correct the list of builtins to build 2022-06-17 16:38:59 -07:00
Andrew Kelley
4200f89d94 compiler-rt: sort source files 2022-06-17 16:38:59 -07:00
Andrew Kelley
a8a7f15106 compiler-rt: use callconv(.AAPCS) on all __aeabi_ functions 2022-06-17 16:38:59 -07:00
Andrew Kelley
25671f5a97 compiler-rt: move SPARC functions into appropriate compilation units 2022-06-17 16:38:59 -07:00
Andrew Kelley
c99c085d70 compiler-rt: break up functions even more
The purpose of this branch is to switch to using an object file for each
independent function, in order to make linking simpler - instead of
relying on `-ffunction-sections` and `--gc-sections`, which involves the
linker doing the work of linking everything and then undoing work via
garbage collection, this will allow the linker to only include the
compilation units that are depended on in the first place.

This commit makes progress towards that goal.
2022-06-17 16:38:59 -07:00
Jakub Konka
47c834e477 macho: unify flushing object path with other linkers 2022-06-17 16:38:59 -07:00
Jakub Konka
f572e5a0c4 compiler_rt: shuffle order of imports to mark relevant symbols for export 2022-06-17 16:38:59 -07:00
Jakub Konka
57c530155f compiler_rt: correctly export allrem and aullrem for i386-windows-msvc 2022-06-17 16:38:59 -07:00
Jakub Konka
2259d629d3 compiler_rt: use single cache for libcompiler_rt.a static lib 2022-06-17 16:38:59 -07:00
Jakub Konka
80790be309 compiler_rt: compile each unit separately for improved archiving 2022-06-17 16:38:59 -07:00
Andrew Kelley
33cf6ef621 Merge pull request #11881 from Vexu/stage2
Stage2: fixes for bugs found while looking for miscompilations
2022-06-17 19:23:08 -04:00
Veikka Tuominen
28986a0590 stage2: check that struct is a tuple when value tags differ in eql 2022-06-17 21:04:21 +03:00
Veikka Tuominen
a224dfceee std.tz: fix function returning pointer to local variable 2022-06-17 21:04:21 +03:00
Xavier Bouchoux
b66247c97a stage2: coerce tuple to vector 2022-06-17 19:06:17 +03:00
Omar Alhammadi
69e2cac0d3 stage2: comptime @bitCast packed struct bug fix 2022-06-17 19:04:51 +03:00
Veikka Tuominen
b9dcbe6b4c Sema: handle sentinels in tupleToArray 2022-06-17 18:57:02 +03:00
Veikka Tuominen
ffa6f895ff Sema: validateArrayInit detect bitcast before store 2022-06-17 18:57:02 +03:00
d506275a06 [elf] understand -no-pie
This passes -Wl,-no-pie linker arg. Golang uses that. From the `ld(1)`
man page:

   Create a position dependent executable.  This is the default.

Not adding to the help text, because this is the default.
2022-06-16 15:27:30 -04:00
Jakub Konka
d3caacfab7 Merge pull request #11864 from jedisct1/wasi-libc-update
Update the WASI libc to 30094b6ed05f19cee102115215863d185f2db4f0
2022-06-15 12:33:17 +02:00
Frank Denis
27610b0a0f std/crypto: add support for ECDSA signatures (#11855)
ECDSA is the most commonly used signature scheme today, mainly for
historical and conformance reasons. It is a necessary evil for
many standard protocols such as TLS and JWT.

It is tricky to implement securely and has been the root cause of
multiple security disasters, from the Playstation 3 hack to multiple
critical issues in OpenSSL and Java.

This implementation combines lessons learned from the past with
recent recommendations.

In Zig, the NIST curves that ECDSA is almost always instantied with
use formally verified field arithmetic, giving us peace of mind
even on edge cases. And the API rejects neutral elements where it
matters, and unconditionally checks for non-canonical encoding for
scalars and group elements. This automatically eliminates common
vulnerabilities such as https://sk.tl/2LpS695v .

ECDSA's security heavily relies on the security of the random number
generator, which is a concern in some environments.

This implementation mitigates this by computing deterministic
nonces using the conservative scheme from Pornin et al. with the
optional addition of randomness as proposed in Ericsson's
"Deterministic ECDSA and EdDSA Signatures with Additional Randomness"
document. This approach mitigates both the implications of a weak RNG
and the practical implications of fault attacks.

Project Wycheproof is a Google project to test crypto libraries against
known attacks by triggering edge cases. It discovered vulnerabilities
in virtually all major ECDSA implementations.

The entire set of ECDSA-P256-SHA256 test vectors from Project Wycheproof
is included here. Zero defects were found in this implementation.

The public API differs from the Ed25519 one. Instead of raw byte strings
for keys and signatures, we introduce Signature, PublicKey and SecretKey
structures.

The reason is that a raw byte representation would not be optimal.
There are multiple standard representations for keys and signatures,
and decoding/encoding them may not be cheap (field elements have to be
converted from/to the montgomery domain).

So, the intent is to eventually move ed25519 to the same API, which
is not going to introduce any performance regression, but will bring
us a consistent API, that we can also reuse for RSA.
2022-06-15 08:55:39 +02:00
Andrew Kelley
0e9458a3fc test-cases: avoid using realpath since it is not portable
For example FreeBSD does not support this syscall.
2022-06-14 22:15:22 -07:00
Andrew Kelley
8caa206417 test-cases: fix race with zig run on C backend tests
Also avoid redundantly doing compile-error checks on multiple targets
for test cases where that is not helpful.
2022-06-14 15:27:43 -07:00
Frank Denis
8c63037695 Update the WASI libc
Update our copy of wasi-libc up to the commit
30094b6ed05f19cee102115215863d185f2db4f0 from the upstream repository.
2022-06-14 23:20:39 +02:00
Andrew Kelley
22690efcc2 multi-thread zig build test-cases
Instead of always using std.testing.allocator, the test harness now follows
the same logic as self-hosted for choosing an allocator - that is - it
uses C allocator when linking libc, std.testing.allocator otherwise, and
respects `-Dforce-gpa` to override the decision. I did this because
I found GeneralPurposeAllocator to be prohibitively slow when doing
multi-threading, even in the context of a debug build.

There is now a second thread pool which is used to spawn each
test case. The stage2 tests are passed the first thread pool. If it were
only multi-threading the stage1 tests then we could use the same thread
pool for everything. However, the problem with this strategy with stage2
is that stage2 wants to spawn tasks and then call wait() on the main
thread. If we use the same thread pool for everything, we get a deadlock
because all the threads end up all hanging at wait() and nothing is
getting done. So we use our second thread pool to simulate a "process pool"
of sorts.

I spent most of the time working on this commit scratching my head trying
to figure out why I was getting ETXTBSY when spawning the test cases.
Turns out it's a fundamental Unix design flaw, already a known, unsolved
issue by Go and Java maintainers:

https://github.com/golang/go/issues/22315
https://bugs.openjdk.org/browse/JDK-8068370

With this change, the following command, executed on my laptop, went from
6m24s to 1m44s:

```
stage1/bin/zig build test-cases -fqemu -fwasmtime -Denable-llvm
```

closes #11818
2022-06-14 17:15:13 -04:00
Mikael Berthe
47c4d44502 std.math.big.int: update Managed.toString() to use provided allocator (#11839) 2022-06-13 17:19:37 +02:00
Frank Denis
7c660d17cd crypto/pcurves: compute constants for inversion at comptime (#11780) 2022-06-13 08:13:52 +02:00
Andrew Kelley
13f02c30e6 stage2: fix some inline asm incompatibilities with stage1 2022-06-12 14:46:05 -07:00
Andrew Kelley
ffa700ee58 Merge pull request #11837 from Vexu/stage2
Fix (nearly) all stage2 crashes when testing stdlib
2022-06-12 17:45:57 -04:00
Andrew Kelley
6e42d45dcc Merge pull request #11851 from ziglang/stage2-comptime-store
Sema: rework beginComptimePtrMutation
2022-06-12 15:19:15 -04:00
Veikka Tuominen
0a9d6956e7 Sema: add missing set_union_tag 2022-06-12 19:17:41 +03:00
Andrew Kelley
e64d5a0753 Sema: rework beginComptimePtrMutation
This comment is now deleted because the task is completed in this
commit:

```
// TODO: Update this to behave like `beginComptimePtrLoad` and properly check/use
// `container_ty` and `array_ty`, instead of trusting that the parent decl type
// matches the type used to derive the elem_ptr/field_ptr/etc.
//
// This is needed because the types will not match if the pointer we're mutating
// through is reinterpreting comptime memory.
```

The main strategy is to change the ComptimePtrMutationKit struct so that
instead of `val: *Value` it now returns a tagged union which can be one
of three possibilities:

 * The pointer type matches the actual comptime Value so a direct
   modification is possible. Before this commit, the implementation
   incorrectly assumed this was always the case.

 * In the case of needing to write through a reinterpreted pointer, a
   mutable base Value pointer is provided along with a byte offset
   pointing to the element value in virtual memory.

 * Otherwise, it means a compile error must be emitted because one or
   both of the types (the owner of the value, or the pointer type being
   used to write through) do not have a well-defined memory layout.

After calling beginComptimePtrMutation, the one callsite now switches on
this tagged union and does the appropriate thing. The main new logic is
for the second case, which involves pointer reinterpretation, which now
takes this strategy:

 1. write the base value to a memory buffer.
 2. perform the pointer store at the proper byte offset, thereby
    modifying a subset of the buffer.
 3. read the base value from the memory buffer, overwriting the old base
    value.
2022-06-12 01:33:56 -07:00
Andrew Kelley
c29746aa55 add std.debug.Trace.format
This makes it show up in some useful places; for example in the
self-hosted compiler we already print it now with
--debug-compile-errors.
2022-06-12 00:57:59 -07:00
Andrew Kelley
85492f2b91 std.mem.zeroes: remove call to std.meta
everybody is so horny for std.meta
2022-06-12 00:56:59 -07:00
Veikka Tuominen
6b36774adc std: disable failing tests, add zig2 build test-std to CI 2022-06-12 10:43:28 +03:00
Veikka Tuominen
35c7e376b8 stage2: improve anon name strategy for local variables 2022-06-11 23:49:33 +03:00
Veikka Tuominen
0333ff4476 stage2: make error{} the same size as anyerror
Having `error{}` be a zero bit type causes issues when it interracts
with empty inferred error sets which are the same size as `anyerror`.
2022-06-11 23:49:33 +03:00
Veikka Tuominen
488e1e5f51 stage2: small fixes + adjustments to std tests 2022-06-11 23:49:33 +03:00
Veikka Tuominen
95ab942184 Sema: make @src give absolute paths 2022-06-11 23:12:52 +03:00
Andrew Kelley
9360cfebc7 Sema: type safety for "runtime_index" field
This commit does not change any behavior, but changes the type of
the runtime_index field from u32 to a non-exhaustive enum. This allows
us to put `std.math.maxInt(u32)` only in the enum type definition and
give it an official meaning.
2022-06-11 12:18:04 -07:00
Luuk de Gram
13123afedb wasm: implement @ceil, @floor and @trunc 2022-06-11 19:38:00 +02:00
Luuk de Gram
f05e09a0cf wasm: optimize & simplify sign extension
Rather than storing all the shifts in temporaries, we perform the correct
shifting without temporaries. This makes the runtime code more performant
and also the backend code is simplified as we have a singular abstraction.
2022-06-11 19:38:00 +02:00
Luuk de Gram
18afcc34c6 wasm: implement @divFloor for signed integers 2022-06-11 19:38:00 +02:00
Luuk de Gram
3011ef2d82 wasm: signed integer division (non-floor)
Implements the non-floor variants of signed integer division.
2022-06-11 19:38:00 +02:00
Luuk de Gram
9b84f29503 wasm: support all @div{trunc/floor/exact} ops
This does however not support floats of bitsizes
different than 32 or 64. f16, f80, f126 will require
support for compiler-rt and are out-of-scope for this commit.

Signed integers are currently not supported either.
2022-06-11 19:38:00 +02:00
Luuk de Gram
180baa0546 wasm:@byteSwap for 24 bit integers 2022-06-11 19:38:00 +02:00
Luuk de Gram
bc499de328 wasm: implement @byteSwap for 16/32bit integers 2022-06-11 19:38:00 +02:00
Veikka Tuominen
eaa6b04c3c Sema: skip decl causing namespace lookup when doing lookup 2022-06-11 11:02:56 +03:00
Veikka Tuominen
0f820d0bdf stage2: improve debugging tools
llvm: dump failed module when -femit-llvm-ir set
print_air:
 * print fully qualified name
 * use Type.fmt and Value.fmtValue, fmtDebug is useless

TypedValue
 * handle anon structs and tuples
 * fix bugs
2022-06-11 11:02:56 +03:00
Veikka Tuominen
002df65b6e Sema: handle tuple and anon_struct in resolveTypeFully 2022-06-11 11:02:56 +03:00
Andrew Kelley
c1eb6c30e8 Merge pull request #11835 from ziglang/stage2-behavior
stage2: fix handling of aggregates with mixed comptime-only fields
2022-06-11 00:27:41 -04:00
Cody Tapscott
9b05474d79 ThreadPool: Make join() a no-op in single-threaded mode
This comptime gate is needed to make sure that purely single-threaded
programs don't generate calls to the std.Thread API.

WASI targets successfully build again with this change.
2022-06-10 21:59:39 -04:00
Andrew Kelley
6bf529dc38 link/wasm: fix writing past the end of debug info buffer
The function `writeDbgInfoNopsBuffered` was based on the function
`pwriteDbgInfoNops`, originally written by me, and then modified to
write to a memory buffer instead of an open file. When writing to a
file, any extra bytes beyond the end of the file extend the size of
the file, and the function body of `pwriteDbgInfoNops` takes advantage
of this when `next_padding_bytes` causes the write to go beyond the
end of the file. However, when writing to a memory buffer, the
underlying array list must be expanded if the write would cause the
buffer to expand.
2022-06-10 17:55:17 -07:00
Jakub Konka
62023c60b4 stage2: correctly work out dirname for ar 2022-06-11 00:23:10 +02:00
Andrew Kelley
3c3bc5af29 Sema: introduce bitSizeAdvanced to recursively resolve types
Same pattern as abiSizeAdvanced.

Fixes compiler crash for nested packed structs.
2022-06-10 15:04:39 -07:00
Andrew Kelley
fcfeafe99a Merge pull request #11819 from ziglang/std.debug.Trace
introduce std.debug.Trace and use it to debug a LazySrcLoc in stage2 that is set to a bogus value
2022-06-10 05:26:59 -04:00
Andrew Kelley
58bc562cb4 update packed struct behavior tests to new language semantics 2022-06-09 20:37:24 -07:00
Andrew Kelley
436aafd3e2 remove a stage2 test case that relies on a very deep compiler stack
It's causing Drone CI failure on aarch64. I will open a follow-up issue
to track this missing test case.
2022-06-09 20:00:59 -07:00
Andrew Kelley
2bf532fc23 stage2: use std.debug.Trace only when explicitly enabled
Because it bumps up the stack space requirements, which is making a test
case fail on aarch64 drone CI.
2022-06-09 20:00:59 -07:00
Andrew Kelley
32c90cb553 stage2: fix handling of aggregates with mixed comptime-only fields 2022-06-09 19:23:36 -07:00
Isaac Freund
5816d3eaec linker: remove -z noexecstack option
Note that the current documentation for the `-z noexecstack` is
incorrect. This indicates that an object *does not* require an
executable stack.

This is actually the default of LLD, and there has never been a way to
override this default by passing `-z execstack` to LLD.

This commit removes the redundant `-z noexecstack` option from
zig build-exe/build-lib/build-obj and ignores the option if passed
to zig cc for compatibility.

As far as I can tell, there is no reason for code to require an
executable stack. This option only exists because the stack was
originally executable by default and some programs came to depend
on that behavior. Instead, mprotect(2) may be used to make memory
pages executable.
2022-06-09 18:51:43 -04:00
Andrew Kelley
bc36da0cb8 test harness: fix handling of counts
I'm not really happy with parsing compile errors; I think we should just
be checking that the expected compile error matches the actual rendered
version. I will save that change for a later date however.
2022-06-09 15:37:16 -07:00
Andrew Kelley
fd32f6890d stage2: fold redundant error notes 2022-06-09 15:37:16 -07:00
Andrew Kelley
af909f6c93 std.debug.Trace: improve API
Now `std.debug.Trace` is a concrete type with pre-chosen defaults.
`std.debug.ConfigurableTrace` can be used for more advanced cases.
2022-06-09 15:37:16 -07:00
Andrew Kelley
83f300218f upgrade behavior test to stage2 fn ptr semantics 2022-06-09 15:37:16 -07:00
Andrew Kelley
bac132bc8f introduce std.debug.Trace
And use it to debug a LazySrcLoc in stage2 that is set to a bogus value.

The actual fix in this commit is:

```diff
-        try sema.emitBackwardBranch(&child_block, call_src);
+        try sema.emitBackwardBranch(block, call_src);
```
2022-06-09 15:37:16 -07:00
Andrew Kelley
f1cff4fa4a Sema: avoid use of undefined value for generic fn calls
I saw some issues in Valgrind which are fixed after this commit.
2022-06-09 15:09:48 -07:00
Andrew Kelley
a3f05b80f1 Merge pull request #11827 from ziglang/stage2-behavior
stage2: enhancements aimed at more behavior tests passing
2022-06-09 06:13:47 -04:00
Andrew Kelley
f4d5fcde72 AstGen: avoid redundant "ref" instructions
Whenever a `ref` instruction is needed, it is created and saved in
`AstGen.ref_table` instead of being immediately appended to the current
block body. Then, when the referenced instruction is being added to the
parent block (e.g. from setBlockBody), if it has a ref_table entry, then
the ref instruction is added directly after the instruction being referenced.
This makes sure two properties are upheld:
1. All pointers to the same locals return the same address. This is required
   to be compliant with the language specification.
2. `ref` instructions will dominate their uses. This is a required property
   of ZIR.

A complication arises when a ref instruction refs another ref
instruction. The logic in appendBodyWithFixups must take this into
account, recursively handling ref refs.
2022-06-08 20:40:16 -07:00
Andrew Kelley
7c0614ea65 Sema: implement zirRetErrValueCode 2022-06-08 15:51:48 -07:00
Andrew Kelley
d557dedf6c add a missing align() to a behavior test 2022-06-08 15:38:15 -07:00
Andrew Kelley
434226c89d stage2: fix type printing of sub-byte pointers 2022-06-08 15:18:43 -07:00
Andrew Kelley
93d7fd9547 test harness: fix sort comparator
It was returning "true" for lessThan() when the objects were in fact
equal.
2022-06-08 15:17:53 -07:00
Isaac Freund
29dd9a5880 parser: sync comments with formal grammar 2022-06-08 21:53:06 +02:00
Andrew Kelley
868a39b296 Merge pull request #11821 from ziglang/stage2-packed-structs
stage2: better codegen for byte-aligned packed struct fields
2022-06-08 15:24:17 -04:00
Andrew Kelley
f5d97e5e48 Merge pull request #11825 from ifreund/std-build-relro
Enable full RELRO by default, expose in std.build
2022-06-08 15:21:22 -04:00
Isaac Freund
d8cae4d197 std.build: Expose -z norelro and -z lazy 2022-06-08 15:13:04 +02:00
Isaac Freund
3381779426 linker: Enable full RELRO by default
Full RELRO is a hardening feature that makes it impossible to perform
certian attacks involving overwriting parts of the Global Offset Table
to invoke arbitrary code.

It requires all symbols to be resolved before execution of the program
starts which may have an impact on startup time. However most if
not all popular Linux distributions enable full RELRO by default for
all binaries and this does not seem to make a noticeable difference
in practice.

"Partial RELRO" is equivalent to `-z relro -z lazy`.
"Full RELRO" is equivalent to `-z relro -z now`.

LLD defaults to `-z relro -z lazy`, which means Zig's current `-z relro`
option has no effect on LLD's behavior.

The changes made by this commit are as follows:

- Document that `-z relro` is the default and add `-z norelro`.
- Pass `-z now` to LLD by default to enable full RELRO by default.
- Add `-z lazy` to disable passing `-z now`.
2022-06-08 14:33:11 +02:00
Andrew Kelley
53c86febcb stage2: packed struct fixes for big-endian targets 2022-06-07 22:47:08 -07:00
Andrew Kelley
3e30ba3f20 stage2: better codegen for byte-aligned packed struct fields
* Sema: handle overaligned packed struct field pointers
 * LLVM: handle byte-aligned packed struct field pointers
2022-06-07 21:05:40 -07:00
joachimschmidt557
61844b6bd4 stage2 AArch64: introduce MCValue.condition_flags
Follows 9747303d16 for AArch64
2022-06-07 23:34:42 -04:00
Cody Tapscott
70dc910086 std.math: Add O(log N) implementation of log2(x) for comptime_int
Since Zig provides @clz and not @ffs (find-first-set), log2 for comptime
integers needs to be computed algorithmically. To avoid hitting the
backward branch quota, this updates log2(x) to use a simple O(log N)
algorithm.
2022-06-07 20:07:40 -04:00
Andrew Kelley
6ff7b437ff Merge pull request #11813 from Vexu/stage2
`zig2 build test-std` finale
2022-06-07 20:07:28 -04:00
Jakub Konka
3cb3873382 Merge pull request #11814 from ziglang/x64-stack-handling
x64: improves stack handling, fixes a heisenbug, adds micro-optimisations
2022-06-07 23:22:20 +02:00
Jakub Konka
6c59aa9e02 Merge pull request #11806 from koachan/sparc64-codegen
stage2: sparc64: Some more Air lowerings
2022-06-07 21:24:56 +02:00
Jonathan Marler
523fae420b add const to msghdr_const iov and control pointers
alongside the typical msghdr struct, Zig has added a msghdr_const
type that can be used with sendmsg which allows const data to
be provided.  I believe that data pointed to by the iov and control
fields in msghdr are also left unmodified, in which case they can
be marked const as well.
2022-06-07 15:23:44 -04:00
Jakub Konka
27dad11ef1 x64: remove outdated TODO comment 2022-06-07 21:05:11 +02:00
Veikka Tuominen
413577c881 std: adjust for stage2 semantics 2022-06-07 21:27:07 +03:00
Veikka Tuominen
6de9eea7bc stage2 llvm: fix float/int conversion compiler-rt calls 2022-06-07 21:27:06 +03:00
Veikka Tuominen
fbd7e4506f stage2: implement asm with multiple outputs 2022-06-07 21:27:06 +03:00
Veikka Tuominen
e4c0b848a4 Sema: allow simple else body even when all errors handled 2022-06-07 21:27:06 +03:00
Veikka Tuominen
d5e3d5d74c Sema: make analyzeIsNonErr even lazier for inferred error sets 2022-06-07 21:27:06 +03:00
Jakub Konka
76ad7af4d8 x64: pull common codepath between store and genSetStack into a helper 2022-06-07 19:33:43 +02:00
Jakub Konka
03068ce6a6 x64: clean up store helper 2022-06-07 19:33:43 +02:00
Jakub Konka
a8bce8f14b x64: pass behavior test bugs/1381 2022-06-07 19:33:43 +02:00
Jakub Konka
0c72760454 x64: optimise element offset calculation if dealing with immediates
If `index` MCValue is actually an immediate, we can calculate offset
directly at "comptime" rather than at runtime.
2022-06-07 19:33:43 +02:00
Jakub Konka
fc015231ad x64: account for non-pow-two stores via register deref
In this case, we need to proceed rather carefully to avoid writing
containing register width rather than the precise amount of bytes.
2022-06-07 19:33:43 +02:00
Jakub Konka
117f9f69e7 x64: simplify saving registers to stack in prologue 2022-06-07 19:33:40 +02:00
Andrew Kelley
e9fc58eab7 LLVM: handle extern function name collisions
Zig allows multiple extern functions with the same name, and the
backends have to handle this possibility.

For LLVM, we keep a sparse map of collisions, and then resolve them in
flushModule(). This introduces some technical debt that will have to be
resolved when adding incremental compilation support to the LLVM
backend.
2022-06-07 00:47:10 -04:00
Jakub Konka
d9b0c984aa Merge pull request #11794 from ziglang/elf-macho-alignment
elf+macho: use explicit alignment on Decl if specified
2022-06-07 01:03:15 +02:00
Andrew Kelley
d1bfc83774 Merge pull request #11783 from ziglang/stage2-try
introduce a "try" ZIR and AIR instruction
2022-06-06 19:01:39 -04:00
Andrew Kelley
be639eecc2 Merge pull request #11565 from matu3ba/port_abort
std.os: ported signal handling in abort() from musl
2022-06-06 18:35:24 -04:00
Andrew Kelley
073762395e std.os.abort patch cleanups
* move global into function scope
 * clarify comments
 * avoid unnecessary usage of std.atomic API
 * switch on error instead of `catch unreachable`
 * call linux.gettid() instead of going through higher level API and
   doing unnecessary casting
2022-06-06 15:34:20 -07:00
Jan Philipp Hafer
d1e8b73939 std.os.abort: ported signal handling from musl
* Document deviation from Linux man page, which is identical to musl.
  Man page wants always enabled user-provided abort handlers.
  Worst case logic bug, which this can introduce:
    + user disables SIGABRT handler to prevent tear down to last safe
      state
    + abort() gets called and enables user-provided SIGABRT handler
    + SIGABRT tears down to supposed last safe state instead of crash
    + Application, instead of crashing, continues
* Pid 1 within containers needs special handling.
  - fatal signals are not transmitted without privileges,
    so use exit as fallback
* Fix some signaling bits
* Add checks in Debug and ReleaseSafe for wrong sigprocmask
2022-06-06 15:32:39 -07:00
Jakub Konka
920f1dcd27 Merge pull request #11804 from ziglang/elf-dwarf-unions
dwarf: fix incorrect type relocations for union payloads
2022-06-07 00:22:36 +02:00
Andrew Kelley
367e2b2fe4 Merge pull request #11800 from Vexu/stage2
`zig2 build test-std` progress
2022-06-06 16:12:31 -04:00
Veikka Tuominen
14685e59b2 stage2: use correct type (u29) for alignment 2022-06-06 13:11:54 -07:00
Veikka Tuominen
32568dba74 std: handle stage2 function pointer semantics in test 2022-06-06 13:11:50 -07:00
Veikka Tuominen
61c5d8f8f1 std.fs: fix incorrect passing of pointer to temporary 2022-06-06 13:11:50 -07:00
Veikka Tuominen
bb84c87a47 std: add necessary @alignCasts 2022-06-06 13:11:50 -07:00
Veikka Tuominen
15ec55406d std: fix ambiguous references 2022-06-06 13:11:50 -07:00
Veikka Tuominen
84000aa820 Sema: fix inline call of func using ret_ptr with comptime only type 2022-06-06 13:11:50 -07:00
Veikka Tuominen
8fa88c88c2 AstGen: fix coercion scope type when stores are eliminated 2022-06-06 13:11:50 -07:00
Veikka Tuominen
cb5d2b691a Sema: validate equality on store to comptime field 2022-06-06 13:11:50 -07:00
Veikka Tuominen
a040ccb42f Sema: fix coerce result ptr outside of functions 2022-06-06 13:11:50 -07:00
joachimschmidt557
8ca6dc33d1 stage2 AArch64: implement try AIR instruction 2022-06-06 21:27:36 +02:00
Andrew Kelley
41bf81dc32 Revert "Treat blocks with "return" as "noreturn""
This reverts commit 135b91aecd.

"endsWithBreak()" is not a meaningful question to ask and should not be
used this way. A simple example that defeats this logic is:

```zig
export fn entry() void {
    outer: {
        {
            break :outer;
        }
        return;
    }
}
```
2022-06-06 11:31:54 -07:00
Jakub Konka
e05de31a5f dwarf: fix incorrect type reloc for unions
Split type relocs into two kinds: local and global. Global relocs
use a global type resolver and calculate offset to the existing
definition of a type abbreviation.

Local relocs use offset in the abbrev section of the containing
atom plus addend to generate a local relocation.
2022-06-06 19:58:51 +02:00
Jakub Konka
0cab01adbf elf: refactor and enhance logging symtab 2022-06-06 19:58:47 +02:00
Koakuma
97d35a5147 behaviortest: Skip 'align(N) on functions' on sparc64 for now 2022-06-06 21:17:09 +07:00
Koakuma
ec7f2a105f stage2: sparc64: Implement airPtrElemPtr 2022-06-06 21:17:09 +07:00
Koakuma
f6eb83c91c stage2: sparc64: Implement airArrayToSlice 2022-06-06 21:17:09 +07:00
BratishkaErik
1bdc2b777b tools: fix update-linux-headers.zig and process_headers.zig
Signed-off-by: BratishkaErik <bratishkaerik@getgoogleoff.me>
2022-06-06 15:53:53 +02:00
Koakuma
f87dd285bb stage2: sparc64: binOp/mul: Use template from add 2022-06-06 20:34:53 +07:00
Koakuma
31f24dbc55 stage2: sparc64: Implement airWrapErrUnionErr 2022-06-06 20:34:53 +07:00
Koakuma
c00d493a00 stage2: sparc64: Add some notes about stack space allocation 2022-06-06 20:34:53 +07:00
Koakuma
5d61f32887 stage2: sparc64: Implement airSlice 2022-06-06 20:34:53 +07:00
Koakuma
8b70abfcc6 stage2: sparc64: Fix & optimize 64-bit truncRegister 2022-06-06 20:34:53 +07:00
Koakuma
4d50e52c37 stage2: sparc64: Implement SPARCv9 xor, xnor, & not 2022-06-06 20:34:53 +07:00
Koakuma
97f9bf7e90 stage2: sparc64: Add BPr relocation to performReloc 2022-06-06 20:34:53 +07:00
Koakuma
23150de9c4 stage2: sparc64: Implement airNot 2022-06-06 20:34:53 +07:00
Koakuma
9ad74b6087 stage2: sparc64: Implement SPARCv9 addcc and movcc 2022-06-06 20:34:53 +07:00
Koakuma
97c43afefe stage2: sparc64: Spill CCR before doing calls 2022-06-06 20:34:53 +07:00
Koakuma
2dfe307d60 stage2: sparc64: Some bookkeeping fixes 2022-06-06 20:34:53 +07:00
Koakuma
89b4195c69 stage2: sparc64: Account for delay slot in airBlock 2022-06-06 20:34:53 +07:00
Koakuma
3220e0b61c stage2: sparc64: Proper handling of compare flags 2022-06-06 20:34:53 +07:00
Koakuma
9db81fee5d stage2: sparc64: Implement airStructFieldVal 2022-06-06 20:34:53 +07:00
Koakuma
3d662cfaf4 stage2: sparc64: Implement airAddSubOverflow 2022-06-06 20:34:53 +07:00
Koakuma
093332c02e stage2: sparc64: Implement condition code spilling 2022-06-06 20:34:53 +07:00
Koakuma
38aa431e03 stage2: sparc64: Fix CompareOperator <-> ICondition mapping 2022-06-06 20:34:52 +07:00
joachimschmidt557
a34f3ff04a stage2 ARM: implement try AIR instruction 2022-06-06 14:22:40 +02:00
Gregory Anders
135b91aecd Treat blocks with "return" as "noreturn"
Block statements that end with "break" should not be considered
"noreturn" for the enclosing scope, but other "noreturn" instructions
(return, panic, compile error, etc.) should be. This differentiation
necessitates handling "break" differently from the other "noreturn"
instructions when inside a block statement.
2022-06-06 13:13:52 +03:00
Jakub Konka
5dade176d8 sema: set new Decl alignment to 0 for generic call instantiation 2022-06-05 17:31:22 +02:00
Jakub Konka
95966f6fd7 elf+macho: use explicit alignment on decl is specified 2022-06-05 16:46:50 +02:00
Jakub Konka
ff00bbf4de x64: lower try and try_ptr 2022-06-05 10:37:08 +02:00
Andrew Kelley
6da420419d Sema: avoid emitting unused is_non_err AIR instruction 2022-06-05 10:37:08 +02:00
Andrew Kelley
d2f31d315e C backend: implement try instruction 2022-06-05 10:37:08 +02:00
Luuk de Gram
779770cff5 wasm: Implement try instruction 2022-06-05 10:37:08 +02:00
Andrew Kelley
f4ac37f55d Sema: extract out zirTryPtr from zirTry
This function took is_ptr: bool and then branched on it three times.
Now, instead, each implementation does no branching and the logic is
easier to follow, both for maintainers and compilers.

I also fixed a bug with TryPtr not ensuring enough capacity in the extra
array.
2022-06-05 10:37:08 +02:00
Andrew Kelley
6d3586e0ed explicit "_ptr" variants of ZIR try instruction
* Introduce "_ptr" variants of ZIR try instruction to disallow constructs
   such as `try` on a pointer value instead of an error union value.
 * Disable the "_inline" variants of the ZIR try instruction for now because
   we are out of ZIR tags. I will free up some space in an independent commit.
 * AstGen: fix tryExpr calling rvalue() on ResultLoc.ref
2022-06-05 10:37:08 +02:00
Andrew Kelley
00720c52f6 Sema: implement try_inline 2022-06-05 10:37:08 +02:00
Andrew Kelley
ef885a78d6 stage2: implement the new "try" ZIR/AIR instruction
Implements semantic analysis for the new try/try_inline ZIR
instruction. Adds the new try/try_ptr AIR instructions and implements
them for the LLVM backend.

Fixes not calling rvalue() for tryExpr in AstGen.

This is part of an effort to implement #11772.
2022-06-05 10:37:08 +02:00
Andrew Kelley
0224ad19b8 AstGen: introduce try instruction
This introduces two ZIR instructions:
 * `try`
 * `try_inline`

This is part of an effort to implement #11772.
2022-06-05 10:37:08 +02:00
Jakub Konka
33826a6a2e x64: disable misbehaving behavior tests 2022-06-05 10:36:54 +02:00
Jakub Konka
1b5dd4e148 Merge pull request #11790 from joachimschmidt557/stage2-arm
stage2 ARM: implement basic switch expressions
2022-06-05 09:10:12 +02:00
Andrew Kelley
43db697b46 Merge pull request #11789 from Vexu/stage2
Stage2 fixes towards `zig2 build test-std` working
2022-06-04 16:29:26 -04:00
joachimschmidt557
d5ee451177 stage2 ARM: introduce support for basic switch expressions 2022-06-04 19:58:34 +02:00
Veikka Tuominen
50a6b0f3ac Sema: fix function type callconv inference 2022-06-04 11:33:18 +03:00
Veikka Tuominen
6d44c0a16c std: update tests to stage2 semantics 2022-06-03 20:21:20 +03:00
Veikka Tuominen
1a7b4ddeae std: disable tests that crash stage2 2022-06-03 20:21:20 +03:00
Veikka Tuominen
2b93546b39 Sema: fix initialization of array with comptime only elem type 2022-06-03 20:21:20 +03:00
Veikka Tuominen
4e1aa5d543 Sema: handle the_only_possible_value in beginComptimePtrMutation 2022-06-03 15:25:53 +03:00
Veikka Tuominen
019537cb2a Sema: @sizeOf function should give an error 2022-06-03 15:24:58 +03:00
Veikka Tuominen
8f45e81c84 stage2: ignore asm inputs named _
This is a hacky solution but the entire asm syntax is supposed to be
reworked anyways.
2022-06-03 15:10:37 +03:00
Veikka Tuominen
5c65b086d6 Value: implement {read,write}Value for more types 2022-06-03 14:29:24 +03:00
Veikka Tuominen
3db4513b33 Sema: fix type of alloc 2022-06-03 14:28:56 +03:00
Veikka Tuominen
1258b5f7d6 Type: implement elemType2 for anyframe 2022-06-03 14:28:10 +03:00
Veikka Tuominen
9aae4d57cb compiler_rt: fix infinite loop 2022-06-03 14:27:45 +03:00
joachimschmidt557
4fdacca512 stage2 ARM: rework cmp in preparation for switch 2022-06-02 20:19:18 +02:00
Jakub Konka
e498fb1550 tapi: sync with upstream
gitrev kubkon/zig-yaml 8cf8dc3bb901fac8189f441392fc0989ad14cf71

Calculate line and col info indexed by token index. We can then
re-use this info to track current column number (aka indentation
level) of each "key:value" pair (map) or "- element" (list).
This significantly cleans up the code, and leads naturally to
handling of unindented lists in tbd files.
2022-06-02 10:41:13 +02:00
Andrew Kelley
288e89b606 Sema: fix compiler crash with comptime arithmetic involving @ptrToInt 2022-06-01 16:45:28 -07:00
Andrew Kelley
a4cdb49a58 Merge pull request #11763 from Vexu/stage2-alloc-const
Stage2: detect when initializer of const variable is comptime known
2022-06-01 18:59:13 -04:00
Andrew Kelley
b82cccc9e9 Sema: fix alignment of element ptr result type 2022-06-01 15:43:21 -07:00
Andrew Kelley
b095aa6986 CI: skip single-threaded tests on Drone
sure would be nice if they would just give us another hour of CI run time.
2022-06-01 14:05:58 -07:00
Andrew Kelley
de14fba247 LLVM: convert two ArrayLists into a MultiArrayList 2022-06-01 11:53:47 -07:00
Andrew Kelley
69323fc143 CI: skip non native ReleaseFast and ReleaseSafe tests on drone
Because we're hitting the 2 hour time limit.
2022-06-01 11:19:19 -07:00
Veikka Tuominen
94624893d8 disable failing test 2022-06-01 13:06:31 +03:00
Veikka Tuominen
9431100736 Sema: apply previous changes to validateUnionInit 2022-06-01 13:01:39 +03:00
Andrew Kelley
cbb806da6e stage2: -fbuild-id causes default linker to be LLD
until zig's self-hosted linker gains this functionality.
2022-05-31 22:56:39 -07:00
Andrew Kelley
8c0f4e6f54 LLVM: add target-cpu and target-features fn attributes 2022-05-31 22:13:24 -07:00
Andrew Kelley
2f9533f639 LLVM: pass slices as ptr/len combo
LLVM optimization passes handle this better, and it allows Zig to
specify pointer parameter attributes such as readonly, nonnull, noalias,
and alignment.

closes #561
2022-05-31 18:25:57 -07:00
Andrew Kelley
356a865b87 stage2: introduce support for noalias
Not implemented yet is enhancements to coerceInMemory to account for
noalias parameters.

Related to #11498.
2022-05-31 17:38:42 -07:00
Andrew Kelley
602af1b88f Merge pull request #11765 from ziglang/llvm-param-attrs
LLVM: add readonly, nonnull, align attributes to pointer params
2022-05-31 20:25:13 -04:00
Veikka Tuominen
3c4e7abfbf Sema: handle dbg_smtts when deleting runtime instructions in validateStructInit 2022-06-01 02:18:45 +03:00
Veikka Tuominen
a73895339a Sema: handle bitcasts produced by coerce_result_ptr in validate{Array,Struct}Init 2022-06-01 02:10:18 +03:00
Andrew Kelley
ec919c3c9b LLVM: integrate param attrs with iterateParamTypes
This moves some logic from resolveLlvmFunction to updateFunc and takes
advantage of the iteration we already do that takes into account C ABI
lowering, making LLVM parameter attributes accurate for C ABI functions
as well as our own unspecified calling convention.

Related to #11498.
2022-05-31 15:32:15 -07:00
Veikka Tuominen
f2626a3d8e Sema: validate{Array,Struct}Init shortcut only valid if base ptr is comptime known 2022-06-01 01:24:11 +03:00
Veikka Tuominen
e49fd39463 Sema: detect comptime values in zirMakePtrConst 2022-06-01 01:23:52 +03:00
Andrew Kelley
43311e19f4 LLVM: add readonly, nonnull, align attributes to pointer params 2022-05-31 15:16:38 -07:00
Andrew Kelley
6d691d3540 build: include a build-id note only if explicitly requested 2022-05-31 13:51:59 -07:00
Andrew Kelley
59219e7e91 stage2: add support for -fbuild-id,-fno-build-id
closes #3047
2022-05-31 13:36:33 -07:00
Andrew Kelley
d09d61be97 Merge pull request #11762 from Vexu/stage2
Stage2 fixes
2022-05-31 15:19:25 -04:00
Andrew Kelley
282437c753 stage2: fix hash/eql on function types
to account for generic callconv and generic alignment.
2022-05-31 12:17:48 -07:00
Andrew Kelley
d410693dad LLVM: elide some loads when lowering
Generally, the load instruction may need to make a copy of an
isByRef=true value, such as in the case of the following code:

```zig
pub fn swap(comptime T: type, a: *T, b: *T) void {
    const tmp = a.*;
    a.* = b.*;
    b.* = tmp;
}
```

However, it only needs to do so if there are any instructions which can
possibly write to memory. When calling functions with isByRef=true
parameters, the AIR code that is generated looks like loads followed
directly by call.

This allows for a peephole optimization when lowering loads: if the load
instruction operates on an isByRef=true type and dies before any side effects
occur, then we can safely lower the load as a no-op that returns its
operand.

This is one out of three changes I intend to make to address #11498.
However I will put these changes in separate branches and merge them
separately so that we can have three independent points on the perf
charts.
2022-05-31 14:17:54 -04:00
Frank Denis
26aea8cfa1 crypto: add support for the NIST P-384 curve (#11735)
After P-256, here comes P-384, also known as secp384r1.

Like P-256, it is required for TLS, and is the current NIST recommendation for key exchange and signatures, for better or for worse.

Like P-256, all the finite field arithmetic has been computed and verified to be correct by fiat-crypto.
2022-05-31 17:29:38 +02:00
Veikka Tuominen
56608cbb3d Sema: do not add calls to returnError for comptime known non-error values 2022-05-31 17:14:49 +03:00
Veikka Tuominen
36df79cd37 stage2: ignore generic return type when hashing function type
Generic parameter types are already ignored.
2022-05-31 16:43:58 +03:00
Veikka Tuominen
febc7d3cd6 Sema: take dbg_stmt into account in zirResolveInferredAlloc 2022-05-31 16:22:00 +03:00
Andrew Kelley
83beed09e1 LLVM: omit memset of 0xaa bytes in unsafe optimization modes
This is one out of three changes I intend to make to address #11498.
However I will put these changes in separate branches and merge them
separately so that we can have three independent points on the perf
charts.
2022-05-31 00:39:14 -07:00
Andrew Kelley
c3ef4ac15f Merge pull request #11752 from ziglang/zir-fancy-fns
stage2: add missing data to ZIR encoding of functions
2022-05-30 21:18:10 -04:00
Andrew Kelley
c84f5a5f91 Merge pull request #11749 from Vexu/stage2
Stage2: improve AstGen for array init expressions
2022-05-30 17:35:18 -04:00
Andrew Kelley
bd89a73d52 Sema: implement functions generic across callconv() or align() 2022-05-30 14:16:28 -07:00
Andrew Kelley
7e98b047dd AstGen: simplify function return type expressions
This check for primitives is already handled by the generic logic that
checks if the body ends up being empty. I kept this commit in the git
history in case we ever want that nodePrimitive function again in the
future, it might be useful.
2022-05-30 12:03:53 -07:00
Andrew Kelley
9da3a058d8 stage2: add missing data to ZIR encoding of functions
The main purpose of this commit is to prepare to implement support for
callconv(), align(), linksection(), and addrspace() annotations on
generic functions where the provided expression depends on comptime
parameters (making the function generic).

It's a rather involved change, so this commit only makes the necessary
changes to AstGen without regressing any behavior, and a follow-up
commit can finish the task by making the enhancements to Sema.

By my quick estimation, the new encoding for functions is a negligible
improvement - along the lines of 0.005% fewer total ZIR bytes on
average. Still, it's nice that this commit, while adding more
data into ZIR, actually ends up reducing the storage size thanks to a
slightly more sophisticated encoding.

Zir.Inst.ExtendedFunc is renamed to Zir.Inst.FuncFancy to eliminate
confusion about it being an extended instruction (it used to be but is
no longer). The encoding for this instruction is completely reworked.

The encoding for Zir.Inst.Func is also changed slightly - when the
return type body length is 1, then only a Zir.Inst.Ref is provided; not
a full body.

linksection() and addrspace() are now communicated via func_fancy ZIR
instruction rather than as part of the corresponding decl. This allows
their expressions to observe comptime parameters.
2022-05-30 12:03:53 -07:00
Veikka Tuominen
f846dc420f Merge pull request #10474 from TwoClocks/master
translate-c: fix for #10461. Check child records for opaque types
2022-05-30 16:01:05 +03:00
Veikka Tuominen
0e8307789a AstGen: add tuple aware elem_type_index 2022-05-29 13:19:03 +03:00
Veikka Tuominen
c7b778992e AstGen: improve generated Zir for array init exprs 2022-05-29 13:19:03 +03:00
Veikka Tuominen
0274e2f1fd translate-c: check variable types being demoted to opaque 2022-05-29 12:07:29 +03:00
TwoClocks
36b4658752 translate-c: check record fields for opaque demotions 2022-05-29 12:06:37 +03:00
Veikka Tuominen
ee651c3cd3 Revert "reserve correct space for bitfields"
This reverts commit 22cb693889.
2022-05-29 12:04:50 +03:00
TwoClocks
22cb693889 reserve correct space for bitfields 2022-05-28 17:31:26 +03:00
Ali Chraghi
0e6285c8fc math: make cast return optional instead of an error 2022-05-27 16:43:33 -04:00
joachimschmidt557
ddd5b57045 stage2 AArch64: complete genTypedValue 2022-05-27 16:43:11 -04:00
Andrew Kelley
4994ac18e4 Merge pull request #11733 from Vexu/stage2
more misc stage2 fixes
2022-05-27 16:20:49 -04:00
Veikka Tuominen
989c0f55e8 stage2: add test for fixed issue 2022-05-27 10:29:24 +03:00
Veikka Tuominen
8bf3e1f8d0 AstGen: preserve inferred ptr result loc for breaks 2022-05-27 10:29:24 +03:00
Veikka Tuominen
e08cdad53b Sema: add error for runtime indexing comptime array 2022-05-27 10:29:15 +03:00
r00ster
b3672e0738 Fix grammatical error
Fixes #11675
2022-05-27 01:00:15 -04:00
Andrew Kelley
83a2c41cd5 fix alignment behavior test case
As demonstrated by this new test case, stage1's functionality is
incorrect since it does not handle slicing from len..len correctly.

stage2 already has the correct behavior here.
2022-05-26 21:58:19 -07:00
Andrew Kelley
4751356d7f clean up some behavior tests
* improve names
 * properly categorize a couple of bug cases
 * mark one as already passing
2022-05-26 21:58:19 -07:00
Andrew Kelley
f2e8c79763 std.Progress.log: adjust API
Now it will fall back to std.debug.print if there is no tty.
2022-05-26 21:58:19 -07:00
Andreas Reischuck
5a8b6149fb add more corner case tests to float_parse (#11727)
also drop some unused constants

Co-authored-by: Andrew Kelley <andrew@ziglang.org>
2022-05-26 22:05:53 -04:00
Andrew Kelley
41162ed646 stage0: fix -fsingle-threaded CLI arg parsing
closes #11730
2022-05-26 18:59:55 -07:00
Yuto Oguchi
43373e61fa std.c: Fix incorrect dirent structure (#11602)
d_name is a null-terminated string, but it is not guaranteed that the
last byte of the array is null.
2022-05-26 20:15:51 -04:00
Andrew Kelley
e0a0df5a8a Merge pull request #11598 from aiotter/master
Add functions from `dirent.h` to std.c
2022-05-26 20:11:54 -04:00
Jonathan Marler
ee1a95b555 fix semantic error with std.os.linux.all_mask
all_mask is a value of type sigset_t, which is defined as an array type
[N]u32.  However, all_mask references sigset_t.len, but, the array type
does not have a len field.  Fix is to use @typeInfo(sigset_t).Array.len
instead.
2022-05-26 19:50:10 -04:00
Hanna
4e918873e7 Rename std.build.Pkg.path to std.build.Pkg.source (#11557) 2022-05-26 19:32:28 -04:00
Andrew Kelley
67d5bfefba std.testing: remove tight coupling with executing zig as child process
This tight coupling causes problems for various targets, requires
hacky "get args" functionality, and bungles relative file system paths,
making invalid assumptions about the zig-cache directory.

In short, these are not unit tests; these should be standalone tests
instead.

Reverts e5d4a694ea
Reverts d976456ef6
Reverts dbbda0f41a
Closes #11542
2022-05-26 16:22:47 -07:00
Andrew Kelley
ba426f0a54 Merge pull request #10197 from vrischmann/io_uring-provide_buffers
io_uring: implement automatic buffer selection
2022-05-26 18:39:17 -04:00
Jakub Konka
326b2aa27b Merge pull request #11729 from ziglang/fix-test-harness
test: correctly track identical error msgs in handled errors list
2022-05-26 21:00:40 +02:00
joachimschmidt557
7deae07101 std.PriorityQueue: fix missing siftUp in remove
When the replacement node is smaller than its parent, we need to sift
up instead of sifting down.
2022-05-26 14:50:24 -04:00
Jakub Konka
5ce9c878cf apply Vexu's suggestion to use failing_allocator for now 2022-05-26 16:55:31 +02:00
Jakub Konka
d1e4600675 test: correctly track identical error msgs in handled errors list
Prior to this change, for an example compiler error test case with
multiple identical errors messages such as

```
:1:2: error: foo
:1:2: error: foo
```

the test harness would never increment the error index thus only
marking the very first error message as handled yielding a false
positive.

Additionally, while here, regress `dereference_anyopaque` test case
as not passing on `wasm32-wasi` target.
2022-05-26 16:23:56 +02:00
Frank Denis
b08d32ceb5 crypto/25519: add scalar.random(), use CompressedScalar type
Add the ability to generate a random, canonical curve25519 scalar,
like we do for p256.

Also leverage the existing CompressedScalar type to represent these
scalars.
2022-05-26 13:30:03 +02:00
Jakub Konka
01607b54fc Merge pull request #11722 from ziglang/stage2-behavior
stage2: enhance array concatenation and multiplication
2022-05-26 13:28:30 +02:00
Veikka Tuominen
92c4e4f2c2 Sema: zirArrayType does need source location 2022-05-26 13:26:55 +03:00
Jakub Konka
90f12a9186 Merge pull request #11723 from koachan/sparc64-codegen
stage2: sparc64: Small refactorings and stack pointer accounting fixes
2022-05-26 12:06:11 +02:00
Jakub Konka
0e0b00fd48 regalloc: use StaticBitSet internally 2022-05-26 12:05:51 +02:00
Koakuma
c5b99267c0 stage2: sparc64: Remove saved_regs_stack_space calculation
SPARC does not have an explicit notion of saving/restoring registers.
The usual windowing mechanism (save/restore/return) already takes care of that
for us.
2022-05-26 13:48:39 +07:00
Koakuma
3923722cc6 stage2: sparc64: Account for stack bias & reserved area in genSetReg
genSetReg with ptr_stack_offset should add the bias and reserved area
before emitting the instruction.
2022-05-26 13:48:29 +07:00
Koakuma
5fa971610e stage2: sparc64: Change binOpImmediate immediates to u12
Sync with the check in binOp.
2022-05-26 13:09:56 +07:00
Koakuma
0310d88d7e stage2: sparc64: Add cmp and mov synthetic instructions 2022-05-26 13:08:39 +07:00
Andrew Kelley
83f69af971 stage2: implement runtime array multiplication
Additionally:

 * Sema: fix array cat/mul not setting the sentinel value
   - This required an LLVM backend enhancement to the handling of the
     AIR instruction aggregate_init that likely needs to be
     propagated to the other backends.
 * Sema: report integer overflow of array concatenation in a proper
   compile error instead of crashing.
 * Sema: fix not using proper pointer address space for array cat/mul
2022-05-25 22:33:48 -07:00
Andrew Kelley
b82081e709 Sema: implement array concatenation with runtime operands 2022-05-25 22:33:48 -07:00
Andrew Kelley
ab88165326 Sema: generic function instantiations inherit branch quota 2022-05-25 23:32:52 -04:00
Andrew Kelley
1dd7109476 Merge pull request #11716 from Vexu/stage2
Stage2 misc fixes
2022-05-25 22:30:08 -04:00
Jakub Konka
97816e3cb8 aarch64: check lo/cc flag for unsigned sub_with_overflow
With this change, we are now correctly lowering `sub_with_overflow`
for signed and unsigned integers of register-sized integers (32-
or 64-bit precisely). We also match LLVM's behavior and so, the
condition flags we now set are:

* unsigned:
  - `add_with_overflow`: `hs`/`cs` (carry set)
  - `sub_with_overflow`: `lo`/`cc` (carry clear)
* signed:
  - `add_with_overflow`/`sub_with_overflow`: `vs` (overflow)
2022-05-25 23:43:45 +02:00
Veikka Tuominen
f409d925ad Sema: check for generic poison in resolveInst 2022-05-25 23:11:13 +03:00
Jakub Konka
39ebfedd2b Merge pull request #11715 from ziglang/stage2-x64-cond-codes 2022-05-25 20:33:43 +02:00
Helio Machado
e0be22b6c0 std.crypto: cosmetic improvement to AES multiplication algorithm (#11616)
std.crypto: cosmetic improvement to AES multiplication algorithm (#11616)
2022-05-25 19:23:49 +02:00
Veikka Tuominen
eba66f4a58 Sema: handle block.is_typeof in more places 2022-05-25 19:57:44 +03:00
Veikka Tuominen
d214b6bdf0 stage2: packed struct fields do not have a byte offset 2022-05-25 19:57:38 +03:00
Jakub Konka
7000395a7d x64: use new condition codes enum for register with overflow mcv 2022-05-25 17:18:43 +02:00
Jakub Konka
5fb7070642 x64: move from compare_flags_* mcv to eflags with condition codes enum 2022-05-25 17:06:47 +02:00
Veikka Tuominen
b0e8bf15f5 Sema: add error for dereferencing comptime value at runtime 2022-05-25 17:39:55 +03:00
Vincent Rischmann
3c58d3e281 io_uring: replace the readv method with a read on a new ReadBuffer type
readv() is essentially identical to read() except for the buffer type,
this simplifies the API for the caller at the cost of not clearly mapping to the liburing C API.
2022-05-25 13:53:09 +02:00
Vincent Rischmann
acb8af468f io_uring: add tests for automatic buffer selection 2022-05-25 13:53:09 +02:00
Vincent Rischmann
d8798ef0cd io_uring: use the socket test harness 2022-05-25 13:53:09 +02:00
Vincent Rischmann
456716b30d io_uring: add a test harness for server/client TCP socket tests 2022-05-25 13:53:09 +02:00
Vincent Rischmann
270a5039d4 io_uring: change recv() to use a RecvBuffer instead
RecvBuffer is equivalent to ReadBuffer but tailored for recv only.
2022-05-25 13:53:09 +02:00
Vincent Rischmann
52dd468cc3 io_uring: change read() to use a ReadBuffer instead
Reads can be done in two ways with io_uring:
* using a simple buffer
* using a automatic buffer selection which requires the user to have
provided a number of buffers before

ReadBuffer let's the caller choose where the data should be read.
2022-05-25 13:53:09 +02:00
Vincent Rischmann
7b3e5ce0b3 io_uring: add provide_buffers and remove_buffers
These functions are needed to implement automatic buffer selection.

This maps to the IORING_OP_PROVIDE_BUFFERS and IORING_OP_PROVIDE_BUFFERS ops.
2022-05-25 13:53:09 +02:00
Andrew Kelley
71e2a56e3e mark some more behavior tests as passing 2022-05-25 00:12:56 -07:00
Andrew Kelley
8373520785 Merge pull request #11699 from ziglang/empty-error-sets
stage2: fixes for error union semantics
2022-05-25 03:12:34 -04:00
Francesco Alemanno
a0775fdaa1 Add std.rand.RomuTrio
Co-authored-by: ominitay <37453713+ominitay@users.noreply.github.com>
2022-05-24 22:48:51 -04:00
Andrew Kelley
60af42705d mark two behavior tests as passing 2022-05-24 18:21:34 -07:00
Andrew Kelley
a4ff94804c Sema: additional check for one-possible-value types in analyzeLoad
This is needed because pointers to zero-bit types are not necessarily
comptime known, but when doing a load, only the element type having one
possible value is relevant.
2022-05-24 18:20:03 -07:00
Andrew Kelley
1f16b07d6f stage2: treat error{}!void as a zero-bit type 2022-05-24 17:53:04 -07:00
Andrew Kelley
c711c788f0 stage2: fixes for error unions, optionals, errors
* `?E` where E is an error set with only one field now lowers the same
   as `bool`.
 * Fix implementation of errUnionErrOffset and errUnionPayloadOffset to
   properly compute the offset of each field. Also name them the same
   as the corresponding LLVM functions and have the same function
   signature, to avoid confusion. This fixes a bug where wasm was
   passing the error union type instead of the payload type.
 * Fix C backend handling of optionals with zero-bit payload types.
 * C backend: separate out airOptionalPayload and airOptionalPayloadPtr
   which reduces branching and cleans up control flow.
 * Make Type.isNoReturn return true for error sets with no fields.
 * Make `?error{}` have only one possible value (null).
2022-05-24 15:34:52 -07:00
joachimschmidt557
c847a462ae stage2 ARM: update to new union layout 2022-05-24 15:34:52 -07:00
Jakub Konka
26376c9fda wasm: use errUnionPayloadOffset and errUnionErrOffset from codegen.zig 2022-05-24 15:34:52 -07:00
Jakub Konka
8c49420928 aarch64: update for new error union layout 2022-05-24 15:34:52 -07:00
Jakub Konka
c043d57cab x64,arm,aarch64: omit unsupported tests for now 2022-05-24 15:34:52 -07:00
Jakub Konka
41f517e5f5 x64: update for new error union layout 2022-05-24 15:34:52 -07:00
Jakub Konka
b42100c70f dwarf: update abbrev info generation for new error union layout 2022-05-24 15:34:52 -07:00
Andrew Kelley
cd59b8277d LLVM: rename two functions
llvmType -> lowerType
genTypedValue -> lowerValue
2022-05-24 15:34:52 -07:00
Andrew Kelley
7db39384f7 move bound function behavior test to compile error test 2022-05-24 15:34:52 -07:00
Andrew Kelley
1bf7a6dff5 enable passing behavior test
This was disabled for macOS but I just tested it on my M1 and it works
fine.
2022-05-24 15:34:52 -07:00
Andrew Kelley
02e9d9b43b stage2: make ?anyerror represented the same as anyerror
I was able to get the backend implementation working on LLVM and the C
backend, but I'm going to ask for some help on the other backends.
2022-05-24 15:34:52 -07:00
Andrew Kelley
c97c7f9e3b C backend: update to new error union semantics 2022-05-24 15:34:52 -07:00
Luuk de Gram
3a059ebe4c wasm: Fixes for error union semantics 2022-05-24 15:34:52 -07:00
Luuk de Gram
c90a97f9be codegen: Order error union fields per alignment
Based on the size of the payload the native backends will lower
the error union with its fields (errorset & payload) in the correct order.
e.g. ErrorA!u8 will first lower the error set's value and then the payload.
In the event of ErrorA!u32 will lower the payload first.
2022-05-24 15:34:52 -07:00
Andrew Kelley
3264abe3d8 stage2: fixes for error union semantics
* Sema: avoid unnecessary safety checks when an error set is empty.
 * Sema: make zirErrorToInt handle comptime errors that are represented
   as integers.
 * Sema: make empty error sets properly integrate with
   typeHasOnePossibleValue.
 * Type: correct the ABI alignment and size of error unions which have
   both zero-bit error set and zero-bit payload. The previous code did
   not account for the fact that we still need to store a bit for
   whether there is an error.
 * LLVM: lower error unions possibly with the payload first or with the
   error code first, depending on alignment. Previously it always put
   the error code first and used a padding array.
 * LLVM: lower functions which have an empty error set as the return
   type the same as anyerror, so that they can be used where
   fn()anyerror function pointers are expected. In such functions, Zig
   will lower ret to returning zero instead of void.

As a result, one more behavior test is passing.
2022-05-24 15:34:52 -07:00
Andrew Kelley
60f0acd9b9 Merge pull request #11706 from ziglang/string-literal-interning
stage2: string literal interning
2022-05-24 15:32:12 -04:00
Andrew Kelley
953e2778d4 clean up a compile error test case
These should be build-obj, not build-exe, where possible.
2022-05-24 01:20:18 -07:00
Andrew Kelley
818fbd9c56 stage2: string literal interning
This is a temporary addition to stage2 in order to match stage1 behavior,
however the end-game once the lang spec is settled will be to use a global
InternPool for comptime memoized objects, making this behavior consistent
across all types, not only string literals. Or, we might decide to not
guarantee string literals to have equal comptime pointers, in which case
this commit can be reverted.
2022-05-24 01:01:24 -07:00
Dominic Tarr
8171972cbb document bufPrint, and format now uses writer not output 2022-05-23 11:58:13 +03:00
Thomas Cheng
64de32b341 Fix segfault in error note 2022-05-23 11:57:30 +03:00
Andrew Kelley
b64a1d5abb Merge pull request #11684 from ziglang/fix-10318
Set macOS/iPhoneOS/tvOS/watchOS ABI to none (unspecified) by default
2022-05-22 19:29:42 -04:00
Jakub Konka
cbefd354a6 Bump support macOS versions; clean up allocs in llvm.targetTriple 2022-05-22 22:31:41 +02:00
joachimschmidt557
b56b4428a3 stage2 ARM: fix recursive fibonacci
Some handling of register_c_flag/register_v_flag was incorrect.
2022-05-22 21:02:32 +02:00
Jakub Konka
e306d04473 Return an error when macOS ABI is not {none, simulator, macabi} 2022-05-22 17:45:07 +02:00
Jakub Konka
f8a1a2c4a1 stage2: append min version to target triple when lowering to LLVM 2022-05-22 17:45:07 +02:00
Jakub Konka
5b813f1a2a Set macOS/iPhoneOS/tvOS/watchOS ABI to none (unspecified) by default
Prior to this change we would assume the ABI for Apple targets to
be GNU which could result in subtle errors in LLVM emitting calls
to non-existent system libc provided functions such as `_sincosf`
which is a GNU extension and as such is not provided by macOS for example.
This would result in linker errors where the linker would not be
able to find the said symbol in `libSystem.tbd`.

With this change, we now correctly identify macOS (and other Apple
platforms) as having ABI `unknown` which translates to unspecified
in LLVM under-the-hood:

```
// main.ll
target triple = "aarch64-unknown-macos-unknown"
```

Note however that we never suffix the target OS with target version
such as `macos11` or `macos12` which means we fail to instruct LLVM
of potential optimisations provided by the OS such as the availability
of function `___sincosf_stret`. I suggest we investigate that in a
follow-up commit.
2022-05-22 17:45:02 +02:00
joachimschmidt557
9747303d16 stage2 ARM: Introduce MCValue.cpsr_flags
MCValue.cpsr_flags replaces
MCValue.compare_flags_{signed,unsigned}. This simplifies a lot of
stuff and enables an MCValue to represent only the overflow bits in
the CPU (previously, it was only possible to represent a register +
the overflow bits).
2022-05-21 22:15:04 +02:00
Andrew Kelley
1f5b0c1156 Merge pull request #11689 from ziglang/llvm-cc
LLVM: rework calling convention lowering
2022-05-21 15:22:52 -04:00
Andrew Kelley
f31f86a86a LLVM: fix calling convention lowering involving pointers
The previous commit caused LLVM module verification failure because we
attemped to bitcast LLVM pointers to i64 parameters. This is exactly
what we want, however it's technically not allowed according to LLVM's
type system. It could have been fixed trivially by using ptrtoint
instead of bitcast in the case of pointers, however, out of concern for
inttoptr being problematic for the optimizer, I put in special code to
detect when a given parameter can be treated as its actual type rather
than an integer type. This makes Zig's output LLVM IR closer to what
Clang outputs.
2022-05-21 00:09:30 -07:00
Jakub Konka
800edb03b5 regalloc: test allocating from multiple register claases 2022-05-21 08:40:47 +02:00
Andrew Kelley
1697a6f044 LLVM: rework calling convention lowering
The previous implementation of calling conventions was hacky and broken.
This commit reworks lowerFnParamTy into iterateParamTypes which returns
enum tags indicating how to handle each parameter. This is then used in
the three places that matter:
 * lowering a function type to llvm type
 * converting function parameters to the canonical type representation
   (with respect to isByRef).
 * converting canonical type representation to function arguments at
   callsites (again with respect to isByRef).

As a result, we are one step closer to the C ABI tests passing. Before
this commit, attempting to build them crashed the compiler. I isolated
the broken function and verified that it now is lowered correctly. I
will keep working on this one piece at a time until all the C ABI tests
pass, and then I will enable all of them in the CI.
2022-05-20 21:50:23 -07:00
Andrew Kelley
1a92264b3d Merge pull request #11671 from ziglang/stage2-behavior
stage2 bug fixes aimed towards more behavior tests passing
2022-05-20 18:35:19 -04:00
Jakub Konka
704d38ba49 Merge pull request #11681 from ziglang/x64-floats-tmp
x64: add prelim support for SSE/AVX-based floating-point ops
2022-05-20 17:19:28 +02:00
Jakub Konka
274654d73e x64: implement matching SSE instructions for generic cross-comp target 2022-05-20 13:52:52 +02:00
Andrew Kelley
fcd4efd8ec Sema: introduce laziness to @sizeOf
Motivation: the behavior test that is now passing.

The main change in this commit is introducing `Type.abiSizeAdvanced`,
`Value.Tag.lazy_size`, and adjusting `Sema.zirSizeOf` to take advantage
of these.

However, the bulk of lines changed in this commit ended up being moving
logic from value.zig and type.zig into Sema.zig. This logic had no
business being in Type/Value as it was only called from a Sema context,
and we need access to the Sema context for error reporting when a lazy
Value is resolved.

Also worth mentioning is that I bumped up the comptime `@floatToInt`
implementation from using f64 to f128.
2022-05-20 02:47:20 -07:00
Andrew Kelley
cd04b49041 stage2: fix @call when used in a comptime or nosuspend block
`@call` allows specifying the modifier explicitly, however it can still
appear in a context that overrides the modifier. This commit adds flags
to the BuiltinCall ZIR encoding. Since we have unused bits I also threw
in the ensure_result_used mechanism.

I also deleted a behavior test that was checking for bound function
behavior where I think stage2 behavior is correct and stage1 behavior
is incorrect.
2022-05-20 02:47:20 -07:00
Andrew Kelley
5626bb45d2 Sema: fix comptime @floatCast downcast 2022-05-20 02:47:20 -07:00
Ali Chraghi
58943fc627 wasm-linker: add -mwasm64 linker parameter for wasm64 target 2022-05-20 08:26:41 +02:00
Jakub Konka
0e43d007c0 regalloc: temporarily nerf back to raw ints until stage2 catches up 2022-05-20 07:36:15 +02:00
Andrew Kelley
dd6ac9a22a Merge pull request #11581 from erikarvstedt/fix-trailerflags
Fix `std.meta.TrailerFlags`
2022-05-19 21:15:16 -04:00
Andrew Kelley
85a9bd932f Merge pull request #11491 from poinwn/copysign-signbit
std.math: simplify signbit and copysign
2022-05-19 21:11:45 -04:00
1d532f12b5 [Elf] add -z nocopyreloc
Warnings about non-implemented `-z nocopyreloc` are common when
compiling go code (including Go's tests themselves). Let's just
make it stop complaining.
2022-05-19 20:21:07 -04:00
Jakub Konka
e95dfac03e regalloc: make register class bitmask non-optional 2022-05-19 23:54:48 +02:00
frmdstryr
7b63f98cd7 Add aliases to math builtins back into std.math (#11666) 2022-05-19 15:04:40 -04:00
Jakub Konka
f766b25f82 x64: load float from memory to register on PIE targets 2022-05-19 20:24:06 +02:00
Jakub Konka
5cbfd5819e x64: check for floating-point intrinsics in codegen 2022-05-19 19:39:34 +02:00
Jakub Konka
283f40e4e9 x64: use StaticBitSet instead of an integer internally in RegisterManager 2022-05-19 19:39:34 +02:00
Jakub Konka
080d138b9d x64: re-enable incremental tests 2022-05-19 19:39:34 +02:00
Jakub Konka
6d32498c55 x64: re-enable behavior tests 2022-05-19 19:39:34 +02:00
Jakub Konka
36b939e8db x64: handle basic f32 using AVX registers 2022-05-19 19:39:34 +02:00
Jakub Konka
020f99d893 x64: remove special-casing of AVX for br() 2022-05-19 19:39:34 +02:00
Jakub Konka
f346150820 x64: use register classes mask to select between gp and avx 2022-05-19 19:39:34 +02:00
Jakub Konka
549174f743 regalloc: allow for optional selector mask when allocating 2022-05-19 19:39:32 +02:00
Jakub Konka
9e5c8cb008 x64: merge general purpose with simd register into one bitset
This way, we do not have to tweak the `RegisterManager` to handle
multiple register types - we have one linear space instead. Additionally
we can use the bitset itself to separate the registers into overlapping
(the ones that are aliases of differing bitwidths) and nonoverlapping
classes (for example, AVX registers do not overlap general purpose
registers, thus they can be allocated simultaneously).

Another huge benefit of this simple approach is the fact that we can
still refer to *all* registers regardless of their class via enum
literals which makes the code so much more readable.

Finally, `RegisterLock` is universal across different register classes.
2022-05-19 19:37:29 +02:00
Jakub Konka
2aee230251 x64: add unordered cmp with EFLAGS 2022-05-19 19:37:28 +02:00
Jakub Konka
357561840d x64: load/store to/from AVX registers for f64 2022-05-19 19:36:35 +02:00
Jakub Konka
0835486249 x64: add vmovsd RM and MR lowerings (first draft) 2022-05-19 19:36:35 +02:00
Jakub Konka
019cc94ec7 x64: clean up populating VEX prefix 2022-05-19 19:36:35 +02:00
Jakub Konka
875a16030c x64: extend Emit to allow for AVX registers 2022-05-19 19:36:35 +02:00
Jakub Konka
70d809e0bb x64: add AVX registers and Vex prefix sub-encoder 2022-05-19 19:36:35 +02:00
Andrew Kelley
50a5ddecc5 Merge pull request #11635 from wsengir/stage2-errsetcast-safety
stage2: `@errSetCast` safety
2022-05-18 16:35:37 -04:00
Andrew Kelley
8660661af4 Merge pull request #11660 from ziglang/stage2-behavior
stage2: bug fixes towards more behavior tests passing
2022-05-18 15:29:19 -04:00
Andrew Kelley
9031cc54f2 Sema: implement @intCast for vectors 2022-05-17 23:50:38 -07:00
Andrew Kelley
691fba38d8 enable passing behavior test 2022-05-17 23:50:38 -07:00
Andrew Kelley
0fafc8cc44 std.Thread: insert a missing @alignCast
stage1 has a missing compile error for this situation.
2022-05-17 23:50:38 -07:00
Andrew Kelley
b6798c26ef stage2: fix pointer arithmetic result type
This makes it so the result of doing pointer arithmetic creates a new
pointer type that has adjusted alignment.
2022-05-17 23:50:38 -07:00
Andrew Kelley
95f5e17e49 behavior tests: correction of C pointer test
This test was also covering this behavior:

```zig
test "equality of pointers to comptime const" {
    const a: i32 = undefined;
    comptime assert(&a == &a);
}
```

This check belongs in its own behavior test which isolates this
behavior; not bundled along with a C pointer test.
2022-05-17 23:50:38 -07:00
Andrew Kelley
00f3d84f38 LLVM: support mixing extern and export with the same symbol name 2022-05-17 23:50:38 -07:00
Luuk de Gram
e252f92b99 wasm: enable 128bit integer behavior tests 2022-05-18 07:43:33 +02:00
Luuk de Gram
ed25ce77f5 wasm: Implement {add/sub}WithOverflow for 128bit 2022-05-18 07:43:33 +02:00
Luuk de Gram
fd081c74f1 wasm: Support not instruction for 128 bit integers
This also fixes the instruction for all other integer bitsizes,
as it was previously assuming to always be a bool.

128 bit substraction was also fixed as it contained a bug where it swapped
lhs with rhs.
2022-05-18 07:43:33 +02:00
Luuk de Gram
10fe24c043 wasm: Implement trunc/wrap for 128 bit integers
This also implments wrapping for arbitrary integer widths between 64 and 128.
`@truncate` was fixed where the wasm types between operand and result differentiated.
We solved this by first casting and then wrapping.
2022-05-18 07:43:33 +02:00
Luuk de Gram
ea073a6b76 wasm: Support 128bit integers for max/min/ctz/clz
`airMaxMin` was slightly updated to automatically support 128 bit integers,
by using the `cmp` function, instead of doing it manually. This makes the function
more maintanable as well.

`ctz` and `clz` now support 128 bit integers, while updating the previous implementation
also.
2022-05-18 07:43:33 +02:00
Luuk de Gram
502f5d8246 wasm: Fix C-ABI for 128 bit integers
We now pass the correct wasm type when the return type is a 128-bit integer.
When a function accepts a 128-bit integer, we now allocate space on the virtual stack
and store both arguments within that space as currently all following instructions
assume the 128 bit integer doesn't live in a local, but the stack.
2022-05-18 07:43:33 +02:00
Luuk de Gram
03a3ea2c15 wasm: 128 bit intcast and binary operations
Also fixes some bugs in 128-bit binary comparisons where we checked
if the lsb were equal, rather than msb.
2022-05-18 07:43:33 +02:00
Luuk de Gram
167d3089ea wasm: Support 128bit add/sub wrapping operands 2022-05-18 07:43:33 +02:00
Luuk de Gram
59d3714b8d wasm: 128bit integer cmp support
This implements support for all compare operations on a 128bit integer,
for both signed and unsigned integers.

The new implementation is almost more efficient as it requires no control-flow,
unlike the old implementation which used a block with breaks.
2022-05-18 07:43:33 +02:00
Luuk de Gram
c0ad0606df wasm: Support 128bit integer coercion
The Wasm backend now correctly supports coercing a smaller integer
into a 128bit integer. Regardless of signedness.
2022-05-18 07:43:33 +02:00
alice
951ab802a3 std.math: simpler error handling 2022-05-17 22:04:12 +01:00
alice
70b6b98e91 Simplify Copysign 2022-05-17 21:55:22 +01:00
alice
ceeec8d19f Simplify signbit 2022-05-17 21:41:57 +01:00
Vincenzo Palazzo
80f3c8d276 docs: add documentation on errdefer with caputure syntax
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2022-05-17 21:08:32 +02:00
Jan Philipp Hafer
cf744cf04f add suggestions by ifreund
also remove 2 redundant and outcommented tests
2022-05-17 18:56:06 +02:00
Jan Philipp Hafer
405f4286f7 std.unicode: add utf16 byte length and codepoints counting routines
* comptime and runtime tests are based on tests for counting utf8 code points
2022-05-17 18:54:29 +02:00
Vincenzo Palazzo
8328f5ed51 docs: add documentation about return stm in the defer method
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2022-05-17 18:34:28 +02:00
YeonJiKun
f3517a1aa6 zig test: Add proper detection for Windows console 2022-05-17 14:22:10 +03:00
Andrew Kelley
df74c45fa7 Merge pull request #11501 from Vexu/stage2-err-return-trace
stage2: error return traces
2022-05-17 03:27:03 -04:00
Jakub Konka
3fde14035b Merge pull request #11658 from koachan/sparc64-codegen
stage2: sparc64: Make basic test harness run
2022-05-17 09:20:02 +02:00
aiotter
552ef5f2e4 std.c: Implement dirent on std/c/linux.zig 2022-05-17 15:23:55 +09:00
Stephen Gregoratto
a4369918b1 Generate linux syscalls via. the linux source tree
Previously, updating the `SYS` enum for each architecture required
manually looking at the syscall tables and inserting any new additions.

This commit adds a tool, `generate_linux_syscalls.zig`, that automates
this process using the syscall tables in the Linux source tree. On
architectures without a table, it runs `zig cc` as a pre-processor to
extract the system-call numbers from the Linux headers.
2022-05-16 23:55:11 -04:00
Felix "xq" Queißner
6d27341b96 Fixes comptime 'error: cannot assign to constant' error in siphash. 2022-05-16 22:31:09 -04:00
Veikka Tuominen
0a7f3be42e Sema: improve index out of bounds panic message 2022-05-16 17:42:51 -07:00
Veikka Tuominen
ab4ec35b8b stage2: add runtime safety for unwrapping error 2022-05-16 17:42:51 -07:00
Veikka Tuominen
e369752430 Sema: do not call returnError when returning payload of error union 2022-05-16 17:42:51 -07:00
Veikka Tuominen
53a5aee3b3 stage2: enable error return tracing on llvm backend 2022-05-16 17:42:51 -07:00
Veikka Tuominen
66c3988e5e stage2: disable error return tracing on unsupported targets 2022-05-16 17:42:51 -07:00
Veikka Tuominen
eee8fffec7 stage2: implement error return traces 2022-05-16 17:42:51 -07:00
Andrew Kelley
5888446c03 Merge pull request #11316 from wsengir/stage2-overflow-safety
stage2: vectorized overflow arithmetic, integer overflow safety, left-shift overflow safety
2022-05-16 20:40:57 -04:00
Thiago Teodoro Pereira Silva
7a4758ed78 std.os: add timerfd_create, timerfd_settime and timerfd_gettime 2022-05-17 00:56:33 +02:00
leesongun
1de7b8d26c std.math.powi: use standard definition of underflow/overflow, implement u0, i0, i1 edge case (#11499) 2022-05-16 18:28:20 -04:00
Isaac Freund
1392c24166 std.os: Add memfd_create for FreeBSD
This is minorly breaking as e.g. std.os.linux.MFD_CLOEXEC is now
std.os.linux.MFD.CLOEXEC.
2022-05-16 17:43:44 -04:00
Andrew Kelley
f33b3fc3ea zig.h: add casts for overflow arithmetic operations
This avoids the following error:

```
error: incompatible pointer types passing 'int64_t *' (aka 'long long *') to parameter of type 'long *'
    overflow = __builtin_saddl_overflow(lhs, rhs, res);
                                                  ^~~
```

My previous understanding was that this error would not occur because
prior to this line we check that int64_t is equivalent to long, like
this:

```c
```

However, it appears that this is still a warning in C if int64_t is
primarily aliased to `long long`, even though `long` and `long long` are
the same thing.
2022-05-16 14:30:28 -07:00
Jakub Konka
a0de0adb8e arm: disable recursive fibonacci 2022-05-16 13:55:26 -07:00
Jakub Konka
7f96ca101a arm: sub_with_overflow should always track V flag 2022-05-16 13:55:26 -07:00
Jakub Konka
852c820841 aarch64: sub_with_overflow should always track V flag 2022-05-16 13:55:26 -07:00
Andrew Kelley
a84be7e988 zig.h: improve overflow shl
* zig_addo_u128: fix type-o
 * redo the shift-left overflow inline functions. no need to depend on
   compiler-rt.
2022-05-16 13:55:26 -07:00
Luuk de Gram
160aa4c11d wasm: Improve shl_with_overflow
This re-implements the shl_with_overflow operation from scratch,
making it a lot more robust and outputs the equal code to the LLVM backend.
2022-05-16 13:55:26 -07:00
Luuk de Gram
0a2d3d4155 wasm: Improve overflow add/sub for ints <= 64bits
The implementation for add_with_overflow and sub_with_overflow is now a lot
more robust and takes account for signed integers and arbitrary integer bitsizes.
The final output is equal to that of the LLVM backend.
2022-05-16 13:55:26 -07:00
Jakub Konka
b94d165b69 x64: fix capacity prealloc limit in lowerToMrEnc helper 2022-05-16 13:55:26 -07:00
Andrew Kelley
316bf4fce5 disable 5 failing stage2_wasm tests 2022-05-16 13:55:26 -07:00
Andrew Kelley
03ed0f0d28 C backend: implement overflow arithmetic
Most of the work here was additions to zig.h. The lowering code is
mainly responsible for calling the correct function name depending on
the operand type.

Some of the compiler-rt calls here are not implemented yet and are
non-standard symbols due to the C programming language not needing them.

After this commit, the behavior tests with -ofmt=c are passing again.
2022-05-16 13:55:26 -07:00
William Sengir
a5ea22d069 LLVM: correctly pad result tuple of airOverflow 2022-05-16 13:55:26 -07:00
William Sengir
bb3532e775 stage2: add more vector overflow tests 2022-05-16 13:55:26 -07:00
William Sengir
21be3d9166 stage2: add vectorized overflow arithmetic behavior tests 2022-05-16 13:55:26 -07:00
William Sengir
afc714d5e5 stage2: implement runtime safety checks for shl_exact 2022-05-16 13:55:26 -07:00
William Sengir
c2980f332e Sema: implement integer overflow safety for add, sub, mul 2022-05-16 13:55:26 -07:00
William Sengir
eb06c78a8a Sema: vectorize overflow arithmetic 2022-05-16 13:55:26 -07:00
William Sengir
86a928ce61 stage2: perform comptime vectorization of *_with_overflow in Value 2022-05-16 13:55:26 -07:00
William Sengir
e8117bab6f stage2: clean up creation of boolean Values 2022-05-16 13:55:26 -07:00
William Sengir
6b5c87957b stage2: handle vectors in Value.intFitsInType 2022-05-16 13:55:26 -07:00
William Sengir
ca1ab38d3a stage2: add global Type constant for u1 2022-05-16 13:55:26 -07:00
William Sengir
c2cb9b7cad stage2: vectorize shl_with_overflow in LLVM backend 2022-05-16 13:55:26 -07:00
William Sengir
c641fb8f05 stage2: fix {add,sub,mul}_with_overflow vectorization in LLVM backend 2022-05-16 13:55:26 -07:00
Koakuma
b618dbdf69 stage2: sparc64: Implement SPARCv9 mulx 2022-05-16 23:30:54 +07:00
Koakuma
7245aad689 stage2: sparc64: Implement airBinOp for addition 2022-05-16 23:30:54 +07:00
Koakuma
67a1fedf84 stage2: sparc64: Implement airUnwrapErrErr 2022-05-16 23:30:54 +07:00
Koakuma
77eef33c04 stage2: sparc64: Implement airStructFieldPtrIndex 2022-05-16 23:30:54 +07:00
Koakuma
26116211ec stage2: sparc64: Implement inline memcpy for genSetStack 2022-05-16 23:30:54 +07:00
Koakuma
7822426ff2 stage2: sparc64: Implement airSliceElemVal 2022-05-16 23:30:54 +07:00
Koakuma
ccf438e4de stage2: sparc64: Replace freezeRegs with RegisterLock 2022-05-16 23:30:54 +07:00
Koakuma
26e3d36d74 stage2: sparc64: Implement airSliceLen 2022-05-16 23:30:54 +07:00
Koakuma
8ea80fdf7a stage2: sparc64: Implement airLoop 2022-05-16 23:30:47 +07:00
Koakuma
e4a725c597 stage2: sparc64: Implement airBitCast 2022-05-16 23:17:11 +07:00
Koakuma
0c8ce9ed9d stage2: sparc64: Implement airCmp 2022-05-16 23:17:11 +07:00
Koakuma
ae2d6b7eea stage2: sparc64: Add BPr support for airCondBr 2022-05-16 23:17:11 +07:00
Koakuma
e057ff2496 stage2: sparc64: Implement SPARCv9 bpr 2022-05-16 23:17:11 +07:00
Koakuma
8f8853cd4f stage2: sparc64: Implement airLoad/airStore 2022-05-16 23:17:06 +07:00
Koakuma
0b54649cac stage2: sparc64: Implement error value generation 2022-05-16 22:48:49 +07:00
Koakuma
3ab6634370 stage2: sparc64: Implement airAlloc 2022-05-16 22:48:49 +07:00
Koakuma
339b0517b3 stage2: sparc64: Implement SPARCv9 bpcc 2022-05-16 22:48:49 +07:00
Koakuma
5d260eb573 stage2: sparc64: Implement SPARCv9 subcc 2022-05-16 22:47:53 +07:00
Koakuma
2770f9a034 stage2: sparc64: Implement airBr 2022-05-16 22:47:53 +07:00
Koakuma
b6de8d2565 stage2: sparc64: Implement airUnwrapErrPayload 2022-05-16 22:47:53 +07:00
Koakuma
2dc2ab091e stage2: sparc64: Implement airCondBr from flags register 2022-05-16 22:47:53 +07:00
Koakuma
fd781195de stage2: sparc64: Split the conditionals between integer and FP ones
On SPARCv9 the integer and FP conditional branch codes doesn't align
with each other at all, so the two need to be treated separately.
2022-05-16 22:47:52 +07:00
Koakuma
662a61fcc3 stage2: sparc64: Implement airIsErr and airIsNonErr 2022-05-16 22:47:52 +07:00
Jakub Konka
5b03d55c5e x64: rename brk to int3, and MIR to interrupt 2022-05-15 19:52:43 +02:00
Jakub Konka
5f97652da8 x64: remove verbose_mir functionality
Originally I thought interleaving AIR with MIR will be useful, however
as it stands, I have used it very sporadically, and recently, not at
all, and I do not think anyone else is actually using it. If there is
a simple error such as a wrong instruction emitted,
`objdump` is perfectly capable of narrowing it down, while if there's
something more subtle happening, regardless of having `--verbose-mir`
functionality or not, you still gotta go via the debugger which
offers a better view at interleaved source program with the emitted
machine code. Finally, I believe `-femit-asm` when we add it will offer a
more generic substitute.
2022-05-15 18:21:50 +02:00
Luuk de Gram
5138856a72 test harness: Set filename on error return
While calling `next` an error can occur while parsing the file.
However, we don't set the filename that is currently being processed, until `next` completed successfully.
This means that for invalid test names, the wrong filename was being displayed in the panic message.
The fix is to retrieve the correct filename when an error occurs and then setting the filename appropriately.
2022-05-15 09:30:59 +02:00
Robin
1bdcbd18ae init-exe: add note about log_level in ReleaseSmall and ReleaseFast build mode (#11626)
As suggested in https://github.com/ziglang/zig/issues/9945#issuecomment-950114977 by @wizzard0.

Fixes #9945.
2022-05-14 12:56:58 +02:00
Andrew Kelley
802f220739 Merge pull request #11647 from ziglang/migrate-runtime-safety-tests
migrate runtime safety tests to the new test harness
2022-05-13 23:57:15 -04:00
Andrew Kelley
0cd43b0f86 runtime safety tests only on the native target
This matches master branch. We can look into adding more target coverage
as we switch to stage2. As it stands, this works around having to
duplicate the "Executor" logic to figure out when to not run the tests
due to them being non-native.
2022-05-13 17:59:06 -07:00
Andrew Kelley
7d8b90b905 test harness: actually run the stage1 "run" tests 2022-05-13 17:32:23 -07:00
Andrew Kelley
c30edd78f9 std.Progress: activate() calls maybeRefresh()
This makes the progress bar display the ongoing operation in the case
that the API user calls activate().
2022-05-13 14:31:30 -07:00
Andrew Kelley
b986fcfc99 test-cases: honor -Dtest-filter argument from zig build 2022-05-13 14:31:02 -07:00
Andrew Kelley
f6e9b6620d build.zig: rename a local variable 2022-05-13 14:30:43 -07:00
Andrew Kelley
915032715f test harness: dump stderr when compiler crashes 2022-05-13 14:03:20 -07:00
Andrew Kelley
7755f7863a disable a runtime safety test that is failing on WASI 2022-05-13 14:03:20 -07:00
Andrew Kelley
66f3efb63b migrate runtime safety tests to the new test harness
* migrate runtime safety tests to the new test harness
   - this required adding compare output / execution support for stage1
     to the test harness.
 * rename `zig build test-stage2` to `zig build test-cases` since it now
   does quite a bit of stage1 testing actually. I named it this way
   since the main directory in the source tree associated with these
   tests is "test/cases/".
 * add some documentation for the test manifest format.
2022-05-13 14:03:20 -07:00
Andrew Kelley
f32928c50d Merge pull request #11641 from erikarvstedt/fixup_rand_float_improvement
Minor fixes for random float generation
2022-05-13 16:50:18 -04:00
Kirk Scheibelhut
24633b5613 zig fmt: make --exclude ignore missing dirs 2022-05-13 16:45:00 -04:00
Koakuma
fb0692334e target: Rename sparcv9 -> sparc64
Rename all references of sparcv9 to sparc64, to make Zig align more with
other projects. Also, added new function to convert glibc arch name to Zig
arch name, since it refers to the architecture as sparcv9.

This is based on the suggestion by @kubkon in PR 11847.
(https://github.com/ziglang/zig/pull/11487#pullrequestreview-963761757)
2022-05-13 16:43:59 -04:00
Jonathan Marler
aceb7e18bd std.os.linux: fix signature of setgroups
the list parameter should be a multi-item pointer rather than a single-item
pointer. see: https://linux.die.net/man/2/setgroups

> setgroups() sets the supplementary group IDs for the calling process...
> the size argument specifies the number of supplementary group IDs in the buffer pointed to by list.
2022-05-13 17:46:56 +02:00
Andrew Kelley
537f905216 fix bad runtime safety test cases
The "slicing operator with sentinel" runtime safety test cases should
all have been compile errors in their current forms. In this commit I
adjust them to use runtime-known slices before triggering the runtime
safety.

Furthermore the test cases did not actually have unique names.
2022-05-12 21:15:41 -07:00
Travis Staloch
974af5f291 add std.math.sign 2022-05-12 16:09:09 -04:00
Erik Arvstedt
23ef7a8060 std.rand.float: simplify leading zero calculations
This saves a `bitwise or` operation in the common case and
removes the (slightly magic) mask constants.
2022-05-12 16:23:39 +02:00
Erik Arvstedt
1d5ea10bee std.rand: fixup 'improve random float generation'
- Test: Fix bucket counting. Previously, the first hit was not counted.
  This off-by-one error slightly increased the mean of `*_total_variance`,
  which decreased the acceptance rate for a particular random seed
  from 95% to 92.6%. (Irrelevant for test failure because the seed is fixed.)
- Improve comments
2022-05-12 15:39:19 +02:00
Andrew Kelley
5c20c7036b Merge pull request #10796 from marler8997/envmap
Envmap
2022-05-12 02:49:11 -04:00
Jonathan Marler
aef642fc07 remove RtlUpcaseUnicodeString, no longer needed 2022-05-11 18:43:41 -06:00
Jonathan Marler
2ddfe16e1e fix ntdll extern casing
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-05-11 18:41:54 -06:00
Jonathan Marler
a38e6a64d3 document that on Windows, all key arguments in EnvMap must be valid utf8 2022-05-11 18:41:23 -06:00
Jonathan Marler
8492ced075 incorporate review changes from squeek 2022-05-11 18:41:23 -06:00
Jonathan Marler
71f69190ef some fixes to the EnvMap HashContext 2022-05-11 18:41:23 -06:00
Jonathan Marler
1c874a871f reverse some of the now unneeded changes from squeek 2022-05-11 18:41:23 -06:00
Jonathan Marler
e65d8f82c5 add unicode support 2022-05-11 18:41:23 -06:00
Jonathan Marler
69f0a5587d remove extra storage from EnvMap on windows 2022-05-11 18:40:53 -06:00
Ryan Liptak
e70cb04f89 EnvMapWindows: Fix putUtf8 not uppercasing keys 2022-05-11 18:40:53 -06:00
Ryan Liptak
b2b48fbf2c Set EnvMap.Size to BufMap.BufMapHashMap.Size
Now that BufMap.BufMapHashMap is pub, we can just get Size directly
2022-05-11 18:40:53 -06:00
Ryan Liptak
a2069612a5 Fix regression in RunStep.addPathDir
`key` was never being given a value, caused by b83cea12f31feaa0aff9489d5f7bd6159d284567
2022-05-11 18:40:53 -06:00
Ryan Liptak
a65be05a6e Make the BufMap.count return value match its underlying HashMap's Size
Fixes a process.EnvMap compile error on 32-bit architectures
2022-05-11 18:40:53 -06:00
Jonathan Marler
9e89000ffc Update usages of process.getEnvMap and change BufMap -> EnvMap where applicable
# Conflicts:
#	lib/std/build/RunStep.zig
2022-05-11 18:40:53 -06:00
Ryan Liptak
15d5988e69 Add process.EnvMap, a platform-independent environment variable map
EnvMap provides the same API as the previously used BufMap (besides `putMove` and `getPtr`), so usage sites of `getEnvMap` can usually remain unchanged.

For non-Windows, EnvMap is a wrapper around BufMap. On Windows, it uses a new EnvMapWindows to handle some Windows-specific behavior:

- Lookups use Unicode-aware case insensitivity (but `get` cannot return an error because EnvMapWindows has an internal buffer to use for lookup conversions)
- Canonical names are returned when iterating the EnvMap

Fixes #10561, closes #4603
2022-05-11 18:40:53 -06:00
Andrew Kelley
d383b940c2 Revert "add std.rand.RomuTrio"
This reverts commit d1f1f5124f.

The unit tests did not pass on `-target mips-linux`.
2022-05-11 13:50:14 -07:00
Francesco Alemanno
d1f1f5124f add std.rand.RomuTrio 2022-05-11 15:52:38 -04:00
Meghan
3a64693db3 std: add http definitions for Method and Status (#10661) 2022-05-11 15:43:18 -04:00
Andrew Kelley
19003de64c Merge pull request #10595 from squeek502/getenvW-case
os.getenvW: Fix case-insensitivity for Unicode env var names
2022-05-11 15:33:04 -04:00
Veikka Tuominen
090461a695 Merge pull request #11618 from arBmind/json-stringify-patch
JSON stringify string setting affects keys
2022-05-11 19:20:19 +03:00
William Sengir
77d732a85f aarch64,arm: disable broken @errSetCast test 2022-05-11 03:47:03 -07:00
William Sengir
4a6aee9dbe Sema: implement runtime safety checks for zirErrSetCast 2022-05-11 03:47:03 -07:00
William Sengir
363cdb7d5f Sema: add error for disjoint error sets in zirErrSetCast 2022-05-11 03:47:03 -07:00
William Sengir
bd32a0f3db Sema: add "declared here" note to zirErrSetCast 2022-05-11 03:47:03 -07:00
Jakub Konka
6608fa1353 Merge pull request #11628 from ziglang/x64-shifts 2022-05-11 08:24:03 +02:00
Andrew Kelley
b33c8b0b06 Sema: comptime float negation supports negative zero
When handling the `negate` ZIR instruction, Zig now checks for a
comptime operand and handles it as a special case rather than lowering
it as `0 - x` so that the expression `-x` where `x` is a floating point
value known at compile-time, will get the negative zero bitwise
representation.
2022-05-10 21:50:55 -07:00
Andrew Kelley
f5edf78eea Merge pull request #10143 from nuald/single-threaded-cpp1
Normalized C++ compilation options for single-threaded targets
2022-05-10 23:38:44 -04:00
Andrew Kelley
458943e324 Merge pull request #9831 from mathetake/llvmvisibility
Stage1: Add Visibility field to ExportOptions.
2022-05-10 22:04:30 -04:00
Andrew Kelley
ed63d6c7fd Merge pull request #10428 from mrakh/rand_float_improvement
Improve stdlib's random float generation
2022-05-10 22:03:29 -04:00
Andrew Kelley
7bedeb9659 std.rand: move tests to a separate test file 2022-05-10 19:02:03 -07:00
Mahdi Rakhshandehroo
550888e2ac std: improve random float generation 2022-05-10 18:50:12 -07:00
Silver
e0a514df41 std: make IntegerBitSet and ArrayBitSet have defined memory layout
This is useful for wrapping C libraries and native interfaces that make use of bit sets
2022-05-10 21:30:58 -04:00
Andrew Kelley
45415093c6 reduce the scope of this branch
* back out the changes to RunStep
 * move the disabled test to the .cpp code and avoid a confusing
   name-collision with the _LIBCPP macro prefix
 * fix merge conflict with the edits to the same test that ensure global
   initializers are called.

Now this branch is only concerned with single-threaded targets and
passing the correct macro defines to libc++.
2022-05-10 17:31:54 -07:00
Andrew Kelley
1ff9a18cd3 stage1: back out the broken visibility changes
```
$ valgrind ./zig test ../test/behavior.zig -target powerpc-linux-musl -lc -I../test
==2828778== Invalid read of size 1
==2828778==    at 0x6EA0265: LLVMSetVisibility (in /home/andy/Downloads/zig/build/zig)
==2828778==    by 0x1BCE60B: do_code_gen(CodeGen*) (codegen.cpp:9031)
==2828778==    by 0x1BD51E2: codegen_build_object(CodeGen*) (codegen.cpp:10610)
==2828778==    by 0x1BA5C17: zig_stage1_build_object (stage1.cpp:132)
==2828778==    by 0xE61E24: Module.build_object (stage1.zig:149)
==2828778==    by 0xC3D4CE: Compilation.updateStage1Module (Compilation.zig:5025)
==2828778==    by 0xC3117E: Compilation.performAllTheWork (Compilation.zig:2691)
==2828778==    by 0xC2A3ED: Compilation.update (Compilation.zig:2098)
==2828778==    by 0xBB9D1F: main.updateModule (main.zig:3104)
==2828778==    by 0xB16B75: main.buildOutputType (main.zig:2793)
==2828778==    by 0xAD0526: main.mainArgs (main.zig:225)
==2828778==    by 0xACFCB9: main (stage1.zig:48)
```

Since the plan is to ship stage3 for Zig 0.10.0, the stage1
implementation of this hardly matters.
2022-05-10 16:43:51 -07:00
Alexander Slesarev
3997828a61 Added _LIBCPP_HAS_NO_THREADS for single_threaded binaries linked with libcxx.
Fixed single-threaded mode for Windows.
2022-05-10 16:40:48 -07:00
Andrew Kelley
c4c5020f02 fixups to the previous commit
* Rename std.builtin.GlobalVisibility to std.builtin.SymbolVisibility
 * Add missing compile error. From the LLVM language reference: "A
   symbol with internal or private linkage must have default
   visibility."
2022-05-10 15:44:40 -07:00
Takeshi Yoneda
9654a54d4a Add Visibility field to ExportOptions.
Signed-off-by: Takeshi Yoneda <takeshi@tetrate.io>
2022-05-10 15:21:48 -07:00
Kirk Scheibelhut
67c4b16d6e docs: T.bit_count -> @typeInfo(T).Int.bits
bit_count was removed in #6246
2022-05-10 17:28:44 -04:00
Jakub Konka
3c69810fe6 x64: fix binary not implementation 2022-05-10 21:30:39 +02:00
Jakub Konka
f6f98a621f x64: enable additional math test 2022-05-10 21:21:09 +02:00
Jakub Konka
1d3b714125 x64: implement shl with overflow for non-pow-2 2022-05-10 21:19:05 +02:00
Jakub Konka
d31875f7ab x64: implement shl_with_overflow for powers of two 2022-05-10 20:53:44 +02:00
Jakub Konka
2a738599a0 x64: implement missing bits in add_with_overflow and sub_with_overflow 2022-05-10 20:45:57 +02:00
Jakub Konka
f131e41db9 x64: implement shl_exact and shr_exact 2022-05-10 19:34:20 +02:00
Jakub Konka
9725205859 x64: consolidate shifts into single MIR helper fn 2022-05-10 18:52:49 +02:00
Jakub Konka
a9514ae173 x64: handle immediate as RHS of shift bin ops 2022-05-10 18:16:14 +02:00
Jakub Konka
6a4e445f5a x64: pull shl and shr into one helper fn 2022-05-10 17:53:53 +02:00
Jakub Konka
aef3c149e6 x64: refactor genMulDivBinOp helper 2022-05-10 17:25:49 +02:00
Jakub Konka
ef9e3fb2b6 x64: migrate div to genMulDivBinOp 2022-05-10 16:43:44 +02:00
Frank Denis
aaf4011c2c Typo 2022-05-10 15:57:46 +02:00
Brian Gold
52651ae7a0 io_uring cancel test must tolerate CQ reordering
Fixes #11382. Tested on ArchLinux 5.17.5-arch1-1.
2022-05-10 11:49:41 +02:00
Andreas Reischuck
10a671ad09 std.json stringify fix object keys are always is strings
* extracted outputJsonString to avoid code duplication
2022-05-10 09:56:49 +02:00
OfekShochat
b57a356bb6 std.json add stringify struct with string as array 2022-05-10 09:55:06 +02:00
Jakub Konka
85ca14e35a x64: converge add_with_overflow and sub_with_overflow 2022-05-10 09:08:33 +02:00
Jakub Konka
af3ecd04b4 x64: make genBinOp operate on MCValues directly 2022-05-10 09:04:39 +02:00
Jakub Konka
252c5a2339 x64: migrate mod and rem into genBinOp 2022-05-10 01:15:14 +02:00
Jakub Konka
c3b7a5cc26 x64: pass tag and maybe_inst explictly to genBinOp 2022-05-09 23:58:46 +02:00
Jakub Konka
7b9f8bfbd8 x64: migrate mul to new genBinOp helper 2022-05-09 23:50:01 +02:00
Jakub Konka
20e7f1218b x64: make one entry point for binary ops
* rename `genBinMathOp` into `genBinOp` and handle commutativity
* rename `genBinMathOpMir` into `genBinOpMir`
2022-05-09 22:31:36 +02:00
Luuk de Gram
62453496ba wasm: Write nops for padding debug info 2022-05-09 18:51:46 +02:00
Luuk de Gram
2ae2ac33d9 wasm: Emit debug sections
This commit adds the ability to emit the following debug sections:
.debug_info
.debug_abbrev
.debug_line
.debug_str

Line information and files are now being loaded correctly by browser debuggers.
2022-05-09 18:51:46 +02:00
Luuk de Gram
9b6b7034c2 wasm: Flush debug information + commit decl
This implements parts to commit a decl's debug information into
a linear memory buffer. The goal is to write this buffer at once
after we finished linking.
2022-05-09 18:51:46 +02:00
Luuk de Gram
f760272200 wasm: Debug info for lines + pro/epilogue
Maps lines and columns between wasm bytecode and Zig source code.
While this supports prologue and epilogue information, we need to add
support for performing relocations as the offsets are relative to the code section,
which means we must relocate it according to the atom offset's offset while keeping function count
in mind as well (due to leb128 encoding).
2022-05-09 18:51:46 +02:00
Luuk de Gram
d46cdb5396 wasm: Debug information for locals
Implements very basic debug information for locals.
For now it only implements debug info when the variable is stored within a
Wasm local. The goal is to support those that live in the data section (virtual stack).
2022-05-09 18:51:46 +02:00
Luuk de Gram
33b2f4f382 wasm: Implement debug info for parameters 2022-05-09 18:51:46 +02:00
Luuk de Gram
8e1c220be2 wasm: Add basic debug info references 2022-05-09 18:51:46 +02:00
Helio Machado
941b6830b1 std.crypto: generate AES constants at compile time (#11612)
* std/crypto: generate AES constants at compile time

* Apply suggestions from code review

Co-authored-by: Frank Denis <124872+jedisct1@users.noreply.github.com>

* Update lib/std/crypto/aes/soft.zig

* Separate encryption and decryption tables

* Run `zig fmt`

* Increase branch quota and remove redundant align

* Update lib/std/crypto/aes/soft.zig

Co-authored-by: Frank Denis <124872+jedisct1@users.noreply.github.com>

* Rename identifiers and simplify dataflow

* Increase branch quota (again) and fix comment

Co-authored-by: Frank Denis <124872+jedisct1@users.noreply.github.com>
2022-05-09 18:50:01 +02:00
Evan Haas
94b9bcd034 stdlib: escape backslashes and double quotes in Builder response file
Fixes #11595
2022-05-09 18:42:42 +03:00
Jakub Konka
9c3d24ea0b x64: add naive impl of shr 2022-05-09 17:39:19 +02:00
Andrew Kelley
d7f8368da8 Merge pull request #11609 from ziglang/win-compiler-rt
compiler-rt: avoid symbol collisions with Windows libc
2022-05-08 19:29:21 -04:00
Hannes Bredberg
ea3f5905f0 Add Win64 calling convention
Closes ziglang/zig#11585
2022-05-08 16:28:10 -04:00
Andrew Kelley
cd019ee502 compiler_rt: avoid weak aliases on Windows
When exporting math functions for Windows, we provide weak exports of
'l' variants rather than weak aliases. We still use aliases on other
operating systems so that the 'l' variants have one less jump
instruction in this case.
2022-05-08 13:06:21 -07:00
Andrew Kelley
6fde2fcd51 allow in-memory coercion of differently-named floats with same bits
For example, this allows passing a `*c_longdouble` where a `*f80` is
expected, provided that `c_longdouble` maps to `f80` for this target.
2022-05-08 13:05:16 -07:00
Jakub Konka
9416b4d993 Merge pull request #11608 from ziglang/stage2-regalloc 2022-05-08 11:20:14 +02:00
Andrew Kelley
663b67783e compiler-rt: avoid symbol collisions with Windows libc
closes #11600
2022-05-07 17:44:49 -07:00
Andrew Kelley
aa05cd4809 CI: fix universal libc step name
This was a merge conflict that went undetected.
2022-05-07 17:44:37 -07:00
Jakub Konka
f161d3875a Merge pull request #11605 from Luukdegram/wasm-mul-overflow
stage2: wasm - Improve `@mulWithOverflow` implementation
2022-05-07 23:30:08 +02:00
Jakub Konka
6bf67eada4 arm: lock dest register in shl_overflow so that we do not spill it
Nerf two tests - they will require further investigation, but arm
now passes all tests with the safety PR.
2022-05-07 22:53:17 +02:00
Jakub Konka
756ddf0925 arm: fix CF flags spilling and implement genSetStack for reg with overflow flags 2022-05-07 22:35:41 +02:00
Luuk de Gram
a110979582 stage2: Split @mulWithOverflow tests 2022-05-07 20:02:02 +02:00
Luuk de Gram
ad4f0dda8b wasm: Fix @floatToInt and split overflow ops
As we now store negative signed integers as two's complement,
we must also ensure that when truncating a float, its value is wrapped
around the integer's size.

This also splits `@mulWithOverflow` into its own function to make
the code more maintainable and reduce branching.
2022-05-07 17:04:19 +02:00
Luuk de Gram
0c51e703f1 wasm: @addWithOverflow for bitsize 32 2022-05-07 14:24:18 +02:00
Jakub Konka
f57b059e58 regalloc: refactor locking multiple registers at once 2022-05-07 13:27:11 +02:00
Jakub Konka
bf11cdc9d8 x64: refactor code to avoid stage1 sema limitations 2022-05-07 13:19:53 +02:00
Jakub Konka
197c2a465f regalloc: rename freeze/unfreeze to lock/unlock registers 2022-05-07 10:46:05 +02:00
Andrew Kelley
e8c85450fe Merge pull request #11592 from ziglang/stage3-macos-linker
Sema: solve a false positive "depends on itself"
2022-05-07 04:38:19 -04:00
Jakub Konka
43a627927f x64: fix misused register locks 2022-05-07 10:31:08 +02:00
Andrew Kelley
ec95e00e28 flatten lib/std/special and improve "pkg inside another" logic
stage2: change logic for detecting whether the main package is inside
the std package. Previously it relied on realpath() which is not portable.
This uses resolve() which is how imports already work.

 * stage2: fix cleanup bug when creating Module
 * flatten lib/std/special/* to lib/*
   - this was motivated by making main_pkg_is_inside_std false for
     compiler_rt & friends.
 * rename "mini libc" to "universal libc"
2022-05-06 22:41:00 -07:00
Andrew Kelley
3b60ab4872 stage2: fix std lib tests always filtering out all tests 2022-05-06 22:41:00 -07:00
Andrew Kelley
f034cef262 link/MachO: use const instead of var and limit scope of vars 2022-05-06 22:41:00 -07:00
Andrew Kelley
9afc4fe0e2 Sema: solve a false positive "depends on itself"
This improves the ABI alignment resolution code.

This commit fully enables the MachO linker code in stage3. Note,
however, that there are still miscompilations in stage3.
2022-05-06 22:40:57 -07:00
Andrew Kelley
0df28f9d45 Merge pull request #11492 from ziglang/ci-stage3-behavior
CI: add non-LLVM backends to the test matrix
2022-05-06 22:51:55 -04:00
Jakub Konka
efeb031b79 macho: skip cache if cache_mode is .whole 2022-05-07 01:52:00 +02:00
Jakub Konka
a2dbe6589e macho: share traditional codepaths with stage2+llvm backend 2022-05-07 01:44:26 +02:00
Andrew Kelley
a2b8a9756f CI: macos: disable stage2 test-behavior
stage2 on macOS is not yet capable of passing these tests. Such
improvements will be done in a follow-up change.
2022-05-06 16:26:04 -07:00
Jakub Konka
ac954eb539 regalloc: ensure we only freeze/unfreeze at the outermost scope
This prevents a nasty type of bugs where we accidentally unfreeze
a register that was frozen purposely in the outer scope, risking
accidental realloc of a taken register.

Fix CF flags spilling on aarch64 backend.
2022-05-07 00:57:55 +02:00
Andrew Kelley
6d605ca690 CI: macos: stage2 zig build test-behavior 2022-05-06 15:42:52 -07:00
Luuk de Gram
4df65fc264 wasm: Store signed ints as two's complement
When a signed integer is negative, the integer will be stored as a two's complement,
rather than its signed value. Instead, we verify the signed bits during arithmetic operations.
This fixes signed cases of `@mulWithOverflow`.
2022-05-06 21:58:25 +02:00
Andrew Kelley
d136cd3202 LLVM: rework the previous commit
Idiomatic Zig, use const instead of var, simplify the logic.
2022-05-06 11:43:06 -07:00
aiotter
ad7f725dba std.c: Move Darwin-unspecific functions from std/c/darwin.zig to std/c.zig 2022-05-07 00:02:15 +09:00
aiotter
83d8378139 std.c: Add C APIs to read directories 2022-05-06 23:54:13 +09:00
Jakub Konka
ac1aaec9c3 x64: handle CF flags spilling in overflow calls
Handle spilling of CF flags set with an overflow call.
Add saving stack offset to memory.
2022-05-06 13:42:11 +02:00
Jakub Konka
edb3adaa33 stage2,llvm: handle softfloats in @intToFloat and @floatToInt
If the hw doesn't have support for exotic floating-point types such
as `f80`, we lower the call to a compiler-rt function call instead.

I've added a behavior test specifically targeting this use case which
now passes on `aarch64-macos`.

Additionally, this commit makes it possible to successfully build
stage3 on `aarch64-macos`. We can print the compiler's help message,
however, building with it needs a little bit more love still.
2022-05-05 22:29:30 -07:00
Andrew Kelley
413b789e06 std.os.linux.arm-eabi: upgrade to new fn ptr semantics 2022-05-05 22:29:25 -07:00
Andrew Kelley
496eb69273 CI: add non-LLVM backends to the test matrix
We can't yet run the behavior tests with stage3, but at least we can run
them with stage2, and we can use the proper test matrix.

This commit also adds use_llvm and ofmt to the zig build system.
2022-05-05 22:29:25 -07:00
Jakub Konka
df38dfa4d1 Merge pull request #11591 from ziglang/x64-overflow 2022-05-06 07:28:44 +02:00
Jakub Konka
09d2b6c4e1 Merge pull request #11487 from koachan/sparc64-codegen 2022-05-06 07:27:30 +02:00
Jakub Konka
c592f0ca21 test: pass extended mul_with_overflow tests on x64 2022-05-05 22:53:11 +02:00
Jakub Konka
e3160ec573 x64: mul_with_overflow: cannot reuse operand if not the result 2022-05-05 22:51:12 +02:00
Jakub Konka
0728847ce7 x64: handle unsigned mul_with_overflow for non-pow-2 ints 2022-05-05 22:51:12 +02:00
Jakub Konka
0fc1e8b54f x64: handle signed mul_with_overflow for non-pow-2 ints 2022-05-05 22:51:12 +02:00
Jakub Konka
ebfc2825ab x64: explicitly handle Vector vs Int types for overflow arith 2022-05-05 22:51:12 +02:00
Jakub Konka
13d1798ea0 Merge pull request #11574 from ziglang/stage2-aarch64
stage2,aarch64: basic overflow arithmetic support
2022-05-05 22:50:38 +02:00
Jakub Konka
90a8817f55 aarch64: ensure we set correct operand size at codegen stage 2022-05-05 22:33:03 +02:00
Jakub Konka
eab5a1bd5a test: test bitwidths between 1...8 and 8...16 for mul_with_overflow 2022-05-05 21:43:36 +02:00
Jakub Konka
3cef23129a test: test more int sizes for @mulWithOverflow builtin 2022-05-05 21:43:36 +02:00
Jakub Konka
d112cd52f3 aarch64: fix mul_with_overflow for ints <= 32bits 2022-05-05 21:43:36 +02:00
Jakub Konka
f4421c01e8 aarch64: implement mul_with_overflow for ints in range 33-64 bits incl 2022-05-05 21:43:36 +02:00
Jakub Konka
8715b01005 aarch64: implement mul_with_overflow for <= 32bit ints
Add emitters for `smull`, `umull` and `tst (immediate)` instructions.
2022-05-05 21:43:36 +02:00
joachimschmidt557
aaacda4df9 stage2 AArch64: implement shl_with_overflow 2022-05-05 21:43:35 +02:00
joachimschmidt557
f267e7a8b4 stage2 AArch64: implement {add,sub}_with_overflow for all ints < 64 2022-05-05 21:43:35 +02:00
joachimschmidt557
c2d2307d09 stage2 AArch64: initial implementation of {add,sub}_with_overflow 2022-05-05 21:43:35 +02:00
Jakub Konka
9985699943 libstd: map sparcv9 to qemu-sparc64 for test-runner 2022-05-05 20:00:13 +02:00
Jakub Konka
64927aa782 sparcv9: fix typo in def comment 2022-05-05 19:38:55 +02:00
Koakuma
5a6f0d2e51 stage2: sparcv9: Update Mir tag doc comments 2022-05-05 19:34:06 +02:00
Koakuma
bc5b5df2c7 stage2: sparcv9: Update test case 2022-05-05 19:34:06 +02:00
Koakuma
e963d5be0b stage2: sparcv9: Simplify debug info emission, remove unused formats 2022-05-05 19:34:06 +02:00
Koakuma
c73eb00727 stage2: sparcv9: Add debug info generation for args 2022-05-05 19:34:05 +02:00
Koakuma
e76d52c74d stage2: sparcv9: Remove dbg_arg instruction 2022-05-05 19:34:05 +02:00
Koakuma
ae201807f5 stage2: sparcv9: Simplify genLoad/genStore 2022-05-05 19:34:05 +02:00
Koakuma
f6bf3dd78c stage2: sparcv9: Fix stack space accounting 2022-05-05 19:34:04 +02:00
Koakuma
e03ec51b4b stage2: sparcv9: Pad branch delay slots with nops 2022-05-05 19:34:04 +02:00
Koakuma
a00d69ea4a stage2: sparcv9: Implement basic stack load/stores 2022-05-05 19:34:04 +02:00
Koakuma
b6d7f63f34 stage2: sparcv9: Implement jmpl lowering 2022-05-05 19:34:03 +02:00
Andrew Kelley
59905a62f9 Merge pull request #11583 from ziglang/stage2-test-behavior
stage2 behavior tests for all targets passing with the LLVM backend
2022-05-05 12:53:23 -04:00
Isaac Freund
49a7ceb5bc cmake: add /usr/lib/llvm13 to searched paths
Alpine linux installs llvm to this path and currently patches zig's
cmake file in order to build zig from source.

https://git.alpinelinux.org/aports/tree/testing/zig/llvm-include.patch?id=0c3f7850bef38fb4c63fc6af5c14724e5311b0cc
2022-05-05 02:51:48 -04:00
Andrew Kelley
44252f4d35 LLVM: fix C ABI for windows
* sret logic needed a check for hasRuntimeBits()
 * lower f128 on windows targets with the "sse" class rather than
   "memory". For reference, clang emits a compile error when __float128
   is used with the MSVC ABI, saying that this type is not supported.
   The docs for the x64 calling convention have both of these sentences:
   - "Any argument that doesn't fit in 8 bytes, or isn't 1, 2, 4, or 8 bytes,
     must be passed by reference."
   - "All floating point operations are done using the 16 XMM registers."
 * For i128, however, it is clear that the Windows calling convention
   wants such an object to be passed by reference. I fixed the LLVM
   lowering for function parameters to make this work.
2022-05-04 22:57:57 -07:00
Andrew Kelley
17fc44dd12 LLVM: fix x86_64 sysv C ABI for extern structs with sub-64 bit integers 2022-05-04 21:11:55 -07:00
Andrew Kelley
1b432b5576 stage2: implement global assembly
So far it's supported by the LLVM backend only. I recommend for the
other backends to wait for the resolution of #10761 before adding
support for this feature.
2022-05-04 20:38:53 -07:00
Andrew Kelley
ba127058d1 CLI: detect MinGW-flavored static libraries
Ideally on Windows, static libraries look like "foo.lib". However, CMake
and other build systems will unfortunately produce static libraries that
instead look like "libfoo.a". This patch makes Zig's CLI resolve "-lfoo"
arguments into static libraries that match this other pattern.

This patch fixes an issue with zig-bootstrap where it won't find the
LLVM, Clang, and LLD libraries.
2022-05-04 19:15:31 -07:00
Andrew Kelley
0bebb688fb stage2: change max int align from 8 to 16 for more ISAs
These targets now have a similar disagreement with LLVM about the
alignment of 128-bit integers as x86_64:
 * riscv64
 * powerpc64
 * powerpc64le
 * mips64
 * mips64el
 * sparcv9

See #2987
2022-05-04 19:11:02 -07:00
Andrew Kelley
af7e945a7d stage2: fix @sizeOf for structs with comptime fields 2022-05-04 18:45:59 -07:00
Andrew Kelley
2f6a01d0c3 stage1: fix @sizeOf for 128-bit integer types 2022-05-04 17:34:17 -07:00
Andrew Kelley
f21c11a7f7 stage2: change x86_64 max int alignment from 8 to 16
For x86_64, LLVMABIAlignmentOfType(i128) reports 8. However I think 16
is a better number for two reasons:
1. Better machine code when loading into SIMD register.
2. The C ABI wants 16 for extern structs.
2022-05-04 17:34:17 -07:00
Andrew Kelley
5b1c0d922c stage2: improve semantics of atomic operations
ZIR instructions updated: atomic_load, atomic_rmw, atomic_store, cmpxchg
These no longer construct a pointer type as the result location. This
solves a TODO that was preventing the pointer from possibly being
volatile, as well as properly handling allowzero and addrspace.
It also allows the pointer to be over-aligned, which may be needed
depending on the target. As a consequence, the element type needs to be
communicated in the ZIR. This is done by strategically making one of the
operands be ResultLoc.ty instead of ResultLoc.coerced_ty if possible, or
otherwise explicitly adding elem_type into the ZIR encoding, such as in
the case of atomic_load.

The pointer type of atomic operations is now checked in Sema by coercing
it to an expected pointer type, that maybe over-aligned according to
target requirements.

Together with the previous commit, Zig now has smaller alignment for
large integers, depending on the target, and yet still has type safety
for atomic operations that specially require higher alignment.
2022-05-04 17:34:16 -07:00
Andrew Kelley
259f784241 stage2: improve @sizeOf and @alignOf integers
Prior to this commit, the logic for ABI size and ABI alignment for
integers was naive and incorrect. This results in wasted hardware as
well as undefined behavior in the LLVM backend when we memset an
incorrect number of bytes to 0xaa due to disagreeing with LLVM about the
ABI size of integers.

This commit introduces a "max int align" value which is different per
Target. This value is used to derive the ABI size and alignment of all
integers.

This commit makes an interesting change from stage1, which treats
128-bit integers as 16-bytes aligned for x86_64-linux. stage1 is
incorrect. The maximum integer alignment on this system is only 8 bytes.
This change breaks the behavior test called "128-bit cmpxchg" because on
that target, 128-bit cmpxchg does require a 16-bytes aligned pointer to
a 128 bit integer. However, this alignment property does not belong on
*all* 128 bit integers - only on the pointer type in the `@cmpxchg`
builtin function prototype. The user can then use an alignment override
annotation on a 128-bit integer variable or struct field to obtain such
a pointer.
2022-05-04 17:34:16 -07:00
Andrew Kelley
080e870a71 Merge pull request #11572 from ziglang/test-harness
test: improve test/batch sequence iterator and move all tests into cases/ parent dir
2022-05-04 20:28:34 -04:00
Jakub Konka
3624e1ef48 test: move compile errors and incremental tests into common dir 2022-05-04 23:51:16 +02:00
Jakub Konka
9d79b740bc test: improve test batch/sequence iterator
With this improved iterator, type of test is now inferred from
the filename, enabling us to put all cases in one common parent
directory, and iterate over that, thus automating a lot of tasks.
2022-05-04 23:21:35 +02:00
Andrew Kelley
a839ccc153 Merge pull request #11575 from ifreund/musl123
musl: update to 1.2.3
2022-05-04 16:36:57 -04:00
Erik Arvstedt
e5b07d8187 std.meta.TrailerFlags: improve init type 2022-05-04 21:26:48 +02:00
Erik Arvstedt
8b8e57c670 std.meta.TrailerFlags: include in std tests
Previously, TrailerFlags was unreferenced in std,
so its tests were never run.

Also, fix the use of `default_value` whose type was changed in
f4a249325e (#10766).
2022-05-04 20:01:48 +02:00
Isaac Freund
2477a95d29 tools/gen_stubs: sort output by section/symbol name
This will make future diffs smaller and easier to review.
2022-05-04 18:38:45 +02:00
Jay Petacat
28ef79ea80 std: Single-threaded panicImpl sleep is unreachable (#11569)
Adding `unreachable` prevents the futex code from being inspected during
a single-threaded build. Without futex, first draft BYOS packages don't
need to implement `nanosleep` to get a single-threaded "hello world"
program working.

Use of `assert()` did not achieve the desired effect of avoiding futex
in a single-threaded build.
2022-05-04 09:43:27 -05:00
Andrew Kelley
3ed9ef3e6b Sema: fix bigIntToFloat
The implementation had the `@mulAdd` parameters mixed up.
2022-05-03 21:50:00 -07:00
Isaac Freund
f4131cf8a6 musl: update to 1.2.3
This was a bit trickier than it should be due to symbol conflicts with
zig's compiler-rt implementation. We attempt to use weak linkage in
our compiler-rt, but this does not seem to be working in all cases. I
manually disabled export of the problematic compiler-rt math functions
in order to cross compile musl's libc.so for all targets as input to
`tools/gen_stubs.zig`.

Other than that, this update went fairly smoothly. Quite a few
additional symbols were added to the blacklist in `tools/gen_stubs.zig`
due to recent reorganization of zig's compiler-rt.
2022-05-04 01:00:57 +02:00
Andrew Kelley
b6930825b0 github issue templates enhancements
Make the honey traps links instead of actual templates
2022-05-03 14:04:15 -07:00
Andrew Kelley
3cfde183f3 Merge pull request #11571 from ziglang/stage2-test-behavior
progress towards stage2 behavior tests for all targets passing with the LLVM backend
2022-05-03 14:58:46 -04:00
Andrew Kelley
6317da8da4 Merge pull request #11566 from tiehuis/master
add new float-parser based on eisel-lemire algorithm
2022-05-03 14:56:05 -04:00
Jakub Konka
d48789467d x86_64: use math.zig to check isPowerOfTwo and calc log2_int 2022-05-03 16:39:21 +02:00
Marc Tiehuis
2947a2faab export __floatuntikf for PowerPC
PPC __floatuntikf is equivalent to X86 __floatuntitf.
2022-05-03 20:12:29 +12:00
Marc Tiehuis
02209d8a5f fix aarch64 f16 nan parse test failure 2022-05-03 19:04:16 +12:00
Andrew Kelley
aa3c3f66da test runner: enable arg processing for stage2 builds 2022-05-02 22:14:17 -07:00
Andrew Kelley
ea7142c43f LLVM: set module PIC, PIE, and CodeModel
Some simple code from stage1 ported over to stage2.
2022-05-02 22:14:17 -07:00
Andrew Kelley
defda6202a LLVM: insert workaround for aarch64-windows f16 CodeView crash 2022-05-02 22:14:17 -07:00
Andrew Kelley
76b7f56725 std.os.windows: upgrade to new function pointer semantics 2022-05-02 22:14:17 -07:00
Andrew Kelley
48d2f226cb Sema: allow exporting optionals and pointers 2022-05-02 22:14:17 -07:00
Andrew Kelley
65389dc280 stage2: improve inline asm stage1 compatibility
* outputs can have names and be referenced with template replacements
   the same as inputs.
 * fix print_air.zig not decoding correctly.
 * LLVM backend: use a table for template names for simplicity
2022-05-02 22:14:17 -07:00
Marc Tiehuis
5fbda2c579 temporary fix for stage2/stage1 f128 rounding discrepency
This is only to get tests running again. The root issue should be fixed
in stage1 so rounding is consistent between stages.
2022-05-03 17:14:01 +12:00
Andrew Kelley
b95942744c std.pdb: fix incorrect use of packed struct 2022-05-02 22:06:02 -07:00
Andrew Kelley
d98869da43 behavior tests: fix wrong packed struct test case
Packed structs are defined to have the same alignment and size as their
backing integer.
2022-05-02 22:06:02 -07:00
Andrew Kelley
1a1f62a0ce std: enable real start code always for LLVM backend 2022-05-02 22:06:02 -07:00
Marc Tiehuis
bbfe2234c8 update AstGen float literal parsing 2022-05-03 16:46:40 +12:00
Marc Tiehuis
2085a4af56 add new float-parser based on eisel-lemire algorithm
The previous float-parsing method was lacking in a lot of areas. This
commit introduces a state-of-the art implementation that is both
accurate and fast to std.

Code is derived from working repo https://github.com/tiehuis/zig-parsefloat.
This includes more test-cases and performance numbers that are present
in this commit.

* Accuracy

The primary testing regime has been using test-data found at
https://github.com/tiehuis/parse-number-fxx-test-data. This is a fork of
upstream with support for f128 test-cases added. This data has been
verified against other independent implementations and represents
accurate round-to-even IEEE-754 floating point semantics.

* Performance

Compared to the existing parseFloat implementation there is ~5-10x
performance improvement using the above corpus. (f128 parsing excluded
in below measurements).

** Old

    $ time ./test_all_fxx_data
    3520298/5296694 succeeded (1776396 fail)

    ________________________________________________________
    Executed in   28.68 secs    fish           external
       usr time   28.48 secs    0.00 micros   28.48 secs
       sys time    0.08 secs  694.00 micros    0.08 secs

** This Implementation

    $ time ./test_all_fxx_data
    5296693/5296694 succeeded (1 fail)

    ________________________________________________________
    Executed in    4.54 secs    fish           external
       usr time    4.37 secs  515.00 micros    4.37 secs
       sys time    0.10 secs  171.00 micros    0.10 secs

Further performance numbers can be seen using the
https://github.com/tiehuis/simple_fastfloat_benchmark/ repository, which
compares against some other well-known string-to-float conversion
functions. A breakdown can be found here:

0d9f020f1a/PERFORMANCE.md (commit-b15406a0d2e18b50a4b62fceb5a6a3bb60ca5706)

In summary, we are within 20% of the C++ reference implementation and
have about ~600-700MB/s throughput on a Intel I5-6500 3.5Ghz.

* F128 Support

Finally, f128 is now completely supported with full accuracy. This does
use a slower path which is possible to improve in future.

* Behavioural Changes

There are a few behavioural changes to note.

 - `parseHexFloat` is now redundant and these are now supported directly
   in `parseFloat`.
 - We implement round-to-even in all parsing routines. This is as
   specified by IEEE-754. Previous code used different rounding
   mechanisms (standard was round-to-zero, hex-parsing looked to use
   round-up) so there may be subtle differences.

Closes #2207.
Fixes #11169.
2022-05-03 16:46:40 +12:00
Frank Denis
098bee0e56 edwards25519 fixes (#11568)
* edwards25519: fix X coordinate of the base point

Reported by @OfekShochat -- Thanks!

* edwards25519: reduce public scalar when the top bit is set, not cleared

This is an optimization for the unexpected case of a scalar
larger than the field size.

Fixes #11563

* edwards25519: add a test implicit reduction of invalid scalars
2022-05-03 05:28:34 +02:00
Jakub Konka
f648a1b043 test: regression fix: skip stage1 if not enabled 2022-05-02 21:22:07 -04:00
Lee Cannon
3679d737f8 Allocator: correct PanicFree function name 2022-05-02 15:29:27 -04:00
r00ster91
bb55276f06 Avoid some unnecessary underscores in constant names 2022-05-02 15:29:04 -04:00
Andrew Kelley
9af4cada73 Sema: coerce comptime_float to fixed-width float
Instead of doing heterogeneous comparison at comptime. This makes the
following test pass (as it already does for stage1):

```zig
test {
    const x: f64 = 12.34;
    expect(x == 12.34);
}
```

There is already behavior test coverage for this, however, other bugs in
`std.fmt.parseFloat` are masking the failures.

From a language specification perspective, this makes sense because it
makes comptime comparisons with comptime_float work the same way they
work with runtime comparisons.
2022-05-02 12:16:23 -07:00
Andrew Kelley
a3f56154d0 stage1: disable new behavior tests
Oops, I forgot to check if the new behavior tests are passing for
stage1.
2022-05-01 22:11:57 -07:00
Andrew Kelley
1387d2f5ac zig build: use CacheMode.whole for build_runner.zig
Maybe after we have incremental compilation metadata serialization
and non-LLVM backends, it will make sense to switch this back. For now,
however, this makes successive `zig build` commands much faster.
2022-05-01 15:43:52 -07:00
Andrew Kelley
82b96ca0de disable failing behavior tests
Oops, I forgot to run the non-LLVM backend tests on that last commit.
2022-05-01 15:35:35 -07:00
Andrew Kelley
60c2972c5d stage2: fix comptime fixed-width float division 2022-05-01 15:02:06 -07:00
Andrew Kelley
615a983517 cmake: default install prefix to ./stage1 2022-05-01 14:05:01 -07:00
r00ster
f65ca80bbe std.heap: Fix typo 2022-05-01 14:41:12 -04:00
Daniele Cocca
d127c1d59e CBE: handle returning undefined for ErrorUnion
Just like for Struct in 8238d4b335, in the
case of ErrorUnion struct we need to return a compound literal "(T){...}"
instead of just "{}", which is invalid code when used in e.g. a "return"
expression.
2022-04-30 13:29:21 -04:00
sin-ack
032c722d20 Sema: Fix many-pointer array concatenation at comptime (#11512)
* Sema: Correctly determine whether array_cat lhs and rhs are single ptrs

Many-pointers are also not single-pointers and wouldn't be considered
here. This commit makes the conditions use the appropriately-named
isSinglePointer instead.

* Sema: Correctly obtain ArrayInfo for many-pointer concatenation

Many-pointers at comptime have a known size like slices and can be used
in array concatenation. This fixes a stage1 regression.

* test: Add comptime manyptr concatenation test

Co-authored-by: sin-ack <sin-ack@users.noreply.github.com>
2022-04-29 22:53:06 -04:00
InKryption
609896a6e8 std.MultiArrayList: add functions addOne, pop, and popOrNull (#11553)
Update basic usage test to account for these, and by extension for addOneAssumeCapacity.
2022-04-29 22:51:53 -04:00
Andrew Kelley
cc39d453c4 Merge pull request #11549 from Vexu/stage2-fixes
Stage2: fix comptime unreachable, adjust Zir.Extended
2022-04-29 22:50:53 -04:00
Jimmi Holst Christensen
a0a2ce92ca std: Do not allocate the result for ChildProcess.init
Instead, just return ChildProcess directly. This structure does not
require a stable address, so we can put it on the stack just fine. If
someone wants it on the heap they should do.

  const proc = try allocator.create(ChildProcess);
  proc.* = ChildProcess.init(args, allocator);
2022-04-29 22:50:34 -04:00
Veikka Tuominen
596f7df02e Zir: turn extended func into func_extended 2022-04-30 01:06:01 +03:00
Veikka Tuominen
1d455896cb Zir: move more common instructions out of extended 2022-04-30 01:06:01 +03:00
Veikka Tuominen
a6f254ec3e stage2: fix comptime unreachable 2022-04-30 01:05:48 +03:00
Natalia Cholewa
0e49142ce4 std.SegmentedList: add constIterator 2022-04-29 14:48:49 -04:00
Jakub Konka
3b8187072f Merge pull request #11530 from ziglang/test-harness
test: move compare and run tests to new test harness
2022-04-29 08:24:02 +02:00
Daniele Cocca
fda143d5d8 CBE: fix renderValue() for struct fields with no runtime bits
These shouldn't count towards the total emitted, or the stray comma
separators would cause compilation errors.
2022-04-28 23:41:42 -04:00
Stephen Gregoratto
2409041e62 Seccomp fixups re: #10717
- Add type annotation for AUDIT.current.
- Make unsupported archs a compile error.
2022-04-28 23:41:25 -04:00
Andrew Kelley
a242906696 compiler-rt: restore stage1 workaround
18d6523888 regressed compiler-rt tests for
stage1 because it removed a workaround. I updated the comment to better
explain what exactly the workaround is so that it won't happen again.
2022-04-28 20:39:33 -07:00
Andrew Kelley
d8e99164d3 AstGen: encode negativity into float literals
rather than a separate negation instruction. closes #11545
2022-04-28 17:11:42 -07:00
Andrew Kelley
18d6523888 compiler-rt: upgrade to stage2 fn ptr semantics 2022-04-28 17:11:14 -07:00
Andrew Kelley
c5e847744c Revert "Merge pull request #11214 from iddev5/ay-build-runner"
This reverts commit 75c9936737, reversing
changes made to 7f13f5cd5f.

I don't think `runZigBuild` belongs in std.testing. We already have
`test/standalone/*` for this.

Additionally test names should explain what they are testing rather than
referencing GitHub issue numbers.
2022-04-28 14:12:32 -07:00
Veikka Tuominen
091fe78337 Merge pull request #11541 from Vexu/stage2-slice-field-ptr
Stage2: fix slice field modification at comptime
2022-04-28 22:27:50 +03:00
Andrew Kelley
3052597a73 Revert "std.testing: add writeZigFile for TmpDir"
This reverts commit 7f13f5cd5f.

I'd like to review this one before it goes in. This is an awfully
specific API that I don't think belongs in std.testing. Also I don't
want any code snippets in doc strings. We have doctests for that.
2022-04-28 11:20:53 -07:00
Andrew Kelley
9181c98225 std.build: fix dll-export-fns API
We have a pattern using `?bool` for the -f/-fno- style flags.

Fixup for 8e3add8736.
2022-04-28 11:13:33 -07:00
Andrew Kelley
360ecc1a2f Merge pull request #11532 from ziglang/compiler-rt-math
compiler-rt math functions reorg
2022-04-28 13:34:38 -04:00
Jakub Konka
d25f06a71c test: remove redundant codepaths from test harness 2022-04-28 18:35:01 +02:00
Jakub Konka
62625d9d95 test: migrate stage1 compile error tests to updated test manifest 2022-04-28 18:35:01 +02:00
Jakub Konka
c8d0fb0b21 test: migrate stage2 independent compile errors to test manifest parser 2022-04-28 18:35:01 +02:00
Jakub Konka
3c19f694d9 test: fix incorrect error loc in assert_function x86_64-linux test 2022-04-28 18:35:01 +02:00
Jakub Konka
2875216f8e test: fix x86_64-macos failures
This is just a temporary fix - I would like to unify all of x86_64
tests across linux and macos OSes.
2022-04-28 18:35:01 +02:00
Jakub Konka
5a5648c0f0 test: migrate llvm incremental tests 2022-04-28 18:35:01 +02:00
Jakub Konka
2cd456f8f4 test: correctly handle multiple backends
To correctly handle multiple backends crossed with multiple targets,
we need to push all elements in separate allocated arrays rather
than operate on raw iterators. Hence, introduce `getConfigForKeyAlloc`.
2022-04-28 18:35:01 +02:00
Jakub Konka
495bb12e6a test: migrate plan9 and sparcv9 incremental tests 2022-04-28 18:35:01 +02:00
Jakub Konka
ed51a5d02a test: migrate arm incremental tests 2022-04-28 18:35:01 +02:00
Jakub Konka
fc4fbfe8e1 test: migrate aarch64 incremental tests 2022-04-28 18:35:01 +02:00
Jakub Konka
7e17cbbda5 test: migrate riscv64 incremental tests 2022-04-28 18:35:01 +02:00
Jakub Konka
8e05e6a1ed test: migrate wasm incremental tests 2022-04-28 18:35:01 +02:00
Jakub Konka
815dc2c6e7 test: enable wasm32-wasi incremental tests 2022-04-28 18:35:01 +02:00
Jakub Konka
8d5acf7693 test: recursively walk dir with tests
Prune incremental tests by moving non-incremental behavior tests to
behavior test suite instead.
2022-04-28 18:35:01 +02:00
Jakub Konka
c8a0d8ff2b ci: ignore fmt errors in test/incremental/ 2022-04-28 18:35:01 +02:00
Jakub Konka
e4a8a66504 test: remove incremental tests that were ported to the new harness 2022-04-28 18:35:01 +02:00
Jakub Konka
97b781955e test: fix incorrect default target spec; port all incremental tests 2022-04-28 18:35:01 +02:00
Jakub Konka
133708d939 test: leave a todo note to explicitly specify ABI for targets in the future 2022-04-28 18:35:01 +02:00
Jakub Konka
0998185f77 test: adjust error location for assert_function test 2022-04-28 18:35:01 +02:00
Jakub Konka
81e90c7acb test: fix pointer invalidation bug in the harness 2022-04-28 18:35:01 +02:00
Jakub Konka
c1a98cd65d test: set case name from initial filename for a sequence
Port more incremental tests.
2022-04-28 18:35:01 +02:00
Jakub Konka
46db5e2a44 test: unroll into multiple cases, provide default parsers
Provide default parsers for obvious config options such as
`CrossTarget` or `Backend` (or any enum for that matter).

Unroll iterator loops into multiple cases - we need to create
a Cartesian product for all possibilities specified in the
test manifest.
2022-04-28 18:35:01 +02:00
Jakub Konka
bc370311cb test: add comptime struct holding default config values 2022-04-28 18:35:01 +02:00
Jakub Konka
f41dd3617e test: pass Strategy per directory of tests 2022-04-28 18:35:01 +02:00
Jakub Konka
d305a6fb55 test: parse all of manifest in TestManifest abstraction 2022-04-28 18:35:01 +02:00
Jakub Konka
d8d12d51ec test: abstract away test manifest parser into separate struct 2022-04-28 18:35:01 +02:00
Jakub Konka
d5fcb50988 fmt: fix formatting of lib/std/x/net/bpf.zig 2022-04-28 18:34:37 +02:00
Veikka Tuominen
6d48600ea0 Merge pull request #10717 from gh-fork-dump/seccomp-bits
Add Seccomp bits for linux
2022-04-28 18:54:09 +03:00
Veikka Tuominen
75c9936737 Merge pull request #11214 from iddev5/ay-build-runner
std: explicitly handle error.UnexpectedExitCode in build_runner
2022-04-28 18:38:44 +03:00
matu3ba
7f13f5cd5f std.testing: add writeZigFile for TmpDir
* remove need for manual string concatenation for building binaries in test blocks
* include small program snippet to show how to get binary path with subslicing
2022-04-28 18:37:30 +03:00
Erik Hugne
8e3add8736 std.build: make no_dll_export_fns accessible in build step 2022-04-28 18:34:15 +03:00
Erik Hugne
f7bc8900bf std.coff: parse out codebase and entrypoint from optionalheader 2022-04-28 18:31:20 +03:00
Veikka Tuominen
f8940a05ae TypedValue: pretty print slices 2022-04-28 17:48:05 +03:00
Veikka Tuominen
095d51164f Sema: fix slice field modification at comptime 2022-04-28 17:45:33 +03:00
Andrew Kelley
11911f55a7 stage1: fix incorrect struct padding
Before this change, struct {f80, f80} targeting i386-windows-msvc lowers
to

```llvm
%"std.testing.struct:78:61.6" = type { x86_fp80, [6 x i8], x86_fp80, [6 x i8] }
```

which has an incorrect ABI size of 40. After this change, the struct
lowers to

```llvm
%"std.testing.struct:78:61.6" = type { x86_fp80, [4 x i8], x86_fp80, [4 x i8] }
```

which has the correct ABI size of 32, and properly aligns the second
field to 16 bytes.

The other place that calculates field padding (lowering of constant
values in codegen.cpp) already correctly calls LLVMABISizeOfType
rather than LLVMStoreSizeOfType.

This fixes the compiler-rt tests for i386-windows in this branch.
2022-04-27 23:35:56 -07:00
Andrew Kelley
9d098657a0 stage1: fix i386-windows f80 sizeof/alignof 2022-04-27 22:57:12 -07:00
Andrew Kelley
f7f03c699d compiler-rt: provide actual sincos implementations 2022-04-27 22:37:07 -07:00
Andrew Kelley
0b2ed45f5f compiler-rt: inline sin and cos into sincos
This avoids the optimizer turning sincos into a recursive call to
itself.
2022-04-27 20:24:08 -07:00
Andrew Kelley
0ffe82e624 std: use float builtins instead of std.math 2022-04-27 19:35:28 -07:00
Andrew Kelley
c26f7550f0 stage1: add missing comptime float ops
These are only as accurate as f64 even for f128 comptime functions. This
is OK for now; improvements will come with the launch of self-hosted
(#89) and enhancements to compiler-rt implementations.
2022-04-27 19:34:33 -07:00
Andrew Kelley
7d8067878d disable failing behavior test
This is a new test added in this branch but it is not yet passing for
i386-windows with the stage1 compiler.
2022-04-27 18:41:53 -07:00
Andrew Kelley
1cd799317b compiler-rt: remove invalid test
This was leftover from testing std.math.sin
2022-04-27 18:28:33 -07:00
Andrew Kelley
51f8ce1825 compiler-rt: fix powerpc f128 suffix 2022-04-27 18:26:47 -07:00
Andrew Kelley
1ac21cdec5 compiler-rt: avoid symbol conflicts
Weak aliases don't work on Windows, so we avoid exporting the `l` alias
on this platform for functions we know will collide.
2022-04-27 18:14:44 -07:00
Andrew Kelley
dc62dde982 behavior test: use expectApproxEqAbs instead of expectEqual
This is to account for the small differences in math functions of
different libcs. For example, if the compiler links against glibc,
but the target is musl libc, then these values might be
slightly different.

Arguably, this is a bug in the compiler because comptime should
emulate the target, including rounding errors in libc math
functions. However that behavior is not what this particular test
is intended to cover.
2022-04-27 17:58:26 -07:00
Andrew Kelley
758ec9bdd4 enable newly passing behavior tests
closes #11030
2022-04-27 17:24:36 -07:00
Andrew Kelley
09f1d62bdf add new builtin function @tan
The reason for having `@tan` is that we already have `@sin` and `@cos`
because some targets have machine code instructions for them, but in the
case that the implementation needs to go into compiler-rt, sin, cos, and
tan all share a common dependency which includes a table of data. To
avoid duplicating this table of data, we promote tan to become a builtin
alongside sin and cos.

ZIR: The tag enum is at capacity so this commit moves
`field_call_bind_named` to be `extended`. I measured this as one of
the least used tags in the zig codebase.

Fix libc math suffix for `f32` being wrong in both stage1 and stage2.
stage1: add missing libc prefix for float functions.
2022-04-27 16:45:23 -07:00
Andrew Kelley
c4eaff6665 disable failing behavior tests 2022-04-27 14:29:59 -07:00
Andrew Kelley
087aedfa38 stage2: fix recent LLVM backend code
* std.math.snan: fix compilation error. Also make it and nan inline.
 * LLVM: use a proper enum type for float op instead of enum literal.
   Also various cleanups.
 * LLVM: use LLVMBuildVectorSplat for vector splat AIR instruction.
   - also the bindings had parameter order wrong
 * LLVM: additionally handle f16 lowering. For now all targets report OK
   but I think we will need to add some exceptions to this list.
2022-04-27 14:18:34 -07:00
Cody Tapscott
7d6a6ce87f stage2: Manually lower softfloat ops when needed
Updates stage2 to manually lower softfloat operations for all unary
floating point operations and arithmetic.

Softfloat support still needs to be added for conversion operators
(float<->float and int<->float)
2022-04-27 12:22:20 -07:00
Cody Tapscott
0e8242b905 stage1: Manually lower softfloat ops when needed
Updates stage1 to manually lower softfloat operations for all unary
floating point operations, extension/truncation, and arithmetic.
2022-04-27 12:22:09 -07:00
Andrew Kelley
41dd2beaac compiler-rt: math functions reorg
* unify the logic for exporting math functions from compiler-rt,
   with the appropriate suffixes and prefixes.
   - add all missing f128 and f80 exports. Functions with missing
     implementations call other functions and have TODO comments.
   - also add f16 functions
 * move math functions from freestanding libc to compiler-rt (#7265)
 * enable all the f128 and f80 code in the stage2 compiler and behavior
   tests (#11161).
 * update std lib to use builtins rather than `std.math`.
2022-04-27 12:20:44 -07:00
Isaac Freund
6f4343b61a std: replace usage of std.meta.bitCount() with @bitSizeOf() 2022-04-27 11:10:52 +02:00
Isaac Freund
6c0719fd5f std.meta: deprecate bitCount() for @bitSizeOf() 2022-04-27 11:10:52 +02:00
Jimmi Holst Christensen
cea310c908 Remove usage of inline for from print_targets.cmdTargets
This function was one of the biggest zig functions in a debug build of
the compiler.

  $ bloaty stage3-debug/bin/zig -d symbols --tsv -n 10000000 |
      rg -v '(llvm|clang|std|lld|\(anonymous namespace\))::|\[section ' |
      sort -h -k 3

  ...
  translate_c.ast.renderNode                    86168   86219
  main.buildOutputType                         177959  178004
  InfoTable                                    184832  184870
  AArch64SVEIntrinsicMap                       188544  188596
  print_targets.cmdTargets__anon_4735          319156  319216
  __static_initialization_and_destruction_0()  486666  489582
  MatchTable1                                  621884  621997
  OperandMatchTable                           1139622 1139861
  MatchTable0                                 1899764 1900141
2022-04-26 17:52:21 -04:00
protty
18f3034629 std.Thread: ResetEvent improvements (#11523)
* std: start removing redundant ResetEvents

* src: fix other uses of std.Thread.ResetEvent

* src: add builtin.sanitize_thread for tsan detection

* atomic: add Atomic.fence for proper fencing with tsan

* Thread: remove the other ResetEvent's and rewrite the current one

* Thread: ResetEvent docs

* zig fmt + WaitGroup.reset() fix

* src: fix build issues for ResetEvent + tsan

* Thread: ResetEvent tests

* Thread: ResetEvent module doc

* Atomic: replace llvm *p memory constraint with *m

* panicking: handle spurious wakeups in futex.wait() when waiting for abort()

* zig fmt
2022-04-26 16:48:56 -05:00
Andrew Kelley
50f1856476 Merge pull request #11336 from wsengir/stage2-optimize-intcast
Sema: combine signed->unsigned and shrinkage runtime checks in intCast
2022-04-26 13:20:19 -04:00
Andrew Kelley
0324975d1d Merge pull request #11526 from topolarity/f80-div
compiler_rt: Implement `__divxf3` and `fmodx`
2022-04-26 13:05:30 -04:00
Luuk de Gram
5f2d0d414d wasm: Implement codegen for C-ABI
This implements passing arguments and storing return values correctly
for the C-ABI as specified by the tool-convention:
https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md

There's definitely room for better codegen in follow-up commits.
2022-04-26 12:20:27 +02:00
Luuk de Gram
cb49af6c9a wasm: Initial C-ABI implementation
This implements the C-ABI convention as specified by:
https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md
While not an official specification, it's the ABI that is output by clang/LLVM.
As we use LLVM to compile compiler-rt, and want to integrate with C-libraries,
we follow the same convention when the calling convention results in 'C'.
2022-04-26 12:20:27 +02:00
Cody Tapscott
28c05b0a53 compiler_rt: Bypass fmodx impl. on stage2
This function is codegen'd incorrectly in stage2, since it fails to
generate the correct soft-float operations. This will be fixed once
issue #11161 is implemented
2022-04-25 19:38:59 -07:00
Cody Tapscott
96d86e3465 compiler_rt: Fix rounding edge case for __mulxf3 2022-04-25 17:21:09 -07:00
Cody Tapscott
f5540778b5 stdlib: Fix hex-float printing for f80 2022-04-25 17:21:09 -07:00
Cody Tapscott
d930e015c7 compiler_rt: Implement __divxf3 for f80 2022-04-25 17:21:09 -07:00
Cody Tapscott
6c0114e044 compiler_rt: Implement fmodx for f80 2022-04-25 17:21:05 -07:00
Andrew Kelley
ab658e32bd Sema: fix export with Internal linkage
The Export tables should only be populated with non-internal exports.
2022-04-24 20:24:37 -07:00
jagt
76311aebff std: fix crypto and hash benchmark 2022-04-24 23:01:06 -04:00
protty
963ac60918 std.Thread: Mutex and Condition improvements (#11497)
* Thread: minor cleanups

* Thread: rewrite Mutex

* Thread: introduce Futex.Deadline

* Thread: Condition rewrite + cleanup

* Mutex: optimize lock fast path

* Condition: more docs

* Thread: more mutex + condition docs

* Thread: remove broken Condition test

* Thread: zig fmt

* address review comments + fix Thread.DummyMutex in GPA

* Atomic: disable bitRmw x86 inline asm for stage2

* GPA: typo mutex_init

* Thread: remove noalias on stuff

* Thread: comment typos + clarifications
2022-04-23 19:35:56 -05:00
Morritz
daef82d06f add GetProcessTimes binding to the kernel32.zig (#11488) 2022-04-23 16:58:27 -05:00
William Sengir
eac09ac350 CBE: disable int128 test since airWrapOp is needed for runtime safety 2022-04-22 22:22:30 -07:00
William Sengir
fa42fcbc1a Sema: combine signed->unsigned and shrinkage runtime checks in intCast 2022-04-22 22:08:16 -07:00
Andrew Kelley
cf20b97b71 Merge pull request #11279 from igor84/s1_packed_struct
stage1: Fix packed structs (#2627, #10104)
2022-04-22 11:39:12 -04:00
Andrew Kelley
06310e3d4e Revert "Fix C include files not being in whole cache (#11365)"
This reverts commit a430630002.

Wait a minute, I'm sorry, I need to revert this. The whole premise
of this change is broken because the point of the hash is that it tells
whether the same compilation has been done before. This requires items
to be added to the hash in the same sequence every time. This means that
introducing a lock is fundamentally broken because the order needs to be
the same in future runs of the compiler, and not decided by threads
racing against each other.

The proper solution to this is to, in whole cache mode, append the hash
inputs to some data structure, and then after the compilation is
complete, do some kind of sorting on the hash inputs so that they will
be the same order every time, then apply them in sequence. No lock on
the Cache object is needed for this scheme.
2022-04-22 08:19:51 -07:00
Tom Read Cutting
a430630002 Fix C include files not being in whole cache (#11365) 2022-04-22 11:12:51 -04:00
Andrew Kelley
42e81cd81b Merge pull request #11377 from AnnikaCodes/11368
C backend: Fix array declarations
2022-04-22 10:55:41 -04:00
Andrew Kelley
0e830b1630 clean up behavior tests
Split big test into the two separate things it is testing.
Add missing checks to the test which revealed the test is not actually
passing yet for the C backend.
2022-04-22 07:52:21 -07:00
Annika L
c992b25908 C backend: Fix array declarations 2022-04-22 07:42:47 -07:00
Jakub Konka
5da0e03553 Merge pull request #11480 from rabingaire/fix-child-process-hang-on-macos
Fix child process spawn on macos hangs with stdin, stdout behavior set to pipe
2022-04-22 07:26:51 +02:00
Jakub Konka
5c501e8dad Merge pull request #11485 from ziglang/fix-4353 2022-04-22 06:34:06 +02:00
Andrew Kelley
9c5fe5b5a4 LLVM: C calling convention lowering fixes
For parameters and return types of functions with the C calling
convention, the LLVM backend now has a special lowering for the function
type that makes the function adhere to the C ABI. The AIR instruction
lowerings for call, ret, and ret_load are adjusted to bitcast the real
type to the ABI type if necessary.

More work on this will need to be done, however, this improvement is
enough that stage3 now passes all the same behavior tests that stage2
passes - notably, translate-c no longer has a segfault due to C ABI
issues with Zig's Clang C API wrapper.
2022-04-21 20:27:06 -07:00
Andrew Kelley
804d0661f5 Merge pull request #11448 from ziglang/ci-stage3
CI: additionally test building stage3
2022-04-21 18:57:59 -04:00
Andrew Kelley
ffaa045429 stage2: add zig_backend to the cache hash
This makes stage2 and stage3 have different cache namespaces, so that
building something with stage3 does not try to reuse the same cached
artifacts as were produced by stage2. This makes sense since the code
of stage3 is produced by the self-hosted compiler, whereas the code of
stage2 is produced by the bootstrap compiler. Note also that stage4 and
stage3 will share the same zig_backend, end hence cache namespace.
Ideally stage4 and stage3 are identical binaries, so this checks out.
2022-04-21 13:29:46 -07:00
Jakub Konka
74bfb8ba07 pdb: fix resource mgmt 2022-04-21 21:53:29 +02:00
Yusuf Bham
41654a318d std.mem: add concatWithSentinel 2022-04-21 14:39:41 -04:00
6d0283e6bc [doc update] add size_t (#11482)
For those souls looking for a zig `size_t` equivalent, and not
lucky/educated enough (that was me yesterday) to know it's the same as
`uintptr_t`.

From a recent discussion on IRC.
2022-04-21 14:33:42 -04:00
Andrew Kelley
ebfddbaf00 CI: additionally test building stage3 2022-04-21 11:20:26 -07:00
Jakub Konka
42ed34d1f6 macho: create LlvmObject in createEmpty only
Prior to this change we would also create it in `openPath`, but as
`openPath` internally calls `createEmpty` we would end up with a
memory leak.
2022-04-21 10:08:37 -04:00
Andrew Kelley
bd5831ce0e Merge pull request #11467 from ziglang/segmented-list-decls
stage2: use indexes for Decl objects
2022-04-21 09:49:20 -04:00
Jakub Konka
bedd7efa2b debug: add smoke test 2022-04-21 11:51:38 +02:00
Jakub Konka
28ca203b71 debug: fix resource (de)allocation for Elf and Coff targets
With this change, it is now possible to safely call
`var di = std.debug.openSelfDebugInfo(gpa)`. Calling then
`di.deinit()` on the object will correctly free all allocated
resources.

Ensure we store the result of `mmap` with correct alignment.
2022-04-21 11:48:15 +02:00
Rabin Gaire
50ec55faaf ran zig fmt on changes 2022-04-21 14:12:08 +05:45
Rabin Gaire
4ece507b5a update test message and using unreachable keyword for unintended test code path 2022-04-21 13:28:41 +05:45
Andrew Kelley
31758f79db link: Wasm: don't assume we have a zig module 2022-04-20 18:14:38 -07:00
Andrew Kelley
f7596ae942 stage2: use indexes for Decl objects
Rather than allocating Decl objects with an Allocator, we instead allocate
them with a SegmentedList. This provides four advantages:
 * Stable memory so that one thread can access a Decl object while another
   thread allocates additional Decl objects from this list.
 * It allows us to use u32 indexes to reference Decl objects rather than
   pointers, saving memory in Type, Value, and dependency sets.
 * Using integers to reference Decl objects rather than pointers makes
   serialization trivial.
 * It provides a unique integer to be used for anonymous symbol names,
   avoiding multi-threaded contention on an atomic counter.
2022-04-20 17:37:35 -07:00
Andrew Kelley
4f527e5d36 std: fix missing hash map safety
There was a missing compile error for calling ensureUnusedCapacity
without a Context in the case that the Context is non-void.
2022-04-20 17:18:06 -07:00
Jakub Konka
96c1314443 debug: fix resource (de)allocation for MachO targets
With this change, it is now possible to safely call
`var di = std.debug.openSelfDebugInfo(gpa)`. Calling then
`di.deinit()` on the object will correctly free all allocated
resources.
2022-04-21 00:45:01 +02:00
Jakub Konka
26153ce73a dwarf: clean up allocations in std.dwarf module
While this code probably could do with some love and a redesign,
this commit fixes the allocations by making sure we explicitly
pass an allocator where required, and we use arenas for temporary
or narrowly-scoped objects such as a `Die` (for `Die` in particular,
not every `FormValue` will be allocated - we could duplicate, or
we can use an arena which is the proposal of this commit).
2022-04-21 00:06:52 +02:00
Rabin Gaire
d976456ef6 add test case for child_process spawn logic
tests creating a child process with stdin/stdout behavior set to
StdIo.Pipe.
2022-04-20 18:37:10 +05:45
Andrew Kelley
99112b63bd std.SegmentedList: breaking API changes
* Remove the Allocator field; instead it must be passed in as a
   parameter to any function that needs it.
 * Rename `push` to `append` and `pushMany` to `appendSlice` to match
   the conventions set by ArrayList.
2022-04-20 05:31:24 -07:00
Andrew Kelley
711bf55eaa std: bring back SegmentedList
I want to use it for the self-hosted compiler.
2022-04-20 05:31:24 -07:00
Rabin Gaire
9e4cd1f4e6 fix child process spawn on macos hangs issue
When a child process with stdin, stdout behavior set to pipe is
ran on macos it used to hang which has been fixed. Issue existed because
we forgot to call `posix_spawn_file_actions_addclose` syscall on user
exposed file descriptor which resulted on file descriptor not closing
properly.
2022-04-20 18:02:41 +05:45
Joachim Schmidt
1a1b5ee264 Merge pull request #11462 from joachimschmidt557/stage2-aarch64
stage2 AArch64: truncation support
2022-04-20 09:44:43 +02:00
protty
e3cbea934e std.Thread.Futex improvements (#11464)
* atomic: cache_line

* Thread: Futex rewrite + more native platform support

* Futex: tests compile

* Futex: compiles and runs test

* Futex: broadcast test

* Futex: fix PosixImpl for tests

* Futex: fix compile errors for bsd platforms

* Futex: review changes + fix timeout=0 + more comments
2022-04-19 19:42:15 -05:00
Yusuf Bham
2fa7f6e502 std.os.uefi: Add BlockIoProtocol 2022-04-19 19:51:19 -04:00
Robin Voetter
859ae152bc array hash map: fix getOrPutAdapted on Managed array hash map 2022-04-19 19:41:12 -04:00
Andrew Kelley
0c5ad335d2 build system: add -fstage1/-fno-stage1 to zig build
So that people can start experimenting with compiling their projects
with the self-hosted compiler.

I expect this commit to be reverted after #89 is closed.
2022-04-19 14:40:27 -07:00
joachimschmidt557
fa85a739d9 stage2 AArch64: fix shl, shr, shl_exact, shr_exact
Introduces the necessary truncation after shift
2022-04-19 22:40:51 +02:00
joachimschmidt557
cbb13c023e stage2 AArch64: change binOp lowering mechanism to use Mir tags
Mirrors e2e69803dc for AArch64
2022-04-19 22:40:50 +02:00
joachimschmidt557
0a909a6712 stage2 AArch64: implement addwrap, subwrap, mulwrap 2022-04-19 22:40:50 +02:00
joachimschmidt557
d9d9fea6ae stage2 AArch64: Add ldrsb, ldrsh instructions 2022-04-19 22:40:48 +02:00
joachimschmidt557
f95a8ddafa stage2 AArch64: Implement basic truncate functionality 2022-04-19 22:39:14 +02:00
joachimschmidt557
c78daeb642 stage2 AArch64: add basic assertions to bits.zig for correct codegen
Includes many fixes of errors discovered by adding these assertions
2022-04-19 22:37:56 +02:00
Andrew Kelley
9c2cbe39c2 Merge pull request #11461 from Luukdegram/wasm-debug-info
Wasm: add support for debug information
2022-04-19 14:12:13 -04:00
Luuk de Gram
be08d2bdbd wasm: Fix unreachable paths
When the last instruction is a debug instruction, the type of it is void.
Similarly for 'noreturn' emit an 'unreachable' instruction to tell the wasm-validator
the path cannot be reached.

Also respect the '--strip' flag in the self-hosted wasm linker and not emit a 'name' section
when the flag is set to `true`.
2022-04-19 19:58:49 +02:00
Andrew Kelley
78f26b970e Merge pull request #11469 from topolarity/wasm-fixup
stage2: Move `selfExePathWasi` to `introspect.zig`
2022-04-19 13:30:15 -04:00
Andrew Kelley
535d5624e4 wasm: fix lowerDeclRefValue using wrong Decl 2022-04-19 13:04:59 -04:00
Andrew Kelley
f3b3d7f20a Merge pull request #11468 from topolarity/f80-mul
compiler_rt: Implement softfloat multiply for `f80`
2022-04-19 13:04:31 -04:00
Cody Tapscott
f8dc6fc416 stage2: Only bypass flock on WASI 2022-04-18 23:08:00 -07:00
Cody Tapscott
bb9cd6db1c stage2: Move WASI/Zig-specific selfExePath to introspect.zig 2022-04-18 23:06:49 -07:00
Cody Tapscott
b2950866b1 compiler_rt: Fix rounding/NaN handling for f80 add/sub
There were a few minor bugs in the rounding behavior and Inf/NaN
handling for the f80 __addxf3 and __subtf3 functions.

This change updates the original generic implementation to correctly
handle f80 floats, including the explicit integer bit.
2022-04-18 21:45:46 -07:00
Cody Tapscott
d760cae2b1 compiler_rt: implement __mulxf3 for f80 2022-04-18 20:46:03 -07:00
Andrew Kelley
edb4a07d4d Sema: fix not reserving enough memory for comptime shl 2022-04-18 16:41:54 -07:00
Andrew Kelley
c9858f833c stage2: fix building stage3 in release mode
Previously, comptime function calls could cause a crash in the hash
function due to a lazy value depending on an unresolved type.
2022-04-18 16:41:54 -07:00
Andrew Kelley
b75d86027d stage2: avoid binary bloat from GeneralPurposeAllocator
In the case of not using it.
2022-04-18 16:41:54 -07:00
Jakub Konka
b03345f32a Merge pull request #11024 from topolarity/wasi-stage2
stage2: Add limited WASI support for selfExePath and globalCacheDir
2022-04-18 23:53:41 +02:00
Jakub Konka
5195b87639 Merge pull request #11396 from wojtekmach/wm-zig-cc-subsystem
zig cc: support --subsystem linker flag
2022-04-18 19:20:23 +02:00
Cody Tapscott
3a63fa6b7f stage2: Add 'zig.wasm' fallback for binary name 2022-04-18 10:20:20 -07:00
Cody Tapscott
692ccd01b4 stage2: Initialize WASI preopens on startup 2022-04-18 10:20:20 -07:00
Cody Tapscott
089651716c stage2: Bypass file locks in src/Cache.zig for WASI targets 2022-04-18 10:20:15 -07:00
Cody Tapscott
922d8378e7 stage2: Add limited WASI support for selfExePath and globalCacheDir
This change adds support for locating the Zig executable and the library
and global cache directories, based on looking in the fixed "/zig" and
"/cache" directories.

Since our argv[0] on WASI is just the basename (any absolute/relative
path information is deleted by the runtime), there's very limited
introspection we can do on WASI, so we rely on these fixed directories.
These can be provided on the command-line using `--mapdir`, as follows:

```
wasmtime --mapdir=/cwd::. --mapdir=/cache::"$HOME/.cache/zig" --mapdir=/zig::./zig-out/ ./zig-out/bin/zig.wasm
```
2022-04-18 10:19:34 -07:00
Luuk de Gram
2193f7c4a2 wasm: Add support for debug info
This implements basic DWARF output when building for the wasm target.
Stacktraces, however, are currently not supported.
2022-04-18 13:11:37 +02:00
Wojtek Mach
b2344cc18e Support --subsystem=x instead of --subsystem,x 2022-04-18 11:43:17 +02:00
Ryan Liptak
f8d2b87fa1 Update doc comment of ArrayHashMap to include 4th arg in eql fns
4th argument was added in cf88cf2657
2022-04-18 03:47:03 -04:00
Andrew Kelley
a7c05c06be stage2: expose progress bar API to linker backends
This gives us insight as to what is happening when we are waiting for
things such as LLVM emit object and LLD linking.
2022-04-17 04:09:35 -07:00
Yusuf Bham
2aeaa1cfc4 std.os.uefi: fix GUID formatting (#11452) 2022-04-17 06:15:15 -04:00
Cody Tapscott
7b090df668 stdlib std.os: Improve wasi-libc parity for WASI CWD emulation
Two major changes here:
  1. We store the CWD as a simple `[]const u8` and lookup Preopens for
     every absolute or CWD-referenced file operation, based on the
     Preopen with the longest match (i.e. most specific path)
  2. Preorders are normalized to POSIX absolute paths at init time.
     Behavior depends on the "cwd_root" parameter of `initPreopensWasi`:

	`cwd_root` is used for any Preopens that start with "."

	  For example:
            "./foo/bar" - inits to -> "{cwd_root}/foo/bar"
            "foo/bar"   - inits to -> "/foo/bar"
	    "/foo/bar"  - inits to -> "/foo/bar"

        `cwd_root` must be an absolute path.

	Using "/" as `cwd_root` gives behavior similar to wasi-libc.
2022-04-16 18:08:05 +02:00
Jakub Konka
8f75823728 Merge pull request #11446 from ziglang/aarch64-macos-llvm
stage2: fix behavior test failures on aarch64-macos (LLVM+native), and other minor fixes
2022-04-16 18:07:02 +02:00
Andrew Kelley
a315d51c0a Merge pull request #11437 from koachan/sparc64-mutex
compiler_rt: atomics: Add TAS lock support for SPARC
2022-04-16 06:36:54 -04:00
Andrew Kelley
e428f85cfd Merge pull request #11445 from viriuwu/f80-freebsd-tests
re-enable f80 tests on freebsd
2022-04-16 06:26:14 -04:00
Jakub Konka
897df18573 stage2: fix @mulAdd on aarch64 Darwin
According to Apple docs, the long double type is a double precision
IEEE754 binary floating-point type, which makes it identical to the
double type. This behavior contrasts to the standard specification,
in which a long double is a quad-precision, IEEE754 binary,
floating-point type.

Thus, we need to take this into account when using the compiler
intrinsics so that we select the correct function version for
FloatMulAdd.
2022-04-16 12:23:47 +02:00
Andrew Kelley
ec8a6544a3 Merge pull request #11444 from kprotty/treap
Introduce std.Treap
2022-04-16 06:23:18 -04:00
Jakub Konka
1b5a43fdf7 start.zig: make sure macos uses full startup code 2022-04-16 12:07:34 +02:00
Jakub Konka
88d87d6506 stage2,macho: swap out inodes before checking for intermediary basename
This way we avoid the infamous SIGKILL on arm64 macos.
2022-04-16 12:06:58 +02:00
Andrew Kelley
578a792b33 Merge pull request #11442 from Vexu/stage3
Make self hosted compiler capable of building itself
2022-04-16 05:42:25 -04:00
joachimschmidt557
3bfb1616db stage2 ARM: move genArgDbgInfo back to CodeGen
This removes the questionable Air -> Mir dependency that existed
before. The x86_64 backend also performed this change.
2022-04-16 09:41:27 +02:00
vi
4ad1480298 std.math.fabs: enable f80 testing 2022-04-15 16:52:02 -06:00
vi
2ef9a0d9ae std.math: enable f80 tests on freebsd 2022-04-15 16:50:00 -06:00
kprotty
33952dad12 treap: zig fmt 2022-04-15 17:01:01 -05:00
kprotty
4d0303b992 treap: fix + determinstically randomize test cases. 2022-04-15 16:30:45 -05:00
Veikka Tuominen
101aac92c2 stage2: fix bugs preventing stage2 from building stage3 with LLVM 2022-04-15 23:32:26 +03:00
kprotty
7284eb22dc treap: initial implementation 2022-04-15 15:26:51 -05:00
Veikka Tuominen
1c4c826a50 AstGen: fix defer generation in breakExpr 2022-04-15 22:33:07 +03:00
Veikka Tuominen
7be62f695f stage2 llvm: fix optional pointers to zero bit payloads 2022-04-15 19:17:50 +03:00
Andrew Kelley
4c83b11f71 Merge pull request #11438 from Vexu/stage2-fixes
Stage2 fixes
2022-04-15 12:02:55 -04:00
Rekai Musuka
02a43f325b std/math.zig: resolve missed optimization in rotates 2022-04-15 11:51:50 -04:00
Jakub Konka
52c8ac1a84 stage2: lower u128, and refactor some bits in x64 2022-04-15 11:50:08 -04:00
Veikka Tuominen
dbe0d3d579 stage2 llvm: handle dollar signs in asm template 2022-04-15 16:16:22 +03:00
Veikka Tuominen
ef7282bab4 stage2 macho: workaround stage2 bugs 2022-04-15 16:05:27 +03:00
Koakuma
33956b8e55 compiler_rt: atomics: clr -> clrb 2022-04-15 19:48:25 +07:00
Koakuma
fac2a2e754 compiler_rt: atomics: Formatting change for flag definition 2022-04-15 19:44:46 +07:00
Koakuma
5b283fba77 compiler_rt: atomics: Add Leon CAS instruction check for SPARC atomics 2022-04-15 19:40:36 +07:00
Koakuma
6aa89115f9 ompiler_rt: atomics: Split long lines and add comment on constants 2022-04-15 19:31:55 +07:00
iddev5
d9f9948b65 std.build: add test for issue 10381 2022-04-15 17:44:34 +05:30
Veikka Tuominen
3723eb7f31 Merge pull request #11242 from schmee/sema-handle-more-union-errors
stage2: add more union compile errors / improve error messages
2022-04-15 11:34:04 +03:00
r00ster91
62d717e2ff Add std.unicode.replacement_character 2022-04-15 11:20:11 +03:00
Evan Haas
618398b7d3 std.fs: prevent possible integer overflow in Dir.makePath
The call to `makeDir` for the top-level component of `sub_path`
can return `error.FileNotFound` if the directory represented by
`self` has been deleted.

Fixes #11397
2022-04-15 11:19:23 +03:00
Veikka Tuominen
845a30624f std: add workaround for stage2 bug 2022-04-15 11:17:19 +03:00
Veikka Tuominen
6ad510d832 update self hosted sources to language changes 2022-04-15 11:17:19 +03:00
Veikka Tuominen
4911d39769 AstGen: handle rl_ty_inst for mutable variables 2022-04-15 11:17:06 +03:00
Veikka Tuominen
4ef1c1c705 Sema: allow fieldType on optionals and error unions 2022-04-15 10:24:18 +03:00
Koakuma
274e2a1ef1 compiler_rt: atomics: Add TAS lock support for SPARC
Some SPARC CPUs (particularly old and/or embedded ones) only has atomic
TAS instruction available (`ldstub`). This adds support for emitting
that instruction in the spinlock.
2022-04-15 08:09:57 +07:00
Luuk de Gram
d66c61a2cf wasm-linker: Prevent overalignment for segments
Previously, the data segments were being aligned twice.
This caused us to overalign the segment and therefore allocate a much larger
size for each segment than was required. This fix ensures we align and set the size
just once, ensuring semantically correct binaries as well as smaller binaries.
2022-04-14 22:53:13 +02:00
Luuk de Gram
cf37101108 wasm-linker: Add function table indexes
When linking with an object file, verify if a relocation is a table index relocation.
If that's the case, add the relocation target to the function table.
2022-04-14 22:53:13 +02:00
Luuk de Gram
321a164269 wasm-linker: Fix memory leak
This fixes a memory leak when an object file contains one or more element sections which
then contains one or more function indexes. This commit ensures the slice of index functions
for each element section will be freed upon resource deallocation also.
2022-04-14 22:53:13 +02:00
Jakub Konka
2635e4ca6e Merge pull request #11434 from koachan/sparc64-codegen 2022-04-14 21:38:35 +02:00
Jakub Konka
35171dd3db Merge pull request #11433 from ziglang/elf-fixes
elf: support `--strip` option and set symtab size when writing globals
2022-04-14 20:04:29 +02:00
Andrew Kelley
2587474717 stage2: progress towards stage3
* The `@bitCast` workaround is removed in favor of `@ptrCast` properly
   doing element casting for slice element types. This required an
   enhancement both to stage1 and stage2.
 * stage1 incorrectly accepts `.{}` instead of `{}`. stage2 code that
   abused this is fixed.
 * Make some parameters comptime to support functions in switch
   expressions (as opposed to making them function pointers).
 * Avoid relying on local temporaries being mutable.
 * Workarounds for when stage1 and stage2 disagree on function pointer
   types.
 * Workaround recursive formatting bug with a `@panic("TODO")`.
 * Remove unreachable `else` prongs for some inferred error sets.

All in effort towards #89.
2022-04-14 10:12:45 -07:00
Koakuma
c07213269f stage2: zig fmt 2022-04-14 23:26:03 +07:00
Koakuma
e791f062ba stage2: sparcv9: Load tests to the list of testcases 2022-04-14 23:24:46 +07:00
Koakuma
2ee83e76f7 stage2: Adjust line numbers in tests 2022-04-14 23:15:56 +07:00
Koakuma
9201fbe85b stage2: sparcv9: Add cmp_lt_errors_len AIR inst & fix asm parsing 2022-04-14 22:34:51 +07:00
Koakuma
f6b95166eb stage2: sparcv9: Add simple test case 2022-04-14 22:18:06 +07:00
Koakuma
47b136e3b3 stage2: Add SPARC function alignment
This is based on @kubkon's suggestion.
2022-04-14 22:18:06 +07:00
Koakuma
a6ce2fc3dc linker: ELF: Add page sizes for ppc64le and sparcv9 2022-04-14 22:18:06 +07:00
Koakuma
43e69be196 stage2: sparcv9: Add exit2 implementation 2022-04-14 22:18:06 +07:00
Koakuma
b916ba18b6 stage2: sparcv9: Fix Tcc encoding 2022-04-14 22:18:06 +07:00
Koakuma
dcb12a7941 stage2: sparcv9: Use regular structs to encode instructions
Currently packed structs still has endian-dependent behavior, so it results
in code that is not portable across platforms (see also issue 10113).
2022-04-14 22:18:06 +07:00
Koakuma
1467590e40 stage2: sparcv9: Implement enough instruction to compile simple exes 2022-04-14 22:18:06 +07:00
Koakuma
1f63afa7c9 stage2: sparcv9: Register the backend in stdlib & driver 2022-04-14 22:18:06 +07:00
Koakuma
cfd389f927 stage2: sparcv9: zig fmt 2022-04-14 22:18:06 +07:00
Flandre Scarlet
ab2ea9fb09 stage2: sparcv9: Test failure error logging 2022-04-14 22:18:06 +07:00
Koakuma
7051970ad7 stage2: sparcv9: implement basic instruction lowering 2022-04-14 22:18:06 +07:00
Koakuma
5e2045cbe5 stage2: sparcv9: Implement basic asm codegen 2022-04-14 22:18:06 +07:00
Koakuma
42f4bd3421 stage2: sparcv9: Add breakpoint, ret, and calling mechanism 2022-04-14 22:18:06 +07:00
Koakuma
1972a2b080 stage2: sparcv9: Add placeholders to generate a minimal program 2022-04-14 22:18:06 +07:00
Koakuma
cec48f2cf1 stage2: sparcv9: Different formatting for genBody 2022-04-14 22:18:06 +07:00
Koakuma
5ab6b5a777 stage2: sparcv9: implement dbgAdvancePCAndLine 2022-04-14 22:18:06 +07:00
Koakuma
71cd3466ec stage2: sparcv9: Adjust RegisterManager settings 2022-04-14 22:18:06 +07:00
Koakuma
18c98eb429 stage2: sparcv9: Placeholder for Air instructions in genBody 2022-04-14 22:18:06 +07:00
Koakuma
94d70bdb69 stage2: sparcv9: Change ordering in Mir Tag 2022-04-14 22:18:05 +07:00
Koakuma
94a84e783e stage2: sparcv9: Implement basic prologue/epilogue Mir emission 2022-04-14 22:18:05 +07:00
Koakuma
927706e6d0 stage2: sparcv9: Emit debug inst placeholder 2022-04-14 22:18:05 +07:00
Koakuma
cf13356dab stage2: sparcv9: Mir extraData implementation 2022-04-14 22:18:05 +07:00
Koakuma
1ba5227216 stage2: sparcv9: Initial resolveCallingConventionValues implementation 2022-04-14 22:18:05 +07:00
Koakuma
a5a89fde13 stage2: sparcv9: Add skeleton codegen impl and necessary fields 2022-04-14 22:18:05 +07:00
Koakuma
a30688ef2a stage2: sparcv9: Add some initial checks in codegen 2022-04-14 22:18:05 +07:00
Andrew Kelley
0739770739 Sema: workaround for generic instantiation recurison bug 2022-04-14 06:37:11 -07:00
Jakub Konka
4d77ef25f9 elf: check symtab section headers size when writing globals
Without this, it may happen we write the globals without extending
the symtab section header's size. This can potentially lead to
clobbering some data in the file, or simply omitting the globals
from the symtab when displaying with support tooling such as `readelf`.
2022-04-14 15:16:55 +02:00
Jakub Konka
7a00227253 elf: support --strip option
When the user passes `--strip` option on the command line, we do
not emit any debug info by skipping initializing the internal `Dwarf`
module.
2022-04-14 15:15:13 +02:00
Andrew Kelley
2a00df9c09 Sema: fix generic instantiation false negatives
The problem was that types of non-anytype parameters were being included
as part of the check to see if generic function instantiations were
equal. Now, Module.Fn additionally stores the information for whether each
parameter is anytype or not. `generic_poison` cannot be used to signal
this because the type is still needed for comptime arguments; in such
case the type will not be present in the newly generated function
prototype.

This presented one additional challenge: we need to compare equality of
two values where one of them is post-coercion and the other is not. So
we make some minor adjustments to `Type.eql` to support this. I think
this small complexity tradeoff is worth it because it means the compiler
does much less work on the hot path that a generic function is called
and there is already an existing matching instantiation.

closes #11146
2022-04-14 06:08:28 -07:00
Andrew Lee
9b82e7f558 std/bounded_array.zig: Add Writer interface 2022-04-14 02:56:40 -04:00
vi
6ad9ac59e7 std.math.float: fix f80-backed c_longdouble consts 2022-04-14 02:55:46 -04:00
Eric Shrewsberry
497f8a6098 Fix bug in PriorityQueue::removeIndex()
Fix to call siftDown on the removed index instead of always on index 0.
Updated test to a test that fails before and passes now.

PriorityDequeue does not have this issue.
2022-04-14 02:54:41 -04:00
Andrew Kelley
59fa548be8 Merge pull request #11429 from ziglang/stage2-alive-decls
stage2: fix (recursively) marking decls as alive, and improve DWARF for local vars
2022-04-14 02:01:16 -04:00
Ryan Liptak
9c509f1526 Enable passing 'Dir.rename directories' fs test on Windows
Looks like d3f87f8ac0 fixed the standard cases of dir renaming, but the edge cases (renaming onto an existing empty/non-empty directory) are still behaving differently than on non-Windows.
2022-04-13 19:55:16 +02:00
Jakub Konka
edb428fae4 macho,x64: resolve debug info relocs for RIP-based addressing
Sometimes we will want to generate debug info for a constant that
has been lowered to memory and not copied anywhere else. For this
we will need to defer resolution on PIE platforms until all locals
(including GOT entries) have been allocated.
2022-04-13 19:50:23 +02:00
Jakub Konka
3f912430bd stage2,x64: deref memory if referenced via GOT for local vars 2022-04-13 16:24:56 +02:00
Jakub Konka
0bf7283330 dwarf: gen debug info for arrays 2022-04-13 16:22:24 +02:00
Jakub Konka
4c50a27d68 stage2,x64: generate debug info for local vars at hardcoded mem addr 2022-04-13 14:31:04 +02:00
Jakub Konka
baeff1762b stage2,x64: recursively mark decls as alive when lowering 2022-04-13 13:52:01 +02:00
Cody Tapscott
aaac8eae68 Use 0-indexing for incremental compile error tests 2022-04-13 01:09:21 -04:00
Andrew Kelley
8ada446b1f Merge pull request #11407 from topolarity/float-fix
compiler_rt: Add `f80` support to `floatXiYf`/`fixXfYi`
2022-04-13 01:08:33 -04:00
Cody Tapscott
319555a669 Add floatFractionalBits to replace floatMantissaDigits 2022-04-12 12:33:16 -07:00
Andrew Kelley
7972bc8aa8 Sema: fix struct init ref 2022-04-12 12:20:08 -07:00
Andrew Kelley
ff7ef624f5 Sema: fix comptime call with generic function as parameter 2022-04-12 12:19:32 -07:00
Andrew Kelley
99657dca1f Sema: fix comptime equality of extern unions with same tag 2022-04-12 11:36:26 -07:00
Andrew Kelley
b0edd8752a Liveness: modify encoding to support over 32 operands
Prior to this, Liveness encoded `asm`, `call`, and `aggregate_init` with
a single 32-bit integer, allowing up to 35 operands (3 are provided by
the regular tomb_bits). However, the Zig language allows function calls
with more than 35 arguments, inline assembly with more than 35 inputs,
and anonymous tuples with more than 35 elements.

The new encoding stores an index to the extra array instead of the bits
directly, and then as many extra elements as needed to encode all the
operands. The MSB is used as a flag to tell which element is the last
one, allowing for 31 bits per element.

Prior to this, print_air did not bother correctly printing tombstones
for these instructions; now it does.

In addition to updating the BigTomb iteration logic in the machine code
backends, this commit extracts the common logic into the Liveness namespace.
2022-04-12 11:22:12 -07:00
Cody Tapscott
319b5cbce5 Do not detect byte-order using _BIG/_LITTLE_ENDIAN
These defines are present on some FreeBSD systems, regardless of
whether the system is big- or little- endian. This was causing the
FreeBSD CI to be incorrectly flagged as big-endian.

Resolves https://github.com/ziglang/zig/issues/11391
2022-04-12 11:14:33 -07:00
Cody Tapscott
04dd43934a Skip some floatXiYf tests on non-x86 platforms
These need to be skipped because of a bug with `@floatToInt`
on stage1:  https://github.com/ziglang/zig/issues/11408
2022-04-12 10:25:29 -07:00
Cody Tapscott
1c1cfe1533 Skip @rem/@mod tests on stage2, due to missing fmodl implementation 2022-04-12 10:25:29 -07:00
Cody Tapscott
b5d5685a4e compiler_rt: Implement floatXiYf/fixXfYi, incl f80
This change:
 - Adds  generic implementation of the float -> integer conversion
   functions floatXiYf, including support for f80
 - Updates the existing implementation of integer -> float conversion
   fixXiYf to support f16 and f80
 - Fixes the handling of the explicit integer bit in `__trunctfxf2`
 - Combines the test cases for fixXfYi/floatXiYf into a single file
 - Renames `fmodl` to `fmodq`, since it operates on 128-bit floats

The new implementation for floatXiYf has been benchmarked, and generally
provides equal or better performance versus the current implementations:

Throughput (MiB/s) - Before
     |    u32   |    i32   |    u64   |    i64   |   u128   |   i128   |
-----|----------|----------|----------|----------|----------|----------|
 f16 |     none |     none |     none |     none |     none |     none |
 f32 |  2231.67 |  2001.19 |  1745.66 |  1405.77 |  2173.99 |  1874.63 |
 f64 |  1407.17 |  1055.83 |  2911.68 |  2437.21 |  1676.05 |  1476.67 |
 f80 |     none |     none |     none |     none |     none |     none |
f128 |   327.56 |   321.25 |   645.92 |   654.52 |  1153.56 |  1096.27 |

Throughput (MiB/s) - After
     |    u32   |    i32   |    u64   |    i64   |   u128   |   i128   |
-----|----------|----------|----------|----------|----------|----------|
 f16 |  1407.61 |  1637.25 |  3555.03 |  2594.56 |  3680.60 |  3063.34 |
 f32 |  2101.36 |  2122.62 |  3225.46 |  3123.86 |  2860.05 |  1985.21 |
 f64 |  1395.57 |  1314.87 |  2409.24 |  2196.30 |  2384.95 |  1908.15 |
 f80 |   475.53 |   457.92 |   884.50 |   812.12 |  1475.27 |  1382.16 |
f128 |   359.60 |   350.91 |   723.08 |   706.80 |  1296.42 |  1198.87 |
2022-04-12 10:25:26 -07:00
Andrew Kelley
17631cb2d3 Merge pull request #11401 from viriuwu/float-category-misc
math: simplify inf (+f80 support), deprecate old constants (followup for #10133)
2022-04-12 06:37:12 -04:00
Ryan Liptak
17daba1806 std/fs/test.zig: Add test for renaming a dir onto an empty dir
Also split the Dir.rename on directories test into 3 tests:
- General rename of a directory
- Rename of a directory onto an existing empty directory
- Rename of a directory onto an existing non-empty directory

The only new case is the rename onto an existing empty directory, but splitting the tests this way made them much more understandable.
2022-04-12 06:28:16 -04:00
Andrew Kelley
bb4e74103b Merge pull request #11417 from topolarity/incremental-tests
Add file support for incremental compile error tests
2022-04-12 06:27:09 -04:00
Isaac Freund
38d6e1d8a8 std.build: Fix transitive linkSystemLibraryName() dependencies
Currently transitive system library dependencies are always linked using
linkSystemLibrary() and therefore pkg-config even if they were
originally specified with linkSystemLibraryName() instead. This causes
problems in practice for projects needing total control over exactly
what library is linked, such as the mach game engine.

This is fixed by keeping track of whether libraries are to be linked
with pkg-config or not and holding off on actually running pkg-config
until after transitive dependency resolution in LibExeObjStep.make().

This also fixes a separate issue with the pkg-config handling that could
cause partial application of pkg-config flags if the first part of the
pkg-config output parses correctly but there is an error later on. This
error isn't always fatal as we fall back to a plain -lfoo in the case of
linkSystemLibrary().
2022-04-12 06:12:44 -04:00
jagt
b9d86c6bc8 fix link.renameTmpIntoCache on windows when dest dir exists.
Previously it would fail as `renameW` do not ever fail with
`PathAlreadyExists`.

As a workaround we check for dest dir existence before rename
on Windows.
2022-04-12 06:01:25 -04:00
r00ster
c4aac28a42 Reuse code in Utf8Iterator.nextCodepoint 2022-04-12 05:34:12 -04:00
r00ster
988afd51cd Add std.fs.File.sync (#11410) 2022-04-12 05:32:45 -04:00
Cody Tapscott
879b562779 Add file support for incremental error tests
Compile error test cases can now be given as a sequence of files:
  - "foo.1.zig"
  - "foo.2.zig"
  - "foo.3.zig"
  - etc.

This sequence of files is tested as incremental compilation updates to a
single "foo.zig" source file.

To help avoid mistakes, we enforce strict ordering for these files.
"foo.zig" cannot co-exist with "foo.X.zig", the sequence must include
"foo.1.zig", and no numbers may be skipped.
2022-04-11 15:35:28 -07:00
Cody Tapscott
7851377e95 Improve whitespace-handling in (compile-error) test manifest parsing 2022-04-11 10:05:00 -07:00
Stephen Gutekanst
d2681d2537 std.event.WaitGroup: fix compilation (acquire->lock, release->unlock)
In 008b0ec5e5 the `std.Thread.Mutex` API was changed
from `acquire` and `release` to `lock` and `unlock`. `std.event.Lock` still uses `acquire`
and `release`. `std.event.WaitGroup` is using `std.Thread.Mutex` and was not updated to use
`lock` and `unlock`, and so compilation failed prior to this commit.

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-04-11 03:02:41 -04:00
Kirk Scheibelhut
971ef7b9c2 Remove primitive values from keyword reference
5a53ab28 removed these as keywords, and the Primitive Values section
of the docs already exists to describe them.
2022-04-09 12:48:36 +02:00
Igor Stojkovic
19e343b8d4 stage1: Additional fix for packed structs 2022-04-09 12:43:30 +02:00
viri
9b5c02022f compiler-rt(divtf3): fix remark, add more tests 2022-04-08 20:43:27 -06:00
viri
f9a9e8ba73 std.math.isInf: add tests for +-NaN 2022-04-08 20:13:30 -06:00
cryptocode
531d5b213f std: add Thread.Condition.timedWait (#11352)
* std: add Thread.Condition.timedWait

I needed the equivalent of `std::condition_variable::wait_for`, but it's missing in std.
This PR adds an implementation, following the status quo of using std.os.CLOCK.REALTIME in the pthread case (i.e. Futex)

A follow-up patch moving futex/condition stuff to monotonic clocks where available seems like a good idea.
This would involve conditionally exposing more functions and constants through std.c and std.os.
For instance, Chromium picks `pthread_cond_timedwait_relative_np` on macOS and `clock_gettime(CLOCK_MONOTONIC...)` on BSD's.

Tested on Windows 11, macOS 12.2.1 and Linux (with/without libc)

* Sleep in the single threaded case, handle timeout overflow in the Windows case and address a race condition in the AtomicCondition case.
2022-04-08 13:26:56 -05:00
Andrew Kelley
6ae8fe193b Liveness: utilize Air.refToIndex 2022-04-07 23:19:19 -07:00
Andrew Kelley
737ef3e81b Sema: remove unnecessary type resolution
This causes false positive "foo depends on itself" errors. Prior to some
recent enhancements, this type resolution was needed, however, we now
have a more sophisticated type resolution mechanism that fully
resolves types for the backend, but only after the Decl is fully
analyzed, avoiding dependency loops.
2022-04-07 22:58:50 -07:00
viri
e46c612503 use math/float.zig everywhere 2022-04-07 05:04:38 -06:00
viri
5d6a5a1236 std.math.is*Inf: make generic, support f80 2022-04-07 05:04:03 -06:00
Frank Denis
93e11b824a crypto/x25519: implement clearCofactor() (#11355)
This is the x25519 counterpart to `edwards25519.clearCofactor()`.

It is useful to check for low-order points in protocols where it matters and where clamping cannot work, such as PAKEs.
2022-04-07 10:46:23 +02:00
viri
c5c6260534 std.math: generalise inf, even simpler isFinite 2022-04-07 02:38:31 -06:00
viri
a2f5f0da5c std.math.isFinite: make generic, support f80 2022-04-07 02:38:28 -06:00
Wojtek Mach
5eee8f70d1 zig cc: support --subsystem linker flag
Example:

    $ zig cc -o main.exe main.cpp -target x86_64-windows -Wl,--subsystem,windows
2022-04-06 22:48:07 +02:00
Andrew Kelley
289ba5dfc2 stage2: rename InternArena to InternPool 2022-04-06 11:50:23 -07:00
viri
7b7f45dc2a std.{fmt, math}: derive float constants from std
This also addresses a nit from #10133 where IntT might be a confusing
name because it might imply signed integer (iX, not uX). We settled on
TBits for math/float.zig so I've applied that change here too.

When I originally wrote ldexp() I copied the name from parse_hex_float.
2022-04-06 15:50:36 +02:00
viri
cb019b80ac math.fabs: simplify implementation, add tests 2022-04-06 15:50:36 +02:00
viri
2f6ee4a97d math.isNormal: simplify implementation, add tests 2022-04-06 15:50:36 +02:00
viri
5b8ac9821d derive float constants in a generic way (#10133) 2022-04-06 15:50:36 +02:00
Andrew Kelley
62f54aa39c Sema: in-memory coercion of differently named int types
which have the same number of bits and the same signedness.
2022-04-06 02:39:55 -07:00
Andrew Kelley
9213aa789b stage2: ThreadPool: update to new function pointer semantics 2022-04-05 23:16:35 -07:00
Andrew Kelley
dd9782a8bc Sema: fix handling compile errors during circular dependency error
Previously, Zig would try to generate a function whose type contained
structs or unions which had not been fully resolved due to circular
dependency errors. With this commit, `resolveTypeFully` will be sure to
return `error.AnalysisFail` even in this scenario, leading to proper
display of compilation errors instead of a crash.
2022-04-05 23:16:35 -07:00
Luuk de Gram
ac873367b9 wasm: Use 'select' instruction for max/min
Rather than using blocks and control flow to check which operand is the maximum or minimum,
we use wasm's `select` instruction which returns us the operand based on a result from a comparison.
This saves us the need of control flow, as well as reduce the instruction count from 13 to 7.
2022-04-05 21:56:25 +02:00
Damien Firmenich
5fafcc2b62 zig fmt: remove trailing whitespace on doc comments
Fixes #11353

The renderer treats comments and doc comments differently since doc
comments are parsed into the Ast. This commit adds a check after getting
the text for the doc comment and trims whitespace at the end before
rendering.

The `a = 0,` in the test is here to avoid a ParseError while parsing the
test.
2022-04-05 18:08:33 +03:00
Andrew Kelley
95a87e88fa Sema: forward switch condition to captures 2022-04-04 22:46:05 -07:00
Andrew Kelley
51ef31a833 Sema: add empty tuple to mutable slice coercion 2022-04-04 14:29:08 -07:00
Evan Haas
b4bf3bdf7e std.fmt: Fix incorrect behavior with large floating point integers.
I consider this an interim workaround/hack until #1299 is finished.

There is a bug in the original C implementation of the errol3 (and errol4)
algorithm that can result in undefined behavior or an obviously incorrect
result (leading ':' in the output)

This change checks for those two problems and uses a slower fallback
path if they occur. I can't guarantee that this will always produce
the correct result, but since the workaround is only used if the original
algorithm is guaranteed to fail, it should never turn a previously-correct
result into an incorrect one.

Fixes #11283
2022-04-04 16:04:35 -04:00
Jakub Konka
364e53f3bf dwarf: emit debug info for local variables on x86_64
Add support for emitting debug info for local variables within a subprogram.
This required moving bits responsible for populating the debug info back to
`CodeGen` from `Emit` as we require the operand to be resolved at callsite
plus we need to know its type. Without enforcing this, we could end up
with a `dead` mcv.
2022-04-04 21:46:53 +02:00
John Schmidt
94fd914e58 Address review comments 2022-04-04 17:03:09 +02:00
iddev5
8d3e7aa5e0 std.testing: add function zigBuild for running zig build runner commands 2022-04-04 18:33:47 +05:30
Philipp Lühmann
795f075790 langref: rename incorrect expect to assert 2022-04-04 15:44:01 +03:00
ominitay
f654e16d06 std.simd: Fix suggestVectorSizeForCpu 2022-04-04 15:34:27 +03:00
Tom Read Cutting
cdcb34cdf4 Pull elf magic string out to re-used constant 2022-04-04 15:33:24 +03:00
Ryan Liptak
6d04ab6d5b Add std.testing.checkAllAllocationFailures
Adds a function that allows checking for memory leaks (and other problems) by taking advantage of the FailingAllocator and inducing failure at every allocation point within the provided `test_fn` (based on the strategy employed in the Zig parser tests, which can now use this function).
2022-04-04 15:32:43 +03:00
John Schmidt
17b804f56b Fix typo in compile error test 2022-04-03 14:30:37 +02:00
John Schmidt
6bbc2cd59a sema: add compile error for duplicate struct field 2022-04-03 14:30:32 +02:00
John Schmidt
174a889364 sema: add compile error for duplicate union field 2022-04-03 14:28:03 +02:00
John Schmidt
fd1ce329b3 stage2: add union compile error tests 2022-04-03 13:49:34 +02:00
John Schmidt
e4d427f12e refactor: add Sema.addFieldErrNote 2022-04-03 13:49:34 +02:00
John Schmidt
b922caf169 sema: add compile error for missing/extra enum fields in union decl 2022-04-03 13:49:34 +02:00
John Schmidt
f7f4702795 sema: add more info to error messages for enum->union coercion 2022-04-03 13:49:34 +02:00
John Schmidt
8f0dac01ef sema: add more info to error message for invalid comptime union field access 2022-04-03 13:49:34 +02:00
Andrew Kelley
91eb1af917 stage2: more resilient error handling
* If more than one error is reported for the same Decl, the first error
   message is kept and the second one discarded.
 * Prevent functions from being sent to codegen backends if there were
   any errors resolving any of their parameter types or return type.
2022-04-02 19:18:41 -07:00
Andrew Kelley
3432e66faf stage2: remove dependencies on async functions
This commit removes the tiny amount of dependency on async/await that
the self-hosted compiler has so that it can self-host before async/await
language features are working.
2022-04-02 19:18:41 -07:00
Andrew Kelley
843d5adcd6 std.ArrayHashMap: lazier verifyContext calls
Companion commit to b45c6c757c.

Related: #11367
2022-04-02 19:18:41 -07:00
Andrew Kelley
3b32e0be31 behavior tests: disable failing stage1 test
I forgot to check that the new behavior tests also pass in stage1. One
of them does not.

Fixes regression from 4618c41fa6.
2022-04-02 19:02:29 -07:00
Andrew Kelley
4618c41fa6 Sema: mechanism for converting comptime breaks to runtime
closes #11369
2022-04-02 18:30:44 -07:00
Veikka Tuominen
83bb98e13b stage2 llvm: properly align error union payload 2022-04-02 19:31:32 -04:00
Luuk de Gram
a0a587ff85 wasm: Enable passing behavior tests
This shuffles some tests do ensure the new instructions are tested for the wasm backend,
by moving vectors into their own tests as well as move the f16 test cases as those require
special operating also.
2022-04-02 21:54:01 +02:00
Luuk de Gram
2c40b37f79 wasm: Implement @ctz for bitsize <= 64
Implements the `ctz` AIR instruction for integers with bitsize <= 64.
When the bitsize of the integer does not match the bitsize of a wasm type,
we first XOR the value with the value of (1<<bitsize) to set the right bits
and ensure we will only count the trailing zeroes of the integer with the correct bitsize.
2022-04-02 21:54:01 +02:00
Luuk de Gram
bd27fe2bf5 wasm: Implement @clz
Implements the `clz` AIR instruction for integers with bitsize <= 64.
When the bitsize of the integer is not the same as wasm's bitsize,
we substract the difference in bits as those will always be 0 for the integer, but should
not be counted towards the end result. We also wrap the result to ensure it fits
in the result type as documented in the language reference.
2022-04-02 21:54:01 +02:00
Luuk de Gram
5ba03369ee wasm: Implement @mulAdd for f32, f64
This implements the `mul_add` AIR instruction for floats of bitsize 32 and 64.
f16's will require us being able to extend and truncate f16's to correctly
store and load them without losing the accuracy.
2022-04-02 21:54:01 +02:00
Luuk de Gram
219fa192c6 wasm: Implement @maximum & @minimum
This implements the `max` and `min` AIR instructions by checking
whether LHS is great/lesser than RHS. If that's the case, we assign
LHS to the result, otherwise assign RHS to it instead.
2022-04-02 21:54:01 +02:00
Jakub Konka
3ee44ce949 Merge pull request #11373 from joachimschmidt557/stage2-arm
stage2 ARM: implement overflow operations for ints <= 32 bits
2022-04-02 10:52:34 +02:00
joachimschmidt557
8c12ad98b8 stage2 ARM: implement mul_with_overflow for ints <= 32 bits 2022-04-01 22:51:18 +02:00
joachimschmidt557
c4778fc029 stage2 ARM: implement mul_with_overflow for ints <= 16 bits 2022-04-01 22:02:56 +02:00
joachimschmidt557
77e70189f4 stage2 ARM: implement shl_with_overflow for ints <= 32 bits 2022-04-01 22:02:56 +02:00
joachimschmidt557
37a8c28802 stage2 ARM: implement add/sub_with_overflow for ints < 32 bits 2022-04-01 22:02:56 +02:00
joachimschmidt557
7285f0557c stage2 ARM: implement add/sub_with_overflow for u32/i32 2022-04-01 22:02:55 +02:00
joachimschmidt557
e2e69803dc stage2 ARM: change binOp lowering mechanism to use Mir tags
The Air -> Mir correspondence is not 1:1, so this better represents
what Mir insruction we actually want to generate.
2022-04-01 22:02:51 +02:00
Jakub Konka
8b5d5f44e2 macho: set CS_LINKER_SIGNED flag in code signature generated by zld
This way, if the user wants to use `codesign` (or other tool) they
will not be forced to `-f` force signature update. This matches
the behavior promoted by Apple's `ld64` linker.
2022-04-01 14:33:37 +02:00
Jakub Konka
fd29ddc06c x64: implement add/sub with wrapping and xor op 2022-04-01 11:37:18 +02:00
Andrew Kelley
87179d91a7 stage2: hook up Sema to the progress bar 2022-04-01 00:17:02 -07:00
Andrew Kelley
b45c6c757c std.hash_map: workaround for circular dependency
See #11367

It's debatable whether this ends up being a legitimate compile error or
whether the lang spec allows this test case. For now this workaround
seems very reasonable; delaying comptime execution of `verifyContext`
until the struct is instantiated.
2022-04-01 00:17:02 -07:00
Andrew Kelley
26253acf1d AstGen: use block_inline and break_inline consistently
These are more efficiently semantically analyzed. More importantly, if
they don't match, we get a crash in Sema.

Missing places prior to this commit:
 * labeled blocks
 * `break` and `continue` on comptime (not inline) loops
 * `if`, `try`, `orelse`, and `catch` inside comptime scopes
2022-03-31 23:47:34 -07:00
Andrew Kelley
ecd756834b CI: update CLI invokation
243afdcdf5 removed `-Dskip-compile-errors`
and added `-Dskip-stage`.
2022-03-31 16:06:50 -07:00
Andrew Kelley
243afdcdf5 test harness improvements
* `-Dskip-compile-errors` is removed; `-Dskip-stage1` is added.
 * Use `std.testing.allocator` instead of a new instance of GPA.
   - Fix the memory leaks this revealed.
 * Show the file name when it is not parsed correctly such as when the
   manifest is missing.
   - Better error messages when test files are not parsed correctly.
 * Ignore unknown files such as swap files.
 * Move logic from declarative file to the test harness implementation.
 * Move stage1 tests to stage2 tests where appropriate.
2022-03-31 15:10:31 -07:00
Andrew Kelley
df1ba38a88 AstGen: fix treating noreturn instructions as void
Fixes regression introduced in cf4aad4858.
2022-03-31 15:06:12 -07:00
Andrew Kelley
b6133931d0 Sema: fix segfault during resolveInferredErrorSet
There was a simple missing check of adding an inferred error set to
itself, in which case we should not try to mutate the hash map while
iterating over it.
2022-03-31 12:25:48 -07:00
Andrew Kelley
cf4aad4858 AstGen: fix referencing unreferencable instructions
Sema avoids adding map entries for certain instructions such as
`set_eval_branch_quota` and `atomic_store`. This means that result
location semantics in AstGen must not emit any instructions that attempt
to use the result of any of these instructions.

This commit makes AstGen replace such instructions with
`Zir.Inst.Ref.void_value` if their result value ends up being
referenced.

This fixes a compiler crash when running std lib atomic tests.
2022-03-30 23:19:10 -07:00
Meghan Denny
08565b23f9 stage2: fix print_zir for .builtin_src 2022-03-31 02:12:44 -04:00
Veikka Tuominen
75c2cff40e stage2: handle assembly input names 2022-03-31 01:33:28 -04:00
Andrew Kelley
6655c6092e std.base64: upgrade to new function pointer semantics 2022-03-30 20:38:01 -07:00
Andrew Kelley
02d69f5009 Sema: fix usingnamespace decl Value in wrong arena
closes #11297
2022-03-30 17:24:01 -07:00
James Mintram
5d5b1b68fc Remove a std.debug.print from the dwarf.zig file
This was causing freestanding builds to fail due to the
use of `std.debug.print`
2022-03-30 19:35:20 -04:00
Veikka Tuominen
3c64c519e6 Merge pull request #11246 from jmc-88/cbe-asm
CBE: improve support for asm inputs
2022-03-31 00:04:04 +03:00
Andrew Kelley
d227f76afb std.zig.Ast: fix escaped capture of by-value parameters 2022-03-30 11:52:10 -07:00
Andrew Kelley
47dfaf47b8 stage2: test compile errors independently
Until we land some incremental compilation bug fixes, this prevents CI
failures when running the compile errors test cases.
2022-03-30 11:22:27 -07:00
Jakub Konka
f5d9160f1b dwarf: pass DeclState around instead of storing a temp global in Dwarf
Avoids many pitfalls connected with premature/early return in case
there are errors with Decl, etc. This is effectively bringing back
the old design however in a much nicer packaging, where every
mechanism related to tracking Decl's debug info is now nicely
wrapped in a single struct (aka the `DeclState`). This includes
relocation table, type arena, etc. It is now the caller's
responsibility to deinit the state (so that no memory is leaked)
after `Decl` has been analysed (or errored out). The caller here
is typically a linker such as `Elf` or `MachO`.
2022-03-30 14:21:13 -04:00
Meghan
b73cf97c93 replace other uses of std.meta.Vector with @Vector (#11346) 2022-03-30 14:12:14 -04:00
Jakub Konka
b153e156b1 Merge pull request #11342 from ziglang/stage2-x64-mul-div
x64: use all available registers (caller and callee), and fix how we multiply (fixes @mulWithOverflow for byte-size operands)
2022-03-30 11:22:35 +02:00
Daniele Cocca
907dc1e13f CBE: improve support for asm inputs
This is not complete support for asm expressions, but allows a few more
test cases from test/behavior/asm.zig to pass. Since the non-register
inputs are named `input_${n}` they can cause name collisions: I'm
wrapping the asm expressions in their own block to prevent that.

Contextually, this change also makes test/behavior/asm.zig run for
stage2, but skips individual tests for most backends (I only verified
the C and LLVM backends successfully run one new test case) and the
entire test file for aarch64, where it's running into preexisting
shortcomings.
2022-03-30 12:10:02 +03:00
Daniele Cocca
ebafdb958c AstGen: don't coerce inputs to usize in asmExpr
Instead, use ResultLoc.none to allow for the expression type to be
inferred [^1]. This effectively moves the type coercion to Sema, in
order to turn comptime values into usable values for the backends to
consume. Right now the coercion is applies as comptime_int -> usize and
comptime_float -> f64, as an arbitrary choice.

[^1]: 9f25c8140c/src/AstGen.zig (L207-L208)
2022-03-30 11:57:16 +03:00
Daniele Cocca
633fe41a2c Sema: allow comptime blocks for global assembly
An assembly expression in a comptime block is legal Zig in the case of
global assembly [^1]. Instead of unconditionally asserting that the
expression lives in a runtime block, here we assert that if the
expression lives in a comptime block it must be outside of function
scope.

[^1]: https://ziglang.org/documentation/0.9.1/#Global-Assembly
2022-03-30 11:57:15 +03:00
Daniele Cocca
5d5282b5f1 AstGen: support local var references for outputs 2022-03-30 11:57:15 +03:00
Andrew Kelley
c21f046a8b Sema: enhance is_non_err to be comptime more often
* Sema: store the precomputed monomorphed_funcs hash inside Module.Fn.
   This is important because it may be accessed when resizing monomorphed_funcs
   while this Fn has already been added to the set, but does not have the
   owner_decl, comptime_args, or other fields populated yet.
 * Sema: in `analyzeIsNonErr`, take advantage of the AIR tag being
   `wrap_errunion_payload` to infer that `is_non_err` is comptime true
   without performing any error set resolution.
   - Also add some code to check for empty inferred error sets in this
     function. If necessary we do resolve the inferred error set.
 * Sema: queue full type resolution of payload type when
   `wrap_errunion_payload` AIR instruction is emitted. This ensures the
   backend may check the alignment of it.
 * Sema: resolveTypeFully now additionally resolves comptime-only
   status.

closes #11306
2022-03-30 00:47:55 -07:00
Andrew Kelley
05947ea870 stage2: implement @intToError with safety
This commit introduces a new AIR instruction `cmp_lt_errors_len`. It's
specific to this use case for two reasons:

 * The total number of errors is not stable during semantic analysis; it
   can only be reliably checked when flush() is called. So the backend
   that is lowering the instruction must emit a relocation of some kind
   and then populate it during flush().
 * The fewer AIR instructions in memory, the better for compiler
   performance, so we squish complex meanings into AIR tags without
   hesitation.

The instruction is implemented only in the LLVM backend so far. It does
this by creating a simple function which is gutted and re-populated
with each flush().

AstGen now uses ResultLoc.coerced_ty for `@intToError` and Sema does the
coercion.
2022-03-29 22:19:06 -07:00
Andrew Kelley
83617eac59 std: avoid referencing event loop when io_mode is blocking
This prevents unwanted symbols from ending up in the output binary.
2022-03-29 22:16:43 -07:00
Andrew Kelley
9821a0c6f0 Sema: fix generic instantiations of return types with nested captures
* In semaStructFields and semaUnionFields we return error.GenericPoison
   if one of the field types ends up being generic poison.
   - This requires handling function calls and function types taking
     this into account when calling `typeRequiresComptime` on the return
     type.
 * Unrelated: I noticed using Valgrind that struct reification did not
   populate the `known_opv` field. After fixing it, the behavior tests
   run Valgrind-clean.
 * ZIR: use `@ptrCast` to cast between slices instead of exploiting
   the fact that stage1 incorrectly allows `@bitCast` between slices.
   - A future enhancement will make Zig support `@ptrCast` to directly
     cast between slices.
2022-03-29 20:11:48 -07:00
Andrew Kelley
e39c86399d link: half-hearted bug fix for decl_state field
The init()/commit() API of this field leads to the type of bug that this
commit fixes by defering an uncomfortably complex expression. I didn't
bother doing the equivalent fix in link/MachO.zig because instead I
think the `decl_state` field should be entirely removed from Dwarf.
2022-03-29 20:08:28 -07:00
Andrew Kelley
b59428e9f7 Sema: adjust coercion of undefined error union payload
To no longer set the error code to undefined. This fixes the problem
where an undefined single-item pointer coerced to an error union of a
slice set the whole thing to undefined even though the sub-coercion to
the slice would have produced a defined value.
2022-03-29 16:56:12 -07:00
Jakub Konka
376d0878ec x64: spill .rdi to stack if expecting return value saved on stack
Since .rdi is not part of the callee saved registers, it needs to be
proactively spilled to the stack so that we don't clobber the
return address where to save the return value.
2022-03-30 00:37:42 +02:00
Jakub Konka
d447cd940d x64: track callee and caller saved registers
This is now required to correctly track and spill registers
required for some ops such `mul` or `div` (both required use of
`.rax` and `.rdx` registers).
2022-03-30 00:37:42 +02:00
Jakub Konka
60879bc8ae x64: clean up instruction tracking for div/mul ops 2022-03-30 00:37:42 +02:00
Jakub Konka
ee6e3aef5d x64: redo @mulWithOverflow using rax/rdx based multiplication 2022-03-30 00:37:42 +02:00
Jakub Konka
f9773ab622 x64: clean up abstraction for generating integer division 2022-03-30 00:37:42 +02:00
Andrew Kelley
12e1304805 test harness: fix not honoring one_test_case_per_file
I regressed this in 9aa431cba3.

thanks @topolarity for pointing out the issue
2022-03-29 12:20:10 -07:00
Andrew Kelley
9aa431cba3 test harness: include case names for compile errors
in the progress nodes
2022-03-29 12:01:45 -07:00
Daniele Cocca
8238d4b335 CBE: fix C output after PR #11302, reenable tests
Commit 052079c994 surfaced two issues with
the generated C code:

  - renderInt128() contained a seemingly unnecessary assertion to verify
    that the high 64 bits of the number were nonzero, dating back to
    9bf1681990. I removed it.
  - renderValue() didn't have any special handling for undefined structs,
    falling back to printing "{}" which generated invalid expressions
    such as "return {}" for functions returning structs, whereas
    "return (S){}" is the correct form. I changed it accordingly.

At the same time I'm reenabling the relevant tests.
2022-03-29 02:28:20 -04:00
Andrew Kelley
8df84cce8b Sema: queue full type resolution of builtin types 2022-03-28 18:49:49 -07:00
Andrew Kelley
4dd65316b7 AstGen: coerce break operands of labeled blocks
Similar code was already in place for conditional branches. This updates
AstGen to do the same for labeled blocks. It takes advantage of the
`store_to_block_ptr` instructions by mutating them in place to become
`as` instructions, coercing the break operands before they are returned
from the block.
2022-03-28 18:28:08 -07:00
Andrew Kelley
857743473c Merge @schmee's union debug info branch 2022-03-28 16:43:24 -07:00
Andrew Kelley
f4a357d720 stage2: finish debug info for unions in the LLVM backend
Sema:

 * queue full resolution of std.builtin.Type.Error when doing `@typeInfo`
   for error sets.

LLVM backend:

 * change a TODO comment to a proper explanation of why debug info
   for structs is left as a fwd decl sometimes.
 * remove handling of packed unions which does not match the type
   information or constant generation code.
 * remove copy+pasted code
 * fix union debug info not matching the memory layout
 * remove unnecessary error checks and type casting
2022-03-28 16:27:45 -07:00
John Schmidt
c546608fca stage2: LLVM: (WIP) add union fields debug info 2022-03-28 16:24:51 -07:00
Andrew Kelley
b6ccde47ad Sema: allow mixing array and vector operands
* Added peer type resolution for arrays and vectors: the vector type is
   selected.
 * Fixed passing the lhs type or rhs type instead of the peer resolved
   type when calling Value methods during analyzeArithmetic handling of
   comptime expressions.
 * `checkVectorizableBinaryOperands` now allows mixing vectors and
   arrays, as long as one of the operands is a vector.

This matches stage1's handling of `^=` but apparently stage1 is
inconsistent and does not handle e.g. `*=`. stage2 now will always allow
mixing vector and array operands for all operations.
2022-03-28 14:17:05 -07:00
Veikka Tuominen
691c7cb3cd std.build: fix functions returning address of by value parameter 2022-03-28 13:06:11 -07:00
Veikka Tuominen
c517e65d8f Sema: implement coerceInMemoryAllowed for optionals 2022-03-28 13:05:40 -07:00
Veikka Tuominen
5515b81f8c Sema: use the correct integer
Sure would be nice if these two incompatible indexes had distinct types.
2022-03-28 13:05:21 -07:00
Veikka Tuominen
a415fe0bc0 AstGen: clear rl_ty_inst in setBreakResultLoc if one is not provided 2022-03-28 13:05:08 -07:00
Veikka Tuominen
3c4ac47e00 stage2 llvm: fix union init of byRef values 2022-03-28 13:04:50 -07:00
Andrew Kelley
7e47f106cc Value.hashPtr: handle lazy_align as an integer
Although lazy_align is a different tag than integer values, it needs to
be hashed and equality-tested as if it were a simple integer. Otherwise
our basic data structure guarantees fall apart.
2022-03-28 12:05:08 -07:00
Jakub Konka
c38b4bcee7 Merge pull request #11334 from ziglang/stage2-x64-overflow
x64: implement add, sub and mul with overflow
2022-03-28 20:58:18 +02:00
Jakub Konka
e6729036e4 x64: partially fix genImul, enable overflow tests 2022-03-28 17:45:50 +02:00
Jakub Konka
107052aded x64: implement add, sub and mul with overflow 2022-03-28 16:37:35 +02:00
ominitay
25d4c5df70 std.mem.zeroInit: Fix behaviour with empty initialiser 2022-03-28 14:10:36 +03:00
Veikka Tuominen
460e7a2445 Merge pull request #11319 from Vexu/stage2-arg-count
stage2: check arg count before types
2022-03-28 13:05:40 +03:00
Jakub Konka
b8cd56dc94 Merge pull request #11300 from ziglang/stage2-debug-error-sets 2022-03-28 07:40:33 +02:00
Andrew Kelley
7be340e3cc std.crypto.blake3: use @Vector instead of std.meta.Vector 2022-03-27 14:53:40 -07:00
Andrew Kelley
3fc0e0c57b Sema: implement @setFloatMode
We are putting off actual optimization of floats because we have a
couple proposals being considered which would change how it works.

In the meantime, lowering optimized float mode to be the same as
strict is a perfectly legal way to implement the Zig language specification.
2022-03-27 14:52:12 -07:00
Andrew Kelley
c8f8440271 stage1: disable failing test
The new behavior test introduced in the previous commit is not passing
for stage1 on mips.
2022-03-27 14:40:24 -07:00
Andrew Kelley
6d2ec7a4e3 LLVM: handle aggregate_init for packed structs 2022-03-27 14:22:47 -07:00
Veikka Tuominen
d5e89dd70b stage2: add temporary workaround for lack of argument count check 2022-03-27 22:57:43 +03:00
Veikka Tuominen
7217148edf Value: hash lazy_align 2022-03-27 22:38:37 +03:00
Andrew Kelley
052079c994 Merge pull request #11302 from mitchellh/slice-null-cptr
stage2: runtime safety checks for slicing a null C pointer and @intCast truncating bits
2022-03-27 15:37:09 -04:00
Andrew Kelley
0501962b4c Merge pull request #11321 from Luukdegram/wasm-overflow
stage2: wasm - Implement overflow arithmetic
2022-03-27 15:24:39 -04:00
Jakub Konka
366ec21052 dwarf: track type relocation state in Dwarf module 2022-03-27 20:53:06 +02:00
Jakub Konka
4ca9b4c44a dwarf: move DbgInfoTypeRelocsTable into Dwarf module 2022-03-27 20:53:06 +02:00
Jakub Konka
1a80315836 dwarf: rename DebugInfoAtom into Atom; free all allocated memory 2022-03-27 20:53:06 +02:00
Jakub Konka
b4815b3131 dwarf: draft poc of deferred resolution of error sets debug info 2022-03-27 20:53:06 +02:00
Jakub Konka
e444e69dc4 dwarf: do not use Type.errorSetNames() for inferred error sets
Otherwise, we risk tripping an assertion in `Type.errorSetNames()`
in case the inferred error set was not yet fully resolved. This so
far only surfaced when Dwarf triggers recursive analysis of an
error set as part of emitting debug info for an error union.
2022-03-27 20:53:06 +02:00
Jakub Konka
4985abcc49 dwarf: add debug info for error unions 2022-03-27 20:53:06 +02:00
Jakub Konka
a1040a105a dwarf: add debug info for error sets 2022-03-27 20:53:06 +02:00
Veikka Tuominen
bda7993beb Sema: fix error set memory unsafety
All error names are supposed to be owned by Module.
2022-03-27 20:31:54 +03:00
Luuk de Gram
e1bb09648f wasm: Enable overflow behavior tests 2022-03-27 19:02:45 +02:00
Luuk de Gram
3114faddd8 wasm: Implement overflow arithmetic
This implements the overflow arithmetic for unsigned and signed integers.
Meaning the following instructions:
- @addWithOverflow
- @subWithOverflow
- @shlWithOverflow
- @mulWithOverflow
2022-03-27 19:00:49 +02:00
Mitchell Hashimoto
3c91818438 stage2: runtime safety check intCast signedness 2022-03-27 09:20:37 -07:00
Mitchell Hashimoto
4ad98d0714 stage2: runtime safety check intCast to u0 must fit 2022-03-27 09:20:37 -07:00
Mitchell Hashimoto
8fbac2e86d stage2: runtime safety check integer cast truncating bits 2022-03-27 09:20:37 -07:00
Mitchell Hashimoto
01698528d1 stage2: safety checks for slicing a null C pointer 2022-03-27 09:20:35 -07:00
iddev5
df544cace9 std: explicitly handle error.UnexpectedExitCode in build_runner
RunStep on unexpected exit code used to return error.UncleanExit, which
was confusing and unclear. When it was changed, the error handling code
in build_runner was not modified, which produced an error trace.

This commit explicitly handles error.UnexpectedExitCode in build_runner
so that the behavior now matches that of zig 0.8.1 after which it was
regressed.
2022-03-27 18:19:55 +05:30
Jakub Konka
d15bbebe2e macho: do not create dSYM bundle for stage2 LLVM backend
Instead, we fallback to the old-fashioned stabs-based mechanism
until I add the missing mechanism for extracting and relocating
DWARF from relocatable object files and writing it into a dSYM
bundle.
2022-03-27 13:20:13 +02:00
BlueAlmost
406507c6dc std.math.Complex: add 'negation' and 'mulitply by i' 2022-03-27 11:54:43 +03:00
leesongun
7ae22813ee stage1: implement casting from u0 2022-03-27 11:49:54 +03:00
matu3ba
dbbda0f41a std.testing: add methods tmpDirPath, getTestArgs, buildExe
continuation of #11093 to simplify testing IPC

* use cases
  - get path to temporary directory
  - get the test arguments inside test block for reusage
  - build executables from text within test blocks, ie to test IPC
* missing conventions
  - how to name and debug test cases
  - where do simple+repititve build commands for testing belong
2022-03-27 11:43:40 +03:00
Veikka Tuominen
f9a2c0fc6c Merge pull request #10871 from schmee/stage2-bitcast-safety
stage2: add type checking for @bitCast
2022-03-27 11:31:30 +03:00
tecanec
3beef3945c std: SIMD utility functions
This file contains a collections of functions that may be useful for SIMD, such as generating a vector with a linear range of numbers starting at zero, joining two vectors together, getting the index of the first true in a vector of bools, etc.
2022-03-27 11:28:44 +03:00
Yorhel
a3030221c3 std.fs: Handle EINVAL from linux.getdents64
Fixes #11178
2022-03-27 11:24:31 +03:00
jagt
29c32b3dc5 Namespace.decls use context to save memory
change `Module.Namespace.decls` from `AutoArrayHashMapUnmanaged` to
`ArrayHashMapUnmanaged(*Decl, void)` with custom context to eliminate
duplicated decl name strings.

Also see:
https://zig.news/andrewrk/how-to-use-hash-map-contexts-to-save-memory-when-doing-a-string-table-3l33
2022-03-27 11:23:11 +03:00
Veikka Tuominen
23507f20b9 Merge pull request #11315 from wsengir/stage2-simplify-muladd
stage2: simplify mul_add
2022-03-27 11:12:42 +03:00
William Sengir
adc2824fa4 stage2: simplify scalar_ty for mul_add in LLVM backend 2022-03-26 16:29:48 -07:00
William Sengir
6a48345649 Sema: remove redundant mul_add comptime vectorization
Moving comptime vectorization into `Value` has proven to simplify and
clean up a lot of code.
2022-03-26 16:29:48 -07:00
Joachim Schmidt
97a53bb8a1 Merge pull request #11311 from joachimschmidt557/builtin-with-overflow
stage2: Change semantics of AIR arithmetic overflow instructions
2022-03-26 22:29:48 +01:00
Luuk de Gram
16e88b75ba wasm: Enable passing tests 2022-03-26 21:20:29 +01:00
Luuk de Gram
97448e4d5f wasm: Only generate import when referenced
Rather than creating an import for externs on updateDecl, we now
generate them when they're referenced. This is required so using @TypeOf(extern_fn())
will not emit the import into the binary (causing an incorrect function type index
as it won't be fully analyzed).
2022-03-26 21:20:29 +01:00
joachimschmidt557
9070ad7774 stage2 LLVM: Adjust to new AIR arithmetic overflow instructions 2022-03-26 17:21:42 +01:00
joachimschmidt557
e2468e3f27 Sema: change zirOverflowArithmetic to use new version of AIR insts
Also applies the change to Liveness
2022-03-26 17:21:42 +01:00
joachimschmidt557
1803167db2 AIR: change signature of overflow arithmetic instructions
add_with_overflow and similar functions now have the ty_pl data
attached. The Payload will now be a binary operation and the inst is
expected to return a tuple consisting of the destination integer type
and an overflow bit (u1).

Co-authored-by: Jan Philipp Hafer <jan.hafer@rwth-aachen.de>
2022-03-26 17:21:39 +01:00
Igor Stojkovic
109e730c8c stage1: Fix packed structs (#2627, #10104)
Fixed formatting in packed-struct-zig

Skipped packed_structs tests in stage2

simplified packed struct tests
2022-03-26 09:03:37 +01:00
Andrew Kelley
af844931b2 stage2: resolve types more lazily
This avoids unwanted "foo depends on itself" compilation errors.
2022-03-26 00:33:14 -07:00
Andrew Kelley
6ef761307c Merge pull request #11284 from topolarity/compile-errors-indep-files
Add primitive file support for compile error tests
2022-03-26 00:45:38 -04:00
Andrew Kelley
88e98a0611 Merge pull request #11289 from schmee/stage2-select
stage2: implement `@select`
2022-03-26 00:33:22 -04:00
Andrew Kelley
bae35bdf2d stage2: result location types for function call arguments
* AstGen: restore the param_type ZIR instruction and pass it to the
   expression for function call arguments. This does not solve the
   problem for generic function parameters, but it catches stage2 up to
   stage1 which also does not solve the problem for generic function
   parameters.
   - Most of the enhancements in this commit will still be needed for a
     more sophisticated further improvement to handle generic function
     types.
   - In Sema, handling of `as` coercion recognizes the `var_args_param`
     Type Tag and passes the operand through doing no coercion.
   - That was the last ZIR tag and we are now using all 256 ZIR tags.
 * AstGen: array init and struct init expressions use the anon form even
   when the result location has a type. Prevents the type system
   incorrectly believing, for example, that a tuple is actually an array
   when the result location is a param_type of a function with `anytype`
   parameter.
 * Sema: add missing coercion in `unionInit` to coerce the init to the
   corresponding union field type.
 * `Value.fieldValue` now takes a type and does not take an allocator.

closes #11293

After this commit, stage2 passes all the parser tests.
2022-03-26 00:27:12 -04:00
Andrew Kelley
bcd7eb012a Merge pull request #11304 from joachimschmidt557/stage2-aarch64
stage2 AArch64: remove MCValue.embedded_in_code
2022-03-25 22:22:47 -04:00
joachimschmidt557
c1098e9036 stage2 x86_64: remove MCValue.embedded_in_code 2022-03-25 22:22:16 -04:00
Andrew Kelley
600c7fe1da Merge pull request #11299 from Vexu/stage2-build
stage2 fixes on the way to `zig2 build --help` working
2022-03-25 21:35:04 -04:00
John Schmidt
607300a59b sema: simplify @bitCast error messages 2022-03-26 01:07:52 +01:00
John Schmidt
dc5dc3ac59 stage2: add type checking for @bitCast 2022-03-25 23:33:05 +01:00
John Schmidt
a7b3082ba0 Implement type.bitSize for unions 2022-03-25 23:15:37 +01:00
Veikka Tuominen
2f326f24dd Sema: implement zirSwitchCapture multi for unions 2022-03-25 22:32:15 +02:00
Veikka Tuominen
17d214a249 Sema: implement zirStructInit for runtime-known union values 2022-03-25 22:32:15 +02:00
Veikka Tuominen
5ff518fbb9 Sema: implement zirSwitchCapture for error sets 2022-03-25 22:32:14 +02:00
Veikka Tuominen
26dfbf8122 type: fix onePossibleValue for auto numbered enums 2022-03-25 22:32:14 +02:00
Veikka Tuominen
f6bd534fc9 Sema: ensure error_set_merged is sorted 2022-03-25 22:32:14 +02:00
Veikka Tuominen
a4c5ec49f1 Sema: add error for empty switch 2022-03-25 22:30:35 +02:00
Cody Tapscott
0568b45779 Move existing compile errors to independent files
Some cases had to stay behind, either because they required complex case
configuration that we don't support in independent files yet, or because
they have associated comments which we don't want to lose track of.

To make sure I didn't drop any tests in the process, I logged all
obj/test/exe test cases from a run of "zig build test" and compared
before/after this change.

All of the test cases match, with two exceptions:
 - "use of comptime-known undefined function value" was deleted, since
   it was a duplicate
 - "slice sentinel mismatch" was renamed to "vector index out of
   bounds", since it was incorrectly named
2022-03-25 12:27:46 -07:00
Cody Tapscott
1de63ad793 zig fmt: Add --exclude argument to skip dir/file
This change adds a "--exclude" parameter to zig format, which can be
used to make sure that it does not process certain files or folders
when recursively walking a directory.

To do this, we simply piggy-back on the existing "seen" logic in zig
fmt and mark these files/folders as seen before processing begins.
2022-03-25 12:27:46 -07:00
Cody Tapscott
7f64f7c925 Add rudimentary compile error test file support
This brings two quality-of-life improvements for folks working on
compile error test cases:
 - test cases can be added/changed without re-building Zig
 - wrapping the source in a multi-line string literal is not necessary

I decided to keep things as simple as possible for this initial
implementation. The test "manifest" is a contiguous comment block at the
end of the test file:
1. The first line is the test case name
2. The second line is a blank comment
2. The following lines are expected errors

Here's an example:
```zig
const U = union(enum(u2)) {
    A: u8,
    B: u8,
    C: u8,
    D: u8,
    E: u8,
};
export fn entry() void {
    _ = U{ .E = 1 };
}

// union with too small explicit unsigned tag type
//
// tmp.zig:1:22: error: specified integer tag type cannot represent every field
// tmp.zig:1:22: note: type u2 cannot fit values in range 0...4
```

The mode of the test (obj/exe/test), as well as the target
(stage1/stage2) is determined based on the directory containing the
test.

We'll probably eventually want to support embedding this information
in the test files themselves, similar to the arocc test runner, but
that enhancement can be tackled later.
2022-03-25 12:25:43 -07:00
joachimschmidt557
f7da4b9bc8 stage2 AArch64: change semantics of MCValue.stack_offset
Mirrors the changes performed to stack_offset in the ARM backend
2022-03-25 19:21:34 +01:00
joachimschmidt557
16e4966332 stage2 AArch64: remove MCValue.embedded_in_code 2022-03-25 19:21:34 +01:00
joachimschmidt557
061d6699c0 stage2 AArch64: lower cmp to binOp 2022-03-25 19:21:34 +01:00
John Schmidt
cd46daf7d0 sema: coerce inputs to vectors in zirSelect 2022-03-25 19:14:11 +01:00
John Schmidt
f47db0a0db sema: use pl_op for @select 2022-03-25 16:13:54 +01:00
John Schmidt
12d5efcbe6 stage2: implement @select 2022-03-25 16:13:54 +01:00
Jakub Konka
1c33ea2c35 dwarf: add debug info for unions 2022-03-25 13:53:40 +01:00
Evan Haas
0d5d353197 translate-c: Use @Vector for vector expressions
Removes translate-c usage of std.meta.Vector, which was deprecated in d42d31f72f
2022-03-25 14:47:51 +02:00
dxps
9a127501f6 chore: doc fixes, closes 11091 2022-03-25 11:22:30 +02:00
Andrew Kelley
7f91be9c80 AstGen: emit break_inline from inline while loop 2022-03-24 22:45:10 -07:00
Andrew Kelley
bcf2eb1a00 Sema: fix closure capture typeof runtime-known parameter
Closures are not necessarily constant values. For example, Zig
code might do something like this:

    fn foo(x: anytype) void {
        const S = struct {field: @TypeOf(x)};
    }

...in which case the closure_capture instruction has access to a
runtime value only. In such case we preserve the type and use a
dummy runtime value.

closes #11292
2022-03-24 21:47:18 -07:00
Andrew Kelley
b802a67562 std.MultiArrayList: check size of element, not pointer
Ever since a semi-recent language specification update, pointers to
zero-sized types still have runtime bits.
2022-03-24 19:55:12 -07:00
Andrew Kelley
bb0e28a54f Sema: fix generic function with void parameters
This also fixes a bug that I didn't see causing any problems yet in
generic function instantiation where it would read from a GetOrPutResult
too late.

Also it delays full resolution of generic function type parameters until
after the function body is finished being analyzed.

closes #11291
2022-03-24 19:36:36 -07:00
Andrew Kelley
7cfa97aa4e std.meta.trait: remove assumption about vector ABI size
The unit test for hasUniqueRepresentation asserted that a vector of
length 3 would not have a unique representation. This would be true if
it were lowered to ABI size 8 instead of 6. However lowering it to ABI
size 6 is perfectly valid depending on the target.

This commit also simplifies the logic for hasUniqueRepresentation of
integers.
2022-03-24 18:09:45 -07:00
Andrew Kelley
5c68afef94 AstGen: fix const locals with comptime initializations
`const foo = comptime ...` generated invalid ZIR when the initialization
expression contained an array literal because the
validate_array_init_comptime instruction assumed that the corresponding
alloc instruction was comptime. The solution is to look slightly ahead
and notice that the initialization expression would be comptime-known
and affect the alloc instruction tag accordingly.
2022-03-24 17:47:39 -07:00
Andrew Kelley
9a1d5001d4 Sema: fix false negative detecting comptime const
The code for detecting when a local const initialization expression
ended up being comptime-known gave up when it encountered dbg_stmt
instructions, but such instructions are not supposed to matter.
2022-03-24 17:47:39 -07:00
Andrew Kelley
f5f5b9373d std.meta: fix unit tests depending on unstable behavior
The unit tests of std.meta depended on `@typeInfo` for the same type
returning a slice of declarations and fields with the same pointer
address. This is not something guaranteed by the language specification.
2022-03-24 17:47:39 -07:00
Jakub Konka
20cc560c2d Merge pull request #11286 from ziglang/stage2-aggregate-init
stage2: add debug info for tuples (and anon structs), and implement aggregate_init for structs and arrays
2022-03-24 22:29:20 +01:00
Andrew Kelley
b09280b484 move some files to the .github directory 2022-03-24 12:22:23 -07:00
Jakub Konka
04523db6ae x64: fix for 32bit builds 2022-03-24 18:54:17 +01:00
Jakub Konka
4ef26fc355 pass more behaviour tests 2022-03-24 17:04:50 +01:00
Jakub Konka
608025456b x64: account for signed ints in struct_field_val when struct fits in a register 2022-03-24 17:02:29 +01:00
Jakub Konka
9d2ff7ed16 x64: fix struct_field_val for structs fitting in register 2022-03-24 17:02:29 +01:00
Jakub Konka
77352c5bea x64: implement aggregate_init for arrays 2022-03-24 17:02:29 +01:00
Jakub Konka
4e801c2783 x64: implement aggregate_init for structs 2022-03-24 17:02:29 +01:00
Jakub Konka
2286f9bd1f dwarf: add debug info for tuples and anon structs 2022-03-24 17:02:29 +01:00
Andrew Kelley
2af69710a7 stage2: fix some generics issues
* std.meta: correct use of `default_value` in reification. stage1
   accepted a wrong type for `null`.
 * Sema: after instantiating a generic function, if the return type ends
   up being a comptime-known type, then we return an error, undoing the
   generic function instantiation, and making a comptime function call
   instead.
   - We also needed to clean up the dependency graph in this case.
 * Sema: reified enums set tag_ty_inferred to false since an integer tag
   type is provided. This is a limitation of the `@Type` builtin which
   will be addressed with #10710.
 * Sema: fix resolveInferredErrorSet incorrectly calling
   ensureFuncBodyAnalyzed on generic functions.
2022-03-23 23:28:05 -07:00
Andrew Kelley
aca42c6259 Sema: fix comptime elem_ptr compare fixed address 2022-03-23 19:58:13 -07:00
Andrew Kelley
74ccd0c40b Sema: Value.copy: we gotta copy the bytes
For Value.Tag.bytes, the value copy implementation did not copy the
bytes array. No good. This operation must do a deep copy. If we want
some other mechanism for not copying very large byte buffers then it has
to work differently than this one.
2022-03-23 19:20:38 -07:00
Andrew Kelley
7378ce67da Sema: introduce a type resolution queue
That happens after a function body is analyzed. This prevents circular
dependency compile errors and yet a way to mark types that need to be
fully resolved before a given function is sent to the codegen backend.
2022-03-23 18:45:51 -07:00
Andrew Kelley
57539a26b4 std.os: disable failing fnctl file locking test
See #11074
2022-03-23 17:29:39 -07:00
Andrew Kelley
e02ec8f7f5 Merge pull request #11280 from Luukdegram/wasm-errors
stage2: wasm - `@errorName` and more
2022-03-23 20:18:50 -04:00
Mitchell Hashimoto
a36f4ee290 stage2: able to slice to sentinel index at comptime
The runtime behavior allowed this in both stage1 and stage2, but stage1
fails with index out of bounds during comptime. This behavior makes
sense to support, and comptime behavior should match runtime behavior. I
implement this fix only in stage2.
2022-03-23 17:08:08 -04:00
Andrew Kelley
f27d3409bd behavior tests: disable failing stage1 test
My previous commit added a new behavior test that passes for stage2 but
I forgot to check whether it passes for stage1. Since it does not, it
has to be disabled.

Additionally, this commit organizes behavior tests; there is no longer a
section of tests only passing for stage1. Instead, tests are disabled on
an individual basis. There is an except for the file which has global
assembly in it.
2022-03-23 14:06:07 -07:00
Andrew Kelley
a2b0b0015d Merge pull request #11273 from topolarity/bugfix-11272
stage2: Properly "flatten" elem_ptrs before deref
2022-03-23 16:46:50 -04:00
Andrew Kelley
41e300adf1 add behavior test to cover bug fix in previous commit 2022-03-23 13:46:06 -07:00
Cody Tapscott
5374e245c5 stage2: Remove premature elem_val index check
We were enforcing bounds on the index of an elem_ptr in pointerDeref,
but we want to support out-of-bounds accesses by reinterpreting memory.
This removes that check, so that the deref falls back to bitcasting, as
usual.

This was masked by another bug that was forcing bitcasts incorrectly,
which is why this wasn't noticed earlier.
2022-03-23 13:44:31 -07:00
Cody Tapscott
1c22381909 stage2: Properly "flatten" elem_ptrs before deref
Sema.pointerDeref() assumes that elem_ptrs have been "flattened" when
they were created, so that you an elem_ptr will never be the array_ptr
of another elem_ptr when they share the same type.

Value.elemPtr does this already, but a couple of places in Sema were
bypassing this logic.
2022-03-23 13:44:31 -07:00
Luuk de Gram
5cb16dfa59 wasm: Enable all passing tests
All tests have been manually verified which are now passing. This means that any remaining
TODO is an actual to-be-fixed or to-be-implemented test case.
2022-03-23 21:40:33 +01:00
Luuk de Gram
60676a0ba5 wasm: Implement more instructions
Implements the following instructions:
 - int_to_float
 - ptr_slice_len_ptr
 - ptr_slice_ptr_ptr
 - unwrap_errunion_payload_ptr
 - unwrap_errunion_err_ptr
2022-03-23 21:40:33 +01:00
Luuk de Gram
685f05b562 wasm: Implement opt_payload_ptr
Implements lowering constants for pointers of value 'opt_payload_ptr'.
The offset is calculated by determining the abi size of the full type and
then substracting the payload size.
2022-03-23 21:40:33 +01:00
Luuk de Gram
a9a629f89a wasm: Fix switching on errors
Error sets contain the entire global error set.
Users are often switching on specific errors only present within that operand.
This means that cases are almost always sparse and not contiguous.
For this reason, we will instead emit the default case for error values not present in
that specific operand error set. This is fine as those cases will never be hit,
as prevented by the type system.

By still allowing jump tables for those cases, rather than if-else chains, we save runtime cost
as well as binary size.
2022-03-23 21:40:32 +01:00
Luuk de Gram
49051c0651 wasm: Implement @errorName
This implements the `error_name` instruction, which is emit for runtime `@errorName` callsites.

The implementation works by creating 2 symbols and corresponding atoms.
The initial symbol contains a table which each element consisting of a slice where the ptr field
points towards the error name, and the len field contains the error name length without the sentinel.

The secondary symbol contains a list of all error names from the global error set.

During the error_name instruction, we first get a pointer to the first symbol.
Then based on the operand we perform pointer arithmetic, to get the correct index into this table.
e.g. error index 2 = ptr + (2 * ptr size). The result of this will be stored in a local
and then returned as instruction result.

During `flush()` we populate the error names table by looping over the global error set
and creating a relocation for each error name. This relocation is appended to the table symbol.
Then finally, this name is written to the names list itself.

Finally, both symbols' atom are allocated within the rest of the binary.
When no error name is referenced, the `error_name_symbol` is never set, and therefore
no error name table will be emit into the final binary.
2022-03-23 21:40:32 +01:00
William Sengir
b872539a13 stage2: enable some passing array & vector tests 2022-03-23 16:39:29 -04:00
William Sengir
d7530c8f7b stage2: make zero-sized array not cause recursive type definition 2022-03-23 16:38:33 -04:00
Cody Tapscott
6fc07f49a9 stage2: concat/mult of slices yields ptr to array 2022-03-23 16:34:48 -04:00
Locria Cyber
23bae382c9 Add sem_open & sem_close 2022-03-23 16:31:03 -04:00
Cody Tapscott
a9a91a5d49 stage2 CBE: Improve support for unions and error sets
This includes various fixes/improvements to the C backend to improve
error/union support. It also fixes up our handling of decls, where some
decls were not correctly marked alive.
2022-03-23 16:29:38 -04:00
Andrew Kelley
2f9264d8dc stage2: fix -Domit-stage2 regression
This flag is used when building stage1 to omit the stage2 backends from
the compiler to save memory on the CI server. It regressed with the
merging of e8813b296b because Value
functions started calling into Sema functions.

The end goal for this build option is to eliminate it.
2022-03-23 13:24:55 -07:00
Marc Tiehuis
2e0de0b4e2 math/big: correct fix for divmod (#11271)
Fixes #11166.
2022-03-23 19:24:25 +01:00
Andrew Kelley
1cf1346323 Sema: rename isArrayLike to isArrayOrVector 2022-03-22 22:00:03 -07:00
Andrew Kelley
8326ab7adb Sema: fix merge conflicts with previous commit
The previous commit and e8813b296b had
merge conflicts which didn't get caught by git.
2022-03-22 20:44:32 -07:00
Mitchell Hashimoto
e81ebc24e9 stage2: runtime safety checks for slicing 2022-03-22 23:41:59 -04:00
Jakub Konka
47f1a43bb7 dwarf: lower enums 2022-03-22 23:37:20 -04:00
Daniele Cocca
8f9c3fd3df CBE: enable more passing tests (#11258) 2022-03-22 23:24:36 -04:00
Locria Cyber
eb5e0cba21 Fix ucontext_t 2022-03-22 23:19:02 -04:00
Andrew Kelley
4a837dddd0 Merge pull request #11266 from joachimschmidt557/stage2-arm
stage2 ARM: move closer to test runner output working
2022-03-22 23:18:26 -04:00
Andrew Kelley
98b932cfab fix merge conflicts 2022-03-22 20:17:43 -07:00
joachimschmidt557
be1cca3416 stage2 ARM: implement comparison of optional pointers 2022-03-22 20:16:05 -07:00
joachimschmidt557
95e166b2e1 stage2 ARM: implement min, max for integers <= 32 bits 2022-03-22 20:16:05 -07:00
joachimschmidt557
62529a291b stage2 ARM: More support for error unions 2022-03-22 20:16:05 -07:00
joachimschmidt557
a4e8294c91 stage2 ARM: change semantics of MCValue.stack_argument_offset
MCValue.stack_argument_offset now has the same semantics as
MCValue.stack_offset
2022-03-22 20:16:05 -07:00
joachimschmidt557
6ac04d8fd7 stage2 ARM: change semantics of MCValue.stack_offset
A stack_offset will now denote the exact offset applied to the start
of the stack frame (=fp when frame pointer is emitted)
2022-03-22 20:16:05 -07:00
Andrew Kelley
e8813b296b Merge pull request #11260 from ziglang/lazy-alignof
stage2: lazy `@alignOf`
2022-03-22 22:30:38 -04:00
Mitchell Hashimoto
cb6364624f stage2: slice behavior test passes, just has diff behavior from stage1
This is from discussions from #11249. The stage2 behavior is correct and
is strictly more accurate, so we'd prefer to keep it. In that case, I
modified the behavior tests to have the conditional between
stage1/stage2 and get this test passing.
2022-03-22 19:56:10 -04:00
Andrew Kelley
44f9061b71 fix merge conflicts and test cases 2022-03-22 15:58:19 -07:00
Andrew Kelley
60d8c4739d Sema: introduce a mechanism in Value to resolve types
This commit adds a new optional argument to several Value methods which
provides the ability to resolve types if it comes to it. This prevents
having duplicated logic inside both Sema and Value.

With this commit, the "struct contains slice of itself" test is passing
by exploiting the new lazy_align Value Tag.
2022-03-22 15:45:59 -07:00
Andrew Kelley
593130ce0a stage2: lazy @alignOf
Add a `target` parameter to every function that deals with Type and
Value.
2022-03-22 15:45:58 -07:00
Jakub Konka
b74f292410 Revert "ignore target lib dirs when invoked with -feach-lib-rpath"
This reverts commit 3701697a0a.

The commit introduced a regression when building stage2 on nixOS where
the linker would fail to find relevant LLVM dynamic libraries as some
search dirs were missing.
2022-03-22 20:51:34 +01:00
Jan200101
3701697a0a ignore target lib dirs when invoked with -feach-lib-rpath 2022-03-22 09:03:22 +01:00
Jakub Konka
0376fd09bc macho: extend CodeSignature to accept entitlements
With this change, we can now bake in entitlements into the binary.
Additionally, I see this as the first step towards full code signature
support which includes baking in Apple issued certificates for
redistribution, etc.
2022-03-22 07:06:39 +01:00
Mitchell Hashimoto
91fd0f42c8 stage2: out of bounds error for slicing 2022-03-21 22:10:34 -04:00
Andrew Kelley
0fb005d1d0 Sema: dummy implementation of @errorReturnTrace
Also update std/build.zig to use stage2 function pointer semantics.

This gets us a little bit closer to `zig build` working, although it is
now hitting a new crash in the compiler.
2022-03-21 19:08:30 -07:00
Luuk de Gram
be579d4797 wasm: Implement @popCount 2022-03-21 22:01:34 -04:00
Andrew Kelley
7141356838 Merge pull request #11237 from wsengir/stage2-vectors
stage2: implement most vector operations in Sema and LLVM backend
2022-03-21 20:05:29 -04:00
Andrew Kelley
7eddef423d behavior tests: alter test coverage for vectors
* Use `@Vector` syntax instead of `std.meta.Vector`.
 * Use `var` instead of `const` for tests so that we get runtime
   coverage instead of only comptime coverage. Comptime coverage is done
   with `comptime doTheTest()` calls.
2022-03-21 17:03:24 -07:00
Andrew Kelley
513a53e9aa Sema: restore propagation of error.GenericPoison for checking vectors 2022-03-21 17:03:05 -07:00
William Sengir
c9598c4cd3 behavior tests: enable all vector tests for the stage2 LLVM backend 2022-03-21 16:54:19 -07:00
William Sengir
afdcfb005e Sema: make most instructions vector-agnostic
Made most `Value` functions require a `Type`. If the provided type is a
vector, then automatically vectorize the operation and return with
another vector. The Sema side can then automatically become vectorized
with minimal changes. There are already a few manually vectorized
instructions, but we can simplify those later.
2022-03-21 16:54:19 -07:00
William Sengir
3f4676901a stage2: return Value.zero when truncating int to 0 bits at comptime 2022-03-21 16:54:19 -07:00
William Sengir
2d8fef5680 stage2: make bool binop AIR return types based on operand type
This allows vector-of-bools operands to return a vector-of-bools.
2022-03-21 16:54:19 -07:00
William Sengir
4e357151a5 stage2: align store for vector-to-array bitcast in LLVM backend
This was causing a very rare segfault when LLVM would emit `vmovdqa`
using an unaligned memory operand on the stack.
2022-03-21 16:54:19 -07:00
William Sengir
961248cde3 stage2: make more instructions vector-compatible in LLVM backend 2022-03-21 16:54:19 -07:00
William Sengir
b96699059c stage2: implement cmp_vector for LLVM backend 2022-03-21 16:54:19 -07:00
William Sengir
0f48307041 stage2: add AIR instruction cmp_vector
The existing `cmp_*` instructions get their result type from `lhs`, but
vector comparison will always return a vector of bools with only the
length derived from its operands. This necessitates the creation of a
new AIR instruction.
2022-03-21 16:54:19 -07:00
William Sengir
862e63f535 stage2: fix typo in print_air.zig 2022-03-21 16:54:19 -07:00
William Sengir
cda8f65489 behavior tests: use expect instead of expectEqual in vector.zig 2022-03-21 16:54:19 -07:00
Jakub Konka
2f4473b653 macho: add more codesig constants 2022-03-22 00:03:13 +01:00
Jakub Konka
d71bd0300b Merge pull request #11195 from mparadinha/float-to-int
stage2: x86_64: implement `@floatToInt` for `f32` and `f64`
2022-03-21 23:54:36 +01:00
Jakub Konka
a9b6de693c Merge pull request #11223 from mparadinha/ptr-elem-val
stage2: x86_64: implement `ptr_elem_val`
2022-03-21 23:54:17 +01:00
Jakub Konka
00e2113c8b x64: refactor fix reg aliasing in genSetReg 2022-03-21 23:38:01 +01:00
Andrew Kelley
916a65cb7b Merge pull request #11224 from koachan/sparc64-codegen
stage2 sparcv9: Add instruction encoder and placeholder codegen impl
2022-03-21 18:21:31 -04:00
mparadinha
79e2d4b3f6 stage2: x86_64: update passing tests after implementing ptr_elem_val
the 3 tests that called `testArray2DConstDoublePtr` started passing
after implementing `ptr_elem_val`. the rest of these I think were
already passing before.
2022-03-21 20:13:27 +00:00
mparadinha
35eaaed7c4 stage2: x86_64: use correct register size when loading things from memory 2022-03-21 19:32:46 +00:00
mparadinha
6d7808e647 stage2: x86_64: implement ptr_elem_val
The codegen for this is almost identical to `ptr_elem_ptr` except
there's an extra `mov` at the end to replace the pointer with the
value it points to, "in-place" (which can be done in a single
instruction without any extra registers).
2022-03-21 19:32:46 +00:00
Andrew Kelley
18a43b61f9 Merge pull request #11253 from Vexu/pretty-print-values
stage2: print values with types
2022-03-21 15:15:38 -04:00
Veikka Tuominen
0577069af5 stage2 llvm: fix lowerDeclRefValue for function aliases 2022-03-21 15:12:32 -04:00
Veikka Tuominen
59668fbe80 stage2: add test for fixed issue
Closes #11157
2022-03-21 15:05:21 +02:00
Veikka Tuominen
a31fe0ff12 stage2: add way to print values with types 2022-03-21 15:03:42 +02:00
Joachim Schmidt
b48d8cce52 Merge pull request #11235 from joachimschmidt557/stage2-riscv
stage2 RISCV64: remove MCValue.embedded_in_code
2022-03-21 12:36:47 +01:00
Lee Cannon
3d8d6c0a6d OptionsStep: Always use fmtId for type names. 2022-03-21 02:22:43 -04:00
Andrew Kelley
827538b88f Merge pull request #11241 from jagt/master
add compiler_rt ceilf/ceil/ceill
2022-03-21 02:22:07 -04:00
William Sengir
a5dc3f0342 stage2: add safety checks for index out of bounds 2022-03-20 18:04:38 -04:00
Andrew Kelley
65058ebd72 freestanding libc: remove ceil functions
Now that they are in compiler-rt, they can be removed from here.
2022-03-20 13:29:48 -07:00
jagt
b7f4045184 add compiler_rt ceilf/ceil/ceill
this should fix stage1 build error with msvc 2019
2022-03-20 13:29:23 -07:00
William Sengir
9f25c8140c cmake: add missing DWARF files to ZIG_STAGE2_SOURCES 2022-03-20 14:48:37 +01:00
Daniel Hooper
911c839e97 add error when binary ops don't have matching whitespace on both sides
This change also moves the warning about "&&" from the AstGen into the parser so that the "&&" warning can supersede the whitespace warning.
2022-03-20 12:55:04 +02:00
Andrew Kelley
0576086395 stage2: remove Value.Tag.abi_align_default
and make Decl alignment & linksection, and struct & union field alignment
be scalar values, not Value values.

YAGNI
2022-03-20 00:36:44 -07:00
Andrew Kelley
3ef34feaeb tools: fix gdb pretty printers
needed after merging 5c3325588e.
2022-03-20 00:36:44 -07:00
Andrew Kelley
6d73f89bf1 stage2: disable default panic handler when linking -lc
It's failing to compile std.os.dl_iterate_phdr correctly.
2022-03-20 00:36:44 -07:00
Daniele Cocca
b6203b89d6 CBE: implement mod, divFloor, divTrunc 2022-03-19 21:01:36 -04:00
Andrew Kelley
1bd595ceea Merge pull request #11233 from Luukdegram/wasm-tests
stage2: wasm - union_init and passing tests
2022-03-19 19:41:55 -04:00
Cody Tapscott
19331b323d stage2: Correctly align decls for comptime allocs
This updates WipAnonDecl to require an alignment provided by the caller,
which is needed for explicitly aligned comptime allocs.
2022-03-19 19:41:23 -04:00
Robin Voetter
5c3325588e stage1: make type names more unique 2022-03-19 19:40:46 -04:00
Andrew Kelley
a318aeed9b Merge pull request #11222 from Vexu/dbg_block
stage2: add debug info for payload captures + inline function parameters
2022-03-19 16:05:22 -04:00
Luuk de Gram
2fc91a09a2 wasm: Enable passing tests
This enables the tests that now pass due to the changes to lower
parent pointers are lowered, as well as the additional features to unions.
2022-03-19 20:56:04 +01:00
Luuk de Gram
56590218c5 wasm: All union/tuple/array tests passing
This implements improvements/fixes to get all the union, tuple, and array behavior tests passing.
Previously, we lowered parent pointers for field_ptr and element_ptr incompletely. This has now
been improved to recursively lower such pointer.

Also a fix was done to `generateSymbol` when checking a container's layout.
Previously it was assumed to always be a struct. However, the type can also be a tuple, and therefore
panicking. Updating to ask a type's container layout instead allows us to keep a singular branch for both cases.
2022-03-19 20:56:04 +01:00
Luuk de Gram
2041176c5e wasm: Implement union_init instruction
Implements the `@unionInit` builtin instruction.
2022-03-19 20:56:03 +01:00
Mitchell Hashimoto
6766528657 stage2: fix crash that could happen if as zir fails
Example scenario:

    test {
        const a: i32 = blk: {
            if (false) break :blk 24;
        };
        _ = a;
    }

Prior to this, this would panic the compiler with a source needed error.
This provides the source as `sema.src`. This is not ideal, since the
line it points to is pretty far from the true issue. (One block out)

But, this prevents the compiler from straight up crashing and follows a
pattern used by similar ZIR which don't provide a src loc.
2022-03-19 15:55:23 -04:00
joachimschmidt557
a153732d5a stage2 RISCV64: implement add, sub for registers 2022-03-19 20:44:57 +01:00
joachimschmidt557
7cdc47a4e0 stage2 RISCV64: implement move register to register 2022-03-19 19:48:27 +01:00
Andrew Kelley
69e6d455ce Merge pull request #11228 from Vexu/panic
enable default panic handler for stage2 LLVM
2022-03-19 14:32:09 -04:00
zseri
c6cf40a0c0 fix sigaction double panic
Fixes #8357
2022-03-19 19:13:31 +02:00
fn ⌃ ⌥
d62b1c932e translate-c: add missing builtins used by CRuby 2022-03-19 19:08:17 +02:00
Veikka Tuominen
12f3c461a4 Sema: implement zirSwitchCaptureElse for error sets 2022-03-19 15:49:27 +02:00
Veikka Tuominen
c9b6f1bf90 std: enable default panic handler for stage2 LLVM on Linux 2022-03-19 14:05:57 +02:00
Veikka Tuominen
2757237332 Sema: add error for runtime block peer type being comptime only 2022-03-19 13:36:16 +02:00
joachimschmidt557
956d9f4ce0 stage2 RISCV64: remove MCValue.embedded_in_code 2022-03-19 10:52:59 +01:00
Veikka Tuominen
d56e3c988f stage2: fix inline fn parameter debug info being added to wrong block 2022-03-19 11:40:45 +02:00
Veikka Tuominen
1e1f740347 AstGen: always add dbg_block_end before last instruction 2022-03-19 11:20:38 +02:00
Veikka Tuominen
30e17cd5d0 Sema: add debug info for inline function parameters 2022-03-19 11:20:38 +02:00
Veikka Tuominen
f19731948e Sema: balance dbg_block_begins in case of early return 2022-03-19 11:20:38 +02:00
Veikka Tuominen
739734170e stage2: add debug info for payload captures 2022-03-19 11:20:38 +02:00
Veikka Tuominen
a8520fbd0f stage2: add dbg_block_{begin,end} instruction 2022-03-19 11:20:38 +02:00
Koakuma
731dda18dd stage2 sparcv9: zig fmt 2022-03-19 09:06:58 +07:00
Koakuma
59680b40a1 stage2 sparcv9: Fix unused parameter errors in Codegen 2022-03-19 06:58:50 +07:00
Koakuma
93b16de4b4 stage2 sparcv9: Add placeholder files and generate() function
Add placeholder files for Codegen, Emit, and Mir stages, complete with
a placeholder implementation of generate() to make it able to be plugged in
to the frontend. At the moment the implementation just panics, it'll be
worked on incrementally later.

Also, this registers the sparcv9 backend files into CMakeLists.txt.
2022-03-19 06:09:46 +07:00
Andrew Kelley
ad5770eba4 organize behavior tests
* Identify the ones that are passing and stop skipping them.
 * Flatten out the main behavior.zig file and have each individual test
   disable itself if it is not passing.
2022-03-18 15:02:52 -07:00
Andrew Kelley
d5803441cd Merge pull request #11220 from schmee/vector-bitreverse
stage2: implement `@bitReverse` for vectors
2022-03-18 15:27:08 -04:00
Andrew Kelley
e60c0468aa Merge pull request #11217 from jmc-88/cbe-tuples
CBE: add support for tuples
2022-03-18 15:23:40 -04:00
Jakub Konka
338bf55e84 Merge pull request #11216 from joachimschmidt557/stage2-arm
stage2 ARM: remove MCValue.embedded_in_code
2022-03-18 20:02:33 +01:00
Mitchell Hashimoto
3865a61a99 stage2: formatting an error_set value should print members, not decl 2022-03-18 14:53:54 -04:00
Andrew Kelley
5765755fcd Merge pull request #11218 from mitchellh/labeled-break
AstGen: labeled blocks should always complete with a normal break
2022-03-18 14:50:40 -04:00
Andrew Kelley
de8f3bc885 AstGen: remove unused parameter
This function took a parameter that was only ever used with one value,
obscuring the fact that it was a regular `block` which should be used with
`.break` and not `.break_inline`.
2022-03-18 11:49:18 -07:00
Mitchell Hashimoto
3e74acb139 AstGen: labeled blocks should always complete with a normal break
They aren't inline blocks by nature of being labeled.

Fixes #11213
2022-03-18 11:40:39 -07:00
joachimschmidt557
13321c8070 stage2 regalloc: fix tryAllocRegs for specific situations
Previously, tryAllocRegs did not take frozen registers into account
when checking if enough registers are available.
2022-03-18 19:37:01 +01:00
Daniele Cocca
6fdca525de CBE: add support for tuples
Also promote tests that are now passing.
2022-03-18 16:50:34 +00:00
John Schmidt
e99b1b398a Refactor to sema.typeHasOnePossibleValue 2022-03-18 16:28:38 +01:00
John Schmidt
870341e32e stage2: implement @bitReverse for vectors 2022-03-18 16:28:38 +01:00
Daniele Cocca
085e122e29 bugs/3779: replace expectEqual*() with expect() 2022-03-18 11:20:28 +00:00
joachimschmidt557
c32e2c4d3c stage2 ARM: remove MCValue.embedded_in_code 2022-03-18 12:19:22 +01:00
Daniele Cocca
af8586da3a tuple: replace expectEqual() with expect() 2022-03-18 11:18:12 +00:00
joachimschmidt557
3ecba7d7a2 stage2 ARM: implement slice_elem_ptr, ptr_elem_ptr 2022-03-18 12:12:14 +01:00
Andrew Kelley
f3f5a5d05b stage2: improve @typeName
* make it always return a fully qualified name. stage1 is inconsistent
   about this.
 * AstGen: fix anon_name_strategy to correctly be `func` when anon type
   creation happens in the operand of the return expression.
 * Sema: implement type names for the "function" naming strategy.
 * Put "enum", "union", "opaque", or "struct" in place of "anon" when
   creating respective anonymous Decl names.
 * std.testing: add `expectStringStartsWith`. Didn't end up using it
   after all.

Also this enables the real test runner for stage2 LLVM backend (sans
wasm32) since it works now.
2022-03-18 00:12:22 -07:00
Andrew Kelley
69d78bdae4 stage2 test harness: ask for the backend explicitly
Follow-up to 35d6ee08c4
2022-03-17 20:10:00 -07:00
Andrew Kelley
1d1364c3cd Sema: change how undefined is handled in coerce
Instead of doing it before the switch tower, do it afterwards, so that
special handling may be done before undefined gets casted to the
destination type.

In this case the special handling we want to do is *[N]T to []T setting
the slice length based on the array length, even when the array value is
undefined.
2022-03-17 19:59:20 -07:00
Andrew Kelley
46ba24010a CI: explicitly pass -fno-LLVM
Needed because of previous commit.
2022-03-17 19:12:27 -07:00
Andrew Kelley
35d6ee08c4 stage2: default to LLVM backend
on targets for which self-hosted backends are not up to par.

See #89
2022-03-17 19:03:37 -07:00
Andrew Kelley
76b382072a Merge pull request #11200 from Luukdegram/wasm-memcpy
stage2: wasm - Implement memcpy instruction
2022-03-17 18:25:15 -07:00
Luuk de Gram
79679be50d sema: Fix memory leak
When a generic call evaluates to a generic type, the call will be re-generated.
However, the old function was not freed before being re-generated, causing a memory leak.
So rather than only returning an error, we first free the old value.
2022-03-17 18:20:03 -07:00
Steven Fackler
9dc9219b2f Don't strip by default in cc or c++ 2022-03-17 18:16:24 -07:00
Andrew Kelley
ff21cb42a0 Merge pull request #11206 from schmee/vector-byteswap
Implement `@byteSwap` for vectors
2022-03-17 18:04:46 -07:00
Andrew Kelley
4fa5060633 Sema: take advantage of checkIntOrVectorAllowComptime 2022-03-17 18:04:06 -07:00
John Schmidt
d7d2ccb7af Avoid index out of bounds for one-valued types in zirValidateArrayInit
Previously, the code assumed that `ptr_elem_ptr` was always followed by
a `store`, but this is not true for types with one value (such as `u0`).
2022-03-17 18:00:48 -07:00
John Schmidt
adfcc8851b Implement @byteSwap for vectors
Make the behavior tests for this a little more primitive to exercise as
little extra functionality as possible.
2022-03-17 18:00:48 -07:00
Andrew Kelley
7233a3324a stage2: implement @reduce
Notably, Value.eql and Value.hash are improved to treat NaN as equal to
itself, so that Type/Value can be hash map keys. Likewise float hashing
normalizes the float value before computing the hash.
2022-03-17 17:24:35 -07:00
Andrew Kelley
76e103057e zig_llvm.h: fix some declarations not being C compatible 2022-03-17 17:24:11 -07:00
Andrew Kelley
9ed3eb9cde std.testing: fix incorrect docs that mentioned aborting
At some point we changed these functions to return errors instead of
aborting.
2022-03-17 17:23:22 -07:00
Andrew Kelley
73e51133c3 langref: small clarification of @reduce 2022-03-17 17:22:57 -07:00
Luuk de Gram
215a22541c wasm: Improve memset implementation
When the length is comptime-known, we perform an inline loop instead of emitting
a runtime loop into the binary.

This also allows us to easily write 'undefined' to aggregate types.
We now do this when we set the error tag of an error union where the payload will be set to undefined.
2022-03-17 20:41:26 +01:00
Luuk de Gram
eafdc5562f wasm: Implement 'memcpy' instruction
This implements the `memcpy` instruction and also updates the inline memcpy calls
to make use of the same implementation. We use the fast-loop when the length is comptime known,
and use a runtime loop when the length is runtime known.
We also perform feature-dection to emit a simply wasm memory.copy instruction when the feature
'bulk-memory' is enabled. (off by default).
2022-03-17 20:41:23 +01:00
Andrew Kelley
291f5055f4 disable x86_64 behavior test that does not run valgrind clean 2022-03-17 11:48:50 -07:00
Andrew Kelley
1ee7a81627 Revert "link.Elf: swap order of GOT and text program headers"
This reverts commit 8e7b1a74ac.

Sorry, I should have put up a PR and ran that one by Jakub and done some
more inspection.

This causes problems with gdb:

BFD: /home/andy/dev/zig/build-release/test: invalid string offset 3254779904 >= 153524 for section `.shstrtab'
2022-03-17 11:41:17 -07:00
Daniele Cocca
00ed8d9c50 CBE: enable more tests that are currently passing 2022-03-17 11:39:56 -07:00
Andrew Kelley
8e7b1a74ac link.Elf: swap order of GOT and text program headers
This makes Valgrind happier because it results in the program headers
being sorted by VirtAddr in the ELF file.
2022-03-17 11:36:17 -07:00
Jakub Konka
fdee7dd60d debug: msync only current page when validation frame pointer
This fixes lack of stack traces on arm64 macOS which were regressed
and not getting generated at all after this addition to write
current stack traces. Prior to this, function `isValidMemory` would
sync two subsequent pages if the aligned (base) address was different
than the frame pointer. I fail to see what the logic for such assumption
here is as the manual of `msync` clearly states it will fail with error
if the passed in memory region length contains unmapped regions.

This was the very reason why there were no stack traces print on
arm64 macOS as the second page was unmapped thus incorrectly flagging
the frame pointer as invalid.
2022-03-17 18:21:04 +01:00
Jakub Konka
4012fcb0a3 macho: do not allocate new GOT atom when target atom has grown
That's the entire point of our GOT so that we don't have to do that;
simply overwrite the address in the GOT.
2022-03-17 12:48:02 +01:00
Jakub Konka
d53e0234a3 macho: fix snapshot generation 2022-03-17 11:41:08 +01:00
Jakub Konka
648afbc839 macos: update Mach routines for accessing page info 2022-03-17 10:42:11 +01:00
Joachim Schmidt
3c3826bf93 Merge pull request #11192 from joachimschmidt557/stage2-arm
stage2 ARM: misc improvements
2022-03-17 09:40:41 +01:00
Andrew Kelley
87779cfd93 stage2: prevent UB in the LLVM backend
* Sema: fix `zirTypeInfo` allocating with the wrong arenas for some
   stuff.
 * LLVM: split `airDbgInline` into two functions, one for each AIR tag.
   - remove the redundant copy to type_map_arena. This is the first
     thing that lowerDebugType does so this hack was probably just
     accidentally avoiding UB (which is still present prior to this
     commit).
   - don't store an inline fn inst into the di_map for the generic
     decl.
   - use a dummy function type for the debug info to avoid whatever UB
     is happening.
   - we are now ignoring the function type passed in with the
     dbg_inline_begin and dbg_inline_end.
 * behavior tests: prepare the vector tests to be enabled one at a time.

Mitigates #11199.
2022-03-17 00:00:41 -07:00
Mitchell Hashimoto
79d3780fbd stage2: bit_not on u0 is always 0 2022-03-16 23:18:35 -07:00
Andrew Kelley
1af51a0833 Merge pull request #11196 from schmee/vector-muladd
Implement `@mulAdd` for vectors
2022-03-16 20:37:42 -07:00
Andrew Kelley
80642b5984 remove unnecessary TODO comment
`testing.expect` is better than `testing.expectEqual` for behavior
tests. Better for behavior tests to stick to only testing the limited
behavior they are meant to test and avoid functions such as
`expectEqual` that drag in too much of the standard library (in this
case to print helpful diffs about why a value is not equal to another).
2022-03-16 20:35:41 -07:00
John Schmidt
c8ed813097 Implement @mulAdd for vectors 2022-03-16 20:11:05 -07:00
Daniele Cocca
312536540b CBE: better handling of sentineled slices/arrays
Adds the sentinel element to the type name to avoid ambiguous
declarations, and outputs the sentinel element (if needed) even in what
would otherwise be empty arrays.
2022-03-16 19:58:45 -07:00
Andrew Kelley
d78b8c10b9 LLVM: fix slice debug info and functions
with return types that have no runtime bits
2022-03-16 17:22:16 -07:00
Andrew Kelley
942f8d07d1 Merge pull request #11193 from mitchellh/b-elem-ptr
stage2: elem_ptr needs to know if slice or direct access
2022-03-16 19:36:54 -04:00
Andrew Kelley
cdeb1fb881 Sema: different solution to elemVal
I think that reusing the ComptimePtrLoad infrastructure is ultimately
less logic and more robust than adding a `direct` flag to elem_ptr.

 * Some code in zirTypeInfo needed to be fixed to create proper
   Type/Value encodings.
 * comptime elemVal works by constructing an elem_ptr Value and then
   using the already existing pointerDeref function.

There are some remaining calls to Value.elemValue which should be
considered code smells at this point.
2022-03-16 16:29:08 -07:00
Mitchell Hashimoto
418197b6c5 stage2: elem_ptr needs to know if slice or direct access
This fixes one of the major issues plaguing the `std.sort` comptime tests.
The high level issue is that at comptime, we need to know whether `elem_ptr` is
being used to subslice an array-like pointer or access a child value. High-level
example:

    var x: [2][2]i32 = undefined;
    var a = &x[0]; // elem_ptr, type *[2]i32

    var y: [5]i32 = undefined;
    var b = y[1..3]; // elem_ptr, type *[2]i32

`a` is pointing directly to the 0th element of `x`. But `b` is
subslicing the 1st and 2nd element of `y`. At runtime with a well
defined memory layout, this is an inconsequential detail. At comptime,
the values aren't laid out exactly in-memory so we need to know the
difference.

This becomes an issue specifically in this case:

    var c: []i32 = a;
    var d: []i32 = b;

When converting the `*[N]T` to `[]T` we need to know what array to point
to. For runtime, its all the same. For comptime, we need to know if its
the parent array or the child value.

See the behavior tests for more details.

This commit fixes this by adding a boolean to track this on the
`elem_ptr`. We can't just immediately deref the child for `&x[0]`
because it is legal to ptrCast it to a many-pointer, do arithmetic, and
then cast it back (see behavior test) so we need to retain access to the
"parent" indexable.
2022-03-16 16:26:54 -07:00
mparadinha
355d0d0e7e stage2: x86_64: floatToInt for f32 and f64 2022-03-16 21:27:50 +00:00
mparadinha
66ef630006 stage2: x86_64: add new fld instruction 2022-03-16 21:24:09 +00:00
mparadinha
972d923f09 stage2: x86_64: add new fisttp instruction
this instruction does truncating conversion from floating point
values to signed integers.
2022-03-16 21:24:09 +00:00
Andrew Kelley
94672dfb19 stage2: fully resolve fn types after analyzing its body 2022-03-16 13:31:53 -07:00
Andrew Kelley
92a09eb1e4 std.heap.GeneralPurposeAllocator: use var for mutable locals
Required to be compatible with new language semantics.
2022-03-16 13:31:16 -07:00
Koakuma
7579f14e0f stage2 sparcv9: Add param/return regs list 2022-03-17 02:24:21 +07:00
joachimschmidt557
dcc1de12b0 stage2 ARM: implement addwrap, subwrap, mulwrap 2022-03-16 20:20:07 +01:00
joachimschmidt557
2412ac2c5f stage2 ARM: fix shl for ints with bits < 32 2022-03-16 20:20:07 +01:00
joachimschmidt557
0eebdfcad3 stage2 ARM: fix bitwise negation of ints with bits < 32 2022-03-16 20:20:07 +01:00
joachimschmidt557
ca1ffb0951 stage2 ARM: genSetStack for stack_argument_offset 2022-03-16 20:19:58 +01:00
Andrew Kelley
1f313b3d7c LLVM: make the load function copy isByRef=true types 2022-03-16 11:52:22 -07:00
Koakuma
ac50ac699f stage2 sparcv9: Add encoder test and packed struct workaround 2022-03-17 01:47:17 +07:00
Jakub Konka
dd55b72949 std: introduce posix_spawn as an alt to fork-exec
Currently, the new API will only be available on macOS with
the intention of adding more POSIX systems to it incrementally
(such as Linux, etc.).

Changes:
* add `posix_spawn` wrappers in a separate container in
  `os/posix_spawn.zig`
* rewrite `ChildProcess.spawnPosix` using `posix_spawn` targeting macOS
  as `ChildProcess.spawnMacos`
* introduce a `posix_spawn` specific `std.c.waitpid` wrapper which
  does return an error in case the child process failed to exec - this
  is required for any process that was spawned using `posix_spawn`
  mechanism as, by definition, the errors returned by `posix_spawn`
  routine cover only the `fork`-equivalent; `pre-exec()` and `exec()`
  steps are covered by a catch-all error `ECHILD` returned by `waitpid`
  on unsuccessful execution, e.g., no such file error, etc.
2022-03-16 19:40:44 +01:00
Veikka Tuominen
49c0bb1f33 Merge pull request #11177 from Vexu/dbg_func
Add debug info for inlined calls
2022-03-16 20:40:16 +02:00
Andrew Kelley
d4a7a9ac4c Merge pull request #11191 from Snektron/zig-gdb-improvements
Zig gdb improvements
2022-03-16 14:08:06 -04:00
Robin Voetter
4ff7553d6b gdb: restructure pretty printers into different files 2022-03-16 18:13:10 +01:00
Robin Voetter
0bd84e03b9 gdb: add printer for selfhosted Value 2022-03-16 17:57:31 +01:00
Robin Voetter
6830bcbb0a gdb: add printer for selfhosted Type 2022-03-16 17:40:21 +01:00
Koakuma
d9c33a610e stage2 sparcv9: Fix branch format asserts 2022-03-16 22:30:48 +07:00
Robin Voetter
feb8981a95 gdb: add slice, multi array list, and array hash map printers 2022-03-16 15:50:03 +01:00
Koakuma
1cea8b271e stage2 sparcv9: Add list of preserved regs 2022-03-16 21:40:59 +07:00
Koakuma
d6a35500e5 stage2 sparcv9: Reorder Format 4 wrappers too 2022-03-16 21:38:44 +07:00
Koakuma
1d4b9f44ed stage2 sparcv9: cc -> ccr 2022-03-16 21:38:44 +07:00
Koakuma
56413360a1 stage2 sparcv9: Reorder wrapper parameters to textual assembly order 2022-03-16 21:38:44 +07:00
Koakuma
17075bdb0c stage2 sparcv9: Add Format 3 encoder 2022-03-16 21:38:44 +07:00
Koakuma
bfe92f7d8c stage2 sparcv9: Fix bitcast typos 2022-03-16 21:38:43 +07:00
Koakuma
a8dde7f0ae stage2 sparcv9: Minor parameter type changes
Use the `Condition` type for 2b/2c and signed integer for 4b/4d.
2022-03-16 21:38:43 +07:00
Flandre Scarlet
f5a4d24cc0 stage2 sparcv9: Add Format 4 encoder 2022-03-16 21:38:43 +07:00
Koakuma
f64ce3abaf stage2 sparcv9: Fix typo in format2c 2022-03-16 21:38:43 +07:00
Koakuma
672da9c613 stage2 sparcv9: Add CCR and RCondition enums
This adds the list of CCRs and `rcond` constants as specified by the
ISA, and changes the template functions to use them.
2022-03-16 21:38:42 +07:00
Koakuma
fbcea86333 stage2 sparcv9: Add Format 2 encoder 2022-03-16 21:38:42 +07:00
Koakuma
048035ea55 stage2 sparcv9: Add Format 1 encoder 2022-03-16 21:38:42 +07:00
Koakuma
92c262aa93 stage2 sparcv9: Add initial toU32 function for serialization 2022-03-16 21:38:42 +07:00
Koakuma
a212d5931d stage2 sparcv9: Add register definitions & instruction formats
This adds the GPR/FPR register definitions and instruction formats
for SPARCv9.
I need to implement a separate enc() function because the register
values for the FPRs have to be encoded to a special format that's
separate from the normal register ID.
2022-03-16 21:38:41 +07:00
Robin Voetter
e18c29af5b gdb: add arraylist and hashmap printer 2022-03-16 12:40:08 +01:00
Veikka Tuominen
d83a26f068 stage2 llvm: keep track of inlined functions 2022-03-16 10:53:41 +02:00
Veikka Tuominen
0343811836 Sema: emit dbg_func around inline calls 2022-03-16 09:34:26 +02:00
Veikka Tuominen
0f112b9f6d AstGen: emit dbg_stmt before function calls and branch conditions 2022-03-16 09:27:31 +02:00
Veikka Tuominen
af2b03de83 Type: implement ptrInfo for optional pointers 2022-03-16 09:26:10 +02:00
Andrew Kelley
8a43d67c3b LLVM: fix LLVM assertion when slicing 2022-03-16 00:09:00 -07:00
Andrew Kelley
c3663f2617 LLVM: implement debug info for structs
This involved some significant reworking in order to introduce the
concept of "forward declarations" to the system to break dependency
loops.

The `lowerDebugType` function now takes an `enum { full, fwd }` and is moved
from `DeclGen` to `Object` so that it can be called from `flushModule`.

`DITypeMap` is now an `ArrayHashMap` instead of a `HashMap` so that we can
iterate over the entries in `flushModule` and finalize the forward decl
DITypes into full DITypes.

`DITypeMap` now stores `AnnotatedDITypePtr` values instead of
`*DIType` values. This is an abstraction around a `usize` which assumes
the pointers will be at least 2 bytes aligned and uses the least
significant bit to store whether it is forward decl or a fully resolved
debug info type.

`lowerDebugTypeImpl` is extracted out from `lowerDebugType` and it has a
mechanism for completing a forward decl DIType to a fully resolved one.
The function now contains lowering for struct types. Closes #11095.

There is a workaround for struct types which have not had
`resolveFieldTypes` called in Sema, even by the time `flushModule` is
called. This is a deficiency of Sema that should be addressed, and the
workaround removed. I think Sema needs a new mechanism to queue up type
resolution work instead of doing it in-line, so that it does not cause
false dependency loops. We already have one failing behavior test
because of a false dependency loop.
2022-03-16 00:09:00 -07:00
Andrew Kelley
cfc31b5bbd std.dwarf: avoid some async/await stuff in stage2 builds 2022-03-16 00:09:00 -07:00
Veikka Tuominen
2583be7585 stage2 llvm: fix @extern 2022-03-16 00:09:00 -07:00
Mitchell Hashimoto
394252c9db stage2: move duplicate error set check to AstGen 2022-03-16 01:41:22 -04:00
Andrew Kelley
9a6fa67cbc Sema: only do store_ptr tuple optimization for arrays
Check the big comment in the diff for more details.
Fixes default-initialization of structs from empty struct literals.
2022-03-15 19:21:58 -07:00
Mitchell Hashimoto
fd43434149 stage2: TypeInfo for func with generic return type should set null
Prior to these, the return type was non-null but the value was generic
poison which wasn't usable in user-space. This sets the value to null.
This also adds a behavior test for this.

Co-authored-by: InKryption <inkryption07@gmail.com>
2022-03-15 20:12:22 -04:00
Andrew Kelley
1149e8bb08 Merge pull request #11185 from topolarity/bugfix-11159
stage2: resolve panic on array-like tuple initialization
2022-03-15 20:03:58 -04:00
Cody Tapscott
480e7eec65 stage2: Fix panic on initializing comptime fields in tuple
This resolves https://github.com/ziglang/zig/issues/11159

The problem was that:
  1. We were not correctly deleting the field stores after recognizing
     that an array initializer was a comptime-known value.
  2. LLVM was not checking that the final type had no runtime bits, and
     so would generate an invalid store.

This also adds several test cases for related bugs, just to check these
in for later work.
2022-03-15 17:01:16 -07:00
Cody Tapscott
762c4a876b stage2: comptime fields should not affect opv/comptime-only 2022-03-15 17:01:07 -07:00
Mitchell Hashimoto
7d0b6956c0 stage2: resolve type fully when resolving inferred allocs
We must resolve the type fully so that pointer children (i.e. slices)
are resolved. Additionally, we must resolve even if we can know the
value at comptime because the `alloc_inferred` ZIR always produces a
constant in the AIR.

Fixes #11181
2022-03-15 19:55:21 -04:00
Andrew Kelley
2c434cddd6 AstGen: add missing coercion for const locals
A const local which had its init expression write to the result pointer,
but then gets elided to directly initialize, was missing the coercion to
the type annotation.
2022-03-15 16:41:10 -07:00
Andrew Kelley
d4a0d5f959 Sema: implement @truncate for SIMD vectors 2022-03-15 15:09:48 -07:00
Andrew Kelley
ea4d2759a5 Merge pull request #11180 from jmc-88/cbe3
CBE: amending an incorrect test name, plus two small fixes
2022-03-15 17:04:23 -04:00
William Sengir
6de8b4bc3d std.dwarf: implement basic DWARF 5 parsing
DWARF 5 moves around some fields and adds a few new ones that can't be
parsed or ignored by our current DWARF 4 parser. This isn't a complete
implementation of DWARF 5, but this is enough to make stack traces
mostly work. Line numbers from C++ don't show up, but I know the info
is there. I think the answer is to iterate through .debug_line_str in
getLineNumberInfo, but I didn't want to fall into an even deeper rabbit
hole tonight.
2022-03-15 16:53:45 -04:00
Daniele Cocca
71ca0b176f CBE: #undef linux in zig.h
Compilers will sometimes `#define linux 1` if the operating system in
use is Linux. This clashes with the code produced by the C backend when
processing the stdlib, e.g. std.Target.Os.VersionRange [^1] which is a
struct containing a field named `linux`.

The output of the C backend doesn't rely on this macro being defined,
and other code also shouldn't rely on it -- e.g. quoting from the GCC
documentation [^2]:

  """
  The C standard requires that all system-specific macros be part of
  the reserved namespace. All names which begin with two underscores, or
  an underscore and a capital letter, are reserved for the compiler and
  library to use as they wish. However, historically system-specific
  macros have had names with no special prefix; for instance, it is
  common to find unix defined on Unix systems.

  [...]

  We are slowly phasing out all predefined macros which are outside the
  reserved namespace. You should never use them in new programs, and we
  encourage you to correct older code to use the parallel macros
  whenever you find it. We don’t recommend you use the system-specific
  macros that are in the reserved namespace, either. It is better in the
  long run to check specifically for features you need
  """

[^1]: 8c32d989c9/lib/std/target.zig (L224)
[^2]: https://gcc.gnu.org/onlinedocs/cpp/System-specific-Predefined-Macros.html#System-specific-Predefined-Macros
2022-03-15 19:05:15 +00:00
Daniele Cocca
79f74943b5 CBE: fix output of airMinMax()
This was trying to output a ternary operator, but the output was broken
by the lack of a '?'.
2022-03-15 19:00:16 +00:00
Daniele Cocca
9b5737b5a6 s/testClz/testCtz/g
The test name here was likely the result of a bad copy-paste, as the
test code is actually testing for trailing zeroes, not leading zeroes.
2022-03-15 19:00:16 +00:00
Ali Chraghi
47e004d975 remove TODO 2022-03-15 13:49:41 -04:00
Tom Maenan Read Cutting
9bb19a090e std: Add elf.EM, coff.MachineType to Target.CPU.Arch conversions
target.Arch already supports finding the correct encoding for either
target, so being able to do the inverse has use cases for when parsing
files of an unknown target (i.e. for zar).
2022-03-15 13:48:42 -04:00
Andrew Kelley
c64279b15b Sema: fix shl_sat with comptime rhs 2022-03-14 23:15:01 -07:00
Andrew Kelley
1adb15098c LLVM: clean up airUnaryOp to call callFloatUnary
and make callFloatUnary support vectors. I tried to make it use
getIntrinsic, but that resulted in tripping `assert(id != 0)`.
2022-03-14 21:43:57 -07:00
Andrew Kelley
9eceba2485 Merge pull request #11128 from topolarity/comptime-memory-reinterp
stage2: Track parent type for `.elem_ptr`, `.field_ptr`, and `.*_payload_ptr`
2022-03-15 00:43:26 -04:00
Andrew Kelley
2f92d1a026 stage2: fixups for topolarity-comptime-memory-reinterp branch
* don't store `has_well_defined_layout` in memory.
 * remove struct `hasWellDefinedLayout` logic. it's just
   `layout != .Auto`. This means we only need one implementation, in
   Type.
 * fix some of the cases being wrong in `hasWellDefinedLayout`, such as
   optional pointers.
 * move `tag_ty_inferred` field into a position that makes it more
   obvious how the struct layout will be done. Also we don't have a
   compiler that intelligently moves fields around so this layout is
   better.
 * Sema: don't `resolveTypeLayout` in `zirCoerceResultPtr` unless
   necessary.
 * Rename `ComptimePtrLoadKit` `target` field to `pointee` to avoid
   confusion with `target`.
2022-03-14 21:43:03 -07:00
Cody Tapscott
50a1ca24ca Add test for issue #11139 2022-03-14 21:43:02 -07:00
Cody Tapscott
1f76b4c6b8 stage2 llvm: Respect container type when lowering parent pointers
We need to make sure that we bitcast our pointers correctly before
we use get_element_ptr to compute the offset for the parent
pointer.

This also includes a small fix-up for a problem where ptrs to const
i64/u64 were not using the correct type in >1-level decl chains
(where we call lowerParentPtr recursively)
2022-03-14 21:42:43 -07:00
Cody Tapscott
5fa057053c stage2 sema: Respect container_ty of parent ptrs
The core change here is that we no longer blindly trust that parent
pointers (.elem_ptr, .field_ptr, .eu_payload_ptr, .union_payload_ptr)
were derived from the "true" type of the underlying decl. When types
diverge, direct dereference fails and we are forced to bitcast, as
usual.

In order to maximize our chances to have a successful bitcast, this
includes several changes to the dereference procedure:
   - `root` is now `parent` and is the largest Value containing the
     dereference target, with the condition that its layout and the
     byte offset of the target within are both well-defined.
   - If the target cannot be dereferenced directly, because the
     pointers were not derived from the true type of the underlying
     decl, then it is returned as null.
   - `beginComptimePtrDeref` now accepts an optional array_ty param,
     which is used to directly dereference an array from an elem_ptr,
     if necessary. This allows us to dereference array types without
     well-defined layouts (e.g. `[N]?u8`) at an offset

The load_ty also allows us to correctly "over-read" an .elem_ptr to an
array of [N]T, if necessary. This makes direct dereference work for
array types even in the presence of an offset, which is necessary if
the array has no well-defined layout (e.g. loading from `[6]?u8`)
2022-03-14 21:42:43 -07:00
Cody Tapscott
54426bdc82 stage2: Fix assertion in struct field offset when all fields are 0-size 2022-03-14 21:42:42 -07:00
Cody Tapscott
34a6fcd88e stage2: Add hasWellDefinedLayout() to type.zig and Sema.zig
This follows the same strategy as sema.typeRequiresComptime() and
type.comptimeOnly(): Two versions of the function, one which performs
resolution just-in-time and another which asserts that resolution is
complete.

Thankfully, this doesn't cause very viral type resolution, since
auto-layout structs and unions are very common and are known to not have
a well-defined layout without resolving their fields.
2022-03-14 21:42:42 -07:00
Cody Tapscott
bbd750ff05 stage2: Add container_ty/elem_ty to elem_ptr, field_ptr, *_payload_ptr Values 2022-03-14 21:42:42 -07:00
Andrew Kelley
a2a5d3c288 Merge pull request #11167 from mitchellh/codegen-arrays
stage2: codegen of arrays should use type length, not value length
2022-03-15 00:40:32 -04:00
William Sengir
c757f19790 stage2: add debug info for globals in the LLVM backend
LLVM backend: generate DIGlobalVariable's for non-function globals and
rename linkage names when exporting functions and globals.

zig_llvm.cpp: add some wrappers to convert a handful of DI classes
into DINode's since DIGlobalVariable is not a DIScope like the others.

zig_llvm.cpp: add some wrappers to allow replacing the LinkageName of
DISubprogram and DIGlobalVariable.

zig_llvm.cpp: fix DI class mixup causing nonsense reinterpret_cast.

The end result is that GDB is now usable since you now no longer need
to manually cast every global nor fully qualify every export.
2022-03-15 00:38:20 -04:00
Andrew Kelley
f36bf8506c Merge pull request #11164 from mitchellh/reify-union
stage2: reify unions
2022-03-15 00:21:11 -04:00
Mitchell Hashimoto
67647154c1 stage2: apply fix for #11165 to codegen.zig for native backends
Co-authored-by: Cody Tapscott <topolarity@tapscott.me>
2022-03-14 20:00:17 -07:00
Mitchell Hashimoto
a859f94644 stage2: LLVM codegen of arrays should use type length, not value length
It is possible for the value length to be longer than the type because
we allow in-memory coercing of types such as `[5:0]u8` to `[5]u8`. In
such a case, the value length is 6 but the type length if 5.

The `.repeated` value type already got this right, so this is extending
similar logic out to `.aggregate` and `.bytes`. Both scenarios are
tested in behavior tests.

Fixes #11165
2022-03-14 17:41:12 -07:00
Andrew Kelley
84f96779c3 Merge pull request #11143 from jmc-88/cbe
CBE: Implement popCount, byteSwap, bitReverse for ints <= 128 bits
2022-03-14 18:23:00 -04:00
Curtis Tate Wilkinson
3bb4c0c789 zig fmt: Resolve #11131 loss of comment on switch cases
Correct switch cases dropping comments in certain situations by
checking for the presence of the comment before collapsing to one line.
2022-03-14 23:10:59 +01:00
Mitchell Hashimoto
53de31d62c stage2: enum reification should use sliceLen and elemValue 2022-03-14 14:38:05 -07:00
Mitchell Hashimoto
edd07aa808 stage2: reify unions 2022-03-14 14:34:28 -07:00
Daniele Cocca
8643591c9a CBE: split {clz,ctz,mod,popCount,byteSwap,bitReverse} by type
This also surfaces the fact that clz, ctz and popCount didn't actually
support 128 bit integers, despite what was claimed by
226fcd7c70. This was partially hidden by
the fact that the test code for popCount only exercised 128 bit integers
in a comptime context. This commit duplicates that test case for runtime
ints too.
2022-03-14 19:43:31 +00:00
Andrew Kelley
5ea94e7715 stage2: rework Value storage of structs and arrays
Now they both use `Value.Tag.aggregate`.

Additionally the LLVM backend now has implemented lowering of
tuple values.
2022-03-14 12:28:52 -07:00
Mitchell Hashimoto
1ebe3bd01d stage2: reify structs and tuples (#11144)
Implements `@Type` for structs, anon structs, and tuples. This is another place that would probably benefit from a `.reified_struct` type tag but will defer for later in the interest of getting tests passing first.
2022-03-14 13:47:35 -04:00
Andrew Kelley
5919b10048 Merge pull request #11155 from ziglang/stage2-float-fixes
stage2 float fixes
2022-03-14 12:38:56 -04:00
Andrew Kelley
b2a1b4c085 Sema: improve lowering of stores to bitcasted vector pointers
Detect if we are storing an array operand to a bitcasted vector pointer.
If so, we instead reach through the bitcasted pointer to the vector pointer,
bitcast the array operand to a vector, and then lower this as a store of
a vector value to a vector pointer. This generally results in better code,
as well as working around an LLVM bug.

See #11154
2022-03-14 00:11:46 -07:00
Andrew Kelley
eee989d2a0 Sema: Type.abiSize asserts instead of using max with alignment
ABI size is guaranteed to always be >= alignment.
2022-03-14 00:11:46 -07:00
Andrew Kelley
2a50a4629b freestanding libc: include roundl 2022-03-14 00:11:46 -07:00
Andrew Kelley
547e6f6ee1 disable failing nvptx test cases
See #10968
2022-03-14 00:11:46 -07:00
Andrew Kelley
7a477a1110 LLVM: fix int_to_float signedness detection
It was checking if the result (float) type was a signed int rather than
checking the operand (integer) type.
2022-03-14 00:11:46 -07:00
Andrew Kelley
d42d31f72f basic language features do not belong in std.meta 2022-03-14 00:11:46 -07:00
Andrew Kelley
eeaaefb925 LLVM: fix debug info for local vars
Previously we incorrectly used the pointer type as the debug info type.
2022-03-14 00:11:46 -07:00
Daniele Cocca
d912699e08 Remove signed_type from zig_{clz,ctz,popcount}
This parameter is only currently needed by zig_byte_swap() and
zig_bit_reverse(). This commit adds an option to airBuiltinCall() to
allow emitting the signedness information only when needed, removing
this unused parameter from the other builtins.
2022-03-14 01:04:24 +00:00
Daniele Cocca
5a971bbeea Review suggestion: use hasRuntimeBitsIgnoreComptime()
This should cover not only integers, as done in
87744a7ea9, but also void, enums with a
single field, etc...

Co-authored-by: Andrew Kelley <andrew@ziglang.org>
2022-03-14 00:52:20 +00:00
Koakuma
cb3b1dd6dd c/linux: Fix stat struct definition for SPARCv9
The libc interface uses `stat` instead of `stat64` struct.
This fixes, among other things, `zig fmt` accidentally setting the
formatted file's permission to 000.
2022-03-13 16:48:02 -04:00
Joachim Schmidt
bb859a0be7 Merge pull request #11150 from joachimschmidt557/stage2-aarch64
stage2 AArch64: misc improvements
2022-03-13 18:43:18 +01:00
Jakub Konka
76bceb240d std+macho: revert and fix exposing Mach wrappers in std.os and std.c 2022-03-13 17:03:04 +01:00
Jakub Konka
4a2100e820 std: more c/darwin.zig fixes 2022-03-13 15:42:40 +01:00
Jakub Konka
1af0c75d71 std: fix imports for darwin specific flags and funcs 2022-03-13 14:59:15 +01:00
Jakub Konka
68c224d6ec macho: simplify writing atoms for stage2
Also, fix premature exit in `link.File.makeWritable` in case we
are running M1 but executing binaries using Rosetta2.
2022-03-13 14:15:26 +01:00
Jakub Konka
633c4a2a60 macos: add Mach task abstraction
`std.os.darwin.MachTask` wraps `mach_port_t` and can be used to issue
kernel calls tied to the wrapped Mach kernel port/task.
2022-03-13 13:35:39 +01:00
joachimschmidt557
b74cd902c6 stage2 AArch64: enable mul for ints with <= 64 bits 2022-03-13 11:32:08 +01:00
joachimschmidt557
1f28c72c39 stage2 AArch64: implement ptr_add for all element sizes 2022-03-13 11:32:08 +01:00
joachimschmidt557
384e4ddb06 stage2 AArch64: spill compare flags when necessary 2022-03-13 11:32:08 +01:00
joachimschmidt557
12207bbbd6 stage2 AArch64: Implement bit shifting with immediate operands 2022-03-13 11:32:07 +01:00
joachimschmidt557
03dddc8d9c stage2 AArch64: implement bit shifts with register operands 2022-03-13 11:32:04 +01:00
Daniele Cocca
d0277a3d17 CBE: implement popCount, byteSwap, bitReverse for ints <= 128 bits
This folds the airCountZeroes() code from
226fcd7c70 back into airBuiltinCall(),
since most of these builtins happen to require the same arguments and
can be unified under a common function signature.
2022-03-13 09:59:15 +00:00
Daniele Cocca
87744a7ea9 CBE: skip 0 bit integers from function signatures
This was already done for void types, and needs to be done for 0 bit
integer types as well to align the rendered function signatures with the
effective size of extra.data.args_len as seen by airCall().
2022-03-13 09:59:15 +00:00
Jakub Konka
2036af94e9 macos: add kernel return values 2022-03-13 10:49:09 +01:00
Jakub Konka
a60292dfb3 macos: add more mach primitives 2022-03-13 09:42:24 +01:00
Andrew Kelley
0bc9635490 stage2: add debug info for locals in the LLVM backend
Adds 2 new AIR instructions:
 * dbg_var_ptr
 * dbg_var_val

Sema no longer emits dbg_stmt AIR instructions when strip=true.

LLVM backend: fixed lowerPtrToVoid when calling ptrAlignment on
the element type is problematic.

LLVM backend: fixed alloca instructions improperly getting debug
location annotated, causing chaotic debug info behavior.

zig_llvm.cpp: fixed incorrect bindings for a function that should use
unsigned integers for line and column.

A bunch of C test cases regressed because the new dbg_var AIR
instructions caused their operands to be alive, exposing latent bugs.
Mostly it's just a problem that the C backend lowers mutable
and const slices to the same C type, so we need to represent that in the
C backend instead of printing two duplicate typedefs.
2022-03-13 03:41:31 -04:00
Mitchell Hashimoto
7ec2261dbf stage2: add compiler test to ensure typed null doesn't coerce to any
In stage1, this behavior was allowed (by accident?) and also
accidentally exercised by the behavior test changed in this commit. In
discussion on Discord, Andrew decided this should not be allowed in
stage2 since there is currently on real world reason to allow this
strange edge case.

I've added the compiler test to solidify that this behavior should NOT
occur and updated the behavior test to the new valid semantics.
2022-03-12 22:03:01 -05:00
Andrew Kelley
804b82b6e8 Merge pull request #11130 from mitchellh/reify-enum
stage2: zirReify for enums
2022-03-12 16:20:43 -05:00
Guillaume Wenzek
f000f8a59a fix nvptx test failure #10968
allow test cases to chose wether to link libc or not.
default behavior is to not link libc, except for `exeUsingLLVMBackend`
2022-03-12 14:25:59 -05:00
Andrew Kelley
5ff7b04a6a Merge pull request #11133 from Vexu/stage2
stage2: misc fixes on the way to `std.debug.dumpCurrentStackTrace`
2022-03-12 14:18:58 -05:00
Mitchell Hashimoto
ef68420b78 stage2: reify opaque {} 2022-03-12 11:02:24 -08:00
joachimschmidt557
01081ce5a5 stage2 x86_64: Fix assertion in getResolvedInstValue 2022-03-12 18:33:25 +01:00
Veikka Tuominen
d532c21d89 AstGen: fix nosuspendExpr handling result location twice 2022-03-12 13:42:17 +02:00
Veikka Tuominen
487ee79ec9 stage2 llvm: do not use getIntrinsic for airFrameAddress
getIntrinsic gets the return type wrong so we have to add the function manually
2022-03-12 12:33:32 +02:00
Veikka Tuominen
a3cfb15fb4 Sema: always allow coercing error set to current inferred error set 2022-03-12 11:36:05 +02:00
Veikka Tuominen
07cc2fce2a Sema: fix else branch check when switching on error set 2022-03-12 11:25:37 +02:00
Veikka Tuominen
98a01f99c9 Sema: fix typo in resolvePeerTypes 2022-03-12 11:14:17 +02:00
matu3ba
e5d4a694ea std: add test for child_process
- Cli operations should be refactored, since the standard test runner
  has an expected argument structure. This would also ensure that the
  test cli is usable as tested library with checks for subprocess
  error or success instead of "hacky shell script interfaces".
- Default paths generation based on tmpDir would also be useful.
- Anonymous pipes on windows are generated from named pipes
- Async IO does not work on anonymous pipes
- Remove finished TODO
2022-03-12 10:25:18 +02:00
ominitay
42d75f1a25 std.math.lossyCast: fix integer overflow
Fixes integer overflow caused by cast from maxInt(u32) as an f32 to u32.
2022-03-12 10:23:57 +02:00
Andrew Kelley
b3259b47ad Type.eql: check fn attributes before params
slightly better for cache locality
2022-03-11 22:49:08 -07:00
Andrew Kelley
f6b479b81d LLVM: use hasRuntimeBitsIgnoreComptime instead of hasRuntimeBits
LLVM codegen doesn't care whether types are comptime or not. Comptime
types aren't supposed to make it to codegen anyway.
2022-03-11 22:48:35 -07:00
Andrew Kelley
98c950827f std.math: remove redundant namespace in test names
related: #7923
2022-03-11 22:47:45 -07:00
Andrew Kelley
0f3e849719 std.ArrayList: use variable for local mutable state
stage1 has the wrong semantics here
2022-03-11 22:47:24 -07:00
Mitchell Hashimoto
237d08389a stage2: use usizecast for safety 2022-03-11 21:37:41 -08:00
Mitchell Hashimoto
744b4ad578 stage2: reify should use pointerDecl to get array value 2022-03-11 21:36:06 -08:00
Mitchell Hashimoto
08159be375 stage2: enum field length must be a usize 2022-03-11 21:21:29 -08:00
Andrew Kelley
491e3ba6b1 LLVM: fix debug info for pointers to void 2022-03-11 21:00:07 -07:00
Andrew Kelley
60d6037f23 Sema: fix inline/comptime function calls with inferred errors 2022-03-11 20:44:10 -07:00
Andrew Kelley
55ba335e0f Sema: fix resolution of inferred error sets
Introduce `Module.ensureFuncBodyAnalyzed` and corresponding `Sema`
function. This mirrors `ensureDeclAnalyzed` except also waits until the
function body has been semantically analyzed, meaning that inferred
error sets will have been populated.

Resolving error sets can now emit a "unable to resolve inferred error
set" error instead of producing an incorrect error set type. Resolving
error sets now calls `ensureFuncBodyAnalyzed`. Closes #11046.

`coerceInMemoryAllowedErrorSets` now does a lot more work to avoid
resolving an inferred error set if possible. Same with
`wrapErrorUnionSet`.

Inferred error set types no longer check the `func` field to determine if
they are equal. That was incorrect because an inline or comptime function
call produces a unique error set which has the same `*Module.Fn` value for
this field. Instead we use the `*Module.Fn.InferredErrorSet` pointers to
test equality of inferred error sets.
2022-03-11 19:38:07 -07:00
Andrew Kelley
2ee3cc453c stage2: remove SPDX license header comments
These were missed in d29871977f.
2022-03-11 19:38:07 -07:00
Mitchell Hashimoto
015cc41e50 stage2: zirReify for enums 2022-03-11 17:44:52 -08:00
Andrew Kelley
6f986298c6 Merge pull request #11125 from jmc-88/cbe
CBE: promote an already passing test, and add implementation for clz, ctz for integers
2022-03-11 20:15:13 -05:00
Daniele Cocca
226fcd7c70 CBE: implement clz, ctz for ints <= 128 bits 2022-03-11 23:12:15 +00:00
Mitchell Hashimoto
fca51c81bc stage2: is_non_error always returns comptime true for empty error set 2022-03-11 17:16:34 -05:00
Mitchell Hashimoto
797f4db227 stage2: Array len field should be a usize not comptime_int 2022-03-11 17:15:36 -05:00
Daniele Cocca
6dcfbfbfb2 CBE: mark union_with_members as passing 2022-03-11 20:53:14 +00:00
Andrew Kelley
79b169c5a5 Merge pull request #11122 from mitchellh/anon-has-field
stage2: @hasField for anon structs
2022-03-11 15:01:51 -05:00
Andrew Kelley
a2517117e7 Sema: make @hasField support tuples too 2022-03-11 12:59:20 -07:00
Mitchell Hashimoto
6a9c9afbae stage2: @hasField for anon structs 2022-03-11 12:51:21 -07:00
Andrew Kelley
86a98b172b std.os: disable failing fnctl file locking test
See #11074
2022-03-11 12:49:53 -07:00
Andrew Kelley
4c1cc4d8d9 Merge pull request #11120 from Vexu/stage2
Stage2: make std.rand tests pass
2022-03-11 13:48:28 -05:00
Joachim Schmidt
5fbae9cd6f Merge pull request #11121 from joachimschmidt557/stage2-arm
stage2 ARM: implement caller-preserved registers
2022-03-11 17:43:36 +01:00
Veikka Tuominen
03b8206f27 Sema: make check for whether call should be memoized more thorough 2022-03-11 16:56:33 +02:00
joachimschmidt557
4590e980f7 stage2 ARM: implement caller-saved registers 2022-03-11 14:12:11 +01:00
joachimschmidt557
06058ed6f3 stage2 regalloc: replace Register.allocIndex with generic indexOfReg
* callee_preserved_regs and other ABI-specific information have been
moved to the respective abi.zig files
2022-03-11 13:29:16 +01:00
Veikka Tuominen
01cd4119b0 Sema: implement @shuffle at comptime and for differing lengths 2022-03-11 14:25:15 +02:00
Veikka Tuominen
cba68090a6 stage2: implement @shuffle at runtime 2022-03-11 13:12:32 +02:00
Veikka Tuominen
db42624170 Sema: enable shl and bitwise for vectors at runtime 2022-03-11 13:06:22 +02:00
Veikka Tuominen
98a5998d83 Sema: improve detection of generic parameters 2022-03-11 11:25:45 +02:00
Andrew Kelley
078037ab9b stage2: passing threadlocal tests for x86_64-linux
* use the real start code for LLVM backend with x86_64-linux
   - there is still a check for zig_backend after initializing the TLS
     area to skip some stuff.
 * introduce new AIR instructions and implement them for the LLVM
   backend. They are the same as `call` except with a modifier.
   - call_always_tail
   - call_never_tail
   - call_never_inline
 * LLVM backend calls hasRuntimeBitsIgnoringComptime in more places to
   avoid unnecessarily depending on comptimeOnly being resolved for some
   types.
 * LLVM backend: remove duplicate code for setting linkage and value
   name. The canonical place for this is in `updateDeclExports`.
 * LLVM backend: do some assembly template massaging to make `%%`
   rendered as `%`. More hacks will be needed to make inline assembly
   catch up with stage1.
2022-03-11 00:04:42 -07:00
Andrew Kelley
b28b3f6f7b stage2: fix comptime element load of undef array 2022-03-10 22:57:13 -07:00
Andrew Kelley
273da9efd9 AstGen: structInitExpr and arrayInitExpr avoid crash
when an inferred alloc is passed as the result pointer of a block.
2022-03-10 17:52:18 -07:00
Andrew Kelley
a30d283981 AstGen: lower anon struct inits differently
This is a companion commit to f2a5d0bf94.
What that one did for tuples, this one does for anonymous structs.
2022-03-10 17:52:18 -07:00
Andrew Kelley
b642fa24a6 stage2: implement integer pointer constants 2022-03-10 17:52:18 -07:00
Jakub Konka
b0dc61fae2 macos: add mach_* syscalls for process mgmt 2022-03-10 22:39:04 +01:00
Andrew Kelley
96f614d374 Merge pull request #11098 from mitchellh/error-merge-eql
stage2: error set type equality, error and error union value equality
2022-03-10 16:22:20 -05:00
Andrew Kelley
9f163310f2 stage2: improve Type.eql and Type.hash for error sets
* Reduce branching in Type.eql and Type.hash for error sets.
 * `Type.eql` uses element-wise bytes comparison since it can rely on
   the error sets being pre-sorted.
 * Avoid unnecessarily skipping tests that are passing.
2022-03-10 14:21:37 -07:00
Mitchell Hashimoto
569870ca41 stage2: error_set_merged type equality
This implements type equality for error sets. This is done
through element-wise error set comparison.

Inferred error sets are always distinct types and other error sets are
always sorted. See #11022.
2022-03-10 14:20:16 -07:00
Andrew Kelley
0b82c02945 Merge pull request #11113 from Vexu/stage2
stage2: if generic function evaluates to another generic function call it inline
2022-03-10 15:10:51 -05:00
Marc Tiehuis
8bab1b405f math: fix big.int div, gcd and bitAnd edge-cases
Fixes #10932.
2022-03-10 13:56:07 -05:00
Andrew Kelley
6e49ba77f3 std: add sort method to ArrayHashMap and MultiArrayList
This also adds `std.sort.sortContext` and
`std.sort.insertionSortContext` which are more advanced methods that
allow overriding the `swap` method. The former calls the latter for now
because reworking the main sort implementation is a big task that can be
done later without any changes to the API.
2022-03-10 13:13:17 -05:00
Veikka Tuominen
f9e4344bb5 Sema: implement zirStructInit is_ref=true union 2022-03-10 20:00:07 +02:00
Veikka Tuominen
673fafc231 stage2 llvm: implement lowerParentPtr for int_{u,i}64 2022-03-10 19:52:03 +02:00
Veikka Tuominen
e0fb0770d1 Sema: if generic function evaluates to another generic function call it inline
```zig
fn foo(a: anytype, b: @TypeOf(a)) void { _ = b; }
test {
    // foo evaluates to `fn (type) void` and must be called inline
    foo(u32, u32);
}
```
2022-03-10 13:04:55 +02:00
Veikka Tuominen
b9f521b402 Sema: add coercion from [:x]T to [*:x]T 2022-03-10 12:02:31 +02:00
Andrew Kelley
f736cde397 Sema: implement pointer to tuple to pointer to array coercion
This involved an LLVM backend fix for the aggregate_init instruction.
2022-03-09 18:49:37 -07:00
Meghan
017d3864de std: fix false positive for zig.isValidId with empty string (#11104)
* std: fix false positive for `zig.isValidId` with empty string, fixes #11099
* std: add zig.isValidId tests
2022-03-09 19:38:47 -05:00
Andrew Kelley
f32a77b30d Sema: implement pointer-to-tuple coercion to slice and struct 2022-03-09 17:33:01 -07:00
Andrew Kelley
3b6e8fa59e Sema: fix crash with @sizeOf on unions 2022-03-09 16:02:42 -07:00
Andrew Kelley
fd85cfe154 std.mem: remove redundant namespaces in test names
related: #7923
2022-03-09 15:44:08 -07:00
Andrew Kelley
83bb3d1ad6 Sema: fix generic fn instantiation with anytype
When the anytype parameter had only one-possible-value
(e.g. `void`), it would create a mismatch in the function type and the
function call. Now the function type and the callsite both omit the
one-possible-value anytype parameter in instantiated generic functions.
2022-03-09 15:35:13 -07:00
Andrew Kelley
2aa4a32097 Merge pull request #11105 from Luukdegram/wasm-misc
stage2: wasm - miscellaneous improvements
2022-03-09 16:03:20 -05:00
Luuk de Gram
90f08a69aa wasm: Enable passing behavior tests
This also adds some float-related instructions to MIR/Emit
2022-03-09 13:53:20 -07:00
Luuk de Gram
3ea113e008 wasm: Implement field_parent_ptr 2022-03-09 13:53:10 -07:00
Luuk de Gram
f931c0638d wasm: Implement errunion_payload_ptr_set
This also fixes `ret_ptr` where the pointee type is zero-sized.
2022-03-09 13:53:10 -07:00
Luuk de Gram
d01bfa032d wasm: Preliminary fptrunc support
This implements the initial fptrunc instruction. For all other floating-point truncating,
a call to compiler-rt is required. (This also updates fpext to emit the same error).
2022-03-09 13:53:10 -07:00
Luuk de Gram
684b81f366 wasm: Implement fpext
This implements initial support for floating-point promotion for bitsizes <= 64
2022-03-09 13:53:10 -07:00
Luuk de Gram
557f396f61 wasm: Improve switch implementation
- Implement switching over booleans and pointers.
- Fix sparse-detection where the lowest value was never truly set
as it started at a non-zero number and the case was > 50.
- Fix indexing the jump table by ensuring it starts indexing from 0.
2022-03-09 13:53:10 -07:00
Andrew Kelley
b936fe0a58 Merge pull request #11101 from Vexu/stage2
Sema: handle noreturn result in condbr_inline
2022-03-09 15:07:00 -05:00
Veikka Tuominen
01b454f851 AstGen: ensure lableld block implicitly ends in a break 2022-03-09 17:12:40 +02:00
Veikka Tuominen
bb1fa0bdbd Sema: handle noreturn result in condbr_inline 2022-03-09 17:07:25 +02:00
Andrew Kelley
0f0d27ce24 Sema: implement tuple fieldptr and fieldval 2022-03-09 01:19:29 -07:00
Stephen Gregoratto
ee32d11252 Add bits for the Linux Secure Computing facility 2022-03-09 18:49:36 +11:00
Andrew Kelley
bb73775d40 Sema: implement coercion of tuples to structs 2022-03-08 22:19:25 -07:00
Andrew Kelley
6f560c9909 Sema: implement comptime struct fields 2022-03-08 20:52:38 -07:00
Andrew Kelley
a91753219d Merge pull request #11085 from ziglang/llvm-debug-info
stage2 LLVM debug info
2022-03-08 21:09:20 -05:00
Andrew Kelley
935d208ffb Merge pull request #11090 from mitchellh/inferred-ty
stage2: correct comptime-known inferred alloc type, plus comptime array init sentinels
2022-03-08 20:56:00 -05:00
Andrew Kelley
fb4ad37e0b LLVM: fix memory leak of debug type names
This required adjusting `Type.nameAlloc` to be used with a
general-purpose allocator and added `Type.nameAllocArena` for the arena
use case (avoids allocation sometimes).
2022-03-08 15:03:03 -07:00
Andrew Kelley
874b51d8d4 LLVM: add debug info for opaque, vector, and tuples
Also fix UAF of Type memory in the di_type_map.
2022-03-08 14:58:54 -07:00
Andrew Kelley
fa57335ec6 stage2: implement Type.getOwnerDecl for opaque types 2022-03-08 14:58:54 -07:00
Andrew Kelley
1046ead0cc LLVM: no longer store args into alloca instructions
Previously, we did this so that we could insert a debug variable
declaration intrinsic on the alloca. But there is a dbg.value intrinsic
for declaring variables that are values.
2022-03-08 14:58:53 -07:00
Andrew Kelley
7cea8f063f LLVM: add debug info for parameters 2022-03-08 14:58:53 -07:00
Andrew Kelley
ba566eed76 LLVM: fix not handling dbg_stmt relative line
Also make `namespaceToDebugScope` behave correctly for file-level
structs. Instead of being inside their own scope, they use the file
scope.
2022-03-08 14:58:53 -07:00
Andrew Kelley
3654ec8770 LLVM: add debug type lowering for ptr, slice, opaque, optional
also fix issue with memoization and recursiveness.
2022-03-08 14:58:53 -07:00
Andrew Kelley
40c0bdd385 LLVM: memoize debug types and add enum debug types 2022-03-08 14:58:53 -07:00
Andrew Kelley
0d24bc7da0 LLVM: add DISubprogram and DIType lowering; handle dbg_stmt 2022-03-08 14:58:53 -07:00
Andrew Kelley
627209253c langref: fix a stray anyopaque that should be a void 2022-03-08 14:58:53 -07:00
Andrew Kelley
c6160fa3a5 LLVM: add compile unit to debug info
This commit also adds a bunch of bindings for debug info.
2022-03-08 14:58:53 -07:00
joachimschmidt557
95fc41b2b4 stage2 ARM: implement ret_load 2022-03-08 21:10:04 +01:00
Mitchell Hashimoto
ba62853d26 stage2: sentinel array init must add sentinel to array value
I didn't realize that the `array` value type has the sentinel on it.
2022-03-08 12:05:12 -08:00
Mitchell Hashimoto
cd32b11eb8 stage2: inferred alloc can use bitcast ty
The comment notes that we can't because of constness, but the recent
work by @Vexu lets us use the bitcast ty cause constness comes later.

The following tests pass from this:

```
test "A" {
    const ary = [_:0]u8{42};
    const ptr: [*:0]const u8 = &ary;
    try expect(ptr[1] == 0);
}

test "B" {
    comptime {
        const ary = [_:0]u8{42};
        const ptr: [*:0]const u8 = &ary;
        try expect(ptr[1] == 0);
    }
}
```
2022-03-08 12:04:51 -08:00
Mitchell Hashimoto
55ccf4c7a8 stage2: elem vals of many pointers need not deref pointers
By the time zirElemVal is reached for a many pointer, a load has already
happened, making sure the operand is already dereferenced.

This makes `mem.sliceTo` now work.
2022-03-08 14:10:43 -05:00
Andrew Kelley
6ffa44554e Merge pull request #11079 from Vexu/stage2
stage2: make references to const allocs const
2022-03-08 13:49:29 -05:00
Benjamin San Souci
e3c2cc1443 std.json: correctly handle sentinel terminated slices 2022-03-08 20:43:13 +02:00
Evan Haas
4b9fd57aa8 translate-c: use nested scope for comma operator in macros
Fixes #11040
2022-03-08 20:38:51 +02:00
Jonathan Marler
d805adddd6 deprecated TypeInfo in favor of Type
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-03-08 20:38:12 +02:00
Jakub Konka
404f5d6179 x64: pass more behavior/cast.zig tests 2022-03-08 10:56:54 +01:00
joachimschmidt557
3ea603c82a stage2 ARM: implement ptr_add, ptr_sub for all element sizes
Also reduces slice_elem_val to ptr_add, simplifying the implementation
2022-03-08 10:54:08 +01:00
Veikka Tuominen
8f037db885 stage2: correct constness of allocs 2022-03-08 11:23:39 +02:00
Veikka Tuominen
1f4a097117 stage2: fix mem{set,cpy} for non comptime mutable pointers 2022-03-08 11:23:38 +02:00
Jakub Konka
ba17552b4e dwarf: move all dwarf into standalone module
Hook up Elf and MachO linkers to the new solution.
2022-03-08 09:46:27 +01:00
Andrew Kelley
38c161afab Sema: fix @hasDecl for simple enums 2022-03-07 13:54:25 -07:00
Andrew Kelley
c467f6693e stage2: fix union layout returning non-zero for zero-sized tag 2022-03-07 13:36:58 -07:00
Andrew Kelley
f59cbd89e3 Merge pull request #11077 from mitchellh/array-init-ty
stage2: sentinel-terminated array initialization
2022-03-07 13:54:09 -05:00
Mitchell Hashimoto
85b0a4a8fd stage2: new zir array_init_sent for sentinel-terminated array inits
This uses a new ZIR inst `array_init_sent` (and a ref equivalent) to
represent array init expressions that terminate in a a sentinel value.

The sentienl value is the last value in the `MultiOp` payload. This
makes it a bit more awkward to deal with (lots of "len - 1") but makes
it so that the payload matches the fact that sentinels appear at the end
of arrays. However, this is not a hill I want to die on so if we want to
change it to index 0, I'm happy to do so.

This makes the following work properly:

    try expect(@TypeOf([_:0]u8{}) == [0:0]u8);
2022-03-07 08:26:00 -08:00
Mitchell Hashimoto
c9fac41368 stage2: resolve array type for typed array init expressions
Array types with sentinels were not being typed correctly in the
translation from ZIR to Sema (comptime). This modifies the `array_init`
ZIR to also retain the type of the init expression (note: untyped array
initialization is done via the `array_init_anon` ZIR and so is unchanged
in this commit).
2022-03-07 07:30:30 -08:00
Andrew Kelley
8c32d989c9 Merge pull request #11054 from schmee/mul-add
Implement `@mulAdd` for scalar floats
2022-03-07 04:00:45 -05:00
Andrew Kelley
6547da8f97 Sema: handle peer type resolution of optional slices 2022-03-06 21:29:07 -07:00
Andrew Kelley
76d810c568 std: disable flaky os.fcntl test
See tracking issue #11074
2022-03-06 20:49:49 -07:00
Andrew Kelley
e74382b602 ci: azure: update to newest LTS ubuntu 2022-03-06 20:03:57 -07:00
Andrew Kelley
3c1ebf9556 compiler_rt: avoid redundant exports when testing 2022-03-06 19:58:01 -07:00
Andrew Kelley
4c17b93f0a compiler_rt: additional powerpc-specific alias
Apparently LLVM lowers f128 fma to `fmaf128` instead of `fmal`.
2022-03-06 16:34:44 -07:00
Andrew Kelley
488eb8ac29 disable failing @mulAdd test 2022-03-06 16:18:51 -07:00
Andrew Kelley
c52d437224 stage1: improved implementation of target_long_double_is_f128 2022-03-06 16:11:39 -07:00
Andrew Kelley
c68d9773df compiler-rt: make __fmax and fmaq aliases of fmal
on targets where that is the case.
2022-03-06 16:11:39 -07:00
Andrew Kelley
71b8760d3b stage2: rework @mulAdd
* mul_add AIR instruction: use `pl_op` instead of `ty_pl`. The type is
   always the same as the operand; no need to waste bytes redundantly
   storing the type.
 * AstGen: use coerced_ty for all the operands except for one which we
   use to communicate the type.
 * Sema: use the correct source location for requireRuntimeBlock in
   handling of `@mulAdd`.
 * native backends: handle liveness even for the functions that are
   TODO.
 * C backend: implement `@mulAdd`. It lowers to libc calls.
 * LLVM backend: make `@mulAdd` handle all float types.
   - improved fptrunc and fpext to handle f80 with compiler-rt calls.
 * Value.mulAdd: handle all float types and use the `@mulAdd` builtin.
 * behavior tests: revert the changes to testing `@mulAdd`. These
   changes broke the test coverage, making it only tested at
   compile-time.

Improved f80 support:
 * std.math.fma handles f80
 * move fma functions from freestanding libc to compiler-rt
   - add __fmax and fmal
   - make __fmax and fmaq only exported when they don't alias fmal.
   - make their linkage weak just like the rest of compiler-rt symbols.
 * removed `longDoubleIsF128` and replaced it with `longDoubleIs` which
   takes a type as a parameter. The implementation is now more accurate
   and handles more targets. Similarly, in stage2 the function
   CTypes.sizeInBits is more accurate for long double for more targets.
2022-03-06 16:11:39 -07:00
John Schmidt
6637335981 stage2: implement @mulAdd for scalar floats 2022-03-06 15:36:56 -07:00
Luuk de Gram
c7e4c711fc wasm: Fix incremental compilation
- atoms may have relocations, so freeing them when we update the parent
atom will cause segfaults.
- Not all declarations will live in symbol_atom
2022-03-06 23:33:50 +01:00
Jakub Konka
27c084065a Merge pull request #11070 from Luukdegram/wasm-unify
stage2: wasm - unify codegen with other backends
2022-03-06 20:44:51 +01:00
Andrew Kelley
9154a86069 Merge pull request #11065 from hexops/sg/responsefiles-2
Do not fail to build if 'zig build-lib' etc. arguments exceed OS limits (take 2)
2022-03-06 14:35:52 -05:00
Andrew Kelley
e535521619 CI: additionally test wasm32-wasi with LLVM backend 2022-03-06 12:25:33 -07:00
Luuk de Gram
6d84f22fa0 stage2: Fix wasm linker for llvm backend
This fixes 2 entrypoints within the self-hosted wasm linker that would be called
for the llvm backend, whereas we should simply call into the llvm backend to perform such action.
i.e. not allocate a decl index when we have an llvm object, and when flushing a module,
we should be calling it on llvm's object, rather than have the wasm linker perform the operation.

Also, this fixes the wasm intrinsics for wasm.memory.size and wasm.memory.grow.
Lastly, this commit ensures that when an extern function is being resolved, we tell LLVM how
to import such function.
2022-03-06 14:17:36 -05:00
Daniele Cocca
716abe3389 CBE: mark more tests as passing 2022-03-06 14:15:57 -05:00
Luuk de Gram
13fca53b92 wasm: Unify function generation
Like decl code generation, also unify the wasm backend and the wasm linker to call into
the general purpose `codegen.zig` to generate the code for a function.
2022-03-06 19:38:53 +01:00
Luuk de Gram
2faba4092a wasm: Remove old DeclGen/genTypedValue 2022-03-06 19:38:53 +01:00
Luuk de Gram
70fc6e3776 wasm: call into generateSymbol when lowering
This also unifies the wasm backend to use `generateSymbol` when lowering a constant
that cannot be lowered to an immediate value.
As both decls and constants are now refactored, the old `genTypedValue` is removed.
2022-03-06 19:38:53 +01:00
Luuk de Gram
5a45fe2dba wasm: Call generateSymbol for updateDecl
To unify the wasm backend with the other backends, we will now call `generateSymbol` to
lower a Decl into bytes. This means we also have to change some function signatures
to comply with the linker interface.

Since the general purpose generateSymbol is less featureful than wasm's, some tests are
temporarily disabled.
2022-03-06 19:38:50 +01:00
Jakub Konka
12e636c24e Merge pull request #11068 from Luukdegram/codegen-fixes
stage2: Fix codegen for unions and error unions
2022-03-06 19:37:43 +01:00
Jakub Konka
e4039cecc7 x64: fix (un)wrapping error unions + refactor 2022-03-06 19:02:02 +01:00
Luuk de Gram
23e2368ac3 stage2: Fix codegen for unions and error unions
When an union had a zero-sized payload type, we would lower the tag twice. This is fixed
by exiting early when `payload_size` is 0.

With regards to error unions, we were only accounting for padding for the payload field.
However, the errorset value can have a smaller alignment than the payload as well, i.e. error!usize.
We fix this by also accounting for padding/alignment of the error set tag of an error union.
2022-03-06 16:04:15 +01:00
Mitchell Hashimoto
bf972e44d5 stage2: coerce [*:0]u8 to other valid pointer types
This makes the following work properly (as it does in stage1, too):

  var zero_ptr: [*:0]const u8 = undefined;
  var no_zero_ptr: [*]const u8 = zero_ptr;

Prior to this this would fail with an "expected type" error since
coercion failed.
2022-03-06 10:38:53 +02:00
The Depressed Milkman
cd43f323d2 correct @frameSize() params in documentation
The documentation omitted the primary parameter, making it difficult to
understand what this function actually does.
2022-03-06 10:32:07 +02:00
Stephen Gutekanst
c3a2b51a2c fix regression in zig run runtime arguments
This brings back #10950, which was reverted in 5ab5e2e673
because it [introduced a regression in `zig run`](https://github.com/ziglang/zig/pull/10950#issuecomment-1049481212)
where the runtime arguments passed were incorrect.

I've fixed the issue, and notably this was the only location where we
directly relied on accessing arguments by index in this code still (all
other locations use the iterator proper) and so we should be all good to
go now.

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-03-05 16:27:29 -07:00
Stephen Gutekanst
cfb4f48941 Revert "Revert "Merge pull request #10950 from hexops/sg/responsefiles""
This reverts commit 5ab5e2e673.
2022-03-05 16:04:21 -07:00
Jakub Konka
72992b6513 Merge pull request #11062 from ziglang/dwarf-more-types 2022-03-05 23:07:36 +01:00
Jakub Konka
908f41a67c Merge pull request #11021 from topolarity/wasi-cwd
stdlib: Add emulated CWD to std.os for WASI targets
2022-03-05 20:31:44 +01:00
Jakub Konka
1252bdd4d6 elf: add debug info for non-ptr optionals 2022-03-05 20:18:18 +01:00
Jakub Konka
9a027d9ee3 macho: fix incorrect line and pc advancement 2022-03-05 17:55:01 +01:00
Jakub Konka
0a9088bd06 macho: remove anon_struct_type which is now redundant 2022-03-05 17:55:01 +01:00
Jakub Konka
2be003a3b3 macho: write NOPs as padding for machine code section 2022-03-05 17:55:01 +01:00
Jakub Konka
3318400ea3 macho: migrate to named struct for slices 2022-03-05 17:55:01 +01:00
Jakub Konka
eaf08bfb84 macho: handle optional non-ptr types in DWARF 2022-03-05 17:55:01 +01:00
Joachim Schmidt
ac936c0aba Merge pull request #11059 from joachimschmidt557/stage2-aarch64
stage2 AArch64: various improvements
2022-03-05 14:30:02 +01:00
joachimschmidt557
a06e9eca45 stage2 AArch64: add more slice support
* airSlice
* airArrayToSlice
* and initial support for airSlicePtr and co
2022-03-05 11:31:51 +01:00
Mitchell Hashimoto
e297860158 stage2: test changed behavior of c pointer resolution from stage1
stage1 peer resolves the given test to `[*c]u8` but stage2 makes that a
const u8. I believe stage2 behavior is correct since the pointer itself
is const.
2022-03-05 02:56:24 -05:00
joachimschmidt557
ed7e2938ff stage2 AArch64: generate less no-op branches
mirroring d486a7b811 for aarch64
2022-03-05 08:56:01 +01:00
joachimschmidt557
691ec964ef stage2 AArch64: implement bitwise binary operations
for integers with bit sizes <= 64
2022-03-05 08:56:01 +01:00
joachimschmidt557
e3121accac stage2 AArch64: introduce logical immediate instructions 2022-03-05 08:56:01 +01:00
Andrew Kelley
f2a5d0bf94 stage2: fix tuple assigned to variable
Before this we would see ZIR code like this:
```
%69 = alloc_inferred_mut()
%70 = array_base_ptr(%69)
%71 = elem_ptr_imm(%70, 0)
```
This would crash the compiler because it expects to see a
`coerce_result_ptr` instruction after `alloc_inferred_mut`, but that
does not happen in this case because there is no type to coerce the
result pointer to.

In this commit I modified AstGen so that it has similar codegen as when
using a const instead of a var:
```
%69 = alloc_inferred_mut()
%76 = array_init_anon(.{%71, %73, %75})
%77 = store_to_inferred_ptr(%69, %76)
```

This does not obey result locations, meaning if you call a function
inside the initializer, it will end up doing a copy into the LHS.
Solving this problem, or changing the language to make this legal,
will be left for my future self to deal with. Hi future self!
I see you reading this commit log. Hope you're doing OK buddy.

Sema for `store_ptr` of a tuple where the pointer is in fact the same
element type as the operand had an issue where the comptime fields would
get incorrectly lowered to runtime stores to bogus addresses. This is
solved with an exception to the optimization in Sema for storing
pointers that handles tuples element-wise. In the case that we are
storing a tuple to itself, it skips the optimization. This results in
better code and avoids the problem. However this caused a regression in
GeneralPurposeAllocator from the standard library.

I regressed the test runner code back to the simpler path. It's too
hard to debug standard library code in the LLVM backend right now since
we don't have debug info hooked up. Also, we didn't have any behavior
test coverage of whatever was regressed, so let's try to get that
coverage added as a stepping stone to getting the standard library
working.
2022-03-04 18:27:46 -07:00
Andrew Kelley
d3648cc030 zig cc: integrate with -fstack-check, -fno-stack-check 2022-03-04 18:10:37 -07:00
joachimschmidt557
d486a7b811 stage2 ARM: generate less no-op branches
The checks detecting such no-op branches (essentially instructions
that branch to the instruction immediately following the branch) were
tightened to catch more of these occurrences.
2022-03-04 23:28:14 +01:00
Andrew Kelley
7605166426 Merge pull request #11052 from mitchellh/peer-c
stage2: peer resolve *T and [*c]T
2022-03-04 01:16:47 -05:00
Andrew Kelley
63c5c510b1 Sema: rework peer type logic for pointers
Now it's centered around a switch on the chosen type tag which gives us
easy access to pointer data.

The logic is simplied and in some cases logic is removed when it is
sufficient to choose the type that is a better coercion target without
knowing whether such coercion will succeed ahead of time.

A bug is fixed at the bottom of the function; we were doing the opposite
of what we were supposed to with `seen_const`.

Also the bottom of the function has a more complete handling of the
possible combinations of `any_are_null`, `convert_to_slice`, and
`err_set_ty`.

In the behavior tests, not as many backends needed to be skipped.
2022-03-03 23:12:18 -07:00
Mitchell Hashimoto
26be5bb8b1 stage2: peer resolve *T to [*c]T 2022-03-03 21:33:18 -07:00
Andrew Kelley
c9ee3c1e47 Merge pull request #11048 from Luukdegram/wasm-builtins
stage2: Implement wasm builtins
2022-03-03 20:39:10 -05:00
Andrew Kelley
e532b0c0b5 stage2: cleanups to wasm memory intrinsics
* AIR: use pl_op instead of ty_pl for wasm_memory_size. No need to
   store the type because the type is always `u32`.
 * AstGen: use coerced_ty for `@wasmMemorySize` and `@wasmMemoryGrow`
   and do the coercions in Sema.
 * Sema: use more accurate source locations for errors.
 * Provide more information in the compiler error message.
 * Codegen: use liveness data to avoid lowering unused
   `@wasmMemorySize`.
 * LLVM backend: add implementation
   - I wasn't able to test it because we are hitting a linker error for
     `-target wasm32-wasi -fLLVM`.
 * C backend: use `zig_unimplemented()` instead of silently doing wrong
   behavior for these builtins.
 * behavior tests: branch only on stage2_arch for inclusion of the
   wasm.zig file. We would change it to `builtin.cpu.arch` but that is
   causing a compiler crash on some backends.
2022-03-03 18:31:55 -07:00
Luuk de Gram
7fd32de018 cbe: Implement wasm builtins
This implements the wasm builtins by lowering to builtins that are supported by c-compilers.
In this case: Clang.

This also simplifies the `AIR` instruction as it now uses the payload field of `ty_pl` and `pl_op`
directly to store the index argument rather than storing it inside Extra. This saves us 4 bytes
per builtin call.
2022-03-03 16:33:46 -07:00
Luuk de Gram
21f0503c01 Update behavior tests 2022-03-03 16:33:46 -07:00
Luuk de Gram
43cb19ea4d wasm: Implement @wasmMemoryGrow builtin
Similarly to the other wasm builtin, this implements the grow variation where the memory
index is a comptime known value. The operand as well as the result are runtime values.
This also verifies during semantic analysis the target we're building for is wasm, or else
emits a compilation error. This means that other backends do not have to handle this AIR instruction,
other than the wasm and LLVM backends.
2022-03-03 16:33:46 -07:00
Luuk de Gram
ec4c30ae48 wasm: Implement @wasmMemorySize() builtin
This implements the `wasmMemorySize` builtin, in Sema and the Wasm backend.
The Stage2 implementation differs from stage1 in the way that `index` must be a comptime value.
The stage1 variant is incorrect, as the index is part of the instruction encoding, and therefore,
cannot be a runtime value.
2022-03-03 16:33:46 -07:00
Andrew Kelley
0ea51f7f49 Merge pull request #11049 from mitchellh/peer-arrays
stage2: fix a couple issues with peer resolution and const casting arrays
2022-03-03 17:56:37 -05:00
Andrew Kelley
6c045f9e83 Merge pull request #11047 from Vexu/stage2
Stage2: make `expectEqualSlices` work
2022-03-03 17:55:55 -05:00
Cody Tapscott
aafcd8eab3 stdlib std.os: Rename RelativePath to RelativePathWasi 2022-03-03 14:31:49 -07:00
Cody Tapscott
ade2d0c6a2 stdlib WASI: Add realpath() support for non-absolute Preopens 2022-03-03 14:31:49 -07:00
Cody Tapscott
58f961f4cb stdlib: Add emulated CWD to std.os for WASI targets
This adds a special CWD file descriptor, AT.FDCWD (-2), to refer to the
current working directory. The `*at(...)` functions look for this and
resolve relative paths against the stored CWD. Absolute paths are
dynamically matched against the stored Preopens.

"os.initPreopensWasi()" must be called before std.os functions will
resolve relative or absolute paths correctly. This is asserted at
runtime.

Support has been added for: `open`, `rename`, `mkdir`, `rmdir`, `chdir`,
`fchdir`, `link`, `symlink`, `unlink`, `readlink`, `fstatat`, `access`,
and `faccessat`.

This also includes limited support for `getcwd()` and `realpath()`.
These return an error if the CWD does not correspond to a Preopen with
an absolute path. They also do not currently expand symlinks.
2022-03-03 14:31:49 -07:00
Veikka Tuominen
aa7cbca7d3 stage2: make analyzePtrArithmetic no-op with offset=0 2022-03-03 22:42:34 +02:00
Veikka Tuominen
69bd2c243e stage2: remove opaque type workaround from Type.ptrAlignment 2022-03-03 22:16:49 +02:00
Veikka Tuominen
7691013d10 stage2: add 'called from here' error note 2022-03-03 22:14:43 +02:00
Hiroaki Nakamura
3605dd307f os/linux/io_uring: add recvmsg and sendmsg (#10212)
* os/linux/io_uring: add recvmsg and sendmsg

* Use std.os.iovec and std.os.iovec_const

* Remove msg_ prefix in msghdr and msghdr_const in arm64 etc

* Strip msg_ prefix in msghdr and msghdr_const for linux arm-eabi

* Copy msghdr and msghdr_const from i386 to mips

* Add sockaddr to lib/std/os/linux/mips.zig

* Copy msghdr and msghdr_const from x86_64 to riscv64
2022-03-03 14:13:54 -06:00
Andrew Kelley
e91c16e38b Merge pull request #11043 from topolarity/ptr-fixes
stage2: Improve `@ptrCast` support for sliced/optional operands
2022-03-03 15:12:02 -05:00
Andrew Kelley
365aca0e90 Sema: allow pointers to opaques to be aligned 2022-03-03 13:11:06 -07:00
Cody Tapscott
85610a9aff stage2 llvm: Lower 0-bit field-ptr as ptr-to-void 2022-03-03 13:08:14 -07:00
Cody Tapscott
b6a6f05c0d stage2: support @ptrCast for slices with an offset 2022-03-03 13:08:14 -07:00
Cody Tapscott
b6f1a8612b stage2: Preserve larger alignment in @ptrCast 2022-03-03 13:08:14 -07:00
Mitchell Hashimoto
7deadf4301 stage2: reify error sets 2022-03-03 15:07:23 -05:00
Mitchell Hashimoto
b96d5fd71f stage2: peer resolve const array pointer to unknown ptr 2022-03-03 11:08:14 -08:00
Mitchell Hashimoto
0924f17a23 stage2: peer resolve const u8 slices correctly 2022-03-03 11:04:04 -08:00
65943010c7 std.BoundedArray: return explicit errors (#11044)
* std.BoundedArray: return explicit errors

Makes it easier to mark explicit errors when using BoundedArray
downstream.

* std.BoundedArray.insert() returns Overflow only
2022-03-03 19:39:45 +01:00
Andrew Kelley
9aa220ebb5 freestanding libc: add missing export of sqrt, sqrtf
this was a typo in a previous commit, didn't mean to omit these.
2022-03-03 00:52:55 -08:00
Andrew Kelley
0a4f58490f behavior tests cleanup: promote math.zig 2022-03-03 01:24:26 -07:00
Andrew Kelley
67ba4c5679 stage2: add all functions to freestanding libc
Looks like all these functions are at least compiling successfully. I
haven't tried to run their test suites yet.

The one exception is `clone` which is crashing the compiler due to the
inline assembly. Still, this is progress!
2022-03-03 01:24:26 -07:00
Andrew Kelley
b33f3b23c9 LLVM: fix lowering of unions and switches
`Module.Union.getLayout` now additionally returns a `padding` field
which tells how many bytes are between the final field end offset and
the ending offset of the union. This is used by the LLVM backend to
explicitly insert padding.

LLVM backend: lowering of unions now inserts additional padding so that
LLVM's internals will agree on the ABI size to match what ABI size zig
wants unions to be. This is an alternative to calling LLVMABISizeOfType
and LLVMABIAlignmentOfType which end up crashing when recursive struct
definitions come into play. We no longer ever call these two functions
and the bindings are deleted to avoid future footgun firings.

LLVM backend: lowering of unions now represents untagged unions
consistently. Before it was tripping an assertion.

LLVM backend: switch cases call inttoptr on the case items and condition
if necessary. Prevents tripping an LLVM assertion.

After this commit, we are no longer tripping over any LLVM assertions.
2022-03-03 01:19:49 -07:00
Andrew Kelley
06b1a88a15 Sema: implement cast from anon struct ptr to union ptr 2022-03-02 20:18:22 -07:00
Mitchell Hashimoto
ac7028f559 stage2: implement @errSetCast (#11039) 2022-03-02 22:01:55 -05:00
Andrew Kelley
f5e2e301e9 Sema: add coercion from anon structs to unions 2022-03-02 19:22:31 -07:00
Jakub Konka
3ec74a1cd8 codegen: handle elem_ptr when lowering to memory
* x64: handle storing from-to non-stack memory
2022-03-02 20:04:34 -05:00
Andrew Kelley
1c8a86f063 Sema: detect comptime-known union initializations
Follow a similar pattern as we already do for validate_array_init and
validate_struct_init.

I threw in a bit of behavior test cleanup on top of it.
2022-03-02 17:28:39 -07:00
Andrew Kelley
220708e7c3 LLVM: aggregate_init supports structs
in addition to tuples
2022-03-02 13:35:15 -07:00
Andrew Kelley
446324a1d8 Merge pull request #11025 from Vexu/stage2
stage2: implement `@extern`
2022-03-02 14:51:29 -05:00
Curtis Wilkinson
7fc8dd6642 Zir: rename the 'ret_coerce' tag to 'ret_tok' as per TODO 2022-03-02 14:46:09 -05:00
Cody Tapscott
5c8a507e7a stage2 parser: UTF-8 encode \u{NNNNNN} escape sequences
The core of this change is to re-use the escape sequence parsing logic
for parsing both string and character literals.

The actual fix is that UTF-8 encoding was missing for string literals
with \u{...} escape sequences.
2022-03-02 14:45:19 -05:00
Jakub Konka
aa867c7dbe Merge pull request #11036 from ziglang/x64-optionals
x64: handle more optional types
2022-03-02 20:04:53 +01:00
Jakub Konka
77072d1a17 x64: fix bug in lowering optionals directly to immediate 2022-03-02 17:40:37 +01:00
Jakub Konka
b0bb1583cb codegen: leave f80 explicitly unhandled for now 2022-03-02 17:08:16 +01:00
Jakub Konka
c9d1db7e8e x64: fix incorrect calc of rdi spill stack loc for backpatching 2022-03-02 14:53:02 +01:00
Jakub Konka
350bf9db13 x64: fix intCast to properly clear out dest register 2022-03-02 14:34:43 +01:00
Jakub Konka
d35cae551e x64: rectify and add missing optionals bits
Includes changes/additions to:
* `wrap_optional`
* `optional_payload`
* `isNull` helper
2022-03-02 14:05:29 +01:00
Veikka Tuominen
403a1fe5d7 stage2: add cast from ?*T to ?*anyopaque 2022-03-02 12:26:04 +02:00
Veikka Tuominen
58530c1736 stage2: resolve options values 2022-03-02 12:25:44 +02:00
Veikka Tuominen
ef4aca2dc4 stage2: implement @extern 2022-03-02 12:15:50 +02:00
Jakub Konka
2e327d9b63 codegen: lower optionals and floats across linking backends 2022-03-02 11:10:35 +01:00
Jakub Konka
7cfc3f0cfa Merge pull request #11026 from ziglang/codegen-field-ptr
codegen: lower field_ptr to memory across linking backends
2022-03-02 08:58:26 +01:00
Andrew Kelley
ed2364a148 stage2: introduce anonymous struct literals 2022-03-01 23:46:57 -07:00
Andrew Kelley
6f303c01f3 LLVM: add extra padding to structs and tuples sometimes
* Sema: resolve type fully when emitting an alloc AIR instruction to
   avoid tripping assertion for checking struct field alignment.
 * LLVM backend: keep a reference to the LLVM target data alive during
   lowering so that we can ask LLVM what it thinks the ABI alignment
   and size of LLVM types are. We need this in order to lower tuples and
   structs so that we can put in extra padding bytes when Zig disagrees
   with LLVM about the size or alignment of something.
 * LLVM backend: make the LLVM struct type packed that contains the most
   aligned union field and the padding. This prevents the struct from
   being too big according to LLVM. In the future, we may want to
   consider instead emitting unions in a "flat" manner; putting the tag,
   most aligned union field, and padding all in the same struct field
   space.
 * LLVM backend: make structs with 2 or fewer fields return isByRef=false.
   This results in more efficient codegen. This required lowering of
   bitcast to sometimes store the struct into an alloca, ptrcast, and
   then load because LLVM does not allow bitcasting structs.
 * enable more passing behavior tests.
2022-03-01 18:24:00 -07:00
Andrew Kelley
8878f085dc Sema: correct implementation of comptimeOnly for tuples
This makes formatted printing work when mixing comptime and runtime
fields.
2022-03-01 15:26:31 -07:00
Andrew Kelley
f6aaab9406 LLVM: fix tripping assertions
Packed structs were tripping an LLVM assertion due to calling
`LLVMConstZExt` from i16 to i16. Solved by using instead
`LLVMConstZExtOrBitCast`.

Unions were tripping an LLVM assertion due to a typo using the union
llvm type to construct an integer value rather than the tag type.
2022-03-01 14:58:37 -07:00
Andrew Kelley
1b194931b0 LLVM: fix when sret and isByRef ret_ty disagree
This can happen functions use the C ABI.
2022-03-01 14:58:37 -07:00
Jakub Konka
836f007c22 codegen: ensure we descend on nested field_ptrs when lowering 2022-03-01 22:51:04 +01:00
Andrew Kelley
18e42661dc Sema: eliminate use of resolveAlreadyCoercedInt 2022-03-01 14:03:32 -07:00
Jakub Konka
e8eb9778cc codegen: lower field_ptr to memory across linking backends
This requires generating an addend for the target relocation as
the field pointer might point at a field inner to the container.
2022-03-01 22:03:18 +01:00
543bee0adf std.BufSet.clone: fix key ownership
This was introduced in d1a4654834: when a
BufSet clones the keys, it used to assign the new pointers to the old
struct. Fix that by assigning the pointers to the correct, i.e. the new,
struct.

This caused double-free when using arena allocator for the new struct,
also in the test case.
2022-03-01 13:28:47 -05:00
Jakub Konka
52205a3c16 x64: fix array to slice impl 2022-03-01 17:59:39 +01:00
Jakub Konka
ad03fef712 Merge pull request #11019 from ziglang/x64-air-memcpy
x64: memcpy and memset
2022-03-01 17:59:21 +01:00
Jakub Konka
caa4e30ef4 x64: impl airMemset using inline memset 2022-03-01 15:21:10 +01:00
Jakub Konka
5a6f4395e6 x64: impl airMemcpy using inline memcpy 2022-03-01 14:29:48 +01:00
joachimschmidt557
ca97caab8a stage2 ARM: implement return types with abi size > 4 2022-03-01 09:14:52 +01:00
Jakub Konka
ec54ceee6d Merge pull request #11016 from ziglang/x64-more-codegen 2022-03-01 09:14:23 +01:00
Luuk de Gram
f5a31cb0d6 wasm-linker: Intern globals, exports & imports
Symbols that have globals used to have their lookup key be the symbol name.
This key is now the offset into the string table.

Imports have both the module name (library name) and name (of the symbol), those strings are now
also being interned. This can save us up to 24bytes per import which have both their module name and name de-duplicated.
Module names are almost entirely the same for all imports, providing us with a big chance of saving us 12 bytes at least.

Just like imports, exports can also have a seperate name than the internal symbol name. Rather than storing the slice,
we now store the offset of this string instead.
2022-03-01 08:35:20 +01:00
Luuk de Gram
b1159ab7ae wasm-linker: Intern all symbol names
For all symbols read from object files as well as generated from Zig code
will now be interned and have their offset into the string table saved on the `Symbol` instead.

Besides interning, local symbols now also use a decl's fully qualified name.
When a decl/symbol is extern/to-be-imported, the name of the decl itself will be used for symbol resolving.
Similarly for symbols that will be exported, will have their 'export name' set.
2022-03-01 08:35:20 +01:00
Luuk de Gram
49f01c0a0c wasm-object: Use given allocator rather than arena
This is preliminary work for string interning in the wasm linker.
Using an arena would defeat the purpose of de-duplicating strings as we wouldn't be able to free memory
of duplicated strings.
This change also means we can simplify wasm binary parsing, by creating a general purpose parser that
parses the binary into its sections, but untyped. Doing this, allows us to re-use the base of that, for
object file, but also debug info parsing.
2022-03-01 08:35:20 +01:00
Andrew Kelley
eaf1c97ce8 Merge pull request #11010 from mitchellh/peer-errors
stage2: peer resolve error sets and error unions
2022-03-01 01:22:50 -05:00
Andrew Kelley
4763fd1a41 Sema: clean up peer resolution of errors
* Fix compile error for `zirErrorUnionType`.
 * Convert zirMergeErrorSets logic to call `Type.errorSetMerge`.
   It does not need to create a Decl as the TODO comment hinted.
 * Extract out a function called `resolveInferredErrorSetTy`.
 * Rework `resolvePeerTypes` with respect to error unions and
   error sets. This is a less complex implementation that passes all the
   same tests and uses many fewer lines of code by taking advantage of
   the function `coerceInMemoryAllowedErrorSets`.
   - Always merge error sets in the order that makes sense, even when
     that means `@typeInfo` incompatibility with stage1.
 * `Type.errorSetMerge` no longer overallocates.
 * Don't skip passing tests.
2022-02-28 23:15:58 -07:00
Mitchell Hashimoto
5e2e7675d5 stage2: pass generic poison up the chain in peer type resolution 2022-02-28 20:42:13 -07:00
Mitchell Hashimoto
0ce2d46ff9 stage2: error union/set peer resolution switch to "else" form of for loop 2022-02-28 20:42:13 -07:00
Mitchell Hashimoto
ea00e50045 stage2: skip error union test on native 2022-02-28 20:42:13 -07:00
Mitchell Hashimoto
0eb3cb9e8c stage2: order of error set merging should match stage1 2022-02-28 20:42:13 -07:00
Mitchell Hashimoto
6dae1de017 skip tests on native backends 2022-02-28 20:42:13 -07:00
Mitchell Hashimoto
b4ce855788 stage2: error union and non-error set/union peer cast resolution 2022-02-28 20:42:13 -07:00
Mitchell Hashimoto
38aae2cb7c stage2: peer resolve error sets and unions, add more tests 2022-02-28 20:42:13 -07:00
Mitchell Hashimoto
bfada7c514 stage2: implement peer type resolution between error unions 2022-02-28 20:42:13 -07:00
Andrew Kelley
d5131e91eb Sema: complete the Type.hash function
Similar to how Type.eql was reworked in the previous commit, this commit
reworks Type.hash to check all the different kinds of tags that a Type
can be represented with. It also completes the implementation for all
types except error sets, which need to have Type.eql enhanced as well.
2022-02-28 20:05:21 -07:00
Andrew Kelley
157f66ec07 Sema: fix pointer type hash and equality functions
Several issues with pointer types are fixed:

Prior to this commit, Zig would not canonicalize a pointer type with
an explicit alignment to alignment=0 if it matched the pointee ABI
alignment. In order to fix this, `Type.ptr` now takes a Target
parameter. I also moved the host_size canonicalization to `Type.ptr`
since target is now available. Similarly, is_allowzero in the case of
C pointers is now treated as a canonicalization done by the function
rather than a precondition.

in-memory coercion for pointers now properly checks ABI alignment
of pointee types instead of incorrectly treating the 0 value as an
alignment.

Type equality is completely reworked based on the tag() rather than the
zigTypeTag(). It's still semantically based on zigTypeTag() but that
knowledge is implied rather than dictating the control flow of the
logic. Importantly, this fixes cases for opaques, structs, tuples,
enums, and unions, where type equality was incorrectly returning based
on whether the tag() values were equal.

Additionally, pointer type equality now takes into account alignment.
Because we canonicalize non-zero alignment which equals pointee type ABI
alignment to alignment=0, this now can be a simple integer comparison.

Type hashing is implemented for pointers and floats. Array types now
additionally hash their sentinels.

This regressed some behavior tests that were passing but only because
of bugs regarding type equality.

The C backend has a noticeable problem with lowering differently-aligned
pointers (particularly slices) as the same type, causing C compilation
errors due to duplicate declarations.
2022-02-28 19:22:16 -07:00
Jakub Konka
cfbc3537ef x64: pass more behavior tests 2022-02-28 23:20:05 +01:00
Jakub Konka
66d28d0f20 x64: implement get_union_tag for register 2022-02-28 23:20:05 +01:00
Jakub Konka
decc90e0e7 x64: clean up loadMemPtrIntoRegister abstraction 2022-02-28 23:20:05 +01:00
Jakub Konka
12cdb36c5b codegen: fix padding calculation for error unions when lowering
* do not track `rdi` register before `call` inst, but instead freeze
  it from further use, until `call` has been realised
* pass more error union tests
2022-02-28 23:20:05 +01:00
Jakub Konka
05431d7c4a x64: impl unwrap_errunion_payload and unwrap_errunion_err for register 2022-02-28 23:20:05 +01:00
Mitchell Hashimoto
a7ca40b281 stage2: sentinel comp during peer type resolution should use elem type
We were using the array type, not the element type. Also, we should do
the sentinel comparison after we verify that the element types of both
are compatible.
2022-02-28 16:27:16 -05:00
d1a4654834 std.BufSet: add clone and cloneWithAllocator
Following how ArrayList and HashMap does things. This is useful when one
wants to, ahem, clone the BufSet.
2022-02-28 15:51:58 -05:00
Andrew Kelley
2dd5e8b6f8 Merge pull request #11011 from Vexu/stage2
stage2: tuple/slice mul/cat
2022-02-28 15:39:43 -05:00
Andrew Kelley
d5100dc815 stage2: fix frame_address AIR instruction
Various places were assuming different union tags. Now it is
consistently a no-op instruction, just like the similar
instruction ret_addr.
2022-02-28 13:38:33 -07:00
Veikka Tuominen
90bce11f62 stage2: implement @frameAddress 2022-02-28 13:09:14 -07:00
Veikka Tuominen
2682b41da5 make gpa.deinit work with stage2 2022-02-28 13:09:14 -07:00
Veikka Tuominen
dfeffcfbf8 stage2: tuple mul/cat 2022-02-28 13:09:14 -07:00
Veikka Tuominen
3a65fa269f stage2: slice mul/cat 2022-02-28 13:09:14 -07:00
Andrew Kelley
e1375942e5 zig cc: special handling of /dev/null
Now we handle -o /dev/null equivalent to -fno-emit-bin because
otherwise our atomic rename into place will fail. This also
makes Zig do less work, avoiding pointless file system operations.
2022-02-28 12:36:45 -07:00
Jakub Konka
331cc810de Merge pull request #11012 from ziglang/x64-union-tag
stage2,x64: basic (un)tagged unions
2022-02-28 17:42:59 +01:00
Jakub Konka
16f9774d2d x64: fix switch condition mir; pass more union tests 2022-02-28 15:25:40 +01:00
Jakub Konka
a61ac9ecbf x64: fix store with ABI size > 8 on stack; pass union tests 2022-02-28 12:14:41 +01:00
Jakub Konka
57a823582c x64: impl airGetUnionTag 2022-02-28 11:40:25 +01:00
Jakub Konka
4d0c48738b x64: make lowerUnnamedConst a fallthrough condition 2022-02-28 11:40:25 +01:00
Jakub Konka
06f58a0b3b codegen: impl lowering of union type to memory 2022-02-28 11:40:25 +01:00
Jakub Konka
1dc05e9e77 x64: impl airSetUnionTag 2022-02-28 11:40:21 +01:00
Jakub Konka
90059a12e0 Merge pull request #11008 from joachimschmidt557/stage2-arm
stage2 ARM: pass more behavior tests
2022-02-28 09:59:44 +01:00
Veikka Tuominen
87dc60e8de stage2: implement builtin_call 2022-02-27 18:59:44 -05:00
Andrew Kelley
720a5f87d4 Merge pull request #11006 from topolarity/resolve-union-alignment
stage2: Resolve alignment for union field in `@TypeInfo`
2022-02-27 18:58:28 -05:00
Andrew Kelley
9d4cfd9048 Sema: resolve necessary information ahead of time
Do the fallible logic in Sema where we have access to error reporting
mechanisms, rather than in Type/Value.

We can't just do the best guess when resolving queries of "is this type
comptime only?" or "what is the ABI alignment of this field?". The
result needs to be accurate. So we need to keep the assertions that the
data is available active, and instead compute the necessary information
before such functions get called.

Unfortunately we are stuck with two versions of such functions because
the various backends need to be able to ask such queries of Types and
Values while assuming the result has already been computed and validated
by Sema.
2022-02-27 16:51:33 -07:00
Cody Tapscott
71aa5084ed stage2: Resolve alignment for union field in @TypeInfo
This also includes two other small fixes:
 - Instantiate void TypeInfo fields as void
 - Return error in `type.comptimeOnly` on unresolved comptime requirements
2022-02-27 14:24:47 -07:00
joachimschmidt557
1bf8da19e1 stage2 ARM: implement slice and array_to_slice 2022-02-27 21:38:56 +01:00
joachimschmidt557
91fbcf7093 stage2 ARM: enable more behavior tests 2022-02-27 21:38:56 +01:00
joachimschmidt557
528008a981 stage2 ARM: reduce Mir.Inst.Data to 8 bytes 2022-02-27 21:38:55 +01:00
David John
139b731d82 std: rename sched_yield to yield and move it to std.Thread 2022-02-27 15:34:02 -05:00
Andrew Kelley
104a8840db Merge pull request #11002 from topolarity/comptime-int-comparison
stage2: Add comptime result for certain unsigned/comptime comparisons
2022-02-27 15:32:46 -05:00
Cody Tapscott
0bdc3d8f4e stage2: Implement @Type for Array, Optional, Float, and ErrorUnion 2022-02-27 15:29:38 -05:00
Andrew Kelley
b5066fdae2 Merge pull request #11001 from Vexu/stage2
stage2: make formatted printing work
2022-02-27 15:29:03 -05:00
c03b733f09 std.HashMap: return explicit errors (#11000)
All errors from std.HashMap are allocation errors. Mark them as
such. This is helpful when one wants to return explicit errors where
HashMap is used.
2022-02-27 15:24:00 -05:00
Veikka Tuominen
9f59189c95 stage2: do not memoize calls that can mutate comptime state 2022-02-27 16:43:53 +02:00
Veikka Tuominen
7a92b89a9d stage2: forward discard result loc to more expressions 2022-02-27 13:32:55 +02:00
Veikka Tuominen
813f368a3c test runner: remove unnecessary stage2 workaround 2022-02-27 12:25:50 +02:00
Veikka Tuominen
1bbca4f935 stage2: fix bitcast to optional ptr in llvm backend; omit safety check for intToPtr on optional ptr 2022-02-27 12:15:49 +02:00
Veikka Tuominen
950d840be6 stage2: use stage1 test runner for stage2 2022-02-27 11:57:12 +02:00
Cody Tapscott
a7a508fcd9 stage2 sema: Implement comptime result for comparison of uint to comptime value
This adds a comptime result when comparing a comptime value to an
unsigned integer. For example:
   ( 0 <= (unsigned runtime value)) => true
   (-1 <  (unsigned runtime value)) => true
   ((unsigned runtime value) < -15) => false
2022-02-27 02:24:28 -07:00
Cody Tapscott
b52948444f stage2: Resolve union layout before getting tag type in zirTagname
This bug only causes a failure on my machine when running
test/behavior/eval.zig directly. If running the full behavior test
suite, std.builtin.TypeInfo will have already resolved its layout,
causing the test to pass.

I'd love to add a test that can reliably reproduce this problem,
but I'm afraid I'm not sure how to reliably create a union with
un-resolved layout.
2022-02-27 01:58:37 -07:00
Veikka Tuominen
593d23c0d7 stage2: get formatted printing (somewhat) working 2022-02-27 10:05:29 +02:00
Andrew Kelley
4d658f83ed Sema: handle error.GenericPoison in fieldVal
Brings us 1 crash closer to formatted printing test cases.
2022-02-26 21:47:22 -07:00
Andrew Kelley
2687b8f7f4 stage2: implement @unionInit
The ZIR instruction `union_init_ptr` is renamed to `union_init`.
I made it always use by-value semantics for now, not taking the time to
invest in result location semantics, in case we decide to change the
rules for unions. This way is much simpler.

There is a new AIR instruction: union_init. This is for a comptime known
tag, runtime-known field value.
vector_init is renamed to aggregate_init, which solves a TODO comment.
2022-02-26 20:59:36 -07:00
Andrew Kelley
32e89a98d8 Sema: implement union value equality at comptime
Still TODO is extern unions.
2022-02-26 20:59:23 -07:00
Mitchell Hashimoto
e999a925fa stage2: @TypeInfo for error sets (#10998) 2022-02-26 22:59:06 -05:00
Andrew Kelley
aefe4046de Sema: implement @enumToInt for unions 2022-02-26 16:53:23 -07:00
Andrew Kelley
d62229e3ad Sema: Module.Union.abiAlignment can return 0
When the union is a 0-bit type.
2022-02-26 16:53:23 -07:00
Andrew Kelley
822d29286b Sema: make align(a) T same as align(a:0:N) T
where `@sizeOf(T) == N`.
2022-02-26 16:50:35 -07:00
Andrew Kelley
e81b21a0ea Merge pull request #10992 from mitchellh/peer-slices
stage2: peer resolve *[N]T to []T and E![]T and [*]T, handle in-memory coercion
2022-02-26 18:49:44 -05:00
Veikka Tuominen
bf3c88b68d stage2: various fixes to get one test passing
* resolve error sets before merging them
* implement tupleFieldPtr
* make ret_ptr behave like alloc with zero sized types in llvm backend
2022-02-26 18:44:23 -05:00
Mitchell Hashimoto
156316bc7c stage2: skip more tests for native backends 2022-02-26 13:56:50 -08:00
Joachim Schmidt
058e482247 Merge pull request #10996 from joachimschmidt557/stage2-arm
stage2 ARM: implement truncate to integers with <= 32 bits
2022-02-26 22:50:31 +01:00
Andrew Kelley
8349a644d0 Merge pull request #10986 from Vexu/stage2
stage2: actually coerce in coerce_result_ptr at comptime
2022-02-26 14:52:45 -05:00
Veikka Tuominen
bf5c055562 stage2: unify runtime and comptime coerce_result_ptr 2022-02-26 12:52:07 -07:00
Veikka Tuominen
bff7714a7c stage2: fix toAllocatedBytes on slices 2022-02-26 12:52:06 -07:00
Veikka Tuominen
ee149aaa03 stage2: actually coerce in coerce_result_ptr at comptime 2022-02-26 12:51:23 -07:00
Andrew Kelley
b3aa1ab693 Merge pull request #10994 from Vexu/typeof-scope
stage2: `@TypeOf` improvements
2022-02-26 14:47:43 -05:00
Mitchell Hashimoto
a5c9e8a494 typo in comment 2022-02-26 09:33:03 -08:00
Veikka Tuominen
315d4e8442 stage2: do not require function when evaluating typeOf
We only care about the instructions type; it will never actually be codegen'd.
2022-02-26 18:08:31 +02:00
Veikka Tuominen
ff72b8a819 stage2: evaluate TypeOf arguments in a separate scope 2022-02-26 18:08:11 +02:00
joachimschmidt557
f48f4baf67 stage2 ARM: generate correct variants of ldr instruction
When loading an i16 for example, generate ldrsh instead of ldrh
2022-02-26 13:00:01 +01:00
joachimschmidt557
8ef80cfaab stage2 ARM: implement truncate to ints with bits <= 32 2022-02-26 12:59:57 +01:00
Al Hoang
db82c1b982 add constant for haiku
* re-enable zig build on haiku
2022-02-26 10:53:13 +02:00
Endel Dreyer
cd9a6fed4f fix typo on Thread's getHandle docs 2022-02-26 10:48:37 +02:00
Jakub Konka
0474943ddf Merge pull request #10991 from ziglang/macho-pointer-rebase 2022-02-26 08:19:01 +01:00
Mitchell Hashimoto
f0232fc07d stage2: split up the big sentinel peer cast test to multiple
This way we can fix them one at a time.
2022-02-25 18:56:27 -08:00
Mitchell Hashimoto
91af552f87 stage2: resolve peer types that trivially coerce 2022-02-25 18:47:10 -08:00
Mitchell Hashimoto
943ee59bb1 stage2: *[N]T to [*]T (and vice versa) 2022-02-25 17:29:50 -08:00
Mitchell Hashimoto
e442f88b76 stage2: add other backend skips until they determine they pass 2022-02-25 17:03:49 -08:00
Mitchell Hashimoto
4a6f918029 stage2: remove extranneous debug 2022-02-25 13:37:07 -08:00
Mitchell Hashimoto
bcf3eb5663 stage2: another passing test 2022-02-25 13:35:36 -08:00
Mitchell Hashimoto
1019181982 stage2: *[N]T and E![]T 2022-02-25 13:33:11 -08:00
Mitchell Hashimoto
117ef22d3c stage2: peer resolve *[N]T to []T (and vice versa) 2022-02-25 13:21:07 -08:00
Jakub Konka
e0f5627d4a x64+aarch64: check for pointer to zero-bit type when lowering decl
Unless the pointer is a pointer to a function, if the pointee type
has zero-bits, we need to return `MCValue.none` as the `Decl` has
not been lowered to memory, and therefore, any GOT reference will be
wrong.
2022-02-25 21:59:19 +01:00
Jakub Konka
4b14384989 aarch64: check if type has runtime bits before allocating mem ptr 2022-02-25 21:59:19 +01:00
Jakub Konka
1b8ed7842c macho: redo selection of segment/section for decls and consts
* fix alignment issues for consts with natural ABI alignment not
  matching that of the `ldr` instruction in `aarch64` - solved by
  preceeding the `ldr` with an additional `add` instruction to form
  the full address before dereferencing the pointer.
* redo selection of segment/section for decls and consts based on
  combined type and value
2022-02-25 21:59:19 +01:00
Veikka Tuominen
bf6540ce50 Revert "stage2: make array len field type usize to match stage1"
This reverts commit 73bf418eb1.
2022-02-25 11:33:53 +02:00
Veikka Tuominen
73bf418eb1 stage2: make array len field type usize to match stage1
match stage1 behavior to avoid issues in standard library.
2022-02-25 11:25:56 +02:00
Luuk de Gram
0147eb9b58 wasm: Fix error union's size/alignment
Previously error unions were packed in memory. Now each 'field' is correctly
aligned to the error union's alignment.
2022-02-25 09:33:15 +01:00
Luuk de Gram
f4adb53bcf wasm: Refactor lowerUnnamedConst
Rather than ping ponging between codegen and the linker to generate the symbols/atoms
for a local constant and its relocations. We now create all neccesary objects within the linker.

This simplifies the code as we can now simply call `lowerUnnamedConst` from anywhere in codegen,
allowing us to further improve lowering constants into .rodata so we do not have to sacrifice
lowering certain types such as decl_ref's where its type is a slice.
2022-02-25 09:33:15 +01:00
Andrew Kelley
27eb42c15e Sema: implement tupleFieldVal, fix comptime elem_ptr 2022-02-24 22:28:37 -07:00
Andrew Kelley
adb746a701 stage2: improved handling of store_to_block_ptr
* AstGen: remove the setBlockBodyEliding function. This is no longer
   needed after 63788b2a51.
 * Sema: store_to_block_ptr instruction is handled as
   store_to_inferred_ptr or store, as necessary.
2022-02-24 22:28:37 -07:00
protty
5d30e8016d time: introduce Instant (#10972) 2022-02-24 18:51:44 -05:00
Veikka Tuominen
63788b2a51 stage2: change how stale store_to_block_ptrs are detected
Instead of explicitly setting lhs to .none,
check if the lhs instruction was analyzed.
This simpler approach also handles stores from nested blocks correctly.
2022-02-24 18:32:08 -05:00
Isaac Freund
52a2aa11e2 std: work around current packed struct situation
As of 6249a24, align() is not allowed on packed struct fields
and as such the align(4) was removed from the first field of
EdidOverrideProtocolAttributes. The endgame here is packed struct
backed by explicit integers, in this case a u32, but until that
is implemented put the align(4) on the pointer to avoid breaking
someone's UEFI code in a hard to debug way.
2022-02-24 16:08:37 -05:00
Andrew Kelley
e06cb31659 Merge pull request #10982 from Vexu/stage2
stage2: implement fieldParentPtr
2022-02-24 15:52:56 -05:00
Andrew Kelley
5ab5e2e673 Revert "Merge pull request #10950 from hexops/sg/responsefiles"
This reverts commit 136a43934b, reversing
changes made to 9dd839b7ed.

This broke the behavior of `zig run`.
2022-02-24 12:11:11 -07:00
Veikka Tuominen
cbd5d6c704 spirv spec: do not align packed struct fields 2022-02-24 19:48:34 +02:00
Veikka Tuominen
b034c45b2b stage2: implement fieldParentPtr 2022-02-24 19:48:34 +02:00
Andrew Kelley
6249a24e81 stage2: integer-backed packed structs
This implements #10113 for the self-hosted compiler only. It removes the
ability to override alignment of packed struct fields, and removes the
ability to put pointers and arrays inside packed structs.

After this commit, nearly all the behavior tests pass for the stage2 llvm
backend that involve packed structs.

I didn't implement the compile errors or compile error tests yet. I'm
waiting until we have stage2 building itself and then I want to rework
the compile error test harness with inspiration from Vexu's arocc test
harness. At that point it should be a much nicer dev experience to work
on compile errors.
2022-02-23 23:59:25 -07:00
Mitchell Hashimoto
65c0475970 stage2: peer type resolution *[N]T and *[M]T to []const T 2022-02-24 08:50:26 +02:00
Jakub Konka
ffb7ac6755 elf: use fully qualified decl names in the linker 2022-02-24 00:01:11 +01:00
Jakub Konka
9d098318e2 Merge pull request #10977 from joachimschmidt557/stage2-aarch64
stage2 AArch64: more support for PIE targets (Mach-O)
2022-02-24 00:00:15 +01:00
Jakub Konka
136a43934b Merge pull request #10950 from hexops/sg/responsefiles
Do not fail to build if 'zig build-lib' etc. arguments exceed OS limits
2022-02-23 22:54:25 +01:00
Jakub Konka
9dd839b7ed Merge pull request #10976 from ziglang/x64-macos-fixes
x64: print test runner results on macos
2022-02-23 22:40:06 +01:00
Jan Philipp Hafer
5d89955543 compiler_rt: specify goals, organize README and compiler_rt.zig
* goals
  - zig as linker for object files generated by other compilers
  - zig-specific runtime features for eventual standardisation

* changes
  - missing routines are marked with `missing`
  - structure inspired by libgcc docs, but improved order and wording
  - rename misspelled functions
  - reorder and rephrase compiler_rt.zig to reflect documentation
  - potential decimal float or fixed-point arithmetic support:
    * 'Decimal float library routines' ca. 120 functions
    * 'Fixed-point fractional library routines' ca. 300 functions

thanks to @Vexu for multiple reviews and @scheibo for review
2022-02-23 16:38:51 -05:00
Andrew Kelley
ecf56d85ef Merge pull request #10969 from Vexu/stage2
stage2: fn typeinfo params
2022-02-23 16:10:17 -05:00
joachimschmidt557
f91fe9afb9 stage2 AArch64: more support for MCValue.got_load and direct_load 2022-02-23 21:58:13 +01:00
joachimschmidt557
4683f94463 stage2 AArch64: remove MIR load_memory instruction
This instruction now just represents loading from a hard-coded adrress
after extracting the other use cases for load_memory into load_got and
load_direct.
2022-02-23 21:57:59 +01:00
Andrew Kelley
88d1258e08 stage2: make -lgcc_s additionally link libunwind
Previously, Zig ignored -lgcc_s with a warning that this dependency is
redundant because it is satisfied by compiler-rt. However, sfackler
pointed out that it also provides exception handling functions. So if
Zig sees -lgcc_s on the linker line, it needs to fulfill this dependency
with libunwind.

I also made link_libc inferred to be on if libunwind is linked since
libunwind depends on libc.
2022-02-23 13:25:10 -07:00
Jakub Konka
b7760ad742 std: re-enable result printing in the test runner for macos 2022-02-23 19:39:50 +01:00
Jakub Konka
2f0299c3cf x64: account for multiple returns from functions
This is necessary to correctly adjust for spilling of the %rdi
register in the callee.
2022-02-23 19:29:47 +01:00
Jakub Konka
2ca809c32a macho: ensure we save the fully qualified name for any local symbol
Otherwise, we risk collisions in the global symbol table. This is
also an opportunity to generalise and rewrite the symbol table
abstraction.

Also, improve the logs for the symbol table.
2022-02-23 19:10:44 +01:00
Jakub Konka
897a5a4735 macho: synthesising __mh_execute_header needs to work with incremental
Prior to this change, the routine would assume it is called first,
before any symbol was created, thus precluding an option that in the
incremental setting, we might have already pulled a suitably defined
and exported symbol that could collide and/or be replaced by the
symbol synthesised by the linker.
2022-02-23 19:10:40 +01:00
Luuk de Gram
acec06cfaf wasm-linker: Implement updateDeclExports
We now correctly implement exporting decls. This means it is possible to export
a decl with a different name than the decl that is doing the export.
This also sets the symbols with the correct flags, so when we emit a relocatable
object file, a linker can correctly resolve symbols and/or export the symbol to the host environment.

This commit also includes fixes to ensure relocations have the correct offset to how other
linkers will expect the offset, rather than what we use internally.
Other linkers accept the offset, relative to the section.
Internally we use an offset relative to the atom.
2022-02-23 16:07:36 +01:00
Luuk de Gram
0a48a763fd wasm-linker: Emit relocations for object files
When generating a relocatable object file, we now emit a custom "reloc.CODE" and "reloc.DATA" section
which will contain the relocations for each section.

Using a new symbol location -> Atom mapping, we can now easily find the corresponding `Atom` from a symbol.
This can be used to construct the symbol table, as well as easier access to a target atom when performing
a relocation for a data symbol.
2022-02-23 16:07:36 +01:00
Luuk de Gram
2b0431a8d3 wasm-linker: Do not merge data segments for obj
When creating a relocatable object file, we do no longer perform the following actions:
- Merge data segments
- Calculate stack size
- Relocations

We now also make the stack pointer symbol `undefined` for this use case as well as add the symbol
as an import.
2022-02-23 16:07:36 +01:00
Luuk de Gram
daf741318e wasm-linker: Emit segment info
When creating a relocatable object file, also emit the segment information
2022-02-23 16:07:36 +01:00
Luuk de Gram
f7f3678b48 wasm-linker: Emit symbol table for object file
When creating a relocatable object file, emit the symbol table.
We do this by iterating over all atoms, and finding the corresponding
symbols of those. This provides us all the meta information such as size, and offset as well.
This data is required for defined data symbols.

When we emit an object file, the "Names" section does not have to be emitted, as all symbol names
are already in the symbol table, so the names section is redundant.
2022-02-23 16:07:36 +01:00
Exonorid
91a88a789f Add documentation for common mistakes in errdefer scoping 2022-02-23 14:33:51 +02:00
Evan Haas
9716a1c3ab translate-c: Add support for cast-to-union
Fixes #10955
2022-02-23 14:11:46 +02:00
Veikka Tuominen
ab4d693cfc re-enable @src behavior test 2022-02-23 10:40:46 +02:00
Veikka Tuominen
92beb2b490 stage2: misc fixes in Sema 2022-02-23 10:40:40 +02:00
xReveres
4a0b037464 wasm: correct shared memory error text 2022-02-23 08:57:20 +01:00
xReveres
fb7cde3071 wasm: shared memory checks 2022-02-23 08:57:20 +01:00
xReveres
b2805666a7 stage1-wasm: implement shared memory 2022-02-23 08:57:20 +01:00
Veikka Tuominen
923b07bac7 stage2: add parameters to fn typeInfo 2022-02-23 09:44:36 +02:00
Veikka Tuominen
f8154905e7 stage1: rename TypeInfo.FnArg to Fn.Param 2022-02-23 09:44:36 +02:00
Felix Queißner
6fdcf1ad2d std.os.linux.socketpair: fd is an out parameter 2022-02-23 09:32:54 +02:00
Stephen Gutekanst
c577926a7d zig build: style: remove unnecessary constant bindings
Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-02-22 15:49:03 -07:00
Jakub Konka
e5c30eef1f Merge pull request #10949 from ziglang/x64-print-results
stage2,x64: print test_runner results
2022-02-22 23:06:07 +01:00
Jakub Konka
c64d3b0a96 Skip @src for stage1 too 2022-02-22 22:33:57 +01:00
Jakub Konka
160f657156 Skip unsupported while behavior tests 2022-02-22 22:14:49 +01:00
Jakub Konka
8e4a8771f5 Skip unsupported enum behavior tests 2022-02-22 22:04:32 +01:00
Jakub Konka
8abd30019c x64: completely ignore printing tests on macos until I fix the linker 2022-02-22 21:57:44 +01:00
Jakub Konka
d657ede324 x64: disable printing results on macos until I fix the linker
Hopefully, this will make the CI green, and in the meantime I can
fix the bugs in the MachO linker.
2022-02-22 21:57:44 +01:00
Jakub Konka
25e4b16e25 Port more behavior tests 2022-02-22 21:57:42 +01:00
Jakub Konka
a94267b290 std: export ceil builtins in stage2 2022-02-22 21:56:34 +01:00
Jakub Konka
1bbb886694 Port bitcast.zig tests 2022-02-22 21:56:34 +01:00
Jakub Konka
150006d216 std: enable print results in test_runner for stage2_x86_64 2022-02-22 21:56:34 +01:00
Jakub Konka
3be6c79ca2 x64: spill compare flags between blocks, extern calls, and cmp insts
This is just the first step towards the final solution as to get
here I had omit a safety assert check in `getResolvedInst` helper.
2022-02-22 21:56:34 +01:00
Jakub Konka
b9b4e4671f x64: add naive impl of else in switch 2022-02-22 21:56:34 +01:00
Jakub Konka
2617117221 x64: fix lowering of error unions (we didn't pad to alignment)
* fix returning large values on stack from procedure calls - we
  need to explicitly specify source and dest base registers for
  `genSetStack` as well
2022-02-22 21:56:34 +01:00
Jakub Konka
87a0d754be x64: add basic, naive impl of switch 2022-02-22 21:56:34 +01:00
Jakub Konka
2d3462c79a liveness: add helper for extracting liveness of switch branch 2022-02-22 21:56:34 +01:00
Jakub Konka
5ba66911fa x64: add basic impl of shl for integers 2022-02-22 21:56:34 +01:00
Jakub Konka
71dda25f14 x64: add basic impl of minimum builtin for ints 2022-02-22 21:56:34 +01:00
Jakub Konka
25d313f911 codegen: lower repeated and empty_with_sentinel array type 2022-02-22 21:56:34 +01:00
Jakub Konka
57c9eec232 x64: implement unwrap_err_payload and unwrap_err_err for stack offset 2022-02-22 21:56:34 +01:00
Jakub Konka
f4f23e307c codegen: lower error_set and error_union 2022-02-22 21:56:34 +01:00
Jakub Konka
358b544157 x64: recover address in rdi if was spilled 2022-02-22 21:56:34 +01:00
Jakub Konka
630da643c6 x64: pass pointer to stack for return value in .rdi register 2022-02-22 21:56:34 +01:00
Jakub Konka
478f770053 x64: first, really horrible attempt at returning values on stack 2022-02-22 21:56:34 +01:00
Jakub Konka
e582c0a043 x64: reorder resolving call params: return values first, then params 2022-02-22 21:56:34 +01:00
Jakub Konka
8bc95b22dc x64: sub is non-commutative 2022-02-22 21:56:34 +01:00
Andrew Kelley
b23f10b424 Sema: fix comptime coercion of payload to error union 2022-02-22 13:53:10 -07:00
Andrew Kelley
0d422ce342 Sema: auto-numbered enums increment from last tag value
This matches stage1 and the existing behavior tests.
2022-02-22 12:44:35 -07:00
e620b692c6 [std.ArrayList] return explicit errors
All errors from std.ArrayList are allocation errors. Mark them as such.
This is helpful when one wants to obtain a function pointer.
2022-02-22 13:57:51 -05:00
Veikka Tuominen
df38c46bee Merge pull request #10929 from davidmrt98/cbe
stage2: C backend: fix codegen for field_ptr/elem_ptr values
2022-02-22 15:25:50 +02:00
Andrew Kelley
c2a9a591f6 Sema: fix union auto-enum numbering 2022-02-21 23:50:20 -07:00
Andrew Kelley
9dc98fbabb Sema: fix comptime union initialization
The mechanism behind initializing a union's tag is a bit complicated,
depending on whether the union is initialized at runtime,
forced comptime, or implicit comptime.

`coerce_result_ptr` now does not force a block to be a runtime context;
instead of adding runtime instructions directly, it forwards analysis to
the respective functions for initializing optionals and error unions.

`validateUnionInit` now has logic to still emit a runtime
`set_union_tag` instruction even if the union pointer is comptime-known,
for the case of a pointer that is not comptime mutable, such as a
variable or the result of `@intToPtr`.

`validateStructInit` looks for a completely different pattern now; it
now handles the possibility of the corresponding AIR instruction for
the `field_ptr` to be missing or the corresponding `store` to be missing.
See the new comment added to the function for more details. An
equivalent change should probably be made to `validateArrayInit`.

`analyzeOptionalPayloadPtr` and `analyzeErrUnionPayloadPtr` functions now
emit a `optional_payload_ptr_set` or `errunion_payload_ptr_set`
instruction respectively if `initializing` is true and the pointer value
is not comptime-mutable.

`storePtr2` now tries the comptime pointer store before checking if the
element type has one possible value because the comptime pointer store
can have side effects of setting a union tag, setting an optional payload
non-null, or setting an error union to be non-error.

The LLVM backend `lowerParentPtr` function is improved to take into
account the differences in how the LLVM values are lowered depending on
the Zig type. It now handles unions correctly as well as additionally
handling optionals and error unions.

In the LLVM backend, the instructions `optional_payload_ptr_set` and
`errunion_payload_ptr_set` check liveness analysis and only do the side
effects in the case the result of the instruction is unused.

A few wasm and C backend test cases regressed, but they are due to TODOs
in lowering of constants, so this is progress.
2022-02-21 23:49:38 -07:00
Andrew Kelley
7f48bc3493 disable failing nvptx test case
workaround for #10968
2022-02-21 23:48:07 -07:00
Andrew Kelley
6dc5ce931c Merge pull request #10959 from joachimschmidt557/stage2-aarch64
stage2 AArch64: misc improvements
2022-02-22 01:30:49 -05:00
joachimschmidt557
25f73224f7 stage2 AArch64: pass a few more behavior tests 2022-02-21 23:05:16 +01:00
joachimschmidt557
2ba1ef165a stage2 AArch64: implement genSetReg for ptr_stack_offset 2022-02-21 22:54:14 +01:00
joachimschmidt557
ec62e76455 stage2 AArch64: replace genMulConstant with binOp 2022-02-21 22:54:09 +01:00
joachimschmidt557
19c683fab0 stage2 AArch64: distinguish between sp/wsp and xzr/wzr 2022-02-21 22:44:47 +01:00
joachimschmidt557
a9154a7eaf stage2 AArch64: implement storing to memory 2022-02-21 22:44:40 +01:00
Stephen Gutekanst
b341967da0 zig build: use a custom iterator for merging args and response file
Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-02-21 14:20:38 -07:00
Stephen Gutekanst
efd473bbfc std: Builder: use response files for zig test invocations too
Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-02-21 13:06:23 -07:00
Stephen Gutekanst
9c1c4747f4 std: Builder: account for null term considering response files
Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-02-21 12:58:13 -07:00
Stephen Gutekanst
fb61db1ee4 zig build: use orelse to fetch next argument
Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-02-21 12:52:10 -07:00
Andrew Kelley
74303a3d95 Merge pull request #10925 from Vexu/stage2
stage2: support anon init through error unions and optionals
2022-02-21 14:18:17 -05:00
gwenzek
628e9e6d04 enable Gpu address spaces (#10884) 2022-02-21 14:05:27 -05:00
Carlos Zúñiga
d8da9a01fc Use lowercase in shasum for windows builds 2022-02-21 00:40:46 -05:00
Ali Chraghi
a4df443f96 Update Tokenizer Dump Function
fix missed `loc` field
2022-02-20 17:47:42 -05:00
Stephen Gutekanst
2bd10f4db9 std: have Builder use response files if zig build args exceed OS limits
In Mach engine we're seeing command line arguments to `zig build-lib`
exceed the 32 KiB limit that Windows imposes, due to the number of
sources and compiler flags we must pass in order to build gpu-dawn.

This change fixes the issue by having `Builder` check if the arguments
to a `zig build-*` command are >30 KiB and, if so, writes the arguments
to a file `zig-cache/args/<SHA2 of args>`. Then the command invocation
merely becomes `zig build-lib @<that file>`.

Fixes #10693

Fixes hexops/mach#167

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-02-20 14:44:39 -07:00
Stephen Gutekanst
e41d4df93c enable passing build-[lib|exe|obj] params via @args.rsp file
This change enables `zig build-lib` and friends to take a response file
of command line arguments, for example:

```sh
zig build-lib @args.rsp
```

Which effectively does the same thing as this in Bash:

```sh
zig build-lib $(cat args.rsp)
```

Being able to use a file for arguments is important as one can quickly
exceed the 32 KiB limit that Windows imposes on arguments to a process.

Helps #10693

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-02-20 13:50:09 -07:00
Stephen Gutekanst
0778f644b5 use process.argsWithAllocator iterator for command line handling
This change refactors the `zig` argument handling (for `build-lib`, etc.
commands) to use a `process.argsWithAllocator` iterator instead of
directly accessing arguments via array indices. This supports the next
commit which will enable us to use a response file argument iterator
here seamlessly.

Helps #10693

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
2022-02-20 13:47:41 -07:00
Steven Fackler
2c8541bdde Support -Wl,--soname 2022-02-20 13:56:12 -05:00
David John
bdb5713941 stage2: fix typo in riscv64/Emit.zig 2022-02-20 19:10:54 +01:00
Luuk de Gram
bb05a8a08a stage2: Fix 32bit builds 2022-02-20 18:16:28 +01:00
Veikka Tuominen
a5ac062689 stage2: make field/array base ptr work at comptime 2022-02-20 11:59:49 +02:00
Veikka Tuominen
65aa333197 fix formatting in openbsd.zig
CI was failing for unrelated reasons so this went unnoticed
2022-02-20 11:58:42 +02:00
Dante Catalfamo
ec59a04138 Add OpenBSD auth functions 2022-02-20 09:58:58 +02:00
Andrew Kelley
7d9e3840bb Sema: fix inline break from a non-comptime scope to outer one
Prior to this, the compiler would hit an assertion because the
break_inline would not successfully move the compile-time control flow.
2022-02-20 00:20:29 -07:00
Andrew Kelley
01638c250f Sema: implement readFromMemory for arrays 2022-02-20 00:08:05 -07:00
Andrew Kelley
bfff8544e1 AstGen: emit break_inline for corresponding inline loops
Prior to this commit there would be a `break` ZIR instruction to break
from a `block_inline` which is a mismatch.
2022-02-19 20:26:57 -07:00
Veikka Tuominen
a2533e6fca stage2: validate struct/array init ty 2022-02-20 02:11:06 +02:00
Veikka Tuominen
6f0601c793 stage2: support anon init through error unions and optionals at runtime 2022-02-20 02:11:02 +02:00
Ryan Liptak
83a486a064 os.getenvW: Fix handling of special =-prefixed env vars 2022-02-19 15:46:23 -08:00
Ryan Liptak
c87f79c957 os.getenvW: Fix case-insensitivity for Unicode env var names
Windows does Unicode-aware case-insensitivity comparisons for environment variable names. Before, os.getenvW was only doing ASCII case-insensitivity. We can take advantage of RtlEqualUnicodeString in NtDll to get the proper Unicode case insensitivity.
2022-02-19 15:46:23 -08:00
Andrew Kelley
8841a71aa6 AstGen: evaluate comptime var init expressions in a comptime context 2022-02-19 15:11:18 -07:00
Andrew Kelley
746435a954 Sema: implement @typeInfo for list literals 2022-02-19 15:11:18 -07:00
Lee Cannon
b0cdd3d0e6 StackIterator should not try to check validity on freestanding 2022-02-19 15:38:56 -05:00
Veikka Tuominen
27c63bf433 stage2: implement errunion_payload_ptr_set 2022-02-19 20:48:00 +02:00
Veikka Tuominen
89f6ff1771 stage2: correct use of .unwrap_err_union_* in LLVM and C backend 2022-02-19 20:21:48 +02:00
Veikka Tuominen
e027492243 stage2: support anon init through error unions and optionals 2022-02-19 20:21:19 +02:00
Jakub Konka
539bb8a2d7 Merge pull request #10927 from ziglang/x64-idiv-imul
stage2,x64: implement integer division
2022-02-19 17:35:58 +01:00
Joachim Schmidt
e86a89d3f0 Merge pull request #10926 from joachimschmidt557/stage2-arm
stage2 ARM: move to binOp lowering mechanism
2022-02-19 15:37:06 +01:00
Jakub Konka
59df39e949 add integer division tests 2022-02-19 14:24:03 +01:00
Jakub Konka
da86839af0 x64: clean up implementation of divs, mod, rem for integers 2022-02-19 14:24:03 +01:00
Jakub Konka
bd396d7e07 x64: add unsigned div and move logic into a helper fn 2022-02-19 14:24:03 +01:00
Jakub Konka
2c13a4b87e x64: implement div_exact for ints (signed+unsigned) 2022-02-19 14:24:03 +01:00
Jakub Konka
1f4aa5ef78 x64: add lowering for single operand imul and idiv 2022-02-19 14:24:03 +01:00
David Martschenko
176f7b8600 C backend: adjust order of parameters in renderDeclName 2022-02-19 13:05:09 +01:00
David Martschenko
4a6454fb8d C backend: fix codegen for field_ptr/elem_ptr values 2022-02-19 13:04:59 +01:00
joachimschmidt557
669603029e stage2 ARM: implement airCmp with binOp lowering mechanism 2022-02-19 12:12:29 +01:00
joachimschmidt557
c29bf2f51a stage2 ARM: move shl, shr to binOp lowering mechanism 2022-02-19 12:06:34 +01:00
joachimschmidt557
3b1762bb47 stage2 ARM: fix boolean and bitwise not 2022-02-19 12:06:34 +01:00
joachimschmidt557
7b833b2fba stage2 ARM: move {bool,bit}_{or,and} to binOp lowering mechanism 2022-02-19 12:06:34 +01:00
joachimschmidt557
985a442f46 stage2 ARM: move mul to binOp lowering mechanism 2022-02-19 12:06:34 +01:00
joachimschmidt557
67e3346633 stage2 ARM: move add and sub to new binOp lowering mechanism 2022-02-19 12:06:30 +01:00
joachimschmidt557
23915c2c44 stage2 ARM: simplify invocations of genInlineMemcpy 2022-02-19 12:04:54 +01:00
Veikka Tuominen
2f0204aca3 parser: fix "previous field here" pointing to wrong field 2022-02-19 10:15:54 +02:00
Andrew Kelley
2e1c16d649 Merge pull request #10924 from ziglang/air-independence-day
AIR independence day
2022-02-19 02:57:48 -05:00
Andrew Kelley
4e1e5ab622 stage2: make AIR not reference ZIR for inline assembly
Instead it stores all the information it needs to into AIR.

closes #10784
2022-02-18 19:41:32 -07:00
Andrew Kelley
123076ea88 ArrayList: add unusedCapacitySlice to the unmanaged API
This function is super nice thank you whoever added it 👍
2022-02-18 19:35:39 -07:00
Andrew Kelley
09d93ec845 Merge pull request #10887 from topolarity/stage2-bitreverse-byteswap
stage2 llvm: Implement `@bitReverse`, `@byteSwap` built-ins
2022-02-18 20:29:31 -05:00
Andrew Kelley
32edb9b55d stage2: eliminate ZIR arg instruction references to ZIR
Prior to this commit, the AIR arg instruction kept a reference to a ZIR
string index for the corresponding parameter name. This is used by DWARF
emitting code. However, this is a design flaw because we want AIR
objects to be independent from ZIR.

This commit saves the parameter names into memory managed by
`Module.Fn`. This is sub-optimal because we should be able to get the
parameter names from the ZIR for a function without having them
redundantly stored along with `Fn` memory. However the current way that
ZIR param instructions are encoded does not support this case. They
appear in the same ZIR body as the function instruction, just before it.
Instead, they should be embedded within the function instruction, which
will allow this TODO to be solved. That improvement is too big for this
commit, however.

After this there is one last dependency to untangle, which is for inline
assembly. The issue for that is #10784.
2022-02-18 16:56:12 -07:00
Cody Tapscott
db80dff4e0 Add backend-specific skips for bitreverse, byteswap tests 2022-02-18 14:28:32 -07:00
Cody Tapscott
fe1d6c2f56 Skip failing stage1 @bitReverse test 2022-02-18 14:28:32 -07:00
Cody Tapscott
ef417f19e1 stage2: Implement @bitReverse and @byteSwap
This change implements the above built-ins for Sema and the LLVM
backend. Other backends have had placeholders added for lowering.
2022-02-18 14:28:32 -07:00
Lee Cannon
dee96e2e2f std.testing.refAllDecls: force decl to be analyzed with just @field
Co-authored-by: Veikka Tuominen <git@vexu.eu>
2022-02-18 21:21:21 +02:00
Andrew Kelley
2c24bf2f79 Merge pull request #10604 from fifty-six/master
std/os/uefi: additional improvements/fixes
2022-02-18 14:16:30 -05:00
Andrew Kelley
60bb1d4e1c Merge pull request #10906 from topolarity/cbe-array-support
stage2 CBE: Implement 2D array support
2022-02-18 14:08:06 -05:00
Andrew Kelley
736b9dcdd6 Merge pull request #10858 from topolarity/stage2-bitcast
stage2 sema: Fix sign handling of exotic integers in `@bitCast`
2022-02-18 13:49:00 -05:00
chip2n
ab43c045ed Fix incorrect documentation for std.HashMap.remove() 2022-02-18 13:47:38 -05:00
Jakub Konka
5af9d0c603 Merge pull request #10916 from ziglang/x64-args-stack-debug
stage2,x64: pass all args on stack in debug and if not extern fn
2022-02-18 15:18:01 +01:00
Jakub Konka
0f0bb7e5ea x64: ensure 16byte stack alignment across calls 2022-02-18 13:02:08 +01:00
Veikka Tuominen
53241f288e Merge pull request #10913 from Vexu/err
further parser error improvements
2022-02-18 13:53:47 +02:00
Jakub Konka
d74e9b2d98 x64: rename copyToNewRegister to copyToRegisterWithInstTracking for impr clarity 2022-02-18 09:14:15 +01:00
Jakub Konka
83744b92a1 x64: fix wrong regalloc with inst tracking in airCmp
We return compare flags rather than a register which than wrongly
cheats the regalloc into thinking we carry the instruction in the
register which we do not.
2022-02-18 09:14:15 +01:00
Jakub Konka
97c25fb8d0 x64: implement array_elem_val when array is stored in memory 2022-02-18 09:14:15 +01:00
Jakub Konka
abfaf8382b x64: implement array_elem_val when array fits in register 2022-02-18 09:14:15 +01:00
Jakub Konka
085c606b87 x64: implement slice_elem_ptr 2022-02-18 09:14:15 +01:00
Jakub Konka
6d3c7bd436 x64: pass all args on stack in debug and if not extern fn
If the function call is not extern and we are compiling in debug,
pass function params always on stack. This will improve debugging
capabilities since the params will not be volatile and possibly
clobbered by the procedure code.

Finish implementation of `imul_complex`.
2022-02-18 09:14:15 +01:00
Andrew Kelley
56e9575e82 Merge pull request #10919 from ziglang/test-more-stage2
CI: more stage2 test coverage
2022-02-18 01:54:34 -05:00
Andrew Kelley
eee500c0b5 build.zig: restore the ability to bootstrap with zig0 via option 2022-02-17 23:49:13 -07:00
Andrew Kelley
dd12a7b1e5 ci: linux: re-use cmake config for finding LLVM 2022-02-17 23:42:48 -07:00
Andrew Kelley
6f42876e74 CLI: resolve system libs into static libraries
using the provided -L directories before checking if we need to integrate
with system library paths. This prevents false positive of invoking
system cc to find native paths when in fact all dependencies are
satisfied by -L (or --search-prefix to zig build).
2022-02-17 23:42:48 -07:00
Andrew Kelley
419074a81b CI: simplify linux script
* build.zig: remove detour through zig0. I'll add it back as an option
   later. This means you can build stage1 with a freshly built zig
   without detouring through zig0 again.
 * remove unused file windows_script.bat
 * drone.yml: remove unnecessary steps
 * ninja doesn't need a jobs parameter
 * build the release version of zig with zig build instead of cmake.
 * build stage2 with -Dstatic-llvm -Duse-zig-libcxx
2022-02-17 23:42:46 -07:00
Andrew Kelley
2f42a2617b CI: more stage2 test coverage
* Test everything on the Linux CI even if we can't run it, because it's
   our fastest machine.
 * Test stage2 using a build of stage2 (instead of using `-fno-stage1`)
   so that compiler-rt is also built with stage2.
 * Additionally test running x86_64-macos on the macOS CI, both the LLVM
   backend and x86_64 backend.
2022-02-17 23:41:58 -07:00
Andrew Kelley
9ea253b9c4 Sema: implement type info for structs 2022-02-17 20:48:09 -07:00
Andrew Kelley
23567cdd98 build.zig: fix test-stage2 regression with -Denable-llvm
Regressed in cc9eb9e90f due to a merge
conflict.
2022-02-17 20:48:09 -07:00
Andrew Kelley
0bb22600bd Sema: fix typeinfo for enums with no declarations 2022-02-17 20:48:09 -07:00
Andrew Kelley
feb4b01b38 Sema: fix typeinfo for sentinels of array and pointer 2022-02-17 20:48:09 -07:00
J87
b837855317 Replace magic numbers with clearer representation
Replaces two magic numbers with the procedure used to generate them, in order to keep consistent with other implementations for f64 & f128.
2022-02-17 21:20:04 -05:00
Andrew Kelley
5aa35f62c3 Revert "reduce build error noise"
This reverts commit baead472d7.

Let's go through the proposal process on this one. I want to push back
on this. My position is that, at the very least, a full trace of command
lines of sub-processes should be printed on failure, with the exception
of opt-in flags such as `--prominent-compile-errors`.
2022-02-17 14:30:12 -07:00
Veikka Tuominen
6235afc632 stage1: fix f80 negation 2022-02-17 23:06:46 +02:00
Veikka Tuominen
6b65590715 parser: add notes to decl_between_fields error 2022-02-17 22:16:26 +02:00
Andrew Kelley
f20929bd8b stage2: fix crash using -femit-bin 2022-02-17 13:12:31 -07:00
Andrew Kelley
63cbec1a96 stage2: add more functions to freestanding libc
The log functions are not passing behavior tests.
2022-02-17 13:11:58 -07:00
Veikka Tuominen
92f2767814 parser: add error for missing colon before continue expr
If a '(' is found where the continue expression was expected and it is
on the same line as the previous token issue an error about missing
colon before the continue expression.
2022-02-17 20:51:26 +02:00
Luuk de Gram
ced958e8a8 wasm-linker: Simplify symbol names
No longer duplicate the symbol name and instead take the pointer from the decl itself.
Also fix 32bit build
2022-02-17 18:11:48 +01:00
Luuk de Gram
4ebe8a53ca wasm-linker: Fix symbol resolving and relocs
- Correctly get discard symbol by first checking if it was discarded or not.
- Remove imports if extern symbols were resolved by an object file.
- Correctly relocate data symbols by ensuring the atom is from the correct file.
- Fix the `Names` section by using the resolved symbols, rather than the ones defined in Zig code.
2022-02-17 18:11:48 +01:00
Luuk de Gram
a4622501bd wasm-linker: Allocate atoms and handle imports
We now correctly allocate and create atoms for symbols from other object files.
Imports are now also resolved and appended when required.
Besides those changes, we now duplicate all symbol names, so we can correctly
generate unique names for unnamed constants.
TODO: String interning
2022-02-17 18:11:48 +01:00
Luuk de Gram
f1cc5f33e8 wasm-linker: Implement section merging
This implements the merging of all sections, to generate a valid wasm binary where all symbols
have been resolved and their respective sections have been merged into the final binary.
2022-02-17 18:11:48 +01:00
Luuk de Gram
e7be0bef43 wasm-linker: Add Object file parsing
This upstreams the object file parsing from zwld, bringing us closer to being able
to link stage2 code with object files/C-code as well as replacing lld with the self-hosted
linker once feature complete.
2022-02-17 18:11:48 +01:00
Jakub Konka
d1c74ac42d Merge pull request #10914 from ziglang/x64-more-codegen
stage2,x64: refactor stack mgmt mechanics, implement slice, fix ptr_add and ptr_sub
2022-02-17 18:05:30 +01:00
Veikka Tuominen
c9dde10f86 stage1: improve error message when casting tuples 2022-02-17 17:39:54 +02:00
Jakub Konka
3193cc1c1e x64: fix ptr_add and ptr_sub
Add standalone implementation of operand reuse for ptr related
arithmetic operations of add and sub.
2022-02-17 15:07:42 +01:00
Jonathan Marler
baead472d7 reduce build error noise
Address https://github.com/ziglang/zig/issues/3477
This provides a mechanism for builds to fully report an error to the user and prevent zig from piling on extra noise.
2022-02-17 14:48:22 +02:00
John Schmidt
e2ad95c088 stage2: implement vector floatops 2022-02-17 14:47:21 +02:00
Koakuma
755d116ecf stage1: use u16 for __truncxfhf2/__extendhfxf2 on non-Arm CPUs
Non-Arm CPUs use u16 as the parameter to __extendhfxf2 and the return value of
__truncxfhf2, so insert appropriate bitcasts in gen_soft_f80_widen_or_shorten.
Otherwise, LLVM might crash because the functions are called in a different way
than its compiler-rt definition.

This fixes stage1 build on SPARCv9, and possibly other non-x86, non-Arm CPUs.
2022-02-17 14:46:04 +02:00
Veikka Tuominen
35e989235b parser: get rid of "invalid token" error 2022-02-17 14:23:42 +02:00
Veikka Tuominen
9c36cf92f0 parser: make some errors point to end of previous token
For some errors if the found token is not on the same line as
the previous token, point to the end of the previous token.
This usually results in more helpful errors.
2022-02-17 14:23:35 +02:00
Hadrien Dorio
02902cc099 ci: azure: split build-and-test step (#10853)
replace the .bat script by a pwsh script
2022-02-16 22:33:08 -05:00
Andrew Kelley
df8c325012 Merge pull request #10907 from ziglang/ci-windows-zig-cc
CI: windows: depend on Zig instead of CMake and MSVC
2022-02-16 20:44:42 -05:00
Andrew Kelley
25a7025613 ci: use zig-bootstrap for windows 2022-02-16 18:43:45 -07:00
Jakub Konka
c1fb14c51e x64: handle storing non-pow2 values to stack from register
This actually requires storing and shifting mechanics so that we
don't accidentally clobber anything else on the stack.
2022-02-17 00:26:00 +01:00
Andrew Kelley
cc9eb9e90f build.zig: bootstrap stage1 with zig0
Instead of assuming that the zig version used with `zig build` is
appropriate for building the self-hosted compiler component, we follow
the same path as the cmake build script and build zig0, using that to
produce zig1.o, re-linking to produce stage1.

This allows an arbitrarily old Zig version and corresponding build.zig
script to build all future versions of Zig from source via the bootstrap
compiler. In other words, it allows us to use `zig build` as an
alternative to cmake when bootstrapping.
2022-02-16 14:12:15 -07:00
Andrew Kelley
2b3df5c81d link: avoid double close on openPath error 2022-02-16 14:12:15 -07:00
Jakub Konka
94474ec7c7 x64: refactor use of inline memcpy 2022-02-16 21:40:08 +01:00
Cody Tapscott
1639fd4c45 Fix 2D array support for C backend
This updates the C backend to use proper array types.

In order to do that, this commit also:
 - fixes up elem_ptr and field_ptr handling
 - adds `renderTypecast` (renders in C typecast format, e.g. "int* [10]")
 - adds a bit special handling for undefined pointers, which is necessary
   to support slice/elem_ptr to undefined decls
2022-02-16 12:57:11 -07:00
Jakub Konka
09d468b237 x64: overhaul stack handling mechanics
Now, the abstracted stack offsets grow in the same direction as
the real stack values in hardware, and allocating stack memory is done
by the taking the last stack offset, adding required abi size
and aligning to the required abi align. Stack handling is now more
natural as it aligns itself with how it works in hardware; hence
stepping through the debugger and printing out different stack
values is intuitive. Finally, the stack pointers are now correctly
aligned to the required (and not necessarily natural) alignment.
2022-02-16 20:35:03 +01:00
Cody Tapscott
c4baa6696e cbe: Add writeCValueDeref and small re-factor 2022-02-16 12:19:54 -07:00
joachimschmidt557
1a84c23d69 stage2 AArch64: Simplify and correct invocations of genInlineMemcpy
Previously, the invocations used movk instead of movz
2022-02-16 15:47:44 +01:00
Jakub Konka
d3edf298d1 x64: fix signed truncate 2022-02-16 15:24:04 +01:00
Jakub Konka
1b7ec44924 x64: separate ptr_add and ptr_sub from normal bin ops 2022-02-16 15:00:32 +01:00
Jakub Konka
3383064b27 x64: implement airSlice 2022-02-16 14:13:06 +01:00
Jakub Konka
78e6f9c44c x64: fix ptr_add
However, still missing is taking into account pointer alignment
when performing arithmetic.
2022-02-16 14:13:06 +01:00
Jakub Konka
c7775a9f62 x64: impl genBinMathOpMir for ptr_stack_off and PIE memory 2022-02-16 14:13:06 +01:00
iddev5
77e5b042a0 fmt: allow uppercase prefix to be parsed in std.fmt.parseInt()
std.fmt.parseHexFloat allow both 0x and 0X as prefix, so in order to
keep things consistent. This commit modifies std.fmt.parseWithSign to
check for the prefix case insensitively in order to allow both upper
case and lower case prefix.

This change now allows: 0O, 0B and 0X as prefixes for parsing.
2022-02-16 11:27:10 +01:00
Jakub Konka
5283a52af5 macho: handle binary updates in dSYM companion file
* move DWARF in file if LINKEDIT spilled in dSYM
* update VM addresses for all segments
* introduce copyFileRangeOverlappedAll instead of File.copyRangeAll
  since we make lots of overlapping writes in MachO linker
2022-02-16 08:38:28 +01:00
Andrew Kelley
0b22b6b70e ci: update x86_64-linux tarballs
The updated docker images has LLVM, LLD, Clang updated to 13.0.1 and Zig
updated to 0.9.1.
2022-02-15 20:12:10 -07:00
Andrew Kelley
65cb8a03ee CI: update macos and freebsd tarballs 2022-02-15 19:50:38 -07:00
Andrew Kelley
22f464a8c3 zig cc: handle -l :FILE syntax
This "feature" of gcc/clang means to treat this as a positional
link object, but using the library search directories as a prefix.

We solve this problem in the CLI layer, using a separate map for
the data since it is an uncommon case.

Closes #10851
2022-02-15 17:36:12 -07:00
Jakub Konka
092b019a2f Merge pull request #10899 from ziglang/arm64-macos
aarch64,macos: handle GOT and direct loads in codegen
2022-02-16 00:18:42 +01:00
Jakub Konka
1c975607e1 aarch64: add lowerUnnamedConst glue to codegen 2022-02-15 21:04:40 +01:00
Jakub Konka
5bba041bae aarch64: introduce MCValue.got_load and MCValue.direct_load
This matches the current design in x86_64 backend and significantly
simplifies handling of PIE targets in aarch64 backend.
2022-02-15 21:04:40 +01:00
Jakub Konka
9c82f3ae6f stage2: disable failing aarch64-macos behavior tests 2022-02-15 21:04:36 +01:00
Veikka Tuominen
cf5009f9af Merge pull request #10003 from viriuwu/nt-thread-name
std.Thread.getName/setName: rework windows implementation
2022-02-15 13:23:09 +02:00
Anthony Carrico
078aa5f7b2 Adds Linux support for POSIX file locking with fcntl
On Linux, locking fails with EAGAIN (vs. EACCES on other systems).
This commit also adds FcntlErrors for EDEADLK and ENOLCK.
2022-02-15 13:22:50 +02:00
Jan Philipp Hafer
c6cd919a18 stage1: fix comptime saturation subtraction
- also simplifies code
- adding a few more tests

closes #10870
2022-02-15 10:40:53 +02:00
viri
0bde55e881 std.Thread(windows): use NT internals for name fns 2022-02-15 01:20:54 -06:00
Jakub Konka
be98f30a2d Merge pull request #10893 from joachimschmidt557/stage2-aarch64
stage2 AArch64: get zig test working; enable behavior tests
2022-02-15 07:05:24 +01:00
Andrew Kelley
dc6553d93e CI: update download page and langref for 0.9.1 2022-02-14 20:08:04 -07:00
John Schmidt
807edd2234 LLVM backend: refactor LLVM bitcount ops (#10882)
Use `llvm.getIntrinsic` instead of `llvm.getNamedFunction`
2022-02-14 21:52:12 -05:00
joachimschmidt557
6c195db03a ci: add aarch64-linux behavior tests 2022-02-14 22:36:13 +01:00
joachimschmidt557
22895f5616 stage2 AArch64: Enable behavior testing 2022-02-14 22:33:01 +01:00
joachimschmidt557
98c71cc88a stage2 AArch64: Implement calling function pointers 2022-02-14 22:09:44 +01:00
joachimschmidt557
783e216e7d stage2 AArch64: Fix issue in binOp and add regression test 2022-02-14 22:09:44 +01:00
joachimschmidt557
1c37622659 stage2 AArch64: Implement not for booleans 2022-02-14 22:09:44 +01:00
joachimschmidt557
3a33f31334 stage2 AArch64: implement cond_br for other MCValues 2022-02-14 22:09:44 +01:00
joachimschmidt557
edb2a75982 stage2 AArch64: Implement binOp for add, sub 2022-02-14 22:09:44 +01:00
joachimschmidt557
8bfc4b2f9c stage2 AArch64: extract store out of airStore for recursive calls 2022-02-14 22:09:44 +01:00
joachimschmidt557
f47245865e stage2 AArch64: minor refactors in Mir + Emit 2022-02-14 22:09:43 +01:00
joachimschmidt557
f598d2ae05 stage2 AArch64: implement unwrap_errunion_err and struct_field_ptr 2022-02-14 22:09:43 +01:00
joachimschmidt557
8204ad1937 stage2 AArch64: implement slice_len and slice_elem_val 2022-02-14 22:09:43 +01:00
joachimschmidt557
82f91adbb4 stage2 AArch64: Add madd, msub, mul, mneg instructions 2022-02-14 22:09:43 +01:00
joachimschmidt557
77cf000438 stage2 AArch64: implement loading from register 2022-02-14 22:09:43 +01:00
joachimschmidt557
0d16e908fb stage2 AArch64: implement is_err/is_non_err for simple error unions 2022-02-14 22:09:39 +01:00
ominitay
7b938767bb std.os: throw compile error for argv on Windows
On Windows, `argv` is not populated by start code, and instead left as undefined. This is problematic, and can lead to incorrect programs compiling, but panicking when trying to access `argv`. This change causes these programs to produce a compile error on Windows instead, which is far preferable to a runtime panic.
2022-02-14 22:44:17 +02:00
Andrew Kelley
1e49d1fca8 langref: correct info about type info of declarations 2022-02-14 12:26:55 -07:00
Andrew Kelley
d164865308 add missing source file to CMakeLists.txt 2022-02-14 12:26:15 -07:00
Jakub Konka
27cfbf949a macho: re-enable creating dSYM bundle
* update number of type abbrevs to match Elf linker
* update `DebugSymbols` to write symbol and string tables
  at the end to match the `MachO` linker
* TODO: update segment vm addresses when growing segments in
  the binary
* TODO: store DWARF relocations in linker's interned arena
2022-02-14 19:24:23 +01:00
Al Hoang
04f3d93017 haiku add missing cimport include for compilation 2022-02-14 15:24:53 +02:00
Veikka Tuominen
b85c0d6a47 std: fix tests that were not run due to refAllDecls regression 2022-02-14 15:23:45 +02:00
John Schmidt
ee69a4b45f stage2: improve compiler error message for bad union init 2022-02-14 13:05:00 +02:00
Veikka Tuominen
3eb29f15f5 Merge pull request #10849 from sharpobject/sharpobject_fix_json_comptime_fields
std.json: fix compile error for comptime fields
2022-02-14 12:34:33 +02:00
Veikka Tuominen
90f2a8d9c5 Merge pull request #10486 from ominitay/metadata
std: Implement cross-platform metadata API
2022-02-14 12:33:49 +02:00
erikarvstedt
8ed792b640 std.Progress: fix suffix printing
Previously, `suffix` was copied to `output_buffer` at position
`max_end`, thereby writing into reserved space after `max_end`.
This only worked because `suffix` was not larger than
`bytes_needed_for_esc_codes_at_end` (otherwise there'd be a potential
buffer overrun) and no escape codes at end are actually written.

Since 2d5b2bf1c9, escape codes are no
longer written to the end of the buffer. They are now written
exclusively to the front of the buffer.
This allows removing `bytes_needed_for_esc_codes_at_end` and
simplifying the suffix printing logic.

This also fixes the bug that the ellipse suffix was not printed in
Windows terminals because `end.* > max_end` was never true.
2022-02-14 12:14:50 +02:00
Sebastian Keller
9ca3c897ec test_runner.zig: Do not log test name twice
In #10859 I moved the `test_node.end()` call after everything else has
been logged. Now the `test_fn.name` is printed by `Progress` itself,
making the additional log obsolete.
2022-02-14 12:09:24 +02:00
joachimschmidt557
f5068107cd stage2 regalloc: track Inst instead of ?Inst in register mapping
The information whether a register is allocated to an instruction is
already encoded in the free_registers "bitmap". Duplicating that
information in the registers map is unnecessary and may lead to
performance degradations.
2022-02-13 23:24:26 +01:00
Andrew Kelley
5f50980880 Merge pull request #10863 from m-radomski/fix
std: validate frame-pointer address in stack walking
2022-02-13 16:17:40 -05:00
Cody Tapscott
7edf3d9f2d Cast abi_size to usize 2022-02-13 14:16:40 -07:00
Andrew Kelley
f73044dae5 Merge pull request #10879 from Vexu/err
make some errors point to the end of the previous token
2022-02-13 16:15:00 -05:00
ominitay
11b4cc589c std.fs: Implement cross-platform metadata API
Implements a cross-platform metadata API, aiming to reduce unnecessary Unix-dependence of the `std.fs` api. Presently, all OSes beside Windows are treated as Unix; this is likely the best way to treat things by default, instead of explicitly listing each Unix-like OS.

Platform-specific operations are not provided by `File.Metadata`, and instead are to be accessed from `File.Metadata.inner`.

Adds:

- File.setPermissions() : Sets permission of a file according to a `Permissions` struct (not available on WASI)

- File.Permissions : A cross-platform representation of file permissions
  - Permissions.readOnly() : Returns whether the file is read-only
  - Permissions.setReadOnly() : Sets whether the file is read-only
  - Permissions.unixSet() : Sets permissions for a class (UNIX-only)
  - Permissions.unixGet() : Checks a permission for a class (UNIX-only)
  - Permissions.unixNew() : Returns a new Permissions struct to represent the passed mode (UNIX-only)

- File.Metadata : A cross-platform representation of file metadata
  - Metadata.size() : Returns the size of a file
  - Metadata.permissions() : Returns a `Permissions` struct, representing permissions on the file
  - Metadata.kind() : Returns the `Kind` of the file
  - Metadata.accessed() : Returns the time the file was last accessed
  - Metadata.modified() : Returns the time the file was last modified
  - Metadata.created() : Returns the time the file was created (this is an optional, as the underlying filesystem, or OS may not support this)

Methods of `File.Metadata` are also available for the below, so I won't repeat myself
The below may be used for platform-specific functionality

- File.MetadataUnix : The internal implementation of `File.Metadata` on Unices

- File.MetadataLinux : The internal implementation of `File.Metadata` on Linux

- File.MetadataWindows : The implementation of `File.Metadata` on Windows
2022-02-13 20:56:06 +00:00
ominitay
b2610649fc std.c.*: add birthtime function to Stat
Adds a birthtime function to the `Stat` structs of Unices which support this. This is done to match the `atime`, `mtime`, and `ctime` functions.
2022-02-13 20:40:45 +00:00
ominitay
d978fdaa67 std.c.Wasi.Stat: use timespec 2022-02-13 20:40:44 +00:00
ominitay
3dd3c5063b std.c.haiku: move Stat.crtime to Stat.birthtime 2022-02-13 20:40:44 +00:00
ominitay
f23005eba7 std.c.darwin.Stat: use timespec
Uses timespec for times in `Stat` instead of two `isize` fields per time. This matches the <sys/stat.h> header file.
2022-02-13 20:40:44 +00:00
Cody Tapscott
45aed7171c Skip 8/16-bit @bitCast test for wasm 2022-02-13 13:28:08 -07:00
Cody Tapscott
c586e3ba1b Add additional tests for @bitCast 2022-02-13 13:28:08 -07:00
Cody Tapscott
7b72fc6bbc Add abi_size parameter to read/writeTwosComplement
Big-int functions were updated to respect the provided abi_size, rather
than inferring a potentially incorrect abi_size implicitly.

In combination with the convention that any required padding bits are
added on the MSB end, this means that exotic integers can potentially
have a well-defined memory layout.
2022-02-13 13:26:59 -07:00
Tw
2a73700c0f Fix preadv/pwritev bug on 64bit platform
Signed-off-by: Tw <wei.tan@intel.com>
2022-02-13 18:01:07 +00:00
Koakuma
55fa349ad9 Import SPARCv9 libunwind
Import LLVM's D32450/D116857 patch to enable unwinding support on
SPARCv9 systems.
2022-02-13 17:16:22 +02:00
Mateusz Radomski
b5f8fb85e6 Implement f128 @rem 2022-02-13 15:37:38 +02:00
Sebsatian Keller
f22443bb05 Fixed progress indicator for zig test (#10859)
Previously the progress displayed the first item as [0/x]. This was
misleading when x is the number of items. The first item should be
displayed as [1/x]
2022-02-13 15:19:33 +02:00
Cody Tapscott
f516e2c5b1 Simplify implementation of floorPowerOfTwo in std.math 2022-02-13 14:47:58 +02:00
Jacob G-W
3bbe6a28e0 stage2: add decltests 2022-02-13 14:42:20 +02:00
Veikka Tuominen
8937f18a6f std: force refAllDecls to actually resolve all decls
Only about half of the tests in std were actually being run (918 vs 2144).
2022-02-13 14:36:55 +02:00
sharpobject
17822e4a05 std.json: fix compile error for comptime fields
This is covered by an existing test which was already failing.
2022-02-13 14:33:17 +02:00
Veikka Tuominen
0699b29ce0 parser: give better errors for misplaced .{ 2022-02-13 14:21:53 +02:00
Veikka Tuominen
8a432436ae update compile error tests 2022-02-13 13:48:20 +02:00
Veikka Tuominen
6456af5a45 parser: make missing comma errors point to the end of the previous token 2022-02-13 13:46:58 +02:00
Veikka Tuominen
ddd6de86f7 parser: make missing semicolon error point to the end of the previous token 2022-02-13 13:45:35 +02:00
Andrew Kelley
0b7347fd18 move more behavior tests to the "passing" section 2022-02-12 21:35:29 -07:00
Andrew Kelley
c349191b75 organize behavior tests
moving towards disabling failing tests on an individual basis
2022-02-12 21:13:07 -07:00
Andrew Kelley
a005ac9d3c stage2: implement @popCount for SIMD vectors 2022-02-12 20:44:30 -07:00
Jakub Konka
16ec848d2a macho: put linker symlink for cache invalidation in zig-cache
Due to differences in where the output gets emitted in stage1 and stage2,
we were putting the symlink next to the binary rather than in `zig-cache`
directory when building with stage2.
2022-02-12 21:27:23 +01:00
Jakub Konka
d542a588c6 Skip @sqrt f80 test on freebsd 2022-02-12 21:24:18 +01:00
Jakub Konka
9643f32c99 Merge pull request #10861 from ziglang/f80
make f80 less hacky; lower as u80 on non-x86
2022-02-12 13:25:44 +01:00
Andrew Kelley
16076964d6 disable NaN f80 behavior tests
Let's get all these other bug fixes in and figure out f80 NaN later.
Looks like it's not working at comptime in master branch anyway.
2022-02-12 11:18:23 +01:00
Andrew Kelley
774f9bdb79 LLVM backend: disable failing aarch64 behavior test 2022-02-12 11:18:23 +01:00
Andrew Kelley
91508e10ab LLVM backend: handle unnamed structs when lowering array values
LLVM doesn't support lowering union values, so we have to use unnamed
structs to do it, which means any type that contains a union as an
element, even if it is nested in another type, has to have a mechanism
to detect when it can't be lowered normally and has to resort itself to
an unnamed struct.

This includes arrays.
2022-02-12 11:18:23 +01:00
Andrew Kelley
38236533f1 LLVM backend: avoid creating invalid LLVM types
Fixes assertions from creating i0 types which are not allowed in LLVM.
2022-02-12 11:18:23 +01:00
Andrew Kelley
ba31a9469f Sema: int casting to u0 returns const value
Also shift left with u0 rhs returns lhs even when lhs is runtime known.
2022-02-12 11:18:23 +01:00
Andrew Kelley
b92e1ab8cc stage1: override f80 alignment for i386-windows
Comment reproduced here:

Note the following u64 alignments:
  x86-linux:   4
  x86-windows: 8
LLVM makes x86_fp80 have the following alignment and sizes regardless
of operating system:
  x86_64: size=16, align=16
  x86:    size=12, align=4
However in Zig we override x86-windows to have size=16, align=16
in order for the property to hold that u80 and f80 have the same ABI size.

Fixes "error: destination type 'f80' has size 12 but source type 'u80'
has size 16" when trying to bitcast between f80 and u80 on i386-windows.
2022-02-12 11:18:23 +01:00
Andrew Kelley
d72f832b1e LLVM backend: call constPtrToInt instead of constBitCast
when appropriate. Avoids tripping an LLVM assertion.
2022-02-12 11:18:23 +01:00
Andrew Kelley
335c680cde LLVM backend: fix union with only 1 tag tripping llvm assertion 2022-02-12 11:18:23 +01:00
Andrew Kelley
1a8987fe7c CI: additionally test stage2 LLVM backend targeting aarch64-linux 2022-02-12 11:18:23 +01:00
Andrew Kelley
a024aff932 make f80 less hacky; lower as u80 on non-x86
Get rid of `std.math.F80Repr`. Instead of trying to match the memory
layout of f80, we treat it as a value, same as the other floating point
types. The functions `make_f80` and `break_f80` are introduced to
compose an f80 value out of its parts, and the inverse operation.

stage2 LLVM backend: fix pointer to zero length array tripping LLVM
assertion. It now checks for when the element type is a zero-bit type
and lowers such thing the same way that pointers to other zero-bit types
are lowered.

Both stage1 and stage2 LLVM backends are adjusted so that f80 is lowered
as x86_fp80 on x86_64 and i386 architectures, and identical to a u80 on
others. LLVM constants are lowered in a less hacky way now that #10860
is fixed, by using the expression `(exp << 64) | fraction` using llvm
constants.

Sema is improved to handle c_longdouble by recursively handling it
correctly for whatever the float bit width is. In both stage1 and
stage2.
2022-02-12 11:18:23 +01:00
Andrew Kelley
1c23321d03 stage1: fix softfloat not getting correct endianness
needed to include platform.h in more places so that LITTLEENDIAN will be
defined appropriately.

closes #10860
2022-02-12 11:18:23 +01:00
Andrew Kelley
166db1a3ed stage1: fix f80 size and alignment on x86 and arm
* F80Repr extern struct needs no explicit padding; let's match the
   target padding.
 * stage2: fix lowering of f80 constants.
 * stage1: decide ABI size and alignment of f80 based on alignment of
   u64. x86 has alignof u64 equal to 4 but arm has it as 8.
 * stage2: fix Value.floatReadFromMemory to use F80Repr
2022-02-12 11:18:23 +01:00
Andrew Kelley
f293fbbeaf stage2: LLVM backend: adjust replaceAllUsesWith usage
replaceAllUsesWith requires the type to be unchanged. So we bitcast
the new global to the old type and use that as the thing to replace
old uses.

Fixes an LLVM assertion found while troubleshooting #10837.
2022-02-12 11:18:23 +01:00
Jakub Konka
beb275b371 Revert "CI: upgrade both host and target tarballs to llvm 13.0.1 x86_64-macos"
This reverts commit 1072d8a065.
2022-02-12 11:17:41 +01:00
Jakub Konka
1072d8a065 CI: upgrade both host and target tarballs to llvm 13.0.1 x86_64-macos 2022-02-12 11:01:10 +01:00
Andrew Kelley
3fdbc3bba8 CI: upgrade x86_64-macos tarball to llvm 13.0.1 2022-02-12 01:09:13 -07:00
joachimschmidt557
2262640e8b stage2 ARM: lower const slices
Follow-up to e1a535360f for ARM

This also fixes some stack offset calculation bugs
2022-02-12 00:01:05 +01:00
Andrew Kelley
a5a7f0ff00 CI: upgrade x86_64-macos tarball to llvm 13.0.1 2022-02-11 15:57:44 -07:00
m
65299c37d1 validate in Windows using VirtualQuery 2022-02-11 22:15:46 +01:00
Cody Tapscott
eeb043f583 Fix big-endian handling in stage1 bigint_write_twos_complement 2022-02-11 08:49:24 -07:00
Cody Tapscott
70d7f87be0 Fix up sign handling and add arbitrary-length integer support to @bitCast() 2022-02-11 08:49:19 -07:00
m
bd8d6a8342 std: validate frame-pointer address in stack walking 2022-02-11 15:28:36 +01:00
Jakub Konka
e1a535360f Merge pull request #10862 from ziglang/elf-lower-slices
stage2: native backends: lower const slices
2022-02-11 15:02:17 +01:00
Jakub Konka
cad3e3e63a x64: enable more behavior tests 2022-02-11 12:49:06 +01:00
Jakub Konka
066758b1a2 macho: correctly lower slices incl reloc and rebase tracking
Match changes required to `Elf` linker, which enable lowering
of const slices on `MachO` targets.

Expand `Mir` instructions requiring the knowledge of the containing
atom - pass the symbol index into the linker's table from codegen
via mir to emitter, to then utilise it in the linker.
2022-02-11 12:16:32 +01:00
Jakub Konka
b9b1ab0240 elf: store pointer relocations indexed by containing atom
In `getDeclVAddr`, it may happen that the target `Decl` has not
been allocated space in virtual memory. In this case, we store a
relocation in the linker-global table which we will iterate over
when flushing the module, and fill in any missing address in the
final binary. Note that for optimisation, if the address was resolved
at the time of a call to `getDeclVAddr`, we skip relocating this
atom.

This commit also adds the glue code for lowering const slices in
the ARM backend.
2022-02-11 10:52:13 +01:00
Jakub Konka
08e2f5d083 codegen: handle lowering of const slice pointers 2022-02-11 10:52:13 +01:00
Andrew Kelley
f0400ad93e Merge pull request #10857 from Luukdegram/wasm-tests
stage2: Wasm - implement field_ptr
2022-02-10 19:22:23 -05:00
Luuk de Gram
9c6d416bec Activate passing behavior tests
This moves the single bugs behavior tests to the outer branch and disables the test cases
for all non-passing backends.
For the larger files, we move it up a single branch and disable it for the c backend.
All test cases that do pass for the c backend however, are enabled.
2022-02-10 21:40:06 +01:00
Luuk de Gram
0e2fcab334 wasm: Implement 'field_ptr' constants
This implements the `field_ptr` value for pointers. As the value only provides us with the index,
we must calculate the offset from the container type using said index. (i.e. the offset from a struct field at index 2).

Besides this, small miscellaneous fixes/updates were done to get remaining behavior tests passing:
 - We start the function table index at 1, so unresolved function pointers don't can be null-checked properly.
 - Implement genTypedValue for floats up to f64.
 - Fix zero-sized arguments by only creating `args` for non-zero-sized types.
 - lowerConstant now works for all decl_ref's.
 - lowerConstant properly lowers optional pointers, so `null` pointers are lowered to `0`.
2022-02-10 21:40:06 +01:00
Jakub Konka
e139c41fd8 stage2: handle truncate to signed non-pow-two integers 2022-02-10 15:05:12 +01:00
Andrew Kelley
c10fdde5a6 stage2: LLVM backend: make unnamed struct globals
LLVM union globals have to be lowered as unnamed structs if the
non-most-aligned field is the active tag. In this case it bubbles up so
that structs containing unions have the same restriction.

This fix needs to be applied to optionals and other callsites of
createNamedStruct.

The bug fixed in this commit was revealed in searching for
the cause of #10837.
2022-02-10 00:27:02 -07:00
Jakub Konka
57357c43e3 elf: pad out file to the required size when init data
We need to pad out the file to the required maximum size equal the
final section's offset plus the section's size. We only need to
this when populating initial metadata and only when section header
was updated.
2022-02-10 08:12:02 +01:00
Andrew Kelley
65c812842d freestanding libc: fix missing functions
In the previous commit I got mixed up and cut-pasted instead of
copy-pasting. In this commit I made c_stage1.zig additionally included
for stage1 and everything else included for both. So moving forward we
move stuff over from c_stage1.zig to c.zig instead of copying.
2022-02-09 19:13:53 -07:00
Andrew Kelley
f2f1c63daf stage2: add log and logf to freestanding libc 2022-02-09 18:52:32 -07:00
Sebsatian Keller
f5471299d8 stage 1: improve error message if error union is cast to payload (#10770)
Also: Added special error message for for `?T` to `T` casting
2022-02-09 20:35:53 -05:00
Andrew Kelley
1e5a494603 Sema: implement comptime ptr store to optional payload
and error union payload
2022-02-09 18:29:51 -07:00
John Schmidt
7f0cf395aa stage2: implement all builtin floatops for f{16,32,64}
- Merge `floatop.zig` and `floatop_stage1.zig` since most tests now pass
  on stage2.
- Add more behavior tests for a bunch of functions.
2022-02-09 20:29:41 -05:00
Andrew Kelley
44b5fdf326 Revert "ci: azure: split build-and-test step"
This reverts commit 846eb70182.

This did not properly translate the upload portion of the CI script to
powershell which broke our CI pipeline.
2022-02-09 18:26:56 -07:00
Andrew Kelley
274b9d5c1d ci: work around azure networking issue 2022-02-09 16:42:15 -07:00
Andrew Kelley
2836cd5fbd CLI: ignore -lgcc_s when it is redundant with compiler-rt
For some projects, they can't help themselves, -lgcc_s ends up on the
compiler command line even though it does not belong there. In Zig we
know what -lgcc_s does. It's an alternative to compiler-rt. With this
commit we emit a warning telling that it is unnecessary to put such
thing on the command line, and happily ignore it, since we will fulfill
the dependency with compiler-rt.
2022-02-09 11:38:33 -07:00
Andrew Kelley
db56d74a3b Merge pull request #10834 from ziglang/fix-x86-i128-c-abi
stage1: fix x86 i128 C ABI for extern structs
2022-02-09 13:23:20 -05:00
Andrew Kelley
92cb17a331 CI: windows: update env var names 2022-02-09 10:41:12 -07:00
Jakub Konka
2d39142133 Merge pull request #10843 from ziglang/fix-1914
stage2: handle decl ref to void types
2022-02-09 18:12:37 +01:00
Jakub Konka
ec3e638b97 elf: fix unaligned file offset of moved phdr containing GOT section 2022-02-09 13:22:50 +01:00
Jakub Konka
e588e3873c stage2: export trunc, truncf and truncl 2022-02-09 10:28:48 +01:00
Jakub Konka
b28e9e42e0 stage2: resolve struct type when lowering struct_field_* 2022-02-09 10:28:48 +01:00
Jakub Konka
e5ce87f1b1 stage2: handle decl ref to void types
Fixes behavior test 1914
2022-02-09 10:28:48 +01:00
Jakub Konka
4d1e5ef730 Merge pull request #10846 from ziglang/x64-macho-bringup
stage2: handle direct and got load for stack args on x86_64-macos
2022-02-09 08:17:29 +01:00
Andrew Kelley
97019bc56d Sema: handle inferred error set tail call
When Sema sees a store_node instruction, it now checks for
the possibility of this pattern:
  %a = ret_ptr
  %b = store(%a, %c)
Where %c is an error union. In such case we need to add to the
current function's inferred error set, if any.

Coercion from error union to error union will be handled ideally if the
operand is comptime known. In such case it does the appropriate
unwrapping, then wraps again.

In the future, coercion from error union to error union should do the
same thing for a runtime value; emitting a runtime branch to check if
the value is an error or not.

`Value.arrayLen` for structs returns the number of fields. This is so
that Liveness can use it for the `vector_init` instruction (soon to be
renamed to `aggregate_init`).
2022-02-09 00:10:53 -07:00
Andrew Kelley
f4fa32a632 Sema: fix @typeInfo for pointers returning 0 alignment 2022-02-08 23:02:13 -07:00
Andrew Kelley
1678825c14 Sema: fix @ptrCast from slices
Also, fix allocations in comptime contexts with alignments.
2022-02-08 22:51:46 -07:00
Andrew Kelley
59418d1bf6 Sema: fix Value.intFitsInType for comptime int 2022-02-08 22:09:41 -07:00
billzez
470c8ca48c update RwLock to use static initialization (#10838) 2022-02-08 23:35:48 -05:00
Andrew Kelley
77a6031edb C ABI: these tests are not passing yet on Windows
I was too greedy
2022-02-08 21:15:00 -07:00
Andrew Kelley
08808701d2 C ABI tests: give a clue in addition to "test failure" 2022-02-08 21:12:50 -07:00
Andrew Kelley
a35eb9fe8a c_abi tests: allow passing standard target options 2022-02-08 21:12:32 -07:00
Andrew Kelley
a67893b0e1 stage1: fix x86_64-windows C ABI classification logic
16 bytes vectors are special cased because compiler-rt currently relies
on this.
2022-02-08 21:11:53 -07:00
Andrew Kelley
e06ac9537e stage2: fix x86_64-windows C ABI
It didn't return integer status for pointers and also it incorrectly
returned memory for optionals sometimes.
2022-02-08 21:10:29 -07:00
Andrew Kelley
61ed4fe07a stage1: fix x86 i128 C ABI for extern structs
closes #10445
2022-02-08 20:10:55 -07:00
Andrew Kelley
7c1061784b stage2: fix inferred comptime constant locals
`const` declarations inside comptime blocks were not getting properly
evaluated at compile-time. To accomplish this there is a new ZIR
instruction, `alloc_inferred_comptime`. Actually we already had one
named that, but it got renamed to `alloc_inferred_comptime_mut` to match
the naming convention with the other similar instructions.
2022-02-08 20:03:17 -07:00
Andrew Kelley
210ee1067b update more API usage of std.Progress
fixes regression introduced in 5a00e24963
2022-02-08 17:49:40 -07:00
Hadrien Dorio
846eb70182 ci: azure: split build-and-test step
replace the .bat script by a pwsh script
2022-02-08 19:47:46 -05:00
Andrew Kelley
5a00e24963 std.Progress: make the API infallible
by handling `error.TimerUnsupported`. In this case, only explicit calls
to refresh() will cause the progress line to be printed.
2022-02-08 17:26:55 -07:00
Andrew Kelley
fd6c351263 cmake: fix -DZIG_SINGLE_THREADED option
It was still passing --single-threaded instead of -fsingle-threaded.
2022-02-08 17:22:11 -07:00
Jakub Konka
c689df1215 stage2: disable some tests on x86_64-macos 2022-02-08 23:59:10 +01:00
Jakub Konka
f1d2141849 stage2: handle direct and got load for stack args 2022-02-08 23:48:42 +01:00
Jakub Konka
e42b5e76ba stage2: handle void type in Elf DWARF gen
Enable more behavior tests on both x64 and arm
2022-02-08 23:43:25 +01:00
Jakub Konka
c256603eae Merge pull request #10839 from joachimschmidt557/stage2-arm
stage2 ARM: genTypedValue for all integer types
2022-02-08 21:04:38 +01:00
joachimschmidt557
8fe9d2f986 stage2 ARM: airStructFieldVal for more MCValues 2022-02-08 21:02:56 +01:00
joachimschmidt557
6b0c950cb8 stage2 ARM: support all integer types in genTypedValue 2022-02-08 21:02:50 +01:00
Luuk de Gram
37fea3e3dd wasm: Store stack-offset as WValue
Rather than using runtime to perform pointer arithmetic to set the stack offset as
a pointer into a local, we now store the offset as a WValue from the bottom of the stack.
This has the benefit of less instructions, few locals, and less performance impact when
we allocate a value on the virtual stack.
2022-02-08 21:01:01 +01:00
Jakub Konka
9981b3fd2f stage2: tiny improvements all over the place
* pass more x64 behavior tests
* return with a TODO error when lowering a decl with no runtime bits
* insert some debug logs for tracing recursive descent down the
type-value tree when lowering types
* print `Decl`'s name when print debugging `decl_ref` value
2022-02-08 21:00:07 +01:00
Luuk de Gram
f50203c836 wasm: update test runner
This updates the test runner for stage2 to emit to stdout with the passed, skipped and failed tests
similar to the LLVM backend.

Another change to this is the start function, as it's now more in line with stage1's.
The stage2 test infrastructure for wasm/wasi has been updated to reflect this as well.
2022-02-08 10:03:29 +01:00
Jakub Konka
2302ded951 Merge pull request #10832 from ziglang/x64-more-structs
stage2,x64: pass more tests with structs
2022-02-08 10:02:06 +01:00
Jan Philipp Hafer
fc59a04061 compiler_rt: add subo
- approach by Hacker's Delight with wrapping subtraction
- performance expected to be similar to addo
- tests with all relevant combinations of min,max with -1,0,+1 and all
  combinations of sequences +-1,2,4..,max
2022-02-08 02:14:29 -05:00
Andrew Kelley
a15d2d582b stage2: fix crash_report segfault compile error
Regressed in 05cf69209e.
2022-02-07 17:11:26 -08:00
Andrew Kelley
9bbfbacae0 Merge pull request #10801 from schmee/stage2-sqrt
stage2: implement @sqrt for f{16,32,64}
2022-02-07 18:52:57 -05:00
Andrew Kelley
a028488384 Sema: clean up zirUnaryMath
* pass air_tag instead of zir_tag
 * also pass eval function so that the branch only happens once and the
   body of zirUnaryMath is simplified
 * Value.sqrt: update to handle f80 and f128 in the normalized way that
   includes handling c_longdouble.

Semi-related change: fix incorrect sqrt builtin name for f80 in stage1.
2022-02-07 16:52:19 -07:00
John Schmidt
722d4a11bb stage2: implement @sqrt for f{16,32,64}
Support for f128, comptime_float, and c_longdouble require improvements
to compiler_rt and will implemented in a later PR. Some of the code in
this commit could be made more generic, for instance `llvm.airSqrt`
could probably be `llvm.airUnaryMath`, but let's cross that
bridge when we get to it.
2022-02-07 16:52:19 -07:00
Andrew Kelley
dd49ed1c64 Merge pull request #10813 from marler8997/windowsChildHang
child_process: collectOutputWindows handle broken_pipe from ReadFile
2022-02-07 17:33:26 -05:00
John Schmidt
05cf69209e debug: implement segfault handler for macOS aarch64
Tested on a M1 MacBook Pro, macOS Monterey 12.2.
2022-02-07 16:34:05 -05:00
Arnavion
2a415a033c std.bit_set: add setRangeValue(Range, bool)
For large ranges, this is faster than having the caller call setValue() for
each index in the range. Masks wholly covered by the range can be set to
the new mask value in one go, and the two masks at either end that are
partially covered can each set the covered range of bits in one go.
2022-02-07 14:58:07 -05:00
Jakub Konka
785bccd4ce stage2: pass more struct tests 2022-02-07 20:48:31 +01:00
Andrew Kelley
8a94971980 std: fix i386-openbsd failing to build from source
closes #9705
2022-02-07 12:20:25 -07:00
Jakub Konka
becbf446d3 stage2,x64: impl lowering of shift ops in Emit 2022-02-07 20:13:29 +01:00
Jakub Konka
7a9b9df80e stage2,x64: impl masking reg for struct_field_val 2022-02-07 20:13:29 +01:00
Jakub Konka
ac36fe7114 stage2,x64: fix registerAlias helper function 2022-02-07 20:13:29 +01:00
Jakub Konka
bbd7969c87 stage2,x64: implement genSetStack for memory operand 2022-02-07 20:13:29 +01:00
Jakub Konka
0a7801236c stage2,arm: add lowering of unnamed consts
* implement `struct_field_ptr` when `MCValue == .stack_argument_offset`
* enable simple `struct` test for ARM
2022-02-07 20:10:01 +01:00
Andrew Kelley
9acf06d28a Merge pull request #10803 from ziglang/decl-has-lib-name
stage2: store externs lib name as part of decl
2022-02-07 13:30:59 -05:00
matu3ba
3db130ff3d compiler_rt: add addo (#10824)
- approach by Hacker's Delight with wrapping addition
- ca. 1.10x perf over the standard approach on my laptop
- tests with all combinations of min,max with -1,0,+1 and combinations of
  sequences +-1,2,4..,max
2022-02-07 13:27:21 -05:00
Evan Haas
e382e7be2b std: Allow mem.zeroes to work at comptime with extern union
Fixes #10797
2022-02-07 11:34:20 +02:00
boofexxx
435beb4e1d std: fix doc comment typo in os.zig 2022-02-07 09:55:47 +01:00
Jonathan Marler
2cc33367eb fix bug when ReadFile returns synchronously in collectOutputWindows 2022-02-07 01:49:15 -07:00
Jakub Konka
5944e89016 stage2: lower unnamed constants in Elf and MachO
* link: add a virtual function `lowerUnnamedConsts`, similar to
  `updateFunc` or `updateDecl` which needs to be implemented by the
  linker backend in order to be used with the `CodeGen` code
* elf: implement `lowerUnnamedConsts` specialization where we
  lower unnamed constants to `.rodata` section. We keep track of the
  atoms encompassing the lowered unnamed consts in a global table
  indexed by parent `Decl`. When the `Decl` is updated or destroyed,
  we clear the unnamed consts referenced within the `Decl`.
* macho: implement `lowerUnnamedConsts` specialization where we
  lower unnamed constants to `__TEXT,__const` section. We keep track of the
  atoms encompassing the lowered unnamed consts in a global table
  indexed by parent `Decl`. When the `Decl` is updated or destroyed,
  we clear the unnamed consts referenced within the `Decl`.
* x64: change `MCValue.linker_sym_index` into two `MCValue`s: `.got_load` and
  `.direct_load`. The former signifies to the emitter that it should
  emit a GOT load relocation, while the latter that it should emit
  a direct load (`SIGNED`) relocation.
* x64: lower `struct` instantiations
2022-02-07 08:39:00 +01:00
Andrew Kelley
21135387fb Merge pull request #10782 from topolarity/gate-child-processes
Avoid depending on child process execution when not supported by host OS
2022-02-07 00:31:17 -05:00
Andrew Kelley
33fa296019 stage2: pass proper can_exit_early value to LLD
and adjust the warning message for invoking LLD twice in the same
process.
2022-02-06 22:29:40 -07:00
Cody Tapscott
c1cf158729 Replace argvCmd with std.mem.join 2022-02-06 22:21:46 -07:00
Cody Tapscott
5065830aa0 Avoid depending on child process execution when not supported by host OS
In accordance with the requesting issue (#10750):
- `zig test` skips any tests that it cannot spawn, returning success
- `zig run` and `zig build` exit with failure, reporting the command the cannot be run
- `zig clang`, `zig ar`, etc. already punt directly to the appropriate clang/lld main(), even before this change
- Native `libc` Detection is not supported

Additionally, `exec()` and related Builder functions error at run-time, reporting the command that cannot be run
2022-02-06 22:21:46 -07:00
Andrew Kelley
069dd01ce4 Merge pull request #10740 from ziglang/stage2-float-arithmetic
stage2: add more float arithmetic and f80 support
2022-02-06 22:41:43 -05:00
Andrew Kelley
eb82fdf96c Sema: panic instead of lowering to unavailable compiler-rt functions
Once the relevant compiler_rt functions are implemented, these panics
can be removed.
2022-02-06 20:38:57 -07:00
Andrew Kelley
65b6faa048 Sema: avoid @intToFloat for f80 which breaks on non-x86 targets
Currently Zig lowers `@intToFloat` for f80 incorrectly on non-x86
targets:

```
broken LLVM module found:
UIToFP result must be FP or FP vector
  %62 = uitofp i64 %61 to i128
SIToFP result must be FP or FP vector
  %66 = sitofp i64 %65 to i128
```

This happens because on such targets, we use i128 instead of x86_fp80 in
order to avoid "LLVM ERROR: Cannot select". `@intToFloat` must be
lowered differently to account for this difference as well.
2022-02-06 20:23:40 -07:00
Andrew Kelley
3bcce5f6d1 Sema: implement writing structs to memory at comptime 2022-02-06 20:07:43 -07:00
Andrew Kelley
d4805472c3 compiler_rt: addXf3: add coercion to @clz
We're going to remove the first parameter from this function in the
future. Stage2 already ignores the first parameter. So we put an `@as`
in here to make it work for both.
2022-02-06 20:06:00 -07:00
Andrew Kelley
495fd4ee3e AstGen: refactor redundant expressions
This is a non-functional change.
2022-02-06 19:45:49 -07:00
Marc Tiehuis
53e6c719ef std/math: optimize division with divisors less than a half-limb
This adds a new path which avoids using compiler_rt generated div
udivmod instructions in the case that a divisor is less than half the
max usize value. Two half-limb divisions are performed instead which
ensures that non-emulated division instructions are actually used. This
does not improve the udivmod code which should still be reviewed
independently of this issue.

Notably this improves the performance of the toString implementation of
non-power-of-two bases considerably.

Division performance is improved ~1000% based on some coarse testing.

The following test code is used to provide a rough comparison between
the old vs. new method.

```
const std = @import("std");
const Managed = std.math.big.int.Managed;

const allocator = std.heap.c_allocator;

fn fib(a: *Managed, n: usize) !void {
    var b = try Managed.initSet(allocator, 1);
    defer b.deinit();
    var c = try Managed.init(allocator);
    defer c.deinit();

    var i: usize = 0;
    while (i < n) : (i += 1) {
        try c.add(a.toConst(), b.toConst());

        a.swap(&b);
        b.swap(&c);
    }
}

pub fn main() !void {
    var a = try Managed.initSet(allocator, 0);
    defer a.deinit();

    try fib(&a, 1_000_000);

    // Note: Next two lines (and printed digit count) omitted on no-print version.
    const as = try a.toString(allocator, 10, .lower);
    defer allocator.free(as);

    std.debug.print("fib: digit count: {}, limb count: {}\n", .{ as.len, a.limbs.len });
}
```

```
==> time.no-print <==
limb count: 10849

________________________________________________________
Executed in   10.60 secs    fish           external
   usr time   10.44 secs    0.00 millis   10.44 secs
   sys time    0.02 secs    1.12 millis    0.02 secs

==> time.old <==
fib: digit count: 208988, limb count: 10849

________________________________________________________
Executed in   22.78 secs    fish           external
   usr time   22.43 secs    1.01 millis   22.43 secs
   sys time    0.03 secs    0.13 millis    0.03 secs

==> time.optimized <==
fib: digit count: 208988, limb count: 10849

________________________________________________________
Executed in   11.59 secs    fish           external
   usr time   11.56 secs    1.03 millis   11.56 secs
   sys time    0.03 secs    0.12 millis    0.03 secs
```

Perf data for non-optimized and optimized, verifying no udivmod is
generated by the new code.

```
$ perf report -i perf.data.old --stdio
- Total Lost Samples: 0
-
- Samples: 90K of event 'cycles:u'
- Event count (approx.): 71603695208
-
- Overhead  Command  Shared Object     Symbol
- ........  .......  ................  ...........................................
-
    52.97%  t        t                 [.] compiler_rt.udivmod.udivmod
    45.97%  t        t                 [.] std.math.big.int.Mutable.addCarry
     0.83%  t        t                 [.] main
     0.08%  t        libc-2.33.so      [.] __memmove_avx_unaligned_erms
     0.08%  t        t                 [.] __udivti3
     0.03%  t        [unknown]         [k] 0xffffffff9a0010a7
     0.02%  t        t                 [.] std.math.big.int.Managed.ensureCapacity
     0.01%  t        libc-2.33.so      [.] _int_malloc
     0.00%  t        libc-2.33.so      [.] __malloc_usable_size
     0.00%  t        libc-2.33.so      [.] _int_free
     0.00%  t        t                 [.] 0x0000000000004a80
     0.00%  t        t                 [.] std.heap.CAllocator.resize
     0.00%  t        libc-2.33.so      [.] _mid_memalign
     0.00%  t        libc-2.33.so      [.] sysmalloc
     0.00%  t        libc-2.33.so      [.] __posix_memalign
     0.00%  t        t                 [.] std.heap.CAllocator.alloc
     0.00%  t        ld-2.33.so        [.] do_lookup_x

$ perf report -i perf.data.optimized --stdio
- Total Lost Samples: 0
-
- Samples: 46K of event 'cycles:u'
- Event count (approx.): 36790112336
-
- Overhead  Command  Shared Object     Symbol
- ........  .......  ................  ...........................................
-
    79.98%  t        t                 [.] std.math.big.int.Mutable.addCarry
    15.14%  t        t                 [.] main
     4.58%  t        t                 [.] std.math.big.int.Managed.ensureCapacity
     0.21%  t        libc-2.33.so      [.] __memmove_avx_unaligned_erms
     0.05%  t        [unknown]         [k] 0xffffffff9a0010a7
     0.02%  t        libc-2.33.so      [.] _int_malloc
     0.01%  t        t                 [.] std.heap.CAllocator.alloc
     0.01%  t        libc-2.33.so      [.] __malloc_usable_size
     0.00%  t        libc-2.33.so      [.] systrim.constprop.0
     0.00%  t        libc-2.33.so      [.] _mid_memalign
     0.00%  t        t                 [.] 0x0000000000000c7d
     0.00%  t        libc-2.33.so      [.] malloc
     0.00%  t        ld-2.33.so        [.] check_match
```

Closes #10630.
2022-02-06 21:39:34 -05:00
Luuk de Gram
545aa790a4 Sema: Fix memory leak 2022-02-06 21:37:45 -05:00
Andrew Kelley
287ff4ab58 stage2: add more float arithmetic and f80 support
AstGen: Fixed bug where f80 types in source were triggering illegal
behavior.

Value: handle f80 in floating point arithmetic functions.

Value: implement floatRem and floatMod

This commit introduces dependencies on compiler-rt that are not
implemented. Those are a prerequisite to merging this branch.
2022-02-06 19:27:54 -07:00
John Schmidt
fd1284ebd0 stage2: apply type coercion in if expressions
When setting the break value in an if expression we must explicitly
check if a result location type coercion that needs to happen. This was
already done for switch expression, so let's just imitate that check
and fix for if expressions. To make this possible, we now also propagate
`rl_ty_inst` to sub scopes.
2022-02-06 21:26:26 -05:00
Jonathan Marler
4fddb591e2 rework to allow ReadFile to complete synchronously 2022-02-06 18:05:21 -07:00
Jonathan Marler
8f830207c4 fix bug I think I found while manually reviewing 2022-02-06 18:05:21 -07:00
Jonathan Marler
53d8a25dab child_process: collectOutputWindows handle broken_pipe from ReadFile
This was found on a user's machine when calling "git" as a child process from msys.  Instead of getting BROKEN_PIPE on GetOverlappedREsult, it would occur on ReadFile which would then cause the function to hang because the async operation was never started.
2022-02-06 18:05:20 -07:00
joachimschmidt557
adc9a282d8 stage2 ARM: fix load and store for abi_size < 4
Previously, in these cases, we would emit the ldr instruction even
though ldrb oder ldrh are the correct instructions.
2022-02-06 23:29:36 +01:00
Jakub Konka
db9500a314 stage2: handle extern lib name annotation for vars
For example, a situation like this is allowed

```zig
extern "c" var stderrp: c_int;
```

In this case, `Module.Var` wrapping `stderrp` will have `lib_name`
populated with the library name where this import is expected.
2022-02-06 09:24:13 +01:00
Jakub Konka
556f0ce5bf stage2: add new Decl subtype, ExternFn
`ExternFn` will contain a maybe-lib-name if it was defined with
the `extern` keyword like so

```zig
extern "c" fn write(usize, usize, usize) usize;
```

`lib_name` will live as long as `ExternFn` decl does.
2022-02-06 08:42:14 +01:00
joachimschmidt557
4468abfc42 stage2 ARM: enable a handful of passing behavior tests 2022-02-06 02:23:31 -05:00
Johannes Löthberg
6f87f49f3d CLI: remove remainders of --verbose-ast and --verbose-tokenize
These options were removed in 5e63baae8 (CLI: remove --verbose-ast and
--verbose-tokenize, 2021-06-09) but some remainders were left in.

Signed-off-by: Johannes Löthberg <johannes@kyriasis.com>
2022-02-06 01:57:04 -05:00
Andrew Kelley
8dcb1eba60 Merge pull request #10738 from Vexu/f80
Add compiler-rt functions for f80
2022-02-05 20:57:32 -05:00
Jakub Konka
f132f426b9 x86_64: add distinct MCValue representing symbol index in the linker
For PIE targets, we defer getting an address of value until the linker
has allocated all atoms and performed the relocations. In codegen,
we represent this via `MCValue.linker_sym_index` value.
2022-02-06 00:34:24 +01:00
joachimschmidt557
4b3b487627 stage2 regalloc: Introduce error.OutOfRegisters 2022-02-06 00:14:48 +01:00
joachimschmidt557
d4c3475f3d stage2 ARM: clarify usage of unfreezeRegs in airSliceElemVal 2022-02-05 15:58:46 +01:00
praschke
f2a82bafae std: allow tests to use cache and setOutputDir 2022-02-05 16:33:57 +02:00
gwenzek
0e1afb4d98 stage2: add support for Nvptx target
sample command:

/home/guw/github/zig/stage2/bin/zig build-obj cuda_kernel.zig -target nvptx64-cuda -O ReleaseSafe
this will create a kernel.ptx

expose PtxKernel call convention from LLVM
kernels are `export fn f() callconv(.PtxKernel)`
2022-02-05 16:33:00 +02:00
rohlem
fbc06f9c91 std.build.TranslateCStep: add C macro support
The string construction code is moved out of std.build.LibExeObjStep
into std.build.constructCMacroArg, to allow reusing it elsewhere.
2022-02-05 03:17:07 -05:00
Veikka Tuominen
7d04ab1f14 std.process: add option to support single quotes to ArgIteratorGeneral 2022-02-05 02:59:13 -05:00
Jan Philipp Hafer
01d48e55a5 compiler_rt: optimize mulo
- use usize to decide if register size is big enough to store
  multiplication result or if division is necessary
- multiplication routine with check of integer bounds
- wrapping multipliation and division routine from Hacker's Delight
2022-02-05 01:35:46 -05:00
Veikka Tuominen
5a7d43df23 stage1: make f80 always size 16, align 16 2022-02-04 22:44:56 +02:00
Veikka Tuominen
b2f84c6714 stage1: implement f80 negation on non native targets 2022-02-04 22:38:14 +02:00
Veikka Tuominen
6a736f0c8c compiler-rt: add add/sub for f80 2022-02-04 22:38:13 +02:00
Veikka Tuominen
9bbd3ab257 compiler-rt: add comparison functions for f80 2022-02-04 22:22:43 +02:00
Veikka Tuominen
72cef17b1a compiler-rt: add trunc functions for f80 2022-02-04 22:18:44 +02:00
Veikka Tuominen
5c4ef1a64c compiler-rt: add extend functions for f80 2022-02-04 22:16:07 +02:00
joachimschmidt557
04f379dd41 stage2 ARM: optimize airSliceElemVal for elem_size 1 or 4
In these cases, the AIR inst can be lowered to only one ldr
instruction.

Also fixes shifts in arm.bits.Offset
2022-02-04 21:07:10 +01:00
Kirk Scheibelhut
71321b6941 Various documentation fixes
Co-authored-by: Kirk Scheibelhut <kjs@scheibo.com>
Co-authored-by: extrasharp <genericpb@gmail.com>
2022-02-04 21:27:50 +02:00
Andrew Kelley
95fbce2b95 Sema: fixes to fieldVal, resolveStructFully, Type.eql
fieldVal handles pointer to pointer to array. This can happen for
example, if a pointer to an array is used as the condition expression of
a for loop.

resolveStructFully handles tuples (by doing nothing).

fixed Type comparison for tuples to handle comptime fields properly.
2022-02-03 23:59:32 -07:00
Kazuki Sakamoto
64f7231f86 stage1: Fix missing LLD library 2022-02-04 01:45:44 -05:00
Mateusz Radomski
1b6a1e691f Sema: check for NaNs in cmp (#10760) 2022-02-04 00:58:27 -05:00
Andrew Kelley
0893326e0e Sema: slice improvements
* resolve_inferred_alloc now gives a proper mutability attribute to the
   corresponding alloc instruction. Previously, it would fail to mark
   things const.
 * slicing: fix the detection for when the end index equals the length
   of the underlying object. Previously it was using `end - start` but
   it should just use the end index directly. It also takes into account
   when slicing a comptime-known slice.
 * `Type.sentinel`: fix not handling all slice tags
2022-02-03 21:05:10 -07:00
Andrew Kelley
71e0cca7a7 Merge pull request #10780 from Luukdegram/wasm-behavior-tests
stage2: Wasm - Account for stack alignment
2022-02-03 20:23:46 -05:00
Andrew Kelley
5466e87fce update C API bindings to LLVM 14
* zig_clang is fully updated
 * zig_llvm is fully updated

Some initial work on codegen.cpp is in place for upgrading to LLVM's
new opaque pointers. However there is much more to be done.

A few of zig llvm bindings for deprecated functions have been updated;
more need to be updated.
2022-02-03 16:49:24 -07:00
Jakub Konka
4ca9a8d192 x64: implement storing to MCValue.memory for PIE targets 2022-02-04 00:37:43 +01:00
Luuk de Gram
588b88b987 Move passing behavior tests
Singular tests (such as in the bug ones) are moved to top level with exclusions for non-passing backends.
The big behavior tests such as array_llvm and slice are moved to the inner scope with the C backend disabled.
They all pass for the wasm backend now
2022-02-03 22:31:29 +01:00
Andrew Kelley
397e055ddd update C language headers to clang release/14.x
upstream commit 91632c8ac97fa3daffe4ff8f1391735b5d6805e6
2022-02-03 14:18:29 -07:00
Andrew Kelley
60954598e9 apply zig patches to clang and llvm tools 2022-02-03 14:01:32 -07:00
Luuk de Gram
e35414bf5c wasm: Refactor stack to account for alignment
We now calculate the total stack size required for the current frame.
The default alignment of the stack is 16 bytes, and will be overwritten when the alignment
of a given type is larger than that.

After we have generated all instructions for the body, we calculate the total stack size
by forward aligning the stack size while accounting for the max alignment.
We then insert a prologue into the body, where we substract this size from the stack pointer
and save it inside a bottom stackframe local. We use this local then, to calculate
the stack pointer locals of all variables we allocate into the stack.

In a future iteration we can improve this further by storing the offsets as a new `stack_offset` `WValue`.
This has the benefit of not having to spend runtime cost of storing those offsets, but instead we append
those offsets whenever we need the value that lives in the stack.
2022-02-03 21:53:48 +01:00
Andrew Kelley
3479294b6e update llvm and clang tools to release/14.x
upstream commit 91632c8ac97fa3daffe4ff8f1391735b5d6805e6
2022-02-03 13:43:51 -07:00
Luuk de Gram
ae1e3c8f9b wasm: Implement vector_init for array & structs
Implements the instruction `vector_init` for structs and arrays.
For arrays, it checks if the element must be passed by reference or not.
When not, it can simply use the `offset` field of a store instruction to copy the values
into the array. When it is byref, it will move the pointer by the element size, and then perform
a store operation. This ensures types like structs will be moved into the right position.
For structs we will always move the pointer, as we currently cannot verify if all fields are
not by ref.
2022-02-03 21:43:25 +01:00
Luuk de Gram
29013220d9 wasm: Implement elem_ptr
This implements lowering elem_ptr for decl's and constants.
To generate the correct pointer, we perform a relocation by using the addend
that represents the offset. The offset is calculated by taking the element's size
and multiplying that by the index.

For constants this generates a single immediate instruction, and for decl's
this generates a single pointer address.
2022-02-03 21:42:48 +01:00
Andrew Kelley
308f72701a update cmake files to LLVM 14 2022-02-03 13:38:48 -07:00
Jakub Konka
3832b58229 Merge pull request #10775 from ziglang/x64-freeze-api
stage2: migrate x64 to freeze regalloc API, and remove the concept of register exceptions
2022-02-03 20:12:35 +01:00
Jakub Konka
228b798af5 elf: generated DWARF debug info for named structs 2022-02-03 18:47:36 +01:00
Jakub Konka
74a01e3d64 stage2: remove the concept of register exceptions 2022-02-03 18:08:29 +01:00
Jakub Konka
e0b1170b67 x64: swap out register exceptions for freeze/unfreeze api 2022-02-03 17:55:22 +01:00
Jakub Konka
cfceec15e1 Merge branch 'mparadinha-test-1486' 2022-02-03 14:31:36 +01:00
Jakub Konka
f4e0641450 x64: use freeze/unfreeze api; TODO for PIE 2022-02-03 14:31:16 +01:00
Jakub Konka
e52af26856 Merge branch 'test-1486' of git://github.com/mparadinha/zig into mparadinha-test-1486 2022-02-03 14:00:28 +01:00
Jakub Konka
b77757fe39 elf: add basic handling of .data section 2022-02-03 08:47:06 +01:00
Andrew Kelley
557a097523 CLI: link_libcpp implies link_libc
Improves a warning message for some cases of using `zig run -lc++`.
2022-02-02 14:54:14 -07:00
Jakub Konka
7694361832 Merge pull request #10769 from ziglang/link-lib-fixes
stage2: handle name-qualified imports in sema, add a zerofill sections workaround to incremental macho
2022-02-02 20:59:17 +01:00
Andrew Kelley
3eb8d01f52 Merge pull request #10766 from ziglang/yeet-anytype-fields
remove anytype fields from the language
2022-02-02 13:39:27 -05:00
Jakub Konka
f95fcb2b1f Merge pull request #10762 from ziglang/stage2-x86_64-new-regalloc-api
stage2: handle more MCValue types in `struct_field_ptr` in x86_64 and pad out nonpacked struct fields when lowering to bytes (all targets incl wasm32)
2022-02-02 16:33:58 +01:00
Jakub Konka
8f3be0e04f stage2: update stage2 tests with qualified import lib names for externs
From

```zig
extern fn write(...);
```

to

```zig
extern "c" fn write(...);
```
2022-02-02 16:25:46 +01:00
Jakub Konka
06a037bb95 macho: handle bss like normal section in stage2
This is just a temporary workaround until I work out how to manage
non-physical sections between stage2 incremental updates.
2022-02-02 16:22:58 +01:00
Jakub Konka
380462ffc0 sema: do not pass libc or libc++ to the linker 2022-02-02 15:33:38 +01:00
GithubPrankster
23e981bbd1 Correct f80 description 2022-02-02 15:54:30 +02:00
Jakub Konka
c157b19878 wasm32: fix struct padding 2022-02-02 13:43:46 +01:00
Jakub Konka
15ff891f04 stage2: pad out (non-packed) struct fields when lowering to bytes
* pad out (non-packed) struct fields when lowering to bytes to be
  saved in the binary - prior to this change, fields would be
  saved at non-aligned addresses leading to wrong accesses
* add a matching test case to `behavior/struct.zig` tests
* fix offset to field calculation in `struct_field_ptr` on `x86_64`
2022-02-02 13:43:41 +01:00
Jakub Konka
521bd2e94a x86_64: pass more behaviour tests 2022-02-02 10:48:21 +01:00
Jakub Konka
0cccd8a887 x86_64: handle struct_field_ptr for stack_offset mcv 2022-02-02 10:48:21 +01:00
Jakub Konka
9de30bb065 x86_64: handle struct_field_ptr for register mcv 2022-02-02 10:48:21 +01:00
Jakub Konka
09e69c8c77 x86_64: start moving to new regalloc freeze API 2022-02-02 10:48:21 +01:00
mparadinha
ef4c54ba38 need to go through the GOT, and use a temporary register 2022-02-02 09:24:39 +00:00
mparadinha
b67b89025c implement store for 8 byte immediates 2022-02-02 08:50:37 +00:00
mparadinha
cc16ac9314 implement storing to MCValue.memory 2022-02-02 08:50:37 +00:00
Andrew Kelley
449554a730 stage2: remove anytype fields from the language
closes #10705
2022-02-01 19:06:40 -07:00
Andrew Kelley
f4a249325e stage1: avoid anytype fields for type info
prerequisite for #10705
2022-02-01 18:10:19 -07:00
Andrew Kelley
5cf918143c Sema: remove the data field from TypeInfo.Declaration
stage2 follow-up to aa326328d0
2022-02-01 11:40:29 -07:00
Andrew Kelley
217025e9f0 Merge pull request #10751 from mitchellh/stage2/cmp-eq-undefined
stage2: cmp between untyped undefines values results in undef bool
2022-02-01 13:38:56 -05:00
Andrew Kelley
4188d54130 Sema: replace some initTag calls with constants
No functional changes.
2022-02-01 11:37:29 -07:00
Mitchell Hashimoto
970f954039 stage2: cmp_eq between untyped undefines values results in undef bool 2022-02-01 11:21:23 -07:00
Andrew Kelley
3e99495ed8 Merge pull request #10742 from ziglang/ArrayHashMapEql
std: make ArrayHashMap eql function accept an additional param
2022-02-01 13:20:28 -05:00
Andrew Kelley
0298442100 Merge pull request #10753 from ziglang/nerf-type-info
stage1: remove the `data` field from `TypeInfo.Declaration`
2022-02-01 13:16:00 -05:00
Andrew Kelley
4d22fa5a2a update behavior tests and compile error tests 2022-01-31 22:33:49 -07:00
Andrew Kelley
75bbc74d56 a small crusade against std.meta.declarations 2022-01-31 22:25:49 -07:00
Andrew Kelley
aa326328d0 stage1: remove the data field from TypeInfo.Declaration
Partially implements #10706
2022-01-31 22:09:41 -07:00
Andrew Kelley
39983d7ff5 stage2: update to new ArrayHashMap API 2022-01-31 21:12:37 -07:00
Andrew Kelley
44b105a38d stage2: make --debug-log work by default for debug builds
can be disabled with `-Dlog=false`
2022-01-31 21:11:41 -07:00
Andrew Kelley
d3e40b0d80 Merge pull request #10743 from m-radomski/master
std: correct rounding in parse_hex_float.zig
2022-01-31 22:59:49 -05:00
Andrew Kelley
c46f7588ce std.fmt.parseHexFloat: clean up bitwise logic
* fold a couple separate operations into one
 * use const instead of var
 * naming conventions
2022-01-31 20:59:32 -07:00
Mateusz Radomski
7f024d6786 std: correct rounding in parse_hex_float.zig 2022-01-31 20:59:32 -07:00
Jakub Konka
627cf6ce48 astgen: clean up source line calculation and management
Clarify that `astgen.advanceSourceCursor` already increments absolute
values of the line and columns numbers; i.e., `GenZir.calcLine` is thus
not only obsolete but wrong by design.

Incidentally, this clean up allows for specifying the `FnDecl` line
numbers for DWARF use correctly as relative values with respect to
the start of the parent `Decl`. This `Decl` in turn has its line number
information specified relatively to its parent `Decl`, and so on, until
we reach the global scope.
2022-01-31 22:29:29 -05:00
Andrew Kelley
abbcf40327 Sema: fix index type in AIR being u64 instead of usize 2022-01-31 16:41:14 -07:00
John Schmidt
8e497eb32c debug: fix edge cases in macOS debug symbol lookup
This commit fixes two related things:

1. If the loop goes all the way through the slice without a match, on
   the last iteration `mid == symbols.len - 1` which causes
   `&symbols[mid + 1]` to be out of bounds. End one step before that
   instead.

2. If the address we're looking for is greater than the address of the
   last symbol in the slice, we now match it to that symbol. Previously,
   we would miss this case since we only matched if the address was _in
   between_ the address of two symbols.
2022-01-31 23:55:19 +01:00
joachimschmidt557
2913950ca9 stage2 ARM: implement ptr_stack_offset function parameters 2022-01-31 23:52:32 +01:00
Žiga Željko
5210b9074c os,wasi: use wasi-libc if available 2022-01-31 22:54:30 +01:00
Andrew Kelley
cf88cf2657 std: make ArrayHashMap eql function accept an additional param
which is the index of the key that already exists in the hash map.

This enables the use case of using `AutoArrayHashMap(void, void)` which
may seem surprising at first, but is actually pretty handy!
This commit includes a proof-of-concept of how I want to use it, with a
new InternArena abstraction for stage2 that provides a compact way to
store values (and types) in an "internment arena", thus making types
stored exactly once (per arena), representable with a single u32 as a
reference to a type within an InternArena, and comparable with a
simple u32 integer comparison. If both types are in the same
InternArena, you can check if they are equal by seeing if their index is
the same.

What's neat about `AutoArrayHashMap(void, void)` is that it allows us to
look up the indexes by key, *without actually storing the keys*.
Instead, keys are treated as ephemeral values that are constructed as
needed.

As a result, we have an extremely efficient encoding of types and
values, represented only by three arrays, which has no pointers, and can
therefore be serialized and deserialized by a single writev/readv call.
The `map` field is denormalized data and can be computed from the other
two fields.

This is in contrast to our current Type/Value system which makes
extensive use of pointers.

The test at the bottom of InternArena.zig passes in this commit.
2022-01-31 01:20:45 -07:00
joachimschmidt557
66cf011aa9 stage2 ARM: Move to new regalloc freeze API 2022-01-30 19:41:51 -05:00
Andrew Kelley
227968d78c Merge pull request #10723 from joachimschmidt557/stage2-riscv
stage2 RISCV64: Move to new regalloc freeze API
2022-01-30 19:41:35 -05:00
joachimschmidt557
b2338de7fd stage2 AArch64: Move to new regalloc freeze API 2022-01-30 19:41:11 -05:00
Andrew Kelley
fb7060d3c2 stage2: implement shl_exact and shr_exact
These produce an undefined value when one bits are shifted out.

New AIR instruction: shr_exact.
2022-01-30 16:23:31 -07:00
Andrew Kelley
0c30799d40 Sema: fix comptime shl for fixed-width integers 2022-01-30 15:23:40 -07:00
zseri
91ad96b88a ir.cpp: use is_tagged_union to DRY 2022-01-30 21:31:54 +02:00
PhaseMage
8a97807d68 Full response file (*.rsp) support
I hit the "quotes in an RSP file" issue when trying to compile gRPC using
"zig cc". As a fun exercise, I decided to see if I could fix it myself.
I'm fully open to this code being flat-out rejected. Or I can take feedback
to fix it up.

This modifies (and renames) _ArgIteratorWindows_ in process.zig such that
it works with arbitrary strings (or the contents of an RSP file).

In main.zig, this new _ArgIteratorGeneral_ is used to address the "TODO"
listed in _ClangArgIterator_.

This change closes #4833.

**Pros:**

- It has the nice attribute of handling "RSP file" arguments in the same way it
  handles "cmd_line" arguments.
- High Performance, minimal allocations
- Fixed bug in previous _ArgIteratorWindows_, where final trailing backslashes
  in a command line were entirely dropped
- Added a test case for the above bug
- Harmonized the _ArgIteratorXxxx._initWithAllocator()_ and _next()_ interface
  across Windows/Posix/Wasi (Moved Windows errors to _initWithAllocator()_
  rather than _next()_)
- Likely perf benefit on Windows by doing _utf16leToUtf8AllocZ()_ only once
  for the entire cmd_line

**Cons:**

- Breaking Change in std library on Windows: Call
  _ArgIterator.initWithAllocator()_ instead of _ArgIterator.init()_
- PhaseMage is new with contributions to Zig, might need a lot of hand-holding
- PhaseMage is a Windows person, non-Windows stuff will need to be double-checked

**Testing Done:**

- Wrote a few new test cases in process.zig
- zig.exe build test -Dskip-release (no new failures seen)
- zig cc now builds gRPC without error
2022-01-30 21:27:52 +02:00
Jonathan Marler
336aa3c332 remove __muloti4 from libc++
fixes https://github.com/ziglang/zig/issues/10719

compiler_rt already provides __muloti4 but libc++ is also providing it and when linking libc++ it causes a crash on my windows x86_64 machine.
2022-01-30 14:30:46 +01:00
Jakub Konka
dd7309bde4 Merge pull request #10404 from ominitay/iterator
std: Fix using `fs.Dir.Iterator` twice
2022-01-30 14:25:50 +01:00
Veikka Tuominen
9c36ae4626 Merge pull request #10728 from naeu/thread-tests
Add tests for std.Thread.Condition and std.Thread.Semaphore
2022-01-30 12:00:49 +02:00
Veikka Tuominen
924eb08b61 Merge branch 'fixcomptimesat'
Closes #10393
2022-01-30 11:40:03 +02:00
joachimschmidt557
1fd41af356 stage2 RISCV64: Move to new regalloc freeze API 2022-01-30 10:16:17 +01:00
joachimschmidt557
2a1727e93c stage2 RISCV64: Merge Register and RawRegister enums 2022-01-30 10:16:13 +01:00
Andrew Kelley
f8e418c47d Sema: improved comptime % syntax
* comptime known 0 as a numerator returns comptime 0 independent of
   denominator.
 * negative numerator and denominator are allowed when the remainder is
   zero because that means the modulus would be also zero.
 * organize math behavior tests
2022-01-29 14:27:28 -07:00
naeu
bdd1a9e48c std: add test for Thread.Semaphore 2022-01-29 20:30:53 +00:00
naeu
4efd951801 std: add test for Thread.Condition 2022-01-29 20:30:53 +00:00
Meghan
5e60ee4127 std: define static error set for fs.Dir.copyFile 2022-01-29 20:48:36 +02:00
Jean Dao
fedff06079 fix argsAlloc buffer size
The buffer `buf` contains N (= `slice_sizes.len`) slices followed by the
N null-terminated arguments. The N null-terminated arguments are stored
in the `contents` array list. Thus, `buf` size should be:
    @sizeOf([]u8) * slice_sizes.len + contents_slice.len

Instead of:
    @sizeOf([]u8) * slice_sizes.len + contents_slice.len + slice_sizes.len

This bug was found thanks to the gpa allocator which checks if freed
size matches allocated sizes for large allocations.
2022-01-29 20:46:06 +02:00
Andrew Kelley
aa902c7042 ci: azure: update to newer msys2 release 2022-01-29 11:28:57 -07:00
riverbl
3c53667db8 stage2: fix bug where performing wrapping or saturating arithmetic or saturating left shift on type comptime_int executed unreachable code 2022-01-29 18:12:28 +02:00
riverbl
54634991a2 stage1: fix issue with bigint_add that caused incorrect results when adding a large and a small comptime_int of differing sign
stage1: fix issue with to_twos_complement that caused a compile error when performing wrapping addition on two signed ints, both of which have the minimum possible value
2022-01-29 18:12:28 +02:00
riverbl
aa29f4a803 stage1: fix saturating arithmetic producing incorrect results on type comptime_int, allow saturating left shift on type comptime int 2022-01-29 18:12:28 +02:00
Jonathan S
aca665cebd Fix overflow in std.math.isNormal when applied to -Inf or a negative NaN 2022-01-29 18:11:49 +02:00
Jonathan Marler
ba445013c4 improve comptime windows GUID.parse performance
I found that after switching from my custom Guid parser to the one in std that it increased zigwin32 build times substantially (from 40 seconds to over 10 minutes).  More information can be found in the benchmark PR I created here: https://github.com/ziglang/gotta-go-fast/pull/21 .  This PR ports my GUID parser to std so all projects can leverage the faster comptime performance.
2022-01-29 18:10:22 +02:00
Veikka Tuominen
8d0c17f5e4 std: remove superfluous .read = true from deflate tests 2022-01-29 16:57:10 +02:00
Veikka Tuominen
9f16d9ed07 Merge pull request #10665 from Snektron/spirv-improvements
spir-v improvements
2022-01-29 15:59:42 +02:00
Sage Hane
e288148f60 fs: Use OpenMode enum instead of read/write flags. 2022-01-29 15:52:08 +02:00
Veikka Tuominen
88edde4edc Merge pull request #9915 from zzyxyzz/indexOfMinMax
std.mem: add indexOfMin and indexOfMax
2022-01-29 15:49:47 +02:00
ominitay
8ca9452a82 Remove deprecation warnings and enable test
Also fixes previously broken code uncovered by this
2022-01-29 15:49:00 +02:00
John Schmidt
adea9a1765 std.fmt: fix out-of-bounds array write in float printing
This commit fixes an out of bounds write that can occur when
formatting certain float values. The write messes up the stack and
causes incorrect results, segfaults, or nothing at all, depending on the
optimization mode used.

The `errol` function writes the digits of the float into `buffer`
starting from index 1, leaving index 0 untouched, and returns `buffer[1..]`
and the exponent. This is because `roundToPrecision` relies on index 0 being
unused in case the rounding adds a digit (e.g rounding 999.99
to 1000.00). When this happens, pointer arithmetic is used
[here](0e6d2184ca/lib/std/fmt/errol.zig (L61-L65))
to access index 0 and put the ones digit in the right place.

However, `errol3u` contains two special cases: `errolInt` and `errolFixed`,
which return from the function early. For these two special cases
index 0 was never reserved, and the return value contains `buffer`
instead of `buffer[1..]`. This causes the pointer arithmetic in
`roundToPrecision` to write out of bounds, which in the case of
`std.fmt.formatFloatDecimal` messes up the stack and causes undefined behavior.

The fix is to move the slicing of `buffer` to `buffer[1..]` from `errol3u`
to `errol` so that both the default and the special cases operate on the sliced
buffer.
2022-01-29 12:25:25 +01:00
John Schmidt
e51a44b342 fmt: handle doc comments on struct members
Closes https://github.com/ziglang/zig/issues/10443.
2022-01-29 12:19:31 +01:00
Andrew Kelley
225910f934 Merge pull request #10639 from Vexu/f80
Add f80
2022-01-29 03:45:15 -05:00
Stephen Gregoratto
a49f2d9f8d Add bits for the Linux Auditing System
Also adds the _CSKY and _FRV ELF machines that are defined in
`<linux/elf-em.h>`
2022-01-29 13:57:14 +11:00
Stephen Gregoratto
b7c7fba5b4 Add classic BPF library
This library contains:
- The global constants as used by C code.
- An Insn struct that implements can generate all the BPF instructions.
- A simple BPF virtual machine implementation that can be used for
  testing programs. This has complete code-coverage and has been
  extensively fuzzed.
2022-01-29 13:57:14 +11:00
John Schmidt
63ee6e6625 Rename mem.bswapAllFields to byteSwapAllFields
To match the renaming of `@bswap` to `@byteSwap` in
1fdb24827f.
2022-01-28 21:03:21 -05:00
Andrew Kelley
39083c31a5 glibc: version-gate _DYNAMIC_STACK_SIZE_SOURCE
This is a patch to glibc features.h which makes
_DYNAMIC_STACK_SIZE_SOURCE undefined unless the version is >= 2.34.

This feature was introduced with glibc 2.34 and without this patch, code
built against these headers but then run on an older glibc will end up
making a call to sysconf() that returns -1 for the value of SIGSTKSZ
and MINSIGSTKSZ.

Closes #10713
2022-01-28 18:36:23 -07:00
Andrew Kelley
cd5b25c5ae build.zig: fix single-threaded option
Instead of defaulting to false, just keep the option as optional to
communicate default to the build system.

Fixes one problem with building the compiler for single-threaded
targets.
2022-01-28 17:17:31 -07:00
Andrew Kelley
68fc26cd08 std: break up some long lines
This makes packaging Zig for Debian slightly easier since it will no
longer trigger a Lintian warning for long lines.
2022-01-28 16:23:47 -07:00
joachimschmidt557
1a324a8ad6 stage2 regalloc: Fix bug where regs were not marked as allocated 2022-01-28 18:03:03 -05:00
Andrew Kelley
d7deffee8d link: ELF, COFF, WASM: honor the "must_link" flag of positionals
Previously only the MachO linker was honoring the flag.
2022-01-28 12:18:53 -07:00
Andrew Kelley
a0a71709bc stage1: lower const f80 a different way
this way passes the behavior tests
2022-01-28 11:45:04 -07:00
Andrew Kelley
3c827be876 fix invalid const bitcast of f80
LLVM bitcast wants integers that match the number of bits. So the const
bitcast has to use an i80, not an i128.

This commit makes the behavior tests fail for me, so it seems I did not
correctly construct the type. But it gets rid of the LLVM segfault.

I noticed that the strategy of memcpy the buf worked if I simply did an
LLVMConstTrunc() on the i128 to make it into an i80 before the
LLVMConstBitCast().

But is that correct in the face of different endianness? I'm not sure.
2022-01-28 11:45:04 -07:00
Veikka Tuominen
4411f9c019 add behavior tests for f80 2022-01-28 11:45:04 -07:00
Veikka Tuominen
f8b204bb18 stage1: call compiler-rt for math builtins on f80 on unsupported targets 2022-01-28 11:45:04 -07:00
Veikka Tuominen
0f3bd2afa3 stage1: handle compiler-rt calls on vectors of f80 2022-01-28 11:45:04 -07:00
Veikka Tuominen
8e9fd042b8 stage1: emit calls to compiler-rt for f80 on unsupported targets 2022-01-28 11:45:04 -07:00
Veikka Tuominen
67d04a988a std: add f80 bits 2022-01-28 11:45:04 -07:00
Veikka Tuominen
a31a749c42 stage1: add f80 type 2022-01-28 11:45:04 -07:00
ominitay
dc11fe4047 std: Fix using fs.Dir.Iterator twice
This fixes the use of multiple `Iterator`s in a row on a directory.
Previously, on many platforms, using an `Iterator` on an
already-iterated directory would give no entries.

Fixing this involved seeking to the beginning of the directory on the
first call of `next()`.
2022-01-28 16:12:05 +00:00
Robin Voetter
98ee39d1b0 spirv: spir-v dedicated type system 2022-01-28 14:45:23 +01:00
Robin Voetter
1b6ebce0da spirv: new module
This introduces a dedicated struct that handles module-wide information.
2022-01-28 14:38:58 +01:00
Robin Voetter
72e67aaf05 spirv: model spir-v section as separate type
The idea is that this type gains the relevant low-level instruction emitting
functions, and that higher-level checks and deduplications are performed
somewhere else.
2022-01-28 14:38:57 +01:00
Robin Voetter
462d8fd3ac spirv: keep track of air & liveness so that it can be used in flush() 2022-01-28 14:38:57 +01:00
Robin Voetter
94dd763936 spirv: regenerate spec
Regenerate the specification with the improvements previously made to the
spirv spec generator.
2022-01-28 14:38:57 +01:00
Robin Voetter
ff042e8006 spirv: improve generator
The spirv spec generator now also generates some support information:
Opcode gains a function to query a Zig type representing the operands
of the opcode. The idea is that this will enable a richer interface for
emitting spirv instructions.
2022-01-28 14:38:57 +01:00
ominitay
c3ef85aa76 Add test for using fs.Dir.Iterator twice 2022-01-27 20:54:48 +00:00
Andrew Kelley
0e6d2184ca stage2: .stub files are yet another c++ source file extension
however .cu files are a superset of c++.
2022-01-27 13:39:28 -07:00
Andrew Kelley
f589a66062 stage2: make cuda file extensions a separate enum tag than c++
follow-up to 2f41bd3be4.
2022-01-27 13:29:32 -07:00
Mikhail Popov
100b8a244c Add std.mem.minMax() and std.mem.IndexOfMinMax()
For finding the minimum and maximum values (and indices)
in a slice in a single pass.
2022-01-27 21:22:00 +02:00
Vesim
8c90b05add fchown: use the 32-bit uid/gid variant of the syscall on 32-bit linux targets 2022-01-27 20:27:16 +02:00
Mikhail Popov
dddbd2f511 std.mem: Add functions to find the index of the mimimum/maximum value in a slice. 2022-01-27 19:58:27 +02:00
praschke
6d1b1374f7 docs: reorganize @truncate and @intCast for clarity 2022-01-27 19:51:17 +02:00
vnc5
1adb6440db fix startup procedure for async WinMain 2022-01-27 19:49:12 +02:00
David John
80ac022c46 add std.debug.todo 2022-01-27 19:42:40 +02:00
Philipp Lühmann
db1edb6535 fix precedence in langref or example 2022-01-27 19:39:35 +02:00
John Schmidt
997600ac6f Preserve alignment when cloning 2022-01-27 19:35:08 +02:00
John Schmidt
f04007028f Implement clone with initCapacity and appendSliceAssumeCapacity
`ArrayList.ensureTotalCapacityPrecise` uses `Allocator.reallocAtLeast` under
the hood, which can return more than `new_capacity` bytes if `alignment
!= @alignOf(T)`. This implementation of `clone` assures that
the case of `ensureTotalCapacityPrecise` is handled correctly.

Thanks @Vexu and @squeek502 for pointing this out.
2022-01-27 19:35:08 +02:00
John Schmidt
d86b8663fc Use expectEqualSlices instead of loop 2022-01-27 19:35:08 +02:00
John Schmidt
da8e8b89e0 Set len on copied items array
Also fix the argument order for `expectEquals`.
2022-01-27 19:35:08 +02:00
John Schmidt
554734f9f8 Add ArrayList.clone
This is a common operation and matches the API on other stdlib
collections like HashMap and MultiArrayList.
2022-01-27 19:35:08 +02:00
Exonorid
3e6952ad16 Added documentation for implicit struct pointer dereferencing 2022-01-27 19:33:07 +02:00
Daniel Saier
2f41bd3be4 zig cc: Treat cu files as C++ source files
First step towards #10634.

Treating stub files as C++ allows to use zig c++ as a host
compiler for nvcc.

Treating cu files as C++ allow using zig c++ as a host compiler in
CMake. CMake calls the host compiler with -E on a cu file to identify
the compiler.

Using zig c++ to directly compile CUDA code is untested.
2022-01-27 19:23:55 +02:00
Andrew Kelley
35423b0054 organize behavior tests
check the set of passing tests; move towards the disabling logic being
inside each test rather than which files are included.

this enables a few more passing tests.
2022-01-26 20:59:20 -07:00
Andrew Kelley
82bd0ac572 Sema: implement struct init is_ref=true
Takes advantage of the pattern already established with
array_init_anon. Also upgrades array_init (non-anon) to the pattern.

Implements comptime struct value equality and pointer value hashing.
2022-01-26 20:02:01 -07:00
Andrew Kelley
db55f469c1 std.mem.Allocator: upgrade to new function pointer semantics 2022-01-26 20:02:01 -07:00
Andrew Kelley
50accb757f stage2: fix crash on file-level struct field source locations 2022-01-26 20:02:01 -07:00
Andrew Kelley
b463924da2 Merge pull request #10699 from motiejus/arm64
[linux headers] rename arm64 to aarch64
2022-01-26 20:51:59 -05:00
Andrew Kelley
40c9ce2caf zig cc: add --hash-style linker parameter
This is only relevant for ELF files.

I also fixed a bug where passing a zig source file to `zig cc` would
incorrectly punt to clang because it thought there were no positional
arguments.
2022-01-26 15:01:59 -07:00
joachimschmidt557
35503b3d3f stage2 regalloc: Add freezeRegs/unfreezeRegs API
The freeze/unfreeze API replaces the exceptions API for hopefully
preventing bugs in codegen code using the RegisterManager. The
exceptions API is still available for backwards compatibility and will
be removed once all backends transition to the new freeze/unfreeze
API.
2022-01-26 18:23:27 +01:00
Jakub Konka
4192be8403 elf: implement slice types in debug info
Implements slice types including `[]const u8` for passing as
formal parameters in DWARF. Breaking on a function accepting
a slice in `gdb` will now yield the same behavior as stage1 and/or
LLVM backend:

```zig
fn sumArrayLens(a: []const u32, b: []const u8) usize {
  return a.len + b.len;
}
```

Both `a` and `b` can now be inspected in the debugger:

```
Breakpoint 1, sumArrayLens (a=..., b=...) at arr.zig:59
(gdb) p a
$1 = {ptr = 0x7fffffff685c, len = 5}
(gdb) p b
$2 = {ptr = 0x7fffffff683d "\252\252\252\\h\377\377\377\177", len = 3}
(gdb)
```
2022-01-26 17:28:58 +01:00
Jakub Konka
aa4eaea778 Merge branch 'mparadinha-x64-trunc' 2022-01-26 16:19:15 +01:00
Jakub Konka
9f224ebd9a stage2: add zero- and sign-extend moves to x86_64
* remove `LoweringError` error set from `Emit.zig` - it actually
  was less than helpful; it's better to either not throw an error
  since there can be instructions with mismatching operand sizes
  such as `movsx` or assert on a by instruction-basis. Currently,
  let's just pass through and see how we fare.
* when moving integers into registers, check for signedness and move
  with zero- or sign-extension if source operand is smaller than 8
  bytes. The destination operand is always assumed to be full-width,
  i.e., 8 bytes.
* clean up `airTrunc` a little to match the rest of CodeGen inst
  implementations.
2022-01-26 16:14:57 +01:00
Jakub Konka
075e2eaaaf Merge branch 'x64-trunc' of git://github.com/mparadinha/zig into mparadinha-x64-trunc 2022-01-26 11:15:57 +01:00
Andrew Kelley
2c9a5e791b organize behavior tests
Every test that is moved in this commit has been checked to see if it is
now passing.
2022-01-26 00:36:12 -07:00
26e54d8a32 fix aarch64 include path 2022-01-26 09:10:12 +02:00
7107a0fc40 [linux headers] rename arm64 to aarch64
Zig calls it aarch64. Linux calls it arm64. Currently lib/libc/include
has both arm64 and aarch64, which is quite confusing.

tools/update-linux-headers.zig was executed against the latest stable
linux patch version, therefore some other minor header updates. I will
update the wiki on how to do it once this PR is accepted.
2022-01-26 07:57:34 +02:00
Josh Hannaford
178cd60a5e Update the documentation for std.mem.sliceTo for readability 2022-01-26 00:49:17 -05:00
John Schmidt
9ee67b967b stage2: avoid inferred struct in os_version_check.zig
Before this commit, compiling an empty main with Stage 2 on macOS x86_64 results in

```
../stage2/bin/zig build-exe -ODebug -fLLVM empty_main.zig
error: sub-compilation of compiler_rt failed
    [...]/zig/stage2/lib/zig/std/special/compiler_rt/os_version_check.zig:26:10: error: TODO: Sema.zirStructInit for runtime-known struct values
```

By assigning the value to a variable we can sidestep the issue for now.
2022-01-26 00:48:05 -05:00
Andrew Kelley
0c1df96b17 Merge pull request #10552 from hdorio/deflate
compress: add a deflate compressor
2022-01-26 00:43:13 -05:00
Andrew Kelley
f0ddc7f7a2 translate-c: update for new function pointer semantics
After #10656, function pointers are represented with e.g.
`*const fn()void` rather than `fn()void`.

This commit adds code to translate-c to emit different code
depending on whether the output zig source code is intended
to be compiled with stage1 or stage2.

Ideally we will have stage1 and stage2 support the exact same
Zig language, but for now they diverge because I would rather
focus on finishing and shipping stage2 than implementing the
features in stage1.
2022-01-25 22:04:01 -07:00
Andrew Kelley
618055db50 c backend: use an explicit map of reserved idents
rather than unconditionally prepending double underscore to all
identifiers. Also, use the prefix `zig_e_` instead of `__`. Also, avoid
triggering this escaping when rendering an identifier and there has
already been a prefix printed.
2022-01-25 20:49:43 -07:00
mparadinha
575d430f92 stage2: x64: implement airTrunc 2022-01-25 23:53:26 +00:00
Lee Cannon
fbe5336f3b add option to force usage of GeneralPurposeAllocator 2022-01-25 18:21:58 -05:00
Jakub Konka
53c668d3a9 stage2: add naive impl of pointer type in ELF
Augment relocation tracking mechanism to de-duplicate potential
creation of base as well as composite types while unrolling
composite types in the linker - there is still potential for
further space optimisation by moving all type information into
a separate section `.debug_types` and providing references to
entries within that section whenever required (e.g., `ref4` form).
Currently, we duplicate type definitions on a per-decl basis.

Anyhow, with this patch, an example function signature of the following
type:

```zig
fn byPtrPtr(ptr_ptr_x: **u32, ptr_x: *u32) void {
    ptr_ptr_x.* = ptr_x;
}
```

will generate the following `.debug_info` for formal parameters:

```
 <1><1aa>: Abbrev Number: 3 (DW_TAG_subprogram)
    <1ab>   DW_AT_low_pc      : 0x8000197
    <1b3>   DW_AT_high_pc     : 0x2c
    <1b7>   DW_AT_name        : byPtrPtr
 <2><1c0>: Abbrev Number: 7 (DW_TAG_formal_parameter)
    <1c1>   DW_AT_location    : 1 byte block: 55        (DW_OP_reg5 (rdi))
    <1c3>   DW_AT_type        : <0x1df>
    <1c7>   DW_AT_name        : ptr_ptr_x
 <2><1d1>: Abbrev Number: 7 (DW_TAG_formal_parameter)
    <1d2>   DW_AT_location    : 1 byte block: 54        (DW_OP_reg4 (rsi))
    <1d4>   DW_AT_type        : <0x1e4>
    <1d8>   DW_AT_name        : ptr_x
 <2><1de>: Abbrev Number: 0
 <1><1df>: Abbrev Number: 5 (DW_TAG_pointer_type)
    <1e0>   DW_AT_type        : <0x1e4>
 <1><1e4>: Abbrev Number: 5 (DW_TAG_pointer_type)
    <1e5>   DW_AT_type        : <0x1e9>
 <1><1e9>: Abbrev Number: 4 (DW_TAG_base_type)
    <1ea>   DW_AT_encoding    : 7       (unsigned)
    <1eb>   DW_AT_byte_size   : 4
    <1ec>   DW_AT_name        : u32
```
2022-01-25 23:51:19 +01:00
Jakub Konka
05c5bb9edd stage2: populate debug info for args passed on stack
* implement cond_br when MCValue is a stack offset
* implement passing compare flags and immediate on stack
2022-01-25 23:51:04 +01:00
Andrew Kelley
ef7eff3939 Sema: coercion of pointers to C pointers 2022-01-25 14:53:41 -07:00
Andrew Kelley
f2835c6a28 Merge pull request #10679 from Luukdegram/wasm-unions
Stage2: wasm - Implement unions
2022-01-25 16:51:57 -05:00
Andrew Kelley
366c767444 link: Elf, Wasm: forward strip flag when linking with LLD 2022-01-25 11:52:48 -07:00
Andrew Kelley
50905d8851 zig cc: detect more linker args
* --whole-archive, -whole-archive
 * --no-whole-archive, -no-whole-archive
 * -s, --strip-all
 * -S, --strip-debug
2022-01-25 11:52:48 -07:00
Luuk de Gram
0682c9ac33 wasm: Implement genTypedValue for enums
This makes all union test cases succeed.
`rem` was also implemented as all we had to do is enable the instruction.
Loading and storing values based on ABI-size was simplified to a direct abiSize() call.

We also enabled all the newly passing test cases and disable them for all non-passing backends.
All of those test cases were verified to see if they perhaps already pass for the c-backend.
2022-01-25 19:29:40 +01:00
Luuk de Gram
e9d122f164 wasm: Implement lowering unions 2022-01-25 19:00:52 +01:00
Luuk de Gram
288b407fa9 wasm: Implement get_union_tag 2022-01-25 19:00:51 +01:00
Luuk de Gram
4b939fb34d wasm: Implement set_union_tag 2022-01-25 19:00:48 +01:00
Meghan
f1b79c9a44 std.crypto.random: Randoms are no longer passed by reference 2022-01-25 13:00:39 -05:00
Andrew Kelley
0817d6b215 Merge pull request #10656 from ziglang/fn-ptr-type
stage2: type system treats fn ptr and body separately
2022-01-25 12:42:52 -05:00
Andrew Kelley
f037029283 behavior tests: prevent disabled tests from lowering std.Target 2022-01-24 22:04:28 -07:00
Andrew Kelley
a2abbeef90 stage2: rework a lot of stuff
AstGen:
 * rename the known_has_bits flag to known_non_opv to make it better
   reflect what it actually means.
 * add a known_comptime_only flag.
 * make the flags take advantage of identifiers of primitives and the
   fact that zig has no shadowing.
 * correct the known_non_opv flag for function bodies.

Sema:
 * Rename `hasCodeGenBits` to `hasRuntimeBits` to better reflect what it
   does.
   - This function got a bit more complicated in this commit because of
     the duality of function bodies: on one hand they have runtime bits,
     but on the other hand they require being comptime known.
 * WipAnonDecl now takes a LazySrcDecl parameter and performs the type
   resolutions that it needs during finish().
 * Implement comptime `@ptrToInt`.

Codegen:
 * Improved handling of lowering decl_ref; make it work for
   comptime-known ptr-to-int values.
   - This same change had to be made many different times; perhaps we
     should look into merging the implementations of `genTypedValue`
     across x86, arm, aarch64, and riscv.
2022-01-24 21:53:57 -07:00
Andrew Kelley
8bb679bc6e Sema: resolveBody takes a parameter for break blocks
Previously, break instructions which wanted to break out of multiple
nesting layers did not work correctly at comptime.
2022-01-24 21:47:53 -07:00
Andrew Kelley
65576ea2ea llvm backend: fix not updating map after deleting global
This was uncaught UB!
2022-01-24 21:47:53 -07:00
Andrew Kelley
b34f994c0b stage2: type system treats fn ptr and body separately
This commit updates stage2 to enforce the property that the syntax
`fn()void` is a function *body* not a *pointer*. To get a pointer, the
syntax `*const fn()void` is required.

ZIR puts function alignment into the func instruction rather than the
decl because this way it makes it into function types. LLVM backend
respects function alignments.

Struct and Union have methods `fieldSrcLoc` to help look up source
locations of their fields. These trigger full loading, tokenization, and
parsing of source files, so should only be called once it is confirmed
that an error message needs to be printed.

There are some nice new error hints for explaining why a type is
required to be comptime, particularly for structs that contain function
body types.

`Type.requiresComptime` is now moved into Sema because it can fail and
might need to trigger field type resolution. Comptime pointer loading
takes into account types that do not have a well-defined memory layout
and does not try to compute a byte offset for them.

`fn()void` syntax no longer secretly makes a pointer. You get a function
body type, which requires comptime. However a pointer to a function body
can be runtime known (obviously).

Compile errors that report "expected pointer, found ..." are factored
out into convenience functions `checkPtrOperand` and `checkPtrType` and
have a note about function pointers.

Implemented `Value.hash` for functions, enum literals, and undefined values.

stage1 is not updated to this (yet?), so some workarounds and disabled
tests are needed to keep everything working. Should we update stage1 to
these new type semantics? Yes probably because I don't want to add too
much conditional compilation logic in the std lib for the different
backends.
2022-01-24 21:47:53 -07:00
Andrew Kelley
0866fa9d1d Merge pull request #10688 from topolarity/c-backend-union-support
stage2: Add `union` support to C backend
2022-01-24 23:47:41 -05:00
Andrew Kelley
913d61ebb9 Revert "MultiArrayList: Fix error when struct is 0 sized"
This reverts commit 1f10cf4edf.

Re-opens #10618

I want to solve this a different way. `align(S)` where S is a 0-byte
type should work in this context.

This also caused issues such as
https://github.com/Vexu/arocc/issues/221
2022-01-24 21:29:04 -07:00
mparadinha
2e9ce6facd stage2: x64: fix printing of callee preserved regs instructions 2022-01-24 23:19:53 +01:00
joachimschmidt557
7665401500 stage2 ARM: re-enable debug info for arguments
These were disabled during the MIR transition
2022-01-24 23:18:13 +01:00
Frank Denis
4e5495e443 std.crypto.25519.scalar: implement edwards25519 scalar field inversion
This operation is extremely useful for multiplicative blinding.
2022-01-24 23:09:45 +01:00
Cody Tapscott
60e6bf112c Cleanup unnecessary switches in union logic 2022-01-24 12:49:14 -07:00
Cody Tapscott
cb24799368 Run zig fmt 2022-01-24 12:18:16 -07:00
Cody Tapscott
587a4437db Add union support to the C backend.
There are some differences vs. the union encoding in the LLVM backend:
   - Tagged unions with a 0-bit payload do not become their tag type. Instead,
     they are a struct with an empty `union` as their payload field.
   - We do not order the `payload`/`tag` storage based on their alignment
2022-01-24 12:00:04 -07:00
Cody Tapscott
983dfcd3fb Fix rendering of void function args 2022-01-24 12:00:04 -07:00
Cody Tapscott
8c96c64fbb Add support for rendering .enum_numbered 2022-01-24 12:00:04 -07:00
Cody Tapscott
52517e86d6 Avoid identifier conflicts with reserved C keywords 2022-01-24 12:00:01 -07:00
Cody Tapscott
799bd81b08 Add support for rendering .elem_ptr 2022-01-24 11:58:43 -07:00
John Schmidt
40b3c9a592 Handle FormatOptions in fmtDuration/fmtDurationSigned 2022-01-24 20:30:36 +02:00
riverbl
a0732117d0 HashMap: add removeByPtr 2022-01-24 20:29:05 +02:00
Sizhe Zhao
15ef251a15 Avoid duplicate TLS startup symbols 2022-01-24 20:26:29 +02:00
Jonathan Marler
3f341bdc26 Normalize some build function names
An attempt to normalize some of the function names in build.zig.  Normalize add*Dir to add*Path.  Also use "Library" instead of the "Lib" abbreviation.

The PR does not remove the old names, only adds the new normalized ones to faciliate a transition period.
2022-01-24 20:15:32 +02:00
Pablo Santiago Blum de Aguiar
5ba4385971 readUntilDelimiter*: read only if buffer not full
Ref.: #9594
2022-01-24 17:44:26 +02:00
Jonathan Marler
2fc2d88fc6 use explicit integer bit widths for windows GUID
The size of a GUID is not platform-dependent, it's always a fixed number of bits.  So I've updated guid to use fixed bit integer types rather than platform-dependent C integer types.
2022-01-24 17:35:15 +02:00
fifty-six
da8d4d9225 std/fs: Support XDG_DATA_HOME
This is generally used for user-specific data on linux, with the
default being ~/.local/share
2022-01-24 17:33:38 +02:00
riverbl
1f10cf4edf MultiArrayList: Fix error when struct is 0 sized
Also fixes error with ArrayHashMap when both key and value are 0 sized
2022-01-24 17:31:27 +02:00
Lee Cannon
c54a7ca4b2 allow expected_exit_code to be null 2022-01-24 17:29:19 +02:00
Andrew Kelley
12c2de6ee2 Merge pull request #10662 from ziglang/doc-comments-zir
Doc comments zir
2022-01-23 18:31:55 -05:00
Andrew Kelley
8a69726209 AstGen: doc comment fixups
* AstGen: use Ast.zig helper methods to avoid copy pasting token counting logic
   - take advantage of the `first_doc_comment` field we already have for
     param AST nodes
 * Add missing ZIR docs
2022-01-23 16:24:46 -07:00
Jimmi Holst Christensen
f1b91bb41b c backend: Implement aligning fields and local/global variables
There are some restrictions here.

- We either need C11 or a compiler that supports the aligned attribute
- We cannot provide align less than the type's natural C alignment.
2022-01-23 17:23:55 -05:00
Jimmi Holst Christensen
7287c7482a Stop using LinearFifo in BufferedWriter
Looking at the BufferedWriter assembly generated, one can see that is
has to do a lot of work, just to copy over some bytes and increase an
offset. This is because the LinearFifo is a much more general construct
than what BufferedWriter needs and the optimizer cannot prove that we
don't need to do this extra work.
2022-01-23 14:41:15 -05:00
Hadrien Dorio
490f067de8 compress: add a deflate compressor
Replaces the inflate API from `inflateStream(reader: anytype, window_slice: []u8)` to
`decompressor(allocator: mem.Allocator, reader: anytype, dictionary: ?[]const u8)` and
`compressor(allocator: mem.Allocator, writer: anytype, options: CompressorOptions)`
2022-01-23 19:30:06 +01:00
Hadrien Dorio
dba04a272a compress: remove sha256 checks from tests
Read bytes to check expected values instead of reading and hashing them.
Hashing is a waste of time when we can just read and compare.
This also removes a dependency on std.crypto.hash.sha2.Sha256 for tests.
2022-01-23 19:29:57 +01:00
joachimschmidt557
fa84625aeb std: Add some missing termios types to c/linux.zig and os.zig 2022-01-23 17:12:07 +01:00
Jakub Konka
36f13f5911 stage2: remove asserts and comments which are Emit.zig responsibility 2022-01-23 00:31:37 +01:00
Jakub Konka
081ce09575 Merge pull request #10664 from ziglang/stage2-x86_64-refactor-air-call
stage2: refactor how we preserve callee regs and how we pass args on the stack in x86_64 backend
2022-01-23 00:01:12 +01:00
Jakub Konka
406c85f9ba macho+elf: fix integer overflow in allocateAtom
If there is a big atom available for re-use in the free list, and
it's the last atom in section, it's ideal capacity might span the
entire section in which case we do not want to calculate the actual
end VM addr of the symbol since it may overflow. Instead, we just take
the max capacity available as end VM addr estimate. In this case,
the max capacity equals `std.math.maxInt(u64)`.
2022-01-22 08:50:01 +01:00
Jakub Konka
062ddb693f stage2: fix improper capacity prealloc in lowerToRm encoding 2022-01-22 00:58:18 +01:00
Jakub Konka
5fb921539b stage2: do not copy args passed via stack into functions locals 2022-01-22 00:46:35 +01:00
Jakub Konka
4a5e75245b stage2: clean up preserving callee regs on the stack
Instead of using `push` and `pop` combo, we now re-use our stack
allocation mechanism which means we don't have to worry about
16-byte stack adjustments on macOS as it is handled automatically
for us. Another benefit is that we don't have to backpatch stack
offsets when pulling args from the stack.
2022-01-22 00:46:35 +01:00
Loris Cro
8c23b81e86 fix incorrect zir offset loading in sema 2022-01-21 22:46:12 +01:00
Andrew Kelley
d819663543 disable some broken stuff for stage2 llvm backend on aarch64 2022-01-21 14:42:58 -07:00
Loris Cro
ba55e32ef2 add function param doc comment info in zir 2022-01-21 22:00:57 +01:00
Loris Cro
1f56ff8343 add support for more decl attributes in doc comment zir
The previous commit that implemented doc comment zir support for
decls did not properly account for all the possible attribute
keyword combinations (threadlocal, extern, and such).
2022-01-21 22:00:57 +01:00
Loris Cro
98fddd1c54 add field doc comments to zir
Doc comment information is stored in `extra` unconditionally for
each field. This commmit covers Structs, Enums, Unions, and ErrSets.
2022-01-21 22:00:57 +01:00
Loris Cro
3010ccfca5 astgen saves decl doc comments in zir
The field is saved in `extra` unconditionally for each decl.
2022-01-21 22:00:56 +01:00
Andrew Kelley
c9ae24503d Merge pull request #10649 from ziglang/stage2-tuples
stage2: implement tuples
2022-01-20 18:24:01 -05:00
Andrew Kelley
1f823eecdd stage2: fix compilation on 32 bit targets 2022-01-20 16:21:49 -07:00
Luuk de Gram
f763000dc9 Fix abi size of optional slices
Previously, optional slices returned the pointer size as abi size.
We now account for slices to calculate the correct size which is abi-alignment + slice ABI size.
2022-01-20 18:19:20 -05:00
Andrew Kelley
1417698c11 Sema: storePtr optimization for tuples
To generate better code for tuples, we detect a tuple operand in
storePtr, and analyze field loads and stores directly. This avoids
an extra allocation + memcpy which would occur if we used `coerce`.
2022-01-20 16:17:16 -07:00
Andrew Kelley
4fccc95b01 Sema: fix requiresComptime infinite recursion
When asking a struct or union whether the type requires comptime, it may
need to ask itself recursively, for example because of a field which is
a pointer to itself. This commit adds a field to each to keep track of
when computing the "requires comptime" value and returns `false` if the
check is already ongoing.
2022-01-20 16:17:16 -07:00
Andrew Kelley
e86ff712a6 stage2: implement tuples
* AIR instruction vector_init gains the ability to init arrays and
   tuples in addition to vectors. This will probably also gain the
   ability to initialize structs and be renamed to `aggregate_init`.
 * AstGen prefers to use an `anon_array_init` ZIR instruction for
   local variables when the init expr is an array literal and there is
   no type.
2022-01-20 16:17:16 -07:00
Jakub Konka
eb70f6e8d7 Merge pull request #10638 from Luukdegram/wasm-refactor
Stage2: wasm - Refactor lowering constants
2022-01-20 20:26:09 +01:00
Andrew Kelley
664e1a892c stage1: remove the "referenced here" error note
It's generally noise. The parts where it is useful will need to be
redone to not be annoying for the general case.
2022-01-20 13:27:52 -05:00
Jonathan Marler
0e682e71b0 remove unnecessary self argument 2022-01-20 10:55:10 +02:00
Meghan Denny
b7ba728929 std: add meta.DeclEnum 2022-01-20 10:54:45 +02:00
Jakub Konka
5eaac2fb99 macho: do not write out ZEROFILL physically to file
Prior to this change, `__DATA,__bss` and `__DATA,__thread_bss` would
get actually, physically written out to the output file, unnecessarily
filling the output file with 0s.
2022-01-20 02:21:58 -05:00
Jakub Konka
538c9e7baf Merge pull request #10635 from ziglang/stage2-x86_64-params-stack
stage2: fix passing arguments on the stack on x86_64
2022-01-20 00:45:34 +01:00
Daniel Saier
4a401b20e4 glibc: fix passing of __GNU_MINOR__
This was originally introduced in 4d48948b52
but broken immediately afterwards in c8af00c66e.
2022-01-19 17:56:58 -05:00
Luuk de Gram
b9fe6a93ff wasm: Re-use genTypedValue for constants
When a constant will be passed by reference, such as a struct, we will call into genTypedValue
to lower the constant to bytes and store them into the `rodata` section. We will then return the address
of this constant as a `WValue`.
This change means we will have all constants lowered during compilation time, and no longer have
to sacrifice runtime to lower them onto the stack.
2022-01-19 22:29:36 +01:00
C-BJ
7767e52bbf Update CONTRIBUTING.md
Delete unavailable content!
2022-01-19 14:29:55 -05:00
Jakub Konka
7c831cc266 stage2: add tweak to please Apple re stack alignment
This is more like a temp hack than anything else - I think the
mechanism we use for adjusting the stack when pushing args onto
the stack could/should be reused - i.e., we should just calculate
the stack alignment before each call and then reset the `rsp`
rather than relying on the current hack in `gen()` logic.
2022-01-19 20:21:05 +01:00
Jakub Konka
df6c0067b2 stage2: fix passing arguments on the stack
* push the arguments in reverse order
* add logic for pushing args of any abi size to stack - very similar to
  `genSetStack` however, uses `.rsp` as the base register
* increment and decrement `.rsp` if we called a function with args on
  the stack in `airCall`
* add logic for recovering args from the caller's stack in the callee
2022-01-19 20:21:00 +01:00
Luuk de Gram
1fe1e4d292 wasm: Split funcgen and declgen
This allows us to get rid of unused fields when generating code for non-function decls.
We can now create seperate instances of `DeclGen` which in turn can then be used
to generate the code for a constant.
Besides those reasons, it will be much easier to switch to the generic purpose `codegen.zig` that any
backend should use. Allowing us to deduplicate this code.
2022-01-19 20:01:23 +01:00
Luuk de Gram
28acbdb02f wasm-linker: Allow for creation of local symbols
The backend can create annonymous local symbols. This can be used for constants
that will be passed by reference so it will not have to be lowered to the stack, and then
stored into the data section. This also means it's valid to return a pointer to a constant array.

Those local symbols that are created, will be managed by the parent decl. Free'ing the parent decl,
will also free all of its locals.

When a local symbol was created, the index of said symbol will be returned and saved in the `memory`
tag of a `WValue` which is then memoized. This means that each 'emit' of this WValue will create a relocation
for that constant/symbol and the actual pointer value will be set after relocation phase.
2022-01-19 20:01:23 +01:00
Luuk de Gram
9615d7aee7 wasm: Refactor storing values.
Due to the new structure of lowerConstant, we can now simplify the logic in a lot of situations.
- We no longer have to check the `WValue`'s tag to determine how to load/store a value.
- We can now provide simple memcopy's for aggregate types.
- Constants are now memoized, meaning we do no longer lower constants on each callsite.
2022-01-19 20:01:23 +01:00
Luuk de Gram
38253a680d wasm: Refactor emitConstant to lower to WValue 2022-01-19 20:01:23 +01:00
Andrew Kelley
7c6981e0c0 stage2: fix ABI size of slice types to be 2 * ptr size
Previously it was returning 1 * ptr size.
2022-01-19 11:56:01 -07:00
Andrew Kelley
4e8fedffd1 Merge pull request #10475 from lithdew/master
lld: allow for entrypoint symbol name to be set
2022-01-19 13:43:40 -05:00
Andrew Kelley
fd6d1fe015 stage2: improvements to entry point handling
* rename `entry` to `entry_symbol_name` for the zig build API
 * integrate with `zig cc` command line options
 * integrate with COFF linking with LLD
 * integrate with self-hosted ELF linker
 * don't put it in the hash for MachO since it is ignored
2022-01-19 11:41:08 -07:00
Kenta Iwasaki
5ae3e4e9bd lld: allow for entrypoint symbol name to be set
This commit enables for the entrypoint symbol to be set when linking ELF
or WebAssembly modules with lld using the Zig compiler.
2022-01-19 11:22:10 -07:00
Andrew Kelley
beb7495e19 Merge pull request #10624 from ziglang/prefetch
stage2: implement `@prefetch`
2022-01-18 23:25:44 -05:00
Andrew Kelley
de5908548c disable failing atomicrmw test on llvm + aarch64 2022-01-18 21:25:22 -07:00
Andrew Kelley
8375b71f75 Sema: implement declarations for @typeInfo
In the behavior test listings, I had to move type_info.zig test import
to a section that did not include the x86 backend because it got to the
point where adding another test to the file, even if it was an empty
test that just returned immediately, caused a runtime failure when
executing the test binary.

Anyway, type info for opaques is implemented, and the declarations slice
is shared between it, enums, and unions.

Still TODO is the `data` field of a `Declaration`. I want to consider
removing it from the data returned from `@typeInfo` and introducing
`@declInfo` or similar for this data. This would avoid the complexity of
a lazy mechanism.
2022-01-18 18:22:48 -07:00
joachimschmidt557
cd594d10bd stage2 ARM: basic implementation of ptr_slice_{len,ptr}_ptr 2022-01-19 01:33:18 +01:00
Jakub Konka
e80ebc6740 Merge pull request #10625 from ziglang/stage2-x86_64-inline-memset
stage2: add inline memset, partial intcast and more array goodness for x86_64
2022-01-18 22:23:58 +01:00
John Schmidt
305a7def13 Implement segfault handler for macOS x86_64 2022-01-18 15:10:49 -05:00
Andrew Kelley
30efcf22d7 stage2: implement @prefetch
This reverts commit f423b5949b,
re-instating commit d48e4245b6.
2022-01-18 11:59:09 -07:00
Jakub Konka
8201939d7f stage2: implement airArrayElemVal 2022-01-18 18:55:02 +01:00
Andrew Kelley
f423b5949b Revert "stage2: implement @prefetch"
This reverts commit d48e4245b6.

I have no idea why this is failing Drone CI, but in a branch, reverting
this commit solved the problem.
2022-01-18 10:47:02 -07:00
Jakub Konka
8c233687b4 stage2: partially implement intcast on x86_64
* fix violating encoding invariant for memory encoding
* enable some cast tests for x86_64 and arm
2022-01-18 13:18:59 +01:00
Jakub Konka
aaa641feba stage2: add inline memset for x86_64 backend
* introduce new Mir tag `mov_mem_index_imm` which selects instruction
  of the form `OP ptr [reg + rax*1 + imm32], imm32` where the encoded
  flags select the appropriate ptr width for memory store operation
  (note that scale is fixed and set at 1)
2022-01-18 11:58:22 +01:00
Andrew Kelley
4938fb8f5c test runner: stage2 llvm backend prints stats 2022-01-17 22:17:02 -07:00
Andrew Kelley
4d05f2ae5f remove zig_is_stage2 from @import("builtin")
Instead use the standarized option for communicating the
zig compiler backend at comptime, which is `zig_backend`. This was
introduced in commit 1c24ef0d0b.
2022-01-17 21:55:49 -07:00
Andrew Kelley
84c2c47fae Sema: implement else capture value
The ZIR instructions `switch_capture_else` and `switch_capture_ref` are
removed because they are not needed. Instead, the prong index is set to
max int for the special prong.

Else prong with error sets is not handled yet.

Adds a new behavior test because there was not a prior on to cover only
the capture value of else on a switch.
2022-01-17 20:45:55 -07:00
Andrew Kelley
2600978a9d behavior tests: a couple more switch cases are passing 2022-01-17 19:52:24 -07:00
Jakub Konka
e69cb9105a Merge pull request #10616 from ziglang/stage2-x86_64-array-to-slice
stage2: implement airArrayToSlice for x86_64
2022-01-18 01:25:48 +01:00
Andrew Kelley
f4e051e35d Sema: fix comptime break semantics
Previously, breaking from an outer block at comptime would result in
incorrect control flow. Now there is a mechanism, `error.ComptimeBreak`,
similar to `error.ComptimeReturn`, to send comptime control flow further
up the stack, to its matching block.

This commit also introduces a new log scope. To use it, pass
`--debug-log sema_zir` and you will see 1 line per ZIR instruction
semantically analyzed. This is useful when you want to understand what
comptime control flow is doing while debugging the compiler.

One more `switch` test case is passing.
2022-01-17 15:23:50 -07:00
Jakub Konka
3145fa97c2 stage2: separate ptr and stack offset codepaths in genSetStack 2022-01-17 21:52:15 +01:00
Jakub Konka
ab204f81b0 stage2: return error.SkipZigTest in unsupported behavior tests 2022-01-17 20:30:44 +01:00
Jakub Konka
9b715cb462 stage2: implement airArrayToSlice for x86_64
* implement `genSetStack` for `ptr_stack_offset`
* handle `ptr_add`
* implement storing from register into pointer in register
* split alignment and array tests into those that pass on x86_64 and
  those that do not
* pass more tests on x86_64
2022-01-17 20:24:14 +01:00
Jakub Konka
79628d48a4 stage2: implement airCondBr for immediate MCValue in x86_64
Pass more behavior tests.
2022-01-17 16:35:41 +01:00
fn ⌃ ⌥
d46973ee4f translate-c: improve error messages when expecting specific tokens
Old:
  unable to translate C expr: expected ')'
New:
  unable to translate C expr: expected ')' instead got '...'
2022-01-17 17:16:48 +02:00
Meghan
4a92f42ed7 std.c: add shm_open and shm_unlink
https://man7.org/linux/man-pages/man3/shm_open.3.html
2022-01-17 16:56:50 +02:00
riverbl
c71cf48cb5 stage2: do not interpret identifier containing underscores (eg: u3_2) as int primitive type 2022-01-17 16:54:48 +02:00
johnLate
4addb26bba Fix os.rusage when linking with c library on Linux
Fixes ziglang#10543 on Linux.
2022-01-17 16:52:36 +02:00
riverbl
aa5514fcf2 translate-c: Fix issues translating macro define of hex float constant
* Fix incorrect result when the first digit after the decimal point is not 0-9 - eg 0x0.ap0
* Fix compiler panic when the number starts with `0X` with a capital `X` - eg 0X0p0
* Fix compiler panic when the number has a decimal point immediately after `0x` - eg 0x.0p0
2022-01-17 16:49:46 +02:00
Meghan Denny
0d0f277954 std: add json.stringifyAlloc 2022-01-17 12:32:02 +01:00
Jakub Konka
f72a0a2907 Merge branch 'Jarred-Sumner-patch-1' 2022-01-17 12:29:11 +01:00
Jakub Konka
90343d1868 libstd: add smoke test for insert methods in MultiArrayList 2022-01-17 12:26:48 +01:00
Jarred Sumner
144e36770e Fix missing !void in std.MultiArrayList
Calling `insert` on a `std.MultiArrayList` currently fails with a compiler error due to using a `try` without the `!` annotation on the return type

```zig
this.list.insert(allocator, 0, listener);
```

```zig
/Users/jarred/Build/zig/lib/std/multi_array_list.zig:192:13: error: expected type 'void', found '@typeInfo(@typeInfo(@TypeOf(std.multi_array_list.MultiArrayList(src.javascript.jsc.node.types.Listener).ensureUnusedCapacity)).Fn.return_type.?).ErrorUnion.error_set'
            try self.ensureUnusedCapacity(gpa, 1);
```
2022-01-16 17:26:49 -08:00
Andrew Kelley
97063efb69 stage2: fix 32-bit build
Regressed in 7c6f5d26ea.
2022-01-16 10:18:14 -07:00
Andrew Kelley
0f3938e498 behavior tests: move tests around 2022-01-16 10:14:57 -07:00
fifty-six
ff6ece3811 std/os/uefi: Don't treat efi status warnings as errors 2022-01-16 03:50:50 -05:00
fifty-six
03347114c3 std/os/uefi: Add util function for opening protocols 2022-01-16 03:04:37 -05:00
fifty-six
c727bd1bb6 std/os/uefi: Fix parameter type mismatch in edid_override_protocol 2022-01-16 02:52:45 -05:00
fifty-six
628a7f85de std/os/uefi: Add conversion from Status to EfiError
Allows handling uefi function errors in a more zig-style way with try
and catch, using `try f().err()` when a `Status` is returned.
2022-01-16 02:35:22 -05:00
fifty-six
d276a1189d std/os/uefi: Align first field of EdidOverrideProtocolAttributes to 4
This makes the struct align(4), which allows it to be passed as flags
more easily.
2022-01-16 02:05:27 -05:00
fifty-six
4771ac298b std/os/uefi: Simplify packed struct padding and default zero-initialize
Beyond adding default zero-initialization, this commit changes undefined
initialization to zero, as some cases reserved the padding and on other
cases, I've found some systems act strange when giving uninit instead of
zero even when it shouldn't be an issue, one example being
FileProtocol.Open's attributes, which *should* be ignored when not
creating a file, but ended up giving an unrelated error.
2022-01-16 02:04:39 -05:00
Jimmi Holst Christensen
f19b5ecf4b Slice function of BoundedArray now returns slice based on self pointer
If self pointer is const, the slice is const. Otherwise the slice is
mutable.
2022-01-16 01:37:37 -05:00
Andrew Kelley
7f41e20802 AstGen: emit as instructions for branching expressions
There is a mechanism to avoid redundant `as` ZIR instructions which is
to pass `ResultLoc.coerced_ty` instead of `ResultLoc.ty` when it is
known by AstGen that Sema will do the coercion.

This commit downgrades `coerced_ty` to `ty` when a result location
passes through an expression that branches, such as `if`, `switch`,
`while`, and `for`, causing the `as` ZIR instruction to be emitted.

This ensures that the type of a result location will be applied to, e.g.
a `comptime_int` on either side of a branch on a runtime condition.
2022-01-15 23:13:44 -07:00
Andrew Kelley
7c6f5d26ea Sema: populate the sentinel for comptime array inits 2022-01-15 22:46:39 -07:00
viri
12d6bcec02 std.os.windows: add ntdll thread information APIs 2022-01-15 17:46:33 -06:00
joachimschmidt557
0d2f4d0654 stage2 ARM: implement load for stack_offset + stack_argument_offset
1 more behavior test passing
2022-01-15 18:29:06 -05:00
viri
3c2eddae5a std.os.windows: fix casing for ntdll.lib
I've seen having this be wrong break some cross-compilers, and it's
also how it is in other files so it's best to be consistent.

It's also just the actual casing of the file.
2022-01-15 17:27:17 -06:00
Andrew Kelley
d48e4245b6 stage2: implement @prefetch 2022-01-15 15:18:25 -07:00
Jakub Konka
3901b6fb00 Merge pull request #10598 from ziglang/stage2-x86_64-imm-sizes
stage2: rename Isel back to Emit, and fix immediate casts in Emit for x86 64
2022-01-15 22:27:56 +01:00
Jakub Konka
3af4e28dda stage2: implement signed compare 2022-01-15 19:32:16 +01:00
joachimschmidt557
e23f7c01ee stage2 ARM: store all function parameters to stack for unspecified cc 2022-01-15 12:49:36 -05:00
Jakub Konka
6315bcb32a stage2: rename Isel to Emit for x86_64
Clean up generated errors in Emit.
2022-01-15 18:36:13 +01:00
Jakub Konka
4d4bbd7624 stage2: refactor handling of immediates in x86_64 backend
Fixes issues with incorrect operand sizes in a handful of cases
and allows for usage of differently sized integers in Zig sources.
2022-01-15 18:28:39 +01:00
Andrew Kelley
a5c7742ba6 stage2: fix Decl garbage collection not marking enough
It is the job of codegen backends to mark Decls that are referenced as
alive so that the frontend does not sweep them with the garbage. This
commit unifies the code between the backends with an added method on
Decl.

The implementation is more complete than before, switching on the Decl
val tag and recursing into sub-values.

As a result, two more array tests are passing.
2022-01-15 00:17:25 -07:00
Andrew Kelley
41f3799bf0 Sema: fix array_init with runtime element
Previously it emitted an invalid AIR encoding.
2022-01-14 23:08:11 -07:00
Jakub Konka
ba0f72363a Merge pull request #10576 from schmee/macos-resolve-ip
Use libc if_nametoindex for macOS when parsing IPs
2022-01-15 00:47:12 +01:00
Jakub Konka
b3471ef300 macho: code signature needs to be 16 bytes aligned 2022-01-14 22:32:33 +01:00
Andrew Kelley
1e481dfef5 Merge pull request #10587 from xxxbxxx/master
restore compatibility with glibc<=2.33 for global initializers
2022-01-14 14:40:54 -05:00
Andrew Kelley
3ed0741718 glibc: clean up build logic
also use the common naming convention for glibc versions ("2.33" rather
than "2-33").

I also verified that these files are exactly identical to the previous
files from before zig updated to glibc 2.34.
2022-01-14 12:39:06 -07:00
xavier
3f52132a8f tests: include global initializers in c++ compiler test 2022-01-14 11:48:38 -07:00
xavier
f1b14b91f1 glibc: restore compatibility with glibc<=2.33 for global initializers
__libc_start_main() from glibc.2.33.so or older needs to have a __libc_csu_init function callback parameter.

glibc-2.34 on the other hand has a different __libc_start_main() that does not use it,
and the start.S file from glibc-2.34 no longer construct the init function and pass null when calling __libc_start_main.

So, When targetting an older glibc, use the start.s files as they were in glibc-2.33 and construct the __libc_csu_init function.

fixes #10386 #10512
2022-01-14 11:48:37 -07:00
Marc Tiehuis
a64989ee70 stage1: fix bigint_init_bigfloat for single-limb negative floats
Fixes #10592.
2022-01-14 13:29:58 -05:00
fifty-six
dab4c63684 std/os/uefi: Refactor getDevicePath()
Uses comptime loops over the types instead of writing out a large
switch.
2022-01-14 08:58:30 -05:00
John Schmidt
c992164dc7 Check for isDarwin() instead of linked libc 2022-01-14 13:44:38 +01:00
fifty-six
a2a2601da5 std/os/uefi: Complete DevicePathProtocol types 2022-01-14 07:02:55 -05:00
Andrew Kelley
ec58ddf46c Merge pull request #10582 from ziglang/stage2-arrays
stage2: detection of comptime array literals
2022-01-14 00:23:27 -05:00
bryfry
0d45c72d3e Use allocPrintZ to avoid needing assumeSentinel 2022-01-14 00:17:38 -05:00
Andrew Kelley
336d0c97fe stage2: detection of comptime array literals
Introduce `validate_array_init_comptime`, similar to
`validate_struct_init_comptime` introduced in
713d2a9b38.

`zirValidateArrayInit` is improved to detect comptime array literals and
emit AIR accordingly. This code is very similar to the changes
introduced in that same commit for `zirValidateStructInit`.

The C backend needed some improvements to continue passing the same set
of tests:
 * `resolveInst` for arrays now will add a local `static const` with the
   array value and so then `elem_val` instructions reference that local.
   It memoizes accesses using `value_map`, which is changed to use
   `Air.Inst.Ref` as the key rather than `Air.Inst.Index`.
 * This required a mechanism for writing to a "header" which is lines
   that appear at the beginning of a function body, before everything
   else.
 * dbg_stmt output comments rather than `#line` directives.
   TODO comment reproduced here:

We need to re-evaluate whether to emit these or not. If we naively emit
these directives, the output file will report bogus line numbers because
every newline after the #line directive adds one to the line.
We also don't print the filename yet, so the output is strictly unhelpful.
If we wanted to go this route, we would need to go all the way and not output
newlines until the next dbg_stmt occurs.
Perhaps an additional compilation option is in order?

`Value.elemValue` is improved to support `elem_ptr` values.
2022-01-13 22:13:44 -07:00
Andrew Kelley
b019a19b55 Sema: comptime loads and stores for elem_ptr
The index is checked against actual array lengths, and now handles
coerced or casted pointers to single items.
2022-01-13 22:13:44 -07:00
Andrew Kelley
75b6637d60 Merge pull request #10584 from ziglang/macho-rustc-fixes
zld: a couple of fixes which result in better rustc support
2022-01-13 22:09:42 -05:00
joachimschmidt557
7e76aab98a stage2 AArch64: split ldr/str into {ldr,str}_register and _immediate 2022-01-14 00:46:07 +01:00
fifty-six
ae084c5f59 std/os/uefi: Complete AcpiDevicePath and HardwareDevicePaths 2022-01-13 15:47:14 -05:00
fifty-six
322757c4e1 std/os/uefi: Add parameter names to boot_services 2022-01-13 15:47:14 -05:00
fifty-six
88687645b2 std/os/uefi: Fill out remaining runtime services and add parameter names 2022-01-13 15:47:14 -05:00
fifty-six
fe28cb8261 std/os/uefi: Fill out remaining function signatures and docs on boot_services 2022-01-13 15:47:14 -05:00
fifty-six
649b872450 std/builtin: improve panic handler for uefi
Writes the panic message to stderr as well as passing it to
boot_services.exit when boot_services is available.
2022-01-13 15:47:14 -05:00
fifty-six
ea2df2601e std/os/uefi: Use usingnamespace to re-export symbols
`uefi/protocols.zig` and `uefi/tables.zig` just re-exported all the
public symbols, which is basically the purpose of `usingnamespace`
import-wise.
2022-01-13 15:47:13 -05:00
Jakub Konka
e945619728 macho: remove todo from getMatchingSectionDecl 2022-01-13 21:15:17 +01:00
Jakub Konka
5cde5f947f Introduce LinkObject with must_link field 2022-01-13 20:02:11 +01:00
Jakub Konka
a8564df9ed zld: parse addend from BRANCH reloc on x86_64
As usual, MachO, full of surprises!
2022-01-13 20:02:11 +01:00
Jakub Konka
16c55b15cb zld: support -Wl,-force_load=archive_path flag
This actually enables using `zig cc` as a linker for `cargo test`
with `serde_derive`.
2022-01-13 20:02:11 +01:00
Jakub Konka
f9f792ab70 zld: fix num nlist calc when there's no dynsymtab
Handle `__DATA,.rustc` section containing `rustc` metadata - this
is required to get crates like `serde_derive` link properly.
Note to self: this special section has to be copied __verbatim__
from the relocatable object file - this includes preserving its size
even though unpadded according the section's required alignment.
2022-01-13 20:02:11 +01:00
Andrew Kelley
c5ee73f65b stage2: fix build on 32-bit ISAs
Fixes regression introduced in 93b854eb74.
2022-01-13 10:42:38 -07:00
Andrew Kelley
9bf2bda683 compiler_rt: one less exception for stage2 2022-01-13 00:32:48 -07:00
Andrew Kelley
93b854eb74 stage2: implement @ctz and @clz including SIMD
AIR:
 * `array_elem_val` is now allowed to be used with a vector as the array
   type.
 * New instructions: splat, vector_init

AstGen:
 * The splat ZIR instruction uses coerced_ty for the ResultLoc, avoiding
   an unnecessary `as` instruction, since the coercion will be performed
   in Sema.
 * Builtins that accept vectors now ignore the type parameter. Comment
   from this commit reproduced here:

   The accepted proposal #6835 tells us to remove the type parameter from
   these builtins. To stay source-compatible with stage1, we still observe
   the parameter here, but we do not encode it into the ZIR. To implement
   this proposal in stage2, only AstGen code will need to be changed.

Sema:
 * `clz` and `ctz` ZIR instructions are now handled by the same function
   which accept AIR tag and comptime eval function pointer to
   differentiate.
 * `@typeInfo` for vectors is implemented.
 * `@splat` is implemented. It takes advantage of `Value.Tag.repeated` 😎
 * `elemValue` is implemented for vectors, when the index is a scalar.
   Handling a vector index is still TODO.
 * Element-wise coercion is implemented for vectors. It could probably
   be optimized a bit, but it is at least complete & correct.
 * `Type.intInfo` supports vectors, returning int info for the element.
 * `Value.ctz` initial implementation. Needs work.
 * `Value.eql` is implemented for arrays and vectors.

LLVM backend:
 * Implement vector support when lowering `array_elem_val`.
 * Implement vector support when lowering `ctz` and `clz`.
 * Implement `splat` and `vector_init`.
2022-01-12 23:53:26 -07:00
John Schmidt
66fe5bb0d8 Use libc if_nametoindex if available when parsing IPs
Fixes https://github.com/ziglang/zig/issues/10521 and makes a couple of
additional tests pass when linking libc.
2022-01-12 19:32:46 +01:00
riverbl
c4681b4889 translate-c: Fix macro define of float constant using scientific notation
Fixes compiler attempting to use null value when translating macro define of float constant using scientific notation with no decimal point
2022-01-12 13:25:50 -05:00
Jimmi Holst Christensen
a5ac138ae2 Allow BoundArray to be default initialized 2022-01-12 13:17:01 -05:00
Jimmi Holst Christensen
349a7cc272 Make prominent_compile_errors also work for test steps 2022-01-12 00:13:30 -05:00
Andrew Kelley
1a7c47d966 Merge pull request #10572 from Luukdegram/wasm-linker-stack
Stage2: wasm-linker - Place stack at the beginning of the linear memory
2022-01-11 19:41:18 -05:00
Luuk de Gram
975049e96e wasm-ld: Append --stack-first by default
By placing the stack at the start of the memory section, we prevent the runtime
from silently overwriting the global declarations and instead trap.

We do however, allow users to overwrite this behavior by setting the global-base,
which puts the stack at the end of the memory section and the static data at the base that was specified.
The reason a user would want to do this, is when they are sure the stack will not overflow and they want
to decrease the binary size as the offsets to the static memory are generally smaller.
(Having the stack in front, means that accessing the memory after the stack has a bigger offset when loading/storing from memory).
2022-01-11 20:35:44 +01:00
Luuk de Gram
f767f8e3dc wasm: Place the stack at the start of memory 2022-01-11 20:21:22 +01:00
afranchuk
7c4c49ff07 Fix a bug in std.Thread.Condition and add a basic Condition test. (#10538)
* Fix FUTEX usage in std.Thread.Condition - It was using an old name.
2022-01-11 13:04:24 -05:00
Andrew Kelley
64363b10f5 Merge pull request #10566 from fifty-six/master
std.os.uefi improvements/fixes
2022-01-11 13:02:28 -05:00
Andrew Kelley
3d89ff5130 std.fs.path: revert recent public API change
41fd343508 made a breaking change to the
public API; this commit reverts the API changes but keeps the
improved logic.
2022-01-11 11:00:19 -07:00
fifty-six
b65a884169 std/os/uefi: Add pool_allocator and raw_pool_allocator 2022-01-11 10:49:40 -07:00
fifty-six
c78a108d10 std/os/uefi: Add create_file_device_path
This allows users to add file paths to device paths, which is often used
in methods like `boot_services.loadImage` and `boot_services.startImage`,
which take a device path with an additional file path appended to locate
the image.
2022-01-11 10:49:40 -07:00
fifty-six
73e4571b4c std/os/uefi: Add methods next() and size() to DevicePathProtocol
These are used for more easily dealing with a series of Device Path
nodes.
2022-01-11 10:49:40 -07:00
fifty-six
608fceffc4 std/os/uefi: Add FileSystemInfo 2022-01-11 10:49:40 -07:00
fifty-six
b6e1613e58 std/os/uefi: Move FileInfo guid from FileProtocol to FileInfo
The GUID on FileProtocol was for EFI_FILE_INFO, FileProtocol itself doesn't
have a GUID, there are only those for the requested information types.
2022-01-11 10:49:40 -07:00
fifty-six
41fd343508 std: fix path joining on UEFI
UEFI uses `\` for paths exclusively. This changes std.fs.path to use `\`
for UEFI path joining. Also adds a few tests regarding it, specifically
in making sure double-separators do not result from path joining, as the
UEFI spec says to convert any that result from joining into single
separators (UEFI Spec Version 2.7, pg. 448).
2022-01-11 10:49:40 -07:00
Evan Haas
f4b3f1d602 translate-c: Handle typedef'ed void return type for functions.
Fixes #10356
2022-01-11 12:42:23 -05:00
Jakub Konka
6d9c02a54f zig cc: integration with sysroot arg (#10568)
Prior to this change, even if the use specified the sysroot on the
compiler line like so

```
zig cc --sysroot=/path/to/sdk
```

it would only be used as a prefix to include paths and not as a prefix
for `zig ld` linker.
2022-01-11 12:41:26 -05:00
Jakub Konka
48731ccea9 Merge branch 'Luukdegram-linker-eport-symbols' 2022-01-11 13:34:43 +01:00
Jakub Konka
014e55e761 dupe sym name from stage1 before passing to stage2 2022-01-11 13:33:53 +01:00
Jakub Konka
a615425b51 Merge branch 'linker-eport-symbols' of github.com:Luukdegram/zig into Luukdegram-linker-eport-symbols 2022-01-11 11:30:53 +01:00
djg
4731a6e5d5 std: hash_map: optimize isFree/isTombstone (#10562)
- Add an `Metadata.isFree` helper method.
- Implement `Metadata.isTombstone` and `Metadata.isFree` with `@bitCast` then comparing to a constant. I assume `@bitCast`-then-compare is faster than the old method because it only involves one comparison, and doesn't require bitmasking.
- Summary of benchmarked changes (`gotta-go-fast`, run locally, compared to master):
  - 3/4 of the hash map benchmarks used ~10% fewer cycles
  - The last one (project Euler) shows 4% fewer cycles.
2022-01-10 23:54:45 -05:00
Jakub Konka
ada8e17137 Merge pull request #10565 from Luukdegram/wasm-cast
Stage2: wasm - Implement optional equality, casts and more
2022-01-10 23:43:06 +01:00
Jakub Konka
97c6d4fb3e Build fs/filesystem libcxx module when targeting GNU Win 2022-01-10 23:40:15 +01:00
Luuk de Gram
bf46aee878 wasm: Basic 128bit integer support
This implements storing, loading and comparing 128bit integers.
TODO: Make all >64 bit integers make a call to compiler-rt for binary operations.
2022-01-10 21:03:37 +01:00
Luuk de Gram
6a9ddf244a wasm: Implement optional compare
We now pass all optionals.zig behavior tests
2022-01-10 21:01:12 +01:00
Luuk de Gram
e7b7088056 wasm: Implement float_to_int
- This implements the float_to_int AIR instruction.
- Lowering a decl_ref to a slice was previously assumed to contain a pointer
to a slice, rather than an array. This is now fixed, making `@src()` work as well.
- Some preliminary work on 128bit integers have been done to find out what needs to be done
to implement 128bit arithmetic.
2022-01-10 21:01:00 +01:00
Jakub Konka
a4e6291fbd stage2: enable zig test on x86_64-macos (#10551)
* stage2: put decls in different MachO sections

Use `getDeclVAddrWithReloc` when targeting MachO backend rather than
`getDeclVAddr` - this fn returns a zero vaddr and instead creates a
relocation on the linker side which will get automatically updated
whenever the target decl is moved in memory. This fn also records
a rebase of the target pointer so that its value is correctly slid
in presence of ASLR.

This commit enables `zig test` on x86_64-macos.

* stage2: fix output section selection for type,val pairs
2022-01-10 16:02:07 +01:00
Andrew Kelley
42ef95d79d Merge pull request #10554 from joachimschmidt557/stage2-arm
stage2 ARM: refactor and pass 1 more behavior test file
2022-01-10 01:48:49 -05:00
joachimschmidt557
b5f03b3b7a stage2 codegen: fix airBlock bug in 3 backends 2022-01-09 19:09:57 +01:00
joachimschmidt557
a1526f069a stage2 ARM: pass behavior/bool.zig 2022-01-09 19:03:45 +01:00
joachimschmidt557
77ca77cf14 stage2 ARM: make Mir.Inst.cond = .al default 2022-01-09 14:16:29 +01:00
Jakub Konka
d66c97d0ef Merge pull request #10525 from g-w1/plan9-zig-test
Plan9 zig test
2022-01-09 13:27:56 +01:00
Luuk de Gram
2a39d8063d wasm: Implement arrays 2022-01-08 19:56:07 -05:00
Andrew Kelley
7651913fd2 Merge pull request #10542 from Hejsil/stage2-bit-offset-of
Stage2 bitOffsetOf and offsetOf builtin functions
2022-01-08 15:48:14 -05:00
Robin Voetter
cc5c25d48b stage2: implement @src 2022-01-08 14:32:40 -05:00
Robin Voetter
4931b8dc93 stage2: @errorName sema+llvm 2022-01-08 14:30:11 -05:00
Jimmi Holst Christensen
5cbb35abd0 Implement bitOffsetOf
This also refactors getting struct field offsets into two
iterators. This will be useful when implementing bitCast at comptime on
structs.
2022-01-08 14:01:28 +01:00
Jimmi Holst Christensen
d8d5e2d4b9 Implement offsetOf builtin function 2022-01-08 13:00:49 +01:00
Meghan Denny
3f586781b6 std: fix zig.Ast being called Tree internally 2022-01-08 01:01:09 -05:00
Andrew Kelley
c4ab8d9e12 Merge pull request #10532 from Hejsil/stage2-bit-shifting-passing
Stage2 bit_shifting.zig passing
2022-01-08 01:00:59 -05:00
Lee Cannon
1cdc51ec10 handle error.PathAlreadyExists in renameTmpIntoCache 2022-01-07 16:50:37 -05:00
Jimmi Holst Christensen
3871d5e55a bit_shifting.zig now passes stage2 llvm backend 2022-01-07 22:10:36 +01:00
Jimmi Holst Christensen
f48f687c05 Fix llvmFieldIndex for zero sized fields
It is possible for Zig to emit field ptr instructions to fields whos
type is zero sized. In this case llvm should return a pointer which
points to the next none zero sized parameter.
2022-01-07 22:10:36 +01:00
Jimmi Holst Christensen
f78d3b27ca Increment runtime_param_index for zero sized parameters
`runtime_param_index` is used to get the parameter type from `fn_type`,
but this variable was not incremented for zero sized parameters, causing
two zero sized parameters of different type to cause miss complication.
2022-01-07 22:10:36 +01:00
Jimmi Holst Christensen
9d6bef49a5 Add two more resolution status' to Struct and Union
resolveTypeForCodegen is called when we needed to resolve a type fully,
even through pointer. This commit fully implements this, even through
pointer fields on structs and unions.

The function has now also been renamed to resolveTypeFully
2022-01-07 22:10:36 +01:00
Jimmi Holst Christensen
d5093b6c13 Shift right is a noop if rhs is comptime known to be zero 2022-01-07 22:10:36 +01:00
r00ster
dd076d8cba Add missing package to the langref that's always available 2022-01-07 14:18:47 -05:00
Jimmi Holst Christensen
a68e6cd3d7 Return Value.zero when the result of shr requires zero bits 2022-01-07 19:50:00 +01:00
Luuk de Gram
247b638ccf Pass --allow-unknown-exports to wasmtime
Also skip exporting non-function symbols when we're building a WASI command using the stage2 llvm backend.
2022-01-07 18:35:08 +01:00
Meghan
c08b190c69 lint: duplicate import (#10519) 2022-01-07 00:06:06 -05:00
Jacob G-W
398c0b10e4 Plan9: fix amount to say included line count is
Not sure why this was working before...
2022-01-06 22:58:53 -05:00
Jimmi Holst Christensen
7f4fdcc4fc stage2: Implement validating switch on errors 2022-01-06 22:57:45 -05:00
Andrew Kelley
59315463f2 ci: add test coverage for self-hosted arm and x86_64 backends 2022-01-06 22:57:29 -05:00
Jacob G-W
ab400ad624 Plan9: implement getDeclVAddr 2022-01-06 22:47:27 -05:00
Jacob G-W
4d6849ceb8 plan9 debuginfo: fix case where pc change is > 64 * inst quanta 2022-01-06 22:46:55 -05:00
Andrew Kelley
77f230ebd8 C backend is passing test/behavior/undefined.zig
closes #10505
2022-01-06 13:07:38 -07:00
Luuk de Gram
6d951aff7e wasm-linker: Only export symbols notated as such
This exposes a function from stage2 to stage1 to append symbols to automatically export them.

This happends under the following conditions:
- Target is wasm
- User has not provided --export/--rdynamic flags themselves.
2022-01-06 20:19:47 +01:00
Jakub Konka
0772fb0518 Merge pull request #10518 from ziglang/stage2-x86_64-zig-test-fixes
stage2: fix x86_64 backend to actually correctly run Zig tests!
2022-01-06 15:31:39 +01:00
Jacob G-W
b47530b9fe plan9: fix .z symbol in debuginfo
This allows the `acid` debugger on
plan9 to be used to debug a zig source
file without patching `acid`!

The patch adds a second `z` symbol. This z
symbol has a value of 0, which means that it
pops the history stack. We put a very large
number for the value of the second symbol because
it has to be at least as large as the linecount of
the file. The debuginfo format is meant to be used
with c files, where the stack would look something
like this:
```
->  Line: 0x1 (1)  Name: 0x1/0x2/0x3/0xe/0x13/0x1b (/sys/src/libc/port/malloc.c)
->  Line: 0x2 (2)  Name: 0x1/0x6/0x7/0x8 (/amd64/include/u.h)
->  Line: 0x4f (79)  Name:  ()
->  Line: 0x50 (80)  Name: 0x1/0x2/0x7/0x9 (/sys/include/libc.h)
->  Line: 0x358 (856)  Name:  ()
->  Line: 0x359 (857)  Name: 0x1/0x2/0x7/0x1c (/sys/include/pool.h)
->  Line: 0x392 (914)  Name:  ()
->  Line: 0x393 (915)  Name: 0x1/0x2/0x7/0x1d (/sys/include/tos.h)
->  Line: 0x3ab (939)  Name:  ()
->  Line: 0x4eb (1259)  Name:  ()
```
however in zig, we do not use includes and .h files,
so we only need the first and last items in the stack:
the source file that the symbols belong to, and the pop
symbol with a null name and a value of the total linecount of the
preprocessed source. Since there is no preprocessing in zig, we
just make the linecount very large. There do not appear to be
any downsides to this approach. If this causes a bug in the future,
a simple fix would be to make the pop symbol just have the value
of how many newlines are in the source file.
2022-01-06 13:17:00 +01:00
Jakub Konka
97e76bf36c stage2: temporarily disable offending stage2 test on macOS
Another caveat, `zig test` doesn't currently work on stage2.
2022-01-06 12:57:34 +01:00
Jakub Konka
a124192fb0 stage2: implement basics of airWrapErrUnionErr
Enable more behavior tests for x86_64.
2022-01-06 10:12:01 +01:00
Jakub Konka
ee6e9b3c48 stage2: fix airStructFieldPtr and airStructFieldVal
This finally fixes `zig test`.
2022-01-06 09:54:33 +01:00
Jakub Konka
b215241ef2 stage2: fix airSliceElemVal
Refactor codegen and fix a bug in Isel.
2022-01-06 09:54:33 +01:00
Jakub Konka
f4aa276a0c stage2: fix inline memcpy 2022-01-06 09:54:33 +01:00
Jakub Konka
f01e6eec56 stage2: implement slice_ptr 2022-01-06 09:54:33 +01:00
Jakub Konka
2b77775cbb stage2: fix loading pointer value from register
Fix accessing optional payload.
2022-01-06 09:54:33 +01:00
Jakub Konka
b3f70db438 stage2: implement CMP stack value with immediate 2022-01-06 09:54:33 +01:00
Andrew Kelley
1d55e4cae1 zig fmt 2022-01-06 01:18:54 -07:00
Andrew Kelley
8c6175c134 Sema: const inferred alloc infers comptime-ness
const locals now detect if the value ends up being comptime known. In
such case, it replaces the runtime AIR instructions with a decl_ref
const.

In the backends, some more sophisticated logic for marking decls as
alive was needed to prevent Decls incorrectly being garbage collected
that were indirectly referenced in such manner.
2022-01-06 00:52:10 -07:00
Andrew Kelley
713d2a9b38 Sema: better code generated for struct literals
Add a variant of the `validate_struct_init` ZIR instruction:
`validate_struct_init_comptime` which is the same thing except it
indicates a comptime scope.

Sema code for this instruction now handles default struct field
values and detects when the struct initialization resulted in a
comptime value, replacing the already-emitted AIR instructions
to store each individual field with a single `store` instruction
with a comptime struct value as the operand.

In the case of a comptime scope, there is a simpler path that only
evals the implicit store instructions for default field values, avoiding
the mechanism for detecting comptime values.

This regressed one test case for the wasm backend, but it's just hitting
a different prong of `emitConstant` which currently has "TODO" in there,
so I think it's fine.
2022-01-04 23:49:49 -07:00
Andrew Kelley
4bc6b4925c std.builtin: remove deprecated globals 2022-01-04 18:28:42 -07:00
Andrew Kelley
1c24ef0d0b stage2: introduce std.builtin.CompilerBackend
This allows Zig code to perform conditional compilation based on a tag
by which a Zig compiler implementation identifies itself.

See the doc comment in this commit for more details.
2022-01-04 18:12:45 -07:00
Andrew Kelley
5087ec6f41 Merge pull request #10508 from Luukdegram/wasm-behavior-tests
Stage2: wasm - Pass more behavior tests
2022-01-04 14:54:50 -05:00
Luuk de Gram
89b1fdc443 wasm: Implement memset, and sret arguments.
We now detect if the return type will be set by passing the first argument
as a pointer to stack memory from the callee's frame. This way, we do not have to
worry about stack memory being overwritten.

Besides this, we implement memset by either using wasm's memory.fill instruction when available,
or lower it manually. In the future we can lower this to a compiler_rt call.
2022-01-04 17:59:05 +01:00
Luuk de Gram
5c21a45cf0 wasm: Implement 'slice' instruction
Emitting undefined ptr's also has been implemented.
This means we now pass the void.zig behavior tests.
2022-01-04 17:51:49 +01:00
Luuk de Gram
c888485f85 wasm: Fix lowering constant struct values to the stack
We now get the null.zig, this.zig and member_func.zig behavior tests passing.
2022-01-04 17:51:24 +01:00
Luuk de Gram
c519d9c80e wasm: Implement (and fix) most optional instructions
Previously we were performing the wrapping and unwrapping operations incorrectly.
We now correctly create the type and set its values.
Besides this, we also set the null-byte to the incorrect value, which meant we were
doing the opposite action of a is_null check. This is now fixed as well.

While implementing this, I found a small bug in the wrapErrUnionPayload where we
would load a pointer value and save that, rather than store the pointer with the error.
This is now fixed as well, by copying the entire operand into the payload of the error union.
2022-01-04 17:46:58 +01:00
Andrew Kelley
5c228765f1 Merge pull request #10504 from ziglang/linker-plumbing
linker: fix build-obj and -fno-emit-bin
2022-01-04 04:54:30 -05:00
Ryan Liptak
3c87d4e14e Add CANNOT_DELETE as a possible error in os.windows.DeleteFile
Can happen when e.g. trying to delete a file with the Read Only flag set
2022-01-04 02:15:29 -05:00
Andrew Kelley
5b0be0d436 Merge pull request #10499 from paulsnar/paulsnar/stage1-packed-structs-cabi
stage1: Fix LLVM C ABI type resolution for small packed structs
2022-01-04 02:14:29 -05:00
Vincent Rischmann
6630a5ede5 io_uring: improve IO_Uring.copy_cqe
copy_cqes() is not guaranteed to return as many CQEs as provided in the
`wait_nr` argument, meaning the assert in `copy_cqe` can trigger.

Instead, loop until we do get at least one CQE returned.

This mimics the behaviour of liburing's _io_uring_get_cqe.
2022-01-04 02:13:41 -05:00
Andrew Kelley
b6d6152e65 link: avoid creating stage2 llvm module when using stage1 2022-01-04 00:11:45 -07:00
Andrew Kelley
76fd6fc365 Merge pull request #10503 from ziglang/stage2-x86_64-zig-test
stage2: enable "zig test" on x86_64
2022-01-04 01:53:02 -05:00
Andrew Kelley
ff66a18555 linker: fix build-obj and -fno-emit-bin
This commit fixes two problems:

* `zig build-obj` regressed from the cache-mode branch. It would crash
  because it assumed that dirname on the emit bin path would not be
  null. This assumption was invalid when outputting to the current
  working directory - a pretty common use case for `zig build-obj`.

* When using the LLVM backend, `-fno-emit-bin` combined with any other
  kind of emitting, such as `-femit-asm`, emitted nothing.

Both issues are now fixed.
2022-01-03 20:03:22 -07:00
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
Andrew Kelley
4e38b3ed9b readme: dynamic logo light/dark 2022-01-03 17:45:09 -07:00
Jakub Konka
aad20ce92c stage2: pass empty zig test 2022-01-04 01:21:24 +01:00
Jakub Konka
47ed87dab8 stage2: implement struct_field_val and struct_field_val_ptr
Handle function pointers in airCall
2022-01-04 01:21:24 +01:00
Jakub Konka
384b19716d stage2: implement inline memcpy 2022-01-04 01:21:24 +01:00
Jakub Konka
d288f202a4 stage2: implement slice_elem_val 2022-01-04 01:21:24 +01:00
Jakub Konka
e9f069f536 stage2: implement isErr/isNonErr and unwrap error 2022-01-04 01:21:24 +01:00
Jakub Konka
818672312f stage2: implement setting stack from memory value 2022-01-04 01:21:23 +01:00
Jakub Konka
5851e81284 stage2: clean up load function 2022-01-04 01:21:23 +01:00
Jakub Konka
3f7b09bd35 stage2: re-implement arithmetic ops with SIB 2022-01-04 01:21:23 +01:00
Jakub Konka
f37598c779 stage2: clean up encoding of memory operands 2022-01-04 01:21:23 +01:00
Jakub Konka
978de70381 stage2: add helper for encoding imm32 based on target size 2022-01-04 01:21:23 +01:00
Jakub Konka
7a8a630bb2 stage2: dedup DS/RIP encoding for memory operand in Isel 2022-01-04 01:21:23 +01:00
Jakub Konka
8628bb780f stage2: use Encoder.prefix16BitMode() helper to encode 0x66 prefix 2022-01-04 01:21:23 +01:00
Jakub Konka
09bfc122fa stage2: dedup encoding memory op with base register in Isel 2022-01-04 01:21:23 +01:00
Jakub Konka
4590820c4c stage2: implement slice_len for slices on the stack 2022-01-04 01:21:23 +01:00
Jakub Konka
aeff635863 stage2: fix loading ptr into register 2022-01-04 01:21:23 +01:00
Andrew Kelley
81fa31c054 Merge pull request #10451 from ziglang/cache-mode
stage2: introduce CacheMode
2022-01-03 16:50:29 -05:00
Andrew Kelley
d94303be2b stage2: introduce renameTmpIntoCache into the linker API
Doc comments reproduced here:

This function is called by the frontend before flush(). It communicates that
`options.bin_file.emit` directory needs to be renamed from
`[zig-cache]/tmp/[random]` to `[zig-cache]/o/[digest]`.
The frontend would like to simply perform a file system rename, however,
some linker backends care about the file paths of the objects they are linking.
So this function call tells linker backends to rename the paths of object files
to observe the new directory path.
Linker backends which do not have this requirement can fall back to the simple
implementation at the bottom of this function.
This function is only called when CacheMode is `whole`.

This solves stack trace regressions on Windows and macOS because the
linker backends do not observe object file paths until flush().
2022-01-03 14:49:35 -07:00
paulsnar
0736d30774 stage1: Add tests for packed structs in C ABI 2022-01-03 21:25:48 +02:00
paulsnar
822c3a4819 stage1: Resolve LLVM C ABI type for small packed structs
Small packed structs weren't included in this resolution so their
c_abi_type would be NULL when attempting usage later, leading to a
compiler crash.

Resolves #10431.
2022-01-03 21:23:50 +02:00
Andrew Kelley
850b053ea6 Merge pull request #10492 from Snektron/stage2-some-stuff
stage 2 stuff
2022-01-03 05:20:08 -05:00
Andrew Kelley
663ffa5a7a stage2: fix missing items from whole cache mode hash
Without this, Zig would re-use a compiler-rt built with stage2 when one
built by stage1 was needed.
2022-01-02 18:54:47 -07:00
Robin Voetter
67449b659d stage2: move some more tests 2022-01-03 02:09:54 +01:00
Andrew Kelley
5e086b2b4c compiler-rt: small refactor in atomics 2022-01-02 17:58:54 -07:00
Andrew Kelley
d3f87f8ac0 std.fs.rename: fix Windows implementation
The semantics of this function are that it moves both files and
directories. Previously we had this `is_dir` boolean field of
`std.os.windows.OpenFile` which required the API user to choose: are we
opening a file or directory? And the other kind would either cause
error.IsDir or error.NotDir. But that is not a limitation of the Windows
file system API; it was self-imposed.

On Windows, rename is implemented internally with `NtCreateFile` so we
need to allow it to open either files or directories. This is now done
by `std.os.windows.OpenFile` accepting enum{file_only,dir_only,any}
instead of a boolean.
2022-01-02 16:58:05 -08:00
Robin Voetter
7f77d3d671 stage2: pointer reify 2022-01-03 01:56:59 +01:00
Robin Voetter
41e52bd5cc stage2: don't call comptime functions with generic poison arguments
When calling a comptime or inline function, if the parameter is generic and
is resolved to generic_poison or generic_poison_type, the invocation was
part of another function's parameters or return type expression and is
dependent on an as-of-yet type of another parameter. In this case, processing
should stop, and we return error.GenericPoison to let the caller in funcCommon,
zirParam or zirParamAnytype know that the function is generic.
2022-01-03 00:19:59 +01:00
Andrew Kelley
b4d6e85a33 Sema: implement peer type resolution of signed and unsigned ints
This allows stage2 to build more of compiler-rt.

I also changed `-%` to `-` for comptime ints in the div and mul
implementations of compiler-rt. This is clearer code and also happens to
work around a bug in stage2.
2022-01-02 14:11:37 -07:00
Andrew Kelley
6b14c58f63 compiler-rt: simplify implementations
This improves readability as well as compatibility with stage2. Most of
compiler-rt is now enabled for stage2 with just a few functions disabled
(until stage2 passes more behavior tests).
2022-01-02 13:16:17 -07:00
Andrew Kelley
9dc25dd0b6 stage2: fix UAF of system_libs 2022-01-02 13:16:17 -07:00
Andrew Kelley
55243cfb31 stage2: fix implibs
Broken by the introduction of `CacheMode.whole`, they are now working
again by using the same mechanism as emitted binary files.
2022-01-02 13:16:17 -07:00
Andrew Kelley
013c286e43 stage2: fix memory leak in addNonIncrementalStuffToCacheManifest
I accidentally used errdefer instead of defer for the function-local
arena.
2022-01-02 13:16:17 -07:00
Andrew Kelley
73ba6bf30b stage2: fix memory leak of emit_bin.sub_path
Instead of juggling GPA-allocated sub_path (and ultimately dropping the
ball, in this analogy), `Compilation.create` allocates an
already-exactly-correct size `sub_path` that has the digest unpopulated.

This is then overwritten in place as necessary and used as the
`emit_bin.sub_path` value, and no allocations/frees are performed for
this file path.
2022-01-02 13:16:17 -07:00
Andrew Kelley
208a6c7d6a stage2: fix not calling deinit() on whole_cache_manifest
Need to mark it as "needing cleanup" a bit earlier in the function.
2022-01-02 13:16:17 -07:00
Andrew Kelley
0ad2a99675 stage2: CacheMode.whole: trigger loading zig source files
Previously the code asserted source files were already loaded, but this
is not the case when cached ZIR is loaded. Now it will trigger .zig
source code to be loaded for the purposes of hashing the source for
`CacheMode.whole`.

This additionally refactors stat_size, stat_inode, and stat_mtime fields
into using the `Cache.File.Stat` struct.
2022-01-02 13:16:17 -07:00
Andrew Kelley
dbd0a2c35d stage2: fix path to cache artifacts in libcxx,
libtsan, libunwind, and libcxxabi.
2022-01-02 13:16:17 -07:00
Andrew Kelley
d6c5602d46 stage2: fix CLI not populating output binary files
This fixes a regression in this branch that can be reproduced with the
following steps:

1. `zig build-exe hello.zig`
2. delete the "hello" binary
3. `zig build-exe hello.zig`
4. observe that the "hello" binary is missing

This happened because it was a cache hit, but nothing got copied to the
output directory.

This commit sets CacheMode to incremental - even for stage1 - when the
CLI requests `disable_lld_caching` (this option should be renamed),
resulting in the main Compilation to be repeated (uncached) for stage1,
populating the binary into the cwd as expected.

For stage2 the result is even better: the incremental compilation system
will look for build artifacts to incrementally compile, and start fresh
if not found.
2022-01-02 13:16:17 -07:00
Andrew Kelley
e36718165c stage2: add @import and @embedFile to CacheHash
when using `CacheMode.whole`. Also, I verified that `addDepFilePost` is
in fact including the original C source file in addition to the files it
depends on.
2022-01-02 13:16:17 -07:00
Andrew Kelley
67e31807df stage2: CacheMode.whole fixes
* Logic to check whether a bin file is not emitted is more complicated
   in between `Compilation.create` and `Compilation.update`. Fixed the
   logic that decides whether to build compiler-rt and other support
   artifacts.
 * Basically, one cannot inspect the value of `comp.bin_file.emit` until
   after update() is called - fixed another instance of this happening
   in the CLI.
 * In the CLI, `runOrTest` is updated to properly use the result value
   of `comp.bin_file.options.emit` rather than guessing whether the
   output binary is.
 * Don't assume that the emit output has no directory components in
   sub_path. In other words, don't assume that the emit directory is the
   final directory; there may be sub-directories.
2022-01-02 13:16:17 -07:00
Andrew Kelley
e3bed8d81d stage2: introduce CacheMode
The two CacheMode values are `whole` and `incremental`.
`incremental` is what we had before; `whole` is new.
Whole cache mode uses everything as inputs to the cache hash;
and when a hit occurs it skips everything including linking.
This is ideal for when source files change rarely and for backends that
do not have good incremental compilation support, for example
compiler-rt or libc compiled with LLVM with optimizations on.
This is the main motivation for the additional mode, so that we can have
LLVM-optimized compiler-rt/libc builds, without waiting for the LLVM
backend every single time Zig is invoked.

Incremental cache mode hashes only the input file path and a few target
options, intentionally relying on collisions to locate already-existing
build artifacts which can then be incrementally updated.

The bespoke logic for caching stage1 backend build artifacts
is removed since we now have a global caching mechanism for
when we want to cache the entire compilation, *including* linking.
Previously we had to get "creative" with libs.txt and a special
byte in the hash id to communicate flags, so that when the cached
artifacts were re-linked, we had this information from stage1
even though we didn't actually run it. Now that `CacheMode.whole`
includes linking, this extra information does not need to be
preserved for cache hits. So although this changeset introduces
complexity, it also removes complexity.

The main trickiness here comes from the inherent differences between the
two modes: `incremental` wants a directory immediately to operate on,
while `whole` doesn't know the output directory until the compilation is
complete. This commit deals with this problem mostly inside `update()`,
where, on a cache miss, it replaces `zig_cache_artifact_directory` with a
temporary directory, and then renames it into place once the compilation is
complete.

Items remaining before this branch can be merged:

* [ ] make sure these things make it into the cache manifest:
  - @import files
  - @embedFile files
  - we already add dep files from c but make sure the main .c files make
    it in there too, not just the included files

* [ ] double check that the emit paths of other things besides the binary
  are working correctly.

* [ ] test `-fno-emit-bin` + `-fstage1`
* [ ] test `-femit-bin=foo` + `-fstage1`

* [ ] implib emit directory copies bin_file_emit directory in create() and needs
  to be adjusted to be overridden as well.

* [ ] make sure emit-h is handled correctly in the cache hash
* [ ] Cache: detect duplicate files added to the manifest

Some preliminary performance measurements of wall clock time and
peak RSS used:

stage1 behavior (1077 tests), llvm backend, release build:
 * cold global cache: 4.6s, 1.1 GiB
 * warm global cache: 3.4s, 980 MiB

stage2 master branch behavior (575 tests), llvm backend, release build:
 * cold global cache: 0.62s, 191 MiB
 * warm global cache: 0.40s, 128 MiB

stage2 this branch behavior (575 tests), llvm backend, release build:
 * cold global cache: 0.62s, 179 MiB
 * warm global cache: 0.27s, 90 MiB
2022-01-02 13:16:17 -07:00
joachimschmidt557
c710d5eefe stage2 ARM: implement wrap_errunion_err for empty payloads 2022-01-02 15:15:59 -05:00
Andrew Kelley
36b069910e Merge pull request #10456 from Aransentin/master
Support parsing tz timezone data
2022-01-02 15:15:04 -05:00
Andrew Kelley
ae8d6fd7b7 behavior tests: add a "passing for arm backend" section 2022-01-01 14:00:02 -07:00
Andrew Kelley
98e84152bd Merge pull request #10481 from Luukdegram/wasm-behavior-tests
Stage2: wasm - Implement more behavior tests
2022-01-01 15:41:26 -05:00
Jimmi Holst Christensen
a41ad639a8 fmt: Refactor parsing of placeholders into its own function
This saves on comptime format string parsing, as the compiler caches
comptime calls. The catch here, is that parsePlaceHolder cannot take the
placeholder string as a slice. It must take it as an array by value for
the caching to occure.

There is also some logic in here that ensures that the specifier_arg is
always them same slice when the items they contain are the same. This
makes the compiler stamp out less copies of formatType.
2022-01-01 15:40:24 -05:00
Vincent Rischmann
0662f1d522 io_uring: fix version check in tests
For renameat, unlinkat, mkdirat, symlinkat and linkat the error code
differs between kernel 5.4 which returns EBADF and kernel 5.10 which returns EINVAL.

Fixes #10466
2022-01-01 15:37:50 -05:00
Jakub Konka
885d96735d Merge pull request #10480 from joachimschmidt557/stage2-arm
stage2 ARM: zig test working
2022-01-01 17:02:31 +01: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
Jakub Konka
557268a448 stage2: augment stage2 test to test optional payload lowering 2022-01-01 14:29:31 +01:00
Jakub Konka
0e3cd5bb1e stage2: remove safety check for optional payload in codegen
This will be enforced by Sema.
2022-01-01 14:27:06 +01:00
Jens Goldberg
a54788ba7a Support legacy TZ format, expose header struct to a potential writer 2022-01-01 12:47:08 +00: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
joachimschmidt557
a722e1fc0b stage2 codegen: Add generateSymbol for optional stub 2022-01-01 12:51:29 +01:00
joachimschmidt557
845531dde1 stage2 ARM: implement airUnwrapErrErr + airCmp for error sets 2022-01-01 11:16:38 +01:00
joachimschmidt557
f8163f7eaf stage2 ARM: implement airCall for function pointers 2022-01-01 11:16:34 +01:00
r00ster
b100e2ec2a std.fmt: improve @compileError message 2022-01-01 10:29:36 +02:00
Marian Beermann
55709de185 stage1: fix @errorName null termination 2022-01-01 10:28:47 +02:00
Frank Denis
cea6e8b2d8 Y++ 2021-12-31 19:58:21 -05:00
Jens Goldberg
cb06f6f984 Remove a no-op line that was left in by mistake 2021-12-31 22:57:06 +00:00
Jakub Konka
7c1e17a840 Merge pull request #10470 from ziglang/stage2-x86_64-null-non-null
stage2: impl isNull/isNonNull, genSetReg for ptr_stack_offset, loading-storing via pointer (in register)
2021-12-31 20:31:51 +01:00
Jens Goldberg
9a56435666 tz parsing reader interface, test thicc files, and exclude tzif 2021-12-31 17:17:49 +00:00
Jakub Konka
c7f774803a stage2: implement loading-storing via pointer (in register)
* load address (pointer) to a stack variable in a register via
  `lea` instruction
* store value on the stack via a pointer stored in a register via
  `mov [reg], imm` instruction
* the lowerings naturally are handled automatically by Mir -> Isel
  layer
* add initial (without safety) implementation of `.optional_payload`
* add matching stage2 test cases
2021-12-31 18:10:28 +01:00
Jakub Konka
bc12d50170 stage2: implement genSetReg for ptr_stack_offset 2021-12-31 15:13:03 +01:00
Jakub Konka
5ec9f39dfe stage2: implement isNull() and isNonNull() 2021-12-31 15:07:48 +01:00
Jakub Konka
e7ac05e882 stage2: rename Emit to Isel for x86_64 2021-12-31 11:18:23 +01:00
Jarred Sumner
2d9508780a For unused references & redundant keywords, append the compiler error but continue running AstGen 2021-12-30 22:45:43 -05:00
Andrew Kelley
4645ec89f7 Merge pull request #10455 from joachimschmidt557/stage2-arm
stage2 ARM: basic slice + basic struct support
2021-12-30 15:25:36 -05: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
joachimschmidt557
726ee671be stage2 x86_64: add regression test for #7187 2021-12-30 15:12:38 -05:00
Jens Goldberg
e4672c95f1 Actually expose the tz file 2021-12-30 18:20:29 +00:00
Jens Goldberg
bc5c467755 Support parsing tz timezone data 2021-12-30 15:12:20 +00:00
joachimschmidt557
69d03d3a29 stage2 ARM: implement struct_field_ptr and struct_field_val 2021-12-30 14:39:06 +01:00
joachimschmidt557
ac7fa95af4 stage2 ARM: add genArmInlineMemcpy for copying types with size > 4 2021-12-30 14:24:03 +01:00
Andrew Kelley
06286b05a4 Merge pull request #10446 from ziglang/stage2-x86_64-mov-mem-imm
stage2: more fixes to x86_64 codegen, mir and isel
2021-12-29 22:22:26 -05:00
Jakub Konka
4ecc5956f6 stage2: update PrintMir with latest instructions and Isel changes 2021-12-29 22:06:38 +01:00
Jakub Konka
b7e2235973 stage2: lower 1-byte and 2-byte values saved to stack
* fix handling of `ah`, `bh`, `ch`, and `dh` registers (which are
  actually used as aliases to `dil`, etc. registers). Currenly, we
  treat them as aliases only meaning when we encounter `ah` we make
  sure to set the REX.W to promote the instruction to 64bits and use
  `dil` register instead - otherwise we might have mismatch between
  registers used in different parts of the codegen. In the future,
  we can and should use `ah`, etc. as upper 8bit halves of 16bit
  registers `ax`, etc.
* fix bug in `airCmp` where `.cmp` MIR instruction shouldn't force
  type `Bool` but let the type of the original type propagate downwards
  - we need this to make an informed choice of the target register
  size and hence choose the right encoding down the line.
* implement lowering of 1-byte and 2-byte values to stack and add
  matching stage2 tests for x86_64 codegen
2021-12-29 22:06:38 +01:00
Jakub Konka
08ea1a2eab stage2: add separate tag for MI encoding
To request memory-immediate encoding at the MIR side, we should now
use a new tag such as `mov_mem_imm` where the size of the memory
pointer is encoded as the flags:

```
0b00 => .byte_ptr,
0b01 => .word_ptr,
0b10 => .dword_ptr,
0b11 => .qword_ptr,
```
2021-12-29 22:06:38 +01:00
joachimschmidt557
baec07cfcd stage2 ARM: change MCValue.immediate to u32 2021-12-29 11:27:37 +01:00
joachimschmidt557
96e59fd1c2 stage2 ARM: implement slice_elem_val for sizes > 4 2021-12-29 11:08:48 +01: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
efb7148a45 Sema: more union fixes
* `Module.Union.getLayout`: fixes to support components of the union
   being 0 bits.
 * Implement `@typeInfo` for unions.
 * Add missing calls to `resolveTypeFields`.
 * Fix explicitly-provided union tag types passing a `Zir.Inst.Ref`
   where an `Air.Inst.Ref` was expected. We don't have any type safety
   for this; these typess are aliases.
 * Fix explicitly-provided `union(enum)` tag Values allocated to the
   wrong arena.
2021-12-28 23:22:09 -07:00
Andrew Kelley
91619cdf57 Sema: implement calling a fn ptr via a union field
Also, ignore `packed` on unions because that will be removed from the
language.
2021-12-28 23:22:09 -07:00
Tom Manner
2dd7255713 Fixed typo in deprecation error for E format specifier where it would instead complain about a specifier of X. 2021-12-29 01:02:04 -05:00
Andrew Kelley
81a3910e44 Sema: improve union support
* reduce number of branches in zirCmpEq
 * implement equality comparison for enums and unions
 * fix coercion from union to its tag type resulting in the wrong type
 * fix method calls of unions
 * implement peer type resolution for unions, enums, and enum literals
 * fix union tag type memory in the wrong arena
2021-12-28 20:20:30 -07:00
Andrew Kelley
6229d37dcf stage2: handle function dependency failures without crashing 2021-12-28 20:20:30 -07:00
joachimschmidt557
c0ae9647f9 stage2 ARM: implement slice_elem_val for types with size <= 4 2021-12-28 20:38:37 -05:00
Veikka Tuominen
4f4f0bc6f0 stage1: fix access of slice sentinel at comptime 2021-12-28 14:44:46 +02:00
Andrew Kelley
4b9b9e7257 stage2: LLVM backend: fix lowering of union constants
Comment from this commit reproduced here:

LLVM does not allow us to change the type of globals. So we must
create a new global with the correct type, copy all its attributes,
and then update all references to point to the new global,
delete the original, and rename the new one to the old one's name.
This is necessary because LLVM does not support const bitcasting
a struct with padding bytes, which is needed to lower a const union value
to LLVM, when a field other than the most-aligned is active. Instead,
we must lower to an unnamed struct, and pointer cast at usage sites
of the global. Such an unnamed struct is the cause of the global type
mismatch, because we don't have the LLVM type until the *value* is created,
whereas the global needs to be created based on the type alone, because
lowering the value may reference the global as a pointer.
2021-12-28 01:53:58 -07:00
Andrew Kelley
232f8a291d stage2: fix build on 32-bit targets
Regressed in 85d4c8620f.
2021-12-28 01:15:36 -07:00
Andrew Kelley
85d4c8620f Sema: implement array coercion 2021-12-27 22:06:23 -07:00
Ali Chraghi
042b770d62 std: Skip comptime struct fields in mem.zeroes() (#10406)
closes #9934
2021-12-27 23:33:11 -05:00
Andrew Kelley
6ed7850972 Sema: fix anytype parameters whose types require comptime 2021-12-27 19:39:28 -07:00
Andrew Kelley
fc1a5cd9e7 Sema: implement @tagName for enum literals 2021-12-27 18:10:24 -07:00
Andrew Kelley
9dd4fb4130 stage2: fix 0-bit function parameters
Before this commit, Zig would incorrectly emit `arg` AIR instructions
for parameters whose types were 0-bit.
2021-12-27 17:56:33 -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
Frank Denis
3abe464b06 crypto/edwards25519: faster point decompression
Make recovery of the x-coordinate slightly faster.

See https://mailarchive.ietf.org/arch/msg/cfrg/qlKpMBqxXZYmDpXXIx6LO3Oznv4/
for details.
2021-12-27 14:42:58 -08: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
Jan Philipp Hafer
17046674a7 compiler_rt: add __negvsi2, __negvdi2, __negvti2
- neg can only overflow, if a == MIN
- case `-0` is properly handled by hardware, so overflow check by comparing
  `a == MIN` is sufficient
- tests: MIN, MIN+1, MIN+4, -42, -7, -1, 0, 1, 7..

See #1290
2021-12-27 14:35:45 -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
daurnimator
2c23699594 Bcrypt pbkdf (#10331)
* Make bcrypt State struct public

This is useful to implement the various protocols outside of the standard library

* Implement bcrypt pbkdf

This variant is used in e.g. SSH
The OpenBSD implementation was used as a reference
2021-12-27 21:59:32 +01: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
Andrew Kelley
f41b9cdb6d Sema: fix enum tag type not initialized when 0 fields 2021-12-26 21:36:12 -07:00
Andrew Kelley
629a54c711 Sema: improve non-exhaustive enum support
* remove false positive "all prongs handled" compile error for
   non-exhaustive enums.
 * implement `@TypeInfo` for enums, except enums which have any
   declarations is still TODO.
 * `getBuiltin` uses nomespaceLookup/analyzeDeclVal rather than
   namespaceLookupRef/analyzeLoad. Avoids a detour through an
   unnecessary type, and adds a detour through a caching mechanism.
 * `Value.eql`: add missing code to handle enum comparisons for
   non-exhaustive enums. It works by converting the enum tags to numeric
   values and comparing those.
2021-12-26 21:07:16 -07:00
Jan Philipp Hafer
405ff911da compiler_rt: add __absvsi2, __absvdi2, __absvti2
- abs can only overflow, if a == MIN
- comparing the sign change from wrapping addition is branchless
- tests: MIN, MIN+1,..MIN+4, -42, -7, -1, 0, 1, 7..

See #1290
2021-12-26 13:21:18 -08:00
Andrew Kelley
71923d7e40 Merge pull request #10414 from joachimschmidt557/stage2-arm
stage2 ARM: Implement airLoad for slices
2021-12-26 13:18:55 -08:00
joachimschmidt557
8a0e86cd5c stage2 ARM: implement load for types with size 8 (e.g. slices) 2021-12-26 17:05:08 +01:00
joachimschmidt557
15f0f9240d stage2 codegen: Implement generateSymbol for undefined values 2021-12-26 16:40:51 +01:00
Andrew Kelley
6b8e33d14c stage2: LLVM: fix lowering of packed structs
* ensure enough capacity when building the LLVM type and value.
 * add explicit padding field and populate it to ensure proper
   alignment.
2021-12-24 02:37:54 -07:00
Andrew Kelley
5b171f446f stage2: initial implementation of packed structs
Layout algorithm: all `align(0)` fields are squished together as if they
were a single integer with a number of bits equal to `@bitSizeOf` each
field added together. Then the natural ABI alignment of that integer is
used for that pseudo-field.
2021-12-23 23:57:02 -07:00
Andrew Kelley
3763580e1e add missing files to CMakeLists 2021-12-23 17:48:58 -07:00
Andrew Kelley
0049c7180f Merge pull request #10394 from ziglang/stage2-x86_64-mir-intel-syntax
stage2: rewrite MIR -> Isel layer for x86_64
2021-12-23 16:39:51 -08:00
Andrew Kelley
4c11986650 MIR: remove unnecessary TODO comment
it wouldn't save any bytes in the MIR, and we can just check the range of the value when lowering the MIR to machine code.
2021-12-23 16:39:28 -08:00
Jakub Konka
35fe088e0e stage2: add lowering of RMI encoding
Example includes imul with 3 operands such as imul r64, r/m64, imm32.
2021-12-23 21:14:14 +01:00
Jakub Konka
dba5df64ea stage2: use lowerToRmEnc to lower two-operand imul
Fix mismatched register sizes in codegen.
2021-12-23 20:51:48 +01:00
Jakub Konka
c50bb2b80f stage2: lower jcc and setcc conditional jump/set instructions 2021-12-23 20:29:34 +01:00
Jakub Konka
8c664d3f6a stage2: support multibyte opcodes and refactor 1byte opcode changes 2021-12-23 18:49:40 +01:00
Jakub Konka
d23a1487bd stage2: add lowering of ZO encoding
ZO (probably) stands for zero operands encoding which is effectively
only the opcode.
2021-12-23 18:49:40 +01:00
Jakub Konka
a70b4068c6 stage2: add lowering to I encoding
Examples include push imm32.
2021-12-23 10:22:23 +01:00
Jakub Konka
b657956c44 stage2: add lowering to O encoding
Example includes push/pop register.
2021-12-23 09:47:38 +01:00
Andrew Kelley
303bad9989 behavior tests: stage2 is not yet passing this test
Looks like I repeated the same mistake, which last time was addressed in
1e0addcf73.
2021-12-22 20:48:53 -07:00
Andrew Kelley
cc937369fb stage2: Type.hasCodeGenBits asserts structs and unions have fields
Previously, this function would return an incorrect result for structs
and unions which did not have their fields resolved yet.

This required introducing more logic in Sema to resolve types before
doing certain things such as creating an anonmyous Decl and emitting
function call AIR.

As a result a couple more struct tests pass.

Oh, and I implemented the language change to make sizeOf for pointers
always return pointer size bytes even if the element type is 0 bits.
2021-12-22 20:29:26 -07:00
Luuk de Gram
e061d75cdf wasm-linker: Implement symbol names emitting
The linker will now emit names for all function, global and data segment symbols.
This increases the ability to debug wasm modules tremendously as tools like wasm2wat
can use this information to generate named functions, globals etc, rather than placeholders such as $f1.
2021-12-23 01:47:45 +01:00
Jakub Konka
603f826779 stage2: migrate push/pop r/m64 to new lowering mechanism 2021-12-23 01:30:25 +01:00
Jakub Konka
9078cb0197 stage2: add lowering of M encoding
Examples include jmp / call near with memory or register operand
like `jmp [rax]`, or even RIP-relative `call [rip + 0x10]`.
2021-12-23 01:22:07 +01:00
Jakub Konka
1167e248ef stage2: add lowering of D encoding
Example of such encoding includes a near/far call and jmp instructions.
2021-12-23 00:43:38 +01:00
Jakub Konka
362eccf539 stage2: handle RIP relative addressing in MI, RM and MR 2021-12-22 23:07:46 +01:00
Jakub Konka
b40e5adf54 stage2: add lowering for FD/TD encodings 2021-12-22 22:36:56 +01:00
Jakub Konka
b9a6f81d1a stage2: add lowering fn for OI encoding
Implement movabs using OI generic encoding.
2021-12-22 19:01:43 +01:00
Jakub Konka
2b5de9403d stage2: create generic lowering fns for MI, RM, and MR encodings
This way I am hopeful they can be reused for every MIR lowering
function which follows a given encoding. Currently, support MI,
RM and MR encodings without SIB scaling.
2021-12-22 18:10:52 +01:00
Dante Catalfamo
3bd0575cfe Add BSD Authentication constants (#10376) 2021-12-22 00:59:53 -05:00
Andrew Kelley
6fdf7ce0af Sema: simplify coercion logic
Instead of a separate function, `coerceNum` for handling comptime-known
number coercion, outside of the main switch, the `coerce` function now
has a single big switch statement that decides the control flow based on
the zig type tag.
2021-12-21 22:35:24 -07:00
Andrew Kelley
5d6380b38d Merge pull request #10384 from joachimschmidt557/stage2-arm-optionals
stage2 ARM: basic implementation of optionals and error unions
2021-12-21 21:06:08 -08:00
Andrew Kelley
88be5bd81d Sema: fix empty struct init
* Extract common logic between `zirStructInitEmpty` and
   `zirStructInit`.
 * `resolveTypeFields` additionally sets status to `have_layout` if the
   total number of fields is 0.
2021-12-21 20:34:27 -07:00
Andrew Kelley
06d751dbb3 link/wasm: fix regression of wrong assertion
Fixes typo introduced in 2cbeb85a96.
2021-12-21 18:43:19 -07:00
Stephen Lumenta
efab3b1e6d fix expectStringEndsWith error output.
before it started outputting the actual starting, not ending characters.
2021-12-21 17:33:04 -08:00
Jonathan S
24cca2a55e Only check the file's length once in pdb.Msf.init 2021-12-21 17:29:23 -08:00
Andrew Kelley
2cbeb85a96 stage2: error check for mixing --import-table and --export-table
is moved from the linker to the frontend. This is a follow-up from
4cb2f11693.
2021-12-21 18:21:42 -07:00
ominitay
2e887452d5 Fix dead link 2021-12-21 17:13:52 -08:00
joachimschmidt557
c55f58d8bb stage2 ARM: implement is_err and is_non_err for simple error unions 2021-12-21 23:13:30 +01:00
joachimschmidt557
edcebe7013 stage2 ARM: implement is_null and is_non_null for ptr-like optionals 2021-12-21 23:13:30 +01:00
Andrew Kelley
8b6ea9ffe7 C backend: implement ret_addr 2021-12-21 14:32:02 -07:00
Luuk de Gram
4cb2f11693 wasm-linker: Implement the --export-table and --import-table flags.
This implements the flags for both the linker frontend as well as the self-hosted linker.

Closes #5790
2021-12-21 12:38:50 -08:00
Ersikan
e15a267668 elf: Put constant data in the .rodata section
Allocate a new program header and a new section to accomodate the read-only data
section ".rodata".

Separate TextBlock into multiple TextBlockList, to separate decl in different
sections.

If a Decl is not a function, it is added to the .rodata section.
2021-12-21 11:33:12 -08:00
joachimschmidt557
44061cd760 stage2 ARM: Refactor airStore 2021-12-21 11:30:56 -08:00
Andrew Kelley
8df540aeef Merge pull request #10370 from Snektron/stage2-inferred-error-sets-2
stage2: Make page_allocator work
2021-12-21 11:28:40 -08:00
ominitay
7e16bb36d8 Change ArgIterator.next() return type
Changes the return type of `ArgIterator.next()` from
`?(NextError![:0]u8)` to `NextError!?[:0]u8`.
2021-12-21 11:15:33 -08:00
John Schmidt
0d09b87c14 Langref: replace mentions of c_void with anyopaque 2021-12-21 11:13:21 -08:00
Robin Voetter
e106e18d96 stage2: @shlWithOverflow 2021-12-21 01:47:27 +01:00
Robin Voetter
964dbeb826 stage2: @subWithOverflow 2021-12-21 01:41:51 +01:00
Robin Voetter
58d67a6718 stage2: make anyopaque sized
While this is technically incorrect, proper handling of anyopaque, as well
as regular opaque, is probably best left until pointers to zero-sized types
having no bits is abolished.
2021-12-21 01:41:51 +01:00
Robin Voetter
c47ed0c912 stage2: @mulWithOverflow 2021-12-21 01:41:51 +01:00
Robin Voetter
ddd2ef822f stage2: @returnAddress() 2021-12-21 01:41:51 +01:00
Robin Voetter
2f7e98c129 stage2: also write addrspace to pointer typeinfo 2021-12-21 01:41:51 +01:00
Robin Voetter
f3d635b668 stage2: @addWithOverflow 2021-12-21 01:41:51 +01:00
Robin Voetter
28bcd7dbdd os: disable unexpected error tracing on stage 2 builds
The self-hosted compiler cannot yet deal with the print function that this
field enables. It is not critical, however, and allows us to remove formatting
from the list of neccesary features to implement to get the page allocator
working.
2021-12-21 01:41:50 +01:00
Robin Voetter
138f85bf25 stage2: only create inferred error sets for inferred error set functions 2021-12-21 01:41:50 +01:00
Robin Voetter
16bddecff9 stage2: allow @ptrToInt on anything that is a pointer at runtime
This in particular allows @ptrToInt on pointer-like optionals.
2021-12-21 01:41:50 +01:00
Robin Voetter
d5621504b0 stage2: save and restore parameters when resolving inline bodies
This caused zirParam instructions of parent blocks to be present in
inline analyzed blocks, and so function prototypes declared in the
inline blocks would also gain and add to the parameters in the
parent block.

Only block and block_inline are affected in this commit, as prototypes
and declarations are always generated in block_inline. This might need
to be resolved in a more general way at some point.
2021-12-21 01:41:50 +01:00
Robin Voetter
e18c3f3109 stage2: wrap function prototypes in an inline block.
Previously, function parameter instructions for function prototypes would be
generated in the parent block. This caused issues in blocks where multiple
prototypes would be generated in, such as the block for struct fields for
example. This change introduces an inline block around every prototype such
that all parameters for a prototype are confined to a unique block.
2021-12-21 01:41:50 +01:00
Robin Voetter
993197cd86 stage2: merged error sets in wrapErrorUnion 2021-12-21 01:41:50 +01:00
Robin Voetter
9d6c45f697 stage2: inferred error set coercion 2021-12-21 01:41:50 +01:00
Robin Voetter
a2958a4ede stage2: allow multiple inferred error sets per Fn
This allows the inferred error set of comptime and inline invocations to be
resolved separately from the inferred error set of the runtime version or other
comptime/inline invocations.
2021-12-21 01:41:50 +01:00
Robin Voetter
b2343e63bd stage2: move inferred error set state into func 2021-12-21 01:41:50 +01:00
Robin Voetter
cd733ceb85 stage2: replace ErrorSet and ErrorSetMerged arrays with hash maps 2021-12-21 01:41:50 +01:00
Jakub Konka
5156ccd552 stage2: merge MOV back with arith instructions
* turns out MOV and other arithmetic instructions such as ADD can
  naturally share the same lowering codepath (for the same variants)
* there are variants that are specific to ADD, or MOV which will be
  implemented as standalone MIR tags
* tweak Isel tests to generate corresponding test cases for all
  arithmetic instructions in comptime
2021-12-20 23:29:41 +01:00
Andrew Kelley
ea913846c2 ci: add 0.9.0 to downloads json 2021-12-20 15:18:25 -07:00
Andrew Kelley
e3e6516d08 start the 0.10.0 release cycle 2021-12-20 13:13:48 -07:00
Jakub Konka
71c5eebd32 stage2: remove obsolete MOV variant 0b11
* variant `0b11` when both `reg1 != .none` and `reg2 != .none` is
  identical to `0b00` therefore it can safely be removed
* fix proper destination register size calculation when setting register from
  another source register
2021-12-20 18:20:06 +01:00
Jakub Konka
4a40c0a80c stage2: refactor errors thrown for size mismatch in mirMovImpl
* introduce `EmitResult` wrapper struct for easier manipulation of
  intermediate emit results - this is mainly to track errors such as
  size mismatch between operands
* create an informative `ErrorMsg` directly at the callsite
2021-12-20 17:59:47 +01:00
Jakub Konka
70bff2f4d5 stage2: fix MOV MIR -> Isel lowering logic
* ensure that every callsite of basic MOV MIR instruction follows the
  Intel syntax (dst <- src)
* add extensive unit tests for MOV MIR -> Isel lowering
* leave TODOs for cases that are currently not handled and/or missing
* fix any ABI size mismatch between operands
2021-12-20 17:59:37 +01:00
4793 changed files with 484844 additions and 408373 deletions

View File

@@ -1,7 +1,7 @@
image: freebsd/latest image: freebsd/latest
secrets: secrets:
- 51bfddf5-86a6-4e01-8576-358c72a4a0a4 - 51bfddf5-86a6-4e01-8576-358c72a4a0a4
- 512ed797-0927-475a-83fd-bc997792860c - be22288f-b1bc-4243-abe3-43d8f0e7079b
sources: sources:
- https://github.com/ziglang/zig - https://github.com/ziglang/zig
tasks: tasks:

4
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,4 @@
# Autodoc
/src/Autodoc.zig @kristoff-it
/src/autodoc/* @kristoff-it
/lib/docs/* @kristoff-it

View File

@@ -5,7 +5,6 @@
One of the best ways you can contribute to Zig is to start using it for a One of the best ways you can contribute to Zig is to start using it for a
personal project. Here are some great examples: personal project. Here are some great examples:
* [Oxid](https://github.com/dbandstra/oxid) - arcade style game
* [TM35-Metronome](https://github.com/TM35-Metronome) - tools for modifying and randomizing Pokémon games * [TM35-Metronome](https://github.com/TM35-Metronome) - tools for modifying and randomizing Pokémon games
* [River](https://github.com/ifreund/river/) - a dynamic tiling wayland compositor * [River](https://github.com/ifreund/river/) - a dynamic tiling wayland compositor
@@ -69,7 +68,7 @@ test and debug from a git working tree.
- `make` is typically sufficient to build zig during development iterations. - `make` is typically sufficient to build zig during development iterations.
- `make install` performs a build __and__ install. - `make install` performs a build __and__ install.
- `msbuild -p:Configuration=Release INSTALL.vcxproj` on Windows performs a - `msbuild -p:Configuration=Release INSTALL.vcxproj` on Windows performs a
build and install. To avoid install, pass cmake option `-DZIG_SKIP_INSTALL_LIB_FILES=ON`. build and install. To avoid install, pass cmake option `-DZIG_NO_LIB=ON`.
To test changes, do the following from the build directory: To test changes, do the following from the build directory:

12
.github/ISSUE_TEMPLATE/autodoc-issue.md vendored Normal file
View File

@@ -0,0 +1,12 @@
---
name: Autodoc Issue
about: Issues with automatically generated docs, including stdlib docs.
title: 'Autodoc: {your issue}'
labels: autodoc
assignees: kristoff-it
---
Autodoc is still work in progress and as such many bugs and missing features are already known.
# Please report only <ins>regressions</ins>, i.e. things that worked in a previous build of new Autodoc (orange banner) that now don't work any more.

View File

@@ -14,27 +14,20 @@ body:
attributes: attributes:
label: Zig Version label: Zig Version
description: "The output of `zig version`" description: "The output of `zig version`"
placeholder: "0.9.0-dev.1275+ac52e0056" placeholder: "0.10.0-dev.4583+875e98a57"
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: repro id: repro
attributes: attributes:
label: Steps to Reproduce label: Steps to Reproduce and Observed Behavior
description: What exactly can someone else do, in order to observe the problem that you observed? description: What exactly can someone else do, in order to observe the problem that you observed? Include the output and all error messages.
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: expected id: expected
attributes: attributes:
label: Expected Behavior label: Expected Behavior
description: What did you expect to happen? description: What did you expect to happen instead?
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual Behavior
description: What happened instead? Be sure to include all error messages if any.
validations: validations:
required: true required: true

7
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,7 @@
contact_links:
- name: Language Proposal
about: Propose to improve the Zig language
url: https://github.com/ziglang/zig/wiki/Language-Proposals
- name: Question
about: Please use one of the community spaces for questions or general discussions.
url: https://github.com/ziglang/zig/wiki/Community

View File

@@ -1,16 +0,0 @@
name: Language Proposal
description: Propose to improve the Zig language
labels: ["proposal"]
body:
- type: markdown
attributes:
value: |
Thank you for your interest in improving the Zig language. However, we are
not accepting new proposals to change the language at this time.
- type: checkboxes
id: trash
attributes:
label: Please do not file a proposal to change the language
options:
- label: "I understand, thank you. I will not submit a new proposal at this time"
required: true

View File

@@ -1,20 +0,0 @@
name: Question
description: Ask a Zig-related question
labels: ["question"]
body:
- type: markdown
attributes:
value: |
Welcome! There are a bunch of great places to ask Zig-related questions.
Please take a look at
[The Community Wiki Page](https://github.com/ziglang/zig/wiki/Community) and
find a comfy place to ask questions. You will find plenty of helpful people in
these spaces. However, this issue tracker is not for questions. It is for
more actionable items such as bug reports and enhancements.
- type: checkboxes
id: trash
attributes:
label: Please do not open a question issue on the bug tracker
options:
- label: "I understand, thank you. I will take my question to one of the community spaces instead"
required: true

View File

@@ -12,10 +12,26 @@ if(NOT CMAKE_BUILD_TYPE)
endif() endif()
if(NOT CMAKE_INSTALL_PREFIX) if(NOT CMAKE_INSTALL_PREFIX)
set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}" CACHE STRING set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/stage3" CACHE STRING
"Directory to install zig to" FORCE) "Directory to install zig to" FORCE)
endif() endif()
# CMake recognizes the CMAKE_PREFIX_PATH environment variable for some things,
# and also the CMAKE_PREFIX_PATH cache variable for other things. However, it
# does not relate these two things, i.e. if the environment variable is set,
# CMake does not populate the cache variable in a corresponding manner. Some
# package systems, such as Homebrew, set the environment variable but not the
# cache variable. Furthermore, the environment variable follows the system path
# separator, such as ':' on POSIX and ';' on Windows, but the cache variable
# follows CMake's array behavior, i.e. always ';' for a separator.
list(APPEND ZIG_CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH}")
if(WIN32)
list(APPEND ZIG_CMAKE_PREFIX_PATH $ENV{CMAKE_PREFIX_PATH})
else()
string(REGEX REPLACE ":" ";" ZIG_CMAKE_PREFIX_PATH_STRING "$ENV{CMAKE_PREFIX_PATH}")
list(APPEND ZIG_CMAKE_PREFIX_PATH "${ZIG_CMAKE_PREFIX_PATH_STRING}")
endif()
set(CMAKE_USER_MAKE_RULES_OVERRIDE set(CMAKE_USER_MAKE_RULES_OVERRIDE
${CMAKE_CURRENT_SOURCE_DIR}/cmake/c_flag_overrides.cmake) ${CMAKE_CURRENT_SOURCE_DIR}/cmake/c_flag_overrides.cmake)
set(CMAKE_USER_MAKE_RULES_OVERRIDE_CXX set(CMAKE_USER_MAKE_RULES_OVERRIDE_CXX
@@ -25,13 +41,13 @@ project(zig C CXX)
set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH}) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH})
set(ZIG_VERSION_MAJOR 0) set(ZIG_VERSION_MAJOR 0)
set(ZIG_VERSION_MINOR 9) set(ZIG_VERSION_MINOR 10)
set(ZIG_VERSION_PATCH 0) set(ZIG_VERSION_PATCH 0)
set(ZIG_VERSION "" CACHE STRING "Override Zig version string. Default is to find out with git.") set(ZIG_VERSION "" CACHE STRING "Override Zig version string. Default is to find out with git.")
if("${ZIG_VERSION}" STREQUAL "") if("${ZIG_VERSION}" STREQUAL "")
set(ZIG_VERSION "${ZIG_VERSION_MAJOR}.${ZIG_VERSION_MINOR}.${ZIG_VERSION_PATCH}") set(ZIG_VERSION "${ZIG_VERSION_MAJOR}.${ZIG_VERSION_MINOR}.${ZIG_VERSION_PATCH}")
find_program(GIT_EXE NAMES git) find_program(GIT_EXE NAMES git NAMES_PER_DIR)
if(GIT_EXE) if(GIT_EXE)
execute_process( execute_process(
COMMAND ${GIT_EXE} -C ${CMAKE_SOURCE_DIR} describe --match *.*.* --tags COMMAND ${GIT_EXE} -C ${CMAKE_SOURCE_DIR} describe --match *.*.* --tags
@@ -63,12 +79,22 @@ if("${ZIG_VERSION}" STREQUAL "")
endif() endif()
endif() endif()
endif() endif()
message("Configuring zig version ${ZIG_VERSION}") message(STATUS "Configuring zig version ${ZIG_VERSION}")
set(ZIG_NO_LIB off CACHE BOOL
"Disable copying lib/ files to install prefix during the build phase")
set(ZIG_SKIP_INSTALL_LIB_FILES off CACHE BOOL "Deprecated. Use ZIG_NO_LIB")
if(ZIG_SKIP_INSTALL_LIB_FILES)
message(WARNING "ZIG_SKIP_INSTALL_LIB_FILES is deprecated. Use ZIG_NO_LIB instead.")
set(ZIG_NO_LIB ON)
endif()
set(ZIG_STATIC off CACHE BOOL "Attempt to build a static zig executable (not compatible with glibc)") set(ZIG_STATIC off CACHE BOOL "Attempt to build a static zig executable (not compatible with glibc)")
set(ZIG_SHARED_LLVM off CACHE BOOL "Prefer linking against shared LLVM libraries")
set(ZIG_STATIC_LLVM off CACHE BOOL "Prefer linking against static LLVM libraries") set(ZIG_STATIC_LLVM off CACHE BOOL "Prefer linking against static LLVM libraries")
set(ZIG_STATIC_ZLIB off CACHE BOOL "Prefer linking against static zlib") set(ZIG_STATIC_ZLIB off CACHE BOOL "Prefer linking against static zlib")
set(ZIG_PREFER_CLANG_CPP_DYLIB off CACHE BOOL "Try to link against -lclang-cpp") set(ZIG_STATIC_ZSTD off CACHE BOOL "Prefer linking against static zstd")
set(ZIG_USE_CCACHE off CACHE BOOL "Use ccache if available") set(ZIG_USE_CCACHE off CACHE BOOL "Use ccache if available")
if(CCACHE_PROGRAM AND ZIG_USE_CCACHE) if(CCACHE_PROGRAM AND ZIG_USE_CCACHE)
@@ -78,6 +104,11 @@ endif()
if(ZIG_STATIC) if(ZIG_STATIC)
set(ZIG_STATIC_LLVM ON) set(ZIG_STATIC_LLVM ON)
set(ZIG_STATIC_ZLIB ON) set(ZIG_STATIC_ZLIB ON)
set(ZIG_STATIC_ZSTD ON)
endif()
if (ZIG_SHARED_LLVM AND ZIG_STATIC_LLVM)
message(SEND_ERROR "-DZIG_SHARED_LLVM and -DZIG_STATIC_LLVM cannot both be enabled simultaneously")
endif() endif()
string(REGEX REPLACE "\\\\" "\\\\\\\\" ZIG_LIBC_LIB_DIR_ESCAPED "${ZIG_LIBC_LIB_DIR}") string(REGEX REPLACE "\\\\" "\\\\\\\\" ZIG_LIBC_LIB_DIR_ESCAPED "${ZIG_LIBC_LIB_DIR}")
@@ -104,19 +135,25 @@ else()
set(ZIG_USE_LLVM_CONFIG OFF CACHE BOOL "use llvm-config to find LLVM libraries") set(ZIG_USE_LLVM_CONFIG OFF CACHE BOOL "use llvm-config to find LLVM libraries")
endif() endif()
find_package(llvm 13) find_package(llvm 15)
find_package(clang 13) find_package(clang 15)
find_package(lld 13) find_package(lld 15)
if(ZIG_STATIC_ZLIB) if(ZIG_STATIC_ZLIB)
list(REMOVE_ITEM LLVM_LIBRARIES "-lz") list(REMOVE_ITEM LLVM_LIBRARIES "-lz")
find_library(ZLIB NAMES libz.a libzlibstatic.a z zlib libz) find_library(ZLIB NAMES libz.a libzlibstatic.a z zlib libz NAMES_PER_DIR)
list(APPEND LLVM_LIBRARIES "${ZLIB}") list(APPEND LLVM_LIBRARIES "${ZLIB}")
endif() endif()
if(ZIG_STATIC_ZSTD)
list(REMOVE_ITEM LLVM_LIBRARIES "-lzstd")
find_library(ZSTD NAMES libzstd.a libzstdstatic.a zstd NAMES_PER_DIR)
list(APPEND LLVM_LIBRARIES "${ZSTD}")
endif()
if(APPLE AND ZIG_STATIC) if(APPLE AND ZIG_STATIC)
list(REMOVE_ITEM LLVM_LIBRARIES "-lcurses") list(REMOVE_ITEM LLVM_LIBRARIES "-lcurses")
find_library(CURSES NAMES libcurses.a libncurses.a find_library(CURSES NAMES libcurses.a libncurses.a NAMES_PER_DIR
PATHS PATHS
/usr/local/opt/ncurses/lib /usr/local/opt/ncurses/lib
/opt/homebrew/opt/ncurses/lib) /opt/homebrew/opt/ncurses/lib)
@@ -142,15 +179,19 @@ include_directories(${CLANG_INCLUDE_DIRS})
# No patches have been applied to SoftFloat-3e # No patches have been applied to SoftFloat-3e
set(EMBEDDED_SOFTFLOAT_SOURCES set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/f128M_isSignalingNaN.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/f128M_isSignalingNaN.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/extF80M_isSignalingNaN.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToF128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToF128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToExtF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToF16UI.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToF16UI.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToF32UI.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToF32UI.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToF64UI.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_commonNaNToF64UI.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_f128MToCommonNaN.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_f128MToCommonNaN.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_extF80MToCommonNaN.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_f16UIToCommonNaN.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_f16UIToCommonNaN.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_f32UIToCommonNaN.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_f32UIToCommonNaN.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_f64UIToCommonNaN.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_f64UIToCommonNaN.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_propagateNaNF128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_propagateNaNF128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_propagateNaNExtF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_propagateNaNF16UI.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/s_propagateNaNF16UI.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/softfloat_raiseFlags.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/8086/softfloat_raiseFlags.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_add.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_add.c"
@@ -170,6 +211,7 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_f16.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_f16.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_f32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_f32.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_f64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_f64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_extF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_i32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_i32.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_i32_r_minMag.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_i32_r_minMag.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_i64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_i64.c"
@@ -178,6 +220,20 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_ui32_r_minMag.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_ui32_r_minMag.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_ui64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_ui64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_ui64_r_minMag.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_to_ui64_r_minMag.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_add.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_div.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_eq.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_le.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_lt.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_mul.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_rem.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_roundToInt.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_sqrt.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_sub.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_to_f16.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_to_f32.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_to_f64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/extF80M_to_f128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_add.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_add.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_div.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_div.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_eq.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_eq.c"
@@ -188,9 +244,12 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_roundToInt.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_roundToInt.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_sqrt.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_sqrt.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_sub.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_sub.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_to_extF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_to_f128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_to_f128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_to_f64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_to_f64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f32_to_extF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f32_to_f128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f32_to_f128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f64_to_extF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f64_to_f128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f64_to_f128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f64_to_f16.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f64_to_f16.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/i32_to_f128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/i32_to_f128M.c"
@@ -198,6 +257,7 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addCarryM.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addCarryM.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addComplCarryM.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addComplCarryM.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addF128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addF128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addExtF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addM.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addM.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addMagsF16.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addMagsF16.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addMagsF32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_addMagsF32.c"
@@ -208,12 +268,14 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_approxRecip_1Ks.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_approxRecip_1Ks.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_compare128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_compare128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_compare96M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_compare96M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_compareNonnormExtF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_countLeadingZeros16.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_countLeadingZeros16.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_countLeadingZeros32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_countLeadingZeros32.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_countLeadingZeros64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_countLeadingZeros64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_countLeadingZeros8.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_countLeadingZeros8.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_eq128.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_eq128.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_invalidF128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_invalidF128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_invalidExtF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_isNaNF128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_isNaNF128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_le128.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_le128.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_lt128.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_lt128.c"
@@ -224,7 +286,9 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_mulAddF32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_mulAddF32.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_mulAddF64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_mulAddF64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_negXM.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_negXM.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normExtF80SigM.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackMToF128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackMToF128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackMToExtF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackToF16.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackToF16.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackToF32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackToF32.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackToF64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_normRoundPackToF64.c"
@@ -235,6 +299,7 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_remStepMBy32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_remStepMBy32.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundMToI64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundMToI64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundMToUI64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundMToUI64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundPackMToExtF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundPackMToF128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundPackMToF128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundPackToF16.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundPackToF16.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundPackToF32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_roundPackToF32.c"
@@ -263,16 +328,25 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_subMagsF32.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_subMagsF32.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_subMagsF64.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_subMagsF64.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_tryPropagateNaNF128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_tryPropagateNaNF128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/s_tryPropagateNaNExtF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_mulAdd.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f16_mulAdd.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_mulAdd.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/f128M_mulAdd.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/softfloat_state.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/softfloat_state.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/ui32_to_f128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/ui32_to_f128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/ui64_to_f128M.c" "${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/ui64_to_f128M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/ui32_to_extF80M.c"
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e/source/ui64_to_extF80M.c"
) )
add_library(embedded_softfloat STATIC ${EMBEDDED_SOFTFLOAT_SOURCES}) add_library(embedded_softfloat STATIC ${EMBEDDED_SOFTFLOAT_SOURCES})
if(MSVC) if(MSVC)
set(SOFTFLOAT_CFLAGS "/w")
if(NOT "${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set(SOFTFLOAT_CFLAGS "${SOFTFLOAT_CFLAGS} /O2")
endif()
set_target_properties(embedded_softfloat PROPERTIES set_target_properties(embedded_softfloat PROPERTIES
COMPILE_FLAGS "/w /O2" COMPILE_FLAGS ${SOFTFLOAT_CFLAGS}
) )
else() else()
set_target_properties(embedded_softfloat PROPERTIES set_target_properties(embedded_softfloat PROPERTIES
@@ -298,7 +372,7 @@ set(ZIG_CONFIG_H_OUT "${CMAKE_BINARY_DIR}/config.h")
set(ZIG_CONFIG_ZIG_OUT "${CMAKE_BINARY_DIR}/config.zig") set(ZIG_CONFIG_ZIG_OUT "${CMAKE_BINARY_DIR}/config.zig")
# This is our shim which will be replaced by stage1.zig. # This is our shim which will be replaced by stage1.zig.
set(ZIG0_SOURCES set(ZIG1_SOURCES
"${CMAKE_SOURCE_DIR}/src/stage1/zig0.cpp" "${CMAKE_SOURCE_DIR}/src/stage1/zig0.cpp"
) )
@@ -309,7 +383,6 @@ set(STAGE1_SOURCES
"${CMAKE_SOURCE_DIR}/src/stage1/bigint.cpp" "${CMAKE_SOURCE_DIR}/src/stage1/bigint.cpp"
"${CMAKE_SOURCE_DIR}/src/stage1/buffer.cpp" "${CMAKE_SOURCE_DIR}/src/stage1/buffer.cpp"
"${CMAKE_SOURCE_DIR}/src/stage1/codegen.cpp" "${CMAKE_SOURCE_DIR}/src/stage1/codegen.cpp"
"${CMAKE_SOURCE_DIR}/src/stage1/dump_analysis.cpp"
"${CMAKE_SOURCE_DIR}/src/stage1/errmsg.cpp" "${CMAKE_SOURCE_DIR}/src/stage1/errmsg.cpp"
"${CMAKE_SOURCE_DIR}/src/stage1/error.cpp" "${CMAKE_SOURCE_DIR}/src/stage1/error.cpp"
"${CMAKE_SOURCE_DIR}/src/stage1/heap.cpp" "${CMAKE_SOURCE_DIR}/src/stage1/heap.cpp"
@@ -339,9 +412,9 @@ set(ZIG_CPP_SOURCES
# https://github.com/ziglang/zig/issues/6363 # https://github.com/ziglang/zig/issues/6363
"${CMAKE_SOURCE_DIR}/src/windows_sdk.cpp" "${CMAKE_SOURCE_DIR}/src/windows_sdk.cpp"
) )
# Needed because we use cmake, not the zig build system, to build zig1.o. # Needed because we use cmake, not the zig build system, to build zig2.o.
# This list is generated by building zig and then clearing the zig-cache directory, # This list is generated by building zig and then clearing the zig-cache directory,
# then manually running the build-obj command (see BUILD_ZIG1_ARGS), and then looking # then manually running the build-obj command (see BUILD_ZIG2_ARGS), and then looking
# in the zig-cache directory for the compiler-generated list of zig file dependencies. # in the zig-cache directory for the compiler-generated list of zig file dependencies.
set(ZIG_STAGE2_SOURCES set(ZIG_STAGE2_SOURCES
"${ZIG_CONFIG_ZIG_OUT}" "${ZIG_CONFIG_ZIG_OUT}"
@@ -367,6 +440,9 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/lib/std/debug.zig" "${CMAKE_SOURCE_DIR}/lib/std/debug.zig"
"${CMAKE_SOURCE_DIR}/lib/std/dwarf.zig" "${CMAKE_SOURCE_DIR}/lib/std/dwarf.zig"
"${CMAKE_SOURCE_DIR}/lib/std/dwarf/AT.zig" "${CMAKE_SOURCE_DIR}/lib/std/dwarf/AT.zig"
"${CMAKE_SOURCE_DIR}/lib/std/dwarf/ATE.zig"
"${CMAKE_SOURCE_DIR}/lib/std/dwarf/FORM.zig"
"${CMAKE_SOURCE_DIR}/lib/std/dwarf/LANG.zig"
"${CMAKE_SOURCE_DIR}/lib/std/dwarf/OP.zig" "${CMAKE_SOURCE_DIR}/lib/std/dwarf/OP.zig"
"${CMAKE_SOURCE_DIR}/lib/std/dwarf/TAG.zig" "${CMAKE_SOURCE_DIR}/lib/std/dwarf/TAG.zig"
"${CMAKE_SOURCE_DIR}/lib/std/elf.zig" "${CMAKE_SOURCE_DIR}/lib/std/elf.zig"
@@ -410,9 +486,8 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/lib/std/math.zig" "${CMAKE_SOURCE_DIR}/lib/std/math.zig"
"${CMAKE_SOURCE_DIR}/lib/std/math/big.zig" "${CMAKE_SOURCE_DIR}/lib/std/math/big.zig"
"${CMAKE_SOURCE_DIR}/lib/std/math/big/int.zig" "${CMAKE_SOURCE_DIR}/lib/std/math/big/int.zig"
"${CMAKE_SOURCE_DIR}/lib/std/math/floor.zig" "${CMAKE_SOURCE_DIR}/lib/std/math/float.zig"
"${CMAKE_SOURCE_DIR}/lib/std/math/frexp.zig" "${CMAKE_SOURCE_DIR}/lib/std/math/frexp.zig"
"${CMAKE_SOURCE_DIR}/lib/std/math/inf.zig"
"${CMAKE_SOURCE_DIR}/lib/std/math/isinf.zig" "${CMAKE_SOURCE_DIR}/lib/std/math/isinf.zig"
"${CMAKE_SOURCE_DIR}/lib/std/math/isnan.zig" "${CMAKE_SOURCE_DIR}/lib/std/math/isnan.zig"
"${CMAKE_SOURCE_DIR}/lib/std/math/ln.zig" "${CMAKE_SOURCE_DIR}/lib/std/math/ln.zig"
@@ -429,12 +504,14 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/lib/std/meta/trait.zig" "${CMAKE_SOURCE_DIR}/lib/std/meta/trait.zig"
"${CMAKE_SOURCE_DIR}/lib/std/multi_array_list.zig" "${CMAKE_SOURCE_DIR}/lib/std/multi_array_list.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os.zig" "${CMAKE_SOURCE_DIR}/lib/std/os.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/darwin.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/linux.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/linux.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/linux/errno/generic.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/linux/errno/generic.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/linux/x86_64.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/linux/x86_64.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/linux.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/linux.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/linux/io_uring.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/linux/io_uring.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/linux/x86_64.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/linux/x86_64.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/posix_spawn.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/windows.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/windows.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/windows/ntstatus.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/windows/ntstatus.zig"
"${CMAKE_SOURCE_DIR}/lib/std/os/windows/win32error.zig" "${CMAKE_SOURCE_DIR}/lib/std/os/windows/win32error.zig"
@@ -443,72 +520,180 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/lib/std/process.zig" "${CMAKE_SOURCE_DIR}/lib/std/process.zig"
"${CMAKE_SOURCE_DIR}/lib/std/rand.zig" "${CMAKE_SOURCE_DIR}/lib/std/rand.zig"
"${CMAKE_SOURCE_DIR}/lib/std/sort.zig" "${CMAKE_SOURCE_DIR}/lib/std/sort.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/addXf3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/absv.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/atomics.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/absvdi2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/bswap.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/absvsi2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/clear_cache.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/absvti2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/cmp.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/adddf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/compareXf2.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/addf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/count0bits.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/addo.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/divdf3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/addsf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/divsf3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/addtf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/divtf3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/addxf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/divti3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/arm.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/extendXfYf2.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/atomics.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixdfdi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/aulldiv.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixdfsi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/aullrem.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixdfti.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/bswap.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixint.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/ceil.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixsfdi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/clear_cache.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixsfsi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/cmp.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixsfti.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/cmpdf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixtfdi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/cmpsf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixtfsi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/cmptf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixtfti.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/cmpxf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixuint.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/common.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunsdfdi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/comparef.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunsdfsi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/cos.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunsdfti.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/count0bits.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunssfdi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/divdf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunssfsi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/divsf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunssfti.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/divtf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunstfdi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/divti3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunstfsi.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/divxf3.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/fixunstfti.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/emutls.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatXisf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/exp.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatdidf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/exp2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatditf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extenddftf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatsiXf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extenddfxf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floattidf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extendf.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floattitf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extendhfsf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatundidf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extendhftf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatundisf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extendhfxf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatunditf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extendsfdf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatunsidf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extendsftf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatunsisf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extendsfxf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatunsitf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/extendxftf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatuntidf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fabs.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatuntisf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixdfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/floatuntitf.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixdfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/int.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixdfti.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/modti3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixhfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/mulXf3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixhfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/muldi3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixhfti.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/mulo.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixsfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/multi3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixsfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/negXf2.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixsfti.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/negXi2.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixtfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/os_version_check.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixtfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/parity.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixtfti.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/popcount.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunsdfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/shift.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunsdfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/stack_probe.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunsdfti.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/truncXfYf2.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunshfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/udivmod.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunshfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/udivmodti4.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunshfti.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/udivti3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunssfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt/umodti3.zig" "${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunssfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunssfti.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunstfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunstfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunstfti.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunsxfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunsxfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixunsxfti.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixxfdi.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixxfsi.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fixxfti.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/float_to_int.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatdidf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatdihf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatdisf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatditf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatdixf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatsidf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatsihf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatsisf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatsitf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatsixf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floattidf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floattihf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floattisf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floattitf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floattixf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatundidf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatundihf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatundisf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatunditf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatundixf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatunsidf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatunsihf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatunsisf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatunsitf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatunsixf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatuntidf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatuntihf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatuntisf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatuntitf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floatuntixf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/floor.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fma.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fmax.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fmin.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/fmod.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/gedf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/gesf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/getf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/gexf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/int.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/int_to_float.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/log.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/log10.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/log2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/modti3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/muldf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/muldi3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/mulf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/mulo.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/mulsf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/multf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/multi3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/mulxf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/negXi2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/negv.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/os_version_check.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/parity.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/popcount.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/rem_pio2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/rem_pio2_large.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/rem_pio2f.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/round.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/shift.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/sin.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/sincos.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/sqrt.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/stack_probe.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/subo.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/subsf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/subdf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/subtf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/subxf3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/negsf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/negdf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/negtf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/negxf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/tan.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/trig.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/trunc.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/truncdfhf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/truncdfsf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/truncf.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/truncsfhf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/trunctfdf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/trunctfhf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/trunctfsf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/trunctfxf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/truncxfdf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/truncxfhf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/truncxfsf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/udivmod.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/udivmodti4.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/udivti3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/umodti3.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/unorddf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/unordsf2.zig"
"${CMAKE_SOURCE_DIR}/lib/compiler_rt/unordtf2.zig"
"${CMAKE_SOURCE_DIR}/lib/std/start.zig" "${CMAKE_SOURCE_DIR}/lib/std/start.zig"
"${CMAKE_SOURCE_DIR}/lib/std/std.zig" "${CMAKE_SOURCE_DIR}/lib/std/std.zig"
"${CMAKE_SOURCE_DIR}/lib/std/target.zig" "${CMAKE_SOURCE_DIR}/lib/std/target.zig"
@@ -524,20 +709,20 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/lib/std/target/powerpc.zig" "${CMAKE_SOURCE_DIR}/lib/std/target/powerpc.zig"
"${CMAKE_SOURCE_DIR}/lib/std/target/riscv.zig" "${CMAKE_SOURCE_DIR}/lib/std/target/riscv.zig"
"${CMAKE_SOURCE_DIR}/lib/std/target/sparc.zig" "${CMAKE_SOURCE_DIR}/lib/std/target/sparc.zig"
"${CMAKE_SOURCE_DIR}/lib/std/target/systemz.zig" "${CMAKE_SOURCE_DIR}/lib/std/target/s390x.zig"
"${CMAKE_SOURCE_DIR}/lib/std/target/wasm.zig" "${CMAKE_SOURCE_DIR}/lib/std/target/wasm.zig"
"${CMAKE_SOURCE_DIR}/lib/std/target/x86.zig" "${CMAKE_SOURCE_DIR}/lib/std/target/x86.zig"
"${CMAKE_SOURCE_DIR}/lib/std/Thread.zig" "${CMAKE_SOURCE_DIR}/lib/std/Thread.zig"
"${CMAKE_SOURCE_DIR}/lib/std/Thread/AutoResetEvent.zig"
"${CMAKE_SOURCE_DIR}/lib/std/Thread/Futex.zig" "${CMAKE_SOURCE_DIR}/lib/std/Thread/Futex.zig"
"${CMAKE_SOURCE_DIR}/lib/std/Thread/Mutex.zig" "${CMAKE_SOURCE_DIR}/lib/std/Thread/Mutex.zig"
"${CMAKE_SOURCE_DIR}/lib/std/Thread/ResetEvent.zig" "${CMAKE_SOURCE_DIR}/lib/std/Thread/ResetEvent.zig"
"${CMAKE_SOURCE_DIR}/lib/std/Thread/StaticResetEvent.zig"
"${CMAKE_SOURCE_DIR}/lib/std/time.zig" "${CMAKE_SOURCE_DIR}/lib/std/time.zig"
"${CMAKE_SOURCE_DIR}/lib/std/treap.zig"
"${CMAKE_SOURCE_DIR}/lib/std/unicode.zig" "${CMAKE_SOURCE_DIR}/lib/std/unicode.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig.zig" "${CMAKE_SOURCE_DIR}/lib/std/zig.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/Ast.zig" "${CMAKE_SOURCE_DIR}/lib/std/zig/Ast.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/CrossTarget.zig" "${CMAKE_SOURCE_DIR}/lib/std/zig/CrossTarget.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/c_builtins.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/parse.zig" "${CMAKE_SOURCE_DIR}/lib/std/zig/parse.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/render.zig" "${CMAKE_SOURCE_DIR}/lib/std/zig/render.zig"
"${CMAKE_SOURCE_DIR}/lib/std/zig/string_literal.zig" "${CMAKE_SOURCE_DIR}/lib/std/zig/string_literal.zig"
@@ -560,11 +745,34 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/src/TypedValue.zig" "${CMAKE_SOURCE_DIR}/src/TypedValue.zig"
"${CMAKE_SOURCE_DIR}/src/WaitGroup.zig" "${CMAKE_SOURCE_DIR}/src/WaitGroup.zig"
"${CMAKE_SOURCE_DIR}/src/Zir.zig" "${CMAKE_SOURCE_DIR}/src/Zir.zig"
"${CMAKE_SOURCE_DIR}/src/arch/aarch64/CodeGen.zig"
"${CMAKE_SOURCE_DIR}/src/arch/aarch64/Emit.zig"
"${CMAKE_SOURCE_DIR}/src/arch/aarch64/Mir.zig"
"${CMAKE_SOURCE_DIR}/src/arch/aarch64/bits.zig" "${CMAKE_SOURCE_DIR}/src/arch/aarch64/bits.zig"
"${CMAKE_SOURCE_DIR}/src/arch/aarch64/abi.zig"
"${CMAKE_SOURCE_DIR}/src/arch/arm/CodeGen.zig"
"${CMAKE_SOURCE_DIR}/src/arch/arm/Emit.zig"
"${CMAKE_SOURCE_DIR}/src/arch/arm/Mir.zig"
"${CMAKE_SOURCE_DIR}/src/arch/arm/bits.zig" "${CMAKE_SOURCE_DIR}/src/arch/arm/bits.zig"
"${CMAKE_SOURCE_DIR}/src/arch/arm/abi.zig"
"${CMAKE_SOURCE_DIR}/src/arch/riscv64/CodeGen.zig"
"${CMAKE_SOURCE_DIR}/src/arch/riscv64/Emit.zig"
"${CMAKE_SOURCE_DIR}/src/arch/riscv64/Mir.zig"
"${CMAKE_SOURCE_DIR}/src/arch/riscv64/bits.zig" "${CMAKE_SOURCE_DIR}/src/arch/riscv64/bits.zig"
"${CMAKE_SOURCE_DIR}/src/arch/x86_64/bits.zig" "${CMAKE_SOURCE_DIR}/src/arch/riscv64/abi.zig"
"${CMAKE_SOURCE_DIR}/src/arch/sparc64/CodeGen.zig"
"${CMAKE_SOURCE_DIR}/src/arch/sparc64/Emit.zig"
"${CMAKE_SOURCE_DIR}/src/arch/sparc64/Mir.zig"
"${CMAKE_SOURCE_DIR}/src/arch/sparc64/bits.zig"
"${CMAKE_SOURCE_DIR}/src/arch/sparc64/abi.zig"
"${CMAKE_SOURCE_DIR}/src/arch/wasm/CodeGen.zig" "${CMAKE_SOURCE_DIR}/src/arch/wasm/CodeGen.zig"
"${CMAKE_SOURCE_DIR}/src/arch/wasm/Emit.zig"
"${CMAKE_SOURCE_DIR}/src/arch/wasm/Mir.zig"
"${CMAKE_SOURCE_DIR}/src/arch/x86_64/CodeGen.zig"
"${CMAKE_SOURCE_DIR}/src/arch/x86_64/Emit.zig"
"${CMAKE_SOURCE_DIR}/src/arch/x86_64/Mir.zig"
"${CMAKE_SOURCE_DIR}/src/arch/x86_64/bits.zig"
"${CMAKE_SOURCE_DIR}/src/arch/x86_64/abi.zig"
"${CMAKE_SOURCE_DIR}/src/clang.zig" "${CMAKE_SOURCE_DIR}/src/clang.zig"
"${CMAKE_SOURCE_DIR}/src/clang_options.zig" "${CMAKE_SOURCE_DIR}/src/clang_options.zig"
"${CMAKE_SOURCE_DIR}/src/clang_options_data.zig" "${CMAKE_SOURCE_DIR}/src/clang_options_data.zig"
@@ -580,22 +788,30 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/src/libunwind.zig" "${CMAKE_SOURCE_DIR}/src/libunwind.zig"
"${CMAKE_SOURCE_DIR}/src/link.zig" "${CMAKE_SOURCE_DIR}/src/link.zig"
"${CMAKE_SOURCE_DIR}/src/link/C.zig" "${CMAKE_SOURCE_DIR}/src/link/C.zig"
"${CMAKE_SOURCE_DIR}/src/link/C/zig.h"
"${CMAKE_SOURCE_DIR}/src/link/Coff.zig" "${CMAKE_SOURCE_DIR}/src/link/Coff.zig"
"${CMAKE_SOURCE_DIR}/src/link/Coff/Atom.zig"
"${CMAKE_SOURCE_DIR}/src/link/Coff/Object.zig"
"${CMAKE_SOURCE_DIR}/src/link/Coff/lld.zig"
"${CMAKE_SOURCE_DIR}/src/link/Elf.zig" "${CMAKE_SOURCE_DIR}/src/link/Elf.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/Archive.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO/Archive.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/Atom.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO/Atom.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/CodeSignature.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO/CodeSignature.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/DebugSymbols.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO/DebugSymbols.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/DwarfInfo.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/Dylib.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO/Dylib.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/Object.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO/Object.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/Trie.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO/Trie.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/ZldAtom.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/bind.zig" "${CMAKE_SOURCE_DIR}/src/link/MachO/bind.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/dead_strip.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/thunks.zig"
"${CMAKE_SOURCE_DIR}/src/link/MachO/zld.zig"
"${CMAKE_SOURCE_DIR}/src/link/Plan9.zig" "${CMAKE_SOURCE_DIR}/src/link/Plan9.zig"
"${CMAKE_SOURCE_DIR}/src/link/Plan9/aout.zig" "${CMAKE_SOURCE_DIR}/src/link/Plan9/aout.zig"
"${CMAKE_SOURCE_DIR}/src/link/Wasm.zig" "${CMAKE_SOURCE_DIR}/src/link/Wasm.zig"
"${CMAKE_SOURCE_DIR}/src/link/msdos-stub.bin" "${CMAKE_SOURCE_DIR}/src/link/msdos-stub.bin"
"${CMAKE_SOURCE_DIR}/src/link/strtab.zig"
"${CMAKE_SOURCE_DIR}/src/link/tapi.zig" "${CMAKE_SOURCE_DIR}/src/link/tapi.zig"
"${CMAKE_SOURCE_DIR}/src/link/tapi/Tokenizer.zig" "${CMAKE_SOURCE_DIR}/src/link/tapi/Tokenizer.zig"
"${CMAKE_SOURCE_DIR}/src/link/tapi/parse.zig" "${CMAKE_SOURCE_DIR}/src/link/tapi/parse.zig"
@@ -608,6 +824,7 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/src/print_env.zig" "${CMAKE_SOURCE_DIR}/src/print_env.zig"
"${CMAKE_SOURCE_DIR}/src/print_targets.zig" "${CMAKE_SOURCE_DIR}/src/print_targets.zig"
"${CMAKE_SOURCE_DIR}/src/print_zir.zig" "${CMAKE_SOURCE_DIR}/src/print_zir.zig"
"${CMAKE_SOURCE_DIR}/src/register_manager.zig"
"${CMAKE_SOURCE_DIR}/src/stage1.zig" "${CMAKE_SOURCE_DIR}/src/stage1.zig"
"${CMAKE_SOURCE_DIR}/src/target.zig" "${CMAKE_SOURCE_DIR}/src/target.zig"
"${CMAKE_SOURCE_DIR}/src/tracy.zig" "${CMAKE_SOURCE_DIR}/src/tracy.zig"
@@ -694,7 +911,9 @@ else()
endif() endif()
if(MSVC) if(MSVC)
set(OPTIMIZED_C_FLAGS "/O2") if(NOT "${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set(OPTIMIZED_C_FLAGS "/O2")
endif()
else(MSVC) else(MSVC)
set(OPTIMIZED_C_FLAGS "-std=c99 -O3") set(OPTIMIZED_C_FLAGS "-std=c99 -O3")
endif(MSVC) endif(MSVC)
@@ -744,6 +963,9 @@ add_library(opt_c_util STATIC ${OPTIMIZED_C_SOURCES})
set_target_properties(opt_c_util PROPERTIES set_target_properties(opt_c_util PROPERTIES
COMPILE_FLAGS "${OPTIMIZED_C_FLAGS}" COMPILE_FLAGS "${OPTIMIZED_C_FLAGS}"
) )
target_include_directories(opt_c_util PRIVATE
"${CMAKE_SOURCE_DIR}/deps/SoftFloat-3e-prebuilt"
)
add_library(zigstage1 STATIC ${STAGE1_SOURCES}) add_library(zigstage1 STATIC ${STAGE1_SOURCES})
set_target_properties(zigstage1 PROPERTIES set_target_properties(zigstage1 PROPERTIES
@@ -768,111 +990,118 @@ if(MSVC OR MINGW)
endif() endif()
if("${ZIG_EXECUTABLE}" STREQUAL "") if("${ZIG_EXECUTABLE}" STREQUAL "")
add_executable(zig0 ${ZIG0_SOURCES}) add_executable(zig1 ${ZIG1_SOURCES})
set_target_properties(zig0 PROPERTIES set_target_properties(zig1 PROPERTIES
COMPILE_FLAGS ${EXE_CFLAGS} COMPILE_FLAGS ${EXE_CFLAGS}
LINK_FLAGS ${EXE_LDFLAGS} LINK_FLAGS ${EXE_LDFLAGS}
) )
target_link_libraries(zig0 zigstage1) target_link_libraries(zig1 zigstage1)
endif() endif()
if(MSVC) if(MSVC)
set(ZIG1_OBJECT "${CMAKE_BINARY_DIR}/zig1.obj") set(ZIG2_OBJECT "${CMAKE_BINARY_DIR}/zig2.obj")
else() else()
set(ZIG1_OBJECT "${CMAKE_BINARY_DIR}/zig1.o") set(ZIG2_OBJECT "${CMAKE_BINARY_DIR}/zig2.o")
endif() endif()
if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set(ZIG1_RELEASE_ARG "") set(ZIG_RELEASE_ARG "")
elseif("${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo")
set(ZIG_RELEASE_ARG -Drelease)
else() else()
set(ZIG1_RELEASE_ARG -OReleaseFast --strip) set(ZIG_RELEASE_ARG -Drelease -Dstrip)
endif()
if(ZIG_NO_LIB)
set(ZIG_NO_LIB_ARG "-Dno-lib")
else()
set(ZIG_NO_LIB_ARG "")
endif() endif()
if(ZIG_SINGLE_THREADED) if(ZIG_SINGLE_THREADED)
set(ZIG1_SINGLE_THREADED_ARG "--single-threaded") set(ZIG_SINGLE_THREADED_ARG "-fsingle-threaded")
else() else()
set(ZIG1_SINGLE_THREADED_ARG "") set(ZIG_SINGLE_THREADED_ARG "")
endif()
if(ZIG_STATIC)
set(ZIG_STATIC_ARG "-Duse-zig-libcxx")
else()
set(ZIG_STATIC_ARG "")
endif() endif()
set(BUILD_ZIG1_ARGS set(BUILD_ZIG2_ARGS
"src/stage1.zig" "src/stage1.zig"
-target "${ZIG_TARGET_TRIPLE}" --name zig2
"-mcpu=${ZIG_TARGET_MCPU}"
--name zig1
--zig-lib-dir "${CMAKE_SOURCE_DIR}/lib" --zig-lib-dir "${CMAKE_SOURCE_DIR}/lib"
"-femit-bin=${ZIG1_OBJECT}" "-femit-bin=${ZIG2_OBJECT}"
-fcompiler-rt -fcompiler-rt
"${ZIG1_RELEASE_ARG}" ${ZIG_SINGLE_THREADED_ARG}
"${ZIG1_SINGLE_THREADED_ARG}" -target "${ZIG_TARGET_TRIPLE}"
-mcpu "${ZIG_TARGET_MCPU}"
-lc -lc
--pkg-begin build_options "${ZIG_CONFIG_ZIG_OUT}" --pkg-begin build_options "${ZIG_CONFIG_ZIG_OUT}"
--pkg-end --pkg-end
--pkg-begin compiler_rt "${CMAKE_SOURCE_DIR}/lib/std/special/compiler_rt.zig" --pkg-begin compiler_rt "${CMAKE_SOURCE_DIR}/lib/compiler_rt.zig"
--pkg-end --pkg-end
) )
if("${ZIG_EXECUTABLE}" STREQUAL "") if("${ZIG_EXECUTABLE}" STREQUAL "")
add_custom_command( add_custom_command(
OUTPUT "${ZIG1_OBJECT}" OUTPUT "${ZIG2_OBJECT}"
COMMAND zig0 ${BUILD_ZIG1_ARGS} COMMAND zig1 ${BUILD_ZIG2_ARGS}
DEPENDS zig0 "${ZIG_STAGE2_SOURCES}" DEPENDS zig1 "${ZIG_STAGE2_SOURCES}"
COMMENT STATUS "Building self-hosted component ${ZIG1_OBJECT}" COMMENT STATUS "Building stage2 object ${ZIG2_OBJECT}"
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
) )
set(ZIG_EXECUTABLE "${zig_BINARY_DIR}/zig")
if (WIN32) if (WIN32)
set(ZIG_EXECUTABLE "${ZIG_EXECUTABLE}.exe") set(ZIG_EXECUTABLE "${CMAKE_BINARY_DIR}/zig2.exe")
else()
set(ZIG_EXECUTABLE "${CMAKE_BINARY_DIR}/zig2")
endif() endif()
else() else()
add_custom_command( add_custom_command(
OUTPUT "${ZIG1_OBJECT}" OUTPUT "${ZIG2_OBJECT}"
COMMAND "${ZIG_EXECUTABLE}" "build-obj" ${BUILD_ZIG1_ARGS} COMMAND "${ZIG_EXECUTABLE}" "build-obj" ${BUILD_ZIG2_ARGS}
DEPENDS ${ZIG_STAGE2_SOURCES} DEPENDS ${ZIG_STAGE2_SOURCES}
COMMENT STATUS "Building self-hosted component ${ZIG1_OBJECT}" COMMENT STATUS "Building stage2 component ${ZIG2_OBJECT}"
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
) )
endif() endif()
# cmake won't let us configure an executable without C sources. # cmake won't let us configure an executable without C sources.
add_executable(zig "${CMAKE_SOURCE_DIR}/src/stage1/empty.cpp" "${ZIG1_OBJECT}") add_executable(zig2 "${CMAKE_SOURCE_DIR}/src/stage1/empty.cpp" "${ZIG2_OBJECT}")
set_target_properties(zig PROPERTIES set_target_properties(zig2 PROPERTIES
COMPILE_FLAGS ${EXE_CFLAGS} COMPILE_FLAGS ${EXE_CFLAGS}
LINK_FLAGS ${EXE_LDFLAGS} LINK_FLAGS ${EXE_LDFLAGS}
) )
target_link_libraries(zig zigstage1) target_link_libraries(zig2 zigstage1)
if(MSVC) if(MSVC)
target_link_libraries(zig ntdll.lib) target_link_libraries(zig2 ntdll.lib)
elseif(MINGW) elseif(MINGW)
target_link_libraries(zig ntdll) target_link_libraries(zig2 ntdll)
endif() endif()
install(TARGETS zig DESTINATION bin) set(ZIG_BUILD_ARGS
--zig-lib-dir "${CMAKE_SOURCE_DIR}/lib"
"-Dconfig_h=${ZIG_CONFIG_H_OUT}"
"-Denable-llvm"
"-Denable-stage1"
${ZIG_RELEASE_ARG}
${ZIG_STATIC_ARG}
${ZIG_NO_LIB_ARG}
${ZIG_SINGLE_THREADED_ARG}
"-Dtarget=${ZIG_TARGET_TRIPLE}"
"-Dcpu=${ZIG_TARGET_MCPU}"
"-Dversion-string=${ZIG_VERSION}"
)
set(ZIG_SKIP_INSTALL_LIB_FILES off CACHE BOOL add_custom_target(stage3 ALL
"Disable copying lib/ files to install prefix during the build phase") COMMAND zig2 build compile ${ZIG_BUILD_ARGS}
DEPENDS zig2
COMMENT STATUS "Building stage3"
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
)
if(NOT ZIG_SKIP_INSTALL_LIB_FILES) install(CODE "set(ZIG_EXECUTABLE \"${ZIG_EXECUTABLE}\")")
set(ZIG_INSTALL_ARGS "build" install(CODE "set(ZIG_BUILD_ARGS \"${ZIG_BUILD_ARGS}\")")
--zig-lib-dir "${CMAKE_SOURCE_DIR}/lib" install(CODE "set(CMAKE_INSTALL_PREFIX \"${CMAKE_INSTALL_PREFIX}\")")
"-Dlib-files-only" install(CODE "set(CMAKE_SOURCE_DIR \"${CMAKE_SOURCE_DIR}\")")
--prefix "${CMAKE_INSTALL_PREFIX}" install(SCRIPT "${CMAKE_SOURCE_DIR}/cmake/install.cmake")
"-Dconfig_h=${ZIG_CONFIG_H_OUT}"
install
)
# CODE has no effect with Visual Studio build system generator, therefore
# when using Visual Studio build system generator we resort to running
# `zig build install` during the build phase.
if(MSVC)
add_custom_target(zig_install_lib_files ALL
COMMAND zig ${ZIG_INSTALL_ARGS}
DEPENDS zig
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
)
else()
get_target_property(zig_BINARY_DIR zig BINARY_DIR)
install(CODE "set(zig_EXE \"${ZIG_EXECUTABLE}\")")
install(CODE "set(ZIG_INSTALL_ARGS \"${ZIG_INSTALL_ARGS}\")")
install(CODE "set(CMAKE_SOURCE_DIR \"${CMAKE_SOURCE_DIR}\")")
install(SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/cmake/install.cmake)
endif()
endif()

View File

@@ -1,6 +1,6 @@
The MIT License (Expat) The MIT License (Expat)
Copyright (c) 2015-2021, Zig contributors Copyright (c) 2015-2022, Zig contributors
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,4 +1,4 @@
![ZIG](https://ziglang.org/zig-logo.svg) ![ZIG](https://ziglang.org/img/zig-logo-dynamic.svg)
A general-purpose programming language and toolchain for maintaining A general-purpose programming language and toolchain for maintaining
**robust**, **optimal**, and **reusable** software. **robust**, **optimal**, and **reusable** software.
@@ -9,8 +9,8 @@ A general-purpose programming language and toolchain for maintaining
* [Download & Documentation](https://ziglang.org/download) * [Download & Documentation](https://ziglang.org/download)
* [Chapter 0 - Getting Started | ZigLearn.org](https://ziglearn.org/) * [Chapter 0 - Getting Started | ZigLearn.org](https://ziglearn.org/)
* [Community](https://github.com/ziglang/zig/wiki/Community) * [Community](https://github.com/ziglang/zig/wiki/Community)
* [Contributing](https://github.com/ziglang/zig/blob/master/CONTRIBUTING.md) * [Contributing](https://github.com/ziglang/zig/blob/master/.github/CONTRIBUTING.md)
* [Code of Conduct](https://github.com/ziglang/zig/blob/master/CODE_OF_CONDUCT.md) * [Code of Conduct](https://github.com/ziglang/zig/blob/master/.github/CODE_OF_CONDUCT.md)
* [Frequently Asked Questions](https://github.com/ziglang/zig/wiki/FAQ) * [Frequently Asked Questions](https://github.com/ziglang/zig/wiki/FAQ)
* [Community Projects](https://github.com/ziglang/zig/wiki/Community-Projects) * [Community Projects](https://github.com/ziglang/zig/wiki/Community-Projects)

599
build.zig

File diff suppressed because it is too large Load Diff

View File

@@ -1,132 +0,0 @@
#!/bin/sh
set -x
set -e
brew update && brew install ncurses s3cmd
ZIGDIR="$(pwd)"
HOST_ARCH="x86_64"
HOST_TARGET="$HOST_ARCH-macos-gnu"
HOST_MCPU="baseline"
HOST_CACHE_BASENAME="zig+llvm+lld+clang-$HOST_TARGET-0.9.0-dev.1249+210ef5af8"
HOST_PREFIX="$HOME/$HOST_CACHE_BASENAME"
ARCH="aarch64"
TARGET="$ARCH-macos-gnu"
MCPU="apple_a14"
CACHE_BASENAME="zig+llvm+lld+clang-$TARGET-0.9.0-dev.1249+210ef5af8"
PREFIX="$HOME/$CACHE_BASENAME"
JOBS="-j2"
rm -rf $HOST_PREFIX $PREFIX
cd $HOME
wget -nv "https://ziglang.org/deps/$HOST_CACHE_BASENAME.tar.xz"
wget -nv "https://ziglang.org/deps/$CACHE_BASENAME.tar.xz"
tar xf "$HOST_CACHE_BASENAME.tar.xz"
tar xf "$CACHE_BASENAME.tar.xz"
cd $ZIGDIR
# Make the `zig version` number consistent.
# This will affect the cmake command below.
git config core.abbrev 9
git fetch --unshallow || true
git fetch --tags
# Build host zig compiler in debug so that we can get the
# current version when packaging
ZIG="$HOST_PREFIX/bin/zig"
export CC="$ZIG cc -target $HOST_TARGET -mcpu=$HOST_MCPU"
export CXX="$ZIG c++ -target $HOST_TARGET -mcpu=$HOST_MCPU"
mkdir build.host
cd build.host
cmake .. \
-DCMAKE_INSTALL_PREFIX="$(pwd)/release" \
-DCMAKE_PREFIX_PATH="$HOST_PREFIX" \
-DCMAKE_BUILD_TYPE=Release \
-DZIG_TARGET_TRIPLE="$HOST_TARGET" \
-DZIG_TARGET_MCPU="$HOST_MCPU" \
-DZIG_STATIC=ON \
-DZIG_OMIT_STAGE2=ON
unset CC
unset CXX
make $JOBS install
# Build zig compiler cross-compiled for arm64
cd $ZIGDIR
ZIG="$ZIGDIR/build.host/release/bin/zig"
export CC="$ZIG cc -target $TARGET -mcpu=$MCPU"
export CXX="$ZIG c++ -target $TARGET -mcpu=$MCPU"
mkdir build
cd build
cmake .. \
-DCMAKE_INSTALL_PREFIX="$(pwd)/release" \
-DCMAKE_PREFIX_PATH="$PREFIX" \
-DCMAKE_BUILD_TYPE=Release \
-DZIG_TARGET_TRIPLE="$TARGET" \
-DZIG_TARGET_MCPU="$MCPU" \
-DZIG_EXECUTABLE="$ZIG" \
-DZIG_STATIC=ON
unset CC
unset CXX
make $JOBS install
if [ "${BUILD_REASON}" != "PullRequest" ]; then
mv ../LICENSE release/
# We do not run test suite but still need langref.
mkdir -p release/docs
$ZIG run ../doc/docgen.zig -- $ZIG ../doc/langref.html.in release/docs/langref.html
# Produce the experimental std lib documentation.
mkdir -p release/docs/std
$ZIG test ../lib/std/std.zig \
--zig-lib-dir ../lib \
-femit-docs=release/docs/std \
-fno-emit-bin
mv release/bin/zig release/
rmdir release/bin
VERSION=$(../build.host/release/bin/zig version)
DIRNAME="zig-macos-$ARCH-$VERSION"
TARBALL="$DIRNAME.tar.xz"
mv release "$DIRNAME"
tar cfJ "$TARBALL" "$DIRNAME"
mv "$DOWNLOADSECUREFILE_SECUREFILEPATH" "$HOME/.s3cfg"
s3cmd put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/
SHASUM=$(shasum -a 256 $TARBALL | cut '-d ' -f1)
BYTESIZE=$(wc -c < $TARBALL)
JSONFILE="macos-$GITBRANCH.json"
touch $JSONFILE
echo "{\"tarball\": \"$TARBALL\"," >>$JSONFILE
echo "\"shasum\": \"$SHASUM\"," >>$JSONFILE
echo "\"size\": \"$BYTESIZE\"}" >>$JSONFILE
s3cmd put -P --add-header="Cache-Control: max-age=0, must-revalidate" "$JSONFILE" "s3://ziglang.org/builds/$JSONFILE"
s3cmd put -P "$JSONFILE" "s3://ziglang.org/builds/$ARCH-macos-$VERSION.json"
# `set -x` causes these variables to be mangled.
# See https://developercommunity.visualstudio.com/content/problem/375679/pipeline-variable-incorrectly-inserts-single-quote.html
set +x
echo "##vso[task.setvariable variable=tarball;isOutput=true]$TARBALL"
echo "##vso[task.setvariable variable=shasum;isOutput=true]$SHASUM"
echo "##vso[task.setvariable variable=bytesize;isOutput=true]$BYTESIZE"
fi

View File

@@ -7,9 +7,9 @@ brew update && brew install ncurses s3cmd
ZIGDIR="$(pwd)" ZIGDIR="$(pwd)"
ARCH="x86_64" ARCH="x86_64"
TARGET="$ARCH-macos-gnu" TARGET="$ARCH-macos-none"
MCPU="baseline" MCPU="baseline"
CACHE_BASENAME="zig+llvm+lld+clang-$TARGET-0.9.0-dev.1249+210ef5af8" CACHE_BASENAME="zig+llvm+lld+clang-$TARGET-0.10.0-dev.4560+828735ac0"
PREFIX="$HOME/$CACHE_BASENAME" PREFIX="$HOME/$CACHE_BASENAME"
JOBS="-j2" JOBS="-j2"
@@ -34,13 +34,12 @@ git fetch --tags
mkdir build mkdir build
cd build cd build
cmake .. \ cmake .. \
-DCMAKE_INSTALL_PREFIX="$(pwd)/release" \ -DCMAKE_INSTALL_PREFIX="stage3-release" \
-DCMAKE_PREFIX_PATH="$PREFIX" \ -DCMAKE_PREFIX_PATH="$PREFIX" \
-DCMAKE_BUILD_TYPE=Release \ -DCMAKE_BUILD_TYPE=Release \
-DZIG_TARGET_TRIPLE="$TARGET" \ -DZIG_TARGET_TRIPLE="$TARGET" \
-DZIG_TARGET_MCPU="$MCPU" \ -DZIG_TARGET_MCPU="$MCPU" \
-DZIG_STATIC=ON \ -DZIG_STATIC=ON
-DZIG_OMIT_STAGE2=ON
# Now cmake will use zig as the C/C++ compiler. We reset the environment variables # Now cmake will use zig as the C/C++ compiler. We reset the environment variables
# so that installation and testing do not get affected by them. # so that installation and testing do not get affected by them.
@@ -49,29 +48,37 @@ unset CXX
make $JOBS install make $JOBS install
# Here we rebuild zig but this time using the Zig binary we just now produced to stage3-release/bin/zig build test docs \
# build zig1.o rather than relying on the one built with stage0. See --zig-lib-dir "$(pwd)/../lib" \
# https://github.com/ziglang/zig/issues/6830 for more details. -Denable-macos-sdk \
cmake .. -DZIG_EXECUTABLE="$(pwd)/release/bin/zig" -Dstatic-llvm \
make $JOBS install -Dskip-non-native \
--search-prefix "$PREFIX"
# TODO figure out why this causes a segmentation fault # Produce the experimental std lib documentation.
# release/bin/zig test ../test/behavior.zig -fno-stage1 -fLLVM -I ../test mkdir -p "stage3-release/doc/std"
stage3-release/bin/zig test "$(pwd)/../lib/std/std.zig" \
release/bin/zig build test-toolchain -Denable-macos-sdk --zig-lib-dir "$(pwd)/../lib" \
release/bin/zig build test-std -femit-docs="$(pwd)/stage3-release/doc/std" \
release/bin/zig build docs -fno-emit-bin
if [ "${BUILD_REASON}" != "PullRequest" ]; then if [ "${BUILD_REASON}" != "PullRequest" ]; then
mv ../LICENSE release/ # Remove the unnecessary bin dir in stage3-release/bin/zig
mv ../zig-cache/langref.html release/ mv stage3-release/bin/zig stage3-release/
mv release/bin/zig release/ rmdir stage3-release/bin
rmdir release/bin
VERSION=$(release/zig version) # Remove the unnecessary zig dir in stage3-release/lib/zig/std/std.zig
mv stage3-release/lib/zig stage3-release/lib2
rmdir stage3-release/lib
mv stage3-release/lib2 stage3-release/lib
mv ../LICENSE stage3-release/
mv ../zig-cache/langref.html stage3-release/doc
VERSION=$(stage3-release/zig version)
DIRNAME="zig-macos-$ARCH-$VERSION" DIRNAME="zig-macos-$ARCH-$VERSION"
TARBALL="$DIRNAME.tar.xz" TARBALL="$DIRNAME.tar.xz"
mv release "$DIRNAME" mv stage3-release "$DIRNAME"
tar cfJ "$TARBALL" "$DIRNAME" tar cfJ "$TARBALL" "$DIRNAME"
mv "$DOWNLOADSECUREFILE_SECUREFILEPATH" "$HOME/.s3cfg" mv "$DOWNLOADSECUREFILE_SECUREFILEPATH" "$HOME/.s3cfg"

View File

@@ -1,7 +1,7 @@
jobs: jobs:
- job: BuildMacOS - job: BuildMacOS
pool: pool:
vmImage: 'macOS-10.15' vmImage: 'macOS-11'
timeoutInMinutes: 360 timeoutInMinutes: 360
steps: steps:
- task: DownloadSecureFile@1 - task: DownloadSecureFile@1
@@ -10,51 +10,155 @@ jobs:
- script: ci/azure/macos_script - script: ci/azure/macos_script
name: main name: main
displayName: 'Build and test' displayName: 'Build and test'
- job: BuildMacOS_arm64
pool:
vmImage: 'macOS-10.15'
timeoutInMinutes: 180
steps:
- task: DownloadSecureFile@1
inputs:
secureFile: s3cfg
- script: ci/azure/macos_arm64_script
name: main
displayName: 'Build'
- job: BuildWindows - job: BuildWindows
timeoutInMinutes: 360
pool: pool:
vmImage: 'windows-2019' vmImage: 'windows-2019'
timeoutInMinutes: 360 variables:
TARGET: 'x86_64-windows-gnu'
ZIG_LLVM_CLANG_LLD_NAME: 'zig+llvm+lld+clang-${{ variables.TARGET }}-0.10.0-dev.4560+828735ac0'
ZIG_LLVM_CLANG_LLD_URL: 'https://ziglang.org/deps/${{ variables.ZIG_LLVM_CLANG_LLD_NAME }}.zip'
steps: steps:
- powershell: | - pwsh: |
(New-Object Net.WebClient).DownloadFile("https://github.com/msys2/msys2-installer/releases/download/2021-07-25/msys2-base-x86_64-20210725.sfx.exe", "sfx.exe") (New-Object Net.WebClient).DownloadFile("$(ZIG_LLVM_CLANG_LLD_URL)", "${ZIG_LLVM_CLANG_LLD_NAME}.zip")
.\sfx.exe -y -o\ & 'C:\Program Files\7-Zip\7z.exe' x "${ZIG_LLVM_CLANG_LLD_NAME}.zip"
displayName: Download/Extract/Install MSYS2 name: install
- script: | displayName: 'Install ZIG/LLVM/CLANG/LLD'
@REM install updated filesystem package first without dependency checking
@REM because of: https://github.com/msys2/MSYS2-packages/issues/2021 - pwsh: |
%CD:~0,2%\msys64\usr\bin\bash -lc "pacman --noconfirm -Sydd filesystem" Set-Variable -Name ZIGLIBDIR -Value "$(Get-Location)\lib"
displayName: Workaround filesystem dash MSYS2 dependency issue Set-Variable -Name ZIGINSTALLDIR -Value "$(Get-Location)\stage3-release"
- script: | Set-Variable -Name ZIGPREFIXPATH -Value "$(Get-Location)\$(ZIG_LLVM_CLANG_LLD_NAME)"
%CD:~0,2%\msys64\usr\bin\bash -lc "pacman --noconfirm -Syuu"
%CD:~0,2%\msys64\usr\bin\bash -lc "pacman --noconfirm -Syuu" function CheckLastExitCode {
displayName: Update MSYS2 if (!$?) {
exit 1
}
return 0
}
# Make the `zig version` number consistent.
# This will affect the `zig build` command below which uses `git describe`.
git config core.abbrev 9
git fetch --tags
if ((git rev-parse --is-shallow-repository) -eq "true") {
git fetch --unshallow # `git describe` won't work on a shallow repo
}
& "$ZIGPREFIXPATH\bin\zig.exe" build `
--prefix "$ZIGINSTALLDIR" `
--search-prefix "$ZIGPREFIXPATH" `
--zig-lib-dir "$ZIGLIBDIR" `
-Denable-stage1 `
-Dstatic-llvm `
-Drelease `
-Dstrip `
-Duse-zig-libcxx `
-Dtarget=$(TARGET)
CheckLastExitCode
name: build
displayName: 'Build'
- pwsh: |
Set-Variable -Name ZIGLIBDIR -Value "$(Get-Location)\lib"
Set-Variable -Name ZIGINSTALLDIR -Value "$(Get-Location)\stage3-release"
Set-Variable -Name ZIGPREFIXPATH -Value "$(Get-Location)\$(ZIG_LLVM_CLANG_LLD_NAME)"
function CheckLastExitCode {
if (!$?) {
exit 1
}
return 0
}
& "$ZIGINSTALLDIR\bin\zig.exe" build test docs `
--search-prefix "$ZIGPREFIXPATH" `
-Dstatic-llvm `
-Dskip-non-native
CheckLastExitCode
# Produce the experimental std lib documentation.
mkdir "$ZIGINSTALLDIR\doc\std" -force
& "$ZIGINSTALLDIR\bin\zig.exe" test "$ZIGLIBDIR\std\std.zig" `
--zig-lib-dir "$ZIGLIBDIR" `
-femit-docs="$ZIGINSTALLDIR\doc\std" `
-fno-emit-bin
name: test
displayName: 'Test'
- task: DownloadSecureFile@1 - task: DownloadSecureFile@1
inputs: inputs:
secureFile: s3cfg name: aws_credentials
- script: ci/azure/windows_msvc_script.bat secureFile: aws_credentials
name: main
displayName: 'Build and test' - pwsh: |
$Env:AWS_SHARED_CREDENTIALS_FILE = "$Env:DOWNLOADSECUREFILE_SECUREFILEPATH"
# Workaround Azure networking issue
# https://github.com/aws/aws-cli/issues/5749
$Env:AWS_EC2_METADATA_DISABLED = "true"
$Env:AWS_REGION = "us-west-2"
mv LICENSE stage3-release/
mv zig-cache/langref.html stage3-release/
mv stage3-release/bin/zig.exe stage3-release/
rmdir stage3-release/bin
# Remove the unnecessary zig dir in $prefix/lib/zig/std/std.zig
mv stage3-release/lib/zig stage3-release/lib2
rmdir stage3-release/lib
mv stage3-release/lib2 stage3-release/lib
Set-Variable -Name VERSION -Value $(./stage3-release/zig.exe version)
Set-Variable -Name DIRNAME -Value "zig-windows-x86_64-$VERSION"
Set-Variable -Name TARBALL -Value "$DIRNAME.zip"
mv stage3-release "$DIRNAME"
7z a "$TARBALL" "$DIRNAME"
aws s3 cp `
"$TARBALL" `
s3://ziglang.org/builds/ `
--acl public-read `
--cache-control 'public, max-age=31536000, immutable'
Set-Variable -Name SHASUM -Value (Get-FileHash "$TARBALL" -Algorithm SHA256 | select-object -ExpandProperty Hash).ToLower()
Set-Variable -Name BYTESIZE -Value (Get-Item "$TARBALL").length
Set-Variable -Name JSONFILE -Value "windows-${Env:BUILD_SOURCEBRANCHNAME}.json"
echo $null > $JSONFILE
echo ('{"tarball": "' + $TARBALL + '",') >> $JSONFILE
echo ('"shasum": "' + $SHASUM + '",') >> $JSONFILE
echo ('"size": ' + $BYTESIZE + '}' ) >> $JSONFILE
aws s3 cp `
"$JSONFILE" `
s3://ziglang.org/builds/ `
--acl public-read `
--cache-control 'max-age=0, must-revalidate'
aws s3 cp `
"$JSONFILE" `
"s3://ziglang.org/builds/x86_64-windows-${VERSION}.json" `
--acl public-read
echo "##vso[task.setvariable variable=tarball;isOutput=true]$TARBALL"
echo "##vso[task.setvariable variable=shasum;isOutput=true]$SHASUM"
echo "##vso[task.setvariable variable=bytesize;isOutput=true]$BYTESIZE"
name: upload
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
displayName: 'Upload'
- job: OnMasterSuccess - job: OnMasterSuccess
dependsOn: dependsOn:
- BuildMacOS - BuildMacOS
- BuildMacOS_arm64
- BuildWindows - BuildWindows
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master')) condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master'))
strategy: strategy:
maxParallel: 1 maxParallel: 1
pool: pool:
vmImage: 'ubuntu-18.04' vmImage: 'ubuntu-20.04'
variables: variables:
version: $[ dependencies.BuildMacOS.outputs['main.version'] ] version: $[ dependencies.BuildMacOS.outputs['main.version'] ]
steps: steps:

View File

@@ -1,16 +0,0 @@
#!/bin/sh
set -x
set -e
pacman -Suy --needed --noconfirm
pacman -S --needed --noconfirm wget p7zip python3-pip tar xz
TARBALL="llvm+clang+lld-13.0.0-x86_64-windows-msvc-release-mt.tar.xz"
pip install s3cmd
wget -nv "https://ziglang.org/deps/$TARBALL"
# If the first extraction fails, re-try it once; this can happen if the tarball
# contains symlinks that are in the table of contents before the files that
# they point to.
tar -xf $TARBALL || tar --overwrite -xf $TARBALL

View File

@@ -1,39 +0,0 @@
@echo on
SET "SRCROOT=%cd%"
SET "PREVPATH=%PATH%"
SET "PREVMSYSTEM=%MSYSTEM%"
set "PATH=%CD:~0,2%\msys64\usr\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem"
SET "MSYSTEM=MINGW64"
bash -lc "cd ${SRCROOT} && ci/azure/windows_msvc_install" || exit /b
SET "PATH=%PREVPATH%"
SET "MSYSTEM=%PREVMSYSTEM%"
SET "ZIGBUILDDIR=%SRCROOT%\build"
SET "ZIGINSTALLDIR=%ZIGBUILDDIR%\dist"
SET "ZIGPREFIXPATH=%SRCROOT%\llvm+clang+lld-13.0.0-x86_64-windows-msvc-release-mt"
call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x64
REM Make the `zig version` number consistent.
REM This will affect the cmake command below.
git.exe config core.abbrev 9
git.exe fetch --unshallow
git.exe fetch --tags
mkdir %ZIGBUILDDIR%
cd %ZIGBUILDDIR%
cmake.exe .. -Thost=x64 -G"Visual Studio 16 2019" -A x64 "-DCMAKE_INSTALL_PREFIX=%ZIGINSTALLDIR%" "-DCMAKE_PREFIX_PATH=%ZIGPREFIXPATH%" -DCMAKE_BUILD_TYPE=Release -DZIG_OMIT_STAGE2=ON || exit /b
msbuild /maxcpucount /p:Configuration=Release INSTALL.vcxproj || exit /b
REM Sadly, stage2 is omitted from this build to save memory on the CI server. Once self-hosted is
REM built with itself and does not gobble as much memory, we can enable these tests.
REM "%ZIGINSTALLDIR%\bin\zig.exe" test "..\test\behavior.zig" -fno-stage1 -fLLVM -I "..\test" || exit /b
"%ZIGINSTALLDIR%\bin\zig.exe" build test-toolchain -Dskip-non-native -Dskip-stage2-tests || exit /b
"%ZIGINSTALLDIR%\bin\zig.exe" build test-std -Dskip-non-native || exit /b
"%ZIGINSTALLDIR%\bin\zig.exe" build docs || exit /b
set "PATH=%CD:~0,2%\msys64\usr\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem"
SET "MSYSTEM=MINGW64"
bash -lc "cd ${SRCROOT} && ci/azure/windows_upload" || exit /b

View File

@@ -1,46 +0,0 @@
#!/bin/sh
set -x
set -e
if [ "${BUILD_REASON}" != "PullRequest" ]; then
cd "$ZIGBUILDDIR"
mv ../LICENSE dist/
mv ../zig-cache/langref.html dist/
mv dist/bin/zig.exe dist/
rmdir dist/bin
# Remove the unnecessary zig dir in $prefix/lib/zig/std/std.zig
mv dist/lib/zig dist/lib2
rmdir dist/lib
mv dist/lib2 dist/lib
VERSION=$(dist/zig.exe version)
DIRNAME="zig-windows-x86_64-$VERSION"
TARBALL="$DIRNAME.zip"
mv dist "$DIRNAME"
7z a "$TARBALL" "$DIRNAME"
# mv "$DOWNLOADSECUREFILE_SECUREFILEPATH" "$HOME/.s3cfg"
s3cmd -c "$DOWNLOADSECUREFILE_SECUREFILEPATH" put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/
SHASUM=$(sha256sum $TARBALL | cut '-d ' -f1)
BYTESIZE=$(wc -c < $TARBALL)
JSONFILE="windows-$GITBRANCH.json"
touch $JSONFILE
echo "{\"tarball\": \"$TARBALL\"," >>$JSONFILE
echo "\"shasum\": \"$SHASUM\"," >>$JSONFILE
echo "\"size\": \"$BYTESIZE\"}" >>$JSONFILE
s3cmd -c "$DOWNLOADSECUREFILE_SECUREFILEPATH" put -P --add-header="Cache-Control: max-age=0, must-revalidate" "$JSONFILE" "s3://ziglang.org/builds/$JSONFILE"
s3cmd -c "$DOWNLOADSECUREFILE_SECUREFILEPATH" put -P "$JSONFILE" "s3://ziglang.org/builds/x86_64-windows-$VERSION.json"
# `set -x` causes these variables to be mangled.
# See https://developercommunity.visualstudio.com/content/problem/375679/pipeline-variable-incorrectly-inserts-single-quote.html
set +x
echo "##vso[task.setvariable variable=tarball;isOutput=true]$TARBALL"
echo "##vso[task.setvariable variable=shasum;isOutput=true]$SHASUM"
echo "##vso[task.setvariable variable=bytesize;isOutput=true]$BYTESIZE"
fi

View File

@@ -1,76 +1,92 @@
--- ---
kind: pipeline kind: pipeline
type: docker
name: test-aarch64-linux-musl name: test-aarch64-linux-musl
platform: platform:
os: linux
arch: arm64 arch: arm64
steps: steps:
- name: build - name: build
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
commands: commands:
- ./ci/drone/linux_script_build - ./ci/drone/linux_script_build
- name: test-1 - name: behavior
depends_on: depends_on:
- build - build
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
commands: commands:
- ./ci/drone/linux_script_test 1 - ./ci/drone/test_linux_behavior
- name: test-2 - name: std_Debug
depends_on: depends_on:
- build - build
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
commands: commands:
- ./ci/drone/linux_script_test 2 - ./ci/drone/test_linux_std_Debug
- name: test-3 - name: std_ReleaseSafe
depends_on: depends_on:
- build - build
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
commands: commands:
- ./ci/drone/linux_script_test 3 - ./ci/drone/test_linux_std_ReleaseSafe
- name: test-4 - name: std_ReleaseFast
depends_on: depends_on:
- build - build
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
commands: commands:
- ./ci/drone/linux_script_test 4 - ./ci/drone/test_linux_std_ReleaseFast
- name: test-5 - name: std_ReleaseSmall
depends_on: depends_on:
- build - build
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
commands: commands:
- ./ci/drone/linux_script_test 5 - ./ci/drone/test_linux_std_ReleaseSmall
- name: test-6 - name: misc
depends_on: depends_on:
- build - build
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
commands: commands:
- ./ci/drone/linux_script_test 6 - ./ci/drone/test_linux_misc
- name: test-7 - name: cases
depends_on: depends_on:
- build - build
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
commands: commands:
- ./ci/drone/linux_script_test 7 - ./ci/drone/test_linux_cases
- name: standalone
depends_on:
- build
image: ziglang/static-base:llvm15-aarch64-3
commands:
- ./ci/drone/test_linux_standalone
- name: docs
depends_on:
- build
image: ziglang/static-base:llvm15-aarch64-3
commands:
- ./ci/drone/test_linux_docs
- name: finalize - name: finalize
depends_on: depends_on:
- build - build
- test-1 - behavior
- test-2 - std_Debug
- test-3 - std_ReleaseSafe
- test-4 - std_ReleaseFast
- test-5 - std_ReleaseSmall
- test-6 - misc
- test-7 - cases
image: ziglang/static-base:llvm13-aarch64-1 image: ziglang/static-base:llvm15-aarch64-3
environment: environment:
SRHT_OAUTH_TOKEN: SRHT_OAUTH_TOKEN:
from_secret: SRHT_OAUTH_TOKEN from_secret: SRHT_OAUTH_TOKEN

View File

@@ -1,22 +0,0 @@
#!/bin/sh
# https://docs.drone.io/pipeline/docker/syntax/workspace/
#
# Drone automatically creates a temporary volume, known as your workspace,
# where it clones your repository. The workspace is the current working
# directory for each step in your pipeline.
#
# Because the workspace is a volume, filesystem changes are persisted between
# pipeline steps. In other words, individual steps can communicate and share
# state using the filesystem.
#
# Workspace volumes are ephemeral. They are created when the pipeline starts
# and destroyed after the pipeline completes.
set -x
set -e
TRIPLEARCH="$(uname -m)"
DISTDIR="$DRONE_WORKSPACE/dist"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"

View File

@@ -1,17 +1,16 @@
#!/bin/sh #!/bin/sh
. ./ci/drone/linux_script_base set -x
set -e
# Probe CPU/brand details. ARCH="$(uname -m)"
# TODO: `lscpu` is changing package names in EDGE to `util-linux-misc` INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
apk update
apk add util-linux export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
echo "lscpu:"
lscpu | sed 's,^, : ,'
PREFIX="/deps/local" PREFIX="/deps/local"
ZIG="$PREFIX/bin/zig" ZIG="$PREFIX/bin/zig"
TARGET="$TRIPLEARCH-linux-musl" TARGET="$ARCH-linux-musl"
MCPU="baseline" MCPU="baseline"
export CC="$ZIG cc -target $TARGET -mcpu=$MCPU" export CC="$ZIG cc -target $TARGET -mcpu=$MCPU"
@@ -30,8 +29,8 @@ cat <<'ENDFILE' >$PREFIX/bin/ranlib
/deps/local/bin/zig ranlib $@ /deps/local/bin/zig ranlib $@
ENDFILE ENDFILE
chmod +x $PREFIX/bin/ar chmod +x "$PREFIX/bin/ar"
chmod +x $PREFIX/bin/ranlib chmod +x "$PREFIX/bin/ranlib"
# Make the `zig version` number consistent. # Make the `zig version` number consistent.
# This will affect the cmake command below. # This will affect the cmake command below.
@@ -42,8 +41,8 @@ git fetch --tags
mkdir build mkdir build
cd build cd build
cmake .. \ cmake .. \
-DCMAKE_INSTALL_PREFIX="$DISTDIR" \
-DCMAKE_PREFIX_PATH="$PREFIX" \ -DCMAKE_PREFIX_PATH="$PREFIX" \
-DCMAKE_INSTALL_PREFIX="$INSTALL_PREFIX" \
-DCMAKE_BUILD_TYPE=Release \ -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_AR="$PREFIX/bin/ar" \ -DCMAKE_AR="$PREFIX/bin/ar" \
-DCMAKE_RANLIB="$PREFIX/bin/ranlib" \ -DCMAKE_RANLIB="$PREFIX/bin/ranlib" \
@@ -57,9 +56,3 @@ cmake .. \
unset CC unset CC
unset CXX unset CXX
samu install samu install
# Here we rebuild Zig but this time using the Zig binary we just now produced to
# build zig1.o rather than relying on the one built with stage0. See
# https://github.com/ziglang/zig/issues/6830 for more details.
cmake .. -DZIG_EXECUTABLE="$DISTDIR/bin/zig"
samu install

View File

@@ -1,27 +1,36 @@
#!/bin/sh #!/bin/sh
. ./ci/drone/linux_script_base set -x
set -e
ARCH="$(uname -m)"
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
if [ -n "$DRONE_PULL_REQUEST" ]; then if [ -n "$DRONE_PULL_REQUEST" ]; then
exit 0 exit 0
fi fi
apk update
apk add py3-pip perl-utils jq curl
pip3 install s3cmd
cd build cd build
mv ../LICENSE "$DISTDIR/" # Remove the unnecessary bin dir in $INSTALL_PREFIX/bin/zig
mv ../zig-cache/langref.html "$DISTDIR/" mv "$INSTALL_PREFIX/bin/zig" "$INSTALL_PREFIX/"
mv "$DISTDIR/bin/zig" "$DISTDIR/" rmdir "$INSTALL_PREFIX/bin"
rmdir "$DISTDIR/bin"
# Remove the unnecessary zig dir in $INSTALL_PREFIX/lib/zig/std/std.zig
mv "$INSTALL_PREFIX/lib/zig" "$INSTALL_PREFIX/lib2"
rmdir "$INSTALL_PREFIX/lib"
mv "$INSTALL_PREFIX/lib2" "$INSTALL_PREFIX/lib"
mv ../LICENSE "$INSTALL_PREFIX/"
mv ../zig-cache/langref.html "$INSTALL_PREFIX/doc/"
GITBRANCH="$DRONE_BRANCH" GITBRANCH="$DRONE_BRANCH"
VERSION="$("$DISTDIR/zig" version)" VERSION="$("$INSTALL_PREFIX/zig" version)"
DIRNAME="zig-linux-$TRIPLEARCH-$VERSION" DIRNAME="zig-linux-$ARCH-$VERSION"
TARBALL="$DIRNAME.tar.xz" TARBALL="$DIRNAME.tar.xz"
mv "$DISTDIR" "$DIRNAME" mv "$INSTALL_PREFIX" "$DIRNAME"
tar cfJ "$TARBALL" "$DIRNAME" tar cfJ "$TARBALL" "$DIRNAME"
s3cmd put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/ s3cmd put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/
@@ -35,7 +44,7 @@ echo "{\"tarball\": \"$TARBALL\"," >>$JSONFILE
echo "\"shasum\": \"$SHASUM\"," >>$JSONFILE echo "\"shasum\": \"$SHASUM\"," >>$JSONFILE
echo "\"size\": \"$BYTESIZE\"}" >>$JSONFILE echo "\"size\": \"$BYTESIZE\"}" >>$JSONFILE
s3cmd put -P "$JSONFILE" "s3://ziglang.org/builds/$TRIPLEARCH-linux-$VERSION.json" s3cmd put -P "$JSONFILE" "s3://ziglang.org/builds/$ARCH-linux-$VERSION.json"
if [ "$GITBRANCH" = "master" ]; then if [ "$GITBRANCH" = "master" ]; then
# avoid leaking oauth token # avoid leaking oauth token
set +x set +x

View File

@@ -1,52 +0,0 @@
#!/bin/sh
. ./ci/drone/linux_script_base
BUILD_FLAGS="-Dskip-non-native"
case "$1" in
1)
./build/zig build $BUILD_FLAGS test-behavior
./build/zig build $BUILD_FLAGS test-compiler-rt
./build/zig build $BUILD_FLAGS test-fmt
./build/zig build $BUILD_FLAGS docs
;;
2)
# Debug
./build/zig build $BUILD_FLAGS test-std -Dskip-release-safe -Dskip-release-fast -Dskip-release-small
;;
3)
# ReleaseSafe
./build/zig build $BUILD_FLAGS test-std -Dskip-debug -Dskip-release-fast -Dskip-release-small
;;
4)
# Releasefast
./build/zig build $BUILD_FLAGS test-std -Dskip-debug -Dskip-release-safe -Dskip-release-small
;;
5)
# ReleaseSmall
./build/zig build $BUILD_FLAGS test-std -Dskip-debug -Dskip-release-safe -Dskip-release-fast
;;
6)
./build/zig build $BUILD_FLAGS test-minilibc
./build/zig build $BUILD_FLAGS test-compare-output
./build/zig build $BUILD_FLAGS test-standalone -Dskip-release-safe
./build/zig build $BUILD_FLAGS test-stack-traces
./build/zig build $BUILD_FLAGS test-cli
./build/zig build $BUILD_FLAGS test-asm-link
./build/zig build $BUILD_FLAGS test-runtime-safety
./build/zig build $BUILD_FLAGS test-translate-c
;;
7)
./build/zig build $BUILD_FLAGS # test building self-hosted without LLVM
./build/zig build $BUILD_FLAGS test-stage2
;;
'')
echo "error: expecting test group argument"
exit 1
;;
*)
echo "error: unknown test group: $1"
exit 1
;;
esac

10
ci/drone/test_linux_behavior Executable file
View File

@@ -0,0 +1,10 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
$ZIG build test-behavior -Dskip-non-native --zig-lib-dir lib

12
ci/drone/test_linux_cases Executable file
View File

@@ -0,0 +1,12 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
# test building self-hosted without LLVM
$ZIG build -Dskip-non-native --zig-lib-dir lib
$ZIG build test-cases -Dskip-non-native --zig-lib-dir lib

10
ci/drone/test_linux_docs Executable file
View File

@@ -0,0 +1,10 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
$ZIG build docs --zig-lib-dir lib

17
ci/drone/test_linux_misc Executable file
View File

@@ -0,0 +1,17 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
$ZIG build test-compiler-rt -Dskip-non-native --zig-lib-dir lib
$ZIG build test-compare-output -Dskip-non-native --zig-lib-dir lib
$ZIG build test-universal-libc -Dskip-non-native --zig-lib-dir lib
$ZIG build test-stack-traces -Dskip-non-native --zig-lib-dir lib
$ZIG build test-cli -Dskip-non-native --zig-lib-dir lib
$ZIG build test-asm-link -Dskip-non-native --zig-lib-dir lib
$ZIG build test-translate-c -Dskip-non-native --zig-lib-dir lib
$ZIG build test-fmt --zig-lib-dir lib

10
ci/drone/test_linux_standalone Executable file
View File

@@ -0,0 +1,10 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
$ZIG build test-standalone -Dskip-non-native --zig-lib-dir lib -Dskip-release-safe

23
ci/drone/test_linux_std_Debug Executable file
View File

@@ -0,0 +1,23 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
$ZIG build test-std \
--zig-lib-dir lib \
-Dskip-release-safe \
-Dskip-release-fast \
-Dskip-release-small \
-Dskip-non-native \
-Dskip-single-threaded
# Produce the experimental std lib documentation.
mkdir -p "$INSTALL_PREFIX/doc/std"
$ZIG test "$DRONE_WORKSPACE/lib/std/std.zig" \
--zig-lib-dir "$DRONE_WORKSPACE/lib" \
-femit-docs="$INSTALL_PREFIX/doc/std" \
-fno-emit-bin

View File

@@ -0,0 +1,17 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
$ZIG build test-std \
--zig-lib-dir lib \
-Dskip-debug \
-Dskip-release-safe \
-Dskip-release-small \
-Dskip-non-native \
-Dskip-single-threaded \
-Dskip-libc

View File

@@ -0,0 +1,17 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
$ZIG build test-std \
--zig-lib-dir lib \
-Dskip-debug \
-Dskip-release-fast \
-Dskip-release-small \
-Dskip-non-native \
-Dskip-single-threaded \
-Dskip-libc

View File

@@ -0,0 +1,17 @@
#!/bin/sh
set -x
set -e
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"
ZIG="$INSTALL_PREFIX/bin/zig"
export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"
$ZIG build test-std \
--zig-lib-dir lib \
-Dskip-debug \
-Dskip-release-safe \
-Dskip-release-fast \
-Dskip-non-native \
-Dskip-single-threaded \
-Dskip-libc

View File

@@ -4,10 +4,12 @@ set -x
set -e set -e
sudo pkg update -fq sudo pkg update -fq
sudo pkg install -y cmake py38-s3cmd wget curl jq samurai sudo pkg install -y cmake py39-s3cmd wget curl jq samurai
ZIGDIR="$(pwd)" ZIGDIR="$(pwd)"
CACHE_BASENAME="zig+llvm+lld+clang-x86_64-freebsd-gnu-0.9.0-dev.1243+456d7e5f5" TARGET="x86_64-freebsd-gnu"
MCPU="baseline"
CACHE_BASENAME="zig+llvm+lld+clang-$TARGET-0.10.0-dev.4560+828735ac0"
PREFIX="$HOME/$CACHE_BASENAME" PREFIX="$HOME/$CACHE_BASENAME"
cd $HOME cd $HOME
@@ -29,34 +31,62 @@ export TERM=dumb
mkdir build mkdir build
cd build cd build
cmake .. \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_PREFIX_PATH=$PREFIX \
"-DCMAKE_INSTALL_PREFIX=$(pwd)/release" \
-DZIG_STATIC=ON \
-DZIG_TARGET_TRIPLE=x86_64-freebsd-gnu \
-GNinja
samu install
# TODO ld.lld: error: undefined symbol: main
# >>> referenced by crt1_c.c:75 (/usr/src/lib/csu/amd64/crt1_c.c:75) cmake .. \
# >>> /usr/lib/crt1.o:(_start) -DCMAKE_BUILD_TYPE=Release \
#release/bin/zig test ../test/behavior.zig -fno-stage1 -fLLVM -I ../test -DCMAKE_PREFIX_PATH=$PREFIX \
-DZIG_TARGET_TRIPLE="$TARGET" \
-DZIG_TARGET_MCPU="$MCPU" \
-DZIG_STATIC=ON \
-GNinja
# TODO: eliminate this workaround. Without this, zig does not end up passing
# -isystem /usr/include when building libc++, resulting in #include <sys/endian.h>
# "file not found" errors.
echo "include_dir=/usr/include" >>libc.txt
echo "sys_include_dir=/usr/include" >>libc.txt
echo "crt_dir=/usr/lib" >>libc.txt
echo "msvc_lib_dir=" >>libc.txt
echo "kernel32_lib_dir=" >>libc.txt
echo "gcc_dir=" >>libc.txt
ZIG_LIBC_TXT="$(pwd)/libc.txt"
ZIG_LIBC="$ZIG_LIBC_TXT" samu install
# Here we skip some tests to save time. # Here we skip some tests to save time.
release/bin/zig build test -Dskip-compile-errors -Dskip-non-native stage3/bin/zig build test docs \
--zig-lib-dir "$(pwd)/../lib" \
-Dstatic-llvm \
--search-prefix "$PREFIX" \
-Dskip-stage1 \
-Dskip-non-native
# Produce the experimental std lib documentation.
mkdir -p "stage3/doc/std"
stage3/bin/zig test "$(pwd)/../lib/std/std.zig" \
--zig-lib-dir "$(pwd)/../lib" \
-femit-docs="$(pwd)/stage3/doc/std/" \
-fno-emit-bin
if [ -f ~/.s3cfg ]; then if [ -f ~/.s3cfg ]; then
mv ../LICENSE release/ # Remove the unnecessary bin dir in stage3/bin/zig
mv ../zig-cache/langref.html release/ mv stage3/bin/zig stage3/
mv release/bin/zig release/ rmdir stage3/bin
rmdir release/bin
# Remove the unnecessary zig dir in stage3/lib/zig/std/std.zig
mv stage3/lib/zig stage3/lib2
rmdir stage3/lib
mv stage3/lib2 stage3/lib
mv ../LICENSE stage3/
mv ../zig-cache/langref.html stage3/doc/
GITBRANCH=$(basename $GITHUB_REF) GITBRANCH=$(basename $GITHUB_REF)
VERSION=$(release/zig version) VERSION=$(stage3/zig version)
DIRNAME="zig-freebsd-x86_64-$VERSION" DIRNAME="zig-freebsd-x86_64-$VERSION"
TARBALL="$DIRNAME.tar.xz" TARBALL="$DIRNAME.tar.xz"
mv release "$DIRNAME" mv stage3 "$DIRNAME"
tar cfJ "$TARBALL" "$DIRNAME" tar cfJ "$TARBALL" "$DIRNAME"
s3cmd put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/ s3cmd put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/

View File

@@ -40,6 +40,148 @@
"size": "{{AARCH64_LINUX_BYTESIZE}}" "size": "{{AARCH64_LINUX_BYTESIZE}}"
} }
}, },
"0.9.1": {
"date": "2022-02-14",
"docs": "https://ziglang.org/documentation/0.9.1/",
"stdDocs": "https://ziglang.org/documentation/0.9.1/std/",
"notes": "https://ziglang.org/download/0.9.1/release-notes.html",
"src": {
"tarball": "https://ziglang.org/download/0.9.1/zig-0.9.1.tar.xz",
"shasum": "38cf4e84481f5facc766ba72783e7462e08d6d29a5d47e3b75c8ee3142485210",
"size": "13940828"
},
"bootstrap": {
"tarball": "https://ziglang.org/download/0.9.1/zig-bootstrap-0.9.1.tar.xz",
"shasum": "0a8e221c71860d8975c15662b3ed3bd863e81c4fe383455a596e5e0e490d6109",
"size": "42488812"
},
"x86_64-freebsd": {
"tarball": "https://ziglang.org/download/0.9.1/zig-freebsd-x86_64-0.9.1.tar.xz",
"shasum": "4e06009bd3ede34b72757eec1b5b291b30aa0d5046dadd16ecb6b34a02411254",
"size": "39028848"
},
"aarch64-linux": {
"tarball": "https://ziglang.org/download/0.9.1/zig-linux-aarch64-0.9.1.tar.xz",
"shasum": "5d99a39cded1870a3fa95d4de4ce68ac2610cca440336cfd252ffdddc2b90e66",
"size": "37034860"
},
"armv7a-linux": {
"tarball": "https://ziglang.org/download/0.9.1/zig-linux-armv7a-0.9.1.tar.xz",
"shasum": "6de64456cb4757a555816611ea697f86fba7681d8da3e1863fa726a417de49be",
"size": "37974652"
},
"i386-linux": {
"tarball": "https://ziglang.org/download/0.9.1/zig-linux-i386-0.9.1.tar.xz",
"shasum": "e776844fecd2e62fc40d94718891057a1dbca1816ff6013369e9a38c874374ca",
"size": "44969172"
},
"riscv64-linux": {
"tarball": "https://ziglang.org/download/0.9.1/zig-linux-riscv64-0.9.1.tar.xz",
"shasum": "208dea53662c2c52777bd9e3076115d2126a4f71aed7f2ff3b8fe224dc3881aa",
"size": "39390868"
},
"x86_64-linux": {
"tarball": "https://ziglang.org/download/0.9.1/zig-linux-x86_64-0.9.1.tar.xz",
"shasum": "be8da632c1d3273f766b69244d80669fe4f5e27798654681d77c992f17c237d7",
"size": "41011464"
},
"aarch64-macos": {
"tarball": "https://ziglang.org/download/0.9.1/zig-macos-aarch64-0.9.1.tar.xz",
"shasum": "8c473082b4f0f819f1da05de2dbd0c1e891dff7d85d2c12b6ee876887d438287",
"size": "38995640"
},
"x86_64-macos": {
"tarball": "https://ziglang.org/download/0.9.1/zig-macos-x86_64-0.9.1.tar.xz",
"shasum": "2d94984972d67292b55c1eb1c00de46580e9916575d083003546e9a01166754c",
"size": "43713044"
},
"i386-windows": {
"tarball": "https://ziglang.org/download/0.9.1/zig-windows-i386-0.9.1.zip",
"shasum": "74a640ed459914b96bcc572183a8db687bed0af08c30d2ea2f8eba03ae930f69",
"size": "67929868"
},
"x86_64-windows": {
"tarball": "https://ziglang.org/download/0.9.1/zig-windows-x86_64-0.9.1.zip",
"shasum": "443da53387d6ae8ba6bac4b3b90e9fef4ecbe545e1c5fa3a89485c36f5c0e3a2",
"size": "65047697"
},
"aarch64-windows": {
"tarball": "https://ziglang.org/download/0.9.1/zig-windows-aarch64-0.9.1.zip",
"shasum": "621bf95f54dc3ff71466c5faae67479419951d7489e40e87fd26d195825fb842",
"size": "61478151"
}
},
"0.9.0": {
"date": "2021-12-20",
"docs": "https://ziglang.org/documentation/0.9.0/",
"stdDocs": "https://ziglang.org/documentation/0.9.0/std/",
"notes": "https://ziglang.org/download/0.9.0/release-notes.html",
"src": {
"tarball": "https://ziglang.org/download/0.9.0/zig-0.9.0.tar.xz",
"shasum": "cd1be83b12f8269cc5965e59877b49fdd8fa638efb6995ac61eb4cea36a2e381",
"size": "13928772"
},
"bootstrap": {
"tarball": "https://ziglang.org/download/0.9.0/zig-bootstrap-0.9.0.tar.xz",
"shasum": "16b0bdf0bc0a5ed1e0950e08481413d806192e06443a512347526647b2baeabc",
"size": "42557736"
},
"x86_64-freebsd": {
"tarball": "https://ziglang.org/download/0.9.0/zig-freebsd-x86_64-0.9.0.tar.xz",
"shasum": "c95afe679b7cc4110dc2ecd3606c83a699718b7a958d6627f74c20886333e194",
"size": "41293236"
},
"aarch64-linux": {
"tarball": "https://ziglang.org/download/0.9.0/zig-linux-aarch64-0.9.0.tar.xz",
"shasum": "1524fedfdbade2dbc9bae1ed98ad38fa7f2114c9a3e94da0d652573c75efbc5a",
"size": "40008396"
},
"armv7a-linux": {
"tarball": "https://ziglang.org/download/0.9.0/zig-linux-armv7a-0.9.0.tar.xz",
"shasum": "50225dee6e6448a63ee96383a34d9fe3bba34ae8da1a0c8619bde2cdfc1df87d",
"size": "41196876"
},
"i386-linux": {
"tarball": "https://ziglang.org/download/0.9.0/zig-linux-i386-0.9.0.tar.xz",
"shasum": "b0dcf688349268c883292acdd55eaa3c13d73b9146e4b990fad95b84a2ac528b",
"size": "47408656"
},
"riscv64-linux": {
"tarball": "https://ziglang.org/download/0.9.0/zig-linux-riscv64-0.9.0.tar.xz",
"shasum": "85466de07504767ed37f59782672ad41bbdf43d6480fafd07f45543278b07620",
"size": "44171420"
},
"x86_64-linux": {
"tarball": "https://ziglang.org/download/0.9.0/zig-linux-x86_64-0.9.0.tar.xz",
"shasum": "5c55344a877d557fb1b28939785474eb7f4f2f327aab55293998f501f7869fa6",
"size": "43420796"
},
"aarch64-macos": {
"tarball": "https://ziglang.org/download/0.9.0/zig-macos-aarch64-0.9.0.tar.xz",
"shasum": "3991c70594d61d09fb4b316157a7c1d87b1d4ec159e7a5ecd11169ff74cad832",
"size": "39013392"
},
"x86_64-macos": {
"tarball": "https://ziglang.org/download/0.9.0/zig-macos-x86_64-0.9.0.tar.xz",
"shasum": "c5280eeec4d6e5ea5ce5b448dc9a7c4bdd85ecfed4c1b96aa0835e48b36eccf0",
"size": "43764596"
},
"i386-windows": {
"tarball": "https://ziglang.org/download/0.9.0/zig-windows-i386-0.9.0.zip",
"shasum": "bb839434afc75092015cf4c33319d31463c18512bc01dd719aedf5dcbc368466",
"size": "67946715"
},
"x86_64-windows": {
"tarball": "https://ziglang.org/download/0.9.0/zig-windows-x86_64-0.9.0.zip",
"shasum": "084ea2646850aaf068234b0f1a92b914ed629be47075e835f8a67d55c21d880e",
"size": "65045849"
},
"aarch64-windows": {
"tarball": "https://ziglang.org/download/0.9.0/zig-windows-aarch64-0.9.0.zip",
"shasum": "f9018725e3fb2e8992b17c67034726971156eb190685018a9ac8c3a9f7a22340",
"size": "61461921"
}
},
"0.8.1": { "0.8.1": {
"date": "2021-09-06", "date": "2021-09-06",
"docs": "https://ziglang.org/documentation/0.8.1/", "docs": "https://ziglang.org/documentation/0.8.1/",

View File

@@ -57,7 +57,7 @@ unset CXX
#release/bin/zig test ../test/behavior.zig -fno-stage1 -fLLVM -I ../test #release/bin/zig test ../test/behavior.zig -fno-stage1 -fLLVM -I ../test
# Here we skip some tests to save time. # Here we skip some tests to save time.
release/bin/zig build test -Dskip-compile-errors -Dskip-non-native release/bin/zig build test -Dskip-stage1 -Dskip-non-native
if [ -f ~/.s3cfg ]; then if [ -f ~/.s3cfg ]; then
mv ../LICENSE release/ mv ../LICENSE release/

View File

@@ -48,7 +48,7 @@ wget "https://ziglang.org/builds/$NATIVE_TARBALL"
tar xf "$NATIVE_TARBALL" tar xf "$NATIVE_TARBALL"
ZIGDIR="$(pwd)/$(basename $NATIVE_TARBALL .tar.xz)" ZIGDIR="$(pwd)/$(basename $NATIVE_TARBALL .tar.xz)"
ZIG="$ZIGDIR/zig" ZIG="$ZIGDIR/zig"
LANGREF="$ZIGDIR/docs/langref.html" LANGREF="$ZIGDIR/doc/langref.html"
SRCTARBALLDIR="zig-$VERSION" SRCTARBALLDIR="zig-$VERSION"
export SRC_TARBALL="$SRCTARBALLDIR.tar.xz" export SRC_TARBALL="$SRCTARBALLDIR.tar.xz"
mv "$SRCDIR" "$SRCTARBALLDIR" mv "$SRCDIR" "$SRCTARBALLDIR"
@@ -100,20 +100,51 @@ cd "$SRCTARBALLDIR/ci/srht"
CIDIR="$(pwd)" CIDIR="$(pwd)"
cd "$HOME" cd "$HOME"
# Update autodocs and langref directly to S3 in order to prevent the
# www.ziglang.org git repo from growing too big.
# Please do not edit this script to pre-compress the artifacts before they hit
# S3. This prevents the website from working on browsers that do not support gzip
# encoding. Cloudfront will automatically compress files if they are less than
# 9.5 MiB, and the client advertises itself as capable of decompressing.
# The data.js file is currently 16 MiB. In order to fix this problem, we need to do
# one of the following things:
# * Reduce the size of data.js to less than 9.5 MiB.
# * Figure out how to adjust the Cloudfront settings to increase the max size for
# auto-compressed objects.
# * Migrate to fastly.
$S3CMD put -P --no-mime-magic \
--add-header="Cache-Control: max-age=0, must-revalidate" \
"$LANGREF" s3://ziglang.org/documentation/master/index.html
$S3CMD put -P --no-mime-magic \
--add-header="Cache-Control: max-age=0, must-revalidate" \
"$ZIGDIR/doc/std/index.html" s3://ziglang.org/documentation/master/std/index.html
$S3CMD put -P --no-mime-magic \
--add-header="Cache-Control: max-age=0, must-revalidate" \
"$ZIGDIR/doc/std/main.js" s3://ziglang.org/documentation/master/std/main.js
$S3CMD put -P --no-mime-magic \
--add-header="Cache-Control: max-age=0, must-revalidate" \
"$ZIGDIR/doc/std/data.js" s3://ziglang.org/documentation/master/std/data.js
$S3CMD put -P --no-mime-magic --recursive \
--add-header="Cache-Control: max-age=0, must-revalidate" \
-m "text/html" \
"$ZIGDIR/doc/std/src/" s3://ziglang.org/documentation/master/std/src/
$S3CMD put -P --no-mime-magic \
--add-header="cache-control: public, max-age=31536000, immutable" \
"$HOME/$SRC_TARBALL" s3://ziglang.org/builds/
git clone --depth 1 git@github.com:ziglang/www.ziglang.org.git git clone --depth 1 git@github.com:ziglang/www.ziglang.org.git
cd www.ziglang.org cd www.ziglang.org
WWWDIR="$(pwd)" WWWDIR="$(pwd)"
$S3CMD put -P --no-mime-magic --add-header="cache-control: public, max-age=31536000, immutable" "$HOME/$SRC_TARBALL" s3://ziglang.org/builds/
cd "$WWWDIR" cd "$WWWDIR"
cp "$CIDIR/out/index.json" data/releases.json cp "$CIDIR/out/index.json" data/releases.json
mkdir -p content/documentation/master/std
cp "$LANGREF" content/documentation/master/index.html
cp "$ZIGDIR/docs/std/index.html" content/documentation/master/std/index.html
cp "$ZIGDIR/docs/std/data.js" content/documentation/master/std/data.js
cp "$ZIGDIR/docs/std/main.js" content/documentation/master/std/main.js
git add data/releases.json git add data/releases.json
git add content/ git commit -m "CI: update releases"
git commit -m "CI: update releases and docs"
git push origin master git push origin master

20
ci/zinc/build_aarch64_macos Executable file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
set -x
set -e
RELEASE_STAGING="$DRONE_WORKSPACE/_release/staging"
TARGET="aarch64-macos-none"
MCPU="apple_a14"
INSTALL_PREFIX="$DRONE_WORKSPACE/$TARGET"
SEARCH_PREFIX="/deps/$TARGET"
"$RELEASE_STAGING/bin/zig" build \
--prefix "$INSTALL_PREFIX" \
--search-prefix "$SEARCH_PREFIX" \
-Dstatic-llvm \
-Drelease \
-Dstrip \
-Dtarget="$TARGET" \
-Dcpu="$MCPU" \
-Denable-stage1

10
ci/zinc/configure_git Executable file
View File

@@ -0,0 +1,10 @@
#!/bin/sh
set -x
set -e
# Make the `zig version` number consistent.
# This will affect the cmake commands that follow.
# This is in its own script because git does not support this command
# being run concurrently with itself.
git config core.abbrev 9

View File

@@ -9,38 +9,80 @@ workspace:
path: /workspace path: /workspace
steps: steps:
- name: probe - name: configure_git
image: ci/debian-amd64:11.1-2 image: ci/debian-amd64:11.1-12
commands: commands:
- ./ci/zinc/linux_probe.sh - ./ci/zinc/configure_git
- name: build - name: test_stage3_debug
image: ci/debian-amd64:11.1-2
commands:
- ./ci/zinc/linux_build.sh
- name: test
depends_on: depends_on:
- build - configure_git
image: ci/debian-amd64:11.1-2 image: ci/debian-amd64:11.1-12
commands: commands:
- ./ci/zinc/linux_test.sh - ./ci/zinc/linux_test_stage3_debug
- name: package - name: test_stage3_release
depends_on: depends_on:
- test - configure_git
image: ci/debian-amd64:11.1-12
commands:
- ./ci/zinc/linux_test_stage3_release
- name: build_aarch64_macos
depends_on:
- test_stage3_release
image: ci/debian-amd64:11.1-12
commands:
- ./ci/zinc/build_aarch64_macos
- name: linux_package
depends_on:
- test_stage3_debug
- test_stage3_release
when: when:
branch: branch:
- master - master
event: event:
- push - push
image: ci/debian-amd64:11.1-2 image: ci/debian-amd64:11.1-12
environment: environment:
AWS_ACCESS_KEY_ID: AWS_ACCESS_KEY_ID:
from_secret: AWS_ACCESS_KEY_ID from_secret: AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY: AWS_SECRET_ACCESS_KEY:
from_secret: AWS_SECRET_ACCESS_KEY from_secret: AWS_SECRET_ACCESS_KEY
commands:
- ./ci/zinc/linux_package
- name: macos_package
depends_on:
- test_stage3_debug
- build_aarch64_macos
when:
branch:
- master
event:
- push
image: ci/debian-amd64:11.1-12
environment:
AWS_ACCESS_KEY_ID:
from_secret: AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY:
from_secret: AWS_SECRET_ACCESS_KEY
commands:
- ./ci/zinc/macos_package
- name: notify_lavahut
depends_on:
- macos_package
- linux_package
when:
branch:
- master
event:
- push
image: ci/debian-amd64:11.1-12
environment:
SRHT_OAUTH_TOKEN: SRHT_OAUTH_TOKEN:
from_secret: SRHT_OAUTH_TOKEN from_secret: SRHT_OAUTH_TOKEN
commands: commands:
- ./ci/zinc/linux_package.sh - ./ci/zinc/notify_lavahut

View File

@@ -1,28 +0,0 @@
#!/bin/sh
# https://docs.drone.io/pipeline/docker/syntax/workspace/
#
# Drone automatically creates a temporary volume, known as your workspace,
# where it clones your repository. The workspace is the current working
# directory for each step in your pipeline.
#
# Because the workspace is a volume, filesystem changes are persisted between
# pipeline steps. In other words, individual steps can communicate and share
# state using the filesystem.
#
# Workspace volumes are ephemeral. They are created when the pipeline starts
# and destroyed after the pipeline completes.
set -x
set -e
ARCH="$(uname -m)"
JOBS="-j$(nproc)"
DEPS_LOCAL="/deps/local"
WORKSPACE="$DRONE_WORKSPACE"
DEBUG_STAGING="$WORKSPACE/_debug/staging"
RELEASE_STAGING="$WORKSPACE/_release/staging"
export PATH=$DEPS_LOCAL/bin:$PATH

View File

@@ -1,72 +0,0 @@
#!/bin/sh
. ./ci/zinc/linux_base.sh
ZIG="$DEPS_LOCAL/bin/zig"
TARGET="${ARCH}-linux-musl"
MCPU="baseline"
# Make the `zig version` number consistent.
# This will affect the cmake command below.
git config core.abbrev 9
# Build debug zig.
echo "BUILD debug zig with zig:$($ZIG version)"
export CC="$ZIG cc -target $TARGET -mcpu=$MCPU"
export CXX="$ZIG c++ -target $TARGET -mcpu=$MCPU"
mkdir _debug
cd _debug
cmake .. \
-DCMAKE_INSTALL_PREFIX="$DEBUG_STAGING" \
-DCMAKE_PREFIX_PATH="$DEPS_LOCAL" \
-DCMAKE_BUILD_TYPE=Debug \
-DZIG_TARGET_TRIPLE="$TARGET" \
-DZIG_TARGET_MCPU="$MCPU" \
-DZIG_STATIC=ON \
-GNinja
# Now cmake will use zig as the C/C++ compiler. We reset the environment variables
# so that installation and testing do not get affected by them.
unset CC
unset CXX
ninja $JOBS install
ZIG=$DEBUG_STAGING/bin/zig
# Here we rebuild zig but this time using the Zig binary we just now produced to
# build zig1.o rather than relying on the one built with stage0. See
# https://github.com/ziglang/zig/issues/6830 for more details.
cmake .. -DZIG_EXECUTABLE="$ZIG"
ninja $JOBS install
cd $WORKSPACE
# Build release zig.
echo "BUILD release zig with zig:$($ZIG version)"
export CC="$ZIG cc -target $TARGET -mcpu=$MCPU"
export CXX="$ZIG c++ -target $TARGET -mcpu=$MCPU"
mkdir _release
cd _release
cmake .. \
-DCMAKE_INSTALL_PREFIX="$RELEASE_STAGING" \
-DCMAKE_PREFIX_PATH="$DEPS_LOCAL" \
-DCMAKE_BUILD_TYPE=Release \
-DZIG_TARGET_TRIPLE="$TARGET" \
-DZIG_TARGET_MCPU="$MCPU" \
-DZIG_STATIC=ON \
-GNinja
unset CC
unset CXX
ninja $JOBS install
cd $WORKSPACE
# Look for non-conforming code formatting.
# Formatting errors can be fixed by running `zig fmt` on the files printed here.
$ZIG fmt --check .
# Explicit exit helps show last command duration.
exit

45
ci/zinc/linux_package Executable file
View File

@@ -0,0 +1,45 @@
#!/bin/sh
set -x
set -e
ARCH="$(uname -m)"
OS="linux"
RELEASE_STAGING="$DRONE_WORKSPACE/_release/staging"
VERSION=$($RELEASE_STAGING/bin/zig version)
BASENAME="zig-$OS-$ARCH-$VERSION"
TARBALL="$BASENAME.tar.xz"
# This runs concurrently with the macos_package script, so it should not make
# any changes to the filesystem that will cause problems for the other script.
cp -r "$RELEASE_STAGING" "$BASENAME"
# Remove the unnecessary bin dir in $prefix/bin/zig
mv $BASENAME/bin/zig $BASENAME/
rmdir $BASENAME/bin
# Remove the unnecessary zig dir in $prefix/lib/zig/std/std.zig
mv $BASENAME/lib/zig $BASENAME/lib2
rmdir $BASENAME/lib
mv $BASENAME/lib2 $BASENAME/lib
tar cfJ "$TARBALL" "$BASENAME"
SHASUM=$(sha256sum $TARBALL | cut '-d ' -f1)
BYTESIZE=$(wc -c < $TARBALL)
MANIFEST="manifest-$TARGET.json"
touch $MANIFEST
echo "{\"tarball\": \"$TARBALL\"," >>$MANIFEST
echo "\"shasum\": \"$SHASUM\"," >>$MANIFEST
echo "\"size\": \"$BYTESIZE\"}" >>$MANIFEST
# Publish artifact.
s3cmd put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/
# Publish manifest.
s3cmd put -P --add-header="cache-control: max-age=0, must-revalidate" "$MANIFEST" "s3://ziglang.org/builds/$ARCH-$OS-$VERSION.json"
# Explicit exit helps show last command duration.
exit

View File

@@ -1,48 +0,0 @@
#!/bin/sh
. ./ci/zinc/linux_base.sh
cp LICENSE $RELEASE_STAGING/
cp zig-cache/langref.html $RELEASE_STAGING/docs/
# Remove the unnecessary bin dir in $prefix/bin/zig
mv $RELEASE_STAGING/bin/zig $RELEASE_STAGING/
rmdir $RELEASE_STAGING/bin
# Remove the unnecessary zig dir in $prefix/lib/zig/std/std.zig
mv $RELEASE_STAGING/lib/zig $RELEASE_STAGING/lib2
rmdir $RELEASE_STAGING/lib
mv $RELEASE_STAGING/lib2 $RELEASE_STAGING/lib
VERSION=$($RELEASE_STAGING/zig version)
BASENAME="zig-linux-$ARCH-$VERSION"
TARBALL="$BASENAME.tar.xz"
mv "$RELEASE_STAGING" "$BASENAME"
tar cfJ "$TARBALL" "$BASENAME"
ls -l "$TARBALL"
SHASUM=$(sha256sum $TARBALL | cut '-d ' -f1)
BYTESIZE=$(wc -c < $TARBALL)
MANIFEST="manifest.json"
touch $MANIFEST
echo "{\"tarball\": \"$TARBALL\"," >>$MANIFEST
echo "\"shasum\": \"$SHASUM\"," >>$MANIFEST
echo "\"size\": \"$BYTESIZE\"}" >>$MANIFEST
# Publish artifact.
s3cmd put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/
# Publish manifest.
s3cmd put -P --add-header="cache-control: max-age=0, must-revalidate" "$MANIFEST" "s3://ziglang.org/builds/$ARCH-linux-$VERSION.json"
# Avoid leaking oauth token.
set +x
cd $WORKSPACE
./ci/srht/on_master_success "$VERSION" "$SRHT_OAUTH_TOKEN"
set -x
# Explicit exit helps show last command duration.
exit

View File

@@ -1,10 +0,0 @@
#!/bin/sh
. ./ci/zinc/linux_base.sh
# Probe CPU/brand details.
echo "lscpu:"
(lscpu | sed 's,^, : ,') 1>&2
# Explicit exit helps show last command duration.
exit

View File

@@ -1,40 +0,0 @@
#!/bin/sh
. ./ci/zinc/linux_base.sh
ZIG=$DEBUG_STAGING/bin/zig
$ZIG test test/behavior.zig -fno-stage1 -fLLVM -I test
$ZIG test test/behavior.zig -fno-stage1 -ofmt=c -I test
$ZIG test test/behavior.zig -fno-stage1 -target wasm32-wasi --test-cmd wasmtime --test-cmd-bin
$ZIG build test-behavior -fqemu -fwasmtime
$ZIG build test-compiler-rt -fqemu -fwasmtime
$ZIG build test-std -fqemu -fwasmtime
$ZIG build test-minilibc -fqemu -fwasmtime
$ZIG build test-compare-output -fqemu -fwasmtime
$ZIG build test-standalone -fqemu -fwasmtime
$ZIG build test-stack-traces -fqemu -fwasmtime
$ZIG build test-cli -fqemu -fwasmtime
$ZIG build test-asm-link -fqemu -fwasmtime
$ZIG build test-runtime-safety -fqemu -fwasmtime
$ZIG build test-translate-c -fqemu -fwasmtime
$ZIG build test-run-translated-c -fqemu -fwasmtime
$ZIG build docs -fqemu -fwasmtime
$ZIG build # test building self-hosted without LLVM
$ZIG build -Dtarget=arm-linux-musleabihf # test building self-hosted for 32-bit arm
$ZIG build test-fmt -fqemu -fwasmtime
$ZIG build test-stage2 -fqemu -fwasmtime
# Produce the experimental std lib documentation.
mkdir -p $RELEASE_STAGING/docs/std
$ZIG test lib/std/std.zig \
--zig-lib-dir lib \
-femit-docs=$RELEASE_STAGING/docs/std \
-fno-emit-bin
# Look for HTML errors.
tidy --drop-empty-elements no -qe zig-cache/langref.html
# Explicit exit helps show last command duration.
exit

62
ci/zinc/linux_test_stage3_debug Executable file
View File

@@ -0,0 +1,62 @@
#!/bin/sh
set -x
set -e
ARCH="$(uname -m)"
DEPS_LOCAL="/deps/local"
OLD_ZIG="$DEPS_LOCAL/bin/zig"
TARGET="${ARCH}-linux-musl"
MCPU="baseline"
export PATH=$DEPS_LOCAL/bin:$PATH
echo "building stage3-debug with zig version $($OLD_ZIG version)"
# Override the cache directories so that we don't clobber with the release
# testing script which is running concurrently and in the same directory.
# Normally we want processes to cooperate, but in this case we want them isolated.
export ZIG_LOCAL_CACHE_DIR="$(pwd)/zig-cache-local-debug"
export ZIG_GLOBAL_CACHE_DIR="$(pwd)/zig-cache-global-debug"
export CC="$OLD_ZIG cc -target $TARGET -mcpu=$MCPU"
export CXX="$OLD_ZIG c++ -target $TARGET -mcpu=$MCPU"
mkdir build-debug
cd build-debug
cmake .. \
-DCMAKE_INSTALL_PREFIX="$(pwd)/stage3" \
-DCMAKE_PREFIX_PATH="$DEPS_LOCAL" \
-DCMAKE_BUILD_TYPE=Debug \
-DZIG_STATIC=ON \
-DZIG_USE_LLVM_CONFIG=OFF \
-GNinja
# Now cmake will use zig as the C/C++ compiler. We reset the environment variables
# so that installation and testing do not get affected by them.
unset CC
unset CXX
ninja install
echo "Looking for non-conforming code formatting..."
stage3/bin/zig fmt --check .. \
--exclude ../test/cases/ \
--exclude ../build-debug \
--exclude ../build-release \
--exclude "$ZIG_LOCAL_CACHE_DIR" \
--exclude "$ZIG_GLOBAL_CACHE_DIR"
# simultaneously test building self-hosted without LLVM and with 32-bit arm
stage3/bin/zig build -Dtarget=arm-linux-musleabihf
stage3/bin/zig build test \
-fqemu \
-fwasmtime \
-Dstatic-llvm \
-Dtarget=native-native-musl \
--search-prefix "$DEPS_LOCAL" \
--zig-lib-dir "$(pwd)/../lib"
# Explicit exit helps show last command duration.
exit

View File

@@ -0,0 +1,60 @@
#!/bin/sh
set -x
set -e
ARCH="$(uname -m)"
DEPS_LOCAL="/deps/local"
RELEASE_STAGING="$DRONE_WORKSPACE/_release/staging"
OLD_ZIG="$DEPS_LOCAL/bin/zig"
TARGET="${ARCH}-linux-musl"
MCPU="baseline"
export PATH=$DEPS_LOCAL/bin:$PATH
echo "building stage3-release with zig version $($OLD_ZIG version)"
export CC="$OLD_ZIG cc -target $TARGET -mcpu=$MCPU"
export CXX="$OLD_ZIG c++ -target $TARGET -mcpu=$MCPU"
mkdir build-release
cd build-release
cmake .. \
-DCMAKE_INSTALL_PREFIX="$RELEASE_STAGING" \
-DCMAKE_PREFIX_PATH="$DEPS_LOCAL" \
-DCMAKE_BUILD_TYPE=Release \
-DZIG_TARGET_TRIPLE="$TARGET" \
-DZIG_TARGET_MCPU="$MCPU" \
-DZIG_STATIC=ON \
-GNinja
# Now cmake will use zig as the C/C++ compiler. We reset the environment variables
# so that installation and testing do not get affected by them.
unset CC
unset CXX
ninja install
"$RELEASE_STAGING/bin/zig" build test docs \
-fqemu \
-fwasmtime \
-Dstatic-llvm \
-Dtarget=native-native-musl \
--search-prefix "$DEPS_LOCAL" \
--zig-lib-dir "$(pwd)/../lib"
# Produce the experimental std lib documentation.
mkdir -p "$RELEASE_STAGING/doc/std"
"$RELEASE_STAGING/bin/zig" test ../lib/std/std.zig \
-femit-docs=$RELEASE_STAGING/doc/std \
-fno-emit-bin \
--zig-lib-dir "$(pwd)/../lib"
cp ../LICENSE $RELEASE_STAGING/
cp ../zig-cache/langref.html $RELEASE_STAGING/doc/
# Look for HTML errors.
tidy --drop-empty-elements no -qe $RELEASE_STAGING/doc/langref.html
# Explicit exit helps show last command duration.
exit

49
ci/zinc/macos_package Executable file
View File

@@ -0,0 +1,49 @@
#!/bin/sh
set -x
set -e
ARCH="aarch64"
OS=macos
ZIG_PREFIX="$DRONE_WORKSPACE/_release/staging"
VERSION=$($ZIG_PREFIX/bin/zig version)
TARGET="$ARCH-$OS-none"
INSTALL_PREFIX="$DRONE_WORKSPACE/$TARGET"
BASENAME="zig-$OS-$ARCH-$VERSION"
TARBALL="$BASENAME.tar.xz"
# This runs concurrently with the linux_package script, so it should not make
# any changes to the filesystem that will cause problems for the other script.
# Remove the unnecessary bin dir in $prefix/bin/zig
mv $INSTALL_PREFIX/bin/zig $INSTALL_PREFIX/
rmdir $INSTALL_PREFIX/bin
# Remove the unnecessary zig dir in $prefix/lib/zig/std/std.zig
mv $INSTALL_PREFIX/lib/zig $INSTALL_PREFIX/lib2
rmdir $INSTALL_PREFIX/lib
mv $INSTALL_PREFIX/lib2 $INSTALL_PREFIX/lib
cp -r "$ZIG_PREFIX/doc" "$INSTALL_PREFIX/"
cp "$ZIG_PREFIX/LICENSE" "$INSTALL_PREFIX/"
mv "$INSTALL_PREFIX" "$BASENAME"
tar cfJ "$TARBALL" "$BASENAME"
SHASUM=$(sha256sum $TARBALL | cut '-d ' -f1)
BYTESIZE=$(wc -c < $TARBALL)
MANIFEST="manifest-$TARGET.json"
touch $MANIFEST
echo "{\"tarball\": \"$TARBALL\"," >>$MANIFEST
echo "\"shasum\": \"$SHASUM\"," >>$MANIFEST
echo "\"size\": \"$BYTESIZE\"}" >>$MANIFEST
# Publish artifact.
s3cmd put -P --add-header="cache-control: public, max-age=31536000, immutable" "$TARBALL" s3://ziglang.org/builds/
# Publish manifest.
s3cmd put -P --add-header="cache-control: max-age=0, must-revalidate" "$MANIFEST" "s3://ziglang.org/builds/$ARCH-$OS-$VERSION.json"
# Explicit exit helps show last command duration.
exit

9
ci/zinc/notify_lavahut Executable file
View File

@@ -0,0 +1,9 @@
#!/bin/sh
set +x # Avoid leaking oauth token.
set -e
ZIG_PREFIX="$DRONE_WORKSPACE/_release/staging"
VERSION=$($ZIG_PREFIX/bin/zig version)
cd $DRONE_WORKSPACE
./ci/srht/on_master_success "$VERSION" "$SRHT_OAUTH_TOKEN"

View File

@@ -8,51 +8,33 @@
# CLANG_LIBDIRS # CLANG_LIBDIRS
find_path(CLANG_INCLUDE_DIRS NAMES clang/Frontend/ASTUnit.h find_path(CLANG_INCLUDE_DIRS NAMES clang/Frontend/ASTUnit.h
PATHS HINTS ${LLVM_INCLUDE_DIRS}
/usr/lib/llvm/13/include # Only look for Clang next to LLVM or in { CMAKE_PREFIX_PATH, CMAKE_LIBRARY_PATH, CMAKE_FRAMEWORK_PATH }
/usr/lib/llvm-13/include NO_SYSTEM_ENVIRONMENT_PATH
/usr/lib/llvm-13.0/include NO_CMAKE_SYSTEM_PATH
/usr/local/llvm130/include
/usr/local/llvm13/include
/usr/local/opt/llvm@13/include
/opt/homebrew/opt/llvm@13/include
/mingw64/include
) )
if(ZIG_PREFER_CLANG_CPP_DYLIB) if(${LLVM_LINK_MODE} STREQUAL "shared")
find_library(CLANG_LIBRARIES find_library(CLANG_LIBRARIES
NAMES NAMES
clang-cpp-13.0 libclang-cpp.so.15
clang-cpp130 clang-cpp-15.0
clang-cpp150
clang-cpp clang-cpp
PATHS NAMES_PER_DIR
${CLANG_LIBDIRS} HINTS "${LLVM_LIBDIRS}"
/usr/lib/llvm/13/lib # Only look for Clang next to LLVM or in { CMAKE_PREFIX_PATH, CMAKE_LIBRARY_PATH, CMAKE_FRAMEWORK_PATH }
/usr/lib/llvm/13/lib64 NO_SYSTEM_ENVIRONMENT_PATH
/usr/lib/llvm-13/lib NO_CMAKE_SYSTEM_PATH
/usr/local/llvm130/lib
/usr/local/llvm13/lib
/usr/local/opt/llvm@13/lib
/opt/homebrew/opt/llvm@13/lib
) )
endif() else()
if(NOT CLANG_LIBRARIES)
macro(FIND_AND_ADD_CLANG_LIB _libname_) macro(FIND_AND_ADD_CLANG_LIB _libname_)
string(TOUPPER ${_libname_} _prettylibname_) string(TOUPPER ${_libname_} _prettylibname_)
find_library(CLANG_${_prettylibname_}_LIB NAMES ${_libname_} find_library(CLANG_${_prettylibname_}_LIB NAMES ${_libname_} NAMES_PER_DIR
PATHS HINTS "${LLVM_LIBDIRS}"
${CLANG_LIBDIRS} # Only look for Clang next to LLVM or in { CMAKE_PREFIX_PATH, CMAKE_LIBRARY_PATH, CMAKE_FRAMEWORK_PATH }
/usr/lib/llvm/13/lib NO_SYSTEM_ENVIRONMENT_PATH
/usr/lib/llvm-13/lib NO_CMAKE_SYSTEM_PATH
/usr/lib/llvm-13.0/lib
/usr/local/llvm130/lib
/usr/local/llvm13/lib
/usr/local/opt/llvm@13/lib
/opt/homebrew/opt/llvm@13/lib
/mingw64/lib
/c/msys64/mingw64/lib
c:\\msys64\\mingw64\\lib
) )
if(CLANG_${_prettylibname_}_LIB) if(CLANG_${_prettylibname_}_LIB)
set(CLANG_LIBRARIES ${CLANG_LIBRARIES} ${CLANG_${_prettylibname_}_LIB}) set(CLANG_LIBRARIES ${CLANG_LIBRARIES} ${CLANG_${_prettylibname_}_LIB})
@@ -82,6 +64,8 @@ if(NOT CLANG_LIBRARIES)
FIND_AND_ADD_CLANG_LIB(clangCrossTU) FIND_AND_ADD_CLANG_LIB(clangCrossTU)
FIND_AND_ADD_CLANG_LIB(clangIndex) FIND_AND_ADD_CLANG_LIB(clangIndex)
FIND_AND_ADD_CLANG_LIB(clangToolingCore) FIND_AND_ADD_CLANG_LIB(clangToolingCore)
FIND_AND_ADD_CLANG_LIB(clangExtractAPI)
FIND_AND_ADD_CLANG_LIB(clangSupport)
endif() endif()
include(FindPackageHandleStandardArgs) include(FindPackageHandleStandardArgs)

View File

@@ -7,51 +7,51 @@
# LLD_LIBRARIES # LLD_LIBRARIES
find_path(LLD_INCLUDE_DIRS NAMES lld/Common/Driver.h find_path(LLD_INCLUDE_DIRS NAMES lld/Common/Driver.h
HINTS ${LLVM_INCLUDE_DIRS}
PATHS PATHS
/usr/lib/llvm-13/include /usr/lib/llvm-15/include
/usr/local/llvm130/include /usr/local/llvm150/include
/usr/local/llvm13/include /usr/local/llvm15/include
/usr/local/opt/llvm@13/include /usr/local/opt/llvm@15/include
/opt/homebrew/opt/llvm@13/include /opt/homebrew/opt/llvm@15/include
/mingw64/include) /mingw64/include)
find_library(LLD_LIBRARY NAMES lld-13.0 lld130 lld find_library(LLD_LIBRARY NAMES lld-15.0 lld150 lld NAMES_PER_DIR
HINTS ${LLVM_LIBDIRS}
PATHS PATHS
/usr/lib/llvm-13/lib /usr/lib/llvm-15/lib
/usr/local/llvm130/lib /usr/local/llvm150/lib
/usr/local/llvm13/lib /usr/local/llvm15/lib
/usr/local/opt/llvm@13/lib /usr/local/opt/llvm@15/lib
/opt/homebrew/opt/llvm@13/lib /opt/homebrew/opt/llvm@15/lib
) )
if(EXISTS ${LLD_LIBRARY}) if(EXISTS ${LLD_LIBRARY})
set(LLD_LIBRARIES ${LLD_LIBRARY}) set(LLD_LIBRARIES ${LLD_LIBRARY})
else() else()
macro(FIND_AND_ADD_LLD_LIB _libname_) macro(FIND_AND_ADD_LLD_LIB _libname_)
string(TOUPPER ${_libname_} _prettylibname_) string(TOUPPER ${_libname_} _prettylibname_)
find_library(LLD_${_prettylibname_}_LIB NAMES ${_libname_} find_library(LLD_${_prettylibname_}_LIB NAMES ${_libname_} NAMES_PER_DIR
HINTS ${LLVM_LIBDIRS}
PATHS PATHS
${LLD_LIBDIRS} ${LLD_LIBDIRS}
/usr/lib/llvm-13/lib /usr/lib/llvm-15/lib
/usr/local/llvm130/lib /usr/local/llvm150/lib
/usr/local/llvm13/lib /usr/local/llvm15/lib
/usr/local/opt/llvm@13/lib /usr/local/opt/llvm@15/lib
/opt/homebrew/opt/llvm@13/lib /opt/homebrew/opt/llvm@15/lib
/mingw64/lib /mingw64/lib
/c/msys64/mingw64/lib /c/msys64/mingw64/lib
c:/msys64/mingw64/lib) c:/msys64/mingw64/lib)
if(LLD_${_prettylibname_}_LIB) if(LLD_${_prettylibname_}_LIB)
set(LLD_LIBRARIES ${LLD_LIBRARIES} ${LLD_${_prettylibname_}_LIB}) set(LLD_LIBRARIES ${LLD_LIBRARIES} ${LLD_${_prettylibname_}_LIB})
endif() endif()
endmacro(FIND_AND_ADD_LLD_LIB) endmacro(FIND_AND_ADD_LLD_LIB)
FIND_AND_ADD_LLD_LIB(lldDriver)
FIND_AND_ADD_LLD_LIB(lldMinGW) FIND_AND_ADD_LLD_LIB(lldMinGW)
FIND_AND_ADD_LLD_LIB(lldELF) FIND_AND_ADD_LLD_LIB(lldELF)
FIND_AND_ADD_LLD_LIB(lldCOFF) FIND_AND_ADD_LLD_LIB(lldCOFF)
FIND_AND_ADD_LLD_LIB(lldWasm) FIND_AND_ADD_LLD_LIB(lldWasm)
FIND_AND_ADD_LLD_LIB(lldReaderWriter) FIND_AND_ADD_LLD_LIB(lldMachO)
FIND_AND_ADD_LLD_LIB(lldCore)
FIND_AND_ADD_LLD_LIB(lldYAML)
FIND_AND_ADD_LLD_LIB(lldCommon) FIND_AND_ADD_LLD_LIB(lldCommon)
endif() endif()

View File

@@ -6,154 +6,149 @@
# LLVM_INCLUDE_DIRS # LLVM_INCLUDE_DIRS
# LLVM_LIBRARIES # LLVM_LIBRARIES
# LLVM_LIBDIRS # LLVM_LIBDIRS
# LLVM_LINK_MODE
find_path(LLVM_INCLUDE_DIRS NAMES llvm/IR/IRBuilder.h
PATHS
/usr/lib/llvm/13/include
/usr/lib/llvm-13/include
/usr/lib/llvm-13.0/include
/usr/local/llvm13/include
/usr/local/llvm130/include
/usr/local/opt/llvm@13/include
/opt/homebrew/opt/llvm@13/include
/mingw64/include
)
if(ZIG_PREFER_CLANG_CPP_DYLIB) if(ZIG_USE_LLVM_CONFIG)
find_library(LLVM_LIBRARIES set(LLVM_CONFIG_ERROR_MESSAGES "")
NAMES while(1)
LLVM-13.0 unset(LLVM_CONFIG_EXE CACHE)
LLVM-13 find_program(LLVM_CONFIG_EXE
LLVM-130 NAMES llvm-config-15 llvm-config-15.0 llvm-config150 llvm-config15 llvm-config NAMES_PER_DIR
LLVM PATHS
PATHS "/mingw64/bin"
${LLVM_LIBDIRS} "/c/msys64/mingw64/bin"
/usr/lib/llvm/13/lib "c:/msys64/mingw64/bin"
/usr/lib/llvm/13/lib64 "C:/Libraries/llvm-15.0.0/bin")
/usr/lib/llvm-13/lib
/usr/local/llvm13/lib
/usr/local/llvm130/lib
/usr/local/opt/llvm@13/lib
/opt/homebrew/opt/llvm@13/lib
)
find_program(LLVM_CONFIG_EXE if ("${LLVM_CONFIG_EXE}" STREQUAL "LLVM_CONFIG_EXE-NOTFOUND")
NAMES llvm-config-13 llvm-config-13.0 llvm-config130 llvm-config13 llvm-config if (NOT LLVM_CONFIG_ERROR_MESSAGES STREQUAL "")
PATHS list(JOIN LLVM_CONFIG_ERROR_MESSAGES "\n" LLVM_CONFIG_ERROR_MESSAGE)
"/mingw64/bin" message(FATAL_ERROR ${LLVM_CONFIG_ERROR_MESSAGE})
"/c/msys64/mingw64/bin" else()
"c:/msys64/mingw64/bin" message(FATAL_ERROR "unable to find llvm-config")
"C:/Libraries/llvm-13.0.0/bin") endif()
endif()
if ("${LLVM_CONFIG_EXE}" STREQUAL "LLVM_CONFIG_EXE-NOTFOUND") # Check that this LLVM is the right version
message(FATAL_ERROR "unable to find llvm-config") execute_process(
endif() COMMAND ${LLVM_CONFIG_EXE} --version
OUTPUT_VARIABLE LLVM_CONFIG_VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE)
if ("${LLVM_CONFIG_EXE}" STREQUAL "LLVM_CONFIG_EXE-NOTFOUND") get_filename_component(LLVM_CONFIG_DIR "${LLVM_CONFIG_EXE}" DIRECTORY)
message(FATAL_ERROR "unable to find llvm-config") if("${LLVM_CONFIG_VERSION}" VERSION_LESS 15 OR "${LLVM_CONFIG_VERSION}" VERSION_EQUAL 16 OR "${LLVM_CONFIG_VERSION}" VERSION_GREATER 16)
endif() # Save the error message, in case this is the last llvm-config we find
list(APPEND LLVM_CONFIG_ERROR_MESSAGES "expected LLVM 15.x but found ${LLVM_CONFIG_VERSION} using ${LLVM_CONFIG_EXE}")
execute_process( # Ignore this directory and try the search again
COMMAND ${LLVM_CONFIG_EXE} --version list(APPEND CMAKE_IGNORE_PATH "${LLVM_CONFIG_DIR}")
OUTPUT_VARIABLE LLVM_CONFIG_VERSION continue()
OUTPUT_STRIP_TRAILING_WHITESPACE) endif()
if("${LLVM_CONFIG_VERSION}" VERSION_LESS 13) # Check that this LLVM supports linking as a shared/static library, if requested
message(FATAL_ERROR "expected LLVM 13.x but found ${LLVM_CONFIG_VERSION} using ${LLVM_CONFIG_EXE}") if (ZIG_SHARED_LLVM OR ZIG_STATIC_LLVM)
endif() if (ZIG_SHARED_LLVM)
if("${LLVM_CONFIG_VERSION}" VERSION_EQUAL 14) set(STATIC_OR_SHARED_LINK "--link-shared")
message(FATAL_ERROR "expected LLVM 13.x but found ${LLVM_CONFIG_VERSION} using ${LLVM_CONFIG_EXE}") elseif (ZIG_STATIC_LLVM)
endif() set(STATIC_OR_SHARED_LINK "--link-static")
if("${LLVM_CONFIG_VERSION}" VERSION_GREATER 14) endif()
message(FATAL_ERROR "expected LLVM 13.x but found ${LLVM_CONFIG_VERSION} using ${LLVM_CONFIG_EXE}")
endif()
elseif(ZIG_USE_LLVM_CONFIG)
find_program(LLVM_CONFIG_EXE
NAMES llvm-config-13 llvm-config-13.0 llvm-config130 llvm-config13 llvm-config
PATHS
"/mingw64/bin"
"/c/msys64/mingw64/bin"
"c:/msys64/mingw64/bin"
"C:/Libraries/llvm-13.0.0/bin")
if ("${LLVM_CONFIG_EXE}" STREQUAL "LLVM_CONFIG_EXE-NOTFOUND") execute_process(
message(FATAL_ERROR "unable to find llvm-config") COMMAND ${LLVM_CONFIG_EXE} --libs ${STATIC_OR_SHARED_LINK}
endif() OUTPUT_QUIET
ERROR_VARIABLE LLVM_CONFIG_ERROR
ERROR_STRIP_TRAILING_WHITESPACE)
if ("${LLVM_CONFIG_EXE}" STREQUAL "LLVM_CONFIG_EXE-NOTFOUND") if (LLVM_CONFIG_ERROR)
message(FATAL_ERROR "unable to find llvm-config") # Save the error message, in case this is the last llvm-config we find
endif() if (ZIG_SHARED_LLVM)
list(APPEND LLVM_CONFIG_ERROR_MESSAGES "LLVM 15.x found at ${LLVM_CONFIG_EXE} does not support linking as a shared library")
else()
list(APPEND LLVM_CONFIG_ERROR_MESSAGES "LLVM 15.x found at ${LLVM_CONFIG_EXE} does not support linking as a static library")
endif()
execute_process( # Ignore this directory and try the search again
COMMAND ${LLVM_CONFIG_EXE} --version list(APPEND CMAKE_IGNORE_PATH "${LLVM_CONFIG_DIR}")
OUTPUT_VARIABLE LLVM_CONFIG_VERSION continue()
OUTPUT_STRIP_TRAILING_WHITESPACE) endif()
endif()
if("${LLVM_CONFIG_VERSION}" VERSION_LESS 13) execute_process(
message(FATAL_ERROR "expected LLVM 13.x but found ${LLVM_CONFIG_VERSION} using ${LLVM_CONFIG_EXE}") COMMAND ${LLVM_CONFIG_EXE} --targets-built
endif() OUTPUT_VARIABLE LLVM_TARGETS_BUILT_SPACES
if("${LLVM_CONFIG_VERSION}" VERSION_EQUAL 14) OUTPUT_STRIP_TRAILING_WHITESPACE)
message(FATAL_ERROR "expected LLVM 13.x but found ${LLVM_CONFIG_VERSION} using ${LLVM_CONFIG_EXE}") string(REPLACE " " ";" LLVM_TARGETS_BUILT "${LLVM_TARGETS_BUILT_SPACES}")
endif() function(NEED_TARGET TARGET_NAME)
if("${LLVM_CONFIG_VERSION}" VERSION_GREATER 14)
message(FATAL_ERROR "expected LLVM 13.x but found ${LLVM_CONFIG_VERSION} using ${LLVM_CONFIG_EXE}")
endif()
execute_process(
COMMAND ${LLVM_CONFIG_EXE} --targets-built
OUTPUT_VARIABLE LLVM_TARGETS_BUILT_SPACES
OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE " " ";" LLVM_TARGETS_BUILT "${LLVM_TARGETS_BUILT_SPACES}")
function(NEED_TARGET TARGET_NAME)
list (FIND LLVM_TARGETS_BUILT "${TARGET_NAME}" _index) list (FIND LLVM_TARGETS_BUILT "${TARGET_NAME}" _index)
if (${_index} EQUAL -1) if (${_index} EQUAL -1)
message(FATAL_ERROR "LLVM (according to ${LLVM_CONFIG_EXE}) is missing target ${TARGET_NAME}. Zig requires LLVM to be built with all default targets enabled.") # Save the error message, in case this is the last llvm-config we find
endif() list(APPEND LLVM_CONFIG_ERROR_MESSAGES "LLVM (according to ${LLVM_CONFIG_EXE}) is missing target ${TARGET_NAME}. Zig requires LLVM to be built with all default targets enabled.")
endfunction(NEED_TARGET)
NEED_TARGET("AArch64")
NEED_TARGET("AMDGPU")
NEED_TARGET("ARM")
NEED_TARGET("AVR")
NEED_TARGET("BPF")
NEED_TARGET("Hexagon")
NEED_TARGET("Lanai")
NEED_TARGET("Mips")
NEED_TARGET("MSP430")
NEED_TARGET("NVPTX")
NEED_TARGET("PowerPC")
NEED_TARGET("RISCV")
NEED_TARGET("Sparc")
NEED_TARGET("SystemZ")
NEED_TARGET("WebAssembly")
NEED_TARGET("X86")
NEED_TARGET("XCore")
if(ZIG_STATIC_LLVM) # Ignore this directory and try the search again
list(APPEND CMAKE_IGNORE_PATH "${LLVM_CONFIG_DIR}")
continue()
endif()
endfunction(NEED_TARGET)
NEED_TARGET("AArch64")
NEED_TARGET("AMDGPU")
NEED_TARGET("ARM")
NEED_TARGET("AVR")
NEED_TARGET("BPF")
NEED_TARGET("Hexagon")
NEED_TARGET("Lanai")
NEED_TARGET("Mips")
NEED_TARGET("MSP430")
NEED_TARGET("NVPTX")
NEED_TARGET("PowerPC")
NEED_TARGET("RISCV")
NEED_TARGET("Sparc")
NEED_TARGET("SystemZ")
NEED_TARGET("VE")
NEED_TARGET("WebAssembly")
NEED_TARGET("X86")
NEED_TARGET("XCore")
# Got it!
break()
endwhile()
if(ZIG_SHARED_LLVM OR ZIG_STATIC_LLVM)
execute_process( execute_process(
COMMAND ${LLVM_CONFIG_EXE} --libfiles --link-static COMMAND ${LLVM_CONFIG_EXE} --libfiles ${STATIC_OR_SHARED_LINK}
OUTPUT_VARIABLE LLVM_LIBRARIES_SPACES OUTPUT_VARIABLE LLVM_LIBRARIES_SPACES
OUTPUT_STRIP_TRAILING_WHITESPACE) OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE " " ";" LLVM_LIBRARIES "${LLVM_LIBRARIES_SPACES}") string(REPLACE " " ";" LLVM_LIBRARIES "${LLVM_LIBRARIES_SPACES}")
execute_process( execute_process(
COMMAND ${LLVM_CONFIG_EXE} --system-libs --link-static COMMAND ${LLVM_CONFIG_EXE} --libdir ${STATIC_OR_SHARED_LINK}
OUTPUT_VARIABLE LLVM_LIBDIRS_SPACES
OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE " " ";" LLVM_LIBDIRS "${LLVM_LIBDIRS_SPACES}")
execute_process(
COMMAND ${LLVM_CONFIG_EXE} --system-libs ${STATIC_OR_SHARED_LINK}
OUTPUT_VARIABLE LLVM_SYSTEM_LIBS_SPACES OUTPUT_VARIABLE LLVM_SYSTEM_LIBS_SPACES
OUTPUT_STRIP_TRAILING_WHITESPACE) OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE " " ";" LLVM_SYSTEM_LIBS "${LLVM_SYSTEM_LIBS_SPACES}") string(REPLACE " " ";" LLVM_SYSTEM_LIBS "${LLVM_SYSTEM_LIBS_SPACES}")
execute_process( execute_process(
COMMAND ${LLVM_CONFIG_EXE} --libdir --link-static COMMAND ${LLVM_CONFIG_EXE} --shared-mode ${STATIC_OR_SHARED_LINK}
OUTPUT_VARIABLE LLVM_LIBDIRS_SPACES OUTPUT_VARIABLE LLVM_LINK_MODE
OUTPUT_STRIP_TRAILING_WHITESPACE) OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE " " ";" LLVM_LIBDIRS "${LLVM_LIBDIRS_SPACES}") else()
endif()
if(NOT LLVM_LIBRARIES)
execute_process( execute_process(
COMMAND ${LLVM_CONFIG_EXE} --libs COMMAND ${LLVM_CONFIG_EXE} --libs
OUTPUT_VARIABLE LLVM_LIBRARIES_SPACES OUTPUT_VARIABLE LLVM_LIBRARIES_SPACES
OUTPUT_STRIP_TRAILING_WHITESPACE) OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE " " ";" LLVM_LIBRARIES "${LLVM_LIBRARIES_SPACES}") string(REPLACE " " ";" LLVM_LIBRARIES "${LLVM_LIBRARIES_SPACES}")
execute_process(
COMMAND ${LLVM_CONFIG_EXE} --libdir
OUTPUT_VARIABLE LLVM_LIBDIRS_SPACES
OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE " " ";" LLVM_LIBDIRS "${LLVM_LIBDIRS_SPACES}")
execute_process( execute_process(
COMMAND ${LLVM_CONFIG_EXE} --system-libs COMMAND ${LLVM_CONFIG_EXE} --system-libs
OUTPUT_VARIABLE LLVM_SYSTEM_LIBS_SPACES OUTPUT_VARIABLE LLVM_SYSTEM_LIBS_SPACES
@@ -161,17 +156,32 @@ elseif(ZIG_USE_LLVM_CONFIG)
string(REPLACE " " ";" LLVM_SYSTEM_LIBS "${LLVM_SYSTEM_LIBS_SPACES}") string(REPLACE " " ";" LLVM_SYSTEM_LIBS "${LLVM_SYSTEM_LIBS_SPACES}")
execute_process( execute_process(
COMMAND ${LLVM_CONFIG_EXE} --libdir COMMAND ${LLVM_CONFIG_EXE} --shared-mode
OUTPUT_VARIABLE LLVM_LIBDIRS_SPACES OUTPUT_VARIABLE LLVM_LINK_MODE
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if (${LLVM_LINK_MODE} STREQUAL "shared")
# We always ask for the system libs corresponding to static linking,
# since on some distros LLD is only available as a static library
# and we need these libraries to link it successfully
execute_process(
COMMAND ${LLVM_CONFIG_EXE} --system-libs --link-static
OUTPUT_VARIABLE LLVM_STATIC_SYSTEM_LIBS_SPACES
ERROR_QUIET # Some installations have no static libs, we just ignore the failure
OUTPUT_STRIP_TRAILING_WHITESPACE) OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE " " ";" LLVM_LIBDIRS "${LLVM_LIBDIRS_SPACES}") string(REPLACE " " ";" LLVM_STATIC_SYSTEM_LIBS "${LLVM_STATIC_SYSTEM_LIBS_SPACES}")
set(LLVM_LIBRARIES ${LLVM_LIBRARIES} ${LLVM_SYSTEM_LIBS} ${LLVM_STATIC_SYSTEM_LIBS})
else()
set(LLVM_LIBRARIES ${LLVM_LIBRARIES} ${LLVM_SYSTEM_LIBS})
endif() endif()
set(LLVM_LIBRARIES ${LLVM_LIBRARIES} ${LLVM_SYSTEM_LIBS}) execute_process(
COMMAND ${LLVM_CONFIG_EXE} --includedir
if(NOT LLVM_LIBRARIES) OUTPUT_VARIABLE LLVM_INCLUDE_DIRS_SPACES
find_library(LLVM_LIBRARIES NAMES LLVM LLVM-13 LLVM-13.0) OUTPUT_STRIP_TRAILING_WHITESPACE)
endif() string(REPLACE " " ";" LLVM_INCLUDE_DIRS "${LLVM_INCLUDE_DIRS_SPACES}")
link_directories("${CMAKE_PREFIX_PATH}/lib") link_directories("${CMAKE_PREFIX_PATH}/lib")
link_directories("${LLVM_LIBDIRS}") link_directories("${LLVM_LIBDIRS}")
@@ -181,26 +191,18 @@ else()
macro(FIND_AND_ADD_LLVM_LIB _libname_) macro(FIND_AND_ADD_LLVM_LIB _libname_)
string(TOUPPER ${_libname_} _prettylibname_) string(TOUPPER ${_libname_} _prettylibname_)
find_library(LLVM_${_prettylibname_}_LIB NAMES ${_libname_} find_library(LLVM_${_prettylibname_}_LIB
PATHS NAMES ${_libname_} NAMES_PER_DIR)
${LLVM_LIBDIRS}
/usr/lib/llvm/13/lib
/usr/lib/llvm-13/lib
/usr/lib/llvm-13.0/lib
/usr/local/llvm130/lib
/usr/local/llvm13/lib
/usr/local/opt/llvm@13/lib
/opt/homebrew/opt/llvm@13/lib
/mingw64/lib
/c/msys64/mingw64/lib
c:\\msys64\\mingw64\\lib)
set(LLVM_LIBRARIES ${LLVM_LIBRARIES} ${LLVM_${_prettylibname_}_LIB}) set(LLVM_LIBRARIES ${LLVM_LIBRARIES} ${LLVM_${_prettylibname_}_LIB})
endmacro(FIND_AND_ADD_LLVM_LIB) endmacro(FIND_AND_ADD_LLVM_LIB)
set(LLVM_LINK_MODE "static")
# This list can be re-generated with `llvm-config --libfiles` and then # This list can be re-generated with `llvm-config --libfiles` and then
# reformatting using your favorite text editor. Note we do not execute # reformatting using your favorite text editor. Note we do not execute
# `llvm-config` here because we are cross compiling. # `llvm-config` here because we are cross compiling.
FIND_AND_ADD_LLVM_LIB(LLVMWindowsManifest) FIND_AND_ADD_LLVM_LIB(LLVMWindowsManifest)
FIND_AND_ADD_LLVM_LIB(LLVMWindowsDriver)
FIND_AND_ADD_LLVM_LIB(LLVMXRay) FIND_AND_ADD_LLVM_LIB(LLVMXRay)
FIND_AND_ADD_LLVM_LIB(LLVMLibDriver) FIND_AND_ADD_LLVM_LIB(LLVMLibDriver)
FIND_AND_ADD_LLVM_LIB(LLVMDlltoolDriver) FIND_AND_ADD_LLVM_LIB(LLVMDlltoolDriver)
@@ -210,6 +212,7 @@ else()
FIND_AND_ADD_LLVM_LIB(LLVMXCoreCodeGen) FIND_AND_ADD_LLVM_LIB(LLVMXCoreCodeGen)
FIND_AND_ADD_LLVM_LIB(LLVMXCoreDesc) FIND_AND_ADD_LLVM_LIB(LLVMXCoreDesc)
FIND_AND_ADD_LLVM_LIB(LLVMXCoreInfo) FIND_AND_ADD_LLVM_LIB(LLVMXCoreInfo)
FIND_AND_ADD_LLVM_LIB(LLVMX86TargetMCA)
FIND_AND_ADD_LLVM_LIB(LLVMX86Disassembler) FIND_AND_ADD_LLVM_LIB(LLVMX86Disassembler)
FIND_AND_ADD_LLVM_LIB(LLVMX86AsmParser) FIND_AND_ADD_LLVM_LIB(LLVMX86AsmParser)
FIND_AND_ADD_LLVM_LIB(LLVMX86CodeGen) FIND_AND_ADD_LLVM_LIB(LLVMX86CodeGen)
@@ -221,6 +224,11 @@ else()
FIND_AND_ADD_LLVM_LIB(LLVMWebAssemblyDesc) FIND_AND_ADD_LLVM_LIB(LLVMWebAssemblyDesc)
FIND_AND_ADD_LLVM_LIB(LLVMWebAssemblyUtils) FIND_AND_ADD_LLVM_LIB(LLVMWebAssemblyUtils)
FIND_AND_ADD_LLVM_LIB(LLVMWebAssemblyInfo) FIND_AND_ADD_LLVM_LIB(LLVMWebAssemblyInfo)
FIND_AND_ADD_LLVM_LIB(LLVMVEDisassembler)
FIND_AND_ADD_LLVM_LIB(LLVMVEAsmParser)
FIND_AND_ADD_LLVM_LIB(LLVMVECodeGen)
FIND_AND_ADD_LLVM_LIB(LLVMVEDesc)
FIND_AND_ADD_LLVM_LIB(LLVMVEInfo)
FIND_AND_ADD_LLVM_LIB(LLVMSystemZDisassembler) FIND_AND_ADD_LLVM_LIB(LLVMSystemZDisassembler)
FIND_AND_ADD_LLVM_LIB(LLVMSystemZAsmParser) FIND_AND_ADD_LLVM_LIB(LLVMSystemZAsmParser)
FIND_AND_ADD_LLVM_LIB(LLVMSystemZCodeGen) FIND_AND_ADD_LLVM_LIB(LLVMSystemZCodeGen)
@@ -280,6 +288,7 @@ else()
FIND_AND_ADD_LLVM_LIB(LLVMARMDesc) FIND_AND_ADD_LLVM_LIB(LLVMARMDesc)
FIND_AND_ADD_LLVM_LIB(LLVMARMUtils) FIND_AND_ADD_LLVM_LIB(LLVMARMUtils)
FIND_AND_ADD_LLVM_LIB(LLVMARMInfo) FIND_AND_ADD_LLVM_LIB(LLVMARMInfo)
FIND_AND_ADD_LLVM_LIB(LLVMAMDGPUTargetMCA)
FIND_AND_ADD_LLVM_LIB(LLVMAMDGPUDisassembler) FIND_AND_ADD_LLVM_LIB(LLVMAMDGPUDisassembler)
FIND_AND_ADD_LLVM_LIB(LLVMAMDGPUAsmParser) FIND_AND_ADD_LLVM_LIB(LLVMAMDGPUAsmParser)
FIND_AND_ADD_LLVM_LIB(LLVMAMDGPUCodeGen) FIND_AND_ADD_LLVM_LIB(LLVMAMDGPUCodeGen)
@@ -301,11 +310,10 @@ else()
FIND_AND_ADD_LLVM_LIB(LLVMOrcTargetProcess) FIND_AND_ADD_LLVM_LIB(LLVMOrcTargetProcess)
FIND_AND_ADD_LLVM_LIB(LLVMOrcShared) FIND_AND_ADD_LLVM_LIB(LLVMOrcShared)
FIND_AND_ADD_LLVM_LIB(LLVMDWP) FIND_AND_ADD_LLVM_LIB(LLVMDWP)
FIND_AND_ADD_LLVM_LIB(LLVMSymbolize)
FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoPDB)
FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoGSYM) FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoGSYM)
FIND_AND_ADD_LLVM_LIB(LLVMOption) FIND_AND_ADD_LLVM_LIB(LLVMOption)
FIND_AND_ADD_LLVM_LIB(LLVMObjectYAML) FIND_AND_ADD_LLVM_LIB(LLVMObjectYAML)
FIND_AND_ADD_LLVM_LIB(LLVMObjCopy)
FIND_AND_ADD_LLVM_LIB(LLVMMCA) FIND_AND_ADD_LLVM_LIB(LLVMMCA)
FIND_AND_ADD_LLVM_LIB(LLVMMCDisassembler) FIND_AND_ADD_LLVM_LIB(LLVMMCDisassembler)
FIND_AND_ADD_LLVM_LIB(LLVMLTO) FIND_AND_ADD_LLVM_LIB(LLVMLTO)
@@ -324,8 +332,6 @@ else()
FIND_AND_ADD_LLVM_LIB(LLVMGlobalISel) FIND_AND_ADD_LLVM_LIB(LLVMGlobalISel)
FIND_AND_ADD_LLVM_LIB(LLVMMIRParser) FIND_AND_ADD_LLVM_LIB(LLVMMIRParser)
FIND_AND_ADD_LLVM_LIB(LLVMAsmPrinter) FIND_AND_ADD_LLVM_LIB(LLVMAsmPrinter)
FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoMSF)
FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoDWARF)
FIND_AND_ADD_LLVM_LIB(LLVMSelectionDAG) FIND_AND_ADD_LLVM_LIB(LLVMSelectionDAG)
FIND_AND_ADD_LLVM_LIB(LLVMCodeGen) FIND_AND_ADD_LLVM_LIB(LLVMCodeGen)
FIND_AND_ADD_LLVM_LIB(LLVMIRReader) FIND_AND_ADD_LLVM_LIB(LLVMIRReader)
@@ -341,18 +347,26 @@ else()
FIND_AND_ADD_LLVM_LIB(LLVMBitWriter) FIND_AND_ADD_LLVM_LIB(LLVMBitWriter)
FIND_AND_ADD_LLVM_LIB(LLVMAnalysis) FIND_AND_ADD_LLVM_LIB(LLVMAnalysis)
FIND_AND_ADD_LLVM_LIB(LLVMProfileData) FIND_AND_ADD_LLVM_LIB(LLVMProfileData)
FIND_AND_ADD_LLVM_LIB(LLVMSymbolize)
FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoPDB)
FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoMSF)
FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoDWARF)
FIND_AND_ADD_LLVM_LIB(LLVMObject) FIND_AND_ADD_LLVM_LIB(LLVMObject)
FIND_AND_ADD_LLVM_LIB(LLVMTextAPI) FIND_AND_ADD_LLVM_LIB(LLVMTextAPI)
FIND_AND_ADD_LLVM_LIB(LLVMMCParser) FIND_AND_ADD_LLVM_LIB(LLVMMCParser)
FIND_AND_ADD_LLVM_LIB(LLVMMC) FIND_AND_ADD_LLVM_LIB(LLVMMC)
FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoCodeView) FIND_AND_ADD_LLVM_LIB(LLVMDebugInfoCodeView)
FIND_AND_ADD_LLVM_LIB(LLVMBitReader) FIND_AND_ADD_LLVM_LIB(LLVMBitReader)
FIND_AND_ADD_LLVM_LIB(LLVMFuzzerCLI)
FIND_AND_ADD_LLVM_LIB(LLVMCore) FIND_AND_ADD_LLVM_LIB(LLVMCore)
FIND_AND_ADD_LLVM_LIB(LLVMRemarks) FIND_AND_ADD_LLVM_LIB(LLVMRemarks)
FIND_AND_ADD_LLVM_LIB(LLVMBitstreamReader) FIND_AND_ADD_LLVM_LIB(LLVMBitstreamReader)
FIND_AND_ADD_LLVM_LIB(LLVMBinaryFormat) FIND_AND_ADD_LLVM_LIB(LLVMBinaryFormat)
FIND_AND_ADD_LLVM_LIB(LLVMSupport) FIND_AND_ADD_LLVM_LIB(LLVMSupport)
FIND_AND_ADD_LLVM_LIB(LLVMDemangle) FIND_AND_ADD_LLVM_LIB(LLVMDemangle)
get_filename_component(LLVM_LIBDIRS "${LLVM_LLVMCORE_LIB}" DIRECTORY)
find_path(LLVM_INCLUDE_DIRS NAMES llvm/IR/IRBuilder.h)
endif() endif()
include(FindPackageHandleStandardArgs) include(FindPackageHandleStandardArgs)

View File

@@ -1,29 +1,19 @@
message("-- Installing: ${CMAKE_INSTALL_PREFIX}/lib") set(ZIG_INSTALL_ARGS build ${ZIG_BUILD_ARGS} --prefix "${CMAKE_INSTALL_PREFIX}")
execute_process(
COMMAND "${ZIG_EXECUTABLE}" ${ZIG_INSTALL_ARGS}
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
RESULT_VARIABLE _result)
if(NOT EXISTS ${zig_EXE})
message("::")
message(":: ERROR: Executable not found")
message(":: (execute_process)")
message("::")
message(":: executable: ${zig_EXE}")
message("::")
message(FATAL_ERROR)
endif()
execute_process(COMMAND ${zig_EXE} ${ZIG_INSTALL_ARGS}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
RESULT_VARIABLE _result
)
if(_result) if(_result)
message("::") message("::")
message(":: ERROR: ${_result}") message(":: ERROR: ${_result}")
message(":: (execute_process)") message(":: (execute_process)")
string(REPLACE ";" " " s_INSTALL_LIBSTAGE2_ARGS "${ZIG_INSTALL_ARGS}") list(JOIN ZIG_INSTALL_ARGS " " s_INSTALL_LIBSTAGE2_ARGS)
message("::") message("::")
message(":: argv: ${zig_EXE} ${s_INSTALL_LIBSTAGE2_ARGS}") message(":: argv: ${ZIG_EXECUTABLE} ${s_INSTALL_LIBSTAGE2_ARGS}")
set(_args ${zig_EXE} ${ZIG_INSTALL_ARGS}) set(_args ${ZIG_EXECUTABLE} ${ZIG_INSTALL_ARGS})
list(LENGTH _args _len) list(LENGTH _args _len)
math(EXPR _len "${_len} - 1") math(EXPR _len "${_len} - 1")
message("::") message("::")

View File

@@ -3,6 +3,10 @@
#if defined(__BIG_ENDIAN__) #if defined(__BIG_ENDIAN__)
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(_BIG_ENDIAN) && (_BIG_ENDIAN == 1)
#define BIGENDIAN 1
#elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
#define BIGENDIAN 1
#elif defined(__ARMEB__) #elif defined(__ARMEB__)
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(__THUMBEB__) #elif defined(__THUMBEB__)
@@ -15,20 +19,12 @@
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(__MIPSEB__) #elif defined(__MIPSEB__)
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define BIGENDIAN 1
#elif defined(_BIG_ENDIAN)
#define BIGENDIAN 1
#elif defined(__sparc) #elif defined(__sparc)
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(__sparc__) #elif defined(__sparc__)
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(_POWER) #elif defined(_POWER)
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(__powerpc__)
#define BIGENDIAN 1
#elif defined(__ppc__)
#define BIGENDIAN 1
#elif defined(__hpux) #elif defined(__hpux)
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(__hppa) #elif defined(__hppa)
@@ -37,7 +33,13 @@
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(__s390__) #elif defined(__s390__)
#define BIGENDIAN 1 #define BIGENDIAN 1
#elif defined(__LITTLE_ENDIAN__) #endif
#if defined(__LITTLE_ENDIAN__)
#define LITTLEENDIAN 1
#elif defined(_LITTLE_ENDIAN) && (_LITTLE_ENDIAN == 1)
#define LITTLEENDIAN 1
#elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define LITTLEENDIAN 1 #define LITTLEENDIAN 1
#elif defined(__ARMEL__) #elif defined(__ARMEL__)
#define LITTLEENDIAN 1 #define LITTLEENDIAN 1
@@ -51,10 +53,6 @@
#define LITTLEENDIAN 1 #define LITTLEENDIAN 1
#elif defined(__MIPSEL__) #elif defined(__MIPSEL__)
#define LITTLEENDIAN 1 #define LITTLEENDIAN 1
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define LITTLEENDIAN 1
#elif defined(_LITTLE_ENDIAN)
#define LITTLEENDIAN 1
#elif defined(__i386__) #elif defined(__i386__)
#define LITTLEENDIAN 1 #define LITTLEENDIAN 1
#elif defined(__alpha__) #elif defined(__alpha__)
@@ -83,7 +81,11 @@
#define LITTLEENDIAN 1 #define LITTLEENDIAN 1
#elif defined(__bfin__) #elif defined(__bfin__)
#define LITTLEENDIAN 1 #define LITTLEENDIAN 1
#else #endif
#if defined(LITTLEENDIAN) && defined(BIGENDIAN)
#error unable to detect endianness
#elif !defined(LITTLEENDIAN) && !defined(BIGENDIAN)
#error unable to detect endianness #error unable to detect endianness
#endif #endif

View File

@@ -37,6 +37,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef primitiveTypes_h #ifndef primitiveTypes_h
#define primitiveTypes_h 1 #define primitiveTypes_h 1
#include "platform.h"
#include <stdint.h> #include <stdint.h>
#ifdef SOFTFLOAT_FAST_INT64 #ifdef SOFTFLOAT_FAST_INT64

View File

@@ -37,6 +37,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef softfloat_types_h #ifndef softfloat_types_h
#define softfloat_types_h 1 #define softfloat_types_h 1
#include "platform.h"
#include <stdint.h> #include <stdint.h>
/*---------------------------------------------------------------------------- /*----------------------------------------------------------------------------

View File

@@ -23,29 +23,29 @@ pub fn main() !void {
const allocator = arena.allocator(); const allocator = arena.allocator();
var args_it = process.args(); var args_it = try process.argsWithAllocator(allocator);
if (!args_it.skip()) @panic("expected self arg"); if (!args_it.skip()) @panic("expected self arg");
const zig_exe = try (args_it.next(allocator) orelse @panic("expected zig exe arg")); const zig_exe = args_it.next() orelse @panic("expected zig exe arg");
defer allocator.free(zig_exe); defer allocator.free(zig_exe);
const in_file_name = try (args_it.next(allocator) orelse @panic("expected input arg")); const in_file_name = args_it.next() orelse @panic("expected input arg");
defer allocator.free(in_file_name); defer allocator.free(in_file_name);
const out_file_name = try (args_it.next(allocator) orelse @panic("expected output arg")); const out_file_name = args_it.next() orelse @panic("expected output arg");
defer allocator.free(out_file_name); defer allocator.free(out_file_name);
var do_code_tests = true; var do_code_tests = true;
if (args_it.next(allocator)) |arg| { if (args_it.next()) |arg| {
if (mem.eql(u8, try arg, "--skip-code-tests")) { if (mem.eql(u8, arg, "--skip-code-tests")) {
do_code_tests = false; do_code_tests = false;
} else { } else {
@panic("unrecognized arg"); @panic("unrecognized arg");
} }
} }
var in_file = try fs.cwd().openFile(in_file_name, .{ .read = true }); var in_file = try fs.cwd().openFile(in_file_name, .{ .mode = .read_only });
defer in_file.close(); defer in_file.close();
var out_file = try fs.cwd().createFile(out_file_name, .{}); var out_file = try fs.cwd().createFile(out_file_name, .{});
@@ -285,6 +285,7 @@ const Code = struct {
link_objects: []const []const u8, link_objects: []const []const u8,
target_str: ?[]const u8, target_str: ?[]const u8,
link_libc: bool, link_libc: bool,
backend_stage1: bool,
link_mode: ?std.builtin.LinkMode, link_mode: ?std.builtin.LinkMode,
disable_cache: bool, disable_cache: bool,
verbose_cimport: bool, verbose_cimport: bool,
@@ -554,6 +555,7 @@ fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
var link_mode: ?std.builtin.LinkMode = null; var link_mode: ?std.builtin.LinkMode = null;
var disable_cache = false; var disable_cache = false;
var verbose_cimport = false; var verbose_cimport = false;
var backend_stage1 = false;
const source_token = while (true) { const source_token = while (true) {
const content_tok = try eatToken(tokenizer, Token.Id.Content); const content_tok = try eatToken(tokenizer, Token.Id.Content);
@@ -586,6 +588,8 @@ fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
link_libc = true; link_libc = true;
} else if (mem.eql(u8, end_tag_name, "link_mode_dynamic")) { } else if (mem.eql(u8, end_tag_name, "link_mode_dynamic")) {
link_mode = .Dynamic; link_mode = .Dynamic;
} else if (mem.eql(u8, end_tag_name, "backend_stage1")) {
backend_stage1 = true;
} else if (mem.eql(u8, end_tag_name, "code_end")) { } else if (mem.eql(u8, end_tag_name, "code_end")) {
_ = try eatToken(tokenizer, Token.Id.BracketClose); _ = try eatToken(tokenizer, Token.Id.BracketClose);
break content_tok; break content_tok;
@@ -609,6 +613,7 @@ fn genToc(allocator: Allocator, tokenizer: *Tokenizer) !Toc {
.link_objects = link_objects.toOwnedSlice(), .link_objects = link_objects.toOwnedSlice(),
.target_str = target_str, .target_str = target_str,
.link_libc = link_libc, .link_libc = link_libc,
.backend_stage1 = backend_stage1,
.link_mode = link_mode, .link_mode = link_mode,
.disable_cache = disable_cache, .disable_cache = disable_cache,
.verbose_cimport = verbose_cimport, .verbose_cimport = verbose_cimport,
@@ -853,10 +858,11 @@ fn termColor(allocator: Allocator, input: []const u8) ![]u8 {
} }
const builtin_types = [_][]const u8{ const builtin_types = [_][]const u8{
"f16", "f32", "f64", "f128", "c_longdouble", "c_short", "f16", "f32", "f64", "f80", "f128",
"c_ushort", "c_int", "c_uint", "c_long", "c_ulong", "c_longlong", "c_longdouble", "c_short", "c_ushort", "c_int", "c_uint",
"c_ulonglong", "c_char", "anyopaque", "void", "bool", "isize", "c_long", "c_ulong", "c_longlong", "c_ulonglong", "c_char",
"usize", "noreturn", "type", "anyerror", "comptime_int", "comptime_float", "anyopaque", "void", "bool", "isize", "usize",
"noreturn", "type", "anyerror", "comptime_int", "comptime_float",
}; };
fn isType(name: []const u8) bool { fn isType(name: []const u8) bool {
@@ -1052,9 +1058,7 @@ fn tokenizeAndPrintRaw(
} }
}, },
.integer_literal, .number_literal => {
.float_literal,
=> {
try out.writeAll("<span class=\"tok-number\">"); try out.writeAll("<span class=\"tok-number\">");
try writeEscaped(out, src[token.loc.start..token.loc.end]); try writeEscaped(out, src[token.loc.start..token.loc.end]);
try out.writeAll("</span>"); try out.writeAll("</span>");
@@ -1164,7 +1168,7 @@ fn printSourceBlock(allocator: Allocator, docgen_tokenizer: *Tokenizer, out: any
try out.writeAll("</pre></figure>"); try out.writeAll("</pre></figure>");
} }
fn printShell(out: anytype, shell_content: []const u8) !void { fn printShell(out: anytype, shell_content: []const u8, escape: bool) !void {
const trimmed_shell_content = mem.trim(u8, shell_content, " \n"); const trimmed_shell_content = mem.trim(u8, shell_content, " \n");
try out.writeAll("<figure><figcaption class=\"shell-cap\">Shell</figcaption><pre><samp>"); try out.writeAll("<figure><figcaption class=\"shell-cap\">Shell</figcaption><pre><samp>");
var cmd_cont: bool = false; var cmd_cont: bool = false;
@@ -1172,21 +1176,50 @@ fn printShell(out: anytype, shell_content: []const u8) !void {
while (iter.next()) |orig_line| { while (iter.next()) |orig_line| {
const line = mem.trimRight(u8, orig_line, " "); const line = mem.trimRight(u8, orig_line, " ");
if (!cmd_cont and line.len > 1 and mem.eql(u8, line[0..2], "$ ") and line[line.len - 1] != '\\') { if (!cmd_cont and line.len > 1 and mem.eql(u8, line[0..2], "$ ") and line[line.len - 1] != '\\') {
try out.print(start_line ++ "$ <kbd>{s}</kbd>" ++ end_line ++ "\n", .{std.mem.trimLeft(u8, line[1..], " ")}); try out.writeAll(start_line ++ "$ <kbd>");
const s = std.mem.trimLeft(u8, line[1..], " ");
if (escape) {
try writeEscaped(out, s);
} else {
try out.writeAll(s);
}
try out.writeAll("</kbd>" ++ end_line ++ "\n");
} else if (!cmd_cont and line.len > 1 and mem.eql(u8, line[0..2], "$ ") and line[line.len - 1] == '\\') { } else if (!cmd_cont and line.len > 1 and mem.eql(u8, line[0..2], "$ ") and line[line.len - 1] == '\\') {
try out.print(start_line ++ "$ <kbd>{s}" ++ end_line ++ "\n", .{std.mem.trimLeft(u8, line[1..], " ")}); try out.writeAll(start_line ++ "$ <kbd>");
const s = std.mem.trimLeft(u8, line[1..], " ");
if (escape) {
try writeEscaped(out, s);
} else {
try out.writeAll(s);
}
try out.writeAll(end_line ++ "\n");
cmd_cont = true; cmd_cont = true;
} else if (line.len > 0 and line[line.len - 1] != '\\' and cmd_cont) { } else if (line.len > 0 and line[line.len - 1] != '\\' and cmd_cont) {
try out.print(start_line ++ "{s}</kbd>" ++ end_line ++ "\n", .{line}); try out.writeAll(start_line);
if (escape) {
try writeEscaped(out, line);
} else {
try out.writeAll(line);
}
try out.writeAll("</kbd>" ++ end_line ++ "\n");
cmd_cont = false; cmd_cont = false;
} else { } else {
try out.print(start_line ++ "{s}" ++ end_line ++ "\n", .{line}); try out.writeAll(start_line);
if (escape) {
try writeEscaped(out, line);
} else {
try out.writeAll(line);
}
try out.writeAll(end_line ++ "\n");
} }
} }
try out.writeAll("</samp></pre></figure>"); try out.writeAll("</samp></pre></figure>");
} }
// Override this to skip to later tests
const debug_start_line = 0;
fn genHtml( fn genHtml(
allocator: Allocator, allocator: Allocator,
tokenizer: *Tokenizer, tokenizer: *Tokenizer,
@@ -1196,13 +1229,13 @@ fn genHtml(
do_code_tests: bool, do_code_tests: bool,
) !void { ) !void {
var progress = Progress{}; var progress = Progress{};
const root_node = try progress.start("Generating docgen examples", toc.nodes.len); const root_node = progress.start("Generating docgen examples", toc.nodes.len);
defer root_node.end(); defer root_node.end();
var env_map = try process.getEnvMap(allocator); var env_map = try process.getEnvMap(allocator);
try env_map.put("ZIG_DEBUG_COLOR", "1"); try env_map.put("ZIG_DEBUG_COLOR", "1");
const host = try std.zig.system.NativeTargetInfo.detect(allocator, .{}); const host = try std.zig.system.NativeTargetInfo.detect(.{});
const builtin_code = try getBuiltinCode(allocator, &env_map, zig_exe); const builtin_code = try getBuiltinCode(allocator, &env_map, zig_exe);
for (toc.nodes) |node| { for (toc.nodes) |node| {
@@ -1247,7 +1280,7 @@ fn genHtml(
}, },
.Shell => |content_tok| { .Shell => |content_tok| {
const raw_shell_content = tokenizer.buffer[content_tok.start..content_tok.end]; const raw_shell_content = tokenizer.buffer[content_tok.start..content_tok.end];
try printShell(out, raw_shell_content); try printShell(out, raw_shell_content, true);
}, },
.SyntaxBlock => |syntax_block| { .SyntaxBlock => |syntax_block| {
try printSourceBlock(allocator, tokenizer, out, syntax_block); try printSourceBlock(allocator, tokenizer, out, syntax_block);
@@ -1266,6 +1299,13 @@ fn genHtml(
continue; continue;
} }
if (debug_start_line > 0) {
const loc = tokenizer.getTokenLocation(code.source_token);
if (debug_start_line > loc.line) {
continue;
}
}
const raw_source = tokenizer.buffer[code.source_token.start..code.source_token.end]; const raw_source = tokenizer.buffer[code.source_token.start..code.source_token.end];
const trimmed_raw_source = mem.trim(u8, raw_source, " \n"); const trimmed_raw_source = mem.trim(u8, raw_source, " \n");
const tmp_source_file_name = try fs.path.join( const tmp_source_file_name = try fs.path.join(
@@ -1311,6 +1351,10 @@ fn genHtml(
try build_args.append("-lc"); try build_args.append("-lc");
try shell_out.print("-lc ", .{}); try shell_out.print("-lc ", .{});
} }
if (code.backend_stage1) {
try build_args.append("-fstage1");
try shell_out.print("-fstage1", .{});
}
const target = try std.zig.CrossTarget.parse(.{ const target = try std.zig.CrossTarget.parse(.{
.arch_os_abi = code.target_str orelse "native", .arch_os_abi = code.target_str orelse "native",
}); });
@@ -1443,6 +1487,10 @@ fn genHtml(
try test_args.append("-lc"); try test_args.append("-lc");
try shell_out.print("-lc ", .{}); try shell_out.print("-lc ", .{});
} }
if (code.backend_stage1) {
try test_args.append("-fstage1");
try shell_out.print("-fstage1", .{});
}
if (code.target_str) |triple| { if (code.target_str) |triple| {
try test_args.appendSlice(&[_][]const u8{ "-target", triple }); try test_args.appendSlice(&[_][]const u8{ "-target", triple });
try shell_out.print("-target {s} ", .{triple}); try shell_out.print("-target {s} ", .{triple});
@@ -1451,7 +1499,6 @@ fn genHtml(
.arch_os_abi = triple, .arch_os_abi = triple,
}); });
const target_info = try std.zig.system.NativeTargetInfo.detect( const target_info = try std.zig.system.NativeTargetInfo.detect(
allocator,
cross_target, cross_target,
); );
switch (host.getExternalExecutor(target_info, .{ switch (host.getExternalExecutor(target_info, .{
@@ -1490,6 +1537,14 @@ fn genHtml(
try shell_out.print("-O {s} ", .{@tagName(code.mode)}); try shell_out.print("-O {s} ", .{@tagName(code.mode)});
}, },
} }
if (code.link_libc) {
try test_args.append("-lc");
try shell_out.print("-lc ", .{});
}
if (code.backend_stage1) {
try test_args.append("-fstage1");
try shell_out.print("-fstage1", .{});
}
const result = try ChildProcess.exec(.{ const result = try ChildProcess.exec(.{
.allocator = allocator, .allocator = allocator,
.argv = test_args.items, .argv = test_args.items,
@@ -1701,14 +1756,14 @@ fn genHtml(
} }
if (!code.just_check_syntax) { if (!code.just_check_syntax) {
try printShell(out, shell_buffer.items); try printShell(out, shell_buffer.items, false);
} }
}, },
} }
} }
} }
fn exec(allocator: Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult { fn exec(allocator: Allocator, env_map: *process.EnvMap, args: []const []const u8) !ChildProcess.ExecResult {
const result = try ChildProcess.exec(.{ const result = try ChildProcess.exec(.{
.allocator = allocator, .allocator = allocator,
.argv = args, .argv = args,
@@ -1732,7 +1787,7 @@ fn exec(allocator: Allocator, env_map: *std.BufMap, args: []const []const u8) !C
return result; return result;
} }
fn getBuiltinCode(allocator: Allocator, env_map: *std.BufMap, zig_exe: []const u8) ![]const u8 { fn getBuiltinCode(allocator: Allocator, env_map: *process.EnvMap, zig_exe: []const u8) ![]const u8 {
const result = try exec(allocator, env_map, &[_][]const u8{ zig_exe, "build-obj", "--show-builtin" }); const result = try exec(allocator, env_map, &[_][]const u8{ zig_exe, "build-obj", "--show-builtin" });
return result.stdout; return result.stdout;
} }
@@ -1759,7 +1814,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
std.log.emerg("{s}", .{buffer.items}); std.log.emerg("{s}", .{buffer.items});
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
@@ -1777,7 +1832,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
{ {
@@ -1796,7 +1851,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
{ {
@@ -1817,7 +1872,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
{ {
@@ -1836,7 +1891,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
{ {
@@ -1859,14 +1914,14 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
{ {
// intentional space after "--build-option1 \" // intentional space after "--build-option1 \"
const shell_out = const shell_out =
\\$ zig build test.zig \ \\$ zig build test.zig \
\\ --build-option1 \ \\ --build-option1 \
\\ --build-option2 \\ --build-option2
\\$ ./test \\$ ./test
; ;
@@ -1881,7 +1936,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
{ {
@@ -1898,7 +1953,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
{ {
@@ -1917,7 +1972,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
{ {
@@ -1932,7 +1987,7 @@ test "shell parsed" {
var buffer = std.ArrayList(u8).init(test_allocator); var buffer = std.ArrayList(u8).init(test_allocator);
defer buffer.deinit(); defer buffer.deinit();
try printShell(buffer.writer(), shell_out); try printShell(buffer.writer(), shell_out, false);
try testing.expectEqualSlices(u8, expected, buffer.items); try testing.expectEqualSlices(u8, expected, buffer.items);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -24,19 +24,19 @@ pub fn main() !void {
var arg_idx: usize = 1; var arg_idx: usize = 1;
const zig_exe = nextArg(args, &arg_idx) orelse { const zig_exe = nextArg(args, &arg_idx) orelse {
std.debug.print("Expected first argument to be path to zig compiler\n", .{}); std.debug.print("Expected path to zig compiler\n", .{});
return error.InvalidArgs; return error.InvalidArgs;
}; };
const build_root = nextArg(args, &arg_idx) orelse { const build_root = nextArg(args, &arg_idx) orelse {
std.debug.print("Expected second argument to be build root directory path\n", .{}); std.debug.print("Expected build root directory path\n", .{});
return error.InvalidArgs; return error.InvalidArgs;
}; };
const cache_root = nextArg(args, &arg_idx) orelse { const cache_root = nextArg(args, &arg_idx) orelse {
std.debug.print("Expected third argument to be cache root directory path\n", .{}); std.debug.print("Expected cache root directory path\n", .{});
return error.InvalidArgs; return error.InvalidArgs;
}; };
const global_cache_root = nextArg(args, &arg_idx) orelse { const global_cache_root = nextArg(args, &arg_idx) orelse {
std.debug.print("Expected third argument to be global cache root directory path\n", .{}); std.debug.print("Expected global cache root directory path\n", .{});
return error.InvalidArgs; return error.InvalidArgs;
}; };
@@ -147,10 +147,6 @@ pub fn main() !void {
std.debug.print("Expected argument after --glibc-runtimes\n\n", .{}); std.debug.print("Expected argument after --glibc-runtimes\n\n", .{});
return usageAndErr(builder, false, stderr_stream); return usageAndErr(builder, false, stderr_stream);
}; };
} else if (mem.eql(u8, arg, "--verbose-tokenize")) {
builder.verbose_tokenize = true;
} else if (mem.eql(u8, arg, "--verbose-ast")) {
builder.verbose_ast = true;
} else if (mem.eql(u8, arg, "--verbose-link")) { } else if (mem.eql(u8, arg, "--verbose-link")) {
builder.verbose_link = true; builder.verbose_link = true;
} else if (mem.eql(u8, arg, "--verbose-air")) { } else if (mem.eql(u8, arg, "--verbose-air")) {
@@ -185,6 +181,20 @@ pub fn main() !void {
builder.enable_darling = true; builder.enable_darling = true;
} else if (mem.eql(u8, arg, "-fno-darling")) { } else if (mem.eql(u8, arg, "-fno-darling")) {
builder.enable_darling = false; builder.enable_darling = false;
} else if (mem.eql(u8, arg, "-fstage1")) {
builder.use_stage1 = true;
} else if (mem.eql(u8, arg, "-fno-stage1")) {
builder.use_stage1 = false;
} else if (mem.eql(u8, arg, "-freference-trace")) {
builder.reference_trace = 256;
} else if (mem.startsWith(u8, arg, "-freference-trace=")) {
const num = arg["-freference-trace=".len..];
builder.reference_trace = std.fmt.parseUnsigned(u32, num, 10) catch |err| {
std.debug.print("unable to parse reference_trace count '{s}': {s}", .{ num, @errorName(err) });
process.exit(1);
};
} else if (mem.eql(u8, arg, "-fno-reference-trace")) {
builder.reference_trace = null;
} else if (mem.eql(u8, arg, "--")) { } else if (mem.eql(u8, arg, "--")) {
builder.args = argsRest(args, arg_idx); builder.args = argsRest(args, arg_idx);
break; break;
@@ -306,12 +316,15 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: anytype) !void
try out_stream.writeAll( try out_stream.writeAll(
\\ \\
\\Advanced Options: \\Advanced Options:
\\ -fstage1 Force using bootstrap compiler as the codegen backend
\\ -fno-stage1 Prevent using bootstrap compiler as the codegen backend
\\ -freference-trace[=num] How many lines of reference trace should be shown per compile error
\\ -fno-reference-trace Disable reference trace
\\ --build-file [file] Override path to build.zig \\ --build-file [file] Override path to build.zig
\\ --cache-dir [path] Override path to zig cache directory \\ --cache-dir [path] Override path to local Zig cache directory
\\ --global-cache-dir [path] Override path to global Zig cache directory
\\ --zig-lib-dir [arg] Override path to Zig lib directory \\ --zig-lib-dir [arg] Override path to Zig lib directory
\\ --debug-log [scope] Enable debugging the compiler \\ --debug-log [scope] Enable debugging the compiler
\\ --verbose-tokenize Enable compiler debug output for tokenization
\\ --verbose-ast Enable compiler debug output for parsing into an AST
\\ --verbose-link Enable compiler debug output for linking \\ --verbose-link Enable compiler debug output for linking
\\ --verbose-air Enable compiler debug output for Zig AIR \\ --verbose-air Enable compiler debug output for Zig AIR
\\ --verbose-llvm-ir Enable compiler debug output for LLVM IR \\ --verbose-llvm-ir Enable compiler debug output for LLVM IR

555
lib/c.zig Normal file
View File

@@ -0,0 +1,555 @@
//! This is Zig's multi-target implementation of libc.
//! When builtin.link_libc is true, we need to export all the functions and
//! provide an entire C API.
const std = @import("std");
const builtin = @import("builtin");
const math = std.math;
const isNan = std.math.isNan;
const maxInt = std.math.maxInt;
const native_os = builtin.os.tag;
const native_arch = builtin.cpu.arch;
const native_abi = builtin.abi;
const is_wasm = switch (native_arch) {
.wasm32, .wasm64 => true,
else => false,
};
const is_msvc = switch (native_abi) {
.msvc => true,
else => false,
};
const is_freestanding = switch (native_os) {
.freestanding => true,
else => false,
};
comptime {
if (is_freestanding and is_wasm and builtin.link_libc) {
@export(wasm_start, .{ .name = "_start", .linkage = .Strong });
}
if (native_os == .linux) {
@export(clone, .{ .name = "clone" });
}
if (builtin.link_libc) {
@export(strcmp, .{ .name = "strcmp", .linkage = .Strong });
@export(strncmp, .{ .name = "strncmp", .linkage = .Strong });
@export(strerror, .{ .name = "strerror", .linkage = .Strong });
@export(strlen, .{ .name = "strlen", .linkage = .Strong });
@export(strcpy, .{ .name = "strcpy", .linkage = .Strong });
@export(strncpy, .{ .name = "strncpy", .linkage = .Strong });
@export(strcat, .{ .name = "strcat", .linkage = .Strong });
@export(strncat, .{ .name = "strncat", .linkage = .Strong });
} else if (is_msvc) {
@export(_fltused, .{ .name = "_fltused", .linkage = .Strong });
}
}
// Avoid dragging in the runtime safety mechanisms into this .o file,
// unless we're trying to test this file.
pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace, _: ?usize) noreturn {
@setCold(true);
_ = error_return_trace;
if (builtin.is_test) {
std.debug.panic("{s}", .{msg});
}
switch (native_os) {
.freestanding, .other, .amdhsa, .amdpal => while (true) {},
else => std.os.abort(),
}
}
extern fn main(argc: c_int, argv: [*:null]?[*:0]u8) c_int;
fn wasm_start() callconv(.C) void {
_ = main(0, undefined);
}
var _fltused: c_int = 1;
fn strcpy(dest: [*:0]u8, src: [*:0]const u8) callconv(.C) [*:0]u8 {
var i: usize = 0;
while (src[i] != 0) : (i += 1) {
dest[i] = src[i];
}
dest[i] = 0;
return dest;
}
test "strcpy" {
var s1: [9:0]u8 = undefined;
s1[0] = 0;
_ = strcpy(&s1, "foobarbaz");
try std.testing.expectEqualSlices(u8, "foobarbaz", std.mem.sliceTo(&s1, 0));
}
fn strncpy(dest: [*:0]u8, src: [*:0]const u8, n: usize) callconv(.C) [*:0]u8 {
var i: usize = 0;
while (i < n and src[i] != 0) : (i += 1) {
dest[i] = src[i];
}
while (i < n) : (i += 1) {
dest[i] = 0;
}
return dest;
}
test "strncpy" {
var s1: [9:0]u8 = undefined;
s1[0] = 0;
_ = strncpy(&s1, "foobarbaz", @sizeOf(@TypeOf(s1)));
try std.testing.expectEqualSlices(u8, "foobarbaz", std.mem.sliceTo(&s1, 0));
}
fn strcat(dest: [*:0]u8, src: [*:0]const u8) callconv(.C) [*:0]u8 {
var dest_end: usize = 0;
while (dest[dest_end] != 0) : (dest_end += 1) {}
var i: usize = 0;
while (src[i] != 0) : (i += 1) {
dest[dest_end + i] = src[i];
}
dest[dest_end + i] = 0;
return dest;
}
test "strcat" {
var s1: [9:0]u8 = undefined;
s1[0] = 0;
_ = strcat(&s1, "foo");
_ = strcat(&s1, "bar");
_ = strcat(&s1, "baz");
try std.testing.expectEqualSlices(u8, "foobarbaz", std.mem.sliceTo(&s1, 0));
}
fn strncat(dest: [*:0]u8, src: [*:0]const u8, avail: usize) callconv(.C) [*:0]u8 {
var dest_end: usize = 0;
while (dest[dest_end] != 0) : (dest_end += 1) {}
var i: usize = 0;
while (i < avail and src[i] != 0) : (i += 1) {
dest[dest_end + i] = src[i];
}
dest[dest_end + i] = 0;
return dest;
}
test "strncat" {
var s1: [9:0]u8 = undefined;
s1[0] = 0;
_ = strncat(&s1, "foo1111", 3);
_ = strncat(&s1, "bar1111", 3);
_ = strncat(&s1, "baz1111", 3);
try std.testing.expectEqualSlices(u8, "foobarbaz", std.mem.sliceTo(&s1, 0));
}
fn strcmp(s1: [*:0]const u8, s2: [*:0]const u8) callconv(.C) c_int {
return std.cstr.cmp(s1, s2);
}
fn strlen(s: [*:0]const u8) callconv(.C) usize {
return std.mem.len(s);
}
fn strncmp(_l: [*:0]const u8, _r: [*:0]const u8, _n: usize) callconv(.C) c_int {
if (_n == 0) return 0;
var l = _l;
var r = _r;
var n = _n - 1;
while (l[0] != 0 and r[0] != 0 and n != 0 and l[0] == r[0]) {
l += 1;
r += 1;
n -= 1;
}
return @as(c_int, l[0]) - @as(c_int, r[0]);
}
fn strerror(errnum: c_int) callconv(.C) [*:0]const u8 {
_ = errnum;
return "TODO strerror implementation";
}
test "strncmp" {
try std.testing.expect(strncmp("a", "b", 1) < 0);
try std.testing.expect(strncmp("a", "c", 1) < 0);
try std.testing.expect(strncmp("b", "a", 1) > 0);
try std.testing.expect(strncmp("\xff", "\x02", 1) > 0);
}
// 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.
fn clone() callconv(.Naked) void {
switch (native_arch) {
.i386 => {
// __clone(func, stack, flags, arg, ptid, tls, ctid)
// +8, +12, +16, +20, +24, +28, +32
// syscall(SYS_clone, flags, stack, ptid, tls, ctid)
// eax, ebx, ecx, edx, esi, edi
asm volatile (
\\ push %%ebp
\\ mov %%esp,%%ebp
\\ push %%ebx
\\ push %%esi
\\ push %%edi
\\ // Setup the arguments
\\ mov 16(%%ebp),%%ebx
\\ mov 12(%%ebp),%%ecx
\\ and $-16,%%ecx
\\ sub $20,%%ecx
\\ mov 20(%%ebp),%%eax
\\ mov %%eax,4(%%ecx)
\\ mov 8(%%ebp),%%eax
\\ mov %%eax,0(%%ecx)
\\ mov 24(%%ebp),%%edx
\\ mov 28(%%ebp),%%esi
\\ mov 32(%%ebp),%%edi
\\ mov $120,%%eax
\\ int $128
\\ test %%eax,%%eax
\\ jnz 1f
\\ pop %%eax
\\ xor %%ebp,%%ebp
\\ call *%%eax
\\ mov %%eax,%%ebx
\\ xor %%eax,%%eax
\\ inc %%eax
\\ int $128
\\ hlt
\\1:
\\ pop %%edi
\\ pop %%esi
\\ pop %%ebx
\\ pop %%ebp
\\ ret
);
},
.x86_64 => {
asm volatile (
\\ xor %%eax,%%eax
\\ mov $56,%%al // SYS_clone
\\ 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 // SYS_exit
\\ syscall
\\ hlt
\\1: ret
\\
);
},
.aarch64 => {
// __clone(func, stack, flags, arg, ptid, tls, ctid)
// x0, x1, w2, x3, x4, x5, x6
// syscall(SYS_clone, flags, stack, ptid, tls, ctid)
// x8, x0, x1, x2, x3, x4
asm volatile (
\\ // align stack and save func,arg
\\ and x1,x1,#-16
\\ stp x0,x3,[x1,#-16]!
\\
\\ // syscall
\\ uxtw x0,w2
\\ mov x2,x4
\\ mov x3,x5
\\ mov x4,x6
\\ mov x8,#220 // SYS_clone
\\ svc #0
\\
\\ cbz x0,1f
\\ // parent
\\ ret
\\ // child
\\1: ldp x1,x0,[sp],#16
\\ blr x1
\\ mov x8,#93 // SYS_exit
\\ svc #0
);
},
.arm, .thumb => {
// __clone(func, stack, flags, arg, ptid, tls, ctid)
// r0, r1, r2, r3, +0, +4, +8
// syscall(SYS_clone, flags, stack, ptid, tls, ctid)
// r7 r0, r1, r2, r3, r4
asm volatile (
\\ stmfd sp!,{r4,r5,r6,r7}
\\ mov r7,#120
\\ mov r6,r3
\\ mov r5,r0
\\ mov r0,r2
\\ and r1,r1,#-16
\\ ldr r2,[sp,#16]
\\ ldr r3,[sp,#20]
\\ ldr r4,[sp,#24]
\\ svc 0
\\ tst r0,r0
\\ beq 1f
\\ ldmfd sp!,{r4,r5,r6,r7}
\\ bx lr
\\
\\1: mov r0,r6
\\ bl 3f
\\2: mov r7,#1
\\ svc 0
\\ b 2b
\\3: bx r5
);
},
.riscv64 => {
// __clone(func, stack, flags, arg, ptid, tls, ctid)
// a0, a1, a2, a3, a4, a5, a6
// syscall(SYS_clone, flags, stack, ptid, tls, ctid)
// a7 a0, a1, a2, a3, a4
asm volatile (
\\ # Save func and arg to stack
\\ addi a1, a1, -16
\\ sd a0, 0(a1)
\\ sd a3, 8(a1)
\\
\\ # Call SYS_clone
\\ mv a0, a2
\\ mv a2, a4
\\ mv a3, a5
\\ mv a4, a6
\\ li a7, 220 # SYS_clone
\\ ecall
\\
\\ beqz a0, 1f
\\ # Parent
\\ ret
\\
\\ # Child
\\1: ld a1, 0(sp)
\\ ld a0, 8(sp)
\\ jalr a1
\\
\\ # Exit
\\ li a7, 93 # SYS_exit
\\ ecall
);
},
.mips, .mipsel => {
// __clone(func, stack, flags, arg, ptid, tls, ctid)
// 3, 4, 5, 6, 7, 8, 9
// syscall(SYS_clone, flags, stack, ptid, tls, ctid)
// 2 4, 5, 6, 7, 8
asm volatile (
\\ # Save function pointer and argument pointer on new thread stack
\\ and $5, $5, -8
\\ subu $5, $5, 16
\\ sw $4, 0($5)
\\ sw $7, 4($5)
\\ # Shuffle (fn,sp,fl,arg,ptid,tls,ctid) to (fl,sp,ptid,tls,ctid)
\\ move $4, $6
\\ lw $6, 16($sp)
\\ lw $7, 20($sp)
\\ lw $9, 24($sp)
\\ subu $sp, $sp, 16
\\ sw $9, 16($sp)
\\ li $2, 4120
\\ syscall
\\ beq $7, $0, 1f
\\ nop
\\ addu $sp, $sp, 16
\\ jr $ra
\\ subu $2, $0, $2
\\1:
\\ beq $2, $0, 1f
\\ nop
\\ addu $sp, $sp, 16
\\ jr $ra
\\ nop
\\1:
\\ lw $25, 0($sp)
\\ lw $4, 4($sp)
\\ jalr $25
\\ nop
\\ move $4, $2
\\ li $2, 4001
\\ syscall
);
},
.powerpc => {
// __clone(func, stack, flags, arg, ptid, tls, ctid)
// 3, 4, 5, 6, 7, 8, 9
// syscall(SYS_clone, flags, stack, ptid, tls, ctid)
// 0 3, 4, 5, 6, 7
asm volatile (
\\# store non-volatile regs r30, r31 on stack in order to put our
\\# start func and its arg there
\\stwu 30, -16(1)
\\stw 31, 4(1)
\\
\\# save r3 (func) into r30, and r6(arg) into r31
\\mr 30, 3
\\mr 31, 6
\\
\\# create initial stack frame for new thread
\\clrrwi 4, 4, 4
\\li 0, 0
\\stwu 0, -16(4)
\\
\\#move c into first arg
\\mr 3, 5
\\#mr 4, 4
\\mr 5, 7
\\mr 6, 8
\\mr 7, 9
\\
\\# move syscall number into r0
\\li 0, 120
\\
\\sc
\\
\\# check for syscall error
\\bns+ 1f # jump to label 1 if no summary overflow.
\\#else
\\neg 3, 3 #negate the result (errno)
\\1:
\\# compare sc result with 0
\\cmpwi cr7, 3, 0
\\
\\# if not 0, jump to end
\\bne cr7, 2f
\\
\\#else: we're the child
\\#call funcptr: move arg (d) into r3
\\mr 3, 31
\\#move r30 (funcptr) into CTR reg
\\mtctr 30
\\# call CTR reg
\\bctrl
\\# mov SYS_exit into r0 (the exit param is already in r3)
\\li 0, 1
\\sc
\\
\\2:
\\
\\# restore stack
\\lwz 30, 0(1)
\\lwz 31, 4(1)
\\addi 1, 1, 16
\\
\\blr
);
},
.powerpc64, .powerpc64le => {
// __clone(func, stack, flags, arg, ptid, tls, ctid)
// 3, 4, 5, 6, 7, 8, 9
// syscall(SYS_clone, flags, stack, ptid, tls, ctid)
// 0 3, 4, 5, 6, 7
asm volatile (
\\ # create initial stack frame for new thread
\\ clrrdi 4, 4, 4
\\ li 0, 0
\\ stdu 0,-32(4)
\\
\\ # save fn and arg to child stack
\\ std 3, 8(4)
\\ std 6, 16(4)
\\
\\ # shuffle args into correct registers and call SYS_clone
\\ mr 3, 5
\\ #mr 4, 4
\\ mr 5, 7
\\ mr 6, 8
\\ mr 7, 9
\\ li 0, 120 # SYS_clone = 120
\\ sc
\\
\\ # if error, negate return (errno)
\\ bns+ 1f
\\ neg 3, 3
\\
\\1:
\\ # if we're the parent, return
\\ cmpwi cr7, 3, 0
\\ bnelr cr7
\\
\\ # we're the child. call fn(arg)
\\ ld 3, 16(1)
\\ ld 12, 8(1)
\\ mtctr 12
\\ bctrl
\\
\\ # call SYS_exit. exit code is already in r3 from fn return value
\\ li 0, 1 # SYS_exit = 1
\\ sc
);
},
.sparc64 => {
// __clone(func, stack, flags, arg, ptid, tls, ctid)
// i0, i1, i2, i3, i4, i5, sp
// syscall(SYS_clone, flags, stack, ptid, tls, ctid)
// g1 o0, o1, o2, o3, o4
asm volatile (
\\ save %%sp, -192, %%sp
\\ # Save the func pointer and the arg pointer
\\ mov %%i0, %%g2
\\ mov %%i3, %%g3
\\ # Shuffle the arguments
\\ mov 217, %%g1
\\ mov %%i2, %%o0
\\ # Add some extra space for the initial frame
\\ sub %%i1, 176 + 2047, %%o1
\\ mov %%i4, %%o2
\\ mov %%i5, %%o3
\\ ldx [%%fp + 0x8af], %%o4
\\ t 0x6d
\\ bcs,pn %%xcc, 2f
\\ nop
\\ # The child pid is returned in o0 while o1 tells if this
\\ # process is # the child (=1) or the parent (=0).
\\ brnz %%o1, 1f
\\ nop
\\ # Parent process, return the child pid
\\ mov %%o0, %%i0
\\ ret
\\ restore
\\1:
\\ # Child process, call func(arg)
\\ mov %%g0, %%fp
\\ call %%g2
\\ mov %%g3, %%o0
\\ # Exit
\\ mov 1, %%g1
\\ t 0x6d
\\2:
\\ # The syscall failed
\\ sub %%g0, %%o0, %%i0
\\ ret
\\ restore
);
},
else => @compileError("Implement clone() for this arch."),
}
}

217
lib/compiler_rt.zig Normal file
View File

@@ -0,0 +1,217 @@
pub const panic = @import("compiler_rt/common.zig").panic;
comptime {
_ = @import("compiler_rt/atomics.zig");
_ = @import("compiler_rt/addf3.zig");
_ = @import("compiler_rt/addhf3.zig");
_ = @import("compiler_rt/addsf3.zig");
_ = @import("compiler_rt/adddf3.zig");
_ = @import("compiler_rt/addtf3.zig");
_ = @import("compiler_rt/addxf3.zig");
_ = @import("compiler_rt/subhf3.zig");
_ = @import("compiler_rt/subsf3.zig");
_ = @import("compiler_rt/subdf3.zig");
_ = @import("compiler_rt/subtf3.zig");
_ = @import("compiler_rt/subxf3.zig");
_ = @import("compiler_rt/mulf3.zig");
_ = @import("compiler_rt/mulhf3.zig");
_ = @import("compiler_rt/mulsf3.zig");
_ = @import("compiler_rt/muldf3.zig");
_ = @import("compiler_rt/multf3.zig");
_ = @import("compiler_rt/mulxf3.zig");
_ = @import("compiler_rt/mulc3.zig");
_ = @import("compiler_rt/mulhc3.zig");
_ = @import("compiler_rt/mulsc3.zig");
_ = @import("compiler_rt/muldc3.zig");
_ = @import("compiler_rt/mulxc3.zig");
_ = @import("compiler_rt/multc3.zig");
_ = @import("compiler_rt/divc3.zig");
_ = @import("compiler_rt/divhc3.zig");
_ = @import("compiler_rt/divsc3.zig");
_ = @import("compiler_rt/divdc3.zig");
_ = @import("compiler_rt/divxc3.zig");
_ = @import("compiler_rt/divtc3.zig");
_ = @import("compiler_rt/neghf2.zig");
_ = @import("compiler_rt/negsf2.zig");
_ = @import("compiler_rt/negdf2.zig");
_ = @import("compiler_rt/negtf2.zig");
_ = @import("compiler_rt/negxf2.zig");
_ = @import("compiler_rt/comparef.zig");
_ = @import("compiler_rt/cmphf2.zig");
_ = @import("compiler_rt/cmpsf2.zig");
_ = @import("compiler_rt/cmpdf2.zig");
_ = @import("compiler_rt/cmptf2.zig");
_ = @import("compiler_rt/cmpxf2.zig");
_ = @import("compiler_rt/gehf2.zig");
_ = @import("compiler_rt/gesf2.zig");
_ = @import("compiler_rt/gedf2.zig");
_ = @import("compiler_rt/gexf2.zig");
_ = @import("compiler_rt/getf2.zig");
_ = @import("compiler_rt/unordhf2.zig");
_ = @import("compiler_rt/unordsf2.zig");
_ = @import("compiler_rt/unorddf2.zig");
_ = @import("compiler_rt/unordxf2.zig");
_ = @import("compiler_rt/unordtf2.zig");
_ = @import("compiler_rt/extendf.zig");
_ = @import("compiler_rt/extendhfsf2.zig");
_ = @import("compiler_rt/extendhfdf2.zig");
_ = @import("compiler_rt/extendhftf2.zig");
_ = @import("compiler_rt/extendhfxf2.zig");
_ = @import("compiler_rt/extendsfdf2.zig");
_ = @import("compiler_rt/extendsftf2.zig");
_ = @import("compiler_rt/extendsfxf2.zig");
_ = @import("compiler_rt/extenddftf2.zig");
_ = @import("compiler_rt/extenddfxf2.zig");
_ = @import("compiler_rt/extendxftf2.zig");
_ = @import("compiler_rt/truncf.zig");
_ = @import("compiler_rt/truncsfhf2.zig");
_ = @import("compiler_rt/truncdfhf2.zig");
_ = @import("compiler_rt/truncdfsf2.zig");
_ = @import("compiler_rt/truncxfhf2.zig");
_ = @import("compiler_rt/truncxfsf2.zig");
_ = @import("compiler_rt/truncxfdf2.zig");
_ = @import("compiler_rt/trunctfhf2.zig");
_ = @import("compiler_rt/trunctfsf2.zig");
_ = @import("compiler_rt/trunctfdf2.zig");
_ = @import("compiler_rt/trunctfxf2.zig");
_ = @import("compiler_rt/divhf3.zig");
_ = @import("compiler_rt/divsf3.zig");
_ = @import("compiler_rt/divdf3.zig");
_ = @import("compiler_rt/divxf3.zig");
_ = @import("compiler_rt/divtf3.zig");
_ = @import("compiler_rt/sin.zig");
_ = @import("compiler_rt/cos.zig");
_ = @import("compiler_rt/sincos.zig");
_ = @import("compiler_rt/ceil.zig");
_ = @import("compiler_rt/exp.zig");
_ = @import("compiler_rt/exp2.zig");
_ = @import("compiler_rt/fabs.zig");
_ = @import("compiler_rt/floor.zig");
_ = @import("compiler_rt/fma.zig");
_ = @import("compiler_rt/fmax.zig");
_ = @import("compiler_rt/fmin.zig");
_ = @import("compiler_rt/fmod.zig");
_ = @import("compiler_rt/log.zig");
_ = @import("compiler_rt/log10.zig");
_ = @import("compiler_rt/log2.zig");
_ = @import("compiler_rt/round.zig");
_ = @import("compiler_rt/sqrt.zig");
_ = @import("compiler_rt/tan.zig");
_ = @import("compiler_rt/trunc.zig");
_ = @import("compiler_rt/stack_probe.zig");
_ = @import("compiler_rt/divti3.zig");
_ = @import("compiler_rt/modti3.zig");
_ = @import("compiler_rt/multi3.zig");
_ = @import("compiler_rt/udivti3.zig");
_ = @import("compiler_rt/udivmodti4.zig");
_ = @import("compiler_rt/umodti3.zig");
_ = @import("compiler_rt/int_to_float.zig");
_ = @import("compiler_rt/floatsihf.zig");
_ = @import("compiler_rt/floatsisf.zig");
_ = @import("compiler_rt/floatsidf.zig");
_ = @import("compiler_rt/floatsitf.zig");
_ = @import("compiler_rt/floatsixf.zig");
_ = @import("compiler_rt/floatdihf.zig");
_ = @import("compiler_rt/floatdisf.zig");
_ = @import("compiler_rt/floatdidf.zig");
_ = @import("compiler_rt/floatditf.zig");
_ = @import("compiler_rt/floatdixf.zig");
_ = @import("compiler_rt/floattihf.zig");
_ = @import("compiler_rt/floattisf.zig");
_ = @import("compiler_rt/floattidf.zig");
_ = @import("compiler_rt/floattitf.zig");
_ = @import("compiler_rt/floattixf.zig");
_ = @import("compiler_rt/floatundihf.zig");
_ = @import("compiler_rt/floatundisf.zig");
_ = @import("compiler_rt/floatundidf.zig");
_ = @import("compiler_rt/floatunditf.zig");
_ = @import("compiler_rt/floatundixf.zig");
_ = @import("compiler_rt/floatunsihf.zig");
_ = @import("compiler_rt/floatunsisf.zig");
_ = @import("compiler_rt/floatunsidf.zig");
_ = @import("compiler_rt/floatunsitf.zig");
_ = @import("compiler_rt/floatunsixf.zig");
_ = @import("compiler_rt/floatuntihf.zig");
_ = @import("compiler_rt/floatuntisf.zig");
_ = @import("compiler_rt/floatuntidf.zig");
_ = @import("compiler_rt/floatuntitf.zig");
_ = @import("compiler_rt/floatuntixf.zig");
_ = @import("compiler_rt/float_to_int.zig");
_ = @import("compiler_rt/fixhfsi.zig");
_ = @import("compiler_rt/fixhfdi.zig");
_ = @import("compiler_rt/fixhfti.zig");
_ = @import("compiler_rt/fixsfsi.zig");
_ = @import("compiler_rt/fixsfdi.zig");
_ = @import("compiler_rt/fixsfti.zig");
_ = @import("compiler_rt/fixdfsi.zig");
_ = @import("compiler_rt/fixdfdi.zig");
_ = @import("compiler_rt/fixdfti.zig");
_ = @import("compiler_rt/fixtfsi.zig");
_ = @import("compiler_rt/fixtfdi.zig");
_ = @import("compiler_rt/fixtfti.zig");
_ = @import("compiler_rt/fixxfsi.zig");
_ = @import("compiler_rt/fixxfdi.zig");
_ = @import("compiler_rt/fixxfti.zig");
_ = @import("compiler_rt/fixunshfsi.zig");
_ = @import("compiler_rt/fixunshfdi.zig");
_ = @import("compiler_rt/fixunshfti.zig");
_ = @import("compiler_rt/fixunssfsi.zig");
_ = @import("compiler_rt/fixunssfdi.zig");
_ = @import("compiler_rt/fixunssfti.zig");
_ = @import("compiler_rt/fixunsdfsi.zig");
_ = @import("compiler_rt/fixunsdfdi.zig");
_ = @import("compiler_rt/fixunsdfti.zig");
_ = @import("compiler_rt/fixunstfsi.zig");
_ = @import("compiler_rt/fixunstfdi.zig");
_ = @import("compiler_rt/fixunstfti.zig");
_ = @import("compiler_rt/fixunsxfsi.zig");
_ = @import("compiler_rt/fixunsxfdi.zig");
_ = @import("compiler_rt/fixunsxfti.zig");
_ = @import("compiler_rt/count0bits.zig");
_ = @import("compiler_rt/parity.zig");
_ = @import("compiler_rt/popcount.zig");
_ = @import("compiler_rt/bswap.zig");
_ = @import("compiler_rt/int.zig");
_ = @import("compiler_rt/shift.zig");
_ = @import("compiler_rt/negXi2.zig");
_ = @import("compiler_rt/muldi3.zig");
_ = @import("compiler_rt/absv.zig");
_ = @import("compiler_rt/absvsi2.zig");
_ = @import("compiler_rt/absvdi2.zig");
_ = @import("compiler_rt/absvti2.zig");
_ = @import("compiler_rt/negv.zig");
_ = @import("compiler_rt/addo.zig");
_ = @import("compiler_rt/subo.zig");
_ = @import("compiler_rt/mulo.zig");
_ = @import("compiler_rt/cmp.zig");
_ = @import("compiler_rt/os_version_check.zig");
_ = @import("compiler_rt/emutls.zig");
_ = @import("compiler_rt/arm.zig");
_ = @import("compiler_rt/aulldiv.zig");
_ = @import("compiler_rt/aullrem.zig");
_ = @import("compiler_rt/clear_cache.zig");
_ = @import("compiler_rt/memcpy.zig");
_ = @import("compiler_rt/memset.zig");
_ = @import("compiler_rt/memmove.zig");
_ = @import("compiler_rt/memcmp.zig");
_ = @import("compiler_rt/bcmp.zig");
}

508
lib/compiler_rt/README.md Normal file
View File

@@ -0,0 +1,508 @@
If hardware lacks basic or specialized functionality, compiler-rt adds such functionality
for basic arithmetic(s).
One such example is 64-bit integer multiplication on 32-bit x86.
Goals:
1. zig as linker for object files produced by other compilers
=> `function compatibility` to compiler-rt and libgcc for same-named functions
* compatibility conflict between compiler-rt and libgcc: prefer compiler-rt
2. `symbol-level compatibility` low-priority compared to emitted calls by llvm
* symbol-level compatibility: libgcc even lower priority
3. add zig-specific language runtime features, see #7265
* example: arbitrary bit width integer arithmetic
* lower to call those functions for e.g. multiplying two i12345 numbers together
* proper naming + documention for standardizing (allow languages to follow our exmaple)
Current status (tracking libgcc documentation):
- Integer library routines => almost implemented
- Soft float library routines => finished
- Decimal float library routines => unimplemented (~120 functions)
- Fixed-point fractional library routines => unimplemented (~300 functions)
- Exception handling routines => unclear, if supported (~32+x undocumented functions)
- Miscellaneous routines => unclear, if supported (cache control and stack function)
- No zig-specific language runtime features in compiler-rt yet
This library is automatically built as-needed for the compilation target and
then statically linked and therefore is a transparent dependency for the
programmer.
For details see `../compiler_rt.zig`.
The routines in this folder are listed below.
Routines are annotated as `type source routine // description`, with `routine`
being the name used in aforementioned `compiler_rt.zig`.
`dev` means deviating from compiler_rt, `port` ported, `source` is the
information source for the implementation, `none` means unimplemented.
Some examples for the naming convention are:
- dev source name_routine, name_routine2 various implementations for performance, simplicity etc
- port llvm compiler-rt library routines from [LLVM](http://compiler-rt.llvm.org/)
* LLVM emits library calls to compiler-rt, if the hardware lacks functionality
- port musl libc routines from [musl](https://musl.libc.org/)
If the library or information source is uncommon, use the entry `other` for `source`.
Please do not break the search by inserting entries in another format than `impl space source`.
Bugs should be solved by trying to duplicate the bug upstream, if possible.
* If the bug exists upstream, get it fixed upstream and port the fix downstream to Zig.
* If the bug only exists in Zig, use the corresponding C code and debug
both implementations side by side to figure out what is wrong.
## Integer library routines
#### Integer Bit operations
- dev HackersDelight __clzsi2 // count leading zeros
- dev HackersDelight __clzdi2 // count leading zeros
- dev HackersDelight __clzti2 // count leading zeros
- dev HackersDelight __ctzsi2 // count trailing zeros
- dev HackersDelight __ctzdi2 // count trailing zeros
- dev HackersDelight __ctzti2 // count trailing zeros
- dev __ctzsi2 __ffssi2 // find least significant 1 bit
- dev __ctzsi2 __ffsdi2 // find least significant 1 bit
- dev __ctzsi2 __ffsti2 // find least significant 1 bit
- dev BitTwiddlingHacks __paritysi2 // bit parity
- dev BitTwiddlingHacks __paritydi2 // bit parity
- dev BitTwiddlingHacks __parityti2 // bit parity
- dev TAOCP __popcountsi2 // bit population
- dev TAOCP __popcountdi2 // bit population
- dev TAOCP __popcountti2 // bit population
- dev other __bswapsi2 // a byteswapped
- dev other __bswapdi2 // a byteswapped
- dev other __bswapti2 // a byteswapped
#### Integer Comparison
- port llvm __cmpsi2 // a,b: i32, (a<b)-> 0, (a==b) -> 1, (a>b) -> 2
- port llvm __cmpdi2 // a,b: i64
- port llvm __cmpti2 // a,b: i128
- port llvm __ucmpsi2 // a,b: u32, (a<b)-> 0, (a==b) -> 1, (a>b) -> 2
- port llvm __ucmpdi2 // a,b: u64
- port llvm __ucmpti2 // a,b: u128
#### Integer Arithmetic
- none none __ashlsi3 // a,b: i32, a << b unused in llvm, TODO (e.g. used by rl78)
- port llvm __ashldi3 // a,b: u64
- port llvm __ashlti3 // a,b: u128
- none none __ashrsi3 // a,b: i32, a >> b arithmetic (sign fill) TODO (e.g. used by rl78)
- port llvm __ashrdi3 // ..
- port llvm __ashrti3 //
- none none __lshrsi3 // a,b: i32, a >> b logical (zero fill) TODO (e.g. used by rl78)
- port llvm __lshrdi3 //
- port llvm __lshrti3 //
- port llvm __negdi2 // a: i32, -a, symbol-level compatibility with libgcc
- port llvm __negti2 // unnecessary: unused in backends
- port llvm __mulsi3 // a,b: i32, a * b
- port llvm __muldi3 //
- port llvm __multi3 //
- port llvm __divsi3 // a,b: i32, a / b
- port llvm __divdi3 //
- port llvm __divti3 //
- port llvm __udivsi3 // a,b: u32, a / b
- port llvm __udivdi3 //
- port llvm __udivti3 //
- port llvm __modsi3 // a,b: i32, a % b
- port llvm __moddi3 //
- port llvm __modti3 //
- port llvm __umodsi3 // a,b: u32, a % b
- port llvm __umoddi3 //
- port llvm __umodti3 //
- port llvm __udivmoddi4 // a,b: u32, a / b, rem.* = a % b unsigned
- port llvm __udivmodti4 //
- port llvm __udivmodsi4 //
- port llvm __divmodsi4 // a,b: i32, a / b, rem.* = a % b signed, ARM
- port llvm __divmoddi4 //
#### Integer Arithmetic with trapping overflow
- dev BitTwiddlingHacks __absvsi2 // abs(a)
- dev BitTwiddlingHacks __absvdi2 // abs(a)
- dev BitTwiddlingHacks __absvti2 // abs(a)
- port llvm __negvsi2 // -a symbol-level compatibility: libgcc
- port llvm __negvdi2 // -a unnecessary: unused in backends
- port llvm __negvti2 // -a
- TODO upstreaming __addvsi3..__mulvti3 after testing panics works
- dev HackersDelight __addvsi3 // a + b
- dev HackersDelight __addvdi3 //
- dev HackersDelight __addvti3 //
- dev HackersDelight __subvsi3 // a - b
- dev HackersDelight __subvdi3 //
- dev HackersDelight __subvti3 //
- dev HackersDelight __mulvsi3 // a * b
- dev HackersDelight __mulvdi3 //
- dev HackersDelight __mulvti3 //
#### Integer Arithmetic which returns if overflow (would be faster without pointer)
- dev HackersDelight __addosi4 // a + b, overflow->ov.*=1 else 0
- dev HackersDelight __addodi4 // (completeness + performance, llvm does not use them)
- dev HackersDelight __addoti4 //
- dev HackersDelight __subosi4 // a - b, overflow->ov.*=1 else 0
- dev HackersDelight __subodi4 // (completeness + performance, llvm does not use them)
- dev HackersDelight __suboti4 //
- dev HackersDelight __mulosi4 // a * b, overflow->ov.*=1 else 0
- dev HackersDelight __mulodi4 // (required by llvm)
- dev HackersDelight __muloti4 //
## Float library routines
TODO: review source of implementation
#### Float Conversion
- dev other __extendsfdf2 // a: f32 -> f64, TODO: missing tests
- dev other __extendsftf2 // a: f32 -> f128
- dev llvm __extendsfxf2 // a: f32 -> f80, TODO: missing tests
- dev other __extenddftf2 // a: f64 -> f128
- dev llvm __extenddfxf2 // a: f64 -> f80
- dev other __truncdfsf2 // a: f64 -> f32, rounding towards zero
- dev other __trunctfdf2 // a: f128-> f64
- dev other __trunctfsf2 // a: f128-> f32
- dev llvm __truncxfsf2 // a: f80 -> f32, TODO: missing tests
- dev llvm __truncxfdf2 // a: f80 -> f64, TODO: missing tests
- dev unclear __fixsfsi // a: f32 -> i32, rounding towards zero
- dev unclear __fixdfsi // a: f64 -> i32
- dev unclear __fixtfsi // a: f128-> i32
- dev unclear __fixxfsi // a: f80 -> i32, TODO: missing tests
- dev unclear __fixsfdi // a: f32 -> i64, rounding towards zero
- dev unclear __fixdfdi // ..
- dev unclear __fixtfdi //
- dev unclear __fixxfdi // TODO: missing tests
- dev unclear __fixsfti // a: f32 -> i128, rounding towards zero
- dev unclear __fixdfti // ..
- dev unclear __fixtfdi //
- dev unclear __fixxfti // TODO: missing tests
- dev unclear __fixunssfsi // a: f32 -> u32, rounding towards zero. negative values become 0.
- dev unclear __fixunsdfsi // ..
- dev unclear __fixunstfsi //
- dev unclear __fixunsxfsi // TODO: missing tests
- dev unclear __fixunssfdi // a: f32 -> u64, rounding towards zero. negative values become 0.
- dev unclear __fixunsdfdi //
- dev unclear __fixunstfdi //
- dev unclear __fixunsxfdi // TODO: missing tests
- dev unclear __fixunssfti // a: f32 -> u128, rounding towards zero. negative values become 0.
- dev unclear __fixunsdfti //
- dev unclear __fixunstfdi //
- dev unclear __fixunsxfti // TODO: some more tests needed for base coverage
- dev unclear __floatsisf // a: i32 -> f32
- dev unclear __floatsidf // a: i32 -> f64, TODO: missing tests
- dev unclear __floatsitf // ..
- dev unclear __floatsixf // TODO: missing tests
- dev unclear __floatdisf // a: i64 -> f32
- dev unclear __floatdidf //
- dev unclear __floatditf //
- dev unclear __floatdixf // TODO: missing tests
- dev unclear __floattisf // a: i128-> f32
- dev unclear __floattidf //
- dev unclear __floattitf //
- dev unclear __floattixf // TODO: missing tests
- dev unclear __floatunsisf // a: u32 -> f32
- dev unclear __floatunsidf // TODO: missing tests
- dev unclear __floatunsitf //
- dev unclear __floatunsixf // TODO: missing tests
- dev unclear __floatundisf // a: u64 -> f32
- dev unclear __floatundidf //
- dev unclear __floatunditf //
- dev unclear __floatundixf // TODO: missing tests
- dev unclear __floatuntisf // a: u128-> f32
- dev unclear __floatuntidf //
- dev unclear __floatuntitf //
- dev unclear __floatuntixf // TODO: missing tests
#### Float Comparison
- dev other __cmpsf2 // a,b:f32, (a<b)->-1,(a==b)->0,(a>b)->1,Nan->1
- dev other __cmpdf2 // exported from __lesf2, __ledf2, __letf2 (below)
- dev other __cmptf2 // But: if NaN is a possibility, use another routine.
- dev other __unordsf2 // a,b:f32, (a==+-NaN or b==+-NaN) -> !=0, else -> 0
- dev other __unorddf2 // __only reliable for (input!=NaN)__
- dev other __unordtf2 // TODO: missing tests
- dev other __eqsf2 // (a!=NaN) and (b!=Nan) and (a==b) -> output=0
- dev other __eqdf2 //
- dev other __eqtf2 //
- dev other __nesf2 // (a==NaN) or (b==Nan) or (a!=b) -> output!=0
- dev other __nedf2 //
- dev other __netf2 // __eqtf2 and __netf2 have same return value -> tested with __eqsf2
- dev other __gesf2 // (a!=Nan) and (b!=Nan) and (a>=b) -> output>=0
- dev other __gedf2 //
- dev other __getf2 // TODO: missing tests
- dev other __ltsf2 // (a!=Nan) and (b!=Nan) and (a<b) -> output<0
- dev other __ltdf2 //
- dev other __lttf2 // TODO: missing tests
- dev other __lesf2 // (a!=Nan) and (b!=Nan) and (a<=b) -> output<=0
- dev other __ledf2 //
- dev other __letf2 // TODO: missing tests
- dev other __gtsf2 // (a!=Nan) and (b!=Nan) and (a>b) -> output>0
- dev other __gtdf2 //
- dev other __gttf2 // TODO: missing tests
#### Float Arithmetic
- dev unclear __addsf3 // a + b f32, TODO: missing tests
- dev unclear __adddf3 // a + b f64, TODO: missing tests
- dev unclear __addtf3 // a + b f128
- dev unclear __addxf3 // a + b f80
- dev unclear __aeabi_fadd // a + b f64 ARM: AAPCS
- dev unclear __aeabi_dadd // a + b f64 ARM: AAPCS
- dev unclear __subsf3 // a - b, TODO: missing tests
- dev unclear __subdf3 // a - b, TODO: missing tests
- dev unclear __subtf3 // a - b
- dev unclear __subxf3 // a - b f80, TODO: missing tests
- dev unclear __aeabi_fsub // a - b f64 ARM: AAPCS
- dev unclear __aeabi_dsub // a - b f64 ARM: AAPCS
- dev unclear __mulsf3 // a * b, TODO: missing tests
- dev unclear __muldf3 // a * b, TODO: missing tests
- dev unclear __multf3 // a * b
- dev unclear __mulxf3 // a * b
- dev unclear __divsf3 // a / b, TODO: review tests
- dev unclear __divdf3 // a / b, TODO: review tests
- dev unclear __divtf3 // a / b
- dev unclear __divxf3 // a / b
- dev unclear __negsf2 // -a symbol-level compatibility: libgcc uses this for the rl78
- dev unclear __negdf2 // -a unnecessary: can be lowered directly to a xor
- dev unclear __negtf2 // -a, TODO: missing tests
- dev unclear __negxf2 // -a, TODO: missing tests
#### Floating point raised to integer power
- dev unclear __powisf2 // a ^ b, TODO
- dev unclear __powidf2 //
- dev unclear __powitf2 //
- dev unclear __powixf2 //
- dev unclear __mulsc3 // (a+ib) * (c+id)
- dev unclear __muldc3 //
- dev unclear __multc3 //
- dev unclear __mulxc3 //
- dev unclear __divsc3 // (a+ib) * / (c+id)
- dev unclear __divdc3 //
- dev unclear __divtc3 //
- dev unclear __divxc3 //
## Decimal float library routines
BID means Binary Integer Decimal encoding, DPD means Densely Packed Decimal encoding.
BID should be only chosen for binary data, DPD for decimal data (ASCII, Unicode etc).
If possible, use BCD instead of DPD to represent numbers not accurately representable
in binary like the number 0.2.
All routines are TODO.
#### Decimal float Conversion
- __dpd_extendsddd2 // dec32->dec64
- __bid_extendsddd2 // dec32->dec64
- __dpd_extendsdtd2 // dec32->dec128
- __bid_extendsdtd2 // dec32->dec128
- __dpd_extendddtd2 // dec64->dec128
- __bid_extendddtd2 // dec64->dec128
- __dpd_truncddsd2 // dec64->dec32
- __bid_truncddsd2 // dec64->dec32
- __dpd_trunctdsd2 // dec128->dec32
- __bid_trunctdsd2 // dec128->dec32
- __dpd_trunctddd2 // dec128->dec64
- __bid_trunctddd2 // dec128->dec64
- __dpd_extendsfdd // float->dec64
- __bid_extendsfdd // float->dec64
- __dpd_extendsftd // float->dec128
- __bid_extendsftd // float->dec128
- __dpd_extenddftd // double->dec128
- __bid_extenddftd // double->dec128
- __dpd_extendxftd // long double->dec128
- __bid_extendxftd // long double->dec128
- __dpd_truncdfsd // double->dec32
- __bid_truncdfsd // double->dec32
- __dpd_truncxfsd // long double->dec32
- __bid_truncxfsd // long double->dec32
- __dpd_trunctfsd // long double->dec32
- __bid_trunctfsd // long double->dec32
- __dpd_truncxfdd // long double->dec64
- __bid_truncxfdd // long double->dec64
- __dpd_trunctfdd // long double->dec64
- __bid_trunctfdd // long double->dec64
- __dpd_truncddsf // dec64->float
- __bid_truncddsf // dec64->float
- __dpd_trunctdsf // dec128->float
- __bid_trunctdsf // dec128->float
- __dpd_extendsddf // dec32->double
- __bid_extendsddf // dec32->double
- __dpd_trunctddf // dec128->double
- __bid_trunctddf // dec128->double
- __dpd_extendsdxf // dec32->long double
- __bid_extendsdxf // dec32->long double
- __dpd_extendddxf // dec64->long double
- __bid_extendddxf // dec64->long double
- __dpd_trunctdxf // dec128->long double
- __bid_trunctdxf // dec128->long double
- __dpd_extendsdtf // dec32->long double
- __bid_extendsdtf // dec32->long double
- __dpd_extendddtf // dec64->long double
- __bid_extendddtf // dec64->long double
Same size conversion:
- __dpd_extendsfsd // float->dec32
- __bid_extendsfsd // float->dec32
- __dpd_extenddfdd // double->dec64
- __bid_extenddfdd // double->dec64
- __dpd_extendtftd //long double->dec128
- __bid_extendtftd //long double->dec128
- __dpd_truncsdsf // dec32->float
- __bid_truncsdsf // dec32->float
- __dpd_truncdddf // dec64->float
- __bid_truncdddf // dec64->float
- __dpd_trunctdtf // dec128->long double
- __bid_trunctdtf // dec128->long double
- __dpd_fixsdsi // dec32->int
- __bid_fixsdsi // dec32->int
- __dpd_fixddsi // dec64->int
- __bid_fixddsi // dec64->int
- __dpd_fixtdsi // dec128->int
- __bid_fixtdsi // dec128->int
- __dpd_fixsddi // dec32->long
- __bid_fixsddi // dec32->long
- __dpd_fixdddi // dec64->long
- __bid_fixdddi // dec64->long
- __dpd_fixtddi // dec128->long
- __bid_fixtddi // dec128->long
- __dpd_fixunssdsi // dec32->unsigned int, All negative values become zero.
- __bid_fixunssdsi // dec32->unsigned int
- __dpd_fixunsddsi // dec64->unsigned int
- __bid_fixunsddsi // dec64->unsigned int
- __dpd_fixunstdsi // dec128->unsigned int
- __bid_fixunstdsi // dec128->unsigned int
- __dpd_fixunssddi // dec32->unsigned long, All negative values become zero.
- __bid_fixunssddi // dec32->unsigned long
- __dpd_fixunsdddi // dec64->unsigned long
- __bid_fixunsdddi // dec64->unsigned long
- __dpd_fixunstddi // dec128->unsigned long
- __bid_fixunstddi // dec128->unsigned long
- __dpd_floatsisd // int->dec32
- __bid_floatsisd // int->dec32
- __dpd_floatsidd // int->dec64
- __bid_floatsidd // int->dec64
- __dpd_floatsitd // int->dec128
- __bid_floatsitd // int->dec128
- __dpd_floatdisd // long->dec32
- __bid_floatdisd // long->dec32
- __dpd_floatdidd // long->dec64
- __bid_floatdidd // long->dec64
- __dpd_floatditd // long->dec128
- __bid_floatditd // long->dec128
- __dpd_floatunssisd // unsigned int->dec32
- __bid_floatunssisd // unsigned int->dec32
- __dpd_floatunssidd // unsigned int->dec64
- __bid_floatunssidd // unsigned int->dec64
- __dpd_floatunssitd // unsigned int->dec128
- __bid_floatunssitd // unsigned int->dec128
- __dpd_floatunsdisd // unsigned long->dec32
- __bid_floatunsdisd // unsigned long->dec32
- __dpd_floatunsdidd // unsigned long->dec64
- __bid_floatunsdidd // unsigned long->dec64
- __dpd_floatunsditd // unsigned long->dec128
- __bid_floatunsditd // unsigned long->dec128
#### Decimal float Comparison
All decimal float comparison routines return c_int.
- __dpd_unordsd2 // a,b: dec32, a +-NaN or a +-NaN -> 1(nonzero), else -> 0
- __bid_unordsd2 // a,b: dec32
- __dpd_unorddd2 // a,b: dec64
- __bid_unorddd2 // a,b: dec64
- __dpd_unordtd2 // a,b: dec128
- __bid_unordtd2 // a,b: dec128
- __dpd_eqsd2 // a,b: dec32, a!=+-NaN and b!=+-Nan and a==b -> 0, else -> 1(nonzero)
- __bid_eqsd2 // a,b: dec32
- __dpd_eqdd2 // a,b: dec64
- __bid_eqdd2 // a,b: dec64
- __dpd_eqtd2 // a,b: dec128
- __bid_eqtd2 // a,b: dec128
- __dpd_nesd2 // a,b: dec32, a==+-NaN or b==+-NaN or a!=b -> 1(nonzero), else -> 0
- __bid_nesd2 // a,b: dec32
- __dpd_nedd2 // a,b: dec64
- __bid_nedd2 // a,b: dec64
- __dpd_netd2 // a,b: dec128
- __bid_netd2 // a,b: dec128
- __dpd_gesd2 // a,b: dec32, a!=+-NaN and b!=+-NaN and a>=b -> >=0, else -> <0
- __bid_gesd2 // a,b: dec32
- __dpd_gedd2 // a,b: dec64
- __bid_gedd2 // a,b: dec64
- __dpd_getd2 // a,b: dec128
- __bid_getd2 // a,b: dec128
- __dpd_ltsd2 // a,b: dec32, a!=+-NaN and b!=+-NaN and a<b -> <0, else -> >=0
- __bid_ltsd2 // a,b: dec32
- __dpd_ltdd2 // a,b: dec64
- __bid_ltdd2 // a,b: dec64
- __dpd_lttd2 // a,b: dec128
- __bid_lttd2 // a,b: dec128
- __dpd_lesd2 // a,b: dec32, a!=+-NaN and b!=+-NaN and a<=b -> <=0, else -> >=0
- __bid_lesd2 // a,b: dec32
- __dpd_ledd2 // a,b: dec64
- __bid_ledd2 // a,b: dec64
- __dpd_letd2 // a,b: dec128
- __bid_letd2 // a,b: dec128
- __dpd_gtsd2 // a,b: dec32, a!=+-NaN and b!=+-NaN and a>b -> >0, else -> <=0
- __bid_gtsd2 // a,b: dec32
- __dpd_gtdd2 // a,b: dec64
- __bid_gtdd2 // a,b: dec64
- __dpd_gttd2 // a,b: dec128
- __bid_gttd2 // a,b: dec128
#### Decimal float Arithmetic
These numbers include options with routines for +-0 and +-Nan.
- __dpd_addsd3 // a,b: dec32 -> dec32, a + b
- __bid_addsd3 // a,b: dec32 -> dec32
- __dpd_adddd3 // a,b: dec64 -> dec64
- __bid_adddd3 // a,b: dec64 -> dec64
- __dpd_addtd3 // a,b: dec128-> dec128
- __bid_addtd3 // a,b: dec128-> dec128
- __dpd_subsd3 // a,b: dec32, a - b
- __bid_subsd3 // a,b: dec32 -> dec32
- __dpd_subdd3 // a,b: dec64 ..
- __bid_subdd3 // a,b: dec64
- __dpd_subtd3 // a,b: dec128
- __bid_subtd3 // a,b: dec128
- __dpd_mulsd3 // a,b: dec32, a * b
- __bid_mulsd3 // a,b: dec32 -> dec32
- __dpd_muldd3 // a,b: dec64 ..
- __bid_muldd3 // a,b: dec64
- __dpd_multd3 // a,b: dec128
- __bid_multd3 // a,b: dec128
- __dpd_divsd3 // a,b: dec32, a / b
- __bid_divsd3 // a,b: dec32 -> dec32
- __dpd_divdd3 // a,b: dec64 ..
- __bid_divdd3 // a,b: dec64
- __dpd_divtd3 // a,b: dec128
- __bid_divtd3 // a,b: dec128
- __dpd_negsd2 // a,b: dec32, -a
- __bid_negsd2 // a,b: dec32 -> dec32
- __dpd_negdd2 // a,b: dec64 ..
- __bid_negdd2 // a,b: dec64
- __dpd_negtd2 // a,b: dec128
- __bid_negtd2 // a,b: dec128
## Fixed-point fractional library routines
TODO
Too unclear for work items:
- Miscellaneous routines => unclear, if supported (cache control and stack functions)
- Zig-specific language runtime features, for example "Arbitrary length integer library routines"

26
lib/compiler_rt/absv.zig Normal file
View File

@@ -0,0 +1,26 @@
/// absv - absolute oVerflow
/// * @panic if value can not be represented
pub inline fn absv(comptime ST: type, a: ST) ST {
const UT = switch (ST) {
i32 => u32,
i64 => u64,
i128 => u128,
else => unreachable,
};
// taken from Bit Twiddling Hacks
// compute the integer absolute value (abs) without branching
var x: ST = a;
const N: UT = @bitSizeOf(ST);
const sign: ST = a >> N - 1;
x +%= sign;
x ^= sign;
if (x < 0)
@panic("compiler_rt absv: overflow");
return x;
}
test {
_ = @import("absvsi2_test.zig");
_ = @import("absvdi2_test.zig");
_ = @import("absvti2_test.zig");
}

View File

@@ -0,0 +1,12 @@
const common = @import("./common.zig");
const absv = @import("./absv.zig").absv;
pub const panic = common.panic;
comptime {
@export(__absvdi2, .{ .name = "__absvdi2", .linkage = common.linkage });
}
pub fn __absvdi2(a: i64) callconv(.C) i64 {
return absv(i64, a);
}

View File

@@ -0,0 +1,31 @@
const testing = @import("std").testing;
const __absvdi2 = @import("absvdi2.zig").__absvdi2;
fn test__absvdi2(a: i64, expected: i64) !void {
var result = __absvdi2(a);
try testing.expectEqual(expected, result);
}
test "absvdi2" {
// -2^63 <= i64 <= 2^63-1
// 2^63 = 9223372036854775808
// 2^63-1 = 9223372036854775807
// TODO write panic handler for testing panics
//try test__absvdi2(-9223372036854775808, -5); // tested with return -5; and panic
try test__absvdi2(-9223372036854775807, 9223372036854775807);
try test__absvdi2(-9223372036854775806, 9223372036854775806);
try test__absvdi2(-9223372036854775805, 9223372036854775805);
try test__absvdi2(-9223372036854775804, 9223372036854775804);
try test__absvdi2(-42, 42);
try test__absvdi2(-7, 7);
try test__absvdi2(-1, 1);
try test__absvdi2(0, 0);
try test__absvdi2(1, 1);
try test__absvdi2(7, 7);
try test__absvdi2(42, 42);
try test__absvdi2(9223372036854775804, 9223372036854775804);
try test__absvdi2(9223372036854775805, 9223372036854775805);
try test__absvdi2(9223372036854775806, 9223372036854775806);
try test__absvdi2(9223372036854775807, 9223372036854775807);
}

View File

@@ -0,0 +1,12 @@
const common = @import("./common.zig");
const absv = @import("./absv.zig").absv;
pub const panic = common.panic;
comptime {
@export(__absvsi2, .{ .name = "__absvsi2", .linkage = common.linkage });
}
pub fn __absvsi2(a: i32) callconv(.C) i32 {
return absv(i32, a);
}

View File

@@ -0,0 +1,31 @@
const testing = @import("std").testing;
const __absvsi2 = @import("absvsi2.zig").__absvsi2;
fn test__absvsi2(a: i32, expected: i32) !void {
var result = __absvsi2(a);
try testing.expectEqual(expected, result);
}
test "absvsi2" {
// -2^31 <= i32 <= 2^31-1
// 2^31 = 2147483648
// 2^31-1 = 2147483647
// TODO write panic handler for testing panics
//try test__absvsi2(-2147483648, -5); // tested with return -5; and panic
try test__absvsi2(-2147483647, 2147483647);
try test__absvsi2(-2147483646, 2147483646);
try test__absvsi2(-2147483645, 2147483645);
try test__absvsi2(-2147483644, 2147483644);
try test__absvsi2(-42, 42);
try test__absvsi2(-7, 7);
try test__absvsi2(-1, 1);
try test__absvsi2(0, 0);
try test__absvsi2(1, 1);
try test__absvsi2(7, 7);
try test__absvsi2(42, 42);
try test__absvsi2(2147483644, 2147483644);
try test__absvsi2(2147483645, 2147483645);
try test__absvsi2(2147483646, 2147483646);
try test__absvsi2(2147483647, 2147483647);
}

View File

@@ -0,0 +1,12 @@
const common = @import("./common.zig");
const absv = @import("./absv.zig").absv;
pub const panic = common.panic;
comptime {
@export(__absvti2, .{ .name = "__absvti2", .linkage = common.linkage });
}
pub fn __absvti2(a: i128) callconv(.C) i128 {
return absv(i128, a);
}

View File

@@ -0,0 +1,31 @@
const testing = @import("std").testing;
const __absvti2 = @import("absvti2.zig").__absvti2;
fn test__absvti2(a: i128, expected: i128) !void {
var result = __absvti2(a);
try testing.expectEqual(expected, result);
}
test "absvti2" {
// -2^127 <= i128 <= 2^127-1
// 2^127 = 170141183460469231731687303715884105728
// 2^127+1 = 170141183460469231731687303715884105727
// TODO write panic handler for testing panics
//try test__absvti2(-170141183460469231731687303715884105728, -5); // tested with return -5; and panic
try test__absvti2(-170141183460469231731687303715884105727, 170141183460469231731687303715884105727);
try test__absvti2(-170141183460469231731687303715884105726, 170141183460469231731687303715884105726);
try test__absvti2(-170141183460469231731687303715884105725, 170141183460469231731687303715884105725);
try test__absvti2(-170141183460469231731687303715884105724, 170141183460469231731687303715884105724);
try test__absvti2(-42, 42);
try test__absvti2(-7, 7);
try test__absvti2(-1, 1);
try test__absvti2(0, 0);
try test__absvti2(1, 1);
try test__absvti2(7, 7);
try test__absvti2(42, 42);
try test__absvti2(170141183460469231731687303715884105724, 170141183460469231731687303715884105724);
try test__absvti2(170141183460469231731687303715884105725, 170141183460469231731687303715884105725);
try test__absvti2(170141183460469231731687303715884105726, 170141183460469231731687303715884105726);
try test__absvti2(170141183460469231731687303715884105727, 170141183460469231731687303715884105727);
}

View File

@@ -0,0 +1,20 @@
const common = @import("./common.zig");
const addf3 = @import("./addf3.zig").addf3;
pub const panic = common.panic;
comptime {
if (common.want_aeabi) {
@export(__aeabi_dadd, .{ .name = "__aeabi_dadd", .linkage = common.linkage });
} else {
@export(__adddf3, .{ .name = "__adddf3", .linkage = common.linkage });
}
}
fn __adddf3(a: f64, b: f64) callconv(.C) f64 {
return addf3(f64, a, b);
}
fn __aeabi_dadd(a: f64, b: f64) callconv(.AAPCS) f64 {
return addf3(f64, a, b);
}

172
lib/compiler_rt/addf3.zig Normal file
View File

@@ -0,0 +1,172 @@
const std = @import("std");
const math = std.math;
const common = @import("./common.zig");
const normalize = common.normalize;
/// Ported from:
///
/// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/lib/builtins/fp_add_impl.inc
pub inline fn addf3(comptime T: type, a: T, b: T) T {
const bits = @typeInfo(T).Float.bits;
const Z = std.meta.Int(.unsigned, bits);
const S = std.meta.Int(.unsigned, bits - @clz(@as(Z, bits) - 1));
const typeWidth = bits;
const significandBits = math.floatMantissaBits(T);
const fractionalBits = math.floatFractionalBits(T);
const exponentBits = math.floatExponentBits(T);
const signBit = (@as(Z, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const integerBit = (@as(Z, 1) << fractionalBits);
const quietBit = integerBit >> 1;
const significandMask = (@as(Z, 1) << significandBits) - 1;
const absMask = signBit - 1;
const qnanRep = @bitCast(Z, math.nan(T)) | quietBit;
var aRep = @bitCast(Z, a);
var bRep = @bitCast(Z, b);
const aAbs = aRep & absMask;
const bAbs = bRep & absMask;
const infRep = @bitCast(Z, math.inf(T));
// Detect if a or b is zero, infinity, or NaN.
if (aAbs -% @as(Z, 1) >= infRep - @as(Z, 1) or
bAbs -% @as(Z, 1) >= infRep - @as(Z, 1))
{
// NaN + anything = qNaN
if (aAbs > infRep) return @bitCast(T, @bitCast(Z, a) | quietBit);
// anything + NaN = qNaN
if (bAbs > infRep) return @bitCast(T, @bitCast(Z, b) | quietBit);
if (aAbs == infRep) {
// +/-infinity + -/+infinity = qNaN
if ((@bitCast(Z, a) ^ @bitCast(Z, b)) == signBit) {
return @bitCast(T, qnanRep);
}
// +/-infinity + anything remaining = +/- infinity
else {
return a;
}
}
// anything remaining + +/-infinity = +/-infinity
if (bAbs == infRep) return b;
// zero + anything = anything
if (aAbs == 0) {
// but we need to get the sign right for zero + zero
if (bAbs == 0) {
return @bitCast(T, @bitCast(Z, a) & @bitCast(Z, b));
} else {
return b;
}
}
// anything + zero = anything
if (bAbs == 0) return a;
}
// Swap a and b if necessary so that a has the larger absolute value.
if (bAbs > aAbs) {
const temp = aRep;
aRep = bRep;
bRep = temp;
}
// Extract the exponent and significand from the (possibly swapped) a and b.
var aExponent = @intCast(i32, (aRep >> significandBits) & maxExponent);
var bExponent = @intCast(i32, (bRep >> significandBits) & maxExponent);
var aSignificand = aRep & significandMask;
var bSignificand = bRep & significandMask;
// Normalize any denormals, and adjust the exponent accordingly.
if (aExponent == 0) aExponent = normalize(T, &aSignificand);
if (bExponent == 0) bExponent = normalize(T, &bSignificand);
// The sign of the result is the sign of the larger operand, a. If they
// have opposite signs, we are performing a subtraction; otherwise addition.
const resultSign = aRep & signBit;
const subtraction = (aRep ^ bRep) & signBit != 0;
// Shift the significands to give us round, guard and sticky, and or in the
// implicit significand bit. (If we fell through from the denormal path it
// was already set by normalize( ), but setting it twice won't hurt
// anything.)
aSignificand = (aSignificand | integerBit) << 3;
bSignificand = (bSignificand | integerBit) << 3;
// Shift the significand of b by the difference in exponents, with a sticky
// bottom bit to get rounding correct.
const @"align" = @intCast(u32, aExponent - bExponent);
if (@"align" != 0) {
if (@"align" < typeWidth) {
const sticky = if (bSignificand << @intCast(S, typeWidth - @"align") != 0) @as(Z, 1) else 0;
bSignificand = (bSignificand >> @truncate(S, @"align")) | sticky;
} else {
bSignificand = 1; // sticky; b is known to be non-zero.
}
}
if (subtraction) {
aSignificand -= bSignificand;
// If a == -b, return +zero.
if (aSignificand == 0) return @bitCast(T, @as(Z, 0));
// If partial cancellation occured, we need to left-shift the result
// and adjust the exponent:
if (aSignificand < integerBit << 3) {
const shift = @intCast(i32, @clz(aSignificand)) - @intCast(i32, @clz(integerBit << 3));
aSignificand <<= @intCast(S, shift);
aExponent -= shift;
}
} else { // addition
aSignificand += bSignificand;
// If the addition carried up, we need to right-shift the result and
// adjust the exponent:
if (aSignificand & (integerBit << 4) != 0) {
const sticky = aSignificand & 1;
aSignificand = aSignificand >> 1 | sticky;
aExponent += 1;
}
}
// If we have overflowed the type, return +/- infinity:
if (aExponent >= maxExponent) return @bitCast(T, infRep | resultSign);
if (aExponent <= 0) {
// Result is denormal; the exponent and round/sticky bits are zero.
// All we need to do is shift the significand and apply the correct sign.
aSignificand >>= @intCast(S, 4 - aExponent);
return @bitCast(T, resultSign | aSignificand);
}
// Low three bits are round, guard, and sticky.
const roundGuardSticky = aSignificand & 0x7;
// Shift the significand into place, and mask off the integer bit, if it's implicit.
var result = (aSignificand >> 3) & significandMask;
// Insert the exponent and sign.
result |= @intCast(Z, aExponent) << significandBits;
result |= resultSign;
// Final rounding. The result may overflow to infinity, but that is the
// correct result in that case.
if (roundGuardSticky > 0x4) result += 1;
if (roundGuardSticky == 0x4) result += result & 1;
// Restore any explicit integer bit, if it was rounded off
if (significandBits != fractionalBits) {
if ((result >> significandBits) != 0) result |= integerBit;
}
return @bitCast(T, result);
}
test {
_ = @import("addf3_test.zig");
}

View File

@@ -0,0 +1,156 @@
// Ported from:
//
// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/test/builtins/Unit/addtf3_test.c
// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/test/builtins/Unit/subtf3_test.c
const std = @import("std");
const math = std.math;
const qnan128 = @bitCast(f128, @as(u128, 0x7fff800000000000) << 64);
const __addtf3 = @import("addtf3.zig").__addtf3;
const __addxf3 = @import("addxf3.zig").__addxf3;
const __subtf3 = @import("subtf3.zig").__subtf3;
fn test__addtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) !void {
const x = __addtf3(a, b);
const rep = @bitCast(u128, x);
const hi = @intCast(u64, rep >> 64);
const lo = @truncate(u64, rep);
if (hi == expected_hi and lo == expected_lo) {
return;
}
// test other possible NaN representation (signal NaN)
else if (expected_hi == 0x7fff800000000000 and expected_lo == 0x0) {
if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and
((hi & 0xffffffffffff) > 0 or lo > 0))
{
return;
}
}
return error.TestFailed;
}
test "addtf3" {
try test__addtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
// NaN + any = NaN
try test__addtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
// inf + inf = inf
try test__addtf3(math.inf(f128), math.inf(f128), 0x7fff000000000000, 0x0);
// inf + any = inf
try test__addtf3(math.inf(f128), 0x1.2335653452436234723489432abcdefp+5, 0x7fff000000000000, 0x0);
// any + any
try test__addtf3(0x1.23456734245345543849abcdefp+5, 0x1.edcba52449872455634654321fp-1, 0x40042afc95c8b579, 0x61e58dd6c51eb77c);
try test__addtf3(0x1.edcba52449872455634654321fp-1, 0x1.23456734245345543849abcdefp+5, 0x40042afc95c8b579, 0x61e58dd6c51eb77c);
}
fn test__subtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) !void {
const x = __subtf3(a, b);
const rep = @bitCast(u128, x);
const hi = @intCast(u64, rep >> 64);
const lo = @truncate(u64, rep);
if (hi == expected_hi and lo == expected_lo) {
return;
}
// test other possible NaN representation (signal NaN)
else if (expected_hi == 0x7fff800000000000 and expected_lo == 0x0) {
if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and
((hi & 0xffffffffffff) > 0 or lo > 0))
{
return;
}
}
return error.TestFailed;
}
test "subtf3" {
// qNaN - any = qNaN
try test__subtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
// NaN + any = NaN
try test__subtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
// inf - any = inf
try test__subtf3(math.inf(f128), 0x1.23456789abcdefp+5, 0x7fff000000000000, 0x0);
// any + any
try test__subtf3(0x1.234567829a3bcdef5678ade36734p+5, 0x1.ee9d7c52354a6936ab8d7654321fp-1, 0x40041b8af1915166, 0xa44a7bca780a166c);
try test__subtf3(0x1.ee9d7c52354a6936ab8d7654321fp-1, 0x1.234567829a3bcdef5678ade36734p+5, 0xc0041b8af1915166, 0xa44a7bca780a166c);
}
const qnan80 = @bitCast(f80, @bitCast(u80, math.nan(f80)) | (1 << (math.floatFractionalBits(f80) - 1)));
fn test__addxf3(a: f80, b: f80, expected: u80) !void {
const x = __addxf3(a, b);
const rep = @bitCast(u80, x);
if (rep == expected)
return;
if (math.isNan(@bitCast(f80, expected)) and math.isNan(x))
return; // We don't currently test NaN payload propagation
return error.TestFailed;
}
test "addxf3" {
// NaN + any = NaN
try test__addxf3(qnan80, 0x1.23456789abcdefp+5, @bitCast(u80, qnan80));
try test__addxf3(@bitCast(f80, @as(u80, 0x7fff_8000_8000_3000_0000)), 0x1.23456789abcdefp+5, @bitCast(u80, qnan80));
// any + NaN = NaN
try test__addxf3(0x1.23456789abcdefp+5, qnan80, @bitCast(u80, qnan80));
try test__addxf3(0x1.23456789abcdefp+5, @bitCast(f80, @as(u80, 0x7fff_8000_8000_3000_0000)), @bitCast(u80, qnan80));
// NaN + inf = NaN
try test__addxf3(qnan80, math.inf(f80), @bitCast(u80, qnan80));
// inf + NaN = NaN
try test__addxf3(math.inf(f80), qnan80, @bitCast(u80, qnan80));
// inf + inf = inf
try test__addxf3(math.inf(f80), math.inf(f80), @bitCast(u80, math.inf(f80)));
// inf + -inf = NaN
try test__addxf3(math.inf(f80), -math.inf(f80), @bitCast(u80, qnan80));
// -inf + inf = NaN
try test__addxf3(-math.inf(f80), math.inf(f80), @bitCast(u80, qnan80));
// inf + any = inf
try test__addxf3(math.inf(f80), 0x1.2335653452436234723489432abcdefp+5, @bitCast(u80, math.inf(f80)));
// any + inf = inf
try test__addxf3(0x1.2335653452436234723489432abcdefp+5, math.inf(f80), @bitCast(u80, math.inf(f80)));
// any + any
try test__addxf3(0x1.23456789abcdp+5, 0x1.dcba987654321p+5, 0x4005_BFFFFFFFFFFFC400);
try test__addxf3(0x1.23456734245345543849abcdefp+5, 0x1.edcba52449872455634654321fp-1, 0x4004_957E_4AE4_5ABC_B0F3);
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.0p-63, 0x3FFF_FFFFFFFFFFFFFFFF); // exact
try test__addxf3(0x1.ffff_ffff_ffff_fffep+0, 0x0.0p0, 0x3FFF_FFFFFFFFFFFFFFFF); // exact
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.4p-63, 0x3FFF_FFFFFFFFFFFFFFFF); // round down
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.8p-63, 0x4000_8000000000000000); // round up to even
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.cp-63, 0x4000_8000000000000000); // round up
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x2.0p-63, 0x4000_8000000000000000); // exact
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x2.1p-63, 0x4000_8000000000000000); // round down
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x3.0p-63, 0x4000_8000000000000000); // round down to even
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x3.1p-63, 0x4000_8000000000000001); // round up
try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x4.0p-63, 0x4000_8000000000000001); // exact
try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.0p-63, 0x3FFF_8800000000000000); // exact
try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.7p-63, 0x3FFF_8800000000000000); // round down
try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.8p-63, 0x3FFF_8800000000000000); // round down to even
try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.9p-63, 0x3FFF_8800000000000001); // round up
try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x2.0p-63, 0x3FFF_8800000000000001); // exact
try test__addxf3(0x0.ffff_ffff_ffff_fffcp-16382, 0x0.0000_0000_0000_0002p-16382, 0x0000_7FFFFFFFFFFFFFFF); // exact
try test__addxf3(0x0.1fff_ffff_ffff_fffcp-16382, 0x0.0000_0000_0000_0002p-16382, 0x0000_0FFFFFFFFFFFFFFF); // exact
}

View File

@@ -0,0 +1,12 @@
const common = @import("./common.zig");
const addf3 = @import("./addf3.zig").addf3;
pub const panic = common.panic;
comptime {
@export(__addhf3, .{ .name = "__addhf3", .linkage = common.linkage });
}
fn __addhf3(a: f16, b: f16) callconv(.C) f16 {
return addf3(f16, a, b);
}

48
lib/compiler_rt/addo.zig Normal file
View File

@@ -0,0 +1,48 @@
const std = @import("std");
const builtin = @import("builtin");
const is_test = builtin.is_test;
const linkage: std.builtin.GlobalLinkage = if (builtin.is_test) .Internal else .Weak;
pub const panic = @import("common.zig").panic;
comptime {
@export(__addosi4, .{ .name = "__addosi4", .linkage = linkage });
@export(__addodi4, .{ .name = "__addodi4", .linkage = linkage });
@export(__addoti4, .{ .name = "__addoti4", .linkage = linkage });
}
// addo - add overflow
// * return a+%b.
// * return if a+b overflows => 1 else => 0
// - addoXi4_generic as default
inline fn addoXi4_generic(comptime ST: type, a: ST, b: ST, overflow: *c_int) ST {
@setRuntimeSafety(builtin.is_test);
overflow.* = 0;
var sum: ST = a +% b;
// Hackers Delight: section Overflow Detection, subsection Signed Add/Subtract
// Let sum = a +% b == a + b + carry == wraparound addition.
// Overflow in a+b+carry occurs, iff a and b have opposite signs
// and the sign of a+b+carry is the same as a (or equivalently b).
// Slower routine: res = ~(a ^ b) & ((sum ^ a)
// Faster routine: res = (sum ^ a) & (sum ^ b)
// Overflow occured, iff (res < 0)
if (((sum ^ a) & (sum ^ b)) < 0)
overflow.* = 1;
return sum;
}
pub fn __addosi4(a: i32, b: i32, overflow: *c_int) callconv(.C) i32 {
return addoXi4_generic(i32, a, b, overflow);
}
pub fn __addodi4(a: i64, b: i64, overflow: *c_int) callconv(.C) i64 {
return addoXi4_generic(i64, a, b, overflow);
}
pub fn __addoti4(a: i128, b: i128, overflow: *c_int) callconv(.C) i128 {
return addoXi4_generic(i128, a, b, overflow);
}
test {
_ = @import("addosi4_test.zig");
_ = @import("addodi4_test.zig");
_ = @import("addoti4_test.zig");
}

View File

@@ -0,0 +1,77 @@
const addv = @import("addo.zig");
const std = @import("std");
const testing = std.testing;
const math = std.math;
fn test__addodi4(a: i64, b: i64) !void {
var result_ov: c_int = undefined;
var expected_ov: c_int = undefined;
var result = addv.__addodi4(a, b, &result_ov);
var expected: i64 = simple_addodi4(a, b, &expected_ov);
try testing.expectEqual(expected, result);
try testing.expectEqual(expected_ov, result_ov);
}
fn simple_addodi4(a: i64, b: i64, overflow: *c_int) i64 {
overflow.* = 0;
const min: i64 = math.minInt(i64);
const max: i64 = math.maxInt(i64);
if (((a > 0) and (b > max - a)) or
((a < 0) and (b < min - a)))
overflow.* = 1;
return a +% b;
}
test "addodi4" {
const min: i64 = math.minInt(i64);
const max: i64 = math.maxInt(i64);
var i: i64 = 1;
while (i < max) : (i *|= 2) {
try test__addodi4(i, i);
try test__addodi4(-i, -i);
try test__addodi4(i, -i);
try test__addodi4(-i, i);
}
// edge cases
// 0 + 0 = 0
// MIN + MIN overflow
// MAX + MAX overflow
// 0 + MIN MIN
// 0 + MAX MAX
// MIN + 0 MIN
// MAX + 0 MAX
// MIN + MAX -1
// MAX + MIN -1
try test__addodi4(0, 0);
try test__addodi4(min, min);
try test__addodi4(max, max);
try test__addodi4(0, min);
try test__addodi4(0, max);
try test__addodi4(min, 0);
try test__addodi4(max, 0);
try test__addodi4(min, max);
try test__addodi4(max, min);
// derived edge cases
// MIN+1 + MIN overflow
// MAX-1 + MAX overflow
// 1 + MIN = MIN+1
// -1 + MIN overflow
// -1 + MAX = MAX-1
// +1 + MAX overflow
// MIN + 1 = MIN+1
// MIN + -1 overflow
// MAX + 1 overflow
// MAX + -1 = MAX-1
try test__addodi4(min + 1, min);
try test__addodi4(max - 1, max);
try test__addodi4(1, min);
try test__addodi4(-1, min);
try test__addodi4(-1, max);
try test__addodi4(1, max);
try test__addodi4(min, 1);
try test__addodi4(min, -1);
try test__addodi4(max, -1);
try test__addodi4(max, 1);
}

View File

@@ -0,0 +1,78 @@
const addv = @import("addo.zig");
const testing = @import("std").testing;
fn test__addosi4(a: i32, b: i32) !void {
var result_ov: c_int = undefined;
var expected_ov: c_int = undefined;
var result = addv.__addosi4(a, b, &result_ov);
var expected: i32 = simple_addosi4(a, b, &expected_ov);
try testing.expectEqual(expected, result);
try testing.expectEqual(expected_ov, result_ov);
}
fn simple_addosi4(a: i32, b: i32, overflow: *c_int) i32 {
overflow.* = 0;
const min: i32 = -2147483648;
const max: i32 = 2147483647;
if (((a > 0) and (b > max - a)) or
((a < 0) and (b < min - a)))
overflow.* = 1;
return a +% b;
}
test "addosi4" {
// -2^31 <= i32 <= 2^31-1
// 2^31 = 2147483648
// 2^31-1 = 2147483647
const min: i32 = -2147483648;
const max: i32 = 2147483647;
var i: i32 = 1;
while (i < max) : (i *|= 2) {
try test__addosi4(i, i);
try test__addosi4(-i, -i);
try test__addosi4(i, -i);
try test__addosi4(-i, i);
}
// edge cases
// 0 + 0 = 0
// MIN + MIN overflow
// MAX + MAX overflow
// 0 + MIN MIN
// 0 + MAX MAX
// MIN + 0 MIN
// MAX + 0 MAX
// MIN + MAX -1
// MAX + MIN -1
try test__addosi4(0, 0);
try test__addosi4(min, min);
try test__addosi4(max, max);
try test__addosi4(0, min);
try test__addosi4(0, max);
try test__addosi4(min, 0);
try test__addosi4(max, 0);
try test__addosi4(min, max);
try test__addosi4(max, min);
// derived edge cases
// MIN+1 + MIN overflow
// MAX-1 + MAX overflow
// 1 + MIN = MIN+1
// -1 + MIN overflow
// -1 + MAX = MAX-1
// +1 + MAX overflow
// MIN + 1 = MIN+1
// MIN + -1 overflow
// MAX + 1 overflow
// MAX + -1 = MAX-1
try test__addosi4(min + 1, min);
try test__addosi4(max - 1, max);
try test__addosi4(1, min);
try test__addosi4(-1, min);
try test__addosi4(-1, max);
try test__addosi4(1, max);
try test__addosi4(min, 1);
try test__addosi4(min, -1);
try test__addosi4(max, -1);
try test__addosi4(max, 1);
}

View File

@@ -0,0 +1,77 @@
const addv = @import("addo.zig");
const std = @import("std");
const testing = std.testing;
const math = std.math;
fn test__addoti4(a: i128, b: i128) !void {
var result_ov: c_int = undefined;
var expected_ov: c_int = undefined;
var result = addv.__addoti4(a, b, &result_ov);
var expected: i128 = simple_addoti4(a, b, &expected_ov);
try testing.expectEqual(expected, result);
try testing.expectEqual(expected_ov, result_ov);
}
fn simple_addoti4(a: i128, b: i128, overflow: *c_int) i128 {
overflow.* = 0;
const min: i128 = math.minInt(i128);
const max: i128 = math.maxInt(i128);
if (((a > 0) and (b > max - a)) or
((a < 0) and (b < min - a)))
overflow.* = 1;
return a +% b;
}
test "addoti4" {
const min: i128 = math.minInt(i128);
const max: i128 = math.maxInt(i128);
var i: i128 = 1;
while (i < max) : (i *|= 2) {
try test__addoti4(i, i);
try test__addoti4(-i, -i);
try test__addoti4(i, -i);
try test__addoti4(-i, i);
}
// edge cases
// 0 + 0 = 0
// MIN + MIN overflow
// MAX + MAX overflow
// 0 + MIN MIN
// 0 + MAX MAX
// MIN + 0 MIN
// MAX + 0 MAX
// MIN + MAX -1
// MAX + MIN -1
try test__addoti4(0, 0);
try test__addoti4(min, min);
try test__addoti4(max, max);
try test__addoti4(0, min);
try test__addoti4(0, max);
try test__addoti4(min, 0);
try test__addoti4(max, 0);
try test__addoti4(min, max);
try test__addoti4(max, min);
// derived edge cases
// MIN+1 + MIN overflow
// MAX-1 + MAX overflow
// 1 + MIN = MIN+1
// -1 + MIN overflow
// -1 + MAX = MAX-1
// +1 + MAX overflow
// MIN + 1 = MIN+1
// MIN + -1 overflow
// MAX + 1 overflow
// MAX + -1 = MAX-1
try test__addoti4(min + 1, min);
try test__addoti4(max - 1, max);
try test__addoti4(1, min);
try test__addoti4(-1, min);
try test__addoti4(-1, max);
try test__addoti4(1, max);
try test__addoti4(min, 1);
try test__addoti4(min, -1);
try test__addoti4(max, -1);
try test__addoti4(max, 1);
}

View File

@@ -0,0 +1,20 @@
const common = @import("./common.zig");
const addf3 = @import("./addf3.zig").addf3;
pub const panic = common.panic;
comptime {
if (common.want_aeabi) {
@export(__aeabi_fadd, .{ .name = "__aeabi_fadd", .linkage = common.linkage });
} else {
@export(__addsf3, .{ .name = "__addsf3", .linkage = common.linkage });
}
}
fn __addsf3(a: f32, b: f32) callconv(.C) f32 {
return addf3(f32, a, b);
}
fn __aeabi_fadd(a: f32, b: f32) callconv(.AAPCS) f32 {
return addf3(f32, a, b);
}

View File

@@ -0,0 +1,21 @@
const common = @import("./common.zig");
const addf3 = @import("./addf3.zig").addf3;
pub const panic = common.panic;
comptime {
if (common.want_ppc_abi) {
@export(__addtf3, .{ .name = "__addkf3", .linkage = common.linkage });
} else if (common.want_sparc_abi) {
@export(_Qp_add, .{ .name = "_Qp_add", .linkage = common.linkage });
}
@export(__addtf3, .{ .name = "__addtf3", .linkage = common.linkage });
}
pub fn __addtf3(a: f128, b: f128) callconv(.C) f128 {
return addf3(f128, a, b);
}
fn _Qp_add(c: *f128, a: *f128, b: *f128) callconv(.C) void {
c.* = addf3(f128, a.*, b.*);
}

View File

@@ -0,0 +1,12 @@
const common = @import("./common.zig");
const addf3 = @import("./addf3.zig").addf3;
pub const panic = common.panic;
comptime {
@export(__addxf3, .{ .name = "__addxf3", .linkage = common.linkage });
}
pub fn __addxf3(a: f80, b: f80) callconv(.C) f80 {
return addf3(f80, a, b);
}

188
lib/compiler_rt/arm.zig Normal file
View File

@@ -0,0 +1,188 @@
// ARM specific builtins
const std = @import("std");
const builtin = @import("builtin");
const arch = builtin.cpu.arch;
const common = @import("common.zig");
pub const panic = common.panic;
comptime {
if (!builtin.is_test) {
if (arch.isARM() or arch.isThumb()) {
@export(__aeabi_unwind_cpp_pr0, .{ .name = "__aeabi_unwind_cpp_pr0", .linkage = common.linkage });
@export(__aeabi_unwind_cpp_pr1, .{ .name = "__aeabi_unwind_cpp_pr1", .linkage = common.linkage });
@export(__aeabi_unwind_cpp_pr2, .{ .name = "__aeabi_unwind_cpp_pr2", .linkage = common.linkage });
@export(__aeabi_ldivmod, .{ .name = "__aeabi_ldivmod", .linkage = common.linkage });
@export(__aeabi_uldivmod, .{ .name = "__aeabi_uldivmod", .linkage = common.linkage });
@export(__aeabi_idivmod, .{ .name = "__aeabi_idivmod", .linkage = common.linkage });
@export(__aeabi_uidivmod, .{ .name = "__aeabi_uidivmod", .linkage = common.linkage });
@export(__aeabi_memcpy, .{ .name = "__aeabi_memcpy", .linkage = common.linkage });
@export(__aeabi_memcpy4, .{ .name = "__aeabi_memcpy4", .linkage = common.linkage });
@export(__aeabi_memcpy8, .{ .name = "__aeabi_memcpy8", .linkage = common.linkage });
@export(__aeabi_memmove, .{ .name = "__aeabi_memmove", .linkage = common.linkage });
@export(__aeabi_memmove4, .{ .name = "__aeabi_memmove4", .linkage = common.linkage });
@export(__aeabi_memmove8, .{ .name = "__aeabi_memmove8", .linkage = common.linkage });
@export(__aeabi_memset, .{ .name = "__aeabi_memset", .linkage = common.linkage });
@export(__aeabi_memset4, .{ .name = "__aeabi_memset4", .linkage = common.linkage });
@export(__aeabi_memset8, .{ .name = "__aeabi_memset8", .linkage = common.linkage });
@export(__aeabi_memclr, .{ .name = "__aeabi_memclr", .linkage = common.linkage });
@export(__aeabi_memclr4, .{ .name = "__aeabi_memclr4", .linkage = common.linkage });
@export(__aeabi_memclr8, .{ .name = "__aeabi_memclr8", .linkage = common.linkage });
if (builtin.os.tag == .linux) {
@export(__aeabi_read_tp, .{ .name = "__aeabi_read_tp", .linkage = common.linkage });
}
}
}
}
const __divmodsi4 = @import("int.zig").__divmodsi4;
const __udivmodsi4 = @import("int.zig").__udivmodsi4;
const __divmoddi4 = @import("int.zig").__divmoddi4;
const __udivmoddi4 = @import("int.zig").__udivmoddi4;
extern fn memset(dest: ?[*]u8, c: u8, n: usize) ?[*]u8;
extern fn memcpy(noalias dest: ?[*]u8, noalias src: ?[*]const u8, n: usize) ?[*]u8;
extern fn memmove(dest: ?[*]u8, src: ?[*]const u8, n: usize) ?[*]u8;
pub fn __aeabi_memcpy(dest: [*]u8, src: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memcpy(dest, src, n);
}
pub fn __aeabi_memcpy4(dest: [*]u8, src: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memcpy(dest, src, n);
}
pub fn __aeabi_memcpy8(dest: [*]u8, src: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memcpy(dest, src, n);
}
pub fn __aeabi_memmove(dest: [*]u8, src: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memmove(dest, src, n);
}
pub fn __aeabi_memmove4(dest: [*]u8, src: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memmove(dest, src, n);
}
pub fn __aeabi_memmove8(dest: [*]u8, src: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memmove(dest, src, n);
}
pub fn __aeabi_memset(dest: [*]u8, n: usize, c: u8) callconv(.AAPCS) void {
@setRuntimeSafety(false);
// This is dentical to the standard `memset` definition but with the last
// two arguments swapped
_ = memset(dest, c, n);
}
pub fn __aeabi_memset4(dest: [*]u8, n: usize, c: u8) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memset(dest, c, n);
}
pub fn __aeabi_memset8(dest: [*]u8, n: usize, c: u8) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memset(dest, c, n);
}
pub fn __aeabi_memclr(dest: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memset(dest, 0, n);
}
pub fn __aeabi_memclr4(dest: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memset(dest, 0, n);
}
pub fn __aeabi_memclr8(dest: [*]u8, n: usize) callconv(.AAPCS) void {
@setRuntimeSafety(false);
_ = memset(dest, 0, n);
}
// Dummy functions to avoid errors during the linking phase
pub fn __aeabi_unwind_cpp_pr0() callconv(.AAPCS) void {}
pub fn __aeabi_unwind_cpp_pr1() callconv(.AAPCS) void {}
pub fn __aeabi_unwind_cpp_pr2() callconv(.AAPCS) void {}
// This function can only clobber r0 according to the ABI
pub fn __aeabi_read_tp() callconv(.Naked) void {
@setRuntimeSafety(false);
asm volatile (
\\ mrc p15, 0, r0, c13, c0, 3
\\ bx lr
);
unreachable;
}
// The following functions are wrapped in an asm block to ensure the required
// calling convention is always respected
pub fn __aeabi_uidivmod() callconv(.Naked) void {
@setRuntimeSafety(false);
// Divide r0 by r1; the quotient goes in r0, the remainder in r1
asm volatile (
\\ push {lr}
\\ sub sp, #4
\\ mov r2, sp
\\ bl __udivmodsi4
\\ ldr r1, [sp]
\\ add sp, #4
\\ pop {pc}
::: "memory");
unreachable;
}
pub fn __aeabi_uldivmod() callconv(.Naked) void {
@setRuntimeSafety(false);
// Divide r1:r0 by r3:r2; the quotient goes in r1:r0, the remainder in r3:r2
asm volatile (
\\ push {r4, lr}
\\ sub sp, #16
\\ add r4, sp, #8
\\ str r4, [sp]
\\ bl __udivmoddi4
\\ ldr r2, [sp, #8]
\\ ldr r3, [sp, #12]
\\ add sp, #16
\\ pop {r4, pc}
::: "memory");
unreachable;
}
pub fn __aeabi_idivmod() callconv(.Naked) void {
@setRuntimeSafety(false);
// Divide r0 by r1; the quotient goes in r0, the remainder in r1
asm volatile (
\\ push {lr}
\\ sub sp, #4
\\ mov r2, sp
\\ bl __divmodsi4
\\ ldr r1, [sp]
\\ add sp, #4
\\ pop {pc}
::: "memory");
unreachable;
}
pub fn __aeabi_ldivmod() callconv(.Naked) void {
@setRuntimeSafety(false);
// Divide r1:r0 by r3:r2; the quotient goes in r1:r0, the remainder in r3:r2
asm volatile (
\\ push {r4, lr}
\\ sub sp, #16
\\ add r4, sp, #8
\\ str r4, [sp]
\\ bl __divmoddi4
\\ ldr r2, [sp, #8]
\\ ldr r3, [sp, #12]
\\ add sp, #16
\\ pop {r4, pc}
::: "memory");
unreachable;
}

512
lib/compiler_rt/atomics.zig Normal file
View File

@@ -0,0 +1,512 @@
const std = @import("std");
const builtin = @import("builtin");
const cpu = builtin.cpu;
const arch = cpu.arch;
const linkage: std.builtin.GlobalLinkage = if (builtin.is_test) .Internal else .Weak;
pub const panic = @import("common.zig").panic;
// This parameter is true iff the target architecture supports the bare minimum
// to implement the atomic load/store intrinsics.
// Some architectures support atomic load/stores but no CAS, but we ignore this
// detail to keep the export logic clean and because we need some kind of CAS to
// implement the spinlocks.
const supports_atomic_ops = switch (arch) {
.msp430, .avr, .bpfel, .bpfeb => false,
.arm, .armeb, .thumb, .thumbeb =>
// The ARM v6m ISA has no ldrex/strex and so it's impossible to do CAS
// operations (unless we're targeting Linux, the kernel provides a way to
// perform CAS operations).
// XXX: The Linux code path is not implemented yet.
!std.Target.arm.featureSetHas(builtin.cpu.features, .has_v6m),
else => true,
};
// The size (in bytes) of the biggest object that the architecture can
// load/store atomically.
// Objects bigger than this threshold require the use of a lock.
const largest_atomic_size = switch (arch) {
// On SPARC systems that lacks CAS and/or swap instructions, the only
// available atomic operation is a test-and-set (`ldstub`), so we force
// every atomic memory access to go through the lock.
.sparc, .sparcel => if (cpu.features.featureSetHas(.hasleoncasa)) @sizeOf(usize) else 0,
// XXX: On x86/x86_64 we could check the presence of cmpxchg8b/cmpxchg16b
// and set this parameter accordingly.
else => @sizeOf(usize),
};
// The size (in bytes) of the smallest atomic object that the architecture can
// perform fetch/exchange atomically. Note, this does not encompass load and store.
// Objects smaller than this threshold are implemented in terms of compare-exchange
// of a larger value.
const smallest_atomic_fetch_exch_size = switch (arch) {
// On AMDGPU, there are no instructions for atomic operations other than load and store
// (as of LLVM 15), and so these need to be implemented in terms of atomic CAS.
.amdgcn => @sizeOf(u32),
else => @sizeOf(u8),
};
const cache_line_size = 64;
const SpinlockTable = struct {
// Allocate ~4096 bytes of memory for the spinlock table
const max_spinlocks = 64;
const Spinlock = struct {
// SPARC ldstub instruction will write a 255 into the memory location.
// We'll use that as a sign that the lock is currently held.
// See also: Section B.7 in SPARCv8 spec & A.29 in SPARCv9 spec.
const sparc_lock: type = enum(u8) { Unlocked = 0, Locked = 255 };
const other_lock: type = enum(usize) { Unlocked = 0, Locked };
// Prevent false sharing by providing enough padding between two
// consecutive spinlock elements
v: if (arch.isSPARC()) sparc_lock else other_lock align(cache_line_size) = .Unlocked,
fn acquire(self: *@This()) void {
while (true) {
const flag = if (comptime arch.isSPARC()) flag: {
break :flag asm volatile ("ldstub [%[addr]], %[flag]"
: [flag] "=r" (-> @TypeOf(self.v)),
: [addr] "r" (&self.v),
: "memory"
);
} else flag: {
break :flag @atomicRmw(@TypeOf(self.v), &self.v, .Xchg, .Locked, .Acquire);
};
switch (flag) {
.Unlocked => break,
.Locked => {},
}
}
}
fn release(self: *@This()) void {
if (comptime arch.isSPARC()) {
_ = asm volatile ("clrb [%[addr]]"
:
: [addr] "r" (&self.v),
: "memory"
);
} else {
@atomicStore(@TypeOf(self.v), &self.v, .Unlocked, .Release);
}
}
};
list: [max_spinlocks]Spinlock = [_]Spinlock{.{}} ** max_spinlocks,
// The spinlock table behaves as a really simple hash table, mapping
// addresses to spinlocks. The mapping is not unique but that's only a
// performance problem as the lock will be contended by more than a pair of
// threads.
fn get(self: *@This(), address: usize) *Spinlock {
var sl = &self.list[(address >> 3) % max_spinlocks];
sl.acquire();
return sl;
}
};
var spinlocks: SpinlockTable = SpinlockTable{};
// The following builtins do not respect the specified memory model and instead
// uses seq_cst, the strongest one, for simplicity sake.
// Generic version of GCC atomic builtin functions.
// Those work on any object no matter the pointer alignment nor its size.
fn __atomic_load(size: u32, src: [*]u8, dest: [*]u8, model: i32) callconv(.C) void {
_ = model;
var sl = spinlocks.get(@ptrToInt(src));
defer sl.release();
@memcpy(dest, src, size);
}
fn __atomic_store(size: u32, dest: [*]u8, src: [*]u8, model: i32) callconv(.C) void {
_ = model;
var sl = spinlocks.get(@ptrToInt(dest));
defer sl.release();
@memcpy(dest, src, size);
}
fn __atomic_exchange(size: u32, ptr: [*]u8, val: [*]u8, old: [*]u8, model: i32) callconv(.C) void {
_ = model;
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
@memcpy(old, ptr, size);
@memcpy(ptr, val, size);
}
fn __atomic_compare_exchange(
size: u32,
ptr: [*]u8,
expected: [*]u8,
desired: [*]u8,
success: i32,
failure: i32,
) callconv(.C) i32 {
_ = success;
_ = failure;
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
for (ptr[0..size]) |b, i| {
if (expected[i] != b) break;
} else {
// The two objects, ptr and expected, are equal
@memcpy(ptr, desired, size);
return 1;
}
@memcpy(expected, ptr, size);
return 0;
}
// Specialized versions of the GCC atomic builtin functions.
// LLVM emits those iff the object size is known and the pointers are correctly
// aligned.
inline fn atomic_load_N(comptime T: type, src: *T, model: i32) T {
_ = model;
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(src));
defer sl.release();
return src.*;
} else {
return @atomicLoad(T, src, .SeqCst);
}
}
fn __atomic_load_1(src: *u8, model: i32) callconv(.C) u8 {
return atomic_load_N(u8, src, model);
}
fn __atomic_load_2(src: *u16, model: i32) callconv(.C) u16 {
return atomic_load_N(u16, src, model);
}
fn __atomic_load_4(src: *u32, model: i32) callconv(.C) u32 {
return atomic_load_N(u32, src, model);
}
fn __atomic_load_8(src: *u64, model: i32) callconv(.C) u64 {
return atomic_load_N(u64, src, model);
}
inline fn atomic_store_N(comptime T: type, dst: *T, value: T, model: i32) void {
_ = model;
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(dst));
defer sl.release();
dst.* = value;
} else {
@atomicStore(T, dst, value, .SeqCst);
}
}
fn __atomic_store_1(dst: *u8, value: u8, model: i32) callconv(.C) void {
return atomic_store_N(u8, dst, value, model);
}
fn __atomic_store_2(dst: *u16, value: u16, model: i32) callconv(.C) void {
return atomic_store_N(u16, dst, value, model);
}
fn __atomic_store_4(dst: *u32, value: u32, model: i32) callconv(.C) void {
return atomic_store_N(u32, dst, value, model);
}
fn __atomic_store_8(dst: *u64, value: u64, model: i32) callconv(.C) void {
return atomic_store_N(u64, dst, value, model);
}
fn wideUpdate(comptime T: type, ptr: *T, val: T, update: anytype) T {
const WideAtomic = std.meta.Int(.unsigned, smallest_atomic_fetch_exch_size * 8);
const addr = @ptrToInt(ptr);
const wide_addr = addr & ~(@as(T, smallest_atomic_fetch_exch_size) - 1);
const wide_ptr = @alignCast(smallest_atomic_fetch_exch_size, @intToPtr(*WideAtomic, wide_addr));
const inner_offset = addr & (@as(T, smallest_atomic_fetch_exch_size) - 1);
const inner_shift = @intCast(std.math.Log2Int(T), inner_offset * 8);
const mask = @as(WideAtomic, std.math.maxInt(T)) << inner_shift;
var wide_old = @atomicLoad(WideAtomic, wide_ptr, .SeqCst);
while (true) {
const old = @truncate(T, (wide_old & mask) >> inner_shift);
const new = update(val, old);
const wide_new = wide_old & ~mask | (@as(WideAtomic, new) << inner_shift);
if (@cmpxchgWeak(WideAtomic, wide_ptr, wide_old, wide_new, .SeqCst, .SeqCst)) |new_wide_old| {
wide_old = new_wide_old;
} else {
return old;
}
}
}
inline fn atomic_exchange_N(comptime T: type, ptr: *T, val: T, model: i32) T {
_ = model;
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
const value = ptr.*;
ptr.* = val;
return value;
} else if (@sizeOf(T) < smallest_atomic_fetch_exch_size) {
// Machine does not support this type, but it does support a larger type.
const Updater = struct {
fn update(new: T, old: T) T {
_ = old;
return new;
}
};
return wideUpdate(T, ptr, val, Updater.update);
} else {
return @atomicRmw(T, ptr, .Xchg, val, .SeqCst);
}
}
fn __atomic_exchange_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 {
return atomic_exchange_N(u8, ptr, val, model);
}
fn __atomic_exchange_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 {
return atomic_exchange_N(u16, ptr, val, model);
}
fn __atomic_exchange_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 {
return atomic_exchange_N(u32, ptr, val, model);
}
fn __atomic_exchange_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 {
return atomic_exchange_N(u64, ptr, val, model);
}
inline fn atomic_compare_exchange_N(
comptime T: type,
ptr: *T,
expected: *T,
desired: T,
success: i32,
failure: i32,
) i32 {
_ = success;
_ = failure;
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
const value = ptr.*;
if (value == expected.*) {
ptr.* = desired;
return 1;
}
expected.* = value;
return 0;
} else {
if (@cmpxchgStrong(T, ptr, expected.*, desired, .SeqCst, .SeqCst)) |old_value| {
expected.* = old_value;
return 0;
}
return 1;
}
}
fn __atomic_compare_exchange_1(ptr: *u8, expected: *u8, desired: u8, success: i32, failure: i32) callconv(.C) i32 {
return atomic_compare_exchange_N(u8, ptr, expected, desired, success, failure);
}
fn __atomic_compare_exchange_2(ptr: *u16, expected: *u16, desired: u16, success: i32, failure: i32) callconv(.C) i32 {
return atomic_compare_exchange_N(u16, ptr, expected, desired, success, failure);
}
fn __atomic_compare_exchange_4(ptr: *u32, expected: *u32, desired: u32, success: i32, failure: i32) callconv(.C) i32 {
return atomic_compare_exchange_N(u32, ptr, expected, desired, success, failure);
}
fn __atomic_compare_exchange_8(ptr: *u64, expected: *u64, desired: u64, success: i32, failure: i32) callconv(.C) i32 {
return atomic_compare_exchange_N(u64, ptr, expected, desired, success, failure);
}
inline fn fetch_op_N(comptime T: type, comptime op: std.builtin.AtomicRmwOp, ptr: *T, val: T, model: i32) T {
_ = model;
const Updater = struct {
fn update(new: T, old: T) T {
return switch (op) {
.Add => old +% new,
.Sub => old -% new,
.And => old & new,
.Nand => ~(old & new),
.Or => old | new,
.Xor => old ^ new,
else => @compileError("unsupported atomic op"),
};
}
};
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
const value = ptr.*;
ptr.* = Updater.update(val, value);
return value;
} else if (@sizeOf(T) < smallest_atomic_fetch_exch_size) {
// Machine does not support this type, but it does support a larger type.
return wideUpdate(T, ptr, val, Updater.update);
}
return @atomicRmw(T, ptr, op, val, .SeqCst);
}
fn __atomic_fetch_add_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 {
return fetch_op_N(u8, .Add, ptr, val, model);
}
fn __atomic_fetch_add_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 {
return fetch_op_N(u16, .Add, ptr, val, model);
}
fn __atomic_fetch_add_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 {
return fetch_op_N(u32, .Add, ptr, val, model);
}
fn __atomic_fetch_add_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 {
return fetch_op_N(u64, .Add, ptr, val, model);
}
fn __atomic_fetch_sub_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 {
return fetch_op_N(u8, .Sub, ptr, val, model);
}
fn __atomic_fetch_sub_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 {
return fetch_op_N(u16, .Sub, ptr, val, model);
}
fn __atomic_fetch_sub_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 {
return fetch_op_N(u32, .Sub, ptr, val, model);
}
fn __atomic_fetch_sub_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 {
return fetch_op_N(u64, .Sub, ptr, val, model);
}
fn __atomic_fetch_and_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 {
return fetch_op_N(u8, .And, ptr, val, model);
}
fn __atomic_fetch_and_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 {
return fetch_op_N(u16, .And, ptr, val, model);
}
fn __atomic_fetch_and_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 {
return fetch_op_N(u32, .And, ptr, val, model);
}
fn __atomic_fetch_and_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 {
return fetch_op_N(u64, .And, ptr, val, model);
}
fn __atomic_fetch_or_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 {
return fetch_op_N(u8, .Or, ptr, val, model);
}
fn __atomic_fetch_or_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 {
return fetch_op_N(u16, .Or, ptr, val, model);
}
fn __atomic_fetch_or_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 {
return fetch_op_N(u32, .Or, ptr, val, model);
}
fn __atomic_fetch_or_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 {
return fetch_op_N(u64, .Or, ptr, val, model);
}
fn __atomic_fetch_xor_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 {
return fetch_op_N(u8, .Xor, ptr, val, model);
}
fn __atomic_fetch_xor_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 {
return fetch_op_N(u16, .Xor, ptr, val, model);
}
fn __atomic_fetch_xor_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 {
return fetch_op_N(u32, .Xor, ptr, val, model);
}
fn __atomic_fetch_xor_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 {
return fetch_op_N(u64, .Xor, ptr, val, model);
}
fn __atomic_fetch_nand_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 {
return fetch_op_N(u8, .Nand, ptr, val, model);
}
fn __atomic_fetch_nand_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 {
return fetch_op_N(u16, .Nand, ptr, val, model);
}
fn __atomic_fetch_nand_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 {
return fetch_op_N(u32, .Nand, ptr, val, model);
}
fn __atomic_fetch_nand_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 {
return fetch_op_N(u64, .Nand, ptr, val, model);
}
comptime {
if (supports_atomic_ops) {
@export(__atomic_load, .{ .name = "__atomic_load", .linkage = linkage });
@export(__atomic_store, .{ .name = "__atomic_store", .linkage = linkage });
@export(__atomic_exchange, .{ .name = "__atomic_exchange", .linkage = linkage });
@export(__atomic_compare_exchange, .{ .name = "__atomic_compare_exchange", .linkage = linkage });
@export(__atomic_fetch_add_1, .{ .name = "__atomic_fetch_add_1", .linkage = linkage });
@export(__atomic_fetch_add_2, .{ .name = "__atomic_fetch_add_2", .linkage = linkage });
@export(__atomic_fetch_add_4, .{ .name = "__atomic_fetch_add_4", .linkage = linkage });
@export(__atomic_fetch_add_8, .{ .name = "__atomic_fetch_add_8", .linkage = linkage });
@export(__atomic_fetch_sub_1, .{ .name = "__atomic_fetch_sub_1", .linkage = linkage });
@export(__atomic_fetch_sub_2, .{ .name = "__atomic_fetch_sub_2", .linkage = linkage });
@export(__atomic_fetch_sub_4, .{ .name = "__atomic_fetch_sub_4", .linkage = linkage });
@export(__atomic_fetch_sub_8, .{ .name = "__atomic_fetch_sub_8", .linkage = linkage });
@export(__atomic_fetch_and_1, .{ .name = "__atomic_fetch_and_1", .linkage = linkage });
@export(__atomic_fetch_and_2, .{ .name = "__atomic_fetch_and_2", .linkage = linkage });
@export(__atomic_fetch_and_4, .{ .name = "__atomic_fetch_and_4", .linkage = linkage });
@export(__atomic_fetch_and_8, .{ .name = "__atomic_fetch_and_8", .linkage = linkage });
@export(__atomic_fetch_or_1, .{ .name = "__atomic_fetch_or_1", .linkage = linkage });
@export(__atomic_fetch_or_2, .{ .name = "__atomic_fetch_or_2", .linkage = linkage });
@export(__atomic_fetch_or_4, .{ .name = "__atomic_fetch_or_4", .linkage = linkage });
@export(__atomic_fetch_or_8, .{ .name = "__atomic_fetch_or_8", .linkage = linkage });
@export(__atomic_fetch_xor_1, .{ .name = "__atomic_fetch_xor_1", .linkage = linkage });
@export(__atomic_fetch_xor_2, .{ .name = "__atomic_fetch_xor_2", .linkage = linkage });
@export(__atomic_fetch_xor_4, .{ .name = "__atomic_fetch_xor_4", .linkage = linkage });
@export(__atomic_fetch_xor_8, .{ .name = "__atomic_fetch_xor_8", .linkage = linkage });
@export(__atomic_fetch_nand_1, .{ .name = "__atomic_fetch_nand_1", .linkage = linkage });
@export(__atomic_fetch_nand_2, .{ .name = "__atomic_fetch_nand_2", .linkage = linkage });
@export(__atomic_fetch_nand_4, .{ .name = "__atomic_fetch_nand_4", .linkage = linkage });
@export(__atomic_fetch_nand_8, .{ .name = "__atomic_fetch_nand_8", .linkage = linkage });
@export(__atomic_load_1, .{ .name = "__atomic_load_1", .linkage = linkage });
@export(__atomic_load_2, .{ .name = "__atomic_load_2", .linkage = linkage });
@export(__atomic_load_4, .{ .name = "__atomic_load_4", .linkage = linkage });
@export(__atomic_load_8, .{ .name = "__atomic_load_8", .linkage = linkage });
@export(__atomic_store_1, .{ .name = "__atomic_store_1", .linkage = linkage });
@export(__atomic_store_2, .{ .name = "__atomic_store_2", .linkage = linkage });
@export(__atomic_store_4, .{ .name = "__atomic_store_4", .linkage = linkage });
@export(__atomic_store_8, .{ .name = "__atomic_store_8", .linkage = linkage });
@export(__atomic_exchange_1, .{ .name = "__atomic_exchange_1", .linkage = linkage });
@export(__atomic_exchange_2, .{ .name = "__atomic_exchange_2", .linkage = linkage });
@export(__atomic_exchange_4, .{ .name = "__atomic_exchange_4", .linkage = linkage });
@export(__atomic_exchange_8, .{ .name = "__atomic_exchange_8", .linkage = linkage });
@export(__atomic_compare_exchange_1, .{ .name = "__atomic_compare_exchange_1", .linkage = linkage });
@export(__atomic_compare_exchange_2, .{ .name = "__atomic_compare_exchange_2", .linkage = linkage });
@export(__atomic_compare_exchange_4, .{ .name = "__atomic_compare_exchange_4", .linkage = linkage });
@export(__atomic_compare_exchange_8, .{ .name = "__atomic_compare_exchange_8", .linkage = linkage });
}
}

View File

@@ -1,7 +1,20 @@
const std = @import("std");
const builtin = @import("builtin"); const builtin = @import("builtin");
const arch = builtin.cpu.arch;
const abi = builtin.abi;
const common = @import("common.zig");
pub const panic = common.panic;
comptime {
if (arch == .i386 and abi == .msvc) {
// Don't let LLVM apply the stdcall name mangling on those MSVC builtins
@export(_alldiv, .{ .name = "\x01__alldiv", .linkage = common.linkage });
@export(_aulldiv, .{ .name = "\x01__aulldiv", .linkage = common.linkage });
}
}
pub fn _alldiv(a: i64, b: i64) callconv(.Stdcall) i64 { pub fn _alldiv(a: i64, b: i64) callconv(.Stdcall) i64 {
@setRuntimeSafety(builtin.is_test);
const s_a = a >> (64 - 1); const s_a = a >> (64 - 1);
const s_b = b >> (64 - 1); const s_b = b >> (64 - 1);

View File

@@ -1,7 +1,20 @@
const std = @import("std");
const builtin = @import("builtin"); const builtin = @import("builtin");
const arch = builtin.cpu.arch;
const abi = builtin.abi;
const common = @import("common.zig");
pub const panic = common.panic;
comptime {
if (arch == .i386 and abi == .msvc) {
// Don't let LLVM apply the stdcall name mangling on those MSVC builtins
@export(_allrem, .{ .name = "\x01__allrem", .linkage = common.linkage });
@export(_aullrem, .{ .name = "\x01__aullrem", .linkage = common.linkage });
}
}
pub fn _allrem(a: i64, b: i64) callconv(.Stdcall) i64 { pub fn _allrem(a: i64, b: i64) callconv(.Stdcall) i64 {
@setRuntimeSafety(builtin.is_test);
const s_a = a >> (64 - 1); const s_a = a >> (64 - 1);
const s_b = b >> (64 - 1); const s_b = b >> (64 - 1);

30
lib/compiler_rt/bcmp.zig Normal file
View File

@@ -0,0 +1,30 @@
const std = @import("std");
const common = @import("./common.zig");
comptime {
@export(bcmp, .{ .name = "bcmp", .linkage = common.linkage });
}
pub fn bcmp(vl: [*]allowzero const u8, vr: [*]allowzero const u8, n: usize) callconv(.C) c_int {
@setRuntimeSafety(false);
var index: usize = 0;
while (index != n) : (index += 1) {
if (vl[index] != vr[index]) {
return 1;
}
}
return 0;
}
test "bcmp" {
const base_arr = &[_]u8{ 1, 1, 1 };
const arr1 = &[_]u8{ 1, 1, 1 };
const arr2 = &[_]u8{ 1, 0, 1 };
const arr3 = &[_]u8{ 1, 2, 1 };
try std.testing.expect(bcmp(base_arr[0..], arr1[0..], base_arr.len) == 0);
try std.testing.expect(bcmp(base_arr[0..], arr2[0..], base_arr.len) != 0);
try std.testing.expect(bcmp(base_arr[0..], arr3[0..], base_arr.len) != 0);
}

85
lib/compiler_rt/bswap.zig Normal file
View File

@@ -0,0 +1,85 @@
const std = @import("std");
const builtin = @import("builtin");
const common = @import("common.zig");
pub const panic = common.panic;
comptime {
@export(__bswapsi2, .{ .name = "__bswapsi2", .linkage = common.linkage });
@export(__bswapdi2, .{ .name = "__bswapdi2", .linkage = common.linkage });
@export(__bswapti2, .{ .name = "__bswapti2", .linkage = common.linkage });
}
// bswap - byteswap
// - bswapXi2 for unoptimized big and little endian
// ie for u32
// DE AD BE EF <- little|big endian
// FE BE AD DE <- big|little endian
// ff 00 00 00 >> 3*8 (leftmost byte)
// 00 ff 00 00 >> 1*8 (2nd left byte)
// 00 00 ff 00 << 1*8 (2n right byte)
// 00 00 00 ff << 3*8 (rightmost byte)
inline fn bswapXi2(comptime T: type, a: T) T {
switch (@bitSizeOf(T)) {
32 => {
// zig fmt: off
return (((a & 0xff000000) >> 24)
| ((a & 0x00ff0000) >> 8 )
| ((a & 0x0000ff00) << 8 )
| ((a & 0x000000ff) << 24));
// zig fmt: on
},
64 => {
// zig fmt: off
return (((a & 0xff00000000000000) >> 56)
| ((a & 0x00ff000000000000) >> 40 )
| ((a & 0x0000ff0000000000) >> 24 )
| ((a & 0x000000ff00000000) >> 8 )
| ((a & 0x00000000ff000000) << 8 )
| ((a & 0x0000000000ff0000) << 24 )
| ((a & 0x000000000000ff00) << 40 )
| ((a & 0x00000000000000ff) << 56));
// zig fmt: on
},
128 => {
// zig fmt: off
return (((a & 0xff000000000000000000000000000000) >> 120)
| ((a & 0x00ff0000000000000000000000000000) >> 104)
| ((a & 0x0000ff00000000000000000000000000) >> 88 )
| ((a & 0x000000ff000000000000000000000000) >> 72 )
| ((a & 0x00000000ff0000000000000000000000) >> 56 )
| ((a & 0x0000000000ff00000000000000000000) >> 40 )
| ((a & 0x000000000000ff000000000000000000) >> 24 )
| ((a & 0x00000000000000ff0000000000000000) >> 8 )
| ((a & 0x0000000000000000ff00000000000000) << 8 )
| ((a & 0x000000000000000000ff000000000000) << 24 )
| ((a & 0x00000000000000000000ff0000000000) << 40 )
| ((a & 0x0000000000000000000000ff00000000) << 56 )
| ((a & 0x000000000000000000000000ff000000) << 72 )
| ((a & 0x00000000000000000000000000ff0000) << 88 )
| ((a & 0x0000000000000000000000000000ff00) << 104)
| ((a & 0x000000000000000000000000000000ff) << 120));
// zig fmt: on
},
else => unreachable,
}
}
pub fn __bswapsi2(a: u32) callconv(.C) u32 {
return bswapXi2(u32, a);
}
pub fn __bswapdi2(a: u64) callconv(.C) u64 {
return bswapXi2(u64, a);
}
pub fn __bswapti2(a: u128) callconv(.C) u128 {
return bswapXi2(u128, a);
}
test {
_ = @import("bswapsi2_test.zig");
_ = @import("bswapdi2_test.zig");
_ = @import("bswapti2_test.zig");
}

182
lib/compiler_rt/ceil.zig Normal file
View File

@@ -0,0 +1,182 @@
//! Ported from musl, which is MIT licensed.
//! https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
//!
//! https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
//! https://git.musl-libc.org/cgit/musl/tree/src/math/ceil.c
const std = @import("std");
const builtin = @import("builtin");
const arch = builtin.cpu.arch;
const math = std.math;
const expect = std.testing.expect;
const common = @import("common.zig");
pub const panic = common.panic;
comptime {
@export(__ceilh, .{ .name = "__ceilh", .linkage = common.linkage });
@export(ceilf, .{ .name = "ceilf", .linkage = common.linkage });
@export(ceil, .{ .name = "ceil", .linkage = common.linkage });
@export(__ceilx, .{ .name = "__ceilx", .linkage = common.linkage });
if (common.want_ppc_abi) {
@export(ceilq, .{ .name = "ceilf128", .linkage = common.linkage });
}
@export(ceilq, .{ .name = "ceilq", .linkage = common.linkage });
@export(ceill, .{ .name = "ceill", .linkage = common.linkage });
}
pub fn __ceilh(x: f16) callconv(.C) f16 {
// TODO: more efficient implementation
return @floatCast(f16, ceilf(x));
}
pub fn ceilf(x: f32) callconv(.C) f32 {
var u = @bitCast(u32, x);
var e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F;
var m: u32 = undefined;
// TODO: Shouldn't need this explicit check.
if (x == 0.0) {
return x;
}
if (e >= 23) {
return x;
} else if (e >= 0) {
m = @as(u32, 0x007FFFFF) >> @intCast(u5, e);
if (u & m == 0) {
return x;
}
math.doNotOptimizeAway(x + 0x1.0p120);
if (u >> 31 == 0) {
u += m;
}
u &= ~m;
return @bitCast(f32, u);
} else {
math.doNotOptimizeAway(x + 0x1.0p120);
if (u >> 31 != 0) {
return -0.0;
} else {
return 1.0;
}
}
}
pub fn ceil(x: f64) callconv(.C) f64 {
const f64_toint = 1.0 / math.floatEps(f64);
const u = @bitCast(u64, x);
const e = (u >> 52) & 0x7FF;
var y: f64 = undefined;
if (e >= 0x3FF + 52 or x == 0) {
return x;
}
if (u >> 63 != 0) {
y = x - f64_toint + f64_toint - x;
} else {
y = x + f64_toint - f64_toint - x;
}
if (e <= 0x3FF - 1) {
math.doNotOptimizeAway(y);
if (u >> 63 != 0) {
return -0.0;
} else {
return 1.0;
}
} else if (y < 0) {
return x + y + 1;
} else {
return x + y;
}
}
pub fn __ceilx(x: f80) callconv(.C) f80 {
// TODO: more efficient implementation
return @floatCast(f80, ceilq(x));
}
pub fn ceilq(x: f128) callconv(.C) f128 {
const f128_toint = 1.0 / math.floatEps(f128);
const u = @bitCast(u128, x);
const e = (u >> 112) & 0x7FFF;
var y: f128 = undefined;
if (e >= 0x3FFF + 112 or x == 0) return x;
if (u >> 127 != 0) {
y = x - f128_toint + f128_toint - x;
} else {
y = x + f128_toint - f128_toint - x;
}
if (e <= 0x3FFF - 1) {
math.doNotOptimizeAway(y);
if (u >> 127 != 0) {
return -0.0;
} else {
return 1.0;
}
} else if (y < 0) {
return x + y + 1;
} else {
return x + y;
}
}
pub fn ceill(x: c_longdouble) callconv(.C) c_longdouble {
switch (@typeInfo(c_longdouble).Float.bits) {
16 => return __ceilh(x),
32 => return ceilf(x),
64 => return ceil(x),
80 => return __ceilx(x),
128 => return ceilq(x),
else => @compileError("unreachable"),
}
}
test "ceil32" {
try expect(ceilf(1.3) == 2.0);
try expect(ceilf(-1.3) == -1.0);
try expect(ceilf(0.2) == 1.0);
}
test "ceil64" {
try expect(ceil(1.3) == 2.0);
try expect(ceil(-1.3) == -1.0);
try expect(ceil(0.2) == 1.0);
}
test "ceil128" {
try expect(ceilq(1.3) == 2.0);
try expect(ceilq(-1.3) == -1.0);
try expect(ceilq(0.2) == 1.0);
}
test "ceil32.special" {
try expect(ceilf(0.0) == 0.0);
try expect(ceilf(-0.0) == -0.0);
try expect(math.isPositiveInf(ceilf(math.inf(f32))));
try expect(math.isNegativeInf(ceilf(-math.inf(f32))));
try expect(math.isNan(ceilf(math.nan(f32))));
}
test "ceil64.special" {
try expect(ceil(0.0) == 0.0);
try expect(ceil(-0.0) == -0.0);
try expect(math.isPositiveInf(ceil(math.inf(f64))));
try expect(math.isNegativeInf(ceil(-math.inf(f64))));
try expect(math.isNan(ceil(math.nan(f64))));
}
test "ceil128.special" {
try expect(ceilq(0.0) == 0.0);
try expect(ceilq(-0.0) == -0.0);
try expect(math.isPositiveInf(ceilq(math.inf(f128))));
try expect(math.isNegativeInf(ceilq(-math.inf(f128))));
try expect(math.isNan(ceilq(math.nan(f128))));
}

View File

@@ -2,6 +2,7 @@ const std = @import("std");
const builtin = @import("builtin"); const builtin = @import("builtin");
const arch = builtin.cpu.arch; const arch = builtin.cpu.arch;
const os = builtin.os.tag; const os = builtin.os.tag;
pub const panic = @import("common.zig").panic;
// Ported from llvm-project d32170dbd5b0d54436537b6b75beaf44324e0c28 // Ported from llvm-project d32170dbd5b0d54436537b6b75beaf44324e0c28
@@ -10,7 +11,11 @@ const os = builtin.os.tag;
// It is expected to invalidate the instruction cache for the // It is expected to invalidate the instruction cache for the
// specified range. // specified range.
pub fn clear_cache(start: usize, end: usize) callconv(.C) void { comptime {
_ = clear_cache;
}
fn clear_cache(start: usize, end: usize) callconv(.C) void {
const x86 = switch (arch) { const x86 = switch (arch) {
.i386, .x86_64 => true, .i386, .x86_64 => true,
else => false, else => false,
@@ -36,7 +41,7 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {
else => false, else => false,
}; };
const sparc = switch (arch) { const sparc = switch (arch) {
.sparc, .sparcv9, .sparcel => true, .sparc, .sparc64, .sparcel => true,
else => false, else => false,
}; };
const apple = switch (os) { const apple = switch (os) {

View File

@@ -1,14 +1,26 @@
const builtin = @import("builtin");
const clz = @import("count0bits.zig"); const clz = @import("count0bits.zig");
const testing = @import("std").testing; const testing = @import("std").testing;
fn test__clzsi2(a: u32, expected: i32) !void { fn test__clzsi2(a: u32, expected: i32) !void {
// XXX At high optimization levels this test may be horribly miscompiled if // stage1 and stage2 diverge on function pointer semantics
// one of the naked implementations is selected. switch (builtin.zig_backend) {
var nakedClzsi2 = clz.__clzsi2; .stage1 => {
var actualClzsi2 = @ptrCast(fn (a: i32) callconv(.C) i32, nakedClzsi2); // Use of `var` here is working around a stage1 bug.
var x = @bitCast(i32, a); var nakedClzsi2 = clz.__clzsi2;
var result = actualClzsi2(x); var actualClzsi2 = @ptrCast(fn (a: i32) callconv(.C) i32, nakedClzsi2);
try testing.expectEqual(expected, result); var x = @bitCast(i32, a);
var result = actualClzsi2(x);
try testing.expectEqual(expected, result);
},
else => {
const nakedClzsi2 = clz.__clzsi2;
const actualClzsi2 = @ptrCast(*const fn (a: i32) callconv(.C) i32, &nakedClzsi2);
const x = @bitCast(i32, a);
const result = actualClzsi2(x);
try testing.expectEqual(expected, result);
},
}
} }
test "clzsi2" { test "clzsi2" {

69
lib/compiler_rt/cmp.zig Normal file
View File

@@ -0,0 +1,69 @@
const std = @import("std");
const builtin = @import("builtin");
const is_test = builtin.is_test;
const common = @import("common.zig");
pub const panic = common.panic;
comptime {
@export(__cmpsi2, .{ .name = "__cmpsi2", .linkage = common.linkage });
@export(__cmpdi2, .{ .name = "__cmpdi2", .linkage = common.linkage });
@export(__cmpti2, .{ .name = "__cmpti2", .linkage = common.linkage });
@export(__ucmpsi2, .{ .name = "__ucmpsi2", .linkage = common.linkage });
@export(__ucmpdi2, .{ .name = "__ucmpdi2", .linkage = common.linkage });
@export(__ucmpti2, .{ .name = "__ucmpti2", .linkage = common.linkage });
}
// cmp - signed compare
// - cmpXi2_generic for unoptimized little and big endian
// ucmp - unsigned compare
// - ucmpXi2_generic for unoptimized little and big endian
// a < b => 0
// a == b => 1
// a > b => 2
inline fn XcmpXi2(comptime T: type, a: T, b: T) i32 {
var cmp1: i32 = 0;
var cmp2: i32 = 0;
if (a > b)
cmp1 = 1;
if (a < b)
cmp2 = 1;
return cmp1 - cmp2 + 1;
}
pub fn __cmpsi2(a: i32, b: i32) callconv(.C) i32 {
return XcmpXi2(i32, a, b);
}
pub fn __cmpdi2(a: i64, b: i64) callconv(.C) i32 {
return XcmpXi2(i64, a, b);
}
pub fn __cmpti2(a: i128, b: i128) callconv(.C) i32 {
return XcmpXi2(i128, a, b);
}
pub fn __ucmpsi2(a: u32, b: u32) callconv(.C) i32 {
return XcmpXi2(u32, a, b);
}
pub fn __ucmpdi2(a: u64, b: u64) callconv(.C) i32 {
return XcmpXi2(u64, a, b);
}
pub fn __ucmpti2(a: u128, b: u128) callconv(.C) i32 {
return XcmpXi2(u128, a, b);
}
test {
_ = @import("cmpsi2_test.zig");
_ = @import("cmpdi2_test.zig");
_ = @import("cmpti2_test.zig");
_ = @import("ucmpsi2_test.zig");
_ = @import("ucmpdi2_test.zig");
_ = @import("ucmpti2_test.zig");
}

Some files were not shown because too many files have changed in this diff Show More