| std | gcc | arm | description |
|---|---|---|---|
| r0-r3 | r0-r3 | a1-a4 | argument / scratch |
| r4-r7 | r4-r7 | v1-v4 | variable |
| r8 r9 |
r8 r9 | v5 | variable |
| v6/SB | platform specific | ||
| r10 r11 |
sl | v7 | variable |
| fp | v8 | variable / frame pointer | |
| r12 | ip | IP | Intra-Procedure-call scratch |
| r13 | sp | SP | Stack Pointer |
| r14 | lr | LR | Link Register |
| r15 | pc | PC | Program Counter |
| (23.1) |
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| op{cond}{type} Rd, [Rn, Op2] |
mov r2, #1
@ Byte loads
adr r0, bytes
ldrb r3, bytes @ r3= bytes[0]; // r3= 0x000000FF= 255
ldrsb r3, bytes @ r3= (s8)bytes[0]; // r3= 0xFFFFFFFF= -1
ldrb r3, [r0], r2 @ r3= *r0_b++; // r3= 255, r0++;
@ Halfword loads
adr r0, hwords
ldrh r3, hwords+2 @ r3= words[1]; // r3= 0x0000FFFF= 65535
ldrsh r3, [r0, #2] @ r3= (s16)r0_h[1]; // r3= 0xFFFFFFFF= -1
ldrh r3, [r0, r2, lsl #1] @ r3= r0_h[1]? No! Illegal instruction :(
@ Byte array: u8 bytes[3]= { 0xFF, 1, 2 };
bytes:
.byte 0xFF, 1, 2
@ Halfword array u16 hwords[3]= { 0xF001, 0xFFFF, 0xF112 };
.align 1 @ align to even bytes REQUIRED!!!
hwords:
.hword 0xF110, 0xFFFF, 0xF112
#### Block transfers
Block transfers allow you to load or store multiple successive words into registers in one instruction. This is useful because it saves on instructions, but more importantly, it saves time because individual memory instructions are quite costly and with block transfers you only have to pay the overhead once. The basic instructions for block transfers are `ldm` (LoaD Multiple) and `stm` (STore Multiple), and the operands are a base register (with an optional exclamation mark for `Rd` write-back) and a list of registers between braces.
| op{cond}{mode} Rd{!}, {Rlist} |
| Block op | Standard | Stack alt |
|---|---|---|
| Increment After | ldmia / stmia | ldmfd / stmea |
| Increment Before | ldmib / stmib | ldmed / stmfa |
| Decrement After | ldmda / stmda | ldmfa / stmed |
| Decrement Before | ldmdb / stmdb | ldmea / stmfd |
| Affix | Flags | Description |
|---|---|---|
| eq | Z=1 | Zero (EQual to 0) |
| ne | Z=0 | Not zero (Not Equal to 0) |
| cs / hs | C=1 | Carry Set / unsigned Higher or Same |
| cc / lo | C=0 | Carry Clear / unsigned LOwer |
| mi | N=1 | Negative (MInus) |
| pl | N=0 | Positive or zero (PLus) |
| vs | V=1 | Sign overflow (oVerflow Set) |
| vc | V=0 | No sign overflow (oVerflow Clear) |
| hi | C=1 & Z=0 | Unsigned HIgher |
| ls | C=0 | Z=1 | Unsigned Lower or Same |
| ge | N=V | Signed Greater or Equal |
| lt | N != V | Signed Less Than |
| gt | Z=0 & N=V | Signed Greater Than |
| le | Z=1 | N != V | Signed Less or Equal |
| al | - | ALways (default) |
| nv | - | NeVer |
|
|
|
|
| 1F - 1C | 1B 1A | 19 | 18 - 15 | 14 | 13 - 10 | F - C | B - 8 | 7 | 6 5 | 4 | 3 - 0 | |||
| add Rd, Rn, # | cnd | TA | IF | TB | S | Rn | Rd | IR | IN | |||||
| add Rd, Rn, Rm Op # | IS | ST | SF | Rm | ||||||||||
| add Rd, Rn, Rm Op Rs | Rs | 0 | ||||||||||||
| bits | name | description |
|---|---|---|
| C - F | Rd | Destination register. |
| 10 - 13 | Rn | First operand register. |
| 14 | S | Set Status bits (the -s affix). |
| 15-18 | TB | Instruction-type field. Must be 4 for add. |
| 19 | IF | Immediate flag. The second operand is an immediate value if set, and a (shifted) register if clear. |
| 1A - 1C | TA | Another instruction-type field. Is zero for all data instructions. |
| 1D - 1F | cnd | Condition field. |
| bits | name | description |
|---|---|---|
| 0 - 7 | IN | Immediate Number field. The second operand is IN ror 2*IR. |
| 8 - B | IR | Immediate Rotate field. This denotes the rotate-right amount applied to IN. |
| 0 - 3 | Rm | Second operand register. |
| 4 | SF | Shift-operand flag. If set, the shift is the immediate value in IS; if clear, the shift comes from register Rs. |
| 5 - 6 | ST | Shift type. 0: lsl, 1: lsr 2: asr, 3: ror |
| 7 - B | IS | Immediate Shift value. Second operand is Rm Op IS. |
| 8 - B | Rs | Shift Register. Second operand is Rm Op Rs. |
@ Forming 511(0x101)
mov r0, #511 @ Illegal instruction! D:
mov r0, #256 @ 256= 1 ror 24, so still valid
add r0, #255 @ 256+255 = 511
@ Load 511 from memory with ldr
ldr r0, .L0
@ Load 511 from memory with special ldr
@ NOTE: no '#' !
ldr r0,=511
.L0:
.word 511
Anyway, the bit patterns of {@tbl:arm-add} is what the processor actually sees when you use an `add` instruction. You can see what the other instructions look like in the references I gave earlier, especially the quick references. The orthogonality of the whole instruction set shows itself in very similar formatting of a given class of instructions. For example, the data instructions only differ by the `TB` field: 4 for `add`, 2 for `sub`, et cetera.
## Thumb assembly {#sec-thumb}
The Thumb instruction set is a subset of the full list of ARM instructions. The defining feature of Thumb instructions is that they're only 16 bits long. As a result a function in Thumb can be much shorter than in ARM, which can be beneficial if you don't have a lot of room to work with. Another point is that 16bit instructions will pass through a 16bit databus in one go and be executed immediately, whereas execution of 32bit instructions would have to wait for the second chunk to be fetched, effectively halving the instruction speed. Remember that ROM and EWRAM, the two main areas for code have 16bit buses, which is why Thumb instructions are advised for GBA programming.
There are downsides, of course; you can't just cut the size of an instruction in half and expect to get away with it. Even though Thumb code uses many of the same mnemonics as ARM, functionality has been severely reduced. For example, the only instruction that can be conditional is the branch, `b`; instructions can no longer make use of shifts and rotates (these are separate instructions now), and most instructions can only use the lower 8 registers (`r0-r7`); the higher ones are still available, but you have to move things to the lower ones because you can use them.
In short, writing efficient Thumb code is much more challenging. It's not exactly bondage-and-disciple programming, but if you're used to the full ARM set you might be in for a surprise now and then. Thumb uses most of ARM's mnemonics, but a lot of them are restricted in some way so learning how to code in Thumb basically comes down to what you _can't_ do anymore. With that in mind, this section will cover the differences between ARM and Thumb, rather than the Thumb set itself.
- **Removed instructions**. A few instructions have been cut altogether. Of the various multiplication instructions only `mul` remains, reverse subtractions (`rsb`, `rsc`) are gone, as are the swapping and coprocessor instructions, but those are rare anyway.
- **‘New’ instructions**. The mnemonics are new, but really, they're just special cases of conventional ARM instructions. Thumb has separate shift/rotate opcodes: `lsl`, `lsr`, `asr` and `ror` codes, which are functionally equivalent to ‘`mov Rd, Rm, Op2`’. There is also a ‘`neg Rd,Rm`’ for _Rd_= 0−*Rm*, essentially an `rsb`. And I suppose you could call `push` and `pop` new, as they don't appear as ARM opcodes in some devkits.
- **No conditionals**. Except on branch. Hello, gratuitous labelling :\\.
- The **Set Status** flag is always on. So in Thumb `sub` will always work as a `subs`, etc.
- **No barrel shifter**. Well, it still exist, of course; you just can't use it in conjunction with the instructions anymore. This is why there are separate bitshift/-rotate opcodes.
- **Restricted register availability**. Unless explicitly stated otherwise, the instructions can only use `r0-r7`. The exceptions here are `add`, `mov` and `cmp`, which can at times use high-regs as operands. This restriction also applies to memory operations, with small exceptions: `ldr/str` can still use PC-or SP-relative stuff; `push` allows `lr` in its register list and `pop` allows `pc`. With these, you could return from functions quickly, but you should use `bx` for that anyway. Fortunately, `bx` also allows use of every register so you can still do ‘`bx lr`’.
- **Little to no immediate or second operand support**. In ARM-code, most instructions allowed for a second operand _Op2_, which was either an immediate value or a (shifted) register. Most Thumb data instructions are of the form ‘_`ins`_` Rd, Rm`’ and correspond to the C assignment operators like `+=` and `|=`. Note that `Rm` is a register, not an immediate. The only instructions that break this pattern are the shift-codes, `add`, `sub`, `mov` and `cmp`, which can have both immediate values and second operands. See the reference docs for more details.
- **No write-back in memory instructions**. That means you will have to use at least one extra register and extra instructions when traversing arrays. There is one exception to this, namely block-transfers. The only surviving versions are `ldmia` and `stmia`, and in both versions the write-back is actually required.
- **Memory operations are tricky**. Well, they are! ARM memory opcodes were identical in what they could do, but here you have to be on your toes. Some features are completely gone (write-back and shifted register offsets), and the others aren't always available to all types. Register-offset addressing is always available, but immediate offsets do not work for the signed loads (`ldrsh`, `ldrsb`). Remember that the registers can only be `r0-r7`, except for `ldr/str`: there you can also use PC and SP-relative stuff (with immediate offsets). {\*@tbl:thumb-mem} gives an overview.
| [Rn,Rm] | [Rn,#] | [pc/sp,#] | |
|---|---|---|---|
| ldr/str | + | + | + |
| ldrh/strh | + | + | - |
| ldrb/strb | + | + | - |
| ldrsh/ldrsb | + | - | - |
.align 2
word_var: @ int word_var= 0xCAFEBABE
.word 0xCAFEBABE
word_array: @ int word_array[4]= { 1,2,3,4 }
.word 1, 2, 3, 4 @ NO comma at the end!!
byte_var: @ char byte_var= 0;
.byte 0
hword_var: @ NOT short hword_var= 0xDEAD;
.hword 0xDEAD @ due to bad alignment!
str_array: @ Array of NULL-terminated strings:
.string "Hello", "Nurse!"
### Data sections {#ssec-gas-dsec}
So now you know how to make code and variables, you have to put them into the proper sections. A section is a contained area where code and data are stored; the linker uses a linkscript to see where the different sections are and then adds all your symbols and links accordingly. The format for sections is ‘`.section `_`secname`_’, with optional ‘`, "`_`flags`_`", %`_`type`_’ information I'll get to in a minute.
Traditionally, the section for code is called `.text` and that for data is called `.data`, but there are a few more to consider: the general sections `.bss` and `.rodata`, and the GBA-specific `.ewram` and `.iwram`. In principle, these four are data sections, but they can be used for code by setting the correct section flags. As you might have guessed, `.ewram` stands for the EWRAM section (0200:0000h), `.iwram` is IWRAM (0300:0000h) and `.rodata` is ROM (0800:0000). The `.bss` section is a section intended for variables that are either uninitialized or filled with zero. The nice thing about this section is that it requires no ROM space, as it doesn't have data to store there. The section will be placed in IWRAM, just like the `.data`. You may also sometimes see `.sbss` which stands for ‘small bss’ and has a similar function as the standard `.bss`, but happens to be placed in EWRAM.
These data sections can be used to indicate different kinds of data symbols. For example, constants (C keyword `const`) should go into `.rodata`. Non-zero (and non-const, obviously) initialised data goes into `.data`, and zero or uninitialized data is to be placed into `.bss`. Now, you still have to indicate the amount of storage you need for each bss-variable. This can be done with ‘`.space `_`n`_’, which indicates _n_ zero bytes (see also `.fill` and `.skip`), or ‘`.comm `_`name`_`, `_`n`_`, `_`m`_’, which creates a bss symbol called _name_, allocates _n_ bytes for it and aligns it to _m_ bytes too. GCC likes to use this for uninitialized variables.
```c
// C symbols and their asm equivalents
// === C versions ===
int var_data= 12345678;
int var_zeroinit= 0;
int var_uninit;
const u32 cst_array[4]= { 1, 2, 3, 4 };
u8 charlut[256] EWRAM_BSS;
```
```armasm
@ === Assembly versions ===
@ Removed alignment and global directives for clarity
@ --- Non-zero Initialized data ---
.data
var_data:
.word 12345678
@ -- Zero initialized data ---
.bss
var_zeroinit:
.space 4
@ --- Uninitialized data ---
@ NOTE: .comm takes care of section, label and alignment for you
@ so those things need not be explicitly mentioned
.comm var_uninit,4,4
@ --- Constant (initialized) data ---
.section .rodata
cst_array:
.word 1, 2, 3, 4
@ --- Non-zero initialized data in ewram ---
.section .sbss
charlut:
.space 256
```
:::tip Assembly for data exporters
Assembly is a good format for exporting data to. Assembling arrays is faster than compilation, the files can be bigger and you can control alignment more easily. Oh, any you can't be tempted to #include the data, because that simply will not work.
```armasm
.section .rodata @ in ROM, please
.align 2 @ Word alignment
.global foo @ Symbol name
foo:
@ Array goes in here. Type can be .byte, .hword or .word
@ NOTE! No comma at the end of a line! This is important
.hword 0x0000,0x0001,0x0002,0x0003,0x0004,0x0005,0x0006,0x0007
.hword 0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x000F
.hword 0x0010,0x0011,0x0012,0x0013,0x0014,0x0015,0x0016,0x0017
...
```
You need a const section, word alignment, a symbol declaration and definition and the data in soe form of array. To make use of it, make a suitable declaration of the array in C and you're all set.
:::
### Code sections {#ssec-gas-csec}
That was data in different sections, now for code. The normal section for code is `.text`, which will equate to ROM or EWRAM depending on the linker specs. At times, you will want to have code in IWRAM because it's a lot faster than ROM and EWRAM. You might think that ‘`.section .iwram` does the trick, but unfortunately this does not seem generally true. Because IWRAM is actually a data section, you have to add section-type information here as well. The full section declaration needs to be ‘`.section .iwram, "ax", %progbits`’, which marks the section as allocatable and executable (`"ax"`), and that the section contains data as well (`%progbits`), although this last bit doesn't seem to be required.
Another interesting point is how to call the function once you have it in IWRAM. The problem is that IWRAM is too far away from ROM to jump to in one go, so to make it work you have to load the address of your function in a register and then jump to it using `bx`. And set `lr` to the correct return address, of course. The usual practice is to load the function's address into a register and branch to a dummy function that just consists of a `bx` using that register. GCC has these support functions under the name `_call_via_`_`rx`_, where _rx_ is the register you want to use. These names follow the GCC naming scheme as given in {@tbl:regnames}.
```armasm
@ --- ARM function in IWRAM: ---
.section .iwram, "ax", %progbits
.align 2
.arm
.global iw_fun
.type iw_fun STT_FUNC
iw_fun:
@
@ --- Calling iw_fun somewhere ---
ldr r3,=iw_fun @ Load address
bl _call_via_r3 @ Set lr, jump to long-call function
@ --- Provided by GCC: ---
_call_via_r3:
bx r3 @ Branch to r3's address (i.e., iw_fun)
@ No bl means the original lr is still valid
```
The `_call_by_`_`rx`_ indirect branching is how function calling works when you use the `-mlong-calls` compiler flag. It's a little slower than straight branching, but generally safer. Incidentally, this is also how interworking is implemented.
:::note Standard and special sections
Sections `.text`, `.data` and `.bss` are standard GAS sections and do not need explicit mention of the `.section` directive. Sections `.ewram`, `.iwram`, `.rodata` and `.sbss` and more GBA specific, and do need `.section` in front of them.
:::
With this information, you should be able to create functions, variables and even place them into the right sections. This is probably 90% of whay you might want to do with directives already. For the remaining few, read the manual or browse through GCC generated asm. Both should point you in the right direction.
## A real world example: fast 16/32-bit copiers {#sec-cpy}
In the last section, I will present two assembly functions – one ARM and one Thumb – intended for copying data quickly and with safety checks for alignment. They are called `memcpy16()` and `memcpy32()` and I have already used these a number of times throughout Tonc. `memcpy32()` does what `CpuFastSet()` does, but without requiring that the word-count is a multiple of 8. Because this is a primary function, it's put in IWRAM as ARM code. `memcpy16()` is intended for use with 16bit data and calls `memcpy32()` if alignments of the source and destination allow it and the number of copies warrant it. Because its main job is deciding whether to use `memcpy32`, this function can stay in ROM as Thumb code.
This is not merely an exercise; these functions are there to be used. They are optimized and take advantage of most of the features of ARM/Thumb assembly. Nearly everything covered in this chapter can be found here, so I hope you've managed to keep up. To make things a little easier, I've added the C equivalent code here too, so you can compare the two.
Also, these functions are not just for pure assembly projects, but can also be used in conjunction with C code, and I'll show you how to do this too. As you've already seen demos using these functions without any hint that they were assembly functions (apart from me saying so), this part isn't actually to hard. So that's the program for this section. Ready? Here we go.
### memcpy32() {#ssec-cpy-32}
This function will copy words. _Fast_. The idea is to use 8-fold block-transfers where possible (just like `CpuFastSet()`), and then copy the remaining 0 to 7 words of the word count with simple transfers. Yes, one could make an elaborate structure of tests and block-transfers to do these residuals in one go as well, but I really don't think that's worth it.
One could write a function for this in C, which is done below. However, even though GCC does use block-transfers for the BLOCK struct-copies, I've only seen it go up to 4-fold `ldm/stm`s. Furthermore, it tends to use more registers than strictly necessary. You could say that GCC doesn't do its job properly, but it's hard to understand what humans mean, alright? If you want it done as efficient as possible, do it your damn self. Which is exactly what we're here to do, of course.
```c
// C equivalent of memcpy32
typedef struct BLOCK { u32 data[8]; } BLOCK;
void memcpy32(void *dst, const void *src, uint wdcount) IWRAM_CODE
{
u32 blkN= wdcount/8, wdN= wdcount&7;
u32 *dstw= (u32*)dst, *srcw= (u32*)src;
if(blkN)
{
// 8-word copies
BLOCK *dst2= (BLOCK*)dst, *src2= (BLOCK*)src;
while(blkN--)
*dst2++ = *src2++;
dstw= (u32*)dst2; srcw= (u32*)src2;
}
// Residual words
while(wdN--)
*dstw++ = *srcw++;
}
```
The C version should be easy enough to follow. The number of words, `wdcount` is split into a block count and residual word count. If there are full block to copy, then we do so and adjust the pointers so that the residuals copy correctly. Note that `wdcount` is the number of words to copy, not the number of bytes, and that `src` and `dst` are assumed to be word-aligned.
The assembly version –surprise, surprise– does exactly the same thing, only much more efficient than GCC will make it. There is little I can add about what it does because all things have been covered already, but there are a few things about _how_ it does them that deserve a little more attention.
First, note the general program flow. The `movs` gives the number of blocks to copy, and if that's zero then we jump immediately to the residuals, `.Lres_cpy32`. What happens there also interesting: the three instructions after decrementing the word-count (in `r12`) all carry the `cs` flag. This means that if `r12` is (unsigned) lower than one, (i.e., `r12`==0) these instructions are ignored. This is exactly what we want, but usually there is a separate check for zero-ness before the body of the loop and these extra instructions cost space and time. With clever use of conditionals, we can spare those.
The main loop doesn't use these conditionals, nor, it would seem, a zero-check. The check here is actually done at that `movs` lines as well: if it doesn't jump, we can be sure there are blocks to copy, so another check is unnecessary. Also note that the non-scratch registers `r4-r10` are only stacked when we're sure they'll actually be used. GCC normally stacks at the beginning and end of functions, but there is no reason not to delay it until it's actually necessary.
Lastly, a few words on non-assembly matters. First, the general layout: I use one indent for everything except labels, and sometimes more for what in higher languages would be loops or if-blocks. Neither is required, but I find that it makes reading easier. I also make sure that the instruction parameters are all in line, which works best if you reserve 8 spaces for the mnemonic itself. How you set the indents is a matter of personal preference and a subject of many holy wars, so I'm not touching that one here :P
Another point is comments. Comments are even more important in assembly than in C, but don't overdo it! Overcommenting just drowns out the comments that are actually useful and maybe even the code as well. Comment on blocks and what each register is and maybe on important tests/branches, but do you really have to say that ‘`subs r2, r2, #1`’ decrements a loop variable? No, I didn't think so either. It might also help to give the intended declaration of the function if you want to use it in C.
Also, it's a good idea to always add section, alignment and code-set before a function-label. Yes, these things aren't strictly necessary, but what if some yutz decides to add a function in the middle of the file which screws up these things for functions that follow it? Lastly, try to distinguish between symbol-labels and branch-labels. GCC's take on this is starting the latter with ‘`.L`’, which is as good of a convention as any.
```armasm
@ === void memcpy32(void *dst, const void *src, uint wdcount) IWRAM_CODE; =============
@ r0, r1: dst, src
@ r2: wdcount, then wdcount>>3
@ r3-r10: data buffer
@ r12: wdn&7
.section .iwram,"ax", %progbits
.align 2
.code 32
.global memcpy32
.type memcpy32 STT_FUNC
memcpy32:
and r12, r2, #7 @ r12= residual word count
movs r2, r2, lsr #3 @ r2=block count
beq .Lres_cpy32
push {r4-r10}
@ Copy 32byte chunks with 8fold xxmia
@ r2 in [1,inf>
.Lmain_cpy32:
ldmia r1!, {r3-r10}
stmia r0!, {r3-r10}
subs r2, #1
bne .Lmain_cpy32
pop {r4-r10}
@ And the residual 0-7 words. r12 in [0,7]
.Lres_cpy32:
subs r12, #1
ldrcs r3, [r1], #4
strcs r3, [r0], #4
bcs .Lres_cpy32
bx lr
```
### memcpy16() {#ssec-cpy-16}
The job of the halfword copier `memcpy16()` isn't really copying halfwords. If possible, it'll use `memcpy32()` for addresses that can use it, and do the remaining halfword parts (if any) itself. Because it doesn't do much copying on its own we don't have to waste IWRAM with it; the routine can stay as a normal Thumb function in ROM.
Two factors decide whether or not jumping to `memcpy32()` is beneficial. First is the number of halfwords (`hwcount`) to copy. I've ran a number of checks and it seems that the break-even point is about 6 halfwords. At that point, the power of word copies in IWRAM already beats out the cost of function-call overhead and Thumb/ROM code.
The second is whether the incoming source and destination addresses can be resolved to word addresses. This is true if bit 1 of the source and destinations are equal (bit 0 is zero because these are valid halfword addresses), in other words: `(src^dst)&2` should not be zero. If it resolvable, do one halfword copy to word-align the addresses if necessary, then call `memcpy32()` for all the word copies. After than, adjust the original halfword stuff and if there is anything left (or if `memcpy32()` couldn't be used) copy by halfword.
```c
// C equivalent of memcpy16
void memcpy16(void *dst, const void *src, uint hwcount)
{
u16 *dsth= (u16*)dst, *srch= (u16*)src;
// Fast-copy if and only if:
// (1) enough halfwords and
// (2) equal src/dst alignment
if( (hwcount>5) && !(((u32)dst^(u32)src)&2) )
{
if( ((u32)src)&1 ) // (3) align to words
{
*dsth++= *srch++;
hwcount--;
}
// (4) Use memcpy32 for main stint
memcpy32(dsth, srch, hwcount/2);
// (5) and adjust parameters to match
srch += hwcount&~1;
dsth += hwcount&~1;
hwcount &= 1;
}
// (6) Residual halfwords
while(hwcount--)
*dsth++ = *srch++;
}
```
The C version isn't exactly pretty due to all the casting and masking, but it works well enough. If you were to compile it and compare it to the assembly below you should see many similarities, but it won't be exactly equal because the assembly programmer is allowed greater freedoms than GCC, and doesn't have to contend with the syntax of C.
Anyway, before the function actually starts I state the declaration, the use of the registers, and the standard boilerplate for functions. As I need more than 4 registers and I'm calling a function, I need to stack `r4` and `lr`. This time I am doing this at the start and end of the function because it's just too much of a hassle not to. One thing that may seem strange is why I pop `r4` and then `r3` separately, especially as it's `lr` that I need and not `r3`. Remember the register restrictions: `lr` is actually `r14`, which can be reached by `push`, but not `pop`. So I'm using `r3` here instead. I'm also doing this separately from the `r4`-pop because ‘`pop {r4,r3}`’ pops the registers in the wrong order (lower regs are loaded first).
The rest of the code follows the structure of the C code; I've added numbered points to indicate where we are. Point 1 checks the size, and point 2 checks the relative alignment of source and destination. Note that what I actually do here is not AND with 2, but shift by 31, which pushes bit 1 into the carry bit; Thumb code can only AND between registers and rather than putting 2 in a register and ANDing, I just check the carry bit. You can also use the sign bit to shift to, of course, which is what GCC would do. I do something similar to check whether the pointers are already word-aligned or if I have to do that myself.
At point 4 I set up and call `memcpy32()`. Or, rather, I call `_call_via_r3`, which calls `memcpy32()`. I can't use ‘`bl memcpy32`’ directly because its in IWRAM and `memcpy16()` is in ROM and the distance is simply too big. The `_call_via_r3` is an intermediary (in ROM) consisting only of ‘`bx r3`’ and since `memcpy32()`'s address was in `r3` we got where we wanted to go. Returning from `memcpy32()` will work fine, as that was set by the call to `_call_via_r3`.
The C code's point 5 consisted of adjusting the source and destination pointers to account for the work done by `memcpy32()`; in the assembly code, I'm being a very sneaky bastard by not doing any of that. The thing is, after `memcpy32()` is done `r0` and `r1` would _already_ be where I want them; while the rules say that `r0-r3` are clobbered by calling functions and should therefore be stacked, if I _know_ that they'll only end up the way I want them, do I really have to do the extra work? I think not. Fair enough, it's not recommended procedure, but where's the fun in asm programming if you can't cheat a little once in a while? Anyway, the right-shift from `r4` counters the left-shift into `r4` that I had before, corresponding to a `r2&1`; the test after it checks whether the result is zero, signifying that I'm done and I can get out now.
Lastly, point 6 covers the halfword copying loop. I wouldn't have mentioned it here except for one little detail: the array is copied back to front! If this were ARM code I'd have used post-indexing, but this is Thumb code where no such critter exists and I'm restricted to using offsets. I could have used another register for an ascending offset (one extra instruction/loop), or incrementing the `r0` and `r1` (two extra per loop), or I could copy backwards which works just as well. Also note that I use `bcs` at the end of the loop and not `bne`; `bcs` is essential here because `r2` could already be 0 on the first count, which `bne` would miss.
```armasm
@ === void memcpy16(void *dst, const void *src, uint hwcount); =============
@ Reglist:
@ r0, r1: dst, src
@ r2, r4: hwcount
@ r3: tmp and data buffer
.text
.align 2
.code 16
.thumb_func
.global memcpy16
.type memcpy16 STT_FUNC
memcpy16:
push {r4, lr}
@ (1) under 5 hwords -> std cpy
cmp r2, #5
bls .Ltail_cpy16
@ (2) Unreconcilable alignment -> std cpy
@ if (dst^src)&2 -> alignment impossible
mov r3, r0
eor r3, r1
lsl r3, #31 @ (dst^src), bit 1 into carry
bcs .Ltail_cpy16 @ (dst^src)&2 : must copy by halfword
@ (3) src and dst have same alignment -> word align
lsl r3, r0, #31
bcc .Lmain_cpy16 @ ~src&2 : already word aligned
@ Aligning is necessary: copy 1 hword and align
ldrh r3, [r1]
strh r3, [r0]
add r0, #2
add r1, #2
sub r2, #1
@ (4) Right, and for the REAL work, we're gonna use memcpy32
.Lmain_cpy16:
lsl r4, r2, #31
lsr r2, r2, #1
ldr r3,=memcpy32
bl _call_via_r3
@ (5) NOTE: r0,r1 are altered by memcpy32, but in exactly the right
@ way, so we can use them as is.
lsr r2, r4, #31
beq .Lend_cpy16
@ (6) Copy residuals by halfword
.Ltail_cpy16:
sub r2, #1
bcc .Lend_cpy16 @ r2 was 0, bug out
lsl r2, r2, #1 @ r2 is offset (Yes, we're copying backward)
.Lres_cpy16:
ldrh r3, [r1, r2]
strh r3, [r0, r2]
sub r2, r2, #2
bcs .Lres_cpy16
.Lend_cpy16:
pop {r4}
pop {r3}
bx r3
```
### Using memcpy32() and memcpy16() in C {#ssec-cpy-c}
While you're working on uncrossing your eyes, a little story on how you can call these functions from C. It's ridiculously simple actually: all you need is a declaration. Yup, that's it. GCC does really care about the language the functions are in, all it asks is that they have a consistent memory interface, as covered in the AAPCS. As I've kept myself to this standard (well, mostly), there is no problem here.
```c
// Declarations of memcpy32() and memcpy16()
void memcpy16(void *dst, const void *src, uint hwcount);
void memcpy32(void *dst, const void *src, uint wdcount) IWRAM_CODE;
// Example use
{
extern const u16 fooPal[256];
extern const u32 fooTiles[512];
memcpy16(pal_bg_mem, fooPal, 256); // Copy by halfword. Fine
memcpy32(pal_bg_mem, fooPal, 256/2); // Copy by word; Might be unsafe
memcpy32(tile_mem, fooTiles, 512); // Src is words too, no prob.
}
```
See? They can be called just as any other C function. Of course, you have to assemble and link the assembly files instead of #include them, but that's how you're supposed to build projects anyway.
You do need to take care to provide the **correct** declaration, though. The declaration tells the compiler how a function expects to be called, in this case destination and source pointers (in that order), and the number of (half)words to transfer. It is legal to change the order of the parameters or to add or remove some – the function won't _work_ anymore, but the compiler does allow it. This is true of C functions too and should be an obvious point, but assembly functions don't provide an easy check to determine if you've used the correct declaration, so please be careful.
:::tip Make the declaration fit the function
This is a very important point. Every function has expectations on how it's called. The section, return-type and arguments of the declaration must match the function's, lest chaos ensues. The best way would be not explicitly mention the full declaration near the function definition, so that the user just has to copy-paste it.
:::
:::tip Use 'extern "C"' for C++
Declarations for C++ work a little different, due to the [name mangling](https://en.wikipedia.org/wiki/Name_mangling) it expects. To indicate that the function name is _not_ mangled, add ‘`extern "C"`’ to the declaration.
```c++
// C++ declarations of memcpy32() and memcpy16()
extern "C" void memcpy16(void *dst, const void *src, uint hwcount);
extern "C" void memcpy32(void *dst, const void *src, uint wdcount) IWRAM_CODE;
```
:::
And that all folks. As far as this chapter goes anyway. Like all languages, it takes time to fully learn its ins and outs, but with this information and a couple of (quick)reference documents, you should be able to produce some nice ARM assembly, or at least be able to read it well enough. Just keep your wits about you when writing assembly, please. Not just in trying to avoid bugs, but also in keeping the assembly maintainable. Not paying attention in C is bad enough, but here it can be absolutely disastrous. Think of what you want to do first, _then_ start writing the instructions.
Also remember: yes, assembly can be fun. Think of it as one of those shuffle-puzzles: you have a handful of pieces (the registers) and ways of manipulating them. The goal is to get to the final picture in then least amount of moves. For example, take a look at what an [optimized palette blend routine](https://gbadev.net/forum-archive/thread/8/6721.html#53322) would look like. Now it's your turn :P.