45 Commits
v0.1 ... v0.4

Author SHA1 Message Date
Nicolas Clauvelin
6433346d01 Merge branch 'cleanup' 2019-04-24 17:03:09 -04:00
Nicolas Clauvelin
a6f09754ca Add Gitlab templates 2019-04-24 17:02:17 -04:00
Nicolas Clauvelin
c1081a114e Code maintenance
* Revise and simplify most enable_if statements in the project.
* Update code style in all files.
* Update copyright year.
* Add a dedicated Memory.h header with the memory device implementation.
* Update documentation.
* CMake cleanup.
2019-04-24 17:00:57 -04:00
Nicolas Clauvelin
2e0d502674 BUG FIX IN MERGER WRITE IMPLEMENTATION FOR NON CONSTANT VALUES
* For write-only registers the merge write implementation for non-constant values
was properly updating the cache value.
* Unnecessary `inline` have been removed.
2018-11-16 09:28:47 -05:00
Nicolas Clauvelin
e59bc356c8 FIX CASE ISSUE 2018-03-29 06:33:59 -04:00
Nicolas Clauvelin
e763c2bfa8 FIX TYPOS AND OTHER MINOR DETAILS IN PERFORMANCE EXAMPLE
This also adds a link in the README to the performance page.
2018-03-29 06:33:59 -04:00
4b85835035 Removed mention of full example 2018-03-29 06:33:59 -04:00
cd4448b330 Updated to new CPPReg and for the most part done with performance comparison 2018-03-29 06:33:59 -04:00
435e038315 Updated performance.md 2018-03-29 06:33:59 -04:00
5a2a351791 Initial work on comparison 2018-03-29 06:33:59 -04:00
Nicolas Clauvelin
c48108be64 ADD CODE OF CONDUCT 2018-03-21 13:13:24 -04:00
Nicolas Clauvelin
203443c1f8 ADD HARDWARE AND COMPILER REQUIREMENTS TO README
This closes #11.
2018-03-21 13:05:07 -04:00
Nicolas Clauvelin
819a004588 API DOCUMENTATION UPDATED
Register pack loop revised for consistency.
2018-03-20 11:20:42 -04:00
Nicolas Clauvelin
c6c2c5055a UPDATED DOCUMENTATION 2018-03-20 08:38:44 -04:00
Nicolas Clauvelin
8d2cdbf25f UPDATED API DOCUMENTATION
This is related to #12.
2018-03-16 15:09:34 -04:00
Nicolas Clauvelin
5925c223c8 INTERNAL IMPLEMENTATIONS RELOCATED TO AN INTERNALS HEADER
The Internals.h contains the overflow, is_aligned and memory array
implementations.
2018-03-16 14:12:52 -04:00
Nicolas Clauvelin
6085f47115 ADD MISSING NEWLINE 2018-03-16 07:53:14 -04:00
Nicolas Clauvelin
53b74b2b5c FIX QUICK START DOCUMENTATION 2018-03-16 07:53:00 -04:00
Nicolas Clauvelin
8cdc89336f UPDATED SINGLE HEADER 2018-03-15 17:25:06 -04:00
Nicolas Clauvelin
23a5580d2b MINOR FIXES FOR CONSISTENCY PURPOSES 2018-03-15 17:24:03 -04:00
Nicolas Clauvelin
95288090d4 ADD ENUMERATION TYPE FOR SUPPORTED REGISTER SIZES
Register sizes are now represented by an enumeration type. This limits the
possibility to typeset unsupported register sizes, and make the interface easier
to read.

See #12.
2018-03-15 17:13:54 -04:00
Nicolas Clauvelin
c217f34e0c REVISED CHECKS FOR PACKED REGISTER ALIGNMENT
This now relies on a is_aligned implementation. This will needs to be adapted
once register width is defined through an enumeration.

See #12.
2018-03-15 16:16:42 -04:00
Nicolas Clauvelin
1590e7c0e3 UPDATED QUICK START DOCUMENTATION FOR NEW PACK API 2018-03-14 13:15:20 -04:00
Nicolas Clauvelin
6a99ea5de6 UPDATED SINGLE HEADER 2018-03-13 17:44:47 -04:00
Nicolas Clauvelin
7b9a843e2d ADD MORE FUNCTIONALITY TO THE TEMPLATE FOR LOOP IMPLEMENTATION
This adds a C++14 apply method that can be used with polymorphic lambdas.
2018-03-13 17:29:15 -04:00
Nicolas Clauvelin
8ce22c666d REVISED OVERFLOW IMPLEMENTATION USING INTEGRAL CONSTANT
The check_overflow implementation now relies on std::integral_constant.
This avoids the definition of a constexpr bool member.
2018-03-13 17:28:38 -04:00
Nicolas Clauvelin
ee48bbd261 FIX FOR LOOP IMPLEMENTATION AND ADD RANGE LOOP
* Fixes a typo in the for_loop implementation.
* Add a range_loop implementation to help with indexed register pack.
2018-03-13 11:01:34 -04:00
Nicolas Clauvelin
49d19f1b20 FIX TYPO IN PACKED REGISTER STATIC ASSERT 2018-03-13 08:51:23 -04:00
Nicolas Clauvelin
bbdf513156 ADD MIXED REGISTER SIZES SUPPORT TO REGISTER PACK
This relies on a memory map implementation based on std::array and specialized
over the register size. PackedRegister can now be used with all supported
register sizes (i.e., widths).

This relates to #7 and the finalization of the API before performance testing.
2018-03-13 08:48:42 -04:00
Nicolas Clauvelin
ae6da9b7f5 REVISED REGISTER PACK IMPLEMENTATION FOR SIZE ISSUES
The revision brings the support for 16-bits and 32-bits registers.
2018-03-12 22:18:54 -04:00
Nicolas Clauvelin
984d4ceb58 ADD TEMPLATE FOR LOOP IMPLEMENTATION 2018-03-12 17:51:00 -04:00
Nicolas Clauvelin
327e230847 ADD PROPER DOCUMENTATION COMMENTS 2018-03-12 17:20:32 -04:00
Nicolas Clauvelin
4d575c176f UPDATED SINGLE HEADER 2018-03-12 16:37:29 -04:00
Nicolas Clauvelin
154b29bef3 REGISTER PACK FIRST IMPLEMENTATION 2018-03-12 16:35:36 -04:00
Nicolas Clauvelin
e4ae5641ec CPPREG MEMORY ACCESS REVISION
All access to memory are now done through reference (const reference for
read-only access). This is done to facilitate the implementation of register
packs.
2018-03-12 16:35:26 -04:00
Nicolas Clauvelin
f1d98d6bd5 REVISED SHADOW VALUE USING INTEGRAL CONSTANT
This provides a clearer interface compared to defining a constexpr bool member.
2018-03-11 17:34:38 -04:00
Nicolas Clauvelin
058ccbf13d UPDATED DOCUMENTATION FOR REVISED API
This closes #10.
2018-03-11 09:27:03 -04:00
Nicolas Clauvelin
eb9226fe5d API REVISED FOR BETTER READ/WRITE PERFORMANCE
* For trivial read/write operations (over whole register) simpler implementations are now used to avoid unnecessary load/store instructions.
* Merge write implementation has been revised to provide better performance when manipulating constant values.
* `is_set` and `is_clear` are now available for all Field-based types.

This closes #8.
2018-03-09 16:31:56 -05:00
Nicolas Clauvelin
1c27f907a5 FIXES CONSTEXPR STATIC ISSUE WITH GCC 4.8.X
See https://github.com/sendyne/cppreg/issues/2 for a detailed explanation.

This closes #2.
2018-02-23 06:15:58 -05:00
hak8or
816c579d7d Pin in Led::init() should be off before setting pin direction
Super minor, but I figured it might be good to have that looking correct in the getting started guide.
2018-02-23 05:48:37 -05:00
Nicolas Clauvelin
11734b0bf4 FIX POWERPC COMPILATION ISSUE
For some reason compilers other than GCC PowerPC 4.5.8 were not complaining
about the `use_shadow` being (re)defined outside the `Shadow` structure
definition.

This closes #2.
2018-02-22 17:02:59 -05:00
Sendyne Principal Scientist
926eb71df2 Set theme jekyll-theme-cayman 2018-02-22 10:39:37 -05:00
Nicolas Clauvelin
93763cd6ee Merge remote-tracking branch 'github/master' into develop 2018-02-22 10:35:06 -05:00
Nicolas Clauvelin
5cf8a851d8 FIX INLINING OF WRITE CALLS WITH Os ENABLED
The inlining issue was due to a bad template design in the access policies
implementations: the MMIO_t type from the field was used (which is a volatile
type) for all arguments in the write implementation.
The new implementation relies on two template types (one for the register memory
device and another one for the value to be written). This fixes inlining and was
checked on godbolt.
2018-02-22 10:22:51 -05:00
Sendyne dev-team
a31d4a2875 Set theme jekyll-theme-slate 2018-02-20 16:05:48 -05:00
31 changed files with 2548 additions and 1243 deletions

View File

@@ -0,0 +1,41 @@
### Summary
*(Summarize the bug or unexpected behavior encountered concisely)*
### Version and platform information
*(Give the commit/branch or version information of the project for which the bug was observed)*
*(If the bug was observed on a specific platform give the details here)*
### Customer information
*(If the bug was reported by a customer give the relevant details here)*
### Steps to reproduce
*(How can the bug be reproduced - be as accurate as possible)*
### What is the current *bug* behavior?
*(What actually happens: e.g. crash, wrong results, ...)*
### What is the expected *correct* behavior?
*(What you should be happening instead)*
### Relevant logs, screenshots, or inputs
*(Paste using code block (```) or attach any piece of information)*
*(If specific inputs are needed to observe the bug paste them or attach them)*
### Possible causes or fixes
*(If you have identified the cause of the bug or have a potential fix please link the line(s) of code and comment appropriately)*
*Final check: set origin label, set priority/severity if applicable*
*Clean up: remove any comment from the template if not applicable*
/label ~"kind:bug"

View File

@@ -0,0 +1,27 @@
### Questionnaire
* [ ] Issue related to GitLab project configuration?
* [ ] Issue related to project build process (e.g. toolchain)?
* [ ] Issue related to Git configuration (e.g. gitignore file)?
### Version information
*(Give the commit/branch or version information of the project for which this configuration issue needs to be considered)*
### Policy or guidelines reference
*(Refer here to the policy or guideline that relates to this issue and indicate if a violation or deviation should be addressed)*
### Details
*(Explain here or attach what should be done to fix this issue)*
### Attachments
*(Paste using code block (```) or attach any piece of information illustrating the issue)*
*Final check: set origin label, set priority/severity if applicable*
*Clean up: remove any comment from the template if not applicable*
/label ~"kind:configuration"

View File

@@ -0,0 +1,19 @@
### Questionnaire
* [ ] New or additional documentation needed?
* [ ] Current documentation is out of date or erroneous?
* [ ] Documentation needs review?
### Version information
*(Give the commit/branch or version information of the project for which this documentation issue needs to be considered)*
### Details
*(Explain here or attach what should be done to fix this issue)*
*Final check: set origin label, set priority/severity if applicable*
*Clean up: remove any comment from the template if not applicable*
/label ~"kind:documentation"

View File

@@ -0,0 +1,21 @@
### Problem to solve
*(What is the new feature trying to solve or provide?)*
### Customer information
*(If the feature was suggested by a customer give the relevant details here)*
### Proposal
*(Explain what this feature will bring in terms of benefits and how it fits in the project scope)*
### Links and references
*(Add links or references if applicable)*
*Final check: set origin label, set priority/severity if applicable*
*Clean up: remove any comment from the template if not applicable*
/label ~"kind:feature request"

View File

@@ -0,0 +1,21 @@
### Functionality to improve and goal
*(Explain what exactly needs to be improved and what is the goal)*
### Customer information
*(If the improvement was suggested by a customer give the relevant details here)*
### Proposal
*(Explain how the functionality could be improved and the various things to consider to achieve this goal)*
### Links and references
*(Add links or references if applicable)*
*Final check: set origin label, set priority/severity if applicable*
*Clean up: remove any comment from the template if not applicable*
/label ~"kind:improvement"

View File

@@ -0,0 +1,17 @@
### Question
*(Write the question as explicit as you can)*
### Customer information
*(If the question was submitted by a customer give the relevant details here)*
### Additional information
*(Add links, references, or any other piece of information)*
*Final check: set origin label, set priority/severity if applicable*
*Clean up: remove any comment from the template if not applicable*
/label ~"kind:question"

View File

@@ -0,0 +1,21 @@
### Requirement specifications
*(Give the details about the requirement that needs to be implemented)*
### Project information
*(If this issue relates to a requirement defined in a project specification existing somewhere give all references and information here)*
### Customer information
*(If the requirement was defined by a customer give the relevant details here)*
### Testing
*(Explain how the requirement implementation should be tested or how it fit in the current testing plan of the project)*
*Final check: set origin label, set priority/severity if applicable*
*Clean up: remove any comment from the template if not applicable*
/label ~"kind:requirement"

View File

@@ -0,0 +1,23 @@
### Summary of the MR
*(Explain what modifications are part of this MR; refer to issues or milestones if needed)*
### List of issues addressed by this MR
*(Edit the list of issues)*
* Closes #xxx
* Closes #xxx
* ...
### Additional information
* [ ] Does the MR update any submodule?
* [ ] Does the MR break any functionality or alter performance ?
* [ ] Does the MR require issues to be created to deal with side effects?
*(Give more details if needed)*
*Clean up: remove any comment from the template if not applicable*
/label ~"merge:review"

394
API.md
View File

@@ -1,109 +1,251 @@
# cppreg: API #
Copyright Sendyne Corp., 2010-2018. All rights reserved ([LICENSE](LICENSE)).
Copyright Sendyne Corp., 2010-2019. All rights reserved ([LICENSE](LICENSE)).
## Introduction ##
`cppreg` provides ways to define custom C++ data types to represent memory-mapped input/output (MMIO) registers and fields. In essence, `cppreg` does contain very little *executable* code, but it does provide a framework to efficiently manipulate MMIO registers and fields.
`cppreg` is primarily designed to be used in applications on *ARM Cortex-M*-like hardware, that is, MCUs with 32 bits registers and address space. It can easily be extended to support other types of architecture but this is not provided out-of-the-box.
The entire implementation is encapsulated in the `cppreg::` namespace. All the code examples assume this namespace is accessible (*i.e.*, `using namespace cppreg;` is implicit).
The entire implementation is encapsulated in the `cppreg::` namespace.
## Overview ##
`cppreg` provides two template structures that can be customized:
`cppreg` API makes it possible to:
* `Register`: used to define a MMIO register and its memory device,
* `Field`: used to define a field in a MMIO register.
* define a pack of registers: a register pack is simply a group of registers contiguous in memory (this is often the case when dealing with registers associated with a peripheral),
* define single register at a specific memory address: this is provided as a fallback when the register pack implementation cannot be used,
* define fields within registers (packed or not): a field corresponds to a group of bits within a register and comes with a specific access policy which control read and write access.
The `Register` type itself is simply designed to keep track of the register address, size and other additional data (*i.e.*, reset value and shadow value setting). The `Field` type is the most interesting one as it is the type that provides access to part of the register memory device depending on the access policy.
The API was designed such that `cppreg`-based code is safer and more expressive than traditional low-level code while providing the same level of performance.
As explained below, when using `cppreg`, registers and fields are defined as C++ types specializing pre-defined template types. This can be done by explicitly deriving from the specialized template type or by using the `using` keyword (both approaches are strictly equivalent). With the exception of the merged write mechanism discussed below, all methods provided by the `cppreg` types are static methods.
## Data types ##
`cppreg` introduces type aliases in order to parameterize the set of data types used in the implementation. By default the following types are defined (see [cppreg_Defines.h](cppreg_Defines.h) for more details):
* `Address_t` is the data type used to hold addresses of registers and fields; it is equivalent to `std::uintptr_t`,
* `Width_t` and `Offset_t` are the data types to represent register and field sizes and offsets; both are equivalent to `std::uint8_t` (this effectively limits the maximal width and offset to 256).
* `Address` is the data type used to hold addresses of registers and fields; it is equivalent to `std::uintptr_t`,
* register sizes are represented by the enumeration type `RegBitSize`,
* `FieldWidth` and `FieldOffset` are the data types to represent field sizes and offsets; both are equivalent to `std::uint8_t`.
The data type used to manipulate register and field content is derived from the register size. At the moment only 32-bits, 16-bits, and 8-bits registers are supported but additional register sizes can easily be added (see [Traits.h](register/Traits.h)).
### Register size ###
The `RegBitSize` enumeration type represents the register sizes supported in `cppreg` and the values are:
* `RegBitSize::b8` for 8-bit registers,
* `RegBitSize::b16` for 16-bit registers,
* `RegBitSize::b32` for 32-bit registers,
* `RegBitSize::b64` for 64-bit registers.
The register size is used to define the C++ data type that represent the register content in [Traits.h](Traits.h).
## Register ##
The `Register` type implementation (see [Register.h](register/Register.h)) is designed to encapsulate details relevant to a particular MMIO register and provides access to the register memory. In `cppreg` the data type used to represent the memory register is always marked as `volatile`.
## Register interface ##
In `cppreg`, registers are represented as memory locations that contain fields, and do not provide any methods by themselves. There are two possible ways to define registers:
To implement a particular register the following information are required at compile time:
* for registers which are part of a pack (*i.e.*, group) the `RegisterPack` and `PackedRegister` types should be used,
* for standalone register, the `Register` type is available.
* the address of the register,
* the register size (required to be different from `0`),
* the reset value of the register (this is optional and is defaulted to zero),
* a optional boolean flag to indicate if shadow value should be used (see below; this is optional and not enabled by default).
Most of the times registers are part of groups related to peripherals or specific functionalities within a MCU. It is therefore recommended to use the register pack implementation rather than the standalone one. This ensures that the assembly generated from `cppreg`-based code will be optimal. In other words, the difference between packed registers and standalone registers is only a matter of performance in the generated assembly: the packed register interface relies on mapping an array on the pack memory region, which provides to the compiler the ability to use offset between the various registers versus reloading their absolute addresses.
For example, consider a 32-bits register `PeripheralRegister` mapped at `0x40004242`. The `Register` type can be derived from to create a `PeripheralRegister` C++ type:
Moreover, the same level of functionality is provided by both implementations (`RegisterPack` is simply deriving from `Register`). That is, a packed register type can be replaced by a standalone register type (and *vice versa*).
### Register pack interface ###
To define a pack of registers:
1. define a `RegisterPack` type with the base address of the pack and the number of bytes,
2. define `PackedRegister` types for all the registers in the pack.
The interface is (see [RegisterPack.h](register/RegisterPack.h)):
* `struct RegisterPack<pack_base_address, pack_size_in_bytes>`:
| parameter | description |
|:---------------------|:-------------------------------------------|
| `pack_base_address` | starting address of the pack memory region |
| `pack_size_in_bytes` | size in bytes of the pack memory region |
* `struct PackedRegister<pack_type, RegBitSize_value, offset_in_bits, reset_value, use_shadow_value>`:
| parameter | description |
|:---------------------|:-------------------------------------------|
| `pack_type` | starting address of the pack memory region |
| `RegBitSize_value` | size in bytes of the pack memory region |
| `offset_in_bits` | offset in bits wrt pack base address |
| `reset_value` | register reset value (defaulted to zero) |
| `use_shadow_value` | enable shadow value if `true` (see below) |
Note that, the reset value is only used when shadow value support is enabled.
The following example defines a 4 bytes register pack starting at address 0xA4000000 and containing: two 8-bit register and a 16-bit register. The `cppreg` implementation is:
```c++
// Register is defined as a struct so public inheritance is the default.
struct PeripheralRegister : Register<0x40004242, 32u> {};
```
struct SomePeripheral {
If `PeripheralRegister` has a reset value of `0xF0220F00` it can be added to the type definition by adding a template parameter (this is only useful when enabling shadow value as explained later):
// Define a register pack:
// - starting at address 0xA4000000,
// - with a size of 4 bytes.
using SomePack = RegisterPack<0xA4000000, 4>;
// Strictly equivalent formlation:
// struct SomePack : RegisterPack<0xA4000000, 4> {};
```c++
struct PeripheralRegister : Register<0x40004242, 32u, 0xF0220F00> { ... };
```
Note that, it is also possible to simply define a type alias:
```c++
using PeripheralRegister = Register<0x40004242, 32u, 0xF0220F00>;
```
As we shall see below, the derived type `PeripheralRegister` is not very useful by itself. The benefit comes from using it to define `Field`-based types.
## Field ##
The `Field` type provided by `cppreg` (see [Field.h](register/Field.h)) contains the added value of the library in terms of type safety, efficiency and expression of intent. It is defined as a template structure and in order to define a custom field type the following information are required at compile time:
* a `Register`-type describing the register in which the field memory resides,
* the width of the field (required to be different from `0`),
* the offset of the field in the register,
* the access policy of the field (*i.e.*, read-write, read-only, or write-only).
Assume that the register `PeripheralRegister` from the previous example contains a 6-bits field `Frequency ` with an offset of 12 bits (with respect to the register base address; that is, starting at the 13-th bits because the first bit is the 0-th bit). The corresponding custom `Field` type would be defined as:
```c++
using Frequency = Field<PeripheralRegister, 6u, 12u, read_write>;
```
It can also be nested with the definition of `PeripheralRegister`:
```c++
// Register definition with nested field definition.
struct PeripheralRegister : Register<0x40004242, 32u> {
using Frequency = Field<PeripheralRegister, 6u, 12u, read_write>;
};
// This is strictly equivalent to:
namespace PeripheralRegister {
using _REG = Register<0x40004242, 32u>;
using Frequency = Field<_REG, 6u, 12u, read_write>;
// Define the first 8-bit register:
using FirstRegister = PackRegister<SomePack, RegBitSize::b8, 8 * 0>;
// Define the second 8-bit register:
// (the last template parameter indicates the offset in bits)
using SecondRegister = PackRegister<SomePack, RegBitSize::b8, 8 * 1>;
// Define the 16-bit register:
// (the last template parameter indicates the offset in bits)
using ThirdRegister = PackRegister<SomePack, RegBitSize::b16, 8 * 2>;
// Strictly equivalent formulation:
// struct FirstRegister : PackRegister<SomePack, RegBitSize::b8, 0> {};
// ...
}
// Or even:
// (again, Field is defined as a struct so public inheritance is the default.
struct PeripheralRegister : Register<0x40004242, 32u> {
struct Frequency : Field<PeripheralRegister, 6u, 12u, read_write> {};
};
```
which then makes it possible to write expression like:
There are a few requirements when defining packed registers:
* for a register of size N bits, the pack base address has to be aligned on a N bits boundary,
* for a register of size N bits, the pack base address plus the offset has to be aligned on a N bits boundary,
* the offset plus the size of register should be less or equal to the size of the pack.
These requirements are enforced at compile time and errors will be generated if there are not met.
### Standalone register interface ###
The interface for standalone register is (see [Register.h](register/Register.h)):
`struct Register<register_address, RegBitSize_value, reset_value, use_shadow_value>`:
| parameter | description |
|:---------------------|:-------------------------------------------|
| `register_address` | register absolute address |
| `RegBitSize_value` | size in bytes of the pack memory region |
| `reset_value` | register reset value (defaulted to zero) |
| `use_shadow_value` | enable shadow value if `true` (see below) |
Note that, the reset value is only used when shadow value support is enabled.
For example, consider a 32-bit register `SomeRegister` mapped at `0x40004242`. The `Register` type is created using:
```c++
PeripheralRegister::Frequency::clear();
PeripheralRegister::Frequency::write(0x10u);
using SomeRegister = Register<0x40004242, RegBitSize::b32>;
// Strictly equivalent formulation:
// struct PeripheralRegister : Register<0x40004242, RegBitSize::b32> {};
```
to clear the `Frequency` register and then write `0x10` to it.
Similarly to the packed register interface, for a N bits register the address is required to be aligned on a N bits boundary. This requirement is enforced at compile time and an error will be generated if not met.
As the last example suggests, any `Field`-based type must defines its access policy (the last template parameter). Depending on the access policy various static methods are available (or not) to perform read and write operations.
### Register pack goodies ###
`cppreg` provides a few additional goodies to simplify register packs usage. Let's consider the following peripheral with four registers, each containing a single read/write `Data`field:
```c++
struct Peripheral {
// Define a register pack:
// - starting at address 0xA4000000,
// - with a size of 4 bytes.
using Pack = RegisterPack<0xA4000000, 4>;
// Registers and fields:
struct Channel0 : PackedRegister<Pack, RegBistSize::b8, 8 * 0> {
using Data = Field<Channel0, 8u, 0u, read_write>;
};
struct Channel1 : PackedRegister<Pack, RegBistSize::b8, 8 * 1> {
using Data = Field<Channel0, 8u, 0u, read_write>;
};
struct Channel2 : PackedRegister<Pack, RegBistSize::b8, 8 * 2> {
using Data = Field<Channel0, 8u, 0u, read_write>;
};
struct Channel3 : PackedRegister<Pack, RegBistSize::b8, 8 * 3> {
using Data = Field<Channel0, 8u, 0u, read_write>;
};
}
```
`PackIndexing` can be used to easily access field in packed registers using indexes:
```c++
// Map indexes.
using Channels = PackIndexing<
Peripheral::Channel0::Data,
Peripheral::Channel1::Data,
Peripheral::Channel2::Data,
Peripheral::Channel3::Data
>;
// Read some data.
const auto x0 = Channels::elem<0>::read();
const auto x1 = Channels::elem<1>::read();
const auto x2 = Channels::elem<2>::read();
const auto x3 = Channels::elem<3>::read();
```
`cppreg` also provides a template-based for loop implementation to simplify such iterations:
```c++
// Map indexes.
using Channels = PackIndexing<
Peripheral::Channel0::Data,
Peripheral::Channel1::Data,
Peripheral::Channel2::Data,
Peripheral::Channel3::Data
>;
// Define a functor structure to collect data.
static std::array<std::uint8_t, Channels::n_elems> some_buffer = {};
struct ChannelsCollector {
template <std::size_t index>
void operator()() {
some_buffer[index] = Channels::elem<index>::read();
};
};
// Iterate over the pack.
pack_loop<Channels>::apply<ChannelsCollector>();
```
If C++14 is used, another version of the loop is also available that makes it possible to use polymorphic lambdas:
```c++
// Map indexes.
using Channels = PackIndexing<
Peripheral::Channel0::Data,
Peripheral::Channel1::Data,
Peripheral::Channel2::Data,
Peripheral::Channel3::Data
>;
// Define a buffer to collect data.
static std::array<std::uint8_t, Channels::n_elems> some_buffer = {};
// Iterate over the pack and use a lambda.
// Note the "auto index" ... this is required because the loop will
// use std::integral_constant to pass the index while iterating.
pack_loop<Channels>::apply([](auto index) {
some_buffer[index] = Channels::elem<index>::read();
Channels::elem<index>::template write<index>();
});
```
## Field interface ##
The `Field` template type provided by `cppreg` (see [Field.h](register/Field.h)) contains the added value of the library in terms of type safety, efficiency and expression of intent. The interface is:
`struct Field<register, width_in_bits, offset_in_bits, access_policy>`:
| parameter | description |
|:---------------------|:-------------------------------------------|
| `register` | register type owning the field |
| `width_in_bits` | width in bits (*i.e.*, size) |
| `offset_in_bits` | offset in bits wrt to register address |
| `access_policy` | access policy type (see below) |
Compile-time errors will be generated if the field width and offset are not consistent with the parent register size.
### Access policy ###
The last template parameter of a `Field`-based type describes the access policy of the field. Three access policies are available:
@@ -114,78 +256,88 @@ The last template parameter of a `Field`-based type describes the access policy
Depending on the access policy, the `Field`-based type will provide accessors and/or modifier to its data as described by the following table:
| Method | R/W | RO | WO | Description |
| method | R/W | RO | WO | description |
|:--------------|:---------:|:---------:|:---------:| :-----------------------------------------------------|
| `read()` | YES | YES | NO | return the content of the field |
| `write(value)`| YES | NO | YES | write `value` to the field |
| `set()` | YES | NO | NO | set all the bits of the field to `1` |
| `clear()` | YES | NO | NO | clear all the bits of the field (*i.e.*, set to `0`) |
| `toggle()` | YES | NO | NO | toggle all the bits of the field |
| `is_set()` | YES | NO | NO | `true` is all bits set to 1 |
| `is_clear()` | YES | NO | NO | `true` is all bits set to 0 |
Any attempt at calling an access method which is not provided by a given policy will result in a compilation error. This is one of the mechanism used by `cppreg` to provide safety when accessing registers and fields.
For example using our previous `PeripheralRegister` example:
### Example ###
Consider a 32-bit register located at 0x40004242 containing (among other things): a R/W FREQ field over bits [12:17], a WO MODE field over bits [18:21], and a RO STATE field one over bits [28:31]. The `cppreg` implementation is:
```c++
// Register definition with nested fields definitions.
struct PeripheralRegister : Register<0x40004242, 32u> {
using Frequency = Field<PeripheralRegister, 6u, 12u, read_write>;
using Mode = Field<PeripheralRegister, 4u, 18u, write_only>;
using State = Field<PeripheralRegister, 4u, 18u, read_only>;
struct SomeRegister : Register<0x40004242, RegBitSize::b32> {
using Frequency = Field<SomeRegister, 6u, 12u, read_write>;
using Mode = Field<SomeRegister, 4u, 18u, write_only>;
using State = Field<SomeRegister, 4u, 28u, read_only>;
// Strictly equivalent formulation:
// struct Frequency : Field<SomeRegister, 6u, 12u, read_write> {};
// ...
};
// This would compile:
PeripheralRegister::Frequency::write(0x10);
const auto freq = PeripheralRegister::Frequency::read();
const auto state = PeripheralRegister::State::read();
SomeRegister::Frequency::write<0x10>();
const auto freq = SomeRegister::Frequency::read();
const auto state = SomeRegister::State::read();
// This would not compile:
PeripheralRegister::State::write(0x1);
const auto mode = PeripheralRegister::Mode::read();
// This would not compile (State is read-only):
SomeRegister::State::write<0x1>();
const auto mode = SomeRegister::Mode::read();
// This would compile ...
// But read the section dedicated to write-only fields.
PeripheralRegister::Mode::write(0xA);
// But read the section dedicated to write-only fields !!!
SomeRegister::Mode::write<0xA>();
```
### 1-bit addons ###
`Field`-based type which are 1-bit wide and readable (`read_write` or `read_only`) have two additional methods:
### Constant value and overflow check ###
When performing write operations for any `Field`-based type, `cppreg` distinguishes between constant values (known at compile time) and non-constant values:
* `is_set` returns `true` if the single bit is equal to `1` (false otherwise),
* `is_clear` returns `true` if the single bit is equal to `0` (false otherwise).
```c++
SomeField::write<0xAB>(); // Template version for constant value write.
SomeField::write(0xAB); // Function argument version.
```
### Overflow check ###
For writable `Field`-based types overflow will be prevented at runtime: only the bits part of the `Field`-type will be written and any data that does not fit the region of the memory device assigned to the `Field`-type will not be modified. This prevents overflow at runtime. But `cppreg` can also prevent overflow at compile time.
The advantages of using the constant value form are:
If the value to be written is known at compile time (which is often the case when dealing with hardware registers) one can use a template version of the `write` method. The template version does perform a check at compile time to ensure that the value to be written does not overflow:
* `cppreg` will most of the time use a faster implementation for the write operation (this is particularly true if the field spans an entire register),
* a compile-time error will occur if the value overflow the field.
Note that, even when using the non-constant value form overflow will not occur: only the bits fitting in the `Field`-type will be written and any data that does not fit the region of the memory assigned to the `Field`-type will not be modified. For example:
```c++
// Register definition with nested fields definitions.
struct PeripheralRegister : Register<0x40004242, 32u> {
using Frequency = Field<PeripheralRegister, 8u, 12u, read_write>;
struct SomeRegister : SomeRegister <0x40004242, RegBitSize::b32> {
using Frequency = Field<SomeRegister, 8u, 12u, read_write>;
};
// These two calls are strictly equivalent:
PeripheralRegister::Frequency::write(0xAB);
PeripheralRegister::Frequency::write<0xAB>();
SomeRegister::Frequency::write(0xAB);
SomeRegister::Frequency::write<0xAB>();
// This call does not perform a compile-time check for overflow:
PeripheralRegister::Frequency::write(0x111); // But this will only write 0x11 to the memory device.
// But this will only write 0x11 to the memory device.
SomeRegister::Frequency::write(0x111);
// This call does perform a compile-time check for overflow and will not compile:
PeripheralRegister::Frequency::write<0x111>();
SomeRegister::Frequency::write<0x111>();
```
It strongly recommended to use the template version when the value is known at compile time.
## Shadow value: a workaround for write-only fields ##
Write-only fields are somewhat special as extra-care has to be taken when manipulating them. The main difficulty resides in the fact that write-only field can be read but the value obtained by reading it is fixed (*e.g.*, it always reads as zero). `cppreg` assumes that write-only fields can actually be read from; if such an access on some given architecture would trigger an error (*à la FPGA*) then `cppreg` is not a good choice to deal with write-only fields on this particular architecture.
Write-only fields are somewhat special and extra-care has to be taken when manipulating them. The main difficulty resides in the fact that write-only field can be read but the value obtained by reading it is fixed (*e.g.* it always reads as zero). `cppreg` assumes that write-only fields can actually be read from; if such an access on some architecture would trigger an error (*à la FPGA*) then `cppreg` is not a good choice to deal with write-only fields on this particular architecture.
Consider the following situation:
```c++
struct Reg : Register <0x00000001, 8u> {
struct Reg : Register <0x00000001, RegBitSize::b8> {
using f1 = Field<Reg, 1u, 0u, read_write>;
using f2 = Field<Reg, 1u, 1u, write_only>; // Always reads as zero.
}
@@ -194,9 +346,9 @@ struct Reg : Register <0x00000001, 8u> {
Here is what will be happening (assuming the register is initially zeroed out):
```c++
Reg::f1::write<0x1>(); // reg = (... 0000) | (... 0001) = (... 0001)
Reg::f2::write<0x1>(); // reg = (... 0010), f1 got wiped out.
Reg::f1::write<0x1>(); // reg = (... 0000) | (... 0001) = (... 0001), f2 wiped out cause it reads as zero.
Reg::f1::write<0x1>(); // Reg = (... 0000) | (... 0001) = (... 0001)
Reg::f2::write<0x1>(); // Reg = (... 0010), f1 got wiped out.
Reg::f1::write<0x1>(); // Reg = (... 0000) | (... 0001) = (... 0001), f2 wiped out cause it reads as zero.
```
This shows two issues:
@@ -204,13 +356,15 @@ This shows two issues:
* the default `write` implementation for a write-only field will wipe out the register bits that are not part of the field,
* when writing to the read-write field it wipes out the write-only field because there is no way to retrieve the value that was previously written.
On the other hand, if we were considering an example where a single write-only field extend over an entire register there will be no issue.
As a workaround, `cppreg` offers a shadow value implementation which mitigates the issue by tracking the register value. This implementation can be triggered when defining a register type by using an explicit reset value and a boolean flag:
```c++
struct Reg : Register<
0x40004242, // Register address
32u, // Register size
0x42u // Register reset value
RegBitSize::b32, // Register size
0x42u, // Register reset value
true // Enable shadow value for the register
>
{
@@ -219,7 +373,7 @@ struct Reg : Register<
};
```
The shadow value implementation for a write-only field works as follow:
The shadow value implementation for a write-only field works as follows:
* at static initialization time, the reset value of the register owning the field is used to initialize the shadow value (the shadow value is used for the entire register content),
* at each write access to any of the register fields, the shadow value will be updated and written to the entire register memory.
@@ -234,12 +388,12 @@ A few safety guidelines:
## MergeWrite: writing to multiple fields at once ##
It is sometimes the case that multiple fields within a register needs to be written at the same time. For example, when setting the clock dividers in a MCU it is often recommended to write all their values to the corresponding register at the same time (to avoid overclocking part of the MCU).
It is sometimes the case that multiple fields within a register needs to be written at the same time. For example, when setting the clock dividers in a MCU it is often recommended to write all their values to the corresponding register at the same time (to avoid mis-clocking part of the MCU).
Consider the following setup (not so artifical; it is inspired by a real flash memory controller peripheral):
Consider the following setup (not so artificial; it is inspired by a real flash memory controller peripheral):
```c++
struct FlashCtrl : Register<0xF0008282, 8u> {
struct FlashCtrl : Register<0xF0008282, RegBitSize::b8> {
// Command field.
// Can bet set to various values to trigger write, erase or check operations.
@@ -260,29 +414,31 @@ struct FlashCtrl : Register<0xF0008282, 8u> {
Now let's assume the following scenario:
1. The previous flash command failed because it attempted to write or erase in a protected section, at that point the content of the `FlashCtrl` register is `1001 XXXX` where `XXXX` is whatver value associated with the command that failed.
1. The previous flash command failed because it attempted to write or erase in a protected section, at that point the content of the `FlashCtrl` register is `1001 XXXX` where `XXXX` is whatever value associated with the command that failed.
2. Before we can perform a new flash command we need to clear the `ProtectionError` by writing 1 to it (otherwise the new command will not be started); so one could think about doing:
```c++
FlashCtrl::ProtectionError::set(); // Write to ProtectionError to clear it.
```
however this write at `1000 XXXX | 0001 0000 = 1001 XXXX` at the register level and thus start the command that previously failed.
however this write `1000 XXXX | 0001 0000 = 1001 XXXX` at the register level and thus start the command that previously failed.
3. At this point one could try to set the value for the new command but that will fail as well (because `ProtectionError` was not cleared and it is required to be).
4. A possible alternative would be to fully zero out the `FlashCtrl` register but that would somewhat defeat the purpose of `cppreg`.
For this kind of situation a *merge write* mechanism was implemented in `cppreg` to merge multiple write operations into a single one. This makes it possible to write the following code to solve the flash controller issue:
For this kind of situation a *merged write* mechanism was implemented in `cppreg` to merge multiple write operations into a single one. This makes it possible to write the following code to solve the flash controller issue:
```c++
// Write to both ProtectionError and CommandComplete.
FlashCtrl::merge_write<FlashCtrl::ProtectionError>(1).with<FlashCtrl::CommandComplete>(0);
FlashCtrl::merge_write<FlashCtrl::ProtectionError, 0x1>().with<FlashCtrl::CommandComplete, 0x0>().done();
// This will correspond to write with a mask set to 1001 0000,
// which boils down to write (at the register level):
// 0000 XXXX | 0001 0000 = 0001 XXXX ... CommandComplete is not set to 1 !
// 0000 XXXX | 0001 0000 = 0001 XXXX ... CommandComplete is not set to 1!
```
The `merge_write` method is only available in `Register`-based type that do not enable the shadow value mechanism. The `Field`-based types used in the chained call are required to *be from* the `Register` type used to call `merge_write`. In addition, the `Field`-types are also required to be writable.
The `merge_write` method is only available in register type (`PackedRegister` or `Register`) that do not enable the shadow value mechanism. The `Field`-based types used in the chained call are required to *be from* the register type used to call `merge_write`. In addition, the `Field`-types are also required to be writable. By design, the successive write operations have to be chained, that is, it is not possible to capture a `merge_write` context and add other write operations to it; it always has to be of the form: `register::merge_write<field1, xxx>().with<field2, xxx>(). ... .done()`.
Finally, it is possible to use a template form when writing merge write operations to perform overflow checking at compile time (similar to `write(value)/write<value>()` methods).
**Warning:** if`done()` is not called at the end of the successive write operations no write at all will be performed.
Similarly to regular write operations it is recommended to use the template version (as shown in the example) if possible: this will enable overflow checking and possibly use faster write implementations. If not possible the values to be written are passed as arguments to the various calls.

BIN
Assembly_Comparison.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

View File

@@ -7,47 +7,50 @@
# -------------------------------------------------------------------------- #
# --- cppreg library files ---
# --- cppreg library ---
# Header directories.
set(CPPREG_HEADERS_DIRS
set(cppreg_headers_dirs
.
policies/
register/)
# List of API headers.
set(CPPREG_API_HEADERS
set(cppreg_headers
cppreg.h
cppreg_Defines.h
cppreg_Includes.h
policies/AccessPolicy.h
register/Field.h
register/Internals.h
register/Mask.h
register/Overflow.h
register/Memory.h
register/MergeWrite.h
register/Register.h
register/RegisterPack.h
register/ShadowValue.h
register/Traits.h)
# Refactor headers directories.
set(BUILD_HEADERS_DIRS "")
foreach(dir IN ITEMS ${CPPREG_HEADERS_DIRS})
list(APPEND BUILD_HEADERS_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/${dir}")
set(build_cppreg_headers_dirs "")
foreach(dir IN ITEMS ${cppreg_headers_dirs})
list(APPEND build_cppreg_headers_dirs "${CMAKE_CURRENT_SOURCE_DIR}/${dir}")
endforeach()
# Header-only library.
add_library(cppreg INTERFACE)
target_include_directories(cppreg INTERFACE . register/ policies/)
target_include_directories(cppreg INTERFACE ${cppreg_headers_dirs})
# Include directories interfaces.
# This properly setup the API headers for the build and install phase.
set_property(TARGET cppreg
PROPERTY INTERFACE_INCLUDE_DIRECTORIES
$<BUILD_INTERFACE:${BUILD_HEADERS_DIRS}>
$<BUILD_INTERFACE:${build_cppreg_headers_dirs}>
$<INSTALL_INTERFACE:include/cppreg>)
# --- Install directives ---
install(FILES ${CPPREG_API_HEADERS} DESTINATION include/cppreg)
install(TARGETS cppreg DESTINATION lib EXPORT cppreg-libs)
install(EXPORT cppreg-libs DESTINATION include/cppreg)
install(FILES ${cppreg_headers} DESTINATION include/cppreg)
install(TARGETS cppreg DESTINATION lib EXPORT cppreg-target)
install(EXPORT cppreg-target DESTINATION include/cppreg)

View File

@@ -5,7 +5,7 @@
/____/\___/_/ /_/\__,_/\__, /_/ /_/\___/ \___/\____/_/ / .___(_).
/____/ /_/
Copyright 2010-2018 Sendyne Corporation.
Copyright 2010-2019 Sendyne Corporation.
All rights reserved.
Sendyne Corp., 250 West Broadway, New York, NY 10013, USA.

173
Performance.md Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,5 @@
# cppreg: quick start #
Copyright Sendyne Corp., 2010-2018. All rights reserved ([LICENSE](LICENSE)).
Copyright Sendyne Corp., 2010-2019. All rights reserved ([LICENSE](LICENSE)).
This document is a brief introduction to `cppreg` and how to use it. For more details about the implementation refers to the [API documentation](API.md).
@@ -14,7 +14,8 @@ There are two recommended ways to use `cppreg` in a project:
# Include cppreg library.
# The second argument is not necessarily required depending on the project setup.
# This will import the cppreg target.
# Because cppreg is a header-only library the cppreg target is actually an INTERFACE library target.
# Because cppreg is a header-only library the cppreg target is actually an
# INTERFACE library target.
add_subdirectory(/path/to/cppreg ${PROJECT_BINARY_DIR)/cppreg)
...
@@ -28,19 +29,25 @@ There are two recommended ways to use `cppreg` in a project:
### Recommended compiler settings ###
Although `cppreg` is entirely written in C++, there is little (if any) overhead in term of runtime performance if at least some level of optimization are enabled (mostly to take care of inlining). For GCC ARM the following settings are recommended (and similar settings should be used for other compilers):
Although `cppreg` is entirely written in C++, there is little (if any) overhead in term of runtime performance if at least some level of optimization are enabled (mostly to take care of inlining). For GCC/Clang the following settings are recommended (and similar settings should be used for other compilers):
* enable `-Og` for debug builds (this helps significantly with inlining),
* for optimized builds (`-O2`,`-O3` or `-Os`) the default settings will be sufficient,
* link time and dead code optimization (LTO and `--gc-section` with `-ffunction-sections` and `-fdata-sections`) can also help produce a more optimized version of the code.
## Example: peripheral setup ##
Consider an arbitrary peripheral with a setup register:
## Prologue ##
When developing firmware code for embedded MCUs it is customary that peripherals and devices are configured and operated through MMIO registers (for example, a UART or GPIO peripheral). For a given peripheral the related registers are often grouped together at a specific location in memory. `cppreg` makes it possible to *map* C++ constructs to such peripherals registers and fields in order to get safer and more expressive code. The following two examples illustrate how to define such constructs using `cppreg`.
| Absolute address (hex) | Register | Width (bits) | Access |
|:----------------------:|:-----------------|:------------:|:------------------:|
| 0xA400 0000 | Peripheral setup register | 8 | R/W |
## Example: peripheral setup ##
Consider an arbitrary peripheral with the following registers:
| Address (hex) | Register | Width (bits) | Access |
|:-------------:|:-----------------|:------------:|:------------------:|
| 0xA400 0000 | Setup register | 8 | R/W |
| 0xA400 0001 | RX data register | 8 | R |
| 0xA400 0002 | TX data register | 8 | W |
The setup register bits are mapped as:
@@ -48,94 +55,127 @@ The setup register bits are mapped as:
* MODE field bits [5:6] to setup the peripheral mode,
* EN field bits [7] to enable the peripheral.
The goal of `cppreg` is to facilitate the manipulation of such a register and the first step is to define custom types (`Register` and `Field`) that maps to the peripheral:
The RX and TX data registers both contain a single DATA field occupying the whole register. The DATA field is read-only for the RX register and write-only for the TX register.
The goal of `cppreg` is to facilitate the manipulation of such a peripheral. This can be done as follow:
```c++
#include <cppreg.h>
#include <cppreg.h> // use cppreg-all.h if you are using the single header.
using namespace cppreg;
// Peripheral register.
// The first template parameter is the register address.
// The second template parameter is the register width in bits.
struct Peripheral : Register<0xA4000000, 8u> {
// Peripheral structure.
// This will contain all the peripheral registers definitions.
struct Peripheral {
// When defining a Field-based type:
// - the first template parameter is the owning register,
// - the second template parameter is the field width in bits,
// - the third template parameter is the offset in bits,
// - the last parameter is the access policy (readable and writable).
using Frequency = Field<Peripheral, 5u, 0u, read_write>; // FREQ
using Mode = Field<Peripheral, 2u, 5u, read_write>; // MODE
using Enable = Field<Peripheral, 1u, 7u, read_write>; // EN
// Define a register pack type.
// This is used to indicate that the register are packed together in memory.
using periph_pack = RegisterPack<
0xA400 0000, // Base address of the pack (i.e., peripheral).
3 // Number of bytes for all peripheral registers.
>;
// To enable the peripheral:
// write 1 to EN field; if the peripheral fails to start this will be reset to zero.
// To disable the peripheral:
// clear EN field; no effect if not enabled.
// Define the setup register and the fields.
struct Setup : PackedRegister<
periph_pack, // Pack to which the register belongs to.
RegBitSize::b8, // Register size.
0 // Offset in bits from the base.
> {
// When defining a Field-based type:
// - the first template parameter is the owning register,
// - the second template parameter is the field width in bits,
// - the third template parameter is the offset in bits,
// - the last parameter is the access policy.
using Frequency = Field<Setup, 5u, 0u, read_write>; // FREQ
using Mode = Field<Setup, 2u, 5u, read_write>; // MODE
using Enable = Field<Setup, 1u, 7u, read_write>; // EN
};
// Define the RX data register.
struct RX : PackedRegister<
periph_pack, // Pack to which the register belongs to.
RegBitSize::b8, // Register width in bits
8 // Offset in bits from the base.
> {
using Data = Field<RX, 8u, 0u, read_only>;
};
// Define the RX data register.
struct TX : PackedRegister<
periph_pack, // Pack to which the register belongs to.
RegBitSize::b8, // Register width in bits
8 * 2 // Offset in bits from the base.
> {
using Data = Field<TX, 8u, 0u, write_only>;
};
};
```
For more details about the various types (`RegisterPack`, `PackedRegister`, and `Field` see the [API documentation](API.md)).
Now let's assume that we want to setup and enable the peripheral following the procedure:
1. we first set the mode, say with value `0x2`,
2. then the frequency, say with value `0x1A`,
3. then write `1` to the enable field to start the peripheral.
3. then write `1` to the enable field to start the peripheral,
4. if the peripheral fails to start or stop this will be set to zero.
Once enabled we also want to implement a echo loop that will simply read data from the RX register and put them in the TX register so that the peripheral will echo whatever it receives.
This translates to:
```c++
// Setup and enable.
Peripheral::Mode::write<0x2>();
Peripheral::Frequency::write<0x1A>();
Peripheral::Enable::set();
Peripheral::Setup::Mode::write<0x2>();
Peripheral::Setup::Frequency::write<0x1A>();
Peripheral::Setup::Enable::set();
// Echo loopback.
while (true) {
// Check if sill enabled.
if (!Peripheral::Setup::Enable::is_set()) {
break;
};
// Read data.
const auto incoming_data = Peripheral::RX::Data::read();
// Echo the data.
Peripheral::TX::Data::write(incoming_data);
// Check if properly enabled.
if (!Peripheral::Enable::is_set()) {
// Peripheral failed to start ...
};
...
// Later on we want to disable the peripheral.
Peripheral::Enable::clear();
```
A few remarks:
* in the `write` calls we can also use `write(value)` instead of `write<value>()`; the latter only exists if `value` is `constexpr` (*i.e.*, known at compile time) but the benefits is that it will check for overflow at compile time,
* 1-bit wide `Field`-based type have `is_set` and `is_clear` defined to conveniently query their states.
* the `write` calls for the `Setup` register pass the data as template arguments, while the write call for the `TX` register pass it as a function argument: if the value to be written is known at compile time it is recommended to use the template form; the template form will detect overflow (see below) and will also make it possible to use a more efficient write implementation in some cases,
* `Field`-based types have `is_set` and `is_clear` defined to conveniently query their states.
The advantage of `cppreg` is that it limits the possibility of errors (see the [API documentation](API.md) for more details):
In this example, we can already see how `cppreg` limits the possibility of errors (see the [API documentation](API.md) for more details):
```c++
// Overflow checks.
Peripheral::Mode::write<0x4>(); // Would not compile because it overflows the MODE field.
Peripheral::Frequency::write<0xFF>(); // Idem. This overflows the FREQ field.
Peripheral::Enable::set();
Peripheral::Setup::Mode::write<0x4>(); // Would not compile because it overflows the MODE field.
Peripheral::Setup::Frequency::write<0xFF>(); // Idem. This overflows the FREQ field.
Peripheral::Setup::Enable::set();
// Instead if you write:
Peripheral::Mode::write(0x4); // Compile but writes 0x0 to the MODE field.
Peripheral::Frequency::write(0xFF); // Compile but writes 0x1F to the FREQ field
Peripheral::Setup::Mode::write(0x4); // Compile but writes 0x0 to the MODE field.
Peripheral::Setup::Frequency::write(0xFF); // Compile but writes 0x1F to the FREQ field
// Access policies.
Peripheral::RX::Data::write<0x1>(); // Would not compile because read-only.
Peripheral::TX::Data::read(); // Would not compile because write-only.
```
We can even add more expressive methods for our peripheral:
```c++
#include <cppreg.h>
using namespace cppreg;
// Peripheral register.
struct Peripheral : Register<0xA4000000, 8u> {
using Frequency = Field<Peripheral, 5u, 0u, read_write>; // FREQ
using Mode = Field<Peripheral, 2u, 5u, read_write>; // MODE
using Enable = Field<Peripheral, 1u, 7u, read_write>; // EN
// To enable the peripheral:
// write 1 to EN field; if the peripheral fails to start this will be reset to zero.
// To disable the peripheral:
// clear EN field; no effect if not enabled.
struct PeripheralInterface : Peripheral {
// Configuration with mode and frequency.
template <Mode::type mode, Frequency::type f>
@@ -150,15 +190,22 @@ struct Peripheral : Register<0xA4000000, 8u> {
Enable::set();
};
// Is enabled method.
inline static bool is_enabled() {
return Enable::is_set();
};
// Disable method.
inline static void disable() {
Enable::clear();
};
// ...
};
Peripheral::configure<0x2, 01A>();
Peripheral::enable();
PeripheralInterface::configure<0x2, 01A>();
PeripheralInterface::enable();
```
@@ -182,31 +229,32 @@ Using `cppreg` we can define custom types for these registers and define an inte
// GPIO peripheral namespace.
namespace gpio {
// To define a register type:
// using x = Register<register_address, register_width in bits>;
// Register pack.
// 6 x 32-bits = 6 x 4 bytes.
using gpio_pack = RegisterPack<0xF4000000, 6 * 8>;
// Data output register (PDOR).
using pdor = Register<0xF4000000, 32u>;
using pdor = PackedRegister<gpio_pack, RegBitSize::b32, 0 * 32>;
// Set output register (PSOR).
using psor = Register<0xF4000004, 32u>;
using psor = PackedRegister<gpio_pack, RegBitSize::b32, 1 * 32>;
// Clear output register (PCOR).
using pcor = Register<0xF4000008, 32u>;
using pcor = PackedRegister<gpio_pack, RegBitSize::b32, 2 * 32>;
// Toggle output register (PTOR).
using ptor = Register<0xF400000C, 32u>;
using ptor = PackedRegister<gpio_pack, RegBitSize::b32, 3 * 32>;
// Data input register.
using pdir = Register<0xF4000010, 32u>
using pdir = PackedRegister<gpio_pack, RegBitSize::b32, 4 * 32>;
// Data direction output register.
using pddr = Register<0xF4000014, 32u>
using pddr = PackedRegister<gpio_pack, RegBitSize::b32, 5 * 32>;
}
```
For the purpose of this example we further assume that we are only interested in two pins of the GPIO: we have a red LED on pin 14 and a blue LED on pin 16. We can now use the `Register` types defined above to map these pins to specific `Field`. Because the logic is independent of the pin number we can even define a generic LED interface:
For the purpose of this example we further assume that we are only interested in two pins of the GPIO: we have a red LED on pin 14 and a blue LED on pin 16. We can now use the `PackedRegister` types defined above to map these pins to specific `Field`. Because the logic is independent of the pin number we can even define a generic LED interface:
```c++
// LEDs namespace.
@@ -219,10 +267,10 @@ namespace leds {
// Define the relevant fields.
// Some of these fields are write only (e.g., PSOR) but we define them
// as read write (it will always read zero but we will not read them).
using pin_direction = Field<gpio::pddr, 1u, Pin, AccessPolicy::rw>;
using pin_set = Field<gpio::psor, 1u, Pin, AccessPolicy::rw>;
using pin_clear = Field<gpio::pcor, 1u, Pin, AccessPolicy::rw>;
using pin_toggle = Field<gpio::ptor, 1u, Pin, AccessPolicy::rw>;
using pin_direction = Field<gpio::pddr, 1u, Pin, read_write>;
using pin_set = Field<gpio::psor, 1u, Pin, read_write>;
using pin_clear = Field<gpio::pcor, 1u, Pin, read_write>;
using pin_toggle = Field<gpio::ptor, 1u, Pin, read_write>;
// We also define some constants.
constexpr static const gpio::pddr::type pin_output_dir = 1u;
@@ -239,8 +287,8 @@ namespace leds {
pin_toggle::set(); // Set PTOR to 1.
};
inline static void init() {
pin_direction::write(pin_output_dir);
off();
pin_direction::write(pin_output_dir);
};
}
@@ -252,7 +300,7 @@ namespace leds {
}
```
At this point we have defined an interface to initialize and control the LEDs attached to two GPIO pins. Note that, at no moment we had to deal with masking or shifting operations. Furthermore, we only needed to deal with the register addresses when defining the related types. At compile time, `cppreg` also makes sure that the field actually fits within the register specifications (a `Field` type cannot overflow its `Register` type).
At this point we have defined an interface to initialize and control the LEDs attached to two GPIO pins. Note that, at no moment we had to deal with masking or shifting operations. Furthermore, we only needed to deal with the register addresses when defining the mapping. At compile time `cppreg` also makes sure that the field actually fits within the register specifications (a `Field`-based type cannot overflow the register in which it is defined). Similarly, `cppreg` also checks that packed registers are properly aligned and fit within the pack.
Using this interface it becomes easy to write very expressive code such as:
@@ -266,10 +314,10 @@ leds::blue::on();
// Wait a bit.
for (std::size_t i = 0; i < 500000; ++i)
__NOP();
asm("nop");
// Turn off the blue LED.
leds::blue::off();
```
A quick note: in this example some of the registers are write-only (set, clear and toggle); in genereal extra care has to be taken when dealing with write-only fields or registers but for this example the implementation still work fine due to the nature of the GPIO registers. Check the [API documentation](API.md) for more details.
A quick note: in this example some of the fields are write-only (set, clear and toggle); in general extra care has to be taken when dealing with write-only fields but for this example the implementation still work fine due to the nature of the GPIO registers. Check the [API documentation](API.md) for more details.

View File

@@ -1,17 +1,29 @@
# cppreg #
Copyright Sendyne Corp., 2010-2018. All rights reserved ([LICENSE](LICENSE)).
Copyright Sendyne Corp., 2010-2019. All rights reserved ([LICENSE](LICENSE)).
## Description ##
`cppreg`is a header-only C++11 library to facilitate the manipulation of MMIO registers (*i.e.*, memory-mapped I/O registers) in embedded devices. The idea is to make it possible to write expressive code and minimize the likelihood of ill-defined expressions when dealing with hardware registers on a MCU. The current features are:
`cppreg` is a header-only C++11 library to facilitate the manipulation of MMIO registers (*i.e.*, memory-mapped I/O registers) in embedded devices. The idea is to provide a way to write expressive code and minimize the likelihood of ill-defined expressions when dealing with hardware registers on a MCU. The current features are:
* expressive syntax which shows the intent of the code when dealing with registers and fields,
* efficiency and performance on par with traditional C implementations (*e.g.*, CMSIS C code) when *at least some compiler optimizations* are enabled,
* field access policies (*e.g.*, read-only vs read-write) detect ill-defined access at compile-time,
* efficiency and performance on par with traditional C implementations (*e.g.* CMSIS C code) when *at least some compiler optimizations* are enabled,
* [emphasis](Performance.md) on ensuring the assembly is the same if not better than CMSIS versions,
* field access policies (*e.g.* read-only vs read-write) detect ill-defined access at compile-time,
* compile-time detection of overflow,
* easily extendable to support, for example, mock-up.
* register memory can easily be mocked up so that testing is possible.
For a short introduction and how-to see the [quick start guide](QuickStart.md). A more complete and detailed documentation is available [here](API.md).
For a short introduction and how-to see the [quick start guide](QuickStart.md). A more complete and detailed documentation is available [here](API.md).
The features provided by `cppreg` come with no overhead or performance penalty compared to traditional low-level C approaches. We give [here](Performance.md) an example comparing the assembly generated by a CMSIS-like implementation versus a `cppreg`-based one.
## Requirements ##
`cppreg` is designed to be usable on virtually any hardware that satisfies the following requirements:
* MMIO register sizes are integral numbers of bytes (*e.g.*, 8 bits, 16 bits, ...),
* registers are properly aligned: a N-bit register is aligned on a N-bit boundary,
GCC (4.8 and above) and Clang (3.3 and above) are supported and it is expected that any other C++11-compliant compiler should work (see the [quick start guide](QuickStart.md) for recommended compiler settings).
## Manifest ##
@@ -29,11 +41,11 @@ while ((MCG->S & MCG_S_PLLST_MASK) == 0)
This piece of code is part of the clock setup on a flavor of the K64F MCU. `MCG` is a peripheral and `MCG->C6` and `MCG->S` are registers containing some fields which are required to be set to specific values to properly clock the MCU. Some of the issues with such code are:
* the intent of the code is poorly expressed, and it requires at least the MCU data sheet or reference manual to be somewhat deciphered/understood,
* since the offsets and masks are known at compile time, it is error prone and somewhat tedious that the code has to manually implement shifting and masking operations,
* since the offsets and masks are known at compile time, it is error prone and somewhat tedious that the code has to re-implement shifting and masking operations,
* the code syntax itself is extremely error prone; for example, forget the `|` in `|=` and you are most likely going to spend some time debugging the code,
* there is no safety at all, that is, you might overflow the field, or you might try to write to a read-only field and no one will tell you (not the compiler, not the linker, and at runtime this could fail in various ways with little, if any, indication of where is the error coming from).
This does not have to be this way, and C++11 brings a lot of features and concepts that make it possible to achieve the same goal while clearly expressing the intent and being aware of any ill-formed instructions. Some will argue this will come at the cost of a massive performance hit, but this is actually not always the case (and more often than not, a C++ implementation can be very efficient; see [Ken Smith paper] and the example below).
This does not have to be this way, and C++11 brings a lot of features and concepts that make it possible to achieve the same goal while clearly expressing the intent and being aware of any ill-formed instructions. Some will argue this will come at the cost of a massive performance hit, but this is actually not always the case (and more often than not, a C++ implementation can be very efficient; see [Ken Smith] paper and the example below).
This project has been inspired by the following previous works:

1
_config.yml Normal file
View File

@@ -0,0 +1 @@
theme: jekyll-theme-cayman

View File

@@ -2,7 +2,7 @@
/**
* @file cppreg.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*/
@@ -10,10 +10,11 @@
#define CPPREG_CPPREG_H
#include "Register.h"
#include "Field.h"
#include "Internals.h"
#include "MergeWrite.h"
#include "Overflow.h"
#include "Register.h"
#include "RegisterPack.h"
#endif // CPPREG_CPPREG_H
#endif // CPPREG_CPPREG_H

View File

@@ -2,7 +2,7 @@
/**
* @file cppreg_Defines.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* This header mostly defines data types used across the project. These data
* types have been defined with 32-bits address space hardware in mind. It
@@ -17,37 +17,49 @@
#include "cppreg_Includes.h"
//! cppreg namespace.
namespace cppreg {
//! Type alias for register and field addresses.
/**
* By design this type ensures that any address can be stored.
*/
using Address_t = std::uintptr_t;
//! Type alias for register and field addresses.
/**
* By design this type ensures that any address can be stored.
*/
using Address = std::uintptr_t;
//! Type alias for register and field widths.
/**
* This limit the implementation to a maximum size of 256 bits for any
* register or field.
* This corresponds to the number of bits in the a register or field.
*/
using Width_t = std::uint8_t;
//! Enumeration type for register size in bits.
/**
* This is used to enforce the supported register sizes.
*/
enum class RegBitSize : std::uint8_t {
b8, //!< 8-bit register.
b16, //!< 16-bit register.
b32, //!< 32-bit register.
b64 //!< 64-bit register.
};
//! Type alias for register and field offsets.
/**
* This limit the implementation to a maximum offset of 256 bits for any
* register or field.
* Given that we consider 32 bits address space and 32 bits register this
* should be enough.
*/
using Offset_t = std::uint8_t;
//! Type alias field width.
using FieldWidth = std::uint8_t;
}
//! Type alias for field offset.
using FieldOffset = std::uint8_t;
#endif // CPPREG_CPPREG_DEFINES_H
//! Shorthand for max value as a mask.
/**
* @tparam T Data type.
*
* This is used to define register masks.
*/
template <typename T>
struct type_mask {
constexpr static const T value = std::numeric_limits<T>::max();
};
} // namespace cppreg
#endif // CPPREG_CPPREG_DEFINES_H

View File

@@ -2,7 +2,7 @@
/**
* @file cppreg_Defines.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*/
@@ -11,6 +11,8 @@
#include <cstdint>
#include <limits>
#include <tuple>
#endif // CPPREG_CPPREG_INCLUDES_H
#endif // CPPREG_CPPREG_INCLUDES_H

View File

@@ -1,11 +1,22 @@
//! Access policy abstract implementation.
//! Access policy implementation.
/**
* @file AccessPolicy.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* Access policies are used to describe if register fields are read-write,
* read-only or write-only.
*
* - The read and write implementations distinguish between trivial and
* non-trivial operations. A trivial operation corresponds to a read or
* write over a whole register; in such a case no masking of shifting is
* necessary. On the other hand, if the operation is only over a region of
* the register proper masking and shifting is required. The switch between
* trivial and non-trivial implementations is done automatically.
* - The write implementation also distinguishes between writing constant
* values (i.e., known at compile time) and non-constant value. This is
* intended to make it possible to simplify operations at compile time and
* minimize overhead.
*/
@@ -16,113 +27,288 @@
#include "cppreg_Defines.h"
//! cppreg namespace.
namespace cppreg {
//! Read-only access policy.
struct read_only {
//!@{ Trivial register read/write detector.
//! Read access implementation.
/**
* @tparam T Field data type.
* @param mmio_device Pointer to register mapped memory.
* @param mask Field mask.
* @param offset Field offset.
* @return The value at the field location.
*/
template <typename T>
inline static T read(const T* const mmio_device,
const T mask,
const Offset_t offset) noexcept {
return static_cast<T>((*mmio_device & mask) >> offset);
};
//! Boolean flag to detect trivial read/write.
/**
* @tparam T Register data type.
* @tparam mask Mask for the read operation.
* @tparam offset Offset for the read operation.
*/
template <typename T, T mask, FieldOffset offset>
struct is_trivial_rw
: std::integral_constant<bool,
(mask == type_mask<T>::value)
&& (offset == FieldOffset{0})> {};
};
//! Trivial read/write enable_if helper.
/**
* @tparam T Register data type.
* @tparam mask Mask for the read operation.
* @tparam offset Offset for the read operation.
* @tparam U Enabled type if trivial.
*/
template <typename T, T mask, FieldOffset offset, typename U>
using is_trivial =
typename std::enable_if<is_trivial_rw<T, mask, offset>::value, U>::type;
//! Non-trivial read/write enable_if helper.
/**
* @tparam T Register data type.
* @tparam mask Mask for the read operation.
* @tparam offset Offset for the read operation.
* @tparam U Enabled type if non-trivial.
*/
template <typename T, T mask, FieldOffset offset, typename U>
using is_not_trivial =
typename std::enable_if<!is_trivial_rw<T, mask, offset>::value, U>::type;
//!@}
//! Read-write access policy.
struct read_write : read_only {
//! Register read implementation.
/**
* @tparam MMIO Memory device type.
* @tparam T Register data type.
* @tparam mask Mask for the read operation.
* @tparam offset Offset for the read operation.
*/
template <typename MMIO, typename T, T mask, FieldOffset offset>
struct RegisterRead {
//! Write access implementation.
/**
* @tparam T Field data type.
* @param mmio_device Pointer to register mapped memory.
* @param mask Field mask.
* @param offset Field offset.
* @param value Value to be written at the field location.
*/
template <typename T>
inline static void write(T* const mmio_device,
const T mask,
const Offset_t offset,
const T value) noexcept {
*mmio_device = static_cast<T>((*mmio_device & ~mask) |
((value << offset) & mask));
};
//! Non-trivial read implementation.
/**
* @param mmio_device Pointer to the register memory device.
* @return The content of the register field.
*/
template <typename U = void>
static T read(const MMIO& mmio_device,
is_not_trivial<T, mask, offset, U>* = nullptr) noexcept {
return static_cast<T>((mmio_device & mask) >> offset);
}
//! Set field implementation.
/**
* @tparam T Field data type.
* @param mmio_device Pointer to register mapped memory.
* @param mask Field mask.
*/
template <typename T>
inline static void set(T* const mmio_device, const T mask) noexcept {
*mmio_device = static_cast<T>((*mmio_device) | mask);
};
//! Clear field implementation.
/**
* @tparam T Field data type.
* @param mmio_device Pointer to register mapped memory.
* @param mask Field mask.
*/
template <typename T>
inline static void clear(T* const mmio_device, const T mask) noexcept {
*mmio_device = static_cast<T>((*mmio_device) & ~mask);
};
//! Toggle field implementation.
/**
* @tparam T Field data type.
* @param mmio_device Pointer to register mapped memory.
* @param mask Field mask.
*/
template <typename T>
inline static void toggle(T* const mmio_device, const T mask) noexcept {
*mmio_device ^= mask;
};
};
//! Trivial read implementation.
/**
* @param mmio_device Pointer to the register memory device.
* @return The content of the register field.
*/
template <typename U = void>
static T read(const MMIO& mmio_device,
is_trivial<T, mask, offset, U>* = nullptr) noexcept {
return static_cast<T>(mmio_device);
}
};
//! Write-only access policy.
struct write_only {
//! Register write implementation.
/**
* @tparam MMIO Memory device type.
* @tparam T Register data type.
* @tparam mask Mask for the read operation.
* @tparam offset Offset for the read operation.
*/
template <typename MMIO, typename T, T mask, FieldOffset offset>
struct RegisterWrite {
//! Write access implementation.
/**
* @tparam T Field data type.
* @param mmio_device Pointer to register mapped memory.
* @param mask Field mask.
* @param offset Field offset
* @param value Value to be written at the field location.
*/
template <typename T>
inline static void write(T* const mmio_device,
const T mask,
const Offset_t offset,
const T value) noexcept {
//! Non-trivial write implementation.
/**
* @param mmio_device Pointer to the register memory device.
* @param value Value to be written to the register field.
*/
template <typename U = void>
static void write(MMIO& mmio_device,
T value,
is_not_trivial<T, mask, offset, U>* = nullptr) noexcept {
mmio_device =
static_cast<T>((mmio_device & ~mask) | ((value << offset) & mask));
}
// We cannot read the current value so we simply fully write to it.
*mmio_device = ((value << offset) & mask);
};
};
//! Trivial write implementation.
/**
* @param mmio_device Pointer to the register memory device.
* @param value Value to be written to the register field.
*/
template <typename U = void>
static void write(MMIO& mmio_device,
T value,
is_trivial<T, mask, offset, U>* = nullptr) noexcept {
mmio_device = value;
}
};
}
//! Register write constant implementation.
/**
* @tparam MMIO Memory device type.
* @tparam T Register data type.
* @tparam mask Mask for the read operation.
* @tparam offset Offset for the read operation.
* @tparam value Value to be written to the register field.
*/
template <typename MMIO, typename T, T mask, FieldOffset offset, T value>
struct RegisterWriteConstant {
//! Non-trivial write implementation.
/**
* @param mmio_device Pointer to the register memory device.
*/
template <typename U = void>
static void write(MMIO& mmio_device,
is_not_trivial<T, mask, offset, U>* = nullptr) noexcept {
mmio_device =
static_cast<T>((mmio_device & ~mask) | ((value << offset) & mask));
}
//! Trivial write implementation.
/**
* @param mmio_device Pointer to the register memory device.
*/
template <typename U = void>
static void write(MMIO& mmio_device,
is_trivial<T, mask, offset, U>* = nullptr) noexcept {
mmio_device = value;
}
};
#endif // CPPREG_ACCESSPOLICY_H
//! Read-only access policy.
struct read_only {
//! Read access implementation.
/**
* @tparam MMIO Register memory device type.
* @tparam T Field data type.
* @tparam mask Field mask.
* @tparam offset Field offset.
* @param mmio_device Pointer to register mapped memory.
* @return The value at the field location.
*/
template <typename MMIO, typename T, T mask, FieldOffset offset>
static T read(const MMIO& mmio_device) noexcept {
return RegisterRead<MMIO, T, mask, offset>::read(mmio_device);
}
};
//! Read-write access policy.
struct read_write : read_only {
//! Write access implementation.
/**
* @tparam MMIO Register memory device type.
* @tparam T Field data type.
* @tparam mask Field mask.
* @tparam offset Field offset.
* @param mmio_device Pointer to register mapped memory.
* @param value Value to be written at the field location.
*/
template <typename MMIO, typename T, T mask, FieldOffset offset>
static void write(MMIO& mmio_device, const T value) noexcept {
RegisterWrite<MMIO, T, mask, offset>::write(mmio_device, value);
}
//! Write access implementation for constant value.
/**
* @tparam MMIO Register memory device type.
* @tparam T Field data type.
* @tparam mask Field mask.
* @tparam offset Field offset.
* @tparam value Value to be written at the field location.
* @param mmio_device Pointer to register mapped memory.
*/
template <typename MMIO, typename T, T mask, FieldOffset offset, T value>
static void write(MMIO& mmio_device) noexcept {
RegisterWriteConstant<MMIO, T, mask, offset, value>::write(mmio_device);
}
//! Set field implementation.
/**
* @tparam T Field data type.
* @tparam mask Field mask.
* @param mmio_device Pointer to register mapped memory.
*/
template <typename MMIO, typename T, T mask>
static void set(MMIO& mmio_device) noexcept {
RegisterWriteConstant<MMIO, T, mask, FieldOffset{0}, mask>::write(
mmio_device);
}
//! Clear field implementation.
/**
* @tparam MMIO Register memory device type.
* @tparam T Field data type.
* @tparam mask Field mask.
* @param mmio_device Pointer to register mapped memory.
*/
template <typename MMIO, typename T, T mask>
static void clear(MMIO& mmio_device) noexcept {
RegisterWriteConstant<MMIO,
T,
mask,
FieldOffset{0},
static_cast<T>(~mask)>::write(mmio_device);
}
//! Toggle field implementation.
/**
* @tparam MMIO Register memory device type.
* @tparam T Field data type.
* @tparam mask Field mask.
* @param mmio_device Pointer to register mapped memory.
*/
template <typename MMIO, typename T, T mask>
static void toggle(MMIO& mmio_device) noexcept {
mmio_device = static_cast<T>((mmio_device) ^ mask);
}
};
//! Write-only access policy.
struct write_only {
//! Write access implementation.
/**
* @tparam MMIO Register memory device type.
* @tparam T Field data type.
* @tparam mask Field mask.
* @tparam offset Field offset
* @param mmio_device Pointer to register mapped memory.
* @param value Value to be written at the field location.
*/
template <typename MMIO, typename T, T mask, FieldOffset offset>
static void write(MMIO& mmio_device, const T value) noexcept {
// For write-only fields we can only write to the whole register.
RegisterWrite<MMIO, T, type_mask<T>::value, FieldOffset{0}>::write(
mmio_device, ((value << offset) & mask));
}
//! Write access implementation for constant value.
/**
* @tparam MMIO Register memory device type.
* @tparam T Field data type.
* @tparam mask Field mask.
* @tparam offset Field offset
* @tparam value Value to be written at the field location.
* @param mmio_device Pointer to register mapped memory.
*/
template <typename MMIO, typename T, T mask, FieldOffset offset, T value>
static void write(MMIO& mmio_device) noexcept {
// For write-only fields we can only write to the whole register.
RegisterWriteConstant<MMIO,
T,
type_mask<T>::value,
FieldOffset{0},
((value << offset) & mask)>::write(mmio_device);
}
};
} // namespace cppreg
#endif // CPPREG_ACCESSPOLICY_H

View File

@@ -2,10 +2,11 @@
/**
* @file Field.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* This header provides the definitions related to register field
* implementation.
* implementation. Strictly speaking a field is defined as a region of a
* register.
*/
@@ -13,258 +14,195 @@
#define CPPREG_REGISTERFIELD_H
#include "Register.h"
#include "Mask.h"
#include "AccessPolicy.h"
#include "ShadowValue.h"
#include "Internals.h"
#include "Mask.h"
//! cppreg namespace.
namespace cppreg {
//! Register field implementation.
//! Register field implementation.
/**
* @tparam BaseRegister Parent register.
* @tparam width Field width.
* @tparam offset Field offset.
* @tparam P Access policy type.
*
* This data structure provides static methods to deal with field access
* (read, write, set, clear, and toggle). These methods availability depends
* on the access policy (e.g., a read-only field does not implement a
* write method).
* In practice, fields are implemented by deriving from this class to
* create custom types.
*/
template <typename BaseRegister,
FieldWidth field_width,
FieldOffset field_offset,
typename AccessPolicy>
struct Field {
//! Parent register for the field.
using parent_register = BaseRegister;
//! Field data type derived from register data type.
using type = typename parent_register::type;
//! MMIO type.
using MMIO = typename parent_register::MMIO;
//! Field policy.
using policy = AccessPolicy;
//! Field width.
constexpr static auto width = field_width;
//! Field offset.
constexpr static auto offset = field_offset;
//! Field mask.
constexpr static auto mask = make_shifted_mask<type>(width, offset);
//!@{ Helpers for write method selection based on shadow value.
template <type value, typename T>
using if_no_shadow =
typename std::enable_if<!parent_register::shadow::value, T>::type;
template <type value, typename T>
using if_shadow =
typename std::enable_if<parent_register::shadow::value, T>::type;
//!@}
//!@ Field read method.
/**
* @tparam BaseRegister Parent register.
* @tparam width Field width.
* @tparam offset Field offset.
* @tparam P Access policy type (rw, ro, wo).
*
* This data structure provides static methods to deal with field access
* (read, write, set, clear, and toggle). These methods availability depends
* on the access policy (e.g., a read-only field does not implement a
* write method).
* In practice, fields are implemented by deriving from this class to
* create custom types.
* @return Field value.
*/
template <
typename BaseRegister,
Width_t FieldWidth,
Offset_t FieldOffset,
typename AccessPolicy
>
struct Field {
static type read() noexcept {
return policy::template read<MMIO, type, mask, offset>(
parent_register::ro_mem_device());
}
//! Parent register for the field.
using parent_register = BaseRegister;
//! Field write value method (no shadow value).
/**
* @param value Value to be written to the field.
*/
template <typename T = type>
static void write(const if_no_shadow<type{0}, T> value) noexcept {
policy::template write<MMIO, type, mask, offset>(
parent_register::rw_mem_device(), value);
}
//! Field data type derived from register data type.
using type = typename parent_register::type;
//! Field write value method (w/ shadow value).
/**
* @param value Value to be written to the field.
*/
template <typename T = type>
static void write(const if_shadow<type{0}, T> value) noexcept {
//! MMIO type.
using MMIO_t = typename parent_register::MMIO_t;
// Update shadow value.
RegisterWrite<type, type, mask, offset>::write(
parent_register::shadow::shadow_value, value);
//! Field width.
constexpr static const Width_t width = FieldWidth;
// Write as a block to the register, that is, we do not use the
// field mask and field offset.
policy::
template write<MMIO, type, type_mask<type>::value, FieldOffset{0}>(
parent_register::rw_mem_device(),
parent_register::shadow::shadow_value);
}
//! Field offset.
constexpr static const Offset_t offset = FieldOffset;
//! Field write constant method (no shadow value).
/**
* @tparam value Constant to be written to the field
*
* This method performs a compile-time check to avoid overflowing the
* field and uses the constant write implementation.
*/
template <type value, typename T = void>
static void write(if_no_shadow<value, T>* = nullptr) noexcept {
policy::template write<MMIO, type, mask, offset, value>(
parent_register::rw_mem_device());
//! Field policy.
using policy = AccessPolicy;
// Check for overflow.
static_assert(
internals::check_overflow<type, value, (mask >> offset)>::value,
"Field::write<value>: value too large for the field");
}
//! Field mask.
/**
* The field mask is computed at compile time.
*/
constexpr static const type mask = make_shifted_mask<type>(width,
offset);
//! Field write constant method (w/ shadow value).
/**
* @tparam value Constant to be written to the field
*
* This method performs a compile-time check to avoid overflowing the
* field and uses the constant write implementation.
*/
template <type value, typename T = void>
static void write(if_shadow<value, T>* = nullptr) noexcept {
// For this one we simply forward to the non-constant
// implementation because the shadow value needs to be updated.
write(value);
//! Customized overflow check implementation for Field types.
/**
* @tparam value Value to be checked for overflow.
* @return `true` if no overflow, `false` otherwise.
*/
template <type value>
struct check_overflow {
constexpr static const bool result =
internals::check_overflow<
parent_register::size,
value,
(mask >> offset)
>::result::value;
};
// Check for overflow.
static_assert(
internals::check_overflow<type, value, (mask >> offset)>::value,
"Field::write<value>: value too large for the field");
}
//! Field read method.
/**
* @return Field value.
*/
inline static type read() noexcept {
return
AccessPolicy
::template read<MMIO_t>(parent_register::ro_mem_pointer(),
mask,
offset);
};
//! Field set method.
/**
* This method will set all bits in the field.
*/
static void set() noexcept {
policy::template set<MMIO, type, mask>(
parent_register::rw_mem_device());
}
//! Field write method (shadow value disabled).
/**
* @param value Value to be written to the field.
*
* We use SFINAE to discriminate for registers with shadow value
* enabled.
*
* This method does not perform any check on the input value. If the
* input value is too large for the field size it will not overflow
* but only the part that fits in the field will be written.
* For safe write see
*/
template <typename T = type>
inline static void
write(const typename std::enable_if<
!parent_register::shadow::use_shadow, T
>::type value) noexcept {
AccessPolicy
::template write<MMIO_t>(parent_register::rw_mem_pointer(),
mask,
offset,
value);
};
//! Field clear method.
/**
* This method will clear all bits in the field.
*/
static void clear() noexcept {
policy::template clear<MMIO, type, mask>(
parent_register::rw_mem_device());
}
//! Field write method (shadow value enabled).
/**
* @param value Value to be written to the field.
*
* We use SFINAE to discriminate for registers with shadow value
* enabled.
*
* This method does not perform any check on the input value. If the
* input value is too large for the field size it will not overflow
* but only the part that fits in the field will be written.
* For safe write see
*/
template <typename T = type>
inline static void
write(const typename std::enable_if<
parent_register::shadow::use_shadow, T
>::type value) noexcept {
//! Field toggle method.
/**
* This method will toggle all bits in the field.
*/
static void toggle() noexcept {
policy::template toggle<MMIO, type, mask>(
parent_register::rw_mem_device());
}
// Update shadow value.
// Fetch the whole register content.
// This assumes that reading a write-only fields return some value.
parent_register::shadow::value =
(parent_register::shadow::value & ~mask) |
((value << offset) & mask);
//! Is field set bool method.
/**
* @return `true` if all the bits are set to 1, `false` otherwise.
*/
static bool is_set() noexcept {
return (Field::read() == (mask >> offset));
}
// Write as a block to the register, that is, we do not use the
// mask and offset.
AccessPolicy
::template write<MMIO_t>(parent_register::rw_mem_pointer(),
~(0u),
0u,
parent_register::shadow::value);
//! Is field clear bool method.
/**
* @return `true` if all the bits are set to 0, `false` otherwise.
*/
static bool is_clear() noexcept {
return (Field::read() == type{0});
}
};
//! Field write method with compile-time check (shadow value disabled).
/**
* @tparam value Value to be written to the field
*
* We use SFINAE to discriminate for registers with shadow value
* enabled.
*
* This method performs a compile-time check to avoid overflowing the
* field.
*/
template <type value, typename T = void>
inline static
typename std::enable_if<
(!parent_register::shadow::use_shadow)
&&
check_overflow<value>::result,
T
>::type
write() noexcept {
write(value);
};
//! Field write method with compile-time check (shadow value enabled).
/**
* @tparam value Value to be written to the field
*
* We use SFINAE to discriminate for registers with shadow value
* enabled.
*
* This method performs a compile-time check to avoid overflowing the
* field.
*/
template <type value, typename T = void>
inline static
typename std::enable_if<
parent_register::shadow::use_shadow
&&
check_overflow<value>::result,
T
>::type
write() noexcept {
write(value);
};
// Consistency checking.
// The width of the field cannot exceed the register size and the
// width added to the offset cannot exceed the register size.
static_assert(parent_register::size >= width,
"Field:: field width is larger than parent register size");
static_assert(parent_register::size >= width + offset,
"Field:: offset + width is larger than parent register size");
static_assert(width != FieldWidth{0},
"Field:: defining a Field type of zero width is not allowed");
};
//! Field set method.
/**
* This method will set all bits in the field.
*/
inline static void set() noexcept {
AccessPolicy
::template set<MMIO_t>(parent_register::rw_mem_pointer(), mask);
};
//! Field clear method.
/**
* This method will clear all bits in the field.
*/
inline static void clear() noexcept {
AccessPolicy
::template clear<MMIO_t>(parent_register::rw_mem_pointer(), mask);
};
//! Field toggle method.
/**
* This method will toggle all bits in the field.
*/
inline static void toggle() noexcept {
AccessPolicy
::template toggle<MMIO_t>(parent_register::rw_mem_pointer(), mask);
};
//! Is field set bool method.
/**
* @return `true` if the 1-bit field is set to 1, `false` otherwise.
*
* This is only available if the field is 1 bit wide.
*/
template <typename T = bool>
inline static typename std::enable_if<FieldWidth == 1, T>::type
is_set() noexcept {
return (Field::read() == 1u);
};
//! Is field clear bool method.
/**
* @return `true` if the 1-bit field is set to 0, `false` otherwise.
*
* This is only available if the field is 1 bit wide.
*/
template <typename T = bool>
inline static typename std::enable_if<FieldWidth == 1, T>::type
is_clear() noexcept {
return (Field::read() == 0u);
};
// Consistency checking.
// The width of the field cannot exceed the register size and the
// width added to the offset cannot exceed the register size.
static_assert(parent_register::size >= width,
"field width is larger than parent register size");
static_assert(parent_register::size >= width + offset,
"offset + width is larger than parent register size");
static_assert(FieldWidth != 0u,
"defining a Field type of width 0u is not allowed");
};
} // namespace cppreg
}
#endif // CPPREG_REGISTERFIELD_H
#endif // CPPREG_REGISTERFIELD_H

53
register/Internals.h Normal file
View File

@@ -0,0 +1,53 @@
//! Internals implementation.
/**
* @file Internals.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* This header collects various implementations which are required for cppreg
* implementation but not intended to be fully exposed to the user.
*/
#ifndef CPPREG_INTERNALS_H
#define CPPREG_INTERNALS_H
#include "Traits.h"
namespace cppreg {
namespace internals {
//! Overflow check implementation.
/**
* @tparam T Data type.
* @tparam value Value to check.
* @tparam limit Overflow limit value.
*
* This structure defines a type result set to std::true_type if there is
* no overflow and set to std::false_type if there is overflow.
* There is overflow if value if strictly larger than limit.
*/
template <typename T, T value, T limit>
struct check_overflow : std::integral_constant<bool, value <= limit> {};
//! is_aligned implementation.
/**
* @tparam address Address to be checked for alignment.
* @tparam alignment Alignment boundary in bytes.
*
* This will only derived from std::true_type if the address is aligned.
*/
template <Address address, std::size_t alignment>
struct is_aligned
: std::integral_constant<bool, (address & (alignment - 1)) == 0> {};
} // namespace internals
} // namespace cppreg
#endif // CPPREG_INTERNALS_H

View File

@@ -2,7 +2,7 @@
/**
* @file Mask.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* The implementation is designed to compute masks prior to runtime by
* relying on constexpr function. This will work as intended if the function
@@ -17,42 +17,38 @@
#include "cppreg_Defines.h"
//! cppreg namespace.
namespace cppreg {
//! Mask constexpr function.
/**
* @tparam Mask_t Mask data type (will be derived from register).
* @param width Mask width.
* @return The mask value.
*/
template <typename Mask_t>
constexpr Mask_t make_mask(const Width_t width) noexcept {
return width == 0 ?
0u
:
static_cast<Mask_t>(
(make_mask<Mask_t>(Width_t(width - 1)) << 1) | 1
);
};
//! Shifted mask constexpr function.
/**
* @tparam Mask_t Mask data type (will be derived from register).
* @param width Mask width.
* @param offset Mask offset.
* @return The mask value.
*/
template <typename Mask_t>
constexpr Mask_t make_shifted_mask(const Width_t width,
const Offset_t offset) noexcept {
return static_cast<Mask_t>(make_mask<Mask_t>(width) << offset);
};
//! Mask constexpr function.
/**
* @tparam Mask Mask data type (will be derived from register).
* @param width Mask width.
* @return The mask value.
*/
template <typename Mask>
constexpr Mask make_mask(const FieldWidth width) noexcept {
return width == 0 ? static_cast<Mask>(0u)
: static_cast<Mask>(
(make_mask<Mask>(FieldWidth(width - 1)) << 1) | 1);
}
#endif // CPPREG_MASK_H
//! Shifted mask constexpr function.
/**
* @tparam Mask Mask data type (will be derived from register).
* @param width Mask width.
* @param offset Mask offset.
* @return The mask value.
*/
template <typename Mask>
constexpr Mask make_shifted_mask(const FieldWidth width,
const FieldOffset offset) noexcept {
return static_cast<Mask>(make_mask<Mask>(width) << offset);
}
} // namespace cppreg
#endif // CPPREG_MASK_H

106
register/Memory.h Normal file
View File

@@ -0,0 +1,106 @@
//! Memory device implementation.
/**
* @file Memory.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*/
#ifndef CPPREG_DEV_MEMORY_H
#define CPPREG_DEV_MEMORY_H
#include "Traits.h"
#include <array>
namespace cppreg {
//! Register pack base implementation.
/**
* @tparam base_address Pack base address.
* @tparam pack_byte_size Pack size in bytes.
*/
template <Address base_address, std::uint32_t pack_byte_size>
struct RegisterPack {
//! Base address.
constexpr static const Address pack_base = base_address;
//! Pack size in bytes.
constexpr static const std::uint32_t size_in_bytes = pack_byte_size;
};
//! Memory device.
/**
* @tparam mem_address Address of the memory device.
* @tparam mem_byte_size Memory device size in bytes.
*/
template <Address mem_address, std::size_t mem_byte_size>
struct MemoryDevice {
//! Storage type.
using memory_storage = std::array<volatile std::uint8_t, mem_byte_size>;
//! Memory device storage.
static memory_storage& _mem_storage;
//! Accessor.
template <RegBitSize reg_size, std::size_t byte_offset>
static const volatile typename TypeTraits<reg_size>::type& ro_memory() {
// Check alignment.
static_assert(
internals::is_aligned<mem_address + byte_offset,
std::alignment_of<typename TypeTraits<
reg_size>::type>::value>::value,
"MemoryDevice:: ro request not aligned");
return *(reinterpret_cast<const volatile
typename TypeTraits<reg_size>::type*>(
&_mem_storage[byte_offset]));
}
//! Modifier.
template <RegBitSize reg_size, std::size_t byte_offset>
static volatile typename TypeTraits<reg_size>::type& rw_memory() {
// Check alignment.
static_assert(
internals::is_aligned<mem_address + byte_offset,
std::alignment_of<typename TypeTraits<
reg_size>::type>::value>::value,
"MemoryDevice:: rw request not aligned");
return *(
reinterpret_cast<volatile typename TypeTraits<reg_size>::type*>(
&_mem_storage[byte_offset]));
}
};
//! Static reference definition.
template <Address a, std::size_t s>
typename MemoryDevice<a, s>::memory_storage& MemoryDevice<a, s>::_mem_storage =
*(reinterpret_cast<typename MemoryDevice<a, s>::memory_storage*>(a));
//! Register memory device for register pack.
/**
*
* @tparam pack_address Register pack address.
* @tparam n_bytes Register pack size in bytes.
*/
template <typename RegisterPack>
struct RegisterMemoryDevice {
using mem_device =
MemoryDevice<RegisterPack::pack_base, RegisterPack::size_in_bytes>;
};
} // namespace cppreg
#endif // CPPREG_DEV_MEMORY_H

View File

@@ -2,10 +2,15 @@
/**
* @file MergeWrite.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* The "merge write" implementation is designed to make it possible to merge
* write operations on different fields into a single one.
* The implementation distinguishes between values known at compile time and
* value known at run time.
*
* By design the merge write implementation forces the caller to chain and
* finalize all write operations in a single pass.
*/
@@ -13,149 +18,213 @@
#define CPPREG_MERGEWRITE_H
#include "Overflow.h"
#include "AccessPolicy.h"
#include <functional>
#include "Internals.h"
//! cppreg namespace.
namespace cppreg {
//! Write operation holding structure.
//! Merge write constant implementation.
/**
* @tparam Register Register on which the merged write will be performed.
* @tparam mask Initial mask.
* @tparam offset Initial offset.
* @tparam value Initial value.
*
* The initial data will come from the field on which the merge write
* will be initiated.
*
* This implementation is designed for operations in which all data is
* available at compile time. This makes it possible to leverage a
* template implementation and simplify most of the operations (based on
* the access polict implementation that detects trivial operations). In
* addition, this will also perform overflow checking.
*/
template <typename Register,
typename Register::type mask,
FieldOffset offset,
typename Register::type value>
class MergeWrite_tmpl {
private:
// Type alias to register base type.
using base_type = typename Register::type;
// Accumulated value.
constexpr static auto _accumulated_value =
base_type{(value << offset) & mask};
// Combined mask.
constexpr static auto _combined_mask = mask;
// Type helper.
template <typename F, base_type new_value>
using propagated =
MergeWrite_tmpl<Register,
(_combined_mask | F::mask),
FieldOffset{0},
(_accumulated_value & ~F::mask)
| ((new_value << F::offset) & F::mask)>;
// Default constructor.
MergeWrite_tmpl() = default;
// Disabled for shadow value register.
static_assert(!Register::shadow::value,
"merge write is not available for shadow value register");
public:
//! Instantiation method.
static MergeWrite_tmpl create() noexcept {
return {};
}
//!@{ Non-copyable and non-moveable.
MergeWrite_tmpl(const MergeWrite_tmpl&) = delete;
MergeWrite_tmpl& operator=(const MergeWrite_tmpl&) = delete;
MergeWrite_tmpl& operator=(MergeWrite_tmpl&&) = delete;
MergeWrite_tmpl operator=(MergeWrite_tmpl) = delete;
MergeWrite_tmpl(MergeWrite_tmpl&&) = delete;
//!@}
//! Closure method.
/**
* @tparam Register Underlying register for the final write operation.
* This is where the write happens.
*/
template <typename Register>
class MergeWrite {
void done() const&& noexcept {
// Get memory pointer.
typename Register::MMIO& mmio_device = Register::rw_mem_device();
// Write to the whole register using the current accumulated value
// and combined mask.
// No offset needed because we write to the whole register.
RegisterWriteConstant<typename Register::MMIO,
typename Register::type,
_combined_mask,
FieldOffset{0},
_accumulated_value>::write(mmio_device);
}
//! With method for constant value.
/**
* @tparam F Field to be written
* @tparam new_value Value to write to the field.
* @return A merge write instance with accumulated data.
*/
template <typename F, base_type field_value>
propagated<F, field_value>&& with() const&& noexcept {
// Check that the field belongs to the register.
static_assert(
std::is_same<typename F::parent_register, Register>::value,
"MergeWrite_tmpl:: field is not from the same register");
// Check that there is no overflow.
constexpr auto no_overflow =
internals::check_overflow<typename Register::type,
field_value,
(F::mask >> F::offset)>::value;
static_assert(no_overflow,
"MergeWrite_tmpl:: field overflow in with() call");
return std::move(propagated<F, field_value>{});
}
};
public:
//! Merge write implementation.
/**
* @tparam Register Register on which the merged write will be performed.
* @tparam mask Initial mask.
*
* The initial mask will come from the field on which the merge write
* will be initiated.
*/
template <typename Register, typename Register::type mask>
class MergeWrite {
//! Type alias to register base type.
using base_type = typename Register::type;
private:
// Type alias to register base type.
using base_type = typename Register::type;
//! Static instantiation method.
static MergeWrite create_instance(const base_type value,
const base_type mask) noexcept {
MergeWrite mw;
mw._accumulated_value = value;
mw._combined_mask = mask;
return mw;
};
// Accumulated value.
base_type _accumulated_value;
//!@ Move constructor.
MergeWrite(MergeWrite&& mw) noexcept
: _accumulated_value(mw._accumulated_value),
_combined_mask(mw._combined_mask) {
};
// Combined mask.
constexpr static auto _combined_mask = mask;
//!@{ Non-copyable.
MergeWrite(const MergeWrite&) = delete;
MergeWrite& operator=(const MergeWrite&) = delete;
//!@}
// Type helper.
template <typename F>
using propagated = MergeWrite<Register, _combined_mask | F::mask>;
//! Destructor.
/**
* This is where the write operation is performed.
*/
~MergeWrite() {
// Private default constructor.
constexpr MergeWrite() : _accumulated_value{0} {};
constexpr explicit MergeWrite(const base_type v) : _accumulated_value{v} {};
// Get memory pointer.
typename Register::MMIO_t* const mmio_device =
Register::rw_mem_pointer();
// Disabled for shadow value register.
static_assert(!Register::shadow::value,
"merge write is not available for shadow value register");
// Write to the whole register using the current accumulated value
// and combined mask.
// No offset needed because we write to the whole register.
*mmio_device = static_cast<base_type>(
(*mmio_device & ~_combined_mask) |
((_accumulated_value) & _combined_mask)
);
public:
//! Static instantiation method.
constexpr static MergeWrite create(const base_type value) noexcept {
return MergeWrite(value);
}
};
//!@ Move constructor.
MergeWrite(MergeWrite&& mw) noexcept
: _accumulated_value{mw._accumulated_value} {};
//! With method.
/**
* @tparam F Field type describing where to write in the register.
* @param value Value to write to the register.
* @return A reference to the current merge write data.
*
* This method is used to add another operation to the final merged
* write.
*/
template <typename F>
MergeWrite&& with(const base_type value) && noexcept {
//!@{ Non-copyable.
MergeWrite(const MergeWrite&) = delete;
MergeWrite& operator=(const MergeWrite&) = delete;
MergeWrite& operator=(MergeWrite&&) = delete;
//!@}
// Check that the field belongs to the register.
static_assert(std::is_same<
typename F::parent_register,
Register
>::value,
"field is not from the same register in merge_write");
//! Closure method.
/**
* This is where the write happens.
*/
void done() const&& noexcept {
// Update accumulated value.
F::policy::write(&_accumulated_value,
F::mask,
F::offset,
value);
// Get memory pointer.
typename Register::MMIO& mmio_device = Register::rw_mem_device();
// Update combine mask.
_combined_mask = _combined_mask | F::mask;
// Write to the whole register using the current accumulated value
// and combined mask.
// No offset needed because we write to the whole register.
RegisterWrite<typename Register::MMIO,
base_type,
_combined_mask,
FieldOffset{0}>::write(mmio_device, _accumulated_value);
}
return std::move(*this);
//! With method.
/**
* @tparam F Field type describing where to write in the register.
* @param value Value to write to the register.
* @return A merge write instance with accumulated data.
*/
template <typename F>
propagated<F> with(const base_type value) const&& noexcept {
};
// Check that the field belongs to the register.
static_assert(
std::is_same<typename F::parent_register, Register>::value,
"field is not from the same register in merge_write");
//! With method with compile-time check.
/**
* @tparam F Field type describing where to write in the register.
* @param value Value to write to the register.
* @return A reference to the current merge write data.
*
* This method is used to add another operation to the final merged
* write.
*
* This method performs a compile-time check to avoid overflowing the
* field.
*/
template <
typename F,
base_type value,
typename T = MergeWrite
>
typename std::enable_if<
(internals::check_overflow<
Register::size, value, (F::mask >> F::offset)
>::result::value),
T
>::type&&
with() && noexcept {
return std::move(*this).template with<F>(value);
};
// Update accumulated value.
const auto new_value = static_cast<base_type>(
(_accumulated_value & ~F::mask) | ((value << F::offset) & F::mask));
return std::move(propagated<F>::create(new_value));
}
};
private:
// Disabled for shadow value register.
static_assert(!Register::shadow::use_shadow,
"merge write is not available for shadow value register");
// Private default constructor.
MergeWrite() : _accumulated_value(0u),
_combined_mask(0u) {};
// Accumulated value.
base_type _accumulated_value;
// Combined mask.
base_type _combined_mask;
} // namespace cppreg
};
}
#endif // CPPREG_MERGEWRITE_H
#endif // CPPREG_MERGEWRITE_H

View File

@@ -1,47 +0,0 @@
//! Overflow check implementation.
/**
* @file Overflow.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
*/
#ifndef CPPREG_OVERFLOW_H
#define CPPREG_OVERFLOW_H
#include "Traits.h"
#include <type_traits>
//! cppreg::internals namespace.
namespace cppreg {
namespace internals {
//! Overflow check implementation.
/**
* @tparam W Width of the register or field type.
* @tparam value Value to check.
* @tparam limit Overflow limit value.
*
* This structure defines a type result set to std::true_type if there is
* no overflow and set to std::false_type if there is overflow.
* There is overflow if value if strictly larger than limit.
*/
template <
Width_t W,
typename RegisterType<W>::type value,
typename RegisterType<W>::type limit
>
struct check_overflow {
using result =
typename std::integral_constant<bool, value <= limit>::type;
};
}
}
#endif // CPPREG_OVERFLOW_H

View File

@@ -2,7 +2,7 @@
/**
* @file Register.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* This header provides the definitions related to register implementation.
*/
@@ -12,119 +12,119 @@
#define CPPREG_REGISTER_H
#include "Traits.h"
#include "Memory.h"
#include "MergeWrite.h"
#include "ShadowValue.h"
//! cppreg namespace.
namespace cppreg {
//! Register data structure.
//! Register data structure.
/**
* @tparam reg_address Register address.
* @tparam reg_size Register size enum value.
* @tparam reset_value Register reset value (0x0 if unknown).
* @tparam use_shadow shadow Boolean flag to enable shadow value.
*
* This data structure will act as a container for fields and is
* therefore limited to a strict minimum. It only carries information
* about the register base address, size, and reset value.
* In practice, register are implemented by deriving from this class to
* create custom types.
*/
template <Address reg_address,
RegBitSize reg_size,
typename TypeTraits<reg_size>::type reset_value = 0x0,
bool use_shadow = false>
struct Register {
//! Register base type.
using type = typename TypeTraits<reg_size>::type;
//! MMIO pointer type.
using MMIO = volatile type;
//! Boolean flag for shadow value management.
using shadow = Shadow<Register, use_shadow>;
//! Register base address.
constexpr static auto base_address = reg_address;
//! Register size in bits.
constexpr static auto size = TypeTraits<reg_size>::bit_size;
//! Register reset value.
constexpr static auto reset = reset_value;
//! Register pack for memory device.
using pack = RegisterPack<base_address, size / 8u>;
//! Memory modifier.
/**
* @tparam address Register address.
* @tparam width Register total width (i.e., size).
* @tparam reset Register reset value (0x0 if unknown).
* @tparam shadow Boolean flag to enable shadow value (enabled if `true`).
*
* This data structure will act as a container for fields and is
* therefore limited to a strict minimum. It only carries information
* about the register base address, size, and reset value.
* In practice, register are implemented by deriving from this class to
* create custom types.
* @return A reference to the writable register memory.
*/
template <
Address_t RegAddress,
Width_t RegWidth,
typename RegisterType<RegWidth>::type ResetValue = 0x0,
bool UseShadow = false
>
struct Register {
static MMIO& rw_mem_device() {
using mem_device = typename RegisterMemoryDevice<pack>::mem_device;
return mem_device::template rw_memory<reg_size, 0>();
}
//! Register base type.
using type = typename RegisterType<RegWidth>::type;
//! Memory accessor.
/**
* @return A reference to the read-only register memory.
*/
static const MMIO& ro_mem_device() {
using mem_device = typename RegisterMemoryDevice<pack>::mem_device;
return mem_device::template ro_memory<reg_size, 0>();
}
//! MMIO pointer type.
using MMIO_t = volatile type;
//! Merge write start function.
/**
* @tparam F Field on which to perform the first write operation.
* @param value Value to be written to the field.
* @return A merge write data structure to chain further writes.
*/
template <typename F>
static MergeWrite<typename F::parent_register, F::mask> merge_write(
const typename F::type value) noexcept {
return MergeWrite<typename F::parent_register, F::mask>::create(
static_cast<type>((value << F::offset) & F::mask));
}
//! Register base address.
constexpr static const Address_t base_address = RegAddress;
//! Merge write start function for constant value.
/**
* @tparam F Field on which to perform the first write operation.
* @tparam value Value to be written to the field.
* @return A merge write data structure to chain further writes.
*/
template <typename F,
type value,
typename T = MergeWrite_tmpl<typename F::parent_register,
F::mask,
F::offset,
value>>
static T&& merge_write() noexcept {
//! Register total width.
constexpr static const Width_t size = RegWidth;
// Check overflow.
static_assert(
internals::check_overflow<type, value, (F::mask >> F::offset)>::
value,
"Register::merge_write<value>:: value too large for the field");
//! Register reset value.
constexpr static const type reset = ResetValue;
return std::move(T::create());
}
//! Boolean flag for shadow value management.
using shadow = Shadow<Register, UseShadow>;
// Sanity check.
static_assert(size != 0u, "Register:: register definition with zero size");
//! Memory modifier.
/**
* @return A pointer to the writable register memory.
*/
static MMIO_t* rw_mem_pointer() {
return reinterpret_cast<MMIO_t* const>(base_address);
};
//! Memory accessor.
/**
* @return A pointer to the read-only register memory.
*/
static const MMIO_t* ro_mem_pointer() {
return reinterpret_cast<const MMIO_t* const>(base_address);
};
//! Merge write function.
/**
* @tparam F Field on which to perform the write operation.
* @param value Value to write to the field.
* @return A merge write data structure.
*/
template <typename F>
inline static MergeWrite<typename F::parent_register>
merge_write(const typename F::type value) noexcept {
return
MergeWrite<typename F::parent_register>
::create_instance(((value << F::offset) & F::mask), F::mask);
};
//! Merge write function.
/**
* @tparam F Field on which to perform the write operation.
* @param value Value to write to the field.
* @return A merge write data structure.
*/
template <
typename F,
type value,
typename T = MergeWrite<typename F::parent_register>
>
inline static
typename std::enable_if<
internals::check_overflow<
size, value, (F::mask >> F::offset)
>::result::value,
T
>::type
merge_write() noexcept {
return
MergeWrite<typename F::parent_register>
::create_instance(((value << F::offset) & F::mask), F::mask);
};
// Sanity check.
static_assert(RegWidth != 0u,
"defining a Register type of width 0u is not allowed");
};
// Enforce alignment.
static_assert(internals::is_aligned<reg_address,
TypeTraits<reg_size>::byte_size>::value,
"Register:: address is mis-aligned for register type");
};
}
#endif // CPPREG_REGISTER_H
} // namespace cppreg
#endif // CPPREG_REGISTER_H

180
register/RegisterPack.h Normal file
View File

@@ -0,0 +1,180 @@
//! Register pack implementation.
/**
* @file RegisterPack.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* This header provides the definitions related to packed register
* implementation.
*/
#ifndef CPPREG_REGISTERPACK_H
#define CPPREG_REGISTERPACK_H
#include "Internals.h"
#include "Memory.h"
#include "Register.h"
namespace cppreg {
//! Packed register implementation.
/**
* @tparam RegisterPack Pack to which the register belongs.
* @tparam reg_size Register size enum value.
* @tparam bit_offset Offset in bits for the register with respect to base.
* @tparam reset_value Register reset value (0x0 if unknown).
* @tparam use_shadow Boolean flag to enable shadow value.
*
* This implementation is intended to be used when defining a register
* that belongs to a peripheral group.
*/
template <typename RegisterPack,
RegBitSize reg_size,
std::uint32_t bit_offset,
typename TypeTraits<reg_size>::type reset_value = 0x0,
bool use_shadow = false>
struct PackedRegister : Register<RegisterPack::pack_base + (bit_offset / 8u),
reg_size,
reset_value,
use_shadow> {
//! Register pack.
using pack = RegisterPack;
//! Register type.
using base_reg = Register<RegisterPack::pack_base + (bit_offset / 8u),
reg_size,
reset_value,
use_shadow>;
//! Memory modifier.
/**
* @return A reference to the writable register memory.
*/
static typename base_reg::MMIO& rw_mem_device() noexcept {
using mem_device =
typename RegisterMemoryDevice<RegisterPack>::mem_device;
return mem_device::template rw_memory<reg_size, (bit_offset / 8u)>();
}
//! Memory accessor.
/**
* @return A reference to the read-only register memory.
*/
static const typename base_reg::MMIO& ro_mem_device() noexcept {
using mem_device =
typename RegisterMemoryDevice<RegisterPack>::mem_device;
return mem_device::template ro_memory<reg_size, (bit_offset / 8u)>();
}
// Safety check to detect if are overflowing the pack.
static_assert(TypeTraits<reg_size>::byte_size + (bit_offset / 8u)
<= RegisterPack::size_in_bytes,
"PackRegister:: packed register is overflowing the pack");
// A packed register of width N bits requires:
// - the pack address to be N-bits aligned (N/8 aligned),
// - the pack address with offset to be N-bits aligned (N/8 aligned).
static_assert(
internals::is_aligned<RegisterPack::pack_base,
TypeTraits<reg_size>::byte_size>::value,
"PackedRegister:: pack base address is mis-aligned for register type");
static_assert(
internals::is_aligned<RegisterPack::pack_base + (bit_offset / 8u),
TypeTraits<reg_size>::byte_size>::value,
"PackedRegister:: offset address is mis-aligned for register type");
};
//! Pack indexing structure.
/**
* @tparam T List of types (registers or fields) to index.
*
* This can be used to conveniently map indices over packed registers.
* The order in the variadic parameter pack will define the indexing
* (starting at zero).
*/
template <typename... T>
struct PackIndexing {
//! Tuple type.
using tuple_t = typename std::tuple<T...>;
//! Number of elements.
constexpr static const std::size_t n_elems =
std::tuple_size<tuple_t>::value;
//! Element accessor.
template <std::size_t N>
using elem = typename std::tuple_element<N, tuple_t>::type;
};
//! Template for loop implementation.
/**
* @tparam start Start index value.
* @tparam end End index value.
*/
template <std::size_t start, std::size_t end>
struct for_loop {
//! Loop method.
/**
* @tparam Func Function to be called at each iteration.
*
* This will call Op for the range [start, end).
*/
template <typename Func>
static void apply() noexcept {
Func().template operator()<start>();
if (start < end)
for_loop<start + 1ul, end>::template apply<Func>();
}
#if __cplusplus >= 201402L
//! Apply method.
/**
* @tparam Op Operator type to be called.
*
* This is only available with C++14 and up as this requires polymorphic
* lambdas to be used in a somewhat useful manner.
*
* Typical example:
* use lambda [](auto index) { index.value will be the loop index};
*/
template <typename Op>
static void apply(Op&& f) noexcept {
if (start < end) {
f(std::integral_constant<std::size_t, start>{});
for_loop<start + 1ul, end>::apply(std::forward<Op>(f));
};
}
#endif // __cplusplus 201402L
};
template <std::size_t end>
struct for_loop<end, end> {
template <typename Func>
static void apply() noexcept {}
#if __cplusplus >= 201402L
template <typename Op>
static void apply(Op&& f) noexcept {}
#endif // __cplusplus 201402L
};
//! Template range loop implementation.
/**
* @tparam IndexedPack Indexed pack type.
*/
template <typename IndexedPack>
struct pack_loop : for_loop<0, IndexedPack::n_elems> {};
} // namespace cppreg
#endif // CPPREG_REGISTERPACK_H

View File

@@ -2,7 +2,7 @@
/**
* @file ShadowValue.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*/
@@ -13,40 +13,33 @@
#include "cppreg_Defines.h"
//! cppreg namespace.
namespace cppreg {
//! Shadow value generic implementation.
/**
* @tparam Register Register type.
* @tparam UseShadow Boolean flag indicating if shadow value is required.
*
* This implementation is for register which do not require shadow value.
*/
template <typename Register, bool UseShadow>
struct Shadow {
constexpr static const bool use_shadow = false;
};
//! Shadow value generic implementation.
/**
* @tparam Register Register type.
* @tparam use_shadow Boolean flag indicating if shadow value is required.
*/
template <typename Register, bool use_shadow>
struct Shadow : std::false_type {};
//! Shadow value implementation.
/**
* @tparam Register Register type.
*
* This implementation is for register which do require shadow value.
*/
template <typename Register>
struct Shadow<Register, true> {
static typename Register::type value;
constexpr static const bool use_shadow = true;
};
template <typename Register>
typename Register::type Shadow<Register, true>::value = Register::reset;
template <typename Register>
const bool Shadow<Register, true>::use_shadow;
}
//! Shadow value specialization.
/**
* @tparam Register Register type.
*
* This implementation is for register which do require shadow value.
*/
template <typename Register>
struct Shadow<Register, true> : std::true_type {
static typename Register::type shadow_value;
};
template <typename Register>
typename Register::type Shadow<Register, true>::shadow_value = Register::reset;
#endif // CPPREG_SHADOWVALUE_H
} // namespace cppreg
#endif // CPPREG_SHADOWVALUE_H

View File

@@ -2,7 +2,7 @@
/**
* @file Traits.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*
* This header provides some traits for register type instantiation.
*/
@@ -15,27 +15,55 @@
#include "cppreg_Defines.h"
//! cppreg namespace.
namespace cppreg {
//! Register data type default implementation.
/**
* @tparam Size Register size.
*
* This will fail to compile if the register size is not implemented.
*/
template <Width_t Size>
struct RegisterType;
//!@{ Specializations based on register size.
template <> struct RegisterType<8u> { using type = std::uint8_t; };
template <> struct RegisterType<16u> { using type = std::uint16_t; };
template <> struct RegisterType<32u> { using type = std::uint32_t; };
//!@}
//! Register type traits based on size.
/**
* @tparam S Register size in bits.
*/
template <RegBitSize S>
struct TypeTraits {};
}
//!@{ TypeTraits specializations.
//! 8-bit specialization.
template <>
struct TypeTraits<RegBitSize::b8> {
using type = std::uint8_t;
constexpr static auto bit_size = std::uint8_t{8};
constexpr static auto byte_size = std::uint8_t{bit_size / 8};
};
//! 16-bit specialization.
template <>
struct TypeTraits<RegBitSize::b16> {
using type = std::uint16_t;
constexpr static auto bit_size = std::uint8_t{16};
constexpr static auto byte_size = std::uint8_t{bit_size / 8};
};
//! 32-bit specialization.
template <>
struct TypeTraits<RegBitSize::b32> {
using type = std::uint32_t;
constexpr static auto bit_size = std::uint8_t{32};
constexpr static auto byte_size = std::uint8_t{bit_size / 8};
};
//! 64-bit specialization.
template <>
struct TypeTraits<RegBitSize::b64> {
using type = std::uint64_t;
constexpr static auto bit_size = std::uint8_t{64};
constexpr static auto byte_size = std::uint8_t{bit_size / 8};
};
//!@}
#endif // CPPREG_TRAITS_H
} // namespace cppreg
#endif // CPPREG_TRAITS_H

View File

@@ -2,372 +2,577 @@
/**
* @file cppreg-all.h
* @author Nicolas Clauvelin (nclauvelin@sendyne.com)
* @copyright Copyright 2010-2018 Sendyne Corp. All rights reserved.
* @copyright Copyright 2010-2019 Sendyne Corp. All rights reserved.
*/
#include <cstdint>
#include <type_traits>
#include <functional>
#include <limits>
// cppreg_Defines.h
#ifndef CPPREG_CPPREG_DEFINES_H
#define CPPREG_CPPREG_DEFINES_H
namespace cppreg {
using Address_t = std::uintptr_t;
using Width_t = std::uint8_t;
using Offset_t = std::uint8_t;
}
#endif
// AccessPolicy.h
#ifndef CPPREG_ACCESSPOLICY_H
#define CPPREG_ACCESSPOLICY_H
namespace cppreg {
struct read_only {
template <typename T>
inline static T read(const T* const mmio_device,
const T mask,
const Offset_t offset) noexcept {
return static_cast<T>((*mmio_device & mask) >> offset);
};
};
struct read_write : read_only {
template <typename T>
inline static void write(T* const mmio_device,
const T mask,
const Offset_t offset,
const T value) noexcept {
*mmio_device = static_cast<T>((*mmio_device & ~mask) |
((value << offset) & mask));
};
template <typename T>
inline static void set(T* const mmio_device, const T mask) noexcept {
*mmio_device = static_cast<T>((*mmio_device) | mask);
};
template <typename T>
inline static void clear(T* const mmio_device, const T mask) noexcept {
*mmio_device = static_cast<T>((*mmio_device) & ~mask);
};
template <typename T>
inline static void toggle(T* const mmio_device, const T mask) noexcept {
*mmio_device ^= mask;
};
};
struct write_only {
template <typename T>
inline static void write(T* const mmio_device,
const T mask,
const Offset_t offset,
const T value) noexcept {
*mmio_device = ((value << offset) & mask);
};
};
}
#endif
using Address = std::uintptr_t;
enum class RegBitSize : std::uint8_t {
b8,
b16,
b32,
b64
};
using FieldWidth = std::uint8_t;
using FieldOffset = std::uint8_t;
template <typename T>
struct type_mask {
constexpr static const T value = std::numeric_limits<T>::max();
};
}
#endif
// Traits.h
#ifndef CPPREG_TRAITS_H
#define CPPREG_TRAITS_H
namespace cppreg {
template <Width_t Size>
struct RegisterType;
template <> struct RegisterType<8u> { using type = std::uint8_t; };
template <> struct RegisterType<16u> { using type = std::uint16_t; };
template <> struct RegisterType<32u> { using type = std::uint32_t; };
}
#endif
template <RegBitSize S>
struct TypeTraits {};
template <>
struct TypeTraits<RegBitSize::b8> {
using type = std::uint8_t;
constexpr static auto bit_size = std::uint8_t{8};
constexpr static auto byte_size = std::uint8_t{bit_size / 8};
};
template <>
struct TypeTraits<RegBitSize::b16> {
using type = std::uint16_t;
constexpr static auto bit_size = std::uint8_t{16};
constexpr static auto byte_size = std::uint8_t{bit_size / 8};
};
template <>
struct TypeTraits<RegBitSize::b32> {
using type = std::uint32_t;
constexpr static auto bit_size = std::uint8_t{32};
constexpr static auto byte_size = std::uint8_t{bit_size / 8};
};
template <>
struct TypeTraits<RegBitSize::b64> {
using type = std::uint64_t;
constexpr static auto bit_size = std::uint8_t{64};
constexpr static auto byte_size = std::uint8_t{bit_size / 8};
};
}
#endif
// Overflow.h
#ifndef CPPREG_OVERFLOW_H
#define CPPREG_OVERFLOW_H
// Internals.h
#ifndef CPPREG_INTERNALS_H
#define CPPREG_INTERNALS_H
namespace cppreg {
namespace internals {
template <
Width_t W,
typename RegisterType<W>::type value,
typename RegisterType<W>::type limit
>
struct check_overflow {
using result =
typename std::integral_constant<bool, value <= limit>::type;
};
}
}
#endif
template <typename T, T value, T limit>
struct check_overflow : std::integral_constant<bool, value <= limit> {};
template <Address address, std::size_t alignment>
struct is_aligned
: std::integral_constant<bool, (address & (alignment - 1)) == 0> {};
}
}
#endif
// Memory.h
#ifndef CPPREG_DEV_MEMORY_H
#define CPPREG_DEV_MEMORY_H
namespace cppreg {
template <Address base_address, std::uint32_t pack_byte_size>
struct RegisterPack {
constexpr static const Address pack_base = base_address;
constexpr static const std::uint32_t size_in_bytes = pack_byte_size;
};
template <Address mem_address, std::size_t mem_byte_size>
struct MemoryDevice {
using memory_storage = std::array<volatile std::uint8_t, mem_byte_size>;
static memory_storage& _mem_storage;
template <RegBitSize reg_size, std::size_t byte_offset>
static const volatile typename TypeTraits<reg_size>::type& ro_memory() {
static_assert(
internals::is_aligned<mem_address + byte_offset,
std::alignment_of<typename TypeTraits<
reg_size>::type>::value>::value,
"MemoryDevice:: ro request not aligned");
return *(reinterpret_cast<const volatile
typename TypeTraits<reg_size>::type*>(
&_mem_storage[byte_offset]));
}
template <RegBitSize reg_size, std::size_t byte_offset>
static volatile typename TypeTraits<reg_size>::type& rw_memory() {
static_assert(
internals::is_aligned<mem_address + byte_offset,
std::alignment_of<typename TypeTraits<
reg_size>::type>::value>::value,
"MemoryDevice:: rw request not aligned");
return *(
reinterpret_cast<volatile typename TypeTraits<reg_size>::type*>(
&_mem_storage[byte_offset]));
}
};
template <Address a, std::size_t s>
typename MemoryDevice<a, s>::memory_storage& MemoryDevice<a, s>::_mem_storage =
*(reinterpret_cast<typename MemoryDevice<a, s>::memory_storage*>(a));
template <typename RegisterPack>
struct RegisterMemoryDevice {
using mem_device =
MemoryDevice<RegisterPack::pack_base, RegisterPack::size_in_bytes>;
};
}
#endif
// AccessPolicy.h
#ifndef CPPREG_ACCESSPOLICY_H
#define CPPREG_ACCESSPOLICY_H
namespace cppreg {
template <typename T, T mask, FieldOffset offset>
struct is_trivial_rw
: std::integral_constant<bool,
(mask == type_mask<T>::value)
&& (offset == FieldOffset{0})> {};
template <typename T, T mask, FieldOffset offset, typename U>
using is_trivial =
typename std::enable_if<is_trivial_rw<T, mask, offset>::value, U>::type;
template <typename T, T mask, FieldOffset offset, typename U>
using is_not_trivial =
typename std::enable_if<!is_trivial_rw<T, mask, offset>::value, U>::type;
template <typename MMIO, typename T, T mask, FieldOffset offset>
struct RegisterRead {
template <typename U = void>
static T read(const MMIO& mmio_device,
is_not_trivial<T, mask, offset, U>* = nullptr) noexcept {
return static_cast<T>((mmio_device & mask) >> offset);
}
template <typename U = void>
static T read(const MMIO& mmio_device,
is_trivial<T, mask, offset, U>* = nullptr) noexcept {
return static_cast<T>(mmio_device);
}
};
template <typename MMIO, typename T, T mask, FieldOffset offset>
struct RegisterWrite {
template <typename U = void>
static void write(MMIO& mmio_device,
T value,
is_not_trivial<T, mask, offset, U>* = nullptr) noexcept {
mmio_device =
static_cast<T>((mmio_device & ~mask) | ((value << offset) & mask));
}
template <typename U = void>
static void write(MMIO& mmio_device,
T value,
is_trivial<T, mask, offset, U>* = nullptr) noexcept {
mmio_device = value;
}
};
template <typename MMIO, typename T, T mask, FieldOffset offset, T value>
struct RegisterWriteConstant {
template <typename U = void>
static void write(MMIO& mmio_device,
is_not_trivial<T, mask, offset, U>* = nullptr) noexcept {
mmio_device =
static_cast<T>((mmio_device & ~mask) | ((value << offset) & mask));
}
template <typename U = void>
static void write(MMIO& mmio_device,
is_trivial<T, mask, offset, U>* = nullptr) noexcept {
mmio_device = value;
}
};
struct read_only {
template <typename MMIO, typename T, T mask, FieldOffset offset>
static T read(const MMIO& mmio_device) noexcept {
return RegisterRead<MMIO, T, mask, offset>::read(mmio_device);
}
};
struct read_write : read_only {
template <typename MMIO, typename T, T mask, FieldOffset offset>
static void write(MMIO& mmio_device, const T value) noexcept {
RegisterWrite<MMIO, T, mask, offset>::write(mmio_device, value);
}
template <typename MMIO, typename T, T mask, FieldOffset offset, T value>
static void write(MMIO& mmio_device) noexcept {
RegisterWriteConstant<MMIO, T, mask, offset, value>::write(mmio_device);
}
template <typename MMIO, typename T, T mask>
static void set(MMIO& mmio_device) noexcept {
RegisterWriteConstant<MMIO, T, mask, FieldOffset{0}, mask>::write(
mmio_device);
}
template <typename MMIO, typename T, T mask>
static void clear(MMIO& mmio_device) noexcept {
RegisterWriteConstant<MMIO,
T,
mask,
FieldOffset{0},
static_cast<T>(~mask)>::write(mmio_device);
}
template <typename MMIO, typename T, T mask>
static void toggle(MMIO& mmio_device) noexcept {
mmio_device = static_cast<T>((mmio_device) ^ mask);
}
};
struct write_only {
template <typename MMIO, typename T, T mask, FieldOffset offset>
static void write(MMIO& mmio_device, const T value) noexcept {
RegisterWrite<MMIO, T, type_mask<T>::value, FieldOffset{0}>::write(
mmio_device, ((value << offset) & mask));
}
template <typename MMIO, typename T, T mask, FieldOffset offset, T value>
static void write(MMIO& mmio_device) noexcept {
RegisterWriteConstant<MMIO,
T,
type_mask<T>::value,
FieldOffset{0},
((value << offset) & mask)>::write(mmio_device);
}
};
}
#endif
// Mask.h
#ifndef CPPREG_MASK_H
#define CPPREG_MASK_H
namespace cppreg {
template <typename Mask_t>
constexpr Mask_t make_mask(const Width_t width) noexcept {
return width == 0 ?
0u
:
static_cast<Mask_t>(
(make_mask<Mask_t>(Width_t(width - 1)) << 1) | 1
);
};
template <typename Mask_t>
constexpr Mask_t make_shifted_mask(const Width_t width,
const Offset_t offset) noexcept {
return static_cast<Mask_t>(make_mask<Mask_t>(width) << offset);
};
template <typename Mask>
constexpr Mask make_mask(const FieldWidth width) noexcept {
return width == 0 ? static_cast<Mask>(0u)
: static_cast<Mask>(
(make_mask<Mask>(FieldWidth(width - 1)) << 1) | 1);
}
#endif
template <typename Mask>
constexpr Mask make_shifted_mask(const FieldWidth width,
const FieldOffset offset) noexcept {
return static_cast<Mask>(make_mask<Mask>(width) << offset);
}
}
#endif
// ShadowValue.h
#ifndef CPPREG_SHADOWVALUE_H
#define CPPREG_SHADOWVALUE_H
namespace cppreg {
template <typename Register, bool UseShadow>
struct Shadow {
constexpr static const bool use_shadow = false;
};
template <typename Register>
struct Shadow<Register, true> {
static typename Register::type value;
constexpr static const bool use_shadow = true;
};
template <typename Register>
typename Register::type Shadow<Register, true>::value = Register::reset;
template <typename Register>
const bool Shadow<Register, true>::use_shadow;
}
#endif
template <typename Register, bool use_shadow>
struct Shadow : std::false_type {};
template <typename Register>
struct Shadow<Register, true> : std::true_type {
static typename Register::type shadow_value;
};
template <typename Register>
typename Register::type Shadow<Register, true>::shadow_value = Register::reset;
}
#endif
// MergeWrite.h
#ifndef CPPREG_MERGEWRITE_H
#define CPPREG_MERGEWRITE_H
namespace cppreg {
template <typename Register>
class MergeWrite {
public:
using base_type = typename Register::type;
static MergeWrite create_instance(const base_type value,
const base_type mask) noexcept {
MergeWrite mw;
mw._accumulated_value = value;
mw._combined_mask = mask;
return mw;
};
MergeWrite(MergeWrite&& mw) noexcept
: _accumulated_value(mw._accumulated_value),
_combined_mask(mw._combined_mask) {
};
MergeWrite(const MergeWrite&) = delete;
MergeWrite& operator=(const MergeWrite&) = delete;
~MergeWrite() {
typename Register::MMIO_t* const mmio_device =
Register::rw_mem_pointer();
*mmio_device = static_cast<base_type>(
(*mmio_device & ~_combined_mask) |
((_accumulated_value) & _combined_mask)
);
};
template <typename F>
MergeWrite&& with(const base_type value) && noexcept {
static_assert(std::is_same<
typename F::parent_register,
Register
>::value,
"field is not from the same register in merge_write");
F::policy::write(&_accumulated_value,
F::mask,
F::offset,
value);
_combined_mask = _combined_mask | F::mask;
return std::move(*this);
};
template <
typename F,
base_type value,
typename T = MergeWrite
>
typename std::enable_if<
(internals::check_overflow<
Register::size, value, (F::mask >> F::offset)
>::result::value),
T
>::type&&
with() && noexcept {
return std::move(*this).template with<F>(value);
};
private:
static_assert(!Register::shadow::use_shadow,
"merge write is not available for shadow value register");
MergeWrite() : _accumulated_value(0u),
_combined_mask(0u) {};
base_type _accumulated_value;
base_type _combined_mask;
};
}
#endif
template <typename Register,
typename Register::type mask,
FieldOffset offset,
typename Register::type value>
class MergeWrite_tmpl {
private:
using base_type = typename Register::type;
constexpr static auto _accumulated_value =
base_type{(value << offset) & mask};
constexpr static auto _combined_mask = mask;
template <typename F, base_type new_value>
using propagated =
MergeWrite_tmpl<Register,
(_combined_mask | F::mask),
FieldOffset{0},
(_accumulated_value & ~F::mask)
| ((new_value << F::offset) & F::mask)>;
MergeWrite_tmpl() = default;
static_assert(!Register::shadow::value,
"merge write is not available for shadow value register");
public:
static MergeWrite_tmpl create() noexcept {
return {};
}
MergeWrite_tmpl(const MergeWrite_tmpl&) = delete;
MergeWrite_tmpl& operator=(const MergeWrite_tmpl&) = delete;
MergeWrite_tmpl& operator=(MergeWrite_tmpl&&) = delete;
MergeWrite_tmpl operator=(MergeWrite_tmpl) = delete;
MergeWrite_tmpl(MergeWrite_tmpl&&) = delete;
void done() const&& noexcept {
typename Register::MMIO& mmio_device = Register::rw_mem_device();
RegisterWriteConstant<typename Register::MMIO,
typename Register::type,
_combined_mask,
FieldOffset{0},
_accumulated_value>::write(mmio_device);
}
template <typename F, base_type field_value>
propagated<F, field_value>&& with() const&& noexcept {
static_assert(
std::is_same<typename F::parent_register, Register>::value,
"MergeWrite_tmpl:: field is not from the same register");
constexpr auto no_overflow =
internals::check_overflow<typename Register::type,
field_value,
(F::mask >> F::offset)>::value;
static_assert(no_overflow,
"MergeWrite_tmpl:: field overflow in with() call");
return std::move(propagated<F, field_value>{});
}
};
template <typename Register, typename Register::type mask>
class MergeWrite {
private:
using base_type = typename Register::type;
base_type _accumulated_value;
constexpr static auto _combined_mask = mask;
template <typename F>
using propagated = MergeWrite<Register, _combined_mask | F::mask>;
constexpr MergeWrite() : _accumulated_value{0} {};
constexpr explicit MergeWrite(const base_type v) : _accumulated_value{v} {};
static_assert(!Register::shadow::value,
"merge write is not available for shadow value register");
public:
constexpr static MergeWrite create(const base_type value) noexcept {
return MergeWrite(value);
}
MergeWrite(MergeWrite&& mw) noexcept
: _accumulated_value{mw._accumulated_value} {};
MergeWrite(const MergeWrite&) = delete;
MergeWrite& operator=(const MergeWrite&) = delete;
MergeWrite& operator=(MergeWrite&&) = delete;
void done() const&& noexcept {
typename Register::MMIO& mmio_device = Register::rw_mem_device();
RegisterWrite<typename Register::MMIO,
base_type,
_combined_mask,
FieldOffset{0}>::write(mmio_device, _accumulated_value);
}
template <typename F>
propagated<F> with(const base_type value) const&& noexcept {
static_assert(
std::is_same<typename F::parent_register, Register>::value,
"field is not from the same register in merge_write");
const auto new_value = static_cast<base_type>(
(_accumulated_value & ~F::mask) | ((value << F::offset) & F::mask));
return std::move(propagated<F>::create(new_value));
}
};
}
#endif
// Register.h
#ifndef CPPREG_REGISTER_H
#define CPPREG_REGISTER_H
namespace cppreg {
template <
Address_t RegAddress,
Width_t RegWidth,
typename RegisterType<RegWidth>::type ResetValue = 0x0,
bool UseShadow = false
>
struct Register {
using type = typename RegisterType<RegWidth>::type;
using MMIO_t = volatile type;
constexpr static const Address_t base_address = RegAddress;
constexpr static const Width_t size = RegWidth;
constexpr static const type reset = ResetValue;
using shadow = Shadow<Register, UseShadow>;
static MMIO_t* rw_mem_pointer() {
return reinterpret_cast<MMIO_t* const>(base_address);
template <Address reg_address,
RegBitSize reg_size,
typename TypeTraits<reg_size>::type reset_value = 0x0,
bool use_shadow = false>
struct Register {
using type = typename TypeTraits<reg_size>::type;
using MMIO = volatile type;
using shadow = Shadow<Register, use_shadow>;
constexpr static auto base_address = reg_address;
constexpr static auto size = TypeTraits<reg_size>::bit_size;
constexpr static auto reset = reset_value;
using pack = RegisterPack<base_address, size / 8u>;
static MMIO& rw_mem_device() {
using mem_device = typename RegisterMemoryDevice<pack>::mem_device;
return mem_device::template rw_memory<reg_size, 0>();
}
static const MMIO& ro_mem_device() {
using mem_device = typename RegisterMemoryDevice<pack>::mem_device;
return mem_device::template ro_memory<reg_size, 0>();
}
template <typename F>
static MergeWrite<typename F::parent_register, F::mask> merge_write(
const typename F::type value) noexcept {
return MergeWrite<typename F::parent_register, F::mask>::create(
static_cast<type>((value << F::offset) & F::mask));
}
template <typename F,
type value,
typename T = MergeWrite_tmpl<typename F::parent_register,
F::mask,
F::offset,
value>>
static T&& merge_write() noexcept {
static_assert(
internals::check_overflow<type, value, (F::mask >> F::offset)>::
value,
"Register::merge_write<value>:: value too large for the field");
return std::move(T::create());
}
static_assert(size != 0u, "Register:: register definition with zero size");
static_assert(internals::is_aligned<reg_address,
TypeTraits<reg_size>::byte_size>::value,
"Register:: address is mis-aligned for register type");
};
}
#endif
// RegisterPack.h
#ifndef CPPREG_REGISTERPACK_H
#define CPPREG_REGISTERPACK_H
namespace cppreg {
template <typename RegisterPack,
RegBitSize reg_size,
std::uint32_t bit_offset,
typename TypeTraits<reg_size>::type reset_value = 0x0,
bool use_shadow = false>
struct PackedRegister : Register<RegisterPack::pack_base + (bit_offset / 8u),
reg_size,
reset_value,
use_shadow> {
using pack = RegisterPack;
using base_reg = Register<RegisterPack::pack_base + (bit_offset / 8u),
reg_size,
reset_value,
use_shadow>;
static typename base_reg::MMIO& rw_mem_device() noexcept {
using mem_device =
typename RegisterMemoryDevice<RegisterPack>::mem_device;
return mem_device::template rw_memory<reg_size, (bit_offset / 8u)>();
}
static const typename base_reg::MMIO& ro_mem_device() noexcept {
using mem_device =
typename RegisterMemoryDevice<RegisterPack>::mem_device;
return mem_device::template ro_memory<reg_size, (bit_offset / 8u)>();
}
static_assert(TypeTraits<reg_size>::byte_size + (bit_offset / 8u)
<= RegisterPack::size_in_bytes,
"PackRegister:: packed register is overflowing the pack");
static_assert(
internals::is_aligned<RegisterPack::pack_base,
TypeTraits<reg_size>::byte_size>::value,
"PackedRegister:: pack base address is mis-aligned for register type");
static_assert(
internals::is_aligned<RegisterPack::pack_base + (bit_offset / 8u),
TypeTraits<reg_size>::byte_size>::value,
"PackedRegister:: offset address is mis-aligned for register type");
};
template <typename... T>
struct PackIndexing {
using tuple_t = typename std::tuple<T...>;
constexpr static const std::size_t n_elems =
std::tuple_size<tuple_t>::value;
template <std::size_t N>
using elem = typename std::tuple_element<N, tuple_t>::type;
};
template <std::size_t start, std::size_t end>
struct for_loop {
template <typename Func>
static void apply() noexcept {
Func().template operator()<start>();
if (start < end)
for_loop<start + 1ul, end>::template apply<Func>();
}
#if __cplusplus >= 201402L
template <typename Op>
static void apply(Op&& f) noexcept {
if (start < end) {
f(std::integral_constant<std::size_t, start>{});
for_loop<start + 1ul, end>::apply(std::forward<Op>(f));
};
static const MMIO_t* ro_mem_pointer() {
return reinterpret_cast<const MMIO_t* const>(base_address);
};
template <typename F>
inline static MergeWrite<typename F::parent_register>
merge_write(const typename F::type value) noexcept {
return
MergeWrite<typename F::parent_register>
::create_instance(((value << F::offset) & F::mask), F::mask);
};
template <
typename F,
type value,
typename T = MergeWrite<typename F::parent_register>
>
inline static
typename std::enable_if<
internals::check_overflow<
size, value, (F::mask >> F::offset)
>::result::value,
T
>::type
merge_write() noexcept {
return
MergeWrite<typename F::parent_register>
::create_instance(((value << F::offset) & F::mask), F::mask);
};
static_assert(RegWidth != 0u,
"defining a Register type of width 0u is not allowed");
};
}
#endif
}
#endif
};
template <std::size_t end>
struct for_loop<end, end> {
template <typename Func>
static void apply() noexcept {}
#if __cplusplus >= 201402L
template <typename Op>
static void apply(Op&& f) noexcept {}
#endif
};
template <typename IndexedPack>
struct pack_loop : for_loop<0, IndexedPack::n_elems> {};
}
#endif
// Field.h
#ifndef CPPREG_REGISTERFIELD_H
#define CPPREG_REGISTERFIELD_H
namespace cppreg {
template <
typename BaseRegister,
Width_t FieldWidth,
Offset_t FieldOffset,
typename AccessPolicy
>
struct Field {
using parent_register = BaseRegister;
using type = typename parent_register::type;
using MMIO_t = typename parent_register::MMIO_t;
constexpr static const Width_t width = FieldWidth;
constexpr static const Offset_t offset = FieldOffset;
using policy = AccessPolicy;
constexpr static const type mask = make_shifted_mask<type>(width,
offset);
template <type value>
struct check_overflow {
constexpr static const bool result =
internals::check_overflow<
parent_register::size,
value,
(mask >> offset)
>::result::value;
};
inline static type read() noexcept {
return
AccessPolicy
::template read<MMIO_t>(parent_register::ro_mem_pointer(),
mask,
offset);
};
template <typename T = type>
inline static void
write(const typename std::enable_if<
!parent_register::shadow::use_shadow, T
>::type value) noexcept {
AccessPolicy
::template write<MMIO_t>(parent_register::rw_mem_pointer(),
mask,
offset,
value);
};
template <typename T = type>
inline static void
write(const typename std::enable_if<
parent_register::shadow::use_shadow, T
>::type value) noexcept {
parent_register::shadow::value =
(parent_register::shadow::value & ~mask) |
((value << offset) & mask);
AccessPolicy
::template write<MMIO_t>(parent_register::rw_mem_pointer(),
~(0u),
0u,
parent_register::shadow::value);
};
template <type value, typename T = void>
inline static
typename std::enable_if<
(!parent_register::shadow::use_shadow)
&&
check_overflow<value>::result,
T
>::type
write() noexcept {
write(value);
};
template <type value, typename T = void>
inline static
typename std::enable_if<
parent_register::shadow::use_shadow
&&
check_overflow<value>::result,
T
>::type
write() noexcept {
write(value);
};
inline static void set() noexcept {
AccessPolicy
::template set<MMIO_t>(parent_register::rw_mem_pointer(), mask);
};
inline static void clear() noexcept {
AccessPolicy
::template clear<MMIO_t>(parent_register::rw_mem_pointer(), mask);
};
inline static void toggle() noexcept {
AccessPolicy
::template toggle<MMIO_t>(parent_register::rw_mem_pointer(), mask);
};
template <typename T = bool>
inline static typename std::enable_if<FieldWidth == 1, T>::type
is_set() noexcept {
return (Field::read() == 1u);
};
template <typename T = bool>
inline static typename std::enable_if<FieldWidth == 1, T>::type
is_clear() noexcept {
return (Field::read() == 0u);
};
static_assert(parent_register::size >= width,
"field width is larger than parent register size");
static_assert(parent_register::size >= width + offset,
"offset + width is larger than parent register size");
static_assert(FieldWidth != 0u,
"defining a Field type of width 0u is not allowed");
};
}
#endif
template <typename BaseRegister,
FieldWidth field_width,
FieldOffset field_offset,
typename AccessPolicy>
struct Field {
using parent_register = BaseRegister;
using type = typename parent_register::type;
using MMIO = typename parent_register::MMIO;
using policy = AccessPolicy;
constexpr static auto width = field_width;
constexpr static auto offset = field_offset;
constexpr static auto mask = make_shifted_mask<type>(width, offset);
template <type value, typename T>
using if_no_shadow =
typename std::enable_if<!parent_register::shadow::value, T>::type;
template <type value, typename T>
using if_shadow =
typename std::enable_if<parent_register::shadow::value, T>::type;
static type read() noexcept {
return policy::template read<MMIO, type, mask, offset>(
parent_register::ro_mem_device());
}
template <typename T = type>
static void write(const if_no_shadow<type{0}, T> value) noexcept {
policy::template write<MMIO, type, mask, offset>(
parent_register::rw_mem_device(), value);
}
template <typename T = type>
static void write(const if_shadow<type{0}, T> value) noexcept {
RegisterWrite<type, type, mask, offset>::write(
parent_register::shadow::shadow_value, value);
policy::
template write<MMIO, type, type_mask<type>::value, FieldOffset{0}>(
parent_register::rw_mem_device(),
parent_register::shadow::shadow_value);
}
template <type value, typename T = void>
static void write(if_no_shadow<value, T>* = nullptr) noexcept {
policy::template write<MMIO, type, mask, offset, value>(
parent_register::rw_mem_device());
static_assert(
internals::check_overflow<type, value, (mask >> offset)>::value,
"Field::write<value>: value too large for the field");
}
template <type value, typename T = void>
static void write(if_shadow<value, T>* = nullptr) noexcept {
write(value);
static_assert(
internals::check_overflow<type, value, (mask >> offset)>::value,
"Field::write<value>: value too large for the field");
}
static void set() noexcept {
policy::template set<MMIO, type, mask>(
parent_register::rw_mem_device());
}
static void clear() noexcept {
policy::template clear<MMIO, type, mask>(
parent_register::rw_mem_device());
}
static void toggle() noexcept {
policy::template toggle<MMIO, type, mask>(
parent_register::rw_mem_device());
}
static bool is_set() noexcept {
return (Field::read() == (mask >> offset));
}
static bool is_clear() noexcept {
return (Field::read() == type{0});
}
static_assert(parent_register::size >= width,
"Field:: field width is larger than parent register size");
static_assert(parent_register::size >= width + offset,
"Field:: offset + width is larger than parent register size");
static_assert(width != FieldWidth{0},
"Field:: defining a Field type of zero width is not allowed");
};
}
#endif