Code size reduction - Compiler Optimization

             One way to achieve this is to remove the unused data and functions. 

There are many 'library' functions provided in common source files. All code and data is currently linked into every executable, and most of the images do not use most of the functions. Significant SRAM could be saved if only the required code and data are included.

     To identify the unused data and functions, it will be easy if each function or data is created with separate section ( .text.fun1, .text.fun2). Compilers does not create separate sections for each function and data (.text and .data) by default. So, i started looking into the compiler flags and find below. I am using clang compiler and RISC-V GNU Compiler Toolchain.

test.c

Above program contains two functions fun1,fun2 and two variables x,y where fun2 ,x , y is never used. So in our final code we can remove fun2, x, y.

Compiler provides to below flags to achieve this. 

1. -fno-function-sections (default)

This flag create single section functions/data.

  Observe that fun1,fun2 are under section .text and x,y are under section .data

2. -ffunction-sections

This flag creates separate sections for each function.

fun1 is of section .text.fun1 and fun2 is of section .text.fun2 

3. -fdata-sections

This flag creates separate sections for each data


x is of section .data.x and y is of section .data.y

4. --gc-sections & -print-gc-sections
 --gc-sections remove the sections that are unused  while -print-gc-sections print the removed functions and data to standard output.
We can observe that fun2,x and y are removed and size of text and data sections are reduced.

Hope this helps :)

Cheers,
Harry

Comments