Optimisation with tasks

benny1111 wrote on Friday, December 14, 2018:

Hi,

I’m currently in the process of refactoring and optimising some code. I have a questing regarding how the compiler (with optimisations enabled) will see the flow of an application and the initialisation of variables. In the following example, is the compiler aware of the flow from main -> Init task -> Task A? In a tradational bare metal application, a call to the function allows the compiler to be aware that x is changed or used beforehand. Is the function pointer to Task A used in xTaskCreate from the init task essentially telling the compiler the same thing? - That is that x is used/changed before A is executed. In this scenario is there any way the compiler could think that x isn’t ever initialised and remove it? x shouldn’t need to be volatile in this scenario.

Main:
Start Init task
Start scheduler

Init task:
static var x;
Does some stuff
Initialises x
Starts Task A passing a pointer to x
Kills self

Task A:
Loops performing actions and reading parts of var x

Cheers,
Ben

ldb wrote on Saturday, December 15, 2018:

The optimizer won’t be aware of flow or order of things it doesn’t execute the code, It simply looks at what is used and what isn’t.

Your current code will possibly throw a warning at the moment that you are using an uninitialized value of X in task A, but it is unlikely it will be optimized away so long as x is actually used. The optimizer doesn’t know that task A can only be started from init task (as it has no idea what a task is) and if it assumes it is started from elesewhere then x is indeed uninitialized. It’s trivial to remove the warning simply initialize it.
static var x = { 0 };
Will work on any C99 or higher compiler for any type of var even if it is a struct or something like that.