Compare commits

..

169 Commits

Author SHA1 Message Date
deadprogram 26a0819119 main: release 0.14.1
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-08-19 08:37:16 +02:00
Ayke van Laethem b59a46eef0 loader: work around Windows symlink limitation
Currently there will be a problem if the TinyGo installation directory
is not the same filesystem as the cache directory (usually the C drive)
and Developer Mode is disabled. Therefore, let's add another fallback
for when both conditions are true, falling back to copying the file
instead of symlinking/hardlinking it.
2020-08-19 08:37:16 +02:00
deadprogram 8a410b993b make,builder: incorporate feedback from code review on Go 1.15 update
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-08-19 08:37:16 +02:00
deadprogram e412a63a1c make: use buildmode flag to set exe for windows to use standard linker
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-08-19 08:37:16 +02:00
deadprogram a81face618 builder: simplify Go version check message
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-08-19 08:37:16 +02:00
deadprogram 0ac216b093 build: use Golang 1.15 for MS Azure builds
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-08-19 08:37:16 +02:00
deadprogram 9575fe628f internal/bytealg: naive attempt to copy the main Go 1.15 implementatation
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-08-19 08:37:16 +02:00
deadprogram f4e8ea0d23 builder: allow Go 1.15 to pass config check
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-08-19 08:37:16 +02:00
deadprogram 2d03f65d67 build: add Go 1.15 to CircleCI build 2020-08-19 08:37:16 +02:00
Ayke van Laethem 154d4a781f main: release 0.14.0 2020-08-03 12:46:32 +02:00
deadprogram b5ab114514 dockerhub: use post checkout hook for git submodule init
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-08-03 08:30:31 +02:00
BCG 0a7e74045a feather-nrf52840: corrected USB identifier constants 2020-08-01 10:55:33 +02:00
Ayke van Laethem f05b378b89 compiler: add proper parameter names to runtime.initAll
This is required by the coroutines pass, otherwise it will panic. It
checks for the proper parameter names to make sure the function is not
exported. In this case, the runtime.initAll function wasn't exported but
simply didn't have the correct parameter names so the check triggered
even though it shouldn't.
2020-07-31 17:34:44 +02:00
Ayke van Laethem 888ca4ab0c interp: fix sync/atomic.Value load/store methods
These methods do some unsafe pointer casting but can be assumed to not
have significant side effects. Simply call these functions at runtime
instead of compile time.

This is a partial fix for importing image/png.
2020-07-31 17:34:44 +02:00
deadprogram 903bebd071 docs: add Nintendo Switch to list of supported boards/devices
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-07-31 09:12:44 +02:00
waj334 848c3e55a9 compiler: implement func value and builtin defers
Co-authored-by: Justin A. Wilson <maker.pro.game@gmail.com>
2020-07-31 01:48:57 +02:00
Lucas Teske 3650c2c739 nintendoswitch: Add experimental Nintendo Switch support without CRT
Bare minimal nintendo switch support using LLD
2020-07-31 00:58:09 +02:00
Ayke van Laethem d4e04e4e49 compiler: fix named string to []byte slice conversion
This was missing a `.Underlying()` call to avoid testing the named type
(but instead test for the underlying type).
2020-07-29 12:13:37 +02:00
Ayke van Laethem e41e5106cc main: add -target flag to tests
This makes it easy to test one particular architecture, for example:

    go test -v -target=hifive1-qemu

This speeds up testing and allows testing targets that are not included
in the test by default (such as RISC-V tests on Linux).
2020-07-24 16:59:37 +02:00
Ayke van Laethem ca03b8d442 ci: fix Windows QEMU version
It appears that version 2020.07.22 or 2020.07.23 introduced a breaking
change in RISC-V. We will have to fix this eventually, but for now it's
easiest to just pin the QEMU version. Once this new QEMU version
(version 5?) is more widely available, it becomes easier to debug and
fix the underlying cause.
2020-07-24 08:24:20 +02:00
deadprogram d1c4ed664e all: changeover to eliminate all direct use of master/slave terminology
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-07-23 22:45:23 +02:00
Ayke van Laethem fdaddf6917 ci: do not cache TinyGo cache dir
It doesn't seem to speed up the build and it causes issues with a stale
cache.
2020-07-23 21:49:20 +02:00
Ayke van Laethem 50a677e9b7 arm: use CFI directives for stack usage
Call Frame Information is stored in the .debug_frame section and is used
by debuggers for unwinding. For assembly, this information is not known.
Debuggers will normally use heuristics to figure out the parent function
in the absence of call frame information.

This usually works fine, but is not enough for determining stack sizes.
Instead, I hardcoded the stack size information in
stacksize/stacksize.go, which is somewhat fragile. This change uses CFI
assembly directives to store this information instead of hardcoding it.

This change also fixes the following error message that would appear in
GDB:

    Backtrace stopped: previous frame identical to this frame (corrupt stack?)

More information on CFI:
  * https://sourceware.org/binutils/docs/as/CFI-directives.html
  * https://www.imperialviolet.org/2017/01/18/cfi.html
2020-07-20 17:36:50 +02:00
Ethan Reesor 6ad6f14a04 Use a jump table instead of if-then-else 2020-07-18 08:39:26 -04:00
Jaden Weiss 19e0f4709e transform: track 0-index GEPs
It appears that LLVM is turning bitcasts into 0-index GEPs.
This caused stuff to not be tracked, resulting in use-after-free issues.
This solution is sub-optimal, but is the most reasonable solution I could come up with without redesigning the stack slots pass.
2020-07-16 20:50:23 +02:00
Jaden Weiss ae5b297d59 builder: remove optimization level 0
Currently, turning optimizations off causes compile failures.
We rely on the optimizer removing some dead symbols.
Avoid providing an option that does not work right now.
In the future once everything has been fixed we can re-enable this.
2020-07-16 16:41:52 +02:00
Ethan Reesor ca1a282495 Use runtime/volatile.T.ReplaceBits 2020-07-14 06:08:08 +02:00
deadprogram 01f5c51b77 machine/feather-nrf52840: add smoketest for Adafruit Feather nrf52840 board
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-07-14 00:13:10 +02:00
BCG ad6adfd8ff Added board definition for Feather nRF52840 Express 2020-07-13 16:50:06 +02:00
Ethan Reesor 9815628930 Cleanup Teensy 3.6 linker script 2020-07-13 12:35:53 +02:00
Ayke van Laethem 05495c4282 all: fix -gc=none
This option was broken for a long time, in part because we didn't test
for it. This commit fixes that and adds a test to make sure it won't
break again unnoticed.
2020-07-13 12:20:09 +02:00
Ayke van Laethem d606315515 builder: try to determine stack size information at compile time
For now, this is just an extra flag that can be used to print stack
frame information, but this is intended to provide a way to determine
stack sizes for goroutines at compile time in many cases.

Stack sizes are often somewhere around 350 bytes so are in fact not all
that big usually. Once this can be determined at compile time in many
cases, it is possible to use this information when available and as a
result increase the fallback stack size if the size cannot be determined
at compile time. This should reduce stack overflows while at the same
time reducing RAM consumption in many cases.

Interesting output for testdata/channel.go:

    function                                 stack usage (in bytes)
    Reset_Handler                            332
    .Lcommand-line-arguments.fastreceiver    220
    .Lcommand-line-arguments.fastsender      192
    .Lcommand-line-arguments.iterator        192
    .Lcommand-line-arguments.main$1          184
    .Lcommand-line-arguments.main$2          200
    .Lcommand-line-arguments.main$3          200
    .Lcommand-line-arguments.main$4          328
    .Lcommand-line-arguments.receive         176
    .Lcommand-line-arguments.selectDeadlock  72
    .Lcommand-line-arguments.selectNoOp      72
    .Lcommand-line-arguments.send            184
    .Lcommand-line-arguments.sendComplex     192
    .Lcommand-line-arguments.sender          192
    .Lruntime.run$1                          548

This shows that the stack size (if these numbers are correct) can in
fact be determined automatically in many cases, especially for small
goroutines. One of the great things about Go is lightweight goroutines,
and reducing stack sizes is very important to make goroutines
lightweight on microcontrollers.
2020-07-11 14:47:43 +02:00
sago35 60fdf81209 docs: add MAix BiT and Teensy 3.6 to list of supported boards (#1230)
* docs: add MAix BiT and Teensy 3.6 to list of supported boards
2020-07-11 09:21:16 +02:00
Ayke van Laethem 39433a3553 compileopts: automatically add -g flag when including debug symbols
Debug information is often useful and there is no reason to include it
for Go code but not for C code. Also, disabling debug information should
disable it entirely, not just for Go code.
2020-07-10 16:56:13 +02:00
Ethan Reesor 04d097f4ea Implement custom abort and fault handler for debugging 2020-07-08 21:58:15 +02:00
Ethan Reesor 4750635a20 Viable NXP/Teensy support
- Fix UART & putChar
- Timer-based sleep
- Enable systick in abort
- Buffered, interrupt-based UART TX
- Use the new interrupt API and fix sleepTicks
- Make pins behave more like other boards
- Use the MCU's UART numbering
- Allow interrupts to wake the scheduler (#1214)
2020-07-08 21:58:15 +02:00
Ethan Reesor 59218cd784 Working on NXP/Teensy support 2020-07-08 21:58:15 +02:00
Ethan Reesor 079a789d49 Minimal NXP/Teensy support 2020-07-08 21:58:15 +02:00
deadprogram ca8e1b075a targets/maixbit: cleanup output from kflash command by removing ansi colors
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-07-08 20:16:03 +02:00
Branden Timm 33024d4aa2 Fix portL mappings for atmega2560 (#1222)
* machine/atmega2560: fix portL mapping for atmega2560
2020-07-08 19:02:10 +02:00
Branden Timm 49df129ccd docs: add submodule update step prior to 'make release' (#1213)
* docs: add submodule update step prior to 'make release'
2020-07-08 17:37:43 +02:00
Ayke van Laethem 3088dcadec building: add links to tinygo.org
The BUILDING.md file is not intended for developer builds but for
release builds. The website contains more specific and more complete
information on how to build TinyGo, so provide links to these pages.

The Windows link doesn't work yet, but should work with the next
release when we update the website.
2020-07-08 17:35:31 +02:00
Yannis Huber 7ed7e6cb11 risc-v: disable linker relaxations during gp init 2020-07-08 01:58:12 +02:00
Yannis Huber 0b94e486c1 maixbit: changes according to feedback 2020-07-08 00:21:59 +02:00
Yannis Huber 5ff76aacab runtime: reuse common code between 32 and 64-bit RISC-V 2020-07-08 00:21:59 +02:00
Yannis Huber 3ee7599a09 maixbit: use custom linker script
This linker script does not offer stack overflow protection
because the stack cannot be placed at the bottom of the RAM.
2020-07-08 00:21:59 +02:00
Yannis Huber 43a66b39cc riscv: refactor assembly files to support RV64 and F extension 2020-07-08 00:21:59 +02:00
Yannis Huber 66b21b4c86 maixbit (interruptions): fix fpioa function test 2020-07-08 00:21:59 +02:00
Yannis Huber a9568932be maixbit: workaround to avoid medium code model 2020-07-08 00:21:59 +02:00
Yannis Huber f2fbd1dd7e maixbit (gpio): fix pin configuration 2020-07-08 00:21:59 +02:00
Yannis Huber 21a9aa8102 maixbit (i2c): fix rx fifo buffer length 2020-07-08 00:21:59 +02:00
Yannis Huber e1757e0347 builder: add support for 64-bit RISC-V 2020-07-08 00:21:59 +02:00
Yannis Huber a05fc10699 maixbit: add smoke test 2020-07-08 00:21:59 +02:00
Yannis Huber a685217743 maixbit: add I2C support 2020-07-08 00:21:59 +02:00
Yannis Huber ad0c15080a maixbit: add SPI support 2020-07-08 00:21:59 +02:00
Yannis Huber 5446c6927e maixbit: add GPIOHS pin interrupt support 2020-07-08 00:21:59 +02:00
Yannis Huber 53c83fa445 maixbit: support both GPIO and GPIOHS controllers 2020-07-08 00:21:59 +02:00
Yannis Huber 804dc8b1f9 maixbit: init fpioa clock at reset 2020-07-08 00:21:59 +02:00
Yannis Huber e1ceca1931 maixbit: remove atomic operations 2020-07-08 00:21:59 +02:00
Yannis Huber 6620c4d2aa maixbit: add chip datasheet link and reformat code 2020-07-08 00:21:59 +02:00
Yannis Huber ccc604d2e0 riscv: fix offset in 64bit scheduler
Also keep common start.S file for 64 and 32 bit architectures.
2020-07-08 00:21:59 +02:00
Yannis Huber dfab1aa717 maixbit (uart): serial is working with echo example 2020-07-08 00:21:59 +02:00
Yannis Huber 75bcbbe6d8 riscv: align stack and data sections to 8 bytes
Alignment on 4 bytes can cause load/store address misalignment
exceptions when loading/storing 64bit values on the stack.
2020-07-08 00:21:59 +02:00
Yannis Huber d599959711 maixbit (uart): working on data tx
When the data to send is too long the program gives an exception.
2020-07-08 00:21:59 +02:00
Yannis Huber 7814964693 maixbit: add board definition and dummy runtime 2020-07-08 00:21:59 +02:00
Yannis Huber 2fe4a9be71 maix-bit: add code model in target definition
This is needed to avoid linking errors because the globals are placed
in memory at address 0x80000000 which is out of bounds for the default
code model.
2020-07-08 00:21:59 +02:00
Yannis Huber 163631df9e cmsis-svd: change submodule url to the TinyGo fork 2020-07-08 00:21:59 +02:00
Yannis Huber 9ad96fd809 Changes according to @aykevl's feedback 2020-07-08 00:21:59 +02:00
Yannis Huber 4a658b9082 Add llvm code model option in target definition 2020-07-08 00:21:59 +02:00
Yannis Huber 34e0961a79 Split RISC-V targets into 32/64-bit 2020-07-08 00:21:59 +02:00
Yannis Huber 875d36cba0 Add new kendryte k210 target definition 2020-07-08 00:21:59 +02:00
sago35 1a6bed3305 machine/samd51: add DAC support (#1198)
* machine/samd51: add DAC support
2020-07-06 14:02:51 +02:00
Branden Timm e0b9b1ecd1 machine: fix atmega2560 mapping for pins D2 and D5 2020-07-05 21:18:20 +02:00
Johan Brandhorst 149c9533e2 ci: add archlinux release job
Adds the arch-release job, which automatically updates
the tinygo-bin AUR package on every new git tag with
a semver version.
2020-07-05 09:51:44 +02:00
Ron Evans a85df334e6 machine/samd21: basic implementation for DAC (#1183)
* machine/samd21: basic DAC implementation

Signed-off-by: Ron Evans <ron@hybridgroup.com>
2020-07-04 18:16:25 +02:00
Jaden Weiss 89a9c09af5 runtime (atsamd51): allow interrupts to wake the scheduler 2020-07-04 15:00:44 +02:00
Ayke van Laethem 1451eeaf41 machine: change machine.Pin type to uint8
The `machine.Pin` type was a int8, which works fine but limits the
number of pin numbers to 127. This patch changes the type to uint8 and
changes NoPin to 0xff, which allows more pins to be used.

Some boards might not have that many pins but their internal
organization requires more pin numbers to be used (because it is
organized in pin ports and not all pins in a port have a physical
connection). Therefore the range of a int8 is too low to address these
higher pins.

This patch also has the surprising side effect of reducing binary size
in a number of cases. If there is a reduction it's usually just a few
bytes, with one outlier: the driver example amg88xx when compiled for
the pybadge board. I have not seen any increases in binary size.
2020-07-04 09:46:12 +02:00
Jaden Weiss e8c84d24a0 runtime (gc): do not scan the runqueue when the platform is not baremetal with a scheduler 2020-07-04 08:34:39 +02:00
Jaden Weiss a4f3457747 runtime: make channels work in interrupts 2020-07-04 08:34:39 +02:00
Ayke van Laethem aa3481e06a avr: fix target triple
It was `avr-atmel-none`, which is incorrect. It must be
`avr-unknown-unknown`.

Additionally, there is no reason to specify the target triple per chip,
it can be done for all AVR chips at once as it doesn't vary like
Cortex-M chips.
2020-06-30 20:48:42 +02:00
Hiroki Noda 2136cb2f59 Building self-built LLVM faster
Disable LIBEDIT/Z3/OCAMLDOC in LLVM build and use shallow-clone.
2020-06-30 19:09:23 +02:00
Ayke van Laethem acb3cfba6d avr: work around codegen bug in LLVM 10
Commit fc4857e98c (runtime: avoid recursion in printuint64 function)
caused a regression for AVR. I have tried locally with LLVM 11 (which
contains a number of codegen bugs) and the issue is no longer present,
so I'm assuming it's a codegen bug that is now fixed. However, LLVM 11
is not yet released so it seems best to me to work around this
temporarily (for the next few months).

This commit can easily be reverted when we start using LLVM 11.
2020-06-30 17:56:10 +02:00
deadprogram 8cfc4005d3 machine/stm32f4disco: add smoketests for newer version of board
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-06-30 14:08:20 +02:00
deadprogram 2dbe29327a machine/stm32f4disco: add updated target file for newer version of board that have updated st-link
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-06-30 14:08:20 +02:00
sago35 de0fbb5e2f docs: add PyGamer to list of supported boards 2020-06-27 14:16:36 -04:00
Yannis Huber 9b1a19f184 gen-device-svd: fix lowercase in register spaced array 2020-06-26 13:16:34 +02:00
deadprogram 1ad6953858 build: clean tinygo cache before running tests
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-06-23 20:10:30 +02:00
sago35 3e8cdb62c9 main: use ToSlash() to specify pkgName
This change allows windows users to specify the package with backslash
as a path separator
2020-06-23 19:20:18 +02:00
Cornel 720a54a0fe extend stdlib to allow import of more packages (#1099)
* stdlib: extend stdlib to allow import of more packages
2020-06-23 11:56:28 +02:00
deadprogram de45da5df4 docker: try installing lld in initial stage to avoid cache problem with deb package
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-06-22 19:50:56 +02:00
Hiroki Noda c9fc95f6f3 wasm32: Add --no-demangle option
LLD supports only C++ demangle, so disable it.
2020-06-22 11:42:17 +02:00
sago35 2721ab146f Seeed XIAO support (#1170)
* machine/xiao: add support for Seeedstudio XIAO board
2020-06-22 09:01:13 +02:00
Jaden Weiss 81c723db1a device/arm: do not mask fault handlers in critical sections 2020-06-22 00:08:14 +02:00
sago35 9a20af5b59 Add adc settings 2020-06-19 15:07:57 +02:00
APDevice 4e8e3f348f Added Adafruit PyGamer Target (#1173)
* machine/PyGamer: add board support
2020-06-19 14:35:42 +02:00
deadprogram 496452b676 machine/hifive1b: add definitions for UART0 pins
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-06-17 16:28:37 +02:00
Ayke van Laethem e86ca2080d runtime/interrupt: add cross-chip disable/restore interrupt support
This should cover all supported baremetal targets.
2020-06-14 14:44:22 -04:00
Ayke van Laethem e2bf7bbb49 device: add new cross-arch Asm and AsmFull functions
This is necessary to avoid a circular dependency between the device/avr
and runtime/interrupts package in the next commit.

It may be worth replacing existing calls like device/arm.Asm to
device.Asm, to have a single place where these are defined.
2020-06-14 14:44:22 -04:00
Ayke van Laethem 4d1d0c2d3b main: go mod tidy
Clean up the go.mod and go.sum which have gotten a bit messy, and add an
extra line to go.sum that keeps reappearing locally for some reason (so
it seems important).
2020-06-11 08:14:48 +02:00
deadprogram 2281b6a3f5 machine/hifive1b: remove extra println left in by mistake
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-06-09 13:30:22 +02:00
Jaden Weiss 4321923641 compiler/runtime: move the channel blocked list onto the stack
Previously, chansend and chanrecv allocated a heap object before blocking on a channel.
This object was used to implement a linked list of goroutines blocked on the channel.
The chansend and chanrecv now instead accept a buffer to store this object in as an argument.
The compiler now creates a stack allocation for this object and passes it in.
2020-06-08 19:59:57 +02:00
Ayke van Laethem 4e4b5955db nrf: support debugging the PCA10056
This change adds support for `tinygo gdb` on the PCA10056.

The board is normally flashed with the MSD programmer. Debugging needs a
real debugger interface however, which is relatively simple by just
adding the right OpenOCD configuration.
2020-06-08 19:54:41 +02:00
Ayke van Laethem 169d5f17b8 nrf: fix bug in SPI.Tx
There was what appears to be a race condition in the Tx function. While
it would work fine in many cases, when there were interrupts (such as
when using BLE), the function would just hang waiting for `EVENTS_READY`
to arrive.

I think what was happening was that the `spi.Bus.RXD.Get()` would start
the next transfer, which would complete (and generate an event) before
`EVENTS_READY` was reset to 0. The fix is easy: clear `EVENTS_READY`
before doing something that can trigger an event.

I believe I've seen this bug before on the PineTime but I couldn't find
the issue back then.
2020-06-08 19:54:41 +02:00
Ayke van Laethem 9ed5eae6a9 cgo: use scanner.Error in libclang
Previously it would return a `*scanner.Error`, which is not supported in
the error printer of the main package. This can easily be fixed by
making it a regular object (instead of a pointer).
2020-06-08 19:54:41 +02:00
Yannis Huber e2c55e3d26 gen-device-svd: fix lowercase cluster name 2020-06-08 16:59:13 +02:00
Yannis Huber d3f5b51cd8 compiler: add support for custom code model 2020-06-08 16:50:39 +02:00
Yannis Huber 2396c22658 risc-v: add support for 64-bit RISC-V CPUs 2020-06-08 16:47:39 +02:00
Yannis Huber d61d5d7ab1 Zero PLIC threshold value at startup
The PLIC threshold value must be zeroed at startup to permit
all interrupt priorities. Fixes #1128.
2020-06-07 11:45:26 +02:00
sago35 c5a896771d Seeed WioTerminal support (#1124)
* machine/wioterminal: add support for wioterminal board
2020-06-06 12:00:26 +02:00
sago35 0c880ec44c Standardize SAMD51 UART settings (#1155)
* machine/samd51: standardize samd51 uart settings
2020-06-05 08:14:31 +02:00
sago35 64d51b215f Extend SAMD51 pinPadMapping 2020-06-03 19:37:16 +02:00
sago35 f103e910d7 Add SAMD51 pin change interrupt settings 2020-06-03 19:37:16 +02:00
sago35 40afeea569 Add SAMD51 ADC settings 2020-06-03 19:37:16 +02:00
sago35 97122972fb Add SAMD51 pins 2020-06-03 19:37:16 +02:00
sago35 72064e12db WIP flash: fix touchSerialPortAt1200bps on windows 2020-06-03 15:26:03 +02:00
Ayke van Laethem 3c31a3110f builder: use newer version of gohex
This version adds error handling for the DumpIntelHex method, and thus
fixes a TODO comment.
2020-06-01 19:03:15 +02:00
Ayke van Laethem 0e73790d67 Dockerfile: avoid duplicate LLVM apt line
This line causes problems when installing software: apt-get complains
that there are duplicate lines.
2020-06-01 11:47:29 +02:00
deadprogram bcbc241d81 main: improve/simplify auto-retry to locate MSD for UF2 and HEX flashing
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-05-31 13:23:19 +02:00
deadprogram 5e2a8024a3 main: use auto-retry (up to 10 seconds) to locate MSD for UF2 and HEX flashing
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-05-31 13:23:19 +02:00
sago35 b92fad8da6 sam: fix register access for interrupts pins in samd51 (#1141)
* machine/samd51: fix register access for interrupts pins in samd51
2020-05-30 18:03:46 +02:00
sago35 5c8d4e54d6 sam: add support for pin change interrupts (samd5x) 2020-05-29 11:36:22 +02:00
Ayke van Laethem fed433c046 compiler: add support for atomic operations
This also implements DisableInterrupts/EnableInterrupts for RISC-V, as
those operations were needed to implement a few libcalls.
2020-05-28 15:11:46 +02:00
Ayke van Laethem 734613c20e transform: introduce check for method calls on nil interfaces
I ran into an issue where I did a method call on a nil interface and it
resulted in a HardFault. Luckily I quickly realized what was going on so
I could fix it, but I think undefined behavior is definitely the wrong
behavior in this case. This commit therefore changes such calls to cause
a nil panic instead of introducing undefined behavior.

This does have a code size impact. It's relatively minor, much lower
than I expected. When comparing the before and after of the drivers
smoke tests (probably the most representative sample available), I found
that most did not change at all and those that did change, normally not
more than 100 bytes (16 or 32 byte changes are typical).

Right now the pattern is the following:

    switch typecode {
    case 1:
        call method 1
    case 2:
        call method 2
    default:
        nil panic
    }

I also tried the following (in the hope that it would be easier to
optimize), but it didn't really result in a code size reduction:

    switch typecode {
    case 1:
        call method 1
    case 2:
        call method 2
    case 0:
        nil panic
    default:
        unreachable
    }

Some code got smaller, while other code (the majority) got bigger. Maybe
this can be improved once range[1] is finally allowed[2] on function
parameters, but it'll probably take a while before that is implemented.

[1]: https://llvm.org/docs/LangRef.html#range-metadata
[2]: https://github.com/rust-lang/rust/issues/50156
2020-05-28 13:42:36 +02:00
Ayke van Laethem 1570adac1c transform: do not special-case zero or one implementations of a method call
This is a common case, but it also complicates the code. Removing this
special case does have a negative effect on code size in rare cases, but
I don't think it's worth keeping around (and possibly causing bugs) for
such uncommon cases.

This should not result in functional changes, although the output (as
stated above) sometimes changes a little bit.
2020-05-28 13:42:36 +02:00
Ayke van Laethem c72f9eb08c sam: add support for pin change interrupts 2020-05-28 11:20:33 +02:00
Ayke van Laethem 19c7965fc5 nrf: add support for pin change interrupts 2020-05-28 11:20:33 +02:00
Ayke van Laethem c248418dbe compiler: fix a few crashes due to named types
There were a few cases left where a named type would cause a crash in
the compiler. While going through enough code would have found them
eventually, I specifically looked for the `Type().(` pattern: a Type()
call that is then used in a type assert. Most of those were indeed bugs,
although for some I couldn't come up with a reproducer so I left them
as-is.
2020-05-27 16:14:41 +02:00
Ayke van Laethem 4ca2d3f0cf loader: load packages using Go modules
This commit replaces the existing ad-hoc package loader with a package
loader that uses the x/tools/go/packages package to find all
to-be-loaded packages.
2020-05-27 13:08:17 +02:00
Ayke van Laethem 35015a7918 loader: merge roots from both Go and TinyGo in a cached directory
This commit changes the way that packages are looked up. Instead of
working around the loader package by modifying the GOROOT variable for
specific packages, create a new GOROOT using symlinks. This GOROOT is
cached for the specified configuration (Go version, underlying GOROOT
path, TinyGo path, whether to override the syscall package).

This will also enable go module support in the future.

Windows is a bit harder to support, because it only allows the creation
of symlinks when developer mode is enabled. This is worked around by
using symlinks and if that fails, using directory junctions or hardlinks
instead. This should work in the vast majority of cases. The only case
it doesn't work, is if developer mode is disabled and TinyGo, the Go
toolchain, and the cache directory are not all on the same filesystem.
If this is a problem, it is still possible to improve the code by using
file copies instead.

As a side effect, this also makes diagnostics use a relative file path
only when the file is not in GOROOT or in TINYGOROOT.
2020-05-27 13:08:17 +02:00
Ayke van Laethem bde73fc214 main: fix test subcommand
It was broken for quite some time without anybody noticing...
2020-05-27 13:08:17 +02:00
Ayke van Laethem ab2a81cc52 main: move TinyGo version to goenv
This is needed to make it available to more packages, for caching
purposes.

For caching, the version itself may not be enough during development.
But for regular releases, the version provides some protection against
accidentally using a cache entry that is invalid in a newer version.
2020-05-27 13:08:17 +02:00
Ayke van Laethem 2a98433c8e builder: move Go version code to goenv package
This is necessary to avoid a circular dependency in the loader (which
soon will need to read the Go version) and because it seems like a
better place anyway.
2020-05-27 13:08:17 +02:00
Brad Peabody 4918395f88 added test for wasm log output
callback case for log test
2020-05-27 08:43:29 +02:00
Ayke van Laethem 67ac4fdd8e nrf: add microbit-s110v8 target
This makes it possible to use Bluetooth on the BBC micro:bit.

Note that you need to use -programmer=cmsis-dap otherwise the SoftDevice
will be erased while flashing something that uses Bluetooth.
2020-05-26 18:50:33 +02:00
Ayke van Laethem e69131c0d3 nrf: expose the RAM base address
The RAM base address is needed during SoftDevice initialization. So far,
the same magic value has been used in aykevl/go-bluetooth and in TinyGo,
but this should be configured in only one place.

This will have additional benefits in the future:

  * It is currently set to 0x39c0, which is around 14.5kB. Most nrf51822
    chips have only 16kB of RAM, so this is way too much for those
    chips.
  * LLD in LLVM 11 allows expressions in the MEMORY part of linker
    scripts, which will allow overriding the SoftDevice RAM area with a
    linker flag, which might come in handy.
2020-05-26 18:49:44 +02:00
Ayke van Laethem 9f4459cee1 arm: make FPU configuraton consistent
Eventually we might want to start using the FPU, but the easy option
right now is to simply disable it everywhere. Previously, it depended on
whether Clang was built as part of TinyGo or it was an external binary.
By setting the floating point mode explicitly, such inconsistencies are
avoided.

This commit creates a new cortex-m4 target which can be the central
place for setting FPU-related settings across all Cortex-M4 chips.
2020-05-26 16:39:14 +02:00
Ayke van Laethem 3c55689566 runtime: refactor time handling
This commit refactors both determining the current time and sleeping for
a given time. It also improves precision for many chips.

  * The nrf chips had a long-standing TODO comment about a slightly
    inaccurate clock. This should now be fixed.
  * The SAM D2x/D5x chips may have a slightly more accurate clock,
    although probably within the error margin of the RTC. Also, by
    working with RTC ticks and converting in the least number of places,
    code size is often slightly reduced (usually just a few bytes, up to
    around 1kB in some cases).
  * I believe the HiFive1 rev B timer was slightly wrong (32768Hz vs
    30517.6Hz). Because the datasheet says the clock runs at 32768Hz,
    I've used the same conversion code here as in the nrf and sam cases.
  * I couldn't test both stm32 timers, so I kept them as they currently
    are. It may be possible to make them more efficient by using the
    native tick frequency instead of using microseconds everywhere.
2020-05-25 22:08:28 +02:00
Brad Peabody 95f509b109 wasm test suite (#1116)
* wasm: add test suite using headlless chrome
2020-05-23 14:12:01 +02:00
Ayke van Laethem dda576e80b avr: add support for PinInputPullup 2020-05-22 13:17:04 +02:00
Ayke van Laethem da505a6b17 avr: unify GPIO pin/port code
All the AVRs that I've looked at had the same pin/port structure, with
the possible states being input/floating, input/pullup, low, and high
(with the same PORT/DDR registers). The main difference is the number of
available ports and pins. To reduce the amount of code and avoid
duplication (and thus errors) I decided to centralize this, following
the design used by the atmega2560 but while using a trick to save
tracking a few registers.

In the process, I noticed that the Pin.Get() function was incorrect on
the atmega2560 implementation. It is now fixed in the unified code.
2020-05-22 13:17:04 +02:00
deadprogram 424d775bf4 build: remove CircleCI orb, now using different integration
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-05-22 00:07:03 +02:00
Lucas Teske 726d735ad3 cgo: Add LDFlags support 2020-05-21 00:57:19 +02:00
deadprogram b9fd6cee6f build: add webhook notifier orb for circleci
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-05-20 00:15:23 +02:00
cebernardi 76fb3bd177 compileopts: improve error reporting of unsupported flags 2020-05-16 23:29:47 +02:00
Brad Peabody 29ca1147f5 call scheduler from resume 2020-05-16 23:16:53 +02:00
Jaden Weiss 473644d918 internal/bytealg: reimplement bytealg in pure Go
Previously, we implemented individual bytealg functions via linknaming, and had to update them every once in a while when we hit linker errors.
Instead, this change reimplements the bytealg package in pure Go.
If something is missing, it will cause a compiler error rather than a linker error.
This is easier to test and maintain.
2020-05-16 14:56:05 +02:00
Ayke van Laethem 38fc340802 sam: return an error when an incorrect PWM pin is used
Previously it would trigger a nil pointer panic.
2020-05-13 19:19:45 +02:00
Ayke van Laethem b5f028e1f7 ci: build .deb files along with .tar.gz files for Debian 2020-05-13 08:39:12 +02:00
Ayke van Laethem aa40ddc48b ci: do not install the SiFive toolchain
We don't need it anymore since we use lld to link RISC-V binaries.
2020-05-13 08:29:40 +02:00
Ayke van Laethem 6bcb40fe01 os: implement virtual filesystem support
This allows applications to mount filesystems in the os package. This is
useful for mounting external flash filesystems, for example.
2020-05-13 08:08:57 +02:00
cornelk e907db1481 os: add Args and stub it with mock data 2020-05-12 16:53:07 +02:00
Ayke van Laethem 6b8940421e avr: use standard pin numbering
This commit changes pin numbering for atmega328 based boards (Uno, Nano)
to use the standard format, where pin number is determined by the
pin/port. Previously, pin numbers were based on what the Uno uses, which
does not seem to have a clear pattern.

One difference is that counting starts at port B, as there is no port A.
So PB0 is 0, PB1 is 1… PC0 is 8.

This commit also moves PWM code to the atmega328 file, as it may not be
generic to all ATmega chips.
2020-05-12 08:16:34 +02:00
cornelk 2c71f08922 reflect: add Cap and Len support for map and chan 2020-05-12 01:17:27 +02:00
cornelk 7e64bc8f77 runtime: add cap and len support for chans 2020-05-12 01:17:27 +02:00
cornelk 1461563e3f testdata: fix formatting 2020-05-12 01:17:27 +02:00
cornelk acdaa72365 runtime: fix compilation errors when using gc.extalloc 2020-05-12 01:11:46 +02:00
deadprogram 01f5c1d455 machine/arduino-nano33: remove (d)ebug flag to reduce console noise when flashing
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-05-09 13:49:40 +02:00
deadprogram 00f3a65903 machine/arduino-nano33: use (U)SB flag to ensure that device can be found when not on default port
Signed-off-by: deadprogram <ron@hybridgroup.com>
2020-05-09 13:49:40 +02:00
Jaden Weiss b4815192a6 testdata, sync: add sync.Mutex test to testdata/coroutines.go 2020-05-09 01:08:56 +02:00
Jaden Weiss c54e1cc955 sync: modify sync.Cond 2020-05-09 01:08:56 +02:00
Jaden Weiss 7801921cc0 testdata: replace fake waitgroup in channel.go with sync.WaitGroup 2020-05-09 01:08:56 +02:00
Jaden Weiss afc6bd5cdd sync: add WaitGroup 2020-05-09 01:08:56 +02:00
Jaden Weiss ae2cbbf851 internal/task: fix nil panic in (*internal/task.Stack).Pop
While adding some code to clear the Next field when popping from a task stack for safety reasons, the clear was placed outside of a nil pointer check.
As a result, (*internal/task.Stack).Pop panicked when the Stack is empty.
2020-05-09 01:08:56 +02:00
Jaden Weiss ccd79ee289 add sync.Cond 2020-05-09 01:08:56 +02:00
Jaden Weiss 171d0fe123 implement mutex blocking 2020-05-09 01:08:56 +02:00
sago35 5ed0f67e1c sam: fix ROM / RAM size on atsamd51j20 2020-05-07 23:04:10 +02:00
sago35 8ce3cfad40 flash: fix getDefaultPort() fails on Windows locales such as Japan 2020-05-07 22:47:45 +02:00
Ayke van Laethem 904fa852f6 transform: fix debug information in func lowering pass
This commit fixes errors like the following:

    inlinable function call in a function with debug info must have a !dbg location
      call void @runtime.nilPanic(i8* undef, i8* null)
    inlinable function call in a function with debug info must have a !dbg location
      %24 = call fastcc %runtime._interface @"(*github.com/vugu/vugu/domrender.JSRenderer).render$1"(%"github.com/vugu/vugu.VGNode"** %19, i32 %22, i32 %23, i8* %15, i8* undef)
    error: optimizations caused a verification failure

Not all instructions had a debug location, which apparently caused
issues for the inliner.
2020-05-07 08:24:14 +02:00
Ayke van Laethem d0b2585e82 main: update go-llvm to fix macOS build problem 2020-05-05 08:11:20 +02:00
306 changed files with 11406 additions and 1557 deletions
+86 -11
View File
@@ -37,6 +37,13 @@ commands:
sudo tar -C /usr/local -xf node-v10.15.1-linux-x64.tar.xz
sudo ln -s /usr/local/node-v10.15.1-linux-x64/bin/node /usr/bin/node
rm node-v10.15.1-linux-x64.tar.xz
install-chrome:
steps:
- run:
name: "Install Chrome"
command: |
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt install ./google-chrome-stable_current_amd64.deb
llvm-source-linux:
steps:
- restore_cache:
@@ -71,6 +78,7 @@ commands:
- apt-dependencies:
llvm: "<<parameters.llvm>>"
- install-node
- install-chrome
- restore_cache:
keys:
- go-cache-v2-{{ checksum "go.mod" }}-{{ .Environment.CIRCLE_PREVIOUS_BUILD_NUM }}
@@ -88,11 +96,11 @@ commands:
- run: go test -v -tags=llvm<<parameters.llvm>> ./cgo ./compileopts ./interp ./transform .
- run: make gen-device -j4
- run: make smoketest
- run: make wasmtest
- save_cache:
key: go-cache-v2-{{ checksum "go.mod" }}-{{ .Environment.CIRCLE_BUILD_NUM }}
paths:
- ~/.cache/go-build
- ~/.cache/tinygo
- /go/pkg/mod
- run: make fmt-check
assert-test-linux:
@@ -150,7 +158,6 @@ commands:
key: go-cache-v2-{{ checksum "go.mod" }}-{{ .Environment.CIRCLE_BUILD_NUM }}
paths:
- ~/.cache/go-build
- ~/.cache/tinygo
- /go/pkg/mod
- run: make gen-device -j4
- run: make smoketest TINYGO=build/tinygo
@@ -204,18 +211,25 @@ commands:
- run:
name: "Test TinyGo"
command: make test
- run:
name: "Install fpm"
command: |
sudo apt-get install ruby ruby-dev
sudo gem install --no-document fpm
- run:
name: "Build TinyGo release"
command: |
make release -j3
make release deb -j3
cp -p build/release.tar.gz /tmp/tinygo.linux-amd64.tar.gz
cp -p build/release.deb /tmp/tinygo_amd64.deb
- store_artifacts:
path: /tmp/tinygo.linux-amd64.tar.gz
- store_artifacts:
path: /tmp/tinygo_amd64.deb
- save_cache:
key: go-cache-v2-{{ checksum "go.mod" }}-{{ .Environment.CIRCLE_BUILD_NUM }}
paths:
- ~/.cache/go-build
- ~/.cache/tinygo
- /go/pkg/mod
- run:
name: "Extract release tarball"
@@ -294,19 +308,59 @@ commands:
tar -C /usr/local/opt -xf /tmp/tinygo.darwin-amd64.tar.gz
ln -s /usr/local/opt/tinygo/bin/tinygo /usr/local/bin/tinygo
tinygo version
- run:
name: "Download SiFive GNU toolchain"
command: |
curl -O https://static.dev.sifive.com/dev-tools/riscv64-unknown-elf-gcc-8.2.0-2019.05.3-x86_64-apple-darwin.tar.gz
sudo tar -C /usr/local --strip-components=1 -xf riscv64-unknown-elf-gcc-8.2.0-2019.05.3-x86_64-apple-darwin.tar.gz
- run: make smoketest AVR=0
- save_cache:
key: go-cache-macos-v2-{{ checksum "go.mod" }}-{{ .Environment.CIRCLE_BUILD_NUM }}
paths:
- ~/.cache/go-build
- ~/.cache/tinygo
- /go/pkg/mod
arch-release:
steps:
- run:
name: Install dependencies
command: pacman -Sy --noconfirm openssh git pacman-contrib binutils
- run:
name: Create TinyGo user
command: useradd -m tinygo
- run:
name: Become TinyGo user
command: su tinygo
- run:
name: Start SSH Agent
command: eval $(ssh-agent -s)
- run:
name: Add ARCH_RELEASE_SSH_PRIVATE_KEY identity
command: echo "${ARCH_RELEASE_SSH_PRIVATE_KEY}" | tr -d '\r' | ssh-add -
- run:
name: Create SSH directory
command: mkdir -p ~/.ssh && chmod 700 ~/.ssh
- run:
name: Add aur.archlinux.org to known hosts
command: ssh-keyscan aur.archlinux.org >> ~/.ssh/known_hosts
- run:
name: Clone tinygo-bin repo
command: git clone ssh://aur@aur.archlinux.org/tinygo-bin.git ~/tinygo-bin
- run:
name: Update package version
command: sed -i -E "s/(pkgver=)(.*)$/\1${CIRCLE_TAG}/" ~/tinygo-bin/PKGBUILD
- run:
name: Update file checksums
command: cd ~/tinygo-bin && updpkgsums
- run:
name: Update .SRCINFO
command: cd ~/tinygo-bin && makepkg --printsrcinfo > .SRCINFO
# Commit the update
- run:
name: Set git commit config
command: |
git config --global user.email "tinygo-bot@tinygo.org" &&
git config --global user.name "TinyGo Release Bot"
- run:
name: Commit and push changes
command: |
cd ~/tinygo-bin &&
git commit -a -m "Update tinygo-bin to v${CIRCLE_TAG}" &&
git push origin master
jobs:
test-llvm9-go111:
@@ -333,6 +387,12 @@ jobs:
steps:
- test-linux:
llvm: "10"
test-llvm10-go115:
docker:
- image: circleci/golang:1.15-buster
steps:
- test-linux:
llvm: "10"
assert-test-linux:
docker:
- image: circleci/golang:1.14-stretch
@@ -348,6 +408,11 @@ jobs:
xcode: "10.1.0"
steps:
- build-macos
arch-release:
docker:
- image: archlinux:latest
steps:
- arch-release
@@ -359,6 +424,16 @@ workflows:
- test-llvm10-go112
- test-llvm10-go113
- test-llvm10-go114
- test-llvm10-go115
- build-linux
- build-macos
- assert-test-linux
release:
jobs:
- arch-release:
filters:
branches:
ignore: /.*/
tags:
# Runs on every semver release
only: /v[0-9]+(\.[0-9]+)*(-.*)*/
+4
View File
@@ -5,12 +5,16 @@ src/device/avr/*.ld
src/device/avr/*.s
src/device/nrf/*.go
src/device/nrf/*.s
src/device/nxp/*.go
src/device/nxp/*.s
src/device/sam/*.go
src/device/sam/*.s
src/device/sifive/*.go
src/device/sifive/*.s
src/device/stm32/*.go
src/device/stm32/*.s
src/device/kendryte/*.go
src/device/kendryte/*.s
vendor
llvm-build
llvm-project
+1 -1
View File
@@ -9,7 +9,7 @@
url = https://github.com/avr-rust/avr-mcu.git
[submodule "lib/cmsis-svd"]
path = lib/cmsis-svd
url = https://github.com/posborne/cmsis-svd
url = https://github.com/tinygo-org/cmsis-svd
[submodule "lib/compiler-rt"]
path = lib/compiler-rt
url = https://github.com/llvm-mirror/compiler-rt.git
+12
View File
@@ -10,6 +10,14 @@ This guide describes how to statically link TinyGo against LLVM, libclang and
lld so that the binary can be easily moved between systems. It also shows how to
build a release tarball that includes this binary and all necessary extra files.
**Note**: this documentation describes how to build a statically linked release
tarball. If you want to develop TinyGo, you will probably want to follow a
different guide:
* [Linux](https://tinygo.org/getting-started/linux/#source-install)
* [macOS](https://tinygo.org/getting-started/macos/#source-install)
* [Windows](https://tinygo.org/getting-started/windows/#source-install)
## Dependencies
LLVM, Clang and LLD are quite light on dependencies, requiring only standard
@@ -84,6 +92,10 @@ Now that we have a working static build, it's time to make a release tarball:
make release
If you did not clone the repository with the `--recursive` option, you will get errors until you initialize the project submodules:
git submodule update --init
The release tarball is stored in build/release.tar.gz, and can be extracted with
the following command (for example in ~/lib):
+96
View File
@@ -1,3 +1,99 @@
0.14.1
---
* **command-line**
- support for Go 1.15
* **compiler**
- loader: work around Windows symlink limitation
0.14.0
---
* **command-line**
- fix `getDefaultPort()` on non-English Windows locales
- compileopts: improve error reporting of unsupported flags
- fix test subcommand
- use auto-retry to locate MSD for UF2 and HEX flashing
- fix touchSerialPortAt1200bps on Windows
- support package names with backslashes on Windows
* **compiler**
- fix a few crashes due to named types
- add support for atomic operations
- move the channel blocked list onto the stack
- fix -gc=none
- fix named string to `[]byte` slice conversion
- implement func value and builtin defers
- add proper parameter names to runtime.initAll, to fix a panic
- builder: fix picolibc include path
- builder: use newer version of gohex
- builder: try to determine stack size information at compile time
- builder: remove -opt=0
- interp: fix sync/atomic.Value load/store methods
- loader: add Go module support
- transform: fix debug information in func lowering pass
- transform: do not special-case zero or one implementations of a method call
- transform: introduce check for method calls on nil interfaces
- transform: gc: track 0-index GEPs to fix miscompilation
* **cgo**
- Add LDFlags support
* **standard library**
- extend stdlib to allow import of more packages
- replace master/slave terminology with appropriate alternatives (MOSI->SDO
etc)
- `internal/bytealg`: reimplement bytealg in pure Go
- `internal/task`: fix nil panic in (*internal/task.Stack).Pop
- `os`: add Args and stub it with mock data
- `os`: implement virtual filesystem support
- `reflect`: add Cap and Len support for map and chan
- `runtime`: fix return address in scheduler on RISC-V
- `runtime`: avoid recursion in printuint64 function
- `runtime`: replace ReadRegister with AsmFull inline assembly
- `runtime`: fix compilation errors when using gc.extalloc
- `runtime`: add cap and len support for chans
- `runtime`: refactor time handling (improving accuracy)
- `runtime`: make channels work in interrupts
- `runtime/interrupt`: add cross-chip disable/restore interrupt support
- `sync`: implement `sync.Cond`
- `sync`: add WaitGroup
* **targets**
- `arm`: allow nesting in DisableInterrupts and EnableInterrupts
- `arm`: make FPU configuraton consistent
- `arm`: do not mask fault handlers in critical sections
- `atmega2560`: fix pin mapping for pins D2, D5 and the L port
- `atsamd`: return an error when an incorrect PWM pin is used
- `atsamd`: add support for pin change interrupts
- `atsamd`: add DAC support
- `atsamd21`: add more ADC pins
- `atsamd51`: fix ROM / RAM size on atsamd51j20
- `atsamd51`: add more pins
- `atsamd51`: add more ADC pins
- `atsamd51`: add pin change interrupt settings
- `atsamd51`: extend pinPadMapping
- `arduino-nano33`: use (U)SB flag to ensure that device can be found when
not on default port
- `arduino-nano33`: remove (d)ebug flag to reduce console noise when flashing
- `avr`: use standard pin numbering
- `avr`: unify GPIO pin/port code
- `avr`: add support for PinInputPullup
- `avr`: work around codegen bug in LLVM 10
- `avr`: fix target triple
- `fe310`: remove extra println left in by mistake
- `feather-nrf52840`: add support for the Feather nRF52840
- `maixbit`: add board definition and dummy runtime
- `nintendoswitch`: Add experimental Nintendo Switch support without CRT
- `nrf`: expose the RAM base address
- `nrf`: add support for pin change interrupts
- `nrf`: add microbit-s110v8 target
- `nrf`: fix bug in SPI.Tx
- `nrf`: support debugging the PCA10056
- `pygamer`: add Adafruit PyGamer suport
- `riscv`: fix interrupt configuration bug
- `riscv`: disable linker relaxations during gp init
- `stm32f4disco`: add new target with ST-Link v2.1 debugger
- `teensy36`: add Teensy 3.6 support
- `wasm`: fix event handling
- `wasm`: add --no-demangle linker option
- `wioterminal`: add support for the Seeed Wio Terminal
- `xiao`: add support for the Seeed XIAO
0.13.1
---
* **standard library**
+1 -1
View File
@@ -32,7 +32,7 @@ Microcontrollers have lots of peripherals (I2C, SPI, ADC, etc.) and many don't h
## How to use our Github repository
The `master` branch of this repo will always have the latest released version of TinyGo. All of the active development work for the next release will take place in the `dev` branch. TinyGo will use semantic versioning and will create a tag/release for each release.
The `release` branch of this repo will always have the latest released version of TinyGo. All of the active development work for the next release will take place in the `dev` branch. TinyGo will use semantic versioning and will create a tag/release for each release.
Here is how to contribute back some code or documentation:
+2 -5
View File
@@ -4,7 +4,7 @@ FROM golang:1.14 AS tinygo-base
RUN wget -O- https://apt.llvm.org/llvm-snapshot.gpg.key| apt-key add - && \
echo "deb http://apt.llvm.org/buster/ llvm-toolchain-buster-10 main" >> /etc/apt/sources.list && \
apt-get update && \
apt-get install -y llvm-10-dev libclang-10-dev git
apt-get install -y llvm-10-dev libclang-10-dev lld-10 git
COPY . /tinygo
@@ -27,10 +27,7 @@ COPY --from=tinygo-base /go/bin/tinygo /go/bin/tinygo
COPY --from=tinygo-base /tinygo/src /tinygo/src
COPY --from=tinygo-base /tinygo/targets /tinygo/targets
RUN wget -O- https://apt.llvm.org/llvm-snapshot.gpg.key| apt-key add - && \
echo "deb http://apt.llvm.org/buster/ llvm-toolchain-buster-10 main" >> /etc/apt/sources.list && \
apt-get update && \
apt-get install -y libllvm10 lld-10
RUN apt-get install -y libllvm10 lld-10
# tinygo-avr stage installs the needed dependencies to compile TinyGo programs for AVR microcontrollers.
FROM tinygo-base AS tinygo-avr
+56 -9
View File
@@ -51,7 +51,7 @@ else
LLVM_OPTION += '-DLLVM_ENABLE_ASSERTIONS=OFF'
endif
.PHONY: all tinygo test $(LLVM_BUILDDIR) llvm-source clean fmt gen-device gen-device-nrf gen-device-avr
.PHONY: all tinygo test $(LLVM_BUILDDIR) llvm-source clean fmt gen-device gen-device-nrf gen-device-nxp gen-device-avr
LLVM_COMPONENTS = all-targets analysis asmparser asmprinter bitreader bitwriter codegen core coroutines coverage debuginfodwarf executionengine frontendopenmp instrumentation interpreter ipo irreader linker lto mc mcjit objcarcopts option profiledata scalaropts support target
@@ -118,7 +118,7 @@ fmt-check:
@unformatted=$$(gofmt -l $(FMT_PATHS)); [ -z "$$unformatted" ] && exit 0; echo "Unformatted:"; for fn in $$unformatted; do echo " $$fn"; done; exit 1
gen-device: gen-device-avr gen-device-nrf gen-device-sam gen-device-sifive gen-device-stm32
gen-device: gen-device-avr gen-device-nrf gen-device-sam gen-device-sifive gen-device-stm32 gen-device-kendryte gen-device-nxp
gen-device-avr:
$(GO) build -o ./build/gen-device-avr ./tools/gen-device-avr/
@@ -133,6 +133,10 @@ gen-device-nrf: build/gen-device-svd
./build/gen-device-svd -source=https://github.com/NordicSemiconductor/nrfx/tree/master/mdk lib/nrfx/mdk/ src/device/nrf/
GO111MODULE=off $(GO) fmt ./src/device/nrf
gen-device-nxp: build/gen-device-svd
./build/gen-device-svd -source=https://github.com/posborne/cmsis-svd/tree/master/data/NXP lib/cmsis-svd/data/NXP/ src/device/nxp/
GO111MODULE=off $(GO) fmt ./src/device/nxp
gen-device-sam: build/gen-device-svd
./build/gen-device-svd -source=https://github.com/posborne/cmsis-svd/tree/master/data/Atmel lib/cmsis-svd/data/Atmel/ src/device/sam/
GO111MODULE=off $(GO) fmt ./src/device/sam
@@ -141,6 +145,10 @@ gen-device-sifive: build/gen-device-svd
./build/gen-device-svd -source=https://github.com/posborne/cmsis-svd/tree/master/data/SiFive-Community -interrupts=software lib/cmsis-svd/data/SiFive-Community/ src/device/sifive/
GO111MODULE=off $(GO) fmt ./src/device/sifive
gen-device-kendryte: build/gen-device-svd
./build/gen-device-svd -source=https://github.com/posborne/cmsis-svd/tree/master/data/Kendryte-Community -interrupts=software lib/cmsis-svd/data/Kendryte-Community/ src/device/kendryte/
GO111MODULE=off $(GO) fmt ./src/device/kendryte
gen-device-stm32: build/gen-device-svd
./build/gen-device-svd -source=https://github.com/posborne/cmsis-svd/tree/master/data/STMicro lib/cmsis-svd/data/STMicro/ src/device/stm32/
GO111MODULE=off $(GO) fmt ./src/device/stm32
@@ -148,13 +156,13 @@ gen-device-stm32: build/gen-device-svd
# Get LLVM sources.
$(LLVM_PROJECTDIR)/README.md:
git clone -b release/10.x https://github.com/llvm/llvm-project $(LLVM_PROJECTDIR)
git clone -b release/10.x --depth=1 https://github.com/llvm/llvm-project $(LLVM_PROJECTDIR)
llvm-source: $(LLVM_PROJECTDIR)/README.md
# Configure LLVM.
TINYGO_SOURCE_DIR=$(shell pwd)
$(LLVM_BUILDDIR)/build.ninja: llvm-source
mkdir -p $(LLVM_BUILDDIR); cd $(LLVM_BUILDDIR); cmake -G Ninja $(TINYGO_SOURCE_DIR)/$(LLVM_PROJECTDIR)/llvm "-DLLVM_TARGETS_TO_BUILD=X86;ARM;AArch64;RISCV;WebAssembly" "-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=AVR" -DCMAKE_BUILD_TYPE=Release -DLIBCLANG_BUILD_STATIC=ON -DLLVM_ENABLE_TERMINFO=OFF -DLLVM_ENABLE_ZLIB=OFF -DLLVM_ENABLE_PROJECTS="clang;lld" -DLLVM_TOOL_CLANG_TOOLS_EXTRA_BUILD=OFF $(LLVM_OPTION)
mkdir -p $(LLVM_BUILDDIR); cd $(LLVM_BUILDDIR); cmake -G Ninja $(TINYGO_SOURCE_DIR)/$(LLVM_PROJECTDIR)/llvm "-DLLVM_TARGETS_TO_BUILD=X86;ARM;AArch64;RISCV;WebAssembly" "-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=AVR" -DCMAKE_BUILD_TYPE=Release -DLIBCLANG_BUILD_STATIC=ON -DLLVM_ENABLE_TERMINFO=OFF -DLLVM_ENABLE_ZLIB=OFF -DLLVM_ENABLE_LIBEDIT=OFF -DLLVM_ENABLE_Z3_SOLVER=OFF -DLLVM_ENABLE_OCAMLDOC=OFF -DLLVM_ENABLE_PROJECTS="clang;lld" -DLLVM_TOOL_CLANG_TOOLS_EXTRA_BUILD=OFF $(LLVM_OPTION)
# Build LLVM.
$(LLVM_BUILDDIR): $(LLVM_BUILDDIR)/build.ninja
@@ -171,10 +179,10 @@ lib/wasi-libc/sysroot/lib/wasm32-wasi/libc.a:
# Build the Go compiler.
tinygo:
@if [ ! -f "$(LLVM_BUILDDIR)/bin/llvm-config" ]; then echo "Fetch and build LLVM first by running:"; echo " make llvm-source"; echo " make $(LLVM_BUILDDIR)"; exit 1; fi
CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) build -o build/tinygo$(EXE) -tags byollvm .
CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) build -buildmode exe -o build/tinygo$(EXE) -tags byollvm .
test: wasi-libc
CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test -v -tags byollvm ./cgo ./compileopts ./interp ./transform .
CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test -v -buildmode exe -tags byollvm ./cgo ./compileopts ./interp ./transform .
tinygo-test:
cd tests/tinygotest && tinygo test
@@ -182,7 +190,7 @@ tinygo-test:
.PHONY: smoketest
smoketest:
$(TINYGO) version
# test all examples
# test all examples (except pwm)
$(TINYGO) build -size short -o test.hex -target=pca10040 examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10040 examples/adc
@@ -203,7 +211,7 @@ smoketest:
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=microbit examples/microbit-blink
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10040 examples/pwm
$(TINYGO) build -size short -o test.hex -target=pca10040 examples/pininterrupt
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10040 examples/serial
@$(MD5SUM) test.hex
@@ -231,6 +239,8 @@ smoketest:
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=microbit examples/echo
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=microbit-s110v8 examples/echo
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=nrf52840-mdk examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10031 examples/blinky1
@@ -257,6 +267,8 @@ smoketest:
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=stm32f4disco examples/blinky2
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=stm32f4disco-1 examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=circuitplay-bluefruit examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=circuitplay-express examples/i2s
@@ -291,11 +303,25 @@ smoketest:
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=reelboard-s140v7 examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=wioterminal examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pygamer examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=xiao examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=circuitplay-express examples/dac
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pyportal examples/dac
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=feather-nrf52840 examples/blinky1
@$(MD5SUM) test.hex
ifneq ($(AVR), 0)
$(TINYGO) build -size short -o test.hex -target=atmega1284p examples/serial
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=arduino examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=arduino examples/pwm
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=arduino -scheduler=tasks examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=arduino-nano examples/blinky1
@@ -307,10 +333,22 @@ ifneq ($(AVR), 0)
endif
$(TINYGO) build -size short -o test.hex -target=hifive1b examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=maixbit examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -o wasm.wasm -target=wasm examples/wasm/export
$(TINYGO) build -o wasm.wasm -target=wasm examples/wasm/main
# test various compiler flags
$(TINYGO) build -size short -o test.hex -target=pca10040 -gc=none -scheduler=none examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -size short -o test.hex -target=pca10040 -opt=1 examples/blinky1
@$(MD5SUM) test.hex
$(TINYGO) build -o test.elf -target=nintendoswitch examples/serial
@$(MD5SUM) test.elf
release: tinygo gen-device wasi-libc
wasmtest:
$(GO) test ./tests/wasm
build/release: tinygo gen-device wasi-libc
@mkdir -p build/release/tinygo/bin
@mkdir -p build/release/tinygo/lib/clang/include
@mkdir -p build/release/tinygo/lib/CMSIS/CMSIS
@@ -345,4 +383,13 @@ release: tinygo gen-device wasi-libc
./build/tinygo build-library -target=armv6m-none-eabi -o build/release/tinygo/pkg/armv6m-none-eabi/picolibc.a picolibc
./build/tinygo build-library -target=armv7m-none-eabi -o build/release/tinygo/pkg/armv7m-none-eabi/picolibc.a picolibc
./build/tinygo build-library -target=armv7em-none-eabi -o build/release/tinygo/pkg/armv7em-none-eabi/picolibc.a picolibc
release: build/release
tar -czf build/release.tar.gz -C build/release tinygo
deb: build/release
@mkdir -p build/release-deb/usr/local/bin
@mkdir -p build/release-deb/usr/local/lib
cp -ar build/release/tinygo build/release-deb/usr/local/lib/tinygo
ln -sf ../lib/tinygo/bin/tinygo build/release-deb/usr/local/bin/tinygo
fpm -f -s dir -t deb -n tinygo -v $(shell grep "const Version = " goenv/version.go | awk '{print $$NF}') -m '@tinygo-org' --description='TinyGo is a Go compiler for small places.' --license='BSD 3-Clause' --url=https://tinygo.org/ --deb-changelog CHANGELOG.md -p build/release.deb -C ./build/release-deb
+10 -1
View File
@@ -43,17 +43,19 @@ See the [getting started instructions](https://tinygo.org/getting-started/) for
You can compile TinyGo programs for microcontrollers, WebAssembly and Linux.
The following 32 microcontroller boards are currently supported:
The following 39 microcontroller boards/devices are currently supported:
* [Adafruit Circuit Playground Bluefruit](https://www.adafruit.com/product/4333)
* [Adafruit Circuit Playground Express](https://www.adafruit.com/product/3333)
* [Adafruit CLUE Alpha](https://www.adafruit.com/product/4500)
* [Adafruit Feather M0](https://www.adafruit.com/product/2772)
* [Adafruit Feather M4](https://www.adafruit.com/product/3857)
* [Adafruit Feather nRF52840 Express](https://www.adafruit.com/product/4062)
* [Adafruit ItsyBitsy M0](https://www.adafruit.com/product/3727)
* [Adafruit ItsyBitsy M4](https://www.adafruit.com/product/3800)
* [Adafruit Metro M4 Express Airlift](https://www.adafruit.com/product/4000)
* [Adafruit PyBadge](https://www.adafruit.com/product/4200)
* [Adafruit PyGamer](https://www.adafruit.com/product/4242)
* [Adafruit PyPortal](https://www.adafruit.com/product/4116)
* [Adafruit Trinket M0](https://www.adafruit.com/product/3500)
* [Arduino Mega 2560](https://store.arduino.cc/arduino-mega-2560-rev3)
@@ -64,6 +66,7 @@ The following 32 microcontroller boards are currently supported:
* [Digispark](http://digistump.com/products/1)
* [Game Boy Advance](https://en.wikipedia.org/wiki/Game_Boy_Advance)
* [Makerdiary nRF52840-MDK](https://wiki.makerdiary.com/nrf52840-mdk/)
* [Nintendo Switch](https://www.nintendo.com/switch/)
* [Nordic Semiconductor PCA10031](https://www.nordicsemi.com/eng/Products/nRF51-Dongle)
* [Nordic Semiconductor PCA10040](https://www.nordicsemi.com/eng/Products/Bluetooth-low-energy/nRF52-DK)
* [Nordic Semiconductor PCA10056](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK)
@@ -72,6 +75,10 @@ The following 32 microcontroller boards are currently supported:
* [Particle Xenon](https://docs.particle.io/datasheets/discontinued/xenon-datasheet/)
* [Phytec reel board](https://www.phytec.eu/product-eu/internet-of-things/reelboard/)
* [PineTime DevKit](https://www.pine64.org/pinetime/)
* [PJRC Teensy 3.6](https://www.pjrc.com/store/teensy36.html)
* [Seeed Wio Terminal](https://www.seeedstudio.com/Wio-Terminal-p-4509.html)
* [Seeed Seeeduino XIAO](https://www.seeedstudio.com/Seeeduino-XIAO-Arduino-Microcontroller-SAMD21-Cortex-M0+-p-4426.html)
* [Seeed Sipeed MAix BiT](https://www.seeedstudio.com/Sipeed-MAix-BiT-for-RISC-V-AI-IoT-p-2872.html)
* [SiFIve HiFive1](https://www.sifive.com/boards/hifive1)
* [ST Micro "Nucleo F103RB"](https://www.st.com/en/evaluation-tools/nucleo-f103rb.html)
* [ST Micro STM32F103XX "Bluepill"](http://wiki.stm32duino.com/index.php?title=Blue_Pill)
@@ -137,3 +144,5 @@ The original reasoning was: if [Python](https://micropython.org/) can run on mic
This project is licensed under the BSD 3-clause license, just like the [Go project](https://golang.org/LICENSE) itself.
Some code has been copied from the LLVM project and is therefore licensed under [a variant of the Apache 2.0 license](http://releases.llvm.org/10.0.0/LICENSE.TXT). This has been clearly indicated in the header of these files.
Some code has been copied and/or ported from Paul Stoffregen's Teensy libraries and is therefore licensed under PJRC's license. This has been clearly indicated in the header of these files.
+4 -4
View File
@@ -1,7 +1,7 @@
# Avoid lengthy LLVM rebuilds on each newly pushed branch. Pull requests will
# be built anyway.
trigger:
- master
- release
- dev
jobs:
@@ -12,7 +12,7 @@ jobs:
steps:
- task: GoTool@0
inputs:
version: '1.14.1'
version: '1.15'
- checkout: self
- task: CacheBeta@0
displayName: Cache LLVM source
@@ -43,7 +43,7 @@ jobs:
displayName: Install QEMU
inputs:
targetType: inline
script: choco install qemu
script: choco install qemu --version=2020.06.12
- task: CacheBeta@0
displayName: Cache wasi-libc sysroot
inputs:
@@ -69,7 +69,7 @@ jobs:
script: |
export PATH="$PATH:./llvm-build/bin:/c/Program Files/qemu"
unset GOROOT
make release -j4
make build/release -j4
- publish: $(System.DefaultWorkingDirectory)/build/release/tinygo
displayName: Publish zip as artifact
artifact: tinygo
+108 -3
View File
@@ -4,11 +4,13 @@
package builder
import (
"debug/elf"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
@@ -16,6 +18,7 @@ import (
"github.com/tinygo-org/tinygo/compiler"
"github.com/tinygo-org/tinygo/goenv"
"github.com/tinygo-org/tinygo/interp"
"github.com/tinygo-org/tinygo/stacksize"
"github.com/tinygo-org/tinygo/transform"
"tinygo.org/x/go-llvm"
)
@@ -32,7 +35,7 @@ func Build(pkgName, outpath string, config *compileopts.Config, action func(stri
if err != nil {
return err
}
mod, extraFiles, errs := compiler.Compile(pkgName, machine, config)
mod, extraFiles, extraLDFlags, errs := compiler.Compile(pkgName, machine, config)
if errs != nil {
return newMultiError(errs)
}
@@ -73,8 +76,15 @@ func Build(pkgName, outpath string, config *compileopts.Config, action func(stri
// exactly.
errs = nil
switch config.Options.Opt {
case "none", "0":
errs = transform.Optimize(mod, config, 0, 0, 0) // -O0
/*
Currently, turning optimizations off causes compile failures.
We rely on the optimizer removing some dead symbols.
Avoid providing an option that does not work right now.
In the future once everything has been fixed we can re-enable this.
case "none", "0":
errs = transform.Optimize(mod, config, 0, 0, 0) // -O0
*/
case "1":
errs = transform.Optimize(mod, config, 1, 0, 0) // -O1
case "2":
@@ -187,6 +197,10 @@ func Build(pkgName, outpath string, config *compileopts.Config, action func(stri
ldflags = append(ldflags, outpath)
}
if len(extraLDFlags) > 0 {
ldflags = append(ldflags, extraLDFlags...)
}
// Link the object files together.
err = link(config.Target.Linker, ldflags...)
if err != nil {
@@ -212,6 +226,11 @@ func Build(pkgName, outpath string, config *compileopts.Config, action func(stri
}
}
// Print goroutine stack sizes, as far as possible.
if config.Options.PrintStacks {
printStacks(mod, executable)
}
// Get an Intel .hex file or .bin file from the .elf file.
if outext == ".hex" || outext == ".bin" || outext == ".gba" {
tmppath = filepath.Join(dir, "main"+outext)
@@ -230,3 +249,89 @@ func Build(pkgName, outpath string, config *compileopts.Config, action func(stri
return action(tmppath)
}
}
// printStacks prints the maximum stack depth for functions that are started as
// goroutines. Stack sizes cannot always be determined statically, in particular
// recursive functions and functions that call interface methods or function
// pointers may have an unknown stack depth (depending on what the optimizer
// manages to optimize away).
//
// It might print something like the following:
//
// function stack usage (in bytes)
// Reset_Handler 316
// .Lexamples/blinky2.led1 92
// .Lruntime.run$1 300
func printStacks(mod llvm.Module, executable string) {
// Determine which functions call a function pointer.
var callsIndirectFunction []string
for fn := mod.FirstFunction(); !fn.IsNil(); fn = llvm.NextFunction(fn) {
for bb := fn.FirstBasicBlock(); !bb.IsNil(); bb = llvm.NextBasicBlock(bb) {
for inst := bb.FirstInstruction(); !inst.IsNil(); inst = llvm.NextInstruction(inst) {
if inst.IsACallInst().IsNil() {
continue
}
if callee := inst.CalledValue(); callee.IsAFunction().IsNil() && callee.IsAInlineAsm().IsNil() {
callsIndirectFunction = append(callsIndirectFunction, fn.Name())
}
}
}
}
// Load the ELF binary.
f, err := elf.Open(executable)
if err != nil {
fmt.Fprintln(os.Stderr, "could not load executable for stack size analysis:", err)
return
}
defer f.Close()
// Determine the frame size of each function (if available) and the callgraph.
functions, err := stacksize.CallGraph(f, callsIndirectFunction)
if err != nil {
fmt.Fprintln(os.Stderr, "could not parse executable for stack size analysis:", err)
return
}
// Get a list of "go wrappers", small wrapper functions that decode
// parameters when starting a new goroutine.
var gowrappers []string
for name := range functions {
if strings.HasSuffix(name, "$gowrapper") {
gowrappers = append(gowrappers, name)
}
}
sort.Strings(gowrappers)
switch f.Machine {
case elf.EM_ARM:
// Add the reset handler, which runs startup code and is the
// interrupt/scheduler stack with -scheduler=tasks.
// Note that because interrupts happen on this stack, the stack needed
// by just the Reset_Handler is not enough. Stacks needed by interrupt
// handlers should also be taken into account.
gowrappers = append([]string{"Reset_Handler"}, gowrappers...)
}
// Print the sizes of all stacks.
fmt.Printf("%-32s %s\n", "function", "stack usage (in bytes)")
for _, name := range gowrappers {
for _, fn := range functions[name] {
stackSize, stackSizeType, missingStackSize := fn.StackSize()
strippedName := name
if strings.HasSuffix(name, "$gowrapper") {
strippedName = name[:len(name)-len("$gowrapper")]
}
switch stackSizeType {
case stacksize.Bounded:
fmt.Printf("%-32s %d\n", strippedName, stackSize)
case stacksize.Unknown:
fmt.Printf("%-32s unknown, %s does not have stack frame information\n", strippedName, missingStackSize)
case stacksize.Recursive:
fmt.Printf("%-32s recursive, %s may call itself\n", strippedName, missingStackSize)
case stacksize.IndirectCall:
fmt.Printf("%-32s unknown, %s calls a function pointer\n", strippedName, missingStackSize)
}
}
}
}
+2 -2
View File
@@ -25,8 +25,8 @@ func NewConfig(options *compileopts.Options) (*compileopts.Config, error) {
if err != nil {
return nil, fmt.Errorf("could not read version from GOROOT (%v): %v", goroot, err)
}
if major != 1 || minor < 11 || minor > 14 {
return nil, fmt.Errorf("requires go version 1.11, 1.12, 1.13, or 1.14, got go%d.%d", major, minor)
if major != 1 || minor < 11 || minor > 15 {
return nil, fmt.Errorf("requires go version 1.11 through 1.15, got go%d.%d", major, minor)
}
clangHeaderPath := getClangHeaderPath(goenv.Get("TINYGOROOT"))
return &compileopts.Config{
+4 -1
View File
@@ -69,11 +69,14 @@ func (l *Library) Load(target string) (path string, err error) {
// Precalculate the flags to the compiler invocation.
args := append(l.cflags(), "-c", "-Oz", "-g", "-ffunction-sections", "-fdata-sections", "-Wno-macro-redefined", "--target="+target, "-fdebug-prefix-map="+dir+"="+remapDir)
if strings.HasPrefix(target, "arm") || strings.HasPrefix(target, "thumb") {
args = append(args, "-fshort-enums", "-fomit-frame-pointer")
args = append(args, "-fshort-enums", "-fomit-frame-pointer", "-mfloat-abi=soft")
}
if strings.HasPrefix(target, "riscv32-") {
args = append(args, "-march=rv32imac", "-mabi=ilp32", "-fforce-enable-int128")
}
if strings.HasPrefix(target, "riscv64-") {
args = append(args, "-march=rv64gc", "-mabi=lp64")
}
// Compile all sources.
var objs []string
+1 -2
View File
@@ -123,8 +123,7 @@ func objcopy(infile, outfile string) error {
if err != nil {
return objcopyError{"failed to create .hex file", err}
}
mem.DumpIntelHex(f, 16) // TODO: handle error
return nil
return mem.DumpIntelHex(f, 16)
default:
panic("unreachable")
}
+17 -3
View File
@@ -41,6 +41,7 @@ type cgoPackage struct {
elaboratedTypes map[string]*elaboratedTypeInfo
enums map[string]enumInfo
anonStructNum int
ldflags []string
}
// constantInfo stores some information about a CGo constant found by libclang
@@ -156,7 +157,7 @@ typedef unsigned long long _Cgo_ulonglong;
// newly created *ast.File that should be added to the list of to-be-parsed
// files. If there is one or more error, it returns these in the []error slice
// but still modifies the AST.
func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string) (*ast.File, []error) {
func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string) (*ast.File, []string, []error) {
p := &cgoPackage{
dir: dir,
fset: fset,
@@ -183,7 +184,7 @@ func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string
// Find the absolute path for this package.
packagePath, err := filepath.Abs(fset.File(files[0].Pos()).Name())
if err != nil {
return nil, []error{
return nil, nil, []error{
scanner.Error{
Pos: fset.Position(files[0].Pos()),
Msg: "cgo: cannot find absolute path: " + err.Error(), // TODO: wrap this error
@@ -359,6 +360,19 @@ func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string
}
makePathsAbsolute(flags, packagePath)
cflags = append(cflags, flags...)
case "LDFLAGS":
flags, err := shlex.Split(value)
if err != nil {
// TODO: find the exact location where the error happened.
p.addErrorAfter(comment.Slash, comment.Text[:lineStart+colon+1], "failed to parse flags in #cgo line: "+err.Error())
continue
}
if err := checkLinkerFlags(name, flags); err != nil {
p.addErrorAfter(comment.Slash, comment.Text[:lineStart+colon+1], err.Error())
continue
}
makePathsAbsolute(flags, packagePath)
p.ldflags = append(p.ldflags, flags...)
default:
startPos := strings.LastIndex(line[4:colon], name) + 4
p.addErrorAfter(comment.Slash, comment.Text[:lineStart+startPos], "invalid #cgo line: "+name)
@@ -412,7 +426,7 @@ func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string
// Print the newly generated in-memory AST, for debugging.
//ast.Print(fset, p.generated)
return p.generated, p.errors
return p.generated, p.ldflags, p.errors
}
// makePathsAbsolute converts some common path compiler flags (-I, -L) from
+1 -1
View File
@@ -50,7 +50,7 @@ func TestCGo(t *testing.T) {
}
// Process the AST with CGo.
cgoAST, cgoErrors := Process([]*ast.File{f}, "testdata", fset, cflags)
cgoAST, _, cgoErrors := Process([]*ast.File{f}, "testdata", fset, cflags)
// Check the AST for type errors.
var typecheckErrors []error
+3 -3
View File
@@ -246,9 +246,9 @@ func tinygo_clang_globals_visitor(c, parent C.GoCXCursor, client_data C.CXClient
}
value := source[len(name):]
// Try to convert this #define into a Go constant expression.
expr, err := parseConst(pos+token.Pos(len(name)), p.fset, value)
if err != nil {
p.errors = append(p.errors, err)
expr, scannerError := parseConst(pos+token.Pos(len(name)), p.fset, value)
if scannerError != nil {
p.errors = append(p.errors, *scannerError)
}
if expr != nil {
// Parsing was successful.
+7
View File
@@ -21,6 +21,13 @@ package main
#if defined(NOTDEFINED)
#warning flag must not be defined
#endif
// Check Compiler flags
#cgo LDFLAGS: -lc
// This flag is not valid ldflags
#cgo LDFLAGS: -does-not-exists
*/
import "C"
+1
View File
@@ -1,6 +1,7 @@
// CGo errors:
// testdata/flags.go:5:7: invalid #cgo line: NOFLAGS
// testdata/flags.go:8:13: invalid flag: -fdoes-not-exist
// testdata/flags.go:29:14: invalid flag: -does-not-exists
package main
+24 -2
View File
@@ -129,8 +129,8 @@ func (c *Config) NeedsStackObjects() bool {
}
}
// Scheduler returns the scheduler implementation. Valid values are "coroutines"
// and "tasks".
// Scheduler returns the scheduler implementation. Valid values are "none",
//"coroutines" and "tasks".
func (c *Config) Scheduler() string {
if c.Options.Scheduler != "" {
return c.Options.Scheduler
@@ -176,6 +176,9 @@ func (c *Config) CFlags() []string {
cflags = append(cflags, "-nostdlibinc", "-Xclang", "-internal-isystem", "-Xclang", filepath.Join(root, "lib", "picolibc", "newlib", "libc", "include"))
cflags = append(cflags, "-I"+filepath.Join(root, "lib/picolibc-include"))
}
if c.Debug() {
cflags = append(cflags, "-g")
}
return cflags
}
@@ -272,6 +275,25 @@ func (c *Config) OpenOCDConfiguration() (args []string, err error) {
return args, nil
}
// CodeModel returns the code model used on this platform.
func (c *Config) CodeModel() string {
if c.Target.CodeModel != "" {
return c.Target.CodeModel
}
return "default"
}
// RelocationModel returns the relocation model in use on this platform. Valid
// values are "static", "pic", "dynamicnopic".
func (c *Config) RelocationModel() string {
if c.Target.RelocationModel != "" {
return c.Target.RelocationModel
}
return "static"
}
type TestConfig struct {
CompileTestBinary bool
// TODO: Filter the test functions to run, include verbose flag, etc
+63
View File
@@ -1,5 +1,17 @@
package compileopts
import (
"fmt"
"strings"
)
var (
validGCOptions = []string{"none", "leaking", "extalloc", "conservative"}
validSchedulerOptions = []string{"none", "tasks", "coroutines"}
validPrintSizeOptions = []string{"none", "short", "full"}
validPanicStrategyOptions = []string{"print", "trap"}
)
// Options contains extra options to give to the compiler. These options are
// usually passed from the command line.
type Options struct {
@@ -13,6 +25,7 @@ type Options struct {
VerifyIR bool
Debug bool
PrintSizes string
PrintStacks bool
CFlags []string
LDFlags []string
Tags string
@@ -21,3 +34,53 @@ type Options struct {
TestConfig TestConfig
Programmer string
}
// Verify performs a validation on the given options, raising an error if options are not valid.
func (o *Options) Verify() error {
if o.GC != "" {
valid := isInArray(validGCOptions, o.GC)
if !valid {
return fmt.Errorf(`invalid gc option '%s': valid values are %s`,
o.GC,
strings.Join(validGCOptions, ", "))
}
}
if o.Scheduler != "" {
valid := isInArray(validSchedulerOptions, o.Scheduler)
if !valid {
return fmt.Errorf(`invalid scheduler option '%s': valid values are %s`,
o.Scheduler,
strings.Join(validSchedulerOptions, ", "))
}
}
if o.PrintSizes != "" {
valid := isInArray(validPrintSizeOptions, o.PrintSizes)
if !valid {
return fmt.Errorf(`invalid size option '%s': valid values are %s`,
o.PrintSizes,
strings.Join(validPrintSizeOptions, ", "))
}
}
if o.PanicStrategy != "" {
valid := isInArray(validPanicStrategyOptions, o.PanicStrategy)
if !valid {
return fmt.Errorf(`invalid panic option '%s': valid values are %s`,
o.PanicStrategy,
strings.Join(validPanicStrategyOptions, ", "))
}
}
return nil
}
func isInArray(arr []string, item string) bool {
for _, i := range arr {
if i == item {
return true
}
}
return false
}
+138
View File
@@ -0,0 +1,138 @@
package compileopts_test
import (
"errors"
"testing"
"github.com/tinygo-org/tinygo/compileopts"
)
func TestVerifyOptions(t *testing.T) {
expectedGCError := errors.New(`invalid gc option 'incorrect': valid values are none, leaking, extalloc, conservative`)
expectedSchedulerError := errors.New(`invalid scheduler option 'incorrect': valid values are none, tasks, coroutines`)
expectedPrintSizeError := errors.New(`invalid size option 'incorrect': valid values are none, short, full`)
expectedPanicStrategyError := errors.New(`invalid panic option 'incorrect': valid values are print, trap`)
testCases := []struct {
name string
opts compileopts.Options
expectedError error
}{
{
name: "OptionsEmpty",
opts: compileopts.Options{},
},
{
name: "InvalidGCOption",
opts: compileopts.Options{
GC: "incorrect",
},
expectedError: expectedGCError,
},
{
name: "GCOptionNone",
opts: compileopts.Options{
GC: "none",
},
},
{
name: "GCOptionLeaking",
opts: compileopts.Options{
GC: "leaking",
},
},
{
name: "GCOptionExtalloc",
opts: compileopts.Options{
GC: "extalloc",
},
},
{
name: "GCOptionConservative",
opts: compileopts.Options{
GC: "conservative",
},
},
{
name: "InvalidSchedulerOption",
opts: compileopts.Options{
Scheduler: "incorrect",
},
expectedError: expectedSchedulerError,
},
{
name: "SchedulerOptionNone",
opts: compileopts.Options{
Scheduler: "none",
},
},
{
name: "SchedulerOptionTasks",
opts: compileopts.Options{
Scheduler: "tasks",
},
},
{
name: "SchedulerOptionCoroutines",
opts: compileopts.Options{
Scheduler: "coroutines",
},
},
{
name: "InvalidPrintSizeOption",
opts: compileopts.Options{
PrintSizes: "incorrect",
},
expectedError: expectedPrintSizeError,
},
{
name: "PrintSizeOptionNone",
opts: compileopts.Options{
PrintSizes: "none",
},
},
{
name: "PrintSizeOptionShort",
opts: compileopts.Options{
PrintSizes: "short",
},
},
{
name: "PrintSizeOptionFull",
opts: compileopts.Options{
PrintSizes: "full",
},
},
{
name: "InvalidPanicOption",
opts: compileopts.Options{
PanicStrategy: "incorrect",
},
expectedError: expectedPanicStrategyError,
},
{
name: "PanicOptionPrint",
opts: compileopts.Options{
PanicStrategy: "print",
},
},
{
name: "PanicOptionTrap",
opts: compileopts.Options{
PanicStrategy: "trap",
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := tc.opts.Verify()
if tc.expectedError != err {
if tc.expectedError.Error() != err.Error() {
t.Errorf("expected %v, got %v", tc.expectedError, err)
}
}
})
}
}
+9
View File
@@ -49,6 +49,8 @@ type TargetSpec struct {
OpenOCDTarget string `json:"openocd-target"`
OpenOCDTransport string `json:"openocd-transport"`
JLinkDevice string `json:"jlink-device"`
CodeModel string `json:"code-model"`
RelocationModel string `json:"relocation-model"`
}
// copyProperties copies all properties that are set in spec2 into itself.
@@ -130,6 +132,13 @@ func (spec *TargetSpec) copyProperties(spec2 *TargetSpec) {
if spec2.JLinkDevice != "" {
spec.JLinkDevice = spec2.JLinkDevice
}
if spec2.CodeModel != "" {
spec.CodeModel = spec2.CodeModel
}
if spec2.RelocationModel != "" {
spec.RelocationModel = spec2.RelocationModel
}
}
// load reads a target specification from the JSON in the given io.Reader. It
+57
View File
@@ -0,0 +1,57 @@
package compiler
import (
"golang.org/x/tools/go/ssa"
"tinygo.org/x/go-llvm"
)
// createAtomicOp lowers an atomic library call by lowering it as an LLVM atomic
// operation. It returns the result of the operation and true if the call could
// be lowered inline, and false otherwise.
func (b *builder) createAtomicOp(call *ssa.CallCommon) (llvm.Value, bool) {
name := call.Value.(*ssa.Function).Name()
switch name {
case "AddInt32", "AddInt64", "AddUint32", "AddUint64", "AddUintptr":
ptr := b.getValue(call.Args[0])
val := b.getValue(call.Args[1])
oldVal := b.CreateAtomicRMW(llvm.AtomicRMWBinOpAdd, ptr, val, llvm.AtomicOrderingSequentiallyConsistent, true)
// Return the new value, not the original value returned by atomicrmw.
return b.CreateAdd(oldVal, val, ""), true
case "SwapInt32", "SwapInt64", "SwapUint32", "SwapUint64", "SwapUintptr", "SwapPointer":
ptr := b.getValue(call.Args[0])
val := b.getValue(call.Args[1])
isPointer := val.Type().TypeKind() == llvm.PointerTypeKind
if isPointer {
// atomicrmw only supports integers, so cast to an integer.
val = b.CreatePtrToInt(val, b.uintptrType, "")
ptr = b.CreateBitCast(ptr, llvm.PointerType(val.Type(), 0), "")
}
oldVal := b.CreateAtomicRMW(llvm.AtomicRMWBinOpXchg, ptr, val, llvm.AtomicOrderingSequentiallyConsistent, true)
if isPointer {
oldVal = b.CreateIntToPtr(oldVal, b.i8ptrType, "")
}
return oldVal, true
case "CompareAndSwapInt32", "CompareAndSwapInt64", "CompareAndSwapUint32", "CompareAndSwapUint64", "CompareAndSwapUintptr", "CompareAndSwapPointer":
ptr := b.getValue(call.Args[0])
old := b.getValue(call.Args[1])
newVal := b.getValue(call.Args[2])
tuple := b.CreateAtomicCmpXchg(ptr, old, newVal, llvm.AtomicOrderingSequentiallyConsistent, llvm.AtomicOrderingSequentiallyConsistent, true)
swapped := b.CreateExtractValue(tuple, 1, "")
return swapped, true
case "LoadInt32", "LoadInt64", "LoadUint32", "LoadUint64", "LoadUintptr", "LoadPointer":
ptr := b.getValue(call.Args[0])
val := b.CreateLoad(ptr, "")
val.SetOrdering(llvm.AtomicOrderingSequentiallyConsistent)
val.SetAlignment(b.targetData.PrefTypeAlignment(val.Type())) // required
return val, true
case "StoreInt32", "StoreInt64", "StoreUint32", "StoreUint64", "StoreUintptr", "StorePointer":
ptr := b.getValue(call.Args[0])
val := b.getValue(call.Args[1])
store := b.CreateStore(val, ptr)
store.SetOrdering(llvm.AtomicOrderingSequentiallyConsistent)
store.SetAlignment(b.targetData.PrefTypeAlignment(val.Type())) // required
return store, true
default:
return llvm.Value{}, false
}
}
+17 -7
View File
@@ -12,7 +12,7 @@ import (
)
func (b *builder) createMakeChan(expr *ssa.MakeChan) llvm.Value {
elementSize := b.targetData.TypeAllocSize(b.getLLVMType(expr.Type().(*types.Chan).Elem()))
elementSize := b.targetData.TypeAllocSize(b.getLLVMType(expr.Type().Underlying().(*types.Chan).Elem()))
elementSizeValue := llvm.ConstInt(b.uintptrType, elementSize, false)
bufSize := b.getValue(expr.Size)
b.createChanBoundsCheck(elementSize, bufSize, expr.Size.Type().Underlying().(*types.Basic), expr.Pos())
@@ -35,27 +35,37 @@ func (b *builder) createChanSend(instr *ssa.Send) {
valueAlloca, valueAllocaCast, valueAllocaSize := b.createTemporaryAlloca(valueType, "chan.value")
b.CreateStore(chanValue, valueAlloca)
// Do the send.
b.createRuntimeCall("chanSend", []llvm.Value{ch, valueAllocaCast}, "")
// Allocate blockedlist buffer.
channelBlockedList := b.mod.GetTypeByName("runtime.channelBlockedList")
channelBlockedListAlloca, channelBlockedListAllocaCast, channelBlockedListAllocaSize := b.createTemporaryAlloca(channelBlockedList, "chan.blockedList")
// End the lifetime of the alloca.
// Do the send.
b.createRuntimeCall("chanSend", []llvm.Value{ch, valueAllocaCast, channelBlockedListAlloca}, "")
// End the lifetime of the allocas.
// This also works around a bug in CoroSplit, at least in LLVM 8:
// https://bugs.llvm.org/show_bug.cgi?id=41742
b.emitLifetimeEnd(channelBlockedListAllocaCast, channelBlockedListAllocaSize)
b.emitLifetimeEnd(valueAllocaCast, valueAllocaSize)
}
// createChanRecv emits a pseudo chan receive operation. It is lowered to the
// actual channel receive operation during goroutine lowering.
func (b *builder) createChanRecv(unop *ssa.UnOp) llvm.Value {
valueType := b.getLLVMType(unop.X.Type().(*types.Chan).Elem())
valueType := b.getLLVMType(unop.X.Type().Underlying().(*types.Chan).Elem())
ch := b.getValue(unop.X)
// Allocate memory to receive into.
valueAlloca, valueAllocaCast, valueAllocaSize := b.createTemporaryAlloca(valueType, "chan.value")
// Allocate blockedlist buffer.
channelBlockedList := b.mod.GetTypeByName("runtime.channelBlockedList")
channelBlockedListAlloca, channelBlockedListAllocaCast, channelBlockedListAllocaSize := b.createTemporaryAlloca(channelBlockedList, "chan.blockedList")
// Do the receive.
commaOk := b.createRuntimeCall("chanRecv", []llvm.Value{ch, valueAllocaCast}, "")
commaOk := b.createRuntimeCall("chanRecv", []llvm.Value{ch, valueAllocaCast, channelBlockedListAlloca}, "")
received := b.CreateLoad(valueAlloca, "chan.received")
b.emitLifetimeEnd(channelBlockedListAllocaCast, channelBlockedListAllocaSize)
b.emitLifetimeEnd(valueAllocaCast, valueAllocaSize)
if unop.CommaOk {
@@ -117,7 +127,7 @@ func (b *builder) createSelect(expr *ssa.Select) llvm.Value {
switch state.Dir {
case types.RecvOnly:
// Make sure the receive buffer is big enough and has the correct alignment.
llvmType := b.getLLVMType(state.Chan.Type().(*types.Chan).Elem())
llvmType := b.getLLVMType(state.Chan.Type().Underlying().(*types.Chan).Elem())
if size := b.targetData.TypeAllocSize(llvmType); size > recvbufSize {
recvbufSize = size
}
+62 -21
View File
@@ -74,7 +74,14 @@ type builder struct {
deferFuncs map[*ir.Function]int
deferInvokeFuncs map[string]int
deferClosureFuncs map[*ir.Function]int
deferExprFuncs map[ssa.Value]int
selectRecvBuf map[*ssa.Select]llvm.Value
deferBuiltinFuncs map[ssa.Value]deferBuiltin
}
type deferBuiltin struct {
funcName string
callback int
}
type phiNode struct {
@@ -91,7 +98,35 @@ func NewTargetMachine(config *compileopts.Config) (llvm.TargetMachine, error) {
return llvm.TargetMachine{}, err
}
features := strings.Join(config.Features(), ",")
machine := target.CreateTargetMachine(config.Triple(), config.CPU(), features, llvm.CodeGenLevelDefault, llvm.RelocStatic, llvm.CodeModelDefault)
var codeModel llvm.CodeModel
var relocationModel llvm.RelocMode
switch config.CodeModel() {
case "default":
codeModel = llvm.CodeModelDefault
case "tiny":
codeModel = llvm.CodeModelTiny
case "small":
codeModel = llvm.CodeModelSmall
case "kernel":
codeModel = llvm.CodeModelKernel
case "medium":
codeModel = llvm.CodeModelMedium
case "large":
codeModel = llvm.CodeModelLarge
}
switch config.RelocationModel() {
case "static":
relocationModel = llvm.RelocStatic
case "pic":
relocationModel = llvm.RelocPIC
case "dynamicnopic":
relocationModel = llvm.RelocDynamicNoPic
}
machine := target.CreateTargetMachine(config.Triple(), config.CPU(), features, llvm.CodeGenLevelDefault, relocationModel, codeModel)
return machine, nil
}
@@ -103,7 +138,7 @@ func NewTargetMachine(config *compileopts.Config) (llvm.TargetMachine, error) {
// violation. Eventually, this Compile function should only compile a single
// package and not the whole program, and loading of the program (including CGo
// processing) should be moved outside the compiler package.
func Compile(pkgName string, machine llvm.TargetMachine, config *compileopts.Config) (llvm.Module, []string, []error) {
func Compile(pkgName string, machine llvm.TargetMachine, config *compileopts.Config) (mod llvm.Module, extrafiles []string, extraldflags []string, errors []error) {
c := &compilerContext{
Config: config,
difiles: make(map[string]llvm.Metadata),
@@ -139,11 +174,11 @@ func Compile(pkgName string, machine llvm.TargetMachine, config *compileopts.Con
wd, err := os.Getwd()
if err != nil {
return c.mod, nil, []error{err}
return c.mod, nil, nil, []error{err}
}
goroot, err := loader.GetCachedGoroot(c.Config)
if err != nil {
return c.mod, nil, []error{err}
return c.mod, nil, nil, []error{err}
}
lprogram := &loader.Program{
Build: &build.Context{
@@ -172,12 +207,12 @@ func Compile(pkgName string, machine llvm.TargetMachine, config *compileopts.Con
err = lprogram.Load(pkgName)
if err != nil {
return c.mod, nil, []error{err}
return c.mod, nil, nil, []error{err}
}
err = lprogram.Parse()
if err != nil {
return c.mod, nil, []error{err}
return c.mod, nil, nil, []error{err}
}
c.ir = ir.NewProgram(lprogram)
@@ -185,7 +220,7 @@ func Compile(pkgName string, machine llvm.TargetMachine, config *compileopts.Con
// Run a simple dead code elimination pass.
err = c.ir.SimpleDCE()
if err != nil {
return c.mod, nil, []error{err}
return c.mod, nil, nil, []error{err}
}
// Initialize debug information.
@@ -258,6 +293,8 @@ func Compile(pkgName string, machine llvm.TargetMachine, config *compileopts.Con
pos := c.ir.Program.Fset.Position(initFn.Pos())
irbuilder.SetCurrentDebugLocation(uint(pos.Line), uint(pos.Column), difunc, llvm.Metadata{})
}
initFn.LLVMFn.Param(0).SetName("context")
initFn.LLVMFn.Param(1).SetName("parentHandle")
block := c.ctx.AddBasicBlock(initFn.LLVMFn, "entry")
irbuilder.SetInsertPointAtEnd(block)
for _, fn := range initFuncs {
@@ -332,7 +369,7 @@ func Compile(pkgName string, machine llvm.TargetMachine, config *compileopts.Con
}
}
return c.mod, extraFiles, c.diagnostics
return c.mod, extraFiles, lprogram.LDFlags, c.diagnostics
}
// getLLVMRuntimeType obtains a named type from the runtime package and returns
@@ -1053,7 +1090,7 @@ func (b *builder) createInstruction(instr ssa.Instruction) {
// goroutine:
// * The function context, for closures.
// * The function pointer (for tasks).
funcPtr, context := b.decodeFuncValue(b.getValue(instr.Call.Value), instr.Call.Value.Type().(*types.Signature))
funcPtr, context := b.decodeFuncValue(b.getValue(instr.Call.Value), instr.Call.Value.Type().Underlying().(*types.Signature))
params = append(params, context) // context parameter
switch b.Scheduler() {
case "none", "coroutines":
@@ -1150,9 +1187,7 @@ func (b *builder) createBuiltin(args []ssa.Value, callName string, pos token.Pos
var llvmCap llvm.Value
switch args[0].Type().(type) {
case *types.Chan:
// Channel. Buffered channels haven't been implemented yet so always
// return 0.
llvmCap = llvm.ConstInt(b.intType, 0, false)
llvmCap = b.createRuntimeCall("chanCap", []llvm.Value{value}, "cap")
case *types.Slice:
llvmCap = b.CreateExtractValue(value, 2, "cap")
default:
@@ -1208,9 +1243,7 @@ func (b *builder) createBuiltin(args []ssa.Value, callName string, pos token.Pos
// string or slice
llvmLen = b.CreateExtractValue(value, 1, "len")
case *types.Chan:
// Channel. Buffered channels haven't been implemented yet so always
// return 0.
llvmLen = llvm.ConstInt(b.intType, 0, false)
llvmLen = b.createRuntimeCall("chanLen", []llvm.Value{value}, "len")
case *types.Map:
llvmLen = b.createRuntimeCall("hashmapLen", []llvm.Value{value}, "len")
default:
@@ -1313,9 +1346,9 @@ func (b *builder) createFunctionCall(instr *ssa.CallCommon) (llvm.Value, error)
return b.createMemoryCopyCall(fn, instr.Args)
case name == "runtime.memzero":
return b.createMemoryZeroCall(instr.Args)
case name == "device/arm.Asm" || name == "device/avr.Asm" || name == "device/riscv.Asm":
case name == "device.Asm" || name == "device/arm.Asm" || name == "device/avr.Asm" || name == "device/riscv.Asm":
return b.createInlineAsm(instr.Args)
case name == "device/arm.AsmFull" || name == "device/avr.AsmFull" || name == "device/riscv.AsmFull":
case name == "device.AsmFull" || name == "device/arm.AsmFull" || name == "device/avr.AsmFull" || name == "device/riscv.AsmFull":
return b.createInlineAsmFull(instr)
case strings.HasPrefix(name, "device/arm.SVCall"):
return b.emitSVCall(instr.Args)
@@ -1327,6 +1360,14 @@ func (b *builder) createFunctionCall(instr *ssa.CallCommon) (llvm.Value, error)
return b.createVolatileLoad(instr)
case strings.HasPrefix(name, "runtime/volatile.Store"):
return b.createVolatileStore(instr)
case strings.HasPrefix(name, "sync/atomic."):
val, ok := b.createAtomicOp(instr)
if ok {
// This call could be lowered as an atomic operation.
return val, nil
}
// This call couldn't be lowered as an atomic operation, it's
// probably something else. Continue as usual.
case name == "runtime/interrupt.New":
return b.createInterruptGlobal(instr)
}
@@ -1520,7 +1561,7 @@ func (b *builder) createExpr(expr ssa.Value) (llvm.Value, error) {
index := b.getValue(expr.Index)
// Check bounds.
arrayLen := expr.X.Type().(*types.Array).Len()
arrayLen := expr.X.Type().Underlying().(*types.Array).Len()
arrayLenLLVM := llvm.ConstInt(b.uintptrType, uint64(arrayLen), false)
b.createLookupBoundsCheck(arrayLenLLVM, index, expr.Index.Type())
@@ -1632,8 +1673,8 @@ func (b *builder) createExpr(expr ssa.Value) (llvm.Value, error) {
}
// Bounds checking.
lenType := expr.Len.Type().(*types.Basic)
capType := expr.Cap.Type().(*types.Basic)
lenType := expr.Len.Type().Underlying().(*types.Basic)
capType := expr.Cap.Type().Underlying().(*types.Basic)
b.createSliceBoundsCheck(maxSize, sliceLen, sliceCap, sliceCap, lenType, capType, capType)
// Allocate the backing array.
@@ -2514,7 +2555,7 @@ func (b *builder) createConvert(typeFrom, typeTo types.Type, value llvm.Value, p
return llvm.Value{}, b.makeError(pos, "todo: convert: basic non-integer type: "+typeFrom.String()+" -> "+typeTo.String())
case *types.Slice:
if basic, ok := typeFrom.(*types.Basic); !ok || basic.Info()&types.IsString == 0 {
if basic, ok := typeFrom.Underlying().(*types.Basic); !ok || basic.Info()&types.IsString == 0 {
panic("can only convert from a string to a slice")
}
+109 -14
View File
@@ -16,6 +16,7 @@ package compiler
import (
"github.com/tinygo-org/tinygo/compiler/llvmutil"
"github.com/tinygo-org/tinygo/ir"
"go/types"
"golang.org/x/tools/go/ssa"
"tinygo.org/x/go-llvm"
)
@@ -28,6 +29,8 @@ func (b *builder) deferInitFunc() {
b.deferFuncs = make(map[*ir.Function]int)
b.deferInvokeFuncs = make(map[string]int)
b.deferClosureFuncs = make(map[*ir.Function]int)
b.deferExprFuncs = make(map[ssa.Value]int)
b.deferBuiltinFuncs = make(map[ssa.Value]deferBuiltin)
// Create defer list pointer.
deferType := llvm.PointerType(b.getLLVMRuntimeType("_defer"), 0)
@@ -151,9 +154,54 @@ func (b *builder) createDefer(instr *ssa.Defer) {
values = append(values, context)
valueTypes = append(valueTypes, context.Type())
} else if builtin, ok := instr.Call.Value.(*ssa.Builtin); ok {
var funcName string
switch builtin.Name() {
case "close":
funcName = "chanClose"
default:
b.addError(instr.Pos(), "todo: Implement defer for "+builtin.Name())
return
}
if _, ok := b.deferBuiltinFuncs[instr.Call.Value]; !ok {
b.deferBuiltinFuncs[instr.Call.Value] = deferBuiltin{
funcName,
len(b.allDeferFuncs),
}
b.allDeferFuncs = append(b.allDeferFuncs, instr.Call.Value)
}
callback := llvm.ConstInt(b.uintptrType, uint64(b.deferBuiltinFuncs[instr.Call.Value].callback), false)
// Collect all values to be put in the struct (starting with
// runtime._defer fields).
values = []llvm.Value{callback, next}
for _, param := range instr.Call.Args {
llvmParam := b.getValue(param)
values = append(values, llvmParam)
valueTypes = append(valueTypes, llvmParam.Type())
}
} else {
b.addError(instr.Pos(), "todo: defer on uncommon function call type")
return
funcValue := b.getValue(instr.Call.Value)
if _, ok := b.deferExprFuncs[instr.Call.Value]; !ok {
b.deferExprFuncs[instr.Call.Value] = len(b.allDeferFuncs)
b.allDeferFuncs = append(b.allDeferFuncs, &instr.Call)
}
callback := llvm.ConstInt(b.uintptrType, uint64(b.deferExprFuncs[instr.Call.Value]), false)
// Collect all values to be put in the struct (starting with
// runtime._defer fields, followed by all parameters including the
// context pointer).
values = []llvm.Value{callback, next, funcValue}
valueTypes = append(valueTypes, funcValue.Type())
for _, param := range instr.Call.Args {
llvmParam := b.getValue(param)
values = append(values, llvmParam)
valueTypes = append(valueTypes, llvmParam.Type())
}
}
// Make a struct out of the collected values to put in the defer frame.
@@ -243,16 +291,23 @@ func (b *builder) createRunDefers() {
b.SetInsertPointAtEnd(block)
switch callback := callback.(type) {
case *ssa.CallCommon:
// Call on an interface value.
if !callback.IsInvoke() {
panic("expected an invoke call, not a direct call")
}
// Call on an value or interface value.
// Get the real defer struct type and cast to it.
valueTypes := []llvm.Type{b.uintptrType, llvm.PointerType(b.getLLVMRuntimeType("_defer"), 0), b.uintptrType, b.i8ptrType}
valueTypes := []llvm.Type{b.uintptrType, llvm.PointerType(b.getLLVMRuntimeType("_defer"), 0)}
if !callback.IsInvoke() {
//Expect funcValue to be passed through the defer frame.
valueTypes = append(valueTypes, b.getFuncType(callback.Signature()))
} else {
//Expect typecode
valueTypes = append(valueTypes, b.uintptrType, b.i8ptrType)
}
for _, arg := range callback.Args {
valueTypes = append(valueTypes, b.getLLVMType(arg.Type()))
}
deferFrameType := b.ctx.StructType(valueTypes, false)
deferFramePtr := b.CreateBitCast(deferData, llvm.PointerType(deferFrameType, 0), "deferFrame")
@@ -265,18 +320,34 @@ func (b *builder) createRunDefers() {
forwardParams = append(forwardParams, forwardParam)
}
// Isolate the typecode.
typecode, forwardParams := forwardParams[0], forwardParams[1:]
var fnPtr llvm.Value
// Add the context parameter. An interface call cannot also be a
// closure but we have to supply the parameter anyway for platforms
// with a strict calling convention.
forwardParams = append(forwardParams, llvm.Undef(b.i8ptrType))
if !callback.IsInvoke() {
// Isolate the func value.
funcValue := forwardParams[0]
forwardParams = forwardParams[1:]
//Get function pointer and context
fp, context := b.decodeFuncValue(funcValue, callback.Signature())
fnPtr = fp
//Pass context
forwardParams = append(forwardParams, context)
} else {
// Isolate the typecode.
typecode := forwardParams[0]
forwardParams = forwardParams[1:]
fnPtr = b.getInvokePtr(callback, typecode)
// Add the context parameter. An interface call cannot also be a
// closure but we have to supply the parameter anyway for platforms
// with a strict calling convention.
forwardParams = append(forwardParams, llvm.Undef(b.i8ptrType))
}
// Parent coroutine handle.
forwardParams = append(forwardParams, llvm.Undef(b.i8ptrType))
fnPtr := b.getInvokePtr(callback, typecode)
b.createCall(fnPtr, forwardParams, "")
case *ir.Function:
@@ -339,7 +410,31 @@ func (b *builder) createRunDefers() {
// Call deferred function.
b.createCall(fn.LLVMFn, forwardParams, "")
case *ssa.Builtin:
db := b.deferBuiltinFuncs[callback]
//Get parameter types
valueTypes := []llvm.Type{b.uintptrType, llvm.PointerType(b.getLLVMRuntimeType("_defer"), 0)}
//Get signature from call results
params := callback.Type().Underlying().(*types.Signature).Params()
for i := 0; i < params.Len(); i++ {
valueTypes = append(valueTypes, b.getLLVMType(params.At(i).Type()))
}
deferFrameType := b.ctx.StructType(valueTypes, false)
deferFramePtr := b.CreateBitCast(deferData, llvm.PointerType(deferFrameType, 0), "deferFrame")
// Extract the params from the struct.
var forwardParams []llvm.Value
zero := llvm.ConstInt(b.ctx.Int32Type(), 0, false)
for i := 0; i < params.Len(); i++ {
gep := b.CreateInBoundsGEP(deferFramePtr, []llvm.Value{zero, llvm.ConstInt(b.ctx.Int32Type(), uint64(i+2), false)}, "gep")
forwardParam := b.CreateLoad(gep, "param")
forwardParams = append(forwardParams, forwardParam)
}
b.createRuntimeCall(db.funcName, forwardParams, "")
default:
panic("unknown deferred function type")
}
+4 -3
View File
@@ -4,10 +4,11 @@ go 1.11
require (
github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2
github.com/chromedp/cdproto v0.0.0-20200116234248-4da64dd111ac
github.com/chromedp/chromedp v0.5.3
github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf
github.com/marcinbor85/gohex v0.0.0-20180128172054-7a43cd876e46
github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892
go.bug.st/serial v1.0.0
golang.org/x/tools v0.0.0-20200216192241-b320d3a0f5a2
google.golang.org/appengine v1.4.0 // indirect
tinygo.org/x/go-llvm v0.0.0-20200401165421-8d120882fc7a
tinygo.org/x/go-llvm v0.0.0-20200503225853-345b2947b59d
)
+20 -29
View File
@@ -1,13 +1,26 @@
github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2 h1:oMCHnXa6CCCafdPDbMh/lWRhRByN0VFLvv+g+ayx1SI=
github.com/blakesmith/ar v0.0.0-20150311145944-8bd4349a67f2/go.mod h1:PkYb9DJNAwrSvRx5DYA+gUcOIgTGVMNkfSCbZM8cWpI=
github.com/chromedp/cdproto v0.0.0-20200116234248-4da64dd111ac h1:T7V5BXqnYd55Hj/g5uhDYumg9Fp3rMTS6bykYtTIFX4=
github.com/chromedp/cdproto v0.0.0-20200116234248-4da64dd111ac/go.mod h1:PfAWWKJqjlGFYJEidUM6aVIWPr0EpobeyVWEEmplX7g=
github.com/chromedp/chromedp v0.5.3 h1:F9LafxmYpsQhWQBdCs+6Sret1zzeeFyHS5LkRF//Ffg=
github.com/chromedp/chromedp v0.5.3/go.mod h1:YLdPtndaHQ4rCpSpBG+IPpy9JvX0VD+7aaLxYgYj28w=
github.com/creack/goselect v0.1.1 h1:tiSSgKE1eJtxs1h/VgGQWuXUP0YS4CDIFMp6vaI1ls0=
github.com/creack/goselect v0.1.1/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0=
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo=
github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8=
github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo=
github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM=
github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf h1:7+FW5aGwISbqUtkfmIpZJGRgNFg2ioYPvFaUxdqpDsg=
github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf/go.mod h1:RpwtwJQFrIEPstU94h88MWPXP2ektJZ8cZ0YntAmXiE=
github.com/marcinbor85/gohex v0.0.0-20180128172054-7a43cd876e46 h1:wXG2bA8fO7Vv7lLk2PihFMTqmbT173Tje39oKzQ50Mo=
github.com/marcinbor85/gohex v0.0.0-20180128172054-7a43cd876e46/go.mod h1:Pb6XcsXyropB9LNHhnqaknG/vEwYztLkQzVCHv8sQ3M=
github.com/knq/sysutil v0.0.0-20191005231841-15668db23d08 h1:V0an7KRw92wmJysvFvtqtKMAPmvS5O0jtB0nYo6t+gs=
github.com/knq/sysutil v0.0.0-20191005231841-15668db23d08/go.mod h1:dFWs1zEqDjFtnBXsd1vPOZaLsESovai349994nHx3e0=
github.com/mailru/easyjson v0.7.0 h1:aizVhC/NAAcKWb+5QsU1iNOZb4Yws5UO2I+aIprQITM=
github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs=
github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892 h1:6J+qramlHVLmiBOgRiBOnQkno8uprqG6YFFQTt6uYIw=
github.com/marcinbor85/gohex v0.0.0-20200531091804-343a4b548892/go.mod h1:Pb6XcsXyropB9LNHhnqaknG/vEwYztLkQzVCHv8sQ3M=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
@@ -17,43 +30,21 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9 h1:ZBzSG/7F4eNKz2L3GE9o300RX0Az1Bw5HF7PDraD+qU=
golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190227180812-8dcc6e70cdef h1:ymc9FeDom3RIEA3coKokSllBB1hRcMT0tZ1W3Jf9Ids=
golang.org/x/tools v0.0.0-20190227180812-8dcc6e70cdef/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20200216192241-b320d3a0f5a2 h1:0sfSpGSa544Fwnbot3Oxq/U6SXqjty6Jy/3wRhVS7ig=
golang.org/x/tools v0.0.0-20200216192241-b320d3a0f5a2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
tinygo.org/x/go-llvm v0.0.0-20190224120431-7707ae5d1261 h1:rJS2Hga39YAnm7DE4qrPm6Dr/67EOojL0XPzvbEeBiw=
tinygo.org/x/go-llvm v0.0.0-20190224120431-7707ae5d1261/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20190818154551-95bc4ffe1add h1:dFjMH1sLhYADg8UQm7DB56B7e+TfvAmWmEZLhyv3r/w=
tinygo.org/x/go-llvm v0.0.0-20190818154551-95bc4ffe1add/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20191103182207-90b6e4bdc0b9 h1:d6rAX39a3C0pKrY5HcojEGyN8w9ocU0v7X28lC/TRKU=
tinygo.org/x/go-llvm v0.0.0-20191103182207-90b6e4bdc0b9/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20191103200204-37e93e3f04e2 h1:Q5Hv3e5cLMGkiYwYgZL1Zrv6nb/EY+DJpRWrdO6ws6o=
tinygo.org/x/go-llvm v0.0.0-20191103200204-37e93e3f04e2/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20191113125529-bad6d01809e8 h1:9Bfvso+tTVQg16UzOA614NaYA4x8vsRBNtd3eBrXwp0=
tinygo.org/x/go-llvm v0.0.0-20191113125529-bad6d01809e8/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20191124211856-b2db3df3f257 h1:o8VDylrMN7gWemBMu8rEyuogKPhcLTdx5KrUAp9macc=
tinygo.org/x/go-llvm v0.0.0-20191124211856-b2db3df3f257/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20191215173731-ad71f3d24aae h1:s8J5EyxCkHxXB08UI3gk9W9IS/ekizRvSX+PfZxnAB0=
tinygo.org/x/go-llvm v0.0.0-20191215173731-ad71f3d24aae/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20200104190746-1ff21df33566 h1:a4y30bTf7U0zDA75v2PTL+XQ2OzJetj19gK8XwQpUNY=
tinygo.org/x/go-llvm v0.0.0-20200104190746-1ff21df33566/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20200226165415-53522ab6713d h1:mtgZh/e8a3wxneQFuLXoQYO//1mvlki02yZ1JCwMKp4=
tinygo.org/x/go-llvm v0.0.0-20200226165415-53522ab6713d/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20200401165421-8d120882fc7a h1:Ugje2Lxuv8CFncHzs5W+hWfJvPsM+W4K0zRvzFbLvoE=
tinygo.org/x/go-llvm v0.0.0-20200401165421-8d120882fc7a/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
tinygo.org/x/go-llvm v0.0.0-20200503225853-345b2947b59d h1:hcX7vpB067GWM/EH4sGGOti0PMgIx+0bbZwUXctOIvE=
tinygo.org/x/go-llvm v0.0.0-20200503225853-345b2947b59d/go.mod h1:fv1F0BSNpxMfCL0zF3M4OPFbgYHnhtB6ST0HvUtu/LE=
+4
View File
@@ -10,6 +10,10 @@ import (
"strings"
)
// Version of TinyGo.
// Update this value before release of new version of software.
const Version = "0.14.1"
// GetGorootVersion returns the major and minor version for a given GOROOT path.
// If the goroot cannot be determined, (0, 0) is returned.
func GetGorootVersion(goroot string) (major, minor int, err error) {
+5
View File
@@ -0,0 +1,5 @@
# Hooks for Docker Hub
Files in this directory are custom commands to be run during the different Docker Hub build phases.
See https://docs.docker.com/docker-hub/builds/advanced/#custom-build-phase-hooks
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
# Docker hub does a recursive clone, then checks the branch out,
# so when a PR adds a submodule (or updates it), it fails.
git submodule update --init
+6
View File
@@ -62,6 +62,10 @@ func (e *evalPackage) hasSideEffects(fn llvm.Value) (*sideEffectResult, *Error)
return &sideEffectResult{severity: sideEffectNone}, nil
case name == "llvm.dbg.value":
return &sideEffectResult{severity: sideEffectNone}, nil
case name == "(*sync/atomic.Value).Load" || name == "(*sync/atomic.Value).Store":
// These functions do some unsafe pointer loading/storing but are
// otherwise safe.
return &sideEffectResult{severity: sideEffectLimited}, nil
case strings.HasPrefix(name, "llvm.lifetime."):
return &sideEffectResult{severity: sideEffectNone}, nil
}
@@ -122,6 +126,8 @@ func (e *evalPackage) hasSideEffects(fn llvm.Value) (*sideEffectResult, *Error)
// External function call. Assume only limited side effects
// (no affected globals, etc.).
switch child.Name() {
case "runtime.alloc":
continue
case "runtime.typeAssert":
continue // implemented in interp
case "runtime.interfaceImplements":
+2 -40
View File
@@ -67,48 +67,10 @@ func NewProgram(lprogram *loader.Program) *Program {
program := lprogram.LoadSSA()
program.Build()
// Find the main package, which is a bit difficult when running a .go file
// directly.
mainPkg := program.ImportedPackage(lprogram.MainPkg.PkgPath)
if mainPkg == nil {
panic("could not find main package")
}
// Make a list of packages in import order.
packageList := []*ssa.Package{}
packageSet := map[string]struct{}{}
worklist := []string{"runtime", lprogram.MainPkg.PkgPath}
for len(worklist) != 0 {
pkgPath := worklist[0]
pkg := program.ImportedPackage(pkgPath)
if _, ok := packageSet[pkgPath]; ok {
// Package already in the final package list.
worklist = worklist[1:]
continue
}
unsatisfiedImports := make([]string, 0)
imports := pkg.Pkg.Imports()
for _, pkg := range imports {
if _, ok := packageSet[pkg.Path()]; ok {
continue
}
unsatisfiedImports = append(unsatisfiedImports, pkg.Path())
}
if len(unsatisfiedImports) == 0 {
// All dependencies of this package are satisfied, so add this
// package to the list.
packageList = append(packageList, pkg)
packageSet[pkgPath] = struct{}{}
worklist = worklist[1:]
} else {
// Prepend all dependencies to the worklist and reconsider this
// package (by not removing it from the worklist). At that point, it
// must be possible to add it to packageList.
worklist = append(unsatisfiedImports, worklist...)
}
}
p := &Program{
Program: program,
LoaderProgram: lprogram,
@@ -116,8 +78,8 @@ func NewProgram(lprogram *loader.Program) *Program {
functionMap: make(map[*ssa.Function]*Function),
}
for _, pkg := range packageList {
p.AddPackage(pkg)
for _, pkg := range lprogram.Sorted() {
p.AddPackage(program.ImportedPackage(pkg.PkgPath))
}
return p
+45 -12
View File
@@ -7,6 +7,8 @@ import (
"crypto/sha512"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
@@ -32,22 +34,24 @@ func GetCachedGoroot(config *compileopts.Config) (string, error) {
return "", errors.New("could not determine TINYGOROOT")
}
needsSyscallPackage := false
for _, tag := range config.BuildTags() {
if tag == "baremetal" || tag == "darwin" {
needsSyscallPackage = true
}
}
// Determine the location of the cached GOROOT.
version, err := goenv.GorootVersionString(goroot)
if err != nil {
return "", err
}
gorootsHash := sha512.Sum512_256([]byte(goroot + "\x00" + tinygoroot))
// This hash is really a cache key, that contains (hopefully) enough
// information to make collisions unlikely during development.
// By including the Go version and TinyGo version, cache collisions should
// not happen outside of development.
hash := sha512.New512_256()
fmt.Fprintln(hash, goroot)
fmt.Fprintln(hash, version)
fmt.Fprintln(hash, goenv.Version)
fmt.Fprintln(hash, tinygoroot)
gorootsHash := hash.Sum(nil)
gorootsHashHex := hex.EncodeToString(gorootsHash[:])
cachedgoroot := filepath.Join(goenv.Get("GOCACHE"), "goroot-"+version+"-"+gorootsHashHex)
if needsSyscallPackage {
if needsSyscallPackage(config.BuildTags()) {
cachedgoroot += "-syscall"
}
@@ -70,7 +74,7 @@ func GetCachedGoroot(config *compileopts.Config) (string, error) {
return "", err
}
}
err = mergeDirectory(goroot, tinygoroot, tmpgoroot, "", pathsToOverride(needsSyscallPackage))
err = mergeDirectory(goroot, tinygoroot, tmpgoroot, "", pathsToOverride(needsSyscallPackage(config.BuildTags())))
if err != nil {
return "", err
}
@@ -158,6 +162,17 @@ func mergeDirectory(goroot, tinygoroot, tmpgoroot, importPath string, overrides
return nil
}
// needsSyscallPackage returns whether the syscall package should be overriden
// with the TinyGo version. This is the case on some targets.
func needsSyscallPackage(buildTags []string) bool {
for _, tag := range buildTags {
if tag == "baremetal" || tag == "darwin" || tag == "nintendoswitch" {
return true
}
}
return false
}
// The boolean indicates whether to merge the subdirs. True means merge, false
// means use the TinyGo version.
func pathsToOverride(needsSyscallPackage bool) map[string]bool {
@@ -166,6 +181,7 @@ func pathsToOverride(needsSyscallPackage bool) map[string]bool {
"device/": false,
"examples/": false,
"internal/": true,
"internal/bytealg/": false,
"internal/reflectlite/": false,
"internal/task/": false,
"machine/": false,
@@ -213,10 +229,27 @@ func symlink(oldname, newname string) error {
return symlinkErr
}
} else {
// Make a hard link.
// Try making a hard link.
err := os.Link(oldname, newname)
if err != nil {
return symlinkErr
// Making a hardlink failed. Try copying the file as a last
// fallback.
inf, err := os.Open(oldname)
if err != nil {
return err
}
defer inf.Close()
outf, err := os.Create(newname)
if err != nil {
return err
}
defer outf.Close()
_, err = io.Copy(outf, inf)
if err != nil {
os.Remove(newname)
return err
}
// File was copied.
}
}
return nil // success
+57 -18
View File
@@ -7,11 +7,13 @@ import (
"go/ast"
"go/build"
"go/parser"
"go/scanner"
"go/token"
"go/types"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"text/template"
@@ -32,6 +34,7 @@ type Program struct {
Dir string // current working directory (for error reporting)
TINYGOROOT string // root of the TinyGo installation or root of the source code
CFlags []string
LDFlags []string
ClangHeaders string
}
@@ -115,7 +118,26 @@ func (p *Program) loadPackage(importPath string) error {
Pkg: pkg2,
}
for _, err := range pkg.Errors {
importError.Errs = append(importError.Errs, err)
pos := token.Position{}
fields := strings.Split(err.Pos, ":")
if len(fields) >= 2 {
// There is some file/line/column information.
if n, err := strconv.Atoi(fields[len(fields)-2]); err == nil {
// Format: filename.go:line:colum
pos.Filename = strings.Join(fields[:len(fields)-2], ":")
pos.Line = n
pos.Column, _ = strconv.Atoi(fields[len(fields)-1])
} else {
// Format: filename.go:line
pos.Filename = strings.Join(fields[:len(fields)-1], ":")
pos.Line, _ = strconv.Atoi(fields[len(fields)-1])
}
pos.Filename = p.getOriginalPath(pos.Filename)
}
importError.Errs = append(importError.Errs, scanner.Error{
Pos: pos,
Msg: err.Msg,
})
}
return
}
@@ -136,11 +158,41 @@ func (p *Program) loadPackage(importPath string) error {
}
addPackages(pkg)
if importError != nil {
return importError
return *importError
}
return nil
}
// getOriginalPath looks whether this path is in the generated GOROOT and if so,
// replaces the path with the original path (in GOROOT or TINYGOROOT). Otherwise
// the input path is returned.
func (p *Program) getOriginalPath(path string) string {
originalPath := path
if strings.HasPrefix(path, p.Build.GOROOT+string(filepath.Separator)) {
// If this file is part of the synthetic GOROOT, try to infer the
// original path.
relpath := path[len(filepath.Join(p.Build.GOROOT, "src"))+1:]
realgorootPath := filepath.Join(goenv.Get("GOROOT"), "src", relpath)
if _, err := os.Stat(realgorootPath); err == nil {
originalPath = realgorootPath
}
maybeInTinyGoRoot := false
for prefix := range pathsToOverride(needsSyscallPackage(p.Build.BuildTags)) {
if !strings.HasPrefix(relpath, prefix) {
continue
}
maybeInTinyGoRoot = true
}
if maybeInTinyGoRoot {
tinygoPath := filepath.Join(p.TINYGOROOT, "src", relpath)
if _, err := os.Stat(tinygoPath); err == nil {
originalPath = tinygoPath
}
}
}
return originalPath
}
// newPackage instantiates a new *Package object with initialized members.
func (p *Program) newPackage(pkg *packages.Package) *Package {
return &Package{
@@ -282,21 +334,7 @@ func (p *Program) parseFile(path string, mode parser.Mode) (*ast.File, error) {
return nil, err
}
defer rd.Close()
diagnosticPath := path
if strings.HasPrefix(path, p.Build.GOROOT+string(filepath.Separator)) {
// If this file is part of the synthetic GOROOT, try to infer the
// original path.
relpath := path[len(p.Build.GOROOT)+1:]
tinygoPath := filepath.Join(p.TINYGOROOT, relpath)
if _, err := os.Stat(tinygoPath); err == nil {
diagnosticPath = tinygoPath
}
realgorootPath := filepath.Join(goenv.Get("GOROOT"), relpath)
if _, err := os.Stat(realgorootPath); err == nil {
diagnosticPath = realgorootPath
}
}
return parser.ParseFile(p.fset, diagnosticPath, rd, mode)
return parser.ParseFile(p.fset, p.getOriginalPath(path), rd, mode)
}
// Parse parses and typechecks this package.
@@ -383,11 +421,12 @@ func (p *Package) parseFiles() ([]*ast.File, error) {
if p.ClangHeaders != "" {
cflags = append(cflags, "-Xclang", "-internal-isystem", "-Xclang", p.ClangHeaders)
}
generated, errs := cgo.Process(files, p.Program.Dir, p.fset, cflags)
generated, ldflags, errs := cgo.Process(files, p.Program.Dir, p.fset, cflags)
if errs != nil {
fileErrs = append(fileErrs, errs...)
}
files = append(files, generated)
p.LDFlags = append(p.LDFlags, ldflags...)
}
if len(fileErrs) != 0 {
return nil, Errors{p, fileErrs}
+98 -70
View File
@@ -2,7 +2,6 @@ package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
@@ -480,6 +479,13 @@ func touchSerialPortAt1200bps(port string) (err error) {
// Open port
p, e := serial.Open(port, &serial.Mode{BaudRate: 1200})
if e != nil {
if runtime.GOOS == `windows` {
se, ok := e.(*serial.PortError)
if ok && se.Code() == serial.InvalidSerialPort {
// InvalidSerialPort error occurs when transitioning to boot
return nil
}
}
time.Sleep(1 * time.Second)
err = e
continue
@@ -492,6 +498,8 @@ func touchSerialPortAt1200bps(port string) (err error) {
return fmt.Errorf("opening port: %s", err)
}
const maxMSDRetries = 10
func flashUF2UsingMSD(volume, tmppath string) error {
// find standard UF2 info path
var infoPath string
@@ -508,15 +516,12 @@ func flashUF2UsingMSD(volume, tmppath string) error {
infoPath = path + "/INFO_UF2.TXT"
}
d, err := filepath.Glob(infoPath)
d, err := locateDevice(volume, infoPath)
if err != nil {
return err
}
if d == nil {
return errors.New("unable to locate UF2 device: " + volume)
}
return moveFile(tmppath, filepath.Dir(d[0])+"/flash.uf2")
return moveFile(tmppath, filepath.Dir(d)+"/flash.uf2")
}
func flashHexUsingMSD(volume, tmppath string) error {
@@ -535,15 +540,31 @@ func flashHexUsingMSD(volume, tmppath string) error {
destPath = path + "/"
}
d, err := filepath.Glob(destPath)
d, err := locateDevice(volume, destPath)
if err != nil {
return err
}
if d == nil {
return errors.New("unable to locate device: " + volume)
}
return moveFile(tmppath, d[0]+"/flash.hex")
return moveFile(tmppath, d+"/flash.hex")
}
func locateDevice(volume, path string) (string, error) {
var d []string
var err error
for i := 0; i < maxMSDRetries; i++ {
d, err = filepath.Glob(path)
if err != nil {
return "", err
}
if d != nil {
break
}
time.Sleep(500 * time.Millisecond)
}
if d == nil {
return "", errors.New("unable to locate device: " + volume)
}
return d[0], nil
}
func windowsFindUSBDrive(volume string) (string, error) {
@@ -604,29 +625,18 @@ func getDefaultPort() (port string, err error) {
case "freebsd":
portPath = "/dev/cuaU*"
case "windows":
cmd := exec.Command("wmic",
"PATH", "Win32_SerialPort", "WHERE", "Caption LIKE 'USB Serial%'", "GET", "DeviceID")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
ports, err := serial.GetPortsList()
if err != nil {
return "", err
}
if out.String() == "No Instance(s) Available." {
if len(ports) == 0 {
return "", errors.New("no serial ports available")
} else if len(ports) > 1 {
return "", errors.New("multiple serial ports available - use -port flag")
}
for _, line := range strings.Split(out.String(), "\n") {
words := strings.Fields(line)
if len(words) == 1 {
if strings.Contains(words[0], "COM") {
return words[0], nil
}
}
}
return "", errors.New("unable to locate a serial port")
return ports[0], nil
default:
return "", errors.New("unable to search for a default USB device to be flashed on this OS")
}
@@ -674,7 +684,7 @@ func runGoList(config *compileopts.Config, flagJSON, flagDeps bool, pkgs []strin
func usage() {
fmt.Fprintln(os.Stderr, "TinyGo is a Go compiler for small places.")
fmt.Fprintln(os.Stderr, "version:", version)
fmt.Fprintln(os.Stderr, "version:", goenv.Version)
fmt.Fprintf(os.Stderr, "usage: %s command [-printir] [-target=<target>] -o <output> <input>\n", os.Args[0])
fmt.Fprintln(os.Stderr, "\ncommands:")
fmt.Fprintln(os.Stderr, " build: compile packages and dependencies")
@@ -690,6 +700,20 @@ func usage() {
flag.PrintDefaults()
}
// try to make the path relative to the current working directory. If any error
// occurs, this error is ignored and the absolute path is returned instead.
func tryToMakePathRelative(dir string) string {
wd, err := os.Getwd()
if err != nil {
return dir
}
relpath, err := filepath.Rel(wd, dir)
if err != nil {
return dir
}
return relpath
}
// printCompilerError prints compiler errors using the provided logger function
// (similar to fmt.Println).
//
@@ -697,8 +721,24 @@ func usage() {
// to limitations in the LLVM bindings.
func printCompilerError(logln func(...interface{}), err error) {
switch err := err.(type) {
case types.Error, scanner.Error:
case types.Error:
printCompilerError(logln, scanner.Error{
Pos: err.Fset.Position(err.Pos),
Msg: err.Msg,
})
case scanner.Error:
if !strings.HasPrefix(err.Pos.Filename, filepath.Join(goenv.Get("GOROOT"), "src")) && !strings.HasPrefix(err.Pos.Filename, filepath.Join(goenv.Get("TINYGOROOT"), "src")) {
// This file is not from the standard library (either the GOROOT or
// the TINYGOROOT). Make the path relative, for easier reading.
// Ignore any errors in the process (falling back to the absolute
// path).
err.Pos.Filename = tryToMakePathRelative(err.Pos.Filename)
}
logln(err)
case scanner.ErrorList:
for _, scannerErr := range err {
printCompilerError(logln, *scannerErr)
}
case *interp.Error:
logln("#", err.ImportPath)
logln(err.Error())
@@ -717,11 +757,11 @@ func printCompilerError(logln func(...interface{}), err error) {
case loader.Errors:
logln("#", err.Pkg.PkgPath)
for _, err := range err.Errs {
logln(err)
printCompilerError(logln, err)
}
case *builder.MultiError:
for _, err := range err.Errs {
logln(err)
printCompilerError(logln, err)
}
default:
logln("error:", err)
@@ -749,13 +789,14 @@ func main() {
opt := flag.String("opt", "z", "optimization level: 0, 1, 2, s, z")
gc := flag.String("gc", "", "garbage collector to use (none, leaking, extalloc, conservative)")
panicStrategy := flag.String("panic", "print", "panic strategy (print, trap)")
scheduler := flag.String("scheduler", "", "which scheduler to use (coroutines, tasks)")
scheduler := flag.String("scheduler", "", "which scheduler to use (none, coroutines, tasks)")
printIR := flag.Bool("printir", false, "print LLVM IR")
dumpSSA := flag.Bool("dumpssa", false, "dump internal Go SSA")
verifyIR := flag.Bool("verifyir", false, "run extra verification steps on LLVM IR")
tags := flag.String("tags", "", "a space-separated list of extra build tags")
target := flag.String("target", "", "LLVM target | .json file with TargetSpec")
printSize := flag.String("size", "", "print sizes (none, short, full)")
printStacks := flag.Bool("print-stacks", false, "print stack sizes of goroutines")
nodebug := flag.Bool("no-debug", false, "disable DWARF debug symbol generation")
ocdOutput := flag.Bool("ocd-output", false, "print OCD daemon output during debug")
port := flag.String("port", "", "flash port")
@@ -766,10 +807,8 @@ func main() {
heapSize := flag.String("heap-size", "1M", "default heap size in bytes (only supported by WebAssembly)")
var flagJSON, flagDeps *bool
if command == "list" || command == "env" {
flagJSON = flag.Bool("json", false, "print data in JSON format")
}
if command == "list" {
flagJSON = flag.Bool("json", false, "print data in JSON format")
flagDeps = flag.Bool("deps", false, "")
}
@@ -797,6 +836,7 @@ func main() {
VerifyIR: *verifyIR,
Debug: !*nodebug,
PrintSizes: *printSize,
PrintStacks: *printStacks,
Tags: *tags,
WasmAbi: *wasmAbi,
Programmer: *programmer,
@@ -810,12 +850,6 @@ func main() {
options.LDFlags = strings.Split(*ldFlags, " ")
}
if *panicStrategy != "print" && *panicStrategy != "trap" {
fmt.Fprintln(os.Stderr, "Panic strategy must be either print or trap.")
usage()
os.Exit(1)
}
var err error
if options.HeapSize, err = parseSize(*heapSize); err != nil {
fmt.Fprintln(os.Stderr, "Could not read heap size:", *heapSize)
@@ -825,6 +859,13 @@ func main() {
os.Setenv("CC", "clang -target="+*target)
err = options.Verify()
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
usage()
os.Exit(1)
}
switch command {
case "build":
if *outpath == "" {
@@ -834,7 +875,7 @@ func main() {
}
pkgName := "."
if flag.NArg() == 1 {
pkgName = flag.Arg(0)
pkgName = filepath.ToSlash(flag.Arg(0))
} else if flag.NArg() > 1 {
fmt.Fprintln(os.Stderr, "build only accepts a single positional argument: package name, but multiple were specified")
usage()
@@ -843,6 +884,7 @@ func main() {
if options.Target == "" && filepath.Ext(*outpath) == ".wasm" {
options.Target = "wasm"
}
err := Build(pkgName, *outpath, options)
handleCompilerError(err)
case "build-library":
@@ -879,8 +921,9 @@ func main() {
usage()
os.Exit(1)
}
pkgName := filepath.ToSlash(flag.Arg(0))
if command == "flash" {
err := Flash(flag.Arg(0), *port, options)
err := Flash(pkgName, *port, options)
handleCompilerError(err)
} else {
if !options.Debug {
@@ -888,7 +931,7 @@ func main() {
usage()
os.Exit(1)
}
err := FlashGDB(flag.Arg(0), *ocdOutput, options)
err := FlashGDB(pkgName, *ocdOutput, options)
handleCompilerError(err)
}
case "run":
@@ -897,12 +940,13 @@ func main() {
usage()
os.Exit(1)
}
err := Run(flag.Arg(0), options)
pkgName := filepath.ToSlash(flag.Arg(0))
err := Run(pkgName, options)
handleCompilerError(err)
case "test":
pkgName := "."
if flag.NArg() == 1 {
pkgName = flag.Arg(0)
pkgName = filepath.ToSlash(flag.Arg(0))
} else if flag.NArg() > 1 {
fmt.Fprintln(os.Stderr, "test only accepts a single positional argument: package name, but multiple were specified")
usage()
@@ -961,33 +1005,17 @@ func main() {
if s, err := goenv.GorootVersionString(goenv.Get("GOROOT")); err == nil {
goversion = s
}
fmt.Printf("tinygo version %s %s/%s (using go version %s and LLVM version %s)\n", version, runtime.GOOS, runtime.GOARCH, goversion, llvm.Version)
fmt.Printf("tinygo version %s %s/%s (using go version %s and LLVM version %s)\n", goenv.Version, runtime.GOOS, runtime.GOARCH, goversion, llvm.Version)
case "env":
if *flagJSON {
keys := goenv.Keys
if flag.NArg() != 0 {
// Show only one (or a few) environment variables.
keys = flag.Args()
if flag.NArg() == 0 {
// Show all environment variables.
for _, key := range goenv.Keys {
fmt.Printf("%s=%#v\n", key, goenv.Get(key))
}
// Show environment variables in JSON format.
env := make(map[string]string)
for _, key := range keys {
env[key] = goenv.Get(key)
}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", "\t")
encoder.Encode(env)
} else {
if flag.NArg() == 0 {
// Show all environment variables.
for _, key := range goenv.Keys {
fmt.Printf("%s=%#v\n", key, goenv.Get(key))
}
} else {
// Show only one (or a few) environment variables.
for i := 0; i < flag.NArg(); i++ {
fmt.Println(goenv.Get(flag.Arg(i)))
}
// Show only one (or a few) environment variables.
for i := 0; i < flag.NArg(); i++ {
fmt.Println(goenv.Get(flag.Arg(i)))
}
}
default:
+11
View File
@@ -6,6 +6,7 @@ package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
@@ -25,6 +26,8 @@ import (
const TESTDATA = "testdata"
var testTarget = flag.String("target", "", "override test target")
func TestCompiler(t *testing.T) {
matches, err := filepath.Glob(filepath.Join(TESTDATA, "*.go"))
if err != nil {
@@ -44,6 +47,14 @@ func TestCompiler(t *testing.T) {
sort.Strings(matches)
if *testTarget != "" {
// This makes it possible to run one specific test (instead of all),
// which is especially useful to quickly check whether some changes
// affect a particular target architecture.
runPlatTests(*testTarget, matches, t)
return
}
if runtime.GOOS != "windows" {
t.Run("Host", func(t *testing.T) {
runPlatTests("", matches, t)
+6 -1
View File
@@ -174,6 +174,11 @@ func EnableIRQ(irq uint32) {
NVIC.ISER[irq>>5].Set(1 << (irq & 0x1F))
}
// Disable the given interrupt number.
func DisableIRQ(irq uint32) {
NVIC.ICER[irq>>5].Set(1 << (irq & 0x1F))
}
// Set the priority of the given interrupt number.
// Note that the priority is given as a 0-255 number, where some of the lower
// bits are not implemented by the hardware. For example, to set a low interrupt
@@ -196,7 +201,7 @@ func SetPriority(irq uint32, priority uint32) {
func DisableInterrupts() uintptr {
return AsmFull(`
mrs {}, PRIMASK
cpsid if
cpsid i
`, nil)
}
+1
View File
@@ -19,6 +19,7 @@ HardFault_Handler:
// Continue handling this error in Go.
bl handleHardFault
.size HardFault_Handler, .-HardFault_Handler
// This is a convenience function for semihosting support.
// At some point, this should be replaced by inline assembly.
+21
View File
@@ -0,0 +1,21 @@
package device
// Run the given assembly code. The code will be marked as having side effects,
// as it doesn't produce output and thus would normally be eliminated by the
// optimizer.
func Asm(asm string)
// Run the given inline assembly. The code will be marked as having side
// effects, as it would otherwise be optimized away. The inline assembly string
// recognizes template values in the form {name}, like so:
//
// arm.AsmFull(
// "str {value}, {result}",
// map[string]interface{}{
// "value": 1
// "result": &dest,
// })
//
// You can use {} in the asm string (which expands to a register) to set the
// return value.
func AsmFull(asm string, regs map[string]interface{}) uintptr
+130
View File
@@ -0,0 +1,130 @@
#ifdef __riscv_flen
#define NREG 48
#define LFREG flw
#define SFREG fsw
#else
#define NREG 16
#endif
#if __riscv_xlen==64
#define REGSIZE 8
#define SREG sd
#define LREG ld
#else
#define REGSIZE 4
#define SREG sw
#define LREG lw
#endif
.section .text.handleInterruptASM
.global handleInterruptASM
.type handleInterruptASM,@function
handleInterruptASM:
// Save and restore all registers, because the hardware only saves/restores
// the pc.
// Note: we have to do this in assembly because the "interrupt"="machine"
// attribute is broken in LLVM: https://bugs.llvm.org/show_bug.cgi?id=42984
addi sp, sp, -NREG*REGSIZE
SREG ra, 0*REGSIZE(sp)
SREG t0, 1*REGSIZE(sp)
SREG t1, 2*REGSIZE(sp)
SREG t2, 3*REGSIZE(sp)
SREG a0, 4*REGSIZE(sp)
SREG a1, 5*REGSIZE(sp)
SREG a2, 6*REGSIZE(sp)
SREG a3, 7*REGSIZE(sp)
SREG a4, 8*REGSIZE(sp)
SREG a5, 9*REGSIZE(sp)
SREG a6, 10*REGSIZE(sp)
SREG a7, 11*REGSIZE(sp)
SREG t3, 12*REGSIZE(sp)
SREG t4, 13*REGSIZE(sp)
SREG t5, 14*REGSIZE(sp)
SREG t6, 15*REGSIZE(sp)
#ifdef __riscv_flen
SFREG f0, (0 + 16)*REGSIZE(sp)
SFREG f1, (1 + 16)*REGSIZE(sp)
SFREG f2, (2 + 16)*REGSIZE(sp)
SFREG f3, (3 + 16)*REGSIZE(sp)
SFREG f4, (4 + 16)*REGSIZE(sp)
SFREG f5, (5 + 16)*REGSIZE(sp)
SFREG f6, (6 + 16)*REGSIZE(sp)
SFREG f7, (7 + 16)*REGSIZE(sp)
SFREG f8, (8 + 16)*REGSIZE(sp)
SFREG f9, (9 + 16)*REGSIZE(sp)
SFREG f10,(10 + 16)*REGSIZE(sp)
SFREG f11,(11 + 16)*REGSIZE(sp)
SFREG f12,(12 + 16)*REGSIZE(sp)
SFREG f13,(13 + 16)*REGSIZE(sp)
SFREG f14,(14 + 16)*REGSIZE(sp)
SFREG f15,(15 + 16)*REGSIZE(sp)
SFREG f16,(16 + 16)*REGSIZE(sp)
SFREG f17,(17 + 16)*REGSIZE(sp)
SFREG f18,(18 + 16)*REGSIZE(sp)
SFREG f19,(19 + 16)*REGSIZE(sp)
SFREG f20,(20 + 16)*REGSIZE(sp)
SFREG f21,(21 + 16)*REGSIZE(sp)
SFREG f22,(22 + 16)*REGSIZE(sp)
SFREG f23,(23 + 16)*REGSIZE(sp)
SFREG f24,(24 + 16)*REGSIZE(sp)
SFREG f25,(25 + 16)*REGSIZE(sp)
SFREG f26,(26 + 16)*REGSIZE(sp)
SFREG f27,(27 + 16)*REGSIZE(sp)
SFREG f28,(28 + 16)*REGSIZE(sp)
SFREG f29,(29 + 16)*REGSIZE(sp)
SFREG f30,(30 + 16)*REGSIZE(sp)
SFREG f31,(31 + 16)*REGSIZE(sp)
#endif
call handleInterrupt
#ifdef __riscv_flen
LFREG f0, (31 + 16)*REGSIZE(sp)
LFREG f1, (30 + 16)*REGSIZE(sp)
LFREG f2, (29 + 16)*REGSIZE(sp)
LFREG f3, (28 + 16)*REGSIZE(sp)
LFREG f4, (27 + 16)*REGSIZE(sp)
LFREG f5, (26 + 16)*REGSIZE(sp)
LFREG f6, (25 + 16)*REGSIZE(sp)
LFREG f7, (24 + 16)*REGSIZE(sp)
LFREG f8, (23 + 16)*REGSIZE(sp)
LFREG f9, (22 + 16)*REGSIZE(sp)
LFREG f10,(21 + 16)*REGSIZE(sp)
LFREG f11,(20 + 16)*REGSIZE(sp)
LFREG f12,(19 + 16)*REGSIZE(sp)
LFREG f13,(18 + 16)*REGSIZE(sp)
LFREG f14,(17 + 16)*REGSIZE(sp)
LFREG f15,(16 + 16)*REGSIZE(sp)
LFREG f16,(15 + 16)*REGSIZE(sp)
LFREG f17,(14 + 16)*REGSIZE(sp)
LFREG f18,(13 + 16)*REGSIZE(sp)
LFREG f19,(12 + 16)*REGSIZE(sp)
LFREG f20,(11 + 16)*REGSIZE(sp)
LFREG f21,(10 + 16)*REGSIZE(sp)
LFREG f22,(9 + 16)*REGSIZE(sp)
LFREG f23,(8 + 16)*REGSIZE(sp)
LFREG f24,(7 + 16)*REGSIZE(sp)
LFREG f25,(6 + 16)*REGSIZE(sp)
LFREG f26,(5 + 16)*REGSIZE(sp)
LFREG f27,(4 + 16)*REGSIZE(sp)
LFREG f28,(3 + 16)*REGSIZE(sp)
LFREG f29,(2 + 16)*REGSIZE(sp)
LFREG f30,(1 + 16)*REGSIZE(sp)
LFREG f31,(0 + 16)*REGSIZE(sp)
#endif
LREG t6, 15*REGSIZE(sp)
LREG t5, 14*REGSIZE(sp)
LREG t4, 13*REGSIZE(sp)
LREG t3, 12*REGSIZE(sp)
LREG a7, 11*REGSIZE(sp)
LREG a6, 10*REGSIZE(sp)
LREG a5, 9*REGSIZE(sp)
LREG a4, 8*REGSIZE(sp)
LREG a3, 7*REGSIZE(sp)
LREG a2, 6*REGSIZE(sp)
LREG a1, 5*REGSIZE(sp)
LREG a0, 4*REGSIZE(sp)
LREG t2, 3*REGSIZE(sp)
LREG t1, 2*REGSIZE(sp)
LREG t0, 1*REGSIZE(sp)
LREG ra, 0*REGSIZE(sp)
addi sp, sp, NREG*REGSIZE
mret
+16
View File
@@ -19,3 +19,19 @@ func Asm(asm string)
// You can use {} in the asm string (which expands to a register) to set the
// return value.
func AsmFull(asm string, regs map[string]interface{}) uintptr
// DisableInterrupts disables all interrupts, and returns the old interrupt
// state.
func DisableInterrupts() uintptr {
// Note: this can be optimized with a CSRRW instruction, which atomically
// swaps the value and returns the old value.
mask := MIE.Get()
MIE.Set(0)
return mask
}
// EnableInterrupts enables all interrupts again. The value passed in must be
// the mask returned by DisableInterrupts.
func EnableInterrupts(mask uintptr) {
MIE.Set(mask)
}
+5 -45
View File
@@ -9,52 +9,12 @@ _start:
// Load the globals pointer. The program will load pointers relative to this
// register, so it must be set to the right value on startup.
// See: https://gnu-mcu-eclipse.github.io/arch/riscv/programmer/#the-gp-global-pointer-register
// Linker relaxations must be disabled to avoid the initialization beign
// relaxed with an uninitialized global pointer: mv gp, gp
.option push
.option norelax
la gp, __global_pointer$
.option pop
// Jump to runtime.main
call main
.section .text.handleInterruptASM
.global handleInterruptASM
.type handleInterruptASM,@function
handleInterruptASM:
// Save and restore all registers, because the hardware only saves/restores
// the pc.
// Note: we have to do this in assembly because the "interrupt"="machine"
// attribute is broken in LLVM: https://bugs.llvm.org/show_bug.cgi?id=42984
addi sp, sp, -64
sw ra, 60(sp)
sw t0, 56(sp)
sw t1, 52(sp)
sw t2, 48(sp)
sw a0, 44(sp)
sw a1, 40(sp)
sw a2, 36(sp)
sw a3, 32(sp)
sw a4, 28(sp)
sw a5, 24(sp)
sw a6, 20(sp)
sw a7, 16(sp)
sw t3, 12(sp)
sw t4, 8(sp)
sw t5, 4(sp)
sw t6, 0(sp)
call handleInterrupt
lw t6, 0(sp)
lw t5, 4(sp)
lw t4, 8(sp)
lw t3, 12(sp)
lw a7, 16(sp)
lw a6, 20(sp)
lw a5, 24(sp)
lw a4, 28(sp)
lw a3, 32(sp)
lw a2, 36(sp)
lw a1, 40(sp)
lw a0, 44(sp)
lw t2, 48(sp)
lw t1, 52(sp)
lw t0, 56(sp)
lw ra, 60(sp)
addi sp, sp, 64
mret
+2 -4
View File
@@ -5,16 +5,14 @@ import (
"time"
)
// This example assumes that the button is connected to pin 8. Change the value
// below to use a different pin.
const (
led = machine.LED
button = machine.Pin(8)
button = machine.BUTTON
)
func main() {
led.Configure(machine.PinConfig{Mode: machine.PinOutput})
button.Configure(machine.PinConfig{Mode: machine.PinInput})
button.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
for {
if button.Get() {
+13
View File
@@ -0,0 +1,13 @@
// +build circuitplay_express
package main
import (
"machine"
)
func init() {
enable := machine.PA30
enable.Configure(machine.PinConfig{Mode: machine.PinOutput})
enable.Set(true)
}
+36
View File
@@ -0,0 +1,36 @@
// Simplistic example using the DAC on the Circuit Playground Express.
//
// To actually use the DAC for producing complex waveforms or samples requires a DMA
// timer-based playback mechanism which is beyond the scope of this example.
package main
import (
"machine"
"time"
)
func main() {
speaker := machine.A0
speaker.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.DAC0.Configure(machine.DACConfig{})
data := []uint16{0xFFFF, 0x8000, 0x4000, 0x2000, 0x1000, 0x0000}
for {
for _, val := range data {
play(val)
time.Sleep(500 * time.Millisecond)
}
}
}
func play(val uint16) {
for i := 0; i < 100; i++ {
machine.DAC0.Set(val)
time.Sleep(2 * time.Millisecond)
machine.DAC0.Set(0)
time.Sleep(2 * time.Millisecond)
}
}
+13
View File
@@ -0,0 +1,13 @@
// +build pyportal
package main
import (
"machine"
)
func init() {
enable := machine.SPK_SD
enable.Configure(machine.PinConfig{Mode: machine.PinOutput})
enable.Set(true)
}
@@ -0,0 +1,10 @@
// +build circuitplay_express
package main
import "machine"
const (
buttonMode = machine.PinInputPulldown
buttonPinChange = machine.PinFalling
)
+10
View File
@@ -0,0 +1,10 @@
// +build pca10040
package main
import "machine"
const (
buttonMode = machine.PinInputPullup
buttonPinChange = machine.PinRising
)
+52
View File
@@ -0,0 +1,52 @@
package main
// This example demonstrates how to use pin change interrupts.
//
// This is only an example and should not be copied directly in any serious
// circuit, because it lacks an important feature: debouncing.
// See: https://en.wikipedia.org/wiki/Switch#Contact_bounce
import (
"machine"
"runtime/volatile"
"time"
)
const (
button = machine.BUTTON
led = machine.LED
)
func main() {
var lightLed volatile.Register8
lightLed.Set(0)
// Configure the LED, defaulting to on (usually setting the pin to low will
// turn the LED on).
led.Configure(machine.PinConfig{Mode: machine.PinOutput})
led.Low()
// Make sure the pin is configured as a pullup to avoid floating inputs.
// Pullup works for most buttons, as most buttons short to ground when
// pressed.
button.Configure(machine.PinConfig{Mode: buttonMode})
// Set an interrupt on this pin.
err := button.SetInterrupt(buttonPinChange, func(machine.Pin) {
if lightLed.Get() != 0 {
lightLed.Set(0)
led.Low()
} else {
lightLed.Set(1)
led.High()
}
})
if err != nil {
println("could not configure pin interrupt:", err.Error())
}
// Make sure the program won't exit.
for {
time.Sleep(time.Hour)
}
}
+10
View File
@@ -0,0 +1,10 @@
// +build wioterminal
package main
import "machine"
const (
buttonMode = machine.PinInput
buttonPinChange = machine.PinFalling
)
+16 -6
View File
@@ -8,9 +8,9 @@ import (
// This example assumes that an RGB LED is connected to pins 3, 5 and 6 on an Arduino.
// Change the values below to use different pins.
const (
redPin = 3
greenPin = 5
bluePin = 6
redPin = machine.D3
greenPin = machine.D5
bluePin = machine.D6
)
// cycleColor is just a placeholder until math/rand or some equivalent is working.
@@ -28,13 +28,16 @@ func main() {
machine.InitPWM()
red := machine.PWM{redPin}
red.Configure()
err := red.Configure()
checkError(err, "failed to configure red pin")
green := machine.PWM{greenPin}
green.Configure()
err = green.Configure()
checkError(err, "failed to configure green pin")
blue := machine.PWM{bluePin}
blue.Configure()
err = blue.Configure()
checkError(err, "failed to configure blue pin")
var rc uint8
var gc uint8 = 20
@@ -52,3 +55,10 @@ func main() {
time.Sleep(time.Millisecond * 500)
}
}
func checkError(err error, msg string) {
if err != nil {
print(msg, ": ", err.Error())
println()
}
}
+10 -7
View File
@@ -5,6 +5,8 @@ import (
"machine"
)
var timerCh = make(chan struct{}, 1)
func main() {
machine.LED.Configure(machine.PinConfig{Mode: machine.PinOutput})
@@ -12,17 +14,18 @@ func main() {
arm.SetupSystemTimer(machine.CPUFrequency() / 10)
for {
machine.LED.Low()
<-timerCh
machine.LED.High()
<-timerCh
}
}
var led_state bool
//export SysTick_Handler
func timer_isr() {
if led_state {
machine.LED.Low()
} else {
machine.LED.High()
select {
case timerCh <- struct{}{}:
default:
// The consumer is running behind.
}
led_state = !led_state
}
+253
View File
@@ -0,0 +1,253 @@
package bytealg
const (
// Index can search any valid length of string.
MaxLen = int(-1) >> 31
MaxBruteForce = MaxLen
)
// Compare two byte slices.
// Returns -1 if the first differing byte is lower in a, or 1 if the first differing byte is greater in b.
// If the byte slices are equal, returns 0.
// If the lengths are different and there are no differing bytes, compares based on length.
func Compare(a, b []byte) int {
// Compare for differing bytes.
for i := 0; i < len(a) && i < len(b); i++ {
switch {
case a[0] < b[0]:
return -1
case a[0] > b[0]:
return 1
}
}
// Compare lengths.
switch {
case len(a) > len(b):
return 1
case len(a) < len(b):
return -1
default:
return 0
}
}
// Count the number of instances of a byte in a slice.
func Count(b []byte, c byte) int {
// Use a simple implementation, as there is no intrinsic that does this like we want.
n := 0
for _, v := range b {
if v == c {
n++
}
}
return n
}
// Count the number of instances of a byte in a string.
func CountString(s string, c byte) int {
// Use a simple implementation, as there is no intrinsic that does this like we want.
// Currently, the compiler does not generate zero-copy byte-string conversions, so this needs to be seperate from Count.
n := 0
for i := 0; i < len(s); i++ {
if s[i] == c {
n++
}
}
return n
}
// Cutover is not reachable in TinyGo, but must exist as it is referenced.
func Cutover(n int) int {
// Setting MaxLen and MaxBruteForce should force a different path to be taken.
// This should never be called.
panic("cutover is unreachable")
}
// Equal checks if two byte slices are equal.
// It is equivalent to bytes.Equal.
func Equal(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
// Index finds the base index of the first instance of the byte sequence b in a.
// If a does not contain b, this returns -1.
func Index(a, b []byte) int {
for i := 0; i <= len(a)-len(b); i++ {
if Equal(a[i:i+len(b)], b) {
return i
}
}
return -1
}
// Index finds the index of the first instance of the specified byte in the slice.
// If the byte is not found, this returns -1.
func IndexByte(b []byte, c byte) int {
for i, v := range b {
if v == c {
return i
}
}
return -1
}
// Index finds the index of the first instance of the specified byte in the string.
// If the byte is not found, this returns -1.
func IndexByteString(s string, c byte) int {
for i := 0; i < len(s); i++ {
if s[i] == c {
return i
}
}
return -1
}
// Index finds the base index of the first instance of a substring in a string.
// If the substring is not found, this returns -1.
func IndexString(str, sub string) int {
for i := 0; i <= len(str)-len(sub); i++ {
if str[i:i+len(sub)] == sub {
return i
}
}
return -1
}
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The following code has been copied from the Go 1.15 release tree.
// PrimeRK is the prime base used in Rabin-Karp algorithm.
const PrimeRK = 16777619
// HashStrBytes returns the hash and the appropriate multiplicative
// factor for use in Rabin-Karp algorithm.
func HashStrBytes(sep []byte) (uint32, uint32) {
hash := uint32(0)
for i := 0; i < len(sep); i++ {
hash = hash*PrimeRK + uint32(sep[i])
}
var pow, sq uint32 = 1, PrimeRK
for i := len(sep); i > 0; i >>= 1 {
if i&1 != 0 {
pow *= sq
}
sq *= sq
}
return hash, pow
}
// HashStr returns the hash and the appropriate multiplicative
// factor for use in Rabin-Karp algorithm.
func HashStr(sep string) (uint32, uint32) {
hash := uint32(0)
for i := 0; i < len(sep); i++ {
hash = hash*PrimeRK + uint32(sep[i])
}
var pow, sq uint32 = 1, PrimeRK
for i := len(sep); i > 0; i >>= 1 {
if i&1 != 0 {
pow *= sq
}
sq *= sq
}
return hash, pow
}
// HashStrRevBytes returns the hash of the reverse of sep and the
// appropriate multiplicative factor for use in Rabin-Karp algorithm.
func HashStrRevBytes(sep []byte) (uint32, uint32) {
hash := uint32(0)
for i := len(sep) - 1; i >= 0; i-- {
hash = hash*PrimeRK + uint32(sep[i])
}
var pow, sq uint32 = 1, PrimeRK
for i := len(sep); i > 0; i >>= 1 {
if i&1 != 0 {
pow *= sq
}
sq *= sq
}
return hash, pow
}
// HashStrRev returns the hash of the reverse of sep and the
// appropriate multiplicative factor for use in Rabin-Karp algorithm.
func HashStrRev(sep string) (uint32, uint32) {
hash := uint32(0)
for i := len(sep) - 1; i >= 0; i-- {
hash = hash*PrimeRK + uint32(sep[i])
}
var pow, sq uint32 = 1, PrimeRK
for i := len(sep); i > 0; i >>= 1 {
if i&1 != 0 {
pow *= sq
}
sq *= sq
}
return hash, pow
}
// IndexRabinKarpBytes uses the Rabin-Karp search algorithm to return the index of the
// first occurence of substr in s, or -1 if not present.
func IndexRabinKarpBytes(s, sep []byte) int {
// Rabin-Karp search
hashsep, pow := HashStrBytes(sep)
n := len(sep)
var h uint32
for i := 0; i < n; i++ {
h = h*PrimeRK + uint32(s[i])
}
if h == hashsep && Equal(s[:n], sep) {
return 0
}
for i := n; i < len(s); {
h *= PrimeRK
h += uint32(s[i])
h -= pow * uint32(s[i-n])
i++
if h == hashsep && Equal(s[i-n:i], sep) {
return i - n
}
}
return -1
}
// IndexRabinKarp uses the Rabin-Karp search algorithm to return the index of the
// first occurence of substr in s, or -1 if not present.
func IndexRabinKarp(s, substr string) int {
// Rabin-Karp search
hashss, pow := HashStr(substr)
n := len(substr)
var h uint32
for i := 0; i < n; i++ {
h = h*PrimeRK + uint32(s[i])
}
if h == hashss && s[:n] == substr {
return 0
}
for i := n; i < len(s); {
h *= PrimeRK
h += uint32(s[i])
h -= pow * uint32(s[i-n])
i++
if h == hashss && s[i-n:i] == substr {
return i - n
}
}
return -1
}
+28 -2
View File
@@ -1,5 +1,7 @@
package task
import "runtime/interrupt"
const asserts = false
// Queue is a FIFO container of tasks.
@@ -10,7 +12,9 @@ type Queue struct {
// Push a task onto the queue.
func (q *Queue) Push(t *Task) {
i := interrupt.Disable()
if asserts && t.Next != nil {
interrupt.Restore(i)
panic("runtime: pushing a task to a queue with a non-nil Next pointer")
}
if q.tail != nil {
@@ -21,12 +25,15 @@ func (q *Queue) Push(t *Task) {
if q.head == nil {
q.head = t
}
interrupt.Restore(i)
}
// Pop a task off of the queue.
func (q *Queue) Pop() *Task {
i := interrupt.Disable()
t := q.head
if t == nil {
interrupt.Restore(i)
return nil
}
q.head = t.Next
@@ -34,11 +41,13 @@ func (q *Queue) Pop() *Task {
q.tail = nil
}
t.Next = nil
interrupt.Restore(i)
return t
}
// Append pops the contents of another queue and pushes them onto the end of this queue.
func (q *Queue) Append(other *Queue) {
i := interrupt.Disable()
if q.head == nil {
q.head = other.head
} else {
@@ -46,6 +55,15 @@ func (q *Queue) Append(other *Queue) {
}
q.tail = other.tail
other.head, other.tail = nil, nil
interrupt.Restore(i)
}
// Empty checks if the queue is empty.
func (q *Queue) Empty() bool {
i := interrupt.Disable()
empty := q.head == nil
interrupt.Restore(i)
return empty
}
// Stack is a LIFO container of tasks.
@@ -57,19 +75,24 @@ type Stack struct {
// Push a task onto the stack.
func (s *Stack) Push(t *Task) {
i := interrupt.Disable()
if asserts && t.Next != nil {
interrupt.Restore(i)
panic("runtime: pushing a task to a stack with a non-nil Next pointer")
}
s.top, t.Next = t, s.top
interrupt.Restore(i)
}
// Pop a task off of the stack.
func (s *Stack) Pop() *Task {
i := interrupt.Disable()
t := s.top
if t != nil {
s.top = t.Next
t.Next = nil
}
t.Next = nil
interrupt.Restore(i)
return t
}
@@ -89,10 +112,13 @@ func (t *Task) tail() *Task {
// Queue moves the contents of the stack into a queue.
// Elements can be popped from the queue in the same order that they would be popped from the stack.
func (s *Stack) Queue() Queue {
i := interrupt.Disable()
head := s.top
s.top = nil
return Queue{
q := Queue{
head: head,
tail: head.tail(),
}
interrupt.Restore(i)
return q
}
+27 -9
View File
@@ -7,21 +7,39 @@ func CPUFrequency() uint32 {
return 16000000
}
// Digital pins, marked as plain numbers on the board.
const (
D0 = PD0 // RX
D1 = PD1 // TX
D2 = PD2
D3 = PD3
D4 = PD4
D5 = PD5
D6 = PD6
D7 = PD7
D8 = PB0
D9 = PB1
D10 = PB2
D11 = PB3
D12 = PB4
D13 = PB5
)
// LED on the Arduino
const LED Pin = 13
const LED Pin = D13
// ADC on the Arduino
const (
ADC0 Pin = 0
ADC1 Pin = 1
ADC2 Pin = 2
ADC3 Pin = 3
ADC4 Pin = 4 // Used by TWI for SDA
ADC5 Pin = 5 // Used by TWI for SCL
ADC0 Pin = PC0
ADC1 Pin = PC1
ADC2 Pin = PC2
ADC3 Pin = PC3
ADC4 Pin = PC4 // Used by TWI for SDA
ADC5 Pin = PC5 // Used by TWI for SCL
)
// UART pins
const (
UART_TX_PIN Pin = 1
UART_RX_PIN Pin = 0
UART_TX_PIN Pin = PD1
UART_RX_PIN Pin = PD0
)
+1 -1
View File
@@ -49,7 +49,7 @@ const (
// Digital pins
D0 Pin = PE0
D1 Pin = PE1
D2 Pin = PE6
D2 Pin = PE4
D3 Pin = PE5
D4 Pin = PG5
D5 Pin = PE3
+27 -9
View File
@@ -7,21 +7,39 @@ func CPUFrequency() uint32 {
return 16000000
}
// Digital pins.
const (
D0 = PD0 // RX0
D1 = PD1 // TX1
D2 = PD2
D3 = PD3
D4 = PD4
D5 = PD5
D6 = PD6
D7 = PD7
D8 = PB0
D9 = PB1
D10 = PB2
D11 = PB3
D12 = PB4
D13 = PB5
)
// LED on the Arduino
const LED Pin = 13
const LED Pin = D13
// ADC on the Arduino
const (
ADC0 Pin = 0
ADC1 Pin = 1
ADC2 Pin = 2
ADC3 Pin = 3
ADC4 Pin = 4 // Used by TWI for SDA
ADC5 Pin = 5 // Used by TWI for SCL
ADC0 Pin = PC0
ADC1 Pin = PC1
ADC2 Pin = PC2
ADC3 Pin = PC3
ADC4 Pin = PC4 // Used by TWI for SDA
ADC5 Pin = PC5 // Used by TWI for SCL
)
// UART pins
const (
UART_TX_PIN Pin = 1
UART_RX_PIN Pin = 0
UART_TX_PIN Pin = PD1
UART_RX_PIN Pin = PD0
)
+5 -5
View File
@@ -66,15 +66,15 @@ const (
// SPI pins
const (
SPI0_SCK_PIN Pin = D13 // SCK: SERCOM1/PAD[1]
SPI0_MOSI_PIN Pin = D11 // MOSI: SERCOM1/PAD[0]
SPI0_MISO_PIN Pin = D12 // MISO: SERCOM1/PAD[3]
SPI0_SCK_PIN Pin = D13 // SCK: SERCOM1/PAD[1]
SPI0_SDO_PIN Pin = D11 // SDO: SERCOM1/PAD[0]
SPI0_SDI_PIN Pin = D12 // SDI: SERCOM1/PAD[3]
)
// NINA-W102 Pins
const (
NINA_MOSI Pin = PA12
NINA_MISO Pin = PA13
NINA_SDO Pin = PA12
NINA_SDI Pin = PA13
NINA_CS Pin = PA14
NINA_SCK Pin = PA15
NINA_GPIO0 Pin = PA27
+37
View File
@@ -0,0 +1,37 @@
// +build avr,atmega328p arduino arduino_nano
package machine
const (
// Note: start at port B because there is no port A.
portB Pin = iota * 8
portC
portD
)
const (
PB0 = portB + 0
PB1 = portB + 1
PB2 = portB + 2
PB3 = portB + 3
PB4 = portB + 4
PB5 = portB + 5
PB6 = portB + 6
PB7 = portB + 7
PC0 = portC + 0
PC1 = portC + 1
PC2 = portC + 2
PC3 = portC + 3
PC4 = portC + 4
PC5 = portC + 5
PC6 = portC + 6
PC7 = portC + 7
PD0 = portD + 0
PD1 = portD + 1
PD2 = portD + 2
PD3 = portD + 3
PD4 = portD + 4
PD5 = portD + 5
PD6 = portD + 6
PD7 = portD + 7
)
+3 -3
View File
@@ -74,9 +74,9 @@ func init() {
// SPI pins
const (
SPI0_SCK_PIN = PA5
SPI0_MOSI_PIN = PA7
SPI0_MISO_PIN = PA6
SPI0_SCK_PIN = PA5
SPI0_SDO_PIN = PA7
SPI0_SDI_PIN = PA6
)
// I2C pins
+3 -3
View File
@@ -72,9 +72,9 @@ const (
// SPI pins (internal flash)
const (
SPI0_SCK_PIN = P0_19 // SCK
SPI0_MOSI_PIN = P0_21 // MOSI
SPI0_MISO_PIN = P0_23 // MISO
SPI0_SCK_PIN = P0_19 // SCK
SPI0_SDO_PIN = P0_21 // SDO
SPI0_SDI_PIN = P0_23 // SDI
)
// USB CDC identifiers
+3 -3
View File
@@ -77,9 +77,9 @@ const (
// SPI pins (internal flash)
const (
SPI0_SCK_PIN = PA21 // SCK: SERCOM3/PAD[3]
SPI0_MOSI_PIN = PA20 // MOSI: SERCOM3/PAD[2]
SPI0_MISO_PIN = PA16 // MISO: SERCOM3/PAD[0]
SPI0_SCK_PIN = PA21 // SCK: SERCOM3/PAD[3]
SPI0_SDO_PIN = PA20 // SDO: SERCOM3/PAD[2]
SPI0_SDI_PIN = PA16 // SDI: SERCOM3/PAD[0]
)
// I2S pins
+4 -4
View File
@@ -78,7 +78,7 @@ const (
// 240x240 ST7789 display is connected to these pins (use RowOffset = 80)
TFT_SCK = D29
TFT_MOSI = D30
TFT_SDO = D30
TFT_CS = D31
TFT_DC = D32
TFT_RESET = D33
@@ -116,9 +116,9 @@ const (
// SPI pins
const (
SPI0_SCK_PIN = D13 // SCK
SPI0_MOSI_PIN = D15 // MOSI
SPI0_MISO_PIN = D14 // MISO
SPI0_SCK_PIN = D13 // SCK
SPI0_SDO_PIN = D15 // SDO
SPI0_SDI_PIN = D14 // SDI
)
// USB CDC identifiers
+3 -3
View File
@@ -83,9 +83,9 @@ var (
// SPI pins
const (
SPI0_SCK_PIN = PB11 // SCK: SERCOM4/PAD[3]
SPI0_MOSI_PIN = PB10 // MOSI: SERCOM4/PAD[2]
SPI0_MISO_PIN = PA12 // MISO: SERCOM4/PAD[0]
SPI0_SCK_PIN = PB11 // SCK: SERCOM4/PAD[3]
SPI0_SDO_PIN = PB10 // SDO: SERCOM4/PAD[2]
SPI0_SDI_PIN = PA12 // SDI: SERCOM4/PAD[0]
)
// SPI on the Feather M0.
+4 -24
View File
@@ -1,9 +1,7 @@
// +build sam,atsamd51,feather_m4
// +build feather_m4
package machine
import "device/sam"
// used to reset into bootloader
const RESET_MAGIC_VALUE = 0xf01669ef
@@ -47,13 +45,11 @@ const (
USBCDC_DP_PIN = PA25
)
// UART1 pins
const (
UART_TX_PIN = D1
UART_RX_PIN = D0
)
// UART2 pins
const (
UART2_TX_PIN = A4
UART2_RX_PIN = A5
@@ -65,27 +61,11 @@ const (
SCL_PIN = D21 // SCL: SERCOM2/PAD[1]
)
// I2C on the Feather M4.
var (
I2C0 = I2C{
Bus: sam.SERCOM2_I2CM,
SERCOM: 2,
}
)
// SPI pins
const (
SPI0_SCK_PIN = D25 // SCK: SERCOM1/PAD[1]
SPI0_MOSI_PIN = D24 // MOSI: SERCOM1/PAD[3]
SPI0_MISO_PIN = D23 // MISO: SERCOM1/PAD[2]
)
// SPI on the Feather M4.
var (
SPI0 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
SPI0_SCK_PIN = D25 // SCK: SERCOM1/PAD[1]
SPI0_SDO_PIN = D24 // SDO: SERCOM1/PAD[3]
SPI0_SDI_PIN = D23 // SDI: SERCOM1/PAD[2]
)
// USB CDC identifiers
+43
View File
@@ -0,0 +1,43 @@
// +build sam,atsamd51,feather_m4
package machine
import (
"device/sam"
"runtime/interrupt"
)
var (
UART1 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM5_USART_INT,
SERCOM: 5,
}
UART2 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
}
)
func init() {
UART1.Interrupt = interrupt.New(sam.IRQ_SERCOM5_2, UART1.handleInterrupt)
UART2.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, UART2.handleInterrupt)
}
// I2C on the Feather M4.
var (
I2C0 = I2C{
Bus: sam.SERCOM2_I2CM,
SERCOM: 2,
}
)
// SPI on the Feather M4.
var (
SPI0 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
)
+105
View File
@@ -0,0 +1,105 @@
// +build feather_nrf52840
package machine
const HasLowFrequencyCrystal = true
// GPIO Pins
const (
D0 = P0_25 // UART TX
D1 = P0_24 // UART RX
D2 = P0_10 // NFC2
D3 = P1_15 // LED1
D4 = P1_10 // LED2
D5 = P1_08
D6 = P0_07
D7 = P1_02 // Button
D8 = P0_16 // NeoPixel
D9 = P0_26
D10 = P0_27
D11 = P0_06
D12 = P0_08
D13 = P1_09
D14 = P0_04 // A0
D15 = P0_05 // A1
D16 = P0_30 // A2
D17 = P0_28 // A3
D18 = P0_02 // A4
D19 = P0_03 // A5
D20 = P0_29 // Battery
D21 = P0_31 // AREF
D22 = P0_12 // I2C SDA
D23 = P0_11 // I2C SCL
D24 = P0_15 // SPI MISO
D25 = P0_13 // SPI MOSI
D26 = P0_14 // SPI SCK
D27 = P0_19 // QSPI CLK
D28 = P0_20 // QSPI CS
D29 = P0_17 // QSPI Data 0
D30 = P0_22 // QSPI Data 1
D31 = P0_23 // QSPI Data 2
D32 = P0_21 // QSPI Data 3
D33 = P0_09 // NFC1 (test point on bottom of board)
)
// Analog Pins
const (
A0 = D14
A1 = D15
A2 = D16
A3 = D17
A4 = D18
A5 = D19
A6 = D20 // Battery
A7 = D21 // ARef
)
const (
LED = D3
LED1 = LED
LED2 = D4
NEOPIXEL = D8
BUTTON = D7
QSPI_SCK = D27
QSPI_CS = D28
QSPI_DATA0 = D29
QSPI_DATA1 = D30
QSPI_DATA2 = D31
QSPI_DATA3 = D32
)
// UART0 pins (logical UART1)
const (
UART_RX_PIN = D0
UART_TX_PIN = D1
)
// UART0 is the USB device
var (
UART0 = USB
)
// I2C pins
const (
SDA_PIN = D22 // I2C0 external
SCL_PIN = D23 // I2C0 external
)
// SPI pins
const (
SPI0_SCK_PIN = D26 // SCK
SPI0_SDO_PIN = D25 // SDO
SPI0_SDI_PIN = D24 // SDI
)
// USB CDC identifiers
const (
usb_STRING_PRODUCT = "Feather nRF52840 Express"
usb_STRING_MANUFACTURER = "Adafruit Industries LLC"
)
var (
usb_VID uint16 = 0x239A
usb_PID uint16 = 0x802A
)
+8 -8
View File
@@ -37,19 +37,19 @@ const (
const (
// TODO: figure out the pin numbers for these.
UART_TX_PIN = NoPin
UART_RX_PIN = NoPin
UART_TX_PIN = D1
UART_RX_PIN = D0
)
// SPI pins
const (
SPI0_SCK_PIN = NoPin
SPI0_MOSI_PIN = NoPin
SPI0_MISO_PIN = NoPin
SPI0_SCK_PIN = NoPin
SPI0_SDO_PIN = NoPin
SPI0_SDI_PIN = NoPin
SPI1_SCK_PIN = D13
SPI1_MOSI_PIN = D11
SPI1_MISO_PIN = D12
SPI1_SCK_PIN = D13
SPI1_SDO_PIN = D11
SPI1_SDI_PIN = D12
)
// I2C pins
+7 -7
View File
@@ -83,9 +83,9 @@ var (
// SPI pins
const (
SPI0_SCK_PIN = PB11 // SCK: SERCOM4/PAD[3]
SPI0_MOSI_PIN = PB10 // MOSI: SERCOM4/PAD[2]
SPI0_MISO_PIN = PA12 // MISO: SERCOM4/PAD[0]
SPI0_SCK_PIN = PB11 // SCK: SERCOM4/PAD[3]
SPI0_SDO_PIN = PB10 // SDO: SERCOM4/PAD[2]
SPI0_SDI_PIN = PA12 // SDI: SERCOM4/PAD[0]
)
// SPI on the ItsyBitsy M0.
@@ -98,10 +98,10 @@ var (
// "Internal" SPI pins; SPI flash is attached to these on ItsyBitsy M0
const (
SPI1_CS_PIN = PA27
SPI1_SCK_PIN = PB23
SPI1_MOSI_PIN = PB22
SPI1_MISO_PIN = PB03
SPI1_CS_PIN = PA27
SPI1_SCK_PIN = PB23
SPI1_SDO_PIN = PB22
SPI1_SDI_PIN = PB03
)
// "Internal" SPI on Sercom 5
+4 -27
View File
@@ -1,9 +1,7 @@
// +build sam,atsamd51,itsybitsy_m4
// +build itsybitsy_m4
package machine
import "device/sam"
// used to reset into bootloader
const RESET_MAGIC_VALUE = 0xf01669ef
@@ -51,43 +49,22 @@ const (
UART_RX_PIN = D0
)
// UART1 var is on SERCOM3, defined in atsamd51.go
// UART2 pins
const (
UART2_TX_PIN = A4
UART2_RX_PIN = D2
)
// UART2 var is on SERCOM0, defined in atsamd51.go
// I2C pins
const (
SDA_PIN = PA12 // SDA: SERCOM2/PAD[0]
SCL_PIN = PA13 // SCL: SERCOM2/PAD[1]
)
// I2C on the ItsyBitsy M4.
var (
I2C0 = I2C{
Bus: sam.SERCOM2_I2CM,
SERCOM: 2,
}
)
// SPI pins
const (
SPI0_SCK_PIN = PA01 // SCK: SERCOM1/PAD[1]
SPI0_MOSI_PIN = PA00 // MOSI: SERCOM1/PAD[0]
SPI0_MISO_PIN = PB23 // MISO: SERCOM1/PAD[3]
)
// SPI on the ItsyBitsy M4.
var (
SPI0 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
SPI0_SCK_PIN = PA01 // SCK: SERCOM1/PAD[1]
SPI0_SDO_PIN = PA00 // SDO: SERCOM1/PAD[0]
SPI0_SDI_PIN = PB23 // SDI: SERCOM1/PAD[3]
)
// USB CDC identifiers
@@ -0,0 +1,43 @@
// +build sam,atsamd51,itsybitsy_m4
package machine
import (
"device/sam"
"runtime/interrupt"
)
var (
UART1 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM3_USART_INT,
SERCOM: 3,
}
UART2 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
}
)
func init() {
UART1.Interrupt = interrupt.New(sam.IRQ_SERCOM3_2, UART1.handleInterrupt)
UART2.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, UART2.handleInterrupt)
}
// I2C on the ItsyBitsy M4.
var (
I2C0 = I2C{
Bus: sam.SERCOM2_I2CM,
SERCOM: 2,
}
)
// SPI on the ItsyBitsy M4.
var (
SPI0 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
)
+354
View File
@@ -0,0 +1,354 @@
// +build maixbit
// Chip datasheet: https://s3.cn-north-1.amazonaws.com.cn/dl.kendryte.com/documents/kendryte_datasheet_20181011163248_en.pdf
package machine
// K210 IO pins.
const (
P00 Pin = 0
P01 Pin = 1
P02 Pin = 2
P03 Pin = 3
P04 Pin = 4
P05 Pin = 5
P06 Pin = 6
P07 Pin = 7
P08 Pin = 8
P09 Pin = 9
P10 Pin = 10
P11 Pin = 11
P12 Pin = 12
P13 Pin = 13
P14 Pin = 14
P15 Pin = 15
P16 Pin = 16
P17 Pin = 17
P18 Pin = 18
P19 Pin = 19
P20 Pin = 20
P21 Pin = 21
P22 Pin = 22
P23 Pin = 23
P24 Pin = 24
P25 Pin = 25
P26 Pin = 26
P27 Pin = 27
P28 Pin = 28
P29 Pin = 29
P30 Pin = 30
P31 Pin = 31
P32 Pin = 32
P33 Pin = 33
P34 Pin = 34
P35 Pin = 35
P36 Pin = 36
P37 Pin = 37
P38 Pin = 38
P39 Pin = 39
P40 Pin = 40
P41 Pin = 41
P42 Pin = 42
P43 Pin = 43
P44 Pin = 44
P45 Pin = 45
P46 Pin = 46
P47 Pin = 47
)
type FPIOAFunction uint8
// Every pin on the Kendryte K210 is assigned to an FPIOA function.
// Each pin can be configured with every function below.
const (
FUNC_JTAG_TCLK FPIOAFunction = 0 // JTAG Test Clock
FUNC_JTAG_TDI FPIOAFunction = 1 // JTAG Test Data In
FUNC_JTAG_TMS FPIOAFunction = 2 // JTAG Test Mode Select
FUNC_JTAG_TDO FPIOAFunction = 3 // JTAG Test Data Out
FUNC_SPI0_D0 FPIOAFunction = 4 // SPI0 Data 0
FUNC_SPI0_D1 FPIOAFunction = 5 // SPI0 Data 1
FUNC_SPI0_D2 FPIOAFunction = 6 // SPI0 Data 2
FUNC_SPI0_D3 FPIOAFunction = 7 // SPI0 Data 3
FUNC_SPI0_D4 FPIOAFunction = 8 // SPI0 Data 4
FUNC_SPI0_D5 FPIOAFunction = 9 // SPI0 Data 5
FUNC_SPI0_D6 FPIOAFunction = 10 // SPI0 Data 6
FUNC_SPI0_D7 FPIOAFunction = 11 // SPI0 Data 7
FUNC_SPI0_SS0 FPIOAFunction = 12 // SPI0 Chip Select 0
FUNC_SPI0_SS1 FPIOAFunction = 13 // SPI0 Chip Select 1
FUNC_SPI0_SS2 FPIOAFunction = 14 // SPI0 Chip Select 2
FUNC_SPI0_SS3 FPIOAFunction = 15 // SPI0 Chip Select 3
FUNC_SPI0_ARB FPIOAFunction = 16 // SPI0 Arbitration
FUNC_SPI0_SCLK FPIOAFunction = 17 // SPI0 Serial Clock
FUNC_UARTHS_RX FPIOAFunction = 18 // UART High speed Receiver
FUNC_UARTHS_TX FPIOAFunction = 19 // UART High speed Transmitter
FUNC_RESV6 FPIOAFunction = 20 // Reserved function
FUNC_RESV7 FPIOAFunction = 21 // Reserved function
FUNC_CLK_SPI1 FPIOAFunction = 22 // Clock SPI1
FUNC_CLK_I2C1 FPIOAFunction = 23 // Clock I2C1
FUNC_GPIOHS0 FPIOAFunction = 24 // GPIO High speed 0
FUNC_GPIOHS1 FPIOAFunction = 25 // GPIO High speed 1
FUNC_GPIOHS2 FPIOAFunction = 26 // GPIO High speed 2
FUNC_GPIOHS3 FPIOAFunction = 27 // GPIO High speed 3
FUNC_GPIOHS4 FPIOAFunction = 28 // GPIO High speed 4
FUNC_GPIOHS5 FPIOAFunction = 29 // GPIO High speed 5
FUNC_GPIOHS6 FPIOAFunction = 30 // GPIO High speed 6
FUNC_GPIOHS7 FPIOAFunction = 31 // GPIO High speed 7
FUNC_GPIOHS8 FPIOAFunction = 32 // GPIO High speed 8
FUNC_GPIOHS9 FPIOAFunction = 33 // GPIO High speed 9
FUNC_GPIOHS10 FPIOAFunction = 34 // GPIO High speed 10
FUNC_GPIOHS11 FPIOAFunction = 35 // GPIO High speed 11
FUNC_GPIOHS12 FPIOAFunction = 36 // GPIO High speed 12
FUNC_GPIOHS13 FPIOAFunction = 37 // GPIO High speed 13
FUNC_GPIOHS14 FPIOAFunction = 38 // GPIO High speed 14
FUNC_GPIOHS15 FPIOAFunction = 39 // GPIO High speed 15
FUNC_GPIOHS16 FPIOAFunction = 40 // GPIO High speed 16
FUNC_GPIOHS17 FPIOAFunction = 41 // GPIO High speed 17
FUNC_GPIOHS18 FPIOAFunction = 42 // GPIO High speed 18
FUNC_GPIOHS19 FPIOAFunction = 43 // GPIO High speed 19
FUNC_GPIOHS20 FPIOAFunction = 44 // GPIO High speed 20
FUNC_GPIOHS21 FPIOAFunction = 45 // GPIO High speed 21
FUNC_GPIOHS22 FPIOAFunction = 46 // GPIO High speed 22
FUNC_GPIOHS23 FPIOAFunction = 47 // GPIO High speed 23
FUNC_GPIOHS24 FPIOAFunction = 48 // GPIO High speed 24
FUNC_GPIOHS25 FPIOAFunction = 49 // GPIO High speed 25
FUNC_GPIOHS26 FPIOAFunction = 50 // GPIO High speed 26
FUNC_GPIOHS27 FPIOAFunction = 51 // GPIO High speed 27
FUNC_GPIOHS28 FPIOAFunction = 52 // GPIO High speed 28
FUNC_GPIOHS29 FPIOAFunction = 53 // GPIO High speed 29
FUNC_GPIOHS30 FPIOAFunction = 54 // GPIO High speed 30
FUNC_GPIOHS31 FPIOAFunction = 55 // GPIO High speed 31
FUNC_GPIO0 FPIOAFunction = 56 // GPIO pin 0
FUNC_GPIO1 FPIOAFunction = 57 // GPIO pin 1
FUNC_GPIO2 FPIOAFunction = 58 // GPIO pin 2
FUNC_GPIO3 FPIOAFunction = 59 // GPIO pin 3
FUNC_GPIO4 FPIOAFunction = 60 // GPIO pin 4
FUNC_GPIO5 FPIOAFunction = 61 // GPIO pin 5
FUNC_GPIO6 FPIOAFunction = 62 // GPIO pin 6
FUNC_GPIO7 FPIOAFunction = 63 // GPIO pin 7
FUNC_UART1_RX FPIOAFunction = 64 // UART1 Receiver
FUNC_UART1_TX FPIOAFunction = 65 // UART1 Transmitter
FUNC_UART2_RX FPIOAFunction = 66 // UART2 Receiver
FUNC_UART2_TX FPIOAFunction = 67 // UART2 Transmitter
FUNC_UART3_RX FPIOAFunction = 68 // UART3 Receiver
FUNC_UART3_TX FPIOAFunction = 69 // UART3 Transmitter
FUNC_SPI1_D0 FPIOAFunction = 70 // SPI1 Data 0
FUNC_SPI1_D1 FPIOAFunction = 71 // SPI1 Data 1
FUNC_SPI1_D2 FPIOAFunction = 72 // SPI1 Data 2
FUNC_SPI1_D3 FPIOAFunction = 73 // SPI1 Data 3
FUNC_SPI1_D4 FPIOAFunction = 74 // SPI1 Data 4
FUNC_SPI1_D5 FPIOAFunction = 75 // SPI1 Data 5
FUNC_SPI1_D6 FPIOAFunction = 76 // SPI1 Data 6
FUNC_SPI1_D7 FPIOAFunction = 77 // SPI1 Data 7
FUNC_SPI1_SS0 FPIOAFunction = 78 // SPI1 Chip Select 0
FUNC_SPI1_SS1 FPIOAFunction = 79 // SPI1 Chip Select 1
FUNC_SPI1_SS2 FPIOAFunction = 80 // SPI1 Chip Select 2
FUNC_SPI1_SS3 FPIOAFunction = 81 // SPI1 Chip Select 3
FUNC_SPI1_ARB FPIOAFunction = 82 // SPI1 Arbitration
FUNC_SPI1_SCLK FPIOAFunction = 83 // SPI1 Serial Clock
FUNC_SPI_PERIPHERAL_D0 FPIOAFunction = 84 // SPI Peripheral Data 0
FUNC_SPI_PERIPHERAL_SS FPIOAFunction = 85 // SPI Peripheral Select
FUNC_SPI_PERIPHERAL_SCLK FPIOAFunction = 86 // SPI Peripheral Serial Clock
FUNC_I2S0_MCLK FPIOAFunction = 87 // I2S0 Main Clock
FUNC_I2S0_SCLK FPIOAFunction = 88 // I2S0 Serial Clock(BCLK)
FUNC_I2S0_WS FPIOAFunction = 89 // I2S0 Word Select(LRCLK)
FUNC_I2S0_IN_D0 FPIOAFunction = 90 // I2S0 Serial Data Input 0
FUNC_I2S0_IN_D1 FPIOAFunction = 91 // I2S0 Serial Data Input 1
FUNC_I2S0_IN_D2 FPIOAFunction = 92 // I2S0 Serial Data Input 2
FUNC_I2S0_IN_D3 FPIOAFunction = 93 // I2S0 Serial Data Input 3
FUNC_I2S0_OUT_D0 FPIOAFunction = 94 // I2S0 Serial Data Output 0
FUNC_I2S0_OUT_D1 FPIOAFunction = 95 // I2S0 Serial Data Output 1
FUNC_I2S0_OUT_D2 FPIOAFunction = 96 // I2S0 Serial Data Output 2
FUNC_I2S0_OUT_D3 FPIOAFunction = 97 // I2S0 Serial Data Output 3
FUNC_I2S1_MCLK FPIOAFunction = 98 // I2S1 Main Clock
FUNC_I2S1_SCLK FPIOAFunction = 99 // I2S1 Serial Clock(BCLK)
FUNC_I2S1_WS FPIOAFunction = 100 // I2S1 Word Select(LRCLK)
FUNC_I2S1_IN_D0 FPIOAFunction = 101 // I2S1 Serial Data Input 0
FUNC_I2S1_IN_D1 FPIOAFunction = 102 // I2S1 Serial Data Input 1
FUNC_I2S1_IN_D2 FPIOAFunction = 103 // I2S1 Serial Data Input 2
FUNC_I2S1_IN_D3 FPIOAFunction = 104 // I2S1 Serial Data Input 3
FUNC_I2S1_OUT_D0 FPIOAFunction = 105 // I2S1 Serial Data Output 0
FUNC_I2S1_OUT_D1 FPIOAFunction = 106 // I2S1 Serial Data Output 1
FUNC_I2S1_OUT_D2 FPIOAFunction = 107 // I2S1 Serial Data Output 2
FUNC_I2S1_OUT_D3 FPIOAFunction = 108 // I2S1 Serial Data Output 3
FUNC_I2S2_MCLK FPIOAFunction = 109 // I2S2 Main Clock
FUNC_I2S2_SCLK FPIOAFunction = 110 // I2S2 Serial Clock(BCLK)
FUNC_I2S2_WS FPIOAFunction = 111 // I2S2 Word Select(LRCLK)
FUNC_I2S2_IN_D0 FPIOAFunction = 112 // I2S2 Serial Data Input 0
FUNC_I2S2_IN_D1 FPIOAFunction = 113 // I2S2 Serial Data Input 1
FUNC_I2S2_IN_D2 FPIOAFunction = 114 // I2S2 Serial Data Input 2
FUNC_I2S2_IN_D3 FPIOAFunction = 115 // I2S2 Serial Data Input 3
FUNC_I2S2_OUT_D0 FPIOAFunction = 116 // I2S2 Serial Data Output 0
FUNC_I2S2_OUT_D1 FPIOAFunction = 117 // I2S2 Serial Data Output 1
FUNC_I2S2_OUT_D2 FPIOAFunction = 118 // I2S2 Serial Data Output 2
FUNC_I2S2_OUT_D3 FPIOAFunction = 119 // I2S2 Serial Data Output 3
FUNC_RESV0 FPIOAFunction = 120 // Reserved function
FUNC_RESV1 FPIOAFunction = 121 // Reserved function
FUNC_RESV2 FPIOAFunction = 122 // Reserved function
FUNC_RESV3 FPIOAFunction = 123 // Reserved function
FUNC_RESV4 FPIOAFunction = 124 // Reserved function
FUNC_RESV5 FPIOAFunction = 125 // Reserved function
FUNC_I2C0_SCLK FPIOAFunction = 126 // I2C0 Serial Clock
FUNC_I2C0_SDA FPIOAFunction = 127 // I2C0 Serial Data
FUNC_I2C1_SCLK FPIOAFunction = 128 // I2C1 Serial Clock
FUNC_I2C1_SDA FPIOAFunction = 129 // I2C1 Serial Data
FUNC_I2C2_SCLK FPIOAFunction = 130 // I2C2 Serial Clock
FUNC_I2C2_SDA FPIOAFunction = 131 // I2C2 Serial Data
FUNC_CMOS_XCLK FPIOAFunction = 132 // DVP System Clock
FUNC_CMOS_RST FPIOAFunction = 133 // DVP System Reset
FUNC_CMOS_PWDN FPIOAFunction = 134 // DVP Power Down Mode
FUNC_CMOS_VSYNC FPIOAFunction = 135 // DVP Vertical Sync
FUNC_CMOS_HREF FPIOAFunction = 136 // DVP Horizontal Reference output
FUNC_CMOS_PCLK FPIOAFunction = 137 // Pixel Clock
FUNC_CMOS_D0 FPIOAFunction = 138 // Data Bit 0
FUNC_CMOS_D1 FPIOAFunction = 139 // Data Bit 1
FUNC_CMOS_D2 FPIOAFunction = 140 // Data Bit 2
FUNC_CMOS_D3 FPIOAFunction = 141 // Data Bit 3
FUNC_CMOS_D4 FPIOAFunction = 142 // Data Bit 4
FUNC_CMOS_D5 FPIOAFunction = 143 // Data Bit 5
FUNC_CMOS_D6 FPIOAFunction = 144 // Data Bit 6
FUNC_CMOS_D7 FPIOAFunction = 145 // Data Bit 7
FUNC_SCCB_SCLK FPIOAFunction = 146 // SCCB Serial Clock
FUNC_SCCB_SDA FPIOAFunction = 147 // SCCB Serial Data
FUNC_UART1_CTS FPIOAFunction = 148 // UART1 Clear To Send
FUNC_UART1_DSR FPIOAFunction = 149 // UART1 Data Set Ready
FUNC_UART1_DCD FPIOAFunction = 150 // UART1 Data Carrier Detect
FUNC_UART1_RI FPIOAFunction = 151 // UART1 Ring Indicator
FUNC_UART1_SIR_IN FPIOAFunction = 152 // UART1 Serial Infrared Input
FUNC_UART1_DTR FPIOAFunction = 153 // UART1 Data Terminal Ready
FUNC_UART1_RTS FPIOAFunction = 154 // UART1 Request To Send
FUNC_UART1_OUT2 FPIOAFunction = 155 // UART1 User-designated Output 2
FUNC_UART1_OUT1 FPIOAFunction = 156 // UART1 User-designated Output 1
FUNC_UART1_SIR_OUT FPIOAFunction = 157 // UART1 Serial Infrared Output
FUNC_UART1_BAUD FPIOAFunction = 158 // UART1 Transmit Clock Output
FUNC_UART1_RE FPIOAFunction = 159 // UART1 Receiver Output Enable
FUNC_UART1_DE FPIOAFunction = 160 // UART1 Driver Output Enable
FUNC_UART1_RS485_EN FPIOAFunction = 161 // UART1 RS485 Enable
FUNC_UART2_CTS FPIOAFunction = 162 // UART2 Clear To Send
FUNC_UART2_DSR FPIOAFunction = 163 // UART2 Data Set Ready
FUNC_UART2_DCD FPIOAFunction = 164 // UART2 Data Carrier Detect
FUNC_UART2_RI FPIOAFunction = 165 // UART2 Ring Indicator
FUNC_UART2_SIR_IN FPIOAFunction = 166 // UART2 Serial Infrared Input
FUNC_UART2_DTR FPIOAFunction = 167 // UART2 Data Terminal Ready
FUNC_UART2_RTS FPIOAFunction = 168 // UART2 Request To Send
FUNC_UART2_OUT2 FPIOAFunction = 169 // UART2 User-designated Output 2
FUNC_UART2_OUT1 FPIOAFunction = 170 // UART2 User-designated Output 1
FUNC_UART2_SIR_OUT FPIOAFunction = 171 // UART2 Serial Infrared Output
FUNC_UART2_BAUD FPIOAFunction = 172 // UART2 Transmit Clock Output
FUNC_UART2_RE FPIOAFunction = 173 // UART2 Receiver Output Enable
FUNC_UART2_DE FPIOAFunction = 174 // UART2 Driver Output Enable
FUNC_UART2_RS485_EN FPIOAFunction = 175 // UART2 RS485 Enable
FUNC_UART3_CTS FPIOAFunction = 176 // UART3 Clear To Send
FUNC_UART3_DSR FPIOAFunction = 177 // UART3 Data Set Ready
FUNC_UART3_DCD FPIOAFunction = 178 // UART3 Data Carrier Detect
FUNC_UART3_RI FPIOAFunction = 179 // UART3 Ring Indicator
FUNC_UART3_SIR_IN FPIOAFunction = 180 // UART3 Serial Infrared Input
FUNC_UART3_DTR FPIOAFunction = 181 // UART3 Data Terminal Ready
FUNC_UART3_RTS FPIOAFunction = 182 // UART3 Request To Send
FUNC_UART3_OUT2 FPIOAFunction = 183 // UART3 User-designated Output 2
FUNC_UART3_OUT1 FPIOAFunction = 184 // UART3 User-designated Output 1
FUNC_UART3_SIR_OUT FPIOAFunction = 185 // UART3 Serial Infrared Output
FUNC_UART3_BAUD FPIOAFunction = 186 // UART3 Transmit Clock Output
FUNC_UART3_RE FPIOAFunction = 187 // UART3 Receiver Output Enable
FUNC_UART3_DE FPIOAFunction = 188 // UART3 Driver Output Enable
FUNC_UART3_RS485_EN FPIOAFunction = 189 // UART3 RS485 Enable
FUNC_TIMER0_TOGGLE1 FPIOAFunction = 190 // TIMER0 Toggle Output 1
FUNC_TIMER0_TOGGLE2 FPIOAFunction = 191 // TIMER0 Toggle Output 2
FUNC_TIMER0_TOGGLE3 FPIOAFunction = 192 // TIMER0 Toggle Output 3
FUNC_TIMER0_TOGGLE4 FPIOAFunction = 193 // TIMER0 Toggle Output 4
FUNC_TIMER1_TOGGLE1 FPIOAFunction = 194 // TIMER1 Toggle Output 1
FUNC_TIMER1_TOGGLE2 FPIOAFunction = 195 // TIMER1 Toggle Output 2
FUNC_TIMER1_TOGGLE3 FPIOAFunction = 196 // TIMER1 Toggle Output 3
FUNC_TIMER1_TOGGLE4 FPIOAFunction = 197 // TIMER1 Toggle Output 4
FUNC_TIMER2_TOGGLE1 FPIOAFunction = 198 // TIMER2 Toggle Output 1
FUNC_TIMER2_TOGGLE2 FPIOAFunction = 199 // TIMER2 Toggle Output 2
FUNC_TIMER2_TOGGLE3 FPIOAFunction = 200 // TIMER2 Toggle Output 3
FUNC_TIMER2_TOGGLE4 FPIOAFunction = 201 // TIMER2 Toggle Output 4
FUNC_CLK_SPI2 FPIOAFunction = 202 // Clock SPI2
FUNC_CLK_I2C2 FPIOAFunction = 203 // Clock I2C2
FUNC_INTERNAL0 FPIOAFunction = 204 // Internal function signal 0
FUNC_INTERNAL1 FPIOAFunction = 205 // Internal function signal 1
FUNC_INTERNAL2 FPIOAFunction = 206 // Internal function signal 2
FUNC_INTERNAL3 FPIOAFunction = 207 // Internal function signal 3
FUNC_INTERNAL4 FPIOAFunction = 208 // Internal function signal 4
FUNC_INTERNAL5 FPIOAFunction = 209 // Internal function signal 5
FUNC_INTERNAL6 FPIOAFunction = 210 // Internal function signal 6
FUNC_INTERNAL7 FPIOAFunction = 211 // Internal function signal 7
FUNC_INTERNAL8 FPIOAFunction = 212 // Internal function signal 8
FUNC_INTERNAL9 FPIOAFunction = 213 // Internal function signal 9
FUNC_INTERNAL10 FPIOAFunction = 214 // Internal function signal 10
FUNC_INTERNAL11 FPIOAFunction = 215 // Internal function signal 11
FUNC_INTERNAL12 FPIOAFunction = 216 // Internal function signal 12
FUNC_INTERNAL13 FPIOAFunction = 217 // Internal function signal 13
FUNC_INTERNAL14 FPIOAFunction = 218 // Internal function signal 14
FUNC_INTERNAL15 FPIOAFunction = 219 // Internal function signal 15
FUNC_INTERNAL16 FPIOAFunction = 220 // Internal function signal 16
FUNC_INTERNAL17 FPIOAFunction = 221 // Internal function signal 17
FUNC_CONSTANT FPIOAFunction = 222 // Constant function
FUNC_INTERNAL18 FPIOAFunction = 223 // Internal function signal 18
FUNC_DEBUG0 FPIOAFunction = 224 // Debug function 0
FUNC_DEBUG1 FPIOAFunction = 225 // Debug function 1
FUNC_DEBUG2 FPIOAFunction = 226 // Debug function 2
FUNC_DEBUG3 FPIOAFunction = 227 // Debug function 3
FUNC_DEBUG4 FPIOAFunction = 228 // Debug function 4
FUNC_DEBUG5 FPIOAFunction = 229 // Debug function 5
FUNC_DEBUG6 FPIOAFunction = 230 // Debug function 6
FUNC_DEBUG7 FPIOAFunction = 231 // Debug function 7
FUNC_DEBUG8 FPIOAFunction = 232 // Debug function 8
FUNC_DEBUG9 FPIOAFunction = 233 // Debug function 9
FUNC_DEBUG10 FPIOAFunction = 234 // Debug function 10
FUNC_DEBUG11 FPIOAFunction = 235 // Debug function 11
FUNC_DEBUG12 FPIOAFunction = 236 // Debug function 12
FUNC_DEBUG13 FPIOAFunction = 237 // Debug function 13
FUNC_DEBUG14 FPIOAFunction = 238 // Debug function 14
FUNC_DEBUG15 FPIOAFunction = 239 // Debug function 15
FUNC_DEBUG16 FPIOAFunction = 240 // Debug function 16
FUNC_DEBUG17 FPIOAFunction = 241 // Debug function 17
FUNC_DEBUG18 FPIOAFunction = 242 // Debug function 18
FUNC_DEBUG19 FPIOAFunction = 243 // Debug function 19
FUNC_DEBUG20 FPIOAFunction = 244 // Debug function 20
FUNC_DEBUG21 FPIOAFunction = 245 // Debug function 21
FUNC_DEBUG22 FPIOAFunction = 246 // Debug function 22
FUNC_DEBUG23 FPIOAFunction = 247 // Debug function 23
FUNC_DEBUG24 FPIOAFunction = 248 // Debug function 24
FUNC_DEBUG25 FPIOAFunction = 249 // Debug function 25
FUNC_DEBUG26 FPIOAFunction = 250 // Debug function 26
FUNC_DEBUG27 FPIOAFunction = 251 // Debug function 27
FUNC_DEBUG28 FPIOAFunction = 252 // Debug function 28
FUNC_DEBUG29 FPIOAFunction = 253 // Debug function 29
FUNC_DEBUG30 FPIOAFunction = 254 // Debug function 30
FUNC_DEBUG31 FPIOAFunction = 255 // Debug function 31
)
// These are the default FPIOA values for each function.
// (source: https://github.com/kendryte/kendryte-standalone-sdk/blob/develop/lib/drivers/fpioa.c#L69)
var fpioaFuncDefaults [256]uint32 = [256]uint32{
0x00900000, 0x00900001, 0x00900002, 0x00001f03, 0x00b03f04, 0x00b03f05, 0x00b03f06, 0x00b03f07, 0x00b03f08,
0x00b03f09, 0x00b03f0a, 0x00b03f0b, 0x00001f0c, 0x00001f0d, 0x00001f0e, 0x00001f0f, 0x03900010, 0x00001f11,
0x00900012, 0x00001f13, 0x00900014, 0x00900015, 0x00001f16, 0x00001f17, 0x00901f18, 0x00901f19, 0x00901f1a,
0x00901f1b, 0x00901f1c, 0x00901f1d, 0x00901f1e, 0x00901f1f, 0x00901f20, 0x00901f21, 0x00901f22, 0x00901f23,
0x00901f24, 0x00901f25, 0x00901f26, 0x00901f27, 0x00901f28, 0x00901f29, 0x00901f2a, 0x00901f2b, 0x00901f2c,
0x00901f2d, 0x00901f2e, 0x00901f2f, 0x00901f30, 0x00901f31, 0x00901f32, 0x00901f33, 0x00901f34, 0x00901f35,
0x00901f36, 0x00901f37, 0x00901f38, 0x00901f39, 0x00901f3a, 0x00901f3b, 0x00901f3c, 0x00901f3d, 0x00901f3e,
0x00901f3f, 0x00900040, 0x00001f41, 0x00900042, 0x00001f43, 0x00900044, 0x00001f45, 0x00b03f46, 0x00b03f47,
0x00b03f48, 0x00b03f49, 0x00b03f4a, 0x00b03f4b, 0x00b03f4c, 0x00b03f4d, 0x00001f4e, 0x00001f4f, 0x00001f50,
0x00001f51, 0x03900052, 0x00001f53, 0x00b03f54, 0x00900055, 0x00900056, 0x00001f57, 0x00001f58, 0x00001f59,
0x0090005a, 0x0090005b, 0x0090005c, 0x0090005d, 0x00001f5e, 0x00001f5f, 0x00001f60, 0x00001f61, 0x00001f62,
0x00001f63, 0x00001f64, 0x00900065, 0x00900066, 0x00900067, 0x00900068, 0x00001f69, 0x00001f6a, 0x00001f6b,
0x00001f6c, 0x00001f6d, 0x00001f6e, 0x00001f6f, 0x00900070, 0x00900071, 0x00900072, 0x00900073, 0x00001f74,
0x00001f75, 0x00001f76, 0x00001f77, 0x00000078, 0x00000079, 0x0000007a, 0x0000007b, 0x0000007c, 0x0000007d,
0x0099107e, 0x0099107f, 0x00991080, 0x00991081, 0x00991082, 0x00991083, 0x00001f84, 0x00001f85, 0x00001f86,
0x00900087, 0x00900088, 0x00900089, 0x0090008a, 0x0090008b, 0x0090008c, 0x0090008d, 0x0090008e, 0x0090008f,
0x00900090, 0x00900091, 0x00993092, 0x00993093, 0x00900094, 0x00900095, 0x00900096, 0x00900097, 0x00900098,
0x00001f99, 0x00001f9a, 0x00001f9b, 0x00001f9c, 0x00001f9d, 0x00001f9e, 0x00001f9f, 0x00001fa0, 0x00001fa1,
0x009000a2, 0x009000a3, 0x009000a4, 0x009000a5, 0x009000a6, 0x00001fa7, 0x00001fa8, 0x00001fa9, 0x00001faa,
0x00001fab, 0x00001fac, 0x00001fad, 0x00001fae, 0x00001faf, 0x009000b0, 0x009000b1, 0x009000b2, 0x009000b3,
0x009000b4, 0x00001fb5, 0x00001fb6, 0x00001fb7, 0x00001fb8, 0x00001fb9, 0x00001fba, 0x00001fbb, 0x00001fbc,
0x00001fbd, 0x00001fbe, 0x00001fbf, 0x00001fc0, 0x00001fc1, 0x00001fc2, 0x00001fc3, 0x00001fc4, 0x00001fc5,
0x00001fc6, 0x00001fc7, 0x00001fc8, 0x00001fc9, 0x00001fca, 0x00001fcb, 0x00001fcc, 0x00001fcd, 0x00001fce,
0x00001fcf, 0x00001fd0, 0x00001fd1, 0x00001fd2, 0x00001fd3, 0x00001fd4, 0x009000d5, 0x009000d6, 0x009000d7,
0x009000d8, 0x009100d9, 0x00991fda, 0x009000db, 0x009000dc, 0x009000dd, 0x000000de, 0x009000df, 0x00001fe0,
0x00001fe1, 0x00001fe2, 0x00001fe3, 0x00001fe4, 0x00001fe5, 0x00001fe6, 0x00001fe7, 0x00001fe8, 0x00001fe9,
0x00001fea, 0x00001feb, 0x00001fec, 0x00001fed, 0x00001fee, 0x00001fef, 0x00001ff0, 0x00001ff1, 0x00001ff2,
0x00001ff3, 0x00001ff4, 0x00001ff5, 0x00001ff6, 0x00001ff7, 0x00001ff8, 0x00001ff9, 0x00001ffa, 0x00001ffb,
0x00001ffc, 0x00001ffd, 0x00001ffe, 0x00001fff,
}
+72
View File
@@ -0,0 +1,72 @@
// +build maixbit
package machine
// Pins on the MAix Bit.
const (
D0 = P00 // JTAG_TCLK
D1 = P01 // JTAG_TDI
D2 = P02 // JTAG_TMS
D3 = P03 // JTAG_TDO
D4 = P04 // UARTHS_RX
D5 = P05 // UARTHS_TX
D6 = P06 // RESV0
D7 = P07 // RESV0
D8 = P08 // GPIO1
D9 = P09 // GPIO2
D10 = P10 // GPIO3
D11 = P11 // GPIO4
D12 = P12 // GPIO5
D13 = P13 // GPIO6
D14 = P14 // GPIO7
D15 = P15 // GPIO8
D16 = P16 // GPIOHS0
D17 = P17 // GPIOHS1
D18 = P18 // GPIOHS2
D19 = P19 // GPIOHS3
D20 = P20 // GPIOHS4
D21 = P21 // GPIOHS5
D22 = P22 // GPIOHS6
D23 = P23 // GPIOHS7
D24 = P24 // GPIOHS8
D25 = P25 // GPIOHS9
D26 = P26 // GPIOHS10 / SPI0_SDI
D27 = P27 // GPIOHS11 / SPI0_SCLK
D28 = P28 // GPIOHS12 / SPI0_SDO
D29 = P29 // GPIOHS13
D30 = P30 // GPIOHS14
D31 = P31 // GPIOHS15
D32 = P32 // GPIOHS16
D33 = P33 // GPIOHS17
D34 = P34 // GPIOHS18
D35 = P35 // GPIOHS19
)
const (
LED = LED1
LED1 = LED_RED
LED2 = LED_GREEN
LED3 = LED_BLUE
LED_RED = D13
LED_GREEN = D12
LED_BLUE = D14
)
// Default pins for UARTHS.
const (
UART_TX_PIN = D5
UART_RX_PIN = D4
)
// SPI pins.
const (
SPI0_SCK_PIN = D27
SPI0_SDO_PIN = D28
SPI0_SDI_PIN = D26
)
// I2C pins.
const (
I2C0_SDA_PIN = D34
I2C0_SCL_PIN = D35
)
+28
View File
@@ -0,0 +1,28 @@
// +build k210,maixbit
package machine
import "device/kendryte"
// SPI on the MAix Bit.
var (
SPI0 = SPI{
Bus: kendryte.SPI0,
}
SPI1 = SPI{
Bus: kendryte.SPI1,
}
)
// I2C on the MAix Bit.
var (
I2C0 = I2C{
Bus: kendryte.I2C0,
}
I2C1 = I2C{
Bus: kendryte.I2C1,
}
I2C2 = I2C{
Bus: kendryte.I2C2,
}
)
+14 -41
View File
@@ -1,9 +1,7 @@
// +build sam,atsamd51,metro_m4_airlift
// +build metro_m4_airlift
package machine
import "device/sam"
// used to reset into bootloader
const RESET_MAGIC_VALUE = 0xf01669ef
@@ -53,7 +51,10 @@ const (
UART_RX_PIN = D0
)
// Note: UART1 is on SERCOM3, defined in machine_atsamd51.go
const (
UART2_TX_PIN = PA04
UART2_RX_PIN = PA07
)
const (
NINA_CS = PA15
@@ -66,55 +67,27 @@ const (
NINA_RTS = PB23
)
// UART2 is on SERCOM0, defined in machine_atsamd51.go, and connects to the
// onboard ESP32-WROOM chip.
// I2C pins
const (
SDA_PIN = PB02 // SDA: SERCOM5/PAD[0]
SCL_PIN = PB03 // SCL: SERCOM5/PAD[1]
)
// I2C on the Metro M4.
var (
I2C0 = I2C{
Bus: sam.SERCOM5_I2CM,
SERCOM: 5,
}
)
// SPI pins
const (
SPI0_SCK_PIN = PA13 // SCK: SERCOM2/PAD[1]
SPI0_MOSI_PIN = PA12 // MOSI: SERCOM2/PAD[0]
SPI0_MISO_PIN = PA14 // MISO: SERCOM2/PAD[2]
SPI0_SCK_PIN = PA13 // SCK: SERCOM2/PAD[1]
SPI0_SDO_PIN = PA12 // SDO: SERCOM2/PAD[0]
SPI0_SDI_PIN = PA14 // SDI: SERCOM2/PAD[2]
NINA_MOSI = SPI0_MOSI_PIN
NINA_MISO = SPI0_MISO_PIN
NINA_SCK = SPI0_SCK_PIN
)
// SPI on the Metro M4.
var (
SPI0 = SPI{
Bus: sam.SERCOM2_SPIM,
SERCOM: 2,
}
NINA_SPI = SPI0
NINA_SDO = SPI0_SDO_PIN
NINA_SDI = SPI0_SDI_PIN
NINA_SCK = SPI0_SCK_PIN
)
const (
SPI1_SCK_PIN = D12 // MISO: SERCOM1/PAD[1]
SPI1_MOSI_PIN = D11 // MOSI: SERCOM1/PAD[3]
SPI1_MISO_PIN = D13 // SCK: SERCOM1/PAD[0]
)
// SPI1 on the Metro M4 on pins 11,12,13
var (
SPI1 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
SPI1_SCK_PIN = D12 // SDI: SERCOM1/PAD[1]
SPI1_SDO_PIN = D11 // SDO: SERCOM1/PAD[3]
SPI1_SDI_PIN = D13 // SCK: SERCOM1/PAD[0]
)
// USB CDC identifiers
@@ -0,0 +1,52 @@
// +build sam,atsamd51,metro_m4_airlift
package machine
import (
"device/sam"
"runtime/interrupt"
)
var (
UART1 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM3_USART_INT,
SERCOM: 3,
}
UART2 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
}
)
func init() {
UART1.Interrupt = interrupt.New(sam.IRQ_SERCOM3_2, UART1.handleInterrupt)
UART2.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, UART2.handleInterrupt)
}
// I2C on the Metro M4.
var (
I2C0 = I2C{
Bus: sam.SERCOM5_I2CM,
SERCOM: 5,
}
)
// SPI on the Metro M4.
var (
SPI0 = SPI{
Bus: sam.SERCOM2_SPIM,
SERCOM: 2,
}
NINA_SPI = SPI0
)
// SPI1 on the Metro M4 on pins 11,12,13
var (
SPI1 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
)
+3 -3
View File
@@ -33,9 +33,9 @@ const (
// SPI pins
const (
SPI0_SCK_PIN Pin = 23 // P13 on the board
SPI0_MOSI_PIN Pin = 21 // P15 on the board
SPI0_MISO_PIN Pin = 22 // P14 on the board
SPI0_SCK_PIN Pin = 23 // P13 on the board
SPI0_SDO_PIN Pin = 21 // P15 on the board
SPI0_SDI_PIN Pin = 22 // P14 on the board
)
// GPIO/Analog pins
+3 -3
View File
@@ -31,9 +31,9 @@ const (
// SPI pins (unused)
const (
SPI0_SCK_PIN = NoPin
SPI0_MOSI_PIN = NoPin
SPI0_MISO_PIN = NoPin
SPI0_SCK_PIN = NoPin
SPI0_SDO_PIN = NoPin
SPI0_SDI_PIN = NoPin
)
// USB CDC identifiers
+3 -3
View File
@@ -113,9 +113,9 @@ func init() {
// SPI pins
const (
SPI0_SCK_PIN = PA5
SPI0_MISO_PIN = PA6
SPI0_MOSI_PIN = PA7
SPI0_SCK_PIN = PA5
SPI0_SDI_PIN = PA6
SPI0_SDO_PIN = PA7
)
// I2C pins
+7 -7
View File
@@ -34,8 +34,8 @@ const (
D8 Pin = 35
D9 Pin = 6 // Also TX
D10 Pin = 8 // Also RX
D11 Pin = 46 // Also MISO
D12 Pin = 45 // Also MOSI
D11 Pin = 46 // Also SDI
D12 Pin = 45 // Also SDO
D13 Pin = 47 // Also SCK
)
@@ -58,16 +58,16 @@ const (
// SPI pins
const (
SPI0_SCK_PIN Pin = 47
SPI0_MOSI_PIN Pin = 45
SPI0_MISO_PIN Pin = 46
SPI0_SCK_PIN Pin = 47
SPI0_SDO_PIN Pin = 45
SPI0_SDI_PIN Pin = 46
)
// Internal 4MB SPI Flash
const (
SPI1_SCK_PIN Pin = 19
SPI1_MOSI_PIN Pin = 20
SPI1_MISO_PIN Pin = 21
SPI1_SDO_PIN Pin = 20
SPI1_SDI_PIN Pin = 21
SPI1_CS_PIN Pin = 17
SPI1_WP_PIN Pin = 22
SPI1_HOLD_PIN Pin = 23
+7 -7
View File
@@ -34,8 +34,8 @@ const (
D8 Pin = 35
D9 Pin = 6 // Also TX
D10 Pin = 8 // Also RX
D11 Pin = 46 // Also MISO
D12 Pin = 45 // Also MOSI
D11 Pin = 46 // Also SDI
D12 Pin = 45 // Also SDO
D13 Pin = 47 // Also SCK
)
@@ -63,16 +63,16 @@ const (
// SPI pins
const (
SPI0_SCK_PIN Pin = 47
SPI0_MOSI_PIN Pin = 45
SPI0_MISO_PIN Pin = 46
SPI0_SCK_PIN Pin = 47
SPI0_SDO_PIN Pin = 45
SPI0_SDI_PIN Pin = 46
)
// Internal 4MB SPI Flash
const (
SPI1_SCK_PIN Pin = 19
SPI1_MOSI_PIN Pin = 20
SPI1_MISO_PIN Pin = 21
SPI1_SDO_PIN Pin = 20
SPI1_SDI_PIN Pin = 21
SPI1_CS_PIN Pin = 17
SPI1_WP_PIN Pin = 22
SPI1_HOLD_PIN Pin = 23
+7 -7
View File
@@ -34,8 +34,8 @@ const (
D8 Pin = 35
D9 Pin = 6 // Also TX
D10 Pin = 8 // Also RX
D11 Pin = 46 // Also MISO
D12 Pin = 45 // Also MOSI
D11 Pin = 46 // Also SDI
D12 Pin = 45 // Also SDO
D13 Pin = 47 // Also SCK
)
@@ -58,16 +58,16 @@ const (
// SPI pins
const (
SPI0_SCK_PIN Pin = 47
SPI0_MOSI_PIN Pin = 45
SPI0_MISO_PIN Pin = 46
SPI0_SCK_PIN Pin = 47
SPI0_SDO_PIN Pin = 45
SPI0_SDI_PIN Pin = 46
)
// Internal 4MB SPI Flash
const (
SPI1_SCK_PIN Pin = 19
SPI1_MOSI_PIN Pin = 20
SPI1_MISO_PIN Pin = 21
SPI1_SDO_PIN Pin = 20
SPI1_SDI_PIN Pin = 21
SPI1_CS_PIN Pin = 17
SPI1_WP_PIN Pin = 22
SPI1_HOLD_PIN Pin = 23
+3 -3
View File
@@ -33,7 +33,7 @@ const (
// SPI pins (unused)
const (
SPI0_SCK_PIN = NoPin
SPI0_MOSI_PIN = NoPin
SPI0_MISO_PIN = NoPin
SPI0_SCK_PIN = NoPin
SPI0_SDO_PIN = NoPin
SPI0_SDI_PIN = NoPin
)
+3 -3
View File
@@ -47,7 +47,7 @@ const (
// SPI pins
const (
SPI0_SCK_PIN Pin = 25
SPI0_MOSI_PIN Pin = 23
SPI0_MISO_PIN Pin = 24
SPI0_SCK_PIN Pin = 25
SPI0_SDO_PIN Pin = 23
SPI0_SDI_PIN Pin = 24
)
+3 -3
View File
@@ -46,9 +46,9 @@ const (
// SPI pins
const (
SPI0_SCK_PIN Pin = 47 // P1.15
SPI0_MOSI_PIN Pin = 45 // P1.13
SPI0_MISO_PIN Pin = 46 // P1.14
SPI0_SCK_PIN Pin = 47 // P1.15
SPI0_SDO_PIN Pin = 45 // P1.13
SPI0_SDI_PIN Pin = 46 // P1.14
)
// USB CDC identifiers
+4 -4
View File
@@ -27,9 +27,9 @@ const (
// SPI pins for the PineTime.
const (
SPI0_SCK_PIN Pin = 2
SPI0_MOSI_PIN Pin = 3
SPI0_MISO_PIN Pin = 4
SPI0_SCK_PIN Pin = 2
SPI0_SDO_PIN Pin = 3
SPI0_SDI_PIN Pin = 4
)
// I2C pins for the PineTime.
@@ -51,7 +51,7 @@ const VIBRATOR_PIN Pin = 16
// http://files.pine64.org/doc/PineTime/PineTime%20Port%20Assignment%20rev1.0.pdf
const (
LCD_SCK = SPI0_SCK_PIN
LCD_SDI = SPI0_MOSI_PIN
LCD_SDI = SPI0_SDO_PIN
LCD_RS Pin = 18
LCD_CS Pin = 25
LCD_RESET Pin = 26
+7 -38
View File
@@ -1,9 +1,7 @@
// +build sam,atsamd51,pybadge
// +build pybadge
package machine
import "device/sam"
// used to reset into bootloader
const RESET_MAGIC_VALUE = 0xf01669ef
@@ -80,58 +78,29 @@ const (
UART_RX_PIN = D0
)
// UART1 var is on SERCOM3, defined in atsamd51.go
// UART2 pins
const (
UART2_TX_PIN = A4
UART2_RX_PIN = A5
)
// UART2 var is on SERCOM0, defined in atsamd51.go
// I2C pins
const (
SDA_PIN = PA12 // SDA: SERCOM2/PAD[0]
SCL_PIN = PA13 // SCL: SERCOM2/PAD[1]
)
// I2C on the ItsyBitsy M4.
var (
I2C0 = I2C{
Bus: sam.SERCOM2_I2CM,
SERCOM: 2,
}
)
// SPI pins
const (
SPI0_SCK_PIN = PA17 // SCK: SERCOM1/PAD[1]
SPI0_MOSI_PIN = PB23 // MOSI: SERCOM1/PAD[3]
SPI0_MISO_PIN = PB22 // MISO: SERCOM1/PAD[2]
)
// SPI on the PyBadge.
var (
SPI0 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
SPI0_SCK_PIN = PA17 // SCK: SERCOM1/PAD[1]
SPI0_SDO_PIN = PB23 // SDO: SERCOM1/PAD[3]
SPI0_SDI_PIN = PB22 // SDI: SERCOM1/PAD[2]
)
// TFT SPI pins
const (
SPI1_SCK_PIN = PB13 // SCK: SERCOM4/PAD[1]
SPI1_MOSI_PIN = PB15 // MOSI: SERCOM4/PAD[3]
SPI1_MISO_PIN = NoPin
)
// TFT SPI on the PyBadge.
var (
SPI1 = SPI{
Bus: sam.SERCOM4_SPIM,
SERCOM: 4,
}
SPI1_SCK_PIN = PB13 // SCK: SERCOM4/PAD[1]
SPI1_SDO_PIN = PB15 // SDO: SERCOM4/PAD[3]
SPI1_SDI_PIN = NoPin
)
// USB CDC identifiers
+51
View File
@@ -0,0 +1,51 @@
// +build sam,atsamd51,pybadge
package machine
import (
"device/sam"
"runtime/interrupt"
)
var (
UART1 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM5_USART_INT,
SERCOM: 5,
}
UART2 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
}
)
func init() {
UART1.Interrupt = interrupt.New(sam.IRQ_SERCOM5_2, UART1.handleInterrupt)
UART2.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, UART2.handleInterrupt)
}
// I2C on the ItsyBitsy M4.
var (
I2C0 = I2C{
Bus: sam.SERCOM2_I2CM,
SERCOM: 2,
}
)
// SPI on the PyBadge.
var (
SPI0 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
)
// TFT SPI on the PyBadge.
var (
SPI1 = SPI{
Bus: sam.SERCOM4_SPIM,
SERCOM: 4,
}
)
+147
View File
@@ -0,0 +1,147 @@
// +build sam,atsamd51,pygamer
package machine
import "device/sam"
// used to reset into bootloader
const RESET_MAGIC_VALUE = 0xf01669ef
// GPIO Pins
const (
D0 = PB17 // UART0 RX/PWM available
D1 = PB16 // UART0 TX/PWM available
D2 = PB03
D3 = PB02
D4 = PA14 // PWM available
D5 = PA16 // PWM available
D6 = PA18 // PWM available
D7 = PB14 // CS for microSD card slot
D8 = PA15 // built-in neopixel
D9 = PA19 // PWM available
D10 = PA20 // can be used for PWM or UART1 TX
D11 = PA21 // can be used for PWM or UART1 RX
D12 = PA22 // PWM available
D13 = PA23 // PWM available
)
// Analog pins
const (
A0 = PA02 // ADC/AIN[0]
A1 = PA05 // ADC/AIN[2]
A2 = PB08 // ADC/AIN[3]
A3 = PB09 // ADC/AIN[4]
A4 = PA04 // ADC/AIN[5]
A5 = PA06 // ADC/AIN[6]
A6 = PB01 // ADC/AIN[12]/VMEAS
A7 = PB04 // ADC/AIN[6]/LIGHT
A8 = D2 // ADC/AIN[14]
A9 = D3 // ADC/AIN[15]
)
const (
LED = D13
NEOPIXELS = D8
SD_CS = D7
LIGHTSENSOR = A7
BUTTON_LATCH = PB00
BUTTON_OUT = PB30
BUTTON_CLK = PB31
JOYY = PB06
JOYX = PB07
TFT_DC = PB05
TFT_CS = PB12
TFT_RST = PA00
TFT_LITE = PA01
SPEAKER_ENABLE = PA27
)
const (
BUTTON_SELECT_MASK = 16
BUTTON_START_MASK = 32
BUTTON_A_MASK = 64
BUTTON_B_MASK = 128
)
// UART0 aka USBCDC pins
const (
USBCDC_DM_PIN = PA24
USBCDC_DP_PIN = PA25
)
// UART1 pins
const (
UART_TX_PIN = D1
UART_RX_PIN = D0
)
// UART1 var is on SERCOM3, defined in atsamd51.go
// UART2 pins
const (
UART2_TX_PIN = A4
UART2_RX_PIN = A5
)
// UART2 var is on SERCOM0, defined in atsamd51.go
// I2C pins
const (
SDA_PIN = PA12 // SDA: SERCOM2/PAD[0]
SCL_PIN = PA13 // SCL: SERCOM2/PAD[1]
)
// I2C on the PyGamer.
var (
I2C0 = I2C{
Bus: sam.SERCOM2_I2CM,
SERCOM: 2,
}
)
// SPI pins
const (
SPI0_SCK_PIN = PA17 // SCK: SERCOM1/PAD[1]
SPI0_SDO_PIN = PB23 // SDO: SERCOM1/PAD[3]
SPI0_SDI_PIN = PB22 // SDI: SERCOM1/PAD[2]
)
// SPI on the PyGamer.
var (
SPI0 = SPI{
Bus: sam.SERCOM1_SPIM,
SERCOM: 1,
}
)
// TFT SPI pins
const (
SPI1_SCK_PIN = PB13 // SCK: SERCOM4/PAD[1]
SPI1_SDO_PIN = PB15 // SDO: SERCOM4/PAD[3]
SPI1_SDI_PIN = NoPin
)
// TFT SPI on the PyGamer.
var (
SPI1 = SPI{
Bus: sam.SERCOM4_SPIM,
SERCOM: 4,
}
)
// USB CDC identifiers
const (
usb_STRING_PRODUCT = "Adafruit pyGamer M4"
usb_STRING_MANUFACTURER = "Adafruit"
)
var (
usb_VID uint16 = 0x239A
usb_PID uint16 = 0x8033
)
+12 -33
View File
@@ -1,11 +1,7 @@
// +build sam,atsamd51,pyportal
// +build pyportal
package machine
import (
"device/sam"
)
// used to reset into bootloader
const RESET_MAGIC_VALUE = 0xf01669ef
@@ -30,9 +26,9 @@ const (
D26 = PB09 // TFT_WR
D27 = PB02 // SDA
D28 = PB03 // SCL
D29 = PA12 // MOSI
D29 = PA12 // SDO
D30 = PA13 // SCK
D31 = PA14 // MISO
D31 = PA14 // SDI
D32 = PB30 // SD_CS
D33 = PA01 // SD_CARD_DETECT
D34 = PA16 // LCD_DATA0
@@ -104,10 +100,10 @@ const (
USBCDC_DP_PIN = PA25
)
// TODO: add configuration for UART on SERCOM4 that is connected to TX/RX of ESP32
// UART1 aka NINA_TX/NINA_RX
const (
UART_TX_PIN = NoPin
UART_RX_PIN = NoPin
UART_TX_PIN = D1
UART_RX_PIN = D0
)
// I2C pins
@@ -116,32 +112,15 @@ const (
SCL_PIN = PB03 // SCL: SERCOM2/PAD[1]
)
// I2C on the PyPortal.
var (
I2C0 = I2C{
Bus: sam.SERCOM5_I2CM,
SERCOM: 5,
}
)
// SPI pins
const (
SPI0_SCK_PIN = PA13 // SCK: SERCOM1/PAD[1]
SPI0_MOSI_PIN = PA12 // MOSI: SERCOM1/PAD[3]
SPI0_MISO_PIN = PA14 // MISO: SERCOM1/PAD[2]
SPI0_SCK_PIN = PA13 // SCK: SERCOM1/PAD[1]
SPI0_SDO_PIN = PA12 // SDO: SERCOM1/PAD[3]
SPI0_SDI_PIN = PA14 // SDI: SERCOM1/PAD[2]
NINA_MOSI = SPI0_MOSI_PIN
NINA_MISO = SPI0_MISO_PIN
NINA_SCK = SPI0_SCK_PIN
)
// SPI on the PyPortal.
var (
SPI0 = SPI{
Bus: sam.SERCOM2_SPIM,
SERCOM: 2,
}
NINA_SPI = SPI0
NINA_SDO = SPI0_SDO_PIN
NINA_SDI = SPI0_SDI_PIN
NINA_SCK = SPI0_SCK_PIN
)
// USB CDC identifiers
+37
View File
@@ -0,0 +1,37 @@
// +build sam,atsamd51,pyportal
package machine
import (
"device/sam"
"runtime/interrupt"
)
var (
UART1 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM4_USART_INT,
SERCOM: 4,
}
)
func init() {
UART1.Interrupt = interrupt.New(sam.IRQ_SERCOM4_2, UART1.handleInterrupt)
}
// I2C on the PyPortal.
var (
I2C0 = I2C{
Bus: sam.SERCOM5_I2CM,
SERCOM: 5,
}
)
// SPI on the PyPortal.
var (
SPI0 = SPI{
Bus: sam.SERCOM2_SPIM,
SERCOM: 2,
}
NINA_SPI = SPI0
)
+4 -4
View File
@@ -20,7 +20,7 @@ const (
EPD_DC_PIN Pin = 16
EPD_CS_PIN Pin = 17
EPD_SCK_PIN Pin = 19
EPD_MOSI_PIN Pin = 20
EPD_SDO_PIN Pin = 20
POWER_SUPPLY_PIN Pin = 32
)
@@ -43,9 +43,9 @@ const (
// SPI pins
const (
SPI0_SCK_PIN Pin = 47
SPI0_MOSI_PIN Pin = 45
SPI0_MISO_PIN Pin = 46
SPI0_SCK_PIN Pin = 47
SPI0_SDO_PIN Pin = 45
SPI0_SDI_PIN Pin = 46
)
// PowerSupplyActive enables the supply voltages for nRF52840 and peripherals (true) or only for nRF52840 (false)
+6 -6
View File
@@ -132,12 +132,12 @@ func init() {
// SPI pins
const (
SPI1_SCK_PIN = PA5
SPI1_MISO_PIN = PA6
SPI1_MOSI_PIN = PA7
SPI0_SCK_PIN = SPI1_SCK_PIN
SPI0_MISO_PIN = SPI1_MISO_PIN
SPI0_MOSI_PIN = SPI1_MOSI_PIN
SPI1_SCK_PIN = PA5
SPI1_SDI_PIN = PA6
SPI1_SDO_PIN = PA7
SPI0_SCK_PIN = SPI1_SCK_PIN
SPI0_SDI_PIN = SPI1_SDI_PIN
SPI0_SDO_PIN = SPI1_SDO_PIN
)
// MEMs accelerometer
+101
View File
@@ -0,0 +1,101 @@
// +build nxp,mk66f18,teensy36
package machine
// CPUFrequency returns the frequency of the ARM core clock (180MHz)
func CPUFrequency() uint32 { return 180000000 }
// ClockFrequency returns the frequency of the external oscillator (16MHz)
func ClockFrequency() uint32 { return 16000000 }
// LED on the Teensy
const LED = PC05
// digital IO
const (
D00 = PB16
D01 = PB17
D02 = PD00
D03 = PA12
D04 = PA13
D05 = PD07
D06 = PD04
D07 = PD02
D08 = PD03
D09 = PC03
D10 = PC04
D11 = PC06
D12 = PC07
D13 = PC05
D14 = PD01
D15 = PC00
D16 = PB00
D17 = PB01
D18 = PB03
D19 = PB02
D20 = PD05
D21 = PD06
D22 = PC01
D23 = PC02
D24 = PE26
D25 = PA05
D26 = PA14
D27 = PA15
D28 = PA16
D29 = PB18
D30 = PB19
D31 = PB10
D32 = PB11
D33 = PE24
D34 = PE25
D35 = PC08
D36 = PC09
D37 = PC10
D38 = PC11
D39 = PA17
D40 = PA28
D41 = PA29
D42 = PA26
D43 = PB20
D44 = PB22
D45 = PB23
D46 = PB21
D47 = PD08
D48 = PD09
D49 = PB04
D50 = PB05
D51 = PD14
D52 = PD13
D53 = PD12
D54 = PD15
D55 = PD11
D56 = PE10
D57 = PE11
D58 = PE00
D59 = PE01
D60 = PE02
D61 = PE03
D62 = PE04
D63 = PE05
)
var (
TeensyUART1 = &UART0
TeensyUART2 = &UART1
TeensyUART3 = &UART2
TeensyUART4 = &UART3
TeensyUART5 = &UART4
)
const (
defaultUART0RX = D00
defaultUART0TX = D01
defaultUART1RX = D09
defaultUART1TX = D10
defaultUART2RX = D07
defaultUART2TX = D08
defaultUART3RX = D31
defaultUART3TX = D32
defaultUART4RX = D34
defaultUART4TX = D33
)
+3 -3
View File
@@ -60,9 +60,9 @@ func init() {
// SPI pins
const (
SPI0_SCK_PIN = D3
SPI0_MOSI_PIN = D4
SPI0_MISO_PIN = D2
SPI0_SCK_PIN = D3
SPI0_SDO_PIN = D4
SPI0_SDI_PIN = D2
)
// SPI on the Trinket M0.
+389
View File
@@ -0,0 +1,389 @@
// +build wioterminal
package machine
// used to reset into bootloader
const RESET_MAGIC_VALUE = 0xf01669ef
const (
ADC0 = A0
ADC1 = A1
ADC2 = A2
ADC3 = A3
ADC4 = A4
ADC5 = A5
ADC6 = A6
ADC7 = A7
ADC8 = A8
LED = PIN_LED
BUTTON = BUTTON_1
)
const (
// https://github.com/Seeed-Studio/ArduinoCore-samd/blob/master/variants/wio_terminal/variant.h
// LEDs
PIN_LED_13 = PA15
PIN_LED_RXL = PA15
PIN_LED_TXL = PA15
PIN_LED = PIN_LED_13
PIN_LED2 = PIN_LED_RXL
PIN_LED3 = PIN_LED_TXL
LED_BUILTIN = PIN_LED_13
PIN_NEOPIXEL = PA15
//Digital PINs
D0 = PB08
D1 = PB09
D2 = PA07
D3 = PB04
D4 = PB05
D5 = PB06
D6 = PA04
D7 = PB07
D8 = PA06
//Analog PINs
A0 = PB08 // ADC/AIN[0]
A1 = PB09 // ADC/AIN[2]
A2 = PA07 // ADC/AIN[3]
A3 = PB04 // ADC/AIN[4]
A4 = PB05 // ADC/AIN[5]
A5 = PB06 // ADC/AIN[10]
A6 = PA04 // ADC/AIN[10]
A7 = PB07 // ADC/AIN[10]
A8 = PA06 // ADC/AIN[10]
// 3.3V || 5V
// BCM2 || 5V
// BCM3 || GND
// BCM4 || BCM14
// GND || BCM15
// BCM17 || BCM18
// BCM27 || GND
// BCM22 || BCM23
// GND || BCM24
// BCM10 || GND
// BCM9 || BCM25
// BCM11 || BCM8
// GND || BCM7
// BCM0 || BCM1
// BCM5 || GND
// BCM6 || BCM12
// BCM13 || GND
// BCM19 || BCM16
// BCM26 || BCM20
// GND || BCM21
//PIN DEFINE FOR RPI
BCM0 = PA13 // I2C Wire1
BCM1 = PA12 // I2C Wire1
BCM2 = PA17 // I2C Wire2
BCM3 = PA16 // I2C Wire2
BCM4 = PB14 // GCLK
BCM5 = PB12 // GCLK
BCM6 = PB13 // GCLK
BCM7 = PA05 // DAC1
BCM8 = PB01 // SPI SS
BCM9 = PB00 // SPI SDI
BCM10 = PB02 // SPI SDO
BCM11 = PB03 // SPI SCK
BCM12 = PB06
BCM13 = PA07
BCM14 = PB27 // UART Serial1
BCM15 = PB26 // UART Serial1
BCM16 = PB07
BCM17 = PA02 // DAC0
BCM18 = PB28 // FPC Digital & AD pins
BCM19 = PA20 // WIO_IR
BCM20 = PA21 // I2S SDO
BCM21 = PA22 // I2S SDI
BCM22 = PB09
BCM23 = PA07
BCM24 = PB04
BCM25 = PB05
BCM26 = PA06
BCM27 = PB08
// FPC NEW DEFINE
FPC1 = PB28 // FPC Digital & AD pins
FPC2 = PB17
FPC3 = PB29
FPC4 = PA14
FPC5 = PC01
FPC6 = PC02
FPC7 = PC03
FPC8 = PC04
FPC9 = PC31
FPC10 = PD00
// RPI Analog RPIs
RPI_A0 = PB08
RPI_A1 = PB09
RPI_A2 = PA07
RPI_A3 = PB04
RPI_A4 = PB05
RPI_A5 = PB06
RPI_A6 = PA04
RPI_A7 = PB07
RPI_A8 = PA06
PIN_DAC0 = PA02
PIN_DAC1 = PA05
// FPO Analog RPIs
//FPC_A7 = FPC_D7
//FPC_A8 = FPC_D8
//FPC_A9 = FPC_D9
//FPC_A11 = FPC_D11
//FPC_A12 = FPC_D12
//FPC_A13 = FPC_D13
// USB
PIN_USB_DM = PA24
PIN_USB_DP = PA25
PIN_USB_HOST_ENABLE = PA27
// BUTTON
BUTTON_1 = PC26
BUTTON_2 = PC27
BUTTON_3 = PC28
WIO_KEY_A = PC26
WIO_KEY_B = PC27
WIO_KEY_C = PC28
// SWITCH
SWITCH_X = PD20
SWITCH_Y = PD12
SWITCH_Z = PD09
SWITCH_B = PD08
SWITCH_U = PD10
WIO_5S_UP = PD20
WIO_5S_LEFT = PD12
WIO_5S_RIGHT = PD09
WIO_5S_DOWN = PD08
WIO_5S_PRESS = PD10
// IRQ0 : RTL8720D
IRQ0 = PC20
// BUZZER_CTR
BUZZER_CTR = PD11
WIO_BUZZER = PD11
// MIC_INPUT
MIC_INPUT = PC30
WIO_MIC = PC30
// GCLK
GCLK0 = PB14
GCLK1 = PB12
GCLK2 = PB13
// Serial interfaces
// Serial1
PIN_SERIAL1_RX = PB27
PIN_SERIAL1_TX = PB26
// Serial2 : RTL8720D
PIN_SERIAL2_RX = PC23
PIN_SERIAL2_TX = PC22
// Wire Interfaces
// I2C Wire2
// I2C1
PIN_WIRE_SDA = PA17
PIN_WIRE_SCL = PA16
SDA = PIN_WIRE_SDA
SCL = PIN_WIRE_SCL
// I2C Wire1
// I2C0 : LIS3DHTR and ATECC608
PIN_WIRE1_SDA = PA13
PIN_WIRE1_SCL = PA12
SDA1 = PIN_WIRE1_SDA
SCL1 = PIN_WIRE1_SCL
PIN_GYROSCOPE_WIRE_SDA = PIN_WIRE1_SDA
PIN_GYROSCOPE_WIRE_SCL = PIN_WIRE1_SCL
GYROSCOPE_INT1 = PC21
WIO_LIS3DH_SDA = PIN_WIRE1_SDA
WIO_LIS3DH_SCL = PIN_WIRE1_SCL
WIO_LIS3DH_INT = PC21
// SPI
PIN_SPI_SDI = PB00
PIN_SPI_SDO = PB02
PIN_SPI_SCK = PB03
PIN_SPI_SS = PB01
SS = PIN_SPI_SS
SDO = PIN_SPI_SDO
SDI = PIN_SPI_SDI
SCK = PIN_SPI_SCK
// SPI1 RTL8720D_SPI
PIN_SPI1_SDI = PC24
PIN_SPI1_SDO = PB24
PIN_SPI1_SCK = PB25
PIN_SPI1_SS = PC25
SS1 = PIN_SPI1_SS
SDO1 = PIN_SPI1_SDO
SDI1 = PIN_SPI1_SDI
SCK1 = PIN_SPI1_SCK
// SPI2 SD_SPI
PIN_SPI2_SDI = PC18
PIN_SPI2_SDO = PC16
PIN_SPI2_SCK = PC17
PIN_SPI2_SS = PC19
SS2 = PIN_SPI2_SS
SDO2 = PIN_SPI2_SDO
SDI2 = PIN_SPI2_SDI
SCK2 = PIN_SPI2_SCK
// SPI3 LCD_SPI
PIN_SPI3_SDI = PB18
PIN_SPI3_SDO = PB19
PIN_SPI3_SCK = PB20
PIN_SPI3_SS = PB21
SS3 = PIN_SPI3_SS
SDO3 = PIN_SPI3_SDO
SDI3 = PIN_SPI3_SDI
SCK3 = PIN_SPI3_SCK
// Needed for SD library
SDCARD_SDI_PIN = PIN_SPI2_SDI
SDCARD_SDO_PIN = PIN_SPI2_SDO
SDCARD_SCK_PIN = PIN_SPI2_SCK
SDCARD_SS_PIN = PIN_SPI2_SS
SDCARD_DET_PIN = PD21
LCD_SDI_PIN = PIN_SPI3_SDI
LCD_SDO_PIN = PIN_SPI3_SDO
LCD_SCK_PIN = PIN_SPI3_SCK
LCD_SS_PIN = PIN_SPI3_SS
LCD_DC = PC06
LCD_RESET = PC07
LCD_BACKLIGHT = PC05
// 4 WIRE LCD TOUCH
LCD_XL = PC10
LCD_YU = PC11
LCD_XR = PC12
LCD_YD = PC13
// Needed for RTL8720D
RTL8720D_SDI_PIN = PIN_SPI1_SDI
RTL8720D_SDO_PIN = PIN_SPI1_SDO
RTL8720D_SCK_PIN = PIN_SPI1_SCK
RTL8720D_SS_PIN = PIN_SPI1_SS
//QSPI Pins
PIN_QSPI_IO0 = PA08
PIN_QSPI_IO1 = PA09
PIN_QSPI_IO2 = PA10
PIN_QSPI_IO3 = PA11
PIN_QSPI_SCK = PB10
PIN_QSPI_CS = PB11
// I2S Interfaces
PIN_I2S_FS = PA20
PIN_I2S_SCK = PB16
PIN_I2S_SDO = PA22
PIN_I2S_SDI = PA21
I2S_LRCLK = PA20
I2S_BLCK = PB16
I2S_SDOUT = PA22
I2S_SDIN = PA21
// RTL8720D Interfaces
RTL8720D_CHIP_PU = PA18
RTL8720D_GPIO0 = PA19 // SYNC
// SWD
SWDCLK = PA30
SWDIO = PA31
SWO = PB30
// light sensor
WIO_LIGHT = PD01
// ir sensor
WIO_IR = PB31
// OUTPUT_CTR
OUTPUT_CTR_5V = PC14
OUTPUT_CTR_3V3 = PC15
)
// UART0 aka USBCDC pins
const (
USBCDC_DM_PIN = PIN_USB_DM
USBCDC_DP_PIN = PIN_USB_DP
)
// UART1 pins
const (
UART_TX_PIN = PIN_SERIAL1_TX
UART_RX_PIN = PIN_SERIAL1_RX
)
// UART2 pins RTL8720D
const (
UART2_TX_PIN = PIN_SERIAL2_TX
UART2_RX_PIN = PIN_SERIAL2_RX
)
// I2C pins
const (
SDA0_PIN = PIN_WIRE_SDA // SDA: SERCOM3/PAD[0]
SCL0_PIN = PIN_WIRE_SCL // SCL: SERCOM3/PAD[1]
SDA1_PIN = PIN_WIRE1_SDA // SDA: SERCOM4/PAD[0]
SCL1_PIN = PIN_WIRE1_SCL // SCL: SERCOM4/PAD[1]
SDA_PIN = SDA0_PIN
SCL_PIN = SCL0_PIN
)
// SPI pins
const (
SPI0_SCK_PIN = SCK // SCK: SERCOM5/PAD[1]
SPI0_SDO_PIN = SDO // SDO: SERCOM5/PAD[0]
SPI0_SDI_PIN = SDI // SDI: SERCOM5/PAD[2]
// RTL8720D
SPI1_SCK_PIN = SCK1 // SCK: SERCOM0/PAD[1]
SPI1_SDO_PIN = SDO1 // SDO: SERCOM0/PAD[0]
SPI1_SDI_PIN = SDI1 // SDI: SERCOM0/PAD[2]
// SD
SPI2_SCK_PIN = SCK2 // SCK: SERCOM6/PAD[1]
SPI2_SDO_PIN = SDO2 // SDO: SERCOM6/PAD[0]
SPI2_SDI_PIN = SDI2 // SDI: SERCOM6/PAD[2]
// LCD
SPI3_SCK_PIN = SCK3 // SCK: SERCOM7/PAD[1]
SPI3_SDO_PIN = SDO3 // SDO: SERCOM7/PAD[3]
SPI3_SDI_PIN = SDI3 // SDI: SERCOM7/PAD[2]
)
// USB CDC identifiers
const (
usb_STRING_PRODUCT = "Seeed Wio Terminal"
usb_STRING_MANUFACTURER = "Seeed"
)
var (
usb_VID uint16 = 0x2886
usb_PID uint16 = 0x802D
)
@@ -0,0 +1,67 @@
// +build sam,atsamd51,wioterminal
package machine
import (
"device/sam"
"runtime/interrupt"
)
var (
UART1 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM2_USART_INT,
SERCOM: 2,
}
// RTL8720D
UART2 = UART{
Buffer: NewRingBuffer(),
Bus: sam.SERCOM1_USART_INT,
SERCOM: 1,
}
)
func init() {
UART1.Interrupt = interrupt.New(sam.IRQ_SERCOM2_2, UART1.handleInterrupt)
UART2.Interrupt = interrupt.New(sam.IRQ_SERCOM1_2, UART2.handleInterrupt)
}
// I2C on the Wio Terminal
var (
I2C0 = I2C{
Bus: sam.SERCOM4_I2CM,
SERCOM: 4,
}
I2C1 = I2C{
Bus: sam.SERCOM4_I2CM,
SERCOM: 4,
}
)
// SPI on the Wio Terminal
var (
SPI0 = SPI{
Bus: sam.SERCOM5_SPIM,
SERCOM: 5,
}
// RTL8720D
SPI1 = SPI{
Bus: sam.SERCOM0_SPIM,
SERCOM: 0,
}
// SD
SPI2 = SPI{
Bus: sam.SERCOM6_SPIM,
SERCOM: 6,
}
// LCD
SPI3 = SPI{
Bus: sam.SERCOM7_SPIM,
SERCOM: 7,
}
)

Some files were not shown because too many files have changed in this diff Show More