[llvm-dev] [RFC] Adding thread group semantics to LangRef (motivated by GPUs)

Nicolai Hähnle via llvm-dev llvm-dev at lists.llvm.org
Thu Dec 20 05:01:57 PST 2018

Hi Justin,

On 19.12.18 20:45, Justin Lebar wrote:
> Hi from one of the people who works/worked on the NVPTX backend.
>  > The key issue is that *the set of threads participating in the 
> exchange of data is implicitly defined by control flow*.
> I agree that this is the root of the problem.
> The way nvidia GPUs "solve" this is that in Volta and newer, it's up to 
> the user to track explicitly which set of threads participate in 
> warp-synchronous functions.  You cannot safely ballot().  Problem 
> "solved".  :)

Yeah. Though there are costs associated with this approach, no matter 
how you implement it exactly, which is something I'd like to avoid.

The costs come from handling the case where the user tracks the set of 
threads "incorrectly", i.e. the set of threads conflicts with what would 
be naturally implied by control flow. "Incorrectly" in quotation marks 
because one could imagine this happening on purpose. But the more common 
case is for the programmer to intend to match their set of threads to 
align with control flow, and then we shouldn't have to pay the 
additional cost.

Now, if part of a clean solution was to somehow represent the set of 
threads explicitly in LLVM IR as values, I wouldn't be fundamentally 
opposed to that. The important point is that doing so isn't sufficient, 
because you also want to express the tie-in back to control flow somehow.

> We already have the notion of "convergent" functions like syncthreads(), 
> to which we cannot add control-flow dependencies.  That is, it's legal 
> to hoist syncthreads out of an "if", but it's not legal to sink it into 
> an "if".  It's not clear to me why we can't have "anticonvergent" 
> (terrible name) functions which cannot have control-flow dependencies 
> removed from them?  ballot() would be both convergent and anticonvergent.
> Would that solve your problem?

Right, thanks for reminding me of this line of thought. I think that 
already came up in a failed (and in hindsight misguided) review of mine 
on Phabricator a long time ago that you participated on.

There's a mixture of reasons why I have given up on this kind of approach.

The first is that "control-flow dependencies" aren't a particularly 
standard concept for unstructured control flow graphs in the first 
place, so forcing CPU folks to think about it is a bit problematic. 
Related to this is that all the definition attempts I'm aware of suffer 
from spooky action at a distance. An example of what I mean:

   flag = true;
   if (cond) {
     flag = ...;
   if (flag) {

There's a natural jump threading here that you would want to do for a 
CPU. Is that jump threading legal for a GPU?

The jump threading *should* be legal if the ballot wasn't there -- after 
all, it's legal and desired on CPUs. However, the jump threading pass 
does not naturally look at the basic block that contains the ballot, so 
it cannot make that judgment without an unnatural compile-time impact. 
Hence "spooky action at a distance".

And there are definitely implementations for which the jump threading 
here is illegal (classic PDOM reconvergence, for one). FWIW, the AMDGPU 
backend would currently just undo the jump threading entirely if the 
program is as simple as this, although I'm not comfortable with how 
reliably that works in more complex control flow (e.g., if there are 
loop nests involved as well). Since correctness requires reconverging 
anyway, it's preferable that jump threading is not legal here as long as 
the ballot is present.

But then, if `cond` is uniform, the jump threading can be both legal and 
desirable -- this goes in the direction of what Sameer wrote in his email.

An `anticonvergent` is simply insufficient to cover all this, but 
explicitly placing strategic "reconverging points" (in the form of some 
intrinsic) can solve all these problems.

At a higher level, all of the `convergent` / `anticonvergent` approaches 
are ultimately cop-outs. There are reasons why they developed the way 
they did, but I think it's time to face the reality of what's happening, 
which is that there is communication / synchronization between threads. 
If we just modeled that honestly, a lot of the confusion should disappear.

>  > However, the basic block containing the ballot call in the natural 
> lowering to LLVM IR is not part of the loop at all. The information that 
> it was intended to be run as part of the loop is currently lost forever.
> Sounds like the natural lowering of this example is not respecting 
> anticonvergence and just needs to be made more unnatural?

Right, though two points:

1. The optional structured control flow elements in SPIR-V point a way 
towards annotating an otherwise natural lowering with intrinsics in a 
way that models the required semantics.

2. If some other way was used that involved an unnatural lowering, we 
must be careful to guarantee that control flow transforms are unable to 
transform it back to the natural lowering.

> I also think it's worthwhile to consider the reasons behind nvidia's 
> move away from functions like ballot() towards explicit tracking of 
> which threads are active. +Olivier Giroux 
> <mailto:ogiroux at gmail.com> told me a while ago that he was working on a 
> paper which showed that the old way of doing things is even more 
> fraught/broken/difficult-to-specify than I thought; I'm not sure if 
> anything ended up being published.

I'm curious about that, too.

I understand how the Volta architecture helps to avoid deadlocks with 
independent locking of threads, and it seems to me that co-operative 
groups mostly just fall out as a relatively easily implementable feature 
on top of that. IMHO they're mostly a move in the wrong direction 
though, at least from a programmer ergonomics point of view. They make 
it easier to shoot yourself in the foot for some of the typical use 
cases of cross-lane operations.

There are difficulties with specifying semantics of the implicit groups, 
sure, but I'm rather convinced they can be solved, so I'm curious to 
read some well-stated arguments stating the opposite :)


> On Wed, Dec 19, 2018 at 11:32 AM Nicolai Hähnle via llvm-dev 
> <llvm-dev at lists.llvm.org <mailto:llvm-dev at lists.llvm.org>> wrote:
>     Hi all,
>     LLVM needs a solution to the long-standing problem that the IR is
>     unable
>     to express certain semantics expected by high-level programming
>     languages that target GPUs.
>     Solving this issue is necessary both for upstream use of LLVM as a
>     compiler backend for GPUs and for correctly supporting LLVM IR <->
>     SPIR-V roundtrip translation. It may also be useful for compilers
>     targeting SPMD-on-CPU a la ispc -- after all, some GPU hardware really
>     just looks like a CPU with extra-wide SIMD.
>     After thinking and talking about the problem on and off for more than
>     two years now, I'm convinced that it can only be solved by adding
>     dedicated semantics to LLVM IR, which take the shape of:
>     - a new function (and call) attribute similar to `convergent`,
>     - explicitly adding language to the LangRef that talks about groups of
>     threads and their communication with each other via special functions,
>     - including how these groups of threads are impacted (split and merged)
>     by branches etc., and
>     - new target-independent intrinsic(s) which manipulate subgroups of
>     threads, mostly by marking locations in the program where threads
>     reconverge
>     Details to be determined, of course.
>     In this mail, I would mostly like to make initial contact with the
>     larger community. First, to explain the problem to CPU-centric folks
>     and
>     maybe help get over the initial shock. Second, to reach out to other
>     people thinking about GPUs: Has anybody else given this issue much
>     thought? How can we proceed to get this solved?
>     The Problem
>     ===========
>     Programming languages for GPUs have "cross-lane" or "subgroup"
>     operations which allow fine-grained exchange of data between threads
>     being executed together in a "wave" or "warp".
>     The poster-child is ballot, which takes a boolean argument and
>     returns a
>     bitmask of the value of the argument across the
>     "subgroup"/"wave"/"warp", but more complex operations exist as well
>     e.g.
>     for reducing a value across all active lanes of a wave or for computing
>     a prefix scan.
>     The key issue is that *the set of threads participating in the exchange
>     of data is implicitly defined by control flow*.
>     Two examples to demonstrate the resulting problem and the limitation of
>     the existing LLVM IR semantics. The first one:
>             bool value = ...;
>             if (condition) {
>               bitmask0 = ballot(value);
>               foo(bitmask0);
>             } else {
>               bitmask1 = ballot(value);
>               bar(bitmask1);
>             }
>     The semantics of high-level languages demand that `bitmask0` only
>     contains set bits for threads (lanes) for which `condition` is true,
>     and
>     analogously for `bitmask1`. However, there is no reasonable way in LLVM
>     IR to prevent the ballot call from being hoisted above the
>     if-statement,
>     which changes the behavior.
>     (Existing frontends for the AMDGPU target currently implement a gross
>     hack where `value` is passed through a call to a unique chunk of no-op
>     inline assembly that is marked as having unspecified side effects...)
>     The second example:
>             uint64_t bitmask;
>             for (;;) {
>               ...
>               if (...) {
>                 bool value = ...;
>                 bitmask = ballot(value);
>                 break;
>               }
>               ...
>             }
>     The semantics of high-level languages expect that `bitmask` only
>     contains set bits for threads (lanes) which break from the loop in the
>     same iteration. However, the basic block containing the ballot call in
>     the natural lowering to LLVM IR is not part of the loop at all. The
>     information that it was intended to be run as part of the loop is
>     currently lost forever.
>     The Design Space of Solutions
>     =============================
>     The relevant high-level languages are structured programming languages,
>     where the behavior of subgroups falls out quite naturally. Needless to
>     say, we cannot rely on structured control flow in LLVM IR.
>     HSAIL defines subgroups as forking at branches and joining at the
>     immediate post-dominator. It also attempts to define restrictions on
>     program transformations in terms of immediate dominators and
>     post-dominators. I am not certain that this definition is sound in all
>     cases, and it is too restrictive in places.
>     Its main disadvantage is that describing restrictions on
>     transformations
>     purely in terms of dominators and post-dominators causes non-local
>     effects. For example, jump threading can change the
>     dominator/post-dominator tree, but verifying whether the corresponding
>     transform is legal in the face of subgroup operations requires
>     inspecting distant parts of the code that jump threading would not have
>     to look at for a CPU target.
>     So I reject HSAIL-like approaches based on the fact that they would
>     require invasive changes in generic middle-end passes.
>     There is a type of approach that most people who come into contact with
>     this problem eventually at least think about, which suggests replacing
>     the implicit dependence on control flow by an explicit one. That is,
>     augment subgroup intrinsics with an additional argument that represents
>     the subgroup of threads which participate in the exchange of data
>     described by this intrinsic, which results in code that looks
>     similar to
>     the co-operative groups in new versions of Cuda.
>     This kind of approach can be a valid solution to the problem of
>     preserving the correct semantics, although it imposes annoying
>     restrictions on function call ABIs.
>     The major problem with this kind of approach is that it does not
>     actually restrict the transforms made by middle-end passes, and so the
>     final IR before code generation might end up containing code patterns
>     that cannot be natively expressed on a target that implements SPMD with
>     lock-step execution. The burden on the backend to reliably catch and
>     implement the rare cases when this happens is excessive. Even for
>     targets without lock-step execution, these transforms may have unwanted
>     performance impacts. So I reject this type of proposal as well.
>     The literature from practicioners on SPMD/SIMT control flow (a lot
>     of it
>     targeting a hardware audience rather than a compiler audience) does not
>     concern itself with this problem to my knowledge, but there is a
>     commonly recurring theme of reconverging or rejoining threads at
>     explicit instructions and/or post-dominators.
>     This suggests a viable path towards a solution to me.
>     The SPIR-V spec has a notion of explicitly structured control flow with
>     merge basic blocks. It also defines "dynamic instances" of instructions
>     that are distinguished by control flow path, which provides a decent
>     option for modeling the set of threads which participate in subgroup
>     operations.
>     The SPIR-V spec itself is IMO quite lacking, in that the formalism is
>     very incomplete, the concrete structured control flow constructs are
>     very complex, and the details of how they are expressed lead to the
>     same
>     non-local effects you get with the HSAIL approach. Nevertheless, I
>     think
>     there's another viable path towards a solution hidden there.
>     Finally and for completeness, it should be noted that if we were to
>     forbid irreducible control flow in LLVM IR entirely, that would open up
>     more freedom in the design since we could properly define some
>     things in
>     terms of loop structure.
>     Final Thoughts
>     ==============
>     Formalizing these semantics could also help put divergence analysis
>     on a
>     more solid foundation.
>     Mostly I'm interested in general feedback at this point. Is there an
>     important part of the design space that I missed? What do people think
>     about explicitly talking about thread groups and e.g. dynamic instances
>     as in SPIR-V as part of the LLVM LangRef? Are people generally happy
>     with the notion? If not, how can we get to a place where people are
>     happy with it?
>     Thanks,
>     Nicolai
>     -- 
>     Lerne, wie die Welt wirklich ist,
>     Aber vergiss niemals, wie sie sein sollte.
>     _______________________________________________
>     LLVM Developers mailing list
>     llvm-dev at lists.llvm.org <mailto:llvm-dev at lists.llvm.org>
>     http://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev

Lerne, wie die Welt wirklich ist,
Aber vergiss niemals, wie sie sein sollte.

More information about the llvm-dev mailing list