llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

`vpdpwssd` instruction not generated despite giving better performance than `vpmaddwd+vpaddd` expansion

Open bjacob opened this issue 2 years ago • 31 comments

Filing this Issue with two Compiler Explorer testcases - one in LLVM IR and the other in C.

LLVM IR testcase

Compiler Explorer link: https://godbolt.org/z/3Wf1cfEo1

Problem: when the parent function has "target-cpu"="znver4", the @llvm.x86.avx512.vpdpwssd.512 intrinsic fails to compile to the expected AVX-512-VNNI vpdpwssd instruction and instead generates a (vpmaddwd, vpaddd) fallback implementation.

The problem only reproduces with "target-cpu"="znver4" and not with "target-cpu"="cascadelake" or when "target-cpu" is simply omitted, as shown in the Compiler Explorer link.

Inlining the LLVM IR testcase here for completeness:

; Testing with "target-cpu"="znver4" in attributes #0 below. Nothing else changes between testcases.

define dso_local <8 x i64> @foo(<8 x i64> noundef %0, <8 x i64> noundef %1, <8 x i64> noundef %2) local_unnamed_addr #0 {
  %4 = bitcast <8 x i64> %0 to <16 x i32>
  %5 = bitcast <8 x i64> %1 to <16 x i32>
  %6 = bitcast <8 x i64> %2 to <16 x i32>
  %7 = tail call <16 x i32> @llvm.x86.avx512.vpdpwssd.512(<16 x i32> %4, <16 x i32> %5, <16 x i32> %6)
  %8 = bitcast <16 x i32> %7 to <8 x i64>
  ret <8 x i64> %8
}

declare <16 x i32> @llvm.x86.avx512.vpdpwssd.512(<16 x i32>, <16 x i32>, <16 x i32>) #1

declare void @llvm.dbg.value(metadata, metadata, metadata) #2

attributes #0 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) uwtable "min-legal-vector-width"="512" "no-trapping-math"="true" "stack-protector-buffer-size"="8"
  "target-cpu"="znver4" "target-features"="+adx,+aes,+avx,+avx2,+avx512bf16,+avx512bitalg,+avx512bw,+avx512cd,+avx512dq,+avx512f,+avx512ifma,+avx512vbmi,+avx512vbmi2,+avx512vl,+avx512vnni,+avx512vpopcntdq,+bmi,+bmi2,+clflushopt,+clwb,+clzero,+crc32,+cx16,+cx8,+evex512,+f16c,+fma,+fsgsbase,+fxsr,+gfni,+invpcid,+lzcnt,+mmx,+movbe,+mwaitx,+pclmul,+pku,+popcnt,+prfchw,+rdpid,+rdpru,+rdrnd,+rdseed,+sahf,+sha,+shstk,+sse,+sse2,+sse3,+sse4.1,+sse4.2,+sse4a,+ssse3,+vaes,+vpclmulqdq,+wbnoinvd,+x87,+xsave,+xsavec,+xsaveopt,+xsaves" }
attributes #1 = { mustprogress nocallback nofree nosync nounwind willreturn memory(none) }
attributes #2 = { nocallback nofree nosync nounwind speculatable willreturn memory(none) }

C testcase

Compiler Explorer link: https://godbolt.org/z/z6xxf35hG

Problem: when compiling with -march=znver4, the _mm512_dpwssd_epi32 intrinsic fails to compile to the expected AVX-512-VNNI vpdpwssd instruction and instead generates a (vpmaddwd, vpaddd) fallback implementation.

The problem only reproduces with -march=znver4 and not with -march=cascade or when -march is simply omitted and individual AVX-512 features are passed instead, as shown in the Compiler Explorer link.

Inlining the C testcase here for completeness:

#include <immintrin.h>

__m512i foo(__m512i x, __m512i y, __m512i z) {
    return _mm512_dpwssd_epi32(x, y, z);
}

bjacob avatar Mar 06 '24 14:03 bjacob

@llvm/issue-subscribers-backend-x86

Author: Benoit Jacob (bjacob)

Filing this Issue with two Compiler Explorer testcases - one in LLVM IR and the other in C.

LLVM IR testcase

Compiler Explorer link: https://godbolt.org/z/3Wf1cfEo1

Problem: when the parent function has "target-cpu"="znver4", the @<!-- -->llvm.x86.avx512.vpdpwssd.512 intrinsic fails to compile to the expected AVX-512-VNNI vpdpwssd instruction and instead generates a (vpmaddwd, vpaddd) fallback implementation.

The problem only reproduces with "target-cpu"="znver4" and not with "target-cpu"="cascadelake" or when "target-cpu" is simply omitted, as shown in the Compiler Explorer link.

Inlining the LLVM IR testcase here for completeness:

; Testing with "target-cpu"="znver4" in attributes #<!-- -->0 below. Nothing else changes between testcases.

define dso_local &lt;8 x i64&gt; @<!-- -->foo(&lt;8 x i64&gt; noundef %0, &lt;8 x i64&gt; noundef %1, &lt;8 x i64&gt; noundef %2) local_unnamed_addr #<!-- -->0 {
  %4 = bitcast &lt;8 x i64&gt; %0 to &lt;16 x i32&gt;
  %5 = bitcast &lt;8 x i64&gt; %1 to &lt;16 x i32&gt;
  %6 = bitcast &lt;8 x i64&gt; %2 to &lt;16 x i32&gt;
  %7 = tail call &lt;16 x i32&gt; @<!-- -->llvm.x86.avx512.vpdpwssd.512(&lt;16 x i32&gt; %4, &lt;16 x i32&gt; %5, &lt;16 x i32&gt; %6)
  %8 = bitcast &lt;16 x i32&gt; %7 to &lt;8 x i64&gt;
  ret &lt;8 x i64&gt; %8
}

declare &lt;16 x i32&gt; @<!-- -->llvm.x86.avx512.vpdpwssd.512(&lt;16 x i32&gt;, &lt;16 x i32&gt;, &lt;16 x i32&gt;) #<!-- -->1

declare void @<!-- -->llvm.dbg.value(metadata, metadata, metadata) #<!-- -->2

attributes #<!-- -->0 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) uwtable "min-legal-vector-width"="512" "no-trapping-math"="true" "stack-protector-buffer-size"="8"
  "target-cpu"="znver4" "target-features"="+adx,+aes,+avx,+avx2,+avx512bf16,+avx512bitalg,+avx512bw,+avx512cd,+avx512dq,+avx512f,+avx512ifma,+avx512vbmi,+avx512vbmi2,+avx512vl,+avx512vnni,+avx512vpopcntdq,+bmi,+bmi2,+clflushopt,+clwb,+clzero,+crc32,+cx16,+cx8,+evex512,+f16c,+fma,+fsgsbase,+fxsr,+gfni,+invpcid,+lzcnt,+mmx,+movbe,+mwaitx,+pclmul,+pku,+popcnt,+prfchw,+rdpid,+rdpru,+rdrnd,+rdseed,+sahf,+sha,+shstk,+sse,+sse2,+sse3,+sse4.1,+sse4.2,+sse4a,+ssse3,+vaes,+vpclmulqdq,+wbnoinvd,+x87,+xsave,+xsavec,+xsaveopt,+xsaves" }
attributes #<!-- -->1 = { mustprogress nocallback nofree nosync nounwind willreturn memory(none) }
attributes #<!-- -->2 = { nocallback nofree nosync nounwind speculatable willreturn memory(none) }

C testcase

Compiler Explorer link: https://godbolt.org/z/z6xxf35hG

Problem: when compiling with -march=znver4, the _mm512_dpwssd_epi32 intrinsic fails to compile to the expected AVX-512-VNNI vpdpwssd instruction and instead generates a (vpmaddwd, vpaddd) fallback implementation.

The problem only reproduces with -march=znver4 and not with -march=cascade or when -march is simply omitted and individual AVX-512 features are passed instead, as shown in the Compiler Explorer link.

Inlining the C testcase here for completeness:

#include &lt;immintrin.h&gt;

__m512i foo(__m512i x, __m512i y, __m512i z) {
    return _mm512_dpwssd_epi32(x, y, z);
}

llvmbot avatar Mar 06 '24 14:03 llvmbot

The problem is avoided by adding the "tune-cpu"="generic" attribute in the LLVM IR testcase, or equivalently passing -mtune=generic in the C testcase.

This points to an issue with the scheduling model for znver4 ?

bjacob avatar Mar 06 '24 15:03 bjacob

This comes from practical matrix multiplication kernels and benchmarks show when the fallback from vpdpwssd to (vpmaddwd, vpaddd) occurs, this results in the matrix multiplication kernel running about 1.45x slower on my Zen4-architecture CPU (AMD Ryzen 9 7950X3D).

Single-thread i16xi16->i32 matrix multiplication performance on this Zen4 CPU:

Matrix multiplication kernel Gop/s
Without -mtune=znver4 336
With -mtune=znver4 231

The C source code for this kernel is here for completeness: https://github.com/openxla/iree/blob/f34e534a16f9cfe328f0a513ef474fd44af29a30/runtime/src/iree/builtins/ukernel/arch/x86_64/mmt4d_x86_64_avx512_vnni.c#L138-L171

bjacob avatar Mar 06 '24 15:03 bjacob

This is also a regression that occurred between LLVM 16 (good) and LLVM 17 (bad).

bjacob avatar Mar 06 '24 15:03 bjacob

This is due to the MachineCombinerPattern::DPWSSD expansion sequence which is scheduler model driven - so we need to confirm the state of the vnni instructions in the znver4 scheduler model

RKSimon avatar Mar 06 '24 15:03 RKSimon

If I understand correctly, this is the part of the scheduler model that affects VPDPWSSD? https://github.com/llvm/llvm-project/blob/f448b8ec03bbd0e1b47d56f461b324fb2af8c113/llvm/lib/Target/X86/X86ScheduleZnver4.td#L1568-L1577

bjacob avatar Mar 06 '24 15:03 bjacob

Naive question: the measure of cost that is the most important to practical code using this kind of arithmetic instruction, tends to be throughput rather than latency. I'm confused how is throughput taken into account here? EDIT - I see, Zn4FPFMisc01 describes the pipeline.

bjacob avatar Mar 06 '24 15:03 bjacob

Yes - looking at uops.info it suggests that the entire override block is unnecessary (so it'd use the default WriteVecIMul* classes) - which uops.info + Agner ALSO says should be FPU0/1 not FPU0/3 (which was the znver3 port mapping).

RKSimon avatar Mar 06 '24 15:03 RKSimon

Completed bisection, points to https://github.com/llvm/llvm-project/commit/8f7f9d86a7555263ef08fded15a6b778d796ec3f / https://reviews.llvm.org/D148980.

@RKSimon WDYT, is this commit merely exposing the above-discussed scheduling model issue?

(HEAD) ~/iree/third_party/llvm-project git bisect good
8f7f9d86a7555263ef08fded15a6b778d796ec3f is the first bad commit
commit 8f7f9d86a7555263ef08fded15a6b778d796ec3f
Author: Luo, Yuanke <[email protected]>
Date:   Fri Apr 21 19:28:58 2023 +0800

    [X86] Machine combine vnni instruction.
    
    "vpmaddwd + vpaddd" can be combined to vpdpwssd and the latency is
    reduced after combination. However when vpdpwssd is in a critical path
    the combination get less ILP. It happens when vpdpwssd is in a loop, the
    vpmaddwd can be executed in parallel in multi-iterations while vpdpwssd
    has data dependency for each iterations. If vpaddd is in a critical path
    while vpmaddwd is not, it is profitable to split vpdpwssd into "vpmaddwd
    + vpaddd".
    This patch is based on the machine combiner framework to acheive decision
    on "vpmaddwd + vpaddd" combination. The typical example code is as
    below.
    ```
    __m256i foo(int cnt, __m256i c, __m256i b, __m256i *p) {
    
        for (int i = 0; i < cnt; ++i) {
            __m256i a = p[i];
            __m256i m = _mm256_madd_epi16 (b, a);
            c = _mm256_add_epi32(m, c);
        }
    
        return c;
    }
    ```
    
    Differential Revision: https://reviews.llvm.org/D148980

 llvm/include/llvm/CodeGen/MachineCombinerPattern.h |   3 +
 llvm/include/llvm/CodeGen/TargetInstrInfo.h        |   7 +
 llvm/lib/CodeGen/MachineCombiner.cpp               |  34 +-
 llvm/lib/Target/X86/X86InstrInfo.cpp               | 137 +++++
 llvm/lib/Target/X86/X86InstrInfo.h                 |  28 +
 llvm/test/CodeGen/X86/avx512vnni-combine.ll        |  31 +-
 llvm/test/CodeGen/X86/avxvnni-combine.ll           | 589 ++++++++++++++-------
 7 files changed, 618 insertions(+), 211 deletions(-)

bjacob avatar Mar 06 '24 16:03 bjacob

yes - that patch is fine, its just a lot of accuracy issues with the znver4 model

RKSimon avatar Mar 06 '24 16:03 RKSimon

Yes - looking at uops.info it suggests that the entire override block is unnecessary (so it'd use the default WriteVecIMul* classes) - which uops.info + Agner ALSO says should be FPU0/1 not FPU0/3 (which was the znver3 port mapping).

Thanks a ton for these pointers -- I'll try that. Next naive question (sorry): it seems tempting to try to systematically import the tables from uops.info or Agner into LLVM x86 scheduling models. But surely this has been tried before? Do you know of past attempts or reasons why that's not a good idea ? Either way I'll look into the specific fix you suggested here but I was curious about how one generalizes from there.

bjacob avatar Mar 06 '24 16:03 bjacob

The problem is none of the sources are 100% correct / complete so scraping isn't a great idea - auto comparison with the uops.info xml is possible though, I played with converting it to llvm-exegesis capture data a while ago as llvm-exegesis analysis mode can then validate against the scheduler model, but I think I gave up when I hit the the instruction mapping @boomanaiden154 might have some ideas?

RKSimon avatar Mar 06 '24 16:03 RKSimon

Removing the override block does fix my issue here, vpdpwssd gets generated. However, it also causes some existing tests to fail (tools/llvm-mca/X86/Znver4/resources-avxvnni.s and a few others in that directory). That is because falling back on WriteVecIMul causes the latency to change from 4 to 3. According to uops.info, the current scheduling table is correct about the latencies: vpmaddwd has 3 and the instructions in the override block have 4 (vpdpwssd, vmpadd52huq).

If I keep the override block but just change Zn4FPFMisc01 to Zn4FPVMul01 then that doesn't fix my issue.

So, to summarize:

  • It really is true that vpmaddwd has lower latency than vpdpwssd (3 vs 4). However, vpdpwssd is a replacement for the vpmaddwd + vpaddd pair.
  • We need the override block at least to document the precise latencies for consumers who care about that (such as llvm-mca).
  • Latency isn't necessarily the metric to decide instruction selection.
  • How do we convey that vpdpwssd is preferable to the vpmaddwd + vpaddd pair despite having higher latency than vpmaddwd? Is the current instruction selection logic simply omitting the cost of the 2nd vpaddd instruction here ? If there wasn't that second instruction, then vpmaddwd would indeed be preferable.

bjacob avatar Mar 06 '24 18:03 bjacob

Here is what llc -debug says while performing the rewrite of vpdpwssd to vpmaddwd + vpaddd:

Machine InstCombiner: vpdpwssd_test
Combining MBB 
Computing MinInstr trace through %bb.0
  pred for %bb.0: null
  succ for %bb.0: null

Depths for %bb.0:
      0 Instructions
0       %2:vr512 = COPY $zmm2
0       %1:vr512 = COPY $zmm1
0       %0:vr512 = COPY $zmm0
0       %3:vr512 = VPDPWSSDZr %0:vr512(tied-def 0), %1:vr512, %2:vr512
4       $zmm0 = COPY %3:vr512
4       RET 0, $zmm0
Heights for %bb.0:
      2 Instructions
     1c @ Zn4AGU012 (1 ops x12)
     1c @ Zn4BRU01 (1 ops x18)
     1c @ Zn4FP (4 ops x6)
     2c @ Zn4FPAES01 (4 ops x18)
     2c @ Zn4FPCLM01 (4 ops x18)
     2c @ Zn4FPFMisc01 (4 ops x18)
     1c @ Zn4FPFMisc0123 (4 ops x9)
     2c @ Zn4FPFMul01 (4 ops x18)
     1c @ Zn4FPU0123 (4 ops x9)
     2c @ Zn4FPVAdd01 (4 ops x18)
     1c @ Zn4FPVAdd0123 (4 ops x9)
     1c @ Zn4FPVMisc0123 (4 ops x9)
     1c @ Zn4Int (2 ops x4)
     1c @ Zn4LSU (1 ops x12)
     1c @ Zn4Load (1 ops x12)
4       0       RET 0, $zmm0
4       0       $zmm0 = COPY %3:vr512
4       4       %3:vr512 = VPDPWSSDZr %0:vr512(tied-def 0), %1:vr512, %2:vr512
4       4       %0:vr512 = COPY $zmm0
4       4       %1:vr512 = COPY $zmm1
4       4       %2:vr512 = COPY $zmm2
%bb.0 Live-ins: XMM0@4 XMM1@4 XMM2@4
Critical path: 4
  Dependence data for %3:vr512 = VPDPWSSDZr %0:vr512(tied-def 0), %1:vr512, %2:vr512
        NewRootDepth: 3 RootDepth: 0
        NewRootLatency: 1       RootLatency: 4
        RootSlack: 0 SlackIsAccurate=1
        NewRootDepth + NewRootLatency = 4
        RootDepth + RootLatency + RootSlack = 4
          It IMPROVES PathLen because
                NewCycleCount = 4, OldCycleCount = 4
                Resource length before replacement: 4 and after: 2
                  As result it IMPROVES/PRESERVES Resource Length
Invalidate %bb.0 MinInstr height.
Invalidate %bb.0 MinInstr depth.
********** X86 cmov Conversion : vpdpwssd_test**********

bjacob avatar Mar 06 '24 19:03 bjacob

The logic as stated in that log seems to be ignoring the dependency between the producer vpmaddwd and the consumer vpaddd. Indeed, its stated rationale for the rewrite is It IMPROVES PathLen because ... Resource length before replacement: 4 and after: 2 ... As result it IMPROVES/PRESERVES Resource Length.

I found this comment explaining the concept of resource length: https://github.com/llvm/llvm-project/blob/04bbbba271ebe4c2421f34a4fbf34c328df9f111/llvm/include/llvm/CodeGen/MachineTraceMetrics.h#L287-L298

So resource length is not modelling the dependency in the vpmaddwd + vpaddd chain.

Secondarily, leaving that aside, I don't understand where the value 2 comes from, since vpmaddwd alone has latency 3. The value 2 is the max latency of the vpaddd. Is it counting only that?

My test:

; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mcpu=znver4 | FileCheck %s

define <16 x i32> @vpdpwssd_test(<16 x i32> %0, <16 x i32> %1, <16 x i32> %2) {
; CHECK-LABEL: vpdpwssd_test:
; CHECK:       # %bb.0:
; CHECK-NEXT:    vpdpwssd %zmm2, %zmm1, %zmm0
; CHECK-NEXT:    retq
  %4 = tail call <16 x i32> @llvm.x86.avx512.vpdpwssd.512(<16 x i32> %0, <16 x i32> %1, <16 x i32> %2)
  ret <16 x i32> %4
}

declare <16 x i32> @llvm.x86.avx512.vpdpwssd.512(<16 x i32>, <16 x i32>, <16 x i32>) #1

attributes #1 = { mustprogress nocallback nofree nosync nounwind willreturn memory(none) }

bjacob avatar Mar 06 '24 19:03 bjacob

I would like to discuss the commit identified above by git bisect: https://github.com/llvm/llvm-project/commit/8f7f9d86a7555263ef08fded15a6b778d796ec3f

  1. It is concerned with the dependency in the case back-to-back accumulation on the same accumulator in a loop. But my above testcase has no loop and only a single intrinsic, so this can't, in itself, justify a change to how it's compiled.
  2. The loop given as example in the commit message of https://github.com/llvm/llvm-project/commit/8f7f9d86a7555263ef08fded15a6b778d796ec3f has a data dependency that seems artificially exacerbated by using only a single accumulator register, which puts emphasis on instruction latency. But in real optimized numerical code, one would generally tile/unroll the caller's loops to compute multiple more results in parallel; e.g. with 8x unrolling the loop body would now have 8 mutually-independent vpdpwssd instructions on separate accumulators, so even at a throughput of 2 per cycle, the 4-cycle latency would not be felt anymore. The general idea here is that in numerical computation, emphasis on instruction latency is generally a smell that the focus is on an artificial/suboptimal test case.
  3. I wonder if there is some CPU-specific assumption baked in the logic here, outside of the scheduling model. Specifically, CPUs often have short-circuit special cases for back-to-back multiply-add instructions on the same accumulator, bypassing the register file. As a result, as a detail of each CPU, the cost of an accumulator dependency can be lower than it would appear from a general scheduling model that doesn't account for that (and I don't see where the current scheduling model accounts for that, so perhaps that's what's missing?).

bjacob avatar Mar 06 '24 20:03 bjacob

Sent https://github.com/llvm/llvm-project/pull/84347 for review.

bjacob avatar Mar 07 '24 17:03 bjacob

CC @LuoYuanke @phoebewang This was reported on znver4 but I'm not convinced its working properly on any VNNI AVX512 target where VPDPWSSD is (always?) better than VPMADDWD+VPADDD?

RKSimon avatar Mar 07 '24 17:03 RKSimon

If I recall correctly the report that added the machine combiner change was related to the compiler combining vpmaddwd+vpadd into vpdwssd. If the user used the vpdwssd intrinsic directly should we trust them and never break it?

topperc avatar Mar 07 '24 18:03 topperc

cc @williamweixiao. @LuoYuanke is not working on X86 now.

I'm not convinced its working properly on any VNNI AVX512 target where VPDPWSSD is (always?) better than VPMADDWD+VPADDD?

According to D148980's description, it solves the data dependency of following VPDPWSSD instructions. And the test cases in the patch also demonstrated it (The fisrt VPDPWSSD is not split).

Given the single vpdpwssd always been split on znver4. I'm guessing znver4's scheduler model may indicate VPMADDWD+VPADDD always better than VPDPWSSD?

This comes from practical matrix multiplication kernels and benchmarks show when the fallback from vpdpwssd to (vpmaddwd, vpaddd) occurs, this results in the matrix multiplication kernel running about 1.45x slower on my Zen4-architecture CPU (AMD Ryzen 9 7950X3D).

We once noticed a similar issue. Our analysis showed it's caused by the following machine instructions scheduling instead of spliting here. Maybe the same reason here?

phoebewang avatar Mar 08 '24 02:03 phoebewang