简体   繁体   中英

Why does the compiler not optimize away interrupt code?

I recently ran into a problem with a variable only being modified in an interrupt handler. The variable itself was not declared volatile so at higher levels of optimization the compiler broke the code. However, the compiler is smart enough to compile the interrupt code because the interrupt still fires.

So here are my questions:

  1. If the compiler is smart enough to compile the interrupt code, why is it not smart enough to realize that variables are changed inside that interrupt?

  2. At higher levels of optimization, functions that aren't called get optimized out. Since no code calls the interrupt handler it should get optimized away. What causes the compiler to compile the interrupt code anyway?

  1. The language execution model says that an ordinary (non-volatile) variable cannot be changed by "external forces". Ie if your code flow does not explicitly change the variable, then from that code flow's point of view the variable cannot possibly change. (Besides what's defined by C11 for multithreaded execution). You have to manually "designate" variables that can be changed by interrupt handlers.

    This is one of the main factors that enables efficient optimizations of C code. It cannot be eliminated without making a significant negative impact on the performance of C programs.

  2. Firstly, compilers don't usually optimize away functions with external linkage. Is your interrupt handler declared with external linkage?

    Secondly, the decision to optimize out a function or keep it is not really based on whether the function is called or not. It is based on whether the corresponding symbol is referenced in your program in any way. Non-referenced symbols are removed, while the referenced ones are kept. There are other ways to reference a function symbol besides calling it. For example, taking address of a function also counts as a reference to function symbol. Functions whose addresses are taken anywhere in the program are never optimized away.

    Your interrupt vector entry gets initialized somehow at program startup, which normally involves taking address of the handler function. That is already sufficient to protect this function from being optimized out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM