Optimizations should be irrelevant for this code. The compiler is required to generate code that behaves as the language standard requires it to behave, and in this case, there is no flexibility in the values that your function can return for any particular argument value.
The compiler can generate whatever code it likes, as long as the function returns the required result. If getting the correct result from the function is all you care about, the language standard already covers that. either g++ does this right, or g++ has a bug. (I'm not aware of any g++ bug in this area, and I'd be surprised if there were such a bug.)
If you care about something other than having the function returning the correct result (for example, the particular sequence of CPU instructions), then (a) I have to wonder why you'd care, and (b) C++ is not a language that lets you impose such constraints. If the sequence of instructions matters to you, you might consider using assembly language.
What exactly is your concern?