Hasty Briefsbeta

Loop-Invariant Code Motion

3 days ago
  • #Compiler Optimizations
  • #C++
  • #Loop-Invariant Code Motion
  • The article discusses Loop-Invariant Code Motion (LICM), where compilers optimize loops by moving invariant code outside the loop.
  • An example is provided where `vec.size()` is called in each iteration, but the compiler optimizes by calculating it once before the loop.
  • A more complex example involves counting characters in a range using `std::string_view`, where the compiler moves the `get_range` call outside the loop.
  • Clang demonstrates clever optimizations like avoiding branches inside loops using `setle` and `setge` instructions.
  • GCC, surprisingly, fails to perform the same optimization, possibly due to issues with common subexpression elimination (CSE) on structured types like `std::pair`.
  • The article emphasizes trusting the compiler but also verifying its output using tools like Compiler Explorer.
  • The post is part of the 'Advent of Compiler Optimisations 2025' series and was written by Matt Godbolt, with review by LLMs and humans.