IT lexicon › Programming › Loop flattening

Loop flattening

Programming På svenska → Updated: 2026-11-07

Merging two nested loops into one, so for i … for j … becomes a single loop over i*M + j.

When a two-dimensional array is walked row by row and the rows sit back to back in memory, the nesting is mere bookkeeping. The inner loop's counter, comparison and branch get set up again for every row, and on small cores without much branch prediction that shows. After flattening there's one induction variable, one condition and one long loop that is easier to unroll and vectorize.

The precondition is that N*M cannot overflow, which the compiler must either prove or check at run time, falling back to the original loops if the check fails. LLVM gained its LoopFlatten pass around 2020, with Arm's microcontroller cores as the main motivation. OpenMP's collapse clause does the same thing by hand, to get more iterations to spread across threads.

← Back to the lexicon