简体   繁体   中英

Redundant mov operations if you passing variable by reference

Is there any reason why modern C++ compilers can't optimize redundant mov instruction if you changing variable passed by reference?

Slow: https://gcc.godbolt.org/z/2Bmidk

Redundant mov:

10:        mov     QWORD PTR [rdi], rdx

Fast: https://gcc.godbolt.org/z/u3GMLx

Why compiler just don't store begin_ variable in CPU register and write it to memory in the end of function?

It seems that it may be invalid optimisation. What if begin_ equals to this ie address of CharStream itself (and it's valid to read bytes of any object using char* )? In that case after first read CharStream will change and so may the value of range [begin; end)

To avoid this you may do one of the following:

  • accept CharStream by value (so that it's address is unique and doesn't coincide with any char* ): https://gcc.godbolt.org/z/QfOUwW (note the change in behaviour. You'll need to return the stream if you need modifications)
  • use another type instead of char so that it can't alias with CharStream : https://gcc.godbolt.org/z/2_gREf (beware, it might be undefined to read your data using Byte* instead of char* because it's some_other_type* originally)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM