[ThinLTO] Add code comment. NFC
[llvm-core.git] / docs / MIRLangRef.rst
blobc2c14d9db7c1ef6013e3d0b1fb3a9a09f4be246a
1 ========================================
2 Machine IR (MIR) Format Reference Manual
3 ========================================
5 .. contents::
6    :local:
8 .. warning::
9   This is a work in progress.
11 Introduction
12 ============
14 This document is a reference manual for the Machine IR (MIR) serialization
15 format. MIR is a human readable serialization format that is used to represent
16 LLVM's :ref:`machine specific intermediate representation
17 <machine code representation>`.
19 The MIR serialization format is designed to be used for testing the code
20 generation passes in LLVM.
22 Overview
23 ========
25 The MIR serialization format uses a YAML container. YAML is a standard
26 data serialization language, and the full YAML language spec can be read at
27 `yaml.org
28 <http://www.yaml.org/spec/1.2/spec.html#Introduction>`_.
30 A MIR file is split up into a series of `YAML documents`_. The first document
31 can contain an optional embedded LLVM IR module, and the rest of the documents
32 contain the serialized machine functions.
34 .. _YAML documents: http://www.yaml.org/spec/1.2/spec.html#id2800132
36 MIR Testing Guide
37 =================
39 You can use the MIR format for testing in two different ways:
41 - You can write MIR tests that invoke a single code generation pass using the
42   ``-run-pass`` option in llc.
44 - You can use llc's ``-stop-after`` option with existing or new LLVM assembly
45   tests and check the MIR output of a specific code generation pass.
47 Testing Individual Code Generation Passes
48 -----------------------------------------
50 The ``-run-pass`` option in llc allows you to create MIR tests that invoke just
51 a single code generation pass. When this option is used, llc will parse an
52 input MIR file, run the specified code generation pass(es), and output the
53 resulting MIR code.
55 You can generate an input MIR file for the test by using the ``-stop-after`` or
56 ``-stop-before`` option in llc. For example, if you would like to write a test
57 for the post register allocation pseudo instruction expansion pass, you can
58 specify the machine copy propagation pass in the ``-stop-after`` option, as it
59 runs just before the pass that we are trying to test:
61    ``llc -stop-after=machine-cp bug-trigger.ll > test.mir``
63 If the same pass is run multiple times, a run index can be included
64 after the name with a comma.
66    ``llc -stop-after=dead-mi-elimination,1 bug-trigger.ll > test.mir``
68 After generating the input MIR file, you'll have to add a run line that uses
69 the ``-run-pass`` option to it. In order to test the post register allocation
70 pseudo instruction expansion pass on X86-64, a run line like the one shown
71 below can be used:
73     ``# RUN: llc -o - %s -mtriple=x86_64-- -run-pass=postrapseudos | FileCheck %s``
75 The MIR files are target dependent, so they have to be placed in the target
76 specific test directories (``lib/CodeGen/TARGETNAME``). They also need to
77 specify a target triple or a target architecture either in the run line or in
78 the embedded LLVM IR module.
80 Simplifying MIR files
81 ^^^^^^^^^^^^^^^^^^^^^
83 The MIR code coming out of ``-stop-after``/``-stop-before`` is very verbose;
84 Tests are more accessible and future proof when simplified:
86 - Use the ``-simplify-mir`` option with llc.
88 - Machine function attributes often have default values or the test works just
89   as well with default values. Typical candidates for this are: `alignment:`,
90   `exposesReturnsTwice`, `legalized`, `regBankSelected`, `selected`.
91   The whole `frameInfo` section is often unnecessary if there is no special
92   frame usage in the function. `tracksRegLiveness` on the other hand is often
93   necessary for some passes that care about block livein lists.
95 - The (global) `liveins:` list is typically only interesting for early
96   instruction selection passes and can be removed when testing later passes.
97   The per-block `liveins:` on the other hand are necessary if
98   `tracksRegLiveness` is true.
100 - Branch probability data in block `successors:` lists can be dropped if the
101   test doesn't depend on it. Example:
102   `successors: %bb.1(0x40000000), %bb.2(0x40000000)` can be replaced with
103   `successors: %bb.1, %bb.2`.
105 - MIR code contains a whole IR module. This is necessary because there are
106   no equivalents in MIR for global variables, references to external functions,
107   function attributes, metadata, debug info. Instead some MIR data references
108   the IR constructs. You can often remove them if the test doesn't depend on
109   them.
111 - Alias Analysis is performed on IR values. These are referenced by memory
112   operands in MIR. Example: `:: (load 8 from %ir.foobar, !alias.scope !9)`.
113   If the test doesn't depend on (good) alias analysis the references can be
114   dropped: `:: (load 8)`
116 - MIR blocks can reference IR blocks for debug printing, profile information
117   or debug locations. Example: `bb.42.myblock` in MIR references the IR block
118   `myblock`. It is usually possible to drop the `.myblock` reference and simply
119   use `bb.42`.
121 - If there are no memory operands or blocks referencing the IR then the
122   IR function can be replaced by a parameterless dummy function like
123   `define @func() { ret void }`.
125 - It is possible to drop the whole IR section of the MIR file if it only
126   contains dummy functions (see above). The .mir loader will create the
127   IR functions automatically in this case.
129 .. _limitations:
131 Limitations
132 -----------
134 Currently the MIR format has several limitations in terms of which state it
135 can serialize:
137 - The target-specific state in the target-specific ``MachineFunctionInfo``
138   subclasses isn't serialized at the moment.
140 - The target-specific ``MachineConstantPoolValue`` subclasses (in the ARM and
141   SystemZ backends) aren't serialized at the moment.
143 - The ``MCSymbol`` machine operands don't support temporary or local symbols.
145 - A lot of the state in ``MachineModuleInfo`` isn't serialized - only the CFI
146   instructions and the variable debug information from MMI is serialized right
147   now.
149 These limitations impose restrictions on what you can test with the MIR format.
150 For now, tests that would like to test some behaviour that depends on the state
151 of temporary or local ``MCSymbol``  operands or the exception handling state in
152 MMI, can't use the MIR format. As well as that, tests that test some behaviour
153 that depends on the state of the target specific ``MachineFunctionInfo`` or
154 ``MachineConstantPoolValue`` subclasses can't use the MIR format at the moment.
156 High Level Structure
157 ====================
159 .. _embedded-module:
161 Embedded Module
162 ---------------
164 When the first YAML document contains a `YAML block literal string`_, the MIR
165 parser will treat this string as an LLVM assembly language string that
166 represents an embedded LLVM IR module.
167 Here is an example of a YAML document that contains an LLVM module:
169 .. code-block:: llvm
171        define i32 @inc(i32* %x) {
172        entry:
173          %0 = load i32, i32* %x
174          %1 = add i32 %0, 1
175          store i32 %1, i32* %x
176          ret i32 %1
177        }
179 .. _YAML block literal string: http://www.yaml.org/spec/1.2/spec.html#id2795688
181 Machine Functions
182 -----------------
184 The remaining YAML documents contain the machine functions. This is an example
185 of such YAML document:
187 .. code-block:: text
189      ---
190      name:            inc
191      tracksRegLiveness: true
192      liveins:
193        - { reg: '$rdi' }
194      callSites:
195        - { bb: 0, offset: 3, fwdArgRegs:
196            - { arg: 0, reg: '$edi' } }
197      body: |
198        bb.0.entry:
199          liveins: $rdi
201          $eax = MOV32rm $rdi, 1, _, 0, _
202          $eax = INC32r killed $eax, implicit-def dead $eflags
203          MOV32mr killed $rdi, 1, _, 0, _, $eax
204          CALL64pcrel32 @foo <regmask...>
205          RETQ $eax
206      ...
208 The document above consists of attributes that represent the various
209 properties and data structures in a machine function.
211 The attribute ``name`` is required, and its value should be identical to the
212 name of a function that this machine function is based on.
214 The attribute ``body`` is a `YAML block literal string`_. Its value represents
215 the function's machine basic blocks and their machine instructions.
217 The attribute ``callSites`` is a representation of call site information which
218 keeps track of call instructions and registers used to transfer call arguments.
220 Machine Instructions Format Reference
221 =====================================
223 The machine basic blocks and their instructions are represented using a custom,
224 human readable serialization language. This language is used in the
225 `YAML block literal string`_ that corresponds to the machine function's body.
227 A source string that uses this language contains a list of machine basic
228 blocks, which are described in the section below.
230 Machine Basic Blocks
231 --------------------
233 A machine basic block is defined in a single block definition source construct
234 that contains the block's ID.
235 The example below defines two blocks that have an ID of zero and one:
237 .. code-block:: text
239     bb.0:
240       <instructions>
241     bb.1:
242       <instructions>
244 A machine basic block can also have a name. It should be specified after the ID
245 in the block's definition:
247 .. code-block:: text
249     bb.0.entry:       ; This block's name is "entry"
250        <instructions>
252 The block's name should be identical to the name of the IR block that this
253 machine block is based on.
255 .. _block-references:
257 Block References
258 ^^^^^^^^^^^^^^^^
260 The machine basic blocks are identified by their ID numbers. Individual
261 blocks are referenced using the following syntax:
263 .. code-block:: text
265     %bb.<id>
267 Example:
269 .. code-block:: llvm
271     %bb.0
273 The following syntax is also supported, but the former syntax is preferred for
274 block references:
276 .. code-block:: text
278     %bb.<id>[.<name>]
280 Example:
282 .. code-block:: llvm
284     %bb.1.then
286 Successors
287 ^^^^^^^^^^
289 The machine basic block's successors have to be specified before any of the
290 instructions:
292 .. code-block:: text
294     bb.0.entry:
295       successors: %bb.1.then, %bb.2.else
296       <instructions>
297     bb.1.then:
298       <instructions>
299     bb.2.else:
300       <instructions>
302 The branch weights can be specified in brackets after the successor blocks.
303 The example below defines a block that has two successors with branch weights
304 of 32 and 16:
306 .. code-block:: text
308     bb.0.entry:
309       successors: %bb.1.then(32), %bb.2.else(16)
311 .. _bb-liveins:
313 Live In Registers
314 ^^^^^^^^^^^^^^^^^
316 The machine basic block's live in registers have to be specified before any of
317 the instructions:
319 .. code-block:: text
321     bb.0.entry:
322       liveins: $edi, $esi
324 The list of live in registers and successors can be empty. The language also
325 allows multiple live in register and successor lists - they are combined into
326 one list by the parser.
328 Miscellaneous Attributes
329 ^^^^^^^^^^^^^^^^^^^^^^^^
331 The attributes ``IsAddressTaken``, ``IsLandingPad`` and ``Alignment`` can be
332 specified in brackets after the block's definition:
334 .. code-block:: text
336     bb.0.entry (address-taken):
337       <instructions>
338     bb.2.else (align 4):
339       <instructions>
340     bb.3(landing-pad, align 4):
341       <instructions>
343 .. TODO: Describe the way the reference to an unnamed LLVM IR block can be
344    preserved.
346 ``Alignment`` is specified in bytes, and must be a power of two.
348 Machine Instructions
349 --------------------
351 A machine instruction is composed of a name,
352 :ref:`machine operands <machine-operands>`,
353 :ref:`instruction flags <instruction-flags>`, and machine memory operands.
355 The instruction's name is usually specified before the operands. The example
356 below shows an instance of the X86 ``RETQ`` instruction with a single machine
357 operand:
359 .. code-block:: text
361     RETQ $eax
363 However, if the machine instruction has one or more explicitly defined register
364 operands, the instruction's name has to be specified after them. The example
365 below shows an instance of the AArch64 ``LDPXpost`` instruction with three
366 defined register operands:
368 .. code-block:: text
370     $sp, $fp, $lr = LDPXpost $sp, 2
372 The instruction names are serialized using the exact definitions from the
373 target's ``*InstrInfo.td`` files, and they are case sensitive. This means that
374 similar instruction names like ``TSTri`` and ``tSTRi`` represent different
375 machine instructions.
377 .. _instruction-flags:
379 Instruction Flags
380 ^^^^^^^^^^^^^^^^^
382 The flag ``frame-setup`` or ``frame-destroy`` can be specified before the
383 instruction's name:
385 .. code-block:: text
387     $fp = frame-setup ADDXri $sp, 0, 0
389 .. code-block:: text
391     $x21, $x20 = frame-destroy LDPXi $sp
393 .. _registers:
395 Bundled Instructions
396 ^^^^^^^^^^^^^^^^^^^^
398 The syntax for bundled instructions is the following:
400 .. code-block:: text
402     BUNDLE implicit-def $r0, implicit-def $r1, implicit $r2 {
403       $r0 = SOME_OP $r2
404       $r1 = ANOTHER_OP internal $r0
405     }
407 The first instruction is often a bundle header. The instructions between ``{``
408 and ``}`` are bundled with the first instruction.
410 Registers
411 ---------
413 Registers are one of the key primitives in the machine instructions
414 serialization language. They are primarily used in the
415 :ref:`register machine operands <register-operands>`,
416 but they can also be used in a number of other places, like the
417 :ref:`basic block's live in list <bb-liveins>`.
419 The physical registers are identified by their name and by the '$' prefix sigil.
420 They use the following syntax:
422 .. code-block:: text
424     $<name>
426 The example below shows three X86 physical registers:
428 .. code-block:: text
430     $eax
431     $r15
432     $eflags
434 The virtual registers are identified by their ID number and by the '%' sigil.
435 They use the following syntax:
437 .. code-block:: text
439     %<id>
441 Example:
443 .. code-block:: text
445     %0
447 The null registers are represented using an underscore ('``_``'). They can also be
448 represented using a '``$noreg``' named register, although the former syntax
449 is preferred.
451 .. _machine-operands:
453 Machine Operands
454 ----------------
456 There are seventeen different kinds of machine operands, and all of them can be
457 serialized.
459 Immediate Operands
460 ^^^^^^^^^^^^^^^^^^
462 The immediate machine operands are untyped, 64-bit signed integers. The
463 example below shows an instance of the X86 ``MOV32ri`` instruction that has an
464 immediate machine operand ``-42``:
466 .. code-block:: text
468     $eax = MOV32ri -42
470 An immediate operand is also used to represent a subregister index when the
471 machine instruction has one of the following opcodes:
473 - ``EXTRACT_SUBREG``
475 - ``INSERT_SUBREG``
477 - ``REG_SEQUENCE``
479 - ``SUBREG_TO_REG``
481 In case this is true, the Machine Operand is printed according to the target.
483 For example:
485 In AArch64RegisterInfo.td:
487 .. code-block:: text
489   def sub_32 : SubRegIndex<32>;
491 If the third operand is an immediate with the value ``15`` (target-dependent
492 value), based on the instruction's opcode and the operand's index the operand
493 will be printed as ``%subreg.sub_32``:
495 .. code-block:: text
497     %1:gpr64 = SUBREG_TO_REG 0, %0, %subreg.sub_32
499 For integers > 64bit, we use a special machine operand, ``MO_CImmediate``,
500 which stores the immediate in a ``ConstantInt`` using an ``APInt`` (LLVM's
501 arbitrary precision integers).
503 .. TODO: Describe the FPIMM immediate operands.
505 .. _register-operands:
507 Register Operands
508 ^^^^^^^^^^^^^^^^^
510 The :ref:`register <registers>` primitive is used to represent the register
511 machine operands. The register operands can also have optional
512 :ref:`register flags <register-flags>`,
513 :ref:`a subregister index <subregister-indices>`,
514 and a reference to the tied register operand.
515 The full syntax of a register operand is shown below:
517 .. code-block:: text
519     [<flags>] <register> [ :<subregister-idx-name> ] [ (tied-def <tied-op>) ]
521 This example shows an instance of the X86 ``XOR32rr`` instruction that has
522 5 register operands with different register flags:
524 .. code-block:: text
526   dead $eax = XOR32rr undef $eax, undef $eax, implicit-def dead $eflags, implicit-def $al
528 .. _register-flags:
530 Register Flags
531 ~~~~~~~~~~~~~~
533 The table below shows all of the possible register flags along with the
534 corresponding internal ``llvm::RegState`` representation:
536 .. list-table::
537    :header-rows: 1
539    * - Flag
540      - Internal Value
542    * - ``implicit``
543      - ``RegState::Implicit``
545    * - ``implicit-def``
546      - ``RegState::ImplicitDefine``
548    * - ``def``
549      - ``RegState::Define``
551    * - ``dead``
552      - ``RegState::Dead``
554    * - ``killed``
555      - ``RegState::Kill``
557    * - ``undef``
558      - ``RegState::Undef``
560    * - ``internal``
561      - ``RegState::InternalRead``
563    * - ``early-clobber``
564      - ``RegState::EarlyClobber``
566    * - ``debug-use``
567      - ``RegState::Debug``
569    * - ``renamable``
570      - ``RegState::Renamable``
572 .. _subregister-indices:
574 Subregister Indices
575 ~~~~~~~~~~~~~~~~~~~
577 The register machine operands can reference a portion of a register by using
578 the subregister indices. The example below shows an instance of the ``COPY``
579 pseudo instruction that uses the X86 ``sub_8bit`` subregister index to copy 8
580 lower bits from the 32-bit virtual register 0 to the 8-bit virtual register 1:
582 .. code-block:: text
584     %1 = COPY %0:sub_8bit
586 The names of the subregister indices are target specific, and are typically
587 defined in the target's ``*RegisterInfo.td`` file.
589 Constant Pool Indices
590 ^^^^^^^^^^^^^^^^^^^^^
592 A constant pool index (CPI) operand is printed using its index in the
593 function's ``MachineConstantPool`` and an offset.
595 For example, a CPI with the index 1 and offset 8:
597 .. code-block:: text
599     %1:gr64 = MOV64ri %const.1 + 8
601 For a CPI with the index 0 and offset -12:
603 .. code-block:: text
605     %1:gr64 = MOV64ri %const.0 - 12
607 A constant pool entry is bound to a LLVM IR ``Constant`` or a target-specific
608 ``MachineConstantPoolValue``. When serializing all the function's constants the
609 following format is used:
611 .. code-block:: text
613     constants:
614       - id:               <index>
615         value:            <value>
616         alignment:        <alignment>
617         isTargetSpecific: <target-specific>
619 where:
620   - ``<index>`` is a 32-bit unsigned integer;
621   - ``<value>`` is a `LLVM IR Constant
622     <https://www.llvm.org/docs/LangRef.html#constants>`_;
623   - ``<alignment>`` is a 32-bit unsigned integer specified in bytes, and must be
624     power of two;
625   - ``<target-specific>`` is either true or false.
627 Example:
629 .. code-block:: text
631     constants:
632       - id:               0
633         value:            'double 3.250000e+00'
634         alignment:        8
635       - id:               1
636         value:            'g-(LPC0+8)'
637         alignment:        4
638         isTargetSpecific: true
640 Global Value Operands
641 ^^^^^^^^^^^^^^^^^^^^^
643 The global value machine operands reference the global values from the
644 :ref:`embedded LLVM IR module <embedded-module>`.
645 The example below shows an instance of the X86 ``MOV64rm`` instruction that has
646 a global value operand named ``G``:
648 .. code-block:: text
650     $rax = MOV64rm $rip, 1, _, @G, _
652 The named global values are represented using an identifier with the '@' prefix.
653 If the identifier doesn't match the regular expression
654 `[-a-zA-Z$._][-a-zA-Z$._0-9]*`, then this identifier must be quoted.
656 The unnamed global values are represented using an unsigned numeric value with
657 the '@' prefix, like in the following examples: ``@0``, ``@989``.
659 Target-dependent Index Operands
660 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
662 A target index operand is a target-specific index and an offset. The
663 target-specific index is printed using target-specific names and a positive or
664 negative offset.
666 For example, the ``amdgpu-constdata-start`` is associated with the index ``0``
667 in the AMDGPU backend. So if we have a target index operand with the index 0
668 and the offset 8:
670 .. code-block:: text
672     $sgpr2 = S_ADD_U32 _, target-index(amdgpu-constdata-start) + 8, implicit-def _, implicit-def _
674 Jump-table Index Operands
675 ^^^^^^^^^^^^^^^^^^^^^^^^^
677 A jump-table index operand with the index 0 is printed as following:
679 .. code-block:: text
681     tBR_JTr killed $r0, %jump-table.0
683 A machine jump-table entry contains a list of ``MachineBasicBlocks``. When serializing all the function's jump-table entries, the following format is used:
685 .. code-block:: text
687     jumpTable:
688       kind:             <kind>
689       entries:
690         - id:             <index>
691           blocks:         [ <bbreference>, <bbreference>, ... ]
693 where ``<kind>`` is describing how the jump table is represented and emitted (plain address, relocations, PIC, etc.), and each ``<index>`` is a 32-bit unsigned integer and ``blocks`` contains a list of :ref:`machine basic block references <block-references>`.
695 Example:
697 .. code-block:: text
699     jumpTable:
700       kind:             inline
701       entries:
702         - id:             0
703           blocks:         [ '%bb.3', '%bb.9', '%bb.4.d3' ]
704         - id:             1
705           blocks:         [ '%bb.7', '%bb.7', '%bb.4.d3', '%bb.5' ]
707 External Symbol Operands
708 ^^^^^^^^^^^^^^^^^^^^^^^^^
710 An external symbol operand is represented using an identifier with the ``&``
711 prefix. The identifier is surrounded with ""'s and escaped if it has any
712 special non-printable characters in it.
714 Example:
716 .. code-block:: text
718     CALL64pcrel32 &__stack_chk_fail, csr_64, implicit $rsp, implicit-def $rsp
720 MCSymbol Operands
721 ^^^^^^^^^^^^^^^^^
723 A MCSymbol operand is holding a pointer to a ``MCSymbol``. For the limitations
724 of this operand in MIR, see :ref:`limitations <limitations>`.
726 The syntax is:
728 .. code-block:: text
730     EH_LABEL <mcsymbol Ltmp1>
732 CFIIndex Operands
733 ^^^^^^^^^^^^^^^^^
735 A CFI Index operand is holding an index into a per-function side-table,
736 ``MachineFunction::getFrameInstructions()``, which references all the frame
737 instructions in a ``MachineFunction``. A ``CFI_INSTRUCTION`` may look like it
738 contains multiple operands, but the only operand it contains is the CFI Index.
739 The other operands are tracked by the ``MCCFIInstruction`` object.
741 The syntax is:
743 .. code-block:: text
745     CFI_INSTRUCTION offset $w30, -16
747 which may be emitted later in the MC layer as:
749 .. code-block:: text
751     .cfi_offset w30, -16
753 IntrinsicID Operands
754 ^^^^^^^^^^^^^^^^^^^^
756 An Intrinsic ID operand contains a generic intrinsic ID or a target-specific ID.
758 The syntax for the ``returnaddress`` intrinsic is:
760 .. code-block:: text
762    $x0 = COPY intrinsic(@llvm.returnaddress)
764 Predicate Operands
765 ^^^^^^^^^^^^^^^^^^
767 A Predicate operand contains an IR predicate from ``CmpInst::Predicate``, like
768 ``ICMP_EQ``, etc.
770 For an int eq predicate ``ICMP_EQ``, the syntax is:
772 .. code-block:: text
774    %2:gpr(s32) = G_ICMP intpred(eq), %0, %1
776 .. TODO: Describe the parsers default behaviour when optional YAML attributes
777    are missing.
778 .. TODO: Describe the syntax for virtual register YAML definitions.
779 .. TODO: Describe the machine function's YAML flag attributes.
780 .. TODO: Describe the syntax for the register mask machine operands.
781 .. TODO: Describe the frame information YAML mapping.
782 .. TODO: Describe the syntax of the stack object machine operands and their
783    YAML definitions.
784 .. TODO: Describe the syntax of the block address machine operands.
785 .. TODO: Describe the syntax of the metadata machine operands, and the
786    instructions debug location attribute.
787 .. TODO: Describe the syntax of the register live out machine operands.
788 .. TODO: Describe the syntax of the machine memory operands.