1 ===========================
2 QBE Intermediate Language
3 ===========================
10 1. <@ Basic Concepts >
19 * <@ Aggregate Types >
26 * <@ Arithmetic and Bits >
34 7. <@ Instructions Index >
39 The intermediate language (IL) is a higher-level language
40 than the machine's assembly language. It smoothes most
41 of the irregularities of the underlying hardware and
42 allows an infinite number of temporaries to be used.
43 This higher abstraction level allows frontend programmers
44 to focus on language design issues.
49 The intermediate language is provided to QBE as text.
50 Usually, one file is generated per each compilation unit from
51 the frontend input language. An IL file is a sequence of
52 <@ Definitions > for data, functions, and types. Once
53 processed by QBE, the resulting file can be assembled and
54 linked using a standard toolchain (e.g., GNU binutils).
56 Here is a complete "Hello World" IL file which defines a
57 function that prints to the screen. Since the string is
58 not a first class object (only the pointer is) it is
59 defined outside the function's body. Comments start with
60 a # character and finish with the end of the line.
62 # Define the string constant.
63 data $str = { b "hello world", b 0 }
67 # Call the puts function with $str as argument.
68 %r =w call $puts(l $str)
72 If you have read the LLVM language reference, you might
73 recognize the example above. In comparison, QBE makes a
74 much lighter use of types and the syntax is terser.
79 The language syntax is vaporously described in the sections
80 below using BNF syntax. The different BNF constructs used
83 * Keywords are enclosed between quotes;
84 * `... | ...` expresses disjunctions;
85 * `[ ... ]` marks some syntax as optional;
86 * `( ... ),` designates a comma-separated list of the
88 * `...*` and `...+` are used for arbitrary and
89 at-least-once repetition respectively.
94 The intermediate language makes heavy use of sigils, all
95 user-defined names are prefixed with a sigil. This is
96 to avoid keyword conflicts, and also to quickly spot the
97 scope and nature of identifiers.
99 * `:` is for user-defined <@ Aggregate Types>
100 * `$` is for globals (represented by a pointer)
101 * `%` is for function-scope temporaries
102 * `@` is for block labels
104 In this BNF syntax, we use `?IDENT` to designate an identifier
105 starting with the sigil `?`.
114 BASETY := 'w' | 'l' | 's' | 'd' # Base types
115 EXTTY := BASETY | 'b' | 'h' # Extended types
117 The IL makes minimal use of types. By design, the types
118 used are restricted to what is necessary for unambiguous
119 compilation to machine code and C interfacing. Unlike LLVM,
120 QBE is not using types as a means to safety; they are only
121 here for semantic purposes.
123 The four base types are `w` (word), `l` (long), `s` (single),
124 and `d` (double), they stand respectively for 32-bit and
125 64-bit integers, and 32-bit and 64-bit floating-point numbers.
126 There are no pointer types available; pointers are typed
127 by an integer type sufficiently wide to represent all memory
128 addresses (e.g., `l` on 64-bit architectures). Temporaries
129 in the IL can only have a basic type.
131 Extended types contain base types plus `b` (byte) and `h`
132 (half word), respectively for 8-bit and 16-bit integers.
133 They are used in <@ Aggregate Types> and <@ Data> definitions.
135 For C interfacing, the IL also provides user-defined aggregate
136 types. The syntax used to designate them is `:foo`. Details
137 about their definition are given in the <@ Aggregate Types >
143 The IL has a minimal subtyping feature, for integer types only.
144 Any value of type `l` can be used in a `w` context. In that
145 case, only the 32 least significant bits of the word value
148 Make note that it is the opposite of the usual subtyping on
149 integers (in C, we can safely use an `int` where a `long`
150 is expected). A long value cannot be used in word context.
151 The rationale is that a word can be signed or unsigned, so
152 extending it to a long could be done in two ways, either
153 by zero-extension, or by sign-extension.
160 ['-'] NUMBER # Decimal integer
161 | 's_' FP # Single-precision float
162 | 'd_' FP # Double-precision float
163 | $IDENT # Global symbol
165 Throughout the IL, constants are specified with a unified
166 syntax and semantics. Constants are immediates, meaning
167 that they can be used directly in instructions; there is
168 no need for a "load constant" instruction.
170 The representation of integers is two's complement.
171 Floating-point numbers are represented using the
172 single-precision and double-precision formats of the
175 Constants specify a sequence of bits and are untyped.
176 They are always parsed as 64-bit blobs. Depending on
177 the context surrounding a constant, only some of its
178 bits are used. For example, in the program below, the
179 two variables defined have the same value since the first
180 operand of the subtraction is a word (32-bit) context.
183 %y =w sub 4294967295, 0
185 Because specifying floating-point constants by their bits
186 makes the code less readable, syntactic sugar is provided
187 to express them. Standard scientific notation is prefixed
188 with `s_` and `d_` for single and double precision numbers
189 respectively. Once again, the following example defines twice
190 the same double-precision constant.
193 %y =d add d_0, -4616189618054758400
195 Global symbols can also be used directly as constants;
196 they will be resolved and turned into actual numeric
197 constants by the linker.
202 Definitions are the essential components of an IL file.
203 They can define three types of objects: aggregate types,
204 data, and functions. Aggregate types are never exported
205 and do not compile to any code. Data and function
206 definitions have file scope and are mutually recursive
207 (even across IL files). Their visibility can be controlled
208 using the `export` keyword.
216 'type' :IDENT '=' ['align' NUMBER]
221 'type' :IDENT '=' 'align' NUMBER '{' NUMBER '}'
223 SUBTY := EXTTY | :IDENT
225 Aggregate type definitions start with the `type` keyword.
226 They have file scope, but types must be defined before being
227 referenced. The inner structure of a type is expressed by a
228 comma-separated list of types enclosed in curly braces.
230 type :fourfloats = { s, s, d, d }
232 For ease of IL generation, a trailing comma is tolerated by
233 the parser. In case many items of the same type are
234 sequenced (like in a C array), the shorter array syntax
237 type :abyteandmanywords = { b, w 100 }
239 By default, the alignment of an aggregate type is the
240 maximum alignment of its members. The alignment can be
241 explicitly specified by the programmer.
243 type :cryptovector = align 16 { w 4 }
245 Opaque types are used when the inner structure of an
246 aggregate cannot be specified; the alignment for opaque
247 types is mandatory. They are defined simply by enclosing
248 their size between curly braces.
250 type :opaque = align 16 { 32 }
257 ['export'] 'data' $IDENT '=' ['align' NUMBER]
264 $IDENT ['+' NUMBER] # Symbol and offset
265 | '"' ... '"' # String
268 Data definitions express objects that will be emitted in the
269 compiled file. They can be local to the file or exported
270 with global visibility to the whole program.
272 They define a global identifier (starting with the sigil
273 `$`), that will contain a pointer to the object specified
276 Objects are described by a sequence of fields that start with
277 a type letter. This letter can either be an extended type,
278 or the `z` letter. If the letter used is an extended type,
279 the data item following specifies the bits to be stored in
280 the field. When several data items follow a letter, they
281 initialize multiple fields of the same size.
283 The members of a struct will be packed. This means that
284 padding has to be emitted by the frontend when necessary.
285 Alignment of the whole data objects can be manually specified,
286 and when no alignment is provided, the maximum alignment from
287 the platform is used.
289 When the `z` letter is used the number following indicates
290 the size of the field; the contents of the field are zero
291 initialized. It can be used to add padding between fields
292 or zero-initialize big arrays.
294 Here are various examples of data definitions.
296 # Three 32-bit values 1, 2, and 3
297 # followed by a 0 byte.
298 data $a = { w 1 2 3, b 0 }
300 # A thousand bytes 0 initialized.
303 # An object containing two 64-bit
304 # fields, one with all bits sets and the
305 # other containing a pointer to the
307 data $c = { l -1, l $c }
314 ['export'] 'function' [ABITY] $IDENT '(' (PARAM), ')'
320 ABITY %IDENT # Regular parameter
321 | 'env' %IDENT # Environment parameter (first)
322 | '...' # Variadic marker (last)
324 ABITY := BASETY | :IDENT
326 Function definitions contain the actual code to emit in
327 the compiled file. They define a global symbol that
328 contains a pointer to the function code. This pointer
329 can be used in `call` instructions or stored in memory.
331 The type given right before the function name is the
332 return type of the function. All return values of this
333 function must have this return type. If the return
334 type is missing, the function cannot return any value.
336 The parameter list is a comma separated list of
337 temporary names prefixed by types. The types are used
338 to correctly implement C compatibility. When an argument
339 has an aggregate type, a pointer to the aggregate is passed
340 by the caller. In the example below, we have to use a load
341 instruction to get the value of the first (and only)
342 member of the struct.
346 function w $getone(:one %p) {
352 If the parameter list ends with `...`, the function is
353 a variadic function: it can accept a variable number of
354 arguments. To access the extra arguments provided by
355 the caller, use the `vastart` and `vaarg` instructions
356 described in the <@ Variadic > section.
358 Optionally, the parameter list can start with an
359 environment parameter `env %e`. This special parameter is
360 a 64-bit integer temporary (i.e., of type `l`). If the
361 function does not use its environment parameter, callers
362 can safely omit it. This parameter is invisible to a C
363 caller: for example, the function
365 export function w $add(env %e, w %a, w %b) {
371 must be given the C prototype `int add(int, int)`.
372 The intended use of this feature is to pass the
373 environment pointer of closures while retaining a
374 very good compatibility with C. The <@ Call > section
375 explains how to pass an environment parameter.
377 Since global symbols are defined mutually recursive,
378 there is no need for function declarations: a function
379 can be referenced before its definition.
380 Similarly, functions from other modules can be used
381 without previous declaration. All the type information
382 is provided in the call instructions.
384 The syntax and semantics for the body of functions
385 are described in the <@ Control > section.
390 The IL represents programs as textual transcriptions of
391 control flow graphs. The control flow is serialized as
392 a sequence of blocks of straight-line code which are
393 connected using jump instructions.
401 PHI* # Phi instructions
402 INST* # Regular instructions
403 JUMP # Jump or return
405 All blocks have a name that is specified by a label at
406 their beginning. Then follows a sequence of instructions
407 that have "fall-through" flow. Finally one jump terminates
408 the block. The jump can either transfer control to another
409 block of the same function or return; they are described
412 The first block in a function must not be the target of
413 any jump in the program. If this is really needed,
414 the frontend could insert an empty prelude block
415 at the beginning of the function.
417 When one block jumps to the next block in the IL file,
418 it is not necessary to give the jump instruction, it
419 will be automatically added by the parser. For example
420 the start block in the example below jumps directly
426 %x =w phi @start 100, @loop %x1
438 'jmp' @IDENT # Unconditional
439 | 'jnz' VAL, @IDENT, @IDENT # Conditional
440 | 'ret' [VAL] # Return
442 A jump instruction ends every block and transfers the
443 control to another program location. The target of
444 a jump must never be the first block in a function.
445 The three kinds of jumps available are described in
448 1. Unconditional jump.
450 Simply jumps to another block of the same function.
454 When its word argument is non-zero, it jumps to its
455 first label argument; otherwise it jumps to the other
456 label. The argument must be of word type; because of
457 subtyping a long argument can be passed, but only its
458 least significant 32 bits will be compared to 0.
462 Terminates the execution of the current function,
463 optionally returning a value to the caller. The value
464 returned must be of the type given in the function
465 prototype. If the function prototype does not specify
466 a return type, no return value can be used.
471 Instructions are the smallest piece of code in the IL, they
472 form the body of <@ Blocks >. The IL uses a three-address
473 code, which means that one instruction computes an operation
474 between two operands and assigns the result to a third one.
476 An instruction has both a name and a return type, this
477 return type is a base type that defines the size of the
478 instruction's result. The type of the arguments can be
479 unambiguously inferred using the instruction name and the
480 return type. For example, for all arithmetic instructions,
481 the type of the arguments is the same as the return type.
482 The two additions below are valid if `%y` is a word or a long
483 (because of <@ Subtyping >).
488 Some instructions, like comparisons and memory loads
489 have operand types that differ from their return types.
490 For instance, two floating points can be compared to give a
491 word result (0 if the comparison succeeds, 1 if it fails).
495 In the example above, both operands have to have single type.
496 This is made explicit by the instruction suffix.
498 The types of instructions are described below using a short
499 type string. A type string specifies all the valid return
500 types an instruction can have, its arity, and the type of
501 its arguments depending on its return type.
503 Type strings begin with acceptable return types, then
504 follows, in parentheses, the possible types for the arguments.
505 If the N-th return type of the type string is used for an
506 instruction, the arguments must use the N-th type listed for
507 them in the type string. When an instruction does not have a
508 return type, the type string only contains the types of the
511 The following abbreviations are used.
513 * `T` stands for `wlsd`
514 * `I` stands for `wl`
515 * `F` stands for `sd`
516 * `m` stands for the type of pointers on the target; on
517 64-bit architectures it is the same as `l`
519 For example, consider the type string `wl(F)`, it mentions
520 that the instruction has only one argument and that if the
521 return type used is long, the argument must be of type double.
523 ~ Arithmetic and Bits
524 ~~~~~~~~~~~~~~~~~~~~~
526 * `add`, `sub`, `div`, `mul` -- `T(T,T)`
527 * `udiv`, `rem`, `urem` -- `I(I,I)`
528 * `or`, `xor`, `and` -- `I(I,I)`
529 * `sar`, `shr`, `shl` -- `I(I,ww)`
531 The base arithmetic instructions in the first bullet are
532 available for all types, integers and floating points.
534 When `div` is used with word or long return type, the
535 arguments are treated as signed. The unsigned integral
536 division is available as `udiv` instruction. When the
537 result of a division is not an integer, it is truncated
540 The signed and unsigned remainder operations are available
541 as `rem` and `urem`. The sign of the remainder is the same
542 as the one of the dividend. Its magnitude is smaller than
543 the divisor one. These two instructions and `udiv` are only
544 available with integer arguments and result.
546 Bitwise OR, AND, and XOR operations are available for both
547 integer types. Logical operations of typical programming
548 languages can be implemented using <@ Comparisons > and
551 Shift instructions `sar`, `shr`, and `shl`, shift right or
552 left their first operand by the amount from the second
553 operand. The shifting amount is taken modulo the size of
554 the result type. Shifting right can either preserve the
555 sign of the value (using `sar`), or fill the newly freed
556 bits with zeroes (using `shr`). Shifting left always
557 fills the freed bits with zeroes.
559 Remark that an arithmetic shift right (`sar`) is only
560 equivalent to a division by a power of two for non-negative
561 numbers. This is because the shift right "truncates"
562 towards minus infinity, while the division truncates
568 * Store instructions.
570 * `stored` -- `(d,m)`
571 * `stores` -- `(s,m)`
572 * `storel` -- `(l,m)`
573 * `storew` -- `(w,m)`
574 * `storeh` -- `(w,m)`
575 * `storeb` -- `(w,m)`
577 Store instructions exist to store a value of any base type
578 and any extended type. Since halfwords and bytes are not
579 first class in the IL, `storeh` and `storeb` take a word
580 as argument. Only the first 16 or 8 bits of this word will
581 be stored in memory at the address specified in the second
589 * `loadsw`, `loaduw` -- `I(mm)`
590 * `loadsh`, `loaduh` -- `I(mm)`
591 * `loadsb`, `loadub` -- `I(mm)`
593 For types smaller than long, two variants of the load
594 instruction are available: one will sign extend the loaded
595 value, while the other will zero extend it. Note that
596 all loads smaller than long can load to either a long or
599 The two instructions `loadsw` and `loaduw` have the same
600 effect when they are used to define a word temporary.
601 A `loadw` instruction is provided as syntactic sugar for
602 `loadsw` to make explicit that the extension mechanism
609 * `alloc16` -- `m(l)`
611 These instructions allocate a chunk of memory on the
612 stack. The number ending the instruction name is the
613 alignment required for the allocated slot. QBE will
614 make sure that the returned address is a multiple of
615 that alignment value.
617 Stack allocation instructions are used, for example,
618 when compiling the C local variables, because their
619 address can be taken. When compiling Fortran,
620 temporaries can be used directly instead, because
621 it is illegal to take the address of a variable.
623 The following example makes use some of the memory
624 instructions. Pointers are stored in long temporaries.
626 %A0 =l alloc4 8 # stack allocate an array A of 2 words
628 storew 43, %A0 # A[0] <- 43
629 storew 255, %A1 # A[1] <- 255
630 %v1 =w loadw %A0 # %v1 <- A[0] as word
631 %v2 =w loadsb %A1 # %v2 <- A[1] as signed byte
632 %v3 =w add %v1, %v2 # %v3 is 42 here
637 Comparison instructions return an integer value (either a word
638 or a long), and compare values of arbitrary types. The returned
639 value is 1 if the two operands satisfy the comparison
640 relation, or 0 otherwise. The names of comparisons respect
641 a standard naming scheme in three parts.
643 1. All comparisons start with the letter `c`.
645 2. Then comes a comparison type. The following
646 types are available for integer comparisons:
649 * `ne` for inequality
650 * `sle` for signed lower or equal
651 * `slt` for signed lower
652 * `sge` for signed greater or equal
653 * `sgt` for signed greater
654 * `ule` for unsigned lower or equal
655 * `ult` for unsigned lower
656 * `uge` for unsigned greater or equal
657 * `ugt` for unsigned greater
659 Floating point comparisons use one of these types:
662 * `ne` for inequality
663 * `le` for lower or equal
665 * `ge` for greater or equal
667 * `o` for ordered (no operand is a NaN)
668 * `uo` for unordered (at least one operand is a NaN)
670 Because floating point types always have a sign bit,
671 all the comparisons available are signed.
673 3. Finally, the instruction name is terminated with a
674 basic type suffix precising the type of the operands
677 For example, `cod` (`I(dd,dd)`) compares two double-precision
678 floating point numbers and returns 1 if the two floating points
679 are not NaNs, or 0 otherwise. The `csltw` (`I(ww,ww)`)
680 instruction compares two words representing signed numbers and
681 returns 1 when the first argument is smaller than the second one.
686 Conversion operations allow to change the representation of
687 a value, possibly modifying it if the target type cannot hold
688 the value of the source type. Conversions can extend the
689 precision of a temporary (e.g., from signed 8-bit to 32-bit),
690 or convert a floating point into an integer and vice versa.
692 * `extsw`, `extuw` -- `l(w)`
693 * `extsh`, `extuh` -- `I(ww)`
694 * `extsb`, `extub` -- `I(ww)`
702 Extending the precision of a temporary is done using the
703 `ext` family of instructions. Because QBE types do not
704 precise the signedness (like in LLVM), extension instructions
705 exist to sign-extend and zero-extend a value. For example,
706 `extsb` takes a word argument and sign-extend the 8
707 least-significant bits to a full word or long, depending on
710 The instructions `exts` and `truncd` are provided to change
711 the precision of a floating point value. When the double
712 argument of `truncd` cannot be represented as a
713 single-precision floating point, it is truncated towards
716 Converting between signed integers and floating points is
717 done using `stosi` (single to signed integer), `dtosi`
718 (double to signed integer), `swtof` (signed word to float),
719 and `sltof` (signed long to float). These instructions
720 only handle signed integers, conversion to and from
721 unsigned types are not yet supported.
723 Because of <@ Subtyping >, there is no need to have an
724 instruction to lower the precision of an integer temporary.
729 The `cast` and `copy` instructions return the bits of their
730 argument verbatim. However a `cast` will change an integer
731 into a floating point of the same width and vice versa.
733 * `cast` -- `wlsd(sdwl)`
736 Casts can be used to make bitwise operations on the
737 representation of floating point numbers. For example
738 the following program will compute the opposite of the
739 single-precision floating point number `%f` into `%rs`.
742 %b1 =w xor 2147483648, %b0 # flip the msb
749 CALL := [%IDENT '=' ABITY] 'call' VAL '(' (ARG), ')'
752 ABITY VAL # Regular argument
753 | 'env' VAL # Environment argument (first)
754 | '...' # Variadic marker (last)
756 ABITY := BASETY | :IDENT
758 The call instruction is special in several ways. It is not
759 a three-address instruction and requires the type of all
760 its arguments to be given. Also, the return type can be
761 either a base type or an aggregate type. These specifics
762 are required to compile calls with C compatibility (i.e.,
765 When an aggregate type is used as argument type or return
766 type, the value respectively passed or returned needs to be
767 a pointer to a memory location holding the value. This is
768 because aggregate types are not first-class citizens of
771 Unless the called function does not return a value, a
772 return temporary must be specified, even if it is never
775 An environment parameter can be passed as first argument
776 using the `env` keyword. The passed value must be a 64-bit
777 integer. If the called function does not expect an environment
778 parameter, it will be safely discarded. See the <@ Functions >
779 section for more information about environment parameters.
781 When the called function is variadic, the last argument
787 The `vastart` and `vaarg` instructions provide a portable
788 way to access the extra parameters of a variadic function.
791 * `vaarg` -- `T(mmmm)`
793 The `vastart` instruction initializes a *variable argument
794 list* used to access the extra parameters of the enclosing
795 variadic function. It is safe to call it multiple times.
797 The `vaarg` instruction fetches the next argument from
798 a variable argument list. It is currently limited to
799 fetching arguments that have a base type. This instruction
800 is essentially effectful: calling it twice in a row will
801 return two consecutive arguments from the argument list.
803 Both instructions take a pointer to a variable argument
804 list as sole argument. The size and alignment of variable
805 argument lists depend on the target used. However, it
806 is possible to conservatively use the maximum size and
807 alignment required by all the targets.
809 type :valist = align 8 { 24 } # For amd64_sysv
810 type :valist = align 8 { 32 } # For arm64
812 The following example defines a variadic function adding
813 its first three arguments.
815 function s $add3(s %a, ...) {
819 %r =s call $vadd(s %a, l %ap)
823 function s $vadd(s %a, l %ap) {
836 PHI := %IDENT '=' BASETY 'phi' ( @IDENT VAL ),
838 First and foremost, phi instructions are NOT necessary when
839 writing a frontend to QBE. One solution to avoid having to
840 deal with SSA form is to use stack allocated variables for
841 all source program variables and perform assignments and
842 lookups using <@ Memory > operations. This is what LLVM
845 Another solution is to simply emit code that is not in SSA
846 form! Contrary to LLVM, QBE is able to fixup programs not
847 in SSA form without requiring the boilerplate of loading
848 and storing in memory. For example, the following program
849 will be correctly compiled by QBE.
861 Now, if you want to know what phi instructions are and how
862 to use them in QBE, you can read the following.
864 Phi instructions are specific to SSA form. In SSA form
865 values can only be assigned once, without phi instructions,
866 this requirement is too strong to represent many programs.
867 For example consider the following C program.
878 The variable `y` is assigned twice, the solution to
879 translate it in SSA form is to insert a phi instruction.
888 %y =w phi @ift 1, @iff 2
891 Phi instructions return one of their arguments depending
892 on where the control came from. In the example, `%y` is
893 set to 1 if the `@ift` branch is taken, or it is set to
896 An important remark about phi instructions is that QBE
897 assumes that if a variable is defined by a phi it respects
898 all the SSA invariants. So it is critical to not use phi
899 instructions unless you know exactly what you are doing.
901 - 7. Instructions Index
902 -----------------------
904 * <@ Arithmetic and Bits >:
996 * <@ Cast and Copy > :