|
| 1 | +// ARM freestanding: compiler options effect demonstration |
| 2 | +// Uses only freestanding headers for ARM cross-compilation |
| 3 | +// Compare assembly with: -O0, -Os, -O2, -O3 |
| 4 | +#include <cstddef> |
| 5 | +#include <cstdint> |
| 6 | + |
| 7 | +// ---- Simple function: inlining candidate ---- |
| 8 | +int add_simple(int a, int b) { |
| 9 | + return a + b; |
| 10 | +} |
| 11 | + |
| 12 | +// ---- Loop: shows loop optimization ---- |
| 13 | +int accumulate(const int* data, size_t n) { |
| 14 | + int sum = 0; |
| 15 | + for (size_t i = 0; i < n; ++i) { |
| 16 | + sum += data[i]; |
| 17 | + } |
| 18 | + return sum; |
| 19 | +} |
| 20 | + |
| 21 | +// ---- Compile-time computation: should disappear at any -O ---- |
| 22 | +template <int N> constexpr int factorial() { |
| 23 | + int result = 1; |
| 24 | + for (int i = 2; i <= N; ++i) |
| 25 | + result *= i; |
| 26 | + return result; |
| 27 | +} |
| 28 | + |
| 29 | +constexpr int f10 = factorial<10>(); |
| 30 | +static_assert(f10 == 3628800); |
| 31 | + |
| 32 | +// ---- Struct with ctor: shows ctor optimization ---- |
| 33 | +struct TimerConfig { |
| 34 | + uint32_t period; |
| 35 | + uint32_t prescaler; |
| 36 | + uint8_t enabled; |
| 37 | + |
| 38 | + constexpr TimerConfig(uint32_t p, uint32_t ps, bool e) |
| 39 | + : period(p), prescaler(ps), enabled(e ? 1u : 0u) {} |
| 40 | +}; |
| 41 | + |
| 42 | +constexpr TimerConfig default_cfg{1000, 72, true}; |
| 43 | +static_assert(default_cfg.period == 1000); |
| 44 | + |
| 45 | +// ---- Callable wrappers to observe code generation ---- |
| 46 | +int call_add() { |
| 47 | + return add_simple(3, 4); |
| 48 | +} |
| 49 | + |
| 50 | +int call_accumulate() { |
| 51 | + const int data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
| 52 | + return accumulate(data, 10); |
| 53 | +} |
| 54 | + |
| 55 | +int call_factorial() { |
| 56 | + return f10; |
| 57 | +} |
| 58 | + |
| 59 | +uint32_t call_config() { |
| 60 | + return default_cfg.period + default_cfg.prescaler; |
| 61 | +} |
0 commit comments