Debian Codegraph @

gcc/ada/doc/gnat_ugn/gnat_and_program_execution.rst

raw
1 .. role:: switch(samp)
2
3 .. |with| replace:: *with*
4 .. |withs| replace:: *with*\ s
5 .. |withed| replace:: *with*\ ed
6 .. |withing| replace:: *with*\ ing
7
8 .. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
9
10
11 .. _GNAT_and_Program_Execution:
12
13 **************************
14 GNAT and Program Execution
15 **************************
16
17 This chapter covers several topics:
18
19 * `Running and Debugging Ada Programs`_
20 * `Profiling`_
21 * `Improving Performance`_
22 * `Overflow Check Handling in GNAT`_
23 * `Performing Dimensionality Analysis in GNAT`_
24 * `Stack Related Facilities`_
25 * `Memory Management Issues`_
26
27 .. _Running_and_Debugging_Ada_Programs:
28
29 Running and Debugging Ada Programs
30 ==================================
31
32 .. index:: Debugging
33
34 This section discusses how to debug Ada programs.
35
36 An incorrect Ada program may be handled in three ways by the GNAT compiler:
37
38 * The illegality may be a violation of the static semantics of Ada. In
39 that case GNAT diagnoses the constructs in the program that are illegal.
40 It is then a straightforward matter for the user to modify those parts of
41 the program.
42
43 * The illegality may be a violation of the dynamic semantics of Ada. In
44 that case the program compiles and executes, but may generate incorrect
45 results, or may terminate abnormally with some exception.
46
47 * When presented with a program that contains convoluted errors, GNAT
48 itself may terminate abnormally without providing full diagnostics on
49 the incorrect user program.
50
51 .. index:: Debugger
52
53 .. index:: ! gdb
54
55 .. _The_GNAT_Debugger_GDB:
56
57 The GNAT Debugger GDB
58 ---------------------
59
60 ``GDB`` is a general purpose, platform-independent debugger that
61 can be used to debug mixed-language programs compiled with ``gcc``,
62 and in particular is capable of debugging Ada programs compiled with
63 GNAT. The latest versions of ``GDB`` are Ada-aware and can handle
64 complex Ada data structures.
65
66 See :title:`Debugging with GDB`,
67 for full details on the usage of ``GDB``, including a section on
68 its usage on programs. This manual should be consulted for full
69 details. The section that follows is a brief introduction to the
70 philosophy and use of ``GDB``.
71
72 When GNAT programs are compiled, the compiler optionally writes debugging
73 information into the generated object file, including information on
74 line numbers, and on declared types and variables. This information is
75 separate from the generated code. It makes the object files considerably
76 larger, but it does not add to the size of the actual executable that
77 will be loaded into memory, and has no impact on run-time performance. The
78 generation of debug information is triggered by the use of the
79 :switch:`-g` switch in the ``gcc`` or ``gnatmake`` command
80 used to carry out the compilations. It is important to emphasize that
81 the use of these options does not change the generated code.
82
83 The debugging information is written in standard system formats that
84 are used by many tools, including debuggers and profilers. The format
85 of the information is typically designed to describe C types and
86 semantics, but GNAT implements a translation scheme which allows full
87 details about Ada types and variables to be encoded into these
88 standard C formats. Details of this encoding scheme may be found in
89 the file exp_dbug.ads in the GNAT source distribution. However, the
90 details of this encoding are, in general, of no interest to a user,
91 since ``GDB`` automatically performs the necessary decoding.
92
93 When a program is bound and linked, the debugging information is
94 collected from the object files, and stored in the executable image of
95 the program. Again, this process significantly increases the size of
96 the generated executable file, but it does not increase the size of
97 the executable program itself. Furthermore, if this program is run in
98 the normal manner, it runs exactly as if the debug information were
99 not present, and takes no more actual memory.
100
101 However, if the program is run under control of ``GDB``, the
102 debugger is activated. The image of the program is loaded, at which
103 point it is ready to run. If a run command is given, then the program
104 will run exactly as it would have if ``GDB`` were not present. This
105 is a crucial part of the ``GDB`` design philosophy. ``GDB`` is
106 entirely non-intrusive until a breakpoint is encountered. If no
107 breakpoint is ever hit, the program will run exactly as it would if no
108 debugger were present. When a breakpoint is hit, ``GDB`` accesses
109 the debugging information and can respond to user commands to inspect
110 variables, and more generally to report on the state of execution.
111
112 .. _Running_GDB:
113
114 Running GDB
115 -----------
116
117 This section describes how to initiate the debugger.
118
119 The debugger can be launched from a ``GNAT Studio`` menu or
120 directly from the command line. The description below covers the latter use.
121 All the commands shown can be used in the ``GNAT Studio`` debug console window,
122 but there are usually more GUI-based ways to achieve the same effect.
123
124 The command to run ``GDB`` is
125
126 ::
127
128 $ gdb program
129
130 where ``program`` is the name of the executable file. This
131 activates the debugger and results in a prompt for debugger commands.
132 The simplest command is simply ``run``, which causes the program to run
133 exactly as if the debugger were not present. The following section
134 describes some of the additional commands that can be given to ``GDB``.
135
136
137 .. _Introduction_to_GDB_Commands:
138
139 Introduction to GDB Commands
140 ----------------------------
141
142 ``GDB`` contains a large repertoire of commands.
143 See :title:`Debugging with GDB` for extensive documentation on the use
144 of these commands, together with examples of their use. Furthermore,
145 the command *help* invoked from within GDB activates a simple help
146 facility which summarizes the available commands and their options.
147 In this section we summarize a few of the most commonly
148 used commands to give an idea of what ``GDB`` is about. You should create
149 a simple program with debugging information and experiment with the use of
150 these ``GDB`` commands on the program as you read through the
151 following section.
152
153 * :samp:`set args {arguments}`
154 The *arguments* list above is a list of arguments to be passed to
155 the program on a subsequent run command, just as though the arguments
156 had been entered on a normal invocation of the program. The ``set args``
157 command is not needed if the program does not require arguments.
158
159
160 * :samp:`run`
161 The ``run`` command causes execution of the program to start from
162 the beginning. If the program is already running, that is to say if
163 you are currently positioned at a breakpoint, then a prompt will ask
164 for confirmation that you want to abandon the current execution and
165 restart.
166
167
168 * :samp:`breakpoint {location}`
169 The breakpoint command sets a breakpoint, that is to say a point at which
170 execution will halt and ``GDB`` will await further
171 commands. *location* is
172 either a line number within a file, given in the format ``file:linenumber``,
173 or it is the name of a subprogram. If you request that a breakpoint be set on
174 a subprogram that is overloaded, a prompt will ask you to specify on which of
175 those subprograms you want to breakpoint. You can also
176 specify that all of them should be breakpointed. If the program is run
177 and execution encounters the breakpoint, then the program
178 stops and ``GDB`` signals that the breakpoint was encountered by
179 printing the line of code before which the program is halted.
180
181
182 * :samp:`catch exception {name}`
183 This command causes the program execution to stop whenever exception
184 ``name`` is raised. If ``name`` is omitted, then the execution is
185 suspended when any exception is raised.
186
187
188 * :samp:`print {expression}`
189 This will print the value of the given expression. Most simple
190 Ada expression formats are properly handled by ``GDB``, so the expression
191 can contain function calls, variables, operators, and attribute references.
192
193
194 * :samp:`continue`
195 Continues execution following a breakpoint, until the next breakpoint or the
196 termination of the program.
197
198
199 * :samp:`step`
200 Executes a single line after a breakpoint. If the next statement
201 is a subprogram call, execution continues into (the first statement of)
202 the called subprogram.
203
204
205 * :samp:`next`
206 Executes a single line. If this line is a subprogram call, executes and
207 returns from the call.
208
209
210 * :samp:`list`
211 Lists a few lines around the current source location. In practice, it
212 is usually more convenient to have a separate edit window open with the
213 relevant source file displayed. Successive applications of this command
214 print subsequent lines. The command can be given an argument which is a
215 line number, in which case it displays a few lines around the specified one.
216
217
218 * :samp:`backtrace`
219 Displays a backtrace of the call chain. This command is typically
220 used after a breakpoint has occurred, to examine the sequence of calls that
221 leads to the current breakpoint. The display includes one line for each
222 activation record (frame) corresponding to an active subprogram.
223
224
225 * :samp:`up`
226 At a breakpoint, ``GDB`` can display the values of variables local
227 to the current frame. The command ``up`` can be used to
228 examine the contents of other active frames, by moving the focus up
229 the stack, that is to say from callee to caller, one frame at a time.
230
231
232 * :samp:`down`
233 Moves the focus of ``GDB`` down from the frame currently being
234 examined to the frame of its callee (the reverse of the previous command),
235
236
237 * :samp:`frame {n}`
238 Inspect the frame with the given number. The value 0 denotes the frame
239 of the current breakpoint, that is to say the top of the call stack.
240
241
242 * :samp:`kill`
243 Kills the child process in which the program is running under GDB.
244 This may be useful for several purposes:
245
246 * It allows you to recompile and relink your program, since on many systems
247 you cannot regenerate an executable file while it is running in a process.
248
249 * You can run your program outside the debugger, on systems that do not
250 permit executing a program outside GDB while breakpoints are set
251 within GDB.
252
253 * It allows you to debug a core dump rather than a running process.
254
255 The above list is a very short introduction to the commands that
256 ``GDB`` provides. Important additional capabilities, including conditional
257 breakpoints, the ability to execute command sequences on a breakpoint,
258 the ability to debug at the machine instruction level and many other
259 features are described in detail in :title:`Debugging with GDB`.
260 Note that most commands can be abbreviated
261 (for example, c for continue, bt for backtrace).
262
263
264 .. _Using_Ada_Expressions:
265
266 Using Ada Expressions
267 ---------------------
268
269 .. index:: Ada expressions (in gdb)
270
271 ``GDB`` supports a fairly large subset of Ada expression syntax, with some
272 extensions. The philosophy behind the design of this subset is
273
274 * That ``GDB`` should provide basic literals and access to operations for
275 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
276 leaving more sophisticated computations to subprograms written into the
277 program (which therefore may be called from ``GDB``).
278
279 * That type safety and strict adherence to Ada language restrictions
280 are not particularly relevant in a debugging context.
281
282 * That brevity is important to the ``GDB`` user.
283
284 Thus, for brevity, the debugger acts as if there were
285 implicit ``with`` and ``use`` clauses in effect for all user-written
286 packages, thus making it unnecessary to fully qualify most names with
287 their packages, regardless of context. Where this causes ambiguity,
288 ``GDB`` asks the user's intent.
289
290 For details on the supported Ada syntax, see :title:`Debugging with GDB`.
291
292
293 .. _Calling_User-Defined_Subprograms:
294
295 Calling User-Defined Subprograms
296 --------------------------------
297
298 An important capability of ``GDB`` is the ability to call user-defined
299 subprograms while debugging. This is achieved simply by entering
300 a subprogram call statement in the form:
301
302 ::
303
304 call subprogram-name (parameters)
305
306 The keyword ``call`` can be omitted in the normal case where the
307 ``subprogram-name`` does not coincide with any of the predefined
308 ``GDB`` commands.
309
310 The effect is to invoke the given subprogram, passing it the
311 list of parameters that is supplied. The parameters can be expressions and
312 can include variables from the program being debugged. The
313 subprogram must be defined
314 at the library level within your program, and ``GDB`` will call the
315 subprogram within the environment of your program execution (which
316 means that the subprogram is free to access or even modify variables
317 within your program).
318
319 The most important use of this facility is in allowing the inclusion of
320 debugging routines that are tailored to particular data structures
321 in your program. Such debugging routines can be written to provide a suitably
322 high-level description of an abstract type, rather than a low-level dump
323 of its physical layout. After all, the standard
324 ``GDB print`` command only knows the physical layout of your
325 types, not their abstract meaning. Debugging routines can provide information
326 at the desired semantic level and are thus enormously useful.
327
328 For example, when debugging GNAT itself, it is crucial to have access to
329 the contents of the tree nodes used to represent the program internally.
330 But tree nodes are represented simply by an integer value (which in turn
331 is an index into a table of nodes).
332 Using the ``print`` command on a tree node would simply print this integer
333 value, which is not very useful. But the PN routine (defined in file
334 treepr.adb in the GNAT sources) takes a tree node as input, and displays
335 a useful high level representation of the tree node, which includes the
336 syntactic category of the node, its position in the source, the integers
337 that denote descendant nodes and parent node, as well as varied
338 semantic information. To study this example in more detail, you might want to
339 look at the body of the PN procedure in the stated file.
340
341 Another useful application of this capability is to deal with situations of
342 complex data which are not handled suitably by GDB. For example, if you specify
343 Convention Fortran for a multi-dimensional array, GDB does not know that
344 the ordering of array elements has been switched and will not properly
345 address the array elements. In such a case, instead of trying to print the
346 elements directly from GDB, you can write a callable procedure that prints
347 the elements in the desired format.
348
349
350 .. _Using_the_Next_Command_in_a_Function:
351
352 Using the *next* Command in a Function
353 --------------------------------------
354
355 When you use the ``next`` command in a function, the current source
356 location will advance to the next statement as usual. A special case
357 arises in the case of a ``return`` statement.
358
359 Part of the code for a return statement is the 'epilogue' of the function.
360 This is the code that returns to the caller. There is only one copy of
361 this epilogue code, and it is typically associated with the last return
362 statement in the function if there is more than one return. In some
363 implementations, this epilogue is associated with the first statement
364 of the function.
365
366 The result is that if you use the ``next`` command from a return
367 statement that is not the last return statement of the function you
368 may see a strange apparent jump to the last return statement or to
369 the start of the function. You should simply ignore this odd jump.
370 The value returned is always that from the first return statement
371 that was stepped through.
372
373
374 .. _Stopping_When_Ada_Exceptions_Are_Raised:
375
376 Stopping When Ada Exceptions Are Raised
377 ---------------------------------------
378
379 .. index:: Exceptions (in gdb)
380
381 You can set catchpoints that stop the program execution when your program
382 raises selected exceptions.
383
384
385 * :samp:`catch exception`
386 Set a catchpoint that stops execution whenever (any task in the) program
387 raises any exception.
388
389
390 * :samp:`catch exception {name}`
391 Set a catchpoint that stops execution whenever (any task in the) program
392 raises the exception *name*.
393
394
395 * :samp:`catch exception unhandled`
396 Set a catchpoint that stops executing whenever (any task in the) program
397 raises an exception for which there is no handler.
398
399
400 * :samp:`info exceptions`, :samp:`info exceptions {regexp}`
401 The ``info exceptions`` command permits the user to examine all defined
402 exceptions within Ada programs. With a regular expression, *regexp*, as
403 argument, prints out only those exceptions whose name matches *regexp*.
404
405
406 .. index:: Tasks (in gdb)
407
408 .. _Ada_Tasks:
409
410 Ada Tasks
411 ---------
412
413 ``GDB`` allows the following task-related commands:
414
415
416 * :samp:`info tasks`
417 This command shows a list of current Ada tasks, as in the following example:
418
419 ::
420
421 (gdb) info tasks
422 ID TID P-ID Thread Pri State Name
423 1 8088000 0 807e000 15 Child Activation Wait main_task
424 2 80a4000 1 80ae000 15 Accept/Select Wait b
425 3 809a800 1 80a4800 15 Child Activation Wait a
426 * 4 80ae800 3 80b8000 15 Running c
427
428
429 In this listing, the asterisk before the first task indicates it to be the
430 currently running task. The first column lists the task ID that is used
431 to refer to tasks in the following commands.
432
433
434 .. index:: Breakpoints and tasks
435
436 * ``break``*linespec* ``task`` *taskid*, ``break`` *linespec* ``task`` *taskid* ``if`` ...
437
438 These commands are like the ``break ... thread ...``.
439 *linespec* specifies source lines.
440
441 Use the qualifier :samp:`task {taskid}` with a breakpoint command
442 to specify that you only want ``GDB`` to stop the program when a
443 particular Ada task reaches this breakpoint. *taskid* is one of the
444 numeric task identifiers assigned by ``GDB``, shown in the first
445 column of the ``info tasks`` display.
446
447 If you do not specify :samp:`task {taskid}` when you set a
448 breakpoint, the breakpoint applies to *all* tasks of your
449 program.
450
451 You can use the ``task`` qualifier on conditional breakpoints as
452 well; in this case, place :samp:`task {taskid}` before the
453 breakpoint condition (before the ``if``).
454
455 .. index:: Task switching (in gdb)
456
457 * :samp:`task {taskno}`
458
459 This command allows switching to the task referred by *taskno*. In
460 particular, this allows browsing of the backtrace of the specified
461 task. It is advisable to switch back to the original task before
462 continuing execution otherwise the scheduling of the program may be
463 perturbed.
464
465 For more detailed information on the tasking support,
466 see :title:`Debugging with GDB`.
467
468
469 .. index:: Debugging Generic Units
470 .. index:: Generics
471
472 .. _Debugging_Generic_Units:
473
474 Debugging Generic Units
475 -----------------------
476
477 GNAT always uses code expansion for generic instantiation. This means that
478 each time an instantiation occurs, a complete copy of the original code is
479 made, with appropriate substitutions of formals by actuals.
480
481 It is not possible to refer to the original generic entities in
482 ``GDB``, but it is always possible to debug a particular instance of
483 a generic, by using the appropriate expanded names. For example, if we have
484
485 .. code-block:: ada
486
487 procedure g is
488
489 generic package k is
490 procedure kp (v1 : in out integer);
491 end k;
492
493 package body k is
494 procedure kp (v1 : in out integer) is
495 begin
496 v1 := v1 + 1;
497 end kp;
498 end k;
499
500 package k1 is new k;
501 package k2 is new k;
502
503 var : integer := 1;
504
505 begin
506 k1.kp (var);
507 k2.kp (var);
508 k1.kp (var);
509 k2.kp (var);
510 end;
511
512 Then to break on a call to procedure kp in the k2 instance, simply
513 use the command:
514
515 ::
516
517 (gdb) break g.k2.kp
518
519 When the breakpoint occurs, you can step through the code of the
520 instance in the normal manner and examine the values of local variables, as for
521 other units.
522
523
524 .. index:: Remote Debugging with gdbserver
525
526 .. _Remote_Debugging_with_gdbserver:
527
528 Remote Debugging with gdbserver
529 -------------------------------
530
531 On platforms where gdbserver is supported, it is possible to use this tool
532 to debug your application remotely. This can be useful in situations
533 where the program needs to be run on a target host that is different
534 from the host used for development, particularly when the target has
535 a limited amount of resources (either CPU and/or memory).
536
537 To do so, start your program using gdbserver on the target machine.
538 gdbserver then automatically suspends the execution of your program
539 at its entry point, waiting for a debugger to connect to it. The
540 following commands starts an application and tells gdbserver to
541 wait for a connection with the debugger on localhost port 4444.
542
543
544 ::
545
546 $ gdbserver localhost:4444 program
547 Process program created; pid = 5685
548 Listening on port 4444
549
550 Once gdbserver has started listening, we can tell the debugger to establish
551 a connection with this gdbserver, and then start the same debugging session
552 as if the program was being debugged on the same host, directly under
553 the control of GDB.
554
555 ::
556
557 $ gdb program
558 (gdb) target remote targethost:4444
559 Remote debugging using targethost:4444
560 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
561 (gdb) b foo.adb:3
562 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
563 (gdb) continue
564 Continuing.
565
566 Breakpoint 1, foo () at foo.adb:4
567 4 end foo;
568
569 It is also possible to use gdbserver to attach to an already running
570 program, in which case the execution of that program is simply suspended
571 until the connection between the debugger and gdbserver is established.
572
573 For more information on how to use gdbserver, see the *Using the gdbserver Program*
574 section in :title:`Debugging with GDB`.
575 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
576
577
578 .. index:: Abnormal Termination or Failure to Terminate
579
580 .. _GNAT_Abnormal_Termination_or_Failure_to_Terminate:
581
582 GNAT Abnormal Termination or Failure to Terminate
583 -------------------------------------------------
584
585 When presented with programs that contain serious errors in syntax
586 or semantics,
587 GNAT may on rare occasions experience problems in operation, such
588 as aborting with a
589 segmentation fault or illegal memory access, raising an internal
590 exception, terminating abnormally, or failing to terminate at all.
591 In such cases, you can activate
592 various features of GNAT that can help you pinpoint the construct in your
593 program that is the likely source of the problem.
594
595 The following strategies are presented in increasing order of
596 difficulty, corresponding to your experience in using GNAT and your
597 familiarity with compiler internals.
598
599 * Run ``gcc`` with the :switch:`-gnatf`. This first
600 switch causes all errors on a given line to be reported. In its absence,
601 only the first error on a line is displayed.
602
603 The :switch:`-gnatdO` switch causes errors to be displayed as soon as they
604 are encountered, rather than after compilation is terminated. If GNAT
605 terminates prematurely or goes into an infinite loop, the last error
606 message displayed may help to pinpoint the culprit.
607
608 * Run ``gcc`` with the :switch:`-v` (verbose) switch. In this
609 mode, ``gcc`` produces ongoing information about the progress of the
610 compilation and provides the name of each procedure as code is
611 generated. This switch allows you to find which Ada procedure was being
612 compiled when it encountered a code generation problem.
613
614 .. index:: -gnatdc switch
615
616 * Run ``gcc`` with the :switch:`-gnatdc` switch. This is a GNAT specific
617 switch that does for the front-end what :switch:`-v` does
618 for the back end. The system prints the name of each unit,
619 either a compilation unit or nested unit, as it is being analyzed.
620
621 * Finally, you can start
622 ``gdb`` directly on the ``gnat1`` executable. ``gnat1`` is the
623 front-end of GNAT, and can be run independently (normally it is just
624 called from ``gcc``). You can use ``gdb`` on ``gnat1`` as you
625 would on a C program (but :ref:`The_GNAT_Debugger_GDB` for caveats). The
626 ``where`` command is the first line of attack; the variable
627 ``lineno`` (seen by ``print lineno``), used by the second phase of
628 ``gnat1`` and by the ``gcc`` backend, indicates the source line at
629 which the execution stopped, and ``input_file name`` indicates the name of
630 the source file.
631
632
633 .. _Naming_Conventions_for_GNAT_Source_Files:
634
635 Naming Conventions for GNAT Source Files
636 ----------------------------------------
637
638 In order to examine the workings of the GNAT system, the following
639 brief description of its organization may be helpful:
640
641 * Files with prefix :file:`sc` contain the lexical scanner.
642
643 * All files prefixed with :file:`par` are components of the parser. The
644 numbers correspond to chapters of the Ada Reference Manual. For example,
645 parsing of select statements can be found in :file:`par-ch9.adb`.
646
647 * All files prefixed with :file:`sem` perform semantic analysis. The
648 numbers correspond to chapters of the Ada standard. For example, all
649 issues involving context clauses can be found in :file:`sem_ch10.adb`. In
650 addition, some features of the language require sufficient special processing
651 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
652 dynamic dispatching, etc.
653
654 * All files prefixed with :file:`exp` perform normalization and
655 expansion of the intermediate representation (abstract syntax tree, or AST).
656 these files use the same numbering scheme as the parser and semantics files.
657 For example, the construction of record initialization procedures is done in
658 :file:`exp_ch3.adb`.
659
660 * The files prefixed with :file:`bind` implement the binder, which
661 verifies the consistency of the compilation, determines an order of
662 elaboration, and generates the bind file.
663
664 * The files :file:`atree.ads` and :file:`atree.adb` detail the low-level
665 data structures used by the front-end.
666
667 * The files :file:`sinfo.ads` and :file:`sinfo.adb` detail the structure of
668 the abstract syntax tree as produced by the parser.
669
670 * The files :file:`einfo.ads` and :file:`einfo.adb` detail the attributes of
671 all entities, computed during semantic analysis.
672
673 * Library management issues are dealt with in files with prefix
674 :file:`lib`.
675
676 .. index:: Annex A (in Ada Reference Manual)
677
678 * Ada files with the prefix :file:`a-` are children of ``Ada``, as
679 defined in Annex A.
680
681 .. index:: Annex B (in Ada reference Manual)
682
683 * Files with prefix :file:`i-` are children of ``Interfaces``, as
684 defined in Annex B.
685
686 .. index:: System (package in Ada Reference Manual)
687
688 * Files with prefix :file:`s-` are children of ``System``. This includes
689 both language-defined children and GNAT run-time routines.
690
691 .. index:: GNAT (package)
692
693 * Files with prefix :file:`g-` are children of ``GNAT``. These are useful
694 general-purpose packages, fully documented in their specs. All
695 the other :file:`.c` files are modifications of common ``gcc`` files.
696
697
698 .. _Getting_Internal_Debugging_Information:
699
700 Getting Internal Debugging Information
701 --------------------------------------
702
703 Most compilers have internal debugging switches and modes. GNAT
704 does also, except GNAT internal debugging switches and modes are not
705 secret. A summary and full description of all the compiler and binder
706 debug flags are in the file :file:`debug.adb`. You must obtain the
707 sources of the compiler to see the full detailed effects of these flags.
708
709 The switches that print the source of the program (reconstructed from
710 the internal tree) are of general interest for user programs, as are the
711 options to print
712 the full internal tree, and the entity table (the symbol table
713 information). The reconstructed source provides a readable version of the
714 program after the front-end has completed analysis and expansion,
715 and is useful when studying the performance of specific constructs.
716 For example, constraint checks are indicated, complex aggregates
717 are replaced with loops and assignments, and tasking primitives
718 are replaced with run-time calls.
719
720
721 .. index:: traceback
722 .. index:: stack traceback
723 .. index:: stack unwinding
724
725 .. _Stack_Traceback:
726
727 Stack Traceback
728 ---------------
729
730 Traceback is a mechanism to display the sequence of subprogram calls that
731 leads to a specified execution point in a program. Often (but not always)
732 the execution point is an instruction at which an exception has been raised.
733 This mechanism is also known as *stack unwinding* because it obtains
734 its information by scanning the run-time stack and recovering the activation
735 records of all active subprograms. Stack unwinding is one of the most
736 important tools for program debugging.
737
738 The first entry stored in traceback corresponds to the deepest calling level,
739 that is to say the subprogram currently executing the instruction
740 from which we want to obtain the traceback.
741
742 Note that there is no runtime performance penalty when stack traceback
743 is enabled, and no exception is raised during program execution.
744
745 .. index:: traceback, non-symbolic
746
747 .. _Non-Symbolic_Traceback:
748
749 Non-Symbolic Traceback
750 ^^^^^^^^^^^^^^^^^^^^^^
751
752 Note: this feature is not supported on all platforms. See
753 :samp:`GNAT.Traceback` spec in :file:`g-traceb.ads`
754 for a complete list of supported platforms.
755
756 .. rubric:: Tracebacks From an Unhandled Exception
757
758 A runtime non-symbolic traceback is a list of addresses of call instructions.
759 To enable this feature you must use the :switch:`-E`
760 ``gnatbind`` option. With this option a stack traceback is stored as part
761 of exception information. You can retrieve this information using the
762 ``addr2line`` tool.
763
764 Here is a simple example:
765
766 .. code-block:: ada
767
768 procedure STB is
769
770 procedure P1 is
771 begin
772 raise Constraint_Error;
773 end P1;
774
775 procedure P2 is
776 begin
777 P1;
778 end P2;
779
780 begin
781 P2;
782 end STB;
783
784 ::
785
786 $ gnatmake stb -bargs -E
787 $ stb
788
789 Execution terminated by unhandled exception
790 Exception name: CONSTRAINT_ERROR
791 Message: stb.adb:5
792 Call stack traceback locations:
793 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
794
795 As we see the traceback lists a sequence of addresses for the unhandled
796 exception ``CONSTRAINT_ERROR`` raised in procedure P1. It is easy to
797 guess that this exception come from procedure P1. To translate these
798 addresses into the source lines where the calls appear, the
799 ``addr2line`` tool, described below, is invaluable. The use of this tool
800 requires the program to be compiled with debug information.
801
802 ::
803
804 $ gnatmake -g stb -bargs -E
805 $ stb
806
807 Execution terminated by unhandled exception
808 Exception name: CONSTRAINT_ERROR
809 Message: stb.adb:5
810 Call stack traceback locations:
811 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
812
813 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
814 0x4011f1 0x77e892a4
815
816 00401373 at d:/stb/stb.adb:5
817 0040138B at d:/stb/stb.adb:10
818 0040139C at d:/stb/stb.adb:14
819 00401335 at d:/stb/b~stb.adb:104
820 004011C4 at /build/.../crt1.c:200
821 004011F1 at /build/.../crt1.c:222
822 77E892A4 in ?? at ??:0
823
824 The ``addr2line`` tool has several other useful options:
825
826 ======================== ========================================================
827 :samp:`--functions` to get the function name corresponding to any location
828 :samp:`--demangle=gnat` to use the gnat decoding mode for the function names.
829 Note that for binutils version 2.9.x the option is
830 simply :samp:`--demangle`.
831 ======================== ========================================================
832
833 ::
834
835 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
836 0x40139c 0x401335 0x4011c4 0x4011f1
837
838 00401373 in stb.p1 at d:/stb/stb.adb:5
839 0040138B in stb.p2 at d:/stb/stb.adb:10
840 0040139C in stb at d:/stb/stb.adb:14
841 00401335 in main at d:/stb/b~stb.adb:104
842 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
843 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
844
845 From this traceback we can see that the exception was raised in
846 :file:`stb.adb` at line 5, which was reached from a procedure call in
847 :file:`stb.adb` at line 10, and so on. The :file:`b~std.adb` is the binder file,
848 which contains the call to the main program.
849 :ref:`Running_gnatbind`. The remaining entries are assorted runtime routines,
850 and the output will vary from platform to platform.
851
852 It is also possible to use ``GDB`` with these traceback addresses to debug
853 the program. For example, we can break at a given code location, as reported
854 in the stack traceback:
855
856 ::
857
858 $ gdb -nw stb
859
860 Furthermore, this feature is not implemented inside Windows DLL. Only
861 the non-symbolic traceback is reported in this case.
862
863 ::
864
865 (gdb) break *0x401373
866 Breakpoint 1 at 0x401373: file stb.adb, line 5.
867
868 It is important to note that the stack traceback addresses
869 do not change when debug information is included. This is particularly useful
870 because it makes it possible to release software without debug information (to
871 minimize object size), get a field report that includes a stack traceback
872 whenever an internal bug occurs, and then be able to retrieve the sequence
873 of calls with the same program compiled with debug information.
874
875
876 .. rubric:: Tracebacks From Exception Occurrences
877
878 Non-symbolic tracebacks are obtained by using the :switch:`-E` binder argument.
879 The stack traceback is attached to the exception information string, and can
880 be retrieved in an exception handler within the Ada program, by means of the
881 Ada facilities defined in ``Ada.Exceptions``. Here is a simple example:
882
883 .. code-block:: ada
884
885 with Ada.Text_IO;
886 with Ada.Exceptions;
887
888 procedure STB is
889
890 use Ada;
891 use Ada.Exceptions;
892
893 procedure P1 is
894 K : Positive := 1;
895 begin
896 K := K - 1;
897 exception
898 when E : others =>
899 Text_IO.Put_Line (Exception_Information (E));
900 end P1;
901
902 procedure P2 is
903 begin
904 P1;
905 end P2;
906
907 begin
908 P2;
909 end STB;
910
911 This program will output:
912
913 ::
914
915 $ stb
916
917 Exception name: CONSTRAINT_ERROR
918 Message: stb.adb:12
919 Call stack traceback locations:
920 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
921
922
923 .. rubric:: Tracebacks From Anywhere in a Program
924
925 It is also possible to retrieve a stack traceback from anywhere in a
926 program. For this you need to
927 use the ``GNAT.Traceback`` API. This package includes a procedure called
928 ``Call_Chain`` that computes a complete stack traceback, as well as useful
929 display procedures described below. It is not necessary to use the
930 :switch:`-E` ``gnatbind`` option in this case, because the stack traceback mechanism
931 is invoked explicitly.
932
933 In the following example we compute a traceback at a specific location in
934 the program, and we display it using ``GNAT.Debug_Utilities.Image`` to
935 convert addresses to strings:
936
937
938 .. code-block:: ada
939
940 with Ada.Text_IO;
941 with GNAT.Traceback;
942 with GNAT.Debug_Utilities;
943
944 procedure STB is
945
946 use Ada;
947 use GNAT;
948 use GNAT.Traceback;
949
950 procedure P1 is
951 TB : Tracebacks_Array (1 .. 10);
952 -- We are asking for a maximum of 10 stack frames.
953 Len : Natural;
954 -- Len will receive the actual number of stack frames returned.
955 begin
956 Call_Chain (TB, Len);
957
958 Text_IO.Put ("In STB.P1 : ");
959
960 for K in 1 .. Len loop
961 Text_IO.Put (Debug_Utilities.Image (TB (K)));
962 Text_IO.Put (' ');
963 end loop;
964
965 Text_IO.New_Line;
966 end P1;
967
968 procedure P2 is
969 begin
970 P1;
971 end P2;
972
973 begin
974 P2;
975 end STB;
976
977 ::
978
979 $ gnatmake -g stb
980 $ stb
981
982 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
983 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
984
985
986 You can then get further information by invoking the ``addr2line``
987 tool as described earlier (note that the hexadecimal addresses
988 need to be specified in C format, with a leading '0x').
989
990 .. index:: traceback, symbolic
991
992 .. _Symbolic_Traceback:
993
994 Symbolic Traceback
995 ^^^^^^^^^^^^^^^^^^
996
997 A symbolic traceback is a stack traceback in which procedure names are
998 associated with each code location.
999
1000 Note that this feature is not supported on all platforms. See
1001 :samp:`GNAT.Traceback.Symbolic` spec in :file:`g-trasym.ads` for a complete
1002 list of currently supported platforms.
1003
1004 Note that the symbolic traceback requires that the program be compiled
1005 with debug information. If it is not compiled with debug information
1006 only the non-symbolic information will be valid.
1007
1008
1009 .. rubric:: Tracebacks From Exception Occurrences
1010
1011 Here is an example:
1012
1013 .. code-block:: ada
1014
1015 with Ada.Text_IO;
1016 with GNAT.Traceback.Symbolic;
1017
1018 procedure STB is
1019
1020 procedure P1 is
1021 begin
1022 raise Constraint_Error;
1023 end P1;
1024
1025 procedure P2 is
1026 begin
1027 P1;
1028 end P2;
1029
1030 procedure P3 is
1031 begin
1032 P2;
1033 end P3;
1034
1035 begin
1036 P3;
1037 exception
1038 when E : others =>
1039 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
1040 end STB;
1041
1042 ::
1043
1044 $ gnatmake -g .\stb -bargs -E
1045 $ stb
1046
1047 0040149F in stb.p1 at stb.adb:8
1048 004014B7 in stb.p2 at stb.adb:13
1049 004014CF in stb.p3 at stb.adb:18
1050 004015DD in ada.stb at stb.adb:22
1051 00401461 in main at b~stb.adb:168
1052 004011C4 in __mingw_CRTStartup at crt1.c:200
1053 004011F1 in mainCRTStartup at crt1.c:222
1054 77E892A4 in ?? at ??:0
1055
1056 In the above example the ``.\`` syntax in the ``gnatmake`` command
1057 is currently required by ``addr2line`` for files that are in
1058 the current working directory.
1059 Moreover, the exact sequence of linker options may vary from platform
1060 to platform.
1061 The above :switch:`-largs` section is for Windows platforms. By contrast,
1062 under Unix there is no need for the :switch:`-largs` section.
1063 Differences across platforms are due to details of linker implementation.
1064
1065
1066 .. rubric:: Tracebacks From Anywhere in a Program
1067
1068 It is possible to get a symbolic stack traceback
1069 from anywhere in a program, just as for non-symbolic tracebacks.
1070 The first step is to obtain a non-symbolic
1071 traceback, and then call ``Symbolic_Traceback`` to compute the symbolic
1072 information. Here is an example:
1073
1074 .. code-block:: ada
1075
1076 with Ada.Text_IO;
1077 with GNAT.Traceback;
1078 with GNAT.Traceback.Symbolic;
1079
1080 procedure STB is
1081
1082 use Ada;
1083 use GNAT.Traceback;
1084 use GNAT.Traceback.Symbolic;
1085
1086 procedure P1 is
1087 TB : Tracebacks_Array (1 .. 10);
1088 -- We are asking for a maximum of 10 stack frames.
1089 Len : Natural;
1090 -- Len will receive the actual number of stack frames returned.
1091 begin
1092 Call_Chain (TB, Len);
1093 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
1094 end P1;
1095
1096 procedure P2 is
1097 begin
1098 P1;
1099 end P2;
1100
1101 begin
1102 P2;
1103 end STB;
1104
1105
1106 .. rubric:: Automatic Symbolic Tracebacks
1107
1108 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
1109 in ``gprbuild -g ... -bargs -Es``).
1110 This will cause the Exception_Information to contain a symbolic traceback,
1111 which will also be printed if an unhandled exception terminates the
1112 program.
1113
1114
1115 .. _Pretty-Printers_For_The_GNAT_Runtime:
1116
1117 Pretty-Printers for the GNAT runtime
1118 ------------------------------------
1119
1120 As discussed in :title:`Calling User-Defined Subprograms`, GDB's
1121 ``print`` command only knows about the physical layout of program data
1122 structures and therefore normally displays only low-level dumps, which
1123 are often hard to understand.
1124
1125 An example of this is when trying to display the contents of an Ada
1126 standard container, such as ``Ada.Containers.Ordered_Maps.Map``:
1127
1128 .. code-block:: ada
1129
1130 with Ada.Containers.Ordered_Maps;
1131
1132 procedure PP is
1133 package Int_To_Nat is
1134 new Ada.Containers.Ordered_Maps (Integer, Natural);
1135
1136 Map : Int_To_Nat.Map;
1137 begin
1138 Map.Insert (1, 10);
1139 Map.Insert (2, 20);
1140 Map.Insert (3, 30);
1141
1142 Map.Clear; -- BREAK HERE
1143 end PP;
1144
1145 When this program is built with debugging information and run under
1146 GDB up to the ``Map.Clear`` statement, trying to print ``Map`` will
1147 yield information that is only relevant to the developers of our standard
1148 containers:
1149
1150 ::
1151
1152 (gdb) print map
1153 $1 = (
1154 tree => (
1155 first => 0x64e010,
1156 last => 0x64e070,
1157 root => 0x64e040,
1158 length => 3,
1159 tc => (
1160 busy => 0,
1161 lock => 0
1162 )
1163 )
1164 )
1165
1166 Fortunately, GDB has a feature called `pretty-printers
1167 <http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction>`_,
1168 which allows customizing how GDB displays data structures. The GDB
1169 shipped with GNAT embeds such pretty-printers for the most common
1170 containers in the standard library. To enable them, either run the
1171 following command manually under GDB or add it to your ``.gdbinit`` file:
1172
1173 ::
1174
1175 python import gnatdbg; gnatdbg.setup()
1176
1177 Once this is done, GDB's ``print`` command will automatically use
1178 these pretty-printers when appropriate. Using the previous example:
1179
1180 ::
1181
1182 (gdb) print map
1183 $1 = pp.int_to_nat.map of length 3 = {
1184 [1] = 10,
1185 [2] = 20,
1186 [3] = 30
1187 }
1188
1189 Pretty-printers are invoked each time GDB tries to display a value,
1190 including when displaying the arguments of a called subprogram (in
1191 GDB's ``backtrace`` command) or when printing the value returned by a
1192 function (in GDB's ``finish`` command).
1193
1194 To display a value without involving pretty-printers, ``print`` can be
1195 invoked with its ``/r`` option:
1196
1197 ::
1198
1199 (gdb) print/r map
1200 $1 = (
1201 tree => (...
1202
1203 Finer control of pretty-printers is also possible: see `GDB's online
1204 documentation
1205 <http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Commands>`_
1206 for more information.
1207
1208
1209 .. index:: Profiling
1210
1211
1212 .. _Profiling:
1213
1214 Profiling
1215 =========
1216
1217 This section describes how to use the ``gprof`` profiler tool on Ada programs.
1218
1219 .. index:: ! gprof
1220 .. index:: Profiling
1221
1222 .. _Profiling_an_Ada_Program_with_gprof:
1223
1224 Profiling an Ada Program with gprof
1225 -----------------------------------
1226
1227 This section is not meant to be an exhaustive documentation of ``gprof``.
1228 Full documentation for it can be found in the :title:`GNU Profiler User's Guide`
1229 documentation that is part of this GNAT distribution.
1230
1231 Profiling a program helps determine the parts of a program that are executed
1232 most often, and are therefore the most time-consuming.
1233
1234 ``gprof`` is the standard GNU profiling tool; it has been enhanced to
1235 better handle Ada programs and multitasking.
1236 It is currently supported on the following platforms
1237
1238 * linux x86/x86_64
1239 * windows x86
1240
1241 In order to profile a program using ``gprof``, several steps are needed:
1242
1243 #. Instrument the code, which requires a full recompilation of the project with the
1244 proper switches.
1245
1246 #. Execute the program under the analysis conditions, i.e. with the desired
1247 input.
1248
1249 #. Analyze the results using the ``gprof`` tool.
1250
1251 The following sections detail the different steps, and indicate how
1252 to interpret the results.
1253
1254
1255 .. _Compilation_for_profiling:
1256
1257 Compilation for profiling
1258 ^^^^^^^^^^^^^^^^^^^^^^^^^
1259
1260 .. index:: -pg (gcc), for profiling
1261 .. index:: -pg (gnatlink), for profiling
1262
1263 In order to profile a program the first step is to tell the compiler
1264 to generate the necessary profiling information. The compiler switch to be used
1265 is ``-pg``, which must be added to other compilation switches. This
1266 switch needs to be specified both during compilation and link stages, and can
1267 be specified once when using gnatmake:
1268
1269 ::
1270
1271 $ gnatmake -f -pg -P my_project
1272
1273 Note that only the objects that were compiled with the ``-pg`` switch will
1274 be profiled; if you need to profile your whole project, use the ``-f``
1275 gnatmake switch to force full recompilation.
1276
1277 .. _Program_execution:
1278
1279
1280 Program execution
1281 ^^^^^^^^^^^^^^^^^
1282
1283 Once the program has been compiled for profiling, you can run it as usual.
1284
1285 The only constraint imposed by profiling is that the program must terminate
1286 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
1287 properly analyzed.
1288
1289 Once the program completes execution, a data file called :file:`gmon.out` is
1290 generated in the directory where the program was launched from. If this file
1291 already exists, it will be overwritten.
1292
1293
1294 .. _Running_gprof:
1295
1296 Running gprof
1297 ^^^^^^^^^^^^^
1298
1299 The ``gprof`` tool is called as follow:
1300
1301 ::
1302
1303 $ gprof my_prog gmon.out
1304
1305 or simply:
1306
1307 ::
1308
1309 $ gprof my_prog
1310
1311 The complete form of the gprof command line is the following:
1312
1313 ::
1314
1315 $ gprof [switches] [executable [data-file]]
1316
1317 ``gprof`` supports numerous switches. The order of these
1318 switch does not matter. The full list of options can be found in
1319 the GNU Profiler User's Guide documentation that comes with this documentation.
1320
1321 The following is the subset of those switches that is most relevant:
1322
1323 .. index:: --demangle (gprof)
1324
1325 :samp:`--demangle[={style}]`, :samp:`--no-demangle`
1326 These options control whether symbol names should be demangled when
1327 printing output. The default is to demangle C++ symbols. The
1328 ``--no-demangle`` option may be used to turn off demangling. Different
1329 compilers have different mangling styles. The optional demangling style
1330 argument can be used to choose an appropriate demangling style for your
1331 compiler, in particular Ada symbols generated by GNAT can be demangled using
1332 ``--demangle=gnat``.
1333
1334
1335 .. index:: -e (gprof)
1336
1337 :samp:`-e {function_name}`
1338 The :samp:`-e {function}` option tells ``gprof`` not to print
1339 information about the function ``function_name`` (and its
1340 children...) in the call graph. The function will still be listed
1341 as a child of any functions that call it, but its index number will be
1342 shown as ``[not printed]``. More than one ``-e`` option may be
1343 given; only one ``function_name`` may be indicated with each ``-e``
1344 option.
1345
1346
1347 .. index:: -E (gprof)
1348
1349 :samp:`-E {function_name}`
1350 The :samp:`-E {function}` option works like the ``-e`` option, but
1351 execution time spent in the function (and children who were not called from
1352 anywhere else), will not be used to compute the percentages-of-time for
1353 the call graph. More than one :switch:`-E` option may be given; only one
1354 ``function_name`` may be indicated with each :switch:`-E`` option.
1355
1356
1357 .. index:: -f (gprof)
1358
1359 :samp:`-f {function_name}`
1360 The :samp:`-f {function}` option causes ``gprof`` to limit the
1361 call graph to the function ``function_name`` and its children (and
1362 their children...). More than one ``-f`` option may be given;
1363 only one ``function_name`` may be indicated with each ``-f``
1364 option.
1365
1366
1367 .. index:: -F (gprof)
1368
1369 :samp:`-F {function_name}`
1370 The :samp:`-F {function}` option works like the ``-f`` option, but
1371 only time spent in the function and its children (and their
1372 children...) will be used to determine total-time and
1373 percentages-of-time for the call graph. More than one ``-F`` option
1374 may be given; only one ``function_name`` may be indicated with each
1375 ``-F`` option. The ``-F`` option overrides the ``-E`` option.
1376
1377
1378 .. _Interpretation_of_profiling_results:
1379
1380 Interpretation of profiling results
1381 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1382
1383 The results of the profiling analysis are represented by two arrays: the
1384 'flat profile' and the 'call graph'. Full documentation of those outputs
1385 can be found in the GNU Profiler User's Guide.
1386
1387 The flat profile shows the time spent in each function of the program, and how
1388 many time it has been called. This allows you to locate easily the most
1389 time-consuming functions.
1390
1391 The call graph shows, for each subprogram, the subprograms that call it,
1392 and the subprograms that it calls. It also provides an estimate of the time
1393 spent in each of those callers/called subprograms.
1394
1395
1396
1397 .. _Improving_Performance:
1398
1399 Improving Performance
1400 =====================
1401
1402 .. index:: Improving performance
1403
1404 This section presents several topics related to program performance.
1405 It first describes some of the tradeoffs that need to be considered
1406 and some of the techniques for making your program run faster.
1407
1408 It then documents the unused subprogram/data elimination feature,
1409 which can reduce the size of program executables.
1410
1411 .. _Performance_Considerations:
1412
1413 Performance Considerations
1414 --------------------------
1415
1416 The GNAT system provides a number of options that allow a trade-off
1417 between
1418
1419 * performance of the generated code
1420
1421 * speed of compilation
1422
1423 * minimization of dependences and recompilation
1424
1425 * the degree of run-time checking.
1426
1427 The defaults (if no options are selected) aim at improving the speed
1428 of compilation and minimizing dependences, at the expense of performance
1429 of the generated code:
1430
1431 * no optimization
1432
1433 * no inlining of subprogram calls
1434
1435 * all run-time checks enabled except overflow and elaboration checks
1436
1437 These options are suitable for most program development purposes. This
1438 section describes how you can modify these choices, and also provides
1439 some guidelines on debugging optimized code.
1440
1441
1442 .. _Controlling_Run-Time_Checks:
1443
1444 Controlling Run-Time Checks
1445 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1446
1447 By default, GNAT generates all run-time checks, except stack overflow
1448 checks, and checks for access before elaboration on subprogram
1449 calls. The latter are not required in default mode, because all
1450 necessary checking is done at compile time.
1451
1452 .. index:: -gnatp (gcc)
1453 .. index:: -gnato (gcc)
1454
1455 The gnat switch, :switch:`-gnatp` allows this default to be modified. See
1456 :ref:`Run-Time_Checks`.
1457
1458 Our experience is that the default is suitable for most development
1459 purposes.
1460
1461 Elaboration checks are off by default, and also not needed by default, since
1462 GNAT uses a static elaboration analysis approach that avoids the need for
1463 run-time checking. This manual contains a full chapter discussing the issue
1464 of elaboration checks, and if the default is not satisfactory for your use,
1465 you should read this chapter.
1466
1467 For validity checks, the minimal checks required by the Ada Reference
1468 Manual (for case statements and assignments to array elements) are on
1469 by default. These can be suppressed by use of the :switch:`-gnatVn` switch.
1470 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
1471 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
1472 it may be reasonable to routinely use :switch:`-gnatVn`. Validity checks
1473 are also suppressed entirely if :switch:`-gnatp` is used.
1474
1475 .. index:: Overflow checks
1476 .. index:: Checks, overflow
1477
1478 .. index:: Suppress
1479 .. index:: Unsuppress
1480 .. index:: pragma Suppress
1481 .. index:: pragma Unsuppress
1482
1483 Note that the setting of the switches controls the default setting of
1484 the checks. They may be modified using either ``pragma Suppress`` (to
1485 remove checks) or ``pragma Unsuppress`` (to add back suppressed
1486 checks) in the program source.
1487
1488
1489 .. _Use_of_Restrictions:
1490
1491 Use of Restrictions
1492 ^^^^^^^^^^^^^^^^^^^
1493
1494 The use of pragma Restrictions allows you to control which features are
1495 permitted in your program. Apart from the obvious point that if you avoid
1496 relatively expensive features like finalization (enforceable by the use
1497 of pragma Restrictions (No_Finalization), the use of this pragma does not
1498 affect the generated code in most cases.
1499
1500 One notable exception to this rule is that the possibility of task abort
1501 results in some distributed overhead, particularly if finalization or
1502 exception handlers are used. The reason is that certain sections of code
1503 have to be marked as non-abortable.
1504
1505 If you use neither the ``abort`` statement, nor asynchronous transfer
1506 of control (``select ... then abort``), then this distributed overhead
1507 is removed, which may have a general positive effect in improving
1508 overall performance. Especially code involving frequent use of tasking
1509 constructs and controlled types will show much improved performance.
1510 The relevant restrictions pragmas are
1511
1512 .. code-block:: ada
1513
1514 pragma Restrictions (No_Abort_Statements);
1515 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
1516
1517 It is recommended that these restriction pragmas be used if possible. Note
1518 that this also means that you can write code without worrying about the
1519 possibility of an immediate abort at any point.
1520
1521
1522 .. _Optimization_Levels:
1523
1524 Optimization Levels
1525 ^^^^^^^^^^^^^^^^^^^
1526
1527 .. index:: -O (gcc)
1528
1529 Without any optimization option,
1530 the compiler's goal is to reduce the cost of
1531 compilation and to make debugging produce the expected results.
1532 Statements are independent: if you stop the program with a breakpoint between
1533 statements, you can then assign a new value to any variable or change
1534 the program counter to any other statement in the subprogram and get exactly
1535 the results you would expect from the source code.
1536
1537 Turning on optimization makes the compiler attempt to improve the
1538 performance and/or code size at the expense of compilation time and
1539 possibly the ability to debug the program.
1540
1541 If you use multiple
1542 -O options, with or without level numbers,
1543 the last such option is the one that is effective.
1544
1545 The default is optimization off. This results in the fastest compile
1546 times, but GNAT makes absolutely no attempt to optimize, and the
1547 generated programs are considerably larger and slower than when
1548 optimization is enabled. You can use the
1549 :switch:`-O` switch (the permitted forms are :switch:`-O0`, :switch:`-O1`
1550 :switch:`-O2`, :switch:`-O3`, and :switch:`-Os`)
1551 to ``gcc`` to control the optimization level:
1552
1553
1554 * :switch:`-O0`
1555 No optimization (the default);
1556 generates unoptimized code but has
1557 the fastest compilation time.
1558
1559 Note that many other compilers do substantial optimization even
1560 if 'no optimization' is specified. With gcc, it is very unusual
1561 to use :switch:`-O0` for production if execution time is of any concern,
1562 since :switch:`-O0` means (almost) no optimization. This difference
1563 between gcc and other compilers should be kept in mind when
1564 doing performance comparisons.
1565
1566 * :switch:`-O1`
1567 Moderate optimization;
1568 optimizes reasonably well but does not
1569 degrade compilation time significantly.
1570
1571 * :switch:`-O2`
1572 Full optimization;
1573 generates highly optimized code and has
1574 the slowest compilation time.
1575
1576 * :switch:`-O3`
1577 Full optimization as in :switch:`-O2`;
1578 also uses more aggressive automatic inlining of subprograms within a unit
1579 (:ref:`Inlining_of_Subprograms`) and attempts to vectorize loops.
1580
1581
1582 * :switch:`-Os`
1583 Optimize space usage (code and data) of resulting program.
1584
1585 Higher optimization levels perform more global transformations on the
1586 program and apply more expensive analysis algorithms in order to generate
1587 faster and more compact code. The price in compilation time, and the
1588 resulting improvement in execution time,
1589 both depend on the particular application and the hardware environment.
1590 You should experiment to find the best level for your application.
1591
1592 Since the precise set of optimizations done at each level will vary from
1593 release to release (and sometime from target to target), it is best to think
1594 of the optimization settings in general terms.
1595 See the *Options That Control Optimization* section in
1596 :title:`Using the GNU Compiler Collection (GCC)`
1597 for details about
1598 the :switch:`-O` settings and a number of :switch:`-f` options that
1599 individually enable or disable specific optimizations.
1600
1601 Unlike some other compilation systems, ``gcc`` has
1602 been tested extensively at all optimization levels. There are some bugs
1603 which appear only with optimization turned on, but there have also been
1604 bugs which show up only in *unoptimized* code. Selecting a lower
1605 level of optimization does not improve the reliability of the code
1606 generator, which in practice is highly reliable at all optimization
1607 levels.
1608
1609 Note regarding the use of :switch:`-O3`: The use of this optimization level
1610 ought not to be automatically preferred over that of level :switch:`-O2`,
1611 since it often results in larger executables which may run more slowly.
1612 See further discussion of this point in :ref:`Inlining_of_Subprograms`.
1613
1614
1615 .. _Debugging_Optimized_Code:
1616
1617 Debugging Optimized Code
1618 ^^^^^^^^^^^^^^^^^^^^^^^^
1619
1620 .. index:: Debugging optimized code
1621 .. index:: Optimization and debugging
1622
1623 Although it is possible to do a reasonable amount of debugging at
1624 nonzero optimization levels,
1625 the higher the level the more likely that
1626 source-level constructs will have been eliminated by optimization.
1627 For example, if a loop is strength-reduced, the loop
1628 control variable may be completely eliminated and thus cannot be
1629 displayed in the debugger.
1630 This can only happen at :switch:`-O2` or :switch:`-O3`.
1631 Explicit temporary variables that you code might be eliminated at
1632 level :switch:`-O1` or higher.
1633
1634 .. index:: -g (gcc)
1635
1636 The use of the :switch:`-g` switch,
1637 which is needed for source-level debugging,
1638 affects the size of the program executable on disk,
1639 and indeed the debugging information can be quite large.
1640 However, it has no effect on the generated code (and thus does not
1641 degrade performance)
1642
1643 Since the compiler generates debugging tables for a compilation unit before
1644 it performs optimizations, the optimizing transformations may invalidate some
1645 of the debugging data. You therefore need to anticipate certain
1646 anomalous situations that may arise while debugging optimized code.
1647 These are the most common cases:
1648
1649 * *The 'hopping Program Counter':* Repeated ``step`` or ``next``
1650 commands show
1651 the PC bouncing back and forth in the code. This may result from any of
1652 the following optimizations:
1653
1654 - *Common subexpression elimination:* using a single instance of code for a
1655 quantity that the source computes several times. As a result you
1656 may not be able to stop on what looks like a statement.
1657
1658 - *Invariant code motion:* moving an expression that does not change within a
1659 loop, to the beginning of the loop.
1660
1661 - *Instruction scheduling:* moving instructions so as to
1662 overlap loads and stores (typically) with other code, or in
1663 general to move computations of values closer to their uses. Often
1664 this causes you to pass an assignment statement without the assignment
1665 happening and then later bounce back to the statement when the
1666 value is actually needed. Placing a breakpoint on a line of code
1667 and then stepping over it may, therefore, not always cause all the
1668 expected side-effects.
1669
1670 * *The 'big leap':* More commonly known as *cross-jumping*, in which
1671 two identical pieces of code are merged and the program counter suddenly
1672 jumps to a statement that is not supposed to be executed, simply because
1673 it (and the code following) translates to the same thing as the code
1674 that *was* supposed to be executed. This effect is typically seen in
1675 sequences that end in a jump, such as a ``goto``, a ``return``, or
1676 a ``break`` in a C ``switch`` statement.
1677
1678 * *The 'roving variable':* The symptom is an unexpected value in a variable.
1679 There are various reasons for this effect:
1680
1681 - In a subprogram prologue, a parameter may not yet have been moved to its
1682 'home'.
1683
1684 - A variable may be dead, and its register re-used. This is
1685 probably the most common cause.
1686
1687 - As mentioned above, the assignment of a value to a variable may
1688 have been moved.
1689
1690 - A variable may be eliminated entirely by value propagation or
1691 other means. In this case, GCC may incorrectly generate debugging
1692 information for the variable
1693
1694 In general, when an unexpected value appears for a local variable or parameter
1695 you should first ascertain if that value was actually computed by
1696 your program, as opposed to being incorrectly reported by the debugger.
1697 Record fields or
1698 array elements in an object designated by an access value
1699 are generally less of a problem, once you have ascertained that the access
1700 value is sensible.
1701 Typically, this means checking variables in the preceding code and in the
1702 calling subprogram to verify that the value observed is explainable from other
1703 values (one must apply the procedure recursively to those
1704 other values); or re-running the code and stopping a little earlier
1705 (perhaps before the call) and stepping to better see how the variable obtained
1706 the value in question; or continuing to step *from* the point of the
1707 strange value to see if code motion had simply moved the variable's
1708 assignments later.
1709
1710 In light of such anomalies, a recommended technique is to use :switch:`-O0`
1711 early in the software development cycle, when extensive debugging capabilities
1712 are most needed, and then move to :switch:`-O1` and later :switch:`-O2` as
1713 the debugger becomes less critical.
1714 Whether to use the :switch:`-g` switch in the release version is
1715 a release management issue.
1716 Note that if you use :switch:`-g` you can then use the ``strip`` program
1717 on the resulting executable,
1718 which removes both debugging information and global symbols.
1719
1720
1721 .. _Inlining_of_Subprograms:
1722
1723 Inlining of Subprograms
1724 ^^^^^^^^^^^^^^^^^^^^^^^
1725
1726 A call to a subprogram in the current unit is inlined if all the
1727 following conditions are met:
1728
1729 * The optimization level is at least :switch:`-O1`.
1730
1731 * The called subprogram is suitable for inlining: It must be small enough
1732 and not contain something that ``gcc`` cannot support in inlined
1733 subprograms.
1734
1735 .. index:: pragma Inline
1736 .. index:: Inline
1737
1738 * Any one of the following applies: ``pragma Inline`` is applied to the
1739 subprogram; the subprogram is local to the unit and called once from
1740 within it; the subprogram is small and optimization level :switch:`-O2` is
1741 specified; optimization level :switch:`-O3` is specified.
1742
1743 Calls to subprograms in |withed| units are normally not inlined.
1744 To achieve actual inlining (that is, replacement of the call by the code
1745 in the body of the subprogram), the following conditions must all be true:
1746
1747 * The optimization level is at least :switch:`-O1`.
1748
1749 * The called subprogram is suitable for inlining: It must be small enough
1750 and not contain something that ``gcc`` cannot support in inlined
1751 subprograms.
1752
1753 * There is a ``pragma Inline`` for the subprogram.
1754
1755 * The :switch:`-gnatn` switch is used on the command line.
1756
1757 Even if all these conditions are met, it may not be possible for
1758 the compiler to inline the call, due to the length of the body,
1759 or features in the body that make it impossible for the compiler
1760 to do the inlining.
1761
1762 Note that specifying the :switch:`-gnatn` switch causes additional
1763 compilation dependencies. Consider the following:
1764
1765 .. code-block:: ada
1766
1767 package R is
1768 procedure Q;
1769 pragma Inline (Q);
1770 end R;
1771 package body R is
1772 ...
1773 end R;
1774
1775 with R;
1776 procedure Main is
1777 begin
1778 ...
1779 R.Q;
1780 end Main;
1781
1782 With the default behavior (no :switch:`-gnatn` switch specified), the
1783 compilation of the ``Main`` procedure depends only on its own source,
1784 :file:`main.adb`, and the spec of the package in file :file:`r.ads`. This
1785 means that editing the body of ``R`` does not require recompiling
1786 ``Main``.
1787
1788 On the other hand, the call ``R.Q`` is not inlined under these
1789 circumstances. If the :switch:`-gnatn` switch is present when ``Main``
1790 is compiled, the call will be inlined if the body of ``Q`` is small
1791 enough, but now ``Main`` depends on the body of ``R`` in
1792 :file:`r.adb` as well as on the spec. This means that if this body is edited,
1793 the main program must be recompiled. Note that this extra dependency
1794 occurs whether or not the call is in fact inlined by ``gcc``.
1795
1796 The use of front end inlining with :switch:`-gnatN` generates similar
1797 additional dependencies.
1798
1799 .. index:: -fno-inline (gcc)
1800
1801 Note: The :switch:`-fno-inline` switch overrides all other conditions and ensures that
1802 no inlining occurs, unless requested with pragma Inline_Always for ``gcc``
1803 back-ends. The extra dependences resulting from :switch:`-gnatn` will still be active,
1804 even if this switch is used to suppress the resulting inlining actions.
1805
1806 .. index:: -fno-inline-functions (gcc)
1807
1808 Note: The :switch:`-fno-inline-functions` switch can be used to prevent
1809 automatic inlining of subprograms if :switch:`-O3` is used.
1810
1811 .. index:: -fno-inline-small-functions (gcc)
1812
1813 Note: The :switch:`-fno-inline-small-functions` switch can be used to prevent
1814 automatic inlining of small subprograms if :switch:`-O2` is used.
1815
1816 .. index:: -fno-inline-functions-called-once (gcc)
1817
1818 Note: The :switch:`-fno-inline-functions-called-once` switch
1819 can be used to prevent inlining of subprograms local to the unit
1820 and called once from within it if :switch:`-O1` is used.
1821
1822 Note regarding the use of :switch:`-O3`: :switch:`-gnatn` is made up of two
1823 sub-switches :switch:`-gnatn1` and :switch:`-gnatn2` that can be directly
1824 specified in lieu of it, :switch:`-gnatn` being translated into one of them
1825 based on the optimization level. With :switch:`-O2` or below, :switch:`-gnatn`
1826 is equivalent to :switch:`-gnatn1` which activates pragma ``Inline`` with
1827 moderate inlining across modules. With :switch:`-O3`, :switch:`-gnatn` is
1828 equivalent to :switch:`-gnatn2` which activates pragma ``Inline`` with
1829 full inlining across modules. If you have used pragma ``Inline`` in
1830 appropriate cases, then it is usually much better to use :switch:`-O2`
1831 and :switch:`-gnatn` and avoid the use of :switch:`-O3` which has the additional
1832 effect of inlining subprograms you did not think should be inlined. We have
1833 found that the use of :switch:`-O3` may slow down the compilation and increase
1834 the code size by performing excessive inlining, leading to increased
1835 instruction cache pressure from the increased code size and thus minor
1836 performance improvements. So the bottom line here is that you should not
1837 automatically assume that :switch:`-O3` is better than :switch:`-O2`, and
1838 indeed you should use :switch:`-O3` only if tests show that it actually
1839 improves performance for your program.
1840
1841 .. _Floating_Point_Operations:
1842
1843 Floating Point Operations
1844 ^^^^^^^^^^^^^^^^^^^^^^^^^
1845
1846 .. index:: Floating-Point Operations
1847
1848 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
1849 64-bit standard IEEE floating-point representations, and operations will
1850 use standard IEEE arithmetic as provided by the processor. On most, but
1851 not all, architectures, the attribute Machine_Overflows is False for these
1852 types, meaning that the semantics of overflow is implementation-defined.
1853 In the case of GNAT, these semantics correspond to the normal IEEE
1854 treatment of infinities and NaN (not a number) values. For example,
1855 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
1856 avoiding explicit overflow checks, the performance is greatly improved
1857 on many targets. However, if required, floating-point overflow can be
1858 enabled by the use of the pragma Check_Float_Overflow.
1859
1860 Another consideration that applies specifically to x86 32-bit
1861 architectures is which form of floating-point arithmetic is used.
1862 By default the operations use the old style x86 floating-point,
1863 which implements an 80-bit extended precision form (on these
1864 architectures the type Long_Long_Float corresponds to that form).
1865 In addition, generation of efficient code in this mode means that
1866 the extended precision form will be used for intermediate results.
1867 This may be helpful in improving the final precision of a complex
1868 expression. However it means that the results obtained on the x86
1869 will be different from those on other architectures, and for some
1870 algorithms, the extra intermediate precision can be detrimental.
1871
1872 In addition to this old-style floating-point, all modern x86 chips
1873 implement an alternative floating-point operation model referred
1874 to as SSE2. In this model there is no extended form, and furthermore
1875 execution performance is significantly enhanced. To force GNAT to use
1876 this more modern form, use both of the switches:
1877
1878 -msse2 -mfpmath=sse
1879
1880 A unit compiled with these switches will automatically use the more
1881 efficient SSE2 instruction set for Float and Long_Float operations.
1882 Note that the ABI has the same form for both floating-point models,
1883 so it is permissible to mix units compiled with and without these
1884 switches.
1885
1886
1887
1888
1889
1890 .. _Vectorization_of_loops:
1891
1892 Vectorization of loops
1893 ^^^^^^^^^^^^^^^^^^^^^^
1894
1895 .. index:: Optimization Switches
1896
1897 You can take advantage of the auto-vectorizer present in the ``gcc``
1898 back end to vectorize loops with GNAT. The corresponding command line switch
1899 is :switch:`-ftree-vectorize` but, as it is enabled by default at :switch:`-O3`
1900 and other aggressive optimizations helpful for vectorization also are enabled
1901 by default at this level, using :switch:`-O3` directly is recommended.
1902
1903 You also need to make sure that the target architecture features a supported
1904 SIMD instruction set. For example, for the x86 architecture, you should at
1905 least specify :switch:`-msse2` to get significant vectorization (but you don't
1906 need to specify it for x86-64 as it is part of the base 64-bit architecture).
1907 Similarly, for the PowerPC architecture, you should specify :switch:`-maltivec`.
1908
1909 The preferred loop form for vectorization is the ``for`` iteration scheme.
1910 Loops with a ``while`` iteration scheme can also be vectorized if they are
1911 very simple, but the vectorizer will quickly give up otherwise. With either
1912 iteration scheme, the flow of control must be straight, in particular no
1913 ``exit`` statement may appear in the loop body. The loop may however
1914 contain a single nested loop, if it can be vectorized when considered alone:
1915
1916 .. code-block:: ada
1917
1918 A : array (1..4, 1..4) of Long_Float;
1919 S : array (1..4) of Long_Float;
1920
1921 procedure Sum is
1922 begin
1923 for I in A'Range(1) loop
1924 for J in A'Range(2) loop
1925 S (I) := S (I) + A (I, J);
1926 end loop;
1927 end loop;
1928 end Sum;
1929
1930 The vectorizable operations depend on the targeted SIMD instruction set, but
1931 the adding and some of the multiplying operators are generally supported, as
1932 well as the logical operators for modular types. Note that compiling
1933 with :switch:`-gnatp` might well reveal cases where some checks do thwart
1934 vectorization.
1935
1936 Type conversions may also prevent vectorization if they involve semantics that
1937 are not directly supported by the code generator or the SIMD instruction set.
1938 A typical example is direct conversion from floating-point to integer types.
1939 The solution in this case is to use the following idiom:
1940
1941 .. code-block:: ada
1942
1943 Integer (S'Truncation (F))
1944
1945 if ``S`` is the subtype of floating-point object ``F``.
1946
1947 In most cases, the vectorizable loops are loops that iterate over arrays.
1948 All kinds of array types are supported, i.e. constrained array types with
1949 static bounds:
1950
1951 .. code-block:: ada
1952
1953 type Array_Type is array (1 .. 4) of Long_Float;
1954
1955 constrained array types with dynamic bounds:
1956
1957
1958 .. code-block:: ada
1959
1960 type Array_Type is array (1 .. Q.N) of Long_Float;
1961
1962 type Array_Type is array (Q.K .. 4) of Long_Float;
1963
1964 type Array_Type is array (Q.K .. Q.N) of Long_Float;
1965
1966 or unconstrained array types:
1967
1968 .. code-block:: ada
1969
1970 type Array_Type is array (Positive range <>) of Long_Float;
1971
1972 The quality of the generated code decreases when the dynamic aspect of the
1973 array type increases, the worst code being generated for unconstrained array
1974 types. This is so because, the less information the compiler has about the
1975 bounds of the array, the more fallback code it needs to generate in order to
1976 fix things up at run time.
1977
1978 It is possible to specify that a given loop should be subject to vectorization
1979 preferably to other optimizations by means of pragma ``Loop_Optimize``:
1980
1981 .. code-block:: ada
1982
1983 pragma Loop_Optimize (Vector);
1984
1985 placed immediately within the loop will convey the appropriate hint to the
1986 compiler for this loop.
1987
1988 It is also possible to help the compiler generate better vectorized code
1989 for a given loop by asserting that there are no loop-carried dependencies
1990 in the loop. Consider for example the procedure:
1991
1992 .. code-block:: ada
1993
1994 type Arr is array (1 .. 4) of Long_Float;
1995
1996 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
1997 begin
1998 for I in Arr'Range loop
1999 R(I) := X(I) + Y(I);
2000 end loop;
2001 end;
2002
2003 By default, the compiler cannot unconditionally vectorize the loop because
2004 assigning to a component of the array designated by R in one iteration could
2005 change the value read from the components of the array designated by X or Y
2006 in a later iteration. As a result, the compiler will generate two versions
2007 of the loop in the object code, one vectorized and the other not vectorized,
2008 as well as a test to select the appropriate version at run time. This can
2009 be overcome by another hint:
2010
2011 .. code-block:: ada
2012
2013 pragma Loop_Optimize (Ivdep);
2014
2015 placed immediately within the loop will tell the compiler that it can safely
2016 omit the non-vectorized version of the loop as well as the run-time test.
2017
2018
2019 .. _Other_Optimization_Switches:
2020
2021 Other Optimization Switches
2022 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
2023
2024 .. index:: Optimization Switches
2025
2026 Since GNAT uses the ``gcc`` back end, all the specialized
2027 ``gcc`` optimization switches are potentially usable. These switches
2028 have not been extensively tested with GNAT but can generally be expected
2029 to work. Examples of switches in this category are :switch:`-funroll-loops`
2030 and the various target-specific :switch:`-m` options (in particular, it has
2031 been observed that :switch:`-march=xxx` can significantly improve performance
2032 on appropriate machines). For full details of these switches, see
2033 the *Submodel Options* section in the *Hardware Models and Configurations*
2034 chapter of :title:`Using the GNU Compiler Collection (GCC)`.
2035
2036
2037 .. _Optimization_and_Strict_Aliasing:
2038
2039 Optimization and Strict Aliasing
2040 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2041
2042 .. index:: Aliasing
2043 .. index:: Strict Aliasing
2044 .. index:: No_Strict_Aliasing
2045
2046 The strong typing capabilities of Ada allow an optimizer to generate
2047 efficient code in situations where other languages would be forced to
2048 make worst case assumptions preventing such optimizations. Consider
2049 the following example:
2050
2051 .. code-block:: ada
2052
2053 procedure R is
2054 type Int1 is new Integer;
2055 type Int2 is new Integer;
2056 type Int1A is access Int1;
2057 type Int2A is access Int2;
2058 Int1V : Int1A;
2059 Int2V : Int2A;
2060 ...
2061
2062 begin
2063 ...
2064 for J in Data'Range loop
2065 if Data (J) = Int1V.all then
2066 Int2V.all := Int2V.all + 1;
2067 end if;
2068 end loop;
2069 ...
2070 end R;
2071
2072 In this example, since the variable ``Int1V`` can only access objects
2073 of type ``Int1``, and ``Int2V`` can only access objects of type
2074 ``Int2``, there is no possibility that the assignment to
2075 ``Int2V.all`` affects the value of ``Int1V.all``. This means that
2076 the compiler optimizer can "know" that the value ``Int1V.all`` is constant
2077 for all iterations of the loop and avoid the extra memory reference
2078 required to dereference it each time through the loop.
2079
2080 This kind of optimization, called strict aliasing analysis, is
2081 triggered by specifying an optimization level of :switch:`-O2` or
2082 higher or :switch:`-Os` and allows GNAT to generate more efficient code
2083 when access values are involved.
2084
2085 However, although this optimization is always correct in terms of
2086 the formal semantics of the Ada Reference Manual, difficulties can
2087 arise if features like ``Unchecked_Conversion`` are used to break
2088 the typing system. Consider the following complete program example:
2089
2090 .. code-block:: ada
2091
2092 package p1 is
2093 type int1 is new integer;
2094 type int2 is new integer;
2095 type a1 is access int1;
2096 type a2 is access int2;
2097 end p1;
2098
2099 with p1; use p1;
2100 package p2 is
2101 function to_a2 (Input : a1) return a2;
2102 end p2;
2103
2104 with Unchecked_Conversion;
2105 package body p2 is
2106 function to_a2 (Input : a1) return a2 is
2107 function to_a2u is
2108 new Unchecked_Conversion (a1, a2);
2109 begin
2110 return to_a2u (Input);
2111 end to_a2;
2112 end p2;
2113
2114 with p2; use p2;
2115 with p1; use p1;
2116 with Text_IO; use Text_IO;
2117 procedure m is
2118 v1 : a1 := new int1;
2119 v2 : a2 := to_a2 (v1);
2120 begin
2121 v1.all := 1;
2122 v2.all := 0;
2123 put_line (int1'image (v1.all));
2124 end;
2125
2126 This program prints out 0 in :switch:`-O0` or :switch:`-O1`
2127 mode, but it prints out 1 in :switch:`-O2` mode. That's
2128 because in strict aliasing mode, the compiler can and
2129 does assume that the assignment to ``v2.all`` could not
2130 affect the value of ``v1.all``, since different types
2131 are involved.
2132
2133 This behavior is not a case of non-conformance with the standard, since
2134 the Ada RM specifies that an unchecked conversion where the resulting
2135 bit pattern is not a correct value of the target type can result in an
2136 abnormal value and attempting to reference an abnormal value makes the
2137 execution of a program erroneous. That's the case here since the result
2138 does not point to an object of type ``int2``. This means that the
2139 effect is entirely unpredictable.
2140
2141 However, although that explanation may satisfy a language
2142 lawyer, in practice an applications programmer expects an
2143 unchecked conversion involving pointers to create true
2144 aliases and the behavior of printing 1 seems plain wrong.
2145 In this case, the strict aliasing optimization is unwelcome.
2146
2147 Indeed the compiler recognizes this possibility, and the
2148 unchecked conversion generates a warning:
2149
2150 ::
2151
2152 p2.adb:5:07: warning: possible aliasing problem with type "a2"
2153 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
2154 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
2155
2156 Unfortunately the problem is recognized when compiling the body of
2157 package ``p2``, but the actual "bad" code is generated while
2158 compiling the body of ``m`` and this latter compilation does not see
2159 the suspicious ``Unchecked_Conversion``.
2160
2161 As implied by the warning message, there are approaches you can use to
2162 avoid the unwanted strict aliasing optimization in a case like this.
2163
2164 One possibility is to simply avoid the use of :switch:`-O2`, but
2165 that is a bit drastic, since it throws away a number of useful
2166 optimizations that do not involve strict aliasing assumptions.
2167
2168 A less drastic approach is to compile the program using the
2169 option :switch:`-fno-strict-aliasing`. Actually it is only the
2170 unit containing the dereferencing of the suspicious pointer
2171 that needs to be compiled. So in this case, if we compile
2172 unit ``m`` with this switch, then we get the expected
2173 value of zero printed. Analyzing which units might need
2174 the switch can be painful, so a more reasonable approach
2175 is to compile the entire program with options :switch:`-O2`
2176 and :switch:`-fno-strict-aliasing`. If the performance is
2177 satisfactory with this combination of options, then the
2178 advantage is that the entire issue of possible "wrong"
2179 optimization due to strict aliasing is avoided.
2180
2181 To avoid the use of compiler switches, the configuration
2182 pragma ``No_Strict_Aliasing`` with no parameters may be
2183 used to specify that for all access types, the strict
2184 aliasing optimization should be suppressed.
2185
2186 However, these approaches are still overkill, in that they causes
2187 all manipulations of all access values to be deoptimized. A more
2188 refined approach is to concentrate attention on the specific
2189 access type identified as problematic.
2190
2191 First, if a careful analysis of uses of the pointer shows
2192 that there are no possible problematic references, then
2193 the warning can be suppressed by bracketing the
2194 instantiation of ``Unchecked_Conversion`` to turn
2195 the warning off:
2196
2197 .. code-block:: ada
2198
2199 pragma Warnings (Off);
2200 function to_a2u is
2201 new Unchecked_Conversion (a1, a2);
2202 pragma Warnings (On);
2203
2204 Of course that approach is not appropriate for this particular
2205 example, since indeed there is a problematic reference. In this
2206 case we can take one of two other approaches.
2207
2208 The first possibility is to move the instantiation of unchecked
2209 conversion to the unit in which the type is declared. In
2210 this example, we would move the instantiation of
2211 ``Unchecked_Conversion`` from the body of package
2212 ``p2`` to the spec of package ``p1``. Now the
2213 warning disappears. That's because any use of the
2214 access type knows there is a suspicious unchecked
2215 conversion, and the strict aliasing optimization
2216 is automatically suppressed for the type.
2217
2218 If it is not practical to move the unchecked conversion to the same unit
2219 in which the destination access type is declared (perhaps because the
2220 source type is not visible in that unit), you may use pragma
2221 ``No_Strict_Aliasing`` for the type. This pragma must occur in the
2222 same declarative sequence as the declaration of the access type:
2223
2224 .. code-block:: ada
2225
2226 type a2 is access int2;
2227 pragma No_Strict_Aliasing (a2);
2228
2229 Here again, the compiler now knows that the strict aliasing optimization
2230 should be suppressed for any reference to type ``a2`` and the
2231 expected behavior is obtained.
2232
2233 Finally, note that although the compiler can generate warnings for
2234 simple cases of unchecked conversions, there are tricker and more
2235 indirect ways of creating type incorrect aliases which the compiler
2236 cannot detect. Examples are the use of address overlays and unchecked
2237 conversions involving composite types containing access types as
2238 components. In such cases, no warnings are generated, but there can
2239 still be aliasing problems. One safe coding practice is to forbid the
2240 use of address clauses for type overlaying, and to allow unchecked
2241 conversion only for primitive types. This is not really a significant
2242 restriction since any possible desired effect can be achieved by
2243 unchecked conversion of access values.
2244
2245 The aliasing analysis done in strict aliasing mode can certainly
2246 have significant benefits. We have seen cases of large scale
2247 application code where the time is increased by up to 5% by turning
2248 this optimization off. If you have code that includes significant
2249 usage of unchecked conversion, you might want to just stick with
2250 :switch:`-O1` and avoid the entire issue. If you get adequate
2251 performance at this level of optimization level, that's probably
2252 the safest approach. If tests show that you really need higher
2253 levels of optimization, then you can experiment with :switch:`-O2`
2254 and :switch:`-O2 -fno-strict-aliasing` to see how much effect this
2255 has on size and speed of the code. If you really need to use
2256 :switch:`-O2` with strict aliasing in effect, then you should
2257 review any uses of unchecked conversion of access types,
2258 particularly if you are getting the warnings described above.
2259
2260
2261 .. _Aliased_Variables_and_Optimization:
2262
2263 Aliased Variables and Optimization
2264 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2265
2266 .. index:: Aliasing
2267
2268 There are scenarios in which programs may
2269 use low level techniques to modify variables
2270 that otherwise might be considered to be unassigned. For example,
2271 a variable can be passed to a procedure by reference, which takes
2272 the address of the parameter and uses the address to modify the
2273 variable's value, even though it is passed as an IN parameter.
2274 Consider the following example:
2275
2276 .. code-block:: ada
2277
2278 procedure P is
2279 Max_Length : constant Natural := 16;
2280 type Char_Ptr is access all Character;
2281
2282 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
2283 pragma Import (C, Get_String, "get_string");
2284
2285 Name : aliased String (1 .. Max_Length) := (others => ' ');
2286 Temp : Char_Ptr;
2287
2288 function Addr (S : String) return Char_Ptr is
2289 function To_Char_Ptr is
2290 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
2291 begin
2292 return To_Char_Ptr (S (S'First)'Address);
2293 end;
2294
2295 begin
2296 Temp := Addr (Name);
2297 Get_String (Temp, Max_Length);
2298 end;
2299
2300 where Get_String is a C function that uses the address in Temp to
2301 modify the variable ``Name``. This code is dubious, and arguably
2302 erroneous, and the compiler would be entitled to assume that
2303 ``Name`` is never modified, and generate code accordingly.
2304
2305 However, in practice, this would cause some existing code that
2306 seems to work with no optimization to start failing at high
2307 levels of optimzization.
2308
2309 What the compiler does for such cases is to assume that marking
2310 a variable as aliased indicates that some "funny business" may
2311 be going on. The optimizer recognizes the aliased keyword and
2312 inhibits optimizations that assume the value cannot be assigned.
2313 This means that the above example will in fact "work" reliably,
2314 that is, it will produce the expected results.
2315
2316
2317 .. _Atomic_Variables_and_Optimization:
2318
2319 Atomic Variables and Optimization
2320 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2321
2322 .. index:: Atomic
2323
2324 There are two considerations with regard to performance when
2325 atomic variables are used.
2326
2327 First, the RM only guarantees that access to atomic variables
2328 be atomic, it has nothing to say about how this is achieved,
2329 though there is a strong implication that this should not be
2330 achieved by explicit locking code. Indeed GNAT will never
2331 generate any locking code for atomic variable access (it will
2332 simply reject any attempt to make a variable or type atomic
2333 if the atomic access cannot be achieved without such locking code).
2334
2335 That being said, it is important to understand that you cannot
2336 assume that the entire variable will always be accessed. Consider
2337 this example:
2338
2339 .. code-block:: ada
2340
2341 type R is record
2342 A,B,C,D : Character;
2343 end record;
2344 for R'Size use 32;
2345 for R'Alignment use 4;
2346
2347 RV : R;
2348 pragma Atomic (RV);
2349 X : Character;
2350 ...
2351 X := RV.B;
2352
2353 You cannot assume that the reference to ``RV.B``
2354 will read the entire 32-bit
2355 variable with a single load instruction. It is perfectly legitimate if
2356 the hardware allows it to do a byte read of just the B field. This read
2357 is still atomic, which is all the RM requires. GNAT can and does take
2358 advantage of this, depending on the architecture and optimization level.
2359 Any assumption to the contrary is non-portable and risky. Even if you
2360 examine the assembly language and see a full 32-bit load, this might
2361 change in a future version of the compiler.
2362
2363 If your application requires that all accesses to ``RV`` in this
2364 example be full 32-bit loads, you need to make a copy for the access
2365 as in:
2366
2367 .. code-block:: ada
2368
2369 declare
2370 RV_Copy : constant R := RV;
2371 begin
2372 X := RV_Copy.B;
2373 end;
2374
2375 Now the reference to RV must read the whole variable.
2376 Actually one can imagine some compiler which figures
2377 out that the whole copy is not required (because only
2378 the B field is actually accessed), but GNAT
2379 certainly won't do that, and we don't know of any
2380 compiler that would not handle this right, and the
2381 above code will in practice work portably across
2382 all architectures (that permit the Atomic declaration).
2383
2384 The second issue with atomic variables has to do with
2385 the possible requirement of generating synchronization
2386 code. For more details on this, consult the sections on
2387 the pragmas Enable/Disable_Atomic_Synchronization in the
2388 GNAT Reference Manual. If performance is critical, and
2389 such synchronization code is not required, it may be
2390 useful to disable it.
2391
2392
2393 .. _Passive_Task_Optimization:
2394
2395 Passive Task Optimization
2396 ^^^^^^^^^^^^^^^^^^^^^^^^^
2397
2398 .. index:: Passive Task
2399
2400 A passive task is one which is sufficiently simple that
2401 in theory a compiler could recognize it an implement it
2402 efficiently without creating a new thread. The original design
2403 of Ada 83 had in mind this kind of passive task optimization, but
2404 only a few Ada 83 compilers attempted it. The problem was that
2405 it was difficult to determine the exact conditions under which
2406 the optimization was possible. The result is a very fragile
2407 optimization where a very minor change in the program can
2408 suddenly silently make a task non-optimizable.
2409
2410 With the revisiting of this issue in Ada 95, there was general
2411 agreement that this approach was fundamentally flawed, and the
2412 notion of protected types was introduced. When using protected
2413 types, the restrictions are well defined, and you KNOW that the
2414 operations will be optimized, and furthermore this optimized
2415 performance is fully portable.
2416
2417 Although it would theoretically be possible for GNAT to attempt to
2418 do this optimization, but it really doesn't make sense in the
2419 context of Ada 95, and none of the Ada 95 compilers implement
2420 this optimization as far as we know. In particular GNAT never
2421 attempts to perform this optimization.
2422
2423 In any new Ada 95 code that is written, you should always
2424 use protected types in place of tasks that might be able to
2425 be optimized in this manner.
2426 Of course this does not help if you have legacy Ada 83 code
2427 that depends on this optimization, but it is unusual to encounter
2428 a case where the performance gains from this optimization
2429 are significant.
2430
2431 Your program should work correctly without this optimization. If
2432 you have performance problems, then the most practical
2433 approach is to figure out exactly where these performance problems
2434 arise, and update those particular tasks to be protected types. Note
2435 that typically clients of the tasks who call entries, will not have
2436 to be modified, only the task definition itself.
2437
2438
2439 .. _Text_IO_Suggestions:
2440
2441 ``Text_IO`` Suggestions
2442 -----------------------
2443
2444 .. index:: Text_IO and performance
2445
2446 The ``Ada.Text_IO`` package has fairly high overheads due in part to
2447 the requirement of maintaining page and line counts. If performance
2448 is critical, a recommendation is to use ``Stream_IO`` instead of
2449 ``Text_IO`` for volume output, since this package has less overhead.
2450
2451 If ``Text_IO`` must be used, note that by default output to the standard
2452 output and standard error files is unbuffered (this provides better
2453 behavior when output statements are used for debugging, or if the
2454 progress of a program is observed by tracking the output, e.g. by
2455 using the Unix *tail -f* command to watch redirected output.
2456
2457 If you are generating large volumes of output with ``Text_IO`` and
2458 performance is an important factor, use a designated file instead
2459 of the standard output file, or change the standard output file to
2460 be buffered using ``Interfaces.C_Streams.setvbuf``.
2461
2462
2463 .. _Reducing_Size_of_Executables_with_Unused_Subprogram/Data_Elimination:
2464
2465 Reducing Size of Executables with Unused Subprogram/Data Elimination
2466 --------------------------------------------------------------------
2467
2468 .. index:: Uunused subprogram/data elimination
2469
2470 This section describes how you can eliminate unused subprograms and data from
2471 your executable just by setting options at compilation time.
2472
2473 .. _About_unused_subprogram/data_elimination:
2474
2475 About unused subprogram/data elimination
2476 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2477
2478 By default, an executable contains all code and data of its composing objects
2479 (directly linked or coming from statically linked libraries), even data or code
2480 never used by this executable.
2481
2482 This feature will allow you to eliminate such unused code from your
2483 executable, making it smaller (in disk and in memory).
2484
2485 This functionality is available on all Linux platforms except for the IA-64
2486 architecture and on all cross platforms using the ELF binary file format.
2487 In both cases GNU binutils version 2.16 or later are required to enable it.
2488
2489 .. _Compilation_options:
2490
2491 Compilation options
2492 ^^^^^^^^^^^^^^^^^^^
2493
2494 The operation of eliminating the unused code and data from the final executable
2495 is directly performed by the linker.
2496
2497 .. index:: -ffunction-sections (gcc)
2498 .. index:: -fdata-sections (gcc)
2499
2500 In order to do this, it has to work with objects compiled with the
2501 following options:
2502 :switch:`-ffunction-sections` :switch:`-fdata-sections`.
2503
2504 These options are usable with C and Ada files.
2505 They will place respectively each
2506 function or data in a separate section in the resulting object file.
2507
2508 Once the objects and static libraries are created with these options, the
2509 linker can perform the dead code elimination. You can do this by setting
2510 the :switch:`-Wl,--gc-sections` option to gcc command or in the
2511 :switch:`-largs` section of ``gnatmake``. This will perform a
2512 garbage collection of code and data never referenced.
2513
2514 If the linker performs a partial link (:switch:`-r` linker option), then you
2515 will need to provide the entry point using the :switch:`-e` / :switch:`--entry`
2516 linker option.
2517
2518 Note that objects compiled without the :switch:`-ffunction-sections` and
2519 :switch:`-fdata-sections` options can still be linked with the executable.
2520 However, no dead code elimination will be performed on those objects (they will
2521 be linked as is).
2522
2523 The GNAT static library is now compiled with -ffunction-sections and
2524 -fdata-sections on some platforms. This allows you to eliminate the unused code
2525 and data of the GNAT library from your executable.
2526
2527
2528 .. _Example_of_unused_subprogram/data_elimination:
2529
2530 Example of unused subprogram/data elimination
2531 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2532
2533 Here is a simple example:
2534
2535 .. code-block:: ada
2536
2537 with Aux;
2538
2539 procedure Test is
2540 begin
2541 Aux.Used (10);
2542 end Test;
2543
2544 package Aux is
2545 Used_Data : Integer;
2546 Unused_Data : Integer;
2547
2548 procedure Used (Data : Integer);
2549 procedure Unused (Data : Integer);
2550 end Aux;
2551
2552 package body Aux is
2553 procedure Used (Data : Integer) is
2554 begin
2555 Used_Data := Data;
2556 end Used;
2557
2558 procedure Unused (Data : Integer) is
2559 begin
2560 Unused_Data := Data;
2561 end Unused;
2562 end Aux;
2563
2564 ``Unused`` and ``Unused_Data`` are never referenced in this code
2565 excerpt, and hence they may be safely removed from the final executable.
2566
2567 ::
2568
2569 $ gnatmake test
2570
2571 $ nm test | grep used
2572 020015f0 T aux__unused
2573 02005d88 B aux__unused_data
2574 020015cc T aux__used
2575 02005d84 B aux__used_data
2576
2577 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
2578 -largs -Wl,--gc-sections
2579
2580 $ nm test | grep used
2581 02005350 T aux__used
2582 0201ffe0 B aux__used_data
2583
2584 It can be observed that the procedure ``Unused`` and the object
2585 ``Unused_Data`` are removed by the linker when using the
2586 appropriate options.
2587
2588
2589 .. index:: Overflow checks
2590 .. index:: Checks (overflow)
2591
2592 .. _Overflow_Check_Handling_in_GNAT:
2593
2594 Overflow Check Handling in GNAT
2595 ===============================
2596
2597 This section explains how to control the handling of overflow checks.
2598
2599 .. _Background:
2600
2601 Background
2602 ----------
2603
2604 Overflow checks are checks that the compiler may make to ensure
2605 that intermediate results are not out of range. For example:
2606
2607 .. code-block:: ada
2608
2609 A : Integer;
2610 ...
2611 A := A + 1;
2612
2613 If ``A`` has the value ``Integer'Last``, then the addition may cause
2614 overflow since the result is out of range of the type ``Integer``.
2615 In this case ``Constraint_Error`` will be raised if checks are
2616 enabled.
2617
2618 A trickier situation arises in examples like the following:
2619
2620 .. code-block:: ada
2621
2622 A, C : Integer;
2623 ...
2624 A := (A + 1) + C;
2625
2626 where ``A`` is ``Integer'Last`` and ``C`` is ``-1``.
2627 Now the final result of the expression on the right hand side is
2628 ``Integer'Last`` which is in range, but the question arises whether the
2629 intermediate addition of ``(A + 1)`` raises an overflow error.
2630
2631 The (perhaps surprising) answer is that the Ada language
2632 definition does not answer this question. Instead it leaves
2633 it up to the implementation to do one of two things if overflow
2634 checks are enabled.
2635
2636 * raise an exception (``Constraint_Error``), or
2637
2638 * yield the correct mathematical result which is then used in
2639 subsequent operations.
2640
2641 If the compiler chooses the first approach, then the assignment of this
2642 example will indeed raise ``Constraint_Error`` if overflow checking is
2643 enabled, or result in erroneous execution if overflow checks are suppressed.
2644
2645 But if the compiler
2646 chooses the second approach, then it can perform both additions yielding
2647 the correct mathematical result, which is in range, so no exception
2648 will be raised, and the right result is obtained, regardless of whether
2649 overflow checks are suppressed.
2650
2651 Note that in the first example an
2652 exception will be raised in either case, since if the compiler
2653 gives the correct mathematical result for the addition, it will
2654 be out of range of the target type of the assignment, and thus
2655 fails the range check.
2656
2657 This lack of specified behavior in the handling of overflow for
2658 intermediate results is a source of non-portability, and can thus
2659 be problematic when programs are ported. Most typically this arises
2660 in a situation where the original compiler did not raise an exception,
2661 and then the application is moved to a compiler where the check is
2662 performed on the intermediate result and an unexpected exception is
2663 raised.
2664
2665 Furthermore, when using Ada 2012's preconditions and other
2666 assertion forms, another issue arises. Consider:
2667
2668 .. code-block:: ada
2669
2670 procedure P (A, B : Integer) with
2671 Pre => A + B <= Integer'Last;
2672
2673 One often wants to regard arithmetic in a context like this from
2674 a mathematical point of view. So for example, if the two actual parameters
2675 for a call to ``P`` are both ``Integer'Last``, then
2676 the precondition should be regarded as False. If we are executing
2677 in a mode with run-time checks enabled for preconditions, then we would
2678 like this precondition to fail, rather than raising an exception
2679 because of the intermediate overflow.
2680
2681 However, the language definition leaves the specification of
2682 whether the above condition fails (raising ``Assert_Error``) or
2683 causes an intermediate overflow (raising ``Constraint_Error``)
2684 up to the implementation.
2685
2686 The situation is worse in a case such as the following:
2687
2688 .. code-block:: ada
2689
2690 procedure Q (A, B, C : Integer) with
2691 Pre => A + B + C <= Integer'Last;
2692
2693 Consider the call
2694
2695 .. code-block:: ada
2696
2697 Q (A => Integer'Last, B => 1, C => -1);
2698
2699 From a mathematical point of view the precondition
2700 is True, but at run time we may (but are not guaranteed to) get an
2701 exception raised because of the intermediate overflow (and we really
2702 would prefer this precondition to be considered True at run time).
2703
2704
2705 .. _Management_of_Overflows_in_GNAT:
2706
2707 Management of Overflows in GNAT
2708 -------------------------------
2709
2710 To deal with the portability issue, and with the problem of
2711 mathematical versus run-time interpretation of the expressions in
2712 assertions, GNAT provides comprehensive control over the handling
2713 of intermediate overflow. GNAT can operate in three modes, and
2714 furthemore, permits separate selection of operating modes for
2715 the expressions within assertions (here the term 'assertions'
2716 is used in the technical sense, which includes preconditions and so forth)
2717 and for expressions appearing outside assertions.
2718
2719 The three modes are:
2720
2721 * *Use base type for intermediate operations* (``STRICT``)
2722
2723 In this mode, all intermediate results for predefined arithmetic
2724 operators are computed using the base type, and the result must
2725 be in range of the base type. If this is not the
2726 case then either an exception is raised (if overflow checks are
2727 enabled) or the execution is erroneous (if overflow checks are suppressed).
2728 This is the normal default mode.
2729
2730 * *Most intermediate overflows avoided* (``MINIMIZED``)
2731
2732 In this mode, the compiler attempts to avoid intermediate overflows by
2733 using a larger integer type, typically ``Long_Long_Integer``,
2734 as the type in which arithmetic is
2735 performed for predefined arithmetic operators. This may be slightly more
2736 expensive at
2737 run time (compared to suppressing intermediate overflow checks), though
2738 the cost is negligible on modern 64-bit machines. For the examples given
2739 earlier, no intermediate overflows would have resulted in exceptions,
2740 since the intermediate results are all in the range of
2741 ``Long_Long_Integer`` (typically 64-bits on nearly all implementations
2742 of GNAT). In addition, if checks are enabled, this reduces the number of
2743 checks that must be made, so this choice may actually result in an
2744 improvement in space and time behavior.
2745
2746 However, there are cases where ``Long_Long_Integer`` is not large
2747 enough, consider the following example:
2748
2749 .. code-block:: ada
2750
2751 procedure R (A, B, C, D : Integer) with
2752 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
2753
2754 where ``A`` = ``B`` = ``C`` = ``D`` = ``Integer'Last``.
2755 Now the intermediate results are
2756 out of the range of ``Long_Long_Integer`` even though the final result
2757 is in range and the precondition is True (from a mathematical point
2758 of view). In such a case, operating in this mode, an overflow occurs
2759 for the intermediate computation (which is why this mode
2760 says *most* intermediate overflows are avoided). In this case,
2761 an exception is raised if overflow checks are enabled, and the
2762 execution is erroneous if overflow checks are suppressed.
2763
2764 * *All intermediate overflows avoided* (``ELIMINATED``)
2765
2766 In this mode, the compiler avoids all intermediate overflows
2767 by using arbitrary precision arithmetic as required. In this
2768 mode, the above example with ``A**2 * B**2`` would
2769 not cause intermediate overflow, because the intermediate result
2770 would be evaluated using sufficient precision, and the result
2771 of evaluating the precondition would be True.
2772
2773 This mode has the advantage of avoiding any intermediate
2774 overflows, but at the expense of significant run-time overhead,
2775 including the use of a library (included automatically in this
2776 mode) for multiple-precision arithmetic.
2777
2778 This mode provides cleaner semantics for assertions, since now
2779 the run-time behavior emulates true arithmetic behavior for the
2780 predefined arithmetic operators, meaning that there is never a
2781 conflict between the mathematical view of the assertion, and its
2782 run-time behavior.
2783
2784 Note that in this mode, the behavior is unaffected by whether or
2785 not overflow checks are suppressed, since overflow does not occur.
2786 It is possible for gigantic intermediate expressions to raise
2787 ``Storage_Error`` as a result of attempting to compute the
2788 results of such expressions (e.g. ``Integer'Last ** Integer'Last``)
2789 but overflow is impossible.
2790
2791
2792 Note that these modes apply only to the evaluation of predefined
2793 arithmetic, membership, and comparison operators for signed integer
2794 arithmetic.
2795
2796 For fixed-point arithmetic, checks can be suppressed. But if checks
2797 are enabled
2798 then fixed-point values are always checked for overflow against the
2799 base type for intermediate expressions (that is such checks always
2800 operate in the equivalent of ``STRICT`` mode).
2801
2802 For floating-point, on nearly all architectures, ``Machine_Overflows``
2803 is False, and IEEE infinities are generated, so overflow exceptions
2804 are never raised. If you want to avoid infinities, and check that
2805 final results of expressions are in range, then you can declare a
2806 constrained floating-point type, and range checks will be carried
2807 out in the normal manner (with infinite values always failing all
2808 range checks).
2809
2810
2811 .. _Specifying_the_Desired_Mode:
2812
2813 Specifying the Desired Mode
2814 ---------------------------
2815
2816 .. index:: pragma Overflow_Mode
2817
2818 The desired mode of for handling intermediate overflow can be specified using
2819 either the ``Overflow_Mode`` pragma or an equivalent compiler switch.
2820 The pragma has the form
2821
2822 .. code-block:: ada
2823
2824 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
2825
2826 where ``MODE`` is one of
2827
2828 * ``STRICT``: intermediate overflows checked (using base type)
2829 * ``MINIMIZED``: minimize intermediate overflows
2830 * ``ELIMINATED``: eliminate intermediate overflows
2831
2832 The case is ignored, so ``MINIMIZED``, ``Minimized`` and
2833 ``minimized`` all have the same effect.
2834
2835 If only the ``General`` parameter is present, then the given ``MODE`` applies
2836 to expressions both within and outside assertions. If both arguments
2837 are present, then ``General`` applies to expressions outside assertions,
2838 and ``Assertions`` applies to expressions within assertions. For example:
2839
2840 .. code-block:: ada
2841
2842 pragma Overflow_Mode
2843 (General => Minimized, Assertions => Eliminated);
2844
2845 specifies that general expressions outside assertions be evaluated
2846 in 'minimize intermediate overflows' mode, and expressions within
2847 assertions be evaluated in 'eliminate intermediate overflows' mode.
2848 This is often a reasonable choice, avoiding excessive overhead
2849 outside assertions, but assuring a high degree of portability
2850 when importing code from another compiler, while incurring
2851 the extra overhead for assertion expressions to ensure that
2852 the behavior at run time matches the expected mathematical
2853 behavior.
2854
2855 The ``Overflow_Mode`` pragma has the same scoping and placement
2856 rules as pragma ``Suppress``, so it can occur either as a
2857 configuration pragma, specifying a default for the whole
2858 program, or in a declarative scope, where it applies to the
2859 remaining declarations and statements in that scope.
2860
2861 Note that pragma ``Overflow_Mode`` does not affect whether
2862 overflow checks are enabled or suppressed. It only controls the
2863 method used to compute intermediate values. To control whether
2864 overflow checking is enabled or suppressed, use pragma ``Suppress``
2865 or ``Unsuppress`` in the usual manner.
2866
2867
2868 .. index:: -gnato? (gcc)
2869 .. index:: -gnato?? (gcc)
2870
2871 Additionally, a compiler switch :switch:`-gnato?` or :switch:`-gnato??`
2872 can be used to control the checking mode default (which can be subsequently
2873 overridden using pragmas).
2874
2875 Here ``?`` is one of the digits ``1`` through ``3``:
2876
2877 ====== ======================================================
2878 ``1`` use base type for intermediate operations (``STRICT``)
2879 ``2`` minimize intermediate overflows (``MINIMIZED``)
2880 ``3`` eliminate intermediate overflows (``ELIMINATED``)
2881 ====== ======================================================
2882
2883 As with the pragma, if only one digit appears then it applies to all
2884 cases; if two digits are given, then the first applies outside
2885 assertions, and the second within assertions. Thus the equivalent
2886 of the example pragma above would be
2887 :switch:`-gnato23`.
2888
2889 If no digits follow the :switch:`-gnato`, then it is equivalent to
2890 :switch:`-gnato11`,
2891 causing all intermediate operations to be computed using the base
2892 type (``STRICT`` mode).
2893
2894
2895 .. _Default_Settings:
2896
2897 Default Settings
2898 ----------------
2899
2900 The default mode for overflow checks is
2901
2902 ::
2903
2904 General => Strict
2905
2906 which causes all computations both inside and outside assertions to use
2907 the base type.
2908
2909 This retains compatibility with previous versions of
2910 GNAT which suppressed overflow checks by default and always
2911 used the base type for computation of intermediate results.
2912
2913 .. Sphinx allows no emphasis within :index: role. As a workaround we
2914 point the index to "switch" and use emphasis for "-gnato".
2915
2916 The :index:`switch <-gnato (gcc)>` :switch:`-gnato` (with no digits following)
2917 is equivalent to
2918
2919 ::
2920
2921 General => Strict
2922
2923 which causes overflow checking of all intermediate overflows
2924 both inside and outside assertions against the base type.
2925
2926 The pragma ``Suppress (Overflow_Check)`` disables overflow
2927 checking, but it has no effect on the method used for computing
2928 intermediate results.
2929
2930 The pragma ``Unsuppress (Overflow_Check)`` enables overflow
2931 checking, but it has no effect on the method used for computing
2932 intermediate results.
2933
2934
2935 .. _Implementation_Notes:
2936
2937 Implementation Notes
2938 --------------------
2939
2940 In practice on typical 64-bit machines, the ``MINIMIZED`` mode is
2941 reasonably efficient, and can be generally used. It also helps
2942 to ensure compatibility with code imported from some other
2943 compiler to GNAT.
2944
2945 Setting all intermediate overflows checking (``CHECKED`` mode)
2946 makes sense if you want to
2947 make sure that your code is compatible with any other possible
2948 Ada implementation. This may be useful in ensuring portability
2949 for code that is to be exported to some other compiler than GNAT.
2950
2951 The Ada standard allows the reassociation of expressions at
2952 the same precedence level if no parentheses are present. For
2953 example, ``A+B+C`` parses as though it were ``(A+B)+C``, but
2954 the compiler can reintepret this as ``A+(B+C)``, possibly
2955 introducing or eliminating an overflow exception. The GNAT
2956 compiler never takes advantage of this freedom, and the
2957 expression ``A+B+C`` will be evaluated as ``(A+B)+C``.
2958 If you need the other order, you can write the parentheses
2959 explicitly ``A+(B+C)`` and GNAT will respect this order.
2960
2961 The use of ``ELIMINATED`` mode will cause the compiler to
2962 automatically include an appropriate arbitrary precision
2963 integer arithmetic package. The compiler will make calls
2964 to this package, though only in cases where it cannot be
2965 sure that ``Long_Long_Integer`` is sufficient to guard against
2966 intermediate overflows. This package does not use dynamic
2967 allocation, but it does use the secondary stack, so an
2968 appropriate secondary stack package must be present (this
2969 is always true for standard full Ada, but may require
2970 specific steps for restricted run times such as ZFP).
2971
2972 Although ``ELIMINATED`` mode causes expressions to use arbitrary
2973 precision arithmetic, avoiding overflow, the final result
2974 must be in an appropriate range. This is true even if the
2975 final result is of type ``[Long_[Long_]]Integer'Base``, which
2976 still has the same bounds as its associated constrained
2977 type at run-time.
2978
2979 Currently, the ``ELIMINATED`` mode is only available on target
2980 platforms for which ``Long_Long_Integer`` is 64-bits (nearly all GNAT
2981 platforms).
2982
2983
2984
2985 .. _Performing_Dimensionality_Analysis_in_GNAT:
2986
2987 Performing Dimensionality Analysis in GNAT
2988 ==========================================
2989
2990 .. index:: Dimensionality analysis
2991
2992 The GNAT compiler supports dimensionality checking. The user can
2993 specify physical units for objects, and the compiler will verify that uses
2994 of these objects are compatible with their dimensions, in a fashion that is
2995 familiar to engineering practice. The dimensions of algebraic expressions
2996 (including powers with static exponents) are computed from their constituents.
2997
2998 .. index:: Dimension_System aspect
2999 .. index:: Dimension aspect
3000
3001 This feature depends on Ada 2012 aspect specifications, and is available from
3002 version 7.0.1 of GNAT onwards.
3003 The GNAT-specific aspect ``Dimension_System``
3004 allows you to define a system of units; the aspect ``Dimension``
3005 then allows the user to declare dimensioned quantities within a given system.
3006 (These aspects are described in the *Implementation Defined Aspects*
3007 chapter of the *GNAT Reference Manual*).
3008
3009 The major advantage of this model is that it does not require the declaration of
3010 multiple operators for all possible combinations of types: it is only necessary
3011 to use the proper subtypes in object declarations.
3012
3013 .. index:: System.Dim.Mks package (GNAT library)
3014 .. index:: MKS_Type type
3015
3016 The simplest way to impose dimensionality checking on a computation is to make
3017 use of one of the instantiations of the package ``System.Dim.Generic_Mks``, which
3018 are part of the GNAT library. This generic package defines a floating-point
3019 type ``MKS_Type``, for which a sequence of dimension names are specified,
3020 together with their conventional abbreviations. The following should be read
3021 together with the full specification of the package, in file
3022 :file:`s-digemk.ads`.
3023
3024 .. index:: s-digemk.ads file
3025
3026 .. code-block:: ada
3027
3028 type Mks_Type is new Float_Type
3029 with
3030 Dimension_System => (
3031 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
3032 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
3033 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
3034 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
3035 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
3036 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
3037 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
3038
3039 The package then defines a series of subtypes that correspond to these
3040 conventional units. For example:
3041
3042 .. code-block:: ada
3043
3044 subtype Length is Mks_Type
3045 with
3046 Dimension => (Symbol => 'm', Meter => 1, others => 0);
3047
3048 and similarly for ``Mass``, ``Time``, ``Electric_Current``,
3049 ``Thermodynamic_Temperature``, ``Amount_Of_Substance``, and
3050 ``Luminous_Intensity`` (the standard set of units of the SI system).
3051
3052 The package also defines conventional names for values of each unit, for
3053 example:
3054
3055 .. code-block:: ada
3056
3057 m : constant Length := 1.0;
3058 kg : constant Mass := 1.0;
3059 s : constant Time := 1.0;
3060 A : constant Electric_Current := 1.0;
3061
3062 as well as useful multiples of these units:
3063
3064 .. code-block:: ada
3065
3066 cm : constant Length := 1.0E-02;
3067 g : constant Mass := 1.0E-03;
3068 min : constant Time := 60.0;
3069 day : constant Time := 60.0 * 24.0 * min;
3070 ...
3071
3072 There are three instantiations of ``System.Dim.Generic_Mks`` defined in the
3073 GNAT library:
3074
3075 * ``System.Dim.Float_Mks`` based on ``Float`` defined in :file:`s-diflmk.ads`.
3076 * ``System.Dim.Long_Mks`` based on ``Long_Float`` defined in :file:`s-dilomk.ads`.
3077 * ``System.Dim.Mks`` based on ``Long_Long_Float`` defined in :file:`s-dimmks.ads`.
3078
3079 Using one of these packages, you can then define a derived unit by providing
3080 the aspect that specifies its dimensions within the MKS system, as well as the
3081 string to be used for output of a value of that unit:
3082
3083 .. code-block:: ada
3084
3085 subtype Acceleration is Mks_Type
3086 with Dimension => ("m/sec^2",
3087 Meter => 1,
3088 Second => -2,
3089 others => 0);
3090
3091 Here is a complete example of use:
3092
3093 .. code-block:: ada
3094
3095 with System.Dim.MKS; use System.Dim.Mks;
3096 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
3097 with Text_IO; use Text_IO;
3098 procedure Free_Fall is
3099 subtype Acceleration is Mks_Type
3100 with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
3101 G : constant acceleration := 9.81 * m / (s ** 2);
3102 T : Time := 10.0*s;
3103 Distance : Length;
3104
3105 begin
3106 Put ("Gravitational constant: ");
3107 Put (G, Aft => 2, Exp => 0); Put_Line ("");
3108 Distance := 0.5 * G * T ** 2;
3109 Put ("distance travelled in 10 seconds of free fall ");
3110 Put (Distance, Aft => 2, Exp => 0);
3111 Put_Line ("");
3112 end Free_Fall;
3113
3114 Execution of this program yields:
3115
3116 ::
3117
3118 Gravitational constant: 9.81 m/sec^2
3119 distance travelled in 10 seconds of free fall 490.50 m
3120
3121 However, incorrect assignments such as:
3122
3123 .. code-block:: ada
3124
3125 Distance := 5.0;
3126 Distance := 5.0 * kg;
3127
3128 are rejected with the following diagnoses:
3129
3130 ::
3131
3132 Distance := 5.0;
3133 >>> dimensions mismatch in assignment
3134 >>> left-hand side has dimension [L]
3135 >>> right-hand side is dimensionless
3136
3137 Distance := 5.0 * kg:
3138 >>> dimensions mismatch in assignment
3139 >>> left-hand side has dimension [L]
3140 >>> right-hand side has dimension [M]
3141
3142 The dimensions of an expression are properly displayed, even if there is
3143 no explicit subtype for it. If we add to the program:
3144
3145 .. code-block:: ada
3146
3147 Put ("Final velocity: ");
3148 Put (G * T, Aft =>2, Exp =>0);
3149 Put_Line ("");
3150
3151 then the output includes:
3152
3153 ::
3154
3155 Final velocity: 98.10 m.s**(-1)
3156
3157
3158 .. index:: Dimensionable type
3159 .. index:: Dimensioned subtype
3160
3161 The type ``Mks_Type`` is said to be a *dimensionable type* since it has a
3162 ``Dimension_System`` aspect, and the subtypes ``Length``, ``Mass``, etc.,
3163 are said to be *dimensioned subtypes* since each one has a ``Dimension``
3164 aspect.
3165
3166 .. index:: Dimension Vector (for a dimensioned subtype)
3167 .. index:: Dimension aspect
3168 .. index:: Dimension_System aspect
3169
3170 The ``Dimension`` aspect of a dimensioned subtype ``S`` defines a mapping
3171 from the base type's Unit_Names to integer (or, more generally, rational)
3172 values. This mapping is the *dimension vector* (also referred to as the
3173 *dimensionality*) for that subtype, denoted by ``DV(S)``, and thus for each
3174 object of that subtype. Intuitively, the value specified for each
3175 ``Unit_Name`` is the exponent associated with that unit; a zero value
3176 means that the unit is not used. For example:
3177
3178 .. code-block:: ada
3179
3180 declare
3181 Acc : Acceleration;
3182 ...
3183 begin
3184 ...
3185 end;
3186
3187 Here ``DV(Acc)`` = ``DV(Acceleration)`` =
3188 ``(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)``.
3189 Symbolically, we can express this as ``Meter / Second**2``.
3190
3191 The dimension vector of an arithmetic expression is synthesized from the
3192 dimension vectors of its components, with compile-time dimensionality checks
3193 that help prevent mismatches such as using an ``Acceleration`` where a
3194 ``Length`` is required.
3195
3196 The dimension vector of the result of an arithmetic expression *expr*, or
3197 :samp:`DV({expr})`, is defined as follows, assuming conventional
3198 mathematical definitions for the vector operations that are used:
3199
3200 * If *expr* is of the type *universal_real*, or is not of a dimensioned subtype,
3201 then *expr* is dimensionless; :samp:`DV({expr})` is the empty vector.
3202
3203 * :samp:`DV({op expr})`, where *op* is a unary operator, is :samp:`DV({expr})`
3204
3205 * :samp:`DV({expr1 op expr2})` where *op* is "+" or "-" is :samp:`DV({expr1})`
3206 provided that :samp:`DV({expr1})` = :samp:`DV({expr2})`.
3207 If this condition is not met then the construct is illegal.
3208
3209 * :samp:`DV({expr1} * {expr2})` is :samp:`DV({expr1})` + :samp:`DV({expr2})`,
3210 and :samp:`DV({expr1} / {expr2})` = :samp:`DV({expr1})` - :samp:`DV({expr2})`.
3211 In this context if one of the *expr*\ s is dimensionless then its empty
3212 dimension vector is treated as ``(others => 0)``.
3213
3214 * :samp:`DV({expr} ** {power})` is *power* * :samp:`DV({expr})`,
3215 provided that *power* is a static rational value. If this condition is not
3216 met then the construct is illegal.
3217
3218 Note that, by the above rules, it is illegal to use binary "+" or "-" to
3219 combine a dimensioned and dimensionless value. Thus an expression such as
3220 ``acc-10.0`` is illegal, where ``acc`` is an object of subtype
3221 ``Acceleration``.
3222
3223 The dimensionality checks for relationals use the same rules as
3224 for "+" and "-", except when comparing to a literal; thus
3225
3226 .. code-block:: ada
3227
3228 acc > len
3229
3230 is equivalent to
3231
3232 .. code-block:: ada
3233
3234 acc-len > 0.0
3235
3236 and is thus illegal, but
3237
3238 .. code-block:: ada
3239
3240 acc > 10.0
3241
3242 is accepted with a warning. Analogously a conditional expression requires the
3243 same dimension vector for each branch (with no exception for literals).
3244
3245 The dimension vector of a type conversion :samp:`T({expr})` is defined
3246 as follows, based on the nature of ``T``:
3247
3248 * If ``T`` is a dimensioned subtype then :samp:`DV(T({expr}))` is ``DV(T)``
3249 provided that either *expr* is dimensionless or
3250 :samp:`DV(T)` = :samp:`DV({expr})`. The conversion is illegal
3251 if *expr* is dimensioned and :samp:`DV({expr})` /= ``DV(T)``.
3252 Note that vector equality does not require that the corresponding
3253 Unit_Names be the same.
3254
3255 As a consequence of the above rule, it is possible to convert between
3256 different dimension systems that follow the same international system
3257 of units, with the seven physical components given in the standard order
3258 (length, mass, time, etc.). Thus a length in meters can be converted to
3259 a length in inches (with a suitable conversion factor) but cannot be
3260 converted, for example, to a mass in pounds.
3261
3262 * If ``T`` is the base type for *expr* (and the dimensionless root type of
3263 the dimension system), then :samp:`DV(T({expr}))` is ``DV(expr)``.
3264 Thus, if *expr* is of a dimensioned subtype of ``T``, the conversion may
3265 be regarded as a "view conversion" that preserves dimensionality.
3266
3267 This rule makes it possible to write generic code that can be instantiated
3268 with compatible dimensioned subtypes. The generic unit will contain
3269 conversions that will consequently be present in instantiations, but
3270 conversions to the base type will preserve dimensionality and make it
3271 possible to write generic code that is correct with respect to
3272 dimensionality.
3273
3274 * Otherwise (i.e., ``T`` is neither a dimensioned subtype nor a dimensionable
3275 base type), :samp:`DV(T({expr}))` is the empty vector. Thus a dimensioned
3276 value can be explicitly converted to a non-dimensioned subtype, which
3277 of course then escapes dimensionality analysis.
3278
3279 The dimension vector for a type qualification :samp:`T'({expr})` is the same
3280 as for the type conversion :samp:`T({expr})`.
3281
3282 An assignment statement
3283
3284 .. code-block:: ada
3285
3286 Source := Target;
3287
3288 requires ``DV(Source)`` = ``DV(Target)``, and analogously for parameter
3289 passing (the dimension vector for the actual parameter must be equal to the
3290 dimension vector for the formal parameter).
3291
3292
3293 .. _Stack_Related_Facilities:
3294
3295 Stack Related Facilities
3296 ========================
3297
3298 This section describes some useful tools associated with stack
3299 checking and analysis. In
3300 particular, it deals with dynamic and static stack usage measurements.
3301
3302 .. _Stack_Overflow_Checking:
3303
3304 Stack Overflow Checking
3305 -----------------------
3306
3307 .. index:: Stack Overflow Checking
3308
3309 .. index:: -fstack-check (gcc)
3310
3311 For most operating systems, ``gcc`` does not perform stack overflow
3312 checking by default. This means that if the main environment task or
3313 some other task exceeds the available stack space, then unpredictable
3314 behavior will occur. Most native systems offer some level of protection by
3315 adding a guard page at the end of each task stack. This mechanism is usually
3316 not enough for dealing properly with stack overflow situations because
3317 a large local variable could "jump" above the guard page.
3318 Furthermore, when the
3319 guard page is hit, there may not be any space left on the stack for executing
3320 the exception propagation code. Enabling stack checking avoids
3321 such situations.
3322
3323 To activate stack checking, compile all units with the ``gcc`` option
3324 :switch:`-fstack-check`. For example:
3325
3326 ::
3327
3328 $ gcc -c -fstack-check package1.adb
3329
3330 Units compiled with this option will generate extra instructions to check
3331 that any use of the stack (for procedure calls or for declaring local
3332 variables in declare blocks) does not exceed the available stack space.
3333 If the space is exceeded, then a ``Storage_Error`` exception is raised.
3334
3335 For declared tasks, the default stack size is defined by the GNAT runtime,
3336 whose size may be modified at bind time through the ``-d`` bind switch
3337 (:ref:`Switches_for_gnatbind`). Task specific stack sizes may be set using the
3338 ``Storage_Size`` pragma.
3339
3340 For the environment task, the stack size is determined by the operating system.
3341 Consequently, to modify the size of the environment task please refer to your
3342 operating system documentation.
3343
3344
3345 .. _Static_Stack_Usage_Analysis:
3346
3347 Static Stack Usage Analysis
3348 ---------------------------
3349
3350 .. index:: Static Stack Usage Analysis
3351
3352 .. index:: -fstack-usage
3353
3354 A unit compiled with ``-fstack-usage`` will generate an extra file
3355 that specifies
3356 the maximum amount of stack used, on a per-function basis.
3357 The file has the same
3358 basename as the target object file with a :file:`.su` extension.
3359 Each line of this file is made up of three fields:
3360
3361 * The name of the function.
3362 * A number of bytes.
3363 * One or more qualifiers: ``static``, ``dynamic``, ``bounded``.
3364
3365 The second field corresponds to the size of the known part of the function
3366 frame.
3367
3368 The qualifier ``static`` means that the function frame size
3369 is purely static.
3370 It usually means that all local variables have a static size.
3371 In this case, the second field is a reliable measure of the function stack
3372 utilization.
3373
3374 The qualifier ``dynamic`` means that the function frame size is not static.
3375 It happens mainly when some local variables have a dynamic size. When this
3376 qualifier appears alone, the second field is not a reliable measure
3377 of the function stack analysis. When it is qualified with ``bounded``, it
3378 means that the second field is a reliable maximum of the function stack
3379 utilization.
3380
3381 A unit compiled with ``-Wstack-usage`` will issue a warning for each
3382 subprogram whose stack usage might be larger than the specified amount of
3383 bytes. The wording is in keeping with the qualifier documented above.
3384
3385
3386 .. _Dynamic_Stack_Usage_Analysis:
3387
3388 Dynamic Stack Usage Analysis
3389 ----------------------------
3390
3391 It is possible to measure the maximum amount of stack used by a task, by
3392 adding a switch to ``gnatbind``, as:
3393
3394 ::
3395
3396 $ gnatbind -u0 file
3397
3398 With this option, at each task termination, its stack usage is output on
3399 :file:`stderr`.
3400 Note that this switch is not compatible with tools like
3401 Valgrind and DrMemory; they will report errors.
3402
3403 It is not always convenient to output the stack usage when the program
3404 is still running. Hence, it is possible to delay this output until program
3405 termination. for a given number of tasks specified as the argument of the
3406 ``-u`` option. For instance:
3407
3408 ::
3409
3410 $ gnatbind -u100 file
3411
3412 will buffer the stack usage information of the first 100 tasks to terminate and
3413 output this info at program termination. Results are displayed in four
3414 columns:
3415
3416 ::
3417
3418 Index | Task Name | Stack Size | Stack Usage
3419
3420 where:
3421
3422 * *Index* is a number associated with each task.
3423
3424 * *Task Name* is the name of the task analyzed.
3425
3426 * *Stack Size* is the maximum size for the stack.
3427
3428 * *Stack Usage* is the measure done by the stack analyzer.
3429 In order to prevent overflow, the stack
3430 is not entirely analyzed, and it's not possible to know exactly how
3431 much has actually been used.
3432
3433 By default the environment task stack, the stack that contains the main unit,
3434 is not processed. To enable processing of the environment task stack, the
3435 environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
3436 the environment task stack. This amount is given in kilobytes. For example:
3437
3438 ::
3439
3440 $ set GNAT_STACK_LIMIT 1600
3441
3442 would specify to the analyzer that the environment task stack has a limit
3443 of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
3444
3445 The package ``GNAT.Task_Stack_Usage`` provides facilities to get
3446 stack-usage reports at run time. See its body for the details.
3447
3448
3449
3450 .. _Memory_Management_Issues:
3451
3452 Memory Management Issues
3453 ========================
3454
3455 This section describes some useful memory pools provided in the GNAT library
3456 and in particular the GNAT Debug Pool facility, which can be used to detect
3457 incorrect uses of access values (including 'dangling references').
3458
3459 .. only:: PRO or GPL
3460
3461 It also describes the ``gnatmem`` tool, which can be used to track down
3462 "memory leaks".
3463
3464 .. _Some_Useful_Memory_Pools:
3465
3466 Some Useful Memory Pools
3467 ------------------------
3468
3469 .. index:: Memory Pool
3470 .. index:: storage, pool
3471
3472 The ``System.Pool_Global`` package offers the Unbounded_No_Reclaim_Pool
3473 storage pool. Allocations use the standard system call ``malloc`` while
3474 deallocations use the standard system call ``free``. No reclamation is
3475 performed when the pool goes out of scope. For performance reasons, the
3476 standard default Ada allocators/deallocators do not use any explicit storage
3477 pools but if they did, they could use this storage pool without any change in
3478 behavior. That is why this storage pool is used when the user
3479 manages to make the default implicit allocator explicit as in this example:
3480
3481 .. code-block:: ada
3482
3483 type T1 is access Something;
3484 -- no Storage pool is defined for T2
3485
3486 type T2 is access Something_Else;
3487 for T2'Storage_Pool use T1'Storage_Pool;
3488 -- the above is equivalent to
3489 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
3490
3491 The ``System.Pool_Local`` package offers the ``Unbounded_Reclaim_Pool`` storage
3492 pool. The allocation strategy is similar to ``Pool_Local``
3493 except that the all
3494 storage allocated with this pool is reclaimed when the pool object goes out of
3495 scope. This pool provides a explicit mechanism similar to the implicit one
3496 provided by several Ada 83 compilers for allocations performed through a local
3497 access type and whose purpose was to reclaim memory when exiting the
3498 scope of a given local access. As an example, the following program does not
3499 leak memory even though it does not perform explicit deallocation:
3500
3501 .. code-block:: ada
3502
3503 with System.Pool_Local;
3504 procedure Pooloc1 is
3505 procedure Internal is
3506 type A is access Integer;
3507 X : System.Pool_Local.Unbounded_Reclaim_Pool;
3508 for A'Storage_Pool use X;
3509 v : A;
3510 begin
3511 for I in 1 .. 50 loop
3512 v := new Integer;
3513 end loop;
3514 end Internal;
3515 begin
3516 for I in 1 .. 100 loop
3517 Internal;
3518 end loop;
3519 end Pooloc1;
3520
3521 The ``System.Pool_Size`` package implements the ``Stack_Bounded_Pool`` used when
3522 ``Storage_Size`` is specified for an access type.
3523 The whole storage for the pool is
3524 allocated at once, usually on the stack at the point where the access type is
3525 elaborated. It is automatically reclaimed when exiting the scope where the
3526 access type is defined. This package is not intended to be used directly by the
3527 user and it is implicitly used for each such declaration:
3528
3529 .. code-block:: ada
3530
3531 type T1 is access Something;
3532 for T1'Storage_Size use 10_000;
3533
3534
3535 .. _The_GNAT_Debug_Pool_Facility:
3536
3537 The GNAT Debug Pool Facility
3538 ----------------------------
3539
3540 .. index:: Debug Pool
3541 .. index:: storage, pool, memory corruption
3542
3543 The use of unchecked deallocation and unchecked conversion can easily
3544 lead to incorrect memory references. The problems generated by such
3545 references are usually difficult to tackle because the symptoms can be
3546 very remote from the origin of the problem. In such cases, it is
3547 very helpful to detect the problem as early as possible. This is the
3548 purpose of the Storage Pool provided by ``GNAT.Debug_Pools``.
3549
3550 In order to use the GNAT specific debugging pool, the user must
3551 associate a debug pool object with each of the access types that may be
3552 related to suspected memory problems. See Ada Reference Manual 13.11.
3553
3554 .. code-block:: ada
3555
3556 type Ptr is access Some_Type;
3557 Pool : GNAT.Debug_Pools.Debug_Pool;
3558 for Ptr'Storage_Pool use Pool;
3559
3560 ``GNAT.Debug_Pools`` is derived from a GNAT-specific kind of
3561 pool: the ``Checked_Pool``. Such pools, like standard Ada storage pools,
3562 allow the user to redefine allocation and deallocation strategies. They
3563 also provide a checkpoint for each dereference, through the use of
3564 the primitive operation ``Dereference`` which is implicitly called at
3565 each dereference of an access value.
3566
3567 Once an access type has been associated with a debug pool, operations on
3568 values of the type may raise four distinct exceptions,
3569 which correspond to four potential kinds of memory corruption:
3570
3571 * ``GNAT.Debug_Pools.Accessing_Not_Allocated_Storage``
3572 * ``GNAT.Debug_Pools.Accessing_Deallocated_Storage``
3573 * ``GNAT.Debug_Pools.Freeing_Not_Allocated_Storage``
3574 * ``GNAT.Debug_Pools.Freeing_Deallocated_Storage``
3575
3576 For types associated with a Debug_Pool, dynamic allocation is performed using
3577 the standard GNAT allocation routine. References to all allocated chunks of
3578 memory are kept in an internal dictionary. Several deallocation strategies are
3579 provided, whereupon the user can choose to release the memory to the system,
3580 keep it allocated for further invalid access checks, or fill it with an easily
3581 recognizable pattern for debug sessions. The memory pattern is the old IBM
3582 hexadecimal convention: ``16#DEADBEEF#``.
3583
3584 See the documentation in the file g-debpoo.ads for more information on the
3585 various strategies.
3586
3587 Upon each dereference, a check is made that the access value denotes a
3588 properly allocated memory location. Here is a complete example of use of
3589 ``Debug_Pools``, that includes typical instances of memory corruption:
3590
3591 .. code-block:: ada
3592
3593 with Gnat.Io; use Gnat.Io;
3594 with Unchecked_Deallocation;
3595 with Unchecked_Conversion;
3596 with GNAT.Debug_Pools;
3597 with System.Storage_Elements;
3598 with Ada.Exceptions; use Ada.Exceptions;
3599 procedure Debug_Pool_Test is
3600
3601 type T is access Integer;
3602 type U is access all T;
3603
3604 P : GNAT.Debug_Pools.Debug_Pool;
3605 for T'Storage_Pool use P;
3606
3607 procedure Free is new Unchecked_Deallocation (Integer, T);
3608 function UC is new Unchecked_Conversion (U, T);
3609 A, B : aliased T;
3610
3611 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
3612
3613 begin
3614 Info (P);
3615 A := new Integer;
3616 B := new Integer;
3617 B := A;
3618 Info (P);
3619 Free (A);
3620 begin
3621 Put_Line (Integer'Image(B.all));
3622 exception
3623 when E : others => Put_Line ("raised: " & Exception_Name (E));
3624 end;
3625 begin
3626 Free (B);
3627 exception
3628 when E : others => Put_Line ("raised: " & Exception_Name (E));
3629 end;
3630 B := UC(A'Access);
3631 begin
3632 Put_Line (Integer'Image(B.all));
3633 exception
3634 when E : others => Put_Line ("raised: " & Exception_Name (E));
3635 end;
3636 begin
3637 Free (B);
3638 exception
3639 when E : others => Put_Line ("raised: " & Exception_Name (E));
3640 end;
3641 Info (P);
3642 end Debug_Pool_Test;
3643
3644 The debug pool mechanism provides the following precise diagnostics on the
3645 execution of this erroneous program:
3646
3647 ::
3648
3649 Debug Pool info:
3650 Total allocated bytes : 0
3651 Total deallocated bytes : 0
3652 Current Water Mark: 0
3653 High Water Mark: 0
3654
3655 Debug Pool info:
3656 Total allocated bytes : 8
3657 Total deallocated bytes : 0
3658 Current Water Mark: 8
3659 High Water Mark: 8
3660
3661 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
3662 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
3663 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
3664 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
3665 Debug Pool info:
3666 Total allocated bytes : 8
3667 Total deallocated bytes : 4
3668 Current Water Mark: 4
3669 High Water Mark: 8
3670
3671 .. only:: PRO or GPL
3672
3673 .. _The_gnatmem_Tool:
3674
3675 The ``gnatmem`` Tool
3676 --------------------
3677
3678 .. index:: ! gnatmem
3679
3680 The ``gnatmem`` utility monitors dynamic allocation and
3681 deallocation activity in a program, and displays information about
3682 incorrect deallocations and possible sources of memory leaks.
3683 It is designed to work for fixed-position executables in association
3684 with a static runtime library only and in this context provides three
3685 types of information:
3686
3687 * General information concerning memory management, such as the total
3688 number of allocations and deallocations, the amount of allocated
3689 memory and the high water mark, i.e., the largest amount of allocated
3690 memory in the course of program execution.
3691
3692 * Backtraces for all incorrect deallocations, that is to say deallocations
3693 which do not correspond to a valid allocation.
3694
3695 * Information on each allocation that is potentially the origin of a memory
3696 leak.
3697
3698 .. _Running_gnatmem:
3699
3700 Running ``gnatmem``
3701 ^^^^^^^^^^^^^^^^^^^
3702
3703 ``gnatmem`` makes use of the output created by the special version of
3704 allocation and deallocation routines that record call information. This allows
3705 it to obtain accurate dynamic memory usage history at a minimal cost to the
3706 execution speed. Note however, that ``gnatmem`` is only supported on
3707 GNU/Linux and Windows.
3708
3709 The ``gnatmem`` command has the form
3710
3711 ::
3712
3713 $ gnatmem [ switches ] [ DEPTH ] user_program
3714
3715 The user program must be linked with the instrumented version of the
3716 allocation and deallocation routines. This is done by linking with the
3717 :file:`libgmem.a` library. For correct symbolic backtrace information,
3718 the user program should also both be compiled with debugging options
3719 (see :ref:`Switches_for_gcc`) and be linked at a fixed position. For
3720 example to build :file:`my_program` with ``gnatmake``:
3721
3722 ::
3723
3724 $ gnatmake -g my_program -largs -lgmem -no-pie
3725
3726 As library :file:`libgmem.a` contains an alternate body for package
3727 ``System.Memory``, :file:`s-memory.adb` should not be compiled and linked
3728 when an executable is linked with library :file:`libgmem.a`. It is then not
3729 recommended to use ``gnatmake`` with switch :switch:`-a`.
3730
3731 When :file:`my_program` is executed, the file :file:`gmem.out` is produced.
3732 This file contains information about all allocations and deallocations
3733 performed by the program. It is produced by the instrumented allocations and
3734 deallocations routines and will be used by ``gnatmem``.
3735
3736 In order to produce symbolic backtrace information for allocations and
3737 deallocations performed by the GNAT run-time library, you need to use a
3738 version of that library that has been compiled with the :switch:`-g` switch
3739 (see :ref:`Rebuilding_the_GNAT_Run-Time_Library`).
3740
3741 ``gnatmem`` must be supplied with the :file:`gmem.out` file and the executable to
3742 examine. If the location of :file:`gmem.out` file was not explicitly supplied by
3743 :switch:`-i` switch, gnatmem will assume that this file can be found in the
3744 current directory. For example, after you have executed :file:`my_program`,
3745 :file:`gmem.out` can be analyzed by ``gnatmem`` using the command:
3746
3747 ::
3748
3749 $ gnatmem my_program
3750
3751 This will produce the output with the following format:
3752
3753 ::
3754
3755 $ gnatmem my_program
3756
3757 Global information
3758 ------------------
3759 Total number of allocations : 45
3760 Total number of deallocations : 6
3761 Final Water Mark (non freed mem) : 11.29 Kilobytes
3762 High Water Mark : 11.40 Kilobytes
3763
3764 .
3765 .
3766 .
3767 Allocation Root # 2
3768 -------------------
3769 Number of non freed allocations : 11
3770 Final Water Mark (non freed mem) : 1.16 Kilobytes
3771 High Water Mark : 1.27 Kilobytes
3772 Backtrace :
3773 my_program.adb:23 my_program.alloc
3774 .
3775 .
3776 .
3777
3778 The first block of output gives general information. In this case, the
3779 Ada construct ``new`` was executed 45 times, and only 6 calls to an
3780 Unchecked_Deallocation routine occurred.
3781
3782 Subsequent paragraphs display information on all allocation roots.
3783 An allocation root is a specific point in the execution of the program
3784 that generates some dynamic allocation, such as a ``new``
3785 construct. This root is represented by an execution backtrace (or subprogram
3786 call stack). By default the backtrace depth for allocations roots is 1, so
3787 that a root corresponds exactly to a source location. The backtrace can
3788 be made deeper, to make the root more specific.
3789
3790 .. _Switches_for_gnatmem:
3791
3792 Switches for ``gnatmem``
3793 ^^^^^^^^^^^^^^^^^^^^^^^^
3794
3795 ``gnatmem`` recognizes the following switches:
3796
3797 .. index:: -q (gnatmem)
3798
3799 :samp:`-q`
3800 Quiet. Gives the minimum output needed to identify the origin of the
3801 memory leaks. Omits statistical information.
3802
3803
3804 .. index:: DEPTH switch (gnatmem)
3805
3806 :samp:`{DEPTH}`
3807 ``DEPTH`` is an integer literal (usually between 1 and 10) which controls
3808 the depth of the backtraces defining allocation root. The default value for
3809 DEPTH is 1. The deeper the backtrace, the more precise the localization of
3810 the root. Note that the total number of roots can depend on this
3811 parameter, in other words there may be more roots when the requested
3812 backtrace depth is higher. This parameter must be specified *before* the
3813 name of the executable to be analyzed, to avoid ambiguity.
3814
3815
3816 .. index:: -b (gnatmem)
3817
3818 :samp:`-b {N}`
3819 This switch has the same effect as just a depth parameter ``N``.
3820
3821
3822 .. index:: -i (gnatmem)
3823
3824 :samp:`-i {file}`
3825 Do the ``gnatmem`` processing starting from :file:`file`, rather than
3826 :file:`gmem.out` in the current directory.
3827
3828
3829 .. index:: -m (gnatmem)
3830
3831 :samp:`-m {n}`
3832 This switch causes ``gnatmem`` to mask the allocation roots that have less
3833 than n leaks. The default value is 1. Specifying the value of 0 will allow
3834 examination of even the roots that did not result in leaks.
3835
3836
3837 .. index:: -s (gnatmem)
3838
3839 :samp:`-s {order}`
3840 This switch causes ``gnatmem`` to sort the allocation roots according to the
3841 specified order of sort criteria, each identified by a single letter. The
3842 currently supported criteria are ``n``, ``h``, and ``w`` standing respectively for
3843 number of unfreed allocations, high watermark, and final watermark
3844 corresponding to a specific root. The default order is ``nwh``.
3845
3846
3847 .. index:: -t (gnatmem)
3848
3849 :samp:`-t`
3850 This switch causes memory allocated size to be always output in bytes.
3851 Default ``gnatmem`` behavior is to show memory sizes less then 1 kilobyte
3852 in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in
3853 megabytes.
3854
3855
3856 .. _Example_of_gnatmem_Usage:
3857
3858 Example of ``gnatmem`` Usage
3859 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3860
3861 The following example shows the use of ``gnatmem``
3862 on a simple memory-leaking program.
3863 Suppose that we have the following Ada program:
3864
3865 .. code-block:: ada
3866
3867 with Unchecked_Deallocation;
3868 procedure Test_Gm is
3869
3870 type T is array (1..1000) of Integer;
3871 type Ptr is access T;
3872 procedure Free is new Unchecked_Deallocation (T, Ptr);
3873 A : Ptr;
3874
3875 procedure My_Alloc is
3876 begin
3877 A := new T;
3878 end My_Alloc;
3879
3880 procedure My_DeAlloc is
3881 B : Ptr := A;
3882 begin
3883 Free (B);
3884 end My_DeAlloc;
3885
3886 begin
3887 My_Alloc;
3888 for I in 1 .. 5 loop
3889 for J in I .. 5 loop
3890 My_Alloc;
3891 end loop;
3892 My_Dealloc;
3893 end loop;
3894 end;
3895
3896 The program needs to be compiled with the debugging option and linked with
3897 the ``gmem`` library:
3898
3899 ::
3900
3901 $ gnatmake -g test_gm -largs -lgmem
3902
3903 Then we execute the program as usual:
3904
3905 ::
3906
3907 $ test_gm
3908
3909 Then ``gnatmem`` is invoked simply with
3910
3911 ::
3912
3913 $ gnatmem test_gm
3914
3915 which produces the following output (result may vary on different platforms):
3916
3917 ::
3918
3919 Global information
3920 ------------------
3921 Total number of allocations : 18
3922 Total number of deallocations : 5
3923 Final Water Mark (non freed mem) : 53.00 Kilobytes
3924 High Water Mark : 56.90 Kilobytes
3925
3926 Allocation Root # 1
3927 -------------------
3928 Number of non freed allocations : 11
3929 Final Water Mark (non freed mem) : 42.97 Kilobytes
3930 High Water Mark : 46.88 Kilobytes
3931 Backtrace :
3932 test_gm.adb:11 test_gm.my_alloc
3933
3934 Allocation Root # 2
3935 -------------------
3936 Number of non freed allocations : 1
3937 Final Water Mark (non freed mem) : 10.02 Kilobytes
3938 High Water Mark : 10.02 Kilobytes
3939 Backtrace :
3940 s-secsta.adb:81 system.secondary_stack.ss_init
3941
3942 Allocation Root # 3
3943 -------------------
3944 Number of non freed allocations : 1
3945 Final Water Mark (non freed mem) : 12 Bytes
3946 High Water Mark : 12 Bytes
3947 Backtrace :
3948 s-secsta.adb:181 system.secondary_stack.ss_init
3949
3950
3951 Note that the GNAT runtime contains itself a certain number of
3952 allocations that have no corresponding deallocation,
3953 as shown here for root #2 and root #3.
3954 This is a normal behavior when the number of non-freed allocations
3955 is one, it allocates dynamic data structures that the run time needs for
3956 the complete lifetime of the program. Note also that there is only one
3957 allocation root in the user program with a single line back trace:
3958 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
3959 program shows that 'My_Alloc' is called at 2 different points in the
3960 source (line 21 and line 24). If those two allocation roots need to be
3961 distinguished, the backtrace depth parameter can be used:
3962
3963 ::
3964
3965 $ gnatmem 3 test_gm
3966
3967 which will give the following output:
3968
3969
3970 ::
3971
3972 Global information
3973 ------------------
3974 Total number of allocations : 18
3975 Total number of deallocations : 5
3976 Final Water Mark (non freed mem) : 53.00 Kilobytes
3977 High Water Mark : 56.90 Kilobytes
3978
3979 Allocation Root # 1
3980 -------------------
3981 Number of non freed allocations : 10
3982 Final Water Mark (non freed mem) : 39.06 Kilobytes
3983 High Water Mark : 42.97 Kilobytes
3984 Backtrace :
3985 test_gm.adb:11 test_gm.my_alloc
3986 test_gm.adb:24 test_gm
3987 b_test_gm.c:52 main
3988
3989 Allocation Root # 2
3990 -------------------
3991 Number of non freed allocations : 1
3992 Final Water Mark (non freed mem) : 10.02 Kilobytes
3993 High Water Mark : 10.02 Kilobytes
3994 Backtrace :
3995 s-secsta.adb:81 system.secondary_stack.ss_init
3996 s-secsta.adb:283 <system__secondary_stack___elabb>
3997 b_test_gm.c:33 adainit
3998
3999 Allocation Root # 3
4000 -------------------
4001 Number of non freed allocations : 1
4002 Final Water Mark (non freed mem) : 3.91 Kilobytes
4003 High Water Mark : 3.91 Kilobytes
4004 Backtrace :
4005 test_gm.adb:11 test_gm.my_alloc
4006 test_gm.adb:21 test_gm
4007 b_test_gm.c:52 main
4008
4009 Allocation Root # 4
4010 -------------------
4011 Number of non freed allocations : 1
4012 Final Water Mark (non freed mem) : 12 Bytes
4013 High Water Mark : 12 Bytes
4014 Backtrace :
4015 s-secsta.adb:181 system.secondary_stack.ss_init
4016 s-secsta.adb:283 <system__secondary_stack___elabb>
4017 b_test_gm.c:33 adainit
4018
4019 The allocation root #1 of the first example has been split in 2 roots #1
4020 and #3, thanks to the more precise associated backtrace.