This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Debugger optimizing out variables? Or some other strange behavior?

Guru 15580 points


I must have a fundamental mis-understanding of the CCS v5 compiler & debugger. Any advice would be appreciated.

Here is some example code that illustrates my confusion:

#include <msp430.h>

/*
* main.c
*/

#include "stdint.h"

int main(void) {

int valid;
uint8_t temp1;
uint8_t temp2;

WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer

P1DIR |= BIT0; // P1.0 set as output
P1OUT = 0;
temp1 = 0xC0;
temp2 = temp1 & 0x80;
if(temp2 != 0) valid = 1;
else valid = 0;
if(valid == 1) P1OUT =1;
}

When I enter debug mode the debugger initially stops on the first executable line (WDTCTL = ...). After that I am able to step into the next two lines of code (P1DIR... and P1OUT...). But then when I attempt to step into the next line (temp1...) the debugger skips both the temp1 and temp2 lines and halts at the if(temp2...) line. So temp1 and temp2 are never set to the values in the code. Also, when I use the memory browser to examine the memory location of temp2, it cannot be found. Also, temp2 does not appear in the "varibles" window in CCS.

What the heck is going on??

  • When you completely switch off the optimizer you will get what you expect.
    But with the optimizer (minimal ‘0’) everything here is handled with CPU registers, and not using RAM.
    This “temp2 = temp1 & 0x80” will never be zero, so “if(temp2 != 0)” will always be true, no need for more code lines and this “P1OUT =1” must be always done.
    So clever these TI compiler makers!
  • temp1 is only written once. so the compiler can (and does) treat it as a constant like #define temp1 0xc0
    This once again happens tor temp2 too:
    #define temp2 temp1 & 0x80 (where temp1 is replaced by 0xc0).
    so the if clause evaluates to (0x80 != 0) which is always true and results in if(-1), which will eliminate the else case.
    If valid is not declared volatile, even the check for valid=1 might be eliminated, since valid was set to 1 right before.

**Attention** This is a public forum