Skip to main content

IAR Embedded Workbench for RX 5.20

Detecting bit loss or undefined behavior when shifting

In this section:
Description

Checks for overflow in shift operations and that shift counts are valid.

Why perform the check

Because the behavior of signed overflow is undefined, and because unsigned overflow results in a truncation that can sometimes be undesirable.

Overflow occurs in a left shift operation E1<<E2 if E1 is negative or if the result, defined as E1*2E2, is not in the range of representable values for its type.

How to use it

Compiler option: ‑‑runtime_checking signed_shift|unsigned_shift

In the IDE: Project>Options>Runtime Checking>Integer shift overflow

The check can be applied to one or more modules.

The check can be avoided by masking before shift:

/* Cannot overflow */ 
int f(int x) { return (x & 0x00007FFF) << 16; } 
How it works

The compiler inserts code to perform the check for each shift operation, unless the compiler determines that the check cannot fail.

The code size increases, which means that if the application has resource constraints this check should be used per module to minimize the overhead.

Example

Follow the procedure described in Getting started using C-RUN runtime error checking, but use the Integer shift overflow option.

This is an example of source code that will be identified during runtime:

crs_shift_Hom7.1_M16_1.PNG

C-RUN will report either Shift overflow or Shift count overflow. This is an example of the message information that will be listed:

message_shift_Hom7.1_M16.PNG