pinMode/digitalWrite() in wiring_digital and SREG [SOLVED]

In wiring_digital ( https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_digital.c ), whenever they poke at the registers for pinMode/digitalWrite(), they always:

*Save SREG to oldSREG *Disable interrupts *Make the changes to the port control registers *Restore SREG to oldSREG

I know there must be good reasons for these things. I think I get why we'd be disabling interrupts - we want to make sure some interrupt doesn't bust in between when we set, say, the DDR vs when we set the PORT, thus ending up with the wrong value while the interrupt runs.

What's the deal with juggling SREG through? How can modifying the port registers make a mess of SREG? We're not doing arithmatic or logical operations, so SREG should stay squeaky clean except for the low bit which we're flipping with cli().

void pinMode(uint8_t pin, uint8_t mode)
{
 uint8_t bit = digitalPinToBitMask(pin);
 uint8_t port = digitalPinToPort(pin);
 volatile uint8_t *reg, *out;

 if (port == NOT_A_PIN) return;

 // JWS: can I let the optimizer do this?
 reg = portModeRegister(port);
 out = portOutputRegister(port);

 if (mode == INPUT) { 
 uint8_t oldSREG = SREG;
                cli();
 *reg &= ~bit;
 *out &= ~bit;
 SREG = oldSREG;
 } else if (mode == INPUT_PULLUP) {
 uint8_t oldSREG = SREG;
                cli();
 *reg &= ~bit;
 *out |= bit;
 SREG = oldSREG;
 } else {
 uint8_t oldSREG = SREG;
                cli();
 *reg |= bit;
 SREG = oldSREG;
 }
}

Thanks

Preserve the interrupt flag. Disable interrupts. Do the thing. Restore the interrupt flag.

If interrupts were disabled before they are disabled after. If interrupts were enabled before they are enabled after.

Make sense?

Aaah, the case of interrupts being disabled in the first place! Yup, that's what I missed, got it. Thanks.