Debian Codegraph @

gcc/ada/doc/gnat_ugn/inline_assembler.rst

raw
1 .. role:: switch(samp)
2
3 .. _Inline_Assembler:
4
5 ****************
6 Inline Assembler
7 ****************
8
9 .. index:: Inline Assembler
10
11 If you need to write low-level software that interacts directly
12 with the hardware, Ada provides two ways for you to incorporate assembly
13 language code into your program. First, you can import and invoke
14 external routines written in assembly language, an Ada feature fully
15 supported by GNAT. However, for small sections of code, it may be simpler
16 or more efficient to include assembly language statements directly
17 in your Ada source program, using the facilities of the implementation-defined
18 package ``System.Machine_Code``, which incorporates the gcc
19 Inline Assembler. The Inline Assembler approach offers a number of advantages,
20 including the following:
21
22 * No need to use non-Ada tools
23 * Consistent interface over different targets
24 * Automatic usage of the proper calling conventions
25 * Access to Ada constants and variables
26 * Definition of intrinsic routines
27 * Possibility of inlining a subprogram consisting of assembler code
28 * Code optimizer can take Inline Assembler code into account
29
30 This appendix presents a series of examples to show you how to use
31 the Inline Assembler. Although it focuses on the Intel x86,
32 the general approach applies also to other processors.
33 It is assumed you are familiar with both Ada
34 and assembly language programming.
35
36 .. _Basic_Assembler_Syntax:
37
38 Basic Assembler Syntax
39 ======================
40
41 The assembler used by GNAT and gcc is based not on the Intel assembly
42 language, but rather on a language that descends from the AT&T Unix
43 assembler ``as`` (and which is often referred to as 'AT&T syntax').
44 The following table summarizes the main features of ``as`` syntax
45 and points out the differences from the Intel conventions.
46 See the gcc ``as`` and ``gas`` (an ``as`` macro
47 pre-processor) documentation for further information.
48
49
50 | *Register names*
51 | gcc / ``as``: Prefix with '%'; for example ``%eax``
52 | Intel: No extra punctuation; for example ``eax``
53
54
55 | *Immediate operand*
56 | gcc / ``as``: Prefix with '$'; for example ``$4``
57 | Intel: No extra punctuation; for example ``4``
58
59
60 | *Address*
61 | gcc / ``as``: Prefix with '$'; for example ``$loc``
62 | Intel: No extra punctuation; for example ``loc``
63
64
65 | *Memory contents*
66 | gcc / ``as``: No extra punctuation; for example ``loc``
67 | Intel: Square brackets; for example ``[loc]``
68
69
70 | *Register contents*
71 | gcc / ``as``: Parentheses; for example ``(%eax)``
72 | Intel: Square brackets; for example ``[eax]``
73
74
75 | *Hexadecimal numbers*
76 | gcc / ``as``: Leading '0x' (C language syntax); for example ``0xA0``
77 | Intel: Trailing 'h'; for example ``A0h``
78
79
80 | *Operand size*
81 | gcc / ``as``: Explicit in op code; for example ``movw`` to move a 16-bit word
82 | Intel: Implicit, deduced by assembler; for example ``mov``
83
84
85 | *Instruction repetition*
86 | gcc / ``as``: Split into two lines; for example
87 | ``rep``
88 | ``stosl``
89 | Intel: Keep on one line; for example ``rep stosl``
90
91
92 | *Order of operands*
93 | gcc / ``as``: Source first; for example ``movw $4, %eax``
94 | Intel: Destination first; for example ``mov eax, 4``
95
96
97 .. _A_Simple_Example_of_Inline_Assembler:
98
99 A Simple Example of Inline Assembler
100 ====================================
101
102 The following example generate a single assembly language statement,
103 ``nop``, which does nothing. Despite its lack of run-time effect,
104 the example is useful in illustrating the basics of
105 the Inline Assembler facility.
106
107 .. code-block:: ada
108
109 with System.Machine_Code; use System.Machine_Code;
110 procedure Nothing is
111 begin
112 Asm ("nop");
113 end Nothing;
114
115 ``Asm`` is a procedure declared in package ``System.Machine_Code``;
116 here it takes one parameter, a *template string* that must be a static
117 expression that produces the generated instruction.
118 ``Asm`` may be regarded as a compile-time procedure that parses
119 the template string and any additional parameters (none, in this case)
120 and generates one or more assembly language instructions.
121
122 The examples in this chapter will illustrate several of the forms
123 for invoking ``Asm``; a complete specification of the syntax
124 is found in the ``Machine_Code_Insertions`` section of the
125 :title:`GNAT Reference Manual`.
126
127 Under the standard GNAT conventions, you should put the ``Nothing`` procedure
128 in a file named :file:`nothing.adb`.
129 You can build the executable in the usual way:
130
131 ::
132
133 $ gnatmake nothing
134
135 However, the interesting aspect of this example is not its run-time behavior
136 but rather the generated assembly code.
137 To see this output, invoke the compiler as follows:
138
139 ::
140
141 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
142
143 where the options are:
144
145 * :switch:`-c`
146 compile only (no bind or link)
147
148 * :switch:`-S`
149 generate assembler listing
150
151 * :switch:`-fomit-frame-pointer`
152 do not set up separate stack frames
153
154 * :switch:`-gnatp`
155 do not add runtime checks
156
157 This gives a human-readable assembler version of the code. The resulting
158 file has the same name as the Ada source file but with a ``.s``
159 extension. In our example, the file :file:`nothing.s` has the following
160 contents:
161
162 ::
163
164 .file "nothing.adb"
165 gcc2_compiled.:
166 ___gnu_compiled_ada:
167 .text
168 .align 4
169 .globl __ada_nothing
170 __ada_nothing:
171 #APP
172 nop
173 #NO_APP
174 jmp L1
175 .align 2,0x90
176 L1:
177 ret
178
179 The assembly code you included is clearly indicated by
180 the compiler, between the ``#APP`` and ``#NO_APP``
181 delimiters. The character before the 'APP' and 'NOAPP'
182 can differ on different targets. For example, GNU/Linux uses '#APP' while
183 on NT you will see '/APP'.
184
185 If you make a mistake in your assembler code (such as using the
186 wrong size modifier or using a wrong operand for the instruction) GNAT
187 will report this error in a temporary file, which is deleted when
188 the compilation is finished. Generating an assembler file will help
189 in such cases, since you can assemble this file separately using the
190 ``as`` assembler that comes with gcc.
191
192 Assembling the file using the command
193
194 ::
195
196 $ as nothing.s
197
198 will give you error messages whose lines correspond to the assembler
199 input file, so you can easily find and correct any mistakes you made.
200 If there are no errors, ``as`` generates an object file called
201 :file:`nothing.out`.
202
203
204 .. _Output_Variables_in_Inline_Assembler:
205
206 Output Variables in Inline Assembler
207 ====================================
208
209 The examples in this section, showing how to access the processor flags,
210 illustrate how to specify the destination operands for assembly language
211 statements.
212
213
214 .. code-block:: ada
215
216 with Interfaces; use Interfaces;
217 with Ada.Text_IO; use Ada.Text_IO;
218 with System.Machine_Code; use System.Machine_Code;
219 procedure Get_Flags is
220 Flags : Unsigned_32;
221 use ASCII;
222 begin
223 Asm ("pushfl" & LF & HT & -- push flags on stack
224 "popl %%eax" & LF & HT & -- load eax with flags
225 "movl %%eax, %0", -- store flags in variable
226 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
227 Put_Line ("Flags register:" & Flags'Img);
228 end Get_Flags;
229
230 We have separated multiple assembler statements in the Asm template
231 string with linefeed (ASCII.LF) and horizontal tab (ASCII.HT)
232 characters in order to have a nicely aligned assembly listing. The
233 resulting section of the assembly output file is:
234
235 ::
236
237 #APP
238 pushfl
239 popl %eax
240 movl %eax, -40(%ebp)
241 #NO_APP
242
243 It would have been legal to write the Asm invocation as:
244
245 .. code-block:: ada
246
247 Asm ("pushfl popl %%eax movl %%eax, %0")
248
249 but in the generated assembler file, this would come out as:
250
251 ::
252
253 #APP
254 pushfl popl %eax movl %eax, -40(%ebp)
255 #NO_APP
256
257 which is not so convenient for the human reader.
258
259 We use Ada comments
260 at the end of each line to explain what the assembler instructions
261 actually do. This is a useful convention.
262
263 When writing Inline Assembler instructions, you need to precede each register
264 and variable name with a percent sign. Since the assembler already requires
265 a percent sign at the beginning of a register name, you need two consecutive
266 percent signs for such names in the Asm template string, thus ``%%eax``.
267 In the generated assembly code, one of the percent signs will be stripped off.
268
269 Names such as ``%0``, ``%1``, ``%2``, etc., denote input or output
270 variables: operands you later define using ``Input`` or ``Output``
271 parameters to ``Asm``.
272 An output variable is shown in
273 the third section of the Asm template string:
274
275 ::
276
277 movl %%eax, %0
278
279 The intent of this section is to store the contents of the ``eax``
280 register in a variable that can be accessed in Ada. Simply writing
281 ``movl %%eax, Flags`` would not necessarily work, since the compiler
282 might optimize by using a register to hold ``Flags``, and the expansion of
283 the ``movl`` instruction would not be aware of this optimization. The
284 solution is not to store the result directly but rather to advise the
285 compiler to choose the correct operand form; that is the purpose of
286 the ``%0`` output variable.
287
288 Information about the output variable is supplied in the ``Outputs``
289 parameter to ``Asm``:
290
291 .. code-block:: ada
292
293 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
294
295 The output is defined by the ``Asm_Output`` attribute of the target type;
296 the general format is:
297
298 .. code-block:: ada
299
300 Type'Asm_Output (constraint_string, variable_name)
301
302 The constraint string directs the compiler how
303 to store/access the associated variable. In the example:
304
305 .. code-block:: ada
306
307 Unsigned_32'Asm_Output ("=m", Flags);
308
309 the ``"m"`` (memory) constraint tells the compiler that the variable
310 ``Flags`` should be stored in a memory variable, thus preventing
311 the optimizer from keeping it in a register. In contrast,
312
313 .. code-block:: ada
314
315 Unsigned_32'Asm_Output ("=r", Flags);
316
317 uses the ``"r"`` (register) constraint, telling the compiler to
318 store the variable in a register.
319
320 If you precede the constraint with the equal character ('='), it tells
321 the compiler that the variable will have data stored into it.
322
323 In the ``Get_Flags`` example, we used the ``"g"`` (global) constraint,
324 allowing the optimizer to choose whatever operand it deems best.
325
326 There are a fairly large number of constraints, but the ones that are
327 most useful for the Intel x86 processor are the following:
328
329 ====== ==========================================
330 *=* output constraint
331 *g* global (i.e., can be stored anywhere)
332 *m* in memory
333 *I* a constant
334 *a* use eax
335 *b* use ebx
336 *c* use ecx
337 *d* use edx
338 *S* use esi
339 *D* use edi
340 *r* use one of eax, ebx, ecx or edx
341 *q* use one of eax, ebx, ecx, edx, esi or edi
342 ====== ==========================================
343
344 The full set of constraints is described in the ``gcc`` and ``as``
345 documentation; note that you can combine certain constraints
346 into one constraint string.
347
348 You specify the association of an output variable with an assembler operand
349 through the :samp:`%{n}` notation, where *n* is a non-negative
350 integer. Thus in
351
352 .. code-block:: ada
353
354 Asm ("pushfl" & LF & HT & -- push flags on stack
355 "popl %%eax" & LF & HT & -- load eax with flags
356 "movl %%eax, %0", -- store flags in variable
357 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
358
359
360 ``%0`` is replaced in the expanded code by the appropriate operand,
361 whatever the compiler chose for the ``Flags`` variable.
362
363 In general, you may have any number of output variables:
364
365 * Count the operands starting at 0; thus ``%0``, ``%1``, etc.
366
367 * Specify the ``Outputs`` parameter as a parenthesized comma-separated list
368 of ``Asm_Output`` attributes
369
370 For example:
371
372 .. code-block:: ada
373
374 Asm ("movl %%eax, %0" & LF & HT &
375 "movl %%ebx, %1" & LF & HT &
376 "movl %%ecx, %2",
377 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
378 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
379 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
380
381 where ``Var_A``, ``Var_B``, and ``Var_C`` are variables
382 in the Ada program.
383
384 As a variation on the ``Get_Flags`` example, we can use the constraint
385 string to direct the compiler to store the ``eax`` register into the ``Flags``
386 variable, instead of including the store instruction explicitly in the
387 ``Asm`` template string:
388
389 .. code-block:: ada
390
391 with Interfaces; use Interfaces;
392 with Ada.Text_IO; use Ada.Text_IO;
393 with System.Machine_Code; use System.Machine_Code;
394 procedure Get_Flags_2 is
395 Flags : Unsigned_32;
396 use ASCII;
397 begin
398 Asm ("pushfl" & LF & HT & -- push flags on stack
399 "popl %%eax", -- save flags in eax
400 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
401 Put_Line ("Flags register:" & Flags'Img);
402 end Get_Flags_2;
403
404 The ``"a"`` constraint tells the compiler that the ``Flags``
405 variable will come from the ``eax`` register. Here is the resulting code:
406
407 ::
408
409 #APP
410 pushfl
411 popl %eax
412 #NO_APP
413 movl %eax,-40(%ebp)
414
415 The compiler generated the store of eax into Flags after
416 expanding the assembler code.
417
418 In fact, there was no need to pop the flags into the ``eax`` register;
419 more simply, we could just pop the flags directly into the program variable:
420
421 .. code-block:: ada
422
423 with Interfaces; use Interfaces;
424 with Ada.Text_IO; use Ada.Text_IO;
425 with System.Machine_Code; use System.Machine_Code;
426 procedure Get_Flags_3 is
427 Flags : Unsigned_32;
428 use ASCII;
429 begin
430 Asm ("pushfl" & LF & HT & -- push flags on stack
431 "pop %0", -- save flags in Flags
432 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
433 Put_Line ("Flags register:" & Flags'Img);
434 end Get_Flags_3;
435
436
437 .. _Input_Variables_in_Inline_Assembler:
438
439 Input Variables in Inline Assembler
440 ===================================
441
442 The example in this section illustrates how to specify the source operands
443 for assembly language statements.
444 The procedure simply increments its input value by 1:
445
446 .. code-block:: ada
447
448 with Interfaces; use Interfaces;
449 with Ada.Text_IO; use Ada.Text_IO;
450 with System.Machine_Code; use System.Machine_Code;
451 procedure Increment is
452
453 function Incr (Value : Unsigned_32) return Unsigned_32 is
454 Result : Unsigned_32;
455 begin
456 Asm ("incl %0",
457 Outputs => Unsigned_32'Asm_Output ("=a", Result),
458 Inputs => Unsigned_32'Asm_Input ("a", Value));
459 return Result;
460 end Incr;
461
462 Value : Unsigned_32;
463
464 begin
465 Value := 5;
466 Put_Line ("Value before is" & Value'Img);
467 Value := Incr (Value);
468 Put_Line ("Value after is" & Value'Img);
469 end Increment;
470
471 The ``Outputs`` parameter to ``Asm`` specifies
472 that the result is in the ``eax`` register and that it is to be stored
473 in the ``Result`` variable.
474
475 The ``Inputs`` parameter looks much like the ``Outputs`` parameter,
476 but with an ``Asm_Input`` attribute.
477 The ``"="`` constraint, indicating an output value, is not present.
478
479 You can have multiple input variables in the same way you can have more
480 than one output variable.
481
482 The parameter count (%0, %1) etc, still starts at the first output statement,
483 and continues with the input statements.
484
485 Just as the ``Outputs`` parameter causes the register to be stored into the
486 target variable after execution of the assembler statements, the
487 ``Inputs`` parameter causes its variable to be loaded into the register
488 before execution of the assembler statements.
489
490 Thus the effect of the ``Asm`` invocation is:
491
492 * load the 32-bit value of ``Value`` into ``eax``
493 * execute the ``incl %eax`` instruction
494 * store the contents of eax into the ``Result`` variable
495
496 The resulting assembler file (with :switch:`-O2` optimization) contains:
497
498 ::
499
500 _increment__incr.1:
501 subl $4,%esp
502 movl 8(%esp),%eax
503 #APP
504 incl %eax
505 #NO_APP
506 movl %eax,%edx
507 movl %ecx,(%esp)
508 addl $4,%esp
509 ret
510
511
512 .. _Inlining_Inline_Assembler_Code:
513
514 Inlining Inline Assembler Code
515 ==============================
516
517 For a short subprogram such as the ``Incr`` function in the previous
518 section, the overhead of the call and return (creating / deleting the stack
519 frame) can be significant, compared to the amount of code in the subprogram
520 body. A solution is to apply Ada's ``Inline`` pragma to the subprogram,
521 which directs the compiler to expand invocations of the subprogram at the
522 point(s) of call, instead of setting up a stack frame for out-of-line calls.
523 Here's the resulting program:
524
525 .. code-block:: ada
526
527 with Interfaces; use Interfaces;
528 with Ada.Text_IO; use Ada.Text_IO;
529 with System.Machine_Code; use System.Machine_Code;
530 procedure Increment_2 is
531
532 function Incr (Value : Unsigned_32) return Unsigned_32 is
533 Result : Unsigned_32;
534 begin
535 Asm ("incl %0",
536 Outputs => Unsigned_32'Asm_Output ("=a", Result),
537 Inputs => Unsigned_32'Asm_Input ("a", Value));
538 return Result;
539 end Incr;
540 pragma Inline (Increment);
541
542 Value : Unsigned_32;
543
544 begin
545 Value := 5;
546 Put_Line ("Value before is" & Value'Img);
547 Value := Increment (Value);
548 Put_Line ("Value after is" & Value'Img);
549 end Increment_2;
550
551 Compile the program with both optimization (:switch:`-O2`) and inlining
552 (:switch:`-gnatn`) enabled.
553
554 The ``Incr`` function is still compiled as usual, but at the
555 point in ``Increment`` where our function used to be called:
556
557
558 ::
559
560 pushl %edi
561 call _increment__incr.1
562
563 the code for the function body directly appears:
564
565
566 ::
567
568 movl %esi,%eax
569 #APP
570 incl %eax
571 #NO_APP
572 movl %eax,%edx
573
574 thus saving the overhead of stack frame setup and an out-of-line call.
575
576
577 .. _Other_Asm_Functionality:
578
579 Other ``Asm`` Functionality
580 ===========================
581
582 This section describes two important parameters to the ``Asm``
583 procedure: ``Clobber``, which identifies register usage;
584 and ``Volatile``, which inhibits unwanted optimizations.
585
586 .. _The_Clobber_Parameter:
587
588 The ``Clobber`` Parameter
589 -------------------------
590
591 One of the dangers of intermixing assembly language and a compiled language
592 such as Ada is that the compiler needs to be aware of which registers are
593 being used by the assembly code. In some cases, such as the earlier examples,
594 the constraint string is sufficient to indicate register usage (e.g.,
595 ``"a"`` for
596 the ``eax`` register). But, more generally, the compiler needs an explicit
597 identification of the registers that are used by the Inline Assembly
598 statements.
599
600 Using a register that the compiler doesn't know about
601 could be a side effect of an instruction (like ``mull``, which
602 stores its result into both ``eax`` and ``edx``).
603 It can also arise from explicit register usage within your
604 assembly code; for example:
605
606 .. code-block:: ada
607
608 Asm ("movl %0, %%ebx" & LF & HT &
609 "movl %%ebx, %1",
610 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
611 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
612
613 where the compiler (since it does not analyze the ``Asm`` template string)
614 does not know you are using the ``ebx`` register.
615
616 In such cases you need to supply the ``Clobber`` parameter to ``Asm``,
617 to identify the registers used by your assembly code:
618
619
620 .. code-block:: ada
621
622 Asm ("movl %0, %%ebx" & LF & HT &
623 "movl %%ebx, %1",
624 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
625 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
626 Clobber => "ebx");
627
628 The Clobber parameter is a static string expression specifying the
629 register(s) you are using. Note that register names are *not*
630 prefixed by a percent sign. Also, if more than one register is used,
631 you separate their names by commas; e.g., ``"eax, ebx"``
632
633 The ``Clobber`` parameter has several additional uses:
634
635 * Use 'register' name ``cc`` to indicate that flags might have changed
636 * Use 'register' name ``memory`` if you changed a memory location
637
638
639 .. _The_Volatile_Parameter:
640
641 The ``Volatile`` Parameter
642 --------------------------
643
644 .. index:: Volatile parameter
645
646 Compiler optimizations in the presence of Inline Assembler may sometimes have
647 unwanted effects. For example, when an ``Asm`` invocation with an input
648 variable is inside a loop, the compiler might move the loading of the input
649 variable outside the loop, regarding it as a one-time initialization.
650
651 If you don't want this to happen, you can disable such optimizations by setting
652 the ``Volatile`` parameter to ``True``; for example:
653
654 .. code-block:: ada
655
656 Asm ("movl %0, %%ebx" & LF & HT &
657 "movl %%ebx, %1",
658 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
659 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
660 Clobber => "ebx",
661 Volatile => True);
662
663 By default, ``Volatile`` is set to ``False`` unless there is no
664 ``Outputs`` parameter.
665
666 Although setting ``Volatile`` to ``True`` prevents unwanted
667 optimizations, it also disables other optimizations that might be
668 important for efficiency. In general, you should set ``Volatile``
669 to ``True`` only if the compiler's optimizations have created
670 problems.