eold
eold

Reputation: 6042

Type of RHS operand in bitwise shift of unsigned types

I want to shift an unsigned type (e.g. size_t) by a non-negative number of (binary) digits / places to the left/right, e.g.

size_t x;
x << non_const_expr

under the assumptions that the value of non_const_expr fits in an (unsigned) int and never causes undefined behavior (its value is non-negative and does not exceed the number of digits in x). (Note that the value is unknown at compile-time.)

Suppose that such a shift occurs in a performance-critical section (e.g. it is the only operation in the innermost loop). My trilemma is which type the right operand (the return type of non_consts_expr) should ideally be for the fastest shift operation:

Does it matter at all? If yes, which one generally results in the fastest code?

Upvotes: 2

Views: 783

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57678

The optimal performance of a left or right shift is when the RHS is a positive numerical constant.

Otherwise, it's processor dependent.

I suggest you code up different examples and look at the assembly language code generated by the compiler. You may also want to adjust the optimization settings also to see if they have any influence.

On the ARM7 processor, a shift operation may occur with a load register instruction; otherwise it would load a value then use a shift assembly instruction.

If you use a variable for the RHS, you are looking at the minimal operations:

  1. Load RHS from memory.
  2. Shift the register holding the LHS value by the RHS value.
  3. Store Result into memory.

The truth will be in the assembly language listing.

Optimizations at this level often don't produce negligible performance gains. Usually bigger gains can be found by optimizing design or code elsewhere.

Upvotes: 1

Related Questions