[flang-commits] [flang] [flang][fir] Convert `fir.do_loop` with the unordered attribute to `scf.parallel`. (PR #168510)

Tom Eccles via flang-commits flang-commits at lists.llvm.org
Thu Nov 20 02:31:23 PST 2025


https://github.com/tblah commented:

I would have thought that this would need some work to decide whether parallelising the loop is going to be profitable, but if it works for your use case that's fine by me (as this pass is not enabled by default).

Executing the loop body in parallel is a stronger requirement on the loop body than merely out of order. A loop executed sequentially but out of order still can't have race conditions and can use the same memory address for each variable for each loop iteration. A loop running in parallel may need thread private allocations of variables in order to produce correct results, even if there are no memory dependencies between each iteration. Plus side effects might not be safe to run in parallel. Two examples:
```
integer :: tmp
integer :: i
integer, dimension(32) :: results

! Flang does not currently add the unordered attribute but it would not be incorrect
! because executing this sequentially in any order will produce the same result.
! However, if this were executed in parallel, multiple threads could try to read/write to
! tmp at the same time.
do i = 1,32
  tmp = i * 3
  results(i) = tmp * (tmp + 1)
end do
```
```
subroutine printMsg
  print *,"hello"
end subroutine

subroutine printMsg100Times
  integer :: i
  ! Flang again would not currently add the unordered attribute but it would not be 
  ! incorrect to do so. The loop body is invariant between iterations so there is no
  ! observable difference from executing this loop out of order. However, the side effects
  ! of the loop body may not be safe to run concurrently. In this case, if the text output
  ! was flushed after each character, and multiple threads wrote characters at the same
  ! time, the output could be jumpbled e.g. "hehhehloolloo"
  do i=1,100
    call printMsg()
  end do
end subroutine 
```

I'm worried that adding a potentially unsound transformation like this (even if it works most of the time for the loops that flang would actually apply `unordered` to) could limit the usefulness of this pass.

One solution would be to continue to transform these loops to scf.for by default and add a pass option which enables this transformation to scf.parallel. You can set that option when you create your custom pipeline using this pass.

https://github.com/llvm/llvm-project/pull/168510


More information about the flang-commits mailing list