<commit_before>---
layout: post
title:  "Syntactic sugarcoating for memory mapped registers"
date:   2016-03-30 19:00:00
categories: embedded C programming
permalink: /articles/register-syntax-sugar
---

Most instruction set architectures (ISAs) nowadays utilize [memory mapped IO][MMIO] (MMIO). Some address ranges are decoded as being directed at IO devices instead of RAM.

For example, on the ARM Cortex-M, the System tick timer's control register is located at `0xE000E010`.
If you wish to calibrate the timer, you can do this easily from C with a tiny bit of pointer fiddling:

```c
*(unsigned long volatile *)0xE000E010 = 5;
```
or the more readable

```c
typedef unsigned long volatile reg;
#define SYSTICK_CTRL (*(reg*)0xE000E010)
SYSTICK_CTRL = 5;
```

In this post, I want to compare different approaches of wrapping access to such a register.




## Approach I: Least effort ##

```c
*(unsigned long volatile *)0xE000E010 = 5;
```

**Pros:** It works and it won't get any faster than that.

The syntax used is standard C syntax, casting integers (`0xE000E010` is an `unsigned int`[^1]) to pointers is implementation-defined behavior, but if you deal with MMIO, the implementation should do the right thing with it.

> The `volatile` is necessary because the compiler is inclined to believe that all variables are its own. Thus running: `*(unsigned long*)0xE000E010 = 0; *(unsigned long*)0xE000E010 = 1;` is the same as `*(unsigned long*)0xE000E010 = 1; ` as far as the compiler is concerned because the `0` is overwritten anyway. 
> 
> With MMIO though, writing has a real world side effect that need not be optimized away. This is the main use for `volatile`[^2].

**Cons:** Magic numbers are bad. You won't get rid of them, but at least put them in a header.

```c
#define SYSTICK_CTRL 0xE000E010
*(unsigned long*)SYSTICK_CTRL = 0
```

isn't much better, so let's skip that one.

Before we move on, let's have a look at the THUMB assembly GCC generated[^3]:

```c
; *(unsigned long volatile *)0xE000E010 = 5;
  b6:	f24e 0310 	movw	r3, #57360	; 0xe010
  ba:	f2ce 0300 	movt	r3, #57344	; 0xe000
  be:	2205      	movs	r2, #5
  c0:	601a      	str	r2, [r3, #0]
```

`r3` will point to our SysTick register. `r2` has the `5` we want to put in. The THUMB ISA doesn't support moving 32 bit immediates at once, so we have a move for the lower 16 bits of the address, then a 16 bit move for the top bits. Finally we store `r3[0]` (i.e. `*r3`) into `r2`.

## Approach II: The usual ##

Probably the most widely used

```c
#define SYSTICK_CTRL (*(unsigned long volatile*)0xE000E010)
SYSTICK_CTRL = 5;
```

After preprocessing, you get the same output as Approach I. But this is more readable and has the magic numbers moved out of the way. You can go the extra mile and have a global header with all addresses, which you then include into the `SysTick.h` header. This is particularly useful, if addresses were to change. Say, you are writing a cheat tool for a game and need to maintain pointers to your health and ammo count. Having all the addresses at one place makes it a bit more straight forward to update the addresses, when the game itself gets updated.

## Approach III: Accessors ##
We won't talk a lot about this one, but for completion's sake:

```c
static inline void setSysTickCtrl(unsigned long x) {
    SYSTICK_CTRL = x;
}

static inline unsigned long getSysTickCtrl(void) {
    return SYSTICK_CTRL;
}
```

The common setter/getter pattern. C99's `inline` is a hint at the compiler, that this function should be inlined (i.e. copy-pasted) into the calling code. `static` specifies internal [linkage], which means the compiler need not expect another function outside the current translation unit (standardese for source file) to call this function.

This approach has [no overhead][inline] but I find it ugly. Having getters and setters allows for mocking out parts for unit testing, but I think mocking should happen at the driver not at the register level.

One could write this as macros at the cost of type safety, but for this, it wouldn't matter.

## Approach IV: Pointer to array##

Controlling SysTick involves 4 sequential registers in memory. Instead of defining every one, we just define the base as an array and use an index

```c
enum {SYSTICK_CTRL, SYSTICK_LOAD, SYSTICK_VAL, SYSTICK_CAL};
unsigned long volatile (*SysTick)[4] = (void*)0xE000E010;
SysTick[SYSTICK_CTRL] = 5;
SysTick[SYSTICK_VAL] = 0;
```

**Cons:** The `enum` looks ugly, but because enumeration constants share a single name space with other identifiers in C, you should prefix your enums, to avoid identifier clashes. Also, this approach isn't as safe, because you can avoid the enums and use integer indices directly. 

Additionally, `SysTick` is a global object. If we define it in more than one translation unit, the linker will complain. Solution: Make it `static`[^4]. The downside is that we need to silence[^5] warnings about including the header when we don't use `SysTick`.

Finally, the code generated can be[^6] suboptimal:

```c
; SysTick[SYSTICK_CTRL] = 5;
  ba:	f240 0300 	movw	r3, #0
  be:	f2c2 0300 	movt	r3, #8192	; 0x2000
  c2:	681b      	ldr	r3, [r3, #0]
  c4:	2205      	movs	r2, #5
  c6:	601a      	str	r2, [r3, #0]<commit_msg>Fix syntax error in IV<commit_after>---
layout: post
title:  "Syntactic sugarcoating for memory mapped registers"
date:   2016-03-30 19:00:00
categories: embedded C programming
permalink: /articles/register-syntax-sugar
---

Most instruction set architectures (ISAs) nowadays utilize [memory mapped IO][MMIO] (MMIO). Some address ranges are decoded as being directed at IO devices instead of RAM.

For example, on the ARM Cortex-M, the System tick timer's control register is located at `0xE000E010`.
If you wish to calibrate the timer, you can do this easily from C with a tiny bit of pointer fiddling:

```c
*(unsigned long volatile *)0xE000E010 = 5;
```
or the more readable

```c
typedef unsigned long volatile reg;
#define SYSTICK_CTRL (*(reg*)0xE000E010)
SYSTICK_CTRL = 5;
```

In this post, I want to compare different approaches of wrapping access to such a register.




## Approach I: Least effort ##

```c
*(unsigned long volatile *)0xE000E010 = 5;
```

**Pros:** It works and it won't get any faster than that.

The syntax used is standard C syntax, casting integers (`0xE000E010` is an `unsigned int`[^1]) to pointers is implementation-defined behavior, but if you deal with MMIO, the implementation should do the right thing with it.

> The `volatile` is necessary because the compiler is inclined to believe that all variables are its own. Thus running: `*(unsigned long*)0xE000E010 = 0; *(unsigned long*)0xE000E010 = 1;` is the same as `*(unsigned long*)0xE000E010 = 1; ` as far as the compiler is concerned because the `0` is overwritten anyway. 
> 
> With MMIO though, writing has a real world side effect that need not be optimized away. This is the main use for `volatile`[^2].

**Cons:** Magic numbers are bad. You won't get rid of them, but at least put them in a header.

```c
#define SYSTICK_CTRL 0xE000E010
*(unsigned long*)SYSTICK_CTRL = 0
```

isn't much better, so let's skip that one.

Before we move on, let's have a look at the THUMB assembly GCC generated[^3]:

```c
; *(unsigned long volatile *)0xE000E010 = 5;
  b6:	f24e 0310 	movw	r3, #57360	; 0xe010
  ba:	f2ce 0300 	movt	r3, #57344	; 0xe000
  be:	2205      	movs	r2, #5
  c0:	601a      	str	r2, [r3, #0]
```

`r3` will point to our SysTick register. `r2` has the `5` we want to put in. The THUMB ISA doesn't support moving 32 bit immediates at once, so we have a move for the lower 16 bits of the address, then a 16 bit move for the top bits. Finally we store `r3[0]` (i.e. `*r3`) into `r2`.

## Approach II: The usual ##

Probably the most widely used

```c
#define SYSTICK_CTRL (*(unsigned long volatile*)0xE000E010)
SYSTICK_CTRL = 5;
```

After preprocessing, you get the same output as Approach I. But this is more readable and has the magic numbers moved out of the way. You can go the extra mile and have a global header with all addresses, which you then include into the `SysTick.h` header. This is particularly useful, if addresses were to change. Say, you are writing a cheat tool for a game and need to maintain pointers to your health and ammo count. Having all the addresses at one place makes it a bit more straight forward to update the addresses, when the game itself gets updated.

## Approach III: Accessors ##
We won't talk a lot about this one, but for completion's sake:

```c
static inline void setSysTickCtrl(unsigned long x) {
    SYSTICK_CTRL = x;
}

static inline unsigned long getSysTickCtrl(void) {
    return SYSTICK_CTRL;
}
```

The common setter/getter pattern. C99's `inline` is a hint at the compiler, that this function should be inlined (i.e. copy-pasted) into the calling code. `static` specifies internal [linkage], which means the compiler need not expect another function outside the current translation unit (standardese for source file) to call this function.

This approach has [no overhead][inline] but I find it ugly. Having getters and setters allows for mocking out parts for unit testing, but I think mocking should happen at the driver not at the register level.

One could write this as macros at the cost of type safety, but for this, it wouldn't matter.

## Approach IV: Pointer to array##

Controlling SysTick involves 4 sequential registers in memory. Instead of defining every one, we just define the base as an array and use an index

```c
enum {SYSTICK_CTRL, SYSTICK_LOAD, SYSTICK_VAL, SYSTICK_CAL};
unsigned long volatile (*SysTick)[4] = (void*)0xE000E010;
(*SysTick)[SYSTICK_CTRL] = 5;
(*SysTick)[SYSTICK_VAL] = 0;
```

**Cons:** The `enum` looks ugly, but because enumeration constants share a single name space with other identifiers in C, you should prefix your enums, to avoid identifier clashes. Also, this approach isn't as safe, because you can avoid the enums and use integer indices directly. 

Additionally, `SysTick` is a global object. If we define it in more than one translation unit, the linker will complain. Solution: Make it `static`[^4]. The downside is that we need to silence[^5] warnings about including the header when we don't use `SysTick`.

Finally, the code generated can be[^6] suboptimal:

```c
; SysTick[SYSTICK_CTRL] = 5;
  ba:	f240 0300 	movw	r3, #0
  be:	f2c2 0300 	movt	r3, #8192	; 0x2000
  c2:	681b      	ldr	r3, [r3, #0]
  c4:	2205      	movs	r2, #5
  c6:	601a      	str	r2, [r3, #0]
{'fraction_non_alphanumeric': 0.0835156472938267, 'fraction_numerical': 0.04280414724626653, 'mean_word_length': 4.228244654400796, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3388492', 'n_tokens_mistral': 3556, 'n_tokens_neox': 3151, 'n_words': 1607}