我用于基于FPGA的硬件的交互式调试和自动初始化(请参阅https://github.com/wzab/wzab/afck_j1b_forth)。上次我开始添加可通过IPBUS或Wishbone Bus访问的寄存器中的BitFields的支持。以下是我对Bitfields读写的单词的实现:
This file implements bitfield operations
It assumes, that we have the bus access
words:
wb@ ( address -- val )
wb! ( val address -- )
The bitfield is defined by its mask
(the ones correspond to the bits used by the field)
and by its shift (position of the LSB in the cell)
: bf@ ( address mask shift -- val )
rot ( mask shift address )
wb@ ( mask shift val )
rot ( shift val mask )
and ( shift val )
swap ( val shift )
rshift ( val )
;
: bf! ( val address mask shift -- )
rot ( val mask shift address )
>r ( val mask shift ) ( R: address )
rot ( mask shift val ) ( R: address )
swap ( mask val shift ) ( R: address )
lshift ( mask val ) ( R: address )
over ( mask val mask ) ( R: address )
and ( mask val ) ( R: address )
swap invert ( val ^mask ) ( R: address )
r@ ( val ^mask address ) ( R: address )
wb@ ( val ^mask oldval ) ( R: address )
and ( val oldval-masked) ( R: address )
or ( val ) ( R: address )
r> ( val address )
wb!
;
上面的实现似乎有效,但是恐怕这不是最佳的。他们可以以更聪明的方式写吗?但是,必须将实现与在J1B CPU上运行的SWAPFORTH兼容。
我不确定,您期望什么样的改进。虽然可能更快,但您对bf!
的定义太整合了,无法像现在一样,我不想维护。
从这些假设开始:
- Swapforth兼容意味着在没有当地人的情况下在堆栈上完成所有操作(如果您是说其他人,请澄清) )
- 提供的价值和面具以相同的右对齐格式提供(假设掩码已经移动会产生很多不合理的组合)
- 对于我的环境,我呆在
@
和!
中,您需要由wb@
和wb!
替换它们
我到达以下代码:
duplicate existing bitfield information on stack
: bf_dup ( n1 n2 n3 -- n1 n2 n3 n1 n2 n3)
2dup 2>r ( n1 n2 n3 R: n2 n3)
rot dup >r -rot ( n1 n2 n3 R: n2 n3 n1)
r> 2r> ;
: bf@ ( address mask shift -- val) 2>r @ r> rshift r> and ;
: (mask-old-value) ( addr mask shift -- val) lshift invert swap @ and ;
: (trim-shift-new) ( val addr mask shift -- addr new-value )
2>r swap 2r> ( addr val mask shift)
-rot and ( addr shift val_masked)
swap lshift ;
: bf! ( val address mask shift -- ) bf_dup (mask-old-value) >r
(trim-shift-new)
r> or swap ! ;
测试和实际应用这些单词的定义要容易得多:
store address mask shift (zero-based) in this sequence
: bitfield create rot , swap , , does> dup @ swap cell+ dup @ swap cell+ @ ;
hex 2018 7 3 ( address mask shift) bitfield mybitfield