Skip to contentSkip to conversation

Introduce helper-to-tcg

RFC PATCH In review Anton Johansson via 7 participants 81 messages Nov 21, 2024 – Dec 5, 2024 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

cover Introduce helper-to-tcg

Hi all, this patchset introduces helper-to-tcg, a LLVM based build-time C to TCG translator, as a QEMU subproject. The purpose of this tool is to simplify implementation of instructions in TCG by automatically translating helper functions for a given target to TCG. It may also be used as a standalone tool for getting a base TCG implementation for complicated instructions.

See KVM forum 2023 presentation: https://www.youtube.com/watch?v=Gwz0kp7IZPE

helper-to-tcg is also applied to the Hexagon frontend, managing to translate 1270 instructions, 160 of which are HVX instructions. For the time being, idef-parser remains translating 289 instructions consisting mostly of complicated load instructions. This count will be reduced over time until idef-parser can be deprecated.

As an example, consider the following helper function implementation of a Hexagon instruction for performing a 2-element scalar product, using signed saturated arithmetic

  void HELPER(V6_vdmpyhvsat)(CPUHexagonState *env,
                             void * restrict VdV_void,
                             void * restrict VuV_void,
                             void * restrict VvV_void)
  {
      fVFOREACH(32, i) {
          size8s_t accum = fMPY16SS(fGETHALF(0,VuV.w[i]),fGETHALF(0, VvV.w[i]));
          accum += fMPY16SS(fGETHALF(1,VuV.w[i]),fGETHALF(1, VvV.w[i]));
          VdV.w[i] = fVSATW(accum);
      }
  }

which at the end of the helper-to-tcg pipeline will have been converted to the following LLVM IR

  define void @helper_V6_vdmpyhvsat(%struct.CPUArchState* %0,
                                    i8* %1, i8* %2, i8* %3) {
      %4 = bitcast i8* %2 to <32 x i32>*
      %wide.load = load <32 x i32>, <32 x i32>* %4
      %5 = call <32 x i32> @VecShlScalar(<32 x i32> %wide.load, i32 16)
      %6 = call <32 x i32> @VecAShrScalar(<32 x i32> %5, i32 16)
      %7 = bitcast i8* %3 to <32 x i32>*
      %wide.load23 = load <32 x i32>, <32 x i32>* %7
      %8 = call <32 x i32> @VecShlScalar(<32 x i32> %wide.load23, i32 16)
      %9 = call <32 x i32> @VecAShrScalar(<32 x i32> %8, i32 16)
      %10 = mul nsw <32 x i32> %9, %6
      %11 = call <32 x i32> @VecAShrScalar(<32 x i32> %wide.load, i32 16)
      %12 = call <32 x i32> @VecAShrScalar(<32 x i32> %wide.load23, i32 16)
      %13 = mul nsw <32 x i32> %12, %11
      %14 = bitcast i8* %1 to <32 x i32>*
      ret void
  }

which, in TCG, gets emitted as

  void emit_V6_vdmpyhvsat(TCGv_env env, intptr_t vec3,
                          intptr_t vec7, intptr_t vec6) {
      VectorMem mem = {0};
      intptr_t vec0 = temp_new_gvec(&mem, 128);
      tcg_gen_gvec_shli(MO_32, vec0, vec7, 16, 128, 128);
      intptr_t vec5 = temp_new_gvec(&mem, 128);
      tcg_gen_gvec_sari(MO_32, vec5, vec0, 16, 128, 128);
      intptr_t vec1 = temp_new_gvec(&mem, 128);
      tcg_gen_gvec_shli(MO_32, vec1, vec6, 16, 128, 128);
      tcg_gen_gvec_sari(MO_32, vec1, vec1, 16, 128, 128);
      tcg_gen_gvec_mul(MO_32, vec1, vec1, vec5, 128, 128);
      intptr_t vec2 = temp_new_gvec(&mem, 128);
      tcg_gen_gvec_sari(MO_32, vec2, vec7, 16, 128, 128);
      tcg_gen_gvec_sari(MO_32, vec0, vec6, 16, 128, 128);
      tcg_gen_gvec_mul(MO_32, vec2, vec0, vec2, 128, 128);
      tcg_gen_gvec_ssadd(MO_32, vec3, vec1, vec2, 128, 128);
  }

consisting of a few vectorized shifts, multiplications, and a signed saturated add.

For a more in-depth usage guide see subprojects/helper-to-tcg/README.md.

Limitations:
* Currently LLVM versions 10-14 are supported, with support for 15+ being in the works.

* Exceeding TB size, for complicated vector instructions with a large amount of gvec instrucions, the TB size of 128 longs can sometimes be exceeded. Particularly on Hexagon with instruction packets.

* Does not handle functions with multiple return values. On Hexagon, a large set of instructions still translated by idef-parser fall into this category.

Patchset overview:
1. helper-to-tcg (patches 9-31) - Introduces the actual translator as a QEMU subproject.

2. Fills gaps in TCG instructions (patches 2,3,4) - Since the tool is LLVM based it allows for translation of vector instructions to gvec instructions in Tinycode. This requires the introduction of a few new tcg_gen_gvec_*() functions for dealing with sign- and zero-extension, along with a function for initializing a vector to a constant, and functions for bitreversal and funnel shift.

3. Automatic calling of generated code (patch 5) - To simplify integration into existing frontends gen_helper_*() calls for non-vector instructions can automatically be hooked to call emitted code for translated helper functions. This works by allowing targets to define a "helper_dispatcher" function that gets called from tcg_gen_callN(), and can override helper function calls. helper-to-tcg can emit such a dispatcher which calls generated code.

4. Mapping of cpu state (patch 6) - helper-to-tcg needs information about the offsets of fields in the cpu state that correspond to TCG globals, so these can be emitted in the output code. For this purpose, a target may define an array of struct cpu_tcg_mapping to map fields in the cpu state to TCG globals in a declarative way. This global array can be parsed by helper-to-tcg, and replaces manually calling tcg_global_mem_new*() in frontend.

5. Increases max size of generated TB code (patch 7) - Due to the power of the LLVM auto-vectorizer, helper-to-tcg can emit quite complicated vectorized gvec code. Particularly for Hexagon where a single instruction packet can consist of multiple vector instructions. A single instruction packet can in rare cases exceed the TB buffer size of 128 longs.

6. Applies helper-to-tcg to Hexagon (patches 34-43) - helper-to-tcg is used on the Hexagon frontend to translate a majority of helper functions in place of idef-parser. For the time being idef-parser will remain in use to translate instructions with multiple return values that are not representable as helper functions and therefore translatable with helper-to-tcg.

Anton Johansson (43):
Add option to enable/disable helper-to-tcg
accel/tcg: Add bitreverse and funnel-shift runtime helper functions accel/tcg: Add gvec size changing operations
tcg: Add gvec functions for creating consant vectors
tcg: Add helper function dispatcher and hook tcg_gen_callN
tcg: Introduce tcg-global-mappings
tcg: Increase maximum TB size and maximum temporaries include/helper-to-tcg: Introduce annotate.h
helper-to-tcg: Introduce get-llvm-ir.py
helper-to-tcg: Add meson.build
helper-to-tcg: Introduce llvm-compat
helper-to-tcg: Introduce custom LLVM pipeline
helper-to-tcg: Introduce Error.h
helper-to-tcg: Introduce PrepareForOptPass
helper-to-tcg: PrepareForOptPass, map annotations
helper-to-tcg: PrepareForOptPass, Cull unused functions
helper-to-tcg: PrepareForOptPass, undef llvm.returnaddress
helper-to-tcg: PrepareForOptPass, Remove noinline attribute
helper-to-tcg: Pipeline, run optimization pass
helper-to-tcg: Introduce pseudo instructions
helper-to-tcg: Introduce PrepareForTcgPass
helper-to-tcg: PrepareForTcgPass, remove functions w. cycles
helper-to-tcg: PrepareForTcgPass, demote phi nodes
helper-to-tcg: PrepareForTcgPass, map TCG globals
helper-to-tcg: PrepareForTcgPass, transform GEPs
helper-to-tcg: PrepareForTcgPass, canonicalize IR
helper-to-tcg: PrepareForTcgPass, identity map trivial expressions
helper-to-tcg: Introduce TcgType.h
helper-to-tcg: Introduce TCG register allocation
helper-to-tcg: TcgGenPass, introduce TcgEmit.[cpp|h]
helper-to-tcg: Introduce TcgGenPass
helper-to-tcg: Add README
helper-to-tcg: Add end-to-end tests
target/hexagon: Add get_tb_mmu_index()
target/hexagon: Use argparse in all python scripts target/hexagon: Add temporary vector storage target/hexagon: Make HVX vector args. restrict * target/hexagon: Use cpu_mapping to map env -> TCG target/hexagon: Keep gen_slotval/check_noshuf for helper-to-tcg target/hexagon: Emit annotations for helpers target/hexagon: Manually call generated HVX instructions target/hexagon: Only translate w. idef-parser if helper-to-tcg failed target/hexagon: Use helper-to-tcg

 accel/tcg/tcg-runtime-gvec.c                  |   41 +
 accel/tcg/tcg-runtime.c                       |   29 +
 accel/tcg/tcg-runtime.h                       |   27 +
 accel/tcg/translate-all.c                     |    4 +
 include/helper-to-tcg/annotate.h              |   28 +
 include/tcg/tcg-global-mappings.h             |  111 +
 include/tcg/tcg-op-gvec-common.h              |   20 +
 include/tcg/tcg.h                             |    8 +-
 meson.build                                   |    7 +
 meson_options.txt                             |    2 +
 scripts/meson-buildoptions.sh                 |    5 +
 subprojects/helper-to-tcg/README.md           |  265 +++
 subprojects/helper-to-tcg/get-llvm-ir.py      |  143 ++
 .../helper-to-tcg/include/CmdLineOptions.h    |   38 +
 subprojects/helper-to-tcg/include/Error.h     |   40 +
 .../include/FunctionAnnotation.h              |   54 +
 .../helper-to-tcg/include/PrepareForOptPass.h |   42 +
 .../helper-to-tcg/include/PrepareForTcgPass.h |   32 +
 .../helper-to-tcg/include/TcgGlobalMap.h      |   31 +
 subprojects/helper-to-tcg/meson.build         |   84 +
 subprojects/helper-to-tcg/meson_options.txt   |    2 +
 .../PrepareForOptPass/PrepareForOptPass.cpp   |  260 +++
 .../PrepareForTcgPass/CanonicalizeIR.cpp      | 1000 +++++++++
 .../passes/PrepareForTcgPass/CanonicalizeIR.h |   25 +
 .../passes/PrepareForTcgPass/IdentityMap.cpp  |   80 +
 .../passes/PrepareForTcgPass/IdentityMap.h    |   39 +
 .../PrepareForTcgPass/PrepareForTcgPass.cpp   |  134 ++
 .../PrepareForTcgPass/TransformGEPs.cpp       |  286 +++
 .../passes/PrepareForTcgPass/TransformGEPs.h  |   37 +
 .../helper-to-tcg/passes/PseudoInst.cpp       |  142 ++
 subprojects/helper-to-tcg/passes/PseudoInst.h |   63 +
 .../helper-to-tcg/passes/PseudoInst.inc       |   76 +
 .../helper-to-tcg/passes/backend/TcgEmit.cpp  | 1074 ++++++++++
 .../helper-to-tcg/passes/backend/TcgEmit.h    |  290 +++
 .../passes/backend/TcgGenPass.cpp             | 1812 +++++++++++++++++
 .../helper-to-tcg/passes/backend/TcgGenPass.h |   57 +
 .../passes/backend/TcgTempAllocationPass.cpp  |  594 ++++++
 .../passes/backend/TcgTempAllocationPass.h    |   79 +
 .../helper-to-tcg/passes/backend/TcgType.h    |  133 ++
 .../helper-to-tcg/passes/llvm-compat.cpp      |  162 ++
 .../helper-to-tcg/passes/llvm-compat.h        |  143 ++
 .../helper-to-tcg/pipeline/Pipeline.cpp       |  297 +++
 subprojects/helper-to-tcg/tests/cpustate.c    |   45 +
 subprojects/helper-to-tcg/tests/ldst.c        |   17 +
 subprojects/helper-to-tcg/tests/meson.build   |   24 +
 subprojects/helper-to-tcg/tests/scalar.c      |   15 +
 .../helper-to-tcg/tests/tcg-global-mappings.h |  115 ++
 subprojects/helper-to-tcg/tests/vector.c      |   26 +
 target/hexagon/cpu.h                          |   16 +
 target/hexagon/gen_analyze_funcs.py           |    6 +-
 target/hexagon/gen_decodetree.py              |   19 +-
 target/hexagon/gen_helper_funcs.py            |   24 +-
 target/hexagon/gen_helper_protos.py           |    9 +-
 target/hexagon/gen_idef_parser_funcs.py       |   17 +-
 target/hexagon/gen_op_attribs.py              |   11 +-
 target/hexagon/gen_opcodes_def.py             |   11 +-
 target/hexagon/gen_printinsn.py               |   11 +-
 target/hexagon/gen_tcg_func_table.py          |   11 +-
 target/hexagon/gen_tcg_funcs.py               |   24 +-
 target/hexagon/gen_trans_funcs.py             |   17 +-
 target/hexagon/genptr.c                       |    2 +-
 target/hexagon/hex_common.py                  |  138 +-
 target/hexagon/meson.build                    |  151 +-
 target/hexagon/mmvec/macros.h                 |   36 +-
 target/hexagon/op_helper.c                    |    3 +-
 target/hexagon/translate.c                    |  116 +-
 tcg/meson.build                               |    1 +
 tcg/tcg-global-mappings.c                     |   61 +
 tcg/tcg-op-gvec.c                             |  108 +
 tcg/tcg.c                                     |    5 +
 70 files changed, 8662 insertions(+), 173 deletions(-)
 create mode 100644 include/helper-to-tcg/annotate.h
 create mode 100644 include/tcg/tcg-global-mappings.h
 create mode 100644 subprojects/helper-to-tcg/README.md
 create mode 100755 subprojects/helper-to-tcg/get-llvm-ir.py
 create mode 100644 subprojects/helper-to-tcg/include/CmdLineOptions.h
 create mode 100644 subprojects/helper-to-tcg/include/Error.h
 create mode 100644 subprojects/helper-to-tcg/include/FunctionAnnotation.h
 create mode 100644 subprojects/helper-to-tcg/include/PrepareForOptPass.h
 create mode 100644 subprojects/helper-to-tcg/include/PrepareForTcgPass.h
 create mode 100644 subprojects/helper-to-tcg/include/TcgGlobalMap.h
 create mode 100644 subprojects/helper-to-tcg/meson.build
 create mode 100644 subprojects/helper-to-tcg/meson_options.txt
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.h
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.h
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.h
 create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.h
 create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.inc
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgEmit.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgEmit.h
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgGenPass.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgGenPass.h
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.h
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgType.h
 create mode 100644 subprojects/helper-to-tcg/passes/llvm-compat.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/llvm-compat.h
 create mode 100644 subprojects/helper-to-tcg/pipeline/Pipeline.cpp
 create mode 100644 subprojects/helper-to-tcg/tests/cpustate.c
 create mode 100644 subprojects/helper-to-tcg/tests/ldst.c
 create mode 100644 subprojects/helper-to-tcg/tests/meson.build
 create mode 100644 subprojects/helper-to-tcg/tests/scalar.c
 create mode 100644 subprojects/helper-to-tcg/tests/tcg-global-mappings.h
 create mode 100644 subprojects/helper-to-tcg/tests/vector.c
 create mode 100644 tcg/tcg-global-mappings.c
Signature · 1 line
2.45.2
#1 lore raw

RFC PATCH 1/43 Add option to enable/disable helper-to-tcg

Adds a meson option for enabling/disabling helper-to-tcg along with a CONFIG_* definition.

CONFIG_* will in future commits be used to conditionally include the helper-to-tcg subproject, and to remove unneeded code/memory when helper-to-tcg is not in use.

Current meson option is limited to Hexagon, as helper-to-tcg will be included as a subproject from target/hexagon. This will change in the future if multiple frontends adopt helper-to-tcg.

---
 meson.build                   | 7 +++++++
 meson_options.txt             | 2 ++
 scripts/meson-buildoptions.sh | 5 +++++
 3 files changed, 14 insertions(+)
meson.build +7 -0
index e0b880e4e1..657ebe43f6 100644
@@ -230,6 +230,7 @@ have_ga = get_option('guest_agent') \
            error_message: 'unsupported OS for QEMU guest agent') \
   .allowed()
 have_block = have_system or have_tools
+helper_to_tcg_enabled = get_option('hexagon_helper_to_tcg')
 
 enable_modules = get_option('modules') \
   .require(host_os != 'windows',
@@ -3245,6 +3246,11 @@ foreach target : target_dirs
       'CONFIG_QEMU_RTSIG_MAP': get_option('rtsig_map'),
     }
   endif
+  if helper_to_tcg_enabled
+    config_target += {
+      'CONFIG_HELPER_TO_TCG': 'y',
+    }
+  endif
 
   target_kconfig = []
   foreach sym: accelerators
@@ -4122,6 +4128,7 @@ foreach target : target_dirs
   if host_os == 'linux'
     target_inc += include_directories('linux-headers', is_system: true)
   endif
+
   if target.endswith('-softmmu')
     target_type='system'
     t = target_system_arch[target_base_arch].apply(config_target, strict: false)
meson_options.txt +2 -0
index 5eeaf3eee5..0730378305 100644
@@ -374,6 +374,8 @@ option('qemu_ga_version', type: 'string', value: '',
 
 option('hexagon_idef_parser', type : 'boolean', value : true,
        description: 'use idef-parser to automatically generate TCG code for the Hexagon frontend')
+option('hexagon_helper_to_tcg', type : 'boolean', value : true,
+       description: 'use the helper-to-tcg translator to automatically generate TCG code for the Hexagon frontend')
 
 option('x86_version', type : 'combo', choices : ['0', '1', '2', '3', '4'], value: '1',
        description: 'tweak required x86_64 architecture version beyond compiler default')
scripts/meson-buildoptions.sh +5 -0
index a8066aab03..19c891a39b 100644
@@ -13,6 +13,9 @@ meson_options_help() {
   printf "%s\n" '  --datadir=VALUE          Data file directory [share]'
   printf "%s\n" '  --disable-coroutine-pool coroutine freelist (better performance)'
   printf "%s\n" '  --disable-debug-info     Enable debug symbols and other information'
+  printf "%s\n" '  --disable-hexagon-helper-to-tcg'
+  printf "%s\n" '                           use the helper-to-tcg translator to automatically'
+  printf "%s\n" '                           generate TCG code for the Hexagon frontend'
   printf "%s\n" '  --disable-hexagon-idef-parser'
   printf "%s\n" '                           use idef-parser to automatically generate TCG'
   printf "%s\n" '                           code for the Hexagon frontend'
@@ -341,6 +344,8 @@ _meson_option_parse() {
     --disable-guest-agent) printf "%s" -Dguest_agent=disabled ;;
     --enable-guest-agent-msi) printf "%s" -Dguest_agent_msi=enabled ;;
     --disable-guest-agent-msi) printf "%s" -Dguest_agent_msi=disabled ;;
+    --enable-hexagon-helper-to-tcg) printf "%s" -Dhexagon_helper_to_tcg=true ;;
+    --disable-hexagon-helper-to-tcg) printf "%s" -Dhexagon_helper_to_tcg=false ;;
     --enable-hexagon-idef-parser) printf "%s" -Dhexagon_idef_parser=true ;;
     --disable-hexagon-idef-parser) printf "%s" -Dhexagon_idef_parser=false ;;
     --enable-hv-balloon) printf "%s" -Dhv_balloon=enabled ;;
Signature · 1 line
2.45.2
Acked-by on v1 1/43
#2 lore raw

Re: [RFC PATCH v1 01/43] Add option to enable/disable helper-to-tcg

Quoted 11 lines · Anton Johansson

Adds a meson option for enabling/disabling helper-to-tcg along with a CONFIG_* definition.

CONFIG_* will in future commits be used to conditionally include the helper-to-tcg subproject, and to remove unneeded code/memory when helper-to-tcg is not in use.

Current meson option is limited to Hexagon, as helper-to-tcg will be included as a subproject from target/hexagon. This will change in the future if multiple frontends adopt helper-to-tcg.

Quoted 6 lines
---
  meson.build                   | 7 +++++++
  meson_options.txt             | 2 ++
  scripts/meson-buildoptions.sh | 5 +++++
  3 files changed, 14 insertions(+)

Looks ok. Could probably stand another set of meson eyes.

r~

Quoted 69 lines
meson.build +7 -0
index e0b880e4e1..657ebe43f6 100644
@@ -230,6 +230,7 @@ have_ga = get_option('guest_agent') \
             error_message: 'unsupported OS for QEMU guest agent') \
    .allowed()
  have_block = have_system or have_tools
+helper_to_tcg_enabled = get_option('hexagon_helper_to_tcg')
 
  enable_modules = get_option('modules') \
    .require(host_os != 'windows',
@@ -3245,6 +3246,11 @@ foreach target : target_dirs
        'CONFIG_QEMU_RTSIG_MAP': get_option('rtsig_map'),
      }
    endif
+  if helper_to_tcg_enabled
+    config_target += {
+      'CONFIG_HELPER_TO_TCG': 'y',
+    }
+  endif
 
    target_kconfig = []
    foreach sym: accelerators
@@ -4122,6 +4128,7 @@ foreach target : target_dirs
    if host_os == 'linux'
      target_inc += include_directories('linux-headers', is_system: true)
    endif
+
    if target.endswith('-softmmu')
      target_type='system'
      t = target_system_arch[target_base_arch].apply(config_target, strict: false)
meson_options.txt +2 -0
index 5eeaf3eee5..0730378305 100644
@@ -374,6 +374,8 @@ option('qemu_ga_version', type: 'string', value: '',
 
  option('hexagon_idef_parser', type : 'boolean', value : true,
         description: 'use idef-parser to automatically generate TCG code for the Hexagon frontend')
+option('hexagon_helper_to_tcg', type : 'boolean', value : true,
+       description: 'use the helper-to-tcg translator to automatically generate TCG code for the Hexagon frontend')
 
  option('x86_version', type : 'combo', choices : ['0', '1', '2', '3', '4'], value: '1',
         description: 'tweak required x86_64 architecture version beyond compiler default')
scripts/meson-buildoptions.sh +5 -0
index a8066aab03..19c891a39b 100644
@@ -13,6 +13,9 @@ meson_options_help() {
    printf "%s\n" '  --datadir=VALUE          Data file directory [share]'
    printf "%s\n" '  --disable-coroutine-pool coroutine freelist (better performance)'
    printf "%s\n" '  --disable-debug-info     Enable debug symbols and other information'
+  printf "%s\n" '  --disable-hexagon-helper-to-tcg'
+  printf "%s\n" '                           use the helper-to-tcg translator to automatically'
+  printf "%s\n" '                           generate TCG code for the Hexagon frontend'
    printf "%s\n" '  --disable-hexagon-idef-parser'
    printf "%s\n" '                           use idef-parser to automatically generate TCG'
    printf "%s\n" '                           code for the Hexagon frontend'
@@ -341,6 +344,8 @@ _meson_option_parse() {
      --disable-guest-agent) printf "%s" -Dguest_agent=disabled ;;
      --enable-guest-agent-msi) printf "%s" -Dguest_agent_msi=enabled ;;
      --disable-guest-agent-msi) printf "%s" -Dguest_agent_msi=disabled ;;
+    --enable-hexagon-helper-to-tcg) printf "%s" -Dhexagon_helper_to_tcg=true ;;
+    --disable-hexagon-helper-to-tcg) printf "%s" -Dhexagon_helper_to_tcg=false ;;
      --enable-hexagon-idef-parser) printf "%s" -Dhexagon_idef_parser=true ;;
      --disable-hexagon-idef-parser) printf "%s" -Dhexagon_idef_parser=false ;;
      --enable-hv-balloon) printf "%s" -Dhv_balloon=enabled ;;
#3 lore raw

Re: [RFC PATCH v1 01/43] Add option to enable/disable helper-to-tcg

Quoted 19 lines · Richard Henderson
Quoted 11 lines · Anton Johansson

Adds a meson option for enabling/disabling helper-to-tcg along with a CONFIG_* definition.

CONFIG_* will in future commits be used to conditionally include the helper-to-tcg subproject, and to remove unneeded code/memory when helper-to-tcg is not in use.

Current meson option is limited to Hexagon, as helper-to-tcg will be included as a subproject from target/hexagon.  This will change in the future if multiple frontends adopt helper-to-tcg.

Quoted 6 lines

---
  meson.build                   | 7 +++++++
  meson_options.txt             | 2 ++
  scripts/meson-buildoptions.sh | 5 +++++

  3 files changed, 14 insertions(+)
Quoted 3 lines

Looks ok.  Could probably stand another set of meson eyes.

/me bows

Since the subproject has a pretty hefty (and specific) set of dependencies, please make this a "feature" option. This allows subprojects/helper-to-tcg to disable itself if it cannot find a dependency or otherwise invokes error(), without breaking the build. The --enable-hexagon-helper-to-tcg flag however *will* force the subproject to be buildable, just like all other QEMU feature options.

Something like this:

########################
# Target configuration #
########################

# a bit gross to hardcode hexagon, but acceptable given the name of the option
helper_to_tcg = subproject('helper-to-tcg', get_option('hexagon_helper_to_tcg') \
   .disable_auto_if('hexagon-linux-user' not in target_dirs))

and replace helper_to_tcg_enabled throughout with helper_to_tcg.found().

Quoted 5 lines
Quoted 5 lines

+  if helper_to_tcg_enabled
+    config_target += {
+      'CONFIG_HELPER_TO_TCG': 'y',
+    }
+  endif

Here I would add instead add CONFIG_HELPER_TO_TCG (maybe renamed to TARGET_HELPER_TO_TCG) in configs/targets/) and add before the loop:

ignored = [ 'TARGET_XML_FILES', 'TARGET_ABI_DIR', 'TARGET_ARCH' ] if not helper_to_tcg.found()

  # do not define it if it is not usable
  ignored += ['TARGET_HELPER_TO_TCG']
endif

Paolo

#4 lore raw

Re: [RFC PATCH v1 01/43] Add option to enable/disable helper-to-tcg

Quoted 57 lines · Paolo Bonzini
Quoted 19 lines · Richard Henderson
Quoted 11 lines · Anton Johansson

Adds a meson option for enabling/disabling helper-to-tcg along with a CONFIG_* definition.

CONFIG_* will in future commits be used to conditionally include the helper-to-tcg subproject, and to remove unneeded code/memory when helper-to-tcg is not in use.

Current meson option is limited to Hexagon, as helper-to-tcg will be included as a subproject from target/hexagon.  This will change in the future if multiple frontends adopt helper-to-tcg.

Quoted 6 lines

---
  meson.build                   | 7 +++++++
  meson_options.txt             | 2 ++
  scripts/meson-buildoptions.sh | 5 +++++

  3 files changed, 14 insertions(+)
Quoted 3 lines

Looks ok.  Could probably stand another set of meson eyes.

/me bows

Since the subproject has a pretty hefty (and specific) set of dependencies, please make this a "feature" option. This allows subprojects/helper-to-tcg to disable itself if it cannot find a dependency or otherwise invokes error(), without breaking the build. The --enable-hexagon-helper-to-tcg flag however *will* force the subproject to be buildable, just like all other QEMU feature options.

Something like this:

########################
# Target configuration #
########################

# a bit gross to hardcode hexagon, but acceptable given the name of the option
helper_to_tcg = subproject('helper-to-tcg', get_option('hexagon_helper_to_tcg') \
   .disable_auto_if('hexagon-linux-user' not in target_dirs))

and replace helper_to_tcg_enabled throughout with helper_to_tcg.found().

Quoted 5 lines
Quoted 5 lines

+  if helper_to_tcg_enabled
+    config_target += {
+      'CONFIG_HELPER_TO_TCG': 'y',
+    }
+  endif

Here I would add instead add CONFIG_HELPER_TO_TCG (maybe renamed to TARGET_HELPER_TO_TCG) in configs/targets/) and add before the loop:

Quoted 8 lines

ignored = [ 'TARGET_XML_FILES', 'TARGET_ABI_DIR', 'TARGET_ARCH' ] if not helper_to_tcg.found()

  # do not define it if it is not usable
  ignored += ['TARGET_HELPER_TO_TCG']
endif

Paolo

Makes sense, appreciate it!:) There's always something new to learn about meson

//Anton

#5 lore raw

RFC PATCH 2/43 accel/tcg: Add bitreverse and funnel-shift runtime helper functions

In reply to Anton Johansson via

Adds necessary helper functions for mapping LLVM IR onto TCG. Specifically, helpers corresponding to the bitreverse and funnel-shift intrinsics in LLVM.

Note: these may be converted to more efficient implementations in the future, but for the time being it allows helper-to-tcg to support a wider subset of LLVM IR.

---
 accel/tcg/tcg-runtime.c | 29 +++++++++++++++++++++++++++++
 accel/tcg/tcg-runtime.h |  5 +++++
 2 files changed, 34 insertions(+)
accel/tcg/tcg-runtime.c +29 -0
index 9fa539ad3d..6372fa3f6f 100644
@@ -23,6 +23,8 @@
  */
 #include "qemu/osdep.h"
 #include "qemu/host-utils.h"
+#include "qemu/int128.h"
+#include "qemu/bitops.h"
 #include "cpu.h"
 #include "exec/helper-proto-common.h"
 #include "exec/cpu_ldst.h"
@@ -57,6 +59,21 @@ uint32_t HELPER(remu_i32)(uint32_t arg1, uint32_t arg2)
     return arg1 % arg2;
 }
 
+uint32_t HELPER(bitreverse8_i32)(uint32_t x)
+{
+  return revbit8((uint8_t) x);
+}
+
+uint32_t HELPER(bitreverse16_i32)(uint32_t x)
+{
+  return revbit16((uint16_t) x);
+}
+
+uint32_t HELPER(bitreverse32_i32)(uint32_t x)
+{
+  return revbit32(x);
+}
+
 /* 64-bit helpers */
 
 uint64_t HELPER(shl_i64)(uint64_t arg1, uint64_t arg2)
@@ -74,6 +91,13 @@ int64_t HELPER(sar_i64)(int64_t arg1, int64_t arg2)
     return arg1 >> arg2;
 }
 
+uint64_t HELPER(fshl_i64)(uint64_t a, uint64_t b, uint64_t c)
+{
+    Int128 d = int128_make128(b, a);
+    Int128 shift = int128_lshift(d, c);
+    return int128_gethi(shift);
+}
+
 int64_t HELPER(div_i64)(int64_t arg1, int64_t arg2)
 {
     return arg1 / arg2;
@@ -94,6 +118,11 @@ uint64_t HELPER(remu_i64)(uint64_t arg1, uint64_t arg2)
     return arg1 % arg2;
 }
 
+uint64_t HELPER(bitreverse64_i64)(uint64_t x)
+{
+    return revbit64(x);
+}
+
 uint64_t HELPER(muluh_i64)(uint64_t arg1, uint64_t arg2)
 {
     uint64_t l, h;
accel/tcg/tcg-runtime.h +5 -0
index c23b5e66c4..0a4d31eb48 100644
@@ -2,15 +2,20 @@ DEF_HELPER_FLAGS_2(div_i32, TCG_CALL_NO_RWG_SE, s32, s32, s32)
 DEF_HELPER_FLAGS_2(rem_i32, TCG_CALL_NO_RWG_SE, s32, s32, s32)
 DEF_HELPER_FLAGS_2(divu_i32, TCG_CALL_NO_RWG_SE, i32, i32, i32)
 DEF_HELPER_FLAGS_2(remu_i32, TCG_CALL_NO_RWG_SE, i32, i32, i32)
+DEF_HELPER_FLAGS_1(bitreverse8_i32,  TCG_CALL_NO_RWG_SE, i32, i32)
+DEF_HELPER_FLAGS_1(bitreverse16_i32, TCG_CALL_NO_RWG_SE, i32, i32)
+DEF_HELPER_FLAGS_1(bitreverse32_i32, TCG_CALL_NO_RWG_SE, i32, i32)
 
 DEF_HELPER_FLAGS_2(div_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64)
 DEF_HELPER_FLAGS_2(rem_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64)
 DEF_HELPER_FLAGS_2(divu_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
 DEF_HELPER_FLAGS_2(remu_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
+DEF_HELPER_FLAGS_1(bitreverse64_i64, TCG_CALL_NO_RWG_SE, i64, i64)
 
 DEF_HELPER_FLAGS_2(shl_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
 DEF_HELPER_FLAGS_2(shr_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
 DEF_HELPER_FLAGS_2(sar_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64)
+DEF_HELPER_FLAGS_3(fshl_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64, i64)
 
 DEF_HELPER_FLAGS_2(mulsh_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64)
 DEF_HELPER_FLAGS_2(muluh_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64)
Signature · 1 line
2.45.2
#6 lore raw

Re: [RFC PATCH v1 02/43] accel/tcg: Add bitreverse and funnel-shift runtime helper functions

Quoted 8 lines · Anton Johansson

Adds necessary helper functions for mapping LLVM IR onto TCG. Specifically, helpers corresponding to the bitreverse and funnel-shift intrinsics in LLVM.

Note: these may be converted to more efficient implementations in the future, but for the time being it allows helper-to-tcg to support a wider subset of LLVM IR.

Quoted 5 lines
---
  accel/tcg/tcg-runtime.c | 29 +++++++++++++++++++++++++++++
  accel/tcg/tcg-runtime.h |  5 +++++
  2 files changed, 34 insertions(+)

For things in tcg-runtime.c, we generally have wrapper functions in include/tcg/tcg-op-common.h which hide the fact that the operation is being expanded by a helper.

We would also have tcg_gen_bitreverse{8,16,32}_i64, and *_tl macros in include/tcg/tcg-op.h.

I've been meaning to add something like these for a while, because they are common to quite a few targets.

accel/tcg/tcg-runtime.c uint32_t HELPER(remu_i32)(uint32_t arg1, uint32_t arg2) · line 65

Quoted 4 lines
accel/tcg/tcg-runtime.c +4 -0
+uint32_t HELPER(bitreverse8_i32)(uint32_t x)
+{
+  return revbit8((uint8_t) x);
+}

Also common is bit-reversing every byte in the word, not just the lowest.
Worth implementing both? Or simply zero-extending the input/output when the target only requires the lowest byte?

We might want to audit the other targets to determine which forms are used...

r~

#7 lore raw

Re: [RFC PATCH v1 02/43] accel/tcg: Add bitreverse and funnel-shift runtime helper functions

Quoted 33 lines · Richard Henderson
Quoted 8 lines · Anton Johansson

Adds necessary helper functions for mapping LLVM IR onto TCG. Specifically, helpers corresponding to the bitreverse and funnel-shift intrinsics in LLVM.

Note: these may be converted to more efficient implementations in the future, but for the time being it allows helper-to-tcg to support a wider subset of LLVM IR.

Quoted 5 lines
---
  accel/tcg/tcg-runtime.c | 29 +++++++++++++++++++++++++++++
  accel/tcg/tcg-runtime.h |  5 +++++
  2 files changed, 34 insertions(+)

For things in tcg-runtime.c, we generally have wrapper functions in include/tcg/tcg-op-common.h which hide the fact that the operation is being expanded by a helper.

We would also have tcg_gen_bitreverse{8,16,32}_i64, and *_tl macros in include/tcg/tcg-op.h.

I've been meaning to add something like these for a while, because they are common to quite a few targets.

accel/tcg/tcg-runtime.c uint32_t HELPER(remu_i32)(uint32_t arg1, uint32_t arg2) · line 65

Quoted 4 lines
accel/tcg/tcg-runtime.c +4 -0
+uint32_t HELPER(bitreverse8_i32)(uint32_t x)
+{
+  return revbit8((uint8_t) x);
+}

Also common is bit-reversing every byte in the word, not just the lowest. Worth implementing both? Or simply zero-extending the input/output when the target only requires the lowest byte?

Quoted 1 line

We might want to audit the other targets to determine which forms are used...

I'll take a stab at auditing usage of revbit*() in targets, and add appropriate tcg_gen_bitreverse*() versions. I guess it makes sense to split this out into a small separate patchset in that case.

//Anton

#8 lore raw

RFC PATCH 3/43 accel/tcg: Add gvec size changing operations

In reply to Anton Johansson via

Adds new functions to the gvec API for truncating, sign- or zero extending vector elements. Currently implemented as helper functions, these may be mapped onto host vector instructions in the future.

For the time being, allows translation of more complicated vector instructions by helper-to-tcg.

---
 accel/tcg/tcg-runtime-gvec.c     | 41 +++++++++++++++++
 accel/tcg/tcg-runtime.h          | 22 +++++++++
 include/tcg/tcg-op-gvec-common.h | 18 ++++++++
 tcg/tcg-op-gvec.c                | 78 ++++++++++++++++++++++++++++++++
 4 files changed, 159 insertions(+)
accel/tcg/tcg-runtime-gvec.c +41 -0
index afca89baa1..685c991e6a 100644
@@ -1569,3 +1569,44 @@ void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc)
     }
     clear_high(d, oprsz, desc);
 }
+
+#define DO_SZ_OP1(NAME, DSTTY, SRCTY)                                      \
+void HELPER(NAME)(void *d, void *a, uint32_t desc)                         \
+{                                                                          \
+    intptr_t oprsz = simd_oprsz(desc);                                     \
+    intptr_t elsz = oprsz/sizeof(DSTTY);                                   \
+    intptr_t i;                                                            \
+                                                                           \
+    for (i = 0; i < elsz; ++i) {                                           \
+        SRCTY aa = *((SRCTY *) a + i);                                     \
+        *((DSTTY *) d + i) = aa;                                           \
+    }                                                                      \
+    clear_high(d, oprsz, desc);                                            \
+}
+
+#define DO_SZ_OP2(NAME, INTTY, DSTSZ, SRCSZ) \
+    DO_SZ_OP1(NAME##SRCSZ##_##DSTSZ, INTTY##DSTSZ##_t, INTTY##SRCSZ##_t)
+
+DO_SZ_OP2(gvec_trunc, uint, 32, 64)
+DO_SZ_OP2(gvec_trunc, uint, 16, 64)
+DO_SZ_OP2(gvec_trunc, uint, 8,  64)
+DO_SZ_OP2(gvec_trunc, uint, 16, 32)
+DO_SZ_OP2(gvec_trunc, uint, 8,  32)
+DO_SZ_OP2(gvec_trunc, uint, 8,  16)
+
+DO_SZ_OP2(gvec_zext, uint, 64, 32)
+DO_SZ_OP2(gvec_zext, uint, 64, 16)
+DO_SZ_OP2(gvec_zext, uint, 64, 8)
+DO_SZ_OP2(gvec_zext, uint, 32, 16)
+DO_SZ_OP2(gvec_zext, uint, 32, 8)
+DO_SZ_OP2(gvec_zext, uint, 16, 8)
+
+DO_SZ_OP2(gvec_sext, int, 64, 32)
+DO_SZ_OP2(gvec_sext, int, 64, 16)
+DO_SZ_OP2(gvec_sext, int, 64, 8)
+DO_SZ_OP2(gvec_sext, int, 32, 16)
+DO_SZ_OP2(gvec_sext, int, 32, 8)
+DO_SZ_OP2(gvec_sext, int, 16, 8)
+
+#undef DO_SZ_OP1
+#undef DO_SZ_OP2
accel/tcg/tcg-runtime.h +22 -0
index 0a4d31eb48..5045655bf8 100644
@@ -1,3 +1,4 @@
+#include "tcg/tcg.h"
 DEF_HELPER_FLAGS_2(div_i32, TCG_CALL_NO_RWG_SE, s32, s32, s32)
 DEF_HELPER_FLAGS_2(rem_i32, TCG_CALL_NO_RWG_SE, s32, s32, s32)
 DEF_HELPER_FLAGS_2(divu_i32, TCG_CALL_NO_RWG_SE, i32, i32, i32)
@@ -328,3 +329,24 @@ DEF_HELPER_FLAGS_4(gvec_leus32, TCG_CALL_NO_RWG, void, ptr, ptr, i64, i32)
 DEF_HELPER_FLAGS_4(gvec_leus64, TCG_CALL_NO_RWG, void, ptr, ptr, i64, i32)
 
 DEF_HELPER_FLAGS_5(gvec_bitsel, TCG_CALL_NO_RWG, void, ptr, ptr, ptr, ptr, i32)
+
+DEF_HELPER_FLAGS_3(gvec_trunc64_32, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_trunc64_16, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_trunc64_8,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_trunc32_16, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_trunc32_8,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_trunc16_8,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+
+DEF_HELPER_FLAGS_3(gvec_zext32_64, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_zext16_64, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_zext8_64,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_zext16_32, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_zext8_32,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_zext8_16,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+
+DEF_HELPER_FLAGS_3(gvec_sext32_64, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_sext16_64, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_sext8_64,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_sext16_32, TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_sext8_32,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
+DEF_HELPER_FLAGS_3(gvec_sext8_16,  TCG_CALL_NO_RWG, void, ptr, ptr, i32)
include/tcg/tcg-op-gvec-common.h +18 -0
index 65553f5f97..39b0c2f64e 100644
@@ -390,6 +390,24 @@ void tcg_gen_gvec_bitsel(unsigned vece, uint32_t dofs, uint32_t aofs,
                          uint32_t bofs, uint32_t cofs,
                          uint32_t oprsz, uint32_t maxsz);
 
+/*
+ * Perform vector element truncation/extension operations
+ */
+
+void tcg_gen_gvec_trunc(unsigned vecde, unsigned vecse,
+                        uint32_t dofs, uint32_t aofs,
+                        uint32_t doprsz, uint32_t aoprsz,
+                        uint32_t maxsz);
+
+void tcg_gen_gvec_zext(unsigned vecde, unsigned vecse,
+                       uint32_t dofs, uint32_t aofs,
+                       uint32_t doprsz, uint32_t aoprsz,
+                       uint32_t maxsz);
+
+void tcg_gen_gvec_sext(unsigned vecde, unsigned vecse,
+                       uint32_t dofs, uint32_t aofs,
+                       uint32_t doprsz, uint32_t aoprsz,
+                       uint32_t maxsz);
 /*
  * 64-bit vector operations.  Use these when the register has been allocated
  * with tcg_global_mem_new_i64, and so we cannot also address it via pointer.
tcg/tcg-op-gvec.c +78 -0

81 lines not on this page · raw message

Signature · 1 line
2.45.2
#9 lore raw

Re: [RFC PATCH v1 03/43] accel/tcg: Add gvec size changing operations

Quoted 26 lines · Anton Johansson

Adds new functions to the gvec API for truncating, sign- or zero extending vector elements. Currently implemented as helper functions, these may be mapped onto host vector instructions in the future.

For the time being, allows translation of more complicated vector instructions by helper-to-tcg.

---
  accel/tcg/tcg-runtime-gvec.c     | 41 +++++++++++++++++
  accel/tcg/tcg-runtime.h          | 22 +++++++++
  include/tcg/tcg-op-gvec-common.h | 18 ++++++++
  tcg/tcg-op-gvec.c                | 78 ++++++++++++++++++++++++++++++++
  4 files changed, 159 insertions(+)
accel/tcg/tcg-runtime-gvec.c +3 -0
index afca89baa1..685c991e6a 100644
@@ -1569,3 +1569,44 @@ void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc)
      }
      clear_high(d, oprsz, desc);
  }
+
+#define DO_SZ_OP1(NAME, DSTTY, SRCTY)                                      \
+void HELPER(NAME)(void *d, void *a, uint32_t desc)                         \

accel/tcg/tcg-runtime-gvec.c void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc) · line 1584

Quoted 10 lines
accel/tcg/tcg-runtime-gvec.c +10 -0
+{                                                                          \
+    intptr_t oprsz = simd_oprsz(desc);                                     \
+    intptr_t elsz = oprsz/sizeof(DSTTY);                                   \
+    intptr_t i;                                                            \
+                                                                           \
+    for (i = 0; i < elsz; ++i) {                                           \
+        SRCTY aa = *((SRCTY *) a + i);                                     \
+        *((DSTTY *) d + i) = aa;                                           \
+    }                                                                      \
+    clear_high(d, oprsz, desc);                                            \

This formulation is not valid.

(1) Generic forms must *always* operate strictly on columns. This formulation is either expanding a narrow vector to a wider vector or compressing a wider vector to a narrow vector.

(2) This takes no care for byte ordering of the data between columns. This is where sticking strictly to columns helps, in that we can assume that data is host-endian *within the column*, but we cannot assume anything about the element indexing of ptr + i.

(3) This takes no care for element overlap if A == D.

The only form of sign/zero-extract that you may add generically is an alias for

d[i] = a[i] & mask

or

d[i] = (a[i] << shift) >> shift

where A and D use the same element type. We could add new tcg opcodes for these (particularly the second, for sign-extension), though x86_64 does not support it, afaics.

r~

#10 lore raw

Re: [RFC PATCH v1 03/43] accel/tcg: Add gvec size changing operations

Quoted 40 lines · Richard Henderson
Quoted 26 lines · Anton Johansson

Adds new functions to the gvec API for truncating, sign- or zero extending vector elements. Currently implemented as helper functions, these may be mapped onto host vector instructions in the future.

For the time being, allows translation of more complicated vector instructions by helper-to-tcg.

---
  accel/tcg/tcg-runtime-gvec.c     | 41 +++++++++++++++++
  accel/tcg/tcg-runtime.h          | 22 +++++++++
  include/tcg/tcg-op-gvec-common.h | 18 ++++++++
  tcg/tcg-op-gvec.c                | 78 ++++++++++++++++++++++++++++++++
  4 files changed, 159 insertions(+)
accel/tcg/tcg-runtime-gvec.c +3 -0
index afca89baa1..685c991e6a 100644
@@ -1569,3 +1569,44 @@ void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc)
      }
      clear_high(d, oprsz, desc);
  }
+
+#define DO_SZ_OP1(NAME, DSTTY, SRCTY)                                      \
+void HELPER(NAME)(void *d, void *a, uint32_t desc)                         \

accel/tcg/tcg-runtime-gvec.c void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc) · line 1584

Quoted 10 lines
accel/tcg/tcg-runtime-gvec.c +10 -0
+{                                                                          \
+    intptr_t oprsz = simd_oprsz(desc);                                     \
+    intptr_t elsz = oprsz/sizeof(DSTTY);                                   \
+    intptr_t i;                                                            \
+                                                                           \
+    for (i = 0; i < elsz; ++i) {                                           \
+        SRCTY aa = *((SRCTY *) a + i);                                     \
+        *((DSTTY *) d + i) = aa;                                           \
+    }                                                                      \
+    clear_high(d, oprsz, desc);                                            \

This formulation is not valid.

Quoted 8 lines

(1) Generic forms must *always* operate strictly on columns. This formulation is either expanding a narrow vector to a wider vector or compressing a wider vector to a narrow vector.

(2) This takes no care for byte ordering of the data between columns. This is where sticking strictly to columns helps, in that we can assume that data is host-endian *within the column*, but we cannot assume anything about the element indexing of ptr + i.

Concerning (1) and (2), is this a limitation imposed on generic vector ops. to simplify mapping to host vector instructions where padding/alignment of elements might differ? From my understanding, the helper above should be fine since we can assume contiguous elements?

But maybe it doesn't make sense to add a gvec op. that is only implemented via helper, I'm not sure.

Quoted 1 line

(3) This takes no care for element overlap if A == D.

Ah, good point!

Quoted 11 lines

The only form of sign/zero-extract that you may add generically is an alias for

d[i] = a[i] & mask

or

d[i] = (a[i] << shift) >> shift

where A and D use the same element type. We could add new tcg opcodes for these (particularly the second, for sign-extension), though x86_64 does not support it, afaics.

I see, I don't think we can make this work for Hexagon vector ops., as an example consider V6_vadduwsat which performs an unsigned saturated add of 32-bit elements, currently we emit

    void emit_V6_vadduwsat(intptr_t vec2, intptr_t vec7, intptr_t vec6) {
        VectorMem mem = {0};
        intptr_t vec5 = temp_new_gvec(&mem, 256);
        tcg_gen_gvec_zext(MO_64, MO_32, vec5, vec7, 256, 128, 256);

        intptr_t vec1 = temp_new_gvec(&mem, 256);
        tcg_gen_gvec_zext(MO_64, MO_32, vec1, vec6, 256, 128, 256);

        tcg_gen_gvec_add(MO_64, vec1, vec1, vec5, 256, 256);

        intptr_t vec3 = temp_new_gvec(&mem, 256);
        tcg_gen_gvec_dup_imm(MO_64, vec3, 256, 256, 4294967295ull);

        tcg_gen_gvec_umin(MO_64, vec1, vec1, vec3, 256, 256);

        tcg_gen_gvec_trunc(MO_32, MO_64, vec2, vec1, 128, 256, 128);
    }

so we really do rely on the size-changing property of zext here, the input vectors are 128-byte and we expand them to 256-byte. We could expand vector operations within the instruction to the largest vector size, but would need to zext and trunc to destination and source registers anyway.

//Anton

#11 lore raw

Re: [RFC PATCH v1 03/43] accel/tcg: Add gvec size changing operations

Quoted 50 lines · Anton Johansson
Quoted 40 lines · Richard Henderson
Quoted 26 lines · Anton Johansson

Adds new functions to the gvec API for truncating, sign- or zero extending vector elements. Currently implemented as helper functions, these may be mapped onto host vector instructions in the future.

For the time being, allows translation of more complicated vector instructions by helper-to-tcg.

---
   accel/tcg/tcg-runtime-gvec.c     | 41 +++++++++++++++++
   accel/tcg/tcg-runtime.h          | 22 +++++++++
   include/tcg/tcg-op-gvec-common.h | 18 ++++++++
   tcg/tcg-op-gvec.c                | 78 ++++++++++++++++++++++++++++++++
   4 files changed, 159 insertions(+)
accel/tcg/tcg-runtime-gvec.c +3 -0
index afca89baa1..685c991e6a 100644
@@ -1569,3 +1569,44 @@ void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc)
       }
       clear_high(d, oprsz, desc);
   }
+
+#define DO_SZ_OP1(NAME, DSTTY, SRCTY)                                      \
+void HELPER(NAME)(void *d, void *a, uint32_t desc)                         \

accel/tcg/tcg-runtime-gvec.c void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc) · line 1584

Quoted 10 lines
accel/tcg/tcg-runtime-gvec.c +10 -0
+{                                                                          \
+    intptr_t oprsz = simd_oprsz(desc);                                     \
+    intptr_t elsz = oprsz/sizeof(DSTTY);                                   \
+    intptr_t i;                                                            \
+                                                                           \
+    for (i = 0; i < elsz; ++i) {                                           \
+        SRCTY aa = *((SRCTY *) a + i);                                     \
+        *((DSTTY *) d + i) = aa;                                           \
+    }                                                                      \
+    clear_high(d, oprsz, desc);                                            \

This formulation is not valid.

Quoted 8 lines

(1) Generic forms must *always* operate strictly on columns. This formulation is either expanding a narrow vector to a wider vector or compressing a wider vector to a narrow vector.

(2) This takes no care for byte ordering of the data between columns. This is where sticking strictly to columns helps, in that we can assume that data is host-endian *within the column*, but we cannot assume anything about the element indexing of ptr + i.

Quoted 4 lines

Concerning (1) and (2), is this a limitation imposed on generic vector ops. to simplify mapping to host vector instructions where padding/alignment of elements might differ? From my understanding, the helper above should be fine since we can assume contiguous elements?

This is a limitation imposed on generic vector ops, because different target/arch/ represent their vectors in different ways.

For instance, Arm and RISC-V chunk the vector in to host-endian uint64_t, with the chunks indexed little-endian. But PPC puts the entire 128-bit vector in host-endian bit ordering, so the uint64_t chunks are host-endian.

On a big-endian host, ptr+1 may be addressing element i-1 or i-7 instead of i+1.

Quoted 22 lines

I see, I don't think we can make this work for Hexagon vector ops., as an example consider V6_vadduwsat which performs an unsigned saturated add of 32-bit elements, currently we emit

     void emit_V6_vadduwsat(intptr_t vec2, intptr_t vec7, intptr_t vec6) {
         VectorMem mem = {0};
         intptr_t vec5 = temp_new_gvec(&mem, 256);
         tcg_gen_gvec_zext(MO_64, MO_32, vec5, vec7, 256, 128, 256);

         intptr_t vec1 = temp_new_gvec(&mem, 256);
         tcg_gen_gvec_zext(MO_64, MO_32, vec1, vec6, 256, 128, 256);

         tcg_gen_gvec_add(MO_64, vec1, vec1, vec5, 256, 256);

         intptr_t vec3 = temp_new_gvec(&mem, 256);
         tcg_gen_gvec_dup_imm(MO_64, vec3, 256, 256, 4294967295ull);

         tcg_gen_gvec_umin(MO_64, vec1, vec1, vec3, 256, 256);

         tcg_gen_gvec_trunc(MO_32, MO_64, vec2, vec1, 128, 256, 128);
     }
Quoted 5 lines

so we really do rely on the size-changing property of zext here, the input vectors are 128-byte and we expand them to 256-byte. We could expand vector operations within the instruction to the largest vector size, but would need to zext and trunc to destination and source registers anyway.

Yes, well, this is the output of llvm though, yes?

Did you forget to describe TCG's native saturating operations to the compiler? tcg_gen_gvec_usadd performs exactly this operation.

And if you'd like to improve llvm, usadd(a, b) equals umin(a, ~b) + b. Fewer operations without having to change vector sizes.
Similarly for unsigned saturating subtract: ussub(a, b) equals umax(a, b) - b.

r~

#12 lore raw

Re: [RFC PATCH v1 03/43] accel/tcg: Add gvec size changing operations

Quoted 56 lines · Richard Henderson
Quoted 50 lines · Anton Johansson
Quoted 40 lines · Richard Henderson
Quoted 26 lines · Anton Johansson

Adds new functions to the gvec API for truncating, sign- or zero extending vector elements. Currently implemented as helper functions, these may be mapped onto host vector instructions in the future.

For the time being, allows translation of more complicated vector instructions by helper-to-tcg.

---
   accel/tcg/tcg-runtime-gvec.c     | 41 +++++++++++++++++
   accel/tcg/tcg-runtime.h          | 22 +++++++++
   include/tcg/tcg-op-gvec-common.h | 18 ++++++++
   tcg/tcg-op-gvec.c                | 78 ++++++++++++++++++++++++++++++++
   4 files changed, 159 insertions(+)
accel/tcg/tcg-runtime-gvec.c +3 -0
index afca89baa1..685c991e6a 100644
@@ -1569,3 +1569,44 @@ void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc)
       }
       clear_high(d, oprsz, desc);
   }
+
+#define DO_SZ_OP1(NAME, DSTTY, SRCTY)                                      \
+void HELPER(NAME)(void *d, void *a, uint32_t desc)                         \

accel/tcg/tcg-runtime-gvec.c void HELPER(gvec_bitsel)(void *d, void *a, void *b, void *c, uint32_t desc) · line 1584

Quoted 10 lines
accel/tcg/tcg-runtime-gvec.c +10 -0
+{                                                                          \
+    intptr_t oprsz = simd_oprsz(desc);                                     \
+    intptr_t elsz = oprsz/sizeof(DSTTY);                                   \
+    intptr_t i;                                                            \
+                                                                           \
+    for (i = 0; i < elsz; ++i) {                                           \
+        SRCTY aa = *((SRCTY *) a + i);                                     \
+        *((DSTTY *) d + i) = aa;                                           \
+    }                                                                      \
+    clear_high(d, oprsz, desc);                                            \

This formulation is not valid.

Quoted 8 lines

(1) Generic forms must *always* operate strictly on columns. This formulation is either expanding a narrow vector to a wider vector or compressing a wider vector to a narrow vector.

(2) This takes no care for byte ordering of the data between columns. This is where sticking strictly to columns helps, in that we can assume that data is host-endian *within the column*, but we cannot assume anything about the element indexing of ptr + i.

Quoted 4 lines

Concerning (1) and (2), is this a limitation imposed on generic vector ops. to simplify mapping to host vector instructions where padding/alignment of elements might differ? From my understanding, the helper above should be fine since we can assume contiguous elements?

Quoted 8 lines

This is a limitation imposed on generic vector ops, because different target/arch/ represent their vectors in different ways.

For instance, Arm and RISC-V chunk the vector in to host-endian uint64_t, with the chunks indexed little-endian. But PPC puts the entire 128-bit vector in host-endian bit ordering, so the uint64_t chunks are host-endian.

On a big-endian host, ptr+1 may be addressing element i-1 or i-7 instead of i+1.

Ah, I see the problem now thanks for the explanation:)

Quoted 22 lines
Quoted 22 lines

I see, I don't think we can make this work for Hexagon vector ops., as an example consider V6_vadduwsat which performs an unsigned saturated add of 32-bit elements, currently we emit

     void emit_V6_vadduwsat(intptr_t vec2, intptr_t vec7, intptr_t vec6) {
         VectorMem mem = {0};
         intptr_t vec5 = temp_new_gvec(&mem, 256);
         tcg_gen_gvec_zext(MO_64, MO_32, vec5, vec7, 256, 128, 256);

         intptr_t vec1 = temp_new_gvec(&mem, 256);
         tcg_gen_gvec_zext(MO_64, MO_32, vec1, vec6, 256, 128, 256);

         tcg_gen_gvec_add(MO_64, vec1, vec1, vec5, 256, 256);

         intptr_t vec3 = temp_new_gvec(&mem, 256);
         tcg_gen_gvec_dup_imm(MO_64, vec3, 256, 256, 4294967295ull);

         tcg_gen_gvec_umin(MO_64, vec1, vec1, vec3, 256, 256);

         tcg_gen_gvec_trunc(MO_32, MO_64, vec2, vec1, 128, 256, 128);
     }
Quoted 6 lines
Quoted 5 lines

so we really do rely on the size-changing property of zext here, the input vectors are 128-byte and we expand them to 256-byte. We could expand vector operations within the instruction to the largest vector size, but would need to zext and trunc to destination and source registers anyway.

Yes, well, this is the output of llvm though, yes?

Yes

Quoted 6 lines

Did you forget to describe TCG's native saturating operations to the compiler? tcg_gen_gvec_usadd performs exactly this operation.

And if you'd like to improve llvm, usadd(a, b) equals umin(a, ~b) + b. Fewer operations without having to change vector sizes.
Similarly for unsigned saturating subtract: ussub(a, b) equals umax(a, b) - b.

In this case LLVM wasn't able to optimize it to a llvm.uadd.sat intrinsic, in which case we would have emitted tcg_gen_gvec_usadd I believe. We can manually optimize the above pattern to a llvm.uadd.sat to avoid extra size changes.

This might be fixed in future LLVM versions, but otherwise seems like a reasonable change to push upstream.

The point is that we have a lot of Hexagon instructions where size changes are probably unavoidable, another example is V6_vshuffh which takes in a <16 x i16> vector and shuffles the upper <8xi16> into the upper 16-bits of a <8 x i32> vector

    void emit_V6_vshuffh(intptr_t vec3, intptr_t vec7) {
        VectorMem mem = {0};
        intptr_t vec2 = temp_new_gvec(&mem, 128);
        tcg_gen_gvec_zext(MO_32, MO_16, vec2, vec7, 128, 64, 128);

        intptr_t vec0 = temp_new_gvec(&mem, 128);
        tcg_gen_gvec_zext(MO_32, MO_16, vec0, (vec7 + 64ull), 128, 64, 128);

        intptr_t vec1 = temp_new_gvec(&mem, 128);
        tcg_gen_gvec_shli(MO_32, vec1, vec0, 16, 128, 128);
        tcg_gen_gvec_or(MO_32, vec3, vec1, vec2, 128, 128);
    }

Not to bloat the email too much with examples, you can see 3 more here

https://pad.rev.ng/11IvAKhiRy2cPwC7MX9nXA

Maybe we rely on the target defining size-changing operations if they are needed?

//Anton

#13 lore raw

Re: [RFC PATCH v1 03/43] accel/tcg: Add gvec size changing operations

Quoted 18 lines · Anton Johansson

The point is that we have a lot of Hexagon instructions where size changes are probably unavoidable, another example is V6_vshuffh which takes in a <16 x i16> vector and shuffles the upper <8xi16> into the upper 16-bits of a <8 x i32> vector

     void emit_V6_vshuffh(intptr_t vec3, intptr_t vec7) {
         VectorMem mem = {0};
         intptr_t vec2 = temp_new_gvec(&mem, 128);
         tcg_gen_gvec_zext(MO_32, MO_16, vec2, vec7, 128, 64, 128);

         intptr_t vec0 = temp_new_gvec(&mem, 128);
         tcg_gen_gvec_zext(MO_32, MO_16, vec0, (vec7 + 64ull), 128, 64, 128);

         intptr_t vec1 = temp_new_gvec(&mem, 128);
         tcg_gen_gvec_shli(MO_32, vec1, vec0, 16, 128, 128);
         tcg_gen_gvec_or(MO_32, vec3, vec1, vec2, 128, 128);
     }
Quoted 6 lines

Not to bloat the email too much with examples, you can see 3 more here

   https://pad.rev.ng/11IvAKhiRy2cPwC7MX9nXA

Maybe we rely on the target defining size-changing operations if they are needed?

Perhaps.

I'll note that emit_V6_vpackwh_sat in particular should probably not use vectors at all. I'm sure it would be shorter to simply expand directly to integer code.

I'll also note that tcg's vector support isn't really designed for the way you're using it. It leads to the creation of many on-stack temporaries that would not otherwise be required.

When targets are emitting their own complex patterns, the expected method is to use the GVecGen* structures and the callbacks therein. This allows the JIT to select different expansions depending on the host cpu vector support (or lack thereof).

For a simple example, see gen_gvec_xar() in target/arm/tcg/gengvec64.c, which simply combines a rotate and an xor. For a more complex example, see gen_gvec_usqadd_qc() later in that same file, where in the worst case we call an out-of-line helper.

r~

#14 lore raw

RFC PATCH 4/43 tcg: Add gvec functions for creating consant vectors

In reply to Anton Johansson via

This commit adds a gvec function for copying data from constant array given in C to a gvec intptr_t. For each element, a host store of each constant is performed, this is not ideal and will inflate TBs for large vectors.

Moreover, data will be copied during each run of the generated code impacting performance. A more suitable solution might store constant vectors separately, this can be handled either on the QEMU or helper-to-tcg side.

---
 include/tcg/tcg-op-gvec-common.h |  2 ++
 tcg/tcg-op-gvec.c                | 30 ++++++++++++++++++++++++++++++
 2 files changed, 32 insertions(+)
include/tcg/tcg-op-gvec-common.h +2 -0
index 39b0c2f64e..409a56c633 100644
@@ -331,6 +331,8 @@ void tcg_gen_gvec_dup_mem(unsigned vece, uint32_t dofs, uint32_t aofs,
                           uint32_t s, uint32_t m);
 void tcg_gen_gvec_dup_imm(unsigned vece, uint32_t dofs, uint32_t s,
                           uint32_t m, uint64_t imm);
+void tcg_gen_gvec_constant(unsigned vece, TCGv_env env, uint32_t dofs,
+                           void *arr, uint32_t maxsz);
 void tcg_gen_gvec_dup_i32(unsigned vece, uint32_t dofs, uint32_t s,
                           uint32_t m, TCGv_i32);
 void tcg_gen_gvec_dup_i64(unsigned vece, uint32_t dofs, uint32_t s,
tcg/tcg-op-gvec.c +30 -0
index 80649dc0d2..71b6875129 100644
@@ -1835,6 +1835,36 @@ void tcg_gen_gvec_dup_imm(unsigned vece, uint32_t dofs, uint32_t oprsz,
     do_dup(vece, dofs, oprsz, maxsz, NULL, NULL, x);
 }
 
+
+void tcg_gen_gvec_constant(unsigned vece, TCGv_env env, uint32_t dofs,
+                           void *arr, uint32_t maxsz)
+{
+    uint32_t elsz = memop_size(vece);
+    for (uint32_t i = 0; i < maxsz/elsz; ++i)
+    {
+        uint32_t off = i*elsz;
+        uint8_t *elptr = (uint8_t *)arr + off;
+        switch (vece) {
+        case MO_8:
+            tcg_gen_st8_i32(tcg_constant_i32(*elptr),
+                            env, dofs + off);
+            break;
+        case MO_16:
+            tcg_gen_st16_i32(tcg_constant_i32(*(uint16_t *) elptr),
+                             env, dofs + off);
+            break;
+        case MO_32:
+            tcg_gen_st_i32(tcg_constant_i32(*(uint32_t *) elptr),
+                             env, dofs + off);
+            break;
+        case MO_64:
+            tcg_gen_st_i64(tcg_constant_i64(*(uint64_t *) elptr),
+                           env, dofs + off);
+            break;
+        }
+    }
+}
+
 void tcg_gen_gvec_not(unsigned vece, uint32_t dofs, uint32_t aofs,
                       uint32_t oprsz, uint32_t maxsz)
 {
Signature · 1 line
2.45.2
#15 lore raw

Re: [RFC PATCH v1 04/43] tcg: Add gvec functions for creating consant vectors

Quoted 11 lines · Anton Johansson

This commit adds a gvec function for copying data from constant array given in C to a gvec intptr_t. For each element, a host store of each constant is performed, this is not ideal and will inflate TBs for large vectors.

Moreover, data will be copied during each run of the generated code impacting performance. A more suitable solution might store constant vectors separately, this can be handled either on the QEMU or helper-to-tcg side.

This is invalid because generic code does not know how to index elements within the target vector, which this is doing with its per-element copy.

The code in target/arch/ knows the element ordering (though I suspect you have not taught llvm), and could arrange for the data to be put in the correct byte order, which could then be copied into place using plain host vector operations. I won't attempt to riff on what such an interface would look like exactly, but I imagine that something sensible could be constructed with only a little effort.

r~

Quoted 59 lines
---
  include/tcg/tcg-op-gvec-common.h |  2 ++
  tcg/tcg-op-gvec.c                | 30 ++++++++++++++++++++++++++++++
  2 files changed, 32 insertions(+)
include/tcg/tcg-op-gvec-common.h +2 -0
index 39b0c2f64e..409a56c633 100644
@@ -331,6 +331,8 @@ void tcg_gen_gvec_dup_mem(unsigned vece, uint32_t dofs, uint32_t aofs,
                            uint32_t s, uint32_t m);
  void tcg_gen_gvec_dup_imm(unsigned vece, uint32_t dofs, uint32_t s,
                            uint32_t m, uint64_t imm);
+void tcg_gen_gvec_constant(unsigned vece, TCGv_env env, uint32_t dofs,
+                           void *arr, uint32_t maxsz);
  void tcg_gen_gvec_dup_i32(unsigned vece, uint32_t dofs, uint32_t s,
                            uint32_t m, TCGv_i32);
  void tcg_gen_gvec_dup_i64(unsigned vece, uint32_t dofs, uint32_t s,
tcg/tcg-op-gvec.c +30 -0
index 80649dc0d2..71b6875129 100644
@@ -1835,6 +1835,36 @@ void tcg_gen_gvec_dup_imm(unsigned vece, uint32_t dofs, uint32_t oprsz,
      do_dup(vece, dofs, oprsz, maxsz, NULL, NULL, x);
  }
 
+
+void tcg_gen_gvec_constant(unsigned vece, TCGv_env env, uint32_t dofs,
+                           void *arr, uint32_t maxsz)
+{
+    uint32_t elsz = memop_size(vece);
+    for (uint32_t i = 0; i < maxsz/elsz; ++i)
+    {
+        uint32_t off = i*elsz;
+        uint8_t *elptr = (uint8_t *)arr + off;
+        switch (vece) {
+        case MO_8:
+            tcg_gen_st8_i32(tcg_constant_i32(*elptr),
+                            env, dofs + off);
+            break;
+        case MO_16:
+            tcg_gen_st16_i32(tcg_constant_i32(*(uint16_t *) elptr),
+                             env, dofs + off);
+            break;
+        case MO_32:
+            tcg_gen_st_i32(tcg_constant_i32(*(uint32_t *) elptr),
+                             env, dofs + off);
+            break;
+        case MO_64:
+            tcg_gen_st_i64(tcg_constant_i64(*(uint64_t *) elptr),
+                           env, dofs + off);
+            break;
+        }
+    }
+}
+
  void tcg_gen_gvec_not(unsigned vece, uint32_t dofs, uint32_t aofs,
                        uint32_t oprsz, uint32_t maxsz)
  {
#16 lore raw

Re: [RFC PATCH v1 04/43] tcg: Add gvec functions for creating consant vectors

Quoted 11 lines · Richard Henderson
Quoted 10 lines · Anton Johansson

This commit adds a gvec function for copying data from constant array given in C to a gvec intptr_t. For each element, a host store of each constant is performed, this is not ideal and will inflate TBs for large vectors.

Moreover, data will be copied during each run of the generated code impacting performance. A more suitable solution might store constant vectors separately, this can be handled either on the QEMU or helper-to-tcg side.

Quoted 4 lines
Quoted 1 line

This is invalid because generic code does not know how to index elements within the target vector, which this is doing with its per-element copy.

Hmm I should take a look at tcg_gen_gvec_dup_imm() again, isn't it doing basically the same thing?

Quoted 6 lines

The code in target/arch/ knows the element ordering (though I suspect you have not taught llvm), and could arrange for the data to be put in the correct byte order, which could then be copied into place using plain host vector operations. I won't attempt to riff on what such an interface would look like exactly, but I imagine that something sensible could be constructed with only a little effort.

I might have misunderstood how gvec works, I thought all elements would be in host order, and so copying from a host C array would be fine?

//Anton

#17 lore raw

Re: [RFC PATCH v1 04/43] tcg: Add gvec functions for creating consant vectors

Quoted 12 lines · Anton Johansson
Quoted 11 lines · Richard Henderson
Quoted 10 lines · Anton Johansson

This commit adds a gvec function for copying data from constant array given in C to a gvec intptr_t. For each element, a host store of each constant is performed, this is not ideal and will inflate TBs for large vectors.

Moreover, data will be copied during each run of the generated code impacting performance. A more suitable solution might store constant vectors separately, this can be handled either on the QEMU or helper-to-tcg side.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

This is invalid because generic code does not know how to index elements within the target vector, which this is doing with its per-element copy.

Hmm I should take a look at tcg_gen_gvec_dup_imm() again, isn't it doing basically the same thing?

No, it's limited to replicating uint64_t.

Quoted 10 lines
Quoted 7 lines

The code in target/arch/ knows the element ordering (though I suspect you have not taught llvm), and could arrange for the data to be put in the correct byte order, which could then be copied into place using plain host vector operations. I won't attempt to riff on what such an interface would look like exactly, but I imagine that something sensible could be constructed with only a little effort.

I might have misunderstood how gvec works, I thought all elements would be in host order, and so copying from a host C array would be fine?

No, they are not. They are chucked into host-endian uint64_t, but the ordering of the uint64_t is specific to target/arch/. You never know what "index 0" is, logically, even knowing host-endian, simply because different targets have different element numberings. Especially big-endian targets.

r~

#18 lore raw

RFC PATCH 5/43 tcg: Add helper function dispatcher and hook tcg_gen_callN

In reply to Anton Johansson via

Adds a function pointer to the TCGContext which may be set by targets via the TARGET_HELPER_DISPATCHER macro. The dispatcher is function

(void *func, TCGTemp *ret, int nargs, TCGTemp **args) -> bool

which allows targets to hook the generation of helper calls in TCG and take over translation. Specifically, this will be used by helper-to-tcg to replace helper function translation, without having to modify frontends.

---
 accel/tcg/translate-all.c | 4 ++++
 include/tcg/tcg.h         | 4 ++++
 tcg/tcg.c                 | 5 +++++
 3 files changed, 13 insertions(+)
accel/tcg/translate-all.c +4 -0
index fdf6d8ac19..814aae93ae 100644
@@ -352,6 +352,10 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
     tcg_ctx->guest_mo = TCG_MO_ALL;
 #endif
 
+#if defined(CONFIG_HELPER_TO_TCG) && defined(TARGET_HELPER_DISPATCHER)
+    tcg_ctx->helper_dispatcher = TARGET_HELPER_DISPATCHER;
+#endif
+
  restart_translate:
     trace_translate_block(tb, pc, tb->tc.ptr);
 
include/tcg/tcg.h +4 -0
index a77ed12b9d..d3e820568f 100644
@@ -549,6 +549,10 @@ struct TCGContext {
 
     /* Exit to translator on overflow. */
     sigjmp_buf jmp_trans;
+
+
+    bool (*helper_dispatcher)(void *func, TCGTemp *ret_temp,
+                              int nargs, TCGTemp **args);
 };
 
 static inline bool temp_readonly(TCGTemp *ts)
tcg/tcg.c +5 -0
index 0babae1b88..5f03bef688 100644
@@ -2252,6 +2252,11 @@ static void tcg_gen_callN(void *func, TCGHelperInfo *info,
     }
 
     total_args = info->nr_out + info->nr_in + 2;
+    if (unlikely(tcg_ctx->helper_dispatcher) &&
+        tcg_ctx->helper_dispatcher(info->func, ret, total_args, args)) {
+        return;
+    }
+
     op = tcg_op_alloc(INDEX_op_call, total_args);
 
 #ifdef CONFIG_PLUGIN
Signature · 1 line
2.45.2
#19 lore raw

Re: [RFC PATCH v1 05/43] tcg: Add helper function dispatcher and hook tcg_gen_callN

Quoted 9 lines · Anton Johansson

Adds a function pointer to the TCGContext which may be set by targets via the TARGET_HELPER_DISPATCHER macro. The dispatcher is function

(void *func, TCGTemp *ret, int nargs, TCGTemp **args) -> bool

which allows targets to hook the generation of helper calls in TCG and take over translation. Specifically, this will be used by helper-to-tcg to replace helper function translation, without having to modify frontends.

Quoted 6 lines
---
  accel/tcg/translate-all.c | 4 ++++
  include/tcg/tcg.h         | 4 ++++
  tcg/tcg.c                 | 5 +++++
  3 files changed, 13 insertions(+)

I guess I'll have to read further to understand this, but my first reaction is: why would we not modify how the gen_helper_* functions are defined instead?

r~

Quoted 47 lines
accel/tcg/translate-all.c +4 -0
index fdf6d8ac19..814aae93ae 100644
@@ -352,6 +352,10 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
      tcg_ctx->guest_mo = TCG_MO_ALL;
  #endif
 
+#if defined(CONFIG_HELPER_TO_TCG) && defined(TARGET_HELPER_DISPATCHER)
+    tcg_ctx->helper_dispatcher = TARGET_HELPER_DISPATCHER;
+#endif
+
   restart_translate:
      trace_translate_block(tb, pc, tb->tc.ptr);
 
include/tcg/tcg.h +4 -0
index a77ed12b9d..d3e820568f 100644
@@ -549,6 +549,10 @@ struct TCGContext {
 
      /* Exit to translator on overflow. */
      sigjmp_buf jmp_trans;
+
+
+    bool (*helper_dispatcher)(void *func, TCGTemp *ret_temp,
+                              int nargs, TCGTemp **args);
  };
 
  static inline bool temp_readonly(TCGTemp *ts)
tcg/tcg.c +5 -0
index 0babae1b88..5f03bef688 100644
@@ -2252,6 +2252,11 @@ static void tcg_gen_callN(void *func, TCGHelperInfo *info,
      }
 
      total_args = info->nr_out + info->nr_in + 2;
+    if (unlikely(tcg_ctx->helper_dispatcher) &&
+        tcg_ctx->helper_dispatcher(info->func, ret, total_args, args)) {
+        return;
+    }
+
      op = tcg_op_alloc(INDEX_op_call, total_args);
 
  #ifdef CONFIG_PLUGIN
#20 lore raw

Re: [RFC PATCH v1 05/43] tcg: Add helper function dispatcher and hook tcg_gen_callN

Quoted 17 lines · Richard Henderson
Quoted 9 lines · Anton Johansson

Adds a function pointer to the TCGContext which may be set by targets via the TARGET_HELPER_DISPATCHER macro. The dispatcher is function

(void *func, TCGTemp *ret, int nargs, TCGTemp **args) -> bool

which allows targets to hook the generation of helper calls in TCG and take over translation. Specifically, this will be used by helper-to-tcg to replace helper function translation, without having to modify frontends.

Quoted 6 lines
---
  accel/tcg/translate-all.c | 4 ++++
  include/tcg/tcg.h         | 4 ++++
  tcg/tcg.c                 | 5 +++++
  3 files changed, 13 insertions(+)
Quoted 3 lines

I guess I'll have to read further to understand this, but my first reaction
is: why would we not modify how the gen_helper_* functions are defined instead?

Hmm this might be a better idea, and we could call the generated could directly without having to go through a massive switch statement. What I have in mind is something like

    #if !glue(OVERRIDE_HELPER_, name) \
    #define DEF_HELPER_FLAGS_1(name, flags, ret, t1)                        \
    extern TCGHelperInfo glue(helper_info_, name);                          \
    static inline void glue(gen_helper_, name)(dh_retvar_decl(ret)          \
        dh_arg_decl(t1, 1))                                                 \
    {                                                                       \
        tcg_gen_call1(glue(helper_info_,name).func,                         \
                      &glue(helper_info_,name), dh_retvar(ret),             \
                      dh_arg(t1, 1));                                       \
    }                                                                       \
    #endif

and we could emit gen_helper_* for helpers which are translated and redefine OVERRIDE_HELPER_* to 1 (would have to be defaulted to 0 somewhere else).

//Anton

#21 lore raw

RFC PATCH 6/43 tcg: Introduce tcg-global-mappings

In reply to Anton Johansson via

Adds a cpu_mapping struct to describe, in a declarative fashion, the mapping between fields in a struct, and a corresponding TCG global. As such, tcg_global_mem_new() can be automatically called given an array of cpu_mappings.

This change is not limited to helper-to-tcg, but will be required in future commits to map between offsets into CPUArchState and TCGv globals in a target-agnostic way.

---
 include/tcg/tcg-global-mappings.h | 111 ++++++++++++++++++++++++++++++
 tcg/meson.build                   |   1 +
 tcg/tcg-global-mappings.c         |  61 ++++++++++++++++
 3 files changed, 173 insertions(+)
 create mode 100644 include/tcg/tcg-global-mappings.h
 create mode 100644 tcg/tcg-global-mappings.c
include/tcg/tcg-global-mappings.h new file +111 -0
new file mode 100644
index 0000000000..736380fb20
@@ -0,0 +1,111 @@
+/*
+ *  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef TCG_GLOBAL_MAP_H
+#define TCG_GLOBAL_MAP_H
+
+#include "qemu/osdep.h"
+
+/**
+ * cpu_tcg_mapping: Declarative mapping of offsets into a struct to global
+ *                  TCGvs.  Parseable by LLVM-based tools.
+ * @tcg_var_name: String name of the TCGv to use as destination of the mapping.
+ * @tcg_var_base_address: Address of the above TCGv.
+ * @cpu_var_names: Array of printable names of TCGvs, used when calling
+ *                 tcg_global_mem_new from init_cpu_tcg_mappings.
+ * @cpu_var_base_offset: Base offset of field in the source struct.
+ * @cpu_var_size: Size of field in the source struct, if the field is an array,
+ *                this holds the size of the element type.
+ * @cpu_var_stride: Stride between array elements in the source struct.  This
+ *                  can be greater than the element size when mapping a field
+ *                  in an array of structs.
+ * @number_of_elements: Number of elements of array in the source struct.
+ */
+typedef struct cpu_tcg_mapping {
+    const char *tcg_var_name;
+    void *tcg_var_base_address;
+
+    const char *const *cpu_var_names;
+    size_t cpu_var_base_offset;
+    size_t cpu_var_size;
+    size_t cpu_var_stride;
+
+    size_t number_of_elements;
+} cpu_tcg_mapping;
+
+#define STRUCT_SIZEOF_FIELD(S, member) sizeof(((S *)0)->member)
+
+#define STRUCT_ARRAY_SIZE(S, array)                                            \
+    (STRUCT_SIZEOF_FIELD(S, array) / STRUCT_SIZEOF_FIELD(S, array[0]))
+
+/*
+ * Following are a few macros that aid in constructing
+ * `cpu_tcg_mapping`s for a few common cases.
+ */
+
+/* Map between single CPU register and to TCG global */
+#define CPU_TCG_MAP(struct_type, tcg_var, cpu_var, name_str)                   \
+    (cpu_tcg_mapping)                                                          \
+    {                                                                          \
+        .tcg_var_name = stringify(tcg_var), .tcg_var_base_address = &tcg_var,  \
+        .cpu_var_names = (const char *[]){name_str},                           \
+        .cpu_var_base_offset = offsetof(struct_type, cpu_var),                 \
+        .cpu_var_size = STRUCT_SIZEOF_FIELD(struct_type, cpu_var),             \
+        .cpu_var_stride = 0, .number_of_elements = 1,                          \
+    }
+
+/* Map between array of CPU registers and array of TCG globals. */
+#define CPU_TCG_MAP_ARRAY(struct_type, tcg_var, cpu_var, names)                \
+    (cpu_tcg_mapping)                                                          \
+    {                                                                          \
+        .tcg_var_name = #tcg_var, .tcg_var_base_address = tcg_var,             \
+        .cpu_var_names = names,                                                \
+        .cpu_var_base_offset = offsetof(struct_type, cpu_var),                 \
+        .cpu_var_size = STRUCT_SIZEOF_FIELD(struct_type, cpu_var[0]),          \
+        .cpu_var_stride = STRUCT_SIZEOF_FIELD(struct_type, cpu_var[0]),        \
+        .number_of_elements = STRUCT_ARRAY_SIZE(struct_type, cpu_var),         \
+    }
+
+/*
+ * Map between single member in an array of structs to an array
+ * of TCG globals, e.g. maps
+ *
+ *     cpu_state.array_of_structs[i].member
+ *
+ * to
+ *
+ *     tcg_global_member[i]
+ */
+#define CPU_TCG_MAP_ARRAY_OF_STRUCTS(struct_type, tcg_var, cpu_struct,         \
+                                     cpu_var, names)                           \
+    (cpu_tcg_mapping)                                                          \
+    {                                                                          \
+        .tcg_var_name = #tcg_var, .tcg_var_base_address = tcg_var,             \
+        .cpu_var_names = names,                                                \
+        .cpu_var_base_offset = offsetof(struct_type, cpu_struct[0].cpu_var),   \
+        .cpu_var_size =                                                        \
+            STRUCT_SIZEOF_FIELD(struct_type, cpu_struct[0].cpu_var),           \
+        .cpu_var_stride = STRUCT_SIZEOF_FIELD(struct_type, cpu_struct[0]),     \
+        .number_of_elements = STRUCT_ARRAY_SIZE(struct_type, cpu_struct),      \
+    }
+
+extern cpu_tcg_mapping tcg_global_mappings[];
+extern size_t tcg_global_mapping_count;
+
+void init_cpu_tcg_mappings(cpu_tcg_mapping *mappings, size_t size);
+
+#endif /* TCG_GLOBAL_MAP_H */
tcg/meson.build +1 -0
index 69ebb4908a..a0d6b09d85 100644
@@ -13,6 +13,7 @@ tcg_ss.add(files(
   'tcg-op-ldst.c',
   'tcg-op-gvec.c',
   'tcg-op-vec.c',
+  'tcg-global-mappings.c',
 ))
 
 if get_option('tcg_interpreter')
tcg/tcg-global-mappings.c new file +61 -0

61 lines not on this page · raw message

Signature · 1 line
2.45.2
#22 lore raw

Re: [RFC PATCH v1 06/43] tcg: Introduce tcg-global-mappings

Quoted 9 lines · Anton Johansson

Adds a cpu_mapping struct to describe, in a declarative fashion, the mapping between fields in a struct, and a corresponding TCG global. As such, tcg_global_mem_new() can be automatically called given an array of cpu_mappings.

This change is not limited to helper-to-tcg, but will be required in future commits to map between offsets into CPUArchState and TCGv globals in a target-agnostic way.

Quoted 8 lines
---
  include/tcg/tcg-global-mappings.h | 111 ++++++++++++++++++++++++++++++
  tcg/meson.build                   |   1 +
  tcg/tcg-global-mappings.c         |  61 ++++++++++++++++
  3 files changed, 173 insertions(+)

create mode 100644 include/tcg/tcg-global-mappings.h create mode 100644 tcg/tcg-global-mappings.c

Plausible.

In the most ideal of cases, helpers would *never* access TCG globals directly. They would always be passed in/out via normal parameters. I know this sometimes becomes impractical with multiple outputs. But quite often we create TCG globals for e.g. control registers which ought not be TCG globals in the first place. This can often allow helpers to be marked TCG_CALL_NO_RWG etc, which helps even out-of-line helpers.

How often is Hexagon referencing globals directly?

r~

Quoted 197 lines
include/tcg/tcg-global-mappings.h new file +111 -0
new file mode 100644
index 0000000000..736380fb20
@@ -0,0 +1,111 @@
+/*
+ *  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef TCG_GLOBAL_MAP_H
+#define TCG_GLOBAL_MAP_H
+
+#include "qemu/osdep.h"
+
+/**
+ * cpu_tcg_mapping: Declarative mapping of offsets into a struct to global
+ *                  TCGvs.  Parseable by LLVM-based tools.
+ * @tcg_var_name: String name of the TCGv to use as destination of the mapping.
+ * @tcg_var_base_address: Address of the above TCGv.
+ * @cpu_var_names: Array of printable names of TCGvs, used when calling
+ *                 tcg_global_mem_new from init_cpu_tcg_mappings.
+ * @cpu_var_base_offset: Base offset of field in the source struct.
+ * @cpu_var_size: Size of field in the source struct, if the field is an array,
+ *                this holds the size of the element type.
+ * @cpu_var_stride: Stride between array elements in the source struct.  This
+ *                  can be greater than the element size when mapping a field
+ *                  in an array of structs.
+ * @number_of_elements: Number of elements of array in the source struct.
+ */
+typedef struct cpu_tcg_mapping {
+    const char *tcg_var_name;
+    void *tcg_var_base_address;
+
+    const char *const *cpu_var_names;
+    size_t cpu_var_base_offset;
+    size_t cpu_var_size;
+    size_t cpu_var_stride;
+
+    size_t number_of_elements;
+} cpu_tcg_mapping;
+
+#define STRUCT_SIZEOF_FIELD(S, member) sizeof(((S *)0)->member)
+
+#define STRUCT_ARRAY_SIZE(S, array)                                            \
+    (STRUCT_SIZEOF_FIELD(S, array) / STRUCT_SIZEOF_FIELD(S, array[0]))
+
+/*
+ * Following are a few macros that aid in constructing
+ * `cpu_tcg_mapping`s for a few common cases.
+ */
+
+/* Map between single CPU register and to TCG global */
+#define CPU_TCG_MAP(struct_type, tcg_var, cpu_var, name_str)                   \
+    (cpu_tcg_mapping)                                                          \
+    {                                                                          \
+        .tcg_var_name = stringify(tcg_var), .tcg_var_base_address = &tcg_var,  \
+        .cpu_var_names = (const char *[]){name_str},                           \
+        .cpu_var_base_offset = offsetof(struct_type, cpu_var),                 \
+        .cpu_var_size = STRUCT_SIZEOF_FIELD(struct_type, cpu_var),             \
+        .cpu_var_stride = 0, .number_of_elements = 1,                          \
+    }
+
+/* Map between array of CPU registers and array of TCG globals. */
+#define CPU_TCG_MAP_ARRAY(struct_type, tcg_var, cpu_var, names)                \
+    (cpu_tcg_mapping)                                                          \
+    {                                                                          \
+        .tcg_var_name = #tcg_var, .tcg_var_base_address = tcg_var,             \
+        .cpu_var_names = names,                                                \
+        .cpu_var_base_offset = offsetof(struct_type, cpu_var),                 \
+        .cpu_var_size = STRUCT_SIZEOF_FIELD(struct_type, cpu_var[0]),          \
+        .cpu_var_stride = STRUCT_SIZEOF_FIELD(struct_type, cpu_var[0]),        \
+        .number_of_elements = STRUCT_ARRAY_SIZE(struct_type, cpu_var),         \
+    }
+
+/*
+ * Map between single member in an array of structs to an array
+ * of TCG globals, e.g. maps
+ *
+ *     cpu_state.array_of_structs[i].member
+ *
+ * to
+ *
+ *     tcg_global_member[i]
+ */
+#define CPU_TCG_MAP_ARRAY_OF_STRUCTS(struct_type, tcg_var, cpu_struct,         \
+                                     cpu_var, names)                           \
+    (cpu_tcg_mapping)                                                          \
+    {                                                                          \
+        .tcg_var_name = #tcg_var, .tcg_var_base_address = tcg_var,             \
+        .cpu_var_names = names,                                                \
+        .cpu_var_base_offset = offsetof(struct_type, cpu_struct[0].cpu_var),   \
+        .cpu_var_size =                                                        \
+            STRUCT_SIZEOF_FIELD(struct_type, cpu_struct[0].cpu_var),           \
+        .cpu_var_stride = STRUCT_SIZEOF_FIELD(struct_type, cpu_struct[0]),     \
+        .number_of_elements = STRUCT_ARRAY_SIZE(struct_type, cpu_struct),      \
+    }
+
+extern cpu_tcg_mapping tcg_global_mappings[];
+extern size_t tcg_global_mapping_count;
+
+void init_cpu_tcg_mappings(cpu_tcg_mapping *mappings, size_t size);
+
+#endif /* TCG_GLOBAL_MAP_H */
tcg/meson.build +1 -0
index 69ebb4908a..a0d6b09d85 100644
@@ -13,6 +13,7 @@ tcg_ss.add(files(
    'tcg-op-ldst.c',
    'tcg-op-gvec.c',
    'tcg-op-vec.c',
+  'tcg-global-mappings.c',
  ))
 
  if get_option('tcg_interpreter')
tcg/tcg-global-mappings.c new file +61 -0
new file mode 100644
index 0000000000..cc1f07fae4
@@ -0,0 +1,61 @@
+/*
+ *  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "tcg/tcg-global-mappings.h"
+#include "tcg/tcg-op-common.h"
+#include "tcg/tcg.h"
+
+void init_cpu_tcg_mappings(cpu_tcg_mapping *mappings, size_t size)
+{
+    uintptr_t tcg_addr;
+    size_t cpu_offset;
+    const char *name;
+    cpu_tcg_mapping m;
+
+    /*
+     * Paranoid assertion, this should always hold since
+     * they're typedef'd to pointers. But you never know!
+     */
+    g_assert(sizeof(TCGv_i32) == sizeof(TCGv_i64));
+
+    /*
+     * Loop over entries in tcg_global_mappings and
+     * create the `mapped to` TCGv's.
+     */
+    for (int i = 0; i < size; ++i) {
+        m = mappings[i];
+
+        for (int j = 0; j < m.number_of_elements; ++j) {
+            /*
+             * Here we are using the fact that
+             * sizeof(TCGv_i32) == sizeof(TCGv_i64) == sizeof(TCGv)
+             */
+            assert(sizeof(TCGv_i32) == sizeof(TCGv_i64));
+            tcg_addr = (uintptr_t)m.tcg_var_base_address + j * sizeof(TCGv_i32);
+            cpu_offset = m.cpu_var_base_offset + j * m.cpu_var_stride;
+            name = m.cpu_var_names[j];
+
+            if (m.cpu_var_size < 8) {
+                *(TCGv_i32 *)tcg_addr =
+                    tcg_global_mem_new_i32(tcg_env, cpu_offset, name);
+            } else {
+                *(TCGv_i64 *)tcg_addr =
+                    tcg_global_mem_new_i64(tcg_env, cpu_offset, name);
+            }
+        }
+    }
+}
#23 lore raw

RFC PATCH 7/43 tcg: Increase maximum TB size and maximum temporaries

In reply to Anton Johansson via

Doubles amount of space allocated for translation blocks. This is needed, particularly for Hexagon, where a single instruction packet may consist of up to four vector instructions. If each vector instruction then gets expanded into gvec operations that utilize a small host vector size the TB blows up quite quickly.

---
 include/tcg/tcg.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
include/tcg/tcg.h +2 -2
index d3e820568f..bd8cb9ff50 100644
@@ -39,7 +39,7 @@
 /* XXX: make safe guess about sizes */
 #define MAX_OP_PER_INSTR 266
 
-#define CPU_TEMP_BUF_NLONGS 128
+#define CPU_TEMP_BUF_NLONGS 256
 #define TCG_STATIC_FRAME_SIZE  (CPU_TEMP_BUF_NLONGS * sizeof(long))
 
 #if TCG_TARGET_REG_BITS == 32
@@ -231,7 +231,7 @@ typedef struct TCGPool {
 
 #define TCG_POOL_CHUNK_SIZE 32768
 
-#define TCG_MAX_TEMPS 512
+#define TCG_MAX_TEMPS 1024
 #define TCG_MAX_INSNS 512
 
 /* when the size of the arguments of a called function is smaller than
Signature · 1 line
2.45.2
#24 lore raw

Re: [RFC PATCH v1 07/43] tcg: Increase maximum TB size and maximum temporaries

Quoted 7 lines · Anton Johansson

Doubles amount of space allocated for translation blocks. This is needed, particularly for Hexagon, where a single instruction packet may consist of up to four vector instructions. If each vector instruction then gets expanded into gvec operations that utilize a small host vector size the TB blows up quite quickly.

I hope this is a performance modification only?
I hope that the normal set of "restart on resource overflow" code functioned correctly? If you're overflowing these values with a single hexagon insn, then I suggest something is wrong.

Quoted 9 lines
---
  include/tcg/tcg.h | 4 ++--
  1 file changed, 2 insertions(+), 2 deletions(-)
include/tcg/tcg.h +0 -0
index d3e820568f..bd8cb9ff50 100644

include/tcg/tcg.h line 43

Quoted 6 lines
include/tcg/tcg.h +1 -1
@@ -39,7 +39,7 @@
  /* XXX: make safe guess about sizes */
  #define MAX_OP_PER_INSTR 266
 
-#define CPU_TEMP_BUF_NLONGS 128
+#define CPU_TEMP_BUF_NLONGS 256
  #define TCG_STATIC_FRAME_SIZE  (CPU_TEMP_BUF_NLONGS * sizeof(long))

Changing this probably requires auditing all tcg/arch/ backends. The various prologue generation code *ought* to catch out of range values, but I bet we weren't that careful.

r~

Quoted 11 lines
include/tcg/tcg.h +1 -1
  #if TCG_TARGET_REG_BITS == 32
@@ -231,7 +231,7 @@ typedef struct TCGPool {
 
  #define TCG_POOL_CHUNK_SIZE 32768
 
-#define TCG_MAX_TEMPS 512
+#define TCG_MAX_TEMPS 1024
  #define TCG_MAX_INSNS 512
 
  /* when the size of the arguments of a called function is smaller than
#25 lore raw

RFC PATCH 8/43 include/helper-to-tcg: Introduce annotate.h

In reply to Anton Johansson via

Wrap __attribute__((annotate(str))) in a macro for convenient function annotations. Will be used in future commits to tag functions for translation by helper-to-tcg, and to specify which helper function arguments correspond to immediate or vector values.

---
 include/helper-to-tcg/annotate.h | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
 create mode 100644 include/helper-to-tcg/annotate.h
include/helper-to-tcg/annotate.h new file +28 -0
new file mode 100644
index 0000000000..80ecf23217
@@ -0,0 +1,28 @@
+/*
+ *  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef ANNOTATE_H
+#define ANNOTATE_H
+
+/* HELPER_TO_TCG can be defined when generating LLVM IR. */
+#ifdef HELPER_TO_TCG
+#define LLVM_ANNOTATE(str) __attribute__((annotate (str)))
+#else
+#define LLVM_ANNOTATE(str) /* str */
+#endif
+
+#endif /* ANNOTATE_H */
Signature · 1 line
2.45.2
#26 lore raw

Re: [RFC PATCH v1 08/43] include/helper-to-tcg: Introduce annotate.h

Quoted 10 lines · Anton Johansson

Wrap __attribute__((annotate(str))) in a macro for convenient function annotations. Will be used in future commits to tag functions for translation by helper-to-tcg, and to specify which helper function arguments correspond to immediate or vector values.

---
  include/helper-to-tcg/annotate.h | 28 ++++++++++++++++++++++++++++
  1 file changed, 28 insertions(+)

create mode 100644 include/helper-to-tcg/annotate.h

Is this really specific to helper-to-tcg, or might it be used for something else in the future? In other words, does it belong in include/qemu/compiler.h?

r~

#27 lore raw

Re: [RFC PATCH v1 08/43] include/helper-to-tcg: Introduce annotate.h

Quoted 6 lines · Richard Henderson
Quoted 5 lines · Anton Johansson

Wrap __attribute__((annotate(str))) in a macro for convenient function annotations.  Will be used in future commits to tag functions for translation by helper-to-tcg, and to specify which helper function arguments correspond to immediate or vector values.

Quoted 7 lines
Quoted 5 lines

---
  include/helper-to-tcg/annotate.h | 28 ++++++++++++++++++++++++++++

  1 file changed, 28 insertions(+)

  create mode 100644 include/helper-to-tcg/annotate.h

Is this really specific to helper-to-tcg, or might it be used for something else in the future?  In other words, does it belong in include/qemu/compiler.h?

We already have there QEMU_ANNOTATE() since end of 2022 (use in commit cbdbc47cee, QEMU macro in d79b9202e4).

#28 lore raw

Re: [RFC PATCH v1 08/43] include/helper-to-tcg: Introduce annotate.h

Quoted 13 lines · Philippe Mathieu-Daudé
Quoted 12 lines · Richard Henderson
Quoted 10 lines · Anton Johansson

Wrap __attribute__((annotate(str))) in a macro for convenient function annotations.  Will be used in future commits to tag functions for translation by helper-to-tcg, and to specify which helper function arguments correspond to immediate or vector values.

---
  include/helper-to-tcg/annotate.h | 28 ++++++++++++++++++++++++++++

  1 file changed, 28 insertions(+)

  create mode 100644 include/helper-to-tcg/annotate.h

Quoted 6 lines
Quoted 3 lines

Is this really specific to helper-to-tcg, or might it be used for something else in the future?  In other words, does it belong in include/qemu/compiler.h?

We already have there QEMU_ANNOTATE() since end of 2022 (use in commit cbdbc47cee, QEMU macro in d79b9202e4).

Oh this is very nice! I'll use QEMU_ANNOTATE() then! Thanks:)

//Anton

#29 lore raw

RFC PATCH 9/43 helper-to-tcg: Introduce get-llvm-ir.py

In reply to Anton Johansson via

Introduces a new python helper script to convert a set of QEMU .c files to LLVM IR .ll using clang. Compile flags are found by looking at compile_commands.json, and llvm-link is used to link together all LLVM modules into a single module.

---
 subprojects/helper-to-tcg/get-llvm-ir.py | 143 +++++++++++++++++++++++
 1 file changed, 143 insertions(+)
 create mode 100755 subprojects/helper-to-tcg/get-llvm-ir.py
subprojects/helper-to-tcg/get-llvm-ir.py new file +143 -0
new file mode 100755
index 0000000000..9ee5d0e136
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+
+##
+##  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+##
+##  This program is free software; you can redistribute it and/or modify
+##  it under the terms of the GNU General Public License as published by
+##  the Free Software Foundation; either version 2 of the License, or
+##  (at your option) any later version.
+##
+##  This program is distributed in the hope that it will be useful,
+##  but WITHOUT ANY WARRANTY; without even the implied warranty of
+##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+##  GNU General Public License for more details.
+##
+##  You should have received a copy of the GNU General Public License
+##  along with this program; if not, see <http://www.gnu.org/licenses/>.
+##
+
+import argparse
+import json
+import os
+import shlex
+import sys
+import subprocess
+
+
+def log(msg):
+    print(msg, file=sys.stderr)
+
+
+def run_command(command):
+    proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+    out = proc.communicate()
+    if proc.wait() != 0:
+        log(f"Command: {' '.join(command)} exited with {proc.returncode}\n")
+        log(f"output:\n{out}\n")
+
+
+def find_compile_commands(compile_commands_path, clang_path, input_path, target):
+    with open(compile_commands_path, "r") as f:
+        compile_commands = json.load(f)
+        for compile_command in compile_commands:
+            path = compile_command["file"]
+            if os.path.basename(path) != os.path.basename(input_path):
+                continue
+
+            os.chdir(compile_command["directory"])
+            command = compile_command["command"]
+
+            # If building multiple targets there's a chance
+            # input files share the same path and name.
+            # This could cause us to find the wrong compile
+            # command, we use the target path to distinguish
+            # between these.
+            if not target in command:
+                continue
+
+            argv = shlex.split(command)
+            argv[0] = clang_path
+
+            return argv
+
+    raise ValueError(f"Unable to find compile command for {input_path}")
+
+
+def generate_llvm_ir(
+    compile_commands_path, clang_path, output_path, input_path, target
+):
+    command = find_compile_commands(
+        compile_commands_path, clang_path, input_path, target
+    )
+
+    flags_to_remove = {
+        "-ftrivial-auto-var-init=zero",
+        "-fzero-call-used-regs=used-gpr",
+        "-Wimplicit-fallthrough=2",
+        "-Wold-style-declaration",
+        "-Wno-psabi",
+        "-Wshadow=local",
+    }
+
+    # Remove
+    #   - output of makefile rules (-MQ,-MF target);
+    #   - output of object files (-o target);
+    #   - excessive zero-initialization of block-scope variables
+    #     (-ftrivial-auto-var-init=zero);
+    #   - and any optimization flags (-O).
+    for i, arg in reversed(list(enumerate(command))):
+        if arg in {"-MQ", "-o", "-MF"}:
+            del command[i : i + 2]
+        elif arg.startswith("-O") or arg in flags_to_remove:
+            del command[i]
+
+    # Define a HELPER_TO_TCG macro for translation units wanting to
+    # conditionally include or exclude code during translation to TCG.
+    # Disable optimization (-O0) and make sure clang doesn't emit optnone
+    # attributes (-disable-O0-optnone) which inhibit further optimization.
+    # Optimization will be performed at a later stage in the helper-to-tcg
+    # pipeline.
+    command += [
+        "-S",
+        "-emit-llvm",
+        "-DHELPER_TO_TCG",
+        "-O0",
+        "-Xclang",
+        "-disable-O0-optnone",
+    ]
+    if output_path:
+        command += ["-o", output_path]
+
+    run_command(command)
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="Produce the LLVM IR of a given .c file."
+    )
+    parser.add_argument(
+        "--compile-commands", required=True, help="Path to compile_commands.json"
+    )
+    parser.add_argument("--clang", default="clang", help="Path to clang.")
+    parser.add_argument("--llvm-link", default="llvm-link", help="Path to llvm-link.")
+    parser.add_argument("-o", "--output", required=True, help="Output .ll file path")
+    parser.add_argument(
+        "--target-path", help="Path to QEMU target dir. (e.q. target/i386)"
+    )
+    parser.add_argument("inputs", nargs="+", help=".c file inputs")
+    args = parser.parse_args()
+
+    outputs = []
+    for input in args.inputs:
+        output = os.path.basename(input) + ".ll"
+        generate_llvm_ir(
+            args.compile_commands, args.clang, output, input, args.target_path
+        )
+        outputs.append(output)
+
+    run_command([args.llvm_link] + outputs + ["-S", "-o", args.output])
+
+
+if __name__ == "__main__":
+    sys.exit(main())
Signature · 1 line
2.45.2
#30 lore raw

Re: [RFC PATCH v1 09/43] helper-to-tcg: Introduce get-llvm-ir.py

Quoted 10 lines · Anton Johansson

Introduces a new python helper script to convert a set of QEMU .c files to LLVM IR .ll using clang. Compile flags are found by looking at compile_commands.json, and llvm-link is used to link together all LLVM modules into a single module.

---
  subprojects/helper-to-tcg/get-llvm-ir.py | 143 +++++++++++++++++++++++
  1 file changed, 143 insertions(+)

create mode 100755 subprojects/helper-to-tcg/get-llvm-ir.py

Is this not something that can be done in meson?

r~

Quoted 150 lines
subprojects/helper-to-tcg/get-llvm-ir.py new file +143 -0
new file mode 100755
index 0000000000..9ee5d0e136
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+
+##
+##  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+##
+##  This program is free software; you can redistribute it and/or modify
+##  it under the terms of the GNU General Public License as published by
+##  the Free Software Foundation; either version 2 of the License, or
+##  (at your option) any later version.
+##
+##  This program is distributed in the hope that it will be useful,
+##  but WITHOUT ANY WARRANTY; without even the implied warranty of
+##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+##  GNU General Public License for more details.
+##
+##  You should have received a copy of the GNU General Public License
+##  along with this program; if not, see <http://www.gnu.org/licenses/>.
+##
+
+import argparse
+import json
+import os
+import shlex
+import sys
+import subprocess
+
+
+def log(msg):
+    print(msg, file=sys.stderr)
+
+
+def run_command(command):
+    proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+    out = proc.communicate()
+    if proc.wait() != 0:
+        log(f"Command: {' '.join(command)} exited with {proc.returncode}\n")
+        log(f"output:\n{out}\n")
+
+
+def find_compile_commands(compile_commands_path, clang_path, input_path, target):
+    with open(compile_commands_path, "r") as f:
+        compile_commands = json.load(f)
+        for compile_command in compile_commands:
+            path = compile_command["file"]
+            if os.path.basename(path) != os.path.basename(input_path):
+                continue
+
+            os.chdir(compile_command["directory"])
+            command = compile_command["command"]
+
+            # If building multiple targets there's a chance
+            # input files share the same path and name.
+            # This could cause us to find the wrong compile
+            # command, we use the target path to distinguish
+            # between these.
+            if not target in command:
+                continue
+
+            argv = shlex.split(command)
+            argv[0] = clang_path
+
+            return argv
+
+    raise ValueError(f"Unable to find compile command for {input_path}")
+
+
+def generate_llvm_ir(
+    compile_commands_path, clang_path, output_path, input_path, target
+):
+    command = find_compile_commands(
+        compile_commands_path, clang_path, input_path, target
+    )
+
+    flags_to_remove = {
+        "-ftrivial-auto-var-init=zero",
+        "-fzero-call-used-regs=used-gpr",
+        "-Wimplicit-fallthrough=2",
+        "-Wold-style-declaration",
+        "-Wno-psabi",
+        "-Wshadow=local",
+    }
+
+    # Remove
+    #   - output of makefile rules (-MQ,-MF target);
+    #   - output of object files (-o target);
+    #   - excessive zero-initialization of block-scope variables
+    #     (-ftrivial-auto-var-init=zero);
+    #   - and any optimization flags (-O).
+    for i, arg in reversed(list(enumerate(command))):
+        if arg in {"-MQ", "-o", "-MF"}:
+            del command[i : i + 2]
+        elif arg.startswith("-O") or arg in flags_to_remove:
+            del command[i]
+
+    # Define a HELPER_TO_TCG macro for translation units wanting to
+    # conditionally include or exclude code during translation to TCG.
+    # Disable optimization (-O0) and make sure clang doesn't emit optnone
+    # attributes (-disable-O0-optnone) which inhibit further optimization.
+    # Optimization will be performed at a later stage in the helper-to-tcg
+    # pipeline.
+    command += [
+        "-S",
+        "-emit-llvm",
+        "-DHELPER_TO_TCG",
+        "-O0",
+        "-Xclang",
+        "-disable-O0-optnone",
+    ]
+    if output_path:
+        command += ["-o", output_path]
+
+    run_command(command)
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        description="Produce the LLVM IR of a given .c file."
+    )
+    parser.add_argument(
+        "--compile-commands", required=True, help="Path to compile_commands.json"
+    )
+    parser.add_argument("--clang", default="clang", help="Path to clang.")
+    parser.add_argument("--llvm-link", default="llvm-link", help="Path to llvm-link.")
+    parser.add_argument("-o", "--output", required=True, help="Output .ll file path")
+    parser.add_argument(
+        "--target-path", help="Path to QEMU target dir. (e.q. target/i386)"
+    )
+    parser.add_argument("inputs", nargs="+", help=".c file inputs")
+    args = parser.parse_args()
+
+    outputs = []
+    for input in args.inputs:
+        output = os.path.basename(input) + ".ll"
+        generate_llvm_ir(
+            args.compile_commands, args.clang, output, input, args.target_path
+        )
+        outputs.append(output)
+
+    run_command([args.llvm_link] + outputs + ["-S", "-o", args.output])
+
+
+if __name__ == "__main__":
+    sys.exit(main())
#31 lore raw

Re: [RFC PATCH v1 09/43] helper-to-tcg: Introduce get-llvm-ir.py

Quoted 6 lines · Richard Henderson
Quoted 5 lines · Anton Johansson

Introduces a new python helper script to convert a set of QEMU .c files to LLVM IR .ll using clang. Compile flags are found by looking at compile_commands.json, and llvm-link is used to link together all LLVM modules into a single module.

Quoted 7 lines
Quoted 5 lines
---
  subprojects/helper-to-tcg/get-llvm-ir.py | 143 +++++++++++++++++++++++
  1 file changed, 143 insertions(+)

create mode 100755 subprojects/helper-to-tcg/get-llvm-ir.py

Is this not something that can be done in meson?

Possibly, I'll look into it, not sure it would be simpler though.

//Anton

#32 lore raw

RFC PATCH 10/43 helper-to-tcg: Add meson.build

In reply to Anton Johansson via

Sets up a barebones meson.build that handles:

1. Exposing command for converting .c files to LLVM IR by looking at

     compile_commads.json;

2. Finding LLVM and verifying the LLVM version manually by running llvm-config, needed for dealing with multiple LLVM versions in a sane way;

3. Building of helper-to-tcg.

A meson option is added to specify the path to llvm-config.

---
 subprojects/helper-to-tcg/meson.build       | 70 +++++++++++++++++++++
 subprojects/helper-to-tcg/meson_options.txt |  2 +
 2 files changed, 72 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/meson.build
 create mode 100644 subprojects/helper-to-tcg/meson_options.txt
subprojects/helper-to-tcg/meson.build new file +70 -0
new file mode 100644
index 0000000000..af593ccdfe
@@ -0,0 +1,70 @@
+##
+##  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+##
+##  This program is free software; you can redistribute it and/or modify
+##  it under the terms of the GNU General Public License as published by
+##  the Free Software Foundation; either version 2 of the License, or
+##  (at your option) any later version.
+##
+##  This program is distributed in the hope that it will be useful,
+##  but WITHOUT ANY WARRANTY; without even the implied warranty of
+##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+##  GNU General Public License for more details.
+##
+##  You should have received a copy of the GNU General Public License
+##  along with this program; if not, see <http://www.gnu.org/licenses/>.
+##
+
+project('helper-to-tcg', ['cpp'],
+        meson_version: '>=0.63.0',
+        version: '0.7',
+        default_options: ['cpp_std=none', 'optimization=2'])
+
+python = import('python').find_installation()
+
+# Find LLVM using llvm-config manually.  Needed as meson struggles when multiple
+# versions of LLVM are installed on the same system (always returns the most
+# recent).
+llvm_config = get_option('llvm_config_path')
+cpp_args = [run_command(llvm_config, '--cxxflags').stdout().strip().split()]
+bindir = run_command(llvm_config, '--bindir').stdout().strip()
+ldflags = run_command(llvm_config, '--ldflags').stdout().strip().split()
+libs = run_command(llvm_config, '--libs').stdout().strip().split()
+syslibs = run_command(llvm_config, '--system-libs').stdout().strip().split()
+incdir = run_command(llvm_config, '--includedir').stdout().strip().split()
+version = run_command(llvm_config, '--version').stdout().strip()
+version_major = version.split('.')[0].to_int()
+
+# Check LLVM version manually
+if version_major < 10 or version_major > 14
+    error('LLVM version', version, 'not supported.')
+endif
+
+sources = [
+]
+
+clang = bindir / 'clang'
+llvm_link = bindir / 'llvm-link'
+
+get_llvm_ir_cmd = [python, meson.current_source_dir() / 'get-llvm-ir.py',
+                   '--compile-commands', 'compile_commands.json',
+                   '--clang', clang,
+                   '--llvm-link', llvm_link]
+
+# NOTE: Add -Wno-template-id-cdtor for GCC versions >= 14.  This warning is
+# related to a change in the C++ standard in C++20, that also applies to C++14
+# for some reason. See defect report DR2237 and commit
+#   https://gcc.gnu.org/git/gitweb.cgi?p=gcc.git;h=4b38d56dbac6742b038551a36ec80200313123a1
+# (temporary)
+compiler_info = meson.get_compiler('cpp')
+compiler = compiler_info.get_id()
+compiler_version = compiler_info.version().split('-').get(0)
+compiler_version_major = compiler_version.split('.').get(0)
+if compiler == 'gcc' and compiler_version_major.to_int() >= 14
+    cpp_args += ['-Wno-template-id-cdtor', '-Wno-missing-template-keyword']
+endif
+
+pipeline = executable('helper-to-tcg', sources,
+                      include_directories: ['passes', './', 'include'] + [incdir],
+                      link_args: [ldflags] + [libs] + [syslibs],
+                      cpp_args: cpp_args)
subprojects/helper-to-tcg/meson_options.txt new file +2 -0
new file mode 100644
index 0000000000..8a4b28a585
@@ -0,0 +1,2 @@
+option('llvm_config_path', type : 'string', value : 'llvm-config',
+       description: 'override default llvm-config used for finding LLVM')
Signature · 1 line
2.45.2
#33 lore raw

RFC PATCH 11/43 helper-to-tcg: Introduce llvm-compat

In reply to Anton Johansson via

Adds a translation unit with the sole purpose of handling inter-LLVM code changes. Instead of littering the code with #ifdefs, most of them will be limited to llvm-compat.[cpp|h] and a saner compat::*() function is exposed in its place.

---
 subprojects/helper-to-tcg/meson.build         |   1 +
 .../helper-to-tcg/passes/llvm-compat.cpp      | 162 ++++++++++++++++++
 .../helper-to-tcg/passes/llvm-compat.h        | 143 ++++++++++++++++
 3 files changed, 306 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/llvm-compat.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/llvm-compat.h
subprojects/helper-to-tcg/meson.build +1 -0
index af593ccdfe..7bb93ce005 100644
@@ -41,6 +41,7 @@ if version_major < 10 or version_major > 14
 endif
 
 sources = [
+    'passes/llvm-compat.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/llvm-compat.cpp new file +162 -0

162 lines not on this page · raw message

subprojects/helper-to-tcg/passes/llvm-compat.h new file +143 -0

143 lines not on this page · raw message

Signature · 1 line
2.45.2
#34 lore raw

RFC PATCH 12/43 helper-to-tcg: Introduce custom LLVM pipeline

In reply to Anton Johansson via

Adds a custom pipeline, similar to LLVM opt, with the goal of taking an input LLVM IR module to an equivalent output .c file implementing functions in TCG.

Initial LLVM boilerplate is added until the creation of a ModulePassManager. A custom target derived from x64 is added, to ensure consistent behaviour across different hosts.

---
 .../helper-to-tcg/include/CmdLineOptions.h    |  23 +++
 subprojects/helper-to-tcg/meson.build         |   1 +
 .../helper-to-tcg/pipeline/Pipeline.cpp       | 159 ++++++++++++++++++
 3 files changed, 183 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/include/CmdLineOptions.h
 create mode 100644 subprojects/helper-to-tcg/pipeline/Pipeline.cpp
subprojects/helper-to-tcg/include/CmdLineOptions.h new file +23 -0
new file mode 100644
index 0000000000..5774ab07b1
@@ -0,0 +1,23 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+#include <llvm/Support/CommandLine.h>
+
+// Options for pipeline
+extern llvm::cl::list<std::string> InputFiles;
subprojects/helper-to-tcg/meson.build +1 -0
index 7bb93ce005..63c6ed17fb 100644
@@ -41,6 +41,7 @@ if version_major < 10 or version_major > 14
 endif
 
 sources = [
+    'pipeline/Pipeline.cpp',
     'passes/llvm-compat.cpp',
 ]
 
subprojects/helper-to-tcg/pipeline/Pipeline.cpp new file +159 -0

159 lines not on this page · raw message

Signature · 1 line
2.45.2
#35 lore raw

RFC PATCH 13/43 helper-to-tcg: Introduce Error.h

In reply to Anton Johansson via

Simple function for creating Expected<> with nice error messages.

---
 subprojects/helper-to-tcg/include/Error.h | 40 +++++++++++++++++++++++
 1 file changed, 40 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/include/Error.h
subprojects/helper-to-tcg/include/Error.h new file +40 -0
new file mode 100644
index 0000000000..10205e29a6
@@ -0,0 +1,40 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+#include <llvm/Support/Error.h>
+#include <llvm/IR/Value.h>
+#include <llvm/IR/ModuleSlotTracker.h>
+
+inline llvm::Error mkError(const llvm::StringRef Msg)
+{
+    return llvm::createStringError(llvm::inconvertibleErrorCode(), Msg);
+}
+
+// TODO: Usage of mkError and dbgs() for serializing Values is __really__ slow,
+// and should only occur for error reporting.  Wrap these in a class with a
+// ModuleSlotTracker.
+inline llvm::Error mkError(const llvm::StringRef Msg, const llvm::Value *V)
+{
+    std::string Str;
+    llvm::raw_string_ostream Stream(Str);
+    Stream << Msg;
+    Stream << *V;
+    Stream.flush();
+    return llvm::createStringError(llvm::inconvertibleErrorCode(), Str);
+}
Signature · 1 line
2.45.2
#36 lore raw

RFC PATCH 14/43 helper-to-tcg: Introduce PrepareForOptPass

In reply to Anton Johansson via

Adds a new LLVM pass that runs early in the pipeline with the goal of preparing the input module for optimization by doing some early culling of functions and information gathering.

This commits sets up a new LLVM pass over the IR module and runs it from the pipeline.

---
 .../helper-to-tcg/include/CmdLineOptions.h    |  2 ++
 .../helper-to-tcg/include/PrepareForOptPass.h | 34 +++++++++++++++++++
 subprojects/helper-to-tcg/meson.build         |  2 ++
 .../PrepareForOptPass/PrepareForOptPass.cpp   | 25 ++++++++++++++
 .../helper-to-tcg/pipeline/Pipeline.cpp       | 27 +++++++++++++++
 5 files changed, 90 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/include/PrepareForOptPass.h
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp
subprojects/helper-to-tcg/include/CmdLineOptions.h +2 -0
index 5774ab07b1..ed60c45f9a 100644
@@ -21,3 +21,5 @@
 
 // Options for pipeline
 extern llvm::cl::list<std::string> InputFiles;
+// Options for PrepareForOptPass
+extern llvm::cl::opt<bool> TranslateAllHelpers;
subprojects/helper-to-tcg/include/PrepareForOptPass.h new file +34 -0
new file mode 100644
index 0000000000..d74618613f
@@ -0,0 +1,34 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+#include <llvm/IR/PassManager.h>
+
+//
+// PrepareForOptPass
+//
+// Pass that performs either early information collection or basic culling of
+// the input module. simplify the module, or to allow for further optimization.
+//
+
+class PrepareForOptPass : public llvm::PassInfoMixin<PrepareForOptPass> {
+public:
+    PrepareForOptPass() {}
+    llvm::PreservedAnalyses run(llvm::Module &M,
+                                llvm::ModuleAnalysisManager &MAM);
+};
subprojects/helper-to-tcg/meson.build +2 -0
index 63c6ed17fb..fd3fd6f0ae 100644
@@ -43,6 +43,8 @@ endif
 sources = [
     'pipeline/Pipeline.cpp',
     'passes/llvm-compat.cpp',
+    'pipeline/Pipeline.cpp',
+    'passes/PrepareForOptPass/PrepareForOptPass.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp new file +25 -0
new file mode 100644
index 0000000000..0a018494fe
@@ -0,0 +1,25 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <PrepareForOptPass.h>
+
+using namespace llvm;
+
+PreservedAnalyses PrepareForOptPass::run(Module &M, ModuleAnalysisManager &MAM)
+{
+    return PreservedAnalyses::none();
+}
subprojects/helper-to-tcg/pipeline/Pipeline.cpp +27 -0
index 9c0e777893..fad335f4a9 100644
@@ -34,7 +34,9 @@
 #include <llvm/Support/SourceMgr.h>
 #include <llvm/Support/TargetSelect.h>
 #include <llvm/Target/TargetMachine.h>
+#include <llvm/Transforms/Scalar/SROA.h>
 
+#include <PrepareForOptPass.h>
 #include "llvm-compat.h"
 
 using namespace llvm;
@@ -155,5 +157,30 @@ int main(int argc, char **argv)
 
     ModulePassManager MPM;
 
+    //
+    // Start by Filtering out functions we don't want to translate,
+    // following by a pass that removes `noinline`s that are inserted
+    // by clang on -O0. We finally run a UnifyExitNodesPass to make sure
+    // the helpers we parse only has a single exit.
+    //
+
+    {
+        FunctionPassManager FPM;
+#if LLVM_VERSION_MAJOR < 14
+        FPM.addPass(SROA());
+#else
+        FPM.addPass(SROAPass());
+#endif
+        MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
+    }
+
+    MPM.addPass(PrepareForOptPass());
+
+    {
+        FunctionPassManager FPM;
+        FPM.addPass(compat::UnifyFunctionExitNodesPass());
+        MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
+    }
+
     return 0;
 }
Signature · 1 line
2.45.2
#37 lore raw

RFC PATCH 15/43 helper-to-tcg: PrepareForOptPass, map annotations

In reply to Anton Johansson via

In the LLVM IR module function annotations are stored in one big global array of strings. Traverse this array and parse the data into a format more useful for future passes. A map between Functions * and a list of annotations is exposed.

---
 .../include/FunctionAnnotation.h              | 54 ++++++++++++
 .../helper-to-tcg/include/PrepareForOptPass.h |  7 +-
 .../PrepareForOptPass/PrepareForOptPass.cpp   | 87 +++++++++++++++++++
 .../helper-to-tcg/pipeline/Pipeline.cpp       |  3 +-
 4 files changed, 149 insertions(+), 2 deletions(-)
 create mode 100644 subprojects/helper-to-tcg/include/FunctionAnnotation.h
subprojects/helper-to-tcg/include/FunctionAnnotation.h new file +54 -0
new file mode 100644
index 0000000000..b562f7c892
@@ -0,0 +1,54 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+#include <llvm/ADT/DenseMap.h>
+#include <llvm/ADT/SmallVector.h>
+#include <stdint.h>
+
+namespace llvm
+{
+class Function;
+}
+
+// Different kind of function annotations which control the behaviour
+// of helper-to-tcg.
+enum class AnnotationKind : uint8_t {
+    // Function should be translated
+    HelperToTcg,
+    // Declares a list of arguments as immediates
+    Immediate,
+    // Declares a list of arguments as vectors, represented by offsets into
+    // the CPU state
+    PtrToOffset,
+};
+
+// Annotation data which may be attached to a function
+struct Annotation {
+    // Indices of function arguments the annotation applies to, only
+    // used for AnnotationKind::[Immediate|PtrToOffset].
+    llvm::SmallVector<uint8_t, 4> ArgIndices;
+    AnnotationKind Kind;
+};
+
+// Map from Function * to a list of struct Annotation.  std::map is used here
+// which allocates for each mapped pair due to the value being large
+// (at least 48*3 bits).  If ArgIndices were to be stored out-of-band this could
+// be reduced, and DenseMap would be more appropriate.
+using AnnotationVectorTy = llvm::SmallVector<Annotation, 3>;
+using AnnotationMapTy = llvm::DenseMap<llvm::Function *, AnnotationVectorTy>;
subprojects/helper-to-tcg/include/PrepareForOptPass.h +6 -1
index d74618613f..5f9c059b97 100644
@@ -17,6 +17,7 @@
 
 #pragma once
 
+#include "FunctionAnnotation.h"
 #include <llvm/IR/PassManager.h>
 
 //
@@ -27,8 +28,12 @@
 //
 
 class PrepareForOptPass : public llvm::PassInfoMixin<PrepareForOptPass> {
+    AnnotationMapTy &ResultAnnotations;
 public:
-    PrepareForOptPass() {}
+    PrepareForOptPass(AnnotationMapTy &ResultAnnotations)
+        : ResultAnnotations(ResultAnnotations)
+    {
+    }
     llvm::PreservedAnalyses run(llvm::Module &M,
                                 llvm::ModuleAnalysisManager &MAM);
 };
subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp +87 -0

97 lines not on this page · raw message

subprojects/helper-to-tcg/pipeline/Pipeline.cpp +2 -1
index fad335f4a9..3b9493bc73 100644
@@ -174,7 +174,8 @@ int main(int argc, char **argv)
         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
     }
 
-    MPM.addPass(PrepareForOptPass());
+    AnnotationMapTy Annotations;
+    MPM.addPass(PrepareForOptPass(Annotations));
 
     {
         FunctionPassManager FPM;
Signature · 1 line
2.45.2
#38 lore raw

RFC PATCH 16/43 helper-to-tcg: PrepareForOptPass, Cull unused functions

In reply to Anton Johansson via

Make an early pass over all functions in the input module and filter out functions with:
1. Invalid return type;
2. No helper-to-tcg annotation.

---
 .../helper-to-tcg/include/PrepareForOptPass.h |  7 +-
 .../PrepareForOptPass/PrepareForOptPass.cpp   | 93 +++++++++++++++++++
 .../helper-to-tcg/pipeline/Pipeline.cpp       |  7 +-
 3 files changed, 104 insertions(+), 3 deletions(-)
subprojects/helper-to-tcg/include/PrepareForOptPass.h +5 -2
index 5f9c059b97..8615625f09 100644
@@ -29,9 +29,12 @@
 
 class PrepareForOptPass : public llvm::PassInfoMixin<PrepareForOptPass> {
     AnnotationMapTy &ResultAnnotations;
+    bool TranslateAllHelpers;
 public:
-    PrepareForOptPass(AnnotationMapTy &ResultAnnotations)
-        : ResultAnnotations(ResultAnnotations)
+    PrepareForOptPass(AnnotationMapTy &ResultAnnotations,
+                      bool TranslateAllHelpers)
+        : ResultAnnotations(ResultAnnotations),
+          TranslateAllHelpers(TranslateAllHelpers)
     {
     }
     llvm::PreservedAnalyses run(llvm::Module &M,
subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp +93 -0

113 lines not on this page · raw message

subprojects/helper-to-tcg/pipeline/Pipeline.cpp +6 -1
index 3b9493bc73..dde3641ab3 100644
@@ -47,6 +47,11 @@ cl::OptionCategory Cat("helper-to-tcg Options");
 cl::opt<std::string> InputFile(cl::Positional, cl::desc("[input LLVM module]"),
                                cl::cat(Cat));
 
+// Options for PrepareForOptPass
+cl::opt<bool> TranslateAllHelpers(
+    "translate-all-helpers", cl::init(false),
+    cl::desc("Translate all functions starting with helper_*"), cl::cat(Cat));
+
 // Define a TargetTransformInfo (TTI) subclass, this allows for overriding
 // common per-llvm-target information expected by other LLVM passes, such
 // as the width of the largest scalar/vector registers.  Needed for consistent
@@ -175,7 +180,7 @@ int main(int argc, char **argv)
     }
 
     AnnotationMapTy Annotations;
-    MPM.addPass(PrepareForOptPass(Annotations));
+    MPM.addPass(PrepareForOptPass(Annotations, TranslateAllHelpers));
 
     {
         FunctionPassManager FPM;
Signature · 1 line
2.45.2
#39 lore raw

RFC PATCH 17/43 helper-to-tcg: PrepareForOptPass, undef llvm.returnaddress

In reply to Anton Johansson via

Convert llvm.returnaddress arguments to cpu_[ld|st]*() to undef, causing the LLVM optmizer to discard the intrinsics. Needed as llvm.returnadress is not representable in TCG, and usually results from usage of GETPC() in helper functions.

---
 .../PrepareForOptPass/PrepareForOptPass.cpp   | 48 +++++++++++++++++++
 1 file changed, 48 insertions(+)
subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp +48 -0
index 22509008c8..b357debb5d 100644
@@ -23,6 +23,7 @@
 #include <llvm/IR/Function.h>
 #include <llvm/IR/Instruction.h>
 #include <llvm/IR/Instructions.h>
+#include <llvm/IR/Intrinsics.h>
 #include <llvm/IR/Module.h>
 
 #include <queue>
@@ -197,9 +198,56 @@ static void cullUnusedFunctions(Module &M, AnnotationMapTy &Annotations,
     }
 }
 
+struct RetAddrReplaceInfo {
+    User *Parent;
+    unsigned OpIndex;
+    Type *Ty;
+};
+
+static void replaceRetaddrWithUndef(Module &M)
+{
+    // Replace uses of llvm.returnaddress arguments to cpu_ld* w. undef,
+    // and let optimizations remove it.  Needed as llvm.returnaddress is
+    // not reprensentable in TCG.
+    SmallVector<RetAddrReplaceInfo, 24> UsesToReplace;
+    Function *Retaddr = Intrinsic::getDeclaration(&M, Intrinsic::returnaddress);
+    // Loop over all calls to llvm.returnaddress
+    for (auto *CallUser : Retaddr->users()) {
+        auto *Call = dyn_cast<CallInst>(CallUser);
+        if (!Call) {
+            continue;
+        }
+        for (auto *PtrToIntUser : Call->users()) {
+            auto *Cast = dyn_cast<PtrToIntInst>(PtrToIntUser);
+            if (!Cast) {
+                continue;
+            }
+            for (Use &U : Cast->uses()) {
+                auto *Call = dyn_cast<CallInst>(U.getUser());
+                Function *F = Call->getCalledFunction();
+                StringRef Name = F->getName();
+                if (Name.startswith("cpu_ld") or Name.startswith("cpu_st")) {
+                    UsesToReplace.push_back({
+                        .Parent = U.getUser(),
+                        .OpIndex = U.getOperandNo(),
+                        .Ty = U->getType(),
+                    });
+                }
+            }
+        }
+    }
+
+    // Defer replacement to not invalidate iterators
+    for (RetAddrReplaceInfo &RI : UsesToReplace) {
+        auto *Undef = UndefValue::get(RI.Ty);
+        RI.Parent->setOperand(RI.OpIndex, Undef);
+    }
+}
+
 PreservedAnalyses PrepareForOptPass::run(Module &M, ModuleAnalysisManager &MAM)
 {
     collectAnnotations(M, ResultAnnotations);
     cullUnusedFunctions(M, ResultAnnotations, TranslateAllHelpers);
+    replaceRetaddrWithUndef(M);
     return PreservedAnalyses::none();
 }
Signature · 1 line
2.45.2
#40 lore raw

RFC PATCH 18/43 helper-to-tcg: PrepareForOptPass, Remove noinline attribute

In reply to Anton Johansson via

When producing LLVM IR using clang -O0, a noinline attribute is added. Remove this attribute to not inhibit future optimization.

---
 .../passes/PrepareForOptPass/PrepareForOptPass.cpp         | 7 +++++++
 1 file changed, 7 insertions(+)
subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp +7 -0
index b357debb5d..cfd1c23c24 100644
@@ -25,6 +25,7 @@
 #include <llvm/IR/Instructions.h>
 #include <llvm/IR/Intrinsics.h>
 #include <llvm/IR/Module.h>
+#include <llvm/Transforms/Utils/Local.h>
 
 #include <queue>
 #include <set>
@@ -249,5 +250,11 @@ PreservedAnalyses PrepareForOptPass::run(Module &M, ModuleAnalysisManager &MAM)
     collectAnnotations(M, ResultAnnotations);
     cullUnusedFunctions(M, ResultAnnotations, TranslateAllHelpers);
     replaceRetaddrWithUndef(M);
+    // Remove noinline function attributes automatically added by -O0
+    for (Function &F : M) {
+        if (F.hasFnAttribute(Attribute::AttrKind::NoInline)) {
+            F.removeFnAttr(Attribute::AttrKind::NoInline);
+        }
+    }
     return PreservedAnalyses::none();
 }
Signature · 1 line
2.45.2
#41 lore raw

RFC PATCH 19/43 helper-to-tcg: Pipeline, run optimization pass

In reply to Anton Johansson via

Run a standard LLVM -Os optimization pass, which makes up the bulk of optimizations in helper-to-tcg.

---
 subprojects/helper-to-tcg/pipeline/Pipeline.cpp | 12 ++++++++++++
 1 file changed, 12 insertions(+)
subprojects/helper-to-tcg/pipeline/Pipeline.cpp +12 -0
index dde3641ab3..a26b7a7350 100644
@@ -188,5 +188,17 @@ int main(int argc, char **argv)
         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
     }
 
+    //
+    // Run a -Os optimization pass.  In general -Os will prefer loop
+    // vectorization over unrolling, as compared to -O3.  In TCG, this
+    // translates to more utilization of gvec and possibly smaller TBs.
+    //
+
+    // Optimization passes
+    MPM.addPass(PB.buildModuleSimplificationPipeline(
+        compat::OptimizationLevel::Os, compat::LTOPhase));
+    MPM.addPass(
+        PB.buildModuleOptimizationPipeline(compat::OptimizationLevel::Os));
+
     return 0;
 }
Signature · 1 line
2.45.2
#42 lore raw

RFC PATCH 20/43 helper-to-tcg: Introduce pseudo instructions

In reply to Anton Johansson via

"pseudo" instructions makes it easy to add custom instructions to LLVM IR in the form of calls to undefined functions. These will be used in future commits to express functionality present in TCG that is missing from LLVM IR (certain vector ops.), or to simplify the backend by collecting similar instruction mappings into a single opcode (idendity mapping).

Mapping from a call instructions in LLVM IR to an enum representing the pseudo instruction is also handled, this avoids string comparisons in the backend, and is easy to switch over.

---
 subprojects/helper-to-tcg/meson.build         |   1 +
 .../helper-to-tcg/passes/PseudoInst.cpp       | 142 ++++++++++++++++++
 subprojects/helper-to-tcg/passes/PseudoInst.h |  63 ++++++++
 .../helper-to-tcg/passes/PseudoInst.inc       |  76 ++++++++++
 4 files changed, 282 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.h
 create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.inc
subprojects/helper-to-tcg/meson.build +1 -0
index fd3fd6f0ae..6aba71d5ca 100644
@@ -45,6 +45,7 @@ sources = [
     'passes/llvm-compat.cpp',
     'pipeline/Pipeline.cpp',
     'passes/PrepareForOptPass/PrepareForOptPass.cpp',
+    'passes/PseudoInst.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/PseudoInst.cpp new file +142 -0

142 lines not on this page · raw message

subprojects/helper-to-tcg/passes/PseudoInst.h new file +63 -0

63 lines not on this page · raw message

subprojects/helper-to-tcg/passes/PseudoInst.inc new file +76 -0

76 lines not on this page · raw message

Signature · 1 line
2.45.2
#43 lore raw

RFC PATCH 21/43 helper-to-tcg: Introduce PrepareForTcgPass

In reply to Anton Johansson via

Adds a new pass over the LLVM module which runs post-optimization with the end-goal of:
* culling functions which aren't worth translating;
* canonicalizing the IR to something closer to TCG, and;
* extracting information which may be useful in the backend pass.

This commits sets up a new LLVM pass over the IR module and runs it from the pipeline.

---
 .../helper-to-tcg/include/CmdLineOptions.h    |  2 ++
 .../helper-to-tcg/include/PrepareForTcgPass.h | 27 +++++++++++++++++++
 subprojects/helper-to-tcg/meson.build         |  1 +
 .../PrepareForTcgPass/PrepareForTcgPass.cpp   | 25 +++++++++++++++++
 .../helper-to-tcg/pipeline/Pipeline.cpp       | 26 +++++++++++++++++-
 5 files changed, 80 insertions(+), 1 deletion(-)
 create mode 100644 subprojects/helper-to-tcg/include/PrepareForTcgPass.h
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp
subprojects/helper-to-tcg/include/CmdLineOptions.h +2 -0
index ed60c45f9a..9553e26407 100644
@@ -23,3 +23,5 @@
 extern llvm::cl::list<std::string> InputFiles;
 // Options for PrepareForOptPass
 extern llvm::cl::opt<bool> TranslateAllHelpers;
+// Options for PrepareForTcgPass
+extern llvm::cl::opt<std::string> TcgGlobalMappingsName;
subprojects/helper-to-tcg/include/PrepareForTcgPass.h new file +27 -0
new file mode 100644
index 0000000000..a41edb4c2e
@@ -0,0 +1,27 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+#include <llvm/IR/PassManager.h>
+
+class PrepareForTcgPass : public llvm::PassInfoMixin<PrepareForTcgPass> {
+public:
+    PrepareForTcgPass() {}
+    llvm::PreservedAnalyses run(llvm::Module &M,
+                                llvm::ModuleAnalysisManager &MAM);
+};
subprojects/helper-to-tcg/meson.build +1 -0
index 6aba71d5ca..6db1a019ce 100644
@@ -46,6 +46,7 @@ sources = [
     'pipeline/Pipeline.cpp',
     'passes/PrepareForOptPass/PrepareForOptPass.cpp',
     'passes/PseudoInst.cpp',
+    'passes/PrepareForTcgPass/PrepareForTcgPass.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp new file +25 -0
new file mode 100644
index 0000000000..f0ef1abd17
@@ -0,0 +1,25 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <PrepareForTcgPass.h>
+
+using namespace llvm;
+
+PreservedAnalyses PrepareForTcgPass::run(Module &M, ModuleAnalysisManager &MAM)
+{
+    return PreservedAnalyses::none();
+}
subprojects/helper-to-tcg/pipeline/Pipeline.cpp +25 -1
index a26b7a7350..7d03389439 100644
@@ -24,6 +24,7 @@
 #include <llvm/IR/LLVMContext.h>
 #include <llvm/IR/Module.h>
 #include <llvm/IR/PassManager.h>
+#include <llvm/IR/Verifier.h>
 #include <llvm/IRReader/IRReader.h>
 #include <llvm/InitializePasses.h>
 #include <llvm/Linker/Linker.h>
@@ -34,10 +35,12 @@
 #include <llvm/Support/SourceMgr.h>
 #include <llvm/Support/TargetSelect.h>
 #include <llvm/Target/TargetMachine.h>
+#include <llvm/Transforms/Scalar/DCE.h>
 #include <llvm/Transforms/Scalar/SROA.h>
 
 #include <PrepareForOptPass.h>
-#include "llvm-compat.h"
+#include <PrepareForTcgPass.h>
+#include <llvm-compat.h>
 
 using namespace llvm;
 
@@ -52,6 +55,13 @@ cl::opt<bool> TranslateAllHelpers(
     "translate-all-helpers", cl::init(false),
     cl::desc("Translate all functions starting with helper_*"), cl::cat(Cat));
 
+// Options for PrepareForTcgPass
+cl::opt<std::string> TcgGlobalMappingsName(
+    "tcg-global-mappings",
+    cl::desc("<Name of global cpu_mappings[] used for mapping accesses"
+             "into a struct to TCG globals>"),
+    cl::Required, cl::cat(Cat));
+
 // Define a TargetTransformInfo (TTI) subclass, this allows for overriding
 // common per-llvm-target information expected by other LLVM passes, such
 // as the width of the largest scalar/vector registers.  Needed for consistent
@@ -200,5 +210,19 @@ int main(int argc, char **argv)
     MPM.addPass(
         PB.buildModuleOptimizationPipeline(compat::OptimizationLevel::Os));
 
+    //
+    // Next, we run our final transformations, including removing phis and our
+    // own instruction combining that prioritizes instructions that map more
+    // easily to TCG.
+    //
+
+    MPM.addPass(PrepareForTcgPass());
+    MPM.addPass(VerifierPass());
+    {
+        FunctionPassManager FPM;
+        FPM.addPass(DCEPass());
+        MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
+    }
+
     return 0;
 }
Signature · 1 line
2.45.2
#44 lore raw

RFC PATCH 22/43 helper-to-tcg: PrepareForTcgPass, remove functions w. cycles

In reply to Anton Johansson via

Functions with cycles are removed for two primary reasons:

* as a simplifying assumption for register allocation which occurs down

    the line, and;

* if a function contains cycles post-optimization neither unrolling or loop vectorization were beneficial, and the function _might_ be better suited as a helper anyway.

Cycles are detected by iterating over Strongly Connected Components (SCCs) which imply the existence of cycles if:
- a SCC contains more than one node, or;
- it has a self-edge.

---
 .../PrepareForTcgPass/PrepareForTcgPass.cpp   | 32 +++++++++++++++++++
 1 file changed, 32 insertions(+)
subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp +32 -0
index f0ef1abd17..ccbe3820a0 100644
@@ -16,10 +16,42 @@
 //
 
 #include <PrepareForTcgPass.h>
+#include <llvm/ADT/SCCIterator.h>
+#include <llvm/IR/Function.h>
+#include <llvm/IR/Module.h>
 
 using namespace llvm;
 
+static void removeFunctionsWithLoops(Module &M, ModuleAnalysisManager &MAM)
+{
+    // Iterate over all Strongly Connected Components (SCCs), a SCC implies
+    // the existence of loops if:
+    //   - it has more than one node, or;
+    //   - it has a self-edge.
+    SmallVector<Function *, 16> FunctionsToRemove;
+    for (Function &F : M) {
+        if (F.isDeclaration()) {
+            continue;
+        }
+        for (auto It = scc_begin(&F); !It.isAtEnd(); ++It) {
+#if LLVM_VERSION_MAJOR > 10
+            if (It.hasCycle()) {
+#else
+            if (It.hasLoop()) {
+#endif
+                FunctionsToRemove.push_back(&F);
+                break;
+            }
+        }
+    }
+
+    for (auto *F : FunctionsToRemove) {
+        F->deleteBody();
+    }
+}
+
 PreservedAnalyses PrepareForTcgPass::run(Module &M, ModuleAnalysisManager &MAM)
 {
+    removeFunctionsWithLoops(M, MAM);
     return PreservedAnalyses::none();
 }
Signature · 1 line
2.45.2
#45 lore raw

RFC PATCH 23/43 helper-to-tcg: PrepareForTcgPass, demote phi nodes

In reply to Anton Johansson via

PHI nodes have no clear analogue in TCG, this commits converts them to stack accesses using a built-in LLVM transformation.

---
 .../PrepareForTcgPass/PrepareForTcgPass.cpp   | 24 +++++++++++++++++++
 1 file changed, 24 insertions(+)
subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp +24 -0
index ccbe3820a0..a2808eafed 100644
@@ -18,7 +18,10 @@
 #include <PrepareForTcgPass.h>
 #include <llvm/ADT/SCCIterator.h>
 #include <llvm/IR/Function.h>
+#include <llvm/IR/InstIterator.h>
+#include <llvm/IR/Instructions.h>
 #include <llvm/IR/Module.h>
+#include <llvm/Transforms/Utils/Local.h>
 
 using namespace llvm;
 
@@ -50,8 +53,29 @@ static void removeFunctionsWithLoops(Module &M, ModuleAnalysisManager &MAM)
     }
 }
 
+inline void demotePhis(Function &F)
+{
+    if (F.isDeclaration()) {
+        return;
+    }
+
+    SmallVector<PHINode *, 10> Phis;
+    for (auto &I : instructions(F)) {
+        if (auto *Phi = dyn_cast<PHINode>(&I)) {
+            Phis.push_back(Phi);
+        }
+    }
+
+    for (auto *Phi : Phis) {
+        DemotePHIToStack(Phi);
+    }
+}
+
 PreservedAnalyses PrepareForTcgPass::run(Module &M, ModuleAnalysisManager &MAM)
 {
     removeFunctionsWithLoops(M, MAM);
+    for (Function &F : M) {
+        demotePhis(F);
+    }
     return PreservedAnalyses::none();
 }
Signature · 1 line
2.45.2
#46 lore raw

RFC PATCH 24/43 helper-to-tcg: PrepareForTcgPass, map TCG globals

In reply to Anton Johansson via

The input LLVM module may define an array of cpu_mapping structs, describing the mapping between fields in a specified struct (usually CPUArchState) and TCG globals.

Create a map between offsets into the specified struct and TCG globals (name, size, number of elements, stride) by iterating over the global cpu_mapping array. The name of this array is configurable via the --tcg-global-mappings flag.

---
 .../helper-to-tcg/include/PrepareForTcgPass.h |  7 ++-
 .../helper-to-tcg/include/TcgGlobalMap.h      | 31 +++++++++++++
 .../PrepareForTcgPass/PrepareForTcgPass.cpp   | 43 +++++++++++++++++++
 .../helper-to-tcg/pipeline/Pipeline.cpp       |  9 ++--
 4 files changed, 85 insertions(+), 5 deletions(-)
 create mode 100644 subprojects/helper-to-tcg/include/TcgGlobalMap.h
subprojects/helper-to-tcg/include/PrepareForTcgPass.h +6 -1
index a41edb4c2e..a731c70b4b 100644
@@ -17,11 +17,16 @@
 
 #pragma once
 
+#include "TcgGlobalMap.h"
 #include <llvm/IR/PassManager.h>
 
 class PrepareForTcgPass : public llvm::PassInfoMixin<PrepareForTcgPass> {
+    TcgGlobalMap &ResultTcgGlobalMap;
 public:
-    PrepareForTcgPass() {}
+    PrepareForTcgPass(TcgGlobalMap &ResultTcgGlobalMap)
+        : ResultTcgGlobalMap(ResultTcgGlobalMap)
+    {
+    }
     llvm::PreservedAnalyses run(llvm::Module &M,
                                 llvm::ModuleAnalysisManager &MAM);
 };
subprojects/helper-to-tcg/include/TcgGlobalMap.h new file +31 -0
new file mode 100644
index 0000000000..7186d805ba
@@ -0,0 +1,31 @@
+#pragma once
+
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <llvm/ADT/StringRef.h>
+#include <llvm/ADT/DenseMap.h>
+#include <stdint.h>
+
+struct TcgGlobal {
+  llvm::StringRef Code;
+  uint64_t Size;
+  uint64_t NumElements;
+  uint64_t Stride;
+};
+
+using TcgGlobalMap = llvm::DenseMap<uint32_t, TcgGlobal>;
subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp +43 -0

60 lines not on this page · raw message

subprojects/helper-to-tcg/pipeline/Pipeline.cpp +5 -4
index 7d03389439..a8df592af3 100644
@@ -58,9 +58,9 @@ cl::opt<bool> TranslateAllHelpers(
 // Options for PrepareForTcgPass
 cl::opt<std::string> TcgGlobalMappingsName(
     "tcg-global-mappings",
-    cl::desc("<Name of global cpu_mappings[] used for mapping accesses"
-             "into a struct to TCG globals>"),
-    cl::Required, cl::cat(Cat));
+    cl::desc("Name of global cpu_mappings[] used for mapping accesses"
+             "into a struct to TCG globals"),
+    cl::init("mappings"), cl::cat(Cat));
 
 // Define a TargetTransformInfo (TTI) subclass, this allows for overriding
 // common per-llvm-target information expected by other LLVM passes, such
@@ -216,7 +216,8 @@ int main(int argc, char **argv)
     // easily to TCG.
     //
 
-    MPM.addPass(PrepareForTcgPass());
+    TcgGlobalMap TcgGlobals;
+    MPM.addPass(PrepareForTcgPass(TcgGlobals));
     MPM.addPass(VerifierPass());
     {
         FunctionPassManager FPM;
Signature · 1 line
2.45.2
#47 lore raw

RFC PATCH 25/43 helper-to-tcg: PrepareForTcgPass, transform GEPs

In reply to Anton Johansson via

getelementpointer (GEP) instructions in LLVM IR represent general pointer arithmetic (struct field access, array indexing, ...). From the perspective of TCG, three distinct cases are important and are transformed into pseudo instructions respectively:

* struct accesses whose offset into the struct map to a TCG global are

    transformed into "call @AccessGlobalValue(offset)";

* struct accesses whose offset into the struct map to an array of TCG

    globals are transformed into "call @AccessGlobalArray(offset, index)";

* otherwise converted to general pointer arithmetic in LLVM IR using

    "call @PtrAdd(...)".

These three cases are treated differently in the backend and all other GEPs are considered an error.

---
 subprojects/helper-to-tcg/meson.build         |   1 +
 .../PrepareForTcgPass/PrepareForTcgPass.cpp   |   4 +
 .../PrepareForTcgPass/TransformGEPs.cpp       | 286 ++++++++++++++++++
 .../passes/PrepareForTcgPass/TransformGEPs.h  |  37 +++
 4 files changed, 328 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.h
subprojects/helper-to-tcg/meson.build +1 -0
index 6db1a019ce..6b18734bad 100644
@@ -47,6 +47,7 @@ sources = [
     'passes/PrepareForOptPass/PrepareForOptPass.cpp',
     'passes/PseudoInst.cpp',
     'passes/PrepareForTcgPass/PrepareForTcgPass.cpp',
+    'passes/PrepareForTcgPass/TransformGEPs.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp +4 -0
index a453aa8558..b1e2932750 100644
@@ -17,6 +17,7 @@
 
 #include <CmdLineOptions.h>
 #include <PrepareForTcgPass.h>
+#include "TransformGEPs.h"
 #include <llvm/ADT/SCCIterator.h>
 #include <llvm/IR/Function.h>
 #include <llvm/IR/InstIterator.h>
@@ -120,5 +121,8 @@ PreservedAnalyses PrepareForTcgPass::run(Module &M, ModuleAnalysisManager &MAM)
         demotePhis(F);
     }
     collectTcgGlobals(M, ResultTcgGlobalMap);
+    for (Function &F : M) {
+        transformGEPs(M, F, ResultTcgGlobalMap);
+    }
     return PreservedAnalyses::none();
 }
subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.cpp new file +286 -0

286 lines not on this page · raw message

subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.h new file +37 -0
new file mode 100644
index 0000000000..11ac9c7e9b
@@ -0,0 +1,37 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+#include "TcgGlobalMap.h"
+#include <llvm/IR/Function.h>
+#include <llvm/IR/Module.h>
+
+//
+// Transform of module that converts getelementptr (GEP) operators to
+// pseudo instructions:
+//   - call @AccessGlobalArray(OffsetInEnv, Index)
+//     if OffsetInEnv is mapped to a global TCGv array.
+//
+//   - call @AccessGlobalValue(OffsetInEnv)
+//     if OffsetInEnv is mapped to a global TCGv value.
+//
+//   - pointer math, if above fails.
+//
+
+void transformGEPs(llvm::Module &M, llvm::Function &F,
+                   const TcgGlobalMap &TcgGlobals);
Signature · 1 line
2.45.2
#48 lore raw

RFC PATCH 26/43 helper-to-tcg: PrepareForTcgPass, canonicalize IR

In reply to Anton Johansson via

Iterates over the IR with the goal of converting it to a form closer to TCG, taking care of IR disparencies between LLVM and TCG. This also simplifies the backend by containing the bulk of custom IR transformations, meaning the backend can be as dumb as possible.

---
 subprojects/helper-to-tcg/meson.build         |    1 +
 .../PrepareForTcgPass/CanonicalizeIR.cpp      | 1000 +++++++++++++++++
 .../passes/PrepareForTcgPass/CanonicalizeIR.h |   25 +
 .../PrepareForTcgPass/PrepareForTcgPass.cpp   |    2 +
 4 files changed, 1028 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.h
subprojects/helper-to-tcg/meson.build +1 -0
index 6b18734bad..50bb926f49 100644
@@ -48,6 +48,7 @@ sources = [
     'passes/PseudoInst.cpp',
     'passes/PrepareForTcgPass/PrepareForTcgPass.cpp',
     'passes/PrepareForTcgPass/TransformGEPs.cpp',
+    'passes/PrepareForTcgPass/CanonicalizeIR.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.cpp new file +1000 -0

1,000 lines not on this page · raw message

subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.h new file +25 -0
new file mode 100644
index 0000000000..441200606d
@@ -0,0 +1,25 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+namespace llvm
+{
+class Module;
+}
+
+void canonicalizeIR(llvm::Module &M);
subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp +2 -0
index b1e2932750..7fdbc2a0c9 100644
@@ -15,6 +15,7 @@
 //  along with this program; if not, see <http://www.gnu.org/licenses/>.
 //
 
+#include "CanonicalizeIR.h"
 #include <CmdLineOptions.h>
 #include <PrepareForTcgPass.h>
 #include "TransformGEPs.h"
@@ -124,5 +125,6 @@ PreservedAnalyses PrepareForTcgPass::run(Module &M, ModuleAnalysisManager &MAM)
     for (Function &F : M) {
         transformGEPs(M, F, ResultTcgGlobalMap);
     }
+    canonicalizeIR(M);
     return PreservedAnalyses::none();
 }
Signature · 1 line
2.45.2
#49 lore raw

RFC PATCH 27/43 helper-to-tcg: PrepareForTcgPass, identity map trivial expressions

In reply to Anton Johansson via

Transformation of the IR, identity mapping trivial expressions which would amount to nothing more than a move when emitted as TCG, but is required in LLVM IR to not break the IR.

Trivial expressions are mapped to a @IdentityMap pseudo instruction allowing them to be dealt with in a uniform manner down the line.

---
 subprojects/helper-to-tcg/meson.build         |  1 +
 .../passes/PrepareForTcgPass/IdentityMap.cpp  | 80 +++++++++++++++++++
 .../passes/PrepareForTcgPass/IdentityMap.h    | 39 +++++++++
 .../PrepareForTcgPass/PrepareForTcgPass.cpp   |  4 +
 4 files changed, 124 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.h
subprojects/helper-to-tcg/meson.build +1 -0
index 50bb926f49..09caa74c63 100644
@@ -49,6 +49,7 @@ sources = [
     'passes/PrepareForTcgPass/PrepareForTcgPass.cpp',
     'passes/PrepareForTcgPass/TransformGEPs.cpp',
     'passes/PrepareForTcgPass/CanonicalizeIR.cpp',
+    'passes/PrepareForTcgPass/IdentityMap.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.cpp new file +80 -0

80 lines not on this page · raw message

subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.h new file +39 -0
new file mode 100644
index 0000000000..b0c938c25d
@@ -0,0 +1,39 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+#include <llvm/IR/Function.h>
+#include <llvm/IR/Module.h>
+
+//
+// Transformation of the IR, taking what would become trivial unary operations
+// and maps them to a single @IdentityMap pseudo instruction.
+//
+// To motivate further, in order to produce nice IR on the other end, generally
+// the operands of these trivial expressions needs to be forwarded and treated
+// as the destination value (identity mapped).  However, directly removing these
+// instructions will result in broken LLVM IR (consider zext i8, i32 where both
+// the source and destination would map to TCGv_i32).
+//
+// Moreover, handling these identity mapped values in an adhoc way quickly
+// becomes cumbersome and spreads throughout the codebase.  Therefore,
+// introducing @IdentityMap allows code further down the pipeline to ignore the
+// source of the identity map.
+//
+
+void identityMap(llvm::Module &M, llvm::Function &F);
subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp +4 -0
index 7fdbc2a0c9..3e4713d837 100644
@@ -17,6 +17,7 @@
 
 #include "CanonicalizeIR.h"
 #include <CmdLineOptions.h>
+#include "IdentityMap.h"
 #include <PrepareForTcgPass.h>
 #include "TransformGEPs.h"
 #include <llvm/ADT/SCCIterator.h>
@@ -126,5 +127,8 @@ PreservedAnalyses PrepareForTcgPass::run(Module &M, ModuleAnalysisManager &MAM)
         transformGEPs(M, F, ResultTcgGlobalMap);
     }
     canonicalizeIR(M);
+    for (Function &F : M) {
+        identityMap(M, F);
+    }
     return PreservedAnalyses::none();
 }
Signature · 1 line
2.45.2
#50 lore raw

RFC PATCH 28/43 helper-to-tcg: Introduce TcgType.h

In reply to Anton Johansson via

Adds a struct representing everything a LLVM value might map to in TCG, this includes:

* TCGv (IrValue);
* TCGv_ptr (IrPtr);
* TCGv_env (IrEnv);
* TCGLabel (IrLabel);
* tcg_constant_*() (IrConst);
* 123123ull (IrImmediate);
* intptr_t gvec_vector (IrPtrToOffset).

NOTE: Patch is subject to change due to rework of the TcgV type system. There is quite significant overlap in handling IrConst/IrImmediate and any other type with the ConstantExpression bool set. Space required for each TcgV can also be reduced by moving to a union.

---
 .../helper-to-tcg/passes/backend/TcgType.h    | 133 ++++++++++++++++++
 1 file changed, 133 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgType.h
subprojects/helper-to-tcg/passes/backend/TcgType.h new file +133 -0
new file mode 100644
index 0000000000..36ebdbe5cb
@@ -0,0 +1,133 @@
+//
+//  Copyright(c) 2024 rev.ng Labs Srl. All Rights Reserved.
+//
+//  This program is free software; you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation; either version 2 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program; if not, see <http://www.gnu.org/licenses/>.
+//
+
+#pragma once
+
+#include <llvm/ADT/Optional.h>
+#include <llvm/ADT/StringRef.h>
+
+#include <assert.h>
+#include <stdint.h>
+#include <string>
+
+enum TcgVKind : uint8_t {
+    IrValue,
+    IrConst,
+    IrEnv,
+    IrImmediate,
+    IrPtr,
+    IrPtrToOffset,
+    IrLabel,
+};
+
+// Counter incremented for every TcgV created, also used in the creation of
+// unique names (e.g. varr_10 for an array).
+extern uint32_t VarIndex;
+
+struct TcgV {
+    uint16_t Id;
+    std::string Name;
+
+    uint32_t TcgSize;
+    uint8_t LlvmSize;
+    uint8_t VectorElementCount;
+
+    TcgVKind Kind;
+
+    bool ConstantExpression = false;
+
+    static TcgV makeVector(uint32_t VectorWidthBits, uint32_t ElementWidthBits,
+                           uint32_t ElementCount)
+    {
+        return TcgV("", VectorWidthBits, ElementWidthBits, ElementCount,
+                    IrPtrToOffset);
+    }
+
+    static TcgV makeImmediate(llvm::StringRef Name, uint32_t TcgWidth,
+                              uint32_t LlvmWidth)
+    {
+        return TcgV(Name.str(), TcgWidth, LlvmWidth, 1, IrImmediate);
+    }
+
+    static TcgV makeTemp(uint32_t TcgWidth, uint32_t LlvmWidth, TcgVKind Kind)
+    {
+        return TcgV("", TcgWidth, LlvmWidth, 1, Kind);
+    }
+
+    static TcgV makeConstantExpression(llvm::StringRef Expression,
+                                       uint32_t TcgWidth, uint32_t LlvmWidth,
+                                       TcgVKind Kind)
+    {
+        TcgV Tcg(Expression.str(), TcgWidth, LlvmWidth, 1, Kind);
+        Tcg.ConstantExpression = true;
+        return Tcg;
+    }
+
+    static TcgV makeLabel() { return TcgV("", 32, 32, 1, IrLabel); }
+
+    TcgV(std::string Name, uint32_t TcgSize, uint32_t LlvmSize,
+         uint32_t VectorElementCount, TcgVKind Kind)
+        : Id(VarIndex++), Name(Name), TcgSize(TcgSize), LlvmSize(LlvmSize),
+          VectorElementCount(VectorElementCount), Kind(Kind)
+    {
+        assert(verifySize());
+    }
+
+    // We make the following assumptions about TcgSize and LLvmSize:
+    //   - TcgSize either 32- or 64-bit;
+    //   - LlvmSize either 1-,8-,16-,32-,64-,or 128-bit.
+    // We also assume that there are only these valid combinations of
+    // (TcgSize, LlvmSize):
+    //   - (64, 64) uint64_t
+    //   - (64, 1)  bool
+    //   - (32, 32) uint32_t
+    //   - (32, 16) uint16_t
+    //   - (32, 8)  uint8_t
+    //   - (32, 1)  bool
+    // So we try to fit the variables in the smallest possible TcgSize,
+    // with the exception of booleans which need to able to be 64-bit
+    // when dealing with conditions.
+    bool verifySize()
+    {
+        return (LlvmSize == 1 || LlvmSize == 8 || LlvmSize == 16 ||
+                LlvmSize == 32 || LlvmSize == 64) &&
+               (LlvmSize <= TcgSize);
+    }
+
+    bool operator==(const TcgV &Other) const { return Other.Id == Id; }
+    bool operator!=(const TcgV &Other) const { return !operator==(Other); }
+};
+
+inline uint64_t llvmToTcgSize(uint64_t LlvmSize)
+{
+    return (LlvmSize <= 32) ? 32 : 64;
+}
+
+inline uint32_t vectorSizeInBytes(const TcgV &Vec)
+{
+    assert(Vec.Kind == IrPtrToOffset);
+    return Vec.LlvmSize * Vec.VectorElementCount / 8;
+}
+
+struct TcgBinOp {
+    std::string Code;
+};
+
+struct TcgVecBinOp {
+    std::string Code;
+    llvm::Optional<uint32_t> RequiredOp2Size;
+};
Signature · 1 line
2.45.2
#51 lore raw

Re: [RFC PATCH v1 28/43] helper-to-tcg: Introduce TcgType.h

Quoted 10 lines · Anton Johansson via

Adds a struct representing everything a LLVM value might map to in TCG, this includes:

* TCGv (IrValue);
* TCGv_ptr (IrPtr);
* TCGv_env (IrEnv);
* TCGLabel (IrLabel);
* tcg_constant_*() (IrConst);
* 123123ull (IrImmediate);
* intptr_t gvec_vector (IrPtrToOffset).

Why would you map TCGv (the TARGET_LONG_BITS alias) rather than the base TCGv_i32 and TCGv_i64 types? This seems like it would be more natural within LLVM, and take advantage of whatever optimization that you're allowing LLVM to do.

r~

#52 lore raw

Re: [RFC PATCH v1 28/43] helper-to-tcg: Introduce TcgType.h

Quoted 12 lines · Richard Henderson
Quoted 10 lines · Anton Johansson via

Adds a struct representing everything a LLVM value might map to in TCG, this includes:

* TCGv (IrValue);
* TCGv_ptr (IrPtr);
* TCGv_env (IrEnv);
* TCGLabel (IrLabel);
* tcg_constant_*() (IrConst);
* 123123ull (IrImmediate);
* intptr_t gvec_vector (IrPtrToOffset).

Quoted 4 lines

Why would you map TCGv (the TARGET_LONG_BITS alias) rather than the base TCGv_i32 and TCGv_i64 types? This seems like it would be more natural within LLVM, and take advantage of whatever optimization that you're allowing LLVM to do.

No you are correct, we map

IrValue + 32-bit size -> TCGv_i32
IrValue + 64-bit size -> TCGv_i64

I was a bit vague in the commit message.

//Anton

#53 lore raw

RFC PATCH 29/43 helper-to-tcg: Introduce TCG register allocation

In reply to Anton Johansson via

Based on the assumption of a cycle free IR, this commit adds a simple register allocator for emitted values in TCG. The goal of this pass is to reduce the number of temporaries required in the output code, which is especially important when dealing with gvec vectors as to not require very large amounts of temporary storage in CPUArchState.

For each LLVM value in the IR, the allocator will assign a struct TcgV reprensenting a variable in the output TCG.

---
 .../helper-to-tcg/include/CmdLineOptions.h    |   2 +
 subprojects/helper-to-tcg/meson.build         |   1 +
 .../passes/backend/TcgTempAllocationPass.cpp  | 594 ++++++++++++++++++
 .../passes/backend/TcgTempAllocationPass.h    |  79 +++
 .../helper-to-tcg/pipeline/Pipeline.cpp       |   6 +
 5 files changed, 682 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.h
subprojects/helper-to-tcg/include/CmdLineOptions.h +2 -0
index 9553e26407..a5e467f8be 100644
@@ -25,3 +25,5 @@ extern llvm::cl::list<std::string> InputFiles;
 extern llvm::cl::opt<bool> TranslateAllHelpers;
 // Options for PrepareForTcgPass
 extern llvm::cl::opt<std::string> TcgGlobalMappingsName;
+// Options for TcgTempAllocation
+extern llvm::cl::opt<uint32_t> GuestPtrSize;
subprojects/helper-to-tcg/meson.build +1 -0
index 09caa74c63..ad3c307b6b 100644
@@ -50,6 +50,7 @@ sources = [
     'passes/PrepareForTcgPass/TransformGEPs.cpp',
     'passes/PrepareForTcgPass/CanonicalizeIR.cpp',
     'passes/PrepareForTcgPass/IdentityMap.cpp',
+    'passes/backend/TcgTempAllocationPass.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.cpp new file +594 -0

594 lines not on this page · raw message

subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.h new file +79 -0

79 lines not on this page · raw message

subprojects/helper-to-tcg/pipeline/Pipeline.cpp +6 -0
index a8df592af3..b933a7bb1a 100644
@@ -62,6 +62,12 @@ cl::opt<std::string> TcgGlobalMappingsName(
              "into a struct to TCG globals"),
     cl::init("mappings"), cl::cat(Cat));
 
+// Options for TcgTempAllocation
+cl::opt<uint32_t>
+    GuestPtrSize("guest-ptr-size",
+                 cl::desc("Pointer size of the guest architecture"),
+                 cl::init(32), cl::cat(Cat));
+
 // Define a TargetTransformInfo (TTI) subclass, this allows for overriding
 // common per-llvm-target information expected by other LLVM passes, such
 // as the width of the largest scalar/vector registers.  Needed for consistent
Signature · 1 line
2.45.2
#54 lore raw

RFC PATCH 30/43 helper-to-tcg: TcgGenPass, introduce TcgEmit.[cpp|h]

In reply to Anton Johansson via

A new translation unit is added with the purpose of containing all code which emits strings of TCG code. The idea is that maintainence of the backend will be simpler if all "tcg_*(*)" strings are contained and wrapped in functions.

---
 .../helper-to-tcg/include/CmdLineOptions.h    |    3 +
 subprojects/helper-to-tcg/meson.build         |    1 +
 .../helper-to-tcg/passes/backend/TcgEmit.cpp  | 1074 +++++++++++++++++
 .../helper-to-tcg/passes/backend/TcgEmit.h    |  290 +++++
 .../helper-to-tcg/pipeline/Pipeline.cpp       |   13 +
 5 files changed, 1381 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgEmit.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgEmit.h
subprojects/helper-to-tcg/include/CmdLineOptions.h +3 -0
index a5e467f8be..f59b700914 100644
@@ -27,3 +27,6 @@ extern llvm::cl::opt<bool> TranslateAllHelpers;
 extern llvm::cl::opt<std::string> TcgGlobalMappingsName;
 // Options for TcgTempAllocation
 extern llvm::cl::opt<uint32_t> GuestPtrSize;
+// Options for TcgEmit
+extern llvm::cl::opt<std::string> MmuIndexFunction;
+extern llvm::cl::opt<std::string> TempVectorBlock;
subprojects/helper-to-tcg/meson.build +1 -0
index ad3c307b6b..55a177bd94 100644
@@ -51,6 +51,7 @@ sources = [
     'passes/PrepareForTcgPass/CanonicalizeIR.cpp',
     'passes/PrepareForTcgPass/IdentityMap.cpp',
     'passes/backend/TcgTempAllocationPass.cpp',
+    'passes/backend/TcgEmit.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/backend/TcgEmit.cpp new file +1074 -0

1,074 lines not on this page · raw message

subprojects/helper-to-tcg/passes/backend/TcgEmit.h new file +290 -0

290 lines not on this page · raw message

subprojects/helper-to-tcg/pipeline/Pipeline.cpp +13 -0
index b933a7bb1a..004c16550a 100644
@@ -68,6 +68,19 @@ cl::opt<uint32_t>
                  cl::desc("Pointer size of the guest architecture"),
                  cl::init(32), cl::cat(Cat));
 
+// Options for TcgEmit
+cl::opt<std::string> MmuIndexFunction(
+    "mmu-index-function",
+    cl::desc("Name of a (uint32_t tb_flag) -> int function returning the "
+             "mmu index from the tb_flags of the current translation block"),
+    cl::init("get_tb_mmu_index"), cl::cat(Cat));
+
+cl::opt<std::string>
+    TempVectorBlock("temp-vector-block",
+                    cl::desc("Name of uint8_t[...] field in CPUArchState used "
+                             "for allocating temporary gvec variables"),
+                    cl::init("tmp_vmem"), cl::cat(Cat));
+
 // Define a TargetTransformInfo (TTI) subclass, this allows for overriding
 // common per-llvm-target information expected by other LLVM passes, such
 // as the width of the largest scalar/vector registers.  Needed for consistent
Signature · 1 line
2.45.2
#55 lore raw

RFC PATCH 31/43 helper-to-tcg: Introduce TcgGenPass

In reply to Anton Johansson via

Adds a backend pass, taking previously optimized and canonicalized LLVM IR and for each function:

1. Runs the TcgV register allocator;

2. Iterates over instructions and calls appropriate functions in TcgEmit.h to emit TCG code.

---
 .../helper-to-tcg/include/CmdLineOptions.h    |    6 +
 subprojects/helper-to-tcg/meson.build         |    1 +
 .../passes/backend/TcgGenPass.cpp             | 1812 +++++++++++++++++
 .../helper-to-tcg/passes/backend/TcgGenPass.h |   57 +
 .../helper-to-tcg/pipeline/Pipeline.cpp       |   49 +
 5 files changed, 1925 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgGenPass.cpp
 create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgGenPass.h
subprojects/helper-to-tcg/include/CmdLineOptions.h +6 -0
index f59b700914..3787fbbaec 100644
@@ -30,3 +30,9 @@ extern llvm::cl::opt<uint32_t> GuestPtrSize;
 // Options for TcgEmit
 extern llvm::cl::opt<std::string> MmuIndexFunction;
 extern llvm::cl::opt<std::string> TempVectorBlock;
+// Options for TcgGenPass
+extern llvm::cl::opt<std::string> OutputSourceFile;
+extern llvm::cl::opt<std::string> OutputHeaderFile;
+extern llvm::cl::opt<std::string> OutputEnabledFile;
+extern llvm::cl::opt<std::string> OutputLogFile;
+extern llvm::cl::opt<bool> ErrorOnTranslationFailure;
subprojects/helper-to-tcg/meson.build +1 -0
index 55a177bd94..4f045eb1da 100644
@@ -52,6 +52,7 @@ sources = [
     'passes/PrepareForTcgPass/IdentityMap.cpp',
     'passes/backend/TcgTempAllocationPass.cpp',
     'passes/backend/TcgEmit.cpp',
+    'passes/backend/TcgGenPass.cpp',
 ]
 
 clang = bindir / 'clang'
subprojects/helper-to-tcg/passes/backend/TcgGenPass.cpp new file +1812 -0

1,812 lines not on this page · raw message

subprojects/helper-to-tcg/passes/backend/TcgGenPass.h new file +57 -0

57 lines not on this page · raw message

subprojects/helper-to-tcg/pipeline/Pipeline.cpp +49 -0

72 lines not on this page · raw message

Signature · 1 line
2.45.2
#56 lore raw

RFC PATCH 32/43 helper-to-tcg: Add README

In reply to Anton Johansson via
---
 subprojects/helper-to-tcg/README.md | 265 ++++++++++++++++++++++++++++
 1 file changed, 265 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/README.md
subprojects/helper-to-tcg/README.md new file +265 -0
new file mode 100644
index 0000000000..8d1304ef4f
@@ -0,0 +1,265 @@
+# helper-to-tcg
+
+`helper-to-tcg` is a standalone LLVM IR to TCG translator, with the goal of simplifying the implementation of complicated instructions in TCG. Instruction semantics can be specified either directly in LLVM IR or any language that can be compiled to it (C, C++, ...). However, the tool is tailored towards QEMU helper functions written in C.
+
+Internally, `helper-to-tcg` consists of a mix of custom and built-in transformation and analysis passes that are applied to the input LLVM IR sequentially. The pipeline of passes is laid out as follows
+```
+           +---------------+    +-----+    +---------------+    +------------+
+LLVM IR -> | PrepareForOpt | -> | -Os | -> | PrepareForTcg | -> | TcgGenPass | -> TCG
+           +---------------+    +-----+    +---------------+    +------------+
+```
+where the custom passes performs:
+* `PrepareForOpt` - Early culling of unneeded functions, mapping of function annotations, removal of `noinline` added by `-O0`
+* `PrepareForTcg` - Post-optimization pass that tries to get the IR as close to Tinycode as possible, goal is to take complexity away from the backend;
+* `TcgGenPass` - Backend pass that allocates TCG variables to LLVM values, and emits final TCG C code.
+
+As for LLVM optimization, `-Os` strikes a good balance between unrolling and vectorization, from testing. More aggressive optimization levels would often unroll loops over compacting it with loop vectorization.
+
+## Project Structure
+
+* `get-llvm-ir.py` - Helper script to convert a QEMU .c file to LLVM IR by getting compile flags from `compile_commands.json`.
+* `pipeline` - Implementation of pipeline orchestrating LLVM passes and handling input.
+* `passes` - Implementation of custom LLVM passes (`PrepareForOpt`,`PrepareForTcg`,`TcgGenPass`).
+* `include` - Shared headers between `passes/pipeline`.
+* `tests` - Simple end-to-end tests of C functions we expect to be able to translate, tests fail if any function fails to translate, output is not verified.
+
+## Example Translations
+
+`helper-to-tcg` is able to deal with a wide variety of helper functions, the following code snippet contains two examples from the Hexagon architecture implementing the semantics of a predicated and instruction (`A2_pandt`) and a vectorized signed saturated 2-element scalar product (`V6_vdmpyhvsat`).
+
+```c
+int32_t HELPER(A2_pandt)(CPUHexagonState *env, int32_t RdV,
+                         int32_t PuV, int32_t RsV, int32_t RtV)
+{
+    if(fLSBOLD(PuV)) {
+        RdV=RsV&RtV;
+    } else {
+        CANCEL;
+    }
+    return RdV;
+}
+
+void HELPER(V6_vdmpyhvsat)(CPUHexagonState *env,
+                           void * restrict VdV_void,
+                           void * restrict VuV_void,
+                           void * restrict VvV_void)
+{
+    fVFOREACH(32, i) {
+        size8s_t accum = fMPY16SS(fGETHALF(0,VuV.w[i]),fGETHALF(0, VvV.w[i]));
+        accum += fMPY16SS(fGETHALF(1,VuV.w[i]),fGETHALF(1, VvV.w[i]));
+        VdV.w[i] = fVSATW(accum);
+    }
+}
+```
+For the above snippet, `helper-to-tcg` produces the following TCG
+```c
+void emit_A2_pandt(TCGv_i32 temp0, TCGv_env env, TCGv_i32 temp4,
+                   TCGv_i32 temp8, TCGv_i32 temp7, TCGv_i32 temp6) {
+    TCGv_i32 temp2 = tcg_temp_new_i32();
+    tcg_gen_andi_i32(temp2, temp8, 1);
+    TCGv_i32 temp5 = tcg_temp_new_i32();
+    tcg_gen_and_i32(temp5, temp6, temp7);
+    tcg_gen_movcond_i32(TCG_COND_EQ, temp0, temp2, tcg_constant_i32(0), temp4, temp5);
+}
+
+void emit_V6_vdmpyhvsat(TCGv_env env, intptr_t vec3,
+                        intptr_t vec7, intptr_t vec6) {
+     VectorMem mem = {0};
+     intptr_t vec0 = temp_new_gvec(&mem, 128);
+     tcg_gen_gvec_shli(MO_32, vec0, vec7, 16, 128, 128);
+     intptr_t vec5 = temp_new_gvec(&mem, 128);
+     tcg_gen_gvec_sari(MO_32, vec5, vec0, 16, 128, 128);
+     intptr_t vec1 = temp_new_gvec(&mem, 128);
+     tcg_gen_gvec_shli(MO_32, vec1, vec6, 16, 128, 128);
+     tcg_gen_gvec_sari(MO_32, vec1, vec1, 16, 128, 128);
+     tcg_gen_gvec_mul(MO_32, vec1, vec1, vec5, 128, 128);
+     intptr_t vec2 = temp_new_gvec(&mem, 128);
+     tcg_gen_gvec_sari(MO_32, vec2, vec7, 16, 128, 128);
+     tcg_gen_gvec_sari(MO_32, vec0, vec6, 16, 128, 128);
+     tcg_gen_gvec_mul(MO_32, vec2, vec0, vec2, 128, 128);
+     tcg_gen_gvec_ssadd(MO_32, vec3, vec1, vec2, 128, 128);
+}
+```
+
+In the first case, the predicated and instruction was made branchless by using a conditional move, and in the latter case the inner loop of the vectorized scalar product could be converted to a few vectorized shifts and multiplications, folllowed by a vectorized signed saturated addition.
+
+## Usage
+
+Building `helper-to-tcg` produces a binary implementing the pipeline outlined above, going from LLVM IR to TCG.
+
+### Specifying Functions to Translate
+
+Unless `--translate-all-helpers` is specified, the default behaviour of `helper-to-tcg` is to only translate functions annotated via a special `"helper-to-tcg"` annotation. Functions called by annotated functions will also be translated, see the following example:
+
+```c
+// Function will be translated, annotation provided
+__attribute__((annotate ("helper-to-tcg")))
+int f(int a, int b) {
+    return 2 * g(a, b);
+}
+
+// Function will be translated, called by annotated `f()` function
+int g(int a, int b) {
+    ...
+}
+
+// Function will not be translated
+int h(int a, int b) {
+    ...
+}
+```
+
+### Immediate and Vector Arguments
+
+Function annotations are in some cases used to provide extra information to `helper-to-tcg` not otherwise present in the IR. For example, whether an integer argument should actually be treated as an immediate rather than a register, or if a pointer argument should be treated as a `gvec` vector (offset into `CPUArchState`). For instance:
+```c
+__attribute__((annotate ("helper-to-tcg")))
+__attribute__((annotate ("immediate: 1")))
+int f(int a, int i) {
+    ...
+}
+
+__attribute__((annotate ("helper-to-tcg")))
+__attribute__((annotate ("ptr-to-offset: 0, 1")))
+void g(void * restrict a, void * restrict b) {
+    ...
+}
+```
+where `"immediate: 1"` tells `helper-to-tcg` that the argument with index `1` should be treated as an immediate (multiple arguments are specified through a comma separated list). Similarly `"ptr-to-offset: 0, 1"` indicates that arguments width index 0 and 1 should be treated as offsets from `CPUArchState` (given as `intptr_t`), rather than actual pointer arguments. For the above code, `helper-to-tcg` emits
+```c
+void emit_f(TCGv_i32 res, TCGv_i32 a, int i) {
+    ...
+}
+
+void emit_g(intptr_t a, intptr_t b) {
+    ...
+}
+```
+
+### Loads and Stores
+
+Translating loads and stores is slightly trickier, as some QEMU specific assumptions are made. Loads and stores in the input are assumed to go through the `cpu_[st|ld]*()` functions defined in `exec/cpu_ldst.h` that a helper function would use. 
+
+If using standalone input functions (not QEMU helper functions), loads and stores are still represented by `cpu_[st|ld]*()` which needs to be declared, consider:
+```c
+/* Opaque CPU state type, will be mapped to tcg_env */
+struct CPUArchState;
+typedef struct CPUArchState CPUArchState;
+
+/* Prototype of QEMU helper guest load/store functions, see exec/cpu_ldst.h */
+uint32_t cpu_ldub_data(CPUArchState *, uint32_t ptr);
+void cpu_stb_data(CPUArchState *, uint32_t ptr, uint32_t data);
+
+uint32_t helper_ld8(CPUArchState *env, uint32_t addr) {
+    return cpu_ldub_data(env, addr);
+}
+
+void helper_st8(CPUArchState *env, uint32_t addr, uint32_t data) {
+    return cpu_stb_data(env, addr, data);
+}
+```
+implementing an 8-bit load and store instruction, these will be translated to the following TCG.
+```c
+void emit_ld8(TCGv_i32 temp0, TCGv_env env, TCGv_i32 temp1) {
+    tcg_gen_qemu_ld_i32(temp0, temp1, tb_mmu_index(tcg_ctx->gen_tb->flags), MO_UB);
+}
+
+void emit_st8(TCGv_env env, TCGv_i32 temp0, TCGv_i32 temp1) {
+    tcg_gen_qemu_st_i32(temp1, temp0, tb_mmu_index(tcg_ctx->gen_tb->flags), MO_UB);
+}
+```
+Note, the emitted code assumes the definition of a `tb_mmu_index()` function to retrieve the current CPU MMU index, the name of this function can be configured via the `--mmu-index-function` flag.
+
+### Mapping CPU State
+
+In QEMU, commonly accessed fields in the `CPUArchState` are often mapped to global `TCGv*` variables representing that piece of CPU state in TCG. When translating helper functions (or other C functions), a method of specifying which fields in the CPU state should be mapped to which globals is needed. To this end, a declarative approach is taken, where mappings between CPU state and globals can be consumed by both `helper-to-tcg` and runtime QEMU for instantiating the `TCGv` globals themselves.
+
+Users must define this mapping via a global `cpu_tcg_mapping []` array, as can be seen in the following example where `mapped_field` of `CPUArchState` is mapped to the global `tcg_field`. For more complicated examples see the tests in `tests/cpustate.c`.
+```c
+#include <stdint.h>
+#include "tcg/tcg-global-mappings.h"
+
+/* Define a CPU state with some different fields */
+
+typedef struct CPUArchState {
+    uint32_t mapped_field;
+    uint32_t unmapped_field;
+} CPUArchState;
+
+/* Dummy struct, in QEMU this would correspond to TCGv_i32 in tcg.h */
+typedef struct TCGv_i32 {} TCGv_i32;
+
+/* Global TCGv representing CPU state */
+TCGv_i32 tcg_field;
+
+/*
+ * Finally provide a mapping of CPUArchState to TCG globals we care about, here
+ * we map mapped_field to tcg_field
+ */
+cpu_tcg_mapping mappings[] = {
+    CPU_TCG_MAP(CPUArchState, tcg_field, mapped_field, NULL),
+};
+
+uint32_t helper_mapped(CPUArchState *env) {
+    return env->mapped_field;
+}
+
+uint32_t helper_unmapped(CPUArchState *env) {
+    return env->unmapped_field;
+}
+```
+Note, the name of the `cpu_tcg_mapping[]` is provided via the `--tcg-global-mappings` flag. For the above example, `helper-to-tcg` emits
+```c
+extern TCGv_i32 tcg_field;
+
+void emit_mapped(TCGv_i32 temp0, TCGv_env env) {
+    tcg_gen_mov_i32(temp0, tcg_field);
+}
+
+void emit_unmapped(TCGv_i32 temp0, TCGv_env env) {
+    TCGv_ptr ptr1 = tcg_temp_new_ptr();
+    tcg_gen_addi_ptr(ptr1, env, 128ull);
+    tcg_gen_ld_i32(temp0, ptr1, 0);
+}
+```
+where accesses in the input C code are correctly mapped to the corresponding TCG globals. The unmapped `CPUArchState` access turns into pointer math and a load, whereas the mapped access turns into a `mov` from a global.
+
+### Automatic Calling of Generated Code
+
+Finally, calling the generated code is as simple as including the output of `helper-to-tcg` into the project and manually calling `emit_*(...)`. However, when dealing with an existing frontend that has a lot of helper functions already in use, we simplify this process somewhat for non-vector instructions. `helper-to-tcg` can emit a dispatcher, which for the above CPU state mapping example looks like
+```c
+int helper_to_tcg_dispatcher(void *func, TCGTemp *ret_temp, int nargs, TCGTemp **args) {
+    if ((uintptr_t) func == (uintptr_t) helper_mapped) {
+        TCGv_i32 temp0 = temp_tcgv_i32(ret_temp);
+        TCGv_env env = temp_tcgv_ptr(args[0]);
+        emit_mapped(temp0, env);
+        return 1;
+    }
+    if ((uintptr_t) func == (uintptr_t) helper_unmapped) {
+        TCGv_i32 temp0 = temp_tcgv_i32(ret_temp);
+        TCGv_env env = temp_tcgv_ptr(args[0]);
+        emit_unmapped(temp0, env);
+        return 1;
+    }
+    return 0;
+}
+```
+Here `emit_mapped()` and `emit_unmapped()` are automatically called if the current helper function call being translated `void *func` corresponds to either of the input helper functions. If the fronend then defines
+```c
+#ifdef CONFIG_HELPER_TO_TCG
+#define TARGET_HELPER_DISPATCHER helper_to_tcg_dispatcher
+#endif
+```
+in `cpu-param.h`, then calls to `gen_helper_mapped()` for instance, will end up in `emit_mapped()` with no change to frontends. Additionally, dispatching from helper calls allows for easy toggling of `helper-to-tcg`, which is increadibly useful for testing purposes.
+
+### Simple Command Usage
+
+Assume a `helpers.c` file with functions to translate, then to obtain LLVM IR
+```bash
+$ clang helpers.c -O0 -Xclang -disable-O0-optnone -S -emit-llvm
+```
+which produces `helpers.ll` to be fed into `helper-to-tcg`
+```bash
+$ ./helper-to-tcg helpers.ll --translate-all-helpers
+```
+where `--translate-all-helpers` means "translate all functions starting with helper_*". Finally, the above command produces `helper-to-tcg-emitted.[c|h]` with emitted TCG code.
Signature · 1 line
2.45.2
#57 lore raw

RFC PATCH 33/43 helper-to-tcg: Add end-to-end tests

In reply to Anton Johansson via

Introduces simple end-to-end tests of helper-to-tcg of functions the translator is expected to handle, any translation failure will result in a test failure. More test cases to come.

---
 subprojects/helper-to-tcg/meson.build         |   2 +
 subprojects/helper-to-tcg/tests/cpustate.c    |  45 +++++++
 subprojects/helper-to-tcg/tests/ldst.c        |  17 +++
 subprojects/helper-to-tcg/tests/meson.build   |  24 ++++
 subprojects/helper-to-tcg/tests/scalar.c      |  15 +++
 .../helper-to-tcg/tests/tcg-global-mappings.h | 115 ++++++++++++++++++
 subprojects/helper-to-tcg/tests/vector.c      |  26 ++++
 7 files changed, 244 insertions(+)
 create mode 100644 subprojects/helper-to-tcg/tests/cpustate.c
 create mode 100644 subprojects/helper-to-tcg/tests/ldst.c
 create mode 100644 subprojects/helper-to-tcg/tests/meson.build
 create mode 100644 subprojects/helper-to-tcg/tests/scalar.c
 create mode 100644 subprojects/helper-to-tcg/tests/tcg-global-mappings.h
 create mode 100644 subprojects/helper-to-tcg/tests/vector.c
subprojects/helper-to-tcg/meson.build +2 -0
index 4f045eb1da..e09f121e18 100644
@@ -80,3 +80,5 @@ pipeline = executable('helper-to-tcg', sources,
                       include_directories: ['passes', './', 'include'] + [incdir],
                       link_args: [ldflags] + [libs] + [syslibs],
                       cpp_args: cpp_args)
+
+subdir('tests')
subprojects/helper-to-tcg/tests/cpustate.c new file +45 -0

45 lines not on this page · raw message

subprojects/helper-to-tcg/tests/ldst.c new file +17 -0
new file mode 100644
index 0000000000..44d32d0875
@@ -0,0 +1,17 @@
+#include <stdint.h>
+
+/* Opaque CPU state type, will be mapped to tcg_env */
+struct CPUArchState;
+typedef struct CPUArchState CPUArchState;
+
+/* Prototype of QEMU helper guest load/store functions, see exec/cpu_ldst.h */
+uint32_t cpu_ldub_data(CPUArchState *, uint32_t ptr);
+void cpu_stb_data(CPUArchState *, uint32_t ptr, uint32_t data);
+
+uint32_t helper_ld8(CPUArchState *env, uint32_t addr) {
+    return cpu_ldub_data(env, addr);
+}
+
+void helper_st8(CPUArchState *env, uint32_t addr, uint32_t data) {
+    return cpu_stb_data(env, addr, data);
+}
subprojects/helper-to-tcg/tests/meson.build new file +24 -0
new file mode 100644
index 0000000000..e7b9329c82
@@ -0,0 +1,24 @@
+sources = [
+    'scalar.c',
+    'vector.c',
+    'ldst.c',
+    'cpustate.c',
+]
+
+
+foreach s : sources
+    name = s.split('.')[0]
+    name_ll = name + '.ll'
+    ll = custom_target(name_ll,
+        input: s,
+        output: name_ll,
+        command: [clang, '-O0', '-Xclang', '-disable-O0-optnone',
+                  '-S', '-emit-llvm', '-o', '@OUTPUT@', '@INPUT@']
+    )
+    test(name, pipeline,
+        args: [ll,
+               '--mmu-index-function=tb_mmu_index',
+               '--tcg-global-mappings=mappings',
+               '--translate-all-helpers'],
+        suite: 'end-to-end')
+endforeach
subprojects/helper-to-tcg/tests/scalar.c new file +15 -0
new file mode 100644
index 0000000000..09af72371d
@@ -0,0 +1,15 @@
+#include <stdint.h>
+
+/* Simple arithmetic */
+uint32_t helper_add(uint32_t a, uint32_t b) {
+    return a + b;
+}
+
+/* Control flow reducable to conditinal move */
+uint32_t helper_cmov(uint32_t c0, uint32_t c1, uint32_t a, uint32_t b) {
+    if (c0 < c1) {
+        return a;
+    } else {
+        return b;
+    }
+}
subprojects/helper-to-tcg/tests/tcg-global-mappings.h new file +115 -0

115 lines not on this page · raw message

subprojects/helper-to-tcg/tests/vector.c new file +26 -0
new file mode 100644
index 0000000000..c40f63b60d
@@ -0,0 +1,26 @@
+#include <stdint.h>
+
+__attribute__((annotate("ptr-to-offset: 0"))) void
+helper_vec_splat_reg(void *restrict d, uint8_t imm)
+{
+    for (int i = 0; i < 32; ++i) {
+        ((uint8_t *)d)[i] = imm;
+    }
+}
+
+__attribute__((annotate("immediate: 1")))
+__attribute__((annotate("ptr-to-offset: 0"))) void
+helper_vec_splat_imm(void *restrict d, uint8_t imm)
+{
+    for (int i = 0; i < 32; ++i) {
+        ((uint8_t *)d)[i] = imm;
+    }
+}
+
+__attribute__((annotate("ptr-to-offset: 0, 1, 2"))) void
+helper_vec_add(void *restrict d, void *restrict a, void *restrict b)
+{
+    for (int i = 0; i < 32; ++i) {
+        ((uint8_t *)d)[i] = ((uint8_t *)a)[i] + ((uint8_t *)b)[i];
+    }
+}
Signature · 1 line
2.45.2
#58 lore raw

RFC PATCH 34/43 target/hexagon: Add get_tb_mmu_index()

In reply to Anton Johansson via

Adds a functions to return the current mmu index given tb_flags of the current translation block. Required by helper-to-tcg in order to retrieve the mmu index for memory operations without changing the signature of helper functions.

---
 target/hexagon/cpu.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)
target/hexagon/cpu.h +12 -0
index 764f3c38cc..7be4b5769e 100644
@@ -153,6 +153,18 @@ static inline void cpu_get_tb_cpu_state(CPUHexagonState *env, vaddr *pc,
     }
 }
 
+// Returns the current mmu index given tb_flags of the current translation
+// block.  Required by helper-to-tcg in order to retrieve the mmu index for
+// memory operations without changing the signature of helper functions.
+static inline int get_tb_mmu_index(uint32_t flags)
+{
+#ifdef CONFIG_USER_ONLY
+    return MMU_USER_IDX;
+#else
+#error System mode not supported on Hexagon yet
+#endif
+}
+
 typedef HexagonCPU ArchCPU;
 
 void hexagon_translate_init(void);
Signature · 1 line
2.45.2
#59 lore raw

Re: [RFC PATCH v1 34/43] target/hexagon: Add get_tb_mmu_index()

Quoted 23 lines · Anton Johansson

Adds a functions to return the current mmu index given tb_flags of the current translation block. Required by helper-to-tcg in order to retrieve the mmu index for memory operations without changing the signature of helper functions.

---
  target/hexagon/cpu.h | 12 ++++++++++++
  1 file changed, 12 insertions(+)
target/hexagon/cpu.h +5 -0
index 764f3c38cc..7be4b5769e 100644
@@ -153,6 +153,18 @@ static inline void cpu_get_tb_cpu_state(CPUHexagonState *env, vaddr *pc,
      }
  }
 
+// Returns the current mmu index given tb_flags of the current translation
+// block.  Required by helper-to-tcg in order to retrieve the mmu index for
+// memory operations without changing the signature of helper functions.
+static inline int get_tb_mmu_index(uint32_t flags)
+{

target/hexagon/cpu.h static inline void cpu_get_tb_cpu_state(CPUHexagonState *env, vaddr *pc, · line 170

Quoted 10 lines
target/hexagon/cpu.h +7 -0
+#ifdef CONFIG_USER_ONLY
+    return MMU_USER_IDX;
+#else
+#error System mode not supported on Hexagon yet
+#endif
+}
+
  typedef HexagonCPU ArchCPU;
 
  void hexagon_translate_init(void);

I suggest placing this somewhere other than cpu.h, as it's private to the translator and its generated code.

r~

#60 lore raw

Re: [RFC PATCH v1 34/43] target/hexagon: Add get_tb_mmu_index()

Quoted 27 lines · Richard Henderson
Quoted 26 lines · Anton Johansson

Adds a functions to return the current mmu index given tb_flags of the current translation block. Required by helper-to-tcg in order to retrieve the mmu index for memory operations without changing the signature of helper functions.

---
  target/hexagon/cpu.h | 12 ++++++++++++
  1 file changed, 12 insertions(+)
target/hexagon/cpu.h +9 -0
index 764f3c38cc..7be4b5769e 100644
@@ -153,6 +153,18 @@ static inline void cpu_get_tb_cpu_state(CPUHexagonState *env, vaddr *pc,
      }
  }
+// Returns the current mmu index given tb_flags of the current translation
+// block.  Required by helper-to-tcg in order to retrieve the mmu index for
+// memory operations without changing the signature of helper functions.
+static inline int get_tb_mmu_index(uint32_t flags)
+{
+#ifdef CONFIG_USER_ONLY
+    return MMU_USER_IDX;
+#else
+#error System mode not supported on Hexagon yet
Quoted 8 lines

target/hexagon/cpu.h static inline void cpu_get_tb_cpu_state(CPUHexagonState *env, vaddr *pc, · line 170

Quoted 5 lines
target/hexagon/cpu.h +3 -0
+#endif
+}
+
  typedef HexagonCPU ArchCPU;
  void hexagon_translate_init(void);

I suggest placing this somewhere other than cpu.h, as it's private to the translator and its generated code.

Makes sense!

//Anton

#61 lore raw

RFC PATCH 35/43 target/hexagon: Use argparse in all python scripts

In reply to Anton Johansson via

QOL commit, all the various gen_* python scripts take a large set arguments where order is implicit. Using argparse we also get decent error messages if a field is missing or too many are added.

---
 target/hexagon/gen_analyze_funcs.py     |  6 +++--
 target/hexagon/gen_decodetree.py        | 19 +++++++++++----
 target/hexagon/gen_helper_funcs.py      |  7 +++---
 target/hexagon/gen_helper_protos.py     |  7 +++---
 target/hexagon/gen_idef_parser_funcs.py | 11 +++++++--
 target/hexagon/gen_op_attribs.py        | 11 +++++++--
 target/hexagon/gen_opcodes_def.py       | 11 +++++++--
 target/hexagon/gen_printinsn.py         | 11 +++++++--
 target/hexagon/gen_tcg_func_table.py    | 11 +++++++--
 target/hexagon/gen_tcg_funcs.py         |  9 +++----
 target/hexagon/gen_trans_funcs.py       | 17 ++++++++++---
 target/hexagon/hex_common.py            | 32 ++++++++++++-------------
 target/hexagon/meson.build              |  2 +-
 13 files changed, 107 insertions(+), 47 deletions(-)
target/hexagon/gen_analyze_funcs.py +4 -2
index 54bac19724..3ac7cc2cfe 100755
@@ -78,11 +78,13 @@ def gen_analyze_func(f, tag, regs, imms):
 
 
 def main():
-    hex_common.read_common_files()
+    args = hex_common.parse_common_args(
+        "Emit functions analyzing register accesses"
+    )
     tagregs = hex_common.get_tagregs()
     tagimms = hex_common.get_tagimms()
 
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
         f.write("#ifndef HEXAGON_ANALYZE_FUNCS_C_INC\n")
         f.write("#define HEXAGON_ANALYZE_FUNCS_C_INC\n\n")
 
target/hexagon/gen_decodetree.py +15 -4
index a4fcd622c5..ce703af41d 100755
@@ -24,6 +24,7 @@
 import textwrap
 import iset
 import hex_common
+import argparse
 
 encs = {
     tag: "".join(reversed(iset.iset[tag]["enc"].replace(" ", "")))
@@ -191,8 +192,18 @@ def gen_decodetree_file(f, class_to_decode):
         f.write(f"{tag}\t{enc_str} @{tag}\n")
 
 
+def main():
+    parser = argparse.ArgumentParser(
+        description="Emit opaque macro calls with instruction semantics"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("class_to_decode", help="instruction class to decode")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+
+    hex_common.read_semantics_file(args.semantics)
+    with open(args.out, "w") as f:
+        gen_decodetree_file(f, args.class_to_decode)
+
 if __name__ == "__main__":
-    hex_common.read_semantics_file(sys.argv[1])
-    class_to_decode = sys.argv[2]
-    with open(sys.argv[3], "w") as f:
-        gen_decodetree_file(f, class_to_decode)
+    main()
target/hexagon/gen_helper_funcs.py +4 -3
index e9685bff2f..c1f806ac4b 100755
@@ -102,12 +102,13 @@ def gen_helper_function(f, tag, tagregs, tagimms):
 
 
 def main():
-    hex_common.read_common_files()
+    args = hex_common.parse_common_args(
+        "Emit helper function definitions for each instruction"
+    )
     tagregs = hex_common.get_tagregs()
     tagimms = hex_common.get_tagimms()
 
-    output_file = sys.argv[-1]
-    with open(output_file, "w") as f:
+    with open(args.out, "w") as f:
         for tag in hex_common.tags:
             ## Skip the priv instructions
             if "A_PRIV" in hex_common.attribdict[tag]:
target/hexagon/gen_helper_protos.py +4 -3
index fd2bfd0f36..77f8e0a6a3 100755
@@ -52,12 +52,13 @@ def gen_helper_prototype(f, tag, tagregs, tagimms):
 
 
 def main():
-    hex_common.read_common_files()
+    args = hex_common.parse_common_args(
+        "Emit helper function prototypes for each instruction"
+    )
     tagregs = hex_common.get_tagregs()
     tagimms = hex_common.get_tagimms()
 
-    output_file = sys.argv[-1]
-    with open(output_file, "w") as f:
+    with open(args.out, "w") as f:
         for tag in hex_common.tags:
             ## Skip the priv instructions
             if "A_PRIV" in hex_common.attribdict[tag]:
target/hexagon/gen_idef_parser_funcs.py +9 -2
index 72f11c68ca..2f6e826f76 100644
@@ -20,6 +20,7 @@
 import sys
 import re
 import string
+import argparse
 from io import StringIO
 
 import hex_common
@@ -43,13 +44,19 @@
 ## them are inputs ("in" prefix), while some others are outputs.
 ##
 def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        "Emit instruction implementations that can be fed to idef-parser"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
     hex_common.calculate_attribs()
     hex_common.init_registers()
     tagregs = hex_common.get_tagregs()
     tagimms = hex_common.get_tagimms()
 
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
         f.write('#include "macros.h.inc"\n\n')
 
         for tag in hex_common.tags:
target/hexagon/gen_op_attribs.py +9 -2
index 99448220da..bbbb02df3a 100755
@@ -21,16 +21,23 @@
 import re
 import string
 import hex_common
+import argparse
 
 
 def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        "Emit opaque macro calls containing instruction attributes"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
     hex_common.calculate_attribs()
 
     ##
     ##     Generate all the attributes associated with each instruction
     ##
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
         for tag in hex_common.tags:
             f.write(
                 f"OP_ATTRIB({tag},ATTRIBS("
target/hexagon/gen_opcodes_def.py +9 -2
index 536f0eb68a..94a19ff412 100755
@@ -21,15 +21,22 @@
 import re
 import string
 import hex_common
+import argparse
 
 
 def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        description="Emit opaque macro calls with instruction names"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
 
     ##
     ##     Generate a list of all the opcodes
     ##
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
         for tag in hex_common.tags:
             f.write(f"OPCODE({tag}),\n")
 
target/hexagon/gen_printinsn.py +9 -2
index 8bf4d0985c..d5f969960a 100755
@@ -21,6 +21,7 @@
 import re
 import string
 import hex_common
+import argparse
 
 
 ##
@@ -96,11 +97,17 @@ def spacify(s):
 
 
 def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        "Emit opaque macro calls with information for printing string representations of instrucions"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
 
     immext_casere = re.compile(r"IMMEXT\(([A-Za-z])")
 
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
         for tag in hex_common.tags:
             if not hex_common.behdict[tag]:
                 continue
target/hexagon/gen_tcg_func_table.py +9 -2
index 978ac1819b..299a39b1aa 100755
@@ -21,15 +21,22 @@
 import re
 import string
 import hex_common
+import argparse
 
 
 def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        "Emit opaque macro calls with instruction semantics"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
     hex_common.calculate_attribs()
     tagregs = hex_common.get_tagregs()
     tagimms = hex_common.get_tagimms()
 
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
         f.write("#ifndef HEXAGON_FUNC_TABLE_H\n")
         f.write("#define HEXAGON_FUNC_TABLE_H\n\n")
 
target/hexagon/gen_tcg_funcs.py +5 -4
index 05aa0a7855..c2ba91ddc0 100755
@@ -108,15 +108,16 @@ def gen_def_tcg_func(f, tag, tagregs, tagimms):
 
 
 def main():
-    is_idef_parser_enabled = hex_common.read_common_files()
+    args = hex_common.parse_common_args(
+        "Emit functions calling generated code implementing instruction semantics (helpers, idef-parser)"
+    )
     tagregs = hex_common.get_tagregs()
     tagimms = hex_common.get_tagimms()
 
-    output_file = sys.argv[-1]
-    with open(output_file, "w") as f:
+    with open(args.out, "w") as f:
         f.write("#ifndef HEXAGON_TCG_FUNCS_H\n")
         f.write("#define HEXAGON_TCG_FUNCS_H\n\n")
-        if is_idef_parser_enabled:
+        if args.idef_parser:
             f.write('#include "idef-generated-emitter.h.inc"\n\n')
 
         for tag in hex_common.tags:
target/hexagon/gen_trans_funcs.py +14 -3
index 30f0c73e0c..aea1c36f7d 100755
@@ -24,6 +24,7 @@
 import textwrap
 import iset
 import hex_common
+import argparse
 
 encs = {
     tag: "".join(reversed(iset.iset[tag]["enc"].replace(" ", "")))
@@ -136,8 +137,18 @@ def gen_trans_funcs(f):
         """))
 
 
-if __name__ == "__main__":
-    hex_common.read_semantics_file(sys.argv[1])
+def main():
+    parser = argparse.ArgumentParser(
+        description="Emit trans_*() functions to be called by instruction decoder"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
     hex_common.init_registers()
-    with open(sys.argv[2], "w") as f:
+    with open(args.out, "w") as f:
         gen_trans_funcs(f)
+
+
+if __name__ == "__main__":
+    main()
target/hexagon/hex_common.py +15 -17
index 15ed4980e4..bb20711a2e 100755
@@ -21,6 +21,7 @@
 import re
 import string
 import textwrap
+import argparse
 
 behdict = {}  # tag ->behavior
 semdict = {}  # tag -> semantics
@@ -1181,22 +1182,19 @@ def helper_args(tag, regs, imms):
     return args
 
 
-def read_common_files():
-    read_semantics_file(sys.argv[1])
-    read_overrides_file(sys.argv[2])
-    read_overrides_file(sys.argv[3])
-    ## Whether or not idef-parser is enabled is
-    ## determined by the number of arguments to
-    ## this script:
-    ##
-    ##   4 args. -> not enabled,
-    ##   5 args. -> idef-parser enabled.
-    ##
-    ## The 5:th arg. then holds a list of the successfully
-    ## parsed instructions.
-    is_idef_parser_enabled = len(sys.argv) > 5
-    if is_idef_parser_enabled:
-        read_idef_parser_enabled_file(sys.argv[4])
+def parse_common_args(desc):
+    parser = argparse.ArgumentParser(desc)
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("overrides", help="overrides file")
+    parser.add_argument("overrides_vec", help="vector overrides file")
+    parser.add_argument("out", help="output file")
+    parser.add_argument("--idef-parser", help="file of instructions translated by idef-parser")
+    args = parser.parse_args()
+    read_semantics_file(args.semantics)
+    read_overrides_file(args.overrides)
+    read_overrides_file(args.overrides_vec)
+    if args.idef_parser:
+        read_idef_parser_enabled_file(args.idef_parser)
     calculate_attribs()
     init_registers()
-    return is_idef_parser_enabled
+    return args
target/hexagon/meson.build +1 -1
index f1723778a6..bb4ebaae81 100644
@@ -346,7 +346,7 @@ if idef_parser_enabled and 'hexagon-linux-user' in target_dirs
     # Setup input and dependencies for the next step, this depends on whether or
     # not idef-parser is enabled
     helper_dep = [semantics_generated, idef_generated_tcg_c, idef_generated_tcg]
-    helper_in = [semantics_generated, gen_tcg_h, gen_tcg_hvx_h, idef_generated_list]
+    helper_in = [semantics_generated, gen_tcg_h, gen_tcg_hvx_h, '--idef-parser', idef_generated_list]
 else
     # Setup input and dependencies for the next step, this depends on whether or
     # not idef-parser is enabled
Signature · 1 line
2.45.2
Reviewed-by on v1 35/43
#62 lore raw

Re: [RFC PATCH v1 35/43] target/hexagon: Use argparse in all python scripts

Quoted 6 lines · Anton Johansson via

QOL commit, all the various gen_* python scripts take a large set arguments where order is implicit. Using argparse we also get decent error messages if a field is missing or too many are added.

---

Quoted 387 lines
  target/hexagon/gen_analyze_funcs.py     |  6 +++--
  target/hexagon/gen_decodetree.py        | 19 +++++++++++----
  target/hexagon/gen_helper_funcs.py      |  7 +++---
  target/hexagon/gen_helper_protos.py     |  7 +++---
  target/hexagon/gen_idef_parser_funcs.py | 11 +++++++--
  target/hexagon/gen_op_attribs.py        | 11 +++++++--
  target/hexagon/gen_opcodes_def.py       | 11 +++++++--
  target/hexagon/gen_printinsn.py         | 11 +++++++--
  target/hexagon/gen_tcg_func_table.py    | 11 +++++++--
  target/hexagon/gen_tcg_funcs.py         |  9 +++----
  target/hexagon/gen_trans_funcs.py       | 17 ++++++++++---
  target/hexagon/hex_common.py            | 32 ++++++++++++-------------
  target/hexagon/meson.build              |  2 +-
  13 files changed, 107 insertions(+), 47 deletions(-)
target/hexagon/gen_analyze_funcs.py +4 -2
index 54bac19724..3ac7cc2cfe 100755
@@ -78,11 +78,13 @@ def gen_analyze_func(f, tag, regs, imms):
 
 
  def main():
-    hex_common.read_common_files()
+    args = hex_common.parse_common_args(
+        "Emit functions analyzing register accesses"
+    )
      tagregs = hex_common.get_tagregs()
      tagimms = hex_common.get_tagimms()
 
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
          f.write("#ifndef HEXAGON_ANALYZE_FUNCS_C_INC\n")
          f.write("#define HEXAGON_ANALYZE_FUNCS_C_INC\n\n")
 
target/hexagon/gen_decodetree.py +15 -4
index a4fcd622c5..ce703af41d 100755
@@ -24,6 +24,7 @@
  import textwrap
  import iset
  import hex_common
+import argparse
 
  encs = {
      tag: "".join(reversed(iset.iset[tag]["enc"].replace(" ", "")))
@@ -191,8 +192,18 @@ def gen_decodetree_file(f, class_to_decode):
          f.write(f"{tag}\t{enc_str} @{tag}\n")
 
 
+def main():
+    parser = argparse.ArgumentParser(
+        description="Emit opaque macro calls with instruction semantics"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("class_to_decode", help="instruction class to decode")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+
+    hex_common.read_semantics_file(args.semantics)
+    with open(args.out, "w") as f:
+        gen_decodetree_file(f, args.class_to_decode)
+
  if __name__ == "__main__":
-    hex_common.read_semantics_file(sys.argv[1])
-    class_to_decode = sys.argv[2]
-    with open(sys.argv[3], "w") as f:
-        gen_decodetree_file(f, class_to_decode)
+    main()
target/hexagon/gen_helper_funcs.py +4 -3
index e9685bff2f..c1f806ac4b 100755
@@ -102,12 +102,13 @@ def gen_helper_function(f, tag, tagregs, tagimms):
 
 
  def main():
-    hex_common.read_common_files()
+    args = hex_common.parse_common_args(
+        "Emit helper function definitions for each instruction"
+    )
      tagregs = hex_common.get_tagregs()
      tagimms = hex_common.get_tagimms()
 
-    output_file = sys.argv[-1]
-    with open(output_file, "w") as f:
+    with open(args.out, "w") as f:
          for tag in hex_common.tags:
              ## Skip the priv instructions
              if "A_PRIV" in hex_common.attribdict[tag]:
target/hexagon/gen_helper_protos.py +4 -3
index fd2bfd0f36..77f8e0a6a3 100755
@@ -52,12 +52,13 @@ def gen_helper_prototype(f, tag, tagregs, tagimms):
 
 
  def main():
-    hex_common.read_common_files()
+    args = hex_common.parse_common_args(
+        "Emit helper function prototypes for each instruction"
+    )
      tagregs = hex_common.get_tagregs()
      tagimms = hex_common.get_tagimms()
 
-    output_file = sys.argv[-1]
-    with open(output_file, "w") as f:
+    with open(args.out, "w") as f:
          for tag in hex_common.tags:
              ## Skip the priv instructions
              if "A_PRIV" in hex_common.attribdict[tag]:
target/hexagon/gen_idef_parser_funcs.py +9 -2
index 72f11c68ca..2f6e826f76 100644
@@ -20,6 +20,7 @@
  import sys
  import re
  import string
+import argparse
  from io import StringIO
 
  import hex_common
@@ -43,13 +44,19 @@
  ## them are inputs ("in" prefix), while some others are outputs.
  ##
  def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        "Emit instruction implementations that can be fed to idef-parser"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
      hex_common.calculate_attribs()
      hex_common.init_registers()
      tagregs = hex_common.get_tagregs()
      tagimms = hex_common.get_tagimms()
 
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
          f.write('#include "macros.h.inc"\n\n')
 
          for tag in hex_common.tags:
target/hexagon/gen_op_attribs.py +9 -2
index 99448220da..bbbb02df3a 100755
@@ -21,16 +21,23 @@
  import re
  import string
  import hex_common
+import argparse
 
 
  def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        "Emit opaque macro calls containing instruction attributes"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
      hex_common.calculate_attribs()
 
      ##
      ##     Generate all the attributes associated with each instruction
      ##
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
          for tag in hex_common.tags:
              f.write(
                  f"OP_ATTRIB({tag},ATTRIBS("
target/hexagon/gen_opcodes_def.py +9 -2
index 536f0eb68a..94a19ff412 100755
@@ -21,15 +21,22 @@
  import re
  import string
  import hex_common
+import argparse
 
 
  def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        description="Emit opaque macro calls with instruction names"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
 
      ##
      ##     Generate a list of all the opcodes
      ##
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
          for tag in hex_common.tags:
              f.write(f"OPCODE({tag}),\n")
 
target/hexagon/gen_printinsn.py +9 -2
index 8bf4d0985c..d5f969960a 100755
@@ -21,6 +21,7 @@
  import re
  import string
  import hex_common
+import argparse
 
 
  ##
@@ -96,11 +97,17 @@ def spacify(s):
 
 
  def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        "Emit opaque macro calls with information for printing string representations of instrucions"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
 
      immext_casere = re.compile(r"IMMEXT\(([A-Za-z])")
 
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
          for tag in hex_common.tags:
              if not hex_common.behdict[tag]:
                  continue
target/hexagon/gen_tcg_func_table.py +9 -2
index 978ac1819b..299a39b1aa 100755
@@ -21,15 +21,22 @@
  import re
  import string
  import hex_common
+import argparse
 
 
  def main():
-    hex_common.read_semantics_file(sys.argv[1])
+    parser = argparse.ArgumentParser(
+        "Emit opaque macro calls with instruction semantics"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
      hex_common.calculate_attribs()
      tagregs = hex_common.get_tagregs()
      tagimms = hex_common.get_tagimms()
 
-    with open(sys.argv[-1], "w") as f:
+    with open(args.out, "w") as f:
          f.write("#ifndef HEXAGON_FUNC_TABLE_H\n")
          f.write("#define HEXAGON_FUNC_TABLE_H\n\n")
 
target/hexagon/gen_tcg_funcs.py +5 -4
index 05aa0a7855..c2ba91ddc0 100755
@@ -108,15 +108,16 @@ def gen_def_tcg_func(f, tag, tagregs, tagimms):
 
 
  def main():
-    is_idef_parser_enabled = hex_common.read_common_files()
+    args = hex_common.parse_common_args(
+        "Emit functions calling generated code implementing instruction semantics (helpers, idef-parser)"
+    )
      tagregs = hex_common.get_tagregs()
      tagimms = hex_common.get_tagimms()
 
-    output_file = sys.argv[-1]
-    with open(output_file, "w") as f:
+    with open(args.out, "w") as f:
          f.write("#ifndef HEXAGON_TCG_FUNCS_H\n")
          f.write("#define HEXAGON_TCG_FUNCS_H\n\n")
-        if is_idef_parser_enabled:
+        if args.idef_parser:
              f.write('#include "idef-generated-emitter.h.inc"\n\n')
 
          for tag in hex_common.tags:
target/hexagon/gen_trans_funcs.py +14 -3
index 30f0c73e0c..aea1c36f7d 100755
@@ -24,6 +24,7 @@
  import textwrap
  import iset
  import hex_common
+import argparse
 
  encs = {
      tag: "".join(reversed(iset.iset[tag]["enc"].replace(" ", "")))
@@ -136,8 +137,18 @@ def gen_trans_funcs(f):
          """))
 
 
-if __name__ == "__main__":
-    hex_common.read_semantics_file(sys.argv[1])
+def main():
+    parser = argparse.ArgumentParser(
+        description="Emit trans_*() functions to be called by instruction decoder"
+    )
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("out", help="output file")
+    args = parser.parse_args()
+    hex_common.read_semantics_file(args.semantics)
      hex_common.init_registers()
-    with open(sys.argv[2], "w") as f:
+    with open(args.out, "w") as f:
          gen_trans_funcs(f)
+
+
+if __name__ == "__main__":
+    main()
target/hexagon/hex_common.py +15 -17
index 15ed4980e4..bb20711a2e 100755
@@ -21,6 +21,7 @@
  import re
  import string
  import textwrap
+import argparse
 
  behdict = {}  # tag ->behavior
  semdict = {}  # tag -> semantics
@@ -1181,22 +1182,19 @@ def helper_args(tag, regs, imms):
      return args
 
 
-def read_common_files():
-    read_semantics_file(sys.argv[1])
-    read_overrides_file(sys.argv[2])
-    read_overrides_file(sys.argv[3])
-    ## Whether or not idef-parser is enabled is
-    ## determined by the number of arguments to
-    ## this script:
-    ##
-    ##   4 args. -> not enabled,
-    ##   5 args. -> idef-parser enabled.
-    ##
-    ## The 5:th arg. then holds a list of the successfully
-    ## parsed instructions.
-    is_idef_parser_enabled = len(sys.argv) > 5
-    if is_idef_parser_enabled:
-        read_idef_parser_enabled_file(sys.argv[4])
+def parse_common_args(desc):
+    parser = argparse.ArgumentParser(desc)
+    parser.add_argument("semantics", help="semantics file")
+    parser.add_argument("overrides", help="overrides file")
+    parser.add_argument("overrides_vec", help="vector overrides file")
+    parser.add_argument("out", help="output file")
+    parser.add_argument("--idef-parser", help="file of instructions translated by idef-parser")
+    args = parser.parse_args()
+    read_semantics_file(args.semantics)
+    read_overrides_file(args.overrides)
+    read_overrides_file(args.overrides_vec)
+    if args.idef_parser:
+        read_idef_parser_enabled_file(args.idef_parser)
      calculate_attribs()
      init_registers()
-    return is_idef_parser_enabled
+    return args
target/hexagon/meson.build +1 -1
index f1723778a6..bb4ebaae81 100644
@@ -346,7 +346,7 @@ if idef_parser_enabled and 'hexagon-linux-user' in target_dirs
      # Setup input and dependencies for the next step, this depends on whether or
      # not idef-parser is enabled
      helper_dep = [semantics_generated, idef_generated_tcg_c, idef_generated_tcg]
-    helper_in = [semantics_generated, gen_tcg_h, gen_tcg_hvx_h, idef_generated_list]
+    helper_in = [semantics_generated, gen_tcg_h, gen_tcg_hvx_h, '--idef-parser', idef_generated_list]
  else
      # Setup input and dependencies for the next step, this depends on whether or
      # not idef-parser is enabled
#63 lore raw

RFC PATCH 36/43 target/hexagon: Add temporary vector storage

In reply to Anton Johansson via

Temporary vectors in helper-to-tcg generated code are allocated from an array of bytes in CPUArchState, specified with --temp-vector-block.

This commits adds such a block of memory to CPUArchState, if CONFIG_HELPER_TO_TCG is set.

---
 target/hexagon/cpu.h | 4 ++++
 1 file changed, 4 insertions(+)
target/hexagon/cpu.h +4 -0
index 7be4b5769e..fa6ac83e01 100644
@@ -97,6 +97,10 @@ typedef struct CPUArchState {
     MMVector future_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
     MMVector tmp_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
 
+#ifdef CONFIG_HELPER_TO_TCG
+    uint8_t tmp_vmem[4096] QEMU_ALIGNED(16);
+#endif
+
     MMQReg QRegs[NUM_QREGS] QEMU_ALIGNED(16);
     MMQReg future_QRegs[NUM_QREGS] QEMU_ALIGNED(16);
 
Signature · 1 line
2.45.2
#64 lore raw

Re: [RFC PATCH v1 36/43] target/hexagon: Add temporary vector storage

Quoted 16 lines · Anton Johansson

Temporary vectors in helper-to-tcg generated code are allocated from an array of bytes in CPUArchState, specified with --temp-vector-block.

This commits adds such a block of memory to CPUArchState, if CONFIG_HELPER_TO_TCG is set.

---
  target/hexagon/cpu.h | 4 ++++
  1 file changed, 4 insertions(+)
target/hexagon/cpu.h +0 -0
index 7be4b5769e..fa6ac83e01 100644

target/hexagon/cpu.h typedef struct CPUArchState { · line 106

Quoted 10 lines
target/hexagon/cpu.h +4 -0
@@ -97,6 +97,10 @@ typedef struct CPUArchState {
      MMVector future_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
      MMVector tmp_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
 
+#ifdef CONFIG_HELPER_TO_TCG
+    uint8_t tmp_vmem[4096] QEMU_ALIGNED(16);
+#endif
+
      MMQReg QRegs[NUM_QREGS] QEMU_ALIGNED(16);
      MMQReg future_QRegs[NUM_QREGS] QEMU_ALIGNED(16);
 

Wow. Do you really require 4k in temp storage?

r~

#65 lore raw

Re: [RFC PATCH v1 36/43] target/hexagon: Add temporary vector storage

Quoted 12 lines · Richard Henderson
Quoted 11 lines · Anton Johansson

Temporary vectors in helper-to-tcg generated code are allocated from an array of bytes in CPUArchState, specified with --temp-vector-block.

This commits adds such a block of memory to CPUArchState, if CONFIG_HELPER_TO_TCG is set.

---
  target/hexagon/cpu.h | 4 ++++
  1 file changed, 4 insertions(+)
Quoted 15 lines

target/hexagon/cpu.h typedef struct CPUArchState { · line 104

Quoted 13 lines
target/hexagon/cpu.h +4 -0
index 7be4b5769e..fa6ac83e01 100644
@@ -97,6 +97,10 @@ typedef struct CPUArchState {
      MMVector future_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
      MMVector tmp_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
+#ifdef CONFIG_HELPER_TO_TCG
+    uint8_t tmp_vmem[4096] QEMU_ALIGNED(16);
+#endif
+
      MMQReg QRegs[NUM_QREGS] QEMU_ALIGNED(16);
      MMQReg future_QRegs[NUM_QREGS] QEMU_ALIGNED(16);

Wow. Do you really require 4k in temp storage?

No, 4k is overkill used during testing. But consider that Hexagon uses 128- and 256-byte vectors in some cases so if the emitted code uses say 5 temporaries in its computation we end up at 1280 bytes as an upper bound.

Two ideas here, we can:

1. Allow users to specify an upper bound on vector memory, and abort

     translation of helpers that surpass this, and;

2. Emit maximum number of bytes used for vector temporaries to a macro.

//Anton

#66 lore raw

Re: [RFC PATCH v1 36/43] target/hexagon: Add temporary vector storage

Quoted 27 lines · Anton Johansson via
Quoted 12 lines · Richard Henderson
Quoted 11 lines · Anton Johansson

Temporary vectors in helper-to-tcg generated code are allocated from an array of bytes in CPUArchState, specified with --temp-vector-block.

This commits adds such a block of memory to CPUArchState, if CONFIG_HELPER_TO_TCG is set.

---
   target/hexagon/cpu.h | 4 ++++
   1 file changed, 4 insertions(+)
Quoted 14 lines

target/hexagon/cpu.h typedef struct CPUArchState { · line 104

Quoted 13 lines
target/hexagon/cpu.h +4 -0
index 7be4b5769e..fa6ac83e01 100644
@@ -97,6 +97,10 @@ typedef struct CPUArchState {
       MMVector future_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
       MMVector tmp_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
+#ifdef CONFIG_HELPER_TO_TCG
+    uint8_t tmp_vmem[4096] QEMU_ALIGNED(16);
+#endif
+
       MMQReg QRegs[NUM_QREGS] QEMU_ALIGNED(16);
       MMQReg future_QRegs[NUM_QREGS] QEMU_ALIGNED(16);

Wow. Do you really require 4k in temp storage?

Quoted 4 lines

No, 4k is overkill used during testing. But consider that Hexagon uses 128- and 256-byte vectors in some cases so if the emitted code uses say 5 temporaries in its computation we end up at 1280 bytes as an upper bound.

Per-packet there should be a maximum of one temporary.  But per-TB it's unbound.  Could we/should we have some guidance to put the brakes on translation early if we encounter ~N temp references?

But maybe that's not needed since the temp space can be reused within a TB among packets.

Quoted 11 lines

Two ideas here, we can:

1. Allow users to specify an upper bound on vector memory, and abort

      translation of helpers that surpass this, and;

2. Emit maximum number of bytes used for vector temporaries to a macro.

//Anton

#67 lore raw

RE: [RFC PATCH v1 36/43] target/hexagon: Add temporary vector storage

Quoted 48 lines

-----Original Message-----
From: Brian Cain <[email protected]>
Sent: Tuesday, December 3, 2024 1:28 PM
To: Anton Johansson <[email protected]>; Richard Henderson <[email protected]>
Cc: [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]
Subject: Re: [RFC PATCH v1 36/43] target/hexagon: Add temporary vector storage

Quoted 13 lines · Anton Johansson via
Quoted 12 lines · Richard Henderson
Quoted 11 lines · Anton Johansson

Temporary vectors in helper-to-tcg generated code are allocated from an array of bytes in CPUArchState, specified with --temp-vector-block.

This commits adds such a block of memory to CPUArchState, if CONFIG_HELPER_TO_TCG is set.

---
   target/hexagon/cpu.h | 4 ++++
   1 file changed, 4 insertions(+)
Quoted 6 lines
Quoted 6 lines

target/hexagon/cpu.h typedef struct CPUArchState { · line 97

Quoted 6 lines
target/hexagon/cpu.h index renamed from target/hexagon/cpu.h +0 -0

7be4b5769e..fa6ac83e01 100644

target/hexagon/cpu.h +0 -0
@@ -97,6 +97,10 @@ typedef struct CPUArchState {
       MMVector future_VRegs[VECTOR_TEMPS_MAX]

QEMU_ALIGNED(16);

Quoted 7 lines
Quoted 7 lines

target/hexagon/cpu.h typedef struct CPUArchState { · line 105

Quoted 6 lines
target/hexagon/cpu.h +3 -0
       MMVector tmp_VRegs[VECTOR_TEMPS_MAX] QEMU_ALIGNED(16);
+#ifdef CONFIG_HELPER_TO_TCG
+    uint8_t tmp_vmem[4096] QEMU_ALIGNED(16); #endif
+
       MMQReg QRegs[NUM_QREGS] QEMU_ALIGNED(16);
       MMQReg future_QRegs[NUM_QREGS] QEMU_ALIGNED(16);

Wow. Do you really require 4k in temp storage?

Quoted 6 lines

No, 4k is overkill used during testing. But consider that Hexagon uses
128- and 256-byte vectors in some cases so if the emitted code uses say
5 temporaries in its computation we end up at 1280 bytes as an upper bound.

Quoted 6 lines

Per-packet there should be a maximum of one temporary. But per-TB it's unbound. Could we/should we have some guidance to put the brakes on translation early if we encounter ~N temp references?

But maybe that's not needed since the temp space can be reused within a TB among packets.

You should only need enough temporaries for one instruction. There are already temporaries (future_VRegs, tmp_VRegs, future_QRegs) in CPUHexagonState to handle the needs within a packet. There shouldn't be any temps needed between the packets in a TB.

The number of temps needed for a given instruction is determined by the compiler - version, level of optimization. So, you can determine this by compiling all the instructions (i.e., build qemu). I'd recommend having a few extra to future proof against changes to LLVM.

Taylor

#68 lore raw

RFC PATCH 37/43 target/hexagon: Make HVX vector args. restrict *

In reply to Anton Johansson via

If pointer arguments to HVX helper functions are not marked restrict *, then LLVM will assume that input vectors may alias and emit runtime checks.

---
 target/hexagon/mmvec/macros.h | 36 +++++++++++++++++------------------
 1 file changed, 18 insertions(+), 18 deletions(-)
target/hexagon/mmvec/macros.h +18 -18
index 1ceb9453ee..dfaefc6b26 100644
@@ -23,26 +23,26 @@
 #include "mmvec/system_ext_mmvec.h"
 
 #ifndef QEMU_GENERATE
-#define VdV      (*(MMVector *)(VdV_void))
-#define VsV      (*(MMVector *)(VsV_void))
-#define VuV      (*(MMVector *)(VuV_void))
-#define VvV      (*(MMVector *)(VvV_void))
-#define VwV      (*(MMVector *)(VwV_void))
-#define VxV      (*(MMVector *)(VxV_void))
-#define VyV      (*(MMVector *)(VyV_void))
+#define VdV      (*(MMVector * restrict)(VdV_void))
+#define VsV      (*(MMVector * restrict)(VsV_void))
+#define VuV      (*(MMVector * restrict)(VuV_void))
+#define VvV      (*(MMVector * restrict)(VvV_void))
+#define VwV      (*(MMVector * restrict)(VwV_void))
+#define VxV      (*(MMVector * restrict)(VxV_void))
+#define VyV      (*(MMVector * restrict)(VyV_void))
 
-#define VddV     (*(MMVectorPair *)(VddV_void))
-#define VuuV     (*(MMVectorPair *)(VuuV_void))
-#define VvvV     (*(MMVectorPair *)(VvvV_void))
-#define VxxV     (*(MMVectorPair *)(VxxV_void))
+#define VddV     (*(MMVectorPair * restrict)(VddV_void))
+#define VuuV     (*(MMVectorPair * restrict)(VuuV_void))
+#define VvvV     (*(MMVectorPair * restrict)(VvvV_void))
+#define VxxV     (*(MMVectorPair * restrict)(VxxV_void))
 
-#define QeV      (*(MMQReg *)(QeV_void))
-#define QdV      (*(MMQReg *)(QdV_void))
-#define QsV      (*(MMQReg *)(QsV_void))
-#define QtV      (*(MMQReg *)(QtV_void))
-#define QuV      (*(MMQReg *)(QuV_void))
-#define QvV      (*(MMQReg *)(QvV_void))
-#define QxV      (*(MMQReg *)(QxV_void))
+#define QeV      (*(MMQReg * restrict)(QeV_void))
+#define QdV      (*(MMQReg * restrict)(QdV_void))
+#define QsV      (*(MMQReg * restrict)(QsV_void))
+#define QtV      (*(MMQReg * restrict)(QtV_void))
+#define QuV      (*(MMQReg * restrict)(QuV_void))
+#define QvV      (*(MMQReg * restrict)(QvV_void))
+#define QxV      (*(MMQReg * restrict)(QxV_void))
 #endif
 
 #define LOG_VTCM_BYTE(VA, MASK, VAL, IDX) \
Signature · 1 line
2.45.2
#69 lore raw

Re: [RFC PATCH v1 37/43] target/hexagon: Make HVX vector args. restrict *

Quoted 46 lines · Anton Johansson

If pointer arguments to HVX helper functions are not marked restrict *, then LLVM will assume that input vectors may alias and emit runtime checks.

---
  target/hexagon/mmvec/macros.h | 36 +++++++++++++++++------------------
  1 file changed, 18 insertions(+), 18 deletions(-)
target/hexagon/mmvec/macros.h +11 -16
index 1ceb9453ee..dfaefc6b26 100644
@@ -23,26 +23,26 @@
  #include "mmvec/system_ext_mmvec.h"
 
  #ifndef QEMU_GENERATE
-#define VdV      (*(MMVector *)(VdV_void))
-#define VsV      (*(MMVector *)(VsV_void))
-#define VuV      (*(MMVector *)(VuV_void))
-#define VvV      (*(MMVector *)(VvV_void))
-#define VwV      (*(MMVector *)(VwV_void))
-#define VxV      (*(MMVector *)(VxV_void))
-#define VyV      (*(MMVector *)(VyV_void))
+#define VdV      (*(MMVector * restrict)(VdV_void))
+#define VsV      (*(MMVector * restrict)(VsV_void))
+#define VuV      (*(MMVector * restrict)(VuV_void))
+#define VvV      (*(MMVector * restrict)(VvV_void))
+#define VwV      (*(MMVector * restrict)(VwV_void))
+#define VxV      (*(MMVector * restrict)(VxV_void))
+#define VyV      (*(MMVector * restrict)(VyV_void))
 
-#define VddV     (*(MMVectorPair *)(VddV_void))
-#define VuuV     (*(MMVectorPair *)(VuuV_void))
-#define VvvV     (*(MMVectorPair *)(VvvV_void))
-#define VxxV     (*(MMVectorPair *)(VxxV_void))
+#define VddV     (*(MMVectorPair * restrict)(VddV_void))
+#define VuuV     (*(MMVectorPair * restrict)(VuuV_void))
+#define VvvV     (*(MMVectorPair * restrict)(VvvV_void))
+#define VxxV     (*(MMVectorPair * restrict)(VxxV_void))
 
-#define QeV      (*(MMQReg *)(QeV_void))
-#define QdV      (*(MMQReg *)(QdV_void))
-#define QsV      (*(MMQReg *)(QsV_void))
-#define QtV      (*(MMQReg *)(QtV_void))
-#define QuV      (*(MMQReg *)(QuV_void))

target/hexagon/mmvec/macros.h line 46

Quoted 10 lines
target/hexagon/mmvec/macros.h +7 -2
-#define QvV      (*(MMQReg *)(QvV_void))
-#define QxV      (*(MMQReg *)(QxV_void))
+#define QeV      (*(MMQReg * restrict)(QeV_void))
+#define QdV      (*(MMQReg * restrict)(QdV_void))
+#define QsV      (*(MMQReg * restrict)(QsV_void))
+#define QtV      (*(MMQReg * restrict)(QtV_void))
+#define QuV      (*(MMQReg * restrict)(QuV_void))
+#define QvV      (*(MMQReg * restrict)(QvV_void))
+#define QxV      (*(MMQReg * restrict)(QxV_void))
  #endif

Maybe we need to fix scripts/checkpatch.pl along?

ERROR: "foo * bar" should be "foo *bar"
#31: FILE: target/hexagon/mmvec/macros.h:26:
+#define VdV (*(MMVector * restrict)(VdV_void))

ERROR: "foo * bar" should be "foo *bar"
#32: FILE: target/hexagon/mmvec/macros.h:27:
+#define VsV (*(MMVector * restrict)(VsV_void))

ERROR: "foo * bar" should be "foo *bar"
#33: FILE: target/hexagon/mmvec/macros.h:28:
+#define VuV (*(MMVector * restrict)(VuV_void))

[...]

#70 lore raw

Re: [RFC PATCH v1 37/43] target/hexagon: Make HVX vector args. restrict *

Quoted 15 lines · Philippe Mathieu-Daudé
Quoted 8 lines
target/hexagon/mmvec/macros.h +7 -0
+#define QeV      (*(MMQReg * restrict)(QeV_void))
+#define QdV      (*(MMQReg * restrict)(QdV_void))
+#define QsV      (*(MMQReg * restrict)(QsV_void))
+#define QtV      (*(MMQReg * restrict)(QtV_void))
+#define QuV      (*(MMQReg * restrict)(QuV_void))
+#define QvV      (*(MMQReg * restrict)(QvV_void))
+#define QxV      (*(MMQReg * restrict)(QxV_void))

  #endif

Maybe we need to fix scripts/checkpatch.pl along?

ERROR: "foo * bar" should be "foo *bar"
#31: FILE: target/hexagon/mmvec/macros.h:26:
+#define VdV      (*(MMVector * restrict)(VdV_void))

Quoted 7 lines

ERROR: "foo * bar" should be "foo *bar"
#32: FILE: target/hexagon/mmvec/macros.h:27:
+#define VsV      (*(MMVector * restrict)(VsV_void))

ERROR: "foo * bar" should be "foo *bar"
#33: FILE: target/hexagon/mmvec/macros.h:28:
+#define VuV      (*(MMVector * restrict)(VuV_void))

I think checkpatch.pl has a point here. :)

Paolo

#71 lore raw

Re: [RFC PATCH v1 37/43] target/hexagon: Make HVX vector args. restrict *

Quoted 20 lines · Paolo Bonzini
Quoted 19 lines · Philippe Mathieu-Daudé
Quoted 8 lines
target/hexagon/mmvec/macros.h +7 -0
+#define QeV      (*(MMQReg * restrict)(QeV_void))
+#define QdV      (*(MMQReg * restrict)(QdV_void))
+#define QsV      (*(MMQReg * restrict)(QsV_void))
+#define QtV      (*(MMQReg * restrict)(QtV_void))
+#define QuV      (*(MMQReg * restrict)(QuV_void))
+#define QvV      (*(MMQReg * restrict)(QvV_void))
+#define QxV      (*(MMQReg * restrict)(QxV_void))

  #endif

Maybe we need to fix scripts/checkpatch.pl along?

ERROR: "foo * bar" should be "foo *bar"
#31: FILE: target/hexagon/mmvec/macros.h:26:
+#define VdV      (*(MMVector * restrict)(VdV_void))

ERROR: "foo * bar" should be "foo *bar"
#32: FILE: target/hexagon/mmvec/macros.h:27:
+#define VsV      (*(MMVector * restrict)(VsV_void))

Quoted 5 lines
Quoted 3 lines

ERROR: "foo * bar" should be "foo *bar"
#33: FILE: target/hexagon/mmvec/macros.h:28:
+#define VuV      (*(MMVector * restrict)(VuV_void))

I think checkpatch.pl has a point here. :)

I'll switch to *restrict!:)

//Anton

Reviewed-by
#72 lore raw

Re: [RFC PATCH v1 37/43] target/hexagon: Make HVX vector args. restrict *

Quoted 20 lines · Anton Johansson via
Quoted 19 lines · Paolo Bonzini
Quoted 18 lines · Philippe Mathieu-Daudé

target/hexagon/mmvec/macros.h line 46

Quoted 8 lines
target/hexagon/mmvec/macros.h +7 -0
+#define QeV      (*(MMQReg * restrict)(QeV_void))
+#define QdV      (*(MMQReg * restrict)(QdV_void))
+#define QsV      (*(MMQReg * restrict)(QsV_void))
+#define QtV      (*(MMQReg * restrict)(QtV_void))
+#define QuV      (*(MMQReg * restrict)(QuV_void))
+#define QvV      (*(MMQReg * restrict)(QvV_void))
+#define QxV      (*(MMQReg * restrict)(QxV_void))
   #endif

Maybe we need to fix scripts/checkpatch.pl along?

ERROR: "foo * bar" should be "foo *bar"
#31: FILE: target/hexagon/mmvec/macros.h:26:
+#define VdV      (*(MMVector * restrict)(VdV_void))

ERROR: "foo * bar" should be "foo *bar"
#32: FILE: target/hexagon/mmvec/macros.h:27:
+#define VsV      (*(MMVector * restrict)(VsV_void))

Quoted 5 lines
Quoted 4 lines
Quoted 3 lines

ERROR: "foo * bar" should be "foo *bar"
#33: FILE: target/hexagon/mmvec/macros.h:28:
+#define VuV      (*(MMVector * restrict)(VuV_void))

I think checkpatch.pl has a point here. :)

I'll switch to *restrict!:)

With this change to fix checkpatch,

Quoted 3 lines

//Anton

#73 lore raw

RFC PATCH 38/43 target/hexagon: Use cpu_mapping to map env -> TCG

In reply to Anton Johansson via

Replaces previous calls to tcg_global_mem_new*() with a declarative global array of cpu_mapping structs. This array can be used to initialize all TCG globals with one function call from the target, and may additionally be used from LLVM based tools to map between offsets into a struct and a mapped TCGv global.

---
 target/hexagon/translate.c | 116 +++++++++++++++++++++----------------
 1 file changed, 65 insertions(+), 51 deletions(-)
target/hexagon/translate.c +65 -51
index 4b1bee3c6d..f9a9de35fe 100644
@@ -15,6 +15,7 @@
  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "qemu/typedefs.h"
 #define QEMU_GENERATE
 #include "qemu/osdep.h"
 #include "cpu.h"
@@ -32,6 +33,7 @@
 #include "translate.h"
 #include "genptr.h"
 #include "printinsn.h"
+#include "tcg/tcg-global-mappings.h"
 
 #define HELPER_H "helper.h"
 #include "exec/helper-info.c.inc"
@@ -1093,7 +1095,6 @@ void gen_intermediate_code(CPUState *cs, TranslationBlock *tb, int *max_insns,
 }
 
 #define NAME_LEN               64
-static char reg_written_names[TOTAL_PER_THREAD_REGS][NAME_LEN];
 static char store_addr_names[STORES_MAX][NAME_LEN];
 static char store_width_names[STORES_MAX][NAME_LEN];
 static char store_val32_names[STORES_MAX][NAME_LEN];
@@ -1101,63 +1102,73 @@ static char store_val64_names[STORES_MAX][NAME_LEN];
 static char vstore_addr_names[VSTORES_MAX][NAME_LEN];
 static char vstore_size_names[VSTORES_MAX][NAME_LEN];
 static char vstore_pending_names[VSTORES_MAX][NAME_LEN];
+#if HEX_DEBUG
+static const char *reg_written_names_ptr[TOTAL_PER_THREAD_REGS];
+#endif
+static const char *store_addr_names_ptr[STORES_MAX];
+static const char *store_width_names_ptr[STORES_MAX];
+static const char *store_val32_names_ptr[STORES_MAX];
+static const char *store_val64_names_ptr[STORES_MAX];
+
+cpu_tcg_mapping tcg_global_mappings[] = {
+    /* General purpose and predicate registers */
+    CPU_TCG_MAP_ARRAY(CPUArchState, hex_gpr,  gpr,  hexagon_regnames),
+    CPU_TCG_MAP_ARRAY(CPUArchState, hex_pred, pred, hexagon_prednames),
+
+    /* Misc */
+    CPU_TCG_MAP(CPUArchState, hex_new_value_usr,    new_value_usr,    "new_value_usr"),
+    CPU_TCG_MAP(CPUArchState, hex_slot_cancelled,   slot_cancelled,   "slot_cancelled"),
+    CPU_TCG_MAP(CPUArchState, hex_llsc_addr,        llsc_addr,        "llsc_addr"),
+    CPU_TCG_MAP(CPUArchState, hex_llsc_val,         llsc_val,         "llsc_val"),
+    CPU_TCG_MAP(CPUArchState, hex_llsc_val_i64,     llsc_val_i64,     "llsc_val_i64"),
 
-void hexagon_translate_init(void)
-{
-    int i;
-
-    opcode_init();
-
-    for (i = 0; i < TOTAL_PER_THREAD_REGS; i++) {
-        hex_gpr[i] = tcg_global_mem_new(tcg_env,
-            offsetof(CPUHexagonState, gpr[i]),
-            hexagon_regnames[i]);
-
-        if (HEX_DEBUG) {
-            snprintf(reg_written_names[i], NAME_LEN, "reg_written_%s",
-                     hexagon_regnames[i]);
-            hex_reg_written[i] = tcg_global_mem_new(tcg_env,
-                offsetof(CPUHexagonState, reg_written[i]),
-                reg_written_names[i]);
-        }
-    }
-    hex_new_value_usr = tcg_global_mem_new(tcg_env,
-        offsetof(CPUHexagonState, new_value_usr), "new_value_usr");
+    /*
+     * New general purpose and predicate register values,
+     * and reg_written used in debugging
+     */
+#if HEX_DEBUG
+    CPU_TCG_MAP_ARRAY(hex_reg_written,    reg_written,    reg_written_names_ptr),
+#endif
+
+    /* Logging stores */
+    CPU_TCG_MAP_ARRAY_OF_STRUCTS(CPUArchState, hex_store_addr,  mem_log_stores, va,     store_addr_names_ptr),
+    CPU_TCG_MAP_ARRAY_OF_STRUCTS(CPUArchState, hex_store_width, mem_log_stores, width,  store_width_names_ptr),
+    CPU_TCG_MAP_ARRAY_OF_STRUCTS(CPUArchState, hex_store_val32, mem_log_stores, data32, store_val32_names_ptr),
+    CPU_TCG_MAP_ARRAY_OF_STRUCTS(CPUArchState, hex_store_val64, mem_log_stores, data64, store_val64_names_ptr),
+};
 
-    for (i = 0; i < NUM_PREGS; i++) {
-        hex_pred[i] = tcg_global_mem_new(tcg_env,
-            offsetof(CPUHexagonState, pred[i]),
-            hexagon_prednames[i]);
-    }
-    hex_slot_cancelled = tcg_global_mem_new(tcg_env,
-        offsetof(CPUHexagonState, slot_cancelled), "slot_cancelled");
-    hex_llsc_addr = tcg_global_mem_new(tcg_env,
-        offsetof(CPUHexagonState, llsc_addr), "llsc_addr");
-    hex_llsc_val = tcg_global_mem_new(tcg_env,
-        offsetof(CPUHexagonState, llsc_val), "llsc_val");
-    hex_llsc_val_i64 = tcg_global_mem_new_i64(tcg_env,
-        offsetof(CPUHexagonState, llsc_val_i64), "llsc_val_i64");
-    for (i = 0; i < STORES_MAX; i++) {
-        snprintf(store_addr_names[i], NAME_LEN, "store_addr_%d", i);
-        hex_store_addr[i] = tcg_global_mem_new(tcg_env,
-            offsetof(CPUHexagonState, mem_log_stores[i].va),
-            store_addr_names[i]);
+size_t tcg_global_mapping_count = ARRAY_SIZE(tcg_global_mappings);
 
+static void init_cpu_reg_names(void) {
+    /*
+     * Create register names and store them in `*_names`,
+     * then copy to and array of pointers in `*_names_ptr`
+     * which is easier to pass around.
+     */
+#if HEX_DEBUG
+    for (int i = 0; i < TOTAL_PER_THREAD_REGS; ++i) {
+        snprintf(reg_written_names[i], NAME_LEN, "reg_written_%s", hexagon_regnames[i]);
+        reg_written_names_ptr[i] = reg_written_names[i];
+    }
+#endif
+    for (int i = 0; i < STORES_MAX; ++i) {
+        snprintf(store_addr_names[i],  NAME_LEN, "store_addr_%d",  i);
         snprintf(store_width_names[i], NAME_LEN, "store_width_%d", i);
-        hex_store_width[i] = tcg_global_mem_new(tcg_env,
-            offsetof(CPUHexagonState, mem_log_stores[i].width),
-            store_width_names[i]);
-
         snprintf(store_val32_names[i], NAME_LEN, "store_val32_%d", i);
-        hex_store_val32[i] = tcg_global_mem_new(tcg_env,
-            offsetof(CPUHexagonState, mem_log_stores[i].data32),
-            store_val32_names[i]);
-
         snprintf(store_val64_names[i], NAME_LEN, "store_val64_%d", i);
-        hex_store_val64[i] = tcg_global_mem_new_i64(tcg_env,
-            offsetof(CPUHexagonState, mem_log_stores[i].data64),
-            store_val64_names[i]);
+        store_addr_names_ptr[i]  = store_addr_names[i];
+        store_width_names_ptr[i] = store_width_names[i];
+        store_val32_names_ptr[i] = store_val32_names[i];
+        store_val64_names_ptr[i] = store_val64_names[i];
     }
+}
+
+void hexagon_translate_init(void)
+{
+    int i;
+
+    opcode_init();
+
     for (i = 0; i < VSTORES_MAX; i++) {
         snprintf(vstore_addr_names[i], NAME_LEN, "vstore_addr_%d", i);
         hex_vstore_addr[i] = tcg_global_mem_new(tcg_env,
@@ -1174,4 +1185,7 @@ void hexagon_translate_init(void)
             offsetof(CPUHexagonState, vstore_pending[i]),
             vstore_pending_names[i]);
     }
+
+    init_cpu_reg_names();
+    init_cpu_tcg_mappings(tcg_global_mappings, tcg_global_mapping_count);
 }
Signature · 1 line
2.45.2
#74 lore raw

RFC PATCH 39/43 target/hexagon: Keep gen_slotval/check_noshuf for helper-to-tcg

In reply to Anton Johansson via

Makes sure gen_slotval() and check_noshuf() remains defined when helper-to-tcg and idef-parser are both used. gen_slotval() is needed for creating a TCGv of the slot value fed to helpers (generated helper-to-tcg code), and check_noshuf() is needed for helper definitions used as input to helper-to-tcg.

---
 target/hexagon/genptr.c    | 2 +-
 target/hexagon/op_helper.c | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
target/hexagon/genptr.c +1 -1
index dbae6c570a..ea3ccf649a 100644
@@ -399,7 +399,7 @@ static inline void gen_store_conditional8(DisasContext *ctx,
     tcg_gen_movi_tl(hex_llsc_addr, ~0);
 }
 
-#ifndef CONFIG_HEXAGON_IDEF_PARSER
+#if !defined(CONFIG_HEXAGON_IDEF_PARSER) || defined(CONFIG_HELPER_TO_TCG)
 static TCGv gen_slotval(DisasContext *ctx)
 {
     int slotval = (ctx->pkt->pkt_has_store_s1 & 1) | (ctx->insn->slot << 1);
target/hexagon/op_helper.c +1 -1
index 90e7aaa097..0f9c6ab19f 100644
@@ -567,7 +567,7 @@ void HELPER(probe_pkt_scalar_hvx_stores)(CPUHexagonState *env, int mask)
     }
 }
 
-#ifndef CONFIG_HEXAGON_IDEF_PARSER
+#if !defined(CONFIG_HEXAGON_IDEF_PARSER) || defined(CONFIG_HELPER_TO_TCG)
 /*
  * mem_noshuf
  * Section 5.5 of the Hexagon V67 Programmer's Reference Manual
Signature · 1 line
2.45.2
#75 lore raw

RFC PATCH 40/43 target/hexagon: Emit annotations for helpers

In reply to Anton Johansson via

Adds the following LLVM_ANNOTATE attributes to helper functions generated by Hexagon:

1. "helper-to-tcg", to specify that a given helper functions should be

     translated, and;

2. "immediate: ..." to make sure immediate arguments to helper functions remain immediates in the emitted TCG code (e.g. slot).

3. "ptr-to-offset: ..." to make sure pointer arguments are treated as immediates representing an offset into the CPU state, needed to work with gvec.

Two functions are also added to hex_common.py, to firstly parse the generated file containing all successfully translated helper functions, and secondly to expose the indices of immediate and pointer (vector) arguments to helper functions. The latter is needed to generate the input of helper-to-tcg.

---
 target/hexagon/gen_helper_funcs.py  | 17 ++++++++++-
 target/hexagon/gen_helper_protos.py |  2 +-
 target/hexagon/gen_tcg_funcs.py     |  2 +-
 target/hexagon/hex_common.py        | 45 +++++++++++++++++++++++------
 target/hexagon/op_helper.c          |  1 +
 5 files changed, 55 insertions(+), 12 deletions(-)
target/hexagon/gen_helper_funcs.py +16 -1
index c1f806ac4b..7f0844d843 100755
@@ -41,9 +41,23 @@ def gen_helper_function(f, tag, tagregs, tagimms):
     ret_type = hex_common.helper_ret_type(tag, regs).func_arg
 
     declared = []
-    for arg in hex_common.helper_args(tag, regs, imms):
+    helper_args, imm_inds, hvx_inds = hex_common.helper_args(tag, regs, imms)
+    for arg in helper_args:
         declared.append(arg.func_arg)
 
+    ## Specify that helpers should be translated by helper-to-tcg
+    f.write(f'LLVM_ANNOTATE("helper-to-tcg")\n')
+    ## Specify which arguments to the helper function should be treated as
+    ## immediate arguments
+    if len(imm_inds) > 0:
+        imm_inds_str = ','.join(str(i) for i in imm_inds)
+        f.write(f'LLVM_ANNOTATE("immediate: {imm_inds_str}")\n')
+    ## Specify which arguments to the helper function should be treated as
+    ## gvec vectors
+    if len(hvx_inds) > 0:
+        hvx_inds_str = ','.join(str(i) for i in hvx_inds)
+        f.write(f'LLVM_ANNOTATE("ptr-to-offset: {hvx_inds_str}")\n')
+
     arguments = ", ".join(declared)
     f.write(f"{ret_type} HELPER({tag})({arguments})\n")
     f.write("{\n")
@@ -51,6 +65,7 @@ def gen_helper_function(f, tag, tagregs, tagimms):
         f.write(hex_common.code_fmt(f"""\
             uint32_t EA;
         """))
+
     ## Declare the return variable
     if not hex_common.is_predicated(tag):
         for regtype, regid in regs:
target/hexagon/gen_helper_protos.py +1 -1
index 77f8e0a6a3..2082757891 100755
@@ -36,7 +36,7 @@ def gen_helper_prototype(f, tag, tagregs, tagimms):
     ret_type = hex_common.helper_ret_type(tag, regs).proto_arg
     declared.append(ret_type)
 
-    for arg in hex_common.helper_args(tag, regs, imms):
+    for arg in hex_common.helper_args(tag, regs, imms)[0]:
         declared.append(arg.proto_arg)
 
     arguments = ", ".join(declared)
target/hexagon/gen_tcg_funcs.py +1 -1
index c2ba91ddc0..a06edeb9de 100755
@@ -85,7 +85,7 @@ def gen_tcg_func(f, tag, regs, imms):
         if ret_type != "void":
             declared.append(ret_type)
 
-        for arg in hex_common.helper_args(tag, regs, imms):
+        for arg in hex_common.helper_args(tag, regs, imms)[0]:
             declared.append(arg.call_arg)
 
         arguments = ", ".join(declared)
target/hexagon/hex_common.py +36 -9

176 lines not on this page · raw message

target/hexagon/op_helper.c +1 -0
index 0f9c6ab19f..182e8fdeab 100644
@@ -31,6 +31,7 @@
 #include "mmvec/macros.h"
 #include "op_helper.h"
 #include "translate.h"
+#include "helper-to-tcg/annotate.h"
 
 #define SF_BIAS        127
 #define SF_MANTBITS    23
Signature · 1 line
2.45.2
#76 lore raw

RFC PATCH 41/43 target/hexagon: Manually call generated HVX instructions

In reply to Anton Johansson via

For HVX instructions that were successfully translated by helper-to-tcg, emit calls to emit_*() "manually" from generate_*(). Recall that scalar instructions translated by helper-to-tcg are automatically called by a hook in tcg_gen_callN.

---
 target/hexagon/gen_tcg_funcs.py | 13 ++++++++
 target/hexagon/hex_common.py    | 57 +++++++++++++++++++++++++++++++++
 2 files changed, 70 insertions(+)
target/hexagon/gen_tcg_funcs.py +13 -0
index a06edeb9de..fd8dbf3724 100755
@@ -75,7 +75,18 @@ def gen_tcg_func(f, tag, regs, imms):
 
         arguments = ", ".join(["ctx", "ctx->insn", "ctx->pkt"] + declared)
         f.write(f"    emit_{tag}({arguments});\n")
+    elif hex_common.is_helper_to_tcg_enabled(tag) and tag.startswith("V6_"):
+        ## For vector functions translated by helper-to-tcg we need to
+        ## manually call the emitted code.  All other instructions translated
+        ## are automatically called by the helper-functions dispatcher in
+        ## tcg_gen_callN.
+        declared = []
+        ## Handle registers
+        for arg in hex_common.helper_to_tcg_hvx_call_args(tag, regs, imms):
+            declared.append(arg)
 
+        arguments = ", ".join(declared)
+        f.write(f"    emit_{tag}({arguments});\n")
     elif hex_common.skip_qemu_helper(tag):
         f.write(f"    fGEN_TCG_{tag}({hex_common.semdict[tag]});\n")
     else:
@@ -119,6 +130,8 @@ def main():
         f.write("#define HEXAGON_TCG_FUNCS_H\n\n")
         if args.idef_parser:
             f.write('#include "idef-generated-emitter.h.inc"\n\n')
+        if args.helper_to_tcg:
+            f.write('#include "helper-to-tcg-emitted.h"\n\n')
 
         for tag in hex_common.tags:
             ## Skip the priv instructions
target/hexagon/hex_common.py +57 -0

75 lines not on this page · raw message

Signature · 1 line
2.45.2
#77 lore raw

RFC PATCH 42/43 target/hexagon: Only translate w. idef-parser if helper-to-tcg failed

In reply to Anton Johansson via

Only generate input functions to idef-parser for instructions which failed to be translated by helper-to-tcg.

---
 target/hexagon/gen_idef_parser_funcs.py | 6 ++++++
 1 file changed, 6 insertions(+)
target/hexagon/gen_idef_parser_funcs.py +6 -0
index 2f6e826f76..08ae94a646 100644
@@ -49,10 +49,13 @@ def main():
     )
     parser.add_argument("semantics", help="semantics file")
     parser.add_argument("out", help="output file")
+    parser.add_argument("--helper-to-tcg", help="file of instructions translated by helper-to-tcg")
     args = parser.parse_args()
     hex_common.read_semantics_file(args.semantics)
     hex_common.calculate_attribs()
     hex_common.init_registers()
+    if args.helper_to_tcg:
+        hex_common.read_helper_to_tcg_enabled_file(args.helper_to_tcg)
     tagregs = hex_common.get_tagregs()
     tagimms = hex_common.get_tagimms()
 
@@ -60,6 +63,9 @@ def main():
         f.write('#include "macros.h.inc"\n\n')
 
         for tag in hex_common.tags:
+            ## Skip instructions translated by helper-to-tcg
+            if hex_common.is_helper_to_tcg_enabled(tag):
+                continue
             ## Skip the priv instructions
             if "A_PRIV" in hex_common.attribdict[tag]:
                 continue
Signature · 1 line
2.45.2
#78 lore raw

RFC PATCH 43/43 target/hexagon: Use helper-to-tcg

In reply to Anton Johansson via

Modifies meson.build to use helper-to-tcg for automatic translation of helper functions. Any helper functions with the "helper-to-tcg" attribute will be automatically translated to TCG.

Order of code generation is changed, and helper functions are always generated first, for all instructions. Helper functions are needed as input helper-to-tcg. Next, input to idef-parser is generated for all instructions that were not successfully translated by helper-to-tcg.

As such, a majority of instructions will be translated by helper-to-tcg, and the remaining instructions fed through idef-parser can be reduced moving forward.

---
 target/hexagon/meson.build | 151 +++++++++++++++++++++++++++----------
 1 file changed, 111 insertions(+), 40 deletions(-)
target/hexagon/meson.build +111 -40
index bb4ebaae81..563d60e976 100644
@@ -262,22 +262,127 @@ hexagon_ss.add(files(
     'mmvec/system_ext_mmvec.c',
 ))
 
+helper_dep = [semantics_generated]
+helper_in = [semantics_generated, gen_tcg_h, gen_tcg_hvx_h]
+
+#
+# Step 5
+# We use Python scripts to generate the following files
+#     helper_protos_generated.h.inc
+#     helper_funcs_generated.c.inc
+#     analyze_funcs_generated.c.inc
+#
+helper_protos_generated = custom_target(
+    'helper_protos_generated.h.inc',
+    output: 'helper_protos_generated.h.inc',
+    depends: helper_dep,
+    depend_files: [hex_common_py, gen_tcg_h, gen_tcg_hvx_h],
+    command: [python, files('gen_helper_protos.py'), helper_in, '@OUTPUT@'],
+)
+hexagon_ss.add(helper_protos_generated)
+
+helper_funcs_generated = custom_target(
+    'helper_funcs_generated.c.inc',
+    output: 'helper_funcs_generated.c.inc',
+    depends: helper_dep,
+    depend_files: [hex_common_py, gen_tcg_h, gen_tcg_hvx_h],
+    command: [python, files('gen_helper_funcs.py'), helper_in, '@OUTPUT@'],
+)
+hexagon_ss.add(helper_funcs_generated)
+
+analyze_funcs_generated = custom_target(
+    'analyze_funcs_generated.c.inc',
+    output: 'analyze_funcs_generated.c.inc',
+    depends: helper_dep,
+    depend_files: [hex_common_py, gen_tcg_h, gen_tcg_hvx_h],
+    command: [python, files('gen_analyze_funcs.py'), helper_in, '@OUTPUT@'],
+)
+hexagon_ss.add(analyze_funcs_generated)
+
+#
+# Step 6
+# If enabled, run helper-to-tcg to attempt to translate any remaining
+# helper functions, producing:
+#     helper-to-tcg-emitted.c
+#     helper-to-tcg-emitted.h
+#     helper-to-tcg-enabled
+#     helper-to-tcg-log
 #
-# Step 4.5
+
+if helper_to_tcg_enabled
+    helper_to_tcg = subproject('helper-to-tcg', required: true)
+    helper_to_tcg_get_llvm_ir_cmd = helper_to_tcg.get_variable('get_llvm_ir_cmd')
+    helper_to_tcg_pipeline = helper_to_tcg.get_variable('pipeline')
+endif
+
+idef_command_extra = []
+idef_dep_extra = []
+if helper_to_tcg_enabled
+    helper_to_tcg_input_files = [
+        meson.current_source_dir() / 'op_helper.c',
+        meson.current_source_dir() / 'translate.c',
+        meson.current_source_dir() / 'reg_fields.c',
+        meson.current_source_dir() / 'arch.c',
+    ]
+
+    ll = custom_target('to-ll',
+        input: helper_to_tcg_input_files,
+        output:'helper-to-tcg-input.ll',
+        depends: [helper_funcs_generated, helper_protos_generated],
+        command: helper_to_tcg_get_llvm_ir_cmd + ['-o', '@OUTPUT@', '@INPUT@', '--target-path', 'target/hexagon']
+    )
+
+    helper_to_tcg_target = custom_target('helper-to-tcg-hexagon',
+        output: ['helper-to-tcg-emitted.c',
+                 'helper-to-tcg-emitted.h',
+                 'helper-to-tcg-enabled',
+                 'helper-to-tcg-log'],
+        input: [ll],
+        depends: [helper_to_tcg_pipeline, analyze_funcs_generated, helper_funcs_generated, helper_protos_generated],
+        command: [helper_to_tcg_pipeline,
+                  '--temp-vector-block=tmp_vmem',
+                  '--mmu-index-function=get_tb_mmu_index',
+                  '--tcg-global-mappings=tcg_global_mappings',
+                  '--output-source=@OUTPUT0@',
+                  '--output-header=@OUTPUT1@',
+                  '--output-enabled=@OUTPUT2@',
+                  '--output-log=@OUTPUT3@',
+                  '@INPUT@']
+    )
+
+    hexagon_ss.add(helper_to_tcg_target)
+
+    # List of instructions for which TCG generation was successful
+    generated_tcg_list = helper_to_tcg_target[2].full_path()
+
+    # Setup dependencies for idef-parser
+    idef_dep_extra += helper_to_tcg_target
+    idef_command_extra += ['--helper-to-tcg', generated_tcg_list]
+
+    # Setup input and dependencies for the final step, this depends on whether
+    helper_dep += [helper_to_tcg_target]
+    helper_in += ['--helper-to-tcg', generated_tcg_list]
+endif
+
+
+
+#
+# Step 6
 # We use flex/bison based idef-parser to generate TCG code for a lot
 # of instructions. idef-parser outputs
 #     idef-generated-emitter.c
 #     idef-generated-emitter.h.inc
 #     idef-generated-enabled-instructions
 #
+
 idef_parser_enabled = get_option('hexagon_idef_parser')
 if idef_parser_enabled and 'hexagon-linux-user' in target_dirs
     idef_parser_input_generated = custom_target(
         'idef_parser_input.h.inc',
         output: 'idef_parser_input.h.inc',
-        depends: [semantics_generated],
+        depends: [semantics_generated, ] + idef_dep_extra,
         depend_files: [hex_common_py],
-        command: [python, files('gen_idef_parser_funcs.py'), semantics_generated, '@OUTPUT@'],
+        command: [python, files('gen_idef_parser_funcs.py'), semantics_generated, '@OUTPUT@'] + idef_command_extra
     )
 
     preprocessed_idef_parser_input_generated = custom_target(
@@ -345,39 +450,14 @@ if idef_parser_enabled and 'hexagon-linux-user' in target_dirs
 
     # Setup input and dependencies for the next step, this depends on whether or
     # not idef-parser is enabled
-    helper_dep = [semantics_generated, idef_generated_tcg_c, idef_generated_tcg]
-    helper_in = [semantics_generated, gen_tcg_h, gen_tcg_hvx_h, '--idef-parser', idef_generated_list]
-else
-    # Setup input and dependencies for the next step, this depends on whether or
-    # not idef-parser is enabled
-    helper_dep = [semantics_generated]
-    helper_in = [semantics_generated, gen_tcg_h, gen_tcg_hvx_h]
+    helper_dep += [idef_generated_tcg_c, idef_generated_tcg]
+    helper_in += ['--idef-parser', idef_generated_list]
 endif
 
 #
-# Step 5
+# Step 7
 # We use Python scripts to generate the following files
-#     helper_protos_generated.h.inc
-#     helper_funcs_generated.c.inc
 #     tcg_funcs_generated.c.inc
-#
-helper_protos_generated = custom_target(
-    'helper_protos_generated.h.inc',
-    output: 'helper_protos_generated.h.inc',
-    depends: helper_dep,
-    depend_files: [hex_common_py, gen_tcg_h, gen_tcg_hvx_h],
-    command: [python, files('gen_helper_protos.py'), helper_in, '@OUTPUT@'],
-)
-hexagon_ss.add(helper_protos_generated)
-
-helper_funcs_generated = custom_target(
-    'helper_funcs_generated.c.inc',
-    output: 'helper_funcs_generated.c.inc',
-    depends: helper_dep,
-    depend_files: [hex_common_py, gen_tcg_h, gen_tcg_hvx_h],
-    command: [python, files('gen_helper_funcs.py'), helper_in, '@OUTPUT@'],
-)
-hexagon_ss.add(helper_funcs_generated)
 
 tcg_funcs_generated = custom_target(
     'tcg_funcs_generated.c.inc',
@@ -388,13 +468,4 @@ tcg_funcs_generated = custom_target(
 )
 hexagon_ss.add(tcg_funcs_generated)
 
-analyze_funcs_generated = custom_target(
-    'analyze_funcs_generated.c.inc',
-    output: 'analyze_funcs_generated.c.inc',
-    depends: helper_dep,
-    depend_files: [hex_common_py, gen_tcg_h, gen_tcg_hvx_h],
-    command: [python, files('gen_analyze_funcs.py'), helper_in, '@OUTPUT@'],
-)
-hexagon_ss.add(analyze_funcs_generated)
-
 target_arch += {'hexagon': hexagon_ss}
Signature · 1 line
2.45.2
#79 lore raw
In reply to Anton Johansson via
Quoted 29 lines · Anton Johansson

create mode 100644 subprojects/helper-to-tcg/README.md
create mode 100755 subprojects/helper-to-tcg/get-llvm-ir.py
create mode 100644 subprojects/helper-to-tcg/include/CmdLineOptions.h
create mode 100644 subprojects/helper-to-tcg/include/Error.h
create mode 100644 subprojects/helper-to-tcg/include/FunctionAnnotation.h create mode 100644 subprojects/helper-to-tcg/include/PrepareForOptPass.h create mode 100644 subprojects/helper-to-tcg/include/PrepareForTcgPass.h create mode 100644 subprojects/helper-to-tcg/include/TcgGlobalMap.h
create mode 100644 subprojects/helper-to-tcg/meson.build
create mode 100644 subprojects/helper-to-tcg/meson_options.txt
create mode 100644 subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.h create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.h create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.h create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.cpp
create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.h
create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.inc
create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgEmit.cpp create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgEmit.h
create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgGenPass.cpp create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgGenPass.h create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.cpp create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.h create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgType.h
create mode 100644 subprojects/helper-to-tcg/passes/llvm-compat.cpp

Quoted 8 lines

create mode 100644 subprojects/helper-to-tcg/passes/llvm-compat.h create mode 100644 subprojects/helper-to-tcg/pipeline/Pipeline.cpp create mode 100644 subprojects/helper-to-tcg/tests/cpustate.c create mode 100644 subprojects/helper-to-tcg/tests/ldst.c create mode 100644 subprojects/helper-to-tcg/tests/meson.build create mode 100644 subprojects/helper-to-tcg/tests/scalar.c create mode 100644 subprojects/helper-to-tcg/tests/tcg-global-mappings.h create mode 100644 subprojects/helper-to-tcg/tests/vector.c

Just wondering, could we name the subproject C++ headers using the .hpp suffix to have checkpatch easily skip them?

#80 lore raw
Quoted 40 lines · Philippe Mathieu-Daudé
Quoted 29 lines · Anton Johansson

create mode 100644 subprojects/helper-to-tcg/README.md
create mode 100755 subprojects/helper-to-tcg/get-llvm-ir.py
create mode 100644 subprojects/helper-to-tcg/include/CmdLineOptions.h
create mode 100644 subprojects/helper-to-tcg/include/Error.h
create mode 100644 subprojects/helper-to-tcg/include/FunctionAnnotation.h create mode 100644 subprojects/helper-to-tcg/include/PrepareForOptPass.h create mode 100644 subprojects/helper-to-tcg/include/PrepareForTcgPass.h create mode 100644 subprojects/helper-to-tcg/include/TcgGlobalMap.h
create mode 100644 subprojects/helper-to-tcg/meson.build
create mode 100644 subprojects/helper-to-tcg/meson_options.txt
create mode 100644 subprojects/helper-to-tcg/passes/PrepareForOptPass/PrepareForOptPass.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/CanonicalizeIR.h create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/IdentityMap.h create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/PrepareForTcgPass.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.cpp create mode 100644 subprojects/helper-to-tcg/passes/PrepareForTcgPass/TransformGEPs.h create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.cpp
create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.h
create mode 100644 subprojects/helper-to-tcg/passes/PseudoInst.inc
create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgEmit.cpp create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgEmit.h
create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgGenPass.cpp create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgGenPass.h create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.cpp create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgTempAllocationPass.h create mode 100644 subprojects/helper-to-tcg/passes/backend/TcgType.h
create mode 100644 subprojects/helper-to-tcg/passes/llvm-compat.cpp

Quoted 8 lines

create mode 100644 subprojects/helper-to-tcg/passes/llvm-compat.h create mode 100644 subprojects/helper-to-tcg/pipeline/Pipeline.cpp create mode 100644 subprojects/helper-to-tcg/tests/cpustate.c create mode 100644 subprojects/helper-to-tcg/tests/ldst.c create mode 100644 subprojects/helper-to-tcg/tests/meson.build create mode 100644 subprojects/helper-to-tcg/tests/scalar.c create mode 100644 subprojects/helper-to-tcg/tests/tcg-global-mappings.h create mode 100644 subprojects/helper-to-tcg/tests/vector.c

Quoted 2 lines

Just wondering, could we name the subproject C++ headers using the .hpp suffix to have checkpatch easily skip them?

Oh sure, not a problem.
//Anton