llvm-install-name-tool - LLVM tool for manipulating install-names and rpaths

llvm-libtool-darwin - LLVM tool for creating libraries for Darwin

Getting Started with the LLVM System using Microsoft Visual Studio

How To Add Your Build Configuration To LLVM Buildbot Infrastructure

Building a JIT: Adding Optimizations – An introduction to ORC Layers

Building a JIT: Adding Optimizations -- An introduction to ORC Layers

Building a JIT: Extreme Laziness - Using LazyReexports to JIT from ASTs

Introduction - Achieving consistency in how we deal with bug reports

Use Namespace Qualifiers to Implement Previously Declared Functions

Don’t use default labels in fully covered switches over enumerations

Don't use default labels in fully covered switches over enumerations

Don’t Use Braces on Simple Single-Statement Bodies of if/else/loop Statements

Don't Use Braces on Simple Single-Statement Bodies of if/else/loop Statements

Can I modify LLVM source code and redistribute the modified source?

Can I modify the LLVM source code and redistribute binaries or other tools based on it, without redistributing the source?

What API do I use to store a value to one of the virtual registers in LLVM IR’s SSA representation?

What API do I use to store a value to one of the virtual registers in LLVM IR's SSA representation?

I’d like to write a self-hosting LLVM compiler. How should I interface with the LLVM middle-end optimizers and back-end code generators?

I'd like to write a self-hosting LLVM compiler. How should I interface with the LLVM middle-end optimizers and back-end code generators?

What support is there for a higher level source language constructs for building a compiler?

Can I compile C or C++ code to platform-independent LLVM bitcode?

Why does instcombine + simplifycfg turn a call to a function with a mismatched calling convention into “unreachable”? Why not make the verifier reject it?

Why does instcombine + simplifycfg turn a call to a function with a mismatched calling convention into "unreachable"? Why not make the verifier reject it?

I’m writing a backend for a target which needs custom lowering for GEP. How do I do this?

I'm writing a backend for a target which needs custom lowering for GEP. How do I do this?

Can I do GEP with a different pointer type than the type of the underlying object?

Can I compute the distance between two objects, and add that value to one address to compute the other address?

G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR, G_SDIV, G_UDIV, G_SREM, G_UREM

G_SADDSAT, G_UADDSAT, G_SSUBSAT, G_USUBSAT, G_SSHLSAT, G_USHLSAT

G_FCEIL, G_FCOS, G_FSIN, G_FSQRT, G_FFLOOR, G_FRINT, G_FNEARBYINT

G_ATOMICRMW_XCHG, G_ATOMICRMW_ADD, G_ATOMICRMW_SUB, G_ATOMICRMW_AND, G_ATOMICRMW_NAND, G_ATOMICRMW_OR, G_ATOMICRMW_XOR, G_ATOMICRMW_MAX, G_ATOMICRMW_MIN, G_ATOMICRMW_UMAX, G_ATOMICRMW_UMIN, G_ATOMICRMW_FADD, G_ATOMICRMW_FSUB

Q. LibFuzzer crashes on my complicated fuzz target (but works fine for me on smaller targets).

What should I know to be able to follow along with this document?

Symbols which can go in either/both of the module info stream & global stream

: Print dominance tree of function to “dot” file (with no function bodies)

: Print dominance tree of function to "dot" file (with no function bodies)

: Print postdominance tree of function to “dot” file (with no function bodies)

: Print postdominance tree of function to "dot" file (with no function bodies)

Bit storage containers (BitVector, SparseBitVector, CoalescingBitVector)

Branching/Stashing/Updating for Local Development or Experiments

Loads folded into data-invariant operations can be hardened after the operation

Hardening of loaded values deferred down the data-invariant expression graph

Preserving the flags while hardening loaded values on Haswell, Zen, and newer processors

Embed the predicate state into the high bit(s) of the stack pointer

Rewrite API of internal functions to directly propagate predicate state

FileCheck command line option; --check-prefixes prefix1,prefix2,...

FileCheck command line option; --comment-prefixes prefix1,prefix2,...

FileCheck command line option; --implicit-check-not check-pattern

FileCheck command line option; -D#<FMT>,<NUMVAR>=<NUMERIC EXPRESSION>

dsymutil command line option; --object-prefix-map <prefix=remapped>

llvm-ar command line option; This option selects the quoting style ``<type>`` for response files

llvm-ar command line option; ``posix`` or ``windows``. The default when on Windows is ``windows``

llvm-cov-show command line option; -ignore-filename-regex=<PATTERN>

llvm-cov-show command line option; -Xdemangler=<TOOL>|<TOOL-OPTION>

llvm-cov-show command line option; -path-equivalence=<from>,<to>

llvm-cov-report command line option; -show-instantiation-summary

llvm-cov-report command line option; -ignore-filename-regex=<PATTERN>

llvm-cov-export command line option; -ignore-filename-regex=<PATTERN>

llvm-dwarfdump command line option; --debug-loclists [=<offset>]

llvm-exegesis command line option; -opcode-index=<LLVM opcode index>

llvm-exegesis command line option; -opcode-name=<opcode name 1>,<opcode name 2>,...

llvm-exegesis command line option; -mode=[latency|uops|inverse_throughput|analysis]

llvm-exegesis command line option; -x86-lbr-sample-period=<nBranches/sample>

llvm-exegesis command line option; -repetition-mode=[duplicate|loop|min]

llvm-exegesis command line option; -num-repetitions=<Number of repetitions>

llvm-exegesis command line option; -loop-body-size=<Preferred loop body size>

llvm-exegesis command line option; -max-configs-per-opcode=<value>

llvm-exegesis command line option; -benchmarks-file=</path/to/file>

llvm-exegesis command line option; -analysis-clusters-output-file=</path/to/file>

llvm-exegesis command line option; -analysis-inconsistencies-output-file=</path/to/file>

llvm-exegesis command line option; -analysis-clustering=[dbscan,naive]

llvm-exegesis command line option; -analysis-numpoints=<dbscan numPoints parameter>

llvm-exegesis command line option; -analysis-clustering-epsilon=<dbscan epsilon parameter>

llvm-exegesis command line option; -analysis-inconsistency-epsilon=<epsilon>

llvm-exegesis command line option; -analysis-display-unstable-clusters

llvm-exegesis command line option; -ignore-invalid-sched-class=false

llvm-install-name-tool command line option; -change <old_install_name> <new_install_name>

llvm-install-name-tool command line option; -delete_rpath <rpath>

llvm-install-name-tool command line option; -rpath <old_rpath> <new_rpath>

llvm-libtool-darwin command line option; -arch_only <architecture>

llvm-libtool-darwin command line option; -filelist <listfile[,dirname]>

llvm-libtool-darwin command line option; -no_warning_for_no_symbols

llvm-lipo command line option; -verify_arch  <architecture 1> [<architecture 2> ...]

llvm-mca command line option; -iterations=<number of iterations>

llvm-mca command line option; -timeline-max-iterations=<iterations>

llvm-objcopy command line option; --add-gnu-debuglink <debug-file>

llvm-objcopy command line option; --disable-deterministic-archives

llvm-objcopy command line option; --dump-section <section>=<file>

llvm-objcopy command line option; --enable-deterministic-archives

llvm-objcopy command line option; --set-section-alignment <section>=<align>

llvm-objcopy command line option; --set-section-flags <section>=<flag>[,<flag>,...]

llvm-objcopy command line option; --strip-unneeded-symbol <symbol>

llvm-objcopy command line option; --strip-unneeded-symbols <filename>

llvm-objcopy command line option; --add-symbol <name>=[<section>:]<value>[,<flags>]

llvm-objcopy command line option; --compress-debug-sections [<style>]

llvm-objcopy command line option; --globalize-symbols <filename>

llvm-objcopy command line option; --keep-global-symbols <filename>

llvm-objcopy command line option; --new-symbol-visibility <visibility>

llvm-objcopy command line option; --prefix-alloc-sections <prefix>

llvm-objcopy command line option; --rename-section <old>=<new>[,<flag>,...]

llvm-objdump command line option; --disassemble-symbols=<symbol1[,symbol2,...]>

llvm-objdump command line option; --section=<section1[,section2,...]>

llvm-objdump command line option; --disassembler-options=<opt1[,opt2,...]>

llvm-pdbutil-pretty command line option; -exclude-compilands=<string>

llvm-pdbutil-pretty command line option; -exclude-symbols=<string>

llvm-pdbutil-pretty command line option; -exclude-types=<string>

llvm-pdbutil-pretty command line option; -include-compilands=<string>

llvm-pdbutil-pretty command line option; -include-symbols=<string>

llvm-pdbutil-pretty command line option; -include-types=<string>

llvm-pdbutil-pretty command line option; -min-class-padding=<uint>

llvm-pdbutil-pretty command line option; -min-class-padding-imm=<uint>

llvm-pdbutil-pretty command line option; -class-definitions=<format>

llvm-pdbutil-pretty command line option; -class-recurse-depth=<uint>

llvm-pdbutil-bytes command line option; -block-range=<start[-end]>

llvm-pdbutil-bytes command line option; -byte-range=<start[-end]>

llvm-profdata-merge command line option; -weighted-input=weight,filename

llvm-profdata-merge command line option; -failure-mode=[any|all]

llvm-profdata-merge command line option; -compress-all-sections=[true|false]

llvm-profdata-merge command line option; -gen-partial-profile=[true|false]

llvm-profdata-merge command line option; -supplement-instr-with-sample=path_to_sample_profile

llvm-profdata-merge command line option; -zero-counter-threshold=threshold_float_number

llvm-profdata-merge command line option; -instr-prof-cold-threshold=threshold_int_number

llvm-profdata-merge command line option; -suppl-min-size-threshold=threshold_int_number

llvm-profdata-show command line option; -show-prof-sym-list=[true|false]

llvm-profdata-show command line option; -show-sec-info-only=[true|false]

llvm-profdata-overlap command line option; -o=output or -o output

llvm-profgen command line option; --perfscript=<string[,string,...]>

llvm-profgen command line option; --binary=<string[,string,...]>

llvm-profgen command line option; --format=[text|binary|extbinary|compbinary|gcc]

llvm-readelf command line option; --hex-dump=<section[,section,...]>

llvm-readelf command line option; --string-dump=<section[,section,...]>

llvm-readobj command line option; --hex-dump=<section[,section,...]>

llvm-readobj command line option; --string-dump=<section[,section,...]>

llvm-strip command line option; --disable-deterministic-archives

llvm-symbolizer command line option; --fallback-debug-path <path>

llvm-symbolizer command line option; --functions [=<none|short|linkage>]

llvm-symbolizer command line option; --output-style <LLVM|GNU|JSON>

llvm-symbolizer command line option; --print-source-context-lines <N>

llvm-symbolizer command line option; --dsym-hint <path/to/file.dSYM>

tblgen command line option; -gen-clang-attr-parser-string-switches

tblgen command line option; -gen-clang-attr-subject-match-rules-parser-string-switches

tblgen command line option; -gen-clang-attr-subject-match-rule-list

tblgen command line option; -gen-clang-attr-template-instantiate

tblgen command line option; -gen-clang-comment-html-tags-properties

tblgen command line option; -gen-clang-comment-html-named-character-references

tblgen command line option; -gen-clang-test-pragma-attribute-supported-attributes

AMDGPU Code Object V2 Supported Processors and Fixed Target Feature Settings

AMDHSA Code Object V4 Metadata Map Changes from amdgpu-amdhsa-code-object-metadata-v3

‘llvm.read_register’, ‘llvm.read_volatile_register’, and ‘llvm.write_register’ Intrinsics

Fine grained debug info with DEBUG_TYPE and the -debug-only option

**Radeon HD 2000/3000 Series (R600)** [AMD-RADEON-HD-2000-3000]_

**Radeon HD 6000 Series (Northern Islands)** [AMD-RADEON-HD-6000]_

**GCN GFX9 (Vega)** [AMD-GCN-GFX900-GFX904-VEGA]_ [AMD-GCN-GFX906-VEGA7NM]_ [AMD-GCN-GFX908-CDNA1]_

OS Support
*(see*
`amdgpu-os`_
*and
corresponding
runtime release
notes for
current
information and
level of
support)*

*and
notes for
current
level of
support)*

and
notes for
current
level of
support)

``amdhsa`` is not supported in ``r600`` architecture (see :ref:`amdgpu-architecture-table`).

.. table:: AMDGPU Processors
   :name: amdgpu-processor-table

   =========== =============== ============ ===== ================= =============== =============== ======================
   Processor   Alternative     Target       dGPU/ Target            Target          OS Support      Example
               Processor       Triple       APU   Features          Properties      *(see*          Products
                               Architecture       Supported                         `amdgpu-os`_
                                                                                    *and
                                                                                    corresponding
                                                                                    runtime release
                                                                                    notes for
                                                                                    current
                                                                                    information and
                                                                                    level of
                                                                                    support)*
   **Radeon HD 2000/3000 Series (R600)** [AMD-RADEON-HD-2000-3000]_
   -----------------------------------------------------------------------------------------------------------------------
   ``r600``                    ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``r630``                    ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``rs880``                   ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``rv670``                   ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   **Radeon HD 4000 Series (R700)** [AMD-RADEON-HD-4000]_
   ``rv710``                   ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``rv730``                   ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``rv770``                   ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   **Radeon HD 5000 Series (Evergreen)** [AMD-RADEON-HD-5000]_
   ``cedar``                   ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``cypress``                 ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``juniper``                 ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``redwood``                 ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``sumo``                    ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   **Radeon HD 6000 Series (Northern Islands)** [AMD-RADEON-HD-6000]_
   ``barts``                   ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``caicos``                  ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``cayman``                  ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``turks``                   ``r600``     dGPU                    - Does not
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   **GCN GFX6 (Southern Islands (SI))** [AMD-GCN-GFX6]_
   ``gfx600``  - ``tahiti``    ``amdgcn``   dGPU                    - Does not      - *pal-amdpal*
                                                                      support
                                                                      generic
                                                                      address
                                                                      space
   ``gfx601``  - ``pitcairn``  ``amdgcn``   dGPU                    - Does not      - *pal-amdpal*
               - ``verde``                                            support
                                                                      generic
                                                                      address
                                                                      space
   ``gfx602``  - ``hainan``    ``amdgcn``   dGPU                    - Does not      - *pal-amdpal*
               - ``oland``                                            support
                                                                      generic
                                                                      address
                                                                      space
   **GCN GFX7 (Sea Islands (CI))** [AMD-GCN-GFX7]_
   ``gfx700``  - ``kaveri``    ``amdgcn``   APU                     - Offset        - *rocm-amdhsa* - A6-7000
                                                                      flat          - *pal-amdhsa*  - A6 Pro-7050B
                                                                      scratch       - *pal-amdpal*  - A8-7100
                                                                                                    - A8 Pro-7150B
                                                                                                    - A10-7300
                                                                                                    - A10 Pro-7350B
                                                                                                    - FX-7500
                                                                                                    - A8-7200P
                                                                                                    - A10-7400P
                                                                                                    - FX-7600P
   ``gfx701``  - ``hawaii``    ``amdgcn``   dGPU                    - Offset        - *rocm-amdhsa* - FirePro W8100
                                                                      flat          - *pal-amdhsa*  - FirePro W9100
                                                                      scratch       - *pal-amdpal*  - FirePro S9150
                                                                                                    - FirePro S9170
   ``gfx702``                  ``amdgcn``   dGPU                    - Offset        - *rocm-amdhsa* - Radeon R9 290
                                                                      flat          - *pal-amdhsa*  - Radeon R9 290x
                                                                      scratch       - *pal-amdpal*  - Radeon R390
                                                                                                    - Radeon R390x
   ``gfx703``  - ``kabini``    ``amdgcn``   APU                     - Offset        - *pal-amdhsa*  - E1-2100
               - ``mullins``                                          flat          - *pal-amdpal*  - E1-2200
                                                                      scratch                       - E1-2500
                                                                                                    - E2-3000
                                                                                                    - E2-3800
                                                                                                    - A4-5000
                                                                                                    - A4-5100
                                                                                                    - A6-5200
                                                                                                    - A4 Pro-3340B
   ``gfx704``  - ``bonaire``   ``amdgcn``   dGPU                    - Offset        - *pal-amdhsa*  - Radeon HD 7790
                                                                      flat          - *pal-amdpal*  - Radeon HD 8770
                                                                      scratch                       - R7 260
                                                                                                    - R7 260X
   ``gfx705``                  ``amdgcn``   APU                     - Offset        - *pal-amdhsa*  *TBA*
                                                                      flat          - *pal-amdpal*
                                                                      scratch                       .. TODO::

                                                                                                      Add product
                                                                                                      names.

   **GCN GFX8 (Volcanic Islands (VI))** [AMD-GCN-GFX8]_
   ``gfx801``  - ``carrizo``   ``amdgcn``   APU   - xnack           - Offset        - *rocm-amdhsa* - A6-8500P
                                                                      flat          - *pal-amdhsa*  - Pro A6-8500B
                                                                      scratch       - *pal-amdpal*  - A8-8600P
                                                                                                    - Pro A8-8600B
                                                                                                    - FX-8800P
                                                                                                    - Pro A12-8800B
                                                                                                    - A10-8700P
                                                                                                    - Pro A10-8700B
                                                                                                    - A10-8780P
                                                                                                    - A10-9600P
                                                                                                    - A10-9630P
                                                                                                    - A12-9700P
                                                                                                    - A12-9730P
                                                                                                    - FX-9800P
                                                                                                    - FX-9830P
                                                                                                    - E2-9010
                                                                                                    - A6-9210
                                                                                                    - A9-9410
   ``gfx802``  - ``iceland``   ``amdgcn``   dGPU                    - Offset        - *rocm-amdhsa* - Radeon R9 285
               - ``tonga``                                            flat          - *pal-amdhsa*  - Radeon R9 380
                                                                      scratch       - *pal-amdpal*  - Radeon R9 385
   ``gfx803``  - ``fiji``      ``amdgcn``   dGPU                                    - *rocm-amdhsa* - Radeon R9 Nano
                                                                                    - *pal-amdhsa*  - Radeon R9 Fury
                                                                                    - *pal-amdpal*  - Radeon R9 FuryX
                                                                                                    - Radeon Pro Duo
                                                                                                    - FirePro S9300x2
                                                                                                    - Radeon Instinct MI8
   \           - ``polaris10`` ``amdgcn``   dGPU                    - Offset        - *rocm-amdhsa* - Radeon RX 470
                                                                      flat          - *pal-amdhsa*  - Radeon RX 480
                                                                      scratch       - *pal-amdpal*  - Radeon Instinct MI6
   \           - ``polaris11`` ``amdgcn``   dGPU                    - Offset        - *rocm-amdhsa* - Radeon RX 460
                                                                      flat          - *pal-amdhsa*
                                                                      scratch       - *pal-amdpal*
   ``gfx805``  - ``tongapro``  ``amdgcn``   dGPU                    - Offset        - *rocm-amdhsa* - FirePro S7150
                                                                      flat          - *pal-amdhsa*  - FirePro S7100
                                                                      scratch       - *pal-amdpal*  - FirePro W7100
                                                                                                    - Mobile FirePro
                                                                                                      M7170
   ``gfx810``  - ``stoney``    ``amdgcn``   APU   - xnack           - Offset        - *rocm-amdhsa* *TBA*
                                                                      scratch       - *pal-amdpal*  .. TODO::

                                                                                                      names.

   **GCN GFX9 (Vega)** [AMD-GCN-GFX900-GFX904-VEGA]_ [AMD-GCN-GFX906-VEGA7NM]_ [AMD-GCN-GFX908-CDNA1]_
   ``gfx900``                  ``amdgcn``   dGPU  - xnack           - Absolute      - *rocm-amdhsa* - Radeon Vega
                                                                      flat          - *pal-amdhsa*    Frontier Edition
                                                                      scratch       - *pal-amdpal*  - Radeon RX Vega 56
                                                                                                    - Radeon RX Vega 64
                                                                                                      Liquid
                                                                                                    - Radeon Instinct MI25
   ``gfx902``                  ``amdgcn``   APU   - xnack           - Absolute      - *rocm-amdhsa* - Ryzen 3 2200G
                                                                      flat          - *pal-amdhsa*  - Ryzen 5 2400G
   ``gfx904``                  ``amdgcn``   dGPU  - xnack                           - *rocm-amdhsa* *TBA*
                                                                                    - *pal-amdhsa*
                                                                                    - *pal-amdpal*  .. TODO::

                                                                                                      names.

   ``gfx906``                  ``amdgcn``   dGPU  - sramecc         - Absolute      - *rocm-amdhsa* - Radeon Instinct MI50
                                                  - xnack             flat          - *pal-amdhsa*  - Radeon Instinct MI60
                                                                      scratch       - *pal-amdpal*  - Radeon VII
                                                                                                    - Radeon Pro VII
   ``gfx908``                  ``amdgcn``   dGPU  - sramecc                         - *rocm-amdhsa* - AMD Instinct MI100 Accelerator
                                                  - xnack           - Absolute
                                                                      flat
                                                                      scratch
   ``gfx909``                  ``amdgcn``   APU   - xnack           - Absolute      - *pal-amdpal*  *TBA*
                                                                      flat

                                                                                                      names.

   ``gfx90a``                  ``amdgcn``   dGPU  - sramecc         - Absolute      - *rocm-amdhsa* *TBA*
                                                  - tgsplit           flat
                                                  - xnack             scratch                       .. TODO::
                                                                    - Packed
                                                                      work-item                       Add product
                                                                      IDs                             names.

   ``gfx90c``                  ``amdgcn``   APU   - xnack           - Absolute      - *pal-amdpal*  - Ryzen 7 4700G
                                                                      flat                          - Ryzen 7 4700GE
                                                                      scratch                       - Ryzen 5 4600G
                                                                                                    - Ryzen 5 4600GE
                                                                                                    - Ryzen 3 4300G
                                                                                                    - Ryzen 3 4300GE
                                                                                                    - Ryzen Pro 4000G
                                                                                                    - Ryzen 7 Pro 4700G
                                                                                                    - Ryzen 7 Pro 4750GE
                                                                                                    - Ryzen 5 Pro 4650G
                                                                                                    - Ryzen 5 Pro 4650GE
                                                                                                    - Ryzen 3 Pro 4350G
                                                                                                    - Ryzen 3 Pro 4350GE

   **GCN GFX10 (RDNA 1)** [AMD-GCN-GFX10-RDNA1]_
   ``gfx1010``                 ``amdgcn``   dGPU  - cumode          - Absolute      - *rocm-amdhsa* - Radeon RX 5700
                                                  - wavefrontsize64   flat          - *pal-amdhsa*  - Radeon RX 5700 XT
                                                  - xnack             scratch       - *pal-amdpal*  - Radeon Pro 5600 XT
                                                                                                    - Radeon Pro 5600M
   ``gfx1011``                 ``amdgcn``   dGPU  - cumode                          - *rocm-amdhsa* - Radeon Pro V520
                                                  - wavefrontsize64 - Absolute      - *pal-amdhsa*
                                                  - xnack             flat          - *pal-amdpal*
                                                                      scratch
   ``gfx1012``                 ``amdgcn``   dGPU  - cumode          - Absolute      - *rocm-amdhsa* - Radeon RX 5500
                                                  - wavefrontsize64   flat          - *pal-amdhsa*  - Radeon RX 5500 XT
                                                  - xnack             scratch       - *pal-amdpal*
   ``gfx1013``                 ``amdgcn``   APU   - cumode          - Absolute      - *rocm-amdhsa* *TBA*
                                                  - wavefrontsize64   flat          - *pal-amdhsa*
                                                  - xnack             scratch       - *pal-amdpal*  .. TODO::

                                                                                                      names.

   **GCN GFX10 (RDNA 2)** [AMD-GCN-GFX10-RDNA2]_
   ``gfx1030``                 ``amdgcn``   dGPU  - cumode          - Absolute      - *rocm-amdhsa* - Radeon RX 6800
                                                  - wavefrontsize64   flat          - *pal-amdhsa*  - Radeon RX 6800 XT
                                                                      scratch       - *pal-amdpal*  - Radeon RX 6900 XT
   ``gfx1031``                 ``amdgcn``   dGPU  - cumode          - Absolute      - *rocm-amdhsa* - Radeon RX 6700 XT
   ``gfx1032``                 ``amdgcn``   dGPU  - cumode          - Absolute      - *rocm-amdhsa* *TBA*

                                                                                                      names.

   ``gfx1033``                 ``amdgcn``   APU   - cumode          - Absolute      - *pal-amdpal*  *TBA*
                                                  - wavefrontsize64   flat

                                                                                                      names.
   ``gfx1034``                 ``amdgcn``   dGPU  - cumode          - Absolute      - *pal-amdpal*  *TBA*

                                                                                                      names.

   ``gfx1035``                 ``amdgcn``   APU   - cumode          - Absolute      - *pal-amdpal*  *TBA*
                                                                                                      names.

The AMDGPU backend provides ISA code generation for AMD GPUs, starting with the
R600 family up until the current GCN families. It lives in the
``llvm/lib/Target/AMDGPU`` directory.

Use the Clang option ``-target <Architecture>-<Vendor>-<OS>-<Environment>``
to specify the target triple:

Compute kernels executed on HSA [HSA]_ compatible runtimes
such as:

AMD's ROCm™ runtime [AMD-ROCm]_ using the *rocm-amdhsa*
loader on Linux. See *AMD ROCm Platform Release Notes*
[AMD-ROCm-Release-Notes]_ for supported hardware and
software.

Graphic shaders and compute kernels executed on AMD's PAL
runtime using the *pal-amdpal* loader on Windows and Linux
Pro.

Graphic shaders and compute kernels executed on AMD’s PAL
runtime using the 

Graphic shaders and compute kernels executed on AMD's Mesa
3D runtime using the *mesa-mesa3d* loader on Linux.

Graphic shaders and compute kernels executed on AMD’s Mesa
3D runtime using the 

Target features control how code is generated to support certain
processor specific features. Not all target features are supported by
all processors. The runtime must ensure that the features supported by
the device used to execute the code match the features enabled when
generating the code. A mismatch of features may result in incorrect
execution, or a reduction in performance.

The target features supported by each processor is listed in
:ref:`amdgpu-processor-table`.

Target features are controlled by exactly one of the following Clang
options:

The ``-mcpu`` and ``--offload-arch`` can specify the target feature as
optional components of the target ID. If omitted, the target feature has the
``any`` value. See :ref:`amdgpu-target-id`.

 can specify the target feature as

Target features not specified by the target ID are specified using a
separate option. These target features can have an ``on`` or ``off``
value.  ``on`` is specified by omitting the ``no-`` prefix, and
``off`` is specified by including the ``no-`` prefix. The default
if not specified is ``off``.

separate option. These target features can have an 

``-mno-cumode``
Disable the ``cumode`` feature.

.. table:: AMDGPU Target Features
   :name: amdgpu-target-features-table

   =============== ============================ ==================================================
   Target Feature  Clang Option to Control      Description
   Name
   cumode          - ``-m[no-]cumode``          Control the wavefront execution mode used
                                                when generating code for kernels. When disabled
                                                native WGP wavefront execution mode is used,
                                                when enabled CU wavefront execution mode is used
                                                (see :ref:`amdgpu-amdhsa-memory-model`).

   sramecc         - ``-mcpu``                  If specified, generate code that can only be
                   - ``--offload-arch``         loaded and executed in a process that has a
                                                matching setting for SRAMECC.

                                                If not specified for code object V2 to V3, generate
                                                code that can be loaded and executed in a process
                                                with SRAMECC enabled.

                                                If not specified for code object V4, generate
                                                with either setting of SRAMECC.

   tgsplit           ``-m[no-]tgsplit``         Enable/disable generating code that assumes
                                                work-groups are launched in threadgroup split mode.
                                                When enabled the waves of a work-group may be
                                                launched in different CUs.

   wavefrontsize64 - ``-m[no-]wavefrontsize64`` Control the wavefront size used when
                                                generating code for kernels. When disabled
                                                native wavefront size 32 is used, when enabled
                                                wavefront size 64 is used.

   xnack           - ``-mcpu``                  If specified, generate code that can only be
                                                matching setting for XNACK replay.

                                                with XNACK replay enabled.

                                                with either setting of XNACK replay.

                                                XNACK replay can be used for demand paging and
                                                page migration. If enabled in the device, then if
                                                a page fault occurs the code may execute
                                                incorrectly unless generated with XNACK replay
                                                enabled, or generated for code object V4 without
                                                specifying XNACK replay. Executing code that was
                                                generated with XNACK replay enabled, or generated
                                                for code object V4 without specifying XNACK replay,
                                                on a device that does not have XNACK replay
                                                enabled will execute correctly but may be less
                                                performant than code generated for XNACK replay
                                                disabled.

Control the wavefront execution mode used
when generating code for kernels. When disabled
native WGP wavefront execution mode is used,
when enabled CU wavefront execution mode is used
(see :ref:`amdgpu-amdhsa-memory-model`).

(see 

If specified, generate code that can only be
loaded and executed in a process that has a
matching setting for SRAMECC.

If not specified for code object V2 to V3, generate
code that can be loaded and executed in a process
with SRAMECC enabled.

If not specified for code object V4, generate
with either setting of SRAMECC.

Enable/disable generating code that assumes
work-groups are launched in threadgroup split mode.
When enabled the waves of a work-group may be
launched in different CUs.

Control the wavefront size used when
generating code for kernels. When disabled
native wavefront size 32 is used, when enabled
wavefront size 64 is used.

matching setting for XNACK replay.

with XNACK replay enabled.

with either setting of XNACK replay.

XNACK replay can be used for demand paging and
page migration. If enabled in the device, then if
a page fault occurs the code may execute
incorrectly unless generated with XNACK replay
enabled, or generated for code object V4 without
specifying XNACK replay. Executing code that was
generated with XNACK replay enabled, or generated
for code object V4 without specifying XNACK replay,
on a device that does not have XNACK replay
enabled will execute correctly but may be less
performant than code generated for XNACK replay
disabled.

AMDGPU supports target IDs. See `Clang Offload Bundler
<https://clang.llvm.org/docs/ClangOffloadBundler.html>`_ for a general
description. The AMDGPU target specific information is:

`Clang Offload Bundler
<https://clang.llvm.org/docs/ClangOffloadBundler.html>`_

 for a general

**processor**
Is an AMDGPU processor or alternative processor name specified in
:ref:`amdgpu-processor-table`. The non-canonical form target ID allows both
the primary processor and alternative processor names. The canonical form
target ID only allow the primary processor name.

. The non-canonical form target ID allows both

**target-feature**
Is a target feature name specified in :ref:`amdgpu-target-features-table` that
is supported by the processor. The target features supported by each processor
is specified in :ref:`amdgpu-processor-table`. Those that can be specified in
a target ID are marked as being controlled by ``-mcpu`` and
``--offload-arch``. Each target feature must appear at most once in a target
ID. The non-canonical form target ID allows the target features to be
specified in any order. The canonical form target ID requires the target
features to be specified in alphabetic order.

 that
is specified in 

. Those that can be specified in
a target ID are marked as being controlled by 

. Each target feature must appear at most once in a target

The target ID syntax for code object V2 to V3 is the same as defined in `Clang
Offload Bundler <https://clang.llvm.org/docs/ClangOffloadBundler.html>`_ except
when used in the :ref:`amdgpu-assembler-directive-amdgcn-target` assembler
directive and the bundle entry ID. In those cases it has the following BNF
syntax:

The target ID syntax for code object V2 to V3 is the same as defined in 

`Clang
Offload Bundler <https://clang.llvm.org/docs/ClangOffloadBundler.html>`_

 assembler
syntax:

Where a target feature is omitted if *Off* and present if *On* or *Any*.

The code object V2 to V3 cannot represent *Any* and treats it the same as
*On*.

AMDGPU supports the HIP and OpenMP languages that perform code object embedding
as described in `Clang Offload Bundler
<https://clang.llvm.org/docs/ClangOffloadBundler.html>`_.

as described in 

The target ID syntax used for code object V2 to V3 for a bundle entry ID
differs from that used elsewhere. See :ref:`amdgpu-target-id-v2-v3`.

differs from that used elsewhere. See 

The AMDGPU architecture supports a number of memory address spaces. The address
space names use the OpenCL standard names, with some additions.

The AMDGPU address spaces correspond to target architecture specific LLVM
address space numbers used in LLVM IR.

The AMDGPU address spaces are described in
:ref:`amdgpu-address-spaces-table`. Only 64-bit process address spaces are
supported for the ``amdgcn`` target.

**Generic**
The generic address space is supported unless the *Target Properties* column
of :ref:`amdgpu-processor-table` specifies *Does not support generic address
space*.

The generic address space uses the hardware flat address support for two fixed
ranges of virtual addresses (the private and local apertures), that are
outside the range of addressable global memory, to map from a flat address to
a private or local address. This uses FLAT instructions that can take a flat
address and access global, private (scratch), and group (LDS) memory depending
on if the address is within one of the aperture ranges.

Flat access to scratch requires hardware aperture setup and setup in the
kernel prologue (see :ref:`amdgpu-amdhsa-kernel-prolog-flat-scratch`). Flat
access to LDS requires hardware aperture setup and M0 (GFX7-GFX8) register
setup (see :ref:`amdgpu-amdhsa-kernel-prolog-m0`).

To convert between a private or group address space address (termed a segment
address) and a flat address the base address of the corresponding aperture
can be used. For GFX7-GFX8 these are available in the
:ref:`amdgpu-amdhsa-hsa-aql-queue` the address of which can be obtained with
Queue Ptr SGPR (see :ref:`amdgpu-amdhsa-initial-kernel-execution-state`). For
GFX9-GFX10 the aperture base addresses are directly available as inline
constant registers ``SRC_SHARED_BASE/LIMIT`` and ``SRC_PRIVATE_BASE/LIMIT``.
In 64-bit address mode the aperture sizes are 2^32 bytes and the base is
aligned to 2^32 which makes it easier to convert from flat to segment or
segment to flat.

A global address space address has the same value when used as a flat address
so no conversion is needed.

space*.

kernel prologue (see 

). Flat
setup (see 

). For
constant registers 

.

**Global and Constant**
The global and constant address spaces both use global virtual addresses,
which are the same virtual address space used by the CPU. However, some
virtual addresses may only be accessible to the CPU, some only accessible
by the GPU, and some by both.

Using the constant address space indicates that the data will not change
during the execution of the kernel. This allows scalar read instructions to
be used. As the constant address space could only be modified on the host
side, a generic pointer loaded from the constant address space is safe to be
assumed as a global pointer since only the device global memory is visible
and managed on the host side. The vector and scalar L1 caches are invalidated
of volatile data before each kernel dispatch execution to allow constant
memory to change values between kernel dispatches.

**Region**
The region address space uses the hardware Global Data Store (GDS). All
wavefronts executing on the same device will access the same memory for any
given region address. However, the same region address accessed by wavefronts
executing on different devices will access different memory. It is higher
performance than global memory. It is allocated by the runtime. The data
store (DS) instructions can be used to access it.

**Local**
The local address space uses the hardware Local Data Store (LDS) which is
automatically allocated when the hardware creates the wavefronts of a
work-group, and freed when all the wavefronts of a work-group have
terminated. All wavefronts belonging to the same work-group will access the
same memory for any given local address. However, the same local address
accessed by wavefronts belonging to different work-groups will access
different memory. It is higher performance than global memory. The data store
(DS) instructions can be used to access it.

**Private**
The private address space uses the hardware scratch memory support which
automatically allocates memory when it creates a wavefront and frees it when
a wavefronts terminates. The memory accessed by a lane of a wavefront for any
given private address will be different to the memory accessed by another lane
of the same or different wavefront for the same private address.

If a kernel dispatch uses scratch, then the hardware allocates memory from a
pool of backing memory allocated by the runtime for each wavefront. The lanes
of the wavefront access this using dword (4 byte) interleaving. The mapping
used from private address to backing memory address is:

  ``wavefront-scratch-base +
  ((private-address / 4) * wavefront-size * 4) +
  (wavefront-lane-id * 4) + (private-address % 4)``

If each lane of a wavefront accesses the same private address, the
interleaving results in adjacent dwords being accessed and hence requires
fewer cache lines to be fetched.

There are different ways that the wavefront scratch base address is
determined by a wavefront (see
:ref:`amdgpu-amdhsa-initial-kernel-execution-state`).

Scratch memory can be accessed in an interleaved manner using buffer
instructions with the scratch buffer descriptor and per wavefront scratch
offset, by the scratch instructions, or by flat instructions. Multi-dword
access is not supported except by flat and scratch instructions in
GFX9-GFX10.

``wavefront-scratch-base +
((private-address / 4) * wavefront-size * 4) +
(wavefront-lane-id * 4) + (private-address % 4)``

wavefront-scratch-base +
(wavefront-lane-id * 4) + (private-address % 4)

**Buffer Fat Pointer**
The buffer fat pointer is an experimental address space that is currently
unsupported in the backend. It exposes a non-integral pointer that is in
the future intended to support the modelling of 128-bit buffer descriptors
plus a 32-bit offset into the buffer (in total encapsulating a 160-bit
*pointer*), allowing normal LLVM load/store/atomic operations to be used to
model the buffer descriptors used heavily in graphics workloads targeting
the backend.

), allowing normal LLVM load/store/atomic operations to be used to

This section provides LLVM memory synchronization scopes supported by the AMDGPU
backend memory model when the target triple OS is ``amdhsa`` (see
:ref:`amdgpu-amdhsa-memory-model` and :ref:`amdgpu-target-triples`).

backend memory model when the target triple OS is 

The memory model supported is based on the HSA memory model [HSA]_ which is
based in turn on HRF-indirect with scope inclusion [HRF]_. The happens-before
relation is transitive over the synchronizes-with relation independent of scope
and synchronizes-with allows the memory scope instances to be inclusive (see
table :ref:`amdgpu-amdhsa-llvm-sync-scopes-table`).

. The happens-before
table 

This is different to the OpenCL [OpenCL]_ memory model which does not have scope
inclusion and requires the memory scopes to exactly match. However, this
is conservatively correct for OpenCL.

 memory model which does not have scope

Synchronizes with, and participates in modification
and seq_cst total orderings with, other operations
(except image operations) for all address spaces
(except private, or generic that accesses private)
provided the other operation's sync scope is:

provided the other operation’s sync scope is:

``system`` or ``agent`` and executed by a thread
on the same agent.

``system``, ``agent`` or ``workgroup`` and
executed by a thread in the same work-group.

``system``, ``agent``, ``workgroup`` or
``wavefront`` and executed by a thread in the
same wavefront.

Only synchronizes with and participates in
modification and seq_cst total orderings with,
other operations (except image operations) running
in the same thread for all address spaces (for
example, in signal handlers).

Same as ``system`` but only synchronizes with other
operations within the same address space.

 but only synchronizes with other

Same as ``agent`` but only synchronizes with other

Same as ``workgroup`` but only synchronizes with
other operations within the same address space.

 but only synchronizes with

Same as ``wavefront`` but only synchronizes with

Same as ``singlethread`` but only synchronizes with

Specify the minimum and maximum flat work group sizes that
will be specified when the kernel is dispatched. Generated
by the ``amdgpu_flat_work_group_size`` CLANG attribute [CLANG-ATTR]_.

by the 

Number of kernel argument bytes to add to the kernel
argument block size for the implicit arguments. This
varies by OS and language (for OpenCL see
:ref:`opencl-kernel-implicit-arguments-appended-for-amdhsa-os-table`).

Specifies the number of SGPRs to use. Generated by
the ``amdgpu_num_sgpr`` CLANG attribute [CLANG-ATTR]_.

Specifies the number of VGPRs to use. Generated by the
``amdgpu_num_vgpr`` CLANG attribute [CLANG-ATTR]_.

Specify the minimum and maximum number of waves per
execution unit. Generated by the ``amdgpu_waves_per_eu``
CLANG attribute [CLANG-ATTR]_.

execution unit. Generated by the 

Specify whether the function expects the IEEE field of the
mode register to be set on entry. Overrides the default for
the calling convention.

Specify whether the function expects the DX10_CLAMP field of
the mode register to be set on entry. Overrides the default
for the calling convention.

Indicates the function does not depend on the value of the
llvm.amdgcn.workitem.id.x intrinsic. If a function is marked with this
attribute, or reached through a call site marked with this attribute,
the value returned by the intrinsic is undefined. The backend can
generally infer this during code generation, so typically there is no
benefit to frontends marking functions with this.

The same as amdgpu-no-workitem-id-x, except for the
llvm.amdgcn.workitem.id.y intrinsic.

llvm.amdgcn.workitem.id.z intrinsic.

llvm.amdgcn.workgroup.id.x intrinsic.

llvm.amdgcn.workgroup.id.y intrinsic.

llvm.amdgcn.workgroup.id.z intrinsic.

llvm.amdgcn.dispatch.ptr intrinsic.

llvm.amdgcn.implicitarg.ptr intrinsic.

llvm.amdgcn.dispatch.id intrinsic.

Similar to amdgpu-no-workitem-id-x, except for the
llvm.amdgcn.queue.ptr intrinsic. Note that unlike the other ABI hint
attributes, the queue pointer may be required in situations where the
intrinsic call does not directly appear in the program. Some subtargets
require the queue pointer for to handle some addrspacecasts, as well
as the llvm.amdgcn.is.shared, llvm.amdgcn.is.private, llvm.trap, and
llvm.debug intrinsics.

The AMDGPU backend generates a standard ELF [ELF]_ relocatable code object that
can be linked by ``lld`` to produce a standard ELF shared code object which can
be loaded and executed on an AMDGPU target.

 to produce a standard ELF shared code object which can

See :ref:`amdgpu-elf-header-e_flags-v2-table`,
:ref:`amdgpu-elf-header-e_flags-table-v3`,
and :ref:`amdgpu-elf-header-e_flags-table-v4`

``e_ident[EI_CLASS]``
The ELF class is:

* ``ELFCLASS32`` for ``r600`` architecture.

* ``ELFCLASS64`` for ``amdgcn`` architecture which only supports 64-bit
  process address space applications.

``ELFCLASS64`` for ``amdgcn`` architecture which only supports 64-bit
process address space applications.

 architecture which only supports 64-bit

``e_ident[EI_DATA]``
All AMDGPU targets use ``ELFDATA2LSB`` for little-endian byte ordering.

``e_ident[EI_OSABI]``
One of the following AMDGPU target architecture specific OS ABIs
(see :ref:`amdgpu-os`):

* ``ELFOSABI_NONE`` for *unknown* OS.

* ``ELFOSABI_AMDGPU_HSA`` for ``amdhsa`` OS.

* ``ELFOSABI_AMDGPU_PAL`` for ``amdpal`` OS.

* ``ELFOSABI_AMDGPU_MESA3D`` for ``mesa3D`` OS.

(see 

``e_ident[EI_ABIVERSION]``
The ABI version of the AMDGPU target architecture specific OS ABI to which the code
object conforms:

* ``ELFABIVERSION_AMDGPU_HSA_V2`` is used to specify the version of AMD HSA
  runtime ABI for code object V2. Specify using the Clang option
  ``-mcode-object-version=2``.

* ``ELFABIVERSION_AMDGPU_HSA_V3`` is used to specify the version of AMD HSA
  runtime ABI for code object V3. Specify using the Clang option
  ``-mcode-object-version=3``. This is the default code object
  version if not specified.

* ``ELFABIVERSION_AMDGPU_HSA_V4`` is used to specify the version of AMD HSA
  runtime ABI for code object V4. Specify using the Clang option
  ``-mcode-object-version=4``.

* ``ELFABIVERSION_AMDGPU_PAL`` is used to specify the version of AMD PAL
  runtime ABI.

* ``ELFABIVERSION_AMDGPU_MESA3D`` is used to specify the version of AMD MESA
  3D runtime ABI.

``ELFABIVERSION_AMDGPU_HSA_V2`` is used to specify the version of AMD HSA
runtime ABI for code object V2. Specify using the Clang option
``-mcode-object-version=2``.

 is used to specify the version of AMD HSA

``ELFABIVERSION_AMDGPU_HSA_V3`` is used to specify the version of AMD HSA
runtime ABI for code object V3. Specify using the Clang option
``-mcode-object-version=3``. This is the default code object
version if not specified.

``ELFABIVERSION_AMDGPU_HSA_V4`` is used to specify the version of AMD HSA
runtime ABI for code object V4. Specify using the Clang option
``-mcode-object-version=4``.

``ELFABIVERSION_AMDGPU_PAL`` is used to specify the version of AMD PAL
runtime ABI.

``ELFABIVERSION_AMDGPU_MESA3D`` is used to specify the version of AMD MESA
3D runtime ABI.

``e_type``
Can be one of the following values:

``ET_REL``
  The type produced by the AMDGPU backend compiler as it is relocatable code
  object.

``ET_DYN``
  The type produced by the linker as it is a shared code object.

The AMD HSA runtime loader requires a ``ET_DYN`` code object.

The type produced by the AMDGPU backend compiler as it is relocatable code
object.

object.

The type produced by the linker as it is a shared code object.

``e_machine``
The value ``EM_AMDGPU`` is used for the machine for all processors supported
by the ``r600`` and ``amdgcn`` architectures (see
:ref:`amdgpu-processor-table`). The specific processor is specified in the
``NT_AMD_HSA_ISA_VERSION`` note record for code object V2 (see
:ref:`amdgpu-note-records-v2`) and in the ``EF_AMDGPU_MACH`` bit field of the
``e_flags`` for code object V3 to V4 (see
:ref:`amdgpu-elf-header-e_flags-table-v3` and
:ref:`amdgpu-elf-header-e_flags-table-v4`).

``e_entry``
The entry point is 0 as the entry points for individual kernels must be
selected in order to invoke them through AQL packets.

``e_flags``
The AMDGPU backend uses the following ELF header flags:

.. table:: AMDGPU ELF Header ``e_flags`` for Code Object V2
   :name: amdgpu-elf-header-e_flags-v2-table

   ===================================== ===== =============================
   Name                                  Value Description
   ``EF_AMDGPU_FEATURE_XNACK_V2``        0x01  Indicates if the ``xnack``
                                               target feature is
                                               enabled for all code
                                               contained in the code object.
                                               If the processor
                                               does not support the
                                               ``xnack`` target
                                               feature then must
                                               be 0.
                                               See
                                               :ref:`amdgpu-target-features`.
   ``EF_AMDGPU_FEATURE_TRAP_HANDLER_V2`` 0x02  Indicates if the trap
                                               handler is enabled for all
                                               code contained in the code
                                               object. If the processor
                                               does not support a trap
                                               handler then must be 0.
                                               See

.. table:: AMDGPU ELF Header ``e_flags`` for Code Object V3
   :name: amdgpu-elf-header-e_flags-table-v3

   ================================= ===== =============================
   Name                              Value Description
   ``EF_AMDGPU_MACH``                0x0ff AMDGPU processor selection
                                           mask for
                                           ``EF_AMDGPU_MACH_xxx`` values
                                           defined in
                                           :ref:`amdgpu-ef-amdgpu-mach-table`.
   ``EF_AMDGPU_FEATURE_XNACK_V3``    0x100 Indicates if the ``xnack``
                                           target feature is
                                           enabled for all code
                                           contained in the code object.
                                           If the processor
                                           does not support the
                                           ``xnack`` target
                                           feature then must
                                           be 0.
                                           See
                                           :ref:`amdgpu-target-features`.
   ``EF_AMDGPU_FEATURE_SRAMECC_V3``  0x200 Indicates if the ``sramecc``
                                           ``sramecc`` target
                                           be 0.
                                           See

.. table:: AMDGPU ELF Header ``e_flags`` for Code Object V4
   :name: amdgpu-elf-header-e_flags-table-v4

   ============================================ ===== ===================================
   Name                                         Value      Description
   ``EF_AMDGPU_MACH``                           0x0ff AMDGPU processor selection
                                                      mask for
                                                      ``EF_AMDGPU_MACH_xxx`` values
                                                      defined in
                                                      :ref:`amdgpu-ef-amdgpu-mach-table`.
   ``EF_AMDGPU_FEATURE_XNACK_V4``               0x300 XNACK selection mask for
                                                      ``EF_AMDGPU_FEATURE_XNACK_*_V4``
                                                      values.
   ``EF_AMDGPU_FEATURE_XNACK_UNSUPPORTED_V4``   0x000 XNACK unsuppored.
   ``EF_AMDGPU_FEATURE_XNACK_ANY_V4``           0x100 XNACK can have any value.
   ``EF_AMDGPU_FEATURE_XNACK_OFF_V4``           0x200 XNACK disabled.
   ``EF_AMDGPU_FEATURE_XNACK_ON_V4``            0x300 XNACK enabled.
   ``EF_AMDGPU_FEATURE_SRAMECC_V4``             0xc00 SRAMECC selection mask for
                                                      ``EF_AMDGPU_FEATURE_SRAMECC_*_V4``
                                                      values.
   ``EF_AMDGPU_FEATURE_SRAMECC_UNSUPPORTED_V4`` 0x000 SRAMECC unsuppored.
   ``EF_AMDGPU_FEATURE_SRAMECC_ANY_V4``         0x400 SRAMECC can have any value.
   ``EF_AMDGPU_FEATURE_SRAMECC_OFF_V4``         0x800 SRAMECC disabled,
   ``EF_AMDGPU_FEATURE_SRAMECC_ON_V4``          0xc00 SRAMECC enabled.

.. table:: AMDGPU ``EF_AMDGPU_MACH`` Values
   :name: amdgpu-ef-amdgpu-mach-table

   ==================================== ========== =============================
   Name                                 Value      Description (see
                                                   :ref:`amdgpu-processor-table`)
   ``EF_AMDGPU_MACH_NONE``              0x000      *not specified*
   ``EF_AMDGPU_MACH_R600_R600``         0x001      ``r600``
   ``EF_AMDGPU_MACH_R600_R630``         0x002      ``r630``
   ``EF_AMDGPU_MACH_R600_RS880``        0x003      ``rs880``
   ``EF_AMDGPU_MACH_R600_RV670``        0x004      ``rv670``
   ``EF_AMDGPU_MACH_R600_RV710``        0x005      ``rv710``
   ``EF_AMDGPU_MACH_R600_RV730``        0x006      ``rv730``
   ``EF_AMDGPU_MACH_R600_RV770``        0x007      ``rv770``
   ``EF_AMDGPU_MACH_R600_CEDAR``        0x008      ``cedar``
   ``EF_AMDGPU_MACH_R600_CYPRESS``      0x009      ``cypress``
   ``EF_AMDGPU_MACH_R600_JUNIPER``      0x00a      ``juniper``
   ``EF_AMDGPU_MACH_R600_REDWOOD``      0x00b      ``redwood``
   ``EF_AMDGPU_MACH_R600_SUMO``         0x00c      ``sumo``
   ``EF_AMDGPU_MACH_R600_BARTS``        0x00d      ``barts``
   ``EF_AMDGPU_MACH_R600_CAICOS``       0x00e      ``caicos``
   ``EF_AMDGPU_MACH_R600_CAYMAN``       0x00f      ``cayman``
   ``EF_AMDGPU_MACH_R600_TURKS``        0x010      ``turks``
   *reserved*                           0x011 -    Reserved for ``r600``
                                        0x01f      architecture processors.
   ``EF_AMDGPU_MACH_AMDGCN_GFX600``     0x020      ``gfx600``
   ``EF_AMDGPU_MACH_AMDGCN_GFX601``     0x021      ``gfx601``
   ``EF_AMDGPU_MACH_AMDGCN_GFX700``     0x022      ``gfx700``
   ``EF_AMDGPU_MACH_AMDGCN_GFX701``     0x023      ``gfx701``
   ``EF_AMDGPU_MACH_AMDGCN_GFX702``     0x024      ``gfx702``
   ``EF_AMDGPU_MACH_AMDGCN_GFX703``     0x025      ``gfx703``
   ``EF_AMDGPU_MACH_AMDGCN_GFX704``     0x026      ``gfx704``
   *reserved*                           0x027      Reserved.
   ``EF_AMDGPU_MACH_AMDGCN_GFX801``     0x028      ``gfx801``
   ``EF_AMDGPU_MACH_AMDGCN_GFX802``     0x029      ``gfx802``
   ``EF_AMDGPU_MACH_AMDGCN_GFX803``     0x02a      ``gfx803``
   ``EF_AMDGPU_MACH_AMDGCN_GFX810``     0x02b      ``gfx810``
   ``EF_AMDGPU_MACH_AMDGCN_GFX900``     0x02c      ``gfx900``
   ``EF_AMDGPU_MACH_AMDGCN_GFX902``     0x02d      ``gfx902``
   ``EF_AMDGPU_MACH_AMDGCN_GFX904``     0x02e      ``gfx904``
   ``EF_AMDGPU_MACH_AMDGCN_GFX906``     0x02f      ``gfx906``
   ``EF_AMDGPU_MACH_AMDGCN_GFX908``     0x030      ``gfx908``
   ``EF_AMDGPU_MACH_AMDGCN_GFX909``     0x031      ``gfx909``
   ``EF_AMDGPU_MACH_AMDGCN_GFX90C``     0x032      ``gfx90c``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1010``    0x033      ``gfx1010``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1011``    0x034      ``gfx1011``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1012``    0x035      ``gfx1012``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1030``    0x036      ``gfx1030``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1031``    0x037      ``gfx1031``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1032``    0x038      ``gfx1032``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1033``    0x039      ``gfx1033``
   ``EF_AMDGPU_MACH_AMDGCN_GFX602``     0x03a      ``gfx602``
   ``EF_AMDGPU_MACH_AMDGCN_GFX705``     0x03b      ``gfx705``
   ``EF_AMDGPU_MACH_AMDGCN_GFX805``     0x03c      ``gfx805``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1035``    0x03d      ``gfx1035``
   ``EF_AMDGPU_MACH_AMDGCN_GFX1034``    0x03e      ``gfx1034``
   ``EF_AMDGPU_MACH_AMDGCN_GFX90A``     0x03f      ``gfx90a``
   *reserved*                           0x040      Reserved.
   *reserved*                           0x041      Reserved.
   ``EF_AMDGPU_MACH_AMDGCN_GFX1013``    0x042      ``gfx1013``
   *reserved*                           0x043      Reserved.
   *reserved*                           0x044      Reserved.
   *reserved*                           0x045      Reserved.

Indicates if the ``xnack``
target feature is
enabled for all code
contained in the code object.
If the processor
does not support the
``xnack`` target
feature then must
be 0.
See
:ref:`amdgpu-target-features`.

Indicates if the trap
handler is enabled for all
code contained in the code
object. If the processor
does not support a trap
handler then must be 0.
See

See

AMDGPU processor selection
mask for
``EF_AMDGPU_MACH_xxx`` values
defined in
:ref:`amdgpu-ef-amdgpu-mach-table`.

Indicates if the ``sramecc``
``sramecc`` target
be 0.
See

XNACK selection mask for
``EF_AMDGPU_FEATURE_XNACK_*_V4``
values.

SRAMECC selection mask for
``EF_AMDGPU_FEATURE_SRAMECC_*_V4``
values.

An AMDGPU target ELF code object has the standard ELF sections which include:

These sections have their standard meanings (see [ELF]_) and are only generated
if needed.

``.debug``\ *\**
The standard DWARF sections. See :ref:`amdgpu-dwarf-debug-information` for
information on the DWARF produced by the AMDGPU backend.

``.dynamic``, ``.dynstr``, ``.dynsym``, ``.hash``
The standard sections used by a dynamic loader.

``.note``
See :ref:`amdgpu-note-records` for the note records supported by the AMDGPU
backend.

backend.

``.rela``\ *name*, ``.rela.dyn``
For relocatable code objects, *name* is the name of the section that the
relocation records apply. For example, ``.rela.text`` is the section name for
relocation records associated with the ``.text`` section.

For linked shared code objects, ``.rela.dyn`` contains all the relocation
records from each of the relocatable code object's ``.rela``\ *name* sections.

See :ref:`amdgpu-relocation-records` for the relocation records supported by
the AMDGPU backend.

 is the name of the section that the
relocation records apply. For example, 

 is the section name for
relocation records associated with the 

 contains all the relocation
records from each of the relocatable code object’s 

records from each of the relocatable code object's 

``.text``
The executable machine code for the kernels and functions they call. Generated
as position independent code. See :ref:`amdgpu-code-conventions` for
information on conventions used in the isa generation.

as position independent code. See 

The AMDGPU backend code object contains ELF note records in the ``.note``
section. The set of generated notes and their semantics depend on the code
object version; see :ref:`amdgpu-note-records-v2` and
:ref:`amdgpu-note-records-v3-v4`.

The AMDGPU backend code object contains ELF note records in the 

object version; see 

As required by ``ELFCLASS32`` and ``ELFCLASS64``, minimal zero-byte padding
must be generated after the ``name`` field to ensure the ``desc`` field is 4
byte aligned. In addition, minimal zero-byte padding must be generated to
ensure the ``desc`` field size is a multiple of 4 bytes. The ``sh_addralign``
field of the ``.note`` section must be at least 4 to indicate at least 8 byte
alignment.

 field is 4
ensure the 

 section must be at least 4 to indicate at least 8 byte

Code object V2 is not the default code object version emitted by
this version of LLVM.

The AMDGPU backend code object uses the following ELF note record in the
``.note`` section when compiling for code object V2.

Additional note records may be present, but any which are not documented here
are deprecated and should not be used.

HSAIL properties generated by the HSAIL
Finalizer and not the LLVM compiler.

``NT_AMD_HSA_CODE_OBJECT_VERSION``
Specifies the code object version number. The description field has the
following layout:

.. code:: c

  struct amdgpu_hsa_note_code_object_version_s {
    uint32_t major_version;
    uint32_t minor_version;
  };

The ``major_version`` has a value less than or equal to 2.

struct amdgpu_hsa_note_code_object_version_s {
  uint32_t major_version;
  uint32_t minor_version;
};

``NT_AMD_HSA_HSAIL``
Specifies the HSAIL properties used by the HSAIL Finalizer. The description
field has the following layout:

.. code:: c

  struct amdgpu_hsa_note_hsail_s {
    uint32_t hsail_major_version;
    uint32_t hsail_minor_version;
    uint8_t profile;
    uint8_t machine_model;
    uint8_t default_float_round;
  };

struct amdgpu_hsa_note_hsail_s {
  uint32_t hsail_major_version;
  uint32_t hsail_minor_version;
  uint8_t profile;
  uint8_t machine_model;
  uint8_t default_float_round;
};

``NT_AMD_HSA_ISA_VERSION``
Specifies the target ISA version. The description field has the following layout:

.. code:: c

  struct amdgpu_hsa_note_isa_s {
    uint16_t vendor_name_size;
    uint16_t architecture_name_size;
    uint32_t major;
    uint32_t minor;
    uint32_t stepping;
    char vendor_and_architecture_name[1];
  };

``vendor_name_size`` and ``architecture_name_size`` are the length of the
vendor and architecture names respectively, including the NUL character.

``vendor_and_architecture_name`` contains the NUL terminates string for the
vendor, immediately followed by the NUL terminated string for the
architecture.

This note record is used by the HSA runtime loader.

Code object V2 only supports a limited number of processors and has fixed
settings for target features. See
:ref:`amdgpu-elf-note-record-supported_processors-v2-table` for a list of
processors and the corresponding target ID. In the table the note record ISA
name is a concatenation of the vendor name, architecture name, major, minor,
and stepping separated by a ":".

The target ID column shows the processor name and fixed target features used
by the LLVM compiler. The LLVM compiler does not generate a
``NT_AMD_HSA_HSAIL`` note record.

A code object generated by the Finalizer also uses code object V2 and always
generates a ``NT_AMD_HSA_HSAIL`` note record. The processor name and
``sramecc`` target feature is as shown in
:ref:`amdgpu-elf-note-record-supported_processors-v2-table` but the ``xnack``
target feature is specified by the ``EF_AMDGPU_FEATURE_XNACK_V2`` ``e_flags``
bit.

struct amdgpu_hsa_note_isa_s {
  uint16_t vendor_name_size;
  uint16_t architecture_name_size;
  uint32_t major;
  uint32_t minor;
  uint32_t stepping;
  char vendor_and_architecture_name[1];
};

 are the length of the

 contains the NUL terminates string for the

 for a list of
and stepping separated by a “:”.

bit.

generates a 

``NT_AMD_HSA_ISA_NAME``
Specifies the target ISA name as a non-NUL terminated string.

This note record is not used by the HSA runtime loader.

See the ``NT_AMD_HSA_ISA_VERSION`` note record description of the code object
V2's limited support of processors and fixed settings for target features.

See :ref:`amdgpu-elf-note-record-supported_processors-v2-table` for a mapping
from the string to the corresponding target ID. If the ``xnack`` target
feature is supported and enabled, the string produced by the LLVM compiler
will may have a ``+xnack`` appended. The Finlizer did not do the appending and
instead used the ``EF_AMDGPU_FEATURE_XNACK_V2`` ``e_flags`` bit.

 note record description of the code object
V2’s limited support of processors and fixed settings for target features.

 for a mapping
from the string to the corresponding target ID. If the 

 target
will may have a 

 appended. The Finlizer did not do the appending and
instead used the 

``NT_AMD_HSA_METADATA``
Specifies extensible metadata associated with the code objects executed on HSA
[HSA]_ compatible runtimes (see :ref:`amdgpu-os`). It is required when the
target triple OS is ``amdhsa`` (see :ref:`amdgpu-target-triples`). See
:ref:`amdgpu-amdhsa-code-object-metadata-v2` for the syntax of the code object
metadata string.

.. table:: AMDGPU Code Object V2 Supported Processors and Fixed Target Feature Settings
   :name: amdgpu-elf-note-record-supported_processors-v2-table

   ===================== ==========================
   Note Record ISA Name  Target ID
   ``AMD:AMDGPU:6:0:0``  ``gfx600``
   ``AMD:AMDGPU:6:0:1``  ``gfx601``
   ``AMD:AMDGPU:6:0:2``  ``gfx602``
   ``AMD:AMDGPU:7:0:0``  ``gfx700``
   ``AMD:AMDGPU:7:0:1``  ``gfx701``
   ``AMD:AMDGPU:7:0:2``  ``gfx702``
   ``AMD:AMDGPU:7:0:3``  ``gfx703``
   ``AMD:AMDGPU:7:0:4``  ``gfx704``
   ``AMD:AMDGPU:7:0:5``  ``gfx705``
   ``AMD:AMDGPU:8:0:0``  ``gfx802``
   ``AMD:AMDGPU:8:0:1``  ``gfx801:xnack+``
   ``AMD:AMDGPU:8:0:2``  ``gfx802``
   ``AMD:AMDGPU:8:0:3``  ``gfx803``
   ``AMD:AMDGPU:8:0:4``  ``gfx803``
   ``AMD:AMDGPU:8:0:5``  ``gfx805``
   ``AMD:AMDGPU:8:1:0``  ``gfx810:xnack+``
   ``AMD:AMDGPU:9:0:0``  ``gfx900:xnack-``
   ``AMD:AMDGPU:9:0:1``  ``gfx900:xnack+``
   ``AMD:AMDGPU:9:0:2``  ``gfx902:xnack-``
   ``AMD:AMDGPU:9:0:3``  ``gfx902:xnack+``
   ``AMD:AMDGPU:9:0:4``  ``gfx904:xnack-``
   ``AMD:AMDGPU:9:0:5``  ``gfx904:xnack+``
   ``AMD:AMDGPU:9:0:6``  ``gfx906:sramecc-:xnack-``
   ``AMD:AMDGPU:9:0:7``  ``gfx906:sramecc-:xnack+``
   ``AMD:AMDGPU:9:0:12`` ``gfx90c:xnack-``

``.note`` section when compiling for code object V3 to V4.

``NT_AMDGPU_METADATA``
Specifies extensible metadata associated with an AMDGPU code object. It is
encoded as a map in the Message Pack [MsgPack]_ binary data format. See
:ref:`amdgpu-amdhsa-code-object-metadata-v3` and
:ref:`amdgpu-amdhsa-code-object-metadata-v4` for the map keys defined for the
``amdhsa`` OS.

encoded as a map in the Message Pack 

Global variable
Global variables both used and defined by the compilation unit.

If the symbol is defined in the compilation unit then it is allocated in the
appropriate section according to if it has initialized data or is readonly.

If the symbol is external then its section is ``STN_UNDEF`` and the loader
will resolve relocations using the definition provided by another code object
or explicitly defined by the runtime.

If the symbol resides in local/group memory (LDS) then its section is the
special processor specific section name ``SHN_AMDGPU_LDS``, and the
``st_value`` field describes alignment requirements as it does for common
symbols.

.. TODO::

   Add description of linked shared object symbols. Seems undefined symbols
   are marked as STT_NOTYPE.

 and the loader

symbols.

special processor specific section name 

 field describes alignment requirements as it does for common
symbols.

Add description of linked shared object symbols. Seems undefined symbols
are marked as STT_NOTYPE.

Kernel descriptor
Every HSA kernel has an associated kernel descriptor. It is the address of the
kernel descriptor that is used in the AQL dispatch packet used to invoke the
kernel, not the kernel entry point. The layout of the HSA kernel descriptor is
defined in :ref:`amdgpu-amdhsa-kernel-descriptor`.

defined in 

Kernel entry point
Every HSA kernel also has a symbol for its machine code entry point.

AMDGPU backend generates ``Elf64_Rela`` relocation records. Supported
relocatable fields are:

``word32``
This specifies a 32-bit field occupying 4 bytes with arbitrary byte
alignment. These values use the same byte order as other word values in the
AMDGPU architecture.

``word64``
This specifies a 64-bit field occupying 8 bytes with arbitrary byte

Following notations are used for specifying relocation calculations:

**A**
Represents the addend used to compute the value of the relocatable field.

**G**
Represents the offset into the global offset table at which the relocation
entry's symbol will reside during execution.

entry’s symbol will reside during execution.

**P**
Represents the place (section offset for ``et_rel`` or address for ``et_dyn``)
of the storage unit being relocated (computed using ``r_offset``).

**S**
Represents the value of the symbol whose index resides in the relocation
entry. Relocations not using this must specify a symbol index of
``STN_UNDEF``.

**B**
Represents the base address of a loaded executable or shared object which is
the difference between the ELF address and the actual load address.
Relocations using this are only valid in executable or shared objects.

``R_AMDGPU_ABS32_LO`` and ``R_AMDGPU_ABS32_HI`` are only supported by
the ``mesa3d`` OS, which does not support ``R_AMDGPU_ABS64``.

There is no current OS loader support for 32-bit programs and so
``R_AMDGPU_ABS32`` is not used.

The AMD GPU code object loader represents the path of the ELF shared object from
which the code object was loaded as a textual Uniform Resource Identifier (URI).
Note that the code object is the in memory loaded relocated form of the ELF
shared object.  Multiple code objects may be loaded at different memory
addresses in the same process from the same ELF shared object.

The loaded code object path URI syntax is defined by the following BNF syntax:

code_object_uri ::== file_uri | memory_uri
file_uri        ::== "file://" file_path [ range_specifier ]
memory_uri      ::== "memory://" process_id range_specifier
range_specifier ::== [ "#" | "?" ] "offset=" number "&" "size=" number
file_path       ::== URI_ENCODED_OS_FILE_PATH
process_id      ::== DECIMAL_NUMBER
number          ::== HEX_NUMBER | DECIMAL_NUMBER | OCTAL_NUMBER

**number**
Is a C integral literal where hexadecimal values are prefixed by "0x" or "0X",
and octal values by "0".

Is a C integral literal where hexadecimal values are prefixed by “0x” or “0X”,
and octal values by “0”.

**file_path**
Is the file's path specified as a URI encoded UTF-8 string. In URI encoding,
every character that is not in the regular expression ``[a-zA-Z0-9/_.~-]`` is
encoded as two uppercase hexadecimal digits proceeded by "%".  Directories in
the path are separated by "/".

Is the file’s path specified as a URI encoded UTF-8 string. In URI encoding,
every character that is not in the regular expression 

 is
encoded as two uppercase hexadecimal digits proceeded by “%”.  Directories in
the path are separated by “/”.

 is

**offset**
Is a 0-based byte offset to the start of the code object.  For a file URI, it
is from the start of the file specified by the ``file_path``, and if omitted
defaults to 0. For a memory URI, it is the memory address and is required.

is from the start of the file specified by the 

, and if omitted

**size**
Is the number of bytes in the code object.  For a file URI, if omitted it
defaults to the size of the file.  It is required for a memory URI.

**process_id**
Is the identity of the process owning the memory.  For Linux it is the C
unsigned integral decimal literal for the process ID (PID).

This section describes **provisional support** for AMDGPU DWARF [DWARF]_ that
is not currently fully implemented and is subject to change.

 that

AMDGPU generates DWARF [DWARF]_ debugging information ELF sections (see
:ref:`amdgpu-elf-code-object`) which contain information that maps the code
object executable code and data to the source language constructs. It can be
used by tools such as debuggers and profilers. It uses features defined in
:doc:`AMDGPUDwarfExtensionsForHeterogeneousDebugging` that are made available in
DWARF Version 4 and DWARF Version 5 as an LLVM vendor extension.

) which contain information that maps the code

 that are made available in

This section defines the AMDGPU target architecture specific DWARF mappings.

This section defines the AMDGPU target architecture register numbers used in
DWARF operation expressions (see DWARF Version 5 section 2.5 and
:ref:`amdgpu-dwarf-operation-expressions`) and Call Frame Information
instructions (see DWARF Version 5 section 6.4 and
:ref:`amdgpu-dwarf-call-frame-information`).

) and Call Frame Information

A single code object can contain code for kernels that have different wavefront
sizes. The vector registers and some scalar registers are based on the wavefront
size. AMDGPU defines distinct DWARF registers for each wavefront size. This
simplifies the consumer of the DWARF so that each register has a fixed size,
rather than being dynamic according to the wavefront size mode. Similarly,
distinct DWARF registers are defined for those registers that vary in size
according to the process address size. This allows a consumer to treat a
specific AMDGPU processor as a single architecture regardless of how it is
configured at run time. The compiler explicitly specifies the DWARF registers
that match the mode in which the code it is generating will be executed.

DWARF registers are encoded as numbers, which are mapped to architecture
registers. The mapping for AMDGPU is defined in
:ref:`amdgpu-dwarf-register-mapping-table`. All AMDGPU targets use the same
mapping.

Program Counter (PC) when
executing in a 32-bit process
address space. Used in the CFI to
describe the PC of the calling
frame.

executing in a 64-bit process
frame.

*Reserved for frequently accessed
registers using DWARF 1-byte ULEB.*

Reserved for frequently accessed
registers using DWARF 1-byte ULEB.

Vector Condition Code Register
when executing in wavefront 32
mode.

*Reserved for future Vector
Architectural Registers when
executing in wavefront 32 mode.*

Reserved for future Vector
executing in wavefront 32 mode.

when executing in wavefront 64
mode.

executing in wavefront 64 mode.*

executing in wavefront 64 mode.

Vector General Purpose Registers
mode.

General Purpose Registers when

Vector Accumulation Registers
mode.

Accumulation Registers when

mode.

mode.

The vector registers are represented as the full size for the wavefront. They
are organized as consecutive dwords (32-bits), one per lane, with the dword at
the least significant bit position corresponding to lane 0 and so forth. DWARF
location expressions involving the ``DW_OP_LLVM_offset`` and
``DW_OP_LLVM_push_lane`` operations are used to select the part of the vector
register corresponding to the lane that is executing the current thread of
execution in languages that are implemented using a SIMD or SIMT execution
model.

location expressions involving the 

 operations are used to select the part of the vector
model.

If the wavefront size is 32 lanes then the wavefront 32 mode register
definitions are used. If the wavefront size is 64 lanes then the wavefront 64
mode register definitions are used. Some AMDGPU targets support executing in
both wavefront 32 and wavefront 64 mode. The register definitions corresponding
to the wavefront mode of the generated code will be used.

If code is generated to execute in a 32-bit process address space, then the
32-bit process address space register definitions are used. If code is generated
to execute in a 64-bit process address space, then the 64-bit process address
space register definitions are used. The ``amdgcn`` target only supports the
64-bit process address space.

space register definitions are used. The 

The DWARF address class represents the source language memory space. See DWARF
Version 5 section 2.12 which is updated by the *DWARF Extensions For
Heterogeneous Debugging* section :ref:`amdgpu-dwarf-segment_addresses`.

Version 5 section 2.12 which is updated by the 

The DWARF address class mapping used for AMDGPU is defined in
:ref:`amdgpu-dwarf-address-class-mapping-table`.

The DWARF address class values defined in the *DWARF Extensions For
Heterogeneous Debugging* section :ref:`amdgpu-dwarf-segment_addresses` are used.

In addition, ``DW_ADDR_AMDGPU_region`` is encoded as a vendor extension. This is
available for use for the AMD extension for access to the hardware GDS memory
which is scratchpad memory allocated per device.

 is encoded as a vendor extension. This is

For AMDGPU if no ``DW_AT_address_class`` attribute is present, then the default
address class of ``DW_ADDR_none`` is used.

See :ref:`amdgpu-dwarf-address-space-identifier` for information on the AMDGPU
mapping of DWARF address classes to DWARF address spaces, including address size
and NULL value.

 for information on the AMDGPU

DWARF address spaces correspond to target architecture specific linear
addressable memory areas. See DWARF Version 5 section 2.12 and *DWARF Extensions
For Heterogeneous Debugging* section :ref:`amdgpu-dwarf-segment_addresses`.

addressable memory areas. See DWARF Version 5 section 2.12 and 

The DWARF address space mapping used for AMDGPU is defined in
:ref:`amdgpu-dwarf-address-space-mapping-table`.

See :ref:`amdgpu-address-spaces` for information on the AMDGPU address spaces
including address size and NULL value.

 for information on the AMDGPU address spaces

The ``DW_ASPACE_none`` address space is the default target architecture address
space used in DWARF operations that do not specify an address space. It
therefore has to map to the global address space so that the ``DW_OP_addr*`` and
related operations can refer to addresses in the program code.

 address space is the default target architecture address
therefore has to map to the global address space so that the 

 and

The ``DW_ASPACE_AMDGPU_generic`` address space allows location expressions to
specify the flat address space. If the address corresponds to an address in the
local address space, then it corresponds to the wavefront that is executing the
focused thread of execution. If the address corresponds to an address in the
private address space, then it corresponds to the lane that is executing the
focused thread of execution for languages that are implemented using a SIMD or
SIMT execution model.

 address space allows location expressions to

CUDA-like languages such as HIP that do not have address spaces in the
language type system, but do allow variables to be allocated in different
address spaces, need to explicitly specify the ``DW_ASPACE_AMDGPU_generic``
address space in the DWARF expression operations as the default address space
is the global address space.

address spaces, need to explicitly specify the 

The ``DW_ASPACE_AMDGPU_local`` address space allows location expressions to
specify the local address space corresponding to the wavefront that is executing
the focused thread of execution.

The ``DW_ASPACE_AMDGPU_private_lane`` address space allows location expressions
to specify the private address space corresponding to the lane that is executing
the focused thread of execution for languages that are implemented using a SIMD
or SIMT execution model.

 address space allows location expressions

The ``DW_ASPACE_AMDGPU_private_wave`` address space allows location expressions
to specify the unswizzled private address space corresponding to the wavefront
that is executing the focused thread of execution. The wavefront view of private
memory is the per wavefront unswizzled backing memory layout defined in
:ref:`amdgpu-address-spaces`, such that address 0 corresponds to the first
location for the backing memory of the wavefront (namely the address is not
offset by ``wavefront-scratch-base``). The following formula can be used to
convert from a ``DW_ASPACE_AMDGPU_private_lane`` address to a
``DW_ASPACE_AMDGPU_private_wave`` address:

, such that address 0 corresponds to the first
offset by 

private-address-wavefront =
  ((private-address-lane / 4) * wavefront-size * 4) +
  (wavefront-lane-id * 4) + (private-address-lane % 4)

If the ``DW_ASPACE_AMDGPU_private_lane`` address is dword aligned, and the start
of the dwords for each lane starting with lane 0 is required, then this
simplifies to:

 address is dword aligned, and the start

  private-address-lane * wavefront-size

A compiler can use the ``DW_ASPACE_AMDGPU_private_wave`` address space to read a
complete spilled vector register back into a complete vector register in the
CFI. The frame pointer can be a private lane address which is dword aligned,
which can be shifted to multiply by the wavefront size, and then used to form a
private wavefront address that gives a location for a contiguous set of dwords,
one per lane, where the vector register dwords are spilled. The compiler knows
the wavefront size since it generates the code. Note that the type of the
address may have to be converted as the size of a
``DW_ASPACE_AMDGPU_private_lane`` address may be smaller than the size of a
``DW_ASPACE_AMDGPU_private_wave`` address.

 address space to read a

DWARF lane identifies specify a target architecture lane position for hardware
that executes in a SIMD or SIMT manner, and on which a source language maps its
threads of execution onto those lanes. The DWARF lane identifier is pushed by
the ``DW_OP_LLVM_push_lane`` DWARF expression operation. See DWARF Version 5
section 2.5 which is updated by *DWARF Extensions For Heterogeneous Debugging*
section :ref:`amdgpu-dwarf-operation-expressions`.

the 

 DWARF expression operation. See DWARF Version 5
section 2.5 which is updated by 

For AMDGPU, the lane identifier corresponds to the hardware lane ID of a
wavefront. It is numbered from 0 to the wavefront size minus 1.

DWARF expressions are used to compute program values and the locations of
program objects. See DWARF Version 5 section 2.5 and
:ref:`amdgpu-dwarf-operation-expressions`.

DWARF location descriptions describe how to access storage which includes memory
and registers. When accessing storage on AMDGPU, bytes are ordered with least
significant bytes first, and bits are ordered within bytes with least
significant bits first.

For AMDGPU CFI expressions, ``DW_OP_LLVM_select_bit_piece`` is used to describe
unwinding vector registers that are spilled under the execution mask to memory:
the zero-single location description is the vector register, and the one-single
location description is the spilled memory location description. The
``DW_OP_LLVM_form_aspace_address`` is used to specify the address space of the
memory location description.

 is used to describe

 is used to specify the address space of the

In AMDGPU expressions, ``DW_OP_LLVM_select_bit_piece`` is used by the
``DW_AT_LLVM_lane_pc`` attribute expression where divergent control flow is
controlled by the execution mask. An undefined location description together
with ``DW_OP_LLVM_extend`` is used to indicate the lane was not active on entry
to the subprogram. See :ref:`amdgpu-dwarf-dw-at-llvm-lane-pc` for an example.

 attribute expression where divergent control flow is
with 

 is used to indicate the lane was not active on entry
to the subprogram. See 

This section describes how certain debugger information entry attributes are
used by AMDGPU. See the sections in DWARF Version 5 section 2 which are updated
by *DWARF Extensions For Heterogeneous Debugging* section
:ref:`amdgpu-dwarf-debugging-information-entry-attributes`.

by 

For AMDGPU, the ``DW_AT_LLVM_lane_pc`` attribute is used to specify the program
location of the separate lanes of a SIMT thread.

 attribute is used to specify the program

If the lane is an active lane then this will be the same as the current program
location.

If the lane is inactive, but was active on entry to the subprogram, then this is
the program location in the subprogram at which execution of the lane is
conceptual positioned.

If the lane was not active on entry to the subprogram, then this will be the
undefined location. A client debugger can check if the lane is part of a valid
work-group by checking that the lane is in the range of the associated
work-group within the grid, accounting for partial work-groups. If it is not,
then the debugger can omit any information for the lane. Otherwise, the debugger
may repeatedly unwind the stack and inspect the ``DW_AT_LLVM_lane_pc`` of the
calling subprogram until it finds a non-undefined location. Conceptually the
lane only has the call frames that it has a non-undefined
``DW_AT_LLVM_lane_pc``.

may repeatedly unwind the stack and inspect the 

 of the

The following example illustrates how the AMDGPU backend can generate a DWARF
location list expression for the nested ``IF/THEN/ELSE`` structures of the
following subprogram pseudo code for a target with 64 lanes per wavefront.

location list expression for the nested 

 structures of the

SUBPROGRAM X
BEGIN
  a;
  IF (c1) THEN
    b;
    IF (c2) THEN
      c;
    ELSE
      d;
    ENDIF
    e;
  ELSE
    f;
  ENDIF
  g;
END

The AMDGPU backend may generate the following pseudo LLVM MIR to manipulate the
execution mask (``EXEC``) to linearize the control flow. The condition is
evaluated to make a mask of the lanes for which the condition evaluates to true.
First the ``THEN`` region is executed by setting the ``EXEC`` mask to the
logical ``AND`` of the current ``EXEC`` mask with the condition mask. Then the
``ELSE`` region is executed by negating the ``EXEC`` mask and logical ``AND`` of
the saved ``EXEC`` mask at the start of the region. After the ``IF/THEN/ELSE``
region the ``EXEC`` mask is restored to the value it had at the beginning of the
region. This is shown below. Other approaches are possible, but the basic
concept is the same.

execution mask (

) to linearize the control flow. The condition is
First the 

 mask is restored to the value it had at the beginning of the

$lex_start:
  a;
  %1 = EXEC
  %2 = c1
$lex_1_start:
  EXEC = %1 & %2
$if_1_then:
    b;
    %3 = EXEC
    %4 = c2
$lex_1_1_start:
    EXEC = %3 & %4
$lex_1_1_then:
      c;
    EXEC = ~EXEC & %3
$lex_1_1_else:
      d;
    EXEC = %3
$lex_1_1_end:
    e;
  EXEC = ~EXEC & %1
$lex_1_else:
    f;
  EXEC = %1
$lex_1_end:
  g;
$lex_end:

To create the DWARF location list expression that defines the location
description of a vector of lane program locations, the LLVM MIR ``DBG_VALUE``
pseudo instruction can be used to annotate the linearized control flow. This can
be done by defining an artificial variable for the lane PC. The DWARF location
list expression created for it is used as the value of the
``DW_AT_LLVM_lane_pc`` attribute on the subprogram's debugger information entry.

description of a vector of lane program locations, the LLVM MIR 

A DWARF procedure is defined for each well nested structured control flow region
which provides the conceptual lane program location for a lane if it is not
active (namely it is divergent). The DWARF operation expression for each region
conceptually inherits the value of the immediately enclosing region and modifies
it according to the semantics of the region.

For an ``IF/THEN/ELSE`` region the divergent program location is at the start of
the region for the ``THEN`` region since it is executed first. For the ``ELSE``
region the divergent program location is at the end of the ``IF/THEN/ELSE``
region since the ``THEN`` region has completed.

 region the divergent program location is at the start of
the region for the 

The lane PC artificial variable is assigned at each region transition. It uses
the immediately enclosing region's DWARF procedure to compute the program
location for each lane assuming they are divergent, and then modifies the result
by inserting the current program location for each lane that the ``EXEC`` mask
indicates is active.

the immediately enclosing region’s DWARF procedure to compute the program
by inserting the current program location for each lane that the 

By having separate DWARF procedures for each region, they can be reused to
define the value for any nested region. This reduces the total size of the DWARF
operation expressions.

  DEFINE_DWARF %__uint_64 = DW_TAG_base_type[
    DW_AT_name = "__uint64";
    DW_AT_byte_size = 8;
    DW_AT_encoding = DW_ATE_unsigned;
  ];
  DEFINE_DWARF %__active_lane_pc = DW_TAG_dwarf_procedure[
    DW_AT_name = "__active_lane_pc";
    DW_AT_location = [
      DW_OP_regx PC;
      DW_OP_LLVM_extend 64, 64;
      DW_OP_regval_type EXEC, %uint_64;
      DW_OP_LLVM_select_bit_piece 64, 64;
    ];
  ];
  DEFINE_DWARF %__divergent_lane_pc = DW_TAG_dwarf_procedure[
    DW_AT_name = "__divergent_lane_pc";
      DW_OP_LLVM_undefined;
    ];
  ];
  DBG_VALUE $noreg, $noreg, %DW_AT_LLVM_lane_pc, DIExpression[
    DW_OP_call_ref %__divergent_lane_pc;
    DW_OP_call_ref %__active_lane_pc;
  ];
  a;
  %1 = EXEC;
  DBG_VALUE %1, $noreg, %__lex_1_save_exec;
  %2 = c1;
  EXEC = %1 & %2;
$lex_1_then:
    DEFINE_DWARF %__divergent_lane_pc_1_then = DW_TAG_dwarf_procedure[
      DW_AT_name = "__divergent_lane_pc_1_then";
      DW_AT_location = DIExpression[
        DW_OP_call_ref %__divergent_lane_pc;
        DW_OP_addrx &lex_1_start;
        DW_OP_stack_value;
        DW_OP_LLVM_extend 64, 64;
        DW_OP_call_ref %__lex_1_save_exec;
        DW_OP_deref_type 64, %__uint_64;
        DW_OP_LLVM_select_bit_piece 64, 64;
      ];
    ];
    DBG_VALUE $noreg, $noreg, %DW_AT_LLVM_lane_pc, DIExpression[
      DW_OP_call_ref %__divergent_lane_pc_1_then;
      DW_OP_call_ref %__active_lane_pc;
    ];
    b;
    %3 = EXEC;
    DBG_VALUE %3, %__lex_1_1_save_exec;
    %4 = c2;
    EXEC = %3 & %4;
      DEFINE_DWARF %__divergent_lane_pc_1_1_then = DW_TAG_dwarf_procedure[
        DW_AT_name = "__divergent_lane_pc_1_1_then";
        DW_AT_location = DIExpression[
          DW_OP_call_ref %__divergent_lane_pc_1_then;
          DW_OP_addrx &lex_1_1_start;
          DW_OP_stack_value;
          DW_OP_LLVM_extend 64, 64;
          DW_OP_call_ref %__lex_1_1_save_exec;
          DW_OP_deref_type 64, %__uint_64;
          DW_OP_LLVM_select_bit_piece 64, 64;
        ];
      ];
      DBG_VALUE $noreg, $noreg, %DW_AT_LLVM_lane_pc, DIExpression[
        DW_OP_call_ref %__divergent_lane_pc_1_1_then;
        DW_OP_call_ref %__active_lane_pc;
      ];
      c;
    EXEC = ~EXEC & %3;
      DEFINE_DWARF %__divergent_lane_pc_1_1_else = DW_TAG_dwarf_procedure[
        DW_AT_name = "__divergent_lane_pc_1_1_else";
          DW_OP_addrx &lex_1_1_end;
        ];
      ];
        DW_OP_call_ref %__divergent_lane_pc_1_1_else;
      ];
      d;
    EXEC = %3;
      DW_OP_call_ref %__divergent_lane_pc;
    ];
    e;
  EXEC = ~EXEC & %1;
    DEFINE_DWARF %__divergent_lane_pc_1_else = DW_TAG_dwarf_procedure[
      DW_AT_name = "__divergent_lane_pc_1_else";
        DW_OP_addrx &lex_1_end;
      ];
    ];
      DW_OP_call_ref %__divergent_lane_pc_1_else;
    ];
    f;
  EXEC = %1;
  DBG_VALUE $noreg, $noreg, %DW_AT_LLVM_lane_pc DIExpression[
  ];
  g;
$lex_end:

The DWARF procedure ``%__active_lane_pc`` is used to update the lane pc elements
that are active, with the current program location.

 is used to update the lane pc elements

Artificial variables %__lex_1_save_exec and %__lex_1_1_save_exec are created for
the execution masks saved on entry to a region. Using the ``DBG_VALUE`` pseudo
instruction, location list entries will be created that describe where the
artificial variables are allocated at any given program location. The compiler
may allocate them to registers or spill them to memory.

the execution masks saved on entry to a region. Using the 

 pseudo

The DWARF procedures for each region use the values of the saved execution mask
artificial variables to only update the lanes that are active on entry to the
region. All other lanes retain the value of the enclosing region where they were
last active. If they were not active on entry to the subprogram, then will have
the undefined location description.

Other structured control flow regions can be handled similarly. For example,
loops would set the divergent program location for the region at the end of the
loop. Any lanes active will be in the loop, and any lanes not active must have
exited the loop.

An ``IF/THEN/ELSEIF/ELSEIF/...`` region can be treated as a nest of
``IF/THEN/ELSE`` regions.

The DWARF procedures can use the active lane artificial variable described in
:ref:`amdgpu-dwarf-amdgpu-dw-at-llvm-active-lane` rather than the actual
``EXEC`` mask in order to support whole or quad wavefront mode.

The ``DW_AT_LLVM_active_lane`` attribute on a subprogram debugger information
entry is used to specify the lanes that are conceptually active for a SIMT
thread.

 attribute on a subprogram debugger information
thread.

The execution mask may be modified to implement whole or quad wavefront mode
operations. For example, all lanes may need to temporarily be made active to
execute a whole wavefront operation. Such regions would save the ``EXEC`` mask,
update it to enable the necessary lanes, perform the operations, and then
restore the ``EXEC`` mask from the saved value. While executing the whole
wavefront region, the conceptual execution mask is the saved value, not the
``EXEC`` value.

execute a whole wavefront operation. Such regions would save the 

 mask,
restore the 

 mask from the saved value. While executing the whole

This is handled by defining an artificial variable for the active lane mask. The
active lane mask artificial variable would be the actual ``EXEC`` mask for
normal regions, and the saved execution mask for regions where the mask is
temporarily updated. The location list expression created for this artificial
variable is used to define the value of the ``DW_AT_LLVM_active_lane``
attribute.

active lane mask artificial variable would be the actual 

 mask for
variable is used to define the value of the 

For AMDGPU, the ``DW_AT_LLVM_augmentation`` attribute of a compilation unit
debugger information entry has the following value for the augmentation string:

 attribute of a compilation unit

The "vX.Y" specifies the major X and minor Y version number of the AMDGPU
extensions used in the DWARF of the compilation unit. The version number
conforms to [SEMVER]_.

The “vX.Y” specifies the major X and minor Y version number of the AMDGPU
conforms to 

DWARF Call Frame Information (CFI) describes how a consumer can virtually
*unwind* call frames in a running process or core dump. See DWARF Version 5
section 6.4 and :ref:`amdgpu-dwarf-call-frame-information`.

 call frames in a running process or core dump. See DWARF Version 5
section 6.4 and 

For AMDGPU, the Common Information Entry (CIE) fields have the following values:

``augmentation`` string contains the following null-terminated UTF-8 string:

::

  [amd:v0.0]

The ``vX.Y`` specifies the major X and minor Y version number of the AMDGPU
extensions used in this CIE or to the FDEs that use it. The version number

 specifies the major X and minor Y version number of the AMDGPU

``address_size`` for the ``Global`` address space is defined in
:ref:`amdgpu-dwarf-address-space-identifier`.

``segment_selector_size`` is 0 as AMDGPU does not use a segment selector.

``code_alignment_factor`` is 4 bytes.

.. TODO::

   Add to :ref:`amdgpu-processor-table` table.

``data_alignment_factor`` is 4 bytes.

.. TODO::

``return_address_register`` is ``PC_32`` for 32-bit processes and ``PC_64``
for 64-bit processes defined in :ref:`amdgpu-dwarf-register-identifier`.

``initial_instructions`` Since a subprogram X with fewer registers can be
called from subprogram Y that has more allocated, X will not change any of
the extra registers as it cannot access them. Therefore, the default rule
for all columns is ``same value``.

 Since a subprogram X with fewer registers can be
for all columns is 

For AMDGPU the register number follows the numbering defined in
:ref:`amdgpu-dwarf-register-identifier`.

For AMDGPU the instructions are variable size. A consumer can subtract 1 from
the return address to get the address of a byte within the call site
instructions. See DWARF Version 5 section 6.4.4.

See DWARF Version 5 section 6.1.1.4.1 and :ref:`amdgpu-dwarf-lookup-by-name`.

Set to the length of the ``augmentation_string`` value which is always a
multiple of 4.

Contains the following UTF-8 string null padded to a multiple of 4 bytes:

extensions used in the DWARF of this index. The version number conforms to
[SEMVER]_.

This is different to the DWARF Version 5 definition that requires the first
4 characters to be the vendor ID. But this is consistent with the other
augmentation strings and does allow multiple vendor contributions. However,
backwards compatibility may be more desirable.

Match the address size for the ``Global`` address space defined in

AMDGPU does not use a segment selector so this is 0. The entries in the
``.debug_aranges`` do not have a segment selector.

See DWARF Version 5 section 6.2 and :ref:`amdgpu-dwarf-line-number-information`.

AMDGPU does not use the ``isa`` state machine registers and always sets it to 0.
The instruction set must be obtained from the ELF file header ``e_flags`` field
in the ``EF_AMDGPU_MACH`` bit position (see :ref:`ELF Header
<amdgpu-elf-header>`). See DWARF Version 5 section 6.2.2.

 state machine registers and always sets it to 0.
The instruction set must be obtained from the ELF file header 

Should the ``isa`` state machine register be used to indicate if the code is
in wavefront32 or wavefront64 mode? Or used to specify the architecture ISA?

 state machine register be used to indicate if the code is

For AMDGPU the line number program header fields have the following values (see
DWARF Version 5 section 6.2.4):

``address_size`` (ubyte)
Matches the address size for the ``Global`` address space defined in

``segment_selector_size`` (ubyte)
AMDGPU does not use a segment selector so this is 0.

``minimum_instruction_length`` (ubyte)
For GFX9-GFX10 this is 4.

``maximum_operations_per_instruction`` (ubyte)
For GFX9-GFX10 this is 1.

Source text for online-compiled programs (for example, those compiled by the
OpenCL language runtime) may be embedded into the DWARF Version 5 line table.
See DWARF Version 5 section 6.2.4.1 which is updated by *DWARF Extensions For
Heterogeneous Debugging* section :ref:`DW_LNCT_LLVM_source
<amdgpu-dwarf-line-number-information-dw-lnct-llvm-source>`.

See DWARF Version 5 section 6.2.4.1 which is updated by 

The Clang option used to control source embedding in AMDGPU is defined in
:ref:`amdgpu-clang-debug-options-table`.

Enable/disable embedding source text in DWARF
debug sections. Useful for environments where
source cannot be written to disk, such as
when performing online compilation.

See DWARF Version 5 section 7.4 and
:ref:`amdgpu-dwarf-32-bit-and-64-bit-dwarf-formats`.

For the ``amdgcn`` target architecture only the 64-bit process address space
is supported.

 target architecture only the 64-bit process address space

The producer can generate either 32-bit or 64-bit DWARF format. LLVM generates
the 32-bit DWARF format.

For AMDGPU the following values apply for each of the unit headers described in
DWARF Version 5 sections 7.5.1.1, 7.5.1.2, and 7.5.1.3:

This section provides code conventions used for each supported target triple OS
(see :ref:`amdgpu-target-triples`).

(see 

This section provides code conventions used when the target triple OS is
``amdhsa`` (see :ref:`amdgpu-target-triples`).

The code object metadata specifies extensible metadata associated with the code
objects executed on HSA [HSA]_ compatible runtimes (see :ref:`amdgpu-os`). The
encoding and semantics of this metadata depends on the code object version; see
:ref:`amdgpu-amdhsa-code-object-metadata-v2`,
:ref:`amdgpu-amdhsa-code-object-metadata-v3`, and
:ref:`amdgpu-amdhsa-code-object-metadata-v4`.

objects executed on HSA 

). The

Code object metadata is specified in a note record (see
:ref:`amdgpu-note-records`) and is required when the target triple OS is
``amdhsa`` (see :ref:`amdgpu-target-triples`). It must contain the minimum
information necessary to support the HSA compatible runtime kernel queries. For
example, the segment sizes needed in a dispatch packet. In addition, a
high-level language runtime may require other information to be included. For
example, the AMD OpenCL runtime records kernel argument information.

). It must contain the minimum

Code object V2 is not the default code object version emitted by this version
of LLVM.

Code object V2 metadata is specified by the ``NT_AMD_HSA_METADATA`` note record
(see :ref:`amdgpu-note-records-v2`).

The metadata is specified as a YAML formatted string (see [YAML]_ and
:doc:`YamlIO`).

Is the string null terminated? It probably should not if YAML allows it to
contain null characters, otherwise it should be.

The metadata is represented as a single YAML document comprised of the mapping
defined in table :ref:`amdgpu-amdhsa-code-object-metadata-map-v2-table` and
referenced tables.

defined in table 

For boolean values, the string values of ``false`` and ``true`` are used for
false and true respectively.

Additional information can be added to the mappings. To avoid conflicts, any
non-AMD key names should be prefixed by "*vendor-name*.".

non-AMD key names should be prefixed by “

non-AMD key names should be prefixed by "

Each string is encoded information
about a printf function call. The
encoded information is organized as
fields separated by colon (':'):

fields separated by colon (‘:’):

``ID``
A 32-bit integer as a unique id for
each printf function call

``N``
A 32-bit integer equal to the number
of arguments of printf function call
minus 1

minus 1

``S[i]`` (where i = 0, 1, ... , N-1)
32-bit integers for the size in bytes
of the i-th FormatString argument of
the printf function call

FormatString
The format string passed to the
printf function call.

Sequence of the mappings for each
kernel in the code object. See
:ref:`amdgpu-amdhsa-code-object-kernel-metadata-map-v2-table`
for the definition of the mapping.

Mapping of kernel attributes.
See
:ref:`amdgpu-amdhsa-code-object-kernel-attribute-metadata-map-v2-table`
for the mapping definition.

Sequence of mappings of the
kernel arguments. See
:ref:`amdgpu-amdhsa-code-object-kernel-argument-metadata-map-v2-table`

Mapping of properties related to
the kernel code. See
:ref:`amdgpu-amdhsa-code-object-kernel-code-properties-metadata-map-v2-table`

If not 0, 0, 0 then all values
must be >=1 and the dispatch
work-group size X, Y, Z must
correspond to the specified
values. Defaults to 0, 0, 0.

The dispatch work-group size
X, Y, Z is likely to be the
specified values.

The external symbol name
associated with a kernel.
OpenCL runtime allocates a
global buffer for the symbol
and saves the kernel's address
to it, which is used for
device side enqueueing. Only
available for device side
enqueued kernels.

and saves the kernel’s address

Kernel argument kind that
specifies how to set up the
corresponding argument.
Values include:

"GlobalBuffer"
A global address space pointer
to the buffer data is passed
in the kernarg.

"DynamicSharedPointer"
A group address space pointer
to dynamically allocated LDS
is passed in the kernarg.

"Sampler"
A global address space
pointer to a S# is passed in
the kernarg.

"Image"
pointer to a T# is passed in

"Pipe"
to an OpenCL pipe is passed in

"Queue"
to an OpenCL device enqueue
queue is passed in the
kernarg.

kernarg.

"HiddenGlobalOffsetX"
The OpenCL grid dispatch
global offset for the X
dimension is passed in the
kernarg.

kernarg.

"HiddenGlobalOffsetY"
global offset for the Y
kernarg.

kernarg.

"HiddenGlobalOffsetZ"
global offset for the Z
kernarg.

kernarg.

"HiddenNone"
An argument that is not used
by the kernel. Space needs to
be left for it, but it does
not need to be set up.

"HiddenPrintfBuffer"
to the runtime printf buffer
is passed in kernarg.

"HiddenHostcallBuffer"
to the runtime hostcall buffer

"HiddenDefaultQueue"
to the OpenCL device enqueue
queue that should be used by
the kernel by default is
passed in the kernarg.

"HiddenCompletionAction"
to help link enqueued kernels into
the ancestor tree for determining
when the parent kernel has finished.

"HiddenMultiGridSyncArg"
A global address space pointer for
multi-grid synchronization is

Unused and deprecated. This should no longer
be emitted, but is accepted for compatibility.

Alignment in bytes of pointee
type for pointer type kernel
argument. Must be a power
of 2. Only present if
"ValueKind" is
"DynamicSharedPointer".

“ValueKind” is
“DynamicSharedPointer”.

Kernel argument address space
qualifier. Only present if
"ValueKind" is "GlobalBuffer" or
"DynamicSharedPointer". Values
are:

“ValueKind” is “GlobalBuffer” or
“DynamicSharedPointer”. Values
are:

Is GlobalBuffer only Global
or Constant? Is
DynamicSharedPointer always
Local? Can HCC allow Generic?
How can Private or Region
ever happen?

Kernel argument access
"ValueKind" is "Image" or
"Pipe". Values
are:

“ValueKind” is “Image” or
“Pipe”. Values
are:

The actual memory accesses
performed by the kernel on the
kernel argument. Only present if
"ValueKind" is "GlobalBuffer",
"Image", or "Pipe". This may be
more restrictive than indicated
by "AccQual" to reflect what the
kernel actual does. If not
present then the runtime must
assume what is implied by
"AccQual" and "IsConst". Values
are:

“ValueKind” is “GlobalBuffer”,
“Image”, or “Pipe”. This may be
by “AccQual” to reflect what the
“AccQual” and “IsConst”. Values
are:

Indicates if the kernel argument
is const qualified. Only present
if "ValueKind" is
"GlobalBuffer".

if “ValueKind” is
“GlobalBuffer”.

is restrict qualified. Only
present if "ValueKind" is

present if “ValueKind” is

is volatile qualified. Only

is pipe qualified. Only present
if "ValueKind" is "Pipe".

if “ValueKind” is “Pipe”.

The size in bytes of
the kernarg segment
that holds the values
of the arguments to
the kernel.

The amount of group
segment memory
required by a
work-group in
bytes. This does not
include any
dynamically allocated
group segment memory
that may be added
when the kernel is
dispatched.

The amount of fixed
private address space
memory required for a
work-item in
bytes. If the kernel
uses a dynamic call
stack then additional
space must be added
to this value for the
call stack.

The maximum byte
alignment of
arguments in the
kernarg segment. Must
be a power of 2.

Number of scalar
registers used by a
wavefront for
GFX6-GFX10. This
includes the special
SGPRs for VCC, Flat
Scratch (GFX7-GFX10)
and XNACK (for
GFX8-GFX10). It does
not include the 16
SGPR added if a trap
handler is
enabled. It is not
rounded up to the
allocation
granularity.

Number of vector
registers used by
each work-item for
GFX6-GFX10

Maximum flat
work-group size
supported by the
kernel in work-items.
Must be >=1 and
consistent with
ReqdWorkGroupSize if
not 0, 0, 0.

Number of stores from
a scalar register to
a register allocator
created spill
location.

a vector register to
location.

Code object V3 to V4 metadata is specified by the ``NT_AMDGPU_METADATA`` note
record (see :ref:`amdgpu-note-records-v3-v4`).

The metadata is represented as Message Pack formatted binary data (see
[MsgPack]_). The top level is a Message Pack map that includes the
keys defined in table
:ref:`amdgpu-amdhsa-code-object-metadata-map-table-v3` and referenced
tables.

). The top level is a Message Pack map that includes the

Additional information can be added to the maps. To avoid conflicts,
any key names should be prefixed by "*vendor-name*." where
``vendor-name`` can be the name of the vendor and specific vendor
tool that generates the information. The prefix is abbreviated to
simply "." when it appears within a map that has been added by the
same *vendor-name*.

any key names should be prefixed by “

any key names should be prefixed by "

 can be the name of the vendor and specific vendor
simply “.” when it appears within a map that has been added by the
same 

same 

Sequence of the maps for each
:ref:`amdgpu-amdhsa-code-object-kernel-metadata-map-table-v3`
for the definition of the keys included
in that map.

Sequence of maps of the
:ref:`amdgpu-amdhsa-code-object-kernel-argument-metadata-map-table-v3`
for the definition of the keys
included in that map.

registers required by a
GFX6-GFX9. A register
is required if it is
used explicitly, or
if a higher numbered
register is used
explicitly. This
Scratch (GFX7-GFX9)
GFX8-GFX9). It does
handler is

registers required by
explicitly.

"init"
These kernels must be
invoked after loading
the containing code
object and must
complete before any
normal and fini
kernels in the same
code object are
invoked.

invoked.

"fini"
invoked before
unloading the
containing code object
and after all init and
normal kernels in the
same code object have
been invoked and
completed.

Kernel argument offset in
bytes. The offset must be a
multiple of the alignment
required by the argument.

"global_buffer"

"dynamic_shared_pointer"

"sampler"

"image"

"pipe"

"queue"
kernarg.

"hidden_global_offset_x"
kernarg.

"hidden_global_offset_y"
kernarg.

"hidden_global_offset_z"
kernarg.

"hidden_none"

"hidden_printf_buffer"

"hidden_hostcall_buffer"

"hidden_default_queue"

"hidden_completion_action"

"hidden_multigrid_sync_arg"

".value_kind" is
"dynamic_shared_pointer".

“.value_kind” is
“dynamic_shared_pointer”.

".value_kind" is "global_buffer" or
"dynamic_shared_pointer". Values
are:

“.value_kind” is “global_buffer” or
“dynamic_shared_pointer”. Values
are:

Is "global_buffer" only "global"
or "constant"? Is
"dynamic_shared_pointer" always
"local"? Can HCC allow "generic"?
How can "private" or "region"

Is “global_buffer” only “global”
or “constant”? Is
“dynamic_shared_pointer” always
“local”? Can HCC allow “generic”?
How can “private” or “region”

".value_kind" is "image" or
"pipe". Values
are:

“.value_kind” is “image” or
“pipe”. Values
are:

".value_kind" is "global_buffer",
"image", or "pipe". This may be
by ".access" to reflect what the
".access" and ".is_const"      . Values
are:

“.value_kind” is “global_buffer”,
“image”, or “pipe”. This may be
by “.access” to reflect what the
“.access” and “.is_const”      . Values
are:

if ".value_kind" is
"global_buffer".

if “.value_kind” is
“global_buffer”.

present if ".value_kind" is

present if “.value_kind” is

if ".value_kind" is "pipe".

if “.value_kind” is “pipe”.

Code object V4 is not the default code object version emitted by this version
of LLVM.

Code object V4 metadata is the same as
:ref:`amdgpu-amdhsa-code-object-metadata-v3` with the changes and additions
defined in table :ref:`amdgpu-amdhsa-code-object-metadata-map-table-v3`.

AMDHSA Code Object V4 Metadata Map Changes from :ref:`amdgpu-amdhsa-code-object-metadata-v3`

A canonical target ID must be
used. See :ref:`amdgpu-target-triples`
and :ref:`amdgpu-target-id`.

The HSA architected queuing language (AQL) defines a user space memory interface
that can be used to control the dispatch of kernels, in an agent independent
way. An agent can have zero or more AQL queues created for it using an HSA
compatible runtime (see :ref:`amdgpu-os`), in which AQL packets (all of which
are 64 bytes) can be placed. See the *HSA Platform System Architecture
Specification* [HSA]_ for the AQL queue mechanics and packet layouts.

compatible runtime (see 

), in which AQL packets (all of which
are 64 bytes) can be placed. See the 

The packet processor of a kernel agent is responsible for detecting and
dispatching HSA kernels from the AQL queues associated with it. For AMD GPUs the
packet processor is implemented by the hardware command processor (CP),
asynchronous dispatch controller (ADC) and shader processor input controller
(SPI).

An HSA compatible runtime can be used to allocate an AQL queue object. It uses
the kernel mode driver to initialize and register the AQL queue with CP.

To dispatch a kernel the following actions are performed. This can occur in the
CPU host program, or from an HSA kernel executing on a GPU.

A pointer to an AQL queue for the kernel agent on which the kernel is to be
executed is obtained.

A pointer to the kernel descriptor (see
:ref:`amdgpu-amdhsa-kernel-descriptor`) of the kernel to execute is obtained.
It must be for a kernel that is contained in a code object that that was
loaded by an HSA compatible runtime on the kernel agent with which the AQL
queue is associated.

) of the kernel to execute is obtained.

Space is allocated for the kernel arguments using the HSA compatible runtime
allocator for a memory region with the kernarg property for the kernel agent
that will execute the kernel. It must be at least 16-byte aligned.

Kernel argument values are assigned to the kernel argument memory
allocation. The layout is defined in the *HSA Programmer's Language
Reference* [HSA]_. For AMDGPU the kernel execution directly accesses the
kernel argument memory in the same way constant memory is accessed. (Note
that the HSA specification allows an implementation to copy the kernel
argument contents to another location that is accessed by the kernel.)

allocation. The layout is defined in the 

. For AMDGPU the kernel execution directly accesses the

An AQL kernel dispatch packet is created on the AQL queue. The HSA compatible
runtime api uses 64-bit atomic operations to reserve space in the AQL queue
for the packet. The packet must be set up, and the final write must use an
atomic store release to set the packet kind to ensure the packet contents are
visible to the kernel agent. AQL defines a doorbell signal mechanism to
notify the kernel agent that the AQL queue has been updated. These rules, and
the layout of the AQL queue and kernel dispatch packet is defined in the *HSA
System Architecture Specification* [HSA]_.

the layout of the AQL queue and kernel dispatch packet is defined in the 

A kernel dispatch packet includes information about the actual dispatch,
such as grid and work-group size, together with information from the code
object about the kernel, such as segment sizes. The HSA compatible runtime
queries on the kernel symbol can be used to obtain the code object values
which are recorded in the :ref:`amdgpu-amdhsa-code-object-metadata`.

which are recorded in the 

CP executes micro-code and is responsible for detecting and setting up the
GPU to execute the wavefronts of a kernel dispatch.

CP ensures that when the a wavefront starts executing the kernel machine
code, the scalar general purpose registers (SGPR) and vector general purpose
registers (VGPR) are set up as required by the machine code. The required
setup is defined in the :ref:`amdgpu-amdhsa-kernel-descriptor`. The initial
register state is defined in
:ref:`amdgpu-amdhsa-initial-kernel-execution-state`.

setup is defined in the 

The prolog of the kernel machine code (see
:ref:`amdgpu-amdhsa-kernel-prolog`) sets up the machine state as necessary
before continuing executing the machine code that corresponds to the kernel.

) sets up the machine state as necessary

When the kernel dispatch has completed execution, CP signals the completion
signal specified in the kernel dispatch packet if not 0.

The global and constant memory spaces both use global virtual addresses, which
are the same virtual address space used by the CPU. However, some virtual
addresses may only be accessible to the CPU, some only accessible by the GPU,
and some by both.

Using the constant memory space indicates that the data will not change during
the execution of the kernel. This allows scalar read instructions to be
used. The vector and scalar L1 caches are invalidated of volatile data before
each kernel dispatch execution to allow constant memory to change values between
kernel dispatches.

The local memory space uses the hardware Local Data Store (LDS) which is
automatically allocated when the hardware creates work-groups of wavefronts, and
freed when all the wavefronts of a work-group have terminated. The data store

The private memory space uses the hardware scratch memory support. If the kernel
uses scratch, then the hardware allocates memory that is accessed using
wavefront lane dword (4 byte) interleaving. The mapping used from private
address to physical address is:

(private-address * wavefront-size * 4) +
(wavefront-lane-id * 4)``

(wavefront-lane-id * 4)

There are different ways that the wavefront scratch base address is determined
by a wavefront (see :ref:`amdgpu-amdhsa-initial-kernel-execution-state`). This
memory can be accessed in an interleaved manner using buffer instruction with
the scratch buffer descriptor and per wavefront scratch offset, by the scratch
instructions, or by flat instructions. If each lane of a wavefront accesses the
same private address, the interleaving results in adjacent dwords being accessed
and hence requires fewer cache lines to be fetched. Multi-dword access is not
supported except by flat and scratch instructions in GFX9-GFX10.

by a wavefront (see 

). This

The generic address space uses the hardware flat address support available in
GFX7-GFX10. This uses two fixed ranges of virtual addresses (the private and
local apertures), that are outside the range of addressible global memory, to
map from a flat address to a private or local address.

FLAT instructions can take a flat address and access global, private (scratch)
and group (LDS) memory depending in if the address is within one of the
aperture ranges. Flat access to scratch requires hardware aperture setup and
setup in the kernel prologue (see
:ref:`amdgpu-amdhsa-kernel-prolog-flat-scratch`). Flat access to LDS requires
hardware aperture setup and M0 (GFX7-GFX8) register setup (see
:ref:`amdgpu-amdhsa-kernel-prolog-m0`).

). Flat access to LDS requires

To convert between a segment address and a flat address the base address of the
apertures address can be used. For GFX7-GFX8 these are available in the
GFX9-GFX10 the aperture base addresses are directly available as inline constant
registers ``SRC_SHARED_BASE/LIMIT`` and ``SRC_PRIVATE_BASE/LIMIT``. In 64 bit
address mode the aperture sizes are 2^32 bytes and the base is aligned to 2^32
which makes it easier to convert from flat to segment or segment to flat.

). For
registers 

. In 64 bit

Image and sample handles created by an HSA compatible runtime (see
:ref:`amdgpu-os`) are 64-bit addresses of a hardware 32-byte V# and 48 byte S#
object respectively. In order to support the HSA ``query_sampler`` operations
two extra dwords are used to store the HSA BRIG enumeration values for the
queries that are not trivially deducible from the S# representation.

) are 64-bit addresses of a hardware 32-byte V# and 48 byte S#
object respectively. In order to support the HSA 

 operations

HSA signal handles created by an HSA compatible runtime (see :ref:`amdgpu-os`)
are 64-bit addresses of a structure allocated in memory accessible from both the
CPU and GPU. The structure is defined by the runtime and subject to change
between releases. For example, see [AMD-ROCm-github]_.

)
between releases. For example, see 

The HSA AQL queue structure is defined by an HSA compatible runtime (see
:ref:`amdgpu-os`) and subject to change between releases. For example, see
[AMD-ROCm-github]_. For some processors it contains fields needed to implement
certain language features such as the flat address aperture bases. It also
contains fields used by CP such as managing the allocation of scratch memory.

. For some processors it contains fields needed to implement

A kernel descriptor consists of the information needed by CP to initiate the
execution of a kernel, including the entry point address of the machine code
that implements the kernel.

CP microcode requires the Kernel descriptor to be allocated on 64-byte

The fields used by CP for code objects before V3 also match those specified in
:ref:`amdgpu-amdhsa-kernel-descriptor-v3-table`.

The amount of fixed local
address space memory
required for a work-group
in bytes. This does not
include any dynamically
allocated local address
space memory that may be
added when the kernel is

work-item in bytes.
Additional space may need to
be added to this value if
the call stack has
non-inlined function calls.

The size of the kernarg
memory pointed to by the
AQL dispatch packet. The
kernarg memory is used to
pass arguments to the
kernel.

If the kernarg pointer in
the dispatch packet is NULL
then there are no kernel
arguments.

the dispatch packet is
not NULL and this value
is 0 then the kernarg
memory size is
unspecified.

is not 0 then the value
specifies the kernarg
memory size in bytes. It
is recommended to provide
a value as it may be used
by CP to optimize making
the kernarg memory
visible to the kernel
code.

code.

Byte offset (possibly
negative) from base
address of kernel
descriptor to kernel's
entry point instruction
which must be 256 byte
aligned.

descriptor to kernel’s
aligned.

GFX90A
Compute Shader (CS)
program settings used by
CP to set up
``COMPUTE_PGM_RSRC3``
configuration
register. See
:ref:`amdgpu-amdhsa-compute_pgm_rsrc3-gfx90a-table`.

CP to set up

GFX10
CP to set up
:ref:`amdgpu-amdhsa-compute_pgm_rsrc3-gfx10-table`.

CP to set up

CP to set up
``COMPUTE_PGM_RSRC1``
:ref:`amdgpu-amdhsa-compute_pgm_rsrc1-gfx6-gfx10-table`.

CP to set up
``COMPUTE_PGM_RSRC2``
:ref:`amdgpu-amdhsa-compute_pgm_rsrc2-gfx6-gfx10-table`.

Enable the setup of the
SGPR user data registers
(see

The total number of SGPR
user data registers
requested must not exceed
16 and match value in
``compute_pgm_rsrc2.user_sgpr.user_sgpr_count``.
Any requests beyond 16
will be ignored.

If the *Target Properties*
column of
:ref:`amdgpu-processor-table`
specifies *Architected flat
scratch* then not supported
and must be 0,

GFX10
- If 0 execute in
  wavefront size 64 mode.
- If 1 execute in
  native wavefront size
  32 mode.

Number of vector register
blocks used by each work-item;
granularity is device
specific:

GFX6-GFX9
- vgprs_used 0..256
- max(0, ceil(vgprs_used / 4) - 1)

GFX90A
- vgprs_used 0..512
- vgprs_used = align(arch_vgprs, 4)
               + acc_vgprs
- max(0, ceil(vgprs_used / 8) - 1)

GFX10 (wavefront size 64)
- max_vgpr 1..256

GFX10 (wavefront size 32)

Where vgprs_used is defined
as the highest VGPR number
explicitly referenced plus
one.

The
:ref:`amdgpu-assembler`
calculates this
automatically for the
selected processor from
values provided to the
`.amdhsa_kernel` directive
by the
`.amdhsa_next_free_vgpr`
nested directive (see
:ref:`amdhsa-kernel-directives-table`).

Number of scalar register
blocks used by a wavefront;
specific:

GFX6-GFX8
- sgprs_used 0..112
- max(0, ceil(sgprs_used / 8) - 1)

GFX9
- 2 * max(0, ceil(sgprs_used / 16) - 1)

Where sgprs_used is
defined as the highest
SGPR number explicitly
referenced plus one, plus
a target specific number
of additional special
SGPRs for VCC,
FLAT_SCRATCH (GFX7+) and
XNACK_MASK (GFX8+), and
any additional
target specific
limitations. It does not
include the 16 SGPRs added
if a trap handler is
enabled.

The target specific
limitations and special
SGPR layout are defined in
the hardware
documentation, which can
be found in the
:ref:`amdgpu-processors`
table.

The
by the
`.amdhsa_next_free_sgpr`
and `.amdhsa_reserve_*`
nested directives (see

CP is responsible for
filling in
``COMPUTE_PGM_RSRC1.PRIORITY``.

Wavefront starts execution
with specified rounding
mode for single (32
bit) floating point
precision floating point
operations.

Floating point rounding
mode values are defined in
:ref:`amdgpu-amdhsa-floating-point-rounding-mode-enumeration-values-table`.

denorm mode for half/double (16
and 64-bit) floating point

with specified denorm mode
for single (32
bit)  floating point

Floating point denorm mode
values are defined in
:ref:`amdgpu-amdhsa-floating-point-denorm-mode-enumeration-values-table`.

for half/double (16

with DX10 clamp mode
enabled. Used by the vector
ALU to force DX10 style
treatment of NaN's (when
set, clamp NaN to zero,
otherwise pass NaN
through).

treatment of NaN’s (when
through).

filling in
``COMPUTE_PGM_RSRC1.DEBUG_MODE``.

with IEEE mode
enabled. Floating point
opcodes that support
exception flag gathering
will quiet and propagate
signaling-NaN inputs per
IEEE 754-2008. Min_dx10 and
max_dx10 become IEEE
754-2008 compliant due to
signaling-NaN propagation
and quieting.

filling in
``COMPUTE_PGM_RSRC1.CDBG_USER``.

GFX9-GFX10
with specified fp16 overflow
mode.

- If 0, fp16 overflow generates
  +/-INF values.
- If 1, fp16 overflow that is the
  result of an +/-INF input value
  or divide by 0 produces a +/-INF,
  otherwise clamps computed
  overflow to +/-MAX_FP16 as
  appropriate.

Used by CP to set up
``COMPUTE_PGM_RSRC1.FP16_OVFL``.

If 1, fp16 overflow that is the
result of an +/-INF input value
or divide by 0 produces a +/-INF,
otherwise clamps computed
overflow to +/-MAX_FP16 as
appropriate.

GFX10
- If 0 execute work-groups in
  CU wavefront execution mode.
- If 1 execute work-groups on
  in WGP wavefront execution mode.

See :ref:`amdgpu-amdhsa-memory-model`.

``COMPUTE_PGM_RSRC1.WGP_MODE``.

GFX10
Controls the behavior of the
s_waitcnt's vmcnt and vscnt
counters.

- If 0 vmcnt reports completion
  of load and atomic with return
  out of order with sample
  instructions, and the vscnt
  reports the completion of
  store and atomic without
  return in order.
- If 1 vmcnt reports completion
  of load, atomic with return
  and sample instructions in
  order, and the vscnt reports
  the completion of store and
  atomic without return in order.

``COMPUTE_PGM_RSRC1.MEM_ORDERED``.

counters.

s_waitcnt’s vmcnt and vscnt
counters.

If 0 vmcnt reports completion
of load and atomic with return
out of order with sample
instructions, and the vscnt
reports the completion of
store and atomic without
return in order.

If 1 vmcnt reports completion
of load, atomic with return
and sample instructions in
order, and the vscnt reports
the completion of store and
atomic without return in order.

GFX10
- If 0 execute SIMD wavefronts
  using oldest first policy.
- If 1 execute SIMD wavefronts to
  ensure wavefronts will make some
  forward progress.

``COMPUTE_PGM_RSRC1.FWD_PROGRESS``.

If 1 execute SIMD wavefronts to
ensure wavefronts will make some
forward progress.

column of
does not specify
*Architected flat
scratch* then enable the
setup of the SGPR
wavefront scratch offset
system register (see

 then enable the

column of
specifies *Architected
flat scratch* then enable
the setup of the
FLAT_SCRATCH register
pair (see

column of
pair (see

requested. This number must
match the number of user
data registers enabled.

This bit represents
``COMPUTE_PGM_RSRC2.TRAP_PRESENT``,
which is set by the CP if
the runtime has installed a
trap handler.

,

system SGPR register for
the work-group id in the X
dimension (see

the work-group id in the Y

the work-group id in the Z

work-group information (see

VGPR system registers used
for the work-item ID.
:ref:`amdgpu-amdhsa-system-vgpr-work-item-id-enumeration-values-table`
defines the values.

with address watch
exceptions enabled which
are generated when L1 has
witnessed a thread access
an *address of
interest*.

an 

filling in the address
watch bit in
``COMPUTE_PGM_RSRC2.EXCP_EN_MSB``
according to what the
runtime requests.

with memory violation
exceptions exceptions
enabled which are generated
when a memory violation has
occurred for this wavefront from
L1 or LDS
(write-to-read-only-memory,
mis-aligned atomic, LDS
address out of range,
illegal address, etc.).

CP sets the memory
violation bit in

CP uses the rounded value
from the dispatch packet,
not this value, as the
dispatch may contain
dynamically allocated group
segment memory. CP writes
directly to
``COMPUTE_PGM_RSRC2.LDS_SIZE``.

Amount of group segment
(LDS) to allocate for each
work-group. Granularity is
device specific:

``COMPUTE_PGM_RSRC2.EXCP_EN``
(set from bits 0..6).

Offset of a first AccVGPR in the unified register file. Granularity 4.
Value 0-63. 0 - accum-offset = 4, 1 - accum-offset = 8, ...,
63 - accum-offset = 256.

Value 0-63. 0 - accum-offset = 4, 1 - accum-offset = 8, …,

If 1 the waves of a work-group can be
launched in different CUs. The waves
cannot use S_BARRIER or LDS.

Number of shared VGPRs for wavefront size 64. Granularity 8. Value 0-120.
compute_pgm_rsrc1.vgprs + shared_vgpr_cnt cannot exceed 64.

This section defines the register state that will be set up by the packet
processor prior to the start of execution of every wavefront. This is limited by
the constraints of the hardware controllers of CP/ADC/SPI.

The order of the SGPR registers is defined, but the compiler can specify which
ones are actually setup in the kernel descriptor using the ``enable_sgpr_*`` bit
fields (see :ref:`amdgpu-amdhsa-kernel-descriptor`). The register numbers used
for enabled registers are dense starting at SGPR0: the first enabled register is
SGPR0, the next enabled register is SGPR1 etc.; disabled registers do not have
an SGPR number.

ones are actually setup in the kernel descriptor using the 

). The register numbers used

The initial SGPRs comprise up to 16 User SRGPs that are set by CP and apply to
all wavefronts of the grid. It is possible to specify more than 16 User SGPRs
using the ``enable_sgpr_*`` bit fields, in which case only the first 16 are
actually initialized. These are then immediately followed by the System SGPRs
that are set up by ADC/SPI and can have different values for each wavefront of
the grid dispatch.

using the 

 bit fields, in which case only the first 16 are

SGPR register initial state is defined in
:ref:`amdgpu-amdhsa-sgpr-register-set-up-order-table`.

64-bit address of AQL dispatch
packet for kernel dispatch
actually executing.

64-bit address of amd_queue_t
object for AQL queue on which
the dispatch packet was
queued.

64-bit address of Kernarg
segment. This is directly
copied from the
kernarg_address in the kernel
dispatch packet.

Having CP load it once avoids
loading it at the beginning of
every wavefront.

The 32-bit byte size of a
single work-item's memory
allocation. This is the
value from the kernel
dispatch packet Private
Segment Byte Size rounded up
by CP to a multiple of
DWORD.

single work-item’s memory
DWORD.

This is not used for
GFX7-GFX8 since it is the same
value as the second SGPR of
Flat Scratch Init. However, it
may be needed for GFX9-GFX10 which
changes the meaning of the
Flat Scratch Init value.

{first_wavefront, 14'b0000,
ordered_append_term[10:0],
threadgroup_size_in_wavefronts[5:0]}

{first_wavefront, 14’b0000,

Scratch Wavefront Offset
(enable_sgpr_private
_segment_wavefront_offset)

See
:ref:`amdgpu-amdhsa-kernel-prolog-flat-scratch`.
and
:ref:`amdgpu-amdhsa-kernel-prolog-private-segment-buffer`.

The order of the VGPR registers is defined, but the compiler can specify which
ones are actually setup in the kernel descriptor using the ``enable_vgpr*`` bit
for enabled registers are dense starting at VGPR0: the first enabled register is
VGPR0, the next enabled register is VGPR1 etc.; disabled registers do not have a
VGPR number.

Unless the *Target Properties* column of :ref:`amdgpu-processor-table`
specifies otherwise, a separate VGPR register is used per work-item ID. The
VGPR register initial state for this method is defined in
:ref:`amdgpu-amdhsa-vgpr-register-set-up-order-for-unpacked-work-item-id-method-table`.

If *Target Properties* column of :ref:`amdgpu-processor-table`
specifies *Packed work-item IDs*, the initial value of VGPR0 register is used
for all work-item IDs. The register layout for this method is defined in
:ref:`amdgpu-amdhsa-register-layout-for-packed-work-item-id-method-table`.

.. table:: VGPR Register Set Up Order for Unpacked Work-Item ID Method
   :name: amdgpu-amdhsa-vgpr-register-set-up-order-for-unpacked-work-item-id-method-table

   ========== ========================== ====== ==============================
   VGPR Order Name                       Number Description
              (kernel descriptor enable  of
              field)                     VGPRs
   First      Work-Item Id X             1      32-bit work-item id in X
              (Always initialized)              dimension of work-group for
                                                wavefront lane.
   then       Work-Item Id Y             1      32-bit work-item id in Y
              (enable_vgpr_workitem_id          dimension of work-group for
              > 0)                              wavefront lane.
   then       Work-Item Id Z             1      32-bit work-item id in Z
              > 1)                              wavefront lane.

, the initial value of VGPR0 register is used

32-bit work-item id in X
dimension of work-group for
wavefront lane.

32-bit work-item id in Y

32-bit work-item id in Z

The setting of registers is done by GPU CP/ADC/SPI hardware as follows:

SGPRs before the Work-Group Ids are set by CP using the 16 User Data
registers.

Work-group Id registers X, Y, Z are set by ADC which supports any
combination including none.

Scratch Wavefront Offset is set by SPI in a per wavefront basis which is why
its value cannot be included with the flat scratch init value which is per
queue (see :ref:`amdgpu-amdhsa-kernel-prolog-flat-scratch`).

queue (see 

The VGPRs are set by SPI which only supports specifying either (X), (X, Y)
or (X, Y, Z).

Flat Scratch register pair initialization is described in

The global segment can be accessed either using buffer instructions (GFX6 which
has V# 64-bit address support), flat instructions (GFX7-GFX10), or global
instructions (GFX9-GFX10).

If buffer operations are used, then the compiler can generate a V# with the
following properties:

MTYPE set to support memory coherence that matches the runtime (such as CC for
APU and NC for dGPU).

The compiler performs initialization in the kernel prologue depending on the
target and information about things like stack usage in the kernel and called
functions. Some of this initialization requires the compiler to request certain
User and System SGPRs be present in the
:ref:`amdgpu-amdhsa-initial-kernel-execution-state` via the
:ref:`amdgpu-amdhsa-kernel-descriptor`.

The CFI CFA is defined using an expression which evaluates to a location
description that comprises one memory location description for the
``DW_ASPACE_AMDGPU_private_lane`` address space address ``0``.

GFX6-GFX8
The M0 register must be initialized with a value at least the total LDS size
if the kernel may access LDS via DS or flat operations. Total LDS size is
available in dispatch packet. For M0, it is also possible to use maximum
possible value of LDS for given target (0x7FFF for GFX6 and 0xFFFF for
GFX7-GFX8).

The M0 register is not used for range checking LDS accesses and so does not
need to be initialized in the prolog.

If the kernel has function calls it must set up the ABI stack pointer described
in :ref:`amdgpu-amdhsa-function-call-convention-non-kernel-functions` by setting
SGPR32 to the unswizzled scratch offset of the address past the last local
allocation.

in 

 by setting

If the kernel needs a frame pointer for the reasons defined in
``SIFrameLowering`` then SGPR33 is used and is always set to ``0`` in the
kernel prolog. If a frame pointer is not required then all uses of the frame
pointer are replaced with immediate ``0`` offsets.

 in the
pointer are replaced with immediate 

If the *Target Properties* column of :ref:`amdgpu-processor-table`
specifies *Does not support generic address space*:

Flat scratch is not supported and there is no flat scratch register pair.

specifies *Offset flat scratch*:

If the kernel or any function it calls may use flat operations to access
scratch memory, the prolog code must set up the FLAT_SCRATCH register pair
(FLAT_SCRATCH_LO/FLAT_SCRATCH_HI). Initialization uses Flat Scratch Init and
Scratch Wavefront Offset SGPR registers (see
:ref:`amdgpu-amdhsa-initial-kernel-execution-state`):

1. The low word of Flat Scratch Init is the 32-bit byte offset from
   ``SH_HIDDEN_PRIVATE_BASE_VIMID`` to the base of scratch backing memory
   being managed by SPI for the queue executing the kernel dispatch. This is
   the same value used in the Scratch Segment Buffer V# base address.

   CP obtains this from the runtime. (The Scratch Segment Buffer base address
   is ``SH_HIDDEN_PRIVATE_BASE_VIMID`` plus this offset.)

   The prolog must add the value of Scratch Wavefront Offset to get the
   wavefront's byte scratch backing memory offset from
   ``SH_HIDDEN_PRIVATE_BASE_VIMID``.

   The Scratch Wavefront Offset must also be used as an offset with Private
   segment address when using the Scratch Segment Buffer.

   Since FLAT_SCRATCH_LO is in units of 256 bytes, the offset must be right
   shifted by 8 before moving into FLAT_SCRATCH_HI.

   FLAT_SCRATCH_HI corresponds to SGPRn-4 on GFX7, and SGPRn-6 on GFX8 (where
   SGPRn is the highest numbered SGPR allocated to the wavefront).
   FLAT_SCRATCH_HI is multiplied by 256 (as it is in units of 256 bytes) and
   added to ``SH_HIDDEN_PRIVATE_BASE_VIMID`` to calculate the per wavefront
   FLAT SCRATCH BASE in flat memory instructions that access the scratch
   aperture.
2. The second word of Flat Scratch Init is 32-bit byte size of a single
   work-items scratch memory usage.

   CP obtains this from the runtime, and it is always a multiple of DWORD. CP
   checks that the value in the kernel dispatch packet Private Segment Byte
   Size is not larger and requests the runtime to increase the queue's scratch
   size if necessary.

   CP directly loads from the kernel dispatch packet Private Segment Byte Size
   field and rounds up to a multiple of DWORD. Having CP load it once avoids
   loading it at the beginning of every wavefront.

   The kernel prolog code must move it to FLAT_SCRATCH_LO which is SGPRn-3 on
   GFX7 and SGPRn-5 on GFX8. FLAT_SCRATCH_LO is used as the FLAT SCRATCH SIZE
   in flat memory instructions.

The low word of Flat Scratch Init is the 32-bit byte offset from
``SH_HIDDEN_PRIVATE_BASE_VIMID`` to the base of scratch backing memory
being managed by SPI for the queue executing the kernel dispatch. This is
the same value used in the Scratch Segment Buffer V# base address.

CP obtains this from the runtime. (The Scratch Segment Buffer base address
is ``SH_HIDDEN_PRIVATE_BASE_VIMID`` plus this offset.)

The prolog must add the value of Scratch Wavefront Offset to get the
wavefront's byte scratch backing memory offset from
``SH_HIDDEN_PRIVATE_BASE_VIMID``.

The Scratch Wavefront Offset must also be used as an offset with Private
segment address when using the Scratch Segment Buffer.

Since FLAT_SCRATCH_LO is in units of 256 bytes, the offset must be right
shifted by 8 before moving into FLAT_SCRATCH_HI.

FLAT_SCRATCH_HI corresponds to SGPRn-4 on GFX7, and SGPRn-6 on GFX8 (where
SGPRn is the highest numbered SGPR allocated to the wavefront).
FLAT_SCRATCH_HI is multiplied by 256 (as it is in units of 256 bytes) and
added to ``SH_HIDDEN_PRIVATE_BASE_VIMID`` to calculate the per wavefront
FLAT SCRATCH BASE in flat memory instructions that access the scratch
aperture.

 to the base of scratch backing memory

is 

wavefront’s byte scratch backing memory offset from

aperture.

added to 

 to calculate the per wavefront
aperture.

The second word of Flat Scratch Init is 32-bit byte size of a single
work-items scratch memory usage.

CP obtains this from the runtime, and it is always a multiple of DWORD. CP
checks that the value in the kernel dispatch packet Private Segment Byte
Size is not larger and requests the runtime to increase the queue's scratch
size if necessary.

CP directly loads from the kernel dispatch packet Private Segment Byte Size
field and rounds up to a multiple of DWORD. Having CP load it once avoids
loading it at the beginning of every wavefront.

The kernel prolog code must move it to FLAT_SCRATCH_LO which is SGPRn-3 on
GFX7 and SGPRn-5 on GFX8. FLAT_SCRATCH_LO is used as the FLAT SCRATCH SIZE
in flat memory instructions.

Size is not larger and requests the runtime to increase the queue’s scratch

specifies *Absolute flat scratch*:

(FLAT_SCRATCH_LO/FLAT_SCRATCH_HI which are in SGPRn-4/SGPRn-3). Initialization
uses Flat Scratch Init and Scratch Wavefront Offset SGPR registers (see

The Flat Scratch Init is the 64-bit address of the base of scratch backing
memory being managed by SPI for the queue executing the kernel dispatch.

CP obtains this from the runtime.

The kernel prolog must add the value of the wave's Scratch Wavefront Offset
and move the result as a 64-bit value to the FLAT_SCRATCH SGPR register pair
which is SGPRn-6 and SGPRn-5. It is used as the FLAT SCRATCH BASE in flat
memory instructions.

segment address when using the Scratch Segment Buffer (see
:ref:`amdgpu-amdhsa-kernel-prolog-private-segment-buffer`).

The kernel prolog must add the value of the wave’s Scratch Wavefront Offset

specifies *Architected flat scratch*:

If ENABLE_PRIVATE_SEGMENT is enabled in
:ref:`amdgpu-amdhsa-compute_pgm_rsrc2-gfx6-gfx10-table` then the FLAT_SCRATCH
register pair will be initialized to the 64-bit address of the base of scratch
backing memory being managed by SPI for the queue executing the kernel
dispatch plus the value of the wave's Scratch Wavefront Offset for use as the
flat scratch base in flat memory instructions.

 then the FLAT_SCRATCH
dispatch plus the value of the wave’s Scratch Wavefront Offset for use as the

If the *Target Properties* column of :ref:`amdgpu-processor-table` specifies
*Architected flat scratch* then a Private Segment Buffer is not supported.
Instead the flat SCRATCH instructions are used.

 then a Private Segment Buffer is not supported.

Otherwise, Private Segment Buffer SGPR register is used to initialize 4 SGPRs
that are used as a V# to access scratch. CP uses the value provided by the
runtime. It is used, together with Scratch Wavefront Offset as an offset, to
access the private memory space using a segment address. See

The scratch V# is a four-aligned SGPR and always selected for the kernel as
follows:

If it is known during instruction selection that there is stack usage,
SGPR0-3 is reserved for use as the scratch V#.  Stack usage is assumed if
optimizations are disabled (``-O0``), if stack objects already exist (for
locals, etc.), or if there are any function calls.

optimizations are disabled (

), if stack objects already exist (for

Otherwise, four high numbered SGPRs beginning at a four-aligned SGPR index
are reserved for the tentative scratch V#. These will be used if it is
determined that spilling is needed.

- If no use is made of the tentative scratch V#, then it is unreserved,
  and the register count is determined ignoring it.
- If use is made of the tentative scratch V#, then its register numbers
  are shifted to the first four-aligned SGPR index after the highest one
  allocated by the register allocator, and all uses are updated. The
  register count includes them in the shifted location.
- In either case, if the processor has the SGPR allocation bug, the
  tentative allocation is not shifted or unreserved in order to ensure
  the register count is higher to workaround the bug.

.. note::

  This approach of using a tentative scratch V# and shifting the register
  numbers if used avoids having to perform register allocation a second
  time if the tentative V# is eliminated. This is more efficient and
  avoids the problem that the second register allocation may perform
  spilling which will fail as there is no longer a scratch V#.

If no use is made of the tentative scratch V#, then it is unreserved,
and the register count is determined ignoring it.

If use is made of the tentative scratch V#, then its register numbers
are shifted to the first four-aligned SGPR index after the highest one
allocated by the register allocator, and all uses are updated. The
register count includes them in the shifted location.

In either case, if the processor has the SGPR allocation bug, the
tentative allocation is not shifted or unreserved in order to ensure
the register count is higher to workaround the bug.

This approach of using a tentative scratch V# and shifting the register
numbers if used avoids having to perform register allocation a second
time if the tentative V# is eliminated. This is more efficient and
avoids the problem that the second register allocation may perform
spilling which will fail as there is no longer a scratch V#.

When the kernel prolog code is being emitted it is known whether the scratch V#
described above is actually used. If it is, the prolog code must set it up by
copying the Private Segment Buffer to the scratch V# registers and then adding
the Private Segment Wavefront Offset to the queue base address in the V#. The
result is a V# with a base address pointing to the beginning of the wavefront
scratch backing memory.

The Private Segment Buffer is always requested, but the Private Segment
Wavefront Offset is only requested if it is used (see

This section describes the mapping of the LLVM memory model onto AMDGPU machine
code (see :ref:`memmodel`).

code (see 

The AMDGPU backend supports the memory synchronization scopes specified in
:ref:`amdgpu-memory-scopes`.

The code sequences used to implement the memory model specify the order of
instructions that a single thread must execute. The ``s_waitcnt`` and cache
management instructions such as ``buffer_wbinvl1_vol`` are defined with respect
to other memory instructions executed by the same thread. This allows them to be
moved earlier or later which can allow them to be combined with other instances
of the same instruction, or hoisted/sunk out of loops to improve performance.
Only the instructions related to the memory model are given; additional
``s_waitcnt`` instructions are required to ensure registers are defined before
being used. These may be able to be combined with the memory model ``s_waitcnt``
instructions as described above.

instructions that a single thread must execute. The 

 are defined with respect

 instructions are required to ensure registers are defined before
being used. These may be able to be combined with the memory model 

HSA Memory Model [HSA]_
The HSA memory model uses a single happens-before relation for all address
spaces (see :ref:`amdgpu-address-spaces`).

spaces (see 

OpenCL Memory Model [OpenCL]_
The OpenCL memory model which has separate happens-before relations for the
global and local address spaces. Only a fence specifying both global and
local address space, and seq_cst instructions join the relationships. Since
the LLVM ``memfence`` instruction does not allow an address space to be
specified the OpenCL fence has to conservatively assume both local and
global address space was specified. However, optimizations can often be
done to eliminate the additional ``s_waitcnt`` instructions when there are
no intervening memory instructions which access the corresponding address
space. The code sequences in the table indicate what can be omitted for the
OpenCL memory. The target triple environment is used to determine if the
source language is OpenCL (see :ref:`amdgpu-opencl`).

the LLVM 

 instruction does not allow an address space to be
done to eliminate the additional 

 instructions when there are
source language is OpenCL (see 

``ds/flat_load/store/atomic`` instructions to local memory are termed LDS

``buffer/global/flat_load/store/atomic`` instructions to global memory are
termed vector memory operations.

 instructions to global memory are

Private address space uses ``buffer_load/store`` using the scratch V#
(GFX6-GFX8), or ``scratch_load/store`` (GFX9-GFX10). Since only a single thread
is accessing the memory, atomic memory orderings are not meaningful, and all
accesses are treated as non-atomic.

 (GFX9-GFX10). Since only a single thread

Constant address space uses ``buffer/global_load`` instructions (or equivalent
scalar memory instructions). Since the constant address space contents do not
change during the execution of a kernel dispatch it is not legal to perform
stores, and atomic memory orderings are not meaningful, and all accesses are
treated as non-atomic.

 instructions (or equivalent

A memory synchronization scope wider than work-group is not meaningful for the
group (LDS) address space and is treated as work-group.

The memory model does not support the region address space which is treated as
non-atomic.

Acquire memory ordering is not meaningful on store atomic instructions and is

Release memory ordering is not meaningful on load atomic instructions and is
treated a non-atomic.

Acquire-release memory ordering is not meaningful on load or store atomic
instructions and is treated as acquire and release respectively.

The memory order also adds the single thread optimization constraints defined in
table
:ref:`amdgpu-amdhsa-memory-model-single-thread-optimization-constraints-table`.

table

If a load atomic/atomicrmw then no following load/load
atomic/store/store atomic/atomicrmw/fence instruction can be
moved before the acquire.

If a fence then same as load atomic, plus no preceding
associated fence-paired-atomic can be moved after the fence.

If a store atomic/atomicrmw then no preceding load/load
moved after the release.

If a fence then same as store atomic, plus no following
associated fence-paired-atomic can be moved before the
fence.

If a load atomic then same constraints as acquire, plus no
preceding sequentially consistent load atomic/store
atomic/atomicrmw/fence instruction can be moved after the
seq_cst.

If a store atomic then the same constraints as release, plus
no following sequentially consistent load atomic/store
atomic/atomicrmw/fence instruction can be moved before the
seq_cst.

The code sequences used to implement the memory model are defined in the
following sections:

The wavefronts for a single work-group are executed in the same CU but may be
executed by different SIMDs.

Each CU has a single LDS memory shared by the wavefronts of the work-groups
executing on it.

All LDS operations of a CU are performed as wavefront wide operations in a
global order and involve no caching. Completion is reported to a wavefront in
execution order.

The LDS memory has multiple request queues shared by the SIMDs of a
CU. Therefore, the LDS operations performed by different wavefronts of a
work-group can be reordered relative to each other, which can result in
reordering the visibility of vector memory operations with respect to LDS
operations of other wavefronts in the same work-group. A ``s_waitcnt
lgkmcnt(0)`` is required to ensure synchronization between LDS operations and
vector memory operations between wavefronts of a work-group, but not between
operations performed by the same wavefront.

operations of other wavefronts in the same work-group. A 

 is required to ensure synchronization between LDS operations and

The vector memory operations are performed as wavefront wide operations and
completion is reported to a wavefront in execution order. The exception is
that for GFX7-GFX9 ``flat_load/store/atomic`` instructions can report out of
vector memory order if they access LDS memory, and out of LDS operation order
if they access global memory.

that for GFX7-GFX9 

 instructions can report out of

The vector memory operations access a single vector L1 cache shared by all
SIMDs a CU. Therefore, no special action is required for coherence between the
lanes of a single wavefront, or for coherence between wavefronts in the same
work-group. A ``buffer_wbinvl1_vol`` is required for coherence between
wavefronts executing in different work-groups as they may be executing on
different CUs.

work-group. A 

 is required for coherence between

The scalar memory operations access a scalar L1 cache shared by all wavefronts
on a group of CUs. The scalar and vector L1 caches are not coherent. However,
scalar operations are used in a restricted way so do not impact the memory
model. See :ref:`amdgpu-amdhsa-memory-spaces`.

model. See 

The vector and scalar memory operations use an L2 cache shared by all CUs on
the same agent.

The L2 cache has independent channels to service disjoint ranges of virtual
addresses.

Each CU has a separate request queue per channel. Therefore, the vector and
scalar memory operations performed by wavefronts executing in different
work-groups (which may be executing on different CUs) of an agent can be
reordered relative to each other. A ``s_waitcnt vmcnt(0)`` is required to
ensure synchronization between vector memory operations of different CUs. It
ensures a previous vector memory operation has completed before executing a
subsequent vector memory or LDS operation and so can be used to meet the
requirements of acquire and release.

reordered relative to each other. A 

 is required to

The L2 cache can be kept coherent with other agents on some targets, or ranges
of virtual addresses can be set up to bypass it to ensure system coherence.

Scalar memory operations are only used to access memory that is proven to not
change during the execution of the kernel dispatch. This includes constant
address space and global address space for program scope ``const`` variables.
Therefore, the kernel machine code does not have to maintain the scalar cache to
ensure it is coherent with the vector caches. The scalar and vector caches are
invalidated between kernel dispatches by CP since constant address space data
may change between kernel dispatch executions. See
:ref:`amdgpu-amdhsa-memory-spaces`.

address space and global address space for program scope 

 variables.

The one exception is if scalar writes are used to spill SGPR registers. In this
case the AMDGPU backend ensures the memory location used to spill is never
accessed by vector memory operations at the same time. If scalar writes are used
then a ``s_dcache_wb`` is inserted before the ``s_endpgm`` and before a function
return since the locations may be used for vector memory instructions by a
future wavefront that uses the same scratch area, or a function call that
creates a frame at the same address, respectively. There is no need for a
``s_dcache_inv`` as all scalar writes are write-before-read in the same thread.

then a 

 and before a function

CP invalidates the L1 cache at the start of each kernel dispatch.

On dGPU the kernarg backing memory is allocated in host memory accessed as
MTYPE UC (uncached) to avoid needing to invalidate the L2 cache. This also
causes it to be treated as non-volatile and so is not invalidated by
``*_vol``.

On APU the kernarg backing memory it is accessed as MTYPE CC (cache coherent)
and so the L2 cache will be coherent with the CPU and other agents.

Scratch backing memory (which is used for the private address space) is accessed
with MTYPE NC_NV (non-coherent non-volatile). Since the private address space is
only accessed by a single thread, and is always write-before-read, there is
never a need to invalidate these entries from the L1 cache. Hence all cache
invalidates are done as ``*_vol`` to only invalidate the volatile cache lines.

invalidates are done as 

The code sequences used to implement the memory model for GFX6-GFX9 are defined
in table :ref:`amdgpu-amdhsa-memory-model-code-sequences-gfx6-gfx9-table`.

in table 

!volatile & nontemporal

1. buffer/global/flat_load
   glc=1 slc=1

volatile

   glc=1
2. s_waitcnt vmcnt(0)

 - Must happen before
   any following volatile
   global/generic
   load/store.
 - Ensures that
   volatile
   operations to
   different
   addresses will not
   be reordered by
   hardware.

Must happen before
any following volatile
global/generic
load/store.

Ensures that
volatile
operations to
different
addresses will not
be reordered by
hardware.

volatile
different
hardware.

1. buffer/global/flat_store

volatile

   volatile
   different
   hardware.

any following
load/load
atomic/store/store
atomic/atomicrmw.

Ensures any
following global
data read is no
older than a local load
atomic value being
acquired.

acquired.

load/load

Ensures the flat_load
has completed
before invalidating
the cache.

the cache.

older than a local
atomicrmw value
being acquired.

Ensures the
atomicrmw has
completed before
invalidating the
cache.

cache.

However, since LLVM
currently has no
address space on
the fence need to
conservatively
always generate. If
fence had an
address space then
set to address
space of OpenCL
fence flag, or to
generic if both
local and global
flags are
specified.

Must happen after
any preceding
local/generic load
atomic/atomicrmw
with an equal or
wider sync scope
and memory ordering
stronger than
unordered (this is
termed the
fence-paired-atomic).

older than the
value read by the
fence-paired-atomic.

system

always generate
(see comment for
previous fence).

Could be split into
separate s_waitcnt
vmcnt(0) and
s_waitcnt
lgkmcnt(0) to allow
them to be
independently moved
according to the
following rules.

s_waitcnt vmcnt(0)
must happen after
global/generic load
termed the

s_waitcnt lgkmcnt(0)
termed the

Ensures that the
fence-paired atomic
the
cache. Therefore
locations read must
be no older than
the value read by
the

the
the

Must happen before any
following global/generic
load/load

local/generic
load/store/load
atomic/store

Ensures that all
memory operations
to local have
performing the
store that is being
released.

released.

to memory have
released.

released.

atomicrmw that is
being released.

to global and local
have completed
before performing
the atomicrmw that
is being released.

load/load

any following store
termed the

following

following

system

have
following

have
following

older than the local load
acquired.

acquired.

system

global

to global have

system

generic

workgroup

However,
since LLVM

performing any
memory operations.

preceding
termed the
acquire-fence-paired-atomic)
before following
global memory
operations. This
satisfies the
requirements of
acquire.

previous memory
operations have
completed before a
following
local/generic store
termed the
release-fence-paired-atomic).
This satisfies the
release.

following
termed the
release.

system

preceding
global/local/generic
load
termed the
the cache. This
acquire.

following
store
termed the
release.

following
store
termed the
release.

following loads
will not see stale
global data. This
acquire.

acquire.

*Same as corresponding
load atomic acquire,
except must generated
all instructions even
for OpenCL.*

Same as corresponding
for OpenCL.

workgroup

generic

Must
happen after
preceding
with memory
ordering of seq_cst
and with equal or
wider sync scope.
(Note that seq_cst
fences have their
own s_waitcnt
lgkmcnt(0) and so do
not need to be
considered.)

preceding
sequential
consistent local
memory instructions
before executing
this sequentially
consistent
instruction. This
prevents reordering
a seq_cst store
followed by a
seq_cst load. (Note
that seq_cst is
acquire/release as
the reordering of
load acquire
followed by a store
release is
prevented by the
s_waitcnt of
the release, but
there is nothing
preventing a store
release followed by
load acquire from
completing out of
order. The s_waitcnt
could be placed after
seq_store or before
the seq_load. We
choose the load to
make the s_waitcnt be
as late as possible
so that the store
may have already
completed.)

preceding
release is

*Following
instructions same as
corresponding load
atomic acquire,

Following

system

generic

vmcnt(0)
and s_waitcnt
them to be

preceding

preceding
vmcnt(0) and so do

preceding
consistent global
release is

preceding
release is

store atomic release,

atomicrmw acq_rel,

fence acq_rel,

executed by different SIMDs. The exception is when in tgsplit execution mode
when the wavefronts may be executed by different SIMDs in different CUs.

executing on it. The exception is when in tgsplit execution mode when no LDS
is allocated as wavefronts of the same work-group can be in different CUs.

that ``flat_load/store/atomic`` instructions can report out of vector memory
order if they access LDS memory, and out of LDS operation order if they access
global memory.

that 

 instructions can report out of vector memory

SIMDs a CU. Therefore:

* No special action is required for coherence between the lanes of a single
  wavefront.

* No special action is required for coherence between wavefronts in the same
  work-group since they execute on the same CU. The exception is when in
  tgsplit execution mode as wavefronts of the same work-group can be in
  different CUs and so a ``buffer_wbinvl1_vol`` is required as described in
  the following item.

* A ``buffer_wbinvl1_vol`` is required for coherence between wavefronts
  executing in different work-groups as they may be executing on different
  CUs.

No special action is required for coherence between the lanes of a single
wavefront.

No special action is required for coherence between wavefronts in the same
work-group since they execute on the same CU. The exception is when in
tgsplit execution mode as wavefronts of the same work-group can be in
different CUs and so a ``buffer_wbinvl1_vol`` is required as described in
the following item.

different CUs and so a 

A ``buffer_wbinvl1_vol`` is required for coherence between wavefronts
executing in different work-groups as they may be executing on different
CUs.

CUs.

 is required for coherence between wavefronts
CUs.

* The L2 cache has independent channels to service disjoint ranges of virtual
  addresses.
* Each CU has a separate request queue per channel. Therefore, the vector and
  scalar memory operations performed by wavefronts executing in different
  work-groups (which may be executing on different CUs), or the same
  work-group if executing in tgsplit mode, of an agent can be reordered
  relative to each other. A ``s_waitcnt vmcnt(0)`` is required to ensure
  synchronization between vector memory operations of different CUs. It
  ensures a previous vector memory operation has completed before executing a
  subsequent vector memory or LDS operation and so can be used to meet the
  requirements of acquire and release.
* The L2 cache of one agent can be kept coherent with other agents by:
  using the MTYPE RW (read-write) or MTYPE CC (cache-coherent) with the PTE
  C-bit for memory local to the L2; and using the MTYPE NC (non-coherent) with
  the PTE C-bit set or MTYPE UC (uncached) for memory not local to the L2.

  * Any local memory cache lines will be automatically invalidated by writes
    from CUs associated with other L2 caches, or writes from the CPU, due to
    the cache probe caused by coherent requests. Coherent requests are caused
    by GPU accesses to pages with the PTE C-bit set, by CPU accesses over
    XGMI, and by PCIe requests that are configured to be coherent requests.
  * XGMI accesses from the CPU to local memory may be cached on the CPU.
    Subsequent access from the GPU will automatically invalidate or writeback
    the CPU cache due to the L2 probe filter and and the PTE C-bit being set.
  * Since all work-groups on the same agent share the same L2, no L2
    invalidation or writeback is required for coherence.
  * To ensure coherence of local and remote memory writes of work-groups in
    different agents a ``buffer_wbl2`` is required. It will writeback dirty L2
    cache lines of MTYPE RW (used for local coarse grain memory) and MTYPE NC
    ()used for remote coarse grain memory). Note that MTYPE CC (used for local
    fine grain memory) causes write through to DRAM, and MTYPE UC (used for
    remote fine grain memory) bypasses the L2, so both will never result in
    dirty L2 cache lines.
  * To ensure coherence of local and remote memory reads of work-groups in
    different agents a ``buffer_invl2`` is required. It will invalidate L2
    cache lines with MTYPE NC (used for remote coarse grain memory). Note that
    MTYPE CC (used for local fine grain memory) and MTYPE RW (used for local
    coarse memory) cause local reads to be invalidated by remote writes with
    with the PTE C-bit so these cache lines are not invalidated. Note that
    MTYPE UC (used for remote fine grain memory) bypasses the L2, so will
    never result in L2 cache lines that need to be invalidated.

* PCIe access from the GPU to the CPU memory is kept coherent by using the
  MTYPE UC (uncached) which bypasses the L2.

work-groups (which may be executing on different CUs), or the same
work-group if executing in tgsplit mode, of an agent can be reordered
relative to each other. A ``s_waitcnt vmcnt(0)`` is required to ensure
synchronization between vector memory operations of different CUs. It

relative to each other. A 

 is required to ensure

The L2 cache of one agent can be kept coherent with other agents by:
using the MTYPE RW (read-write) or MTYPE CC (cache-coherent) with the PTE
C-bit for memory local to the L2; and using the MTYPE NC (non-coherent) with
the PTE C-bit set or MTYPE UC (uncached) for memory not local to the L2.

* Any local memory cache lines will be automatically invalidated by writes
  from CUs associated with other L2 caches, or writes from the CPU, due to
  the cache probe caused by coherent requests. Coherent requests are caused
  by GPU accesses to pages with the PTE C-bit set, by CPU accesses over
  XGMI, and by PCIe requests that are configured to be coherent requests.
* XGMI accesses from the CPU to local memory may be cached on the CPU.
  Subsequent access from the GPU will automatically invalidate or writeback
  the CPU cache due to the L2 probe filter and and the PTE C-bit being set.
* Since all work-groups on the same agent share the same L2, no L2
  invalidation or writeback is required for coherence.
* To ensure coherence of local and remote memory writes of work-groups in
  different agents a ``buffer_wbl2`` is required. It will writeback dirty L2
  cache lines of MTYPE RW (used for local coarse grain memory) and MTYPE NC
  ()used for remote coarse grain memory). Note that MTYPE CC (used for local
  fine grain memory) causes write through to DRAM, and MTYPE UC (used for
  remote fine grain memory) bypasses the L2, so both will never result in
  dirty L2 cache lines.
* To ensure coherence of local and remote memory reads of work-groups in
  different agents a ``buffer_invl2`` is required. It will invalidate L2
  cache lines with MTYPE NC (used for remote coarse grain memory). Note that
  MTYPE CC (used for local fine grain memory) and MTYPE RW (used for local
  coarse memory) cause local reads to be invalidated by remote writes with
  with the PTE C-bit so these cache lines are not invalidated. Note that
  MTYPE UC (used for remote fine grain memory) bypasses the L2, so will
  never result in L2 cache lines that need to be invalidated.

Any local memory cache lines will be automatically invalidated by writes
from CUs associated with other L2 caches, or writes from the CPU, due to
the cache probe caused by coherent requests. Coherent requests are caused
by GPU accesses to pages with the PTE C-bit set, by CPU accesses over
XGMI, and by PCIe requests that are configured to be coherent requests.

XGMI accesses from the CPU to local memory may be cached on the CPU.
Subsequent access from the GPU will automatically invalidate or writeback
the CPU cache due to the L2 probe filter and and the PTE C-bit being set.

Since all work-groups on the same agent share the same L2, no L2
invalidation or writeback is required for coherence.

To ensure coherence of local and remote memory writes of work-groups in
different agents a ``buffer_wbl2`` is required. It will writeback dirty L2
cache lines of MTYPE RW (used for local coarse grain memory) and MTYPE NC
()used for remote coarse grain memory). Note that MTYPE CC (used for local
fine grain memory) causes write through to DRAM, and MTYPE UC (used for
remote fine grain memory) bypasses the L2, so both will never result in
dirty L2 cache lines.

different agents a 

 is required. It will writeback dirty L2

To ensure coherence of local and remote memory reads of work-groups in
different agents a ``buffer_invl2`` is required. It will invalidate L2
cache lines with MTYPE NC (used for remote coarse grain memory). Note that
MTYPE CC (used for local fine grain memory) and MTYPE RW (used for local
coarse memory) cause local reads to be invalidated by remote writes with
with the PTE C-bit so these cache lines are not invalidated. Note that
MTYPE UC (used for remote fine grain memory) bypasses the L2, so will
never result in L2 cache lines that need to be invalidated.

 is required. It will invalidate L2

PCIe access from the GPU to the CPU memory is kept coherent by using the
MTYPE UC (uncached) which bypasses the L2.

On dGPU over XGMI or PCIe the kernarg backing memory is allocated in host
memory accessed as MTYPE UC (uncached) to avoid needing to invalidate the L2
cache. This also causes it to be treated as non-volatile and so is not
invalidated by ``*_vol``.

invalidated by 

On APU the kernarg backing memory is accessed as MTYPE CC (cache coherent) and
so the L2 cache will be coherent with the CPU and other agents.

The code sequences used to implement the memory model for GFX90A are defined
in table :ref:`amdgpu-amdhsa-memory-model-code-sequences-gfx90a-table`.

in table 

*If TgSplit execution mode,
local address space cannot
be used.*

Use lgkmcnt(0) if not
TgSplit execution mode
and vmcnt(0) if TgSplit
execution mode.

the following
buffer_wbinvl1_vol and any
load/load

following buffer_invl2 and
buffer_wbinvl1_vol.

following
loads will not see
stale L1 global data,
nor see stale L2 MTYPE
NC global data.
MTYPE RW and CC memory will
never be stale in L2 due to
the memory probes.

following

following
buffer_invl2 and

the caches.

Ensures the atomicrmw
the cache.

the cache.

older than the local

buffer_wbinvl1_vol and
load/load

caches.

caches.

workgroup

atomic/
atomicrmw
termed the

agent

system

the following buffer_invl2 and

global/generic load/store/
load atomic/store atomic/
atomicrmw.

have
released.

have
released.

Performs L2 writeback to
ensure previous
store/atomicrmw are
visible at system scope.

must happen after any
preceding

preceding

to memory and the L2
writeback have
released.

released.

have

have

workgroup

load/store/

load/load

agent

system

workgroup

global

workgroup

generic

agent

global

system

global

to global and L2 writeback
have completed before

agent

generic

system

generic

workgroup

have

acquire-fence-paired
atomic has completed
the
the
acquire-fence-paired-atomic.

the
the

agent

system

workgroup

generic

s_waitcnt lgkmcnt(0) must
preceding

preceding
consistent global/local
release is

preceding
release is

system

generic

The wavefronts for a single work-group are executed in the same
WGP. In CU wavefront execution mode the wavefronts may be executed by
different SIMDs in the same CU. In WGP wavefront execution mode the
wavefronts may be executed by different SIMDs in different CUs in the same
WGP.

Each WGP has a single LDS memory shared by the wavefronts of the work-groups

All LDS operations of a WGP are performed as wavefront wide operations in a

WGP. Therefore, the LDS operations performed by different wavefronts of a

The vector memory operations are performed as wavefront wide operations.
Completion of load/store/sample operations are reported to a wavefront in
execution order of other load/store/sample operations performed by that

The vector memory operations access a vector L0 cache. There is a single L0
cache per CU. Each SIMD of a CU accesses the same L0 cache. Therefore, no
special action is required for coherence between the lanes of a single
wavefront. However, a ``buffer_gl0_inv`` is required for coherence between
wavefronts executing in the same work-group as they may be executing on SIMDs
of different CUs that access different L0s. A ``buffer_gl0_inv`` is also
required for coherence between wavefronts executing in different work-groups
as they may be executing on different WGPs.

wavefront. However, a 

of different CUs that access different L0s. A 

 is also

The scalar memory operations access a scalar L0 cache shared by all wavefronts
on a WGP. The scalar and vector L0 caches are not coherent. However, scalar
operations are used in a restricted way so do not impact the memory model. See

The vector and scalar memory L0 caches use an L1 cache shared by all WGPs on
the same SA. Therefore, no special action is required for coherence between
the wavefronts of a single work-group. However, a ``buffer_gl1_inv`` is
as they may be executing on different SAs that access different L1s.

the wavefronts of a single work-group. However, a 

 is

The L1 caches have independent quadrants to service disjoint ranges of virtual

Each L0 cache has a separate request queue per L1 quadrant. Therefore, the
vector and scalar memory operations performed by different wavefronts, whether
executing in the same or different work-groups (which may be executing on
different CUs accessing different L0s), can be reordered relative to each
other. A ``s_waitcnt vmcnt(0) & vscnt(0)`` is required to ensure
synchronization between vector memory operations of different wavefronts. It
requirements of acquire, release and sequential consistency.

other. A 

The L1 caches use an L2 cache shared by all SAs on the same agent.

Each L1 quadrant of a single SA accesses a different L2 channel. Each L1
quadrant has a separate request queue per L2 channel. Therefore, the vector
and scalar memory operations performed by wavefronts executing in different
work-groups (which may be executing on different SAs) of an agent can be
reordered relative to each other. A ``s_waitcnt vmcnt(0) & vscnt(0)`` is
required to ensure synchronization between vector memory operations of
different SAs. It ensures a previous vector memory operation has completed
before executing a subsequent vector memory and so can be used to meet the

 is

CP invalidates the L0 and L1 caches at the start of each kernel dispatch.

On dGPU the kernarg backing memory is accessed as MTYPE UC (uncached) to avoid
needing to invalidate the L2 cache.

with MTYPE NC (non-coherent). Since the private address space is only accessed
by a single thread, and is always write-before-read, there is never a need to
invalidate these entries from the L0 or L1 caches.

Wavefronts are executed in native mode with in-order reporting of loads and
sample instructions. In this mode vmcnt reports completion of load, atomic with
return and sample instructions in order, and the vscnt reports the completion of
store and atomic without return in order. See ``MEM_ORDERED`` field in

store and atomic without return in order. See 

Wavefronts can be executed in WGP or CU wavefront execution mode:

In WGP wavefront execution mode the wavefronts of a work-group are executed
on the SIMDs of both CUs of the WGP. Therefore, explicit management of the per
CU L0 caches is required for work-group synchronization. Also accesses to L1
at work-group scope need to be explicitly ordered as the accesses from
different CUs are not ordered.

In CU wavefront execution mode the wavefronts of a work-group are executed on
the SIMDs of a single CU of the WGP. Therefore, all global memory access by
the work-group access the same L0 which in turn ensures L1 accesses are
ordered and so do not require explicit management of the caches for
work-group synchronization.

See ``WGP_MODE`` field in
:ref:`amdgpu-amdhsa-compute_pgm_rsrc1-gfx6-gfx10-table` and

The code sequences used to implement the memory model for GFX10 are defined in
table :ref:`amdgpu-amdhsa-memory-model-code-sequences-gfx10-table`.

table 

volatile

   glc=1 dlc=1

   volatile
   different
   hardware.

 1. buffer/global/flat_store
    slc=1

volatile

 2. s_waitcnt vscnt(0)

   volatile
   different
   hardware.

the following buffer_gl0_inv
and before any following
load/load

load/load

global/generic load/load

buffer_gl0_inv and any
load/load

Use vmcnt(0) if atomic with
return and vscnt(0) if
atomic with no-return.

workgroup

If OpenCL and
address space is
local, omit
vmcnt(0) and vscnt(0).

vmcnt(0), s_waitcnt
vscnt(0) and s_waitcnt
them to be

atomic/
atomicrmw-with-return-value
termed the

s_waitcnt vscnt(0)
atomicrmw-no-return-value
termed the

the
caches. Therefore
the

the
the

atomic/
atomicrmw-with-return-value.

store/store
atomic/
atomicrmw-no-return-value.

vmcnt(0) and s_waitcnt
vscnt(0) to allow
them to be

store/store atomic/

released.

released.

vmcnt(0), s_waitcnt vscnt(0)
them to be

load/load
atomic/

load/load atomic/

workgroup

atomic/store atomic/

system

workgroup

vscnt(0), and s_waitcnt
them to be

workgroup

local

workgroup

generic

older than the load
acquired.

acquired.

global

system

generic

load/load atomic

workgroup

system

preceding
load
termed the
the caches. This
acquire.

generic

preceding
atomic/

preceding
global/generic store
atomic/
vscnt(0) and so do

workgroup

local

preceding
atomic/

system

generic

preceding
local load

For code objects generated by the AMDGPU backend for HSA [HSA]_ compatible
runtimes (see :ref:`amdgpu-os`), the runtime installs a trap handler that
supports the ``s_trap`` instruction. For usage see:

:ref:`amdgpu-trap-handler-for-amdhsa-os-v4-table`

.. table:: AMDGPU Trap Handler for AMDHSA OS Code Object V2
   :name: amdgpu-trap-handler-for-amdhsa-os-v2-table

   =================== =============== =============== =======================================
   Usage               Code Sequence   Trap Handler    Description
                                       Inputs
   reserved            ``s_trap 0x00``                 Reserved by hardware.
   ``debugtrap(arg)``  ``s_trap 0x01`` ``SGPR0-1``:    Reserved for Finalizer HSA ``debugtrap``
                                         ``queue_ptr`` intrinsic (not implemented).
                                       ``VGPR0``:
                                         ``arg``
   ``llvm.trap``       ``s_trap 0x02`` ``SGPR0-1``:    Causes wave to be halted with the PC at
                                         ``queue_ptr`` the trap instruction. The associated
                                                       queue is signalled to put it into the
                                                       error state.  When the queue is put in
                                                       the error state, the waves executing
                                                       dispatches on the queue will be
                                                       terminated.
   ``llvm.debugtrap``  ``s_trap 0x03`` *none*          - If debugger not enabled then behaves
                                                         as a no-operation. The trap handler
                                                         is entered and immediately returns to
                                                         continue execution of the wavefront.
                                                       - If the debugger is enabled, causes
                                                         the debug trap to be reported by the
                                                         debugger and the wavefront is put in
                                                         the halt state with the PC at the
                                                         instruction.  The debugger must
                                                         increment the PC and resume the wave.
   reserved            ``s_trap 0x04``                 Reserved.
   reserved            ``s_trap 0x05``                 Reserved.
   reserved            ``s_trap 0x06``                 Reserved.
   reserved            ``s_trap 0x07``                 Reserved.
   reserved            ``s_trap 0x08``                 Reserved.
   reserved            ``s_trap 0xfe``                 Reserved.
   reserved            ``s_trap 0xff``                 Reserved.

Reserved for Finalizer HSA ``debugtrap``
intrinsic (not implemented).

Causes wave to be halted with the PC at
the trap instruction. The associated
queue is signalled to put it into the
error state.  When the queue is put in
the error state, the waves executing
dispatches on the queue will be
terminated.

If debugger not enabled then behaves
as a no-operation. The trap handler
is entered and immediately returns to
continue execution of the wavefront.

If the debugger is enabled, causes
the debug trap to be reported by the
debugger and the wavefront is put in
the halt state with the PC at the
instruction.  The debugger must
increment the PC and resume the wave.

Reserved for debugger to use for
breakpoints. Causes wave to be halted
with the PC at the trap instruction.
The debugger is responsible to resume
the wave, including the instruction
that the breakpoint overwrote.

This section is currently incomplete and has inaccuracies. It is WIP that will
be updated as information is determined.

See :ref:`amdgpu-dwarf-address-space-identifier` for information on swizzled
addresses. Unswizzled addresses are normal linear addresses.

 for information on swizzled

This section describes the call convention ABI for the outer kernel function.

See :ref:`amdgpu-amdhsa-initial-kernel-execution-state` for the kernel call
convention.

The following is not part of the AMDGPU kernel calling convention but describes
how the AMDGPU implements function calls:

Clang decides the kernarg layout to match the *HSA Programmer's Language
Reference* [HSA]_.

- All structs are passed directly.
- Lambda values are passed *TBA*.

.. TODO::

  - Does this really follow HSA rules? Or are structs >16 bytes passed
    by-value struct?
  - What is ABI for lambda values?

- Does this really follow HSA rules? Or are structs >16 bytes passed
  by-value struct?
- What is ABI for lambda values?

Does this really follow HSA rules? Or are structs >16 bytes passed
by-value struct?

The kernel performs certain setup in its prolog, as described in
:ref:`amdgpu-amdhsa-kernel-prolog`.

This section describes the call convention ABI for functions other than the
outer kernel function.

If a kernel has function calls then scratch is always allocated and used for
the call stack which grows from low address to high address using the swizzled
scratch address space.

SGPR0-3 contain a V# with the following properties (see
:ref:`amdgpu-amdhsa-kernel-prolog-private-segment-buffer`):

* Base address pointing to the beginning of the wavefront scratch backing
  memory.
* Swizzled with dword element size and stride of wavefront size elements.

Base address pointing to the beginning of the wavefront scratch backing
memory.

Swizzled with dword element size and stride of wavefront size elements.

The FLAT_SCRATCH register pair is setup. See

GFX6-GFX8: M0 register set to the size of LDS in bytes. See
:ref:`amdgpu-amdhsa-kernel-prolog-m0`.

The EXEC register is set to the lanes active on entry to the function.

VGPR0-31 and SGPR4-29 are used to pass function input arguments as described
below.

SGPR30-31 return address (RA). The code address that the function must
return to when it completes. The value is undefined if the function is *no
return*.

return to when it completes. The value is undefined if the function is 

SGPR32 is used for the stack pointer (SP). It is an unswizzled scratch
offset relative to the beginning of the wavefront scratch backing memory.

The unswizzled SP can be used with buffer instructions as an unswizzled SGPR
offset with the scratch V# in SGPR0-3 to access the stack in a swizzled
manner.

The unswizzled SP value can be converted into the swizzled SP value by:

  | swizzled SP = unswizzled SP / wavefront size

This may be used to obtain the private address space address of stack
objects and to convert this address to a flat address by adding the flat
scratch aperture base address.

The swizzled SP value is always 4 bytes aligned for the ``r600``
architecture and 16 byte aligned for the ``amdgcn`` architecture.

.. note::

  The ``amdgcn`` value is selected to avoid dynamic stack alignment for the
  OpenCL language which has the largest base type defined as 16 bytes.

On entry, the swizzled SP value is the address of the first function
argument passed on the stack. Other stack passed arguments are positive
offsets from the entry swizzled SP value.

The function may use positive offsets beyond the last stack passed argument
for stack allocated local variables and register spill slots. If necessary,
the function may align these to greater alignment than 16 bytes. After these
the function may dynamically allocate space for such things as runtime sized
``alloca`` local allocations.

If the function calls another function, it will place any stack allocated
arguments after the last local allocation and adjust SGPR32 to the address
after the last local allocation.

manner.

The ``amdgcn`` value is selected to avoid dynamic stack alignment for the
OpenCL language which has the largest base type defined as 16 bytes.

 value is selected to avoid dynamic stack alignment for the

Any necessary ``s_waitcnt`` has been performed to ensure memory is available
to the function.

 has been performed to ensure memory is available

VGPR0-31 and SGPR4-29 are used to pass function result arguments as
described below. Any registers used are considered clobbered registers.

The following registers are preserved and have the same value as on entry:

* FLAT_SCRATCH
* EXEC
* GFX6-GFX8: M0
* All SGPR registers except the clobbered registers of SGPR4-31.
* VGPR40-47
* VGPR56-63
* VGPR72-79
* VGPR88-95
* VGPR104-111
* VGPR120-127
* VGPR136-143
* VGPR152-159
* VGPR168-175
* VGPR184-191
* VGPR200-207
* VGPR216-223
* VGPR232-239
* VGPR248-255

    .. note::

      Except the argument registers, the VGPRs clobbered and the preserved
      registers are intermixed at regular intervals in order to keep a
      similar ratio independent of the number of allocated VGPRs.

* GFX90A: All AGPR registers except the clobbered registers AGPR0-31.
* Lanes of all VGPRs that are inactive at the call site.

  For the AMDGPU backend, an inter-procedural register allocation (IPRA)
  optimization may mark some of clobbered SGPR and VGPR registers as
  preserved if it can be determined that the called function does not change
  their value.

VGPR248-255

  .. note::

    Except the argument registers, the VGPRs clobbered and the preserved
    registers are intermixed at regular intervals in order to keep a
    similar ratio independent of the number of allocated VGPRs.

Except the argument registers, the VGPRs clobbered and the preserved
registers are intermixed at regular intervals in order to keep a
similar ratio independent of the number of allocated VGPRs.

GFX90A: All AGPR registers except the clobbered registers AGPR0-31.

Lanes of all VGPRs that are inactive at the call site.

For the AMDGPU backend, an inter-procedural register allocation (IPRA)
optimization may mark some of clobbered SGPR and VGPR registers as
preserved if it can be determined that the called function does not change
their value.

Any necessary ``s_waitcnt`` has been performed to ensure memory accessed by
function is available to the caller.

 has been performed to ensure memory accessed by

- How are function results returned? The address of structured types is passed
  by reference, but what about other types?

How are function results returned? The address of structured types is passed
by reference, but what about other types?

The function input arguments are made up of the formal arguments explicitly
declared by the source language function plus the implicit input arguments used
by the implementation.

Any source language implicit ``this`` or ``self`` argument comes first as a
pointer type.

Followed by the function formal arguments in left to right source order.

The source language input or result struct type arguments that are less than or
equal to 16 bytes, are decomposed recursively into their base type fields, and
each field is passed as if a separate argument. For input arguments, if the
called function requires the struct to be in memory, for example because its
address is taken, then the function body is responsible for allocating a stack
location and copying the field arguments into it. Clang terms this *direct
struct*.

location and copying the field arguments into it. Clang terms this 

The source language input struct type arguments that are greater than 16 bytes,
are passed by reference. The caller is responsible for allocating a stack
location to make a copy of the struct value and pass the address as the input
argument. The called function is responsible to perform the dereference when
accessing the input argument. Clang terms this *by-value struct*.

accessing the input argument. Clang terms this 

A source language result struct type argument that is greater than 16 bytes, is
returned by reference. The caller is responsible for allocating a stack location
to hold the result value and passes the address as the last input argument
(before the implicit input arguments). In this case there are no result
arguments. The called function is responsible to perform the dereference when
storing the result value. Clang terms this *structured return (sret)*.

storing the result value. Clang terms this 

Is this definition correct? Or is ``sret`` only used if passing in registers, and
pass as non-decomposed struct as stack argument? Or something else? Is the
memory location in the caller stack frame, or a stack memory argument and so
no address is passed as the caller can directly write to the argument stack
location? But then the stack location is still live after return. If an
argument stack location is it the first stack argument or the last one?

 only used if passing in registers, and

Lambda argument types are treated as struct types with an implementation defined
set of fields.

For AMDGPU backend all source language arguments (including the decomposed
struct type arguments) are passed in VGPRs unless marked ``inreg`` in which case
they are passed in SGPRs.

struct type arguments) are passed in VGPRs unless marked 

The AMDGPU backend walks the function call graph from the leaves to determine
which implicit input arguments are used, propagating to each caller of the
function. The used implicit arguments are appended to the function arguments
after the source language arguments in the following order:

Work-Item ID (1 VGPR)

The X, Y and Z work-item ID are packed into a single VGRP with the following
layout. Only fields actually used by the function are set. The other bits
are undefined.

The values come from the initial kernel execution state. See

.. table:: Work-item implicit argument layout
  :name: amdgpu-amdhsa-workitem-implicit-argument-layout-table

  ======= ======= ==============
  Bits    Size    Field Name
  9:0     10 bits X Work-Item ID
  19:10   10 bits Y Work-Item ID
  29:20   10 bits Z Work-Item ID
  31:30   2 bits  Unused

Dispatch Ptr (2 SGPRs)

The value comes from the initial kernel execution state. See

Queue Ptr (2 SGPRs)

Kernarg Segment Ptr (2 SGPRs)

Dispatch id (2 SGPRs)

Work-Group ID X (1 SGPR)

Work-Group ID Y (1 SGPR)

Work-Group ID Z (1 SGPR)

Implicit Argument Ptr (2 SGPRs)

The value is computed by adding an offset to Kernarg Segment Ptr to get the
global address space pointer to the first kernarg implicit argument.

The input and result arguments are assigned in order in the following manner:

There are likely some errors and omissions in the following description that
need correction.

.. TODO::

  Check the Clang source code to decipher how function arguments and return
  results are handled. Also see the AMDGPU specific values used.

Check the Clang source code to decipher how function arguments and return
results are handled. Also see the AMDGPU specific values used.

VGPR arguments are assigned to consecutive VGPRs starting at VGPR0 up to
VGPR31.

If there are more arguments than will fit in these registers, the remaining
arguments are allocated on the stack in order on naturally aligned

.. TODO::

  How are overly aligned structures allocated on the stack?

VGPR31.

SGPR arguments are assigned to consecutive SGPRs starting at SGPR0 up to
SGPR29.

SGPR29.

Note that decomposed struct type arguments may have some fields passed in
registers and some in memory.

So, a struct which can pass some fields as decomposed register arguments, will
pass the rest as decomposed stack elements? But an argument that will not start
in registers will not be decomposed and will be passed as a non-decomposed
stack value?

The following is not part of the AMDGPU function calling convention but
describes how the AMDGPU implements function calls:

SGPR33 is used as a frame pointer (FP) if necessary. Like the SP it is an
unswizzled scratch address. It is only needed if runtime sized ``alloca``
are used, or for the reasons defined in ``SIFrameLowering``.

unswizzled scratch address. It is only needed if runtime sized 

Runtime stack alignment is supported. SGPR34 is used as a base pointer (BP)
to access the incoming stack arguments in the function. The BP is needed
only when the function requires the runtime stack alignment.

No CFI is currently generated. See
:ref:`amdgpu-dwarf-call-frame-information`.

.. note::

  CFI will be generated that defines the CFA as the unswizzled address
  relative to the wave scratch base in the unswizzled private address space
  of the lowest address stack allocated local variable.

  ``DW_AT_frame_base`` will be defined as the swizzled address in the
  swizzled private address space by dividing the CFA by the wavefront size
  (since CFA is always at least dword aligned which matches the scratch
  swizzle element size).

  If no dynamic stack alignment was performed, the stack allocated arguments
  are accessed as negative offsets relative to ``DW_AT_frame_base``, and the
  local variables and register spill slots are accessed as positive offsets
  relative to ``DW_AT_frame_base``.

CFI will be generated that defines the CFA as the unswizzled address
relative to the wave scratch base in the unswizzled private address space
of the lowest address stack allocated local variable.

``DW_AT_frame_base`` will be defined as the swizzled address in the
swizzled private address space by dividing the CFA by the wavefront size
(since CFA is always at least dword aligned which matches the scratch
swizzle element size).

If no dynamic stack alignment was performed, the stack allocated arguments
are accessed as negative offsets relative to ``DW_AT_frame_base``, and the
local variables and register spill slots are accessed as positive offsets
relative to ``DW_AT_frame_base``.

 will be defined as the swizzled address in the

are accessed as negative offsets relative to 

, and the
relative to 

Function argument passing is implemented by copying the input physical
registers to virtual registers on entry. The register allocator can spill if
necessary. These are copied back to physical registers at call sites. The
net effect is that each function call can have these values in entirely
distinct locations. The IPRA can help avoid shuffling argument registers.

Call sites are implemented by setting up the arguments at positive offsets
from SP. Then SP is incremented to account for the known frame size before
the call and decremented after the call.

.. note::

  The CFI will reflect the changed calculation needed to compute the CFA
  from SP.

The CFI will reflect the changed calculation needed to compute the CFA
from SP.

4 byte spill slots are used in the stack frame. One slot is allocated for an
emergency spill slot. Buffer instructions are used for stack accesses and
not the ``flat_scratch`` instruction.

.. TODO::

  Explain when the emergency spill slot is used.

not the 

Possible broken issues:

- Stack arguments must be aligned to required alignment.
- Stack is aligned to max(16, max formal argument alignment)
- Direct argument < 64 bits should check register budget.
- Register budget calculation should respect ``inreg`` for SGPR.
- SGPR overflow is not handled.
- struct with 1 member unpeeling is not checking size of member.
- ``sret`` is after ``this`` pointer.
- Caller is not implementing stack realignment: need an extra pointer.
- Should say AMDGPU passes FP rather than SP.
- Should CFI define CFA as address of locals or arguments. Difference is
  apparent when have implemented dynamic alignment.
- If ``SCRATCH`` instruction could allow negative offsets, then can make FP be
  highest address of stack frame and use negative offset for locals. Would
  allow SP to be the same as FP and could support signal-handler-like as now
  have a real SP for the top of the stack.
- How is ``sret`` passed on the stack? In argument stack area? Can it overlay
  arguments?

Caller is not implementing stack realignment: need an extra pointer.

Should CFI define CFA as address of locals or arguments. Difference is
apparent when have implemented dynamic alignment.

If ``SCRATCH`` instruction could allow negative offsets, then can make FP be
highest address of stack frame and use negative offset for locals. Would
allow SP to be the same as FP and could support signal-handler-like as now
have a real SP for the top of the stack.

 instruction could allow negative offsets, then can make FP be

How is ``sret`` passed on the stack? In argument stack area? Can it overlay
arguments?

 passed on the stack? In argument stack area? Can it overlay

``amdpal`` (see :ref:`amdgpu-target-triples`).

The metadata is currently in development and is subject to major
changes. Only the current version is supported. *When this document
was generated the version was 2.6.*

changes. Only the current version is supported. 

Code object metadata is specified by the ``NT_AMDGPU_METADATA`` note

[MsgPack]_). The top level is a Message Pack map that includes the keys
defined in table :ref:`amdgpu-amdpal-code-object-metadata-map-table`
and referenced tables.

). The top level is a Message Pack map that includes the keys

Additional information can be added to the maps. To avoid conflicts, any
key names should be prefixed by "*vendor-name*." where ``vendor-name``
can be the name of the vendor and specific vendor tool that generates the
information. The prefix is abbreviated to simply "." when it appears
within a map that has been added by the same *vendor-name*.

key names should be prefixed by “

key names should be prefixed by "

information. The prefix is abbreviated to simply “.” when it appears
within a map that has been added by the same 

PAL code object metadata (major, minor) version. The current values
are defined by *Util::Abi::PipelineMetadata(Major|Minor)Version*.

are defined by 

Per-pipeline metadata. See
:ref:`amdgpu-amdpal-code-object-pipeline-metadata-map-table` for the
definition of the keys included in that map.

Internal compiler hash for this pipeline. Lower
64 bits is the "stable" portion of the hash, used
for e.g. shader replacement lookup. Upper 64 bits
is the "unique" portion of the hash, used for
e.g. pipeline cache lookup. The value is
implementation defined, and can not be relied on
between different builds of the compiler.

64 bits is the “stable” portion of the hash, used
is the “unique” portion of the hash, used for

Per-API shader metadata. See
:ref:`amdgpu-amdpal-code-object-shader-map-table`
for the definition of the keys included in that
map.

Per-hardware stage metadata. See
:ref:`amdgpu-amdpal-code-object-hardware-stage-map-table`
map.

Per-shader function metadata. See
:ref:`amdgpu-amdpal-code-object-shader-function-map-table`
map.

Hardware register configuration. See
:ref:`amdgpu-amdpal-code-object-register-map-table`
map.

Indicates whether or not the pipeline uses the
viewport array index feature. Pipelines which use
this feature can render into all 16 viewports,
whereas pipelines which do not use it are
restricted to viewport #0.

Size in bytes of LDS space used internally for
handling data-passing between the ES and GS
shader stages. This can be zero if the data is
passed using off-chip buffers. This value should
be used to program all user-SGPRs which have been
marked with "UserDataMapping::EsGsLdsSize"
(typically only the GS and VS HW stages will ever
have a user-SGPR so marked).

marked with “UserDataMapping::EsGsLdsSize”

Explicit maximum subgroup size for NGG shaders
(maximum number of threads in a subgroup).

Graphics API shader create info binary blob. Can
be defined by the driver using the compiler if
they want to be able to correlate API-specific
information used during creation at a later time.

See :ref:`amdgpu-amdpal-code-object-api-shader-metadata-map-table`
for the definition of the keys included in that map.

Input shader hash, typically passed in from the client. The value
is implementation defined, and can not be relied on between
different builds of the compiler.

Flags indicating the HW stages this API shader maps to. Values
include:

See :ref:`amdgpu-amdpal-code-object-hardware-stage-metadata-map-table`

If non-zero, indicates the shader was compiled with a
directive to instruct the compiler to limit the VGPR usage to
be less than or equal to the specified value (only set if
different from HW default).

The shader uses append and/or consume operations, either
memory or GDS.

*symbol name* is the ELF symbol name of the shader function code
entry address. The value is the function's metadata. See
:ref:`amdgpu-amdpal-code-object-shader-function-metadata-map-table`.

 is the ELF symbol name of the shader function code
entry address. The value is the function’s metadata. See

``reg offset`` is the dword offset into the GFXIP register space of
a GRBM register (i.e., driver accessible GPU register number, not
shader GPR register number). The driver is required to program each
specified register to the corresponding specified value when
executing this pipeline. Typically, the ``reg offsets`` are the
``uint16_t`` offsets to each register as defined by the hardware
chip headers. The register is set to the provided value. However, a
``reg offset`` that specifies a user data register (e.g.,
COMPUTE_USER_DATA_0) needs special treatment. See
:ref:`amdgpu-amdpal-code-object-user-data-section` section for more
information.

 is the dword offset into the GFXIP register space of
executing this pipeline. Typically, the 

 offsets to each register as defined by the hardware

 that specifies a user data register (e.g.,

Each hardware stage has a set of 32-bit physical SPI *user data registers*
(either 16 or 32 based on graphics IP and the stage) which can be
written from a command buffer and then loaded into SGPRs when waves are
launched via a subsequent dispatch or draw operation. This is the way
most arguments are passed from the application/runtime to a hardware
shader.

shader.

PAL abstracts this functionality by exposing a set of 128 *user data
entries* per pipeline a client can use to pass arguments from a command
buffer to one or more shaders in that pipeline. The ELF code object must
specify a mapping from virtualized *user data entries* to physical *user
data registers*, and PAL is responsible for implementing that mapping,
including spilling overflow *user data entries* to memory if needed.

 per pipeline a client can use to pass arguments from a command
specify a mapping from virtualized 

, and PAL is responsible for implementing that mapping,
including spilling overflow 

Since the *user data registers* are GRBM-accessible SPI registers, this
mapping is actually embedded in the ``.registers`` metadata entry. For
most registers, the value in that map is a literal 32-bit value that
should be written to the register by the driver. However, when the
register is a *user data register* (any USER_DATA register e.g.,
SPI_SHADER_USER_DATA_PS_5), the value is instead an encoding that tells
the driver to write either a *user data entry* value or one of several
driver-internal values to the register. This encoding is described in
the following table:

 are GRBM-accessible SPI registers, this
mapping is actually embedded in the 

 metadata entry. For
register is a 

 (any USER_DATA register e.g.,
the driver to write either a 

 value or one of several

Currently, *user data registers* 0 and 1 (e.g., SPI_SHADER_USER_DATA_PS_0,
and SPI_SHADER_USER_DATA_PS_1) are reserved. *User data register* 0 must
always be programmed to the address of the GlobalTable, and *user data
register* 1 must always be programmed to the address of the PerShaderTable.

 0 and 1 (e.g., SPI_SHADER_USER_DATA_PS_0,
and SPI_SHADER_USER_DATA_PS_1) are reserved. 

 0 must
always be programmed to the address of the GlobalTable, and 

 1 must always be programmed to the address of the PerShaderTable.

32-bit value of user_data_entry[N] as specified via *CmdSetUserData()*

32-bit pointer to GPU memory containing the global internal table (should
always point to *user data register* 0).

always point to 

32-bit pointer to GPU memory containing the per-shader internal table. See
:ref:`amdgpu-amdpal-code-object-metadata-user-data-per-shader-table-section`
for more detail (should always point to *user data register* 1).

32-bit pointer to GPU memory containing the user data spill table. See
:ref:`amdgpu-amdpal-code-object-metadata-user-data-spill-table-section` for
more detail.

Vertex offset (32-bit unsigned integer). Not needed if the pipeline doesn't
reference the draw index in the vertex shader. Only supported by the first
stage in a graphics pipeline.

Vertex offset (32-bit unsigned integer). Not needed if the pipeline doesn’t

Instance offset (32-bit unsigned integer). Only supported by the first stage in
a graphics pipeline.

Draw index (32-bit unsigned integer). Only supported by the first stage in a
graphics pipeline.

Thread group count (32-bit unsigned integer). Low half of a 64-bit address of
a buffer containing the grid dimensions for a Compute dispatch operation. The
high half of the address is stored in the next sequential user-SGPR. Only
supported by compute pipelines.

Indicates that PAL will program this user-SGPR to contain the amount of LDS
space used for the ES/GS pseudo-ring-buffer for passing data between shader
stages.

View id (32-bit unsigned integer) identifies a view of graphic
pipeline instancing.

32-bit pointer to GPU memory containing the stream out target SRD table.  This
can only appear for one shader stage per pipeline.

32-bit pointer to GPU memory containing the per-shader performance data buffer.

32-bit pointer to GPU memory containing the vertex buffer SRD table.  This can
only appear for one shader stage per pipeline.

32-bit pointer to GPU memory containing the UAV export SRD table.  This can
only appear for one shader stage per pipeline (PS). These replace color targets
and are completely separate from any UAVs used by the shader. This is optional,
and only used by the PS when UAV exports are used to replace color-target
exports to optimize specific shaders.

64-bit pointer to GPU memory containing the hardware register data needed by
some NGG pipelines to perform culling.  This value contains the address of the
first of two consecutive registers which provide the full GPU address.

64-bit pointer to GPU memory containing the fetch shader subroutine.

Low 32 bits of the GPU address for an optional buffer in the ``.data``
section of the ELF. The high 32 bits of the address match the high 32 bits
of the shader's program counter.

of the shader’s program counter.

The buffer can be anything the shader compiler needs it for, and
allows each shader to have its own region of the ``.data`` section.
Typically, this could be a table of buffer SRD's and the data pointed to
by the buffer SRD's, but it could be a flat-address region of memory as
well. Its layout and usage are defined by the shader compiler.

allows each shader to have its own region of the 

 section.
Typically, this could be a table of buffer SRD’s and the data pointed to
by the buffer SRD’s, but it could be a flat-address region of memory as

 section.

Each shader's table in the ``.data`` section is referenced by the symbol
``_amdgpu_``\ *xs*\ ``_shdr_intrl_data``  where *xs* corresponds with the
hardware shader stage the data is for. E.g.,
``_amdgpu_cs_shdr_intrl_data`` for the compute shader hardware stage.

 corresponds with the

It is possible for a hardware shader to need access to more *user data
entries* than there are slots available in user data registers for one
or more hardware shader stages. In that case, the PAL runtime expects
the necessary *user data entries* to be spilled to GPU memory and use
one user data register to point to the spilled user data memory. The
value of the *user data entry* must then represent the location where
a shader expects to read the low 32-bits of the table's GPU virtual
address. The *spill table* itself represents a set of 32-bit values
managed by the PAL runtime in GPU-accessible memory that can be made
indirectly accessible to a hardware shader.

 than there are slots available in user data registers for one
the necessary 

 to be spilled to GPU memory and use
value of the 

 must then represent the location where
a shader expects to read the low 32-bits of the table’s GPU virtual
address. The 

 itself represents a set of 32-bit values

empty (see :ref:`amdgpu-target-triples`).

empty (see 

For code objects generated by AMDGPU backend for non-amdhsa OS, the runtime does
not install a trap handler. The ``llvm.trap`` and ``llvm.debugtrap``
instructions are handled as follows:

not install a trap handler. The 

The OpenCL memory model is used (see :ref:`amdgpu-amdhsa-memory-model`).

The AMDGPU backend appends additional arguments to the kernel's explicit
arguments for the AMDHSA OS (see

The AMDGPU backend appends additional arguments to the kernel’s explicit

Additional metadata is generated
(see :ref:`amdgpu-amdhsa-code-object-metadata`).

The HSA memory model is used (see :ref:`amdgpu-amdhsa-memory-model`).

AMDGPU backend has LLVM-MC based assembler which is currently in development.
It supports AMDGCN GFX6-GFX10.

This section describes general syntax for instructions and operands.

An instruction has the following :doc:`syntax<AMDGPUInstructionSyntax>`:

``<``\ *opcode*\ ``> <``\ *operand0*\ ``>, <``\ *operand1*\ ``>,...
<``\ *modifier0*\ ``> <``\ *modifier1*\ ``>...``

:doc:`Operands<AMDGPUOperandSyntax>` are comma-separated while
:doc:`modifiers<AMDGPUModifierSyntax>` are space-separated.

The order of operands and modifiers is fixed.
Most modifiers are optional and may be omitted.

Links to detailed instruction syntax description may be found in the following
table. Note that features under development are not included
in this description.

For more information about instructions, their semantics and supported
combinations of operands, refer to one of instruction set architecture manuals
[AMD-GCN-GFX6]_, [AMD-GCN-GFX7]_, [AMD-GCN-GFX8]_,
[AMD-GCN-GFX900-GFX904-VEGA]_, [AMD-GCN-GFX906-VEGA7NM]_
[AMD-GCN-GFX908-CDNA1]_, [AMD-GCN-GFX10-RDNA1]_ and [AMD-GCN-GFX10-RDNA2]_.

Detailed description of operands may be found :doc:`here<AMDGPUOperandSyntax>`.

Detailed description of modifiers may be found
:doc:`here<AMDGPUModifierSyntax>`.

ds_add_u32 v2, v4 offset:16
ds_write_src2_b64 v2 offset0:4 offset1:8
ds_cmpst_f32 v2, v4, v6
ds_min_rtn_f64 v[8:9], v2, v[4:5]

For full list of supported instructions, refer to "LDS/GDS instructions" in ISA
Manual.

For full list of supported instructions, refer to “LDS/GDS instructions” in ISA
Manual.

flat_load_dword v1, v[3:4]
flat_store_dwordx3 v[3:4], v[5:7]
flat_atomic_swap v1, v[3:4], v5 glc
flat_atomic_cmpswap v1, v[3:4], v[5:6] glc slc
flat_atomic_fmax_x2 v[1:2], v[3:4], v[5:6] glc

For full list of supported instructions, refer to "FLAT instructions" in ISA
Manual.

For full list of supported instructions, refer to “FLAT instructions” in ISA
Manual.

buffer_load_dword v1, off, s[4:7], s1
buffer_store_dwordx4 v[1:4], v2, ttmp[4:7], s1 offen offset:4 glc tfe
buffer_store_format_xy v[1:2], off, s[4:7], s1
buffer_wbinvl1
buffer_atomic_inc v1, v2, s[8:11], s4 idxen offset:4 slc

For full list of supported instructions, refer to "MUBUF Instructions" in ISA
Manual.

For full list of supported instructions, refer to “MUBUF Instructions” in ISA
Manual.

s_load_dword s1, s[2:3], 0xfc
s_load_dwordx8 s[8:15], s[2:3], s4
s_load_dwordx16 s[88:103], s[2:3], s4
s_dcache_inv_vol
s_memtime s[4:5]

For full list of supported instructions, refer to "Scalar Memory Operations" in
ISA Manual.

For full list of supported instructions, refer to “Scalar Memory Operations” in

s_mov_b32 s1, s2
s_mov_b64 s[0:1], 0x80000000
s_cmov_b32 s1, 200
s_wqm_b64 s[2:3], s[4:5]
s_bcnt0_i32_b64 s1, s[2:3]
s_swappc_b64 s[2:3], s[4:5]
s_cbranch_join s[4:5]

For full list of supported instructions, refer to "SOP1 Instructions" in ISA
Manual.

For full list of supported instructions, refer to “SOP1 Instructions” in ISA
Manual.

s_add_u32 s1, s2, s3
s_and_b64 s[2:3], s[4:5], s[6:7]
s_cselect_b32 s1, s2, s3
s_andn2_b32 s2, s4, s6
s_lshr_b64 s[2:3], s[4:5], s6
s_ashr_i32 s2, s4, s6
s_bfm_b64 s[2:3], s4, s6
s_bfe_i64 s[2:3], s[4:5], s6
s_cbranch_g_fork s[4:5], s[6:7]

For full list of supported instructions, refer to "SOP2 Instructions" in ISA
Manual.

For full list of supported instructions, refer to “SOP2 Instructions” in ISA
Manual.

s_cmp_eq_i32 s1, s2
s_bitcmp1_b32 s1, s2
s_bitcmp0_b64 s[2:3], s4
s_setvskip s3, s5

For full list of supported instructions, refer to "SOPC Instructions" in ISA
Manual.

For full list of supported instructions, refer to “SOPC Instructions” in ISA
Manual.

s_barrier
s_nop 2
s_endpgm
s_waitcnt 0 ; Wait for all counters to be 0
s_waitcnt vmcnt(0) & expcnt(0) & lgkmcnt(0) ; Equivalent to above
s_waitcnt vmcnt(1) ; Wait for vmcnt counter to be 1.
s_sethalt 9
s_sleep 10
s_sendmsg 0x1
s_sendmsg sendmsg(MSG_INTERRUPT)
s_trap 1

For full list of supported instructions, refer to "SOPP Instructions" in ISA
Manual.

For full list of supported instructions, refer to “SOPP Instructions” in ISA
Manual.

Unless otherwise mentioned, little verification is performed on the operands
of SOPP Instructions, so it is up to the programmer to be familiar with the
range or acceptable values.

For vector ALU instruction opcodes (VOP1, VOP2, VOP3, VOPC, VOP_DPP, VOP_SDWA),
the assembler will automatically use optimal encoding based on its operands. To
force specific encoding, one can add a suffix to the opcode of the instruction:

v_mov_b32 v1, v2
v_mov_b32_e32 v1, v2
v_nop
v_cvt_f64_i32_e32 v[1:2], v2
v_floor_f32_e32 v1, v2
v_bfrev_b32_e32 v1, v2
v_add_f32_e32 v1, v2, v3
v_mul_i32_i24_e64 v1, v2, 3
v_mul_i32_i24_e32 v1, -3, v3
v_mul_i32_i24_e32 v1, -100, v3
v_addc_u32 v1, s[0:1], v2, v3, s[2:3]
v_max_f16_e32 v1, v2, v3

v_mov_b32 v0, v0 quad_perm:[0,2,1,1]
v_sin_f32 v0, v0 row_shl:1 row_mask:0xa bank_mask:0x1 bound_ctrl:0
v_mov_b32 v0, v0 wave_shl:1
v_mov_b32 v0, v0 row_mirror
v_mov_b32 v0, v0 row_bcast:31
v_mov_b32 v0, v0 quad_perm:[1,3,0,1] row_mask:0xa bank_mask:0x1 bound_ctrl:0
v_add_f32 v0, v0, |v0| row_shl:1 row_mask:0xa bank_mask:0x1 bound_ctrl:0
v_max_f16 v1, v2, v3 row_shl:1 row_mask:0xa bank_mask:0x1 bound_ctrl:0

v_mov_b32 v1, v2 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD
v_min_u32 v200, v200, v1 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:DWORD
v_sin_f32 v0, v0 dst_unused:UNUSED_PAD src0_sel:WORD_1
v_fract_f32 v0, |v0| dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1
v_cmpx_le_u32 vcc, v1, v2 src0_sel:BYTE_2 src1_sel:WORD_0

For full list of supported instructions, refer to "Vector ALU instructions".

For full list of supported instructions, refer to “Vector ALU instructions”.

The AMDGPU assembler defines and updates some symbols automatically. These
symbols do not affect code generation.

Set to the GFX major generation number of the target being assembled for. For
example, when assembling for a "GFX9" target this will be set to the integer
value "9". The possible GFX major generation numbers are presented in
:ref:`amdgpu-processors`.

example, when assembling for a “GFX9” target this will be set to the integer
value “9”. The possible GFX major generation numbers are presented in

Set to the GFX minor generation number of the target being assembled for. For
example, when assembling for a "GFX810" target this will be set to the integer
value "1". The possible GFX minor generation numbers are presented in

example, when assembling for a “GFX810” target this will be set to the integer
value “1”. The possible GFX minor generation numbers are presented in

Set to the GFX stepping generation number of the target being assembled for.
For example, when assembling for a "GFX704" target this will be set to the
integer value "4". The possible GFX stepping generation numbers are presented
in :ref:`amdgpu-processors`.

For example, when assembling for a “GFX704” target this will be set to the
integer value “4”. The possible GFX stepping generation numbers are presented
in 

in 

Set to zero each time a
:ref:`amdgpu-amdhsa-assembler-directive-amdgpu_hsa_kernel` directive is
encountered. At each instruction, if the current value of this symbol is less
than or equal to the maximum VGPR number explicitly referenced within that
instruction then the symbol value is updated to equal that VGPR number plus
one.

 directive is
one.

instruction then the symbol value is updated to equal that SGPR number plus
one.

one.

AMDGPU ABI defines auxiliary data in output code object. In assembly source,
one can specify them with assembler directives.

*major* and *minor* are integers that specify the version of the HSA code
object that will be generated by the assembler.

 are integers that specify the version of the HSA code

*major*, *minor*, and *stepping* are all integers that describe the instruction
set architecture (ISA) version of the assembly program.

 are all integers that describe the instruction

*vendor* and *arch* are quoted strings. *vendor* should always be equal to
"AMD" and *arch* should always be equal to "AMDGPU".

By default, the assembler will derive the ISA version, *vendor*, and *arch*
from the value of the -mcpu option that is passed to the assembler.

This directives specifies that the symbol with given name is a kernel entry
point (label) and the object should contain corresponding symbol of type
STT_AMDGPU_HSA_KERNEL.

This directive marks the beginning of a list of key / value pairs that are used
to specify the amd_kernel_code_t object that will be emitted by the assembler.
The list must be terminated by the *.end_amd_kernel_code_t* directive. For any
amd_kernel_code_t values that are unspecified a default value will be used. The
default value for all keys is 0, with the following exceptions:

The list must be terminated by the 

 directive. For any

*amd_machine_version_major*, *machine_version_minor*, and
*amd_machine_version_stepping* are derived from the value of the -mcpu option
that is passed to the assembler.

 are derived from the value of the -mcpu option

*wavefront_size* defaults 6 for all targets before GFX10. For GFX10 onwards
defaults to 6 if target feature ``wavefrontsize64`` is enabled, otherwise 5.
Note that wavefront size is specified as a power of two, so a value of **n**
means a size of 2^ **n**.

 defaults 6 for all targets before GFX10. For GFX10 onwards
defaults to 6 if target feature 

 is enabled, otherwise 5.
Note that wavefront size is specified as a power of two, so a value of 

*kernarg_segment_alignment*, *group_segment_alignment*, and
*private_segment_alignment* default to 4. Note that alignments are specified
as a power of 2, so a value of **n** means an alignment of 2^ **n**.

 default to 4. Note that alignments are specified
as a power of 2, so a value of 

*enable_tg_split* defaults to 1 if target feature ``tgsplit`` is enabled for
GFX90A onwards.

*enable_wgp_mode* defaults to 1 if target feature ``cumode`` is disabled for
GFX10 onwards.

The *.amd_kernel_code_t* directive must be placed immediately after the
function label and before any instructions.

 directive must be placed immediately after the

For a full list of amd_kernel_code_t keys, refer to AMDGPU ABI document,
comments in lib/Target/AMDGPU/AmdKernelCodeT.h and test/CodeGen/AMDGPU/hsa.s.

Code Object V2 is not the default code object version emitted by

Here is an example of a minimal assembly source file, defining one HSA kernel:

.hsa_code_object_version 1,0
.hsa_code_object_isa

.hsatext
.globl  hello_world
.p2align 8
.amdgpu_hsa_kernel hello_world

hello_world:

   .amd_kernel_code_t
      enable_sgpr_kernarg_segment_ptr = 1
      is_ptr64 = 1
      compute_pgm_rsrc1_vgprs = 0
      compute_pgm_rsrc1_sgprs = 0
      compute_pgm_rsrc2_user_sgpr = 2
      compute_pgm_rsrc1_wgp_mode = 0
      compute_pgm_rsrc1_mem_ordered = 0
      compute_pgm_rsrc1_fwd_progress = 1
  .end_amd_kernel_code_t

  s_load_dwordx2 s[0:1], s[0:1] 0x0
  v_mov_b32 v0, 3.14159
  s_waitcnt lgkmcnt(0)
  v_mov_b32 v1, s0
  v_mov_b32 v2, s1
  flat_store_dword v[1:2], v0
  s_endpgm
.Lfunc_end0:
     .size   hello_world, .Lfunc_end0-hello_world

Set to zero before assembly begins. At each instruction, if the current value
of this symbol is less than or equal to the maximum VGPR number explicitly
referenced within that instruction then the symbol value is updated to equal
that VGPR number plus one.

May be used to set the `.amdhsa_next_free_vgpr` directive in
:ref:`amdhsa-kernel-directives-table`.

May be set at any time, e.g. manually set to zero at the start of each kernel.

of this symbol is less than or equal the maximum SGPR number explicitly
that SGPR number plus one.

May be used to set the `.amdhsa_next_free_spgr` directive in

Directives which begin with ``.amdgcn`` are valid for all ``amdgcn``
architecture processors, and are not OS-specific. Directives which begin with
``.amdhsa`` are specific to ``amdgcn`` architecture processors when the
``amdhsa`` OS is specified. See :ref:`amdgpu-target-triples` and

Optional directive which declares the ``<target-triple>-<target-id>`` supported
by the containing assembler source file. Used by the assembler to validate
command-line options such as ``-triple``, ``-mcpu``, and
``--offload-arch=<target-id>``. A non-canonical target ID is allowed. See
:ref:`amdgpu-target-triples` and :ref:`amdgpu-target-id`.

 supported
command-line options such as 

The target ID syntax used for code object V2 to V3 for this directive differs
from that used elsewhere. See :ref:`amdgpu-target-id-v2-v3`.

from that used elsewhere. See 

Creates a correctly aligned AMDHSA kernel descriptor and a symbol,
``<name>.kd``, in the current location of the current section. Only valid when
the OS is ``amdhsa``. ``<name>`` must be a symbol that labels the first
instruction to execute, and does not need to be previously defined.

, in the current location of the current section. Only valid when
the OS is 

 must be a symbol that labels the first

Marks the beginning of a list of directives used to generate the bytes of a
kernel descriptor, as described in :ref:`amdgpu-amdhsa-kernel-descriptor`.
Directives which may appear in this list are described in
:ref:`amdhsa-kernel-directives-table`. Directives may appear in any order, must
be valid for the target being assembled for, and cannot be repeated. Directives
support the range of values specified by the field they reference in
:ref:`amdgpu-amdhsa-kernel-descriptor`. If a directive is not specified, it is
assumed to have its default value, unless it is marked as "Required", in which
case it is an error to omit the directive. This list of directives is
terminated by an ``.end_amdhsa_kernel`` directive.

kernel descriptor, as described in 

. Directives may appear in any order, must

. If a directive is not specified, it is
assumed to have its default value, unless it is marked as “Required”, in which
terminated by an 

Controls GROUP_SEGMENT_FIXED_SIZE in

Controls PRIVATE_SEGMENT_FIXED_SIZE in

Controls KERNARG_SIZE in

Controls ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER in

Controls ENABLE_SGPR_DISPATCH_PTR in

Controls ENABLE_SGPR_QUEUE_PTR in

Controls ENABLE_SGPR_KERNARG_SEGMENT_PTR in

Controls ENABLE_SGPR_DISPATCH_ID in

Controls ENABLE_SGPR_FLAT_SCRATCH_INIT in

Controls ENABLE_SGPR_PRIVATE_SEGMENT_SIZE in

Controls ENABLE_WAVEFRONT_SIZE32 in

Controls ENABLE_PRIVATE_SEGMENT in

Controls ENABLE_SGPR_WORKGROUP_ID_X in

Controls ENABLE_SGPR_WORKGROUP_ID_Y in

Controls ENABLE_SGPR_WORKGROUP_ID_Z in

Controls ENABLE_SGPR_WORKGROUP_INFO in

Controls ENABLE_VGPR_WORKITEM_ID in
Possible values are defined in
:ref:`amdgpu-amdhsa-system-vgpr-work-item-id-enumeration-values-table`.

Maximum VGPR number explicitly referenced, plus one.
Used to calculate GRANULATED_WORKITEM_VGPR_COUNT in

Maximum SGPR number explicitly referenced, plus one.
Used to calculate GRANULATED_WAVEFRONT_SGPR_COUNT in

Offset of a first AccVGPR in the unified register file.
Used to calculate ACCUM_OFFSET in

Whether the kernel may use the special VCC SGPR.

Whether the kernel may use flat instructions to access
scratch memory. Used to calculate
GRANULATED_WAVEFRONT_SGPR_COUNT in

Whether the kernel may trigger XNACK replay.

Controls FLOAT_ROUND_MODE_32 in

Controls FLOAT_ROUND_MODE_16_64 in

Controls FLOAT_DENORM_MODE_32 in

Controls FLOAT_DENORM_MODE_16_64 in

Controls ENABLE_DX10_CLAMP in

Controls ENABLE_IEEE_MODE in

Controls FP16_OVFL in

Controls TG_SPLIT in

Controls ENABLE_WGP_MODE in

Controls MEM_ORDERED in

Controls FWD_PROGRESS in

Controls ENABLE_EXCEPTION_IEEE_754_FP_INVALID_OPERATION in

Controls ENABLE_EXCEPTION_FP_DENORMAL_SOURCE in

Controls ENABLE_EXCEPTION_IEEE_754_FP_DIVISION_BY_ZERO in

Controls ENABLE_EXCEPTION_IEEE_754_FP_OVERFLOW in

Controls ENABLE_EXCEPTION_IEEE_754_FP_UNDERFLOW in

Controls ENABLE_EXCEPTION_IEEE_754_FP_INEXACT in

Controls ENABLE_EXCEPTION_INT_DIVIDE_BY_ZERO in

Optional directive which declares the contents of the ``NT_AMDGPU_METADATA``
note record (see :ref:`amdgpu-elf-note-records-table-v3-v4`).

The contents must be in the [YAML]_ markup format, with the same structure and
semantics described in :ref:`amdgpu-amdhsa-code-object-metadata-v3` or

 markup format, with the same structure and
semantics described in 

This directive is terminated by an ``.end_amdgpu_metadata`` directive.

.amdgcn_target "amdgcn-amd-amdhsa--gfx900+xnack" // optional

.text
.globl hello_world
.p2align 8
.type hello_world,@function
  s_endpgm
  .size   hello_world, .Lfunc_end0-hello_world

.rodata
.p2align 6
.amdhsa_kernel hello_world
  .amdhsa_user_sgpr_kernarg_segment_ptr 1
  .amdhsa_next_free_vgpr .amdgcn.next_free_vgpr
  .amdhsa_next_free_sgpr .amdgcn.next_free_sgpr
.end_amdhsa_kernel

.amdgpu_metadata
---
amdhsa.version:
  - 1
  - 0
amdhsa.kernels:
  - .name: hello_world
    .symbol: hello_world.kd
    .kernarg_segment_size: 48
    .group_segment_fixed_size: 0
    .private_segment_fixed_size: 0
    .kernarg_segment_align: 4
    .wavefront_size: 64
    .sgpr_count: 2
    .vgpr_count: 3
    .max_flat_workgroup_size: 256
    .args:
      - .size: 8
        .offset: 0
        .value_kind: global_buffer
        .address_space: global
        .actual_access: write_only
//...
.end_amdgpu_metadata

If an assembly source file contains multiple kernels and/or functions, the
:ref:`amdgpu-amdhsa-assembler-symbol-next_free_vgpr` and
:ref:`amdgpu-amdhsa-assembler-symbol-next_free_sgpr` symbols may be reset using
the ``.set <symbol>, <expression>`` directive. For example, in the case of two
kernels, where ``function1`` is only called from ``kernel1`` it is sufficient
to group the function with the kernel that calls it and reset the symbols
between the two connected components:

 it is sufficient

// gpr tracking symbols are implicitly set to zero

.text
.globl kern0
.p2align 8
.type kern0,@function
kern0:
  // ...
  s_endpgm
.Lkern0_end:
  .size   kern0, .Lkern0_end-kern0

.rodata
.p2align 6
.amdhsa_kernel kern0
  // ...

// reset symbols to begin tracking usage in func1 and kern1
.set .amdgcn.next_free_vgpr, 0
.set .amdgcn.next_free_sgpr, 0

.text
.hidden func1
.global func1
.p2align 2
.type func1,@function
func1:
  // ...
  s_setpc_b64 s[30:31]
.Lfunc1_end:
.size func1, .Lfunc1_end-func1

.globl kern1
.p2align 8
.type kern1,@function
kern1:
  // ...
  s_getpc_b64 s[4:5]
  s_add_u32 s4, s4, func1@rel32@lo+4
  s_addc_u32 s5, s5, func1@rel32@lo+4
  s_swappc_b64 s[30:31], s[4:5]
  // ...
  s_endpgm
.Lkern1_end:
  .size   kern1, .Lkern1_end-kern1

.rodata
.p2align 6
.amdhsa_kernel kern1
  // ...

These symbols cannot identify connected components in order to automatically
track the usage for each kernel. However, in some cases careful organization of
the kernels and functions in the source file means there is minimal additional
effort required to accurately calculate GPR usage.

`AMD Southern Islands Series ISA <http://developer.amd.com/wordpress/media/2012/12/AMD_Southern_Islands_Instruction_Set_Architecture.pdf>`__

`AMD Sea Islands Series ISA <http://developer.amd.com/wordpress/media/2013/07/AMD_Sea_Islands_Instruction_Set_Architecture.pdf>`_

`AMD GCN3 Instruction Set Architecture <http://amd-dev.wpengine.netdna-cdn.com/wordpress/media/2013/12/AMD_GCN3_Instruction_Set_Architecture_rev1.1.pdf>`__

`AMD Vega Instruction Set Architecture <http://developer.amd.com/wordpress/media/2013/12/Vega_Shader_ISA_28July2017.pdf>`__

`AMD Vega 7nm Instruction Set Architecture <https://gpuopen.com/wp-content/uploads/2019/11/Vega_7nm_Shader_ISA_26November2019.pdf>`__

`AMD Instinct MI100 Instruction Set Architecture <https://developer.amd.com/wp-content/resources/CDNA1_Shader_ISA_14December2020.pdf>`__

`AMD RDNA 1.0 Instruction Set Architecture <https://gpuopen.com/wp-content/uploads/2019/08/RDNA_Shader_ISA_5August2019.pdf>`__

`AMD RDNA 2 Instruction Set Architecture <https://developer.amd.com/wp-content/resources/RDNA2_Shader_ISA_November2020.pdf>`__

`AMD R6xx shader ISA <http://developer.amd.com/wordpress/media/2012/10/R600_Instruction_Set_Architecture.pdf>`__

`AMD R7xx shader ISA <http://developer.amd.com/wordpress/media/2012/10/R700-Family_Instruction_Set_Architecture.pdf>`__

`AMD Evergreen shader ISA <http://developer.amd.com/wordpress/media/2012/10/AMD_Evergreen-Family_Instruction_Set_Architecture.pdf>`__

`AMD Cayman/Trinity shader ISA <http://developer.amd.com/wordpress/media/2012/10/AMD_HD_6900_Series_Instruction_Set_Architecture.pdf>`__

`AMD ROCm Release Notes <https://github.com/RadeonOpenCompute/ROCm>`__

`Attributes in Clang <https://clang.llvm.org/docs/AttributeReference.html>`__

`Executable and Linkable Format (ELF) <http://www.sco.com/developers/gabi/>`__

`Heterogeneous-race-free Memory Models <http://benedictgaster.org/wp-content/uploads/2014/01/asplos269-FINAL.pdf>`__

`Heterogeneous System Architecture (HSA) Foundation <http://www.hsafoundation.com/>`__

`The OpenCL Specification Version 2.0 <http://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`__

`YAML Ain't Markup Language (YAML™) Version 1.2 <http://www.yaml.org/spec/1.2/spec.html>`__

Unexpected possible title overline or transition.
Treating it as ordinary text because it's so short.

Treating it as ordinary text because it’s so short.

Hyperlink target "amdgpu-embedding-bundled-objects" is not referenced.

Hyperlink target "amdgpu-loaded-code-object-path-uniform-resource-identifier" is not referenced.

Hyperlink target "amdgpu-dwarf-debug-information" is not referenced.

Hyperlink target "amdgpu-dwarf-register-identifier" is not referenced.

Hyperlink target "amdgpu-dwarf-address-class-identifier" is not referenced.

Hyperlink target "amdgpu-dwarf-address-space-identifier" is not referenced.

Hyperlink target "amdgpu-dwarf-lane-identifier" is not referenced.

Hyperlink target "amdgpu-dwarf-dw-at-llvm-lane-pc" is not referenced.

Hyperlink target "amdgpu-dwarf-amdgpu-dw-at-llvm-active-lane" is not referenced.

Hyperlink target "amdgpu-amdhsa-code-object-metadata" is not referenced.

Hyperlink target "amdgpu-amdhsa-code-object-metadata-v2" is not referenced.

Hyperlink target "amdgpu-amdhsa-code-object-metadata-v3" is not referenced.

Hyperlink target "amdgpu-amdhsa-code-object-metadata-v4" is not referenced.

Hyperlink target "amdgpu-amdhsa-memory-spaces" is not referenced.

Hyperlink target "amdgpu-amdhsa-hsa-aql-queue" is not referenced.

Hyperlink target "amdgpu-amdhsa-kernel-descriptor" is not referenced.

Hyperlink target "amdgpu-amdhsa-initial-kernel-execution-state" is not referenced.

Hyperlink target "amdgpu-amdhsa-kernel-prolog" is not referenced.

Hyperlink target "amdgpu-amdhsa-kernel-prolog-cfi" is not referenced.

Hyperlink target "amdgpu-amdhsa-kernel-prolog-m0" is not referenced.

Hyperlink target "amdgpu-amdhsa-kernel-prolog-stack-pointer" is not referenced.

Hyperlink target "amdgpu-amdhsa-kernel-prolog-frame-pointer" is not referenced.

Hyperlink target "amdgpu-amdhsa-kernel-prolog-flat-scratch" is not referenced.

Hyperlink target "amdgpu-amdhsa-kernel-prolog-private-segment-buffer" is not referenced.

Hyperlink target "amdgpu-amdhsa-memory-model" is not referenced.

Hyperlink target "amdgpu-amdhsa-memory-model-gfx6-gfx9" is not referenced.

Hyperlink target "amdgpu-amdhsa-memory-model-gfx90a" is not referenced.

Hyperlink target "amdgpu-amdhsa-memory-model-gfx10" is not referenced.

Hyperlink target "amdgpu-amdhsa-function-call-convention" is not referenced.

Hyperlink target "amdgpu-amdhsa-function-call-convention-kernel-functions" is not referenced.

Hyperlink target "amdgpu-amdhsa-function-call-convention-non-kernel-functions" is not referenced.

Hyperlink target "amdgpu-amdpal-code-object-metadata-section" is not referenced.

Hyperlink target "amdgpu-amdpal-code-object-user-data-section" is not referenced.

Hyperlink target "amdgpu-amdpal-code-object-metadata-user-data-per-shader-table-section" is not referenced.

Hyperlink target "amdgpu-amdpal-code-object-metadata-user-data-spill-table-section" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-predefined-symbols-v2" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-directives-v2" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-directive-amdgpu-hsa-kernel" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-example-v2" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-predefined-symbols-v3-v4" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-symbol-next-free-vgpr" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-symbol-next-free-sgpr" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-directives-v3-v4" is not referenced.

Hyperlink target "amdgpu-assembler-directive-amdgcn-target" is not referenced.

Hyperlink target "amdgpu-amdhsa-assembler-example-v3-v4" is not referenced.

Use the Clang options ``-mcpu=<target-id>`` or ``--offload-arch=<target-id>`` to
specify the AMDGPU processor together with optional target features. See
:ref:`amdgpu-target-id` and :ref:`amdgpu-target-features` for AMD GPU target
specific information.

 to

Every processor supports every OS ABI (see :ref:`amdgpu-os`) with the following exceptions:

Explain variables and cache. Move explanation here from #options section.

`CMake <http://www.cmake.org/>`_ is a cross-platform build-generator tool. CMake
does not build the project, it generates the files needed by your build tool
(GNU make, Visual Studio, etc.) for building LLVM.

 is a cross-platform build-generator tool. CMake

If **you are a new contributor**, please start with the :doc:`GettingStarted`
page.  This page is geared for existing contributors moving from the
legacy configure/make system.

If you are really anxious about getting a functional LLVM build, go to the
`Quick start`_ section. If you are a CMake novice, start with `Basic CMake usage`_
and then go back to the `Quick start`_ section once you know what you are doing. The
`Options and variables`_ section is a reference for customizing your build. If
you already have experience with CMake, this is the recommended starting point.

 section is a reference for customizing your build. If

This page is geared towards users of the LLVM CMake build. If you're looking for
information about modifying the LLVM CMake build system you may want to see the
:doc:`CMakePrimer` page. It has a basic overview of the CMake language.

This page is geared towards users of the LLVM CMake build. If you’re looking for

`Download <http://www.cmake.org/cmake/resources/software.html>`_ and install
CMake. Version 3.13.4 is the minimum required.

Open a shell. Your development tools must be reachable from this shell
through the PATH environment variable.

Create a build directory. Building LLVM in the source
directory is not supported. cd to this directory:

.. code-block:: console

  $ mkdir mybuilddir
  $ cd mybuilddir

Execute this command in the shell replacing `path/to/llvm/source/root` with
the path to the root of your LLVM source tree:

  $ cmake path/to/llvm/source/root

CMake will detect your development environment, perform a series of tests, and
generate the files required for building LLVM. CMake will use default values
for all build parameters. See the `Options and variables`_ section for
a list of build parameters that you can modify.

This can fail if CMake can't detect your toolset, or if it thinks that the
environment is not sane enough. In this case, make sure that the toolset that
you intend to use is the only one reachable from the shell, and that the shell
itself is the correct one for your development environment. CMake will refuse
to build MinGW makefiles if you have a POSIX shell reachable through the PATH
environment variable, for instance. You can force CMake to use a given build
tool; for instructions, see the `Usage`_ section, below.  You may
also wish to control which targets LLVM enables, or which LLVM
components are built; see the `Frequently Used LLVM-related
variables`_ below.

for all build parameters. See the 

This can fail if CMake can’t detect your toolset, or if it thinks that the
tool; for instructions, see the 

 section, below.  You may
components are built; see the 

After CMake has finished running, proceed to use IDE project files, or start
the build from the build directory:

  $ cmake --build .

The ``--build`` option tells ``cmake`` to invoke the underlying build
tool (``make``, ``ninja``, ``xcodebuild``, ``msbuild``, etc.)

The underlying build tool can be invoked directly, of course, but
the ``--build`` option is portable.

the 

After LLVM has finished building, install it from the build directory:

  $ cmake --build . --target install

The ``--target`` option with ``install`` parameter in addition to
the ``--build`` option tells ``cmake`` to build the ``install`` target.

It is possible to set a different install prefix at installation time
by invoking the ``cmake_install.cmake`` script generated in the
build directory:

  $ cmake -DCMAKE_INSTALL_PREFIX=/tmp/llvm -P cmake_install.cmake

by invoking the 

Variables customize how the build will be generated. Options are boolean
variables, with possible values ON/OFF. Options and variables are defined on the
CMake command line like this:

You can set a variable after the initial CMake invocation to change its
value. You can also undefine a variable:

Variables are stored in the CMake cache. This is a file named ``CMakeCache.txt``
stored at the root of your build directory that is generated by ``cmake``.
Editing it yourself is not recommended.

stored at the root of your build directory that is generated by 

Variables are listed in the CMake cache and later in this document with
the variable name and type separated by a colon. You can also specify the
variable and type on the CMake command line:

Here are some of the CMake variables that are used often, along with a
brief explanation. For full documentation, consult the CMake manual,
or execute ``cmake --help-variable VARIABLE_NAME``.  See `Frequently
Used LLVM-related Variables`_ below for information about commonly
used variables that control features of LLVM and enabled subprojects.

or execute 

 below for information about commonly

**CMAKE_BUILD_TYPE**:STRING
Sets the build type for ``make``-based generators. Possible values are
Release, Debug, RelWithDebInfo and MinSizeRel. If you are using an IDE such as
Visual Studio, you should use the IDE settings to set the build type.
Be aware that Release and RelWithDebInfo use different optimization levels on
most platforms. Be aware that Release and
RelWithDebInfo use different optimization levels on most
platforms, and that the default value of ``LLVM_ENABLE_ASSERTIONS``
is affected.

-based generators. Possible values are
platforms, and that the default value of 

**CMAKE_INSTALL_PREFIX**:PATH
Path where LLVM will be installed when the "install" target is built.

Path where LLVM will be installed when the “install” target is built.

**CMAKE_{C,CXX}_FLAGS**:STRING
Extra flags to use when compiling C and C++ source files respectively.

**CMAKE_{C,CXX}_COMPILER**:STRING
Specify the C and C++ compilers to use. If you have multiple
compilers installed, CMake might not default to the one you wish to
use.

use.

The default configuration may not match your requirements. Here are
LLVM variables that are frequently used to control that. The full
description is in `LLVM-related variables`_ below.

description is in 

**LLVM_ENABLE_PROJECTS**:STRING
Control which projects are enabled. For example you may want to work on clang
or lldb by specifying ``-DLLVM_ENABLE_PROJECTS="clang;lldb"``.

or lldb by specifying 

**LLVM_LIBDIR_SUFFIX**:STRING
Extra suffix to append to the directory where libraries are to be
installed. On a 64-bit architecture, one could use ``-DLLVM_LIBDIR_SUFFIX=64``
to install libraries to ``/usr/lib64``.

installed. On a 64-bit architecture, one could use 

**LLVM_PARALLEL_{COMPILE,LINK}_JOBS**:STRING
Building the llvm toolchain can use a lot of resources, particularly
linking. These options, when you use the Ninja generator, allow you
to restrict the parallelism. For example, to avoid OOMs or going
into swap, permit only one link job per 15GB of RAM available on a
32GB machine, specify ``-G Ninja -DLLVM_PARALLEL_LINK_JOBS=2``.

32GB machine, specify 

**LLVM_TARGETS_TO_BUILD**:STRING
Control which targets are enabled. For example you may only need to enable
your native target with, for example, ``-DLLVM_TARGETS_TO_BUILD=X86``.

your native target with, for example, 

**LLVM_USE_LINKER**:STRING
Override the system's default linker. For instance use ``lld`` with
``-DLLVM_USE_LINKER=lld``.

Here are some of the CMake variables that are rarely used, along with a brief
explanation and LLVM-related notes.  For full documentation, consult the CMake
manual, or execute ``cmake --help-variable VARIABLE_NAME``.

manual, or execute 

**CMAKE_CXX_STANDARD**:STRING
Sets the C++ standard to conform to when building LLVM.  Possible values are
14, 17, 20.  LLVM Requires C++ 14 or higher.  This defaults to 14.

These variables provide fine control over the build of LLVM and
enabled sub-projects. Nearly all of these variable names begin with
``LLVM_``.

**BUILD_SHARED_LIBS**:BOOL
Flag indicating if each LLVM component (e.g. Support) is built as a shared
library (ON) or as a static library (OFF). Its default value is OFF. On
Windows, shared libraries may be used when building with MinGW, including
mingw-w64, but not when building with the Microsoft toolchain.

.. note:: BUILD_SHARED_LIBS is only recommended for use by LLVM developers.
          If you want to build LLVM as a shared library, you should use the
          ``LLVM_BUILD_LLVM_DYLIB`` option.

BUILD_SHARED_LIBS is only recommended for use by LLVM developers.
If you want to build LLVM as a shared library, you should use the
``LLVM_BUILD_LLVM_DYLIB`` option.

**LLVM_ABI_BREAKING_CHECKS**:STRING
Used to decide if LLVM should be built with ABI breaking checks or
not.  Allowed values are `WITH_ASSERTS` (default), `FORCE_ON` and
`FORCE_OFF`.  `WITH_ASSERTS` turns on ABI breaking checks in an
assertion enabled build.  `FORCE_ON` (`FORCE_OFF`) turns them on
(off) irrespective of whether normal (`NDEBUG`-based) assertions are
enabled or not.  A version of LLVM built with ABI breaking checks
is not ABI compatible with a version built without it.

not.  Allowed values are 

-based) assertions are

**LLVM_APPEND_VC_REV**:BOOL
Embed version control revision info (Git revision id).
The version info is provided by the ``LLVM_REVISION`` macro in
``llvm/include/llvm/Support/VCSRevision.h``. Developers using git who don't
need revision info can disable this option to avoid re-linking most binaries
after a branch switch. Defaults to ON.

The version info is provided by the 

. Developers using git who don’t

. Developers using git who don't

**LLVM_BUILD_32_BITS**:BOOL
Build 32-bit executables and libraries on 64-bit systems. This option is
available only on some 64-bit Unix systems. Defaults to OFF.

**LLVM_BUILD_BENCHMARKS**:BOOL
Adds benchmarks to the list of default targets. Defaults to OFF.

**LLVM_BUILD_DOCS**:BOOL
Adds all *enabled* documentation targets (i.e. Doxgyen and Sphinx targets) as
dependencies of the default build targets.  This results in all of the (enabled)
documentation targets being as part of a normal build.  If the ``install``
target is run then this also enables all built documentation targets to be
installed. Defaults to OFF.  To enable a particular documentation target, see
see LLVM_ENABLE_SPHINX and LLVM_ENABLE_DOXYGEN.

 documentation targets (i.e. Doxgyen and Sphinx targets) as
documentation targets being as part of a normal build.  If the 

**LLVM_BUILD_EXAMPLES**:BOOL
Build LLVM examples. Defaults to OFF. Targets for building each example are
generated in any case. See documentation for *LLVM_BUILD_TOOLS* above for more
details.

details.

generated in any case. See documentation for 

**LLVM_BUILD_INSTRUMENTED_COVERAGE**:BOOL
If enabled, `source-based code coverage
<https://clang.llvm.org/docs/SourceBasedCodeCoverage.html>`_ instrumentation
is enabled while building llvm. If CMake can locate the code coverage
scripts and the llvm-cov and llvm-profdata tools that pair to your compiler,
the build will also generate the `generate-coverage-report` target to generate
the code coverage report for LLVM, and the `clear-profile-data` utility target
to delete captured profile data. See documentation for
*LLVM_CODE_COVERAGE_TARGETS* and *LLVM_COVERAGE_SOURCE_DIRS* for more
information on configuring code coverage reports.

`source-based code coverage
<https://clang.llvm.org/docs/SourceBasedCodeCoverage.html>`_

 instrumentation
the build will also generate the 

 utility target

**LLVM_CODE_COVERAGE_TARGETS**:STRING
If set to a semicolon separated list of targets, those targets will be used
to drive the code coverage reports. If unset, the target list will be
constructed using the LLVM build's CMake export list.

constructed using the LLVM build’s CMake export list.

**LLVM_COVERAGE_SOURCE_DIRS**:STRING
If set to a semicolon separated list of directories, the coverage reports
will limit code coverage summaries to just the listed directories. If unset,
coverage reports will include all sources identified by the tooling.

**LLVM_BUILD_LLVM_DYLIB**:BOOL
If enabled, the target for building the libLLVM shared library is added.
This library contains all of LLVM's components in a single shared library.
Defaults to OFF. This cannot be used in conjunction with BUILD_SHARED_LIBS.
Tools will only be linked to the libLLVM shared library if LLVM_LINK_LLVM_DYLIB
is also ON.
The components in the library can be customised by setting LLVM_DYLIB_COMPONENTS
to a list of the desired components.
This option is not available on Windows.

is also ON.

This library contains all of LLVM’s components in a single shared library.
is also ON.

**LLVM_BUILD_TESTS**:BOOL
Include LLVM unit tests in the 'all' build target. Defaults to OFF. Targets
for building each unit test are generated in any case. You can build a
specific unit test using the targets defined under *unittests*, such as
ADTTests, IRTests, SupportTests, etc. (Search for ``add_llvm_unittest`` in
the subdirectories of *unittests* for a complete list of unit tests.) It is
possible to build all unit tests with the target *UnitTests*.

Include LLVM unit tests in the ‘all’ build target. Defaults to OFF. Targets
specific unit test using the targets defined under 

 for a complete list of unit tests.) It is
possible to build all unit tests with the target 

**LLVM_BUILD_TOOLS**:BOOL
Build LLVM tools. Defaults to ON. Targets for building each tool are generated
in any case. You can build a tool separately by invoking its target. For
example, you can build *llvm-as* with a Makefile-based system by executing *make
llvm-as* at the root of your build directory.

example, you can build 

**LLVM_CCACHE_BUILD**:BOOL
If enabled and the ``ccache`` program is available, then LLVM will be
built using ``ccache`` to speed up rebuilds of LLVM and its components.
Defaults to OFF.  The size and location of the cache maintained
by ``ccache`` can be adjusted via the LLVM_CCACHE_MAXSIZE and LLVM_CCACHE_DIR
options, which are passed to the CCACHE_MAXSIZE and CCACHE_DIR environment
variables, respectively.

 to speed up rebuilds of LLVM and its components.
by 

 can be adjusted via the LLVM_CCACHE_MAXSIZE and LLVM_CCACHE_DIR

**LLVM_CREATE_XCODE_TOOLCHAIN**:BOOL
macOS Only: If enabled CMake will generate a target named
'install-xcode-toolchain'. This target will create a directory at
$CMAKE_INSTALL_PREFIX/Toolchains containing an xctoolchain directory which can
be used to override the default system tools.

‘install-xcode-toolchain’. This target will create a directory at

**LLVM_DOXYGEN_QCH_FILENAME**:STRING
The filename of the Qt Compressed Help file that will be generated when
``-DLLVM_ENABLE_DOXYGEN=ON`` and
``-DLLVM_ENABLE_DOXYGEN_QT_HELP=ON`` are given. Defaults to
``org.llvm.qch``.
This option is only useful in combination with
``-DLLVM_ENABLE_DOXYGEN_QT_HELP=ON``;
otherwise it has no effect.

**LLVM_DOXYGEN_QHELPGENERATOR_PATH**:STRING
The path to the ``qhelpgenerator`` executable. Defaults to whatever CMake's
``find_program()`` can find. This option is only useful in combination with
``-DLLVM_ENABLE_DOXYGEN_QT_HELP=ON``; otherwise it has no
effect.

effect.

**LLVM_DOXYGEN_QHP_CUST_FILTER_NAME**:STRING
See `Qt Help Project`_ for
more information. Defaults to the CMake variable ``${PACKAGE_STRING}`` which
is a combination of the package name and version string. This filter can then
be used in Qt Creator to select only documentation from LLVM when browsing
through all the help files that you might have loaded. This option is only
useful in combination with ``-DLLVM_ENABLE_DOXYGEN_QT_HELP=ON``;

 which
useful in combination with 

.. _Qt Help Project: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-filters

**LLVM_DOXYGEN_QHP_NAMESPACE**:STRING
Namespace under which the intermediate Qt Help Project file lives. See `Qt
Help Project`_
for more information. Defaults to "org.llvm". This option is only useful in
combination with ``-DLLVM_ENABLE_DOXYGEN_QT_HELP=ON``; otherwise
it has no effect.

Namespace under which the intermediate Qt Help Project file lives. See 

for more information. Defaults to “org.llvm”. This option is only useful in
combination with 

**LLVM_DOXYGEN_SVG**:BOOL
Uses .svg files instead of .png files for graphs in the Doxygen output.
Defaults to OFF.

**LLVM_ENABLE_ASSERTIONS**:BOOL
Enables code assertions. Defaults to ON if and only if ``CMAKE_BUILD_TYPE``
is *Debug*.

**LLVM_ENABLE_BINDINGS**:BOOL
If disabled, do not try to build the OCaml and go bindings.

**LLVM_ENABLE_DIA_SDK**:BOOL
Enable building with MSVC DIA SDK for PDB debugging support. Available
only with MSVC. Defaults to ON.

**LLVM_ENABLE_DOXYGEN**:BOOL
Enables the generation of browsable HTML documentation using doxygen.

**LLVM_ENABLE_DOXYGEN_QT_HELP**:BOOL
Enables the generation of a Qt Compressed Help file. Defaults to OFF.
This affects the make target ``doxygen-llvm``. When enabled, apart from
the normal HTML output generated by doxygen, this will produce a QCH file
named ``org.llvm.qch``. You can then load this file into Qt Creator.
This option is only useful in combination with ``-DLLVM_ENABLE_DOXYGEN=ON``;
otherwise this has no effect.

This affects the make target 

. When enabled, apart from
named 

. You can then load this file into Qt Creator.
This option is only useful in combination with 

**LLVM_ENABLE_EH**:BOOL
Build LLVM with exception-handling support. This is necessary if you wish to
link against LLVM libraries and make use of C++ exceptions in your own code
that need to propagate through LLVM code. Defaults to OFF.

**LLVM_ENABLE_EXPENSIVE_CHECKS**:BOOL
Enable additional time/memory expensive checking. Defaults to OFF.

**LLVM_ENABLE_FFI**:BOOL
Indicates whether the LLVM Interpreter will be linked with the Foreign Function
Interface library (libffi) in order to enable calling external functions.
If the library or its headers are installed in a custom
location, you can also set the variables FFI_INCLUDE_DIR and
FFI_LIBRARY_DIR to the directories where ffi.h and libffi.so can be found,
respectively. Defaults to OFF.

**LLVM_ENABLE_IDE**:BOOL
Tell the build system that an IDE is being used. This in turn disables the
creation of certain convenience build system targets, such as the various
``install-*`` and ``check-*`` targets, since IDEs don't always deal well with
a large number of targets. This is usually autodetected, but it can be
configured manually to explicitly control the generation of those targets. One
scenario where a manual override may be desirable is when using Visual Studio
2017's CMake integration, which would not be detected as an IDE otherwise.

 targets, since IDEs don’t always deal well with
2017’s CMake integration, which would not be detected as an IDE otherwise.

 targets, since IDEs don't always deal well with

**LLVM_ENABLE_LIBCXX**:BOOL
If the host compiler and linker supports the stdlib flag, -stdlib=libc++ is
passed to invocations of both so that the project is built using libc++
instead of stdlibc++. Defaults to OFF.

**LLVM_ENABLE_LIBPFM**:BOOL
Enable building with libpfm to support hardware counter measurements in LLVM
tools.
Defaults to ON.

tools.

**LLVM_ENABLE_LLD**:BOOL
This option is equivalent to `-DLLVM_USE_LINKER=lld`, except during a 2-stage
build where a dependency is added from the first stage to the second ensuring
that lld is built before stage2 begins.

, except during a 2-stage

**LLVM_ENABLE_LTO**:STRING
Add ``-flto`` or ``-flto=`` flags to the compile and link command
lines, enabling link-time optimization. Possible values are ``Off``,
``On``, ``Thin`` and ``Full``. Defaults to OFF.

 flags to the compile and link command
lines, enabling link-time optimization. Possible values are 

**LLVM_ENABLE_MODULES**:BOOL
Compile with `Clang Header Modules
<https://clang.llvm.org/docs/Modules.html>`_.

`Clang Header Modules
<https://clang.llvm.org/docs/Modules.html>`_

**LLVM_ENABLE_PEDANTIC**:BOOL
Enable pedantic mode. This disables compiler-specific extensions, if
possible. Defaults to ON.

**LLVM_ENABLE_PIC**:BOOL
Add the ``-fPIC`` flag to the compiler command-line, if the compiler supports
this flag. Some systems, like Windows, do not need this flag. Defaults to ON.

 flag to the compiler command-line, if the compiler supports

Semicolon-separated list of projects to build, or *all* for building all
(clang, libcxx, libcxxabi, lldb, compiler-rt, lld, polly, etc) projects.
This flag assumes that projects are checked out side-by-side and not nested,
i.e. clang needs to be in parallel of llvm instead of nested in `llvm/tools`.
This feature allows to have one build for only LLVM and another for clang+llvm
using the same source checkout.
The full list is:
``clang;clang-tools-extra;compiler-rt;cross-project-tests;libc;libclc;libcxx;libcxxabi;libunwind;lld;lldb;openmp;parallel-libs;polly;pstl``

 for building all
i.e. clang needs to be in parallel of llvm instead of nested in 

.

**LLVM_ENABLE_RUNTIMES**:STRING
Build libc++, libc++abi or other projects using that a just-built compiler.
This is the correct way to build libc++ when putting together a toolchain.
It will build the builtins separately from the other runtimes to preserve
correct dependency ordering.
Note: the list should not have duplicates with `LLVM_ENABLE_PROJECTS`.
``compiler-rt;libc;libcxx;libcxxabi;libunwind;openmp``
To enable all of them, use:
``LLVM_ENABLE_RUNTIMES=all``

Note: the list should not have duplicates with 

**LLVM_ENABLE_RTTI**:BOOL
Build LLVM with run-time type information. Defaults to OFF.

**LLVM_ENABLE_SPHINX**:BOOL
If specified, CMake will search for the ``sphinx-build`` executable and will make
the ``SPHINX_OUTPUT_HTML`` and ``SPHINX_OUTPUT_MAN`` CMake options available.

**LLVM_ENABLE_THREADS**:BOOL
Build with threads support, if available. Defaults to ON.

**LLVM_ENABLE_UNWIND_TABLES**:BOOL
Enable unwind tables in the binary.  Disabling unwind tables can reduce the
size of the libraries.  Defaults to ON.

**LLVM_ENABLE_WARNINGS**:BOOL
Enable all compiler warnings. Defaults to ON.

**LLVM_ENABLE_WERROR**:BOOL
Stop and fail the build, if a compiler warning is triggered. Defaults to OFF.

**LLVM_ENABLE_Z3_SOLVER**:BOOL
If enabled, the Z3 constraint solver is activated for the Clang static analyzer.
A recent version of the z3 library needs to be available on the system.

**LLVM_ENABLE_ZLIB**:BOOL
Enable building with zlib to support compression/uncompression in LLVM tools.

**LLVM_EXPERIMENTAL_TARGETS_TO_BUILD**:STRING
Semicolon-separated list of experimental targets to build and linked into
llvm. This will build the experimental target without needing it to add to the
list of all the targets available in the LLVM's main CMakeLists.txt.

list of all the targets available in the LLVM’s main CMakeLists.txt.

**LLVM_EXTERNAL_{CLANG,LLD,POLLY}_SOURCE_DIR**:PATH
These variables specify the path to the source directory for the external
LLVM projects Clang, lld, and Polly, respectively, relative to the top-level
source directory.  If the in-tree subdirectory for an external project
exists (e.g., llvm/tools/clang for Clang), then the corresponding variable
will not be used.  If the variable for an external project does not point
to a valid path, then that project will not be built.

**LLVM_EXTERNAL_PROJECTS**:STRING
Semicolon-separated list of additional external projects to build as part of
llvm. For each project LLVM_EXTERNAL_<NAME>_SOURCE_DIR have to be specified
with the path for the source code of the project. Example:
``-DLLVM_EXTERNAL_PROJECTS="Foo;Bar"
-DLLVM_EXTERNAL_FOO_SOURCE_DIR=/src/foo
-DLLVM_EXTERNAL_BAR_SOURCE_DIR=/src/bar``.

**LLVM_EXTERNALIZE_DEBUGINFO**:BOOL
Generate dSYM files and strip executables and libraries (Darwin Only).

**LLVM_FORCE_USE_OLD_TOOLCHAIN**:BOOL
If enabled, the compiler and standard library versions won't be checked. LLVM
may not compile at all, or might fail at runtime due to known bugs in these
toolchains.

If enabled, the compiler and standard library versions won’t be checked. LLVM

**LLVM_INCLUDE_BENCHMARKS**:BOOL
Generate build targets for the LLVM benchmarks. Defaults to ON.

**LLVM_INCLUDE_EXAMPLES**:BOOL
Generate build targets for the LLVM examples. Defaults to ON. You can use this
option to disable the generation of build targets for the LLVM examples.

**LLVM_INCLUDE_TESTS**:BOOL
Generate build targets for the LLVM unit tests. Defaults to ON. You can use
this option to disable the generation of build targets for the LLVM unit
tests.

tests.

**LLVM_INCLUDE_TOOLS**:BOOL
Generate build targets for the LLVM tools. Defaults to ON. You can use this
option to disable the generation of build targets for the LLVM tools.

**LLVM_INSTALL_BINUTILS_SYMLINKS**:BOOL
Install symlinks from the binutils tool names to the corresponding LLVM tools.
For example, ar will be symlinked to llvm-ar.

**LLVM_INSTALL_CCTOOLS_SYMLINKS**:BOOL
Install symliks from the cctools tool names to the corresponding LLVM tools.
For example, lipo will be symlinked to llvm-lipo.

**LLVM_INSTALL_OCAMLDOC_HTML_DIR**:STRING
The path to install OCamldoc-generated HTML documentation to. This path can
either be absolute or relative to the CMAKE_INSTALL_PREFIX. Defaults to
`share/doc/llvm/ocaml-html`.

**LLVM_INSTALL_SPHINX_HTML_DIR**:STRING
The path to install Sphinx-generated HTML documentation to. This path can
`share/doc/llvm/html`.

**LLVM_INSTALL_UTILS**:BOOL
If enabled, utility binaries like ``FileCheck`` and ``not`` will be installed
to CMAKE_INSTALL_PREFIX.

**LLVM_INTEGRATED_CRT_ALLOC**:PATH
On Windows, allows embedding a different C runtime allocator into the LLVM
tools and libraries. Using a lock-free allocator such as the ones listed below
greatly decreases ThinLTO link time by about an order of magnitude. It also
midly improves Clang build times, by about 5-10%. At the moment, rpmalloc,
snmalloc and mimalloc are supported. Use the path to `git clone` to select
the respective allocator, for example:

  $ D:\git> git clone https://github.com/mjansson/rpmalloc
  $ D:\llvm-project> cmake ... -DLLVM_INTEGRATED_CRT_ALLOC=D:\git\rpmalloc

This flag needs to be used along with the static CRT, ie. if building the
Release target, add -DLLVM_USE_CRT_RELEASE=MT.

snmalloc and mimalloc are supported. Use the path to 

$ D:\git> git clone https://github.com/mjansson/rpmalloc
$ D:\llvm-project> cmake ... -DLLVM_INTEGRATED_CRT_ALLOC=D:\git\rpmalloc

**LLVM_INSTALL_DOXYGEN_HTML_DIR**:STRING
The path to install Doxygen-generated HTML documentation to. This path can
`share/doc/llvm/doxygen-html`.

**LLVM_LINK_LLVM_DYLIB**:BOOL
If enabled, tools will be linked with the libLLVM shared library. Defaults
to OFF. Setting LLVM_LINK_LLVM_DYLIB to ON also sets LLVM_BUILD_LLVM_DYLIB
to ON.

to ON.

**LLVM_LIT_ARGS**:STRING
Arguments given to lit.  ``make check`` and ``make clang-test`` are affected.
By default, ``'-sv --no-progress-bar'`` on Visual C++ and Xcode, ``'-sv'`` on
others.

others.

**LLVM_LIT_TOOLS_DIR**:PATH
The path to GnuWin32 tools for tests. Valid on Windows host.  Defaults to
the empty string, in which case lit will look for tools needed for tests
(e.g. ``grep``, ``sort``, etc.) in your %PATH%. If GnuWin32 is not in your
%PATH%, then you can set this variable to the GnuWin32 directory so that
lit can find tools needed for tests in that directory.

(e.g. 

, etc.) in your %PATH%. If GnuWin32 is not in your

**LLVM_OPTIMIZED_TABLEGEN**:BOOL
If enabled and building a debug or asserts build the CMake build system will
generate a Release build tree to build a fully optimized tablegen for use
during the build. Enabling this option can significantly speed up build times
especially when building LLVM in Debug configurations.

**LLVM_PARALLEL_COMPILE_JOBS**:STRING
Define the maximum number of concurrent compilation jobs.

**LLVM_PARALLEL_LINK_JOBS**:STRING
Define the maximum number of concurrent link jobs.

**LLVM_PROFDATA_FILE**:PATH
Path to a profdata file to pass into clang's -fprofile-instr-use flag. This
can only be specified if you're building with clang.

Path to a profdata file to pass into clang’s -fprofile-instr-use flag. This
can only be specified if you’re building with clang.

**LLVM_REVERSE_ITERATION**:BOOL
If enabled, all supported unordered llvm containers would be iterated in
reverse order. This is useful for uncovering non-determinism caused by
iteration of unordered containers.

**LLVM_STATIC_LINK_CXX_STDLIB**:BOOL
Statically link to the C++ standard library if possible. This uses the flag
"-static-libstdc++", but a Clang host compiler will statically link to libc++
if used in conjunction with the **LLVM_ENABLE_LIBCXX** flag. Defaults to OFF.

“-static-libstdc++”, but a Clang host compiler will statically link to libc++
if used in conjunction with the 

**LLVM_TABLEGEN**:STRING
Full path to a native TableGen executable (usually named ``llvm-tblgen``). This is
intended for cross-compiling: if the user sets this variable, no native
TableGen will be created.

). This is

**LLVM_TARGET_ARCH**:STRING
LLVM target to use for native code generation. This is required for JIT
generation. It defaults to "host", meaning that it shall pick the architecture
of the machine where LLVM is being built. If you are cross-compiling, set it
to the target architecture name.

generation. It defaults to “host”, meaning that it shall pick the architecture

Semicolon-separated list of targets to build, or *all* for building all
targets. Case-sensitive. Defaults to *all*. Example:
``-DLLVM_TARGETS_TO_BUILD="X86;PowerPC"``.

**LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN**:BOOL
If enabled, the compiler version check will only warn when using a toolchain
which is about to be deprecated, instead of emitting an error.

**LLVM_UBSAN_FLAGS**:STRING
Defines the set of compile flags used to enable UBSan. Only used if
``LLVM_USE_SANITIZER`` contains ``Undefined``. This can be used to override
the default set of UBSan flags.

**LLVM_USE_CRT_{target}**:STRING
On Windows, tells which version of the C runtime library (CRT) should be used.
For example, -DLLVM_USE_CRT_RELEASE=MT would statically link the CRT into the
LLVM tools and library.

**LLVM_USE_INTEL_JITEVENTS**:BOOL
Enable building support for Intel JIT Events API. Defaults to OFF.

Add ``-fuse-ld={name}`` to the link invocation. The possible value depend on
your compiler, for clang the value can be an absolute path to your custom
linker, otherwise clang will prefix the name with ``ld.`` and apply its usual
search. For example to link LLVM with the Gold linker, cmake can be invoked
with ``-DLLVM_USE_LINKER=gold``.

 to the link invocation. The possible value depend on
linker, otherwise clang will prefix the name with 

 and apply its usual
with 

**LLVM_USE_NEWPM**:BOOL
If enabled, use the experimental new pass manager.

**LLVM_USE_OPROFILE**:BOOL
Enable building OProfile JIT support. Defaults to OFF.

**LLVM_USE_PERF**:BOOL
Enable building support for Perf (linux profiling tool) JIT support. Defaults to OFF.

**LLVM_USE_RELATIVE_PATHS_IN_FILES**:BOOL
Rewrite absolute source paths in sources and debug info to relative ones. The
source prefix can be adjusted via the LLVM_SOURCE_PREFIX variable.

**LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO**:BOOL
Rewrite absolute source paths in debug info to relative ones. The source prefix
can be adjusted via the LLVM_SOURCE_PREFIX variable.

**LLVM_USE_SANITIZER**:STRING
Define the sanitizer used to build LLVM binaries and tests. Possible values
are ``Address``, ``Memory``, ``MemoryWithOrigins``, ``Undefined``, ``Thread``,
``DataFlow``, and ``Address;Undefined``. Defaults to empty string.

are 

**SPHINX_EXECUTABLE**:STRING
The path to the ``sphinx-build`` executable detected by CMake.
For installation instructions, see
https://www.sphinx-doc.org/en/master/usage/installation.html

 executable detected by CMake.

**SPHINX_OUTPUT_HTML**:BOOL
If enabled (and ``LLVM_ENABLE_SPHINX`` is enabled) then the targets for
building the documentation as html are added (but not built by default unless
``LLVM_BUILD_DOCS`` is enabled). There is a target for each project in the
source tree that uses sphinx (e.g.  ``docs-llvm-html``, ``docs-clang-html``
and ``docs-lld-html``). Defaults to ON.

 is enabled) then the targets for

 is enabled). There is a target for each project in the
source tree that uses sphinx (e.g.  

**SPHINX_OUTPUT_MAN**:BOOL
If enabled (and ``LLVM_ENABLE_SPHINX`` is enabled) the targets for building
the man pages are added (but not built by default unless ``LLVM_BUILD_DOCS``
is enabled). Currently the only target added is ``docs-llvm-man``. Defaults
to ON.

to ON.

 is enabled) the targets for building
the man pages are added (but not built by default unless 

**SPHINX_WARNINGS_AS_ERRORS**:BOOL
If enabled then sphinx documentation warnings will be treated as
errors. Defaults to ON.

Recently LLVM and Clang have been adding some more complicated build system
features. Utilizing these new features often involves a complicated chain of
CMake variables passed on the command line. Clang provides a collection of CMake
cache scripts to make these features more approachable.

CMake cache scripts are processed in an isolated scope, only cached variables
remain set when the main configuration runs. CMake cached variables do not reset
variables that are already set unless the FORCE option is specified.

Order of command line arguments is important

- -D arguments specified before -C are set before the cache is processed and
  can be read inside the cache file
- -D arguments specified after -C are set after the cache is processed and
  are unset inside the cache file

-D arguments specified before -C are set before the cache is processed and
can be read inside the cache file

-D arguments specified after -C are set after the cache is processed and
are unset inside the cache file

CMAKE_TOOLCHAIN_FILE is evaluated after both the cache file and the command
line arguments

It is recommended that all -D options should be specified *before* -C

For more information about some of the advanced build configurations supported
via Cache files see :doc:`AdvancedBuilds`.

via Cache files see 

Testing is performed when the *check-all* target is built. For instance, if you are
using Makefiles, execute this command in the root of your build directory:

 target is built. For instance, if you are

On Visual Studio, you may run tests by building the project "check-all".
For more information about testing, see the :doc:`TestingGuide`.

On Visual Studio, you may run tests by building the project “check-all”.
For more information about testing, see the 

See `this wiki page <https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/CrossCompiling>`_ for
generic instructions on how to cross-compile with CMake. It goes into detailed
explanations and may seem daunting, but it is not. On the wiki page there are
several examples including toolchain files. Go directly to the
``Information how to set up various cross compiling toolchains`` section
for a quick solution.

`this wiki page <https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/CrossCompiling>`_

 for

``Information how to set up various cross compiling toolchains``

Also see the `LLVM-related variables`_ section for variables used when
cross-compiling.

From LLVM 3.5 onwards the CMake build system exports LLVM libraries as
importable CMake targets. This means that clients of LLVM can now reliably use
CMake to develop their own LLVM-based projects against an installed version of
LLVM regardless of how it was built.

Here is a simple example of a CMakeLists.txt file that imports the LLVM libraries
and uses them to build a simple application ``simple-tool``.

and uses them to build a simple application 

cmake_minimum_required(VERSION 3.13.4)
project(SimpleProject)

find_package(LLVM REQUIRED CONFIG)

message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}")
message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}")

# Set your project compile flags.
# E.g. if using the C++ header files
# you will need to enable C++11 support
# for your compiler.

include_directories(${LLVM_INCLUDE_DIRS})
separate_arguments(LLVM_DEFINITIONS_LIST NATIVE_COMMAND ${LLVM_DEFINITIONS})
add_definitions(${LLVM_DEFINITIONS_LIST})

# Now build our tools
add_executable(simple-tool tool.cpp)

# Find the libraries that correspond to the LLVM components
# that we wish to use
llvm_map_components_to_libnames(llvm_libs support core irreader)

# Link against LLVM libraries
target_link_libraries(simple-tool ${llvm_libs})

The ``find_package(...)`` directive when used in CONFIG mode (as in the above
example) will look for the ``LLVMConfig.cmake`` file in various locations (see
cmake manual for details).  It creates a ``LLVM_DIR`` cache entry to save the
directory where ``LLVMConfig.cmake`` is found or allows the user to specify the
directory (e.g. by passing ``-DLLVM_DIR=/usr/lib/cmake/llvm`` to
the ``cmake`` command or by setting it directly in ``ccmake`` or ``cmake-gui``).

 directive when used in CONFIG mode (as in the above
example) will look for the 

 file in various locations (see
cmake manual for details).  It creates a 

 is found or allows the user to specify the
directory (e.g. by passing 

``<INSTALL_PREFIX>/lib/cmake/llvm/LLVMConfig.cmake`` where
``<INSTALL_PREFIX>`` is the install prefix of an installed version of LLVM.
On Linux typically this is ``/usr/lib/cmake/llvm/LLVMConfig.cmake``.

 is the install prefix of an installed version of LLVM.
On Linux typically this is 

``<LLVM_BUILD_ROOT>/lib/cmake/llvm/LLVMConfig.cmake`` where
``<LLVM_BUILD_ROOT>`` is the root of the LLVM build tree. **Note: this is only
available when building LLVM with CMake.**

If LLVM is installed in your operating system's normal installation prefix (e.g.
on Linux this is usually ``/usr/``) ``find_package(LLVM ...)`` will
automatically find LLVM if it is installed correctly. If LLVM is not installed
or you wish to build directly against the LLVM build tree you can use
``LLVM_DIR`` as previously mentioned.

If LLVM is installed in your operating system’s normal installation prefix (e.g.
on Linux this is usually 

 will

The ``LLVMConfig.cmake`` file sets various useful variables. Notable variables
include

``LLVM_CMAKE_DIR``
The path to the LLVM CMake directory (i.e. the directory containing
LLVMConfig.cmake).

``LLVM_DEFINITIONS``
A list of preprocessor defines that should be used when building against LLVM.

``LLVM_ENABLE_ASSERTIONS``
This is set to ON if LLVM was built with assertions, otherwise OFF.

``LLVM_ENABLE_EH``
This is set to ON if LLVM was built with exception handling (EH) enabled,
otherwise OFF.

``LLVM_ENABLE_RTTI``
This is set to ON if LLVM was built with run time type information (RTTI),

``LLVM_INCLUDE_DIRS``
A list of include paths to directories containing LLVM header files.

``LLVM_PACKAGE_VERSION``
The LLVM version. This string can be used with CMake conditionals, e.g., ``if
(${LLVM_PACKAGE_VERSION} VERSION_LESS "3.5")``.

The LLVM version. This string can be used with CMake conditionals, e.g., 

``LLVM_TOOLS_BINARY_DIR``
The path to the directory containing the LLVM tools (e.g. ``llvm-as``).

Notice that in the above example we link ``simple-tool`` against several LLVM
libraries. The list of libraries is determined by using the
``llvm_map_components_to_libnames()`` CMake function. For a list of available
components look at the output of running ``llvm-config --components``.

 against several LLVM

 CMake function. For a list of available
components look at the output of running 

Note that for LLVM < 3.5 ``llvm_map_components_to_libraries()`` was
used instead of ``llvm_map_components_to_libnames()``. This is now deprecated
and will be removed in a future version of LLVM.

. This is now deprecated

It is possible to develop LLVM passes out of LLVM's source tree (i.e. against an
installed or built LLVM). An example of a project layout is provided below.

It is possible to develop LLVM passes out of LLVM’s source tree (i.e. against an

<project dir>/
    |
    CMakeLists.txt
    <pass name>/
        |
        CMakeLists.txt
        Pass.cpp
        ...

add_subdirectory(<pass name>)

Note if you intend for this pass to be merged into the LLVM source tree at some
point in the future it might make more sense to use LLVM's internal
``add_llvm_library`` function with the MODULE argument instead by...

point in the future it might make more sense to use LLVM’s internal

Adding the following to ``<project dir>/CMakeLists.txt`` (after
``find_package(LLVM ...)``)

list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}")
include(AddLLVM)

And then changing ``<project dir>/<pass name>/CMakeLists.txt`` to

When you are done developing your pass, you may wish to integrate it
into the LLVM source tree. You can achieve it in two easy steps:

Copying ``<pass name>`` folder into ``<LLVM root>/lib/Transform`` directory.

Adding ``add_subdirectory(<pass name>)`` line into
``<LLVM root>/lib/Transform/CMakeLists.txt``.

**LLVM_COMPILER_JOBS**:STRING
Specifies the maximum number of parallel compiler jobs to use per project
when building with msbuild or Visual Studio. Only supported for the Visual
Studio 2010 CMake generator. 0 means use all processors. Default is 0.

Duplicate implicit target name: "frequently used llvm-related variables".

Duplicate implicit target name: “frequently used llvm-related variables”.

This section explains basic aspects of CMake
which you may need in your day-to-day usage.

CMake comes with extensive documentation, in the form of html files, and as
online help accessible via the ``cmake`` executable itself. Execute ``cmake
--help`` for further help options.

online help accessible via the 

CMake allows you to specify a build tool (e.g., GNU make, Visual Studio,
or Xcode). If not specified on the command line, CMake tries to guess which
build tool to use, based on your environment. Once it has identified your
build tool, CMake uses the corresponding *Generator* to create files for your
build tool (e.g., Makefiles or Visual Studio or Xcode project files). You can
explicitly specify the generator with the command line option ``-G "Name of the
generator"``. To see a list of the available generators on your system, execute

build tool, CMake uses the corresponding 

 to create files for your
explicitly specify the generator with the command line option 

. To see a list of the available generators on your system, execute

Generators' names are case-sensitive, and may contain spaces. For this reason,
you should enter them exactly as they are listed in the ``cmake --help``
output, in quotes. For example, to generate project files specifically for
Visual Studio 12, you can execute:

Generators’ names are case-sensitive, and may contain spaces. For this reason,
you should enter them exactly as they are listed in the 

For a given development platform there can be more than one adequate
generator. If you use Visual Studio, "NMake Makefiles" is a generator you can use
for building with NMake. By default, CMake chooses the most specific generator
supported by your development environment. If you want an alternative generator,
you must tell this to CMake with the ``-G`` option.

generator. If you use Visual Studio, “NMake Makefiles” is a generator you can use
you must tell this to CMake with the 

This document describes the CommandLine argument processing library.  It will
show you how to use it, and what it can do.  The CommandLine library uses a
declarative approach to specifying the command line options that your program
takes.  By default, these options declarations implicitly hold the value parsed
for the option declared (of course this `can be changed`_).

for the option declared (of course this 

Although there are a **lot** of command line argument parsing libraries out
there in many different languages, none of them fit well with what I needed.  By
looking at the features and problems of other libraries, I designed the
CommandLine library to have the following features:

 of command line argument parsing libraries out

Speed: The CommandLine library is very quick and uses little resources.  The
parsing time of the library is directly proportional to the number of
arguments parsed, not the number of options recognized.  Additionally,
command line argument values are captured transparently into user defined
global variables, which can be accessed like any other variable (and with the
same performance).

Type Safe: As a user of CommandLine, you don't have to worry about
remembering the type of arguments that you want (is it an int?  a string? a
bool? an enum?) and keep casting it around.  Not only does this help prevent
error prone constructs, it also leads to dramatically cleaner source code.

Type Safe: As a user of CommandLine, you don’t have to worry about

No subclasses required: To use CommandLine, you instantiate variables that
correspond to the arguments that you would like to capture, you don't
subclass a parser.  This means that you don't have to write **any**
boilerplate code.

correspond to the arguments that you would like to capture, you don’t
subclass a parser.  This means that you don’t have to write 

subclass a parser.  This means that you don't have to write 

Globally accessible: Libraries can specify command line arguments that are
automatically enabled in any tool that links to the library.  This is
possible because the application doesn't have to keep a list of arguments to
pass to the parser.  This also makes supporting `dynamically loaded options`_
trivial.

trivial.

possible because the application doesn’t have to keep a list of arguments to
pass to the parser.  This also makes supporting 

Cleaner: CommandLine supports enum and other types directly, meaning that
there is less error and more security built into the library.  You don't have
to worry about whether your integral command line argument accidentally got
assigned a value that is not valid for your enum type.

there is less error and more security built into the library.  You don’t have

Powerful: The CommandLine library supports many different types of arguments,
from simple `boolean flags`_ to `scalars arguments`_ (`strings`_,
`integers`_, `enums`_, `doubles`_), to `lists of arguments`_.  This is
possible because CommandLine is...

from simple 

Extensible: It is very simple to add a new argument type to CommandLine.
Simply specify the parser that you want to use with the command line option
when you declare it. `Custom parsers`_ are no problem.

when you declare it. 

Labor Saving: The CommandLine library cuts down on the amount of grunt work
that you, the user, have to do.  For example, it automatically provides a
``-help`` option that shows the available command line options for your tool.
Additionally, it does most of the basic correctness checking for you.

 option that shows the available command line options for your tool.

Capable: The CommandLine library can handle lots of different forms of
options often found in real programs.  For example, `positional`_ arguments,
``ls`` style `grouping`_ options (to allow processing '``ls -lad``'
naturally), ``ld`` style `prefix`_ options (to parse '``-lmalloc
-L/usr/lib``'), and interpreter style options.

options often found in real programs.  For example, 

This document will hopefully let you jump in and start using CommandLine in your
utility quickly and painlessly.  Additionally it should be a simple reference
manual to figure out how stuff works.

This section of the manual runs through a simple CommandLine'ification of a
basic compiler tool.  This is intended to show you how to jump into using the
CommandLine library in your own program, and show you some of the cool things it
can do.

This section of the manual runs through a simple CommandLine’ification of a
can do.

To start out, you need to include the CommandLine header file into your program:

Additionally, you need to add this as the first line of your main program:

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv);
  ...
}

... which actually parses the arguments and fills in the variable declarations.

… which actually parses the arguments and fills in the variable declarations.

Now that you are ready to support command line arguments, we need to tell the
system which ones we want, and what type of arguments they are.  The CommandLine
library uses a declarative syntax to model command line arguments with the
global variable declarations that capture the parsed values.  This means that
for every command line option that you would like to support, there should be a
global variable declaration to capture the result.  For example, in a compiler,
we would like to support the Unix-standard '``-o <filename>``' option to specify
where to put the output.  With the CommandLine library, this is represented like
this:

we would like to support the Unix-standard ‘

we would like to support the Unix-standard '

’ option to specify
this:

' option to specify
this:

cl::opt<string> OutputFilename("o", cl::desc("Specify output filename"), cl::value_desc("filename"));

This declares a global variable "``OutputFilename``" that is used to capture the
result of the "``o``" argument (first parameter).  We specify that this is a
simple scalar option by using the "``cl::opt``" template (as opposed to the
"``cl::list``" template), and tell the CommandLine library that the data
type that we are parsing is a string.

” argument (first parameter).  We specify that this is a
simple scalar option by using the “

" argument (first parameter).  We specify that this is a
simple scalar option by using the "

” template), and tell the CommandLine library that the data

" template), and tell the CommandLine library that the data

The second and third parameters (which are optional) are used to specify what to
output for the "``-help``" option.  In this case, we get a line that looks like
this:

output for the “

output for the "

USAGE: compiler [options]

OPTIONS:
  -h                - Alias for -help
  -help             - display available options (-help-hidden for more)
  -o <filename>     - Specify output filename

Because we specified that the command line option should parse using the
``string`` data type, the variable declared is automatically usable as a real
string in all contexts that a normal C++ string object may be used.  For
example:

 data type, the variable declared is automatically usable as a real
example:

...
std::ofstream Output(OutputFilename.c_str());
if (Output.good()) ...
...

There are many different options that you can use to customize the command line
option handling library, but the above example shows the general interface to
these options.  The options can be specified in any order, and are specified
with helper functions like `cl::desc(...)`_, so there are no positional
dependencies to remember.  The available options are discussed in detail in the
`Reference Guide`_.

with helper functions like 

, so there are no positional

Continuing the example, we would like to have our compiler take an input
filename as well as an output filename, but we do not want the input filename to
be specified with a hyphen (ie, not ``-filename.c``).  To support this style of
argument, the CommandLine library allows for `positional`_ arguments to be
specified for the program.  These positional arguments are filled with command
line parameters that are not in option form.  We use this feature like this:

be specified with a hyphen (ie, not 

).  To support this style of
argument, the CommandLine library allows for 

 arguments to be

cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));

This declaration indicates that the first positional argument should be treated
as the input filename.  Here we use the `cl::init`_ option to specify an initial
value for the command line option, which is used if the option is not specified
(if you do not specify a `cl::init`_ modifier for an option, then the default
constructor for the data type is used to initialize the value).  Command line
options default to being optional, so if we would like to require that the user
always specify an input filename, we would add the `cl::Required`_ flag, and we
could eliminate the `cl::init`_ modifier, like this:

as the input filename.  Here we use the 

 option to specify an initial
(if you do not specify a 

 modifier for an option, then the default
always specify an input filename, we would add the 

cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::Required);

Again, the CommandLine library does not require the options to be specified in
any particular order, so the above declaration is equivalent to:

cl::opt<string> InputFilename(cl::Positional, cl::Required, cl::desc("<input file>"));

By simply adding the `cl::Required`_ flag, the CommandLine library will
automatically issue an error if the argument is not specified, which shifts all
of the command line option verification code out of your application into the
library.  This is just one example of how using flags can alter the default
behaviour of the library, on a per-option basis.  By adding one of the
declarations above, the ``-help`` option synopsis is now extended to:

 flag, the CommandLine library will
declarations above, the 

USAGE: compiler [options] <input file>

OPTIONS:

In addition to input and output filenames, we would like the compiler example to
support three boolean flags: "``-f``" to force writing binary output to a
terminal, "``--quiet``" to enable quiet mode, and "``-q``" for backwards
compatibility with some of our users.  We can support these by declaring options
of boolean type like this:

support three boolean flags: “

support three boolean flags: "

” for backwards

" for backwards

cl::opt<bool> Force ("f", cl::desc("Enable binary output on terminals"));
cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
cl::opt<bool> Quiet2("q", cl::desc("Don't print informational messages"), cl::Hidden);

This does what you would expect: it declares three boolean variables
("``Force``", "``Quiet``", and "``Quiet2``") to recognize these options.  Note
that the "``-q``" option is specified with the "`cl::Hidden`_" flag.  This
modifier prevents it from being shown by the standard "``-help``" output (note
that it is still shown in the "``-help-hidden``" output).

(“

("

” flag.  This
modifier prevents it from being shown by the standard “

" flag.  This
modifier prevents it from being shown by the standard "

The CommandLine library uses a `different parser`_ for different data types.
For example, in the string case, the argument passed to the option is copied
literally into the content of the string variable... we obviously cannot do that
in the boolean case, however, so we must use a smarter parser.  In the case of
the boolean parser, it allows no options (in which case it assigns the value of
true to the variable), or it allows the values "``true``" or "``false``" to be
specified, allowing any of the following inputs:

 for different data types.
literally into the content of the string variable… we obviously cannot do that
true to the variable), or it allows the values “

true to the variable), or it allows the values "

compiler -f          # No value, 'Force' == true
compiler -f=true     # Value specified, 'Force' == true
compiler -f=TRUE     # Value specified, 'Force' == true
compiler -f=FALSE    # Value specified, 'Force' == false

... you get the idea.  The `bool parser`_ just turns the string values into
boolean values, and rejects things like '``compiler -f=foo``'.  Similarly, the
`float`_, `double`_, and `int`_ parsers work like you would expect, using the
'``strtol``' and '``strtod``' C library calls to parse the string value into the
specified data type.

 just turns the string values into
boolean values, and rejects things like ‘

boolean values, and rejects things like '

’ C library calls to parse the string value into the

' C library calls to parse the string value into the

OPTIONS:
  -f     - Enable binary output on terminals
  -o     - Override output filename
  -quiet - Don't print informational messages
  -help  - display available options (-help-hidden for more)

OPTIONS:
  -q     - Don't print informational messages

This brief example has shown you how to use the '`cl::opt`_' class to parse
simple scalar command line arguments.  In addition to simple scalar arguments,
the CommandLine library also provides primitives to support CommandLine option
`aliases`_, and `lists`_ of options.

’ class to parse

' class to parse

So far, the example works well, except for the fact that we need to check the
quiet condition like this now:

...
  if (!Quiet && !Quiet2) printInformationalMessage(...);
...

... which is a real pain!  Instead of defining two values for the same
condition, we can use the "`cl::alias`_" class to make the "``-q``" option an
**alias** for the "``-quiet``" option, instead of providing a value itself:

… which is a real pain!  Instead of defining two values for the same
condition, we can use the “

condition, we can use the "

cl::opt<bool> Force ("f", cl::desc("Overwrite output files"));
cl::alias     QuietA("q", cl::desc("Alias for -quiet"), cl::aliasopt(Quiet));

The third line (which is the only one we modified from above) defines a "``-q``"
alias that updates the "``Quiet``" variable (as specified by the `cl::aliasopt`_
modifier) whenever it is specified.  Because aliases do not hold state, the only
thing the program has to query is the ``Quiet`` variable now.  Another nice
feature of aliases is that they automatically hide themselves from the ``-help``
output (although, again, they are still visible in the ``-help-hidden output``).

The third line (which is the only one we modified from above) defines a “

The third line (which is the only one we modified from above) defines a "

thing the program has to query is the 

 variable now.  Another nice
feature of aliases is that they automatically hide themselves from the 

... which is much nicer!  The "`cl::alias`_" can be used to specify an
alternative name for any variable type, and has many uses.

” can be used to specify an

" can be used to specify an

So far we have seen how the CommandLine library handles builtin types like
``std::string``, ``bool`` and ``int``, but how does it handle things it doesn't
know about, like enums or '``int*``'s?

, but how does it handle things it doesn’t
know about, like enums or ‘

, but how does it handle things it doesn't
know about, like enums or '

The answer is that it uses a table-driven generic parser (unless you specify
your own parser, as described in the `Extension Guide`_).  This parser maps
literal strings to whatever type is required, and requires you to tell it what
this mapping should be.

your own parser, as described in the 

).  This parser maps

Let's say that we would like to add four optimization levels to our optimizer,
using the standard flags "``-g``", "``-O0``", "``-O1``", and "``-O2``".  We
could easily implement this with boolean options like above, but there are
several problems with this strategy:

Let’s say that we would like to add four optimization levels to our optimizer,
using the standard flags “

using the standard flags "

”.  We

".  We

A user could specify more than one of the options at a time, for example,
"``compiler -O3 -O2``".  The CommandLine library would not be able to catch
this erroneous input for us.

“

"

”.  The CommandLine library would not be able to catch

".  The CommandLine library would not be able to catch

We would have to test 4 different variables to see which ones are set.

This doesn't map to the numeric levels that we want... so we cannot easily
see if some level >= "``-O1``" is enabled.

This doesn’t map to the numeric levels that we want… so we cannot easily
see if some level >= “

see if some level >= "

To cope with these problems, we can use an enum value, and have the CommandLine
library fill it in with the appropriate level directly, which is used like this:

enum OptLevel {
  g, O1, O2, O3
};

cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
  cl::values(
    clEnumVal(g , "No optimizations, enable debugging"),
    clEnumVal(O1, "Enable trivial optimizations"),
    clEnumVal(O2, "Enable default optimizations"),
    clEnumVal(O3, "Enable expensive optimizations")));

...
  if (OptimizationLevel >= O2) doPartialRedundancyElimination(...);
...

This declaration defines a variable "``OptimizationLevel``" of the
"``OptLevel``" enum type.  This variable can be assigned any of the values that
are listed in the declaration.  The CommandLine library enforces that
the user can only specify one of the options, and it ensure that only valid enum
values can be specified.  The "``clEnumVal``" macros ensure that the command
line arguments matched the enum values.  With this option added, our help output
now is:

” enum type.  This variable can be assigned any of the values that
values can be specified.  The “

" enum type.  This variable can be assigned any of the values that
values can be specified.  The "

” macros ensure that the command
now is:

" macros ensure that the command
now is:

OPTIONS:
  Choose optimization level:
    -g          - No optimizations, enable debugging
    -O1         - Enable trivial optimizations
    -O2         - Enable default optimizations
    -O3         - Enable expensive optimizations
  -f            - Enable binary output on terminals
  -help         - display available options (-help-hidden for more)
  -o <filename> - Specify output filename
  -quiet        - Don't print informational messages

In this case, it is sort of awkward that flag names correspond directly to enum
names, because we probably don't want an enum definition named "``g``" in our
program.  Because of this, we can alternatively write this example like this:

names, because we probably don’t want an enum definition named “

names, because we probably don't want an enum definition named "

” in our

" in our

  Debug, O1, O2, O3
};

   clEnumValN(Debug, "g", "No optimizations, enable debugging"),
    clEnumVal(O1        , "Enable trivial optimizations"),
    clEnumVal(O2        , "Enable default optimizations"),
    clEnumVal(O3        , "Enable expensive optimizations")));

...
  if (OptimizationLevel == Debug) outputDebugInfo(...);
...

By using the "``clEnumValN``" macro instead of "``clEnumVal``", we can directly
specify the name that the flag should get.  In general a direct mapping is nice,
but sometimes you can't or don't want to preserve the mapping, which is when you
would use it.

”, we can directly
but sometimes you can’t or don’t want to preserve the mapping, which is when you

", we can directly

Another useful argument form is a named alternative style.  We shall use this
style in our compiler to specify different debug levels that can be used.
Instead of each debug level being its own switch, we want to support the
following options, of which only one can be specified at a time:
"``--debug-level=none``", "``--debug-level=quick``",
"``--debug-level=detailed``".  To do this, we use the exact same format as our
optimization level flags, but we also specify an option name.  For this case,
the code looks like this:

“

"

”.  To do this, we use the exact same format as our

".  To do this, we use the exact same format as our

enum DebugLev {
  nodebuginfo, quick, detailed
};

// Enable Debug Options to be specified on the command line
cl::opt<DebugLev> DebugLevel("debug_level", cl::desc("Set the debugging level:"),
    clEnumValN(nodebuginfo, "none", "disable debug information"),
     clEnumVal(quick,               "enable quick debug information"),
     clEnumVal(detailed,            "enable detailed debug information")));

This definition defines an enumerated command line variable of type "``enum
DebugLev``", which works exactly the same way as before.  The difference here is
just the interface exposed to the user of your program and the help output by
the "``-help``" option:

This definition defines an enumerated command line variable of type “

This definition defines an enumerated command line variable of type "

”, which works exactly the same way as before.  The difference here is
the “

", which works exactly the same way as before.  The difference here is
the "

OPTIONS:
  -debug_level  - Set the debugging level:
    =none       - disable debug information
    =quick      - enable quick debug information
    =detailed   - enable detailed debug information

Again, the only structural difference between the debug level declaration and
the optimization level declaration is that the debug level declaration includes
an option name (``"debug_level"``), which automatically changes how the library
processes the argument.  The CommandLine library supports both forms so that you
can choose the form most appropriate for your application.

an option name (

), which automatically changes how the library

Now that we have the standard run-of-the-mill argument types out of the way,
lets get a little wild and crazy.  Lets say that we want our optimizer to accept
a **list** of optimizations to perform, allowing duplicates.  For example, we
might want to run: "``compiler -dce -instsimplify -inline -dce -strip``".  In this
case, the order of the arguments and the number of appearances is very
important.  This is what the "``cl::list``" template is for.  First, start by
defining an enum of the optimizations that you would like to perform:

a 

 of optimizations to perform, allowing duplicates.  For example, we
might want to run: “

might want to run: "

”.  In this
important.  This is what the “

".  In this
important.  This is what the "

” template is for.  First, start by

" template is for.  First, start by

enum Opts {
  // 'inline' is a C++ keyword, so name it 'inlining'
  dce, instsimplify, inlining, strip
};

cl::list<Opts> OptimizationList(cl::desc("Available Optimizations:"),
    clEnumVal(dce               , "Dead Code Elimination"),
    clEnumVal(instsimplify      , "Instruction Simplification"),
   clEnumValN(inlining, "inline", "Procedure Integration"),
    clEnumVal(strip             , "Strip Symbols")));

This defines a variable that is conceptually of the type
"``std::vector<enum Opts>``".  Thus, you can access it with standard vector
methods:

for (unsigned i = 0; i != OptimizationList.size(); ++i)
  switch (OptimizationList[i])
     ...

Note that the "``cl::list``" template is completely general and may be used with
any data types or other arguments that you can use with the "``cl::opt``"
template.  One especially useful way to use a list is to capture all of the
positional arguments together if there may be more than one specified.  In the
case of a linker, for example, the linker takes several '``.o``' files, and
needs to capture them into a list.  This is naturally specified as:

” template is completely general and may be used with
any data types or other arguments that you can use with the “

" template is completely general and may be used with
any data types or other arguments that you can use with the "

”
case of a linker, for example, the linker takes several ‘

"
case of a linker, for example, the linker takes several '

’ files, and

' files, and

...
cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<Input files>"), cl::OneOrMore);
...

This variable works just like a "``vector<string>``" object.  As such, accessing
the list is simple, just like above.  In this example, we used the
`cl::OneOrMore`_ modifier to inform the CommandLine library that it is an error
if the user does not specify any ``.o`` files on our command line.  Again, this
just reduces the amount of checking we have to do.

” object.  As such, accessing

" object.  As such, accessing

 modifier to inform the CommandLine library that it is an error
if the user does not specify any 

 files on our command line.  Again, this

Instead of collecting sets of options in a list, it is also possible to gather
information for enum values in a **bit vector**.  The representation used by the
`cl::bits`_ class is an ``unsigned`` integer.  An enum value is represented by a
0/1 in the enum's ordinal value bit position. 1 indicating that the enum was
specified, 0 otherwise.  As each specified value is parsed, the resulting enum's
bit is set in the option's bit vector:

information for enum values in a 

 integer.  An enum value is represented by a
0/1 in the enum’s ordinal value bit position. 1 indicating that the enum was
specified, 0 otherwise.  As each specified value is parsed, the resulting enum’s
bit is set in the option’s bit vector:

Options that are specified multiple times are redundant.  Any instances after
the first are discarded.

Reworking the above list example, we could replace `cl::list`_ with `cl::bits`_:

cl::bits<Opts> OptimizationBits(cl::desc("Available Optimizations:"),

To test to see if ``instsimplify`` was specified, we can use the ``cl:bits::isSet``
function:

It's also possible to get the raw bit vector using the ``cl::bits::getBits``
function:

Finally, if external storage is used, then the location specified must be of
**type** ``unsigned``. In all other ways a `cl::bits`_ option is equivalent to a
`cl::list`_ option.

As our program grows and becomes more mature, we may decide to put summary
information about what it does into the help output.  The help output is styled
to look similar to a Unix ``man`` page, providing concise information about a
program.  Unix ``man`` pages, however often have a description about what the
program does.  To add this to your CommandLine program, simply pass a third
argument to the `cl::ParseCommandLineOptions`_ call in main.  This additional
argument is then printed as the overview information for your program, allowing
you to include any additional information that you want.  For example:

to look similar to a Unix 

 pages, however often have a description about what the
argument to the 

 call in main.  This additional

  cl::ParseCommandLineOptions(argc, argv, " CommandLine compiler example\n\n"
                              "  This program blah blah blah...\n");
  ...
}

**OVERVIEW: CommandLine compiler example

  This program blah blah blah...**

OPTIONS:
  ...

If our program has a large number of options it may become difficult for users
of our tool to navigate the output of ``-help``. To alleviate this problem we
can put our options into categories. This can be done by declaring option
categories (`cl::OptionCategory`_ objects) and then placing our options into
these categories using the `cl::cat`_ option attribute. For example:

of our tool to navigate the output of 

. To alleviate this problem we
categories (

 objects) and then placing our options into
these categories using the 

cl::OptionCategory StageSelectionCat("Stage Selection Options",
                                     "These control which stages are run.");

cl::opt<bool> Preprocessor("E",cl::desc("Run preprocessor stage."),
                           cl::cat(StageSelectionCat));

cl::opt<bool> NoLink("c",cl::desc("Run all stages except linking."),
                     cl::cat(StageSelectionCat));

The output of ``-help`` will become categorized if an option category is
declared. The output looks something like ::

 will become categorized if an option category is
declared. The output looks something like

OVERVIEW: This is a small program to demo the LLVM CommandLine API
USAGE: Sample [options]

OPTIONS:

  General options:

    -help              - Display available options (-help-hidden for more)
    -help-list         - Display list of available options (-help-list-hidden for more)

  Stage Selection Options:
  These control which stages are run.

    -E                 - Run preprocessor stage.
    -c                 - Run all stages except linking.

In addition to the behaviour of ``-help`` changing when an option category is
declared, the command line option ``-help-list`` becomes visible which will
print the command line options as uncategorized list.

 changing when an option category is
declared, the command line option 

 becomes visible which will

Note that Options that are not explicitly categorized will be placed in the
``cl::getGeneralCategory()`` category.

Now that you know the basics of how to use the CommandLine library, this section
will give you the detailed information you need to tune how command line options
work, as well as information on more "advanced" command line option processing
capabilities.

work, as well as information on more “advanced” command line option processing

Positional arguments are those arguments that are not named, and are not
specified with a hyphen.  Positional arguments should be used when an option is
specified by its position alone.  For example, the standard Unix ``grep`` tool
takes a regular expression argument, and an optional filename to search through
(which defaults to standard input if a filename is not specified).  Using the
CommandLine library, this would be specified as:

specified by its position alone.  For example, the standard Unix 

 tool

cl::opt<string> Regex   (cl::Positional, cl::desc("<regular expression>"), cl::Required);
cl::opt<string> Filename(cl::Positional, cl::desc("<input file>"), cl::init("-"));

Given these two option declarations, the ``-help`` output for our grep
replacement would look like this:

USAGE: spiffygrep [options] <regular expression> <input file>

OPTIONS:
  -help - display available options (-help-hidden for more)

... and the resultant program could be used just like the standard ``grep``
tool.

… and the resultant program could be used just like the standard 

... and the resultant program could be used just like the standard 

Positional arguments are sorted by their order of construction.  This means that
command line options will be ordered according to how they are listed in a .cpp
file, but will not have an ordering defined if the positional arguments are
defined in multiple .cpp files.  The fix for this problem is simply to define
all of your positional arguments in one .cpp file.

Sometimes you may want to specify a value to your positional argument that
starts with a hyphen (for example, searching for '``-foo``' in a file).  At
first, you will have trouble doing this, because it will try to find an argument
named '``-foo``', and will fail (and single quotes will not save you).  Note
that the system ``grep`` has the same problem:

starts with a hyphen (for example, searching for ‘

starts with a hyphen (for example, searching for '

’ in a file).  At
named ‘

' in a file).  At
named '

’, and will fail (and single quotes will not save you).  Note
that the system 

', and will fail (and single quotes will not save you).  Note

$ spiffygrep '-foo' test.txt
Unknown command line argument '-foo'.  Try: spiffygrep -help'

$ grep '-foo' test.txt
grep: illegal option -- f
grep: illegal option -- o
Usage: grep -hblcnsviw pattern file . . .

The solution for this problem is the same for both your tool and the system
version: use the '``--``' marker.  When the user specifies '``--``' on the
command line, it is telling the program that all options after the '``--``'
should be treated as positional arguments, not options.  Thus, we can use it
like this:

version: use the ‘

version: use the '

‘ on the
command line, it is telling the program that all options after the ‘

' on the
command line, it is telling the program that all options after the '

‘
like this:

'
like this:

Sometimes an option can affect or modify the meaning of another option. For
example, consider ``gcc``'s ``-x LANG`` option. This tells ``gcc`` to ignore the
suffix of subsequent positional arguments and force the file to be interpreted
as if it contained source code in language ``LANG``. In order to handle this
properly, you need to know the absolute position of each argument, especially
those in lists, so their interaction(s) can be applied correctly. This is also
useful for options like ``-llibname`` which is actually a positional argument
that starts with a dash.

example, consider 

 to ignore the
as if it contained source code in language 

. In order to handle this
useful for options like 

 which is actually a positional argument

So, generally, the problem is that you have two ``cl::list`` variables that
interact in some way. To ensure the correct interaction, you can use the
``cl::list::getPosition(optnum)`` method. This method returns the absolute
position (as found on the command line) of the ``optnum`` item in the
``cl::list``.

 variables that

 method. This method returns the absolute
position (as found on the command line) of the 

static cl::list<std::string> Files(cl::Positional, cl::OneOrMore);
static cl::list<std::string> Libraries("l", cl::ZeroOrMore);

int main(int argc, char**argv) {
  // ...
  std::vector<std::string>::iterator fileIt = Files.begin();
  std::vector<std::string>::iterator libIt  = Libraries.begin();
  unsigned libPos = 0, filePos = 0;
  while ( 1 ) {
    if ( libIt != Libraries.end() )
      libPos = Libraries.getPosition( libIt - Libraries.begin() );
    else
      libPos = 0;
    if ( fileIt != Files.end() )
      filePos = Files.getPosition( fileIt - Files.begin() );
    else
      filePos = 0;

    if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
      // Source File Is next
      ++fileIt;
    }
    else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
      // Library is next
      ++libIt;
    }
    else
      break; // we're done with the list
  }
}

Note that, for compatibility reasons, the ``cl::opt`` also supports an
``unsigned getPosition()`` option that will provide the absolute position of
that option. You can apply the same approach as above with a ``cl::opt`` and a
``cl::list`` option as you can with two lists.

 option that will provide the absolute position of
that option. You can apply the same approach as above with a 

The ``cl::ConsumeAfter`` `formatting option`_ is used to construct programs that
use "interpreter style" option processing.  With this style of option
processing, all arguments specified after the last positional argument are
treated as special interpreter arguments that are not interpreted by the command
line argument.

 is used to construct programs that
use “interpreter style” option processing.  With this style of option

As a concrete example, lets say we are developing a replacement for the standard
Unix Bourne shell (``/bin/sh``).  To run ``/bin/sh``, first you specify options
to the shell itself (like ``-x`` which turns on trace output), then you specify
the name of the script to run, then you specify arguments to the script.  These
arguments to the script are parsed by the Bourne shell command line option
processor, but are not interpreted as options to the shell itself.  Using the
CommandLine library, we would specify this as:

Unix Bourne shell (

 which turns on trace output), then you specify

cl::opt<string> Script(cl::Positional, cl::desc("<input script>"), cl::init("-"));
cl::list<string>  Argv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
cl::opt<bool>    Trace("x", cl::desc("Enable trace output"));

USAGE: spiffysh [options] <input script> <program arguments>...

OPTIONS:
  -x    - Enable trace output

At runtime, if we run our new shell replacement as ```spiffysh -x test.sh -a -x
-y bar``', the ``Trace`` variable will be set to true, the ``Script`` variable
will be set to "``test.sh``", and the ``Argv`` list will contain ``["-a", "-x",
"-y", "bar"]``, because they were specified after the last positional argument
(which is the script name).

, because they were specified after the last positional argument

There are several limitations to when ``cl::ConsumeAfter`` options can be
specified.  For example, only one ``cl::ConsumeAfter`` can be specified per
program, there must be at least one `positional argument`_ specified, there must
not be any `cl::list`_ positional arguments, and the ``cl::ConsumeAfter`` option
should be a `cl::list`_ option.

By default, all command line options automatically hold the value that they
parse from the command line.  This is very convenient in the common case,
especially when combined with the ability to define command line options in the
files that use them.  This is called the internal storage model.

Sometimes, however, it is nice to separate the command line option processing
code from the storage of the value parsed.  For example, lets say that we have a
'``-debug``' option that we would like to use to enable debug information across
the entire body of our program.  In this case, the boolean value controlling the
debug code should be globally accessible (in a header file, for example) yet the
command line option processing code should not be exposed to all of these
clients (requiring lots of .cpp files to ``#include CommandLine.h``).

‘

'

’ option that we would like to use to enable debug information across
clients (requiring lots of .cpp files to 

' option that we would like to use to enable debug information across

To do this, set up your .h file with your option, like this for example:

// DebugFlag.h - Get access to the '-debug' command line option
//

// DebugFlag - This boolean is set to true if the '-debug' command line option
// is specified.  This should probably not be referenced directly, instead, use
// the DEBUG macro below.
//
extern bool DebugFlag;

// DEBUG macro - This macro should be used by code to emit debug information.
// In the '-debug' option is specified on the command line, and if this is a
// debug build, then the code specified as the option to the macro will be
// executed.  Otherwise it will not be.
#ifdef NDEBUG
#define LLVM_DEBUG(X)
#else
#define LLVM_DEBUG(X) do { if (DebugFlag) { X; } } while (0)
#endif

This allows clients to blissfully use the ``LLVM_DEBUG()`` macro, or the
``DebugFlag`` explicitly if they want to.  Now we just need to be able to set
the ``DebugFlag`` boolean when the option is set.  To do this, we pass an
additional argument to our command line argument processor, and we specify where
to fill in with the `cl::location`_ attribute:

 explicitly if they want to.  Now we just need to be able to set
the 

 boolean when the option is set.  To do this, we pass an
to fill in with the 

bool DebugFlag;                  // the actual value
static cl::opt<bool, true>       // The parser
Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag));

In the above example, we specify "``true``" as the second argument to the
`cl::opt`_ template, indicating that the template should not maintain a copy of
the value itself.  In addition to this, we specify the `cl::location`_
attribute, so that ``DebugFlag`` is automatically set.

 template, indicating that the template should not maintain a copy of
the value itself.  In addition to this, we specify the 

This section describes the basic attributes that you can specify on options.

The option name attribute (which is required for all options, except
`positional options`_) specifies what the option name is.  This option is
specified in simple double quotes:

.. code-block:: c++

  cl::opt<bool> Quiet("quiet");

) specifies what the option name is.  This option is

The **cl::desc** attribute specifies a description for the option to be
shown in the ``-help`` output for the program. This attribute supports
multi-line descriptions with lines separated by '\n'.

 attribute specifies a description for the option to be
shown in the 

 output for the program. This attribute supports

The **cl::value_desc** attribute specifies a string that can be used to
fine tune the ``-help`` output for a command line option.  Look `here`_ for an
example.

example.

 attribute specifies a string that can be used to
fine tune the 

The **cl::init** attribute specifies an initial value for a `scalar`_
option.  If this attribute is not specified then the command line option value
defaults to the value created by the default constructor for the
type.

.. warning::

  If you specify both **cl::init** and **cl::location** for an option, you
  must specify **cl::location** first, so that when the command-line parser
  sees **cl::init**, it knows where to put the initial value. (You will get an
  error at runtime if you don't put them in the right order.)

type.

type.

If you specify both **cl::init** and **cl::location** for an option, you
must specify **cl::location** first, so that when the command-line parser
sees **cl::init**, it knows where to put the initial value. (You will get an
error at runtime if you don't put them in the right order.)

, it knows where to put the initial value. (You will get an
error at runtime if you don’t put them in the right order.)

The **cl::location** attribute where to store the value for a parsed command
line option if using external storage.  See the section on `Internal vs
External Storage`_ for more information.

 attribute where to store the value for a parsed command
line option if using external storage.  See the section on 

The **cl::aliasopt** attribute specifies which option a `cl::alias`_ option is
an alias for.

The **cl::values** attribute specifies the string-to-value mapping to be used
by the generic parser.  It takes a list of (option, value, description)
triplets that specify the option name, the value mapped to, and the
description shown in the ``-help`` for the tool.  Because the generic parser
is used most frequently with enum values, two macros are often useful:

#. The **clEnumVal** macro is used as a nice simple way to specify a triplet
   for an enum.  This macro automatically makes the option name be the same as
   the enum name.  The first option to the macro is the enum, the second is
   the description for the command line option.

#. The **clEnumValN** macro is used to specify macro options where the option
   name doesn't equal the enum name.  For this macro, the first argument is
   the enum value, the second is the flag name, and the second is the
   description.

You will get a compile time error if you try to use cl::values with a parser
that does not support it.

 attribute specifies the string-to-value mapping to be used
description shown in the 

 for the tool.  Because the generic parser

The **clEnumVal** macro is used as a nice simple way to specify a triplet
for an enum.  This macro automatically makes the option name be the same as
the enum name.  The first option to the macro is the enum, the second is
the description for the command line option.

 macro is used as a nice simple way to specify a triplet

The **clEnumValN** macro is used to specify macro options where the option
name doesn't equal the enum name.  For this macro, the first argument is
the enum value, the second is the flag name, and the second is the
description.

 macro is used to specify macro options where the option
name doesn’t equal the enum name.  For this macro, the first argument is

The **cl::multi_val** attribute specifies that this option takes has multiple
values (example: ``-sectalign segname sectname sectvalue``). This attribute
takes one unsigned argument - the number of values for the option. This
attribute is valid only on ``cl::list`` options (and will fail with compile
error if you try to use it with other option types). It is allowed to use all
of the usual modifiers on multi-valued options (besides
``cl::ValueDisallowed``, obviously).

 attribute specifies that this option takes has multiple
values (example: 

). This attribute
attribute is valid only on 

 options (and will fail with compile

The **cl::cat** attribute specifies the option category that the option
belongs to. The category should be a `cl::OptionCategory`_ object.

 attribute specifies the option category that the option
belongs to. The category should be a 

The **cl::callback** attribute specifies a callback function that is
called when an option is seen, and can be used to set other options,
as in option B implies option A.  If the option is a `cl::list`_,
and `cl::CommaSeparated`_ is also specified, the callback will fire
once for each value.  This could be used to validate combinations or
selectively set other options.

  cl::opt<bool> OptA("a", cl::desc("option a"));
  cl::opt<bool> OptB(
      "b", cl::desc("option b -- This option turns on option a"),
      cl::callback([&](const bool &) { OptA = true; }));
  cl::list<std::string, cl::list<std::string>> List(
    "list",
    cl::desc("option list -- This option turns on options a when "
             "'foo' is included in list"),
    cl::CommaSeparated,
    cl::callback([&](const std::string &Str) {
      if (Str == "foo")
        OptA = true;
    }));

 attribute specifies a callback function that is
as in option B implies option A.  If the option is a 

 is also specified, the callback will fire

cl::opt<bool> OptA("a", cl::desc("option a"));
cl::opt<bool> OptB(
    "b", cl::desc("option b -- This option turns on option a"),
    cl::callback([&](const bool &) { OptA = true; }));
cl::list<std::string, cl::list<std::string>> List(
  "list",
  cl::desc("option list -- This option turns on options a when "
           "'foo' is included in list"),
  cl::CommaSeparated,
  cl::callback([&](const std::string &Str) {
    if (Str == "foo")
      OptA = true;
  }));

Option modifiers are the flags and expressions that you pass into the
constructors for `cl::opt`_ and `cl::list`_.  These modifiers give you the
ability to tweak how options are parsed and how ``-help`` output is generated to
fit your application well.

constructors for 

.  These modifiers give you the
ability to tweak how options are parsed and how 

It is not possible to specify two options from the same category (you'll get a
runtime error) to a single option, except for options in the miscellaneous
category.  The CommandLine library specifies defaults for all of these settings
that are the most useful in practice and the most common, which mean that you
usually shouldn't have to worry about these.

It is not possible to specify two options from the same category (you’ll get a
usually shouldn’t have to worry about these.

The ``cl::NotHidden``, ``cl::Hidden``, and ``cl::ReallyHidden`` modifiers are
used to control whether or not an option appears in the ``-help`` and
``-help-hidden`` output for the compiled program:

 modifiers are
used to control whether or not an option appears in the 

The **cl::NotHidden** modifier (which is the default for `cl::opt`_ and
`cl::list`_ options) indicates the option is to appear in both help
listings.

listings.

 options) indicates the option is to appear in both help
listings.

The **cl::Hidden** modifier (which is the default for `cl::alias`_ options)
indicates that the option should not appear in the ``-help`` output, but
should appear in the ``-help-hidden`` output.

The **cl::ReallyHidden** modifier indicates that the option should not appear
in any help output.

 modifier indicates that the option should not appear

This group of options is used to control how many time an option is allowed (or
required) to be specified on the command line of your program.  Specifying a
value for this setting allows the CommandLine library to do error checking for
you.

The **cl::Optional** modifier (which is the default for the `cl::opt`_ and
`cl::alias`_ classes) indicates that your program will allow either zero or
one occurrence of the option to be specified.

 classes) indicates that your program will allow either zero or

The **cl::ZeroOrMore** modifier (which is the default for the `cl::list`_
class) indicates that your program will allow the option to be specified zero
or more times.

The **cl::Required** modifier indicates that the specified option must be
specified exactly one time.

 modifier indicates that the specified option must be

The **cl::OneOrMore** modifier indicates that the option must be specified at
least one time.

 modifier indicates that the option must be specified at

The **cl::ConsumeAfter** modifier is described in the `Positional arguments
section`_.

If an option is not specified, then the value of the option is equal to the
value specified by the `cl::init`_ attribute.  If the ``cl::init`` attribute is
not specified, the option value is initialized with the default constructor for
the data type.

value specified by the 

 attribute is

If an option is specified multiple times for an option of the `cl::opt`_ class,
only the last value will be retained.

This group of options is used to control whether or not the option allows a
value to be present.  In the case of the CommandLine library, a value is either
specified with an equal sign (e.g. '``-index-depth=17``') or as a trailing
string (e.g. '``-o a.out``').

specified with an equal sign (e.g. ‘

specified with an equal sign (e.g. '

The **cl::ValueOptional** modifier (which is the default for ``bool`` typed
options) specifies that it is acceptable to have a value, or not.  A boolean
argument can be enabled just by appearing on the command line, or it can have
an explicit '``-foo=true``'.  If an option is specified with this mode, it is
illegal for the value to be provided without the equal sign.  Therefore
'``-foo true``' is illegal.  To get this behavior, you must use
the `cl::ValueRequired`_ modifier.

 typed
an explicit ‘

 typed
an explicit '

’.  If an option is specified with this mode, it is
‘

'.  If an option is specified with this mode, it is
'

The **cl::ValueRequired** modifier (which is the default for all other types
except for `unnamed alternatives using the generic parser`_) specifies that a
value must be provided.  This mode informs the command line library that if an
option is not provides with an equal sign, that the next argument provided
must be the value.  This allows things like '``-o a.out``' to work.

) specifies that a
must be the value.  This allows things like ‘

must be the value.  This allows things like '

The **cl::ValueDisallowed** modifier (which is the default for `unnamed
alternatives using the generic parser`_) indicates that it is a runtime error
for the user to specify a value.  This can be provided to disallow users from
providing options to boolean options (like '``-foo=true``').

) indicates that it is a runtime error
providing options to boolean options (like ‘

providing options to boolean options (like '

In general, the default values for this option group work just like you would
want them to.  As mentioned above, you can specify the `cl::ValueDisallowed`_
modifier to a boolean argument to restrict your command line parser.  These
options are mostly useful when `extending the library`_.

want them to.  As mentioned above, you can specify the 

options are mostly useful when 

The formatting option group is used to specify that the command line option has
special abilities and is otherwise different from other command line arguments.
As usual, you can only specify one of these arguments at most.

The **cl::NormalFormatting** modifier (which is the default all options)
specifies that this option is "normal".

 modifier (which is the default all options)
specifies that this option is “normal”.

The **cl::Positional** modifier specifies that this is a positional argument
that does not have a command line option associated with it.  See the
`Positional Arguments`_ section for more information.

 modifier specifies that this is a positional argument

The **cl::ConsumeAfter** modifier specifies that this option is used to
capture "interpreter style" arguments.  See `this section for more
information`_.

 modifier specifies that this option is used to
capture “interpreter style” arguments.  See 

capture "interpreter style" arguments.  See 

The **cl::Prefix** modifier specifies that this option prefixes its value.
With 'Prefix' options, the equal sign does not separate the value from the
option name specified. Instead, the value is everything after the prefix,
including any equal sign if present. This is useful for processing odd
arguments like ``-lmalloc`` and ``-L/usr/lib`` in a linker tool or
``-DNAME=value`` in a compiler tool.  Here, the '``l``', '``D``' and '``L``'
options are normal string (or list) options, that have the **cl::Prefix**
modifier added to allow the CommandLine library to recognize them.  Note that
**cl::Prefix** options must not have the **cl::ValueDisallowed** modifier

 modifier specifies that this option prefixes its value.
With ‘Prefix’ options, the equal sign does not separate the value from the
arguments like 

The **cl::Grouping** modifier can be combined with any formatting types except
for `cl::Positional`_.  It is used to implement Unix-style tools (like ``ls``)
that have lots of single letter arguments, but only require a single dash.
For example, the '``ls -labF``' command actually enables four different options,
all of which are single letters.

)
For example, the ‘

)
For example, the '

’ command actually enables four different options,

' command actually enables four different options,

Note that **cl::Grouping** options can have values only if they are used
separately or at the end of the groups.  For `cl::ValueRequired`_, it is
a runtime error if such an option is used elsewhere in the group.

 options can have values only if they are used
separately or at the end of the groups.  For 

, it is

The CommandLine library does not restrict how you use the **cl::Prefix** or
**cl::Grouping** modifiers, but it is possible to specify ambiguous argument
settings.  Thus, it is possible to have multiple letter options that are prefix
or grouping options, and they will still work as designed.

 modifiers, but it is possible to specify ambiguous argument

To do this, the CommandLine library uses a greedy algorithm to parse the input
option into (potentially multiple) prefix and grouping options.  The strategy
basically looks like this:

parse(string OrigInput) {

1. string Input = OrigInput;
2. if (isOption(Input)) return getOption(Input).parse();  // Normal option
3. while (!Input.empty() && !isOption(Input)) Input.pop_back();  // Remove the last letter
4. while (!Input.empty()) {
     string MaybeValue = OrigInput.substr(Input.length())
     if (getOption(Input).isPrefix())
       return getOption(Input).parse(MaybeValue)
     if (!MaybeValue.empty() && MaybeValue[0] == '=')
       return getOption(Input).parse(MaybeValue.substr(1))
     if (!getOption(Input).isGrouping())
       return error()
     getOption(Input).parse()
     Input = OrigInput = MaybeValue
     while (!Input.empty() && !isOption(Input)) Input.pop_back();
     if (!Input.empty() && !getOption(Input).isGrouping())
   }
5. if (!OrigInput.empty()) error();

}

The miscellaneous option modifiers are the only flags where you can specify more
than one flag from the set: they are not mutually exclusive.  These flags
specify boolean properties that modify the option.

The **cl::CommaSeparated** modifier indicates that any commas specified for an
option's value should be used to split the value up into multiple values for
the option.  For example, these two options are equivalent when
``cl::CommaSeparated`` is specified: "``-foo=a -foo=b -foo=c``" and
"``-foo=a,b,c``".  This option only makes sense to be used in a case where the
option is allowed to accept one or more values (i.e. it is a `cl::list`_
option).

option).

 modifier indicates that any commas specified for an
option’s value should be used to split the value up into multiple values for

”.  This option only makes sense to be used in a case where the
option is allowed to accept one or more values (i.e. it is a 

".  This option only makes sense to be used in a case where the

The **cl::DefaultOption** modifier is used to specify that the option is a
default that can be overridden by application specific parsers. For example,
the ``-help`` alias, ``-h``, is registered this way, so it can be overridden
by applications that need to use the ``-h`` option for another purpose,
either as a regular option or an alias for another option.

 modifier is used to specify that the option is a
the 

, is registered this way, so it can be overridden
by applications that need to use the 

 option for another purpose,

The **cl::PositionalEatsArgs** modifier (which only applies to positional
arguments, and only makes sense for lists) indicates that positional argument
should consume any strings after it (including strings that start with a "-")
up until another recognized positional argument.  For example, if you have two
"eating" positional arguments, "``pos1``" and "``pos2``", the string "``-pos1
-foo -bar baz -pos2 -bork``" would cause the "``-foo -bar -baz``" strings to
be applied to the "``-pos1``" option and the "``-bork``" string to be applied
to the "``-pos2``" option.

 modifier (which only applies to positional
should consume any strings after it (including strings that start with a “-“)
“eating” positional arguments, “

"eating" positional arguments, "

The **cl::Sink** modifier is used to handle unknown options. If there is at
least one option with ``cl::Sink`` modifier specified, the parser passes
unrecognized option strings to it as values instead of signaling an error. As
with ``cl::CommaSeparated``, this modifier only makes sense with a `cl::list`_
option.

option.

 modifier is used to handle unknown options. If there is at
least one option with 

 modifier specified, the parser passes
with 

Some systems, such as certain variants of Microsoft Windows and some older
Unices have a relatively low limit on command-line length. It is therefore
customary to use the so-called 'response files' to circumvent this
restriction. These files are mentioned on the command-line (using the "@file")
syntax. The program reads these files and inserts the contents into argv,
thereby working around the command-line length limits.

customary to use the so-called ‘response files’ to circumvent this
restriction. These files are mentioned on the command-line (using the “@file”)

Despite all of the built-in flexibility, the CommandLine option library really
only consists of one function `cl::ParseCommandLineOptions`_ and three main
classes: `cl::opt`_, `cl::list`_, and `cl::alias`_.  This section describes
these three classes in detail.

only consists of one function 

The ``cl::getRegisteredOptions`` function is designed to give a programmer
access to declared non-positional command line options so that how they appear
in ``-help`` can be modified prior to calling `cl::ParseCommandLineOptions`_.
Note this method should not be called during any static initialisation because
it cannot be guaranteed that all options will have been initialised. Hence it
should be called from ``main``.

 function is designed to give a programmer
in 

.
should be called from 

This function can be used to gain access to options declared in libraries that
the tool writer may not have direct access to.

The function retrieves a :ref:`StringMap <dss_stringmap>` that maps the option
string (e.g. ``-help``) to an ``Option*``.

using namespace llvm;
  cl::OptionCategory AnotherCategory("Some options");

  StringMap<cl::Option*> &Map = cl::getRegisteredOptions();

  //Unhide useful option and put it in a different category
  assert(Map.count("print-all-options") > 0);
  Map["print-all-options"]->setHiddenFlag(cl::NotHidden);
  Map["print-all-options"]->setCategory(AnotherCategory);

  //Hide an option we don't want to see
  assert(Map.count("enable-no-infs-fp-math") > 0);
  Map["enable-no-infs-fp-math"]->setHiddenFlag(cl::Hidden);

  //Change --version to --show-version
  assert(Map.count("version") > 0);
  Map["version"]->setArgStr("show-version");

  //Change --help description
  assert(Map.count("help") > 0);
  Map["help"]->setDescription("Shows help");

  cl::ParseCommandLineOptions(argc, argv, "This is a small program to demo the LLVM CommandLine API");
  ...
}

The ``cl::ParseCommandLineOptions`` function is designed to be called directly
from ``main``, and is used to fill in the values of all of the command line
option variables once ``argc`` and ``argv`` are available.

, and is used to fill in the values of all of the command line
option variables once 

The ``cl::ParseCommandLineOptions`` function requires two parameters (``argc``
and ``argv``), but may also take an optional third parameter which holds
`additional extra text`_ to emit when the ``-help`` option is invoked.

The ``cl::SetVersionPrinter`` function is designed to be called directly from
``main`` and *before* ``cl::ParseCommandLineOptions``. Its use is optional. It
simply arranges for a function to be called in response to the ``--version``
option instead of having the ``CommandLine`` library print out the usual version
string for LLVM. This is useful for programs that are not part of LLVM but wish
to use the ``CommandLine`` facilities. Such programs should just define a small
function that takes no arguments and returns ``void`` and that prints out
whatever version information is appropriate for the program. Pass the address of
that function to ``cl::SetVersionPrinter`` to arrange for it to be called when
the ``--version`` option is given by the user.

. Its use is optional. It
simply arranges for a function to be called in response to the 

 library print out the usual version
to use the 

 facilities. Such programs should just define a small
function that takes no arguments and returns 

 and that prints out
that function to 

The ``cl::opt`` class is the class used to represent scalar command line
options, and is the one used most of the time.  It is a templated class which
can take up to three arguments (all except for the first have default values
though):

 class is the class used to represent scalar command line
though):

namespace cl {
  template <class DataType, bool ExternalStorage = false,
            class ParserClass = parser<DataType> >
  class opt;
}

The first template argument specifies what underlying data type the command line
argument is, and is used to select a default parser implementation.  The second
template argument is used to specify whether the option should contain the
storage for the option (the default) or whether external storage should be used
to contain the value parsed for the option (see `Internal vs External Storage`_
for more information).

to contain the value parsed for the option (see 

The third template argument specifies which parser to use.  The default value
selects an instantiation of the ``parser`` class based on the underlying data
type of the option.  In general, this default works well for most applications,
so this option is only used when using a `custom parser`_.

selects an instantiation of the 

 class based on the underlying data
so this option is only used when using a 

The ``cl::list`` class is the class used to represent a list of command line
options.  It too is a templated class which can take up to three arguments:

 class is the class used to represent a list of command line

  template <class DataType, class Storage = bool,
  class list;
}

This class works the exact same as the `cl::opt`_ class, except that the second
argument is the **type** of the external storage, not a boolean value.  For this
class, the marker type '``bool``' is used to indicate that internal storage
should be used.

 of the external storage, not a boolean value.  For this
class, the marker type ‘

class, the marker type '

The ``cl::bits`` class is the class used to represent a list of command line
options in the form of a bit vector.  It is also a templated class which can
take up to three arguments:

  class bits;
}

This class works the exact same as the `cl::list`_ class, except that the second
argument must be of **type** ``unsigned`` if external storage is used.

The ``cl::alias`` class is a nontemplated class that is used to form aliases for
other arguments.

 class is a nontemplated class that is used to form aliases for

The `cl::aliasopt`_ attribute should be used to specify which option this is an
alias for.  Alias arguments default to being `cl::Hidden`_, and use the aliased
options parser to do the conversion from string to data.

 attribute should be used to specify which option this is an
alias for.  Alias arguments default to being 

, and use the aliased

The ``cl::extrahelp`` class is a nontemplated class that allows extra help text
to be printed out for the ``-help`` option.

 class is a nontemplated class that allows extra help text
to be printed out for the 

To use the extrahelp, simply construct one with a ``const char*`` parameter to
the constructor. The text passed to the constructor will be printed at the
bottom of the help message, verbatim. Note that multiple ``cl::extrahelp``
**can** be used, but this practice is discouraged. If your tool needs to print
additional help information, put all that help into a single ``cl::extrahelp``
instance.

 parameter to
bottom of the help message, verbatim. Note that multiple 

 be used, but this practice is discouraged. If your tool needs to print
additional help information, put all that help into a single 

cl::extrahelp("\nADDITIONAL HELP:\n\n  This is the extra help\n");

The ``cl::OptionCategory`` class is a simple class for declaring
option categories.

An option category must have a name and optionally a description which are
passed to the constructor as ``const char*``.

passed to the constructor as 

Note that declaring an option category and associating it with an option before
parsing options (e.g. statically) will change the output of ``-help`` from
uncategorized to categorized. If an option category is declared but not
associated with an option then it will be hidden from the output of ``-help``
but will be shown in the output of ``-help-hidden``.

parsing options (e.g. statically) will change the output of 

 from
associated with an option then it will be hidden from the output of 

Parsers control how the string value taken from the command line is translated
into a typed value, suitable for use in a C++ program.  By default, the
CommandLine library uses an instance of ``parser<type>`` if the command line
option specifies that it uses values of type '``type``'.  Because of this,
custom option processing is specified with specializations of the '``parser``'
class.

CommandLine library uses an instance of 

 if the command line
option specifies that it uses values of type ‘

option specifies that it uses values of type '

’.  Because of this,
custom option processing is specified with specializations of the ‘

'.  Because of this,
custom option processing is specified with specializations of the '

The CommandLine library provides the following builtin parser specializations,
which are sufficient for most applications. It can, however, also be extended to
work with new data types and new ways of interpreting the same data.  See the
`Writing a Custom Parser`_ for more details on this type of library extension.

The generic ``parser<t>`` parser can be used to map strings values to any data
type, through the use of the `cl::values`_ property, which specifies the
mapping information.  The most common use of this parser is for parsing enum
values, which allows you to use the CommandLine library for all of the error
checking to make sure that only valid enum values are specified (as opposed to
accepting arbitrary strings).  Despite this, however, the generic parser class
can be used for any data type.

 parser can be used to map strings values to any data
type, through the use of the 

 property, which specifies the

The **parser<bool> specialization** is used to convert boolean strings to a
boolean value.  Currently accepted strings are "``true``", "``TRUE``",
"``True``", "``1``", "``false``", "``FALSE``", "``False``", and "``0``".

 is used to convert boolean strings to a
boolean value.  Currently accepted strings are “

boolean value.  Currently accepted strings are "

The **parser<boolOrDefault> specialization** is used for cases where the value
is boolean, but we also need to know whether the option was specified at all.
boolOrDefault is an enum with 3 values, BOU_UNSET, BOU_TRUE and BOU_FALSE.
This parser accepts the same strings as **``parser<bool>``**.

 is used for cases where the value
This parser accepts the same strings as 

The **parser<string> specialization** simply stores the parsed string into the
string value specified.  No conversion or modification of the data is
performed.

 simply stores the parsed string into the

The **parser<int> specialization** uses the C ``strtol`` function to parse the
string input.  As such, it will accept a decimal number (with an optional '+'
or '-' prefix) which must start with a non-zero digit.  It accepts octal
numbers, which are identified with a '``0``' prefix digit, and hexadecimal
numbers with a prefix of '``0x``' or '``0X``'.

 function to parse the
string input.  As such, it will accept a decimal number (with an optional ‘+’
or ‘-‘ prefix) which must start with a non-zero digit.  It accepts octal
numbers, which are identified with a ‘

numbers, which are identified with a '

The **parser<double>** and **parser<float> specializations** use the standard
C ``strtod`` function to convert floating point strings into floating point
values.  As such, a broad range of string formats is supported, including
exponential notation (ex: ``1.7e15``) and properly supports locales.

 function to convert floating point strings into floating point
exponential notation (ex: 

Although the CommandLine library has a lot of functionality built into it
already (as discussed previously), one of its true strengths lie in its
extensibility.  This section discusses how the CommandLine library works under
the covers and illustrates how to do some simple, common, extensions.

One of the simplest and most common extensions is the use of a custom parser.
As `discussed previously`_, parsers are the portion of the CommandLine library
that turns string input from the user into a particular parsed data type,
validating the input in the process.

As 

, parsers are the portion of the CommandLine library

Specialize the `cl::parser`_ template for your custom data type.

This approach has the advantage that users of your custom data type will
automatically use your custom parser whenever they define an option with a
value type of your data type.  The disadvantage of this approach is that it
doesn't work if your fundamental data type is something that is already
supported.

doesn’t work if your fundamental data type is something that is already

Write an independent class, using it explicitly from options that need it.

This approach works well in situations where you would line to parse an
option using special syntax for a not-very-special data-type.  The drawback
of this approach is that users of your parser have to be aware that they are
using your parser instead of the builtin ones.

To guide the discussion, we will discuss a custom parser that accepts file
sizes, specified with an optional unit after the numeric size.  For example, we
would like to parse "102kb", "41M", "1G" into the appropriate integer value.  In
this case, the underlying data type we want to parse into is '``unsigned``'.  We
choose approach #2 above because we don't want to make this the default for all
``unsigned`` options.

would like to parse “102kb”, “41M”, “1G” into the appropriate integer value.  In
this case, the underlying data type we want to parse into is ‘

this case, the underlying data type we want to parse into is '

’.  We
choose approach #2 above because we don’t want to make this the default for all

'.  We

struct FileSizeParser : public cl::parser<unsigned> {
  // parse - Return true on error.
  bool parse(cl::Option &O, StringRef ArgName, const std::string &ArgValue,
             unsigned &Val);
};

Our new class inherits from the ``cl::parser`` template class to fill in
the default, boiler plate code for us.  We give it the data type that we parse
into, the last argument to the ``parse`` method, so that clients of our custom
parser know what object type to pass in to the parse method.  (Here we declare
that we parse into '``unsigned``' variables.)

 template class to fill in
into, the last argument to the 

 method, so that clients of our custom
that we parse into ‘

that we parse into '

For most purposes, the only method that must be implemented in a custom parser
is the ``parse`` method.  The ``parse`` method is called whenever the option is
invoked, passing in the option itself, the option name, the string to parse, and
a reference to a return value.  If the string to parse is not well-formed, the
parser should output an error message and return true.  Otherwise it should
return false and set '``Val``' to the parsed value.  In our example, we
implement ``parse`` as:

is the 

 method is called whenever the option is
return false and set ‘

return false and set '

bool FileSizeParser::parse(cl::Option &O, StringRef ArgName,
                           const std::string &Arg, unsigned &Val) {
  const char *ArgStart = Arg.c_str();
  char *End;

  // Parse integer part, leaving 'End' pointing to the first non-integer char
  Val = (unsigned)strtol(ArgStart, &End, 0);

  while (1) {
    switch (*End++) {
    case 0: return false;   // No error
    case 'i':               // Ignore the 'i' in KiB if people use that
    case 'b': case 'B':     // Ignore B suffix
      break;

    case 'g': case 'G': Val *= 1024*1024*1024; break;
    case 'm': case 'M': Val *= 1024*1024;      break;
    case 'k': case 'K': Val *= 1024;           break;

    default:
      // Print an error message if unrecognized character!
      return O.error("'" + Arg + "' value invalid for file size argument!");
    }
  }
}

This function implements a very simple parser for the kinds of strings we are
interested in.  Although it has some holes (it allows "``123KKK``" for example),
it is good enough for this example.  Note that we use the option itself to print
out the error message (the ``error`` method always returns true) in order to get
a nice error message (shown below).  Now that we have our parser class, we can
use it like this:

interested in.  Although it has some holes (it allows “

interested in.  Although it has some holes (it allows "

” for example),
out the error message (the 

" for example),

 method always returns true) in order to get

static cl::opt<unsigned, false, FileSizeParser>
MFS("max-file-size", cl::desc("Maximum file size to accept"),
    cl::value_desc("size"));

OPTIONS:
  -help                 - display available options (-help-hidden for more)
  ...
  -max-file-size=<size> - Maximum file size to accept

And we can test that our parse works correctly now (the test program just prints
out the max-file-size argument value):

$ ./test
MFS: 0
$ ./test -max-file-size=123MB
MFS: 128974848
$ ./test -max-file-size=3G
MFS: 3221225472
$ ./test -max-file-size=dog
-max-file-size option: 'dog' value invalid for file size argument!

It looks like it works.  The error message that we get is nice and helpful, and
we seem to accept reasonable file sizes.  This wraps up the "custom parser"
tutorial.

we seem to accept reasonable file sizes.  This wraps up the “custom parser”
tutorial.

Duplicate implicit target name: "grouping options into categories".

Duplicate implicit target name: “grouping options into categories”.

Hyperlink target "grouping-options-into-categories" is not referenced.

Several of the LLVM libraries define static ``cl::opt`` instances that will
automatically be included in any program that links with that library.  This is
a feature. However, sometimes it is necessary to know the value of the command
line option outside of the library. In these cases the library does or should
provide an external storage location that is accessible to users of the
library. Examples of this include the ``llvm::DebugFlag`` exported by the
``lib/Support/Debug.cpp`` file and the ``llvm::TimePassesIsEnabled`` flag
exported by the ``lib/IR/PassManager.cpp`` file.

 instances that will
library. Examples of this include the 

Touch on some of the more advanced features, like ``isa_impl`` and
``simplify_type``. However, those two need reference documentation in
the form of doxygen comments as well. We need the doxygen so that we can
say "for full details, see https://llvm.org/doxygen/..."

. However, those two need reference documentation in
say “for full details, see 

say "for full details, see 

LLVM avoids using C++'s built in RTTI. Instead, it  pervasively uses its
own hand-rolled form of RTTI which is much more efficient and flexible,
although it requires a bit more work from you as a class author.

LLVM avoids using C++’s built in RTTI. Instead, it  pervasively uses its

A description of how to use LLVM-style RTTI from a client's perspective is
given in the `Programmer's Manual <ProgrammersManual.html#isa>`_. This
document, in contrast, discusses the steps you need to take as a class
hierarchy author to make LLVM-style RTTI available to your clients.

A description of how to use LLVM-style RTTI from a client’s perspective is
given in the 

. This

Before diving in, make sure that you are familiar with the Object Oriented
Programming concept of "`is-a`_".

Programming concept of “

Programming concept of "

This section describes how to set up the most basic form of LLVM-style RTTI
(which is sufficient for 99.9% of the cases). We will set up LLVM-style
RTTI for this class hierarchy:

class Shape {
public:
  Shape() {}
  virtual double computeArea() = 0;
};

class Square : public Shape {
  double SideLength;
public:
  Square(double S) : SideLength(S) {}
  double computeArea() override;
};

class Circle : public Shape {
  double Radius;
public:
  Circle(double R) : Radius(R) {}
};

The most basic working setup for LLVM-style RTTI requires the following
steps:

In the header where you declare ``Shape``, you will want to ``#include
"llvm/Support/Casting.h"``, which declares LLVM's RTTI templates. That
way your clients don't even have to think about it.

   #include "llvm/Support/Casting.h"

, which declares LLVM’s RTTI templates. That
way your clients don’t even have to think about it.

, which declares LLVM's RTTI templates. That

In the base class, introduce an enum which discriminates all of the
different concrete classes in the hierarchy, and stash the enum value
somewhere in the base class.

Here is the code after introducing this change:

    class Shape {
    public:
   +  /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
   +  enum ShapeKind {
   +    SK_Square,
   +    SK_Circle
   +  };
   +private:
   +  const ShapeKind Kind;
   +public:
   +  ShapeKind getKind() const { return Kind; }
   +
      Shape() {}
      virtual double computeArea() = 0;
    };

You will usually want to keep the ``Kind`` member encapsulated and
private, but let the enum ``ShapeKind`` be public along with providing a
``getKind()`` method. This is convenient for clients so that they can do
a ``switch`` over the enum.

A common naming convention is that these enums are "kind"s, to avoid
ambiguity with the words "type" or "class" which have overloaded meanings
in many contexts within LLVM. Sometimes there will be a natural name for
it, like "opcode". Don't bikeshed over this; when in doubt use ``Kind``.

You might wonder why the ``Kind`` enum doesn't have an entry for
``Shape``. The reason for this is that since ``Shape`` is abstract
(``computeArea() = 0;``), you will never actually have non-derived
instances of exactly that class (only subclasses). See `Concrete Bases
and Deeper Hierarchies`_ for information on how to deal with
non-abstract bases. It's worth mentioning here that unlike
``dynamic_cast<>``, LLVM-style RTTI can be used (and is often used) for
classes that don't have v-tables.

 class Shape {
 public:
+  /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
+  enum ShapeKind {
+    SK_Square,
+    SK_Circle
+  };
+private:
+  const ShapeKind Kind;
+public:
+  ShapeKind getKind() const { return Kind; }
+
   Shape() {}
   virtual double computeArea() = 0;
 };

A common naming convention is that these enums are “kind”s, to avoid
ambiguity with the words “type” or “class” which have overloaded meanings
it, like “opcode”. Don’t bikeshed over this; when in doubt use 

it, like "opcode". Don't bikeshed over this; when in doubt use 

), you will never actually have non-derived
instances of exactly that class (only subclasses). See 

 for information on how to deal with
non-abstract bases. It’s worth mentioning here that unlike

, LLVM-style RTTI can be used (and is often used) for
classes that don’t have v-tables.

Next, you need to make sure that the ``Kind`` gets initialized to the
value corresponding to the dynamic type of the class. Typically, you will
want to have it be an argument to the constructor of the base class, and
then pass in the respective ``XXXKind`` from subclass constructors.

Here is the code after that change:

    public:
      /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
      enum ShapeKind {
        SK_Square,
        SK_Circle
      };
    private:
      const ShapeKind Kind;
    public:
      ShapeKind getKind() const { return Kind; }

   -  Shape() {}
   +  Shape(ShapeKind K) : Kind(K) {}
    };

    class Square : public Shape {
      double SideLength;
    public:
   -  Square(double S) : SideLength(S) {}
   +  Square(double S) : Shape(SK_Square), SideLength(S) {}
      double computeArea() override;
    };

    class Circle : public Shape {
      double Radius;
    public:
   -  Circle(double R) : Radius(R) {}
   +  Circle(double R) : Shape(SK_Circle), Radius(R) {}
    };

 gets initialized to the
then pass in the respective 

 public:
   /// Discriminator for LLVM-style RTTI (dyn_cast<> et al.)
   enum ShapeKind {
     SK_Square,
     SK_Circle
   };
 private:
   const ShapeKind Kind;
 public:
   ShapeKind getKind() const { return Kind; }

-  Shape() {}
+  Shape(ShapeKind K) : Kind(K) {}
 };

 class Square : public Shape {
   double SideLength;
 public:
-  Square(double S) : SideLength(S) {}
+  Square(double S) : Shape(SK_Square), SideLength(S) {}
   double computeArea() override;
 };

 class Circle : public Shape {
   double Radius;
 public:
-  Circle(double R) : Radius(R) {}
+  Circle(double R) : Shape(SK_Circle), Radius(R) {}
 };

Finally, you need to inform LLVM's RTTI templates how to dynamically
determine the type of a class (i.e. whether the ``isa<>``/``dyn_cast<>``
should succeed). The default "99.9% of use cases" way to accomplish this
is through a small static member function ``classof``. In order to have
proper context for an explanation, we will display this code first, and
then below describe each part:

    public:
        SK_Circle
      };
    private:
    public:

      Shape(ShapeKind K) : Kind(K) {}
    };

    public:
      Square(double S) : Shape(SK_Square), SideLength(S) {}
   +
   +  static bool classof(const Shape *S) {
   +    return S->getKind() == SK_Square;
   +  }
    };

    public:
      Circle(double R) : Shape(SK_Circle), Radius(R) {}
   +
   +    return S->getKind() == SK_Circle;
   +  }
    };

The job of ``classof`` is to dynamically determine whether an object of
a base class is in fact of a particular derived class.  In order to
downcast a type ``Base`` to a type ``Derived``, there needs to be a
``classof`` in ``Derived`` which will accept an object of type ``Base``.

To be concrete, consider the following code:

   Shape *S = ...;
   if (isa<Circle>(S)) {
     /* do something ... */
   }

The code of the ``isa<>`` test in this code will eventually boil
down---after template instantiation and some other machinery---to a
check roughly like ``Circle::classof(S)``. For more information, see
:ref:`classof-contract`.

The argument to ``classof`` should always be an *ancestor* class because
the implementation has logic to allow and optimize away
upcasts/up-``isa<>``'s automatically. It is as though every class
``Foo`` automatically has a ``classof`` like:

   class Foo {
     [...]
     template <class T>
     static bool classof(const T *,
                         ::std::enable_if<
                           ::std::is_base_of<Foo, T>::value
                         >::type* = 0) { return true; }
     [...]
   };

Note that this is the reason that we did not need to introduce a
``classof`` into ``Shape``: all relevant classes derive from ``Shape``,
and ``Shape`` itself is abstract (has no entry in the ``Kind`` enum),
so this notional inferred ``classof`` is all we need. See `Concrete
Bases and Deeper Hierarchies`_ for more information about how to extend
this example to more general hierarchies.

Finally, you need to inform LLVM’s RTTI templates how to dynamically
determine the type of a class (i.e. whether the 

should succeed). The default “99.9% of use cases” way to accomplish this
is through a small static member function 

. In order to have

 public:
     SK_Circle
   };
 private:
 public:

   Shape(ShapeKind K) : Kind(K) {}
 };

 public:
   Square(double S) : Shape(SK_Square), SideLength(S) {}
+
+  static bool classof(const Shape *S) {
+    return S->getKind() == SK_Square;
+  }
 };

 public:
   Circle(double R) : Shape(SK_Circle), Radius(R) {}
+
+    return S->getKind() == SK_Circle;
+  }
 };

 is to dynamically determine whether an object of
downcast a type 

Shape *S = ...;
if (isa<Circle>(S)) {
  /* do something ... */
}

 test in this code will eventually boil
down—after template instantiation and some other machinery—to a
check roughly like 

 class because
upcasts/up-

class Foo {
  [...]
  template <class T>
  static bool classof(const T *,
                      ::std::enable_if<
                        ::std::is_base_of<Foo, T>::value
                      >::type* = 0) { return true; }
  [...]
};

 for more information about how to extend

Although for this small example setting up LLVM-style RTTI seems like a lot
of "boilerplate", if your classes are doing anything interesting then this
will end up being a tiny fraction of the code.

of “boilerplate”, if your classes are doing anything interesting then this

For concrete bases (i.e. non-abstract interior nodes of the inheritance
tree), the ``Kind`` check inside ``classof`` needs to be a bit more
complicated. The situation differs from the example above in that

tree), the 

 needs to be a bit more

Since the class is concrete, it must itself have an entry in the ``Kind``
enum because it is possible to have objects with this class as a dynamic
type.

type.

Since the class is concrete, it must itself have an entry in the 

type.

Since the class has children, the check inside ``classof`` must take them
into account.

Say that ``SpecialSquare`` and ``OtherSpecialSquare`` derive
from ``Square``, and so ``ShapeKind`` becomes:

 enum ShapeKind {
   SK_Square,
+  SK_SpecialSquare,
+  SK_OtherSpecialSquare,
   SK_Circle
 }

Then in ``Square``, we would need to modify the ``classof`` like so:

-  static bool classof(const Shape *S) {
-    return S->getKind() == SK_Square;
-  }
+    return S->getKind() >= SK_Square &&
+           S->getKind() <= SK_OtherSpecialSquare;
+  }

The reason that we need to test a range like this instead of just equality
is that both ``SpecialSquare`` and ``OtherSpecialSquare`` "is-a"
``Square``, and so ``classof`` needs to return ``true`` for them.

is that both 

This approach can be made to scale to arbitrarily deep hierarchies. The
trick is that you arrange the enum values so that they correspond to a
preorder traversal of the class hierarchy tree. With that arrangement, all
subclass tests can be done with two comparisons as shown above. If you just
list the class hierarchy like a list of bullet points, you'll get the
ordering right::

list the class hierarchy like a list of bullet points, you’ll get the
ordering right:

| Shape
  | Square
    | SpecialSquare
    | OtherSpecialSquare
  | Circle

The example just given opens the door to bugs where the ``classof``\s are
not updated to match the ``Kind`` enum when adding (or removing) classes to
(from) the hierarchy.

 enum when adding (or removing) classes to

Continuing the example above, suppose we add a ``SomewhatSpecialSquare`` as
a subclass of ``Square``, and update the ``ShapeKind`` enum like so:

   SK_SpecialSquare,
   SK_OtherSpecialSquare,
+  SK_SomewhatSpecialSquare,
   SK_Circle
 }

Now, suppose that we forget to update ``Square::classof()``, so it still
looks like:

static bool classof(const Shape *S) {
  // BUG: Returns false when S->getKind() == SK_SomewhatSpecialSquare,
  // even though SomewhatSpecialSquare "is a" Square.
  return S->getKind() >= SK_Square &&
         S->getKind() <= SK_OtherSpecialSquare;
}

As the comment indicates, this code contains a bug. A straightforward and
non-clever way to avoid this is to introduce an explicit ``SK_LastSquare``
entry in the enum when adding the first subclass(es). For example, we could
rewrite the example at the beginning of `Concrete Bases and Deeper
Hierarchies`_ as:

non-clever way to avoid this is to introduce an explicit 

rewrite the example at the beginning of 

+  SK_LastSquare,
   SK_Circle
 }
...
// Square::classof()
-  }
+           S->getKind() <= SK_LastSquare;
+  }

   SK_LastSquare,
   SK_Circle
 }

The ``Kind`` enum should have one entry per concrete class, ordered
according to a preorder traversal of the inheritance tree.

 enum should have one entry per concrete class, ordered

The argument to ``classof`` should be a ``const Base *``, where ``Base``
is some ancestor in the inheritance hierarchy. The argument should
*never* be a derived class or the class itself: the template machinery
for ``isa<>`` already handles this case and optimizes it.

 be a derived class or the class itself: the template machinery
for 

For each class in the hierarchy that has no children, implement a
``classof`` that checks only against its ``Kind``.

For each class in the hierarchy that has children, implement a
``classof`` that checks a range of the first child's ``Kind`` and the
last child's ``Kind``.

Sometimes it is not possible to know all types in a hierarchy ahead of time.
For example, in the shapes hierarchy described above the authors may have
wanted their code to work for user defined shapes too. To support use cases
that require open hierarchies LLVM provides the ``RTTIRoot`` and
``RTTIExtends`` utilities.

that require open hierarchies LLVM provides the 

The ``RTTIRoot`` class describes an interface for performing RTTI checks. The
``RTTIExtends`` class template provides an implementation of this interface
for classes derived from ``RTTIRoot``. ``RTTIExtends`` uses the "`Curiously
Recurring Template Idiom`_", taking the class being defined as its first
template argument and the parent class as the second argument. Any class that
uses ``RTTIExtends`` must define a ``static char ID`` member, the address of
which will be used to identify the type.

 class template provides an implementation of this interface
for classes derived from 

”, taking the class being defined as its first
uses 

", taking the class being defined as its first
uses 

 member, the address of

This open-hierarchy RTTI support should only be used if your use case requires
it. Otherwise the standard LLVM RTTI system should be preferred.

.. _`Curiously Recurring Template Idiom`:
  https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

class Shape : public RTTIExtends<Shape, RTTIRoot> {
public:
  static char ID;
};

class Square : public RTTIExtends<Square, Shape> {
public:

};

class Circle : public RTTIExtends<Circle, Shape> {
public:

};

char Shape::ID = 0;
char Square::ID = 0;
char Circle::ID = 0;

For example, LLVM-style RTTI can work fine in the presence of
multiple-inheritance by defining an appropriate ``classof``.
An example of this in practice is
`Decl <https://clang.llvm.org/doxygen/classclang_1_1Decl.html>`_ vs.
`DeclContext <https://clang.llvm.org/doxygen/classclang_1_1DeclContext.html>`_
inside Clang.
The ``Decl`` hierarchy is done very similarly to the example setup
demonstrated in this tutorial.
The key part is how to then incorporate ``DeclContext``: all that is needed
is in ``bool DeclContext::classof(const Decl *)``, which asks the question
"Given a ``Decl``, how can I determine if it is-a ``DeclContext``?".
It answers this with a simple switch over the set of ``Decl`` "kinds", and
returning true for ones that are known to be ``DeclContext``'s.

multiple-inheritance by defining an appropriate 

 hierarchy is done very similarly to the example setup
The key part is how to then incorporate 

To be more precise, let ``classof`` be inside a class ``C``.  Then the
contract for ``classof`` is "return ``true`` if the dynamic type of the
argument is-a ``C``".  As long as your implementation fulfills this
contract, you can tweak and optimize it as much as you want.

”.  As long as your implementation fulfills this

".  As long as your implementation fulfills this

Abandon Pygments' horrible `llvm` lexer. It just totally gives up
on highlighting this due to the first line.

 lexer. It just totally gives up

Welcome to Chapter 3 of the "`Implementing a language with
LLVM <index.html>`_" tutorial. This chapter shows you how to transform
the `Abstract Syntax Tree <LangImpl02.html>`_, built in Chapter 2, into
LLVM IR. This will teach you a little bit about how LLVM does things, as
well as demonstrate how easy it is to use. It's much more work to build
a lexer and parser than it is to generate LLVM IR code. :)

, built in Chapter 2, into
well as demonstrate how easy it is to use. It’s much more work to build

**Please note**: the code in this chapter and later require LLVM 3.7 or
later. LLVM 3.6 and before will not work with it. Also note that you
need to use a version of this tutorial that matches your LLVM release:
If you are using an official LLVM release, use the version of the
documentation included with your release or on the `llvm.org releases
page <https://llvm.org/releases/>`_.

: the code in this chapter and later require LLVM 3.7 or
documentation included with your release or on the 

In order to generate LLVM IR, we want some simple setup to get started.
First we define virtual code generation (codegen) methods in each AST
class:

/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
  virtual ~ExprAST() {}
  virtual Value *codegen() = 0;
};

/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
  double Val;

public:
  NumberExprAST(double Val) : Val(Val) {}
  virtual Value *codegen();
};
...

The codegen() method says to emit IR for that AST node along with all
the things it depends on, and they all return an LLVM Value object.
"Value" is the class used to represent a "`Static Single Assignment
(SSA) <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
register" or "SSA value" in LLVM. The most distinct aspect of SSA values
is that their value is computed as the related instruction executes, and
it does not get a new value until (and if) the instruction re-executes.
In other words, there is no way to "change" an SSA value. For more
information, please read up on `Static Single
Assignment <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
- the concepts are really quite natural once you grok them.

“Value” is the class used to represent a “

"Value" is the class used to represent a "

`Static Single Assignment

register” or “SSA value” in LLVM. The most distinct aspect of SSA values
In other words, there is no way to “change” an SSA value. For more
information, please read up on 

`Static Single

Note that instead of adding virtual methods to the ExprAST class
hierarchy, it could also make sense to use a `visitor
pattern <http://en.wikipedia.org/wiki/Visitor_pattern>`_ or some other
way to model this. Again, this tutorial won't dwell on good software
engineering practices: for our purposes, adding a virtual method is
simplest.

hierarchy, it could also make sense to use a 

`visitor
pattern <http://en.wikipedia.org/wiki/Visitor_pattern>`_

 or some other
way to model this. Again, this tutorial won’t dwell on good software
simplest.

simplest.

The second thing we want is a "LogError" method like we used for the
parser, which will be used to report errors found during code generation
(for example, use of an undeclared parameter):

The second thing we want is a “LogError” method like we used for the

static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);
static std::unique_ptr<Module> TheModule;
static std::map<std::string, Value *> NamedValues;

Value *LogErrorV(const char *Str) {
  LogError(Str);
  return nullptr;
}

The static variables will be used during code generation. ``TheContext``
is an opaque object that owns a lot of core LLVM data structures, such as
the type and constant value tables. We don't need to understand it in
detail, we just need a single instance to pass into APIs that require it.

the type and constant value tables. We don’t need to understand it in

The ``Builder`` object is a helper object that makes it easy to generate
LLVM instructions. Instances of the
`IRBuilder <https://llvm.org/doxygen/IRBuilder_8h_source.html>`_
class template keep track of the current place to insert instructions
and has methods to create new instructions.

 object is a helper object that makes it easy to generate

``TheModule`` is an LLVM construct that contains functions and global
variables. In many ways, it is the top-level structure that the LLVM IR
uses to contain code. It will own the memory for all of the IR that we
generate, which is why the codegen() method returns a raw Value\*,
rather than a unique_ptr<Value>.

 is an LLVM construct that contains functions and global
generate, which is why the codegen() method returns a raw Value*,

The ``NamedValues`` map keeps track of which values are defined in the
current scope and what their LLVM representation is. (In other words, it
is a symbol table for the code). In this form of Kaleidoscope, the only
things that can be referenced are function parameters. As such, function
parameters will be in this map when generating code for their function
body.

 map keeps track of which values are defined in the
body.

With these basics in place, we can start talking about how to generate
code for each expression. Note that this assumes that the ``Builder``
has been set up to generate code *into* something. For now, we'll assume
that this has already been done, and we'll just use it to emit code.

code for each expression. Note that this assumes that the 

 something. For now, we’ll assume
that this has already been done, and we’ll just use it to emit code.

 something. For now, we'll assume

Generating LLVM code for expression nodes is very straightforward: less
than 45 lines of commented code for all four of our expression nodes.
First we'll do numeric literals:

First we’ll do numeric literals:

Value *NumberExprAST::codegen() {
  return ConstantFP::get(TheContext, APFloat(Val));
}

In the LLVM IR, numeric constants are represented with the
``ConstantFP`` class, which holds the numeric value in an ``APFloat``
internally (``APFloat`` has the capability of holding floating point
constants of Arbitrary Precision). This code basically just creates
and returns a ``ConstantFP``. Note that in the LLVM IR that constants
are all uniqued together and shared. For this reason, the API uses the
"foo::get(...)" idiom instead of "new foo(..)" or "foo::Create(..)".

 has the capability of holding floating point
and returns a 

. Note that in the LLVM IR that constants
“foo::get(…)” idiom instead of “new foo(..)” or “foo::Create(..)”.

Value *VariableExprAST::codegen() {
  // Look this variable up in the function.
  Value *V = NamedValues[Name];
  if (!V)
    LogErrorV("Unknown variable name");
  return V;
}

References to variables are also quite simple using LLVM. In the simple
version of Kaleidoscope, we assume that the variable has already been
emitted somewhere and its value is available. In practice, the only
values that can be in the ``NamedValues`` map are function arguments.
This code simply checks to see that the specified name is in the map (if
not, an unknown variable is being referenced) and returns the value for
it. In future chapters, we'll add support for `loop induction
variables <LangImpl05.html#for-loop-expression>`_ in the symbol table, and for `local
variables <LangImpl07.html#user-defined-local-variables>`_.

values that can be in the 

 map are function arguments.
it. In future chapters, we’ll add support for 

it. In future chapters, we'll add support for 

`loop induction
variables <LangImpl05.html#for-loop-expression>`_

`local
variables <LangImpl07.html#user-defined-local-variables>`_

Value *BinaryExprAST::codegen() {
  Value *L = LHS->codegen();
  Value *R = RHS->codegen();
  if (!L || !R)
    return nullptr;

  switch (Op) {
  case '+':
    return Builder.CreateFAdd(L, R, "addtmp");
  case '-':
    return Builder.CreateFSub(L, R, "subtmp");
  case '*':
    return Builder.CreateFMul(L, R, "multmp");
  case '<':
    L = Builder.CreateFCmpULT(L, R, "cmptmp");
    // Convert bool 0/1 to double 0.0 or 1.0
    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                "booltmp");
  default:
    return LogErrorV("invalid binary operator");
  }
}

Binary operators start to get more interesting. The basic idea here is
that we recursively emit code for the left-hand side of the expression,
then the right-hand side, then we compute the result of the binary
expression. In this code, we do a simple switch on the opcode to create
the right LLVM instruction.

In the example above, the LLVM builder class is starting to show its
value. IRBuilder knows where to insert the newly created instruction,
all you have to do is specify what instruction to create (e.g. with
``CreateFAdd``), which operands to use (``L`` and ``R`` here) and
optionally provide a name for the generated instruction.

 here) and

One nice thing about LLVM is that the name is just a hint. For instance,
if the code above emits multiple "addtmp" variables, LLVM will
automatically provide each one with an increasing, unique numeric
suffix. Local value names for instructions are purely optional, but it
makes it much easier to read the IR dumps.

if the code above emits multiple “addtmp” variables, LLVM will

`LLVM instructions <../../LangRef.html#instruction-reference>`_ are constrained by strict
rules: for example, the Left and Right operators of an `add
instruction <../../LangRef.html#add-instruction>`_ must have the same type, and the
result type of the add must match the operand types. Because all values
in Kaleidoscope are doubles, this makes for very simple code for add,
sub and mul.

 are constrained by strict
rules: for example, the Left and Right operators of an 

 must have the same type, and the

On the other hand, LLVM specifies that the `fcmp
instruction <../../LangRef.html#fcmp-instruction>`_ always returns an 'i1' value (a
one bit integer). The problem with this is that Kaleidoscope wants the
value to be a 0.0 or 1.0 value. In order to get these semantics, we
combine the fcmp instruction with a `uitofp
instruction <../../LangRef.html#uitofp-to-instruction>`_. This instruction converts its
input integer into a floating point value by treating the input as an
unsigned value. In contrast, if we used the `sitofp
instruction <../../LangRef.html#sitofp-to-instruction>`_, the Kaleidoscope '<' operator
would return 0.0 and -1.0, depending on the input value.

 always returns an ‘i1’ value (a
combine the fcmp instruction with a 

 always returns an 'i1' value (a

`uitofp
instruction <../../LangRef.html#uitofp-to-instruction>`_

. This instruction converts its
unsigned value. In contrast, if we used the 

`sitofp
instruction <../../LangRef.html#sitofp-to-instruction>`_

, the Kaleidoscope ‘<’ operator

, the Kaleidoscope '<' operator

Value *CallExprAST::codegen() {
  // Look up the name in the global module table.
  Function *CalleeF = TheModule->getFunction(Callee);
  if (!CalleeF)
    return LogErrorV("Unknown function referenced");

  // If argument mismatch error.
  if (CalleeF->arg_size() != Args.size())
    return LogErrorV("Incorrect # arguments passed");

  std::vector<Value *> ArgsV;
  for (unsigned i = 0, e = Args.size(); i != e; ++i) {
    ArgsV.push_back(Args[i]->codegen());
    if (!ArgsV.back())
      return nullptr;
  }

  return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
}

Code generation for function calls is quite straightforward with LLVM. The code
above initially does a function name lookup in the LLVM Module's symbol table.
Recall that the LLVM Module is the container that holds the functions we are
JIT'ing. By giving each function the same name as what the user specifies, we
can use the LLVM symbol table to resolve function names for us.

above initially does a function name lookup in the LLVM Module’s symbol table.
JIT’ing. By giving each function the same name as what the user specifies, we

Once we have the function to call, we recursively codegen each argument
that is to be passed in, and create an LLVM `call
instruction <../../LangRef.html#call-instruction>`_. Note that LLVM uses the native C
calling conventions by default, allowing these calls to also call into
standard library functions like "sin" and "cos", with no additional
effort.

that is to be passed in, and create an LLVM 

. Note that LLVM uses the native C
standard library functions like “sin” and “cos”, with no additional
effort.

effort.

This wraps up our handling of the four basic expressions that we have so
far in Kaleidoscope. Feel free to go in and add some more. For example,
by browsing the `LLVM language reference <../../LangRef.html>`_ you'll find
several other interesting instructions that are really easy to plug into
our basic framework.

by browsing the 

 you’ll find

 you'll find

Code generation for prototypes and functions must handle a number of
details, which make their code less beautiful than expression code
generation, but allows us to illustrate some important points. First,
let's talk about code generation for prototypes: they are used both for
function bodies and external function declarations. The code starts
with:

let’s talk about code generation for prototypes: they are used both for
with:

Function *PrototypeAST::codegen() {
  // Make the function type:  double(double,double) etc.
  std::vector<Type*> Doubles(Args.size(),
                             Type::getDoubleTy(TheContext));
  FunctionType *FT =
    FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);

  Function *F =
    Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());

This code packs a lot of power into a few lines. Note first that this
function returns a "Function\*" instead of a "Value\*". Because a
"prototype" really talks about the external interface for a function
(not the value computed by an expression), it makes sense for it to
return the LLVM Function it corresponds to when codegen'd.

The call to ``FunctionType::get`` creates the ``FunctionType`` that
should be used for a given Prototype. Since all function arguments in
Kaleidoscope are of type double, the first line creates a vector of "N"
LLVM double types. It then uses the ``Functiontype::get`` method to
create a function type that takes "N" doubles as arguments, returns one
double as a result, and that is not vararg (the false parameter
indicates this). Note that Types in LLVM are uniqued just like Constants
are, so you don't "new" a type, you "get" it.

 that
Kaleidoscope are of type double, the first line creates a vector of “N”
LLVM double types. It then uses the 

 that

 method to
create a function type that takes “N” doubles as arguments, returns one
are, so you don’t “new” a type, you “get” it.

 method to

The final line above actually creates the IR Function corresponding to
the Prototype. This indicates the type, linkage and name to use, as
well as which module to insert into. "`external
linkage <../../LangRef.html#linkage>`_" means that the function may be
defined outside the current module and/or that it is callable by
functions outside the module. The Name passed in is the name the user
specified: since "``TheModule``" is specified, this name is registered
in "``TheModule``"s symbol table.

well as which module to insert into. “

well as which module to insert into. "

” means that the function may be
specified: since “

" means that the function may be
specified: since "

// Set names for all arguments.
unsigned Idx = 0;
for (auto &Arg : F->args())
  Arg.setName(Args[Idx++]);

return F;

Finally, we set the name of each of the function's arguments according to the
names given in the Prototype. This step isn't strictly necessary, but keeping
the names consistent makes the IR more readable, and allows subsequent code to
refer directly to the arguments for their names, rather than having to look up
them up in the Prototype AST.

Finally, we set the name of each of the function’s arguments according to the
names given in the Prototype. This step isn’t strictly necessary, but keeping

At this point we have a function prototype with no body. This is how LLVM IR
represents function declarations. For extern statements in Kaleidoscope, this
is as far as we need to go. For function definitions however, we need to
codegen and attach a function body.

Function *FunctionAST::codegen() {
    // First, check for an existing function from a previous 'extern' declaration.
  Function *TheFunction = TheModule->getFunction(Proto->getName());

  if (!TheFunction)
    TheFunction = Proto->codegen();

  if (!TheFunction->empty())
    return (Function*)LogErrorV("Function cannot be redefined.");

For function definitions, we start by searching TheModule's symbol table for an
existing version of this function, in case one has already been created using an
'extern' statement. If Module::getFunction returns null then no previous version
exists, so we'll codegen one from the Prototype. In either case, we want to
assert that the function is empty (i.e. has no body yet) before we start.

For function definitions, we start by searching TheModule’s symbol table for an
‘extern’ statement. If Module::getFunction returns null then no previous version
exists, so we’ll codegen one from the Prototype. In either case, we want to

// Create a new basic block to start insertion into.
BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Builder.SetInsertPoint(BB);

// Record the function arguments in the NamedValues map.
NamedValues.clear();
for (auto &Arg : TheFunction->args())
  NamedValues[Arg.getName()] = &Arg;

Now we get to the point where the ``Builder`` is set up. The first line
creates a new `basic block <http://en.wikipedia.org/wiki/Basic_block>`_
(named "entry"), which is inserted into ``TheFunction``. The second line
then tells the builder that new instructions should be inserted into the
end of the new basic block. Basic blocks in LLVM are an important part
of functions that define the `Control Flow
Graph <http://en.wikipedia.org/wiki/Control_flow_graph>`_. Since we
don't have any control flow, our functions will only contain one block
at this point. We'll fix this in `Chapter 5 <LangImpl05.html>`_ :).

. The second line
of functions that define the 

`Control Flow
Graph <http://en.wikipedia.org/wiki/Control_flow_graph>`_

. Since we
don’t have any control flow, our functions will only contain one block
at this point. We’ll fix this in 

. Since we
at this point. We'll fix this in 

Next we add the function arguments to the NamedValues map (after first clearing
it out) so that they're accessible to ``VariableExprAST`` nodes.

it out) so that they’re accessible to 

it out) so that they're accessible to 

if (Value *RetVal = Body->codegen()) {
  // Finish off the function.
  Builder.CreateRet(RetVal);

  // Validate the generated code, checking for consistency.
  verifyFunction(*TheFunction);

  return TheFunction;
}

Once the insertion point has been set up and the NamedValues map populated,
we call the ``codegen()`` method for the root expression of the function. If no
error happens, this emits code to compute the expression into the entry block
and returns the value that was computed. Assuming no error, we then create an
LLVM `ret instruction <../../LangRef.html#ret-instruction>`_, which completes the function.
Once the function is built, we call ``verifyFunction``, which is
provided by LLVM. This function does a variety of consistency checks on
the generated code, to determine if our compiler is doing everything
right. Using this is important: it can catch a lot of bugs. Once the
function is finished and validated, we return it.

we call the 

 method for the root expression of the function. If no
LLVM 

, which completes the function.
Once the function is built, we call 

, which is

  // Error reading body, remove function.
  TheFunction->eraseFromParent();
}

The only piece left here is handling of the error case. For simplicity,
we handle this by merely deleting the function we produced with the
``eraseFromParent`` method. This allows the user to redefine a function
that they incorrectly typed in before: if we didn't delete it, it would
live in the symbol table, with a body, preventing future redefinition.

 method. This allows the user to redefine a function
that they incorrectly typed in before: if we didn’t delete it, it would

This code does have a bug, though: If the ``FunctionAST::codegen()`` method
finds an existing IR Function, it does not validate its signature against the
definition's own prototype. This means that an earlier 'extern' declaration will
take precedence over the function definition's signature, which can cause
codegen to fail, for instance if the function arguments are named differently.
There are a number of ways to fix this bug, see what you can come up with! Here
is a testcase:

 method
definition’s own prototype. This means that an earlier ‘extern’ declaration will
take precedence over the function definition’s signature, which can cause

 method

extern foo(a);     # ok, defines foo.
def foo(b) b;      # Error: Unknown variable name. (decl using 'a' takes precedence).

Here is the complete code listing for our running example, enhanced with
the LLVM code generator. Because this uses the LLVM libraries, we need
to link them in. To do this, we use the
`llvm-config <https://llvm.org/cmds/llvm-config.html>`_ tool to inform
our makefile/command line about which options to use:

 tool to inform

# Compile
clang++ -g -O3 toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core` -o toy
# Run
./toy

#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <string>
#include <vector>

//===----------------------------------------------------------------------===//
// Lexer

// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token {
  tok_eof = -1,

  // commands
  tok_def = -2,
  tok_extern = -3,

  // primary
  tok_identifier = -4,
  tok_number = -5
};

static std::string IdentifierStr; // Filled in if tok_identifier
static double NumVal;             // Filled in if tok_number

/// gettok - Return the next token from standard input.
static int gettok() {
  static int LastChar = ' ';

  // Skip any whitespace.
  while (isspace(LastChar))
    LastChar = getchar();

  if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
    IdentifierStr = LastChar;
    while (isalnum((LastChar = getchar())))
      IdentifierStr += LastChar;

    if (IdentifierStr == "def")
      return tok_def;
    if (IdentifierStr == "extern")
      return tok_extern;
    return tok_identifier;
  }

  if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
    std::string NumStr;
    do {
      NumStr += LastChar;
      LastChar = getchar();
    } while (isdigit(LastChar) || LastChar == '.');

    NumVal = strtod(NumStr.c_str(), nullptr);
    return tok_number;
  }

  if (LastChar == '#') {
    // Comment until end of line.
    do
    while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');

    if (LastChar != EOF)
      return gettok();
  }

  // Check for end of file.  Don't eat the EOF.
  if (LastChar == EOF)
    return tok_eof;

  // Otherwise, just return the character as its ascii value.
  int ThisChar = LastChar;
  LastChar = getchar();
  return ThisChar;
}

// Abstract Syntax Tree (aka Parse Tree)

namespace {

public:
  virtual ~ExprAST() = default;

};

public:

  Value *codegen() override;
};

/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
  std::string Name;

public:
  VariableExprAST(const std::string &Name) : Name(Name) {}

};

/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : public ExprAST {
  char Op;
  std::unique_ptr<ExprAST> LHS, RHS;

public:
  BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
                std::unique_ptr<ExprAST> RHS)
      : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}

};

/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
  std::string Callee;
  std::vector<std::unique_ptr<ExprAST>> Args;

public:
  CallExprAST(const std::string &Callee,
              std::vector<std::unique_ptr<ExprAST>> Args)
      : Callee(Callee), Args(std::move(Args)) {}

};

/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
class PrototypeAST {
  std::vector<std::string> Args;

public:
  PrototypeAST(const std::string &Name, std::vector<std::string> Args)
      : Name(Name), Args(std::move(Args)) {}

  Function *codegen();
  const std::string &getName() const { return Name; }
};

/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
  std::unique_ptr<PrototypeAST> Proto;
  std::unique_ptr<ExprAST> Body;

public:
  FunctionAST(std::unique_ptr<PrototypeAST> Proto,
              std::unique_ptr<ExprAST> Body)
      : Proto(std::move(Proto)), Body(std::move(Body)) {}

};

} // end anonymous namespace

// Parser

/// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
/// token the parser is looking at.  getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() { return CurTok = gettok(); }

/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;

/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
  if (!isascii(CurTok))
    return -1;

  // Make sure it's a declared binop.
  int TokPrec = BinopPrecedence[CurTok];
  if (TokPrec <= 0)
    return -1;
  return TokPrec;
}

/// LogError* - These are little helper functions for error handling.
std::unique_ptr<ExprAST> LogError(const char *Str) {
  fprintf(stderr, "Error: %s\n", Str);
}

std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
}

static std::unique_ptr<ExprAST> ParseExpression();

/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
  auto Result = std::make_unique<NumberExprAST>(NumVal);
  getNextToken(); // consume the number
  return std::move(Result);
}

/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr() {
  getNextToken(); // eat (.
  auto V = ParseExpression();
  if (!V)

  if (CurTok != ')')
    return LogError("expected ')'");
  getNextToken(); // eat ).
  return V;
}

/// identifierexpr
///   ::= identifier
///   ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
  std::string IdName = IdentifierStr;

  getNextToken(); // eat identifier.

  if (CurTok != '(') // Simple variable ref.
    return std::make_unique<VariableExprAST>(IdName);

  // Call.
  getNextToken(); // eat (
  if (CurTok != ')') {
    while (true) {
      if (auto Arg = ParseExpression())
        Args.push_back(std::move(Arg));
      else
        return nullptr;

      if (CurTok == ')')
        break;

      if (CurTok != ',')
        return LogError("Expected ')' or ',' in argument list");
      getNextToken();
    }
  }

  // Eat the ')'.
  getNextToken();

  return std::make_unique<CallExprAST>(IdName, std::move(Args));
}

/// primary
///   ::= identifierexpr
///   ::= numberexpr
///   ::= parenexpr
static std::unique_ptr<ExprAST> ParsePrimary() {
  switch (CurTok) {
  default:
    return LogError("unknown token when expecting an expression");
  case tok_identifier:
    return ParseIdentifierExpr();
  case tok_number:
    return ParseNumberExpr();
  case '(':
    return ParseParenExpr();
  }
}

/// binoprhs
///   ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
                                              std::unique_ptr<ExprAST> LHS) {
  // If this is a binop, find its precedence.
  while (true) {
    int TokPrec = GetTokPrecedence();

    // If this is a binop that binds at least as tightly as the current binop,
    // consume it, otherwise we are done.
    if (TokPrec < ExprPrec)
      return LHS;

    // Okay, we know this is a binop.
    int BinOp = CurTok;
    getNextToken(); // eat binop

    // Parse the primary expression after the binary operator.
    auto RHS = ParsePrimary();
    if (!RHS)

    // If BinOp binds less tightly with RHS than the operator after RHS, let
    // the pending operator take RHS as its LHS.
    int NextPrec = GetTokPrecedence();
    if (TokPrec < NextPrec) {
      RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
      if (!RHS)
    }

    // Merge LHS/RHS.
    LHS =
        std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
  }
}

/// expression
///   ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
  auto LHS = ParsePrimary();
  if (!LHS)

  return ParseBinOpRHS(0, std::move(LHS));
}

/// prototype
///   ::= id '(' id* ')'
static std::unique_ptr<PrototypeAST> ParsePrototype() {
  if (CurTok != tok_identifier)
    return LogErrorP("Expected function name in prototype");

  std::string FnName = IdentifierStr;

  if (CurTok != '(')
    return LogErrorP("Expected '(' in prototype");

  std::vector<std::string> ArgNames;
  while (getNextToken() == tok_identifier)
    ArgNames.push_back(IdentifierStr);
    return LogErrorP("Expected ')' in prototype");

  // success.
  getNextToken(); // eat ')'.

  return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}

/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> ParseDefinition() {
  getNextToken(); // eat def.
  auto Proto = ParsePrototype();
  if (!Proto)

  if (auto E = ParseExpression())
    return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
}

/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
  if (auto E = ParseExpression()) {
    // Make an anonymous proto.
    auto Proto = std::make_unique<PrototypeAST>("__anon_expr",
                                                 std::vector<std::string>());
  }
}

/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
  getNextToken(); // eat extern.
  return ParsePrototype();
}

// Code Generation

static std::unique_ptr<LLVMContext> TheContext;
static std::unique_ptr<IRBuilder<>> Builder;

}

  return ConstantFP::get(*TheContext, APFloat(Val));
}

  if (!V)
    return LogErrorV("Unknown variable name");
  return V;
}

  case '+':
    return Builder->CreateFAdd(L, R, "addtmp");
  case '-':
    return Builder->CreateFSub(L, R, "subtmp");
  case '*':
    return Builder->CreateFMul(L, R, "multmp");
  case '<':
    L = Builder->CreateFCmpULT(L, R, "cmptmp");
    return Builder->CreateUIToFP(L, Type::getDoubleTy(*TheContext), "booltmp");
  default:
  }
}

  }

  return Builder->CreateCall(CalleeF, ArgsV, "calltmp");
}

  std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(*TheContext));
      FunctionType::get(Type::getDoubleTy(*TheContext), Doubles, false);

      Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());

  // Set names for all arguments.
  unsigned Idx = 0;
  for (auto &Arg : F->args())
    Arg.setName(Args[Idx++]);

  return F;
}

  // First, check for an existing function from a previous 'extern' declaration.

  // Create a new basic block to start insertion into.
  BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", TheFunction);
  Builder->SetInsertPoint(BB);

  // Record the function arguments in the NamedValues map.
  NamedValues.clear();
  for (auto &Arg : TheFunction->args())
    NamedValues[std::string(Arg.getName())] = &Arg;

  if (Value *RetVal = Body->codegen()) {
    // Finish off the function.
    Builder->CreateRet(RetVal);

    // Validate the generated code, checking for consistency.
    verifyFunction(*TheFunction);

    return TheFunction;
  }

}

// Top-Level parsing and JIT Driver

static void InitializeModule() {
  // Open a new context and module.
  TheContext = std::make_unique<LLVMContext>();
  TheModule = std::make_unique<Module>("my cool jit", *TheContext);

  // Create a new builder for the module.
  Builder = std::make_unique<IRBuilder<>>(*TheContext);
}

static void HandleDefinition() {
  if (auto FnAST = ParseDefinition()) {
    if (auto *FnIR = FnAST->codegen()) {
      fprintf(stderr, "Read function definition:");
      FnIR->print(errs());
      fprintf(stderr, "\n");
    }
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

static void HandleExtern() {
  if (auto ProtoAST = ParseExtern()) {
    if (auto *FnIR = ProtoAST->codegen()) {
      fprintf(stderr, "Read extern: ");
    }
  } else {
  }
}

static void HandleTopLevelExpression() {
  // Evaluate a top-level expression into an anonymous function.
  if (auto FnAST = ParseTopLevelExpr()) {
      fprintf(stderr, "Read top-level expression:");

      // Remove the anonymous expression.
      FnIR->eraseFromParent();
    }
  } else {
  }
}

/// top ::= definition | external | expression | ';'
static void MainLoop() {
    fprintf(stderr, "ready> ");
    switch (CurTok) {
    case tok_eof:
      return;
    case ';': // ignore top-level semicolons.
      break;
    case tok_def:
      HandleDefinition();
      break;
    case tok_extern:
      HandleExtern();
      break;
    default:
      HandleTopLevelExpression();
      break;
    }
  }
}

// Main driver code.

int main() {
  // Install standard binary operators.
  // 1 is lowest precedence.
  BinopPrecedence['<'] = 10;
  BinopPrecedence['+'] = 20;
  BinopPrecedence['-'] = 20;
  BinopPrecedence['*'] = 40; // highest.

  // Prime the first token.
  fprintf(stderr, "ready> ");

  // Make the module, which holds all the code.
  InitializeModule();

  // Run the main "interpreter loop" now.
  MainLoop();

  // Print out all of the generated code.
  TheModule->print(errs(), nullptr);

  return 0;
}

Note how the parser turns the top-level expression into anonymous
functions for us. This will be handy when we add `JIT
support <LangImpl04.html#adding-a-jit-compiler>`_ in the next chapter. Also note that the
code is very literally transcribed, no optimizations are being performed
except simple constant folding done by IRBuilder. We will `add
optimizations <LangImpl04.html#trivial-constant-folding>`_ explicitly in the next
chapter.

functions for us. This will be handy when we add 

 in the next chapter. Also note that the
except simple constant folding done by IRBuilder. We will 

This wraps up the third chapter of the Kaleidoscope tutorial. Up next,
we'll describe how to `add JIT codegen and optimizer
support <LangImpl04.html>`_ to this so we can actually start running
code!

we’ll describe how to 

we'll describe how to 

For now, code generation to LLVM doesn't really get us much, except that
we can look at the pretty IR calls. The sample code inserts calls to
codegen into the "``HandleDefinition``", "``HandleExtern``" etc
functions, and then dumps out the LLVM IR. This gives a nice way to look
at the LLVM IR for simple functions. For example:

For now, code generation to LLVM doesn’t really get us much, except that
codegen into the “

codegen into the "

” etc

" etc

ready> 4+5;
Read top-level expression:
define double @0() {
entry:
  ret double 9.000000e+00
}

ready> def foo(a b) a*a + 2*a*b + b*b;
Read function definition:
define double @foo(double %a, double %b) {
entry:
  %multmp = fmul double %a, %a
  %multmp1 = fmul double 2.000000e+00, %a
  %multmp2 = fmul double %multmp1, %b
  %addtmp = fadd double %multmp, %multmp2
  %multmp3 = fmul double %b, %b
  %addtmp4 = fadd double %addtmp, %multmp3
  ret double %addtmp4
}

This shows some simple arithmetic. Notice the striking similarity to the
LLVM builder calls that we use to create the instructions.

ready> def bar(a) foo(a, 4.0) + bar(31337);
define double @bar(double %a) {
entry:
  %calltmp = call double @foo(double %a, double 4.000000e+00)
  %calltmp1 = call double @bar(double 3.133700e+04)
  %addtmp = fadd double %calltmp, %calltmp1
  ret double %addtmp
}

This shows some function calls. Note that this function will take a long
time to execute if you call it. In the future we'll add conditional
control flow to actually make recursion useful :).

time to execute if you call it. In the future we’ll add conditional

ready> extern cos(x);
Read extern:
declare double @cos(double)

ready> cos(1.234);
define double @1() {
entry:
  %calltmp = call double @cos(double 1.234000e+00)
  ret double %calltmp
}

This shows an extern for the libm "cos" function, and a call to it.

This shows an extern for the libm “cos” function, and a call to it.

ready> ^D
; ModuleID = 'my cool jit'

entry:
  %addtmp = fadd double 4.000000e+00, 5.000000e+00
}

entry:
}

entry:
}

entry:
}

When you quit the current demo (by sending an EOF via CTRL+D on Linux
or CTRL+Z and ENTER on Windows), it dumps out the IR for the entire
module generated. Here you can see the big picture with all the
functions referencing each other.