1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                             S E M _ E L A B                              --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1997-2018, Free Software Foundation, Inc.         --
10--                                                                          --
11-- GNAT is free software;  you can  redistribute it  and/or modify it under --
12-- terms of the  GNU General Public License as published  by the Free Soft- --
13-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17-- for  more details.  You should have  received  a copy of the GNU General --
18-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19-- http://www.gnu.org/licenses for a complete copy of the license.          --
20--                                                                          --
21-- GNAT was originally developed  by the GNAT team at  New York University. --
22-- Extensive contributions were provided by Ada Core Technologies Inc.      --
23--                                                                          --
24------------------------------------------------------------------------------
25
26with Atree;    use Atree;
27with Checks;   use Checks;
28with Debug;    use Debug;
29with Einfo;    use Einfo;
30with Elists;   use Elists;
31with Errout;   use Errout;
32with Exp_Ch11; use Exp_Ch11;
33with Exp_Tss;  use Exp_Tss;
34with Exp_Util; use Exp_Util;
35with Expander; use Expander;
36with Lib;      use Lib;
37with Lib.Load; use Lib.Load;
38with Namet;    use Namet;
39with Nlists;   use Nlists;
40with Nmake;    use Nmake;
41with Opt;      use Opt;
42with Output;   use Output;
43with Restrict; use Restrict;
44with Rident;   use Rident;
45with Rtsfind;  use Rtsfind;
46with Sem;      use Sem;
47with Sem_Aux;  use Sem_Aux;
48with Sem_Cat;  use Sem_Cat;
49with Sem_Ch7;  use Sem_Ch7;
50with Sem_Ch8;  use Sem_Ch8;
51with Sem_Prag; use Sem_Prag;
52with Sem_Util; use Sem_Util;
53with Sinfo;    use Sinfo;
54with Sinput;   use Sinput;
55with Snames;   use Snames;
56with Stand;    use Stand;
57with Table;
58with Tbuild;   use Tbuild;
59with Uintp;    use Uintp;
60with Uname;    use Uname;
61
62with GNAT.HTable; use GNAT.HTable;
63
64package body Sem_Elab is
65
66   -----------------------------------------
67   -- Access-before-elaboration mechanism --
68   -----------------------------------------
69
70   --  The access-before-elaboration (ABE) mechanism implemented in this unit
71   --  has the following objectives:
72   --
73   --    * Diagnose at compile-time or install run-time checks to prevent ABE
74   --      access to data and behaviour.
75   --
76   --      The high-level idea is to accurately diagnose ABE issues within a
77   --      single unit because the ABE mechanism can inspect the whole unit.
78   --      As soon as the elaboration graph extends to an external unit, the
79   --      diagnostics stop because the body of the unit may not be available.
80   --      Due to control and data flow, the ABE mechanism cannot accurately
81   --      determine whether a particular scenario will be elaborated or not.
82   --      Conditional ABE checks are therefore used to verify the elaboration
83   --      status of a local and external target at run time.
84   --
85   --    * Supply elaboration dependencies for a unit to binde
86   --
87   --      The ABE mechanism registers each outgoing elaboration edge for the
88   --      main unit in its ALI file. GNATbind and binde can then reconstruct
89   --      the full elaboration graph and determine the proper elaboration
90   --      order for all units in the compilation.
91   --
92   --  The ABE mechanism supports three models of elaboration:
93   --
94   --    * Dynamic model - This is the most permissive of the three models.
95   --      When the dynamic model is in effect, the mechanism performs very
96   --      little diagnostics and generates run-time checks to detect ABE
97   --      issues. The behaviour of this model is identical to that specified
98   --      by the Ada RM. This model is enabled with switch -gnatE.
99   --
100   --    * Static model - This is the middle ground of the three models. When
101   --      the static model is in effect, the mechanism diagnoses and installs
102   --      run-time checks to detect ABE issues in the main unit. In addition,
103   --      the mechanism generates implicit Elaborate or Elaborate_All pragmas
104   --      to ensure the prior elaboration of withed units. The model employs
105   --      textual order, with clause context, and elaboration-related source
106   --      pragmas. This is the default model.
107   --
108   --    * SPARK model - This is the most conservative of the three models and
109   --      impelements the semantics defined in SPARK RM 7.7. The SPARK model
110   --      is in effect only when a context resides in a SPARK_Mode On region,
111   --      otherwise the mechanism falls back to one of the previous models.
112   --
113   --  The ABE mechanism consists of a "recording" phase and a "processing"
114   --  phase.
115
116   -----------------
117   -- Terminology --
118   -----------------
119
120   --  * ABE - An attempt to activate, call, or instantiate a scenario which
121   --    has not been fully elaborated.
122   --
123   --  * Bridge target - A type of target. A bridge target is a link between
124   --    scenarios. It is usually a byproduct of expansion and does not have
125   --    any direct ABE ramifications.
126   --
127   --  * Call marker - A special node used to indicate the presence of a call
128   --    in the tree in case expansion transforms or eliminates the original
129   --    call. N_Call_Marker nodes do not have static and run-time semantics.
130   --
131   --  * Conditional ABE - A type of ABE. A conditional ABE occurs when the
132   --    elaboration or invocation of a target by a scenario within the main
133   --    unit causes an ABE, but does not cause an ABE for another scenarios
134   --    within the main unit.
135   --
136   --  * Declaration level - A type of enclosing level. A scenario or target is
137   --    at the declaration level when it appears within the declarations of a
138   --    block statement, entry body, subprogram body, or task body, ignoring
139   --    enclosing packages.
140   --
141   --  * Early call region - A section of code which ends at a subprogram body
142   --    and starts from the nearest non-preelaborable construct which precedes
143   --    the subprogram body. The early call region extends from a package body
144   --    to a package spec when the spec carries pragma Elaborate_Body.
145   --
146   --  * Generic library level - A type of enclosing level. A scenario or
147   --    target is at the generic library level if it appears in a generic
148   --    package library unit, ignoring enclosing packages.
149   --
150   --  * Guaranteed ABE - A type of ABE. A guaranteed ABE occurs when the
151   --    elaboration or invocation of a target by all scenarios within the
152   --    main unit causes an ABE.
153   --
154   --  * Instantiation library level - A type of enclosing level. A scenario
155   --    or target is at the instantiation library level if it appears in an
156   --    instantiation library unit, ignoring enclosing packages.
157   --
158   --  * Library level - A type of enclosing level. A scenario or target is at
159   --    the library level if it appears in a package library unit, ignoring
160   --    enclosng packages.
161   --
162   --  * Non-library-level encapsulator - A construct that cannot be elaborated
163   --    on its own and requires elaboration by a top-level scenario.
164   --
165   --  * Scenario - A construct or context which may be elaborated or executed
166   --    by elaboration code. The scenarios recognized by the ABE mechanism are
167   --    as follows:
168   --
169   --      - '[Unrestricted_]Access of entries, operators, and subprograms
170   --
171   --      - Assignments to variables
172   --
173   --      - Calls to entries, operators, and subprograms
174   --
175   --      - Derived type declarations
176   --
177   --      - Instantiations
178   --
179   --      - Pragma Refined_State
180   --
181   --      - Reads of variables
182   --
183   --      - Task activation
184   --
185   --  * Target - A construct referenced by a scenario. The targets recognized
186   --    by the ABE mechanism are as follows:
187   --
188   --      - For '[Unrestricted_]Access of entries, operators, and subprograms,
189   --        the target is the entry, operator, or subprogram.
190   --
191   --      - For assignments to variables, the target is the variable
192   --
193   --      - For calls, the target is the entry, operator, or subprogram
194   --
195   --      - For derived type declarations, the target is the derived type
196   --
197   --      - For instantiations, the target is the generic template
198   --
199   --      - For pragma Refined_State, the targets are the constituents
200   --
201   --      - For reads of variables, the target is the variable
202   --
203   --      - For task activation, the target is the task body
204   --
205   --  * Top-level scenario - A scenario which appears in a non-generic main
206   --    unit. Depending on the elaboration model is in effect, the following
207   --    addotional restrictions apply:
208   --
209   --      - Dynamic model - No restrictions
210   --
211   --      - SPARK model - Falls back to either the dynamic or static model
212   --
213   --      - Static model - The scenario must be at the library level
214
215   ---------------------
216   -- Recording phase --
217   ---------------------
218
219   --  The Recording phase coincides with the analysis/resolution phase of the
220   --  compiler. It has the following objectives:
221   --
222   --    * Record all top-level scenarios for examination by the Processing
223   --      phase.
224   --
225   --      Saving only a certain number of nodes improves the performance of
226   --      the ABE mechanism. This eliminates the need to examine the whole
227   --      tree in a separate pass.
228   --
229   --    * Record certain SPARK scenarios which are not necessarily executable
230   --      during elaboration, but still require elaboration-related checks.
231   --
232   --      Saving only a certain number of nodes improves the performance of
233   --      the ABE mechanism. This eliminates the need to examine the whole
234   --      tree in a separate pass.
235   --
236   --    * Detect and diagnose calls in preelaborable or pure units, including
237   --      generic bodies.
238   --
239   --      This diagnostic is carried out during the Recording phase because it
240   --      does not need the heavy recursive traversal done by the Processing
241   --      phase.
242   --
243   --    * Detect and diagnose guaranteed ABEs caused by instantiations,
244   --      calls, and task activation.
245   --
246   --      The issues detected by the ABE mechanism are reported as warnings
247   --      because they do not violate Ada semantics. Forward instantiations
248   --      may thus reach gigi, however gigi cannot handle certain kinds of
249   --      premature instantiations and may crash. To avoid this limitation,
250   --      the ABE mechanism must identify forward instantiations as early as
251   --      possible and suppress their bodies. Calls and task activations are
252   --      included in this category for completeness.
253
254   ----------------------
255   -- Processing phase --
256   ----------------------
257
258   --  The Processing phase is a separate pass which starts after instantiating
259   --  and/or inlining of bodies, but before the removal of Ghost code. It has
260   --  the following objectives:
261   --
262   --    * Examine all top-level scenarios saved during the Recording phase
263   --
264   --      The top-level scenarios act as roots for depth-first traversal of
265   --      the call/instantiation/task activation graph. The traversal stops
266   --      when an outgoing edge leaves the main unit.
267   --
268   --    * Examine all SPARK scenarios saved during the Recording phase
269   --
270   --    * Depending on the elaboration model in effect, perform the following
271   --      actions:
272   --
273   --        - Dynamic model - Install run-time conditional ABE checks.
274   --
275   --        - SPARK model - Enforce the SPARK elaboration rules
276   --
277   --        - Static model - Diagnose conditional ABEs, install run-time
278   --          conditional ABE checks, and guarantee the elaboration of
279   --          external units.
280   --
281   --    * Examine nested scenarios
282   --
283   --      Nested scenarios discovered during the depth-first traversal are
284   --      in turn subjected to the same actions outlined above and examined
285   --      for the next level of nested scenarios.
286
287   ------------------
288   -- Architecture --
289   ------------------
290
291   --     Analysis/Resolution
292   --     |
293   --     +- Build_Call_Marker
294   --     |
295   --     +- Build_Variable_Reference_Marker
296   --     |
297   --  +- | -------------------- Recording phase ---------------------------+
298   --  |  v                                                                 |
299   --  |  Record_Elaboration_Scenario                                       |
300   --  |  |                                                                 |
301   --  |  +--> Check_Preelaborated_Call                                     |
302   --  |  |                                                                 |
303   --  |  +--> Process_Guaranteed_ABE                                       |
304   --  |  |    |                                                            |
305   --  |  |    +--> Process_Guaranteed_ABE_Activation                       |
306   --  |  |    |                                                            |
307   --  |  |    +--> Process_Guaranteed_ABE_Call                             |
308   --  |  |    |                                                            |
309   --  |  |    +--> Process_Guaranteed_ABE_Instantiation                    |
310   --  |  |                                                                 |
311   --  +- | ----------------------------------------------------------------+
312   --     |
313   --     |
314   --     +--> SPARK_Scenarios
315   --     |    +-----------+-----------+ .. +-----------+
316   --     |    | Scenario1 | Scenario2 | .. | ScenarioN |
317   --     |    +-----------+-----------+ .. +-----------+
318   --     |
319   --     +--> Top_Level_Scenarios
320   --     |    +-----------+-----------+ .. +-----------+
321   --     |    | Scenario1 | Scenario2 | .. | ScenarioN |
322   --     |    +-----------+-----------+ .. +-----------+
323   --     |
324   --     End of Compilation
325   --     |
326   --  +- | --------------------- Processing phase -------------------------+
327   --  |  v                                                                 |
328   --  |  Check_Elaboration_Scenarios                                       |
329   --  |  |                                                                 |
330   --  |  +--> Check_SPARK_Scenario                                         |
331   --  |  |    |                                                            |
332   --  |  |    +--> Check_SPARK_Derived_Type                                |
333   --  |  |    |                                                            |
334   --  |  |    +--> Check_SPARK_Instantiation                               |
335   --  |  |    |                                                            |
336   --  |  |    +--> Check_SPARK_Refined_State_Pragma                        |
337   --  |  |                                                                 |
338   --  |  +--> Process_Conditional_ABE <---------------------------+        |
339   --  |       |                                                   |        |
340   --  |       +--> Process_Conditional_ABE_Access    Is_Suitable_Scenario  |
341   --  |       |                                                   ^        |
342   --  |       +--> Process_Conditional_ABE_Activation             |        |
343   --  |       |    |                                              |        |
344   --  |       |    +-----------------------------+                |        |
345   --  |       |                                  |                |        |
346   --  |       +--> Process_Conditional_ABE_Call  +--------> Traverse_Body  |
347   --  |       |    |                             |                         |
348   --  |       |    +-----------------------------+                         |
349   --  |       |                                                            |
350   --  |       +--> Process_Conditional_ABE_Instantiation                   |
351   --  |       |                                                            |
352   --  |       +--> Process_Conditional_ABE_Variable_Assignment             |
353   --  |       |                                                            |
354   --  |       +--> Process_Conditional_ABE_Variable_Reference              |
355   --  |                                                                    |
356   --  +--------------------------------------------------------------------+
357
358   ----------------------
359   -- Important points --
360   ----------------------
361
362   --  The Processing phase starts after the analysis, resolution, expansion
363   --  phase has completed. As a result, no current semantic information is
364   --  available. The scope stack is empty, global flags such as In_Instance
365   --  or Inside_A_Generic become useless. To remedy this, the ABE mechanism
366   --  must either save or recompute semantic information.
367
368   --  Expansion heavily transforms calls and to some extent instantiations. To
369   --  remedy this, the ABE mechanism generates N_Call_Marker nodes in order to
370   --  capture the target and relevant attributes of the original call.
371
372   --  The diagnostics of the ABE mechanism depend on accurate source locations
373   --  to determine the spacial relation of nodes.
374
375   --------------
376   -- Switches --
377   --------------
378
379   --  The following switches may be used to control the behavior of the ABE
380   --  mechanism.
381   --
382   --  -gnatd_a stop elaboration checks on accept or select statement
383   --
384   --           The ABE mechanism stops the traversal of a task body when it
385   --           encounters an accept or a select statement. This behavior is
386   --           equivalent to restriction No_Entry_Calls_In_Elaboration_Code,
387   --           but without penalizing actual entry calls during elaboration.
388   --
389   --  -gnatd_e ignore entry calls and requeue statements for elaboration
390   --
391   --           The ABE mechanism does not generate N_Call_Marker nodes for
392   --           protected or task entry calls as well as requeue statements.
393   --           As a result, the calls and requeues are not recorded or
394   --           processed.
395   --
396   --  -gnatdE  elaboration checks on predefined units
397   --
398   --           The ABE mechanism considers scenarios which appear in internal
399   --           units (Ada, GNAT, Interfaces, System).
400   --
401   --  -gnatd.G ignore calls through generic formal parameters for elaboration
402   --
403   --           The ABE mechanism does not generate N_Call_Marker nodes for
404   --           calls which occur in expanded instances, and invoke generic
405   --           actual subprograms through generic formal subprograms. As a
406   --           result, the calls are not recorded or processed.
407   --
408   --  -gnatd_i ignore activations and calls to instances for elaboration
409   --
410   --           The ABE mechanism ignores calls and task activations when they
411   --           target a subprogram or task type defined an external instance.
412   --           As a result, the calls and task activations are not processed.
413   --
414   --  -gnatdL  ignore external calls from instances for elaboration
415   --
416   --           The ABE mechanism does not generate N_Call_Marker nodes for
417   --           calls which occur in expanded instances, do not invoke generic
418   --           actual subprograms through formal subprograms, and the target
419   --           is external to the instance. As a result, the calls are not
420   --           recorded or processed.
421   --
422   --  -gnatd.o conservative elaboration order for indirect calls
423   --
424   --           The ABE mechanism treats '[Unrestricted_]Access of an entry,
425   --           operator, or subprogram as an immediate invocation of the
426   --           target. As a result, it performs ABE checks and diagnostics on
427   --           the immediate call.
428   --
429   --  -gnatd_p ignore assertion pragmas for elaboration
430   --
431   --           The ABE mechanism does not generate N_Call_Marker nodes for
432   --           calls to subprograms which verify the run-time semantics of
433   --           the following assertion pragmas:
434   --
435   --              Default_Initial_Condition
436   --              Initial_Condition
437   --              Invariant
438   --              Invariant'Class
439   --              Post
440   --              Post'Class
441   --              Postcondition
442   --              Type_Invariant
443   --              Type_Invariant_Class
444   --
445   --           As a result, the assertion expressions of the pragmas are not
446   --           processed.
447   --
448   --  -gnatd.U ignore indirect calls for static elaboration
449   --
450   --           The ABE mechanism does not consider '[Unrestricted_]Access of
451   --           entries, operators, and subprograms. As a result, the scenarios
452   --           are not recorder or processed.
453   --
454   --  -gnatd.v enforce SPARK elaboration rules in SPARK code
455   --
456   --           The ABE mechanism applies some of the SPARK elaboration rules
457   --           defined in the SPARK reference manual, chapter 7.7. Note that
458   --           certain rules are always enforced, regardless of whether the
459   --           switch is active.
460   --
461   --  -gnatd.y disable implicit pragma Elaborate_All on task bodies
462   --
463   --           The ABE mechanism does not generate implicit Elaborate_All when
464   --           the need for the pragma came from a task body.
465   --
466   --  -gnatE   dynamic elaboration checking mode enabled
467   --
468   --           The ABE mechanism assumes that any scenario is elaborated or
469   --           invoked by elaboration code. The ABE mechanism performs very
470   --           little diagnostics and generates condintional ABE checks to
471   --           detect ABE issues at run-time.
472   --
473   --  -gnatel  turn on info messages on generated Elaborate[_All] pragmas
474   --
475   --           The ABE mechanism produces information messages on generated
476   --           implicit Elabote[_All] pragmas along with traceback showing
477   --           why the pragma was generated. In addition, the ABE mechanism
478   --           produces information messages for each scenario elaborated or
479   --           invoked by elaboration code.
480   --
481   --  -gnateL  turn off info messages on generated Elaborate[_All] pragmas
482   --
483   --           The complementary switch for -gnatel.
484   --
485   --  -gnatH   legacy elaboration checking mode enabled
486   --
487   --           When this switch is in effect, the pre-18.x ABE model becomes
488   --           the defacto ABE model. This ammounts to cutting off all entry
489   --           points into the new ABE mechanism, and giving full control to
490   --           the old ABE mechanism.
491   --
492   --  -gnatJ   permissive elaboration checking mode enabled
493   --
494   --           This switch activates the following switches:
495   --
496   --              -gnatd_a
497   --              -gnatd_e
498   --              -gnatd.G
499   --              -gnatd_i
500   --              -gnatdL
501   --              -gnatd_p
502   --              -gnatd.U
503   --              -gnatd.y
504   --
505   --           IMPORTANT: The behavior of the ABE mechanism becomes more
506   --           permissive at the cost of accurate diagnostics and runtime
507   --           ABE checks.
508   --
509   --  -gnatw.f turn on warnings for suspicious Subp'Access
510   --
511   --           The ABE mechanism treats '[Unrestricted_]Access of an entry,
512   --           operator, or subprogram as a pseudo invocation of the target.
513   --           As a result, it performs ABE diagnostics on the pseudo call.
514   --
515   --  -gnatw.F turn off warnings for suspicious Subp'Access
516   --
517   --           The complementary switch for -gnatw.f.
518   --
519   --  -gnatwl  turn on warnings for elaboration problems
520   --
521   --           The ABE mechanism produces warnings on detected ABEs along with
522   --           a traceback showing the graph of the ABE.
523   --
524   --  -gnatwL  turn off warnings for elaboration problems
525   --
526   --           The complementary switch for -gnatwl.
527
528   ---------------------------
529   -- Adding a new scenario --
530   ---------------------------
531
532   --  The following steps describe how to add a new elaboration scenario and
533   --  preserve the existing architecture. Note that not all of the steps may
534   --  need to be carried out.
535   --
536   --    1) Update predicate Is_Scenario
537   --
538   --    2) Add predicate Is_Suitable_xxx. Include a call to it in predicate
539   --       Is_Suitable_Scenario.
540   --
541   --    3) Update routine Record_Elaboration_Scenario
542   --
543   --    4) Add routine Process_Conditional_ABE_xxx. Include a call to it in
544   --       routine Process_Conditional_ABE.
545   --
546   --    5) Add routine Process_Guaranteed_ABE_xxx. Include a call to it in
547   --       routine Process_Guaranteed_ABE.
548   --
549   --    6) Add routine Check_SPARK_xxx. Include a call to it in routine
550   --       Check_SPARK_Scenario.
551   --
552   --    7) Add routine Info_xxx. Include a call to it in routine
553   --       Process_Conditional_ABE_xxx.
554   --
555   --    8) Add routine Output_xxx. Include a call to it in routine
556   --       Output_Active_Scenarios.
557   --
558   --    9) Add routine Extract_xxx_Attributes
559   --
560   --   10) Update routine Is_Potential_Scenario
561
562   -------------------------
563   -- Adding a new target --
564   -------------------------
565
566   --  The following steps describe how to add a new elaboration target and
567   --  preserve the existing architecture. Note that not all of the steps may
568   --  need to be carried out.
569   --
570   --    1) Add predicate Is_xxx.
571   --
572   --    2) Update the following predicates
573   --
574   --         Is_Ada_Semantic_Target
575   --         Is_Assertion_Pragma_Target
576   --         Is_Bridge_Target
577   --         Is_SPARK_Semantic_Target
578   --
579   --       If necessary, create a new category.
580   --
581   --    3) Update the appropriate Info_xxx routine.
582   --
583   --    4) Update the appropriate Output_xxx routine.
584   --
585   --    5) Update routine Extract_Target_Attributes. If necessary, create a
586   --       new Extract_xxx routine.
587
588   --------------------------
589   -- Debugging ABE issues --
590   --------------------------
591
592   --  * If the issue involves a call, ensure that the call is eligible for ABE
593   --    processing and receives a corresponding call marker. The routines of
594   --    interest are
595   --
596   --      Build_Call_Marker
597   --      Record_Elaboration_Scenario
598
599   --  * If the issue involves an arbitrary scenario, ensure that the scenario
600   --    is either recorded, or is successfully recognized while traversing a
601   --    body. The routines of interest are
602   --
603   --      Record_Elaboration_Scenario
604   --      Process_Conditional_ABE
605   --      Process_Guaranteed_ABE
606   --      Traverse_Body
607
608   --  * If the issue involves a circularity in the elaboration order, examine
609   --    the ALI files and look for the following encodings next to units:
610   --
611   --       E indicates a source Elaborate
612   --
613   --      EA indicates a source Elaborate_All
614   --
615   --      AD indicates an implicit Elaborate_All
616   --
617   --      ED indicates an implicit Elaborate
618   --
619   --    If possible, compare these encodings with those generated by the old
620   --    ABE mechanism. The routines of interest are
621   --
622   --      Ensure_Prior_Elaboration
623
624   ----------------
625   -- Attributes --
626   ----------------
627
628   --  To minimize the amount of code within routines, the ABE mechanism relies
629   --  on "attribute" records to capture relevant information for a scenario or
630   --  a target.
631
632   --  The following type captures relevant attributes which pertain to a call
633
634   type Call_Attributes is record
635      Elab_Checks_OK : Boolean;
636      --  This flag is set when the call has elaboration checks enabled
637
638      Elab_Warnings_OK : Boolean;
639      --  This flag is set when the call has elaboration warnings elabled
640
641      From_Source : Boolean;
642      --  This flag is set when the call comes from source
643
644      Ghost_Mode_Ignore : Boolean;
645      --  This flag is set when the call appears in a region subject to pragma
646      --  Ghost with policy Ignore.
647
648      In_Declarations : Boolean;
649      --  This flag is set when the call appears at the declaration level
650
651      Is_Dispatching : Boolean;
652      --  This flag is set when the call is dispatching
653
654      SPARK_Mode_On : Boolean;
655      --  This flag is set when the call appears in a region subject to pragma
656      --  SPARK_Mode with value On.
657   end record;
658
659   --  The following type captures relevant attributes which pertain to the
660   --  prior elaboration of a unit. This type is coupled together with a unit
661   --  to form a key -> value relationship.
662
663   type Elaboration_Attributes is record
664      Source_Pragma : Node_Id;
665      --  This attribute denotes a source Elaborate or Elaborate_All pragma
666      --  which guarantees the prior elaboration of some unit with respect
667      --  to the main unit. The pragma may come from the following contexts:
668
669      --    * The main unit
670      --    * The spec of the main unit (if applicable)
671      --    * Any parent spec of the main unit (if applicable)
672      --    * Any parent subunit of the main unit (if applicable)
673
674      --  The attribute remains Empty if no such pragma is available. Source
675      --  pragmas play a role in satisfying SPARK elaboration requirements.
676
677      With_Clause : Node_Id;
678      --  This attribute denotes an internally generated or source with clause
679      --  for some unit withed by the main unit. With clauses carry flags which
680      --  represent implicit Elaborate or Elaborate_All pragmas. These clauses
681      --  play a role in supplying the elaboration dependencies to binde.
682   end record;
683
684   No_Elaboration_Attributes : constant Elaboration_Attributes :=
685     (Source_Pragma => Empty,
686      With_Clause   => Empty);
687
688   --  The following type captures relevant attributes which pertain to an
689   --  instantiation.
690
691   type Instantiation_Attributes is record
692      Elab_Checks_OK : Boolean;
693      --  This flag is set when the instantiation has elaboration checks
694      --  enabled.
695
696      Elab_Warnings_OK : Boolean;
697      --  This flag is set when the instantiation has elaboration warnings
698      --  enabled.
699
700      Ghost_Mode_Ignore : Boolean;
701      --  This flag is set when the instantiation appears in a region subject
702      --  to pragma Ghost with policy ignore, or starts one such region.
703
704      In_Declarations : Boolean;
705      --  This flag is set when the instantiation appears at the declaration
706      --  level.
707
708      SPARK_Mode_On : Boolean;
709      --  This flag is set when the instantiation appears in a region subject
710      --  to pragma SPARK_Mode with value On, or starts one such region.
711   end record;
712
713   --  The following type captures relevant attributes which pertain to the
714   --  state of the Processing phase.
715
716   type Processing_Attributes is record
717      Suppress_Implicit_Pragmas : Boolean;
718      --  This flag is set when the Processing phase must not generate any
719      --  implicit Elaborate[_All] pragmas.
720
721      Within_Initial_Condition : Boolean;
722      --  This flag is set when the Processing phase is currently examining a
723      --  scenario which was reached from an initial condition procedure.
724
725      Within_Instance : Boolean;
726      --  This flag is set when the Processing phase is currently examining a
727      --  scenario which was reached from a scenario defined in an instance.
728
729      Within_Partial_Finalization : Boolean;
730      --  This flag is set when the Processing phase is currently examining a
731      --  scenario which was reached from a partial finalization procedure.
732
733      Within_Task_Body : Boolean;
734      --  This flag is set when the Processing phase is currently examining a
735      --  scenario which was reached from a task body.
736   end record;
737
738   Initial_State : constant Processing_Attributes :=
739     (Suppress_Implicit_Pragmas   => False,
740      Within_Initial_Condition    => False,
741      Within_Instance             => False,
742      Within_Partial_Finalization => False,
743      Within_Task_Body            => False);
744
745   --  The following type captures relevant attributes which pertain to a
746   --  target.
747
748   type Target_Attributes is record
749      Elab_Checks_OK : Boolean;
750      --  This flag is set when the target has elaboration checks enabled
751
752      From_Source : Boolean;
753      --  This flag is set when the target comes from source
754
755      Ghost_Mode_Ignore : Boolean;
756      --  This flag is set when the target appears in a region subject to
757      --  pragma Ghost with policy ignore, or starts one such region.
758
759      SPARK_Mode_On : Boolean;
760      --  This flag is set when the target appears in a region subject to
761      --  pragma SPARK_Mode with value On, or starts one such region.
762
763      Spec_Decl : Node_Id;
764      --  This attribute denotes the declaration of Spec_Id
765
766      Unit_Id : Entity_Id;
767      --  This attribute denotes the top unit where Spec_Id resides
768
769      --  The semantics of the following attributes depend on the target
770
771      Body_Barf : Node_Id;
772      Body_Decl : Node_Id;
773      Spec_Id   : Entity_Id;
774
775      --  The target is a generic package or a subprogram
776      --
777      --    * Body_Barf - Empty
778      --
779      --    * Body_Decl - This attribute denotes the generic or subprogram
780      --      body.
781      --
782      --    * Spec_Id - This attribute denotes the entity of the generic
783      --      package or subprogram.
784
785      --  The target is a protected entry
786      --
787      --    * Body_Barf - This attribute denotes the body of the barrier
788      --      function if expansion took place, otherwise it is Empty.
789      --
790      --    * Body_Decl - This attribute denotes the body of the procedure
791      --      which emulates the entry if expansion took place, otherwise it
792      --      denotes the body of the protected entry.
793      --
794      --    * Spec_Id - This attribute denotes the entity of the procedure
795      --      which emulates the entry if expansion took place, otherwise it
796      --      denotes the protected entry.
797
798      --  The target is a protected subprogram
799      --
800      --    * Body_Barf - Empty
801      --
802      --    * Body_Decl - This attribute denotes the body of the protected or
803      --      unprotected version of the protected subprogram if expansion took
804      --      place, otherwise it denotes the body of the protected subprogram.
805      --
806      --    * Spec_Id - This attribute denotes the entity of the protected or
807      --      unprotected version of the protected subprogram if expansion took
808      --      place, otherwise it is the entity of the protected subprogram.
809
810      --  The target is a task entry
811      --
812      --    * Body_Barf - Empty
813      --
814      --    * Body_Decl - This attribute denotes the body of the procedure
815      --      which emulates the task body if expansion took place, otherwise
816      --      it denotes the body of the task type.
817      --
818      --    * Spec_Id - This attribute denotes the entity of the procedure
819      --      which emulates the task body if expansion took place, otherwise
820      --      it denotes the entity of the task type.
821   end record;
822
823   --  The following type captures relevant attributes which pertain to a task
824   --  type.
825
826   type Task_Attributes is record
827      Body_Decl : Node_Id;
828      --  This attribute denotes the declaration of the procedure body which
829      --  emulates the behaviour of the task body.
830
831      Elab_Checks_OK : Boolean;
832      --  This flag is set when the task type has elaboration checks enabled
833
834      Ghost_Mode_Ignore : Boolean;
835      --  This flag is set when the task type appears in a region subject to
836      --  pragma Ghost with policy ignore, or starts one such region.
837
838      SPARK_Mode_On : Boolean;
839      --  This flag is set when the task type appears in a region subject to
840      --  pragma SPARK_Mode with value On, or starts one such region.
841
842      Spec_Id : Entity_Id;
843      --  This attribute denotes the entity of the initial declaration of the
844      --  procedure body which emulates the behaviour of the task body.
845
846      Task_Decl : Node_Id;
847      --  This attribute denotes the declaration of the task type
848
849      Unit_Id : Entity_Id;
850      --  This attribute denotes the entity of the compilation unit where the
851      --  task type resides.
852   end record;
853
854   --  The following type captures relevant attributes which pertain to a
855   --  variable.
856
857   type Variable_Attributes is record
858      Unit_Id : Entity_Id;
859      --  This attribute denotes the entity of the compilation unit where the
860      --  variable resides.
861   end record;
862
863   ---------------------
864   -- Data structures --
865   ---------------------
866
867   --  The ABE mechanism employs lists and hash tables to store information
868   --  pertaining to scenarios and targets, as well as the Processing phase.
869   --  The need for data structures comes partly from the size limitation of
870   --  nodes. Note that the use of hash tables is conservative and operations
871   --  are carried out only when a particular hash table has at least one key
872   --  value pair (see xxx_In_Use flags).
873
874   --  The following table stores the early call regions of subprogram bodies
875
876   Early_Call_Regions_Max : constant := 101;
877
878   type Early_Call_Regions_Index is range 0 .. Early_Call_Regions_Max - 1;
879
880   function Early_Call_Regions_Hash
881     (Key : Entity_Id) return Early_Call_Regions_Index;
882   --  Obtain the hash value of entity Key
883
884   Early_Call_Regions_In_Use : Boolean := False;
885   --  This flag determines whether table Early_Call_Regions contains at least
886   --  least one key/value pair.
887
888   Early_Call_Regions_No_Element : constant Node_Id := Empty;
889
890   package Early_Call_Regions is new Simple_HTable
891     (Header_Num => Early_Call_Regions_Index,
892      Element    => Node_Id,
893      No_Element => Early_Call_Regions_No_Element,
894      Key        => Entity_Id,
895      Hash       => Early_Call_Regions_Hash,
896      Equal      => "=");
897
898   --  The following table stores the elaboration status of all units withed by
899   --  the main unit.
900
901   Elaboration_Statuses_Max : constant := 1009;
902
903   type Elaboration_Statuses_Index is range 0 .. Elaboration_Statuses_Max - 1;
904
905   function Elaboration_Statuses_Hash
906     (Key : Entity_Id) return Elaboration_Statuses_Index;
907   --  Obtain the hash value of entity Key
908
909   Elaboration_Statuses_In_Use : Boolean := False;
910   --  This flag flag determines whether table Elaboration_Statuses contains at
911   --  least one key/value pair.
912
913   Elaboration_Statuses_No_Element : constant Elaboration_Attributes :=
914                                       No_Elaboration_Attributes;
915
916   package Elaboration_Statuses is new Simple_HTable
917     (Header_Num => Elaboration_Statuses_Index,
918      Element    => Elaboration_Attributes,
919      No_Element => Elaboration_Statuses_No_Element,
920      Key        => Entity_Id,
921      Hash       => Elaboration_Statuses_Hash,
922      Equal      => "=");
923
924   --  The following table stores a status flag for each SPARK scenario saved
925   --  in table SPARK_Scenarios.
926
927   Recorded_SPARK_Scenarios_Max : constant := 127;
928
929   type Recorded_SPARK_Scenarios_Index is
930     range 0 .. Recorded_SPARK_Scenarios_Max - 1;
931
932   function Recorded_SPARK_Scenarios_Hash
933     (Key : Node_Id) return Recorded_SPARK_Scenarios_Index;
934   --  Obtain the hash value of Key
935
936   Recorded_SPARK_Scenarios_In_Use : Boolean := False;
937   --  This flag flag determines whether table Recorded_SPARK_Scenarios
938   --  contains at least one key/value pair.
939
940   Recorded_SPARK_Scenarios_No_Element : constant Boolean := False;
941
942   package Recorded_SPARK_Scenarios is new Simple_HTable
943     (Header_Num => Recorded_SPARK_Scenarios_Index,
944      Element    => Boolean,
945      No_Element => Recorded_SPARK_Scenarios_No_Element,
946      Key        => Node_Id,
947      Hash       => Recorded_SPARK_Scenarios_Hash,
948      Equal      => "=");
949
950   --  The following table stores a status flag for each top-level scenario
951   --  recorded in table Top_Level_Scenarios.
952
953   Recorded_Top_Level_Scenarios_Max : constant := 503;
954
955   type Recorded_Top_Level_Scenarios_Index is
956     range 0 .. Recorded_Top_Level_Scenarios_Max - 1;
957
958   function Recorded_Top_Level_Scenarios_Hash
959     (Key : Node_Id) return Recorded_Top_Level_Scenarios_Index;
960   --  Obtain the hash value of entity Key
961
962   Recorded_Top_Level_Scenarios_In_Use : Boolean := False;
963   --  This flag flag determines whether table Recorded_Top_Level_Scenarios
964   --  contains at least one key/value pair.
965
966   Recorded_Top_Level_Scenarios_No_Element : constant Boolean := False;
967
968   package Recorded_Top_Level_Scenarios is new Simple_HTable
969     (Header_Num => Recorded_Top_Level_Scenarios_Index,
970      Element    => Boolean,
971      No_Element => Recorded_Top_Level_Scenarios_No_Element,
972      Key        => Node_Id,
973      Hash       => Recorded_Top_Level_Scenarios_Hash,
974      Equal      => "=");
975
976   --  The following table stores all active scenarios in a recursive traversal
977   --  starting from a top-level scenario. This table must be maintained in a
978   --  FIFO fashion.
979
980   package Scenario_Stack is new Table.Table
981     (Table_Component_Type => Node_Id,
982      Table_Index_Type     => Int,
983      Table_Low_Bound      => 1,
984      Table_Initial        => 50,
985      Table_Increment      => 100,
986      Table_Name           => "Scenario_Stack");
987
988   --  The following table stores SPARK scenarios which are not necessarily
989   --  executable during elaboration, but still require elaboration-related
990   --  checks.
991
992   package SPARK_Scenarios is new Table.Table
993     (Table_Component_Type => Node_Id,
994      Table_Index_Type     => Int,
995      Table_Low_Bound      => 1,
996      Table_Initial        => 50,
997      Table_Increment      => 100,
998      Table_Name           => "SPARK_Scenarios");
999
1000   --  The following table stores all top-level scenario saved during the
1001   --  Recording phase. The contents of this table act as traversal roots
1002   --  later in the Processing phase. This table must be maintained in a
1003   --  LIFO fashion.
1004
1005   package Top_Level_Scenarios is new Table.Table
1006     (Table_Component_Type => Node_Id,
1007      Table_Index_Type     => Int,
1008      Table_Low_Bound      => 1,
1009      Table_Initial        => 1000,
1010      Table_Increment      => 100,
1011      Table_Name           => "Top_Level_Scenarios");
1012
1013   --  The following table stores the bodies of all eligible scenarios visited
1014   --  during a traversal starting from a top-level scenario. The contents of
1015   --  this table must be reset upon each new traversal.
1016
1017   Visited_Bodies_Max : constant := 511;
1018
1019   type Visited_Bodies_Index is range 0 .. Visited_Bodies_Max - 1;
1020
1021   function Visited_Bodies_Hash (Key : Node_Id) return Visited_Bodies_Index;
1022   --  Obtain the hash value of node Key
1023
1024   Visited_Bodies_In_Use : Boolean := False;
1025   --  This flag determines whether table Visited_Bodies contains at least one
1026   --  key/value pair.
1027
1028   Visited_Bodies_No_Element : constant Boolean := False;
1029
1030   package Visited_Bodies is new Simple_HTable
1031     (Header_Num => Visited_Bodies_Index,
1032      Element    => Boolean,
1033      No_Element => Visited_Bodies_No_Element,
1034      Key        => Node_Id,
1035      Hash       => Visited_Bodies_Hash,
1036      Equal      => "=");
1037
1038   -----------------------
1039   -- Local subprograms --
1040   -----------------------
1041
1042   --  Multiple local subprograms are utilized to lower the semantic complexity
1043   --  of the Recording and Processing phase.
1044
1045   procedure Check_Preelaborated_Call (Call : Node_Id);
1046   pragma Inline (Check_Preelaborated_Call);
1047   --  Verify that entry, operator, or subprogram call Call does not appear at
1048   --  the library level of a preelaborated unit.
1049
1050   procedure Check_SPARK_Derived_Type (Typ_Decl : Node_Id);
1051   pragma Inline (Check_SPARK_Derived_Type);
1052   --  Verify that the freeze node of a derived type denoted by declaration
1053   --  Typ_Decl is within the early call region of each overriding primitive
1054   --  body that belongs to the derived type (SPARK RM 7.7(8)).
1055
1056   procedure Check_SPARK_Instantiation (Exp_Inst : Node_Id);
1057   pragma Inline (Check_SPARK_Instantiation);
1058   --  Verify that expanded instance Exp_Inst does not precede the generic body
1059   --  it instantiates (SPARK RM 7.7(6)).
1060
1061   procedure Check_SPARK_Model_In_Effect (N : Node_Id);
1062   pragma Inline (Check_SPARK_Model_In_Effect);
1063   --  Determine whether a suitable elaboration model is currently in effect
1064   --  for verifying the SPARK rules of scenario N. Emit a warning if this is
1065   --  not the case.
1066
1067   procedure Check_SPARK_Scenario (N : Node_Id);
1068   pragma Inline (Check_SPARK_Scenario);
1069   --  Top-level dispatcher for verifying SPARK scenarios which are not always
1070   --  executable during elaboration but still need elaboration-related checks.
1071
1072   procedure Check_SPARK_Refined_State_Pragma (N : Node_Id);
1073   pragma Inline (Check_SPARK_Refined_State_Pragma);
1074   --  Verify that each constituent of Refined_State pragma N which belongs to
1075   --  an abstract state mentioned in pragma Initializes has prior elaboration
1076   --  with respect to the main unit (SPARK RM 7.7.1(7)).
1077
1078   function Compilation_Unit (Unit_Id : Entity_Id) return Node_Id;
1079   pragma Inline (Compilation_Unit);
1080   --  Return the N_Compilation_Unit node of unit Unit_Id
1081
1082   function Early_Call_Region (Body_Id : Entity_Id) return Node_Id;
1083   pragma Inline (Early_Call_Region);
1084   --  Return the early call region associated with entry or subprogram body
1085   --  Body_Id. IMPORTANT: This routine does not find the early call region.
1086   --  To compute it, use routine Find_Early_Call_Region.
1087
1088   procedure Elab_Msg_NE
1089     (Msg      : String;
1090      N        : Node_Id;
1091      Id       : Entity_Id;
1092      Info_Msg : Boolean;
1093      In_SPARK : Boolean);
1094   pragma Inline (Elab_Msg_NE);
1095   --  Wrapper around Error_Msg_NE. Emit message Msg concerning arbitrary node
1096   --  N and entity. If flag Info_Msg is set, the routine emits an information
1097   --  message, otherwise it emits an error. If flag In_SPARK is set, then
1098   --  string " in SPARK" is added to the end of the message.
1099
1100   function Elaboration_Status
1101     (Unit_Id : Entity_Id) return Elaboration_Attributes;
1102   pragma Inline (Elaboration_Status);
1103   --  Return the set of elaboration attributes associated with unit Unit_Id
1104
1105   procedure Ensure_Prior_Elaboration
1106     (N        : Node_Id;
1107      Unit_Id  : Entity_Id;
1108      Prag_Nam : Name_Id;
1109      State    : Processing_Attributes);
1110   --  Guarantee the elaboration of unit Unit_Id with respect to the main unit
1111   --  by installing pragma Elaborate or Elaborate_All denoted by Prag_Nam. N
1112   --  denotes the related scenario. State denotes the current state of the
1113   --  Processing phase.
1114
1115   procedure Ensure_Prior_Elaboration_Dynamic
1116     (N        : Node_Id;
1117      Unit_Id  : Entity_Id;
1118      Prag_Nam : Name_Id);
1119   --  Guarantee the elaboration of unit Unit_Id with respect to the main unit
1120   --  by suggesting the use of Elaborate[_All] with name Prag_Nam. N denotes
1121   --  the related scenario.
1122
1123   procedure Ensure_Prior_Elaboration_Static
1124     (N        : Node_Id;
1125      Unit_Id  : Entity_Id;
1126      Prag_Nam : Name_Id);
1127   --  Guarantee the elaboration of unit Unit_Id with respect to the main unit
1128   --  by installing an implicit Elaborate[_All] pragma with name Prag_Nam. N
1129   --  denotes the related scenario.
1130
1131   function Extract_Assignment_Name (Asmt : Node_Id) return Node_Id;
1132   pragma Inline (Extract_Assignment_Name);
1133   --  Obtain the Name attribute of assignment statement Asmt
1134
1135   procedure Extract_Call_Attributes
1136     (Call      : Node_Id;
1137      Target_Id : out Entity_Id;
1138      Attrs     : out Call_Attributes);
1139   pragma Inline (Extract_Call_Attributes);
1140   --  Obtain attributes Attrs associated with call Call. Target_Id is the
1141   --  entity of the call target.
1142
1143   function Extract_Call_Name (Call : Node_Id) return Node_Id;
1144   pragma Inline (Extract_Call_Name);
1145   --  Obtain the Name attribute of entry or subprogram call Call
1146
1147   procedure Extract_Instance_Attributes
1148     (Exp_Inst  : Node_Id;
1149      Inst_Body : out Node_Id;
1150      Inst_Decl : out Node_Id);
1151   pragma Inline (Extract_Instance_Attributes);
1152   --  Obtain body Inst_Body and spec Inst_Decl of expanded instance Exp_Inst
1153
1154   procedure Extract_Instantiation_Attributes
1155     (Exp_Inst : Node_Id;
1156      Inst     : out Node_Id;
1157      Inst_Id  : out Entity_Id;
1158      Gen_Id   : out Entity_Id;
1159      Attrs    : out Instantiation_Attributes);
1160   pragma Inline (Extract_Instantiation_Attributes);
1161   --  Obtain attributes Attrs associated with expanded instantiation Exp_Inst.
1162   --  Inst is the instantiation. Inst_Id is the entity of the instance. Gen_Id
1163   --  is the entity of the generic unit being instantiated.
1164
1165   procedure Extract_Target_Attributes
1166     (Target_Id : Entity_Id;
1167      Attrs     : out Target_Attributes);
1168   --  Obtain attributes Attrs associated with an entry, package, or subprogram
1169   --  denoted by Target_Id.
1170
1171   procedure Extract_Task_Attributes
1172     (Typ   : Entity_Id;
1173      Attrs : out Task_Attributes);
1174   pragma Inline (Extract_Task_Attributes);
1175   --  Obtain attributes Attrs associated with task type Typ
1176
1177   procedure Extract_Variable_Reference_Attributes
1178     (Ref    : Node_Id;
1179      Var_Id : out Entity_Id;
1180      Attrs  : out Variable_Attributes);
1181   pragma Inline (Extract_Variable_Reference_Attributes);
1182   --  Obtain attributes Attrs associated with reference Ref that mentions
1183   --  variable Var_Id.
1184
1185   function Find_Code_Unit (N : Node_Or_Entity_Id) return Entity_Id;
1186   pragma Inline (Find_Code_Unit);
1187   --  Return the code unit which contains arbitrary node or entity N. This
1188   --  is the unit of the file which physically contains the related construct
1189   --  denoted by N except when N is within an instantiation. In that case the
1190   --  unit is that of the top-level instantiation.
1191
1192   function Find_Early_Call_Region
1193     (Body_Decl        : Node_Id;
1194      Assume_Elab_Body : Boolean := False;
1195      Skip_Memoization : Boolean := False) return Node_Id;
1196   --  Find the start of the early call region which belongs to subprogram body
1197   --  Body_Decl as defined in SPARK RM 7.7. The behavior of the routine is to
1198   --  find the early call region, memoize it, and return it, but this behavior
1199   --  can be altered. Flag Assume_Elab_Body should be set when a package spec
1200   --  may lack pragma Elaborate_Body, but the routine must still examine that
1201   --  spec. Flag Skip_Memoization should be set when the routine must avoid
1202   --  memoizing the region.
1203
1204   procedure Find_Elaborated_Units;
1205   --  Populate table Elaboration_Statuses with all units which have prior
1206   --  elaboration with respect to the main unit.
1207
1208   function Find_Enclosing_Instance (N : Node_Id) return Node_Id;
1209   pragma Inline (Find_Enclosing_Instance);
1210   --  Find the declaration or body of the nearest expanded instance which
1211   --  encloses arbitrary node N. Return Empty if no such instance exists.
1212
1213   function Find_Top_Unit (N : Node_Or_Entity_Id) return Entity_Id;
1214   pragma Inline (Find_Top_Unit);
1215   --  Return the top unit which contains arbitrary node or entity N. The unit
1216   --  is obtained by logically unwinding instantiations and subunits when N
1217   --  resides within one.
1218
1219   function Find_Unit_Entity (N : Node_Id) return Entity_Id;
1220   pragma Inline (Find_Unit_Entity);
1221   --  Return the entity of unit N
1222
1223   function First_Formal_Type (Subp_Id : Entity_Id) return Entity_Id;
1224   pragma Inline (First_Formal_Type);
1225   --  Return the type of subprogram Subp_Id's first formal parameter. If the
1226   --  subprogram lacks formal parameters, return Empty.
1227
1228   function Has_Body (Pack_Decl : Node_Id) return Boolean;
1229   --  Determine whether package declaration Pack_Decl has a corresponding body
1230   --  or would eventually have one.
1231
1232   function Has_Prior_Elaboration
1233     (Unit_Id      : Entity_Id;
1234      Context_OK   : Boolean := False;
1235      Elab_Body_OK : Boolean := False;
1236      Same_Unit_OK : Boolean := False) return Boolean;
1237   pragma Inline (Has_Prior_Elaboration);
1238   --  Determine whether unit Unit_Id is elaborated prior to the main unit.
1239   --  If flag Context_OK is set, the routine considers the following case
1240   --  as valid prior elaboration:
1241   --
1242   --    * Unit_Id is in the elaboration context of the main unit
1243   --
1244   --  If flag Elab_Body_OK is set, the routine considers the following case
1245   --  as valid prior elaboration:
1246   --
1247   --    * Unit_Id has pragma Elaborate_Body and is not the main unit
1248   --
1249   --  If flag Same_Unit_OK is set, the routine considers the following cases
1250   --  as valid prior elaboration:
1251   --
1252   --    * Unit_Id is the main unit
1253   --
1254   --    * Unit_Id denotes the spec of the main unit body
1255
1256   function In_External_Instance
1257     (N           : Node_Id;
1258      Target_Decl : Node_Id) return Boolean;
1259   pragma Inline (In_External_Instance);
1260   --  Determine whether a target desctibed by its declaration Target_Decl
1261   --  resides in a package instance which is external to scenario N.
1262
1263   function In_Main_Context (N : Node_Id) return Boolean;
1264   pragma Inline (In_Main_Context);
1265   --  Determine whether arbitrary node N appears within the main compilation
1266   --  unit.
1267
1268   function In_Same_Context
1269     (N1        : Node_Id;
1270      N2        : Node_Id;
1271      Nested_OK : Boolean := False) return Boolean;
1272   --  Determine whether two arbitrary nodes N1 and N2 appear within the same
1273   --  context ignoring enclosing library levels. Nested_OK should be set when
1274   --  the context of N1 can enclose that of N2.
1275
1276   procedure Info_Call
1277     (Call      : Node_Id;
1278      Target_Id : Entity_Id;
1279      Info_Msg  : Boolean;
1280      In_SPARK  : Boolean);
1281   --  Output information concerning call Call which invokes target Target_Id.
1282   --  If flag Info_Msg is set, the routine emits an information message,
1283   --  otherwise it emits an error. If flag In_SPARK is set, then the string
1284   --  " in SPARK" is added to the end of the message.
1285
1286   procedure Info_Instantiation
1287     (Inst     : Node_Id;
1288      Gen_Id   : Entity_Id;
1289      Info_Msg : Boolean;
1290      In_SPARK : Boolean);
1291   pragma Inline (Info_Instantiation);
1292   --  Output information concerning instantiation Inst which instantiates
1293   --  generic unit Gen_Id. If flag Info_Msg is set, the routine emits an
1294   --  information message, otherwise it emits an error. If flag In_SPARK
1295   --  is set, then string " in SPARK" is added to the end of the message.
1296
1297   procedure Info_Variable_Reference
1298     (Ref      : Node_Id;
1299      Var_Id   : Entity_Id;
1300      Info_Msg : Boolean;
1301      In_SPARK : Boolean);
1302   pragma Inline (Info_Variable_Reference);
1303   --  Output information concerning reference Ref which mentions variable
1304   --  Var_Id. If flag Info_Msg is set, the routine emits an information
1305   --  message, otherwise it emits an error. If flag In_SPARK is set, then
1306   --  string " in SPARK" is added to the end of the message.
1307
1308   function Insertion_Node (N : Node_Id; Ins_Nod : Node_Id) return Node_Id;
1309   pragma Inline (Insertion_Node);
1310   --  Obtain the proper insertion node of an ABE check or failure for scenario
1311   --  N and candidate insertion node Ins_Nod.
1312
1313   procedure Install_ABE_Check
1314     (N       : Node_Id;
1315      Id      : Entity_Id;
1316      Ins_Nod : Node_Id);
1317   --  Insert a run-time ABE check for elaboration scenario N which verifies
1318   --  whether arbitrary entity Id is elaborated. The check in inserted prior
1319   --  to node Ins_Nod.
1320
1321   procedure Install_ABE_Check
1322     (N           : Node_Id;
1323      Target_Id   : Entity_Id;
1324      Target_Decl : Node_Id;
1325      Target_Body : Node_Id;
1326      Ins_Nod     : Node_Id);
1327   --  Insert a run-time ABE check for elaboration scenario N which verifies
1328   --  whether target Target_Id with initial declaration Target_Decl and body
1329   --  Target_Body is elaborated. The check is inserted prior to node Ins_Nod.
1330
1331   procedure Install_ABE_Failure (N : Node_Id; Ins_Nod : Node_Id);
1332   --  Insert a Program_Error concerning a guaranteed ABE for elaboration
1333   --  scenario N. The failure is inserted prior to node Node_Id.
1334
1335   function Is_Accept_Alternative_Proc (Id : Entity_Id) return Boolean;
1336   pragma Inline (Is_Accept_Alternative_Proc);
1337   --  Determine whether arbitrary entity Id denotes an internally generated
1338   --  procedure which encapsulates the statements of an accept alternative.
1339
1340   function Is_Activation_Proc (Id : Entity_Id) return Boolean;
1341   pragma Inline (Is_Activation_Proc);
1342   --  Determine whether arbitrary entity Id denotes a runtime procedure in
1343   --  charge with activating tasks.
1344
1345   function Is_Ada_Semantic_Target (Id : Entity_Id) return Boolean;
1346   pragma Inline (Is_Ada_Semantic_Target);
1347   --  Determine whether arbitrary entity Id denodes a source or internally
1348   --  generated subprogram which emulates Ada semantics.
1349
1350   function Is_Assertion_Pragma_Target (Id : Entity_Id) return Boolean;
1351   pragma Inline (Is_Assertion_Pragma_Target);
1352   --  Determine whether arbitrary entity Id denotes a procedure which varifies
1353   --  the run-time semantics of an assertion pragma.
1354
1355   function Is_Bodiless_Subprogram (Subp_Id : Entity_Id) return Boolean;
1356   pragma Inline (Is_Bodiless_Subprogram);
1357   --  Determine whether subprogram Subp_Id will never have a body
1358
1359   function Is_Controlled_Proc
1360     (Subp_Id  : Entity_Id;
1361      Subp_Nam : Name_Id) return Boolean;
1362   pragma Inline (Is_Controlled_Proc);
1363   --  Determine whether subprogram Subp_Id denotes controlled type primitives
1364   --  Adjust, Finalize, or Initialize as denoted by name Subp_Nam.
1365
1366   function Is_Default_Initial_Condition_Proc (Id : Entity_Id) return Boolean;
1367   pragma Inline (Is_Default_Initial_Condition_Proc);
1368   --  Determine whether arbitrary entity Id denotes internally generated
1369   --  routine Default_Initial_Condition.
1370
1371   function Is_Finalizer_Proc (Id : Entity_Id) return Boolean;
1372   pragma Inline (Is_Finalizer_Proc);
1373   --  Determine whether arbitrary entity Id denotes internally generated
1374   --  routine _Finalizer.
1375
1376   function Is_Guaranteed_ABE
1377     (N           : Node_Id;
1378      Target_Decl : Node_Id;
1379      Target_Body : Node_Id) return Boolean;
1380   pragma Inline (Is_Guaranteed_ABE);
1381   --  Determine whether scenario N with a target described by its initial
1382   --  declaration Target_Decl and body Target_Decl results in a guaranteed
1383   --  ABE.
1384
1385   function Is_Initial_Condition_Proc (Id : Entity_Id) return Boolean;
1386   pragma Inline (Is_Initial_Condition_Proc);
1387   --  Determine whether arbitrary entity Id denotes internally generated
1388   --  routine Initial_Condition.
1389
1390   function Is_Initialized (Obj_Decl : Node_Id) return Boolean;
1391   pragma Inline (Is_Initialized);
1392   --  Determine whether object declaration Obj_Decl is initialized
1393
1394   function Is_Invariant_Proc (Id : Entity_Id) return Boolean;
1395   pragma Inline (Is_Invariant_Proc);
1396   --  Determine whether arbitrary entity Id denotes an invariant procedure
1397
1398   function Is_Non_Library_Level_Encapsulator (N : Node_Id) return Boolean;
1399   pragma Inline (Is_Non_Library_Level_Encapsulator);
1400   --  Determine whether arbitrary node N is a non-library encapsulator
1401
1402   function Is_Partial_Invariant_Proc (Id : Entity_Id) return Boolean;
1403   pragma Inline (Is_Partial_Invariant_Proc);
1404   --  Determine whether arbitrary entity Id denotes a partial invariant
1405   --  procedure.
1406
1407   function Is_Postconditions_Proc (Id : Entity_Id) return Boolean;
1408   pragma Inline (Is_Postconditions_Proc);
1409   --  Determine whether arbitrary entity Id denotes internally generated
1410   --  routine _Postconditions.
1411
1412   function Is_Preelaborated_Unit (Id : Entity_Id) return Boolean;
1413   pragma Inline (Is_Preelaborated_Unit);
1414   --  Determine whether arbitrary entity Id denotes a unit which is subject to
1415   --  one of the following pragmas:
1416   --
1417   --    * Preelaborable
1418   --    * Pure
1419   --    * Remote_Call_Interface
1420   --    * Remote_Types
1421   --    * Shared_Passive
1422
1423   function Is_Protected_Entry (Id : Entity_Id) return Boolean;
1424   pragma Inline (Is_Protected_Entry);
1425   --  Determine whether arbitrary entity Id denotes a protected entry
1426
1427   function Is_Protected_Subp (Id : Entity_Id) return Boolean;
1428   pragma Inline (Is_Protected_Subp);
1429   --  Determine whether entity Id denotes a protected subprogram
1430
1431   function Is_Protected_Body_Subp (Id : Entity_Id) return Boolean;
1432   pragma Inline (Is_Protected_Body_Subp);
1433   --  Determine whether entity Id denotes the protected or unprotected version
1434   --  of a protected subprogram.
1435
1436   function Is_Recorded_SPARK_Scenario (N : Node_Id) return Boolean;
1437   pragma Inline (Is_Recorded_SPARK_Scenario);
1438   --  Determine whether arbitrary node N is a recorded SPARK scenario which
1439   --  appears in table SPARK_Scenarios.
1440
1441   function Is_Recorded_Top_Level_Scenario (N : Node_Id) return Boolean;
1442   pragma Inline (Is_Recorded_Top_Level_Scenario);
1443   --  Determine whether arbitrary node N is a recorded top-level scenario
1444   --  which appears in table Top_Level_Scenarios.
1445
1446   function Is_Safe_Activation
1447     (Call      : Node_Id;
1448      Task_Decl : Node_Id) return Boolean;
1449   pragma Inline (Is_Safe_Activation);
1450   --  Determine whether call Call which activates a task object described by
1451   --  declaration Task_Decl is always ABE-safe.
1452
1453   function Is_Safe_Call
1454     (Call         : Node_Id;
1455      Target_Attrs : Target_Attributes) return Boolean;
1456   pragma Inline (Is_Safe_Call);
1457   --  Determine whether call Call which invokes a target described by
1458   --  attributes Target_Attrs is always ABE-safe.
1459
1460   function Is_Safe_Instantiation
1461     (Inst      : Node_Id;
1462      Gen_Attrs : Target_Attributes) return Boolean;
1463   pragma Inline (Is_Safe_Instantiation);
1464   --  Determine whether instance Inst which instantiates a generic unit
1465   --  described by attributes Gen_Attrs is always ABE-safe.
1466
1467   function Is_Same_Unit
1468     (Unit_1 : Entity_Id;
1469      Unit_2 : Entity_Id) return Boolean;
1470   pragma Inline (Is_Same_Unit);
1471   --  Determine whether entities Unit_1 and Unit_2 denote the same unit
1472
1473   function Is_Scenario (N : Node_Id) return Boolean;
1474   pragma Inline (Is_Scenario);
1475   --  Determine whether attribute node N denotes a scenario. The scenario may
1476   --  not necessarily be eligible for ABE processing.
1477
1478   function Is_SPARK_Semantic_Target (Id : Entity_Id) return Boolean;
1479   pragma Inline (Is_SPARK_Semantic_Target);
1480   --  Determine whether arbitrary entity Id nodes a source or internally
1481   --  generated subprogram which emulates SPARK semantics.
1482
1483   function Is_Suitable_Access (N : Node_Id) return Boolean;
1484   pragma Inline (Is_Suitable_Access);
1485   --  Determine whether arbitrary node N denotes a suitable attribute for ABE
1486   --  processing.
1487
1488   function Is_Suitable_Call (N : Node_Id) return Boolean;
1489   pragma Inline (Is_Suitable_Call);
1490   --  Determine whether arbitrary node N denotes a suitable call for ABE
1491   --  processing.
1492
1493   function Is_Suitable_Instantiation (N : Node_Id) return Boolean;
1494   pragma Inline (Is_Suitable_Instantiation);
1495   --  Determine whether arbitrary node N is a suitable instantiation for ABE
1496   --  processing.
1497
1498   function Is_Suitable_Scenario (N : Node_Id) return Boolean;
1499   pragma Inline (Is_Suitable_Scenario);
1500   --  Determine whether arbitrary node N is a suitable scenario for ABE
1501   --  processing.
1502
1503   function Is_Suitable_SPARK_Derived_Type (N : Node_Id) return Boolean;
1504   pragma Inline (Is_Suitable_SPARK_Derived_Type);
1505   --  Determine whether arbitrary node N denotes a suitable derived type
1506   --  declaration for ABE processing using the SPARK rules.
1507
1508   function Is_Suitable_SPARK_Instantiation (N : Node_Id) return Boolean;
1509   pragma Inline (Is_Suitable_SPARK_Instantiation);
1510   --  Determine whether arbitrary node N denotes a suitable instantiation for
1511   --  ABE processing using the SPARK rules.
1512
1513   function Is_Suitable_SPARK_Refined_State_Pragma
1514     (N : Node_Id) return Boolean;
1515   pragma Inline (Is_Suitable_SPARK_Refined_State_Pragma);
1516   --  Determine whether arbitrary node N denotes a suitable Refined_State
1517   --  pragma for ABE processing using the SPARK rules.
1518
1519   function Is_Suitable_Variable_Assignment (N : Node_Id) return Boolean;
1520   pragma Inline (Is_Suitable_Variable_Assignment);
1521   --  Determine whether arbitrary node N denotes a suitable assignment for ABE
1522   --  processing.
1523
1524   function Is_Suitable_Variable_Reference (N : Node_Id) return Boolean;
1525   pragma Inline (Is_Suitable_Variable_Reference);
1526   --  Determine whether arbitrary node N is a suitable variable reference for
1527   --  ABE processing.
1528
1529   function Is_Task_Entry (Id : Entity_Id) return Boolean;
1530   pragma Inline (Is_Task_Entry);
1531   --  Determine whether arbitrary entity Id denotes a task entry
1532
1533   function Is_Up_Level_Target (Target_Decl : Node_Id) return Boolean;
1534   pragma Inline (Is_Up_Level_Target);
1535   --  Determine whether the current root resides at the declaration level. If
1536   --  this is the case, determine whether a target described by declaration
1537   --  Target_Decl is within a context which encloses the current root or is in
1538   --  a different unit.
1539
1540   function Is_Visited_Body (Body_Decl : Node_Id) return Boolean;
1541   pragma Inline (Is_Visited_Body);
1542   --  Determine whether subprogram body Body_Decl is already visited during a
1543   --  recursive traversal started from a top-level scenario.
1544
1545   procedure Meet_Elaboration_Requirement
1546     (N         : Node_Id;
1547      Target_Id : Entity_Id;
1548      Req_Nam   : Name_Id);
1549   --  Determine whether elaboration requirement Req_Nam for scenario N with
1550   --  target Target_Id is met by the context of the main unit using the SPARK
1551   --  rules. Req_Nam must denote either Elaborate or Elaborate_All. Emit an
1552   --  error if this is not the case.
1553
1554   function Non_Private_View (Typ : Entity_Id) return Entity_Id;
1555   pragma Inline (Non_Private_View);
1556   --  Return the full view of private type Typ if available, otherwise return
1557   --  type Typ.
1558
1559   procedure Output_Active_Scenarios (Error_Nod : Node_Id);
1560   --  Output the contents of the active scenario stack from earliest to latest
1561   --  to supplement an earlier error emitted for node Error_Nod.
1562
1563   procedure Pop_Active_Scenario (N : Node_Id);
1564   pragma Inline (Pop_Active_Scenario);
1565   --  Pop the top of the scenario stack. A check is made to ensure that the
1566   --  scenario being removed is the same as N.
1567
1568   generic
1569      with procedure Process_Single_Activation
1570        (Call       : Node_Id;
1571         Call_Attrs : Call_Attributes;
1572         Obj_Id     : Entity_Id;
1573         Task_Attrs : Task_Attributes;
1574         State      : Processing_Attributes);
1575      --  Perform ABE checks and diagnostics for task activation call Call
1576      --  which activates task Obj_Id. Call_Attrs are the attributes of the
1577      --  activation call. Task_Attrs are the attributes of the task type.
1578      --  State is the current state of the Processing phase.
1579
1580   procedure Process_Activation_Generic
1581     (Call       : Node_Id;
1582      Call_Attrs : Call_Attributes;
1583      State      : Processing_Attributes);
1584   --  Perform ABE checks and diagnostics for activation call Call by invoking
1585   --  routine Process_Single_Activation on each task object being activated.
1586   --  Call_Attrs are the attributes of the activation call. State is the
1587   --  current state of the Processing phase.
1588
1589   procedure Process_Conditional_ABE
1590     (N     : Node_Id;
1591      State : Processing_Attributes := Initial_State);
1592   --  Top-level dispatcher for processing of various elaboration scenarios.
1593   --  Perform conditional ABE checks and diagnostics for scenario N. State
1594   --  is the current state of the Processing phase.
1595
1596   procedure Process_Conditional_ABE_Access
1597     (Attr  : Node_Id;
1598      State : Processing_Attributes);
1599   --  Perform ABE checks and diagnostics for 'Access to entry, operator, or
1600   --  subprogram denoted by Attr. State is the current state of the Processing
1601   --  phase.
1602
1603   procedure Process_Conditional_ABE_Activation_Impl
1604     (Call       : Node_Id;
1605      Call_Attrs : Call_Attributes;
1606      Obj_Id     : Entity_Id;
1607      Task_Attrs : Task_Attributes;
1608      State      : Processing_Attributes);
1609   --  Perform common conditional ABE checks and diagnostics for call Call
1610   --  which activates task Obj_Id ignoring the Ada or SPARK rules. Call_Attrs
1611   --  are the attributes of the activation call. Task_Attrs are the attributes
1612   --  of the task type. State is the current state of the Processing phase.
1613
1614   procedure Process_Conditional_ABE_Call
1615     (Call       : Node_Id;
1616      Call_Attrs : Call_Attributes;
1617      Target_Id  : Entity_Id;
1618      State      : Processing_Attributes);
1619   --  Top-level dispatcher for processing of calls. Perform ABE checks and
1620   --  diagnostics for call Call which invokes target Target_Id. Call_Attrs
1621   --  are the attributes of the call. State is the current state of the
1622   --  Processing phase.
1623
1624   procedure Process_Conditional_ABE_Call_Ada
1625     (Call         : Node_Id;
1626      Call_Attrs   : Call_Attributes;
1627      Target_Id    : Entity_Id;
1628      Target_Attrs : Target_Attributes;
1629      State        : Processing_Attributes);
1630   --  Perform ABE checks and diagnostics for call Call which invokes target
1631   --  Target_Id using the Ada rules. Call_Attrs are the attributes of the
1632   --  call. Target_Attrs are attributes of the target. State is the current
1633   --  state of the Processing phase.
1634
1635   procedure Process_Conditional_ABE_Call_SPARK
1636     (Call         : Node_Id;
1637      Target_Id    : Entity_Id;
1638      Target_Attrs : Target_Attributes;
1639      State        : Processing_Attributes);
1640   --  Perform ABE checks and diagnostics for call Call which invokes target
1641   --  Target_Id using the SPARK rules. Target_Attrs denotes the attributes of
1642   --  the target. State is the current state of the Processing phase.
1643
1644   procedure Process_Conditional_ABE_Instantiation
1645     (Exp_Inst : Node_Id;
1646      State    : Processing_Attributes);
1647   --  Top-level dispatcher for processing of instantiations. Perform ABE
1648   --  checks and diagnostics for expanded instantiation Exp_Inst. State is
1649   --  the current state of the Processing phase.
1650
1651   procedure Process_Conditional_ABE_Instantiation_Ada
1652     (Exp_Inst   : Node_Id;
1653      Inst       : Node_Id;
1654      Inst_Attrs : Instantiation_Attributes;
1655      Gen_Id     : Entity_Id;
1656      Gen_Attrs  : Target_Attributes;
1657      State      : Processing_Attributes);
1658   --  Perform ABE checks and diagnostics for expanded instantiation Exp_Inst
1659   --  of generic Gen_Id using the Ada rules. Inst is the instantiation node.
1660   --  Inst_Attrs are the attributes of the instance. Gen_Attrs denotes the
1661   --  attributes of the generic. State is the current state of the Processing
1662   --  phase.
1663
1664   procedure Process_Conditional_ABE_Instantiation_SPARK
1665     (Inst      : Node_Id;
1666      Gen_Id    : Entity_Id;
1667      Gen_Attrs : Target_Attributes;
1668      State     : Processing_Attributes);
1669   --  Perform ABE checks and diagnostics for instantiation Inst of generic
1670   --  Gen_Id using the SPARK rules. Gen_Attrs denotes the attributes of the
1671   --  generic. State is the current state of the Processing phase.
1672
1673   procedure Process_Conditional_ABE_Variable_Assignment (Asmt : Node_Id);
1674   --  Top-level dispatcher for processing of variable assignments. Perform ABE
1675   --  checks and diagnostics for assignment statement Asmt.
1676
1677   procedure Process_Conditional_ABE_Variable_Assignment_Ada
1678     (Asmt   : Node_Id;
1679      Var_Id : Entity_Id);
1680   --  Perform ABE checks and diagnostics for assignment statement Asmt that
1681   --  updates the value of variable Var_Id using the Ada rules.
1682
1683   procedure Process_Conditional_ABE_Variable_Assignment_SPARK
1684     (Asmt   : Node_Id;
1685      Var_Id : Entity_Id);
1686   --  Perform ABE checks and diagnostics for assignment statement Asmt that
1687   --  updates the value of variable Var_Id using the SPARK rules.
1688
1689   procedure Process_Conditional_ABE_Variable_Reference (Ref : Node_Id);
1690   --  Top-level dispatcher for processing of variable references. Perform ABE
1691   --  checks and diagnostics for variable reference Ref.
1692
1693   procedure Process_Conditional_ABE_Variable_Reference_Read
1694     (Ref    : Node_Id;
1695      Var_Id : Entity_Id;
1696      Attrs  : Variable_Attributes);
1697   --  Perform ABE checks and diagnostics for reference Ref described by its
1698   --  attributes Attrs, that reads variable Var_Id.
1699
1700   procedure Process_Guaranteed_ABE (N : Node_Id);
1701   --  Top-level dispatcher for processing of scenarios which result in a
1702   --  guaranteed ABE.
1703
1704   procedure Process_Guaranteed_ABE_Activation_Impl
1705     (Call       : Node_Id;
1706      Call_Attrs : Call_Attributes;
1707      Obj_Id     : Entity_Id;
1708      Task_Attrs : Task_Attributes;
1709      State      : Processing_Attributes);
1710   --  Perform common guaranteed ABE checks and diagnostics for call Call which
1711   --  activates task Obj_Id ignoring the Ada or SPARK rules. Call_Attrs are
1712   --  the attributes of the activation call. Task_Attrs are the attributes of
1713   --  the task type. State is provided for compatibility and is not used.
1714
1715   procedure Process_Guaranteed_ABE_Call
1716     (Call       : Node_Id;
1717      Call_Attrs : Call_Attributes;
1718      Target_Id  : Entity_Id);
1719   --  Perform common guaranteed ABE checks and diagnostics for call Call which
1720   --  invokes target Target_Id ignoring the Ada or SPARK rules. Call_Attrs are
1721   --  the attributes of the call.
1722
1723   procedure Process_Guaranteed_ABE_Instantiation (Exp_Inst : Node_Id);
1724   --  Perform common guaranteed ABE checks and diagnostics for expanded
1725   --  instantiation Exp_Inst of generic Gen_Id ignoring the Ada or SPARK
1726   --  rules.
1727
1728   procedure Push_Active_Scenario (N : Node_Id);
1729   pragma Inline (Push_Active_Scenario);
1730   --  Push scenario N on top of the scenario stack
1731
1732   procedure Record_SPARK_Elaboration_Scenario (N : Node_Id);
1733   pragma Inline (Record_SPARK_Elaboration_Scenario);
1734   --  Save SPARK scenario N in table SPARK_Scenarios for later processing
1735
1736   procedure Reset_Visited_Bodies;
1737   pragma Inline (Reset_Visited_Bodies);
1738   --  Clear the contents of table Visited_Bodies
1739
1740   function Root_Scenario return Node_Id;
1741   pragma Inline (Root_Scenario);
1742   --  Return the top-level scenario which started a recursive search for other
1743   --  scenarios. It is assumed that there is a valid top-level scenario on the
1744   --  active scenario stack.
1745
1746   procedure Set_Early_Call_Region (Body_Id : Entity_Id; Start : Node_Id);
1747   pragma Inline (Set_Early_Call_Region);
1748   --  Associate an early call region with begins at construct Start with entry
1749   --  or subprogram body Body_Id.
1750
1751   procedure Set_Elaboration_Status
1752     (Unit_Id : Entity_Id;
1753      Val     : Elaboration_Attributes);
1754   pragma Inline (Set_Elaboration_Status);
1755   --  Associate an set of elaboration attributes with unit Unit_Id
1756
1757   procedure Set_Is_Recorded_SPARK_Scenario
1758     (N   : Node_Id;
1759      Val : Boolean := True);
1760   pragma Inline (Set_Is_Recorded_SPARK_Scenario);
1761   --  Mark scenario N as being recorded in table SPARK_Scenarios
1762
1763   procedure Set_Is_Recorded_Top_Level_Scenario
1764     (N   : Node_Id;
1765      Val : Boolean := True);
1766   pragma Inline (Set_Is_Recorded_Top_Level_Scenario);
1767   --  Mark scenario N as being recorded in table Top_Level_Scenarios
1768
1769   procedure Set_Is_Visited_Body (Subp_Body : Node_Id);
1770   pragma Inline (Set_Is_Visited_Body);
1771   --  Mark subprogram body Subp_Body as being visited during a recursive
1772   --  traversal started from a top-level scenario.
1773
1774   function Static_Elaboration_Checks return Boolean;
1775   pragma Inline (Static_Elaboration_Checks);
1776   --  Determine whether the static model is in effect
1777
1778   procedure Traverse_Body (N : Node_Id; State : Processing_Attributes);
1779   --  Inspect the declarative and statement lists of subprogram body N for
1780   --  suitable elaboration scenarios and process them. State is the current
1781   --  state of the Processing phase.
1782
1783   procedure Update_Elaboration_Scenario (New_N : Node_Id; Old_N : Node_Id);
1784   pragma Inline (Update_Elaboration_Scenario);
1785   --  Update all relevant internal data structures when scenario Old_N is
1786   --  transformed into scenario New_N by Atree.Rewrite.
1787
1788   -----------------------
1789   -- Build_Call_Marker --
1790   -----------------------
1791
1792   procedure Build_Call_Marker (N : Node_Id) is
1793      function In_External_Context
1794        (Call         : Node_Id;
1795         Target_Attrs : Target_Attributes) return Boolean;
1796      pragma Inline (In_External_Context);
1797      --  Determine whether a target described by attributes Target_Attrs is
1798      --  external to call Call which must reside within an instance.
1799
1800      function In_Premature_Context (Call : Node_Id) return Boolean;
1801      --  Determine whether call Call appears within a premature context
1802
1803      function Is_Bridge_Target (Id : Entity_Id) return Boolean;
1804      pragma Inline (Is_Bridge_Target);
1805      --  Determine whether arbitrary entity Id denotes a bridge target
1806
1807      function Is_Default_Expression (Call : Node_Id) return Boolean;
1808      pragma Inline (Is_Default_Expression);
1809      --  Determine whether call Call acts as the expression of a defaulted
1810      --  parameter within a source call.
1811
1812      function Is_Generic_Formal_Subp (Subp_Id : Entity_Id) return Boolean;
1813      pragma Inline (Is_Generic_Formal_Subp);
1814      --  Determine whether subprogram Subp_Id denotes a generic formal
1815      --  subprogram which appears in the "prologue" of an instantiation.
1816
1817      -------------------------
1818      -- In_External_Context --
1819      -------------------------
1820
1821      function In_External_Context
1822        (Call         : Node_Id;
1823         Target_Attrs : Target_Attributes) return Boolean
1824      is
1825         Inst      : Node_Id;
1826         Inst_Body : Node_Id;
1827         Inst_Decl : Node_Id;
1828
1829      begin
1830         --  Performance note: parent traversal
1831
1832         Inst := Find_Enclosing_Instance (Call);
1833
1834         --  The call appears within an instance
1835
1836         if Present (Inst) then
1837
1838            --  The call comes from the main unit and the target does not
1839
1840            if In_Extended_Main_Code_Unit (Call)
1841              and then not In_Extended_Main_Code_Unit (Target_Attrs.Spec_Decl)
1842            then
1843               return True;
1844
1845            --  Otherwise the target declaration must not appear within the
1846            --  instance spec or body.
1847
1848            else
1849               Extract_Instance_Attributes
1850                 (Exp_Inst  => Inst,
1851                  Inst_Decl => Inst_Decl,
1852                  Inst_Body => Inst_Body);
1853
1854               --  Performance note: parent traversal
1855
1856               return not In_Subtree
1857                            (N     => Target_Attrs.Spec_Decl,
1858                             Root1 => Inst_Decl,
1859                             Root2 => Inst_Body);
1860            end if;
1861         end if;
1862
1863         return False;
1864      end In_External_Context;
1865
1866      --------------------------
1867      -- In_Premature_Context --
1868      --------------------------
1869
1870      function In_Premature_Context (Call : Node_Id) return Boolean is
1871         Par : Node_Id;
1872
1873      begin
1874         --  Climb the parent chain looking for premature contexts
1875
1876         Par := Parent (Call);
1877         while Present (Par) loop
1878
1879            --  Aspect specifications and generic associations are premature
1880            --  contexts because nested calls has not been relocated to their
1881            --  final context.
1882
1883            if Nkind_In (Par, N_Aspect_Specification,
1884                              N_Generic_Association)
1885            then
1886               return True;
1887
1888            --  Prevent the search from going too far
1889
1890            elsif Is_Body_Or_Package_Declaration (Par) then
1891               exit;
1892            end if;
1893
1894            Par := Parent (Par);
1895         end loop;
1896
1897         return False;
1898      end In_Premature_Context;
1899
1900      ----------------------
1901      -- Is_Bridge_Target --
1902      ----------------------
1903
1904      function Is_Bridge_Target (Id : Entity_Id) return Boolean is
1905      begin
1906         return
1907           Is_Accept_Alternative_Proc (Id)
1908             or else Is_Finalizer_Proc (Id)
1909             or else Is_Partial_Invariant_Proc (Id)
1910             or else Is_Postconditions_Proc (Id)
1911             or else Is_TSS (Id, TSS_Deep_Adjust)
1912             or else Is_TSS (Id, TSS_Deep_Finalize)
1913             or else Is_TSS (Id, TSS_Deep_Initialize);
1914      end Is_Bridge_Target;
1915
1916      ---------------------------
1917      -- Is_Default_Expression --
1918      ---------------------------
1919
1920      function Is_Default_Expression (Call : Node_Id) return Boolean is
1921         Outer_Call : constant Node_Id := Parent (Call);
1922         Outer_Nam  : Node_Id;
1923
1924      begin
1925         --  To qualify, the node must appear immediately within a source call
1926         --  which invokes a source target.
1927
1928         if Nkind_In (Outer_Call, N_Entry_Call_Statement,
1929                                  N_Function_Call,
1930                                  N_Procedure_Call_Statement)
1931           and then Comes_From_Source (Outer_Call)
1932         then
1933            Outer_Nam := Extract_Call_Name (Outer_Call);
1934
1935            return
1936              Is_Entity_Name (Outer_Nam)
1937                and then Present (Entity (Outer_Nam))
1938                and then Is_Subprogram_Or_Entry (Entity (Outer_Nam))
1939                and then Comes_From_Source (Entity (Outer_Nam));
1940         end if;
1941
1942         return False;
1943      end Is_Default_Expression;
1944
1945      ----------------------------
1946      -- Is_Generic_Formal_Subp --
1947      ----------------------------
1948
1949      function Is_Generic_Formal_Subp (Subp_Id : Entity_Id) return Boolean is
1950         Subp_Decl : constant Node_Id := Unit_Declaration_Node (Subp_Id);
1951         Context   : constant Node_Id := Parent (Subp_Decl);
1952
1953      begin
1954         --  To qualify, the subprogram must rename a generic actual subprogram
1955         --  where the enclosing context is an instantiation.
1956
1957         return
1958           Nkind (Subp_Decl) = N_Subprogram_Renaming_Declaration
1959             and then not Comes_From_Source (Subp_Decl)
1960             and then Nkind_In (Context, N_Function_Specification,
1961                                         N_Package_Specification,
1962                                         N_Procedure_Specification)
1963             and then Present (Generic_Parent (Context));
1964      end Is_Generic_Formal_Subp;
1965
1966      --  Local variables
1967
1968      Call_Attrs   : Call_Attributes;
1969      Call_Nam     : Node_Id;
1970      Marker       : Node_Id;
1971      Target_Attrs : Target_Attributes;
1972      Target_Id    : Entity_Id;
1973
1974   --  Start of processing for Build_Call_Marker
1975
1976   begin
1977      --  Nothing to do when switch -gnatH (legacy elaboration checking mode
1978      --  enabled) is in effect because the legacy ABE mechanism does not need
1979      --  to carry out this action.
1980
1981      if Legacy_Elaboration_Checks then
1982         return;
1983
1984      --  Nothing to do for ASIS. As a result, ABE checks and diagnostics are
1985      --  not performed in this mode.
1986
1987      elsif ASIS_Mode then
1988         return;
1989
1990      --  Nothing to do when the call is being preanalyzed as the marker will
1991      --  be inserted in the wrong place.
1992
1993      elsif Preanalysis_Active then
1994         return;
1995
1996      --  Nothing to do when the input does not denote a call or a requeue
1997
1998      elsif not Nkind_In (N, N_Entry_Call_Statement,
1999                             N_Function_Call,
2000                             N_Procedure_Call_Statement,
2001                             N_Requeue_Statement)
2002      then
2003         return;
2004
2005      --  Nothing to do when the input denotes entry call or requeue statement,
2006      --  and switch -gnatd_e (ignore entry calls and requeue statements for
2007      --  elaboration) is in effect.
2008
2009      elsif Debug_Flag_Underscore_E
2010        and then Nkind_In (N, N_Entry_Call_Statement, N_Requeue_Statement)
2011      then
2012         return;
2013      end if;
2014
2015      Call_Nam := Extract_Call_Name (N);
2016
2017      --  Nothing to do when the call is erroneous or left in a bad state
2018
2019      if not (Is_Entity_Name (Call_Nam)
2020               and then Present (Entity (Call_Nam))
2021               and then Is_Subprogram_Or_Entry (Entity (Call_Nam)))
2022      then
2023         return;
2024
2025      --  Nothing to do when the call invokes a generic formal subprogram and
2026      --  switch -gnatd.G (ignore calls through generic formal parameters for
2027      --  elaboration) is in effect. This check must be performed with the
2028      --  direct target of the call to avoid the side effects of mapping
2029      --  actuals to formals using renamings.
2030
2031      elsif Debug_Flag_Dot_GG
2032        and then Is_Generic_Formal_Subp (Entity (Call_Nam))
2033      then
2034         return;
2035
2036      --  Nothing to do when the call is analyzed/resolved too early within an
2037      --  intermediate context. This check is saved for last because it incurs
2038      --  a performance penalty.
2039
2040      --  Performance note: parent traversal
2041
2042      elsif In_Premature_Context (N) then
2043         return;
2044      end if;
2045
2046      Extract_Call_Attributes
2047        (Call      => N,
2048         Target_Id => Target_Id,
2049         Attrs     => Call_Attrs);
2050
2051      Extract_Target_Attributes
2052        (Target_Id => Target_Id,
2053         Attrs     => Target_Attrs);
2054
2055      --  Nothing to do when the call appears within the expanded spec or
2056      --  body of an instantiated generic, the call does not invoke a generic
2057      --  formal subprogram, the target is external to the instance, and switch
2058      --  -gnatdL (ignore external calls from instances for elaboration) is in
2059      --  effect.
2060
2061      if Debug_Flag_LL
2062        and then not Is_Generic_Formal_Subp (Entity (Call_Nam))
2063
2064        --  Performance note: parent traversal
2065
2066        and then In_External_Context
2067                   (Call         => N,
2068                    Target_Attrs => Target_Attrs)
2069      then
2070         return;
2071
2072      --  Nothing to do when the call invokes an assertion pragma procedure
2073      --  and switch -gnatd_p (ignore assertion pragmas for elaboration) is
2074      --  in effect.
2075
2076      elsif Debug_Flag_Underscore_P
2077        and then Is_Assertion_Pragma_Target (Target_Id)
2078      then
2079         return;
2080
2081      --  Source calls to source targets are always considered because they
2082      --  reflect the original call graph.
2083
2084      elsif Target_Attrs.From_Source and then Call_Attrs.From_Source then
2085         null;
2086
2087      --  A call to a source function which acts as the default expression in
2088      --  another call requires special detection.
2089
2090      elsif Target_Attrs.From_Source
2091        and then Nkind (N) = N_Function_Call
2092        and then Is_Default_Expression (N)
2093      then
2094         null;
2095
2096      --  The target emulates Ada semantics
2097
2098      elsif Is_Ada_Semantic_Target (Target_Id) then
2099         null;
2100
2101      --  The target acts as a link between scenarios
2102
2103      elsif Is_Bridge_Target (Target_Id) then
2104         null;
2105
2106      --  The target emulates SPARK semantics
2107
2108      elsif Is_SPARK_Semantic_Target (Target_Id) then
2109         null;
2110
2111      --  Otherwise the call is not suitable for ABE processing. This prevents
2112      --  the generation of call markers which will never play a role in ABE
2113      --  diagnostics.
2114
2115      else
2116         return;
2117      end if;
2118
2119      --  At this point it is known that the call will play some role in ABE
2120      --  checks and diagnostics. Create a corresponding call marker in case
2121      --  the original call is heavily transformed by expansion later on.
2122
2123      Marker := Make_Call_Marker (Sloc (N));
2124
2125      --  Inherit the attributes of the original call
2126
2127      Set_Target                    (Marker, Target_Id);
2128      Set_Is_Declaration_Level_Node (Marker, Call_Attrs.In_Declarations);
2129      Set_Is_Dispatching_Call       (Marker, Call_Attrs.Is_Dispatching);
2130      Set_Is_Elaboration_Checks_OK_Node
2131                                    (Marker, Call_Attrs.Elab_Checks_OK);
2132      Set_Is_Elaboration_Warnings_OK_Node
2133                                    (Marker, Call_Attrs.Elab_Warnings_OK);
2134      Set_Is_Ignored_Ghost_Node     (Marker, Call_Attrs.Ghost_Mode_Ignore);
2135      Set_Is_Source_Call            (Marker, Call_Attrs.From_Source);
2136      Set_Is_SPARK_Mode_On_Node     (Marker, Call_Attrs.SPARK_Mode_On);
2137
2138      --  The marker is inserted prior to the original call. This placement has
2139      --  several desirable effects:
2140
2141      --    1) The marker appears in the same context, in close proximity to
2142      --       the call.
2143
2144      --         <marker>
2145      --         <call>
2146
2147      --    2) Inserting the marker prior to the call ensures that an ABE check
2148      --       will take effect prior to the call.
2149
2150      --         <ABE check>
2151      --         <marker>
2152      --         <call>
2153
2154      --    3) The above two properties are preserved even when the call is a
2155      --       function which is subsequently relocated in order to capture its
2156      --       result. Note that if the call is relocated to a new context, the
2157      --       relocated call will receive a marker of its own.
2158
2159      --         <ABE check>
2160      --         <maker>
2161      --         Temp : ... := Func_Call ...;
2162      --         ... Temp ...
2163
2164      --  The insertion must take place even when the call does not occur in
2165      --  the main unit to keep the tree symmetric. This ensures that internal
2166      --  name serialization is consistent in case the call marker causes the
2167      --  tree to transform in some way.
2168
2169      Insert_Action (N, Marker);
2170
2171      --  The marker becomes the "corresponding" scenario for the call. Save
2172      --  the marker for later processing by the ABE phase.
2173
2174      Record_Elaboration_Scenario (Marker);
2175   end Build_Call_Marker;
2176
2177   -------------------------------------
2178   -- Build_Variable_Reference_Marker --
2179   -------------------------------------
2180
2181   procedure Build_Variable_Reference_Marker
2182     (N     : Node_Id;
2183      Read  : Boolean;
2184      Write : Boolean)
2185   is
2186      function In_Pragma (Nod : Node_Id) return Boolean;
2187      --  Determine whether arbitrary node Nod appears within a pragma
2188
2189      ---------------
2190      -- In_Pragma --
2191      ---------------
2192
2193      function In_Pragma (Nod : Node_Id) return Boolean is
2194         Par : Node_Id;
2195
2196      begin
2197         Par := Nod;
2198         while Present (Par) loop
2199            if Nkind (Par) = N_Pragma then
2200               return True;
2201
2202            --  Prevent the search from going too far
2203
2204            elsif Is_Body_Or_Package_Declaration (Par) then
2205               exit;
2206            end if;
2207
2208            Par := Parent (Par);
2209         end loop;
2210
2211         return False;
2212      end In_Pragma;
2213
2214      --  Local variables
2215
2216      Marker    : Node_Id;
2217      Prag      : Node_Id;
2218      Var_Attrs : Variable_Attributes;
2219      Var_Id    : Entity_Id;
2220
2221   --  Start of processing for Build_Variable_Reference_Marker
2222
2223   begin
2224      --  Nothing to do when switch -gnatH (legacy elaboration checking mode
2225      --  enabled) is in effect because the legacy ABE mechanism does not need
2226      --  to carry out this action.
2227
2228      if Legacy_Elaboration_Checks then
2229         return;
2230
2231      --  Nothing to do for ASIS. As a result, ABE checks and diagnostics are
2232      --  not performed in this mode.
2233
2234      elsif ASIS_Mode then
2235         return;
2236
2237      --  Nothing to do when the reference is being preanalyzed as the marker
2238      --  will be inserted in the wrong place.
2239
2240      elsif Preanalysis_Active then
2241         return;
2242
2243      --  Nothing to do when the input does not denote a reference
2244
2245      elsif not Nkind_In (N, N_Expanded_Name, N_Identifier) then
2246         return;
2247
2248      --  Nothing to do for internally-generated references
2249
2250      elsif not Comes_From_Source (N) then
2251         return;
2252
2253      --  Nothing to do when the reference is erroneous, left in a bad state,
2254      --  or does not denote a variable.
2255
2256      elsif not (Present (Entity (N))
2257                  and then Ekind (Entity (N)) = E_Variable
2258                  and then Entity (N) /= Any_Id)
2259      then
2260         return;
2261      end if;
2262
2263      Extract_Variable_Reference_Attributes
2264        (Ref    => N,
2265         Var_Id => Var_Id,
2266         Attrs  => Var_Attrs);
2267
2268      Prag := SPARK_Pragma (Var_Id);
2269
2270      if Comes_From_Source (Var_Id)
2271
2272         --  Both the variable and the reference must appear in SPARK_Mode On
2273         --  regions because this scenario falls under the SPARK rules.
2274
2275         and then Present (Prag)
2276         and then Get_SPARK_Mode_From_Annotation (Prag) = On
2277         and then Is_SPARK_Mode_On_Node (N)
2278
2279         --  The reference must not be considered when it appears in a pragma.
2280         --  If the pragma has run-time semantics, then the reference will be
2281         --  reconsidered once the pragma is expanded.
2282
2283         --  Performance note: parent traversal
2284
2285         and then not In_Pragma (N)
2286      then
2287         null;
2288
2289      --  Otherwise the reference is not suitable for ABE processing. This
2290      --  prevents the generation of variable markers which will never play
2291      --  a role in ABE diagnostics.
2292
2293      else
2294         return;
2295      end if;
2296
2297      --  At this point it is known that the variable reference will play some
2298      --  role in ABE checks and diagnostics. Create a corresponding variable
2299      --  marker in case the original variable reference is folded or optimized
2300      --  away.
2301
2302      Marker := Make_Variable_Reference_Marker (Sloc (N));
2303
2304      --  Inherit the attributes of the original variable reference
2305
2306      Set_Target   (Marker, Var_Id);
2307      Set_Is_Read  (Marker, Read);
2308      Set_Is_Write (Marker, Write);
2309
2310      --  The marker is inserted prior to the original variable reference. The
2311      --  insertion must take place even when the reference does not occur in
2312      --  the main unit to keep the tree symmetric. This ensures that internal
2313      --  name serialization is consistent in case the variable marker causes
2314      --  the tree to transform in some way.
2315
2316      Insert_Action (N, Marker);
2317
2318      --  The marker becomes the "corresponding" scenario for the reference.
2319      --  Save the marker for later processing for the ABE phase.
2320
2321      Record_Elaboration_Scenario (Marker);
2322   end Build_Variable_Reference_Marker;
2323
2324   ---------------------------------
2325   -- Check_Elaboration_Scenarios --
2326   ---------------------------------
2327
2328   procedure Check_Elaboration_Scenarios is
2329   begin
2330      --  Nothing to do when switch -gnatH (legacy elaboration checking mode
2331      --  enabled) is in effect because the legacy ABE mechanism does not need
2332      --  to carry out this action.
2333
2334      if Legacy_Elaboration_Checks then
2335         return;
2336
2337      --  Nothing to do for ASIS. As a result, no ABE checks and diagnostics
2338      --  are performed in this mode.
2339
2340      elsif ASIS_Mode then
2341         return;
2342      end if;
2343
2344      --  Examine the context of the main unit and record all units with prior
2345      --  elaboration with respect to it.
2346
2347      Find_Elaborated_Units;
2348
2349      --  Examine each top-level scenario saved during the Recording phase for
2350      --  conditional ABEs and perform various actions depending on the model
2351      --  in effect. The table of visited bodies is created for each new top-
2352      --  level scenario.
2353
2354      for Index in Top_Level_Scenarios.First .. Top_Level_Scenarios.Last loop
2355         Reset_Visited_Bodies;
2356
2357         Process_Conditional_ABE (Top_Level_Scenarios.Table (Index));
2358      end loop;
2359
2360      --  Examine each SPARK scenario saved during the Recording phase which
2361      --  is not necessarily executable during elaboration, but still requires
2362      --  elaboration-related checks.
2363
2364      for Index in SPARK_Scenarios.First .. SPARK_Scenarios.Last loop
2365         Check_SPARK_Scenario (SPARK_Scenarios.Table (Index));
2366      end loop;
2367   end Check_Elaboration_Scenarios;
2368
2369   ------------------------------
2370   -- Check_Preelaborated_Call --
2371   ------------------------------
2372
2373   procedure Check_Preelaborated_Call (Call : Node_Id) is
2374      function In_Preelaborated_Context (N : Node_Id) return Boolean;
2375      --  Determine whether arbitrary node appears in a preelaborated context
2376
2377      ------------------------------
2378      -- In_Preelaborated_Context --
2379      ------------------------------
2380
2381      function In_Preelaborated_Context (N : Node_Id) return Boolean is
2382         Body_Id : constant Entity_Id := Find_Code_Unit (N);
2383         Spec_Id : constant Entity_Id := Unique_Entity (Body_Id);
2384
2385      begin
2386         --  The node appears within a package body whose corresponding spec is
2387         --  subject to pragma Remote_Call_Interface or Remote_Types. This does
2388         --  not result in a preelaborated context because the package body may
2389         --  be on another machine.
2390
2391         if Ekind (Body_Id) = E_Package_Body
2392           and then Ekind_In (Spec_Id, E_Generic_Package, E_Package)
2393           and then (Is_Remote_Call_Interface (Spec_Id)
2394                      or else Is_Remote_Types (Spec_Id))
2395         then
2396            return False;
2397
2398         --  Otherwise the node appears within a preelaborated context when the
2399         --  associated unit is preelaborated.
2400
2401         else
2402            return Is_Preelaborated_Unit (Spec_Id);
2403         end if;
2404      end In_Preelaborated_Context;
2405
2406      --  Local variables
2407
2408      Call_Attrs : Call_Attributes;
2409      Level      : Enclosing_Level_Kind;
2410      Target_Id  : Entity_Id;
2411
2412   --  Start of processing for Check_Preelaborated_Call
2413
2414   begin
2415      Extract_Call_Attributes
2416        (Call      => Call,
2417         Target_Id => Target_Id,
2418         Attrs     => Call_Attrs);
2419
2420      --  Nothing to do when the call is internally generated because it is
2421      --  assumed that it will never violate preelaboration.
2422
2423      if not Call_Attrs.From_Source then
2424         return;
2425      end if;
2426
2427      --  Performance note: parent traversal
2428
2429      Level := Find_Enclosing_Level (Call);
2430
2431      --  Library-level calls are always considered because they are part of
2432      --  the associated unit's elaboration actions.
2433
2434      if Level in Library_Level then
2435         null;
2436
2437      --  Calls at the library level of a generic package body must be checked
2438      --  because they would render an instantiation illegal if the template is
2439      --  marked as preelaborated. Note that this does not apply to calls at
2440      --  the library level of a generic package spec.
2441
2442      elsif Level = Generic_Package_Body then
2443         null;
2444
2445      --  Otherwise the call does not appear at the proper level and must not
2446      --  be considered for this check.
2447
2448      else
2449         return;
2450      end if;
2451
2452      --  The call appears within a preelaborated unit. Emit a warning only for
2453      --  internal uses, otherwise this is an error.
2454
2455      if In_Preelaborated_Context (Call) then
2456         Error_Msg_Warn := GNAT_Mode;
2457         Error_Msg_N
2458           ("<<non-static call not allowed in preelaborated unit", Call);
2459      end if;
2460   end Check_Preelaborated_Call;
2461
2462   ------------------------------
2463   -- Check_SPARK_Derived_Type --
2464   ------------------------------
2465
2466   procedure Check_SPARK_Derived_Type (Typ_Decl : Node_Id) is
2467      Typ : constant Entity_Id := Defining_Entity (Typ_Decl);
2468
2469      --  NOTE: The routines within Check_SPARK_Derived_Type are intentionally
2470      --  unnested to avoid deep indentation of code.
2471
2472      Stop_Check : exception;
2473      --  This exception is raised when the freeze node violates the placement
2474      --  rules.
2475
2476      procedure Check_Overriding_Primitive
2477        (Prim  : Entity_Id;
2478         FNode : Node_Id);
2479      pragma Inline (Check_Overriding_Primitive);
2480      --  Verify that freeze node FNode is within the early call region of
2481      --  overriding primitive Prim's body.
2482
2483      function Freeze_Node_Location (FNode : Node_Id) return Source_Ptr;
2484      pragma Inline (Freeze_Node_Location);
2485      --  Return a more accurate source location associated with freeze node
2486      --  FNode.
2487
2488      function Precedes_Source_Construct (N : Node_Id) return Boolean;
2489      pragma Inline (Precedes_Source_Construct);
2490      --  Determine whether arbitrary node N appears prior to some source
2491      --  construct.
2492
2493      procedure Suggest_Elaborate_Body
2494        (N         : Node_Id;
2495         Body_Decl : Node_Id;
2496         Error_Nod : Node_Id);
2497      pragma Inline (Suggest_Elaborate_Body);
2498      --  Suggest the use of pragma Elaborate_Body when the pragma will allow
2499      --  for node N to appear within the early call region of subprogram body
2500      --  Body_Decl. The suggestion is attached to Error_Nod as a continuation
2501      --  error.
2502
2503      --------------------------------
2504      -- Check_Overriding_Primitive --
2505      --------------------------------
2506
2507      procedure Check_Overriding_Primitive
2508        (Prim  : Entity_Id;
2509         FNode : Node_Id)
2510      is
2511         Prim_Decl : constant Node_Id := Unit_Declaration_Node (Prim);
2512         Body_Decl : Node_Id;
2513         Body_Id   : Entity_Id;
2514         Region    : Node_Id;
2515
2516      begin
2517         Body_Id := Corresponding_Body (Prim_Decl);
2518
2519         --  Nothing to do when the primitive does not have a corresponding
2520         --  body. This can happen when the unit with the bodies is not the
2521         --  main unit subjected to ABE checks.
2522
2523         if No (Body_Id) then
2524            return;
2525
2526         --  The primitive overrides a parent or progenitor primitive
2527
2528         elsif Present (Overridden_Operation (Prim)) then
2529
2530            --  Nothing to do when overriding an interface primitive happens by
2531            --  inheriting a non-interface primitive as the check would be done
2532            --  on the parent primitive.
2533
2534            if Present (Alias (Prim)) then
2535               return;
2536            end if;
2537
2538         --  Nothing to do when the primitive is not overriding. The body of
2539         --  such a primitive cannot be targeted by a dispatching call which
2540         --  is executable during elaboration, and cannot cause an ABE.
2541
2542         else
2543            return;
2544         end if;
2545
2546         Body_Decl := Unit_Declaration_Node (Body_Id);
2547         Region    := Find_Early_Call_Region (Body_Decl);
2548
2549         --  The freeze node appears prior to the early call region of the
2550         --  primitive body.
2551
2552         --  IMPORTANT: This check must always be performed even when -gnatd.v
2553         --  (enforce SPARK elaboration rules in SPARK code) is not specified
2554         --  because the static model cannot guarantee the absence of ABEs in
2555         --  in the presence of dispatching calls.
2556
2557         if Earlier_In_Extended_Unit (FNode, Region) then
2558            Error_Msg_Node_2 := Prim;
2559            Error_Msg_NE
2560              ("first freezing point of type & must appear within early call "
2561               & "region of primitive body & (SPARK RM 7.7(8))",
2562               Typ_Decl, Typ);
2563
2564            Error_Msg_Sloc := Sloc (Region);
2565            Error_Msg_N ("\region starts #", Typ_Decl);
2566
2567            Error_Msg_Sloc := Sloc (Body_Decl);
2568            Error_Msg_N ("\region ends #", Typ_Decl);
2569
2570            Error_Msg_Sloc := Freeze_Node_Location (FNode);
2571            Error_Msg_N ("\first freezing point #", Typ_Decl);
2572
2573            --  If applicable, suggest the use of pragma Elaborate_Body in the
2574            --  associated package spec.
2575
2576            Suggest_Elaborate_Body
2577              (N         => FNode,
2578               Body_Decl => Body_Decl,
2579               Error_Nod => Typ_Decl);
2580
2581            raise Stop_Check;
2582         end if;
2583      end Check_Overriding_Primitive;
2584
2585      --------------------------
2586      -- Freeze_Node_Location --
2587      --------------------------
2588
2589      function Freeze_Node_Location (FNode : Node_Id) return Source_Ptr is
2590         Context : constant Node_Id    := Parent (FNode);
2591         Loc     : constant Source_Ptr := Sloc (FNode);
2592
2593         Prv_Decls : List_Id;
2594         Vis_Decls : List_Id;
2595
2596      begin
2597         --  In general, the source location of the freeze node is as close as
2598         --  possible to the real freeze point, except when the freeze node is
2599         --  at the "bottom" of a package spec.
2600
2601         if Nkind (Context) = N_Package_Specification then
2602            Prv_Decls := Private_Declarations (Context);
2603            Vis_Decls := Visible_Declarations (Context);
2604
2605            --  The freeze node appears in the private declarations of the
2606            --  package.
2607
2608            if Present (Prv_Decls)
2609              and then List_Containing (FNode) = Prv_Decls
2610            then
2611               null;
2612
2613            --  The freeze node appears in the visible declarations of the
2614            --  package and there are no private declarations.
2615
2616            elsif Present (Vis_Decls)
2617              and then List_Containing (FNode) = Vis_Decls
2618              and then (No (Prv_Decls) or else Is_Empty_List (Prv_Decls))
2619            then
2620               null;
2621
2622            --  Otherwise the freeze node is not in the "last" declarative list
2623            --  of the package. Use the existing source location of the freeze
2624            --  node.
2625
2626            else
2627               return Loc;
2628            end if;
2629
2630            --  The freeze node appears at the "bottom" of the package when it
2631            --  is in the "last" declarative list and is either the last in the
2632            --  list or is followed by internal constructs only. In that case
2633            --  the more appropriate source location is that of the package end
2634            --  label.
2635
2636            if not Precedes_Source_Construct (FNode) then
2637               return Sloc (End_Label (Context));
2638            end if;
2639         end if;
2640
2641         return Loc;
2642      end Freeze_Node_Location;
2643
2644      -------------------------------
2645      -- Precedes_Source_Construct --
2646      -------------------------------
2647
2648      function Precedes_Source_Construct (N : Node_Id) return Boolean is
2649         Decl : Node_Id;
2650
2651      begin
2652         Decl := Next (N);
2653         while Present (Decl) loop
2654            if Comes_From_Source (Decl) then
2655               return True;
2656
2657            --  A generated body for a source expression function is treated as
2658            --  a source construct.
2659
2660            elsif Nkind (Decl) = N_Subprogram_Body
2661              and then Was_Expression_Function (Decl)
2662              and then Comes_From_Source (Original_Node (Decl))
2663            then
2664               return True;
2665            end if;
2666
2667            Next (Decl);
2668         end loop;
2669
2670         return False;
2671      end Precedes_Source_Construct;
2672
2673      ----------------------------
2674      -- Suggest_Elaborate_Body --
2675      ----------------------------
2676
2677      procedure Suggest_Elaborate_Body
2678        (N         : Node_Id;
2679         Body_Decl : Node_Id;
2680         Error_Nod : Node_Id)
2681      is
2682         Unt    : constant Node_Id := Unit (Cunit (Main_Unit));
2683         Region : Node_Id;
2684
2685      begin
2686         --  The suggestion applies only when the subprogram body resides in a
2687         --  compilation package body, and a pragma Elaborate_Body would allow
2688         --  for the node to appear in the early call region of the subprogram
2689         --  body. This implies that all code from the subprogram body up to
2690         --  the node is preelaborable.
2691
2692         if Nkind (Unt) = N_Package_Body then
2693
2694            --  Find the start of the early call region again assuming that the
2695            --  package spec has pragma Elaborate_Body. Note that the internal
2696            --  data structures are intentionally not updated because this is a
2697            --  speculative search.
2698
2699            Region :=
2700              Find_Early_Call_Region
2701                (Body_Decl        => Body_Decl,
2702                 Assume_Elab_Body => True,
2703                 Skip_Memoization => True);
2704
2705            --  If the node appears within the early call region, assuming that
2706            --  the package spec carries pragma Elaborate_Body, then it is safe
2707            --  to suggest the pragma.
2708
2709            if Earlier_In_Extended_Unit (Region, N) then
2710               Error_Msg_Name_1 := Name_Elaborate_Body;
2711               Error_Msg_NE
2712                 ("\consider adding pragma % in spec of unit &",
2713                  Error_Nod, Defining_Entity (Unt));
2714            end if;
2715         end if;
2716      end Suggest_Elaborate_Body;
2717
2718      --  Local variables
2719
2720      FNode : constant Node_Id  := Freeze_Node (Typ);
2721      Prims : constant Elist_Id := Direct_Primitive_Operations (Typ);
2722
2723      Prim_Elmt : Elmt_Id;
2724
2725   --  Start of processing for Check_SPARK_Derived_Type
2726
2727   begin
2728      --  A type should have its freeze node set by the time SPARK scenarios
2729      --  are being verified.
2730
2731      pragma Assert (Present (FNode));
2732
2733      --  Verify that the freeze node of the derived type is within the early
2734      --  call region of each overriding primitive body (SPARK RM 7.7(8)).
2735
2736      if Present (Prims) then
2737         Prim_Elmt := First_Elmt (Prims);
2738         while Present (Prim_Elmt) loop
2739            Check_Overriding_Primitive
2740              (Prim  => Node (Prim_Elmt),
2741               FNode => FNode);
2742
2743            Next_Elmt (Prim_Elmt);
2744         end loop;
2745      end if;
2746
2747   exception
2748      when Stop_Check =>
2749         null;
2750   end Check_SPARK_Derived_Type;
2751
2752   -------------------------------
2753   -- Check_SPARK_Instantiation --
2754   -------------------------------
2755
2756   procedure Check_SPARK_Instantiation (Exp_Inst : Node_Id) is
2757      Gen_Attrs  : Target_Attributes;
2758      Gen_Id     : Entity_Id;
2759      Inst       : Node_Id;
2760      Inst_Attrs : Instantiation_Attributes;
2761      Inst_Id    : Entity_Id;
2762
2763   begin
2764      Extract_Instantiation_Attributes
2765        (Exp_Inst => Exp_Inst,
2766         Inst     => Inst,
2767         Inst_Id  => Inst_Id,
2768         Gen_Id   => Gen_Id,
2769         Attrs    => Inst_Attrs);
2770
2771      Extract_Target_Attributes (Gen_Id, Gen_Attrs);
2772
2773      --  The instantiation and the generic body are both in the main unit
2774
2775      if Present (Gen_Attrs.Body_Decl)
2776        and then In_Extended_Main_Code_Unit (Gen_Attrs.Body_Decl)
2777
2778        --  If the instantiation appears prior to the generic body, then the
2779        --  instantiation is illegal (SPARK RM 7.7(6)).
2780
2781        --  IMPORTANT: This check must always be performed even when -gnatd.v
2782        --  (enforce SPARK elaboration rules in SPARK code) is not specified
2783        --  because the rule prevents use-before-declaration of objects that
2784        --  may precede the generic body.
2785
2786        and then Earlier_In_Extended_Unit (Inst, Gen_Attrs.Body_Decl)
2787      then
2788         Error_Msg_NE ("cannot instantiate & before body seen", Inst, Gen_Id);
2789      end if;
2790   end Check_SPARK_Instantiation;
2791
2792   ---------------------------------
2793   -- Check_SPARK_Model_In_Effect --
2794   ---------------------------------
2795
2796   SPARK_Model_Warning_Posted : Boolean := False;
2797   --  This flag prevents the same SPARK model-related warning from being
2798   --  emitted multiple times.
2799
2800   procedure Check_SPARK_Model_In_Effect (N : Node_Id) is
2801   begin
2802      --  Do not emit the warning multiple times as this creates useless noise
2803
2804      if SPARK_Model_Warning_Posted then
2805         null;
2806
2807      --  SPARK rule verification requires the "strict" static model
2808
2809      elsif Static_Elaboration_Checks and not Relaxed_Elaboration_Checks then
2810         null;
2811
2812      --  Any other combination of models does not guarantee the absence of ABE
2813      --  problems for SPARK rule verification purposes. Note that there is no
2814      --  need to check for the legacy ABE mechanism because the legacy code
2815      --  has its own orthogonal processing for SPARK rules.
2816
2817      else
2818         SPARK_Model_Warning_Posted := True;
2819
2820         Error_Msg_N
2821           ("??SPARK elaboration checks require static elaboration model", N);
2822
2823         if Dynamic_Elaboration_Checks then
2824            Error_Msg_N ("\dynamic elaboration model is in effect", N);
2825         else
2826            pragma Assert (Relaxed_Elaboration_Checks);
2827            Error_Msg_N ("\relaxed elaboration model is in effect", N);
2828         end if;
2829      end if;
2830   end Check_SPARK_Model_In_Effect;
2831
2832   --------------------------
2833   -- Check_SPARK_Scenario --
2834   --------------------------
2835
2836   procedure Check_SPARK_Scenario (N : Node_Id) is
2837   begin
2838      --  Ensure that a suitable elaboration model is in effect for SPARK rule
2839      --  verification.
2840
2841      Check_SPARK_Model_In_Effect (N);
2842
2843      --  Add the current scenario to the stack of active scenarios
2844
2845      Push_Active_Scenario (N);
2846
2847      if Is_Suitable_SPARK_Derived_Type (N) then
2848         Check_SPARK_Derived_Type (N);
2849
2850      elsif Is_Suitable_SPARK_Instantiation (N) then
2851         Check_SPARK_Instantiation (N);
2852
2853      elsif Is_Suitable_SPARK_Refined_State_Pragma (N) then
2854         Check_SPARK_Refined_State_Pragma (N);
2855      end if;
2856
2857      --  Remove the current scenario from the stack of active scenarios once
2858      --  all ABE diagnostics and checks have been performed.
2859
2860      Pop_Active_Scenario (N);
2861   end Check_SPARK_Scenario;
2862
2863   --------------------------------------
2864   -- Check_SPARK_Refined_State_Pragma --
2865   --------------------------------------
2866
2867   procedure Check_SPARK_Refined_State_Pragma (N : Node_Id) is
2868
2869      --  NOTE: The routines within Check_SPARK_Refined_State_Pragma are
2870      --  intentionally unnested to avoid deep indentation of code.
2871
2872      procedure Check_SPARK_Constituent (Constit_Id : Entity_Id);
2873      pragma Inline (Check_SPARK_Constituent);
2874      --  Ensure that a single constituent Constit_Id is elaborated prior to
2875      --  the main unit.
2876
2877      procedure Check_SPARK_Constituents (Constits : Elist_Id);
2878      pragma Inline (Check_SPARK_Constituents);
2879      --  Ensure that all constituents found in list Constits are elaborated
2880      --  prior to the main unit.
2881
2882      procedure Check_SPARK_Initialized_State (State : Node_Id);
2883      pragma Inline (Check_SPARK_Initialized_State);
2884      --  Ensure that the constituents of single abstract state State are
2885      --  elaborated prior to the main unit.
2886
2887      procedure Check_SPARK_Initialized_States (Pack_Id : Entity_Id);
2888      pragma Inline (Check_SPARK_Initialized_States);
2889      --  Ensure that the constituents of all abstract states which appear in
2890      --  the Initializes pragma of package Pack_Id are elaborated prior to the
2891      --  main unit.
2892
2893      -----------------------------
2894      -- Check_SPARK_Constituent --
2895      -----------------------------
2896
2897      procedure Check_SPARK_Constituent (Constit_Id : Entity_Id) is
2898         Prag : Node_Id;
2899
2900      begin
2901         --  Nothing to do for "null" constituents
2902
2903         if Nkind (Constit_Id) = N_Null then
2904            return;
2905
2906         --  Nothing to do for illegal constituents
2907
2908         elsif Error_Posted (Constit_Id) then
2909            return;
2910         end if;
2911
2912         Prag := SPARK_Pragma (Constit_Id);
2913
2914         --  The check applies only when the constituent is subject to pragma
2915         --  SPARK_Mode On.
2916
2917         if Present (Prag)
2918           and then Get_SPARK_Mode_From_Annotation (Prag) = On
2919         then
2920            --  An external constituent of an abstract state which appears in
2921            --  the Initializes pragma of a package spec imposes an Elaborate
2922            --  requirement on the context of the main unit. Determine whether
2923            --  the context has a pragma strong enough to meet the requirement.
2924
2925            --  IMPORTANT: This check is performed only when -gnatd.v (enforce
2926            --  SPARK elaboration rules in SPARK code) is in effect because the
2927            --  static model can ensure the prior elaboration of the unit which
2928            --  contains a constituent by installing implicit Elaborate pragma.
2929
2930            if Debug_Flag_Dot_V then
2931               Meet_Elaboration_Requirement
2932                 (N         => N,
2933                  Target_Id => Constit_Id,
2934                  Req_Nam   => Name_Elaborate);
2935
2936            --  Otherwise ensure that the unit with the external constituent is
2937            --  elaborated prior to the main unit.
2938
2939            else
2940               Ensure_Prior_Elaboration
2941                 (N        => N,
2942                  Unit_Id  => Find_Top_Unit (Constit_Id),
2943                  Prag_Nam => Name_Elaborate,
2944                  State    => Initial_State);
2945            end if;
2946         end if;
2947      end Check_SPARK_Constituent;
2948
2949      ------------------------------
2950      -- Check_SPARK_Constituents --
2951      ------------------------------
2952
2953      procedure Check_SPARK_Constituents (Constits : Elist_Id) is
2954         Constit_Elmt : Elmt_Id;
2955
2956      begin
2957         if Present (Constits) then
2958            Constit_Elmt := First_Elmt (Constits);
2959            while Present (Constit_Elmt) loop
2960               Check_SPARK_Constituent (Node (Constit_Elmt));
2961               Next_Elmt (Constit_Elmt);
2962            end loop;
2963         end if;
2964      end Check_SPARK_Constituents;
2965
2966      -----------------------------------
2967      -- Check_SPARK_Initialized_State --
2968      -----------------------------------
2969
2970      procedure Check_SPARK_Initialized_State (State : Node_Id) is
2971         Prag     : Node_Id;
2972         State_Id : Entity_Id;
2973
2974      begin
2975         --  Nothing to do for "null" initialization items
2976
2977         if Nkind (State) = N_Null then
2978            return;
2979
2980         --  Nothing to do for illegal states
2981
2982         elsif Error_Posted (State) then
2983            return;
2984         end if;
2985
2986         State_Id := Entity_Of (State);
2987
2988         --  Sanitize the state
2989
2990         if No (State_Id) then
2991            return;
2992
2993         elsif Error_Posted (State_Id) then
2994            return;
2995
2996         elsif Ekind (State_Id) /= E_Abstract_State then
2997            return;
2998         end if;
2999
3000         --  The check is performed only when the abstract state is subject to
3001         --  SPARK_Mode On.
3002
3003         Prag := SPARK_Pragma (State_Id);
3004
3005         if Present (Prag)
3006           and then Get_SPARK_Mode_From_Annotation (Prag) = On
3007         then
3008            Check_SPARK_Constituents (Refinement_Constituents (State_Id));
3009         end if;
3010      end Check_SPARK_Initialized_State;
3011
3012      ------------------------------------
3013      -- Check_SPARK_Initialized_States --
3014      ------------------------------------
3015
3016      procedure Check_SPARK_Initialized_States (Pack_Id : Entity_Id) is
3017         Prag  : constant Node_Id := Get_Pragma (Pack_Id, Pragma_Initializes);
3018         Init  : Node_Id;
3019         Inits : Node_Id;
3020
3021      begin
3022         if Present (Prag) then
3023            Inits := Expression (Get_Argument (Prag, Pack_Id));
3024
3025            --  Avoid processing a "null" initialization list. The only other
3026            --  alternative is an aggregate.
3027
3028            if Nkind (Inits) = N_Aggregate then
3029
3030               --  The initialization items appear in list form:
3031               --
3032               --    (state1, state2)
3033
3034               if Present (Expressions (Inits)) then
3035                  Init := First (Expressions (Inits));
3036                  while Present (Init) loop
3037                     Check_SPARK_Initialized_State (Init);
3038                     Next (Init);
3039                  end loop;
3040               end if;
3041
3042               --  The initialization items appear in associated form:
3043               --
3044               --    (state1 => item1,
3045               --     state2 => (item2, item3))
3046
3047               if Present (Component_Associations (Inits)) then
3048                  Init := First (Component_Associations (Inits));
3049                  while Present (Init) loop
3050                     Check_SPARK_Initialized_State (Init);
3051                     Next (Init);
3052                  end loop;
3053               end if;
3054            end if;
3055         end if;
3056      end Check_SPARK_Initialized_States;
3057
3058      --  Local variables
3059
3060      Pack_Body : constant Node_Id := Find_Related_Package_Or_Body (N);
3061
3062   --  Start of processing for Check_SPARK_Refined_State_Pragma
3063
3064   begin
3065      --  Pragma Refined_State must be associated with a package body
3066
3067      pragma Assert
3068        (Present (Pack_Body) and then Nkind (Pack_Body) = N_Package_Body);
3069
3070      --  Verify that each external contitunent of an abstract state mentioned
3071      --  in pragma Initializes is properly elaborated.
3072
3073      Check_SPARK_Initialized_States (Unique_Defining_Entity (Pack_Body));
3074   end Check_SPARK_Refined_State_Pragma;
3075
3076   ----------------------
3077   -- Compilation_Unit --
3078   ----------------------
3079
3080   function Compilation_Unit (Unit_Id : Entity_Id) return Node_Id is
3081      Comp_Unit : Node_Id;
3082
3083   begin
3084      Comp_Unit := Parent (Unit_Id);
3085
3086      --  Handle the case where a concurrent subunit is rewritten as a null
3087      --  statement due to expansion activities.
3088
3089      if Nkind (Comp_Unit) = N_Null_Statement
3090        and then Nkind_In (Original_Node (Comp_Unit), N_Protected_Body,
3091                                                      N_Task_Body)
3092      then
3093         Comp_Unit := Parent (Comp_Unit);
3094         pragma Assert (Nkind (Comp_Unit) = N_Subunit);
3095
3096      --  Otherwise use the declaration node of the unit
3097
3098      else
3099         Comp_Unit := Parent (Unit_Declaration_Node (Unit_Id));
3100      end if;
3101
3102      --  Handle the case where a subprogram instantiation which acts as a
3103      --  compilation unit is expanded into an anonymous package that wraps
3104      --  the instantiated subprogram.
3105
3106      if Nkind (Comp_Unit) = N_Package_Specification
3107        and then Nkind_In (Original_Node (Parent (Comp_Unit)),
3108                           N_Function_Instantiation,
3109                           N_Procedure_Instantiation)
3110      then
3111         Comp_Unit := Parent (Parent (Comp_Unit));
3112
3113      --  Handle the case where the compilation unit is a subunit
3114
3115      elsif Nkind (Comp_Unit) = N_Subunit then
3116         Comp_Unit := Parent (Comp_Unit);
3117      end if;
3118
3119      pragma Assert (Nkind (Comp_Unit) = N_Compilation_Unit);
3120
3121      return Comp_Unit;
3122   end Compilation_Unit;
3123
3124   -----------------------
3125   -- Early_Call_Region --
3126   -----------------------
3127
3128   function Early_Call_Region (Body_Id : Entity_Id) return Node_Id is
3129   begin
3130      pragma Assert (Ekind_In (Body_Id, E_Entry,
3131                                        E_Entry_Family,
3132                                        E_Function,
3133                                        E_Procedure,
3134                                        E_Subprogram_Body));
3135
3136      if Early_Call_Regions_In_Use then
3137         return Early_Call_Regions.Get (Body_Id);
3138      end if;
3139
3140      return Early_Call_Regions_No_Element;
3141   end Early_Call_Region;
3142
3143   -----------------------------
3144   -- Early_Call_Regions_Hash --
3145   -----------------------------
3146
3147   function Early_Call_Regions_Hash
3148     (Key : Entity_Id) return Early_Call_Regions_Index
3149   is
3150   begin
3151      return Early_Call_Regions_Index (Key mod Early_Call_Regions_Max);
3152   end Early_Call_Regions_Hash;
3153
3154   -----------------
3155   -- Elab_Msg_NE --
3156   -----------------
3157
3158   procedure Elab_Msg_NE
3159     (Msg      : String;
3160      N        : Node_Id;
3161      Id       : Entity_Id;
3162      Info_Msg : Boolean;
3163      In_SPARK : Boolean)
3164   is
3165      function Prefix return String;
3166      --  Obtain the prefix of the message
3167
3168      function Suffix return String;
3169      --  Obtain the suffix of the message
3170
3171      ------------
3172      -- Prefix --
3173      ------------
3174
3175      function Prefix return String is
3176      begin
3177         if Info_Msg then
3178            return "info: ";
3179         else
3180            return "";
3181         end if;
3182      end Prefix;
3183
3184      ------------
3185      -- Suffix --
3186      ------------
3187
3188      function Suffix return String is
3189      begin
3190         if In_SPARK then
3191            return " in SPARK";
3192         else
3193            return "";
3194         end if;
3195      end Suffix;
3196
3197   --  Start of processing for Elab_Msg_NE
3198
3199   begin
3200      Error_Msg_NE (Prefix & Msg & Suffix, N, Id);
3201   end Elab_Msg_NE;
3202
3203   ------------------------
3204   -- Elaboration_Status --
3205   ------------------------
3206
3207   function Elaboration_Status
3208     (Unit_Id : Entity_Id) return Elaboration_Attributes
3209   is
3210   begin
3211      if Elaboration_Statuses_In_Use then
3212         return Elaboration_Statuses.Get (Unit_Id);
3213      end if;
3214
3215      return Elaboration_Statuses_No_Element;
3216   end Elaboration_Status;
3217
3218   -------------------------------
3219   -- Elaboration_Statuses_Hash --
3220   -------------------------------
3221
3222   function Elaboration_Statuses_Hash
3223     (Key : Entity_Id) return Elaboration_Statuses_Index
3224   is
3225   begin
3226      return Elaboration_Statuses_Index (Key mod Elaboration_Statuses_Max);
3227   end Elaboration_Statuses_Hash;
3228
3229   ------------------------------
3230   -- Ensure_Prior_Elaboration --
3231   ------------------------------
3232
3233   procedure Ensure_Prior_Elaboration
3234     (N        : Node_Id;
3235      Unit_Id  : Entity_Id;
3236      Prag_Nam : Name_Id;
3237      State    : Processing_Attributes)
3238   is
3239   begin
3240      pragma Assert (Nam_In (Prag_Nam, Name_Elaborate, Name_Elaborate_All));
3241
3242      --  Nothing to do when the caller has suppressed the generation of
3243      --  implicit Elaborate[_All] pragmas.
3244
3245      if State.Suppress_Implicit_Pragmas then
3246         return;
3247
3248      --  Nothing to do when the need for prior elaboration came from a partial
3249      --  finalization routine which occurs in an initialization context. This
3250      --  behaviour parallels that of the old ABE mechanism.
3251
3252      elsif State.Within_Partial_Finalization then
3253         return;
3254
3255      --  Nothing to do when the need for prior elaboration came from a task
3256      --  body and switch -gnatd.y (disable implicit pragma Elaborate_All on
3257      --  task bodies) is in effect.
3258
3259      elsif Debug_Flag_Dot_Y and then State.Within_Task_Body then
3260         return;
3261
3262      --  Nothing to do when the unit is elaborated prior to the main unit.
3263      --  This check must also consider the following cases:
3264
3265      --  * No check is made against the context of the main unit because this
3266      --    is specific to the elaboration model in effect and requires custom
3267      --    handling (see Ensure_xxx_Prior_Elaboration).
3268
3269      --  * Unit_Id is subject to pragma Elaborate_Body. An implicit pragma
3270      --    Elaborate[_All] MUST be generated even though Unit_Id is always
3271      --    elaborated prior to the main unit. This is a conservative strategy
3272      --    which ensures that other units withed by Unit_Id will not lead to
3273      --    an ABE.
3274
3275      --      package A is               package body A is
3276      --         procedure ABE;             procedure ABE is ... end ABE;
3277      --      end A;                     end A;
3278
3279      --      with A;
3280      --      package B is               package body B is
3281      --         pragma Elaborate_Body;     procedure Proc is
3282      --                                    begin
3283      --         procedure Proc;               A.ABE;
3284      --      package B;                    end Proc;
3285      --                                 end B;
3286
3287      --      with B;
3288      --      package C is               package body C is
3289      --         ...                        ...
3290      --      end C;                     begin
3291      --                                    B.Proc;
3292      --                                 end C;
3293
3294      --    In the example above, the elaboration of C invokes B.Proc. B is
3295      --    subject to pragma Elaborate_Body. If no pragma Elaborate[_All] is
3296      --    generated for B in C, then the following elaboratio order will lead
3297      --    to an ABE:
3298
3299      --       spec of A elaborated
3300      --       spec of B elaborated
3301      --       body of B elaborated
3302      --       spec of C elaborated
3303      --       body of C elaborated  <--  calls B.Proc which calls A.ABE
3304      --       body of A elaborated  <--  problem
3305
3306      --    The generation of an implicit pragma Elaborate_All (B) ensures that
3307      --    the elaboration order mechanism will not pick the above order.
3308
3309      --    An implicit Elaborate is NOT generated when the unit is subject to
3310      --    Elaborate_Body because both pragmas have the exact same effect.
3311
3312      --  * Unit_Id is the main unit. An implicit pragma Elaborate[_All] MUST
3313      --    NOT be generated in this case because a unit cannot depend on its
3314      --    own elaboration. This case is therefore treated as valid prior
3315      --    elaboration.
3316
3317      elsif Has_Prior_Elaboration
3318              (Unit_Id      => Unit_Id,
3319               Same_Unit_OK => True,
3320               Elab_Body_OK => Prag_Nam = Name_Elaborate)
3321      then
3322         return;
3323
3324      --  Suggest the use of pragma Prag_Nam when the dynamic model is in
3325      --  effect.
3326
3327      elsif Dynamic_Elaboration_Checks then
3328         Ensure_Prior_Elaboration_Dynamic
3329           (N        => N,
3330            Unit_Id  => Unit_Id,
3331            Prag_Nam => Prag_Nam);
3332
3333      --  Install an implicit pragma Prag_Nam when the static model is in
3334      --  effect.
3335
3336      else
3337         pragma Assert (Static_Elaboration_Checks);
3338
3339         Ensure_Prior_Elaboration_Static
3340           (N        => N,
3341            Unit_Id  => Unit_Id,
3342            Prag_Nam => Prag_Nam);
3343      end if;
3344   end Ensure_Prior_Elaboration;
3345
3346   --------------------------------------
3347   -- Ensure_Prior_Elaboration_Dynamic --
3348   --------------------------------------
3349
3350   procedure Ensure_Prior_Elaboration_Dynamic
3351     (N        : Node_Id;
3352      Unit_Id  : Entity_Id;
3353      Prag_Nam : Name_Id)
3354   is
3355      procedure Info_Missing_Pragma;
3356      pragma Inline (Info_Missing_Pragma);
3357      --  Output information concerning missing Elaborate or Elaborate_All
3358      --  pragma with name Prag_Nam for scenario N, which would ensure the
3359      --  prior elaboration of Unit_Id.
3360
3361      -------------------------
3362      -- Info_Missing_Pragma --
3363      -------------------------
3364
3365      procedure Info_Missing_Pragma is
3366      begin
3367         --  Internal units are ignored as they cause unnecessary noise
3368
3369         if not In_Internal_Unit (Unit_Id) then
3370
3371            --  The name of the unit subjected to the elaboration pragma is
3372            --  fully qualified to improve the clarity of the info message.
3373
3374            Error_Msg_Name_1     := Prag_Nam;
3375            Error_Msg_Qual_Level := Nat'Last;
3376
3377            Error_Msg_NE ("info: missing pragma % for unit &", N, Unit_Id);
3378            Error_Msg_Qual_Level := 0;
3379         end if;
3380      end Info_Missing_Pragma;
3381
3382      --  Local variables
3383
3384      Elab_Attrs : Elaboration_Attributes;
3385      Level      : Enclosing_Level_Kind;
3386
3387   --  Start of processing for Ensure_Prior_Elaboration_Dynamic
3388
3389   begin
3390      Elab_Attrs := Elaboration_Status (Unit_Id);
3391
3392      --  Nothing to do when the unit is guaranteed prior elaboration by means
3393      --  of a source Elaborate[_All] pragma.
3394
3395      if Present (Elab_Attrs.Source_Pragma) then
3396         return;
3397      end if;
3398
3399      --  Output extra information on a missing Elaborate[_All] pragma when
3400      --  switch -gnatel (info messages on implicit Elaborate[_All] pragmas
3401      --  is in effect.
3402
3403      if Elab_Info_Messages then
3404
3405         --  Performance note: parent traversal
3406
3407         Level := Find_Enclosing_Level (N);
3408
3409         --  Declaration-level scenario
3410
3411         if (Is_Suitable_Call (N) or else Is_Suitable_Instantiation (N))
3412           and then Level = Declaration_Level
3413         then
3414            null;
3415
3416         --  Library-level scenario
3417
3418         elsif Level in Library_Level then
3419            null;
3420
3421         --  Instantiation library-level scenario
3422
3423         elsif Level = Instantiation then
3424            null;
3425
3426         --  Otherwise the scenario does not appear at the proper level and
3427         --  cannot possibly act as a top-level scenario.
3428
3429         else
3430            return;
3431         end if;
3432
3433         Info_Missing_Pragma;
3434      end if;
3435   end Ensure_Prior_Elaboration_Dynamic;
3436
3437   -------------------------------------
3438   -- Ensure_Prior_Elaboration_Static --
3439   -------------------------------------
3440
3441   procedure Ensure_Prior_Elaboration_Static
3442     (N        : Node_Id;
3443      Unit_Id  : Entity_Id;
3444      Prag_Nam : Name_Id)
3445   is
3446      function Find_With_Clause
3447        (Items     : List_Id;
3448         Withed_Id : Entity_Id) return Node_Id;
3449      pragma Inline (Find_With_Clause);
3450      --  Find a nonlimited with clause in the list of context items Items
3451      --  that withs unit Withed_Id. Return Empty if no such clause is found.
3452
3453      procedure Info_Implicit_Pragma;
3454      pragma Inline (Info_Implicit_Pragma);
3455      --  Output information concerning an implicitly generated Elaborate or
3456      --  Elaborate_All pragma with name Prag_Nam for scenario N which ensures
3457      --  the prior elaboration of unit Unit_Id.
3458
3459      ----------------------
3460      -- Find_With_Clause --
3461      ----------------------
3462
3463      function Find_With_Clause
3464        (Items     : List_Id;
3465         Withed_Id : Entity_Id) return Node_Id
3466      is
3467         Item : Node_Id;
3468
3469      begin
3470         --  Examine the context clauses looking for a suitable with. Note that
3471         --  limited clauses do not affect the elaboration order.
3472
3473         Item := First (Items);
3474         while Present (Item) loop
3475            if Nkind (Item) = N_With_Clause
3476              and then not Error_Posted (Item)
3477              and then not Limited_Present (Item)
3478              and then Entity (Name (Item)) = Withed_Id
3479            then
3480               return Item;
3481            end if;
3482
3483            Next (Item);
3484         end loop;
3485
3486         return Empty;
3487      end Find_With_Clause;
3488
3489      --------------------------
3490      -- Info_Implicit_Pragma --
3491      --------------------------
3492
3493      procedure Info_Implicit_Pragma is
3494      begin
3495         --  Internal units are ignored as they cause unnecessary noise
3496
3497         if not In_Internal_Unit (Unit_Id) then
3498
3499            --  The name of the unit subjected to the elaboration pragma is
3500            --  fully qualified to improve the clarity of the info message.
3501
3502            Error_Msg_Name_1     := Prag_Nam;
3503            Error_Msg_Qual_Level := Nat'Last;
3504
3505            Error_Msg_NE
3506              ("info: implicit pragma % generated for unit &", N, Unit_Id);
3507
3508            Error_Msg_Qual_Level := 0;
3509            Output_Active_Scenarios (N);
3510         end if;
3511      end Info_Implicit_Pragma;
3512
3513      --  Local variables
3514
3515      Main_Cunit : constant Node_Id    := Cunit (Main_Unit);
3516      Loc        : constant Source_Ptr := Sloc (Main_Cunit);
3517      Unit_Cunit : constant Node_Id    := Compilation_Unit (Unit_Id);
3518
3519      Clause     : Node_Id;
3520      Elab_Attrs : Elaboration_Attributes;
3521      Items      : List_Id;
3522
3523   --  Start of processing for Ensure_Prior_Elaboration_Static
3524
3525   begin
3526      Elab_Attrs := Elaboration_Status (Unit_Id);
3527
3528      --  Nothing to do when the unit is guaranteed prior elaboration by means
3529      --  of a source Elaborate[_All] pragma.
3530
3531      if Present (Elab_Attrs.Source_Pragma) then
3532         return;
3533
3534      --  Nothing to do when the unit has an existing implicit Elaborate[_All]
3535      --  pragma installed by a previous scenario.
3536
3537      elsif Present (Elab_Attrs.With_Clause) then
3538
3539         --  The unit is already guaranteed prior elaboration by means of an
3540         --  implicit Elaborate pragma, however the current scenario imposes
3541         --  a stronger requirement of Elaborate_All. "Upgrade" the existing
3542         --  pragma to match this new requirement.
3543
3544         if Elaborate_Desirable (Elab_Attrs.With_Clause)
3545           and then Prag_Nam = Name_Elaborate_All
3546         then
3547            Set_Elaborate_All_Desirable (Elab_Attrs.With_Clause);
3548            Set_Elaborate_Desirable     (Elab_Attrs.With_Clause, False);
3549         end if;
3550
3551         return;
3552      end if;
3553
3554      --  At this point it is known that the unit has no prior elaboration
3555      --  according to pragmas and hierarchical relationships.
3556
3557      Items := Context_Items (Main_Cunit);
3558
3559      if No (Items) then
3560         Items := New_List;
3561         Set_Context_Items (Main_Cunit, Items);
3562      end if;
3563
3564      --  Locate the with clause for the unit. Note that there may not be a
3565      --  clause if the unit is visible through a subunit-body, body-spec, or
3566      --  spec-parent relationship.
3567
3568      Clause :=
3569        Find_With_Clause
3570          (Items     => Items,
3571           Withed_Id => Unit_Id);
3572
3573      --  Generate:
3574      --    with Id;
3575
3576      --  Note that adding implicit with clauses is safe because analysis,
3577      --  resolution, and expansion have already taken place and it is not
3578      --  possible to interfere with visibility.
3579
3580      if No (Clause) then
3581         Clause :=
3582           Make_With_Clause (Loc,
3583             Name => New_Occurrence_Of (Unit_Id, Loc));
3584
3585         Set_Implicit_With (Clause);
3586         Set_Library_Unit  (Clause, Unit_Cunit);
3587
3588         Append_To (Items, Clause);
3589      end if;
3590
3591      --  Mark the with clause depending on the pragma required
3592
3593      if Prag_Nam = Name_Elaborate then
3594         Set_Elaborate_Desirable (Clause);
3595      else
3596         Set_Elaborate_All_Desirable (Clause);
3597      end if;
3598
3599      --  The implicit Elaborate[_All] ensures the prior elaboration of the
3600      --  unit. Include the unit in the elaboration context of the main unit.
3601
3602      Set_Elaboration_Status
3603        (Unit_Id => Unit_Id,
3604         Val     => Elaboration_Attributes'(Source_Pragma => Empty,
3605                                            With_Clause   => Clause));
3606
3607      --  Output extra information on an implicit Elaborate[_All] pragma when
3608      --  switch -gnatel (info messages on implicit Elaborate[_All] pragmas is
3609      --  in effect.
3610
3611      if Elab_Info_Messages then
3612         Info_Implicit_Pragma;
3613      end if;
3614   end Ensure_Prior_Elaboration_Static;
3615
3616   -----------------------------
3617   -- Extract_Assignment_Name --
3618   -----------------------------
3619
3620   function Extract_Assignment_Name (Asmt : Node_Id) return Node_Id is
3621      Nam : Node_Id;
3622
3623   begin
3624      Nam := Name (Asmt);
3625
3626      --  When the name denotes an array or record component, find the whole
3627      --  object.
3628
3629      while Nkind_In (Nam, N_Explicit_Dereference,
3630                           N_Indexed_Component,
3631                           N_Selected_Component,
3632                           N_Slice)
3633      loop
3634         Nam := Prefix (Nam);
3635      end loop;
3636
3637      return Nam;
3638   end Extract_Assignment_Name;
3639
3640   -----------------------------
3641   -- Extract_Call_Attributes --
3642   -----------------------------
3643
3644   procedure Extract_Call_Attributes
3645     (Call      : Node_Id;
3646      Target_Id : out Entity_Id;
3647      Attrs     : out Call_Attributes)
3648   is
3649      From_Source     : Boolean;
3650      In_Declarations : Boolean;
3651      Is_Dispatching  : Boolean;
3652
3653   begin
3654      --  Extraction for call markers
3655
3656      if Nkind (Call) = N_Call_Marker then
3657         Target_Id       := Target (Call);
3658         From_Source     := Is_Source_Call (Call);
3659         In_Declarations := Is_Declaration_Level_Node (Call);
3660         Is_Dispatching  := Is_Dispatching_Call (Call);
3661
3662      --  Extraction for entry calls, requeue, and subprogram calls
3663
3664      else
3665         pragma Assert (Nkind_In (Call, N_Entry_Call_Statement,
3666                                        N_Function_Call,
3667                                        N_Procedure_Call_Statement,
3668                                        N_Requeue_Statement));
3669
3670         Target_Id   := Entity (Extract_Call_Name (Call));
3671         From_Source := Comes_From_Source (Call);
3672
3673         --  Performance note: parent traversal
3674
3675         In_Declarations := Find_Enclosing_Level (Call) = Declaration_Level;
3676         Is_Dispatching  :=
3677           Nkind_In (Call, N_Function_Call, N_Procedure_Call_Statement)
3678             and then Present (Controlling_Argument (Call));
3679      end if;
3680
3681      --  Obtain the original entry or subprogram which the target may rename
3682      --  except when the target is an instantiation. In this case the alias
3683      --  is the internally generated subprogram which appears within the the
3684      --  anonymous package created for the instantiation. Such an alias is not
3685      --  a suitable target.
3686
3687      if not (Is_Subprogram (Target_Id)
3688               and then Is_Generic_Instance (Target_Id))
3689      then
3690         Target_Id := Get_Renamed_Entity (Target_Id);
3691      end if;
3692
3693      --  Set all attributes
3694
3695      Attrs.Elab_Checks_OK    := Is_Elaboration_Checks_OK_Node (Call);
3696      Attrs.Elab_Warnings_OK  := Is_Elaboration_Warnings_OK_Node (Call);
3697      Attrs.From_Source       := From_Source;
3698      Attrs.Ghost_Mode_Ignore := Is_Ignored_Ghost_Node (Call);
3699      Attrs.In_Declarations   := In_Declarations;
3700      Attrs.Is_Dispatching    := Is_Dispatching;
3701      Attrs.SPARK_Mode_On     := Is_SPARK_Mode_On_Node (Call);
3702   end Extract_Call_Attributes;
3703
3704   -----------------------
3705   -- Extract_Call_Name --
3706   -----------------------
3707
3708   function Extract_Call_Name (Call : Node_Id) return Node_Id is
3709      Nam : Node_Id;
3710
3711   begin
3712      Nam := Name (Call);
3713
3714      --  When the call invokes an entry family, the name appears as an indexed
3715      --  component.
3716
3717      if Nkind (Nam) = N_Indexed_Component then
3718         Nam := Prefix (Nam);
3719      end if;
3720
3721      --  When the call employs the object.operation form, the name appears as
3722      --  a selected component.
3723
3724      if Nkind (Nam) = N_Selected_Component then
3725         Nam := Selector_Name (Nam);
3726      end if;
3727
3728      return Nam;
3729   end Extract_Call_Name;
3730
3731   ---------------------------------
3732   -- Extract_Instance_Attributes --
3733   ---------------------------------
3734
3735   procedure Extract_Instance_Attributes
3736     (Exp_Inst  : Node_Id;
3737      Inst_Body : out Node_Id;
3738      Inst_Decl : out Node_Id)
3739   is
3740      Body_Id : Entity_Id;
3741
3742   begin
3743      --  Assume that the attributes are unavailable
3744
3745      Inst_Body := Empty;
3746      Inst_Decl := Empty;
3747
3748      --  Generic package or subprogram spec
3749
3750      if Nkind_In (Exp_Inst, N_Package_Declaration,
3751                             N_Subprogram_Declaration)
3752      then
3753         Inst_Decl := Exp_Inst;
3754         Body_Id   := Corresponding_Body (Inst_Decl);
3755
3756         if Present (Body_Id) then
3757            Inst_Body := Unit_Declaration_Node (Body_Id);
3758         end if;
3759
3760      --  Generic package or subprogram body
3761
3762      else
3763         pragma Assert
3764           (Nkind_In (Exp_Inst, N_Package_Body, N_Subprogram_Body));
3765
3766         Inst_Body := Exp_Inst;
3767         Inst_Decl := Unit_Declaration_Node (Corresponding_Spec (Inst_Body));
3768      end if;
3769   end Extract_Instance_Attributes;
3770
3771   --------------------------------------
3772   -- Extract_Instantiation_Attributes --
3773   --------------------------------------
3774
3775   procedure Extract_Instantiation_Attributes
3776     (Exp_Inst : Node_Id;
3777      Inst     : out Node_Id;
3778      Inst_Id  : out Entity_Id;
3779      Gen_Id   : out Entity_Id;
3780      Attrs    : out Instantiation_Attributes)
3781   is
3782   begin
3783      Inst    := Original_Node (Exp_Inst);
3784      Inst_Id := Defining_Entity (Inst);
3785
3786      --  Traverse a possible chain of renamings to obtain the original generic
3787      --  being instantiatied.
3788
3789      Gen_Id := Get_Renamed_Entity (Entity (Name (Inst)));
3790
3791      --  Set all attributes
3792
3793      Attrs.Elab_Checks_OK    := Is_Elaboration_Checks_OK_Node (Inst);
3794      Attrs.Elab_Warnings_OK  := Is_Elaboration_Warnings_OK_Node (Inst);
3795      Attrs.Ghost_Mode_Ignore := Is_Ignored_Ghost_Node (Inst);
3796      Attrs.In_Declarations   := Is_Declaration_Level_Node (Inst);
3797      Attrs.SPARK_Mode_On     := Is_SPARK_Mode_On_Node (Inst);
3798   end Extract_Instantiation_Attributes;
3799
3800   -------------------------------
3801   -- Extract_Target_Attributes --
3802   -------------------------------
3803
3804   procedure Extract_Target_Attributes
3805     (Target_Id : Entity_Id;
3806      Attrs     : out Target_Attributes)
3807   is
3808      procedure Extract_Package_Or_Subprogram_Attributes
3809        (Spec_Id   : out Entity_Id;
3810         Body_Decl : out Node_Id);
3811      --  Obtain the attributes associated with a package or a subprogram.
3812      --  Spec_Id is the package or subprogram. Body_Decl is the declaration
3813      --  of the corresponding package or subprogram body.
3814
3815      procedure Extract_Protected_Entry_Attributes
3816        (Spec_Id   : out Entity_Id;
3817         Body_Decl : out Node_Id;
3818         Body_Barf : out Node_Id);
3819      --  Obtain the attributes associated with a protected entry [family].
3820      --  Spec_Id is the entity of the protected body subprogram. Body_Decl
3821      --  is the declaration of Spec_Id's corresponding body. Body_Barf is
3822      --  the declaration of the barrier function body.
3823
3824      procedure Extract_Protected_Subprogram_Attributes
3825        (Spec_Id   : out Entity_Id;
3826         Body_Decl : out Node_Id);
3827      --  Obtain the attributes associated with a protected subprogram. Formal
3828      --  Spec_Id is the entity of the protected body subprogram. Body_Decl is
3829      --  the declaration of Spec_Id's corresponding body.
3830
3831      procedure Extract_Task_Entry_Attributes
3832        (Spec_Id   : out Entity_Id;
3833         Body_Decl : out Node_Id);
3834      --  Obtain the attributes associated with a task entry [family]. Formal
3835      --  Spec_Id is the entity of the task body procedure. Body_Decl is the
3836      --  declaration of Spec_Id's corresponding body.
3837
3838      ----------------------------------------------
3839      -- Extract_Package_Or_Subprogram_Attributes --
3840      ----------------------------------------------
3841
3842      procedure Extract_Package_Or_Subprogram_Attributes
3843        (Spec_Id   : out Entity_Id;
3844         Body_Decl : out Node_Id)
3845      is
3846         Body_Id   : Entity_Id;
3847         Init_Id   : Entity_Id;
3848         Spec_Decl : Node_Id;
3849
3850      begin
3851         --  Assume that the body is not available
3852
3853         Body_Decl := Empty;
3854         Spec_Id   := Target_Id;
3855
3856         --  For body retrieval purposes, the entity of the initial declaration
3857         --  is that of the spec.
3858
3859         Init_Id := Spec_Id;
3860
3861         --  The only exception to the above is a function which returns a
3862         --  constrained array type in a SPARK-to-C compilation. In this case
3863         --  the function receives a corresponding procedure which has an out
3864         --  parameter. The proper body for ABE checks and diagnostics is that
3865         --  of the procedure.
3866
3867         if Ekind (Init_Id) = E_Function
3868           and then Rewritten_For_C (Init_Id)
3869         then
3870            Init_Id := Corresponding_Procedure (Init_Id);
3871         end if;
3872
3873         --  Extract the attributes of the body
3874
3875         Spec_Decl := Unit_Declaration_Node (Init_Id);
3876
3877         --  The initial declaration is a stand alone subprogram body
3878
3879         if Nkind (Spec_Decl) = N_Subprogram_Body then
3880            Body_Decl := Spec_Decl;
3881
3882         --  Otherwise the package or subprogram has a spec and a completing
3883         --  body.
3884
3885         elsif Nkind_In (Spec_Decl, N_Generic_Package_Declaration,
3886                                    N_Generic_Subprogram_Declaration,
3887                                    N_Package_Declaration,
3888                                    N_Subprogram_Body_Stub,
3889                                    N_Subprogram_Declaration)
3890         then
3891            Body_Id := Corresponding_Body (Spec_Decl);
3892
3893            if Present (Body_Id) then
3894               Body_Decl := Unit_Declaration_Node (Body_Id);
3895            end if;
3896         end if;
3897      end Extract_Package_Or_Subprogram_Attributes;
3898
3899      ----------------------------------------
3900      -- Extract_Protected_Entry_Attributes --
3901      ----------------------------------------
3902
3903      procedure Extract_Protected_Entry_Attributes
3904        (Spec_Id   : out Entity_Id;
3905         Body_Decl : out Node_Id;
3906         Body_Barf : out Node_Id)
3907      is
3908         Barf_Id : Entity_Id;
3909         Body_Id : Entity_Id;
3910
3911      begin
3912         --  Assume that the bodies are not available
3913
3914         Body_Barf := Empty;
3915         Body_Decl := Empty;
3916
3917         --  When the entry [family] has already been expanded, it carries both
3918         --  the procedure which emulates the behavior of the entry [family] as
3919         --  well as the barrier function.
3920
3921         if Present (Protected_Body_Subprogram (Target_Id)) then
3922            Spec_Id := Protected_Body_Subprogram (Target_Id);
3923
3924            --  Extract the attributes of the barrier function
3925
3926            Barf_Id :=
3927              Corresponding_Body
3928                (Unit_Declaration_Node (Barrier_Function (Target_Id)));
3929
3930            if Present (Barf_Id) then
3931               Body_Barf := Unit_Declaration_Node (Barf_Id);
3932            end if;
3933
3934         --  Otherwise no expansion took place
3935
3936         else
3937            Spec_Id := Target_Id;
3938         end if;
3939
3940         --  Extract the attributes of the entry body
3941
3942         Body_Id := Corresponding_Body (Unit_Declaration_Node (Spec_Id));
3943
3944         if Present (Body_Id) then
3945            Body_Decl := Unit_Declaration_Node (Body_Id);
3946         end if;
3947      end Extract_Protected_Entry_Attributes;
3948
3949      ---------------------------------------------
3950      -- Extract_Protected_Subprogram_Attributes --
3951      ---------------------------------------------
3952
3953      procedure Extract_Protected_Subprogram_Attributes
3954        (Spec_Id   : out Entity_Id;
3955         Body_Decl : out Node_Id)
3956      is
3957         Body_Id : Entity_Id;
3958
3959      begin
3960         --  Assume that the body is not available
3961
3962         Body_Decl := Empty;
3963
3964         --  When the protected subprogram has already been expanded, it
3965         --  carries the subprogram which seizes the lock and invokes the
3966         --  original statements.
3967
3968         if Present (Protected_Subprogram (Target_Id)) then
3969            Spec_Id :=
3970              Protected_Body_Subprogram (Protected_Subprogram (Target_Id));
3971
3972         --  Otherwise no expansion took place
3973
3974         else
3975            Spec_Id := Target_Id;
3976         end if;
3977
3978         --  Extract the attributes of the body
3979
3980         Body_Id := Corresponding_Body (Unit_Declaration_Node (Spec_Id));
3981
3982         if Present (Body_Id) then
3983            Body_Decl := Unit_Declaration_Node (Body_Id);
3984         end if;
3985      end Extract_Protected_Subprogram_Attributes;
3986
3987      -----------------------------------
3988      -- Extract_Task_Entry_Attributes --
3989      -----------------------------------
3990
3991      procedure Extract_Task_Entry_Attributes
3992        (Spec_Id   : out Entity_Id;
3993         Body_Decl : out Node_Id)
3994      is
3995         Task_Typ : constant Entity_Id := Non_Private_View (Scope (Target_Id));
3996         Body_Id  : Entity_Id;
3997
3998      begin
3999         --  Assume that the body is not available
4000
4001         Body_Decl := Empty;
4002
4003         --  The the task type has already been expanded, it carries the
4004         --  procedure which emulates the behavior of the task body.
4005
4006         if Present (Task_Body_Procedure (Task_Typ)) then
4007            Spec_Id := Task_Body_Procedure (Task_Typ);
4008
4009         --  Otherwise no expansion took place
4010
4011         else
4012            Spec_Id := Task_Typ;
4013         end if;
4014
4015         --  Extract the attributes of the body
4016
4017         Body_Id := Corresponding_Body (Unit_Declaration_Node (Spec_Id));
4018
4019         if Present (Body_Id) then
4020            Body_Decl := Unit_Declaration_Node (Body_Id);
4021         end if;
4022      end Extract_Task_Entry_Attributes;
4023
4024      --  Local variables
4025
4026      Prag      : constant Node_Id := SPARK_Pragma (Target_Id);
4027      Body_Barf : Node_Id;
4028      Body_Decl : Node_Id;
4029      Spec_Id   : Entity_Id;
4030
4031   --  Start of processing for Extract_Target_Attributes
4032
4033   begin
4034      --  Assume that the body of the barrier function is not available
4035
4036      Body_Barf := Empty;
4037
4038      --  The target is a protected entry [family]
4039
4040      if Is_Protected_Entry (Target_Id) then
4041         Extract_Protected_Entry_Attributes
4042           (Spec_Id   => Spec_Id,
4043            Body_Decl => Body_Decl,
4044            Body_Barf => Body_Barf);
4045
4046      --  The target is a protected subprogram
4047
4048      elsif Is_Protected_Subp (Target_Id)
4049        or else Is_Protected_Body_Subp (Target_Id)
4050      then
4051         Extract_Protected_Subprogram_Attributes
4052           (Spec_Id   => Spec_Id,
4053            Body_Decl => Body_Decl);
4054
4055      --  The target is a task entry [family]
4056
4057      elsif Is_Task_Entry (Target_Id) then
4058         Extract_Task_Entry_Attributes
4059           (Spec_Id   => Spec_Id,
4060            Body_Decl => Body_Decl);
4061
4062      --  Otherwise the target is a package or a subprogram
4063
4064      else
4065         Extract_Package_Or_Subprogram_Attributes
4066           (Spec_Id   => Spec_Id,
4067            Body_Decl => Body_Decl);
4068      end if;
4069
4070      --  Set all attributes
4071
4072      Attrs.Body_Barf         := Body_Barf;
4073      Attrs.Body_Decl         := Body_Decl;
4074      Attrs.Elab_Checks_OK    := Is_Elaboration_Checks_OK_Id (Target_Id);
4075      Attrs.From_Source       := Comes_From_Source (Target_Id);
4076      Attrs.Ghost_Mode_Ignore := Is_Ignored_Ghost_Entity (Target_Id);
4077      Attrs.SPARK_Mode_On     :=
4078        Present (Prag) and then Get_SPARK_Mode_From_Annotation (Prag) = On;
4079      Attrs.Spec_Decl         := Unit_Declaration_Node (Spec_Id);
4080      Attrs.Spec_Id           := Spec_Id;
4081      Attrs.Unit_Id           := Find_Top_Unit (Target_Id);
4082
4083      --  At this point certain attributes should always be available
4084
4085      pragma Assert (Present (Attrs.Spec_Decl));
4086      pragma Assert (Present (Attrs.Spec_Id));
4087      pragma Assert (Present (Attrs.Unit_Id));
4088   end Extract_Target_Attributes;
4089
4090   -----------------------------
4091   -- Extract_Task_Attributes --
4092   -----------------------------
4093
4094   procedure Extract_Task_Attributes
4095     (Typ   : Entity_Id;
4096      Attrs : out Task_Attributes)
4097   is
4098      Task_Typ : constant Entity_Id := Non_Private_View (Typ);
4099
4100      Body_Decl : Node_Id;
4101      Body_Id   : Entity_Id;
4102      Prag      : Node_Id;
4103      Spec_Id   : Entity_Id;
4104
4105   begin
4106      --  Assume that the body of the task procedure is not available
4107
4108      Body_Decl := Empty;
4109
4110      --  The initial declaration is that of the task body procedure
4111
4112      Spec_Id := Get_Task_Body_Procedure (Task_Typ);
4113      Body_Id := Corresponding_Body (Unit_Declaration_Node (Spec_Id));
4114
4115      if Present (Body_Id) then
4116         Body_Decl := Unit_Declaration_Node (Body_Id);
4117      end if;
4118
4119      Prag := SPARK_Pragma (Task_Typ);
4120
4121      --  Set all attributes
4122
4123      Attrs.Body_Decl         := Body_Decl;
4124      Attrs.Elab_Checks_OK    := Is_Elaboration_Checks_OK_Id (Task_Typ);
4125      Attrs.Ghost_Mode_Ignore := Is_Ignored_Ghost_Entity (Task_Typ);
4126      Attrs.SPARK_Mode_On     :=
4127        Present (Prag) and then Get_SPARK_Mode_From_Annotation (Prag) = On;
4128      Attrs.Spec_Id           := Spec_Id;
4129      Attrs.Task_Decl         := Declaration_Node (Task_Typ);
4130      Attrs.Unit_Id           := Find_Top_Unit (Task_Typ);
4131
4132      --  At this point certain attributes should always be available
4133
4134      pragma Assert (Present (Attrs.Spec_Id));
4135      pragma Assert (Present (Attrs.Task_Decl));
4136      pragma Assert (Present (Attrs.Unit_Id));
4137   end Extract_Task_Attributes;
4138
4139   -------------------------------------------
4140   -- Extract_Variable_Reference_Attributes --
4141   -------------------------------------------
4142
4143   procedure Extract_Variable_Reference_Attributes
4144     (Ref    : Node_Id;
4145      Var_Id : out Entity_Id;
4146      Attrs  : out Variable_Attributes)
4147   is
4148      function Get_Renamed_Variable (Id : Entity_Id) return Entity_Id;
4149      --  Obtain the ultimate renamed variable of variable Id
4150
4151      --------------------------
4152      -- Get_Renamed_Variable --
4153      --------------------------
4154
4155      function Get_Renamed_Variable (Id : Entity_Id) return Entity_Id is
4156         Ren_Id : Entity_Id;
4157
4158      begin
4159         Ren_Id := Id;
4160         while Present (Renamed_Entity (Ren_Id))
4161           and then Nkind (Renamed_Entity (Ren_Id)) in N_Entity
4162         loop
4163            Ren_Id := Renamed_Entity (Ren_Id);
4164         end loop;
4165
4166         return Ren_Id;
4167      end Get_Renamed_Variable;
4168
4169   --  Start of processing for Extract_Variable_Reference_Attributes
4170
4171   begin
4172      --  Extraction for variable reference markers
4173
4174      if Nkind (Ref) = N_Variable_Reference_Marker then
4175         Var_Id := Target (Ref);
4176
4177      --  Extraction for expanded names and identifiers
4178
4179      else
4180         Var_Id := Entity (Ref);
4181      end if;
4182
4183      --  Obtain the original variable which the reference mentions
4184
4185      Var_Id        := Get_Renamed_Variable (Var_Id);
4186      Attrs.Unit_Id := Find_Top_Unit (Var_Id);
4187
4188      --  At this point certain attributes should always be available
4189
4190      pragma Assert (Present (Attrs.Unit_Id));
4191   end Extract_Variable_Reference_Attributes;
4192
4193   --------------------
4194   -- Find_Code_Unit --
4195   --------------------
4196
4197   function Find_Code_Unit (N : Node_Or_Entity_Id) return Entity_Id is
4198   begin
4199      return Find_Unit_Entity (Unit (Cunit (Get_Code_Unit (N))));
4200   end Find_Code_Unit;
4201
4202   ----------------------------
4203   -- Find_Early_Call_Region --
4204   ----------------------------
4205
4206   function Find_Early_Call_Region
4207     (Body_Decl        : Node_Id;
4208      Assume_Elab_Body : Boolean := False;
4209      Skip_Memoization : Boolean := False) return Node_Id
4210   is
4211      --  NOTE: The routines within Find_Early_Call_Region are intentionally
4212      --  unnested to avoid deep indentation of code.
4213
4214      ECR_Found : exception;
4215      --  This exception is raised when the early call region has been found
4216
4217      Start : Node_Id := Empty;
4218      --  The start of the early call region. This variable is updated by the
4219      --  various nested routines. Due to the use of exceptions, the variable
4220      --  must be global to the nested routines.
4221
4222      --  The algorithm implemented in this routine attempts to find the early
4223      --  call region of a subprogram body by inspecting constructs in reverse
4224      --  declarative order, while navigating the tree. The algorithm consists
4225      --  of an Inspection phase and an Advancement phase. The pseudocode is as
4226      --  follows:
4227      --
4228      --    loop
4229      --       inspection phase
4230      --       advancement phase
4231      --    end loop
4232      --
4233      --  The infinite loop is terminated by raising exception ECR_Found. The
4234      --  algorithm utilizes two pointers, Curr and Start, to represent the
4235      --  current construct to inspect and the start of the early call region.
4236      --
4237      --  IMPORTANT: The algorithm must maintain the following invariant at all
4238      --  time for it to function properly - a nested construct is entered only
4239      --  when it contains suitable constructs. This guarantees that leaving a
4240      --  nested or encapsulating construct functions properly.
4241      --
4242      --  The Inspection phase determines whether the current construct is non-
4243      --  preelaborable, and if it is, the algorithm terminates.
4244      --
4245      --  The Advancement phase walks the tree in reverse declarative order,
4246      --  while entering and leaving nested and encapsulating constructs. It
4247      --  may also terminate the elaborithm. There are several special cases
4248      --  of advancement.
4249      --
4250      --  1) General case:
4251      --
4252      --    <construct 1>
4253      --     ...
4254      --    <construct N-1>                      <- Curr
4255      --    <construct N>                        <- Start
4256      --    <subprogram body>
4257      --
4258      --  In the general case, a declarative or statement list is traversed in
4259      --  reverse order where Curr is the lead pointer, and Start indicates the
4260      --  last preelaborable construct.
4261      --
4262      --  2) Entering handled bodies
4263      --
4264      --    package body Nested is               <- Curr (2.3)
4265      --       <declarations>                    <- Curr (2.2)
4266      --    begin
4267      --       <statements>                      <- Curr (2.1)
4268      --    end Nested;
4269      --    <construct>                          <- Start
4270      --
4271      --  In this case, the algorithm enters a handled body by starting from
4272      --  the last statement (2.1), or the last declaration (2.2), or the body
4273      --  is consumed (2.3) because it is empty and thus preelaborable.
4274      --
4275      --  3) Entering package declarations
4276      --
4277      --    package Nested is                    <- Curr (2.3)
4278      --       <visible declarations>            <- Curr (2.2)
4279      --    private
4280      --       <private declarations>            <- Curr (2.1)
4281      --    end Nested;
4282      --    <construct>                          <- Start
4283      --
4284      --  In this case, the algorithm enters a package declaration by starting
4285      --  from the last private declaration (2.1), the last visible declaration
4286      --  (2.2), or the package is consumed (2.3) because it is empty and thus
4287      --  preelaborable.
4288      --
4289      --  4) Transitioning from list to list of the same construct
4290      --
4291      --  Certain constructs have two eligible lists. The algorithm must thus
4292      --  transition from the second to the first list when the second list is
4293      --  exhausted.
4294      --
4295      --    declare                              <- Curr (4.2)
4296      --       <declarations>                    <- Curr (4.1)
4297      --    begin
4298      --       <statements>                      <- Start
4299      --    end;
4300      --
4301      --  In this case, the algorithm has exhausted the second list (statements
4302      --  in the example), and continues with the last declaration (4.1) or the
4303      --  construct is consumed (4.2) because it contains only preelaborable
4304      --  code.
4305      --
4306      --  5) Transitioning from list to construct
4307      --
4308      --    tack body Task is                    <- Curr (5.1)
4309      --                                         <- Curr (Empty)
4310      --       <construct 1>                     <- Start
4311      --
4312      --  In this case, the algorithm has exhausted a list, Curr is Empty, and
4313      --  the owner of the list is consumed (5.1).
4314      --
4315      --  6) Transitioning from unit to unit
4316      --
4317      --  A package body with a spec subject to pragma Elaborate_Body extends
4318      --  the possible range of the early call region to the package spec.
4319      --
4320      --    package Pack is                      <- Curr (6.3)
4321      --       pragma Elaborate_Body;            <- Curr (6.2)
4322      --       <visible declarations>            <- Curr (6.2)
4323      --    private
4324      --       <private declarations>            <- Curr (6.1)
4325      --    end Pack;
4326      --
4327      --    package body Pack is                 <- Curr, Start
4328      --
4329      --  In this case, the algorithm has reached a package body compilation
4330      --  unit whose spec is subject to pragma Elaborate_Body, or the caller
4331      --  of the algorithm has specified this behavior. This transition is
4332      --  equivalent to 3).
4333      --
4334      --  7) Transitioning from unit to termination
4335      --
4336      --  Reaching a compilation unit always terminates the algorithm as there
4337      --  are no more lists to examine. This must take 6) into account.
4338      --
4339      --  8) Transitioning from subunit to stub
4340      --
4341      --    package body Pack is separate;       <- Curr (8.1)
4342      --
4343      --    separate (...)
4344      --    package body Pack is                 <- Curr, Start
4345      --
4346      --  Reaching a subunit continues the search from the corresponding stub
4347      --  (8.1).
4348
4349      procedure Advance (Curr : in out Node_Id);
4350      pragma Inline (Advance);
4351      --  Update the Curr and Start pointers depending on their location in the
4352      --  tree to the next eligible construct. This routine raises ECR_Found.
4353
4354      procedure Enter_Handled_Body (Curr : in out Node_Id);
4355      pragma Inline (Enter_Handled_Body);
4356      --  Update the Curr and Start pointers to enter a nested handled body if
4357      --  applicable. This routine raises ECR_Found.
4358
4359      procedure Enter_Package_Declaration (Curr : in out Node_Id);
4360      pragma Inline (Enter_Package_Declaration);
4361      --  Update the Curr and Start pointers to enter a nested package spec if
4362      --  applicable. This routine raises ECR_Found.
4363
4364      function Find_ECR (N : Node_Id) return Node_Id;
4365      pragma Inline (Find_ECR);
4366      --  Find an early call region starting from arbitrary node N
4367
4368      function Has_Suitable_Construct (List : List_Id) return Boolean;
4369      pragma Inline (Has_Suitable_Construct);
4370      --  Determine whether list List contains at least one suitable construct
4371      --  for inclusion into an early call region.
4372
4373      procedure Include (N : Node_Id; Curr : out Node_Id);
4374      pragma Inline (Include);
4375      --  Update the Curr and Start pointers to include arbitrary construct N
4376      --  in the early call region. This routine raises ECR_Found.
4377
4378      function Is_OK_Preelaborable_Construct (N : Node_Id) return Boolean;
4379      pragma Inline (Is_OK_Preelaborable_Construct);
4380      --  Determine whether arbitrary node N denotes a preelaboration-safe
4381      --  construct.
4382
4383      function Is_Suitable_Construct (N : Node_Id) return Boolean;
4384      pragma Inline (Is_Suitable_Construct);
4385      --  Determine whether arbitrary node N denotes a suitable construct for
4386      --  inclusion into the early call region.
4387
4388      procedure Transition_Body_Declarations
4389        (Bod  : Node_Id;
4390         Curr : in out Node_Id);
4391      pragma Inline (Transition_Body_Declarations);
4392      --  Update the Curr and Start pointers when construct Bod denotes a block
4393      --  statement or a suitable body. This routine raises ECR_Found.
4394
4395      procedure Transition_Handled_Statements
4396        (HSS  : Node_Id;
4397         Curr : in out Node_Id);
4398      pragma Inline (Transition_Handled_Statements);
4399      --  Update the Curr and Start pointers when node HSS denotes a handled
4400      --  sequence of statements. This routine raises ECR_Found.
4401
4402      procedure Transition_Spec_Declarations
4403        (Spec : Node_Id;
4404         Curr : in out Node_Id);
4405      pragma Inline (Transition_Spec_Declarations);
4406      --  Update the Curr and Start pointers when construct Spec denotes
4407      --  a concurrent definition or a package spec. This routine raises
4408      --  ECR_Found.
4409
4410      procedure Transition_Unit (Unit : Node_Id; Curr : in out Node_Id);
4411      pragma Inline (Transition_Unit);
4412      --  Update the Curr and Start pointers when node Unit denotes a potential
4413      --  compilation unit. This routine raises ECR_Found.
4414
4415      -------------
4416      -- Advance --
4417      -------------
4418
4419      procedure Advance (Curr : in out Node_Id) is
4420         Context : Node_Id;
4421
4422      begin
4423         --  Curr denotes one of the following cases upon entry into this
4424         --  routine:
4425         --
4426         --    * Empty - There is no current construct when a declarative or a
4427         --      statement list has been exhausted. This does not necessarily
4428         --      indicate that the early call region has been computed as it
4429         --      may still be possible to transition to another list.
4430         --
4431         --    * Encapsulator - The current construct encapsulates declarations
4432         --      and/or statements. This indicates that the early call region
4433         --      may extend within the nested construct.
4434         --
4435         --    * Preelaborable - The current construct is always preelaborable
4436         --      because Find_ECR would not invoke Advance if this was not the
4437         --      case.
4438
4439         --  The current construct is an encapsulator or is preelaborable
4440
4441         if Present (Curr) then
4442
4443            --  Enter encapsulators by inspecting their declarations and/or
4444            --  statements.
4445
4446            if Nkind_In (Curr, N_Block_Statement, N_Package_Body) then
4447               Enter_Handled_Body (Curr);
4448
4449            elsif Nkind (Curr) = N_Package_Declaration then
4450               Enter_Package_Declaration (Curr);
4451
4452            --  Early call regions have a property which can be exploited to
4453            --  optimize the algorithm.
4454            --
4455            --    <preceding subprogram body>
4456            --    <preelaborable construct 1>
4457            --     ...
4458            --    <preelaborable construct N>
4459            --    <initiating subprogram body>
4460            --
4461            --  If a traversal initiated from a subprogram body reaches a
4462            --  preceding subprogram body, then both bodies share the same
4463            --  early call region.
4464            --
4465            --  The property results in the following desirable effects:
4466            --
4467            --  * If the preceding body already has an early call region, then
4468            --    the initiating body can reuse it. This minimizes the amount
4469            --    of processing performed by the algorithm.
4470            --
4471            --  * If the preceding body lack an early call region, then the
4472            --    algorithm can compute the early call region, and reuse it
4473            --    for the initiating body. This processing performs the same
4474            --    amount of work, but has the beneficial effect of computing
4475            --    the early call regions of all preceding bodies.
4476
4477            elsif Nkind_In (Curr, N_Entry_Body, N_Subprogram_Body) then
4478               Start :=
4479                 Find_Early_Call_Region
4480                   (Body_Decl        => Curr,
4481                    Assume_Elab_Body => Assume_Elab_Body,
4482                    Skip_Memoization => Skip_Memoization);
4483
4484               raise ECR_Found;
4485
4486            --  Otherwise current construct is preelaborable. Unpdate the early
4487            --  call region to include it.
4488
4489            else
4490               Include (Curr, Curr);
4491            end if;
4492
4493         --  Otherwise the current construct is missing, indicating that the
4494         --  current list has been exhausted. Depending on the context of the
4495         --  list, several transitions are possible.
4496
4497         else
4498            --  The invariant of the algorithm ensures that Curr and Start are
4499            --  at the same level of nesting at the point of a transition. The
4500            --  algorithm can determine which list the traversal came from by
4501            --  examining Start.
4502
4503            Context := Parent (Start);
4504
4505            --  Attempt the following transitions:
4506            --
4507            --    private declarations -> visible declarations
4508            --    private declarations -> upper level
4509            --    private declarations -> terminate
4510            --    visible declarations -> upper level
4511            --    visible declarations -> terminate
4512
4513            if Nkind_In (Context, N_Package_Specification,
4514                                  N_Protected_Definition,
4515                                  N_Task_Definition)
4516            then
4517               Transition_Spec_Declarations (Context, Curr);
4518
4519            --  Attempt the following transitions:
4520            --
4521            --    statements -> declarations
4522            --    statements -> upper level
4523            --    statements -> corresponding package spec (Elab_Body)
4524            --    statements -> terminate
4525
4526            elsif Nkind (Context) = N_Handled_Sequence_Of_Statements then
4527               Transition_Handled_Statements (Context, Curr);
4528
4529            --  Attempt the following transitions:
4530            --
4531            --    declarations -> upper level
4532            --    declarations -> corresponding package spec (Elab_Body)
4533            --    declarations -> terminate
4534
4535            elsif Nkind_In (Context, N_Block_Statement,
4536                                     N_Entry_Body,
4537                                     N_Package_Body,
4538                                     N_Protected_Body,
4539                                     N_Subprogram_Body,
4540                                     N_Task_Body)
4541            then
4542               Transition_Body_Declarations (Context, Curr);
4543
4544            --  Otherwise it is not possible to transition. Stop the search
4545            --  because there are no more declarations or statements to check.
4546
4547            else
4548               raise ECR_Found;
4549            end if;
4550         end if;
4551      end Advance;
4552
4553      --------------------------
4554      -- Enter_Handled_Body --
4555      --------------------------
4556
4557      procedure Enter_Handled_Body (Curr : in out Node_Id) is
4558         Decls : constant List_Id := Declarations (Curr);
4559         HSS   : constant Node_Id := Handled_Statement_Sequence (Curr);
4560         Stmts : List_Id := No_List;
4561
4562      begin
4563         if Present (HSS) then
4564            Stmts := Statements (HSS);
4565         end if;
4566
4567         --  The handled body has a non-empty statement sequence. The construct
4568         --  to inspect is the last statement.
4569
4570         if Has_Suitable_Construct (Stmts) then
4571            Curr := Last (Stmts);
4572
4573         --  The handled body lacks statements, but has non-empty declarations.
4574         --  The construct to inspect is the last declaration.
4575
4576         elsif Has_Suitable_Construct (Decls) then
4577            Curr := Last (Decls);
4578
4579         --  Otherwise the handled body lacks both declarations and statements.
4580         --  The construct to inspect is the node which precedes the handled
4581         --  body. Update the early call region to include the handled body.
4582
4583         else
4584            Include (Curr, Curr);
4585         end if;
4586      end Enter_Handled_Body;
4587
4588      -------------------------------
4589      -- Enter_Package_Declaration --
4590      -------------------------------
4591
4592      procedure Enter_Package_Declaration (Curr : in out Node_Id) is
4593         Pack_Spec : constant Node_Id := Specification (Curr);
4594         Prv_Decls : constant List_Id := Private_Declarations (Pack_Spec);
4595         Vis_Decls : constant List_Id := Visible_Declarations (Pack_Spec);
4596
4597      begin
4598         --  The package has a non-empty private declarations. The construct to
4599         --  inspect is the last private declaration.
4600
4601         if Has_Suitable_Construct (Prv_Decls) then
4602            Curr := Last (Prv_Decls);
4603
4604         --  The package lacks private declarations, but has non-empty visible
4605         --  declarations. In this case the construct to inspect is the last
4606         --  visible declaration.
4607
4608         elsif Has_Suitable_Construct (Vis_Decls) then
4609            Curr := Last (Vis_Decls);
4610
4611         --  Otherwise the package lacks any declarations. The construct to
4612         --  inspect is the node which precedes the package. Update the early
4613         --  call region to include the package declaration.
4614
4615         else
4616            Include (Curr, Curr);
4617         end if;
4618      end Enter_Package_Declaration;
4619
4620      --------------
4621      -- Find_ECR --
4622      --------------
4623
4624      function Find_ECR (N : Node_Id) return Node_Id is
4625         Curr : Node_Id;
4626
4627      begin
4628         --  The early call region starts at N
4629
4630         Curr  := Prev (N);
4631         Start := N;
4632
4633         --  Inspect each node in reverse declarative order while going in and
4634         --  out of nested and enclosing constructs. Note that the only way to
4635         --  terminate this infinite loop is to raise exception ECR_Found.
4636
4637         loop
4638            --  The current construct is not preelaboration-safe. Terminate the
4639            --  traversal.
4640
4641            if Present (Curr)
4642              and then not Is_OK_Preelaborable_Construct (Curr)
4643            then
4644               raise ECR_Found;
4645            end if;
4646
4647            --  Advance to the next suitable construct. This may terminate the
4648            --  traversal by raising ECR_Found.
4649
4650            Advance (Curr);
4651         end loop;
4652
4653      exception
4654         when ECR_Found =>
4655            return Start;
4656      end Find_ECR;
4657
4658      ----------------------------
4659      -- Has_Suitable_Construct --
4660      ----------------------------
4661
4662      function Has_Suitable_Construct (List : List_Id) return Boolean is
4663         Item : Node_Id;
4664
4665      begin
4666         --  Examine the list in reverse declarative order, looking for a
4667         --  suitable construct.
4668
4669         if Present (List) then
4670            Item := Last (List);
4671            while Present (Item) loop
4672               if Is_Suitable_Construct (Item) then
4673                  return True;
4674               end if;
4675
4676               Prev (Item);
4677            end loop;
4678         end if;
4679
4680         return False;
4681      end Has_Suitable_Construct;
4682
4683      -------------
4684      -- Include --
4685      -------------
4686
4687      procedure Include (N : Node_Id; Curr : out Node_Id) is
4688      begin
4689         Start := N;
4690
4691         --  The input node is a compilation unit. This terminates the search
4692         --  because there are no more lists to inspect and there are no more
4693         --  enclosing constructs to climb up to. The transitions are:
4694         --
4695         --    private declarations -> terminate
4696         --    visible declarations -> terminate
4697         --    statements           -> terminate
4698         --    declarations         -> terminate
4699
4700         if Nkind (Parent (Start)) = N_Compilation_Unit then
4701            raise ECR_Found;
4702
4703         --  Otherwise the input node is still within some list
4704
4705         else
4706            Curr := Prev (Start);
4707         end if;
4708      end Include;
4709
4710      -----------------------------------
4711      -- Is_OK_Preelaborable_Construct --
4712      -----------------------------------
4713
4714      function Is_OK_Preelaborable_Construct (N : Node_Id) return Boolean is
4715      begin
4716         --  Assignment statements are acceptable as long as they were produced
4717         --  by the ABE mechanism to update elaboration flags.
4718
4719         if Nkind (N) = N_Assignment_Statement then
4720            return Is_Elaboration_Code (N);
4721
4722         --  Block statements are acceptable even though they directly violate
4723         --  preelaborability. The intention is not to penalize the early call
4724         --  region when a block contains only preelaborable constructs.
4725         --
4726         --    declare
4727         --       Val : constant Integer := 1;
4728         --    begin
4729         --       pragma Assert (Val = 1);
4730         --       null;
4731         --    end;
4732         --
4733         --  Note that the Advancement phase does enter blocks, and will detect
4734         --  any non-preelaborable declarations or statements within.
4735
4736         elsif Nkind (N) = N_Block_Statement then
4737            return True;
4738         end if;
4739
4740         --  Otherwise the construct must be preelaborable. The check must take
4741         --  the syntactic and semantic structure of the construct. DO NOT use
4742         --  Is_Preelaborable_Construct here.
4743
4744         return not Is_Non_Preelaborable_Construct (N);
4745      end Is_OK_Preelaborable_Construct;
4746
4747      ---------------------------
4748      -- Is_Suitable_Construct --
4749      ---------------------------
4750
4751      function Is_Suitable_Construct (N : Node_Id) return Boolean is
4752         Context : constant Node_Id := Parent (N);
4753
4754      begin
4755         --  An internally-generated statement sequence which contains only a
4756         --  single null statement is not a suitable construct because it is a
4757         --  byproduct of the parser. Such a null statement should be excluded
4758         --  from the early call region because it carries the source location
4759         --  of the "end" keyword, and may lead to confusing diagnistics.
4760
4761         if Nkind (N) = N_Null_Statement
4762           and then not Comes_From_Source (N)
4763           and then Present (Context)
4764           and then Nkind (Context) = N_Handled_Sequence_Of_Statements
4765           and then not Comes_From_Source (N)
4766         then
4767            return False;
4768         end if;
4769
4770         --  Otherwise only constructs which correspond to pure Ada constructs
4771         --  are considered suitable.
4772
4773         case Nkind (N) is
4774            when N_Call_Marker
4775               | N_Freeze_Entity
4776               | N_Freeze_Generic_Entity
4777               | N_Implicit_Label_Declaration
4778               | N_Itype_Reference
4779               | N_Pop_Constraint_Error_Label
4780               | N_Pop_Program_Error_Label
4781               | N_Pop_Storage_Error_Label
4782               | N_Push_Constraint_Error_Label
4783               | N_Push_Program_Error_Label
4784               | N_Push_Storage_Error_Label
4785               | N_SCIL_Dispatch_Table_Tag_Init
4786               | N_SCIL_Dispatching_Call
4787               | N_SCIL_Membership_Test
4788               | N_Variable_Reference_Marker
4789            =>
4790               return False;
4791
4792            when others =>
4793               return True;
4794         end case;
4795      end Is_Suitable_Construct;
4796
4797      ----------------------------------
4798      -- Transition_Body_Declarations --
4799      ----------------------------------
4800
4801      procedure Transition_Body_Declarations
4802        (Bod  : Node_Id;
4803         Curr : in out Node_Id)
4804      is
4805         Decls : constant List_Id := Declarations (Bod);
4806
4807      begin
4808         --  The search must come from the declarations of the body
4809
4810         pragma Assert
4811           (Is_Non_Empty_List (Decls)
4812             and then List_Containing (Start) = Decls);
4813
4814         --  The search finished inspecting the declarations. The construct
4815         --  to inspect is the node which precedes the handled body, unless
4816         --  the body is a compilation unit. The transitions are:
4817         --
4818         --    declarations -> upper level
4819         --    declarations -> corresponding package spec (Elab_Body)
4820         --    declarations -> terminate
4821
4822         Transition_Unit (Bod, Curr);
4823      end Transition_Body_Declarations;
4824
4825      -----------------------------------
4826      -- Transition_Handled_Statements --
4827      -----------------------------------
4828
4829      procedure Transition_Handled_Statements
4830        (HSS  : Node_Id;
4831         Curr : in out Node_Id)
4832      is
4833         Bod   : constant Node_Id := Parent (HSS);
4834         Decls : constant List_Id := Declarations (Bod);
4835         Stmts : constant List_Id := Statements (HSS);
4836
4837      begin
4838         --  The search must come from the statements of certain bodies or
4839         --  statements.
4840
4841         pragma Assert (Nkind_In (Bod, N_Block_Statement,
4842                                       N_Entry_Body,
4843                                       N_Package_Body,
4844                                       N_Protected_Body,
4845                                       N_Subprogram_Body,
4846                                       N_Task_Body));
4847
4848         --  The search must come from the statements of the handled sequence
4849
4850         pragma Assert
4851           (Is_Non_Empty_List (Stmts)
4852             and then List_Containing (Start) = Stmts);
4853
4854         --  The search finished inspecting the statements. The handled body
4855         --  has non-empty declarations. The construct to inspect is the last
4856         --  declaration. The transitions are:
4857         --
4858         --    statements -> declarations
4859
4860         if Has_Suitable_Construct (Decls) then
4861            Curr := Last (Decls);
4862
4863         --  Otherwise the handled body lacks declarations. The construct to
4864         --  inspect is the node which precedes the handled body, unless the
4865         --  body is a compilation unit. The transitions are:
4866         --
4867         --    statements -> upper level
4868         --    statements -> corresponding package spec (Elab_Body)
4869         --    statements -> terminate
4870
4871         else
4872            Transition_Unit (Bod, Curr);
4873         end if;
4874      end Transition_Handled_Statements;
4875
4876      ----------------------------------
4877      -- Transition_Spec_Declarations --
4878      ----------------------------------
4879
4880      procedure Transition_Spec_Declarations
4881        (Spec : Node_Id;
4882         Curr : in out Node_Id)
4883      is
4884         Prv_Decls : constant List_Id := Private_Declarations (Spec);
4885         Vis_Decls : constant List_Id := Visible_Declarations (Spec);
4886
4887      begin
4888         pragma Assert (Present (Start) and then Is_List_Member (Start));
4889
4890         --  The search came from the private declarations and finished their
4891         --  inspection.
4892
4893         if Has_Suitable_Construct (Prv_Decls)
4894           and then List_Containing (Start) = Prv_Decls
4895         then
4896            --  The context has non-empty visible declarations. The node to
4897            --  inspect is the last visible declaration. The transitions are:
4898            --
4899            --    private declarations -> visible declarations
4900
4901            if Has_Suitable_Construct (Vis_Decls) then
4902               Curr := Last (Vis_Decls);
4903
4904            --  Otherwise the context lacks visible declarations. The construct
4905            --  to inspect is the node which precedes the context unless the
4906            --  context is a compilation unit. The transitions are:
4907            --
4908            --    private declarations -> upper level
4909            --    private declarations -> terminate
4910
4911            else
4912               Transition_Unit (Parent (Spec), Curr);
4913            end if;
4914
4915         --  The search came from the visible declarations and finished their
4916         --  inspections. The construct to inspect is the node which precedes
4917         --  the context, unless the context is a compilaton unit. The
4918         --  transitions are:
4919         --
4920         --    visible declarations -> upper level
4921         --    visible declarations -> terminate
4922
4923         elsif Has_Suitable_Construct (Vis_Decls)
4924           and then List_Containing (Start) = Vis_Decls
4925         then
4926            Transition_Unit (Parent (Spec), Curr);
4927
4928         --  At this point both declarative lists are empty, but the traversal
4929         --  still came from within the spec. This indicates that the invariant
4930         --  of the algorithm has been violated.
4931
4932         else
4933            pragma Assert (False);
4934            raise ECR_Found;
4935         end if;
4936      end Transition_Spec_Declarations;
4937
4938      ---------------------
4939      -- Transition_Unit --
4940      ---------------------
4941
4942      procedure Transition_Unit
4943        (Unit : Node_Id;
4944         Curr : in out Node_Id)
4945      is
4946         Context : constant Node_Id := Parent (Unit);
4947
4948      begin
4949         --  The unit is a compilation unit. This terminates the search because
4950         --  there are no more lists to inspect and there are no more enclosing
4951         --  constructs to climb up to.
4952
4953         if Nkind (Context) = N_Compilation_Unit then
4954
4955            --  A package body with a corresponding spec subject to pragma
4956            --  Elaborate_Body is an exception to the above. The annotation
4957            --  allows the search to continue into the package declaration.
4958            --  The transitions are:
4959            --
4960            --    statements   -> corresponding package spec (Elab_Body)
4961            --    declarations -> corresponding package spec (Elab_Body)
4962
4963            if Nkind (Unit) = N_Package_Body
4964              and then (Assume_Elab_Body
4965                         or else Has_Pragma_Elaborate_Body
4966                                   (Corresponding_Spec (Unit)))
4967            then
4968               Curr := Unit_Declaration_Node (Corresponding_Spec (Unit));
4969               Enter_Package_Declaration (Curr);
4970
4971            --  Otherwise terminate the search. The transitions are:
4972            --
4973            --    private declarations -> terminate
4974            --    visible declarations -> terminate
4975            --    statements           -> terminate
4976            --    declarations         -> terminate
4977
4978            else
4979               raise ECR_Found;
4980            end if;
4981
4982         --  The unit is a subunit. The construct to inspect is the node which
4983         --  precedes the corresponding stub. Update the early call region to
4984         --  include the unit.
4985
4986         elsif Nkind (Context) = N_Subunit then
4987            Start := Unit;
4988            Curr  := Corresponding_Stub (Context);
4989
4990         --  Otherwise the unit is nested. The construct to inspect is the node
4991         --  which precedes the unit. Update the early call region to include
4992         --  the unit.
4993
4994         else
4995            Include (Unit, Curr);
4996         end if;
4997      end Transition_Unit;
4998
4999      --  Local variables
5000
5001      Body_Id : constant Entity_Id := Defining_Entity (Body_Decl);
5002      Region  : Node_Id;
5003
5004   --  Start of processing for Find_Early_Call_Region
5005
5006   begin
5007      --  The caller demands the start of the early call region without saving
5008      --  or retrieving it to/from internal data structures.
5009
5010      if Skip_Memoization then
5011         Region := Find_ECR (Body_Decl);
5012
5013      --  Default behavior
5014
5015      else
5016         --  Check whether the early call region of the subprogram body is
5017         --  available.
5018
5019         Region := Early_Call_Region (Body_Id);
5020
5021         if No (Region) then
5022
5023            --  Traverse the declarations in reverse order, starting from the
5024            --  subprogram body, searching for the nearest non-preelaborable
5025            --  construct. The early call region starts after this construct
5026            --  and ends at the subprogram body.
5027
5028            Region := Find_ECR (Body_Decl);
5029
5030            --  Associate the early call region with the subprogram body in
5031            --  case other scenarios need it.
5032
5033            Set_Early_Call_Region (Body_Id, Region);
5034         end if;
5035      end if;
5036
5037      --  A subprogram body must always have an early call region
5038
5039      pragma Assert (Present (Region));
5040
5041      return Region;
5042   end Find_Early_Call_Region;
5043
5044   ---------------------------
5045   -- Find_Elaborated_Units --
5046   ---------------------------
5047
5048   procedure Find_Elaborated_Units is
5049      procedure Add_Pragma (Prag : Node_Id);
5050      --  Determine whether pragma Prag denotes a legal Elaborate[_All] pragma.
5051      --  If this is the case, add the related unit to the elaboration context.
5052      --  For pragma Elaborate_All, include recursively all units withed by the
5053      --  related unit.
5054
5055      procedure Add_Unit
5056        (Unit_Id      : Entity_Id;
5057         Prag         : Node_Id;
5058         Full_Context : Boolean);
5059      --  Add unit Unit_Id to the elaboration context. Prag denotes the pragma
5060      --  which prompted the inclusion of the unit to the elaboration context.
5061      --  If flag Full_Context is set, examine the nonlimited clauses of unit
5062      --  Unit_Id and add each withed unit to the context.
5063
5064      procedure Find_Elaboration_Context (Comp_Unit : Node_Id);
5065      --  Examine the context items of compilation unit Comp_Unit for suitable
5066      --  elaboration-related pragmas and add all related units to the context.
5067
5068      ----------------
5069      -- Add_Pragma --
5070      ----------------
5071
5072      procedure Add_Pragma (Prag : Node_Id) is
5073         Prag_Args : constant List_Id := Pragma_Argument_Associations (Prag);
5074         Prag_Nam  : constant Name_Id := Pragma_Name (Prag);
5075         Unit_Arg  : Node_Id;
5076
5077      begin
5078         --  Nothing to do if the pragma is not related to elaboration
5079
5080         if not Nam_In (Prag_Nam, Name_Elaborate, Name_Elaborate_All) then
5081            return;
5082
5083         --  Nothing to do when the pragma is illegal
5084
5085         elsif Error_Posted (Prag) then
5086            return;
5087         end if;
5088
5089         Unit_Arg := Get_Pragma_Arg (First (Prag_Args));
5090
5091         --  The argument of the pragma may appear in package.package form
5092
5093         if Nkind (Unit_Arg) = N_Selected_Component then
5094            Unit_Arg := Selector_Name (Unit_Arg);
5095         end if;
5096
5097         Add_Unit
5098           (Unit_Id      => Entity (Unit_Arg),
5099            Prag         => Prag,
5100            Full_Context => Prag_Nam = Name_Elaborate_All);
5101      end Add_Pragma;
5102
5103      --------------
5104      -- Add_Unit --
5105      --------------
5106
5107      procedure Add_Unit
5108        (Unit_Id      : Entity_Id;
5109         Prag         : Node_Id;
5110         Full_Context : Boolean)
5111      is
5112         Clause     : Node_Id;
5113         Elab_Attrs : Elaboration_Attributes;
5114
5115      begin
5116         --  Nothing to do when some previous error left a with clause or a
5117         --  pragma in a bad state.
5118
5119         if No (Unit_Id) then
5120            return;
5121         end if;
5122
5123         Elab_Attrs := Elaboration_Status (Unit_Id);
5124
5125         --  The unit is already included in the context by means of pragma
5126         --  Elaborate[_All].
5127
5128         if Present (Elab_Attrs.Source_Pragma) then
5129
5130            --  Upgrade an existing pragma Elaborate when the unit is subject
5131            --  to Elaborate_All because the new pragma covers a larger set of
5132            --  units.
5133
5134            if Pragma_Name (Elab_Attrs.Source_Pragma) = Name_Elaborate
5135              and then Pragma_Name (Prag) = Name_Elaborate_All
5136            then
5137               Elab_Attrs.Source_Pragma := Prag;
5138
5139            --  Otherwise the unit retains its existing pragma and does not
5140            --  need to be included in the context again.
5141
5142            else
5143               return;
5144            end if;
5145
5146         --  The current unit is not part of the context. Prepare a new set of
5147         --  attributes.
5148
5149         else
5150            Elab_Attrs :=
5151              Elaboration_Attributes'(Source_Pragma => Prag,
5152                                      With_Clause   => Empty);
5153         end if;
5154
5155         --  Add or update the attributes of the unit
5156
5157         Set_Elaboration_Status (Unit_Id, Elab_Attrs);
5158
5159         --  Includes all units withed by the current one when computing the
5160         --  full context.
5161
5162         if Full_Context then
5163
5164            --  Process all nonlimited with clauses found in the context of
5165            --  the current unit. Note that limited clauses do not impose an
5166            --  elaboration order.
5167
5168            Clause := First (Context_Items (Compilation_Unit (Unit_Id)));
5169            while Present (Clause) loop
5170               if Nkind (Clause) = N_With_Clause
5171                 and then not Error_Posted (Clause)
5172                 and then not Limited_Present (Clause)
5173               then
5174                  Add_Unit
5175                    (Unit_Id      => Entity (Name (Clause)),
5176                     Prag         => Prag,
5177                     Full_Context => Full_Context);
5178               end if;
5179
5180               Next (Clause);
5181            end loop;
5182         end if;
5183      end Add_Unit;
5184
5185      ------------------------------
5186      -- Find_Elaboration_Context --
5187      ------------------------------
5188
5189      procedure Find_Elaboration_Context (Comp_Unit : Node_Id) is
5190         Prag : Node_Id;
5191
5192      begin
5193         pragma Assert (Nkind (Comp_Unit) = N_Compilation_Unit);
5194
5195         --  Process all elaboration-related pragmas found in the context of
5196         --  the compilation unit.
5197
5198         Prag := First (Context_Items (Comp_Unit));
5199         while Present (Prag) loop
5200            if Nkind (Prag) = N_Pragma then
5201               Add_Pragma (Prag);
5202            end if;
5203
5204            Next (Prag);
5205         end loop;
5206      end Find_Elaboration_Context;
5207
5208      --  Local variables
5209
5210      Par_Id : Entity_Id;
5211      Unt    : Node_Id;
5212
5213   --  Start of processing for Find_Elaborated_Units
5214
5215   begin
5216      --  Perform a traversal which examines the context of the main unit and
5217      --  populates the Elaboration_Context table with all units elaborated
5218      --  prior to the main unit. The traversal performs the following jumps:
5219
5220      --    subunit        -> parent subunit
5221      --    parent subunit -> body
5222      --    body           -> spec
5223      --    spec           -> parent spec
5224      --    parent spec    -> grandparent spec and so on
5225
5226      --  The traversal relies on units rather than scopes because the scope of
5227      --  a subunit is some spec, while this traversal must process the body as
5228      --  well. Given that protected and task bodies can also be subunits, this
5229      --  complicates the scope approach even further.
5230
5231      Unt := Unit (Cunit (Main_Unit));
5232
5233      --  Perform the following traversals when the main unit is a subunit
5234
5235      --    subunit        -> parent subunit
5236      --    parent subunit -> body
5237
5238      while Present (Unt) and then Nkind (Unt) = N_Subunit loop
5239         Find_Elaboration_Context (Parent (Unt));
5240
5241         --  Continue the traversal by going to the unit which contains the
5242         --  corresponding stub.
5243
5244         if Present (Corresponding_Stub (Unt)) then
5245            Unt := Unit (Cunit (Get_Source_Unit (Corresponding_Stub (Unt))));
5246
5247         --  Otherwise the subunit may be erroneous or left in a bad state
5248
5249         else
5250            exit;
5251         end if;
5252      end loop;
5253
5254      --  Perform the following traversal now that subunits have been taken
5255      --  care of, or the main unit is a body.
5256
5257      --    body -> spec
5258
5259      if Present (Unt)
5260        and then Nkind_In (Unt, N_Package_Body, N_Subprogram_Body)
5261      then
5262         Find_Elaboration_Context (Parent (Unt));
5263
5264         --  Continue the traversal by going to the unit which contains the
5265         --  corresponding spec.
5266
5267         if Present (Corresponding_Spec (Unt)) then
5268            Unt := Unit (Cunit (Get_Source_Unit (Corresponding_Spec (Unt))));
5269         end if;
5270      end if;
5271
5272      --  Perform the following traversals now that the body has been taken
5273      --  care of, or the main unit is a spec.
5274
5275      --    spec        -> parent spec
5276      --    parent spec -> grandparent spec and so on
5277
5278      if Present (Unt)
5279        and then Nkind_In (Unt, N_Generic_Package_Declaration,
5280                                N_Generic_Subprogram_Declaration,
5281                                N_Package_Declaration,
5282                                N_Subprogram_Declaration)
5283      then
5284         Find_Elaboration_Context (Parent (Unt));
5285
5286         --  Process a potential chain of parent units which ends with the
5287         --  main unit spec. The traversal can now safely rely on the scope
5288         --  chain.
5289
5290         Par_Id := Scope (Defining_Entity (Unt));
5291         while Present (Par_Id) and then Par_Id /= Standard_Standard loop
5292            Find_Elaboration_Context (Compilation_Unit (Par_Id));
5293
5294            Par_Id := Scope (Par_Id);
5295         end loop;
5296      end if;
5297   end Find_Elaborated_Units;
5298
5299   -----------------------------
5300   -- Find_Enclosing_Instance --
5301   -----------------------------
5302
5303   function Find_Enclosing_Instance (N : Node_Id) return Node_Id is
5304      Par     : Node_Id;
5305      Spec_Id : Entity_Id;
5306
5307   begin
5308      --  Climb the parent chain looking for an enclosing instance spec or body
5309
5310      Par := N;
5311      while Present (Par) loop
5312
5313         --  Generic package or subprogram spec
5314
5315         if Nkind_In (Par, N_Package_Declaration,
5316                           N_Subprogram_Declaration)
5317           and then Is_Generic_Instance (Defining_Entity (Par))
5318         then
5319            return Par;
5320
5321         --  Generic package or subprogram body
5322
5323         elsif Nkind_In (Par, N_Package_Body, N_Subprogram_Body) then
5324            Spec_Id := Corresponding_Spec (Par);
5325
5326            if Present (Spec_Id) and then Is_Generic_Instance (Spec_Id) then
5327               return Par;
5328            end if;
5329         end if;
5330
5331         Par := Parent (Par);
5332      end loop;
5333
5334      return Empty;
5335   end Find_Enclosing_Instance;
5336
5337   --------------------------
5338   -- Find_Enclosing_Level --
5339   --------------------------
5340
5341   function Find_Enclosing_Level (N : Node_Id) return Enclosing_Level_Kind is
5342      function Level_Of (Unit : Node_Id) return Enclosing_Level_Kind;
5343      --  Obtain the corresponding level of unit Unit
5344
5345      --------------
5346      -- Level_Of --
5347      --------------
5348
5349      function Level_Of (Unit : Node_Id) return Enclosing_Level_Kind is
5350         Spec_Id : Entity_Id;
5351
5352      begin
5353         if Nkind (Unit) in N_Generic_Instantiation then
5354            return Instantiation;
5355
5356         elsif Nkind (Unit) = N_Generic_Package_Declaration then
5357            return Generic_Package_Spec;
5358
5359         elsif Nkind (Unit) = N_Package_Declaration then
5360            return Package_Spec;
5361
5362         elsif Nkind (Unit) = N_Package_Body then
5363            Spec_Id := Corresponding_Spec (Unit);
5364
5365            --  The body belongs to a generic package
5366
5367            if Present (Spec_Id)
5368              and then Ekind (Spec_Id) = E_Generic_Package
5369            then
5370               return Generic_Package_Body;
5371
5372            --  Otherwise the body belongs to a non-generic package. This also
5373            --  treats an illegal package body without a corresponding spec as
5374            --  a non-generic package body.
5375
5376            else
5377               return Package_Body;
5378            end if;
5379         end if;
5380
5381         return No_Level;
5382      end Level_Of;
5383
5384      --  Local variables
5385
5386      Context : Node_Id;
5387      Curr    : Node_Id;
5388      Prev    : Node_Id;
5389
5390   --  Start of processing for Find_Enclosing_Level
5391
5392   begin
5393      --  Call markers and instantiations which appear at the declaration level
5394      --  but are later relocated in a different context retain their original
5395      --  declaration level.
5396
5397      if Nkind_In (N, N_Call_Marker,
5398                      N_Function_Instantiation,
5399                      N_Package_Instantiation,
5400                      N_Procedure_Instantiation)
5401        and then Is_Declaration_Level_Node (N)
5402      then
5403         return Declaration_Level;
5404      end if;
5405
5406      --  Climb the parent chain looking at the enclosing levels
5407
5408      Prev := N;
5409      Curr := Parent (Prev);
5410      while Present (Curr) loop
5411
5412         --  A traversal from a subunit continues via the corresponding stub
5413
5414         if Nkind (Curr) = N_Subunit then
5415            Curr := Corresponding_Stub (Curr);
5416
5417         --  The current construct is a package. Packages are ignored because
5418         --  they are always elaborated when the enclosing context is invoked
5419         --  or elaborated.
5420
5421         elsif Nkind_In (Curr, N_Package_Body, N_Package_Declaration) then
5422            null;
5423
5424         --  The current construct is a block statement
5425
5426         elsif Nkind (Curr) = N_Block_Statement then
5427
5428            --  Ignore internally generated blocks created by the expander for
5429            --  various purposes such as abort defer/undefer.
5430
5431            if not Comes_From_Source (Curr) then
5432               null;
5433
5434            --  If the traversal came from the handled sequence of statments,
5435            --  then the node appears at the level of the enclosing construct.
5436            --  This is a more reliable test because transients scopes within
5437            --  the declarative region of the encapsulator are hard to detect.
5438
5439            elsif Nkind (Prev) = N_Handled_Sequence_Of_Statements
5440              and then Handled_Statement_Sequence (Curr) = Prev
5441            then
5442               return Find_Enclosing_Level (Parent (Curr));
5443
5444            --  Otherwise the traversal came from the declarations, the node is
5445            --  at the declaration level.
5446
5447            else
5448               return Declaration_Level;
5449            end if;
5450
5451         --  The current construct is a declaration-level encapsulator
5452
5453         elsif Nkind_In (Curr, N_Entry_Body,
5454                               N_Subprogram_Body,
5455                               N_Task_Body)
5456         then
5457            --  If the traversal came from the handled sequence of statments,
5458            --  then the node cannot possibly appear at any level. This is
5459            --  a more reliable test because transients scopes within the
5460            --  declarative region of the encapsulator are hard to detect.
5461
5462            if Nkind (Prev) = N_Handled_Sequence_Of_Statements
5463              and then Handled_Statement_Sequence (Curr) = Prev
5464            then
5465               return No_Level;
5466
5467            --  Otherwise the traversal came from the declarations, the node is
5468            --  at the declaration level.
5469
5470            else
5471               return Declaration_Level;
5472            end if;
5473
5474         --  The current construct is a non-library-level encapsulator which
5475         --  indicates that the node cannot possibly appear at any level.
5476         --  Note that this check must come after the declaration-level check
5477         --  because both predicates share certain nodes.
5478
5479         elsif Is_Non_Library_Level_Encapsulator (Curr) then
5480            Context := Parent (Curr);
5481
5482            --  The sole exception is when the encapsulator is the compilation
5483            --  utit itself because the compilation unit node requires special
5484            --  processing (see below).
5485
5486            if Present (Context)
5487              and then Nkind (Context) = N_Compilation_Unit
5488            then
5489               null;
5490
5491            --  Otherwise the node is not at any level
5492
5493            else
5494               return No_Level;
5495            end if;
5496
5497         --  The current construct is a compilation unit. The node appears at
5498         --  the [generic] library level when the unit is a [generic] package.
5499
5500         elsif Nkind (Curr) = N_Compilation_Unit then
5501            return Level_Of (Unit (Curr));
5502         end if;
5503
5504         Prev := Curr;
5505         Curr := Parent (Prev);
5506      end loop;
5507
5508      return No_Level;
5509   end Find_Enclosing_Level;
5510
5511   -------------------
5512   -- Find_Top_Unit --
5513   -------------------
5514
5515   function Find_Top_Unit (N : Node_Or_Entity_Id) return Entity_Id is
5516   begin
5517      return Find_Unit_Entity (Unit (Cunit (Get_Top_Level_Code_Unit (N))));
5518   end Find_Top_Unit;
5519
5520   ----------------------
5521   -- Find_Unit_Entity --
5522   ----------------------
5523
5524   function Find_Unit_Entity (N : Node_Id) return Entity_Id is
5525      Context : constant Node_Id := Parent (N);
5526      Orig_N  : constant Node_Id := Original_Node (N);
5527
5528   begin
5529      --  The unit denotes a package body of an instantiation which acts as
5530      --  a compilation unit. The proper entity is that of the package spec.
5531
5532      if Nkind (N) = N_Package_Body
5533        and then Nkind (Orig_N) = N_Package_Instantiation
5534        and then Nkind (Context) = N_Compilation_Unit
5535      then
5536         return Corresponding_Spec (N);
5537
5538      --  The unit denotes an anonymous package created to wrap a subprogram
5539      --  instantiation which acts as a compilation unit. The proper entity is
5540      --  that of the "related instance".
5541
5542      elsif Nkind (N) = N_Package_Declaration
5543        and then Nkind_In (Orig_N, N_Function_Instantiation,
5544                                   N_Procedure_Instantiation)
5545        and then Nkind (Context) = N_Compilation_Unit
5546      then
5547         return
5548           Related_Instance (Defining_Entity (N, Concurrent_Subunit => True));
5549
5550      --  Otherwise the proper entity is the defining entity
5551
5552      else
5553         return Defining_Entity (N, Concurrent_Subunit => True);
5554      end if;
5555   end Find_Unit_Entity;
5556
5557   -----------------------
5558   -- First_Formal_Type --
5559   -----------------------
5560
5561   function First_Formal_Type (Subp_Id : Entity_Id) return Entity_Id is
5562      Formal_Id : constant Entity_Id := First_Formal (Subp_Id);
5563      Typ       : Entity_Id;
5564
5565   begin
5566      if Present (Formal_Id) then
5567         Typ := Etype (Formal_Id);
5568
5569         --  Handle various combinations of concurrent and private types
5570
5571         loop
5572            if Ekind_In (Typ, E_Protected_Type, E_Task_Type)
5573              and then Present (Anonymous_Object (Typ))
5574            then
5575               Typ := Anonymous_Object (Typ);
5576
5577            elsif Is_Concurrent_Record_Type (Typ) then
5578               Typ := Corresponding_Concurrent_Type (Typ);
5579
5580            elsif Is_Private_Type (Typ) and then Present (Full_View (Typ)) then
5581               Typ := Full_View (Typ);
5582
5583            else
5584               exit;
5585            end if;
5586         end loop;
5587
5588         return Typ;
5589      end if;
5590
5591      return Empty;
5592   end First_Formal_Type;
5593
5594   --------------
5595   -- Has_Body --
5596   --------------
5597
5598   function Has_Body (Pack_Decl : Node_Id) return Boolean is
5599      function Find_Corresponding_Body (Spec_Id : Entity_Id) return Node_Id;
5600      --  Try to locate the corresponding body of spec Spec_Id. If no body is
5601      --  found, return Empty.
5602
5603      function Find_Body
5604        (Spec_Id : Entity_Id;
5605         From    : Node_Id) return Node_Id;
5606      --  Try to locate the corresponding body of spec Spec_Id in the node list
5607      --  which follows arbitrary node From. If no body is found, return Empty.
5608
5609      function Load_Package_Body (Unit_Nam : Unit_Name_Type) return Node_Id;
5610      --  Attempt to load the body of unit Unit_Nam. If the load failed, return
5611      --  Empty. If the compilation will not generate code, return Empty.
5612
5613      -----------------------------
5614      -- Find_Corresponding_Body --
5615      -----------------------------
5616
5617      function Find_Corresponding_Body (Spec_Id : Entity_Id) return Node_Id is
5618         Context   : constant Entity_Id := Scope (Spec_Id);
5619         Spec_Decl : constant Node_Id   := Unit_Declaration_Node (Spec_Id);
5620         Body_Decl : Node_Id;
5621         Body_Id   : Entity_Id;
5622
5623      begin
5624         if Is_Compilation_Unit (Spec_Id) then
5625            Body_Id := Corresponding_Body (Spec_Decl);
5626
5627            if Present (Body_Id) then
5628               return Unit_Declaration_Node (Body_Id);
5629
5630            --  The package is at the library and requires a body. Load the
5631            --  corresponding body because the optional body may be declared
5632            --  there.
5633
5634            elsif Unit_Requires_Body (Spec_Id) then
5635               return
5636                 Load_Package_Body
5637                   (Get_Body_Name (Unit_Name (Get_Source_Unit (Spec_Decl))));
5638
5639            --  Otherwise there is no optional body
5640
5641            else
5642               return Empty;
5643            end if;
5644
5645         --  The immediate context is a package. The optional body may be
5646         --  within the body of that package.
5647
5648         --    procedure Proc is
5649         --       package Nested_1 is
5650         --          package Nested_2 is
5651         --             generic
5652         --             package Pack is
5653         --             end Pack;
5654         --          end Nested_2;
5655         --       end Nested_1;
5656
5657         --       package body Nested_1 is
5658         --          package body Nested_2 is separate;
5659         --       end Nested_1;
5660
5661         --    separate (Proc.Nested_1.Nested_2)
5662         --    package body Nested_2 is
5663         --       package body Pack is           --  optional body
5664         --          ...
5665         --       end Pack;
5666         --    end Nested_2;
5667
5668         elsif Is_Package_Or_Generic_Package (Context) then
5669            Body_Decl := Find_Corresponding_Body (Context);
5670
5671            --  The optional body is within the body of the enclosing package
5672
5673            if Present (Body_Decl) then
5674               return
5675                 Find_Body
5676                   (Spec_Id => Spec_Id,
5677                    From    => First (Declarations (Body_Decl)));
5678
5679            --  Otherwise the enclosing package does not have a body. This may
5680            --  be the result of an error or a genuine lack of a body.
5681
5682            else
5683               return Empty;
5684            end if;
5685
5686         --  Otherwise the immediate context is a body. The optional body may
5687         --  be within the same list as the spec.
5688
5689         --    procedure Proc is
5690         --       generic
5691         --       package Pack is
5692         --       end Pack;
5693
5694         --       package body Pack is           --  optional body
5695         --          ...
5696         --       end Pack;
5697
5698         else
5699            return
5700              Find_Body
5701                (Spec_Id => Spec_Id,
5702                 From    => Next (Spec_Decl));
5703         end if;
5704      end Find_Corresponding_Body;
5705
5706      ---------------
5707      -- Find_Body --
5708      ---------------
5709
5710      function Find_Body
5711        (Spec_Id : Entity_Id;
5712         From    : Node_Id) return Node_Id
5713      is
5714         Spec_Nam : constant Name_Id := Chars (Spec_Id);
5715         Item     : Node_Id;
5716         Lib_Unit : Node_Id;
5717
5718      begin
5719         Item := From;
5720         while Present (Item) loop
5721
5722            --  The current item denotes the optional body
5723
5724            if Nkind (Item) = N_Package_Body
5725              and then Chars (Defining_Entity (Item)) = Spec_Nam
5726            then
5727               return Item;
5728
5729            --  The current item denotes a stub, the optional body may be in
5730            --  the subunit.
5731
5732            elsif Nkind (Item) = N_Package_Body_Stub
5733              and then Chars (Defining_Entity (Item)) = Spec_Nam
5734            then
5735               Lib_Unit := Library_Unit (Item);
5736
5737               --  The corresponding subunit was previously loaded
5738
5739               if Present (Lib_Unit) then
5740                  return Lib_Unit;
5741
5742               --  Otherwise attempt to load the corresponding subunit
5743
5744               else
5745                  return Load_Package_Body (Get_Unit_Name (Item));
5746               end if;
5747            end if;
5748
5749            Next (Item);
5750         end loop;
5751
5752         return Empty;
5753      end Find_Body;
5754
5755      -----------------------
5756      -- Load_Package_Body --
5757      -----------------------
5758
5759      function Load_Package_Body (Unit_Nam : Unit_Name_Type) return Node_Id is
5760         Body_Decl : Node_Id;
5761         Unit_Num  : Unit_Number_Type;
5762
5763      begin
5764         --  The load is performed only when the compilation will generate code
5765
5766         if Operating_Mode = Generate_Code then
5767            Unit_Num :=
5768              Load_Unit
5769                (Load_Name  => Unit_Nam,
5770                 Required   => False,
5771                 Subunit    => False,
5772                 Error_Node => Pack_Decl);
5773
5774            --  The load failed most likely because the physical file is
5775            --  missing.
5776
5777            if Unit_Num = No_Unit then
5778               return Empty;
5779
5780            --  Otherwise the load was successful, return the body of the unit
5781
5782            else
5783               Body_Decl := Unit (Cunit (Unit_Num));
5784
5785               --  If the unit is a subunit with an available proper body,
5786               --  return the proper body.
5787
5788               if Nkind (Body_Decl) = N_Subunit
5789                 and then Present (Proper_Body (Body_Decl))
5790               then
5791                  Body_Decl := Proper_Body (Body_Decl);
5792               end if;
5793
5794               return Body_Decl;
5795            end if;
5796         end if;
5797
5798         return Empty;
5799      end Load_Package_Body;
5800
5801      --  Local variables
5802
5803      Pack_Id : constant Entity_Id := Defining_Entity (Pack_Decl);
5804
5805   --  Start of processing for Has_Body
5806
5807   begin
5808      --  The body is available
5809
5810      if Present (Corresponding_Body (Pack_Decl)) then
5811         return True;
5812
5813      --  The body is required if the package spec contains a construct which
5814      --  requires a completion in a body.
5815
5816      elsif Unit_Requires_Body (Pack_Id) then
5817         return True;
5818
5819      --  The body may be optional
5820
5821      else
5822         return Present (Find_Corresponding_Body (Pack_Id));
5823      end if;
5824   end Has_Body;
5825
5826   ---------------------------
5827   -- Has_Prior_Elaboration --
5828   ---------------------------
5829
5830   function Has_Prior_Elaboration
5831     (Unit_Id      : Entity_Id;
5832      Context_OK   : Boolean := False;
5833      Elab_Body_OK : Boolean := False;
5834      Same_Unit_OK : Boolean := False) return Boolean
5835   is
5836      Main_Id : constant Entity_Id := Cunit_Entity (Main_Unit);
5837
5838   begin
5839      --  A preelaborated unit is always elaborated prior to the main unit
5840
5841      if Is_Preelaborated_Unit (Unit_Id) then
5842         return True;
5843
5844      --  An internal unit is always elaborated prior to a non-internal main
5845      --  unit.
5846
5847      elsif In_Internal_Unit (Unit_Id)
5848        and then not In_Internal_Unit (Main_Id)
5849      then
5850         return True;
5851
5852      --  A unit has prior elaboration if it appears within the context of the
5853      --  main unit. Consider this case only when requested by the caller.
5854
5855      elsif Context_OK
5856        and then Elaboration_Status (Unit_Id) /= No_Elaboration_Attributes
5857      then
5858         return True;
5859
5860      --  A unit whose body is elaborated together with its spec has prior
5861      --  elaboration except with respect to itself. Consider this case only
5862      --  when requested by the caller.
5863
5864      elsif Elab_Body_OK
5865        and then Has_Pragma_Elaborate_Body (Unit_Id)
5866        and then not Is_Same_Unit (Unit_Id, Main_Id)
5867      then
5868         return True;
5869
5870      --  A unit has no prior elaboration with respect to itself, but does not
5871      --  require any means of ensuring its own elaboration either. Treat this
5872      --  case as valid prior elaboration only when requested by the caller.
5873
5874      elsif Same_Unit_OK and then Is_Same_Unit (Unit_Id, Main_Id) then
5875         return True;
5876      end if;
5877
5878      return False;
5879   end Has_Prior_Elaboration;
5880
5881   --------------------------
5882   -- In_External_Instance --
5883   --------------------------
5884
5885   function In_External_Instance
5886     (N           : Node_Id;
5887      Target_Decl : Node_Id) return Boolean
5888   is
5889      Dummy     : Node_Id;
5890      Inst_Body : Node_Id;
5891      Inst_Decl : Node_Id;
5892
5893   begin
5894      --  Performance note: parent traversal
5895
5896      Inst_Decl := Find_Enclosing_Instance (Target_Decl);
5897
5898      --  The target declaration appears within an instance spec. Visibility is
5899      --  ignored because internally generated primitives for private types may
5900      --  reside in the private declarations and still be invoked from outside.
5901
5902      if Present (Inst_Decl)
5903        and then Nkind (Inst_Decl) = N_Package_Declaration
5904      then
5905         --  The scenario comes from the main unit and the instance does not
5906
5907         if In_Extended_Main_Code_Unit (N)
5908           and then not In_Extended_Main_Code_Unit (Inst_Decl)
5909         then
5910            return True;
5911
5912         --  Otherwise the scenario must not appear within the instance spec or
5913         --  body.
5914
5915         else
5916            Extract_Instance_Attributes
5917              (Exp_Inst  => Inst_Decl,
5918               Inst_Body => Inst_Body,
5919               Inst_Decl => Dummy);
5920
5921            --  Performance note: parent traversal
5922
5923            return not In_Subtree
5924                         (N     => N,
5925                          Root1 => Inst_Decl,
5926                          Root2 => Inst_Body);
5927         end if;
5928      end if;
5929
5930      return False;
5931   end In_External_Instance;
5932
5933   ---------------------
5934   -- In_Main_Context --
5935   ---------------------
5936
5937   function In_Main_Context (N : Node_Id) return Boolean is
5938   begin
5939      --  Scenarios outside the main unit are not considered because the ALI
5940      --  information supplied to binde is for the main unit only.
5941
5942      if not In_Extended_Main_Code_Unit (N) then
5943         return False;
5944
5945      --  Scenarios within internal units are not considered unless switch
5946      --  -gnatdE (elaboration checks on predefined units) is in effect.
5947
5948      elsif not Debug_Flag_EE and then In_Internal_Unit (N) then
5949         return False;
5950      end if;
5951
5952      return True;
5953   end In_Main_Context;
5954
5955   ---------------------
5956   -- In_Same_Context --
5957   ---------------------
5958
5959   function In_Same_Context
5960     (N1        : Node_Id;
5961      N2        : Node_Id;
5962      Nested_OK : Boolean := False) return Boolean
5963   is
5964      function Find_Enclosing_Context (N : Node_Id) return Node_Id;
5965      --  Return the nearest enclosing non-library-level or compilation unit
5966      --  node which which encapsulates arbitrary node N. Return Empty is no
5967      --  such context is available.
5968
5969      function In_Nested_Context
5970        (Outer : Node_Id;
5971         Inner : Node_Id) return Boolean;
5972      --  Determine whether arbitrary node Outer encapsulates arbitrary node
5973      --  Inner.
5974
5975      ----------------------------
5976      -- Find_Enclosing_Context --
5977      ----------------------------
5978
5979      function Find_Enclosing_Context (N : Node_Id) return Node_Id is
5980         Context : Node_Id;
5981         Par     : Node_Id;
5982
5983      begin
5984         Par := Parent (N);
5985         while Present (Par) loop
5986
5987            --  A traversal from a subunit continues via the corresponding stub
5988
5989            if Nkind (Par) = N_Subunit then
5990               Par := Corresponding_Stub (Par);
5991
5992            --  Stop the traversal when the nearest enclosing non-library-level
5993            --  encapsulator has been reached.
5994
5995            elsif Is_Non_Library_Level_Encapsulator (Par) then
5996               Context := Parent (Par);
5997
5998               --  The sole exception is when the encapsulator is the unit of
5999               --  compilation because this case requires special processing
6000               --  (see below).
6001
6002               if Present (Context)
6003                 and then Nkind (Context) = N_Compilation_Unit
6004               then
6005                  null;
6006
6007               else
6008                  return Par;
6009               end if;
6010
6011            --  Reaching a compilation unit node without hitting a non-library-
6012            --  level encapsulator indicates that N is at the library level in
6013            --  which case the compilation unit is the context.
6014
6015            elsif Nkind (Par) = N_Compilation_Unit then
6016               return Par;
6017            end if;
6018
6019            Par := Parent (Par);
6020         end loop;
6021
6022         return Empty;
6023      end Find_Enclosing_Context;
6024
6025      -----------------------
6026      -- In_Nested_Context --
6027      -----------------------
6028
6029      function In_Nested_Context
6030        (Outer : Node_Id;
6031         Inner : Node_Id) return Boolean
6032      is
6033         Par : Node_Id;
6034
6035      begin
6036         Par := Inner;
6037         while Present (Par) loop
6038
6039            --  A traversal from a subunit continues via the corresponding stub
6040
6041            if Nkind (Par) = N_Subunit then
6042               Par := Corresponding_Stub (Par);
6043
6044            elsif Par = Outer then
6045               return True;
6046            end if;
6047
6048            Par := Parent (Par);
6049         end loop;
6050
6051         return False;
6052      end In_Nested_Context;
6053
6054      --  Local variables
6055
6056      Context_1 : constant Node_Id := Find_Enclosing_Context (N1);
6057      Context_2 : constant Node_Id := Find_Enclosing_Context (N2);
6058
6059   --  Start of processing for In_Same_Context
6060
6061   begin
6062      --  Both nodes appear within the same context
6063
6064      if Context_1 = Context_2 then
6065         return True;
6066
6067      --  Both nodes appear in compilation units. Determine whether one unit
6068      --  is the body of the other.
6069
6070      elsif Nkind (Context_1) = N_Compilation_Unit
6071        and then Nkind (Context_2) = N_Compilation_Unit
6072      then
6073         return
6074           Is_Same_Unit
6075             (Unit_1 => Defining_Entity (Unit (Context_1)),
6076              Unit_2 => Defining_Entity (Unit (Context_2)));
6077
6078      --  The context of N1 encloses the context of N2
6079
6080      elsif Nested_OK and then In_Nested_Context (Context_1, Context_2) then
6081         return True;
6082      end if;
6083
6084      return False;
6085   end In_Same_Context;
6086
6087   ----------------
6088   -- Initialize --
6089   ----------------
6090
6091   procedure Initialize is
6092   begin
6093      --  Set the soft link which enables Atree.Rewrite to update a top-level
6094      --  scenario each time it is transformed into another node.
6095
6096      Set_Rewriting_Proc (Update_Elaboration_Scenario'Access);
6097   end Initialize;
6098
6099   ---------------
6100   -- Info_Call --
6101   ---------------
6102
6103   procedure Info_Call
6104     (Call      : Node_Id;
6105      Target_Id : Entity_Id;
6106      Info_Msg  : Boolean;
6107      In_SPARK  : Boolean)
6108   is
6109      procedure Info_Accept_Alternative;
6110      pragma Inline (Info_Accept_Alternative);
6111      --  Output information concerning an accept alternative
6112
6113      procedure Info_Simple_Call;
6114      pragma Inline (Info_Simple_Call);
6115      --  Output information concerning the call
6116
6117      procedure Info_Type_Actions (Action : String);
6118      pragma Inline (Info_Type_Actions);
6119      --  Output information concerning action Action of a type
6120
6121      procedure Info_Verification_Call
6122        (Pred    : String;
6123         Id      : Entity_Id;
6124         Id_Kind : String);
6125      pragma Inline (Info_Verification_Call);
6126      --  Output information concerning the verification of predicate Pred
6127      --  applied to related entity Id with kind Id_Kind.
6128
6129      -----------------------------
6130      -- Info_Accept_Alternative --
6131      -----------------------------
6132
6133      procedure Info_Accept_Alternative is
6134         Entry_Id : constant Entity_Id := Receiving_Entry (Target_Id);
6135
6136      begin
6137         pragma Assert (Present (Entry_Id));
6138
6139         Elab_Msg_NE
6140           (Msg      => "accept for entry & during elaboration",
6141            N        => Call,
6142            Id       => Entry_Id,
6143            Info_Msg => Info_Msg,
6144            In_SPARK => In_SPARK);
6145      end Info_Accept_Alternative;
6146
6147      ----------------------
6148      -- Info_Simple_Call --
6149      ----------------------
6150
6151      procedure Info_Simple_Call is
6152      begin
6153         Elab_Msg_NE
6154           (Msg      => "call to & during elaboration",
6155            N        => Call,
6156            Id       => Target_Id,
6157            Info_Msg => Info_Msg,
6158            In_SPARK => In_SPARK);
6159      end Info_Simple_Call;
6160
6161      -----------------------
6162      -- Info_Type_Actions --
6163      -----------------------
6164
6165      procedure Info_Type_Actions (Action : String) is
6166         Typ : constant Entity_Id := First_Formal_Type (Target_Id);
6167
6168      begin
6169         pragma Assert (Present (Typ));
6170
6171         Elab_Msg_NE
6172           (Msg      => Action & " actions for type & during elaboration",
6173            N        => Call,
6174            Id       => Typ,
6175            Info_Msg => Info_Msg,
6176            In_SPARK => In_SPARK);
6177      end Info_Type_Actions;
6178
6179      ----------------------------
6180      -- Info_Verification_Call --
6181      ----------------------------
6182
6183      procedure Info_Verification_Call
6184        (Pred    : String;
6185         Id      : Entity_Id;
6186         Id_Kind : String)
6187      is
6188      begin
6189         pragma Assert (Present (Id));
6190
6191         Elab_Msg_NE
6192           (Msg      =>
6193              "verification of " & Pred & " of " & Id_Kind & " & during "
6194              & "elaboration",
6195            N        => Call,
6196            Id       => Id,
6197            Info_Msg => Info_Msg,
6198            In_SPARK => In_SPARK);
6199      end Info_Verification_Call;
6200
6201   --  Start of processing for Info_Call
6202
6203   begin
6204      --  Do not output anything for targets defined in internal units because
6205      --  this creates noise.
6206
6207      if not In_Internal_Unit (Target_Id) then
6208
6209         --  Accept alternative
6210
6211         if Is_Accept_Alternative_Proc (Target_Id) then
6212            Info_Accept_Alternative;
6213
6214         --  Adjustment
6215
6216         elsif Is_TSS (Target_Id, TSS_Deep_Adjust) then
6217            Info_Type_Actions ("adjustment");
6218
6219         --  Default_Initial_Condition
6220
6221         elsif Is_Default_Initial_Condition_Proc (Target_Id) then
6222            Info_Verification_Call
6223              (Pred    => "Default_Initial_Condition",
6224               Id      => First_Formal_Type (Target_Id),
6225               Id_Kind => "type");
6226
6227         --  Entries
6228
6229         elsif Is_Protected_Entry (Target_Id) then
6230            Info_Simple_Call;
6231
6232         --  Task entry calls are never processed because the entry being
6233         --  invoked does not have a corresponding "body", it has a select.
6234
6235         elsif Is_Task_Entry (Target_Id) then
6236            null;
6237
6238         --  Finalization
6239
6240         elsif Is_TSS (Target_Id, TSS_Deep_Finalize) then
6241            Info_Type_Actions ("finalization");
6242
6243         --  Calls to _Finalizer procedures must not appear in the output
6244         --  because this creates confusing noise.
6245
6246         elsif Is_Finalizer_Proc (Target_Id) then
6247            null;
6248
6249         --  Initial_Condition
6250
6251         elsif Is_Initial_Condition_Proc (Target_Id) then
6252            Info_Verification_Call
6253              (Pred    => "Initial_Condition",
6254               Id      => Find_Enclosing_Scope (Call),
6255               Id_Kind => "package");
6256
6257         --  Initialization
6258
6259         elsif Is_Init_Proc (Target_Id)
6260           or else Is_TSS (Target_Id, TSS_Deep_Initialize)
6261         then
6262            Info_Type_Actions ("initialization");
6263
6264         --  Invariant
6265
6266         elsif Is_Invariant_Proc (Target_Id) then
6267            Info_Verification_Call
6268              (Pred    => "invariants",
6269               Id      => First_Formal_Type (Target_Id),
6270               Id_Kind => "type");
6271
6272         --  Partial invariant calls must not appear in the output because this
6273         --  creates confusing noise.
6274
6275         elsif Is_Partial_Invariant_Proc (Target_Id) then
6276            null;
6277
6278         --  _Postconditions
6279
6280         elsif Is_Postconditions_Proc (Target_Id) then
6281            Info_Verification_Call
6282              (Pred    => "postconditions",
6283               Id      => Find_Enclosing_Scope (Call),
6284               Id_Kind => "subprogram");
6285
6286         --  Subprograms must come last because some of the previous cases fall
6287         --  under this category.
6288
6289         elsif Ekind (Target_Id) = E_Function then
6290            Info_Simple_Call;
6291
6292         elsif Ekind (Target_Id) = E_Procedure then
6293            Info_Simple_Call;
6294
6295         else
6296            pragma Assert (False);
6297            null;
6298         end if;
6299      end if;
6300   end Info_Call;
6301
6302   ------------------------
6303   -- Info_Instantiation --
6304   ------------------------
6305
6306   procedure Info_Instantiation
6307     (Inst     : Node_Id;
6308      Gen_Id   : Entity_Id;
6309      Info_Msg : Boolean;
6310      In_SPARK : Boolean)
6311   is
6312   begin
6313      Elab_Msg_NE
6314        (Msg      => "instantiation of & during elaboration",
6315         N        => Inst,
6316         Id       => Gen_Id,
6317         Info_Msg => Info_Msg,
6318         In_SPARK => In_SPARK);
6319   end Info_Instantiation;
6320
6321   -----------------------------
6322   -- Info_Variable_Reference --
6323   -----------------------------
6324
6325   procedure Info_Variable_Reference
6326     (Ref      : Node_Id;
6327      Var_Id   : Entity_Id;
6328      Info_Msg : Boolean;
6329      In_SPARK : Boolean)
6330   is
6331   begin
6332      if Is_Read (Ref) then
6333         Elab_Msg_NE
6334           (Msg      => "read of variable & during elaboration",
6335            N        => Ref,
6336            Id       => Var_Id,
6337            Info_Msg => Info_Msg,
6338            In_SPARK => In_SPARK);
6339      end if;
6340   end Info_Variable_Reference;
6341
6342   --------------------
6343   -- Insertion_Node --
6344   --------------------
6345
6346   function Insertion_Node (N : Node_Id; Ins_Nod : Node_Id) return Node_Id is
6347   begin
6348      --  When the scenario denotes an instantiation, the proper insertion node
6349      --  is the instance spec. This ensures that the generic actuals will not
6350      --  be evaluated prior to a potential ABE.
6351
6352      if Nkind (N) in N_Generic_Instantiation
6353        and then Present (Instance_Spec (N))
6354      then
6355         return Instance_Spec (N);
6356
6357      --  Otherwise the proper insertion node is the candidate insertion node
6358
6359      else
6360         return Ins_Nod;
6361      end if;
6362   end Insertion_Node;
6363
6364   -----------------------
6365   -- Install_ABE_Check --
6366   -----------------------
6367
6368   procedure Install_ABE_Check
6369     (N       : Node_Id;
6370      Id      : Entity_Id;
6371      Ins_Nod : Node_Id)
6372   is
6373      Check_Ins_Nod : constant Node_Id := Insertion_Node (N, Ins_Nod);
6374      --  Insert the check prior to this node
6375
6376      Loc     : constant Source_Ptr := Sloc (N);
6377      Spec_Id : constant Entity_Id  := Unique_Entity (Id);
6378      Unit_Id : constant Entity_Id  := Find_Top_Unit (Id);
6379      Scop_Id : Entity_Id;
6380
6381   begin
6382      --  Nothing to do when compiling for GNATprove because raise statements
6383      --  are not supported.
6384
6385      if GNATprove_Mode then
6386         return;
6387
6388      --  Nothing to do when the compilation will not produce an executable
6389
6390      elsif Serious_Errors_Detected > 0 then
6391         return;
6392
6393      --  Nothing to do for a compilation unit because there is no executable
6394      --  environment at that level.
6395
6396      elsif Nkind (Parent (Check_Ins_Nod)) = N_Compilation_Unit then
6397         return;
6398
6399      --  Nothing to do when the unit is elaborated prior to the main unit.
6400      --  This check must also consider the following cases:
6401
6402      --  * Id's unit appears in the context of the main unit
6403
6404      --  * Id's unit is subject to pragma Elaborate_Body. An ABE check MUST
6405      --    NOT be generated because Id's unit is always elaborated prior to
6406      --    the main unit.
6407
6408      --  * Id's unit is the main unit. An ABE check MUST be generated in this
6409      --    case because a conditional ABE may be raised depending on the flow
6410      --    of execution within the main unit (flag Same_Unit_OK is False).
6411
6412      elsif Has_Prior_Elaboration
6413              (Unit_Id      => Unit_Id,
6414               Context_OK   => True,
6415               Elab_Body_OK => True)
6416      then
6417         return;
6418      end if;
6419
6420      --  Prevent multiple scenarios from installing the same ABE check
6421
6422      Set_Is_Elaboration_Checks_OK_Node (N, False);
6423
6424      --  Install the nearest enclosing scope of the scenario as there must be
6425      --  something on the scope stack.
6426
6427      --  Performance note: parent traversal
6428
6429      Scop_Id := Find_Enclosing_Scope (Check_Ins_Nod);
6430      pragma Assert (Present (Scop_Id));
6431
6432      Push_Scope (Scop_Id);
6433
6434      --  Generate:
6435      --    if not Spec_Id'Elaborated then
6436      --       raise Program_Error with "access before elaboration";
6437      --    end if;
6438
6439      Insert_Action (Check_Ins_Nod,
6440        Make_Raise_Program_Error (Loc,
6441          Condition =>
6442            Make_Op_Not (Loc,
6443              Right_Opnd =>
6444                Make_Attribute_Reference (Loc,
6445                  Prefix         => New_Occurrence_Of (Spec_Id, Loc),
6446                  Attribute_Name => Name_Elaborated)),
6447          Reason    => PE_Access_Before_Elaboration));
6448
6449      Pop_Scope;
6450   end Install_ABE_Check;
6451
6452   -----------------------
6453   -- Install_ABE_Check --
6454   -----------------------
6455
6456   procedure Install_ABE_Check
6457     (N           : Node_Id;
6458      Target_Id   : Entity_Id;
6459      Target_Decl : Node_Id;
6460      Target_Body : Node_Id;
6461      Ins_Nod     : Node_Id)
6462   is
6463      procedure Build_Elaboration_Entity;
6464      pragma Inline (Build_Elaboration_Entity);
6465      --  Create a new elaboration flag for Target_Id, insert it prior to
6466      --  Target_Decl, and set it after Body_Decl.
6467
6468      ------------------------------
6469      -- Build_Elaboration_Entity --
6470      ------------------------------
6471
6472      procedure Build_Elaboration_Entity is
6473         Loc     : constant Source_Ptr := Sloc (Target_Id);
6474         Flag_Id : Entity_Id;
6475
6476      begin
6477         --  Create the declaration of the elaboration flag. The name carries a
6478         --  unique counter in case of name overloading.
6479
6480         Flag_Id :=
6481           Make_Defining_Identifier (Loc,
6482             Chars => New_External_Name (Chars (Target_Id), 'E', -1));
6483
6484         Set_Elaboration_Entity          (Target_Id, Flag_Id);
6485         Set_Elaboration_Entity_Required (Target_Id);
6486
6487         Push_Scope (Scope (Target_Id));
6488
6489         --  Generate:
6490         --    Enn : Short_Integer := 0;
6491
6492         Insert_Action (Target_Decl,
6493           Make_Object_Declaration (Loc,
6494             Defining_Identifier => Flag_Id,
6495             Object_Definition   =>
6496               New_Occurrence_Of (Standard_Short_Integer, Loc),
6497             Expression          => Make_Integer_Literal (Loc, Uint_0)));
6498
6499         --  Generate:
6500         --    Enn := 1;
6501
6502         Set_Elaboration_Flag (Target_Body, Target_Id);
6503
6504         Pop_Scope;
6505      end Build_Elaboration_Entity;
6506
6507      --  Local variables
6508
6509      Target_Unit_Id : constant Entity_Id := Find_Top_Unit (Target_Id);
6510
6511   --  Start for processing for Install_ABE_Check
6512
6513   begin
6514      --  Nothing to do when compiling for GNATprove because raise statements
6515      --  are not supported.
6516
6517      if GNATprove_Mode then
6518         return;
6519
6520      --  Nothing to do when the compilation will not produce an executable
6521
6522      elsif Serious_Errors_Detected > 0 then
6523         return;
6524
6525      --  Nothing to do when the target is a protected subprogram because the
6526      --  check is associated with the protected body subprogram.
6527
6528      elsif Is_Protected_Subp (Target_Id) then
6529         return;
6530
6531      --  Nothing to do when the target is elaborated prior to the main unit.
6532      --  This check must also consider the following cases:
6533
6534      --  * The unit of the target appears in the context of the main unit
6535
6536      --  * The unit of the target is subject to pragma Elaborate_Body. An ABE
6537      --    check MUST NOT be generated because the unit is always elaborated
6538      --    prior to the main unit.
6539
6540      --  * The unit of the target is the main unit. An ABE check MUST be added
6541      --    in this case because a conditional ABE may be raised depending on
6542      --    the flow of execution within the main unit (flag Same_Unit_OK is
6543      --    False).
6544
6545      elsif Has_Prior_Elaboration
6546              (Unit_Id      => Target_Unit_Id,
6547               Context_OK   => True,
6548               Elab_Body_OK => True)
6549      then
6550         return;
6551
6552      --  Create an elaboration flag for the target when it does not have one
6553
6554      elsif No (Elaboration_Entity (Target_Id)) then
6555         Build_Elaboration_Entity;
6556      end if;
6557
6558      Install_ABE_Check
6559        (N       => N,
6560         Ins_Nod => Ins_Nod,
6561         Id      => Target_Id);
6562   end Install_ABE_Check;
6563
6564   -------------------------
6565   -- Install_ABE_Failure --
6566   -------------------------
6567
6568   procedure Install_ABE_Failure (N : Node_Id; Ins_Nod : Node_Id) is
6569      Fail_Ins_Nod : constant Node_Id := Insertion_Node (N, Ins_Nod);
6570      --  Insert the failure prior to this node
6571
6572      Loc     : constant Source_Ptr := Sloc (N);
6573      Scop_Id : Entity_Id;
6574
6575   begin
6576      --  Nothing to do when compiling for GNATprove because raise statements
6577      --  are not supported.
6578
6579      if GNATprove_Mode then
6580         return;
6581
6582      --  Nothing to do when the compilation will not produce an executable
6583
6584      elsif Serious_Errors_Detected > 0 then
6585         return;
6586
6587      --  Do not install an ABE check for a compilation unit because there is
6588      --  no executable environment at that level.
6589
6590      elsif Nkind (Parent (Fail_Ins_Nod)) = N_Compilation_Unit then
6591         return;
6592      end if;
6593
6594      --  Prevent multiple scenarios from installing the same ABE failure
6595
6596      Set_Is_Elaboration_Checks_OK_Node (N, False);
6597
6598      --  Install the nearest enclosing scope of the scenario as there must be
6599      --  something on the scope stack.
6600
6601      --  Performance note: parent traversal
6602
6603      Scop_Id := Find_Enclosing_Scope (Fail_Ins_Nod);
6604      pragma Assert (Present (Scop_Id));
6605
6606      Push_Scope (Scop_Id);
6607
6608      --  Generate:
6609      --    raise Program_Error with "access before elaboration";
6610
6611      Insert_Action (Fail_Ins_Nod,
6612        Make_Raise_Program_Error (Loc,
6613          Reason => PE_Access_Before_Elaboration));
6614
6615      Pop_Scope;
6616   end Install_ABE_Failure;
6617
6618   --------------------------------
6619   -- Is_Accept_Alternative_Proc --
6620   --------------------------------
6621
6622   function Is_Accept_Alternative_Proc (Id : Entity_Id) return Boolean is
6623   begin
6624      --  To qualify, the entity must denote a procedure with a receiving entry
6625
6626      return Ekind (Id) = E_Procedure and then Present (Receiving_Entry (Id));
6627   end Is_Accept_Alternative_Proc;
6628
6629   ------------------------
6630   -- Is_Activation_Proc --
6631   ------------------------
6632
6633   function Is_Activation_Proc (Id : Entity_Id) return Boolean is
6634   begin
6635      --  To qualify, the entity must denote one of the runtime procedures in
6636      --  charge of task activation.
6637
6638      if Ekind (Id) = E_Procedure then
6639         if Restricted_Profile then
6640            return Is_RTE (Id, RE_Activate_Restricted_Tasks);
6641         else
6642            return Is_RTE (Id, RE_Activate_Tasks);
6643         end if;
6644      end if;
6645
6646      return False;
6647   end Is_Activation_Proc;
6648
6649   ----------------------------
6650   -- Is_Ada_Semantic_Target --
6651   ----------------------------
6652
6653   function Is_Ada_Semantic_Target (Id : Entity_Id) return Boolean is
6654   begin
6655      return
6656        Is_Activation_Proc (Id)
6657          or else Is_Controlled_Proc (Id, Name_Adjust)
6658          or else Is_Controlled_Proc (Id, Name_Finalize)
6659          or else Is_Controlled_Proc (Id, Name_Initialize)
6660          or else Is_Init_Proc (Id)
6661          or else Is_Invariant_Proc (Id)
6662          or else Is_Protected_Entry (Id)
6663          or else Is_Protected_Subp (Id)
6664          or else Is_Protected_Body_Subp (Id)
6665          or else Is_Task_Entry (Id);
6666   end Is_Ada_Semantic_Target;
6667
6668   --------------------------------
6669   -- Is_Assertion_Pragma_Target --
6670   --------------------------------
6671
6672   function Is_Assertion_Pragma_Target (Id : Entity_Id) return Boolean is
6673   begin
6674      return
6675        Is_Default_Initial_Condition_Proc (Id)
6676          or else Is_Initial_Condition_Proc (Id)
6677          or else Is_Invariant_Proc (Id)
6678          or else Is_Partial_Invariant_Proc (Id)
6679          or else Is_Postconditions_Proc (Id);
6680   end Is_Assertion_Pragma_Target;
6681
6682   ----------------------------
6683   -- Is_Bodiless_Subprogram --
6684   ----------------------------
6685
6686   function Is_Bodiless_Subprogram (Subp_Id : Entity_Id) return Boolean is
6687   begin
6688      --  An abstract subprogram does not have a body
6689
6690      if Ekind_In (Subp_Id, E_Function,
6691                            E_Operator,
6692                            E_Procedure)
6693        and then Is_Abstract_Subprogram (Subp_Id)
6694      then
6695         return True;
6696
6697      --  A formal subprogram does not have a body
6698
6699      elsif Is_Formal_Subprogram (Subp_Id) then
6700         return True;
6701
6702      --  An imported subprogram may have a body, however it is not known at
6703      --  compile or bind time where the body resides and whether it will be
6704      --  elaborated on time.
6705
6706      elsif Is_Imported (Subp_Id) then
6707         return True;
6708      end if;
6709
6710      return False;
6711   end Is_Bodiless_Subprogram;
6712
6713   ------------------------
6714   -- Is_Controlled_Proc --
6715   ------------------------
6716
6717   function Is_Controlled_Proc
6718     (Subp_Id  : Entity_Id;
6719      Subp_Nam : Name_Id) return Boolean
6720   is
6721      Formal_Id : Entity_Id;
6722
6723   begin
6724      pragma Assert (Nam_In (Subp_Nam, Name_Adjust,
6725                                       Name_Finalize,
6726                                       Name_Initialize));
6727
6728      --  To qualify, the subprogram must denote a source procedure with name
6729      --  Adjust, Finalize, or Initialize where the sole formal is controlled.
6730
6731      if Comes_From_Source (Subp_Id)
6732        and then Ekind (Subp_Id) = E_Procedure
6733        and then Chars (Subp_Id) = Subp_Nam
6734      then
6735         Formal_Id := First_Formal (Subp_Id);
6736
6737         return
6738           Present (Formal_Id)
6739             and then Is_Controlled (Etype (Formal_Id))
6740             and then No (Next_Formal (Formal_Id));
6741      end if;
6742
6743      return False;
6744   end Is_Controlled_Proc;
6745
6746   ---------------------------------------
6747   -- Is_Default_Initial_Condition_Proc --
6748   ---------------------------------------
6749
6750   function Is_Default_Initial_Condition_Proc
6751     (Id : Entity_Id) return Boolean
6752   is
6753   begin
6754      --  To qualify, the entity must denote a Default_Initial_Condition
6755      --  procedure.
6756
6757      return Ekind (Id) = E_Procedure and then Is_DIC_Procedure (Id);
6758   end Is_Default_Initial_Condition_Proc;
6759
6760   -----------------------
6761   -- Is_Finalizer_Proc --
6762   -----------------------
6763
6764   function Is_Finalizer_Proc (Id : Entity_Id) return Boolean is
6765   begin
6766      --  To qualify, the entity must denote a _Finalizer procedure
6767
6768      return Ekind (Id) = E_Procedure and then Chars (Id) = Name_uFinalizer;
6769   end Is_Finalizer_Proc;
6770
6771   -----------------------
6772   -- Is_Guaranteed_ABE --
6773   -----------------------
6774
6775   function Is_Guaranteed_ABE
6776     (N           : Node_Id;
6777      Target_Decl : Node_Id;
6778      Target_Body : Node_Id) return Boolean
6779   is
6780   begin
6781      --  Avoid cascaded errors if there were previous serious infractions.
6782      --  As a result the scenario will not be treated as a guaranteed ABE.
6783      --  This behaviour parallels that of the old ABE mechanism.
6784
6785      if Serious_Errors_Detected > 0 then
6786         return False;
6787
6788      --  The scenario and the target appear within the same context ignoring
6789      --  enclosing library levels.
6790
6791      --  Performance note: parent traversal
6792
6793      elsif In_Same_Context (N, Target_Decl) then
6794
6795         --  The target body has already been encountered. The scenario results
6796         --  in a guaranteed ABE if it appears prior to the body.
6797
6798         if Present (Target_Body) then
6799            return Earlier_In_Extended_Unit (N, Target_Body);
6800
6801         --  Otherwise the body has not been encountered yet. The scenario is
6802         --  a guaranteed ABE since the body will appear later. It is assumed
6803         --  that the caller has already checked whether the scenario is ABE-
6804         --  safe as optional bodies are not considered here.
6805
6806         else
6807            return True;
6808         end if;
6809      end if;
6810
6811      return False;
6812   end Is_Guaranteed_ABE;
6813
6814   -------------------------------
6815   -- Is_Initial_Condition_Proc --
6816   -------------------------------
6817
6818   function Is_Initial_Condition_Proc (Id : Entity_Id) return Boolean is
6819   begin
6820      --  To qualify, the entity must denote an Initial_Condition procedure
6821
6822      return
6823        Ekind (Id) = E_Procedure and then Is_Initial_Condition_Procedure (Id);
6824   end Is_Initial_Condition_Proc;
6825
6826   --------------------
6827   -- Is_Initialized --
6828   --------------------
6829
6830   function Is_Initialized (Obj_Decl : Node_Id) return Boolean is
6831   begin
6832      --  To qualify, the object declaration must have an expression
6833
6834      return
6835        Present (Expression (Obj_Decl)) or else Has_Init_Expression (Obj_Decl);
6836   end Is_Initialized;
6837
6838   -----------------------
6839   -- Is_Invariant_Proc --
6840   -----------------------
6841
6842   function Is_Invariant_Proc (Id : Entity_Id) return Boolean is
6843   begin
6844      --  To qualify, the entity must denote the "full" invariant procedure
6845
6846      return Ekind (Id) = E_Procedure and then Is_Invariant_Procedure (Id);
6847   end Is_Invariant_Proc;
6848
6849   ---------------------------------------
6850   -- Is_Non_Library_Level_Encapsulator --
6851   ---------------------------------------
6852
6853   function Is_Non_Library_Level_Encapsulator (N : Node_Id) return Boolean is
6854   begin
6855      case Nkind (N) is
6856         when N_Abstract_Subprogram_Declaration
6857            | N_Aspect_Specification
6858            | N_Component_Declaration
6859            | N_Entry_Body
6860            | N_Entry_Declaration
6861            | N_Expression_Function
6862            | N_Formal_Abstract_Subprogram_Declaration
6863            | N_Formal_Concrete_Subprogram_Declaration
6864            | N_Formal_Object_Declaration
6865            | N_Formal_Package_Declaration
6866            | N_Formal_Type_Declaration
6867            | N_Generic_Association
6868            | N_Implicit_Label_Declaration
6869            | N_Incomplete_Type_Declaration
6870            | N_Private_Extension_Declaration
6871            | N_Private_Type_Declaration
6872            | N_Protected_Body
6873            | N_Protected_Type_Declaration
6874            | N_Single_Protected_Declaration
6875            | N_Single_Task_Declaration
6876            | N_Subprogram_Body
6877            | N_Subprogram_Declaration
6878            | N_Task_Body
6879            | N_Task_Type_Declaration
6880         =>
6881            return True;
6882
6883         when others =>
6884            return Is_Generic_Declaration_Or_Body (N);
6885      end case;
6886   end Is_Non_Library_Level_Encapsulator;
6887
6888   -------------------------------
6889   -- Is_Partial_Invariant_Proc --
6890   -------------------------------
6891
6892   function Is_Partial_Invariant_Proc (Id : Entity_Id) return Boolean is
6893   begin
6894      --  To qualify, the entity must denote the "partial" invariant procedure
6895
6896      return
6897        Ekind (Id) = E_Procedure and then Is_Partial_Invariant_Procedure (Id);
6898   end Is_Partial_Invariant_Proc;
6899
6900   ----------------------------
6901   -- Is_Postconditions_Proc --
6902   ----------------------------
6903
6904   function Is_Postconditions_Proc (Id : Entity_Id) return Boolean is
6905   begin
6906      --  To qualify, the entity must denote a _Postconditions procedure
6907
6908      return
6909        Ekind (Id) = E_Procedure and then Chars (Id) = Name_uPostconditions;
6910   end Is_Postconditions_Proc;
6911
6912   ---------------------------
6913   -- Is_Preelaborated_Unit --
6914   ---------------------------
6915
6916   function Is_Preelaborated_Unit (Id : Entity_Id) return Boolean is
6917   begin
6918      return
6919        Is_Preelaborated (Id)
6920          or else Is_Pure (Id)
6921          or else Is_Remote_Call_Interface (Id)
6922          or else Is_Remote_Types (Id)
6923          or else Is_Shared_Passive (Id);
6924   end Is_Preelaborated_Unit;
6925
6926   ------------------------
6927   -- Is_Protected_Entry --
6928   ------------------------
6929
6930   function Is_Protected_Entry (Id : Entity_Id) return Boolean is
6931   begin
6932      --  To qualify, the entity must denote an entry defined in a protected
6933      --  type.
6934
6935      return
6936        Is_Entry (Id)
6937          and then Is_Protected_Type (Non_Private_View (Scope (Id)));
6938   end Is_Protected_Entry;
6939
6940   -----------------------
6941   -- Is_Protected_Subp --
6942   -----------------------
6943
6944   function Is_Protected_Subp (Id : Entity_Id) return Boolean is
6945   begin
6946      --  To qualify, the entity must denote a subprogram defined within a
6947      --  protected type.
6948
6949      return
6950        Ekind_In (Id, E_Function, E_Procedure)
6951          and then Is_Protected_Type (Non_Private_View (Scope (Id)));
6952   end Is_Protected_Subp;
6953
6954   ----------------------------
6955   -- Is_Protected_Body_Subp --
6956   ----------------------------
6957
6958   function Is_Protected_Body_Subp (Id : Entity_Id) return Boolean is
6959   begin
6960      --  To qualify, the entity must denote a subprogram with attribute
6961      --  Protected_Subprogram set.
6962
6963      return
6964        Ekind_In (Id, E_Function, E_Procedure)
6965          and then Present (Protected_Subprogram (Id));
6966   end Is_Protected_Body_Subp;
6967
6968   --------------------------------
6969   -- Is_Recorded_SPARK_Scenario --
6970   --------------------------------
6971
6972   function Is_Recorded_SPARK_Scenario (N : Node_Id) return Boolean is
6973   begin
6974      if Recorded_SPARK_Scenarios_In_Use then
6975         return Recorded_SPARK_Scenarios.Get (N);
6976      end if;
6977
6978      return Recorded_SPARK_Scenarios_No_Element;
6979   end Is_Recorded_SPARK_Scenario;
6980
6981   ------------------------------------
6982   -- Is_Recorded_Top_Level_Scenario --
6983   ------------------------------------
6984
6985   function Is_Recorded_Top_Level_Scenario (N : Node_Id) return Boolean is
6986   begin
6987      if Recorded_Top_Level_Scenarios_In_Use then
6988         return Recorded_Top_Level_Scenarios.Get (N);
6989      end if;
6990
6991      return Recorded_Top_Level_Scenarios_No_Element;
6992   end Is_Recorded_Top_Level_Scenario;
6993
6994   ------------------------
6995   -- Is_Safe_Activation --
6996   ------------------------
6997
6998   function Is_Safe_Activation
6999     (Call      : Node_Id;
7000      Task_Decl : Node_Id) return Boolean
7001   is
7002   begin
7003      --  The activation of a task coming from an external instance cannot
7004      --  cause an ABE because the generic was already instantiated. Note
7005      --  that the instantiation itself may lead to an ABE.
7006
7007      return
7008        In_External_Instance
7009          (N           => Call,
7010           Target_Decl => Task_Decl);
7011   end Is_Safe_Activation;
7012
7013   ------------------
7014   -- Is_Safe_Call --
7015   ------------------
7016
7017   function Is_Safe_Call
7018     (Call         : Node_Id;
7019      Target_Attrs : Target_Attributes) return Boolean
7020   is
7021   begin
7022      --  The target is either an abstract subprogram, formal subprogram, or
7023      --  imported, in which case it does not have a body at compile or bind
7024      --  time. Assume that the call is ABE-safe.
7025
7026      if Is_Bodiless_Subprogram (Target_Attrs.Spec_Id) then
7027         return True;
7028
7029      --  The target is an instantiation of a generic subprogram. The call
7030      --  cannot cause an ABE because the generic was already instantiated.
7031      --  Note that the instantiation itself may lead to an ABE.
7032
7033      elsif Is_Generic_Instance (Target_Attrs.Spec_Id) then
7034         return True;
7035
7036      --  The invocation of a target coming from an external instance cannot
7037      --  cause an ABE because the generic was already instantiated. Note that
7038      --  the instantiation itself may lead to an ABE.
7039
7040      elsif In_External_Instance
7041              (N           => Call,
7042               Target_Decl => Target_Attrs.Spec_Decl)
7043      then
7044         return True;
7045
7046      --  The target is a subprogram body without a previous declaration. The
7047      --  call cannot cause an ABE because the body has already been seen.
7048
7049      elsif Nkind (Target_Attrs.Spec_Decl) = N_Subprogram_Body
7050        and then No (Corresponding_Spec (Target_Attrs.Spec_Decl))
7051      then
7052         return True;
7053
7054      --  The target is a subprogram body stub without a prior declaration.
7055      --  The call cannot cause an ABE because the proper body substitutes
7056      --  the stub.
7057
7058      elsif Nkind (Target_Attrs.Spec_Decl) = N_Subprogram_Body_Stub
7059        and then No (Corresponding_Spec_Of_Stub (Target_Attrs.Spec_Decl))
7060      then
7061         return True;
7062
7063      --  Subprogram bodies which wrap attribute references used as actuals
7064      --  in instantiations are always ABE-safe. These bodies are artifacts
7065      --  of expansion.
7066
7067      elsif Present (Target_Attrs.Body_Decl)
7068        and then Nkind (Target_Attrs.Body_Decl) = N_Subprogram_Body
7069        and then Was_Attribute_Reference (Target_Attrs.Body_Decl)
7070      then
7071         return True;
7072      end if;
7073
7074      return False;
7075   end Is_Safe_Call;
7076
7077   ---------------------------
7078   -- Is_Safe_Instantiation --
7079   ---------------------------
7080
7081   function Is_Safe_Instantiation
7082     (Inst      : Node_Id;
7083      Gen_Attrs : Target_Attributes) return Boolean
7084   is
7085   begin
7086      --  The generic is an intrinsic subprogram in which case it does not
7087      --  have a body at compile or bind time. Assume that the instantiation
7088      --  is ABE-safe.
7089
7090      if Is_Bodiless_Subprogram (Gen_Attrs.Spec_Id) then
7091         return True;
7092
7093      --  The instantiation of an external nested generic cannot cause an ABE
7094      --  if the outer generic was already instantiated. Note that the instance
7095      --  of the outer generic may lead to an ABE.
7096
7097      elsif In_External_Instance
7098              (N           => Inst,
7099               Target_Decl => Gen_Attrs.Spec_Decl)
7100      then
7101         return True;
7102
7103      --  The generic is a package. The instantiation cannot cause an ABE when
7104      --  the package has no body.
7105
7106      elsif Ekind (Gen_Attrs.Spec_Id) = E_Generic_Package
7107        and then not Has_Body (Gen_Attrs.Spec_Decl)
7108      then
7109         return True;
7110      end if;
7111
7112      return False;
7113   end Is_Safe_Instantiation;
7114
7115   ------------------
7116   -- Is_Same_Unit --
7117   ------------------
7118
7119   function Is_Same_Unit
7120     (Unit_1 : Entity_Id;
7121      Unit_2 : Entity_Id) return Boolean
7122   is
7123      function Is_Subunit (Unit_Id : Entity_Id) return Boolean;
7124      pragma Inline (Is_Subunit);
7125      --  Determine whether unit Unit_Id is a subunit
7126
7127      function Normalize_Unit (Unit_Id : Entity_Id) return Entity_Id;
7128      --  Strip a potential subunit chain ending with unit Unit_Id and return
7129      --  the corresponding spec.
7130
7131      ----------------
7132      -- Is_Subunit --
7133      ----------------
7134
7135      function Is_Subunit (Unit_Id : Entity_Id) return Boolean is
7136      begin
7137         return Nkind (Parent (Unit_Declaration_Node (Unit_Id))) = N_Subunit;
7138      end Is_Subunit;
7139
7140      --------------------
7141      -- Normalize_Unit --
7142      --------------------
7143
7144      function Normalize_Unit (Unit_Id : Entity_Id) return Entity_Id is
7145         Result : Entity_Id;
7146
7147      begin
7148         --  Eliminate a potential chain of subunits to reach to proper body
7149
7150         Result := Unit_Id;
7151         while Present (Result)
7152           and then Result /= Standard_Standard
7153           and then Is_Subunit (Result)
7154         loop
7155            Result := Scope (Result);
7156         end loop;
7157
7158         --  Obtain the entity of the corresponding spec (if any)
7159
7160         return Unique_Entity (Result);
7161      end Normalize_Unit;
7162
7163   --  Start of processing for Is_Same_Unit
7164
7165   begin
7166      return Normalize_Unit (Unit_1) = Normalize_Unit (Unit_2);
7167   end Is_Same_Unit;
7168
7169   -----------------
7170   -- Is_Scenario --
7171   -----------------
7172
7173   function Is_Scenario (N : Node_Id) return Boolean is
7174   begin
7175      case Nkind (N) is
7176         when N_Assignment_Statement
7177            | N_Attribute_Reference
7178            | N_Call_Marker
7179            | N_Entry_Call_Statement
7180            | N_Expanded_Name
7181            | N_Function_Call
7182            | N_Function_Instantiation
7183            | N_Identifier
7184            | N_Package_Instantiation
7185            | N_Procedure_Call_Statement
7186            | N_Procedure_Instantiation
7187            | N_Requeue_Statement
7188         =>
7189            return True;
7190
7191         when others =>
7192            return False;
7193      end case;
7194   end Is_Scenario;
7195
7196   ------------------------------
7197   -- Is_SPARK_Semantic_Target --
7198   ------------------------------
7199
7200   function Is_SPARK_Semantic_Target (Id : Entity_Id) return Boolean is
7201   begin
7202      return
7203        Is_Default_Initial_Condition_Proc (Id)
7204          or else Is_Initial_Condition_Proc (Id);
7205   end Is_SPARK_Semantic_Target;
7206
7207   ------------------------
7208   -- Is_Suitable_Access --
7209   ------------------------
7210
7211   function Is_Suitable_Access (N : Node_Id) return Boolean is
7212      Nam     : Name_Id;
7213      Pref    : Node_Id;
7214      Subp_Id : Entity_Id;
7215
7216   begin
7217      --  This scenario is relevant only when the static model is in effect
7218      --  because it is graph-dependent and does not involve any run-time
7219      --  checks. Allowing it in the dynamic model would create confusing
7220      --  noise.
7221
7222      if not Static_Elaboration_Checks then
7223         return False;
7224
7225      --  Nothing to do when switch -gnatd.U (ignore 'Access) is in effect
7226
7227      elsif Debug_Flag_Dot_UU then
7228         return False;
7229
7230      --  Nothing to do when the scenario is not an attribute reference
7231
7232      elsif Nkind (N) /= N_Attribute_Reference then
7233         return False;
7234
7235      --  Nothing to do for internally-generated attributes because they are
7236      --  assumed to be ABE safe.
7237
7238      elsif not Comes_From_Source (N) then
7239         return False;
7240      end if;
7241
7242      Nam  := Attribute_Name (N);
7243      Pref := Prefix (N);
7244
7245      --  Sanitize the prefix of the attribute
7246
7247      if not Is_Entity_Name (Pref) then
7248         return False;
7249
7250      elsif No (Entity (Pref)) then
7251         return False;
7252      end if;
7253
7254      Subp_Id := Entity (Pref);
7255
7256      if not Is_Subprogram_Or_Entry (Subp_Id) then
7257         return False;
7258      end if;
7259
7260      --  Traverse a possible chain of renamings to obtain the original entry
7261      --  or subprogram which the prefix may rename.
7262
7263      Subp_Id := Get_Renamed_Entity (Subp_Id);
7264
7265      --  To qualify, the attribute must meet the following prerequisites:
7266
7267      return
7268
7269        --  The prefix must denote a source entry, operator, or subprogram
7270        --  which is not imported.
7271
7272        Comes_From_Source (Subp_Id)
7273          and then Is_Subprogram_Or_Entry (Subp_Id)
7274          and then not Is_Bodiless_Subprogram (Subp_Id)
7275
7276          --  The attribute name must be one of the 'Access forms. Note that
7277          --  'Unchecked_Access cannot apply to a subprogram.
7278
7279          and then Nam_In (Nam, Name_Access, Name_Unrestricted_Access);
7280   end Is_Suitable_Access;
7281
7282   ----------------------
7283   -- Is_Suitable_Call --
7284   ----------------------
7285
7286   function Is_Suitable_Call (N : Node_Id) return Boolean is
7287   begin
7288      --  Entry and subprogram calls are intentionally ignored because they
7289      --  may undergo expansion depending on the compilation mode, previous
7290      --  errors, generic context, etc. Call markers play the role of calls
7291      --  and provide a uniform foundation for ABE processing.
7292
7293      return Nkind (N) = N_Call_Marker;
7294   end Is_Suitable_Call;
7295
7296   -------------------------------
7297   -- Is_Suitable_Instantiation --
7298   -------------------------------
7299
7300   function Is_Suitable_Instantiation (N : Node_Id) return Boolean is
7301      Orig_N : constant Node_Id := Original_Node (N);
7302      --  Use the original node in case an instantiation library unit is
7303      --  rewritten as a package or subprogram.
7304
7305   begin
7306      --  To qualify, the instantiation must come from source
7307
7308      return
7309        Comes_From_Source (Orig_N)
7310          and then Nkind (Orig_N) in N_Generic_Instantiation;
7311   end Is_Suitable_Instantiation;
7312
7313   --------------------------
7314   -- Is_Suitable_Scenario --
7315   --------------------------
7316
7317   function Is_Suitable_Scenario (N : Node_Id) return Boolean is
7318   begin
7319      --  NOTE: Derived types and pragma Refined_State are intentionally left
7320      --  out because they are not executable during elaboration.
7321
7322      return
7323        Is_Suitable_Access (N)
7324          or else Is_Suitable_Call (N)
7325          or else Is_Suitable_Instantiation (N)
7326          or else Is_Suitable_Variable_Assignment (N)
7327          or else Is_Suitable_Variable_Reference (N);
7328   end Is_Suitable_Scenario;
7329
7330   ------------------------------------
7331   -- Is_Suitable_SPARK_Derived_Type --
7332   ------------------------------------
7333
7334   function Is_Suitable_SPARK_Derived_Type (N : Node_Id) return Boolean is
7335      Prag : Node_Id;
7336      Typ  : Entity_Id;
7337
7338   begin
7339      --  To qualify, the type declaration must denote a derived tagged type
7340      --  with primitive operations, subject to pragma SPARK_Mode On.
7341
7342      if Nkind (N) = N_Full_Type_Declaration
7343        and then Nkind (Type_Definition (N)) = N_Derived_Type_Definition
7344      then
7345         Typ  := Defining_Entity (N);
7346         Prag := SPARK_Pragma (Typ);
7347
7348         return
7349           Is_Tagged_Type (Typ)
7350             and then Has_Primitive_Operations (Typ)
7351             and then Present (Prag)
7352             and then Get_SPARK_Mode_From_Annotation (Prag) = On;
7353      end if;
7354
7355      return False;
7356   end Is_Suitable_SPARK_Derived_Type;
7357
7358   -------------------------------------
7359   -- Is_Suitable_SPARK_Instantiation --
7360   -------------------------------------
7361
7362   function Is_Suitable_SPARK_Instantiation (N : Node_Id) return Boolean is
7363      Gen_Attrs  : Target_Attributes;
7364      Gen_Id     : Entity_Id;
7365      Inst       : Node_Id;
7366      Inst_Attrs : Instantiation_Attributes;
7367      Inst_Id    : Entity_Id;
7368
7369   begin
7370      --  To qualify, both the instantiation and the generic must be subject to
7371      --  SPARK_Mode On.
7372
7373      if Is_Suitable_Instantiation (N) then
7374         Extract_Instantiation_Attributes
7375           (Exp_Inst => N,
7376            Inst     => Inst,
7377            Inst_Id  => Inst_Id,
7378            Gen_Id   => Gen_Id,
7379            Attrs    => Inst_Attrs);
7380
7381         Extract_Target_Attributes (Gen_Id, Gen_Attrs);
7382
7383         return Inst_Attrs.SPARK_Mode_On and Gen_Attrs.SPARK_Mode_On;
7384      end if;
7385
7386      return False;
7387   end Is_Suitable_SPARK_Instantiation;
7388
7389   --------------------------------------------
7390   -- Is_Suitable_SPARK_Refined_State_Pragma --
7391   --------------------------------------------
7392
7393   function Is_Suitable_SPARK_Refined_State_Pragma
7394     (N : Node_Id) return Boolean
7395   is
7396   begin
7397      --  To qualfy, the pragma must denote Refined_State
7398
7399      return
7400        Nkind (N) = N_Pragma
7401          and then Pragma_Name (N) = Name_Refined_State;
7402   end Is_Suitable_SPARK_Refined_State_Pragma;
7403
7404   -------------------------------------
7405   -- Is_Suitable_Variable_Assignment --
7406   -------------------------------------
7407
7408   function Is_Suitable_Variable_Assignment (N : Node_Id) return Boolean is
7409      N_Unit      : Node_Id;
7410      N_Unit_Id   : Entity_Id;
7411      Nam         : Node_Id;
7412      Var_Decl    : Node_Id;
7413      Var_Id      : Entity_Id;
7414      Var_Unit    : Node_Id;
7415      Var_Unit_Id : Entity_Id;
7416
7417   begin
7418      --  This scenario is relevant only when the static model is in effect
7419      --  because it is graph-dependent and does not involve any run-time
7420      --  checks. Allowing it in the dynamic model would create confusing
7421      --  noise.
7422
7423      if not Static_Elaboration_Checks then
7424         return False;
7425
7426      --  Nothing to do when the scenario is not an assignment
7427
7428      elsif Nkind (N) /= N_Assignment_Statement then
7429         return False;
7430
7431      --  Nothing to do for internally-generated assignments because they are
7432      --  assumed to be ABE safe.
7433
7434      elsif not Comes_From_Source (N) then
7435         return False;
7436
7437      --  Assignments are ignored in GNAT mode on the assumption that they are
7438      --  ABE-safe. This behaviour parallels that of the old ABE mechanism.
7439
7440      elsif GNAT_Mode then
7441         return False;
7442      end if;
7443
7444      Nam := Extract_Assignment_Name (N);
7445
7446      --  Sanitize the left hand side of the assignment
7447
7448      if not Is_Entity_Name (Nam) then
7449         return False;
7450
7451      elsif No (Entity (Nam)) then
7452         return False;
7453      end if;
7454
7455      Var_Id := Entity (Nam);
7456
7457      --  Sanitize the variable
7458
7459      if Var_Id = Any_Id then
7460         return False;
7461
7462      elsif Ekind (Var_Id) /= E_Variable then
7463         return False;
7464      end if;
7465
7466      Var_Decl := Declaration_Node (Var_Id);
7467
7468      if Nkind (Var_Decl) /= N_Object_Declaration then
7469         return False;
7470      end if;
7471
7472      N_Unit_Id := Find_Top_Unit (N);
7473      N_Unit    := Unit_Declaration_Node (N_Unit_Id);
7474
7475      Var_Unit_Id := Find_Top_Unit (Var_Decl);
7476      Var_Unit    := Unit_Declaration_Node (Var_Unit_Id);
7477
7478      --  To qualify, the assignment must meet the following prerequisites:
7479
7480      return
7481        Comes_From_Source (Var_Id)
7482
7483          --  The variable must be declared in the spec of compilation unit U
7484
7485          and then Nkind (Var_Unit) = N_Package_Declaration
7486
7487          --  Performance note: parent traversal
7488
7489          and then Find_Enclosing_Level (Var_Decl) = Package_Spec
7490
7491          --  The assignment must occur in the body of compilation unit U
7492
7493          and then Nkind (N_Unit) = N_Package_Body
7494          and then Present (Corresponding_Body (Var_Unit))
7495          and then Corresponding_Body (Var_Unit) = N_Unit_Id;
7496   end Is_Suitable_Variable_Assignment;
7497
7498   ------------------------------------
7499   -- Is_Suitable_Variable_Reference --
7500   ------------------------------------
7501
7502   function Is_Suitable_Variable_Reference (N : Node_Id) return Boolean is
7503   begin
7504      --  Expanded names and identifiers are intentionally ignored because they
7505      --  be folded, optimized away, etc. Variable references markers play the
7506      --  role of variable references and provide a uniform foundation for ABE
7507      --  processing.
7508
7509      return Nkind (N) = N_Variable_Reference_Marker;
7510   end Is_Suitable_Variable_Reference;
7511
7512   -------------------
7513   -- Is_Task_Entry --
7514   -------------------
7515
7516   function Is_Task_Entry (Id : Entity_Id) return Boolean is
7517   begin
7518      --  To qualify, the entity must denote an entry defined in a task type
7519
7520      return
7521        Is_Entry (Id) and then Is_Task_Type (Non_Private_View (Scope (Id)));
7522   end Is_Task_Entry;
7523
7524   ------------------------
7525   -- Is_Up_Level_Target --
7526   ------------------------
7527
7528   function Is_Up_Level_Target (Target_Decl : Node_Id) return Boolean is
7529      Root : constant Node_Id := Root_Scenario;
7530
7531   begin
7532      --  The root appears within the declaratons of a block statement, entry
7533      --  body, subprogram body, or task body ignoring enclosing packages. The
7534      --  root is always within the main unit. An up-level target is a notion
7535      --  applicable only to the static model because scenarios are reached by
7536      --  means of graph traversal started from a fixed declarative or library
7537      --  level.
7538
7539      --  Performance note: parent traversal
7540
7541      if Static_Elaboration_Checks
7542        and then Find_Enclosing_Level (Root) = Declaration_Level
7543      then
7544         --  The target is within the main unit. It acts as an up-level target
7545         --  when it appears within a context which encloses the root.
7546
7547         --    package body Main_Unit is
7548         --       function Func ...;             --  target
7549
7550         --       procedure Proc is
7551         --          X : ... := Func;            --  root scenario
7552
7553         if In_Extended_Main_Code_Unit (Target_Decl) then
7554
7555            --  Performance note: parent traversal
7556
7557            return not In_Same_Context (Root, Target_Decl, Nested_OK => True);
7558
7559         --  Otherwise the target is external to the main unit which makes it
7560         --  an up-level target.
7561
7562         else
7563            return True;
7564         end if;
7565      end if;
7566
7567      return False;
7568   end Is_Up_Level_Target;
7569
7570   ---------------------
7571   -- Is_Visited_Body --
7572   ---------------------
7573
7574   function Is_Visited_Body (Body_Decl : Node_Id) return Boolean is
7575   begin
7576      if Visited_Bodies_In_Use then
7577         return Visited_Bodies.Get (Body_Decl);
7578      end if;
7579
7580      return Visited_Bodies_No_Element;
7581   end Is_Visited_Body;
7582
7583   -------------------------------
7584   -- Kill_Elaboration_Scenario --
7585   -------------------------------
7586
7587   procedure Kill_Elaboration_Scenario (N : Node_Id) is
7588      procedure Kill_SPARK_Scenario;
7589      pragma Inline (Kill_SPARK_Scenario);
7590      --  Eliminate scenario N from table SPARK_Scenarios if it is recorded
7591      --  there.
7592
7593      procedure Kill_Top_Level_Scenario;
7594      pragma Inline (Kill_Top_Level_Scenario);
7595      --  Eliminate scenario N from table Top_Level_Scenarios if it is recorded
7596      --  there.
7597
7598      -------------------------
7599      -- Kill_SPARK_Scenario --
7600      -------------------------
7601
7602      procedure Kill_SPARK_Scenario is
7603         package Scenarios renames SPARK_Scenarios;
7604
7605      begin
7606         if Is_Recorded_SPARK_Scenario (N) then
7607
7608            --  Performance note: list traversal
7609
7610            for Index in Scenarios.First .. Scenarios.Last loop
7611               if Scenarios.Table (Index) = N then
7612                  Scenarios.Table (Index) := Empty;
7613
7614                  --  The SPARK scenario is no longer recorded
7615
7616                  Set_Is_Recorded_SPARK_Scenario (N, False);
7617                  return;
7618               end if;
7619            end loop;
7620
7621            --  A recorded SPARK scenario must be in the table of recorded
7622            --  SPARK scenarios.
7623
7624            pragma Assert (False);
7625         end if;
7626      end Kill_SPARK_Scenario;
7627
7628      -----------------------------
7629      -- Kill_Top_Level_Scenario --
7630      -----------------------------
7631
7632      procedure Kill_Top_Level_Scenario is
7633         package Scenarios renames Top_Level_Scenarios;
7634
7635      begin
7636         if Is_Recorded_Top_Level_Scenario (N) then
7637
7638            --  Performance node: list traversal
7639
7640            for Index in Scenarios.First .. Scenarios.Last loop
7641               if Scenarios.Table (Index) = N then
7642                  Scenarios.Table (Index) := Empty;
7643
7644                  --  The top-level scenario is no longer recorded
7645
7646                  Set_Is_Recorded_Top_Level_Scenario (N, False);
7647                  return;
7648               end if;
7649            end loop;
7650
7651            --  A recorded top-level scenario must be in the table of recorded
7652            --  top-level scenarios.
7653
7654            pragma Assert (False);
7655         end if;
7656      end Kill_Top_Level_Scenario;
7657
7658   --  Start of processing for Kill_Elaboration_Scenario
7659
7660   begin
7661      --  Nothing to do when switch -gnatH (legacy elaboration checking mode
7662      --  enabled) is in effect because the legacy ABE lechanism does not need
7663      --  to carry out this action.
7664
7665      if Legacy_Elaboration_Checks then
7666         return;
7667      end if;
7668
7669      --  Eliminate a recorded scenario when it appears within dead code
7670      --  because it will not be executed at elaboration time.
7671
7672      if Is_Scenario (N) then
7673         Kill_SPARK_Scenario;
7674         Kill_Top_Level_Scenario;
7675      end if;
7676   end Kill_Elaboration_Scenario;
7677
7678   ----------------------------------
7679   -- Meet_Elaboration_Requirement --
7680   ----------------------------------
7681
7682   procedure Meet_Elaboration_Requirement
7683     (N         : Node_Id;
7684      Target_Id : Entity_Id;
7685      Req_Nam   : Name_Id)
7686   is
7687      Main_Id : constant Entity_Id := Cunit_Entity (Main_Unit);
7688      Unit_Id : constant Entity_Id := Find_Top_Unit (Target_Id);
7689
7690      function Find_Preelaboration_Pragma
7691        (Prag_Nam : Name_Id) return Node_Id;
7692      pragma Inline (Find_Preelaboration_Pragma);
7693      --  Traverse the visible declarations of unit Unit_Id and locate a source
7694      --  preelaboration-related pragma with name Prag_Nam.
7695
7696      procedure Info_Requirement_Met (Prag : Node_Id);
7697      pragma Inline (Info_Requirement_Met);
7698      --  Output information concerning pragma Prag which meets requirement
7699      --  Req_Nam.
7700
7701      procedure Info_Scenario;
7702      pragma Inline (Info_Scenario);
7703      --  Output information concerning scenario N
7704
7705      --------------------------------
7706      -- Find_Preelaboration_Pragma --
7707      --------------------------------
7708
7709      function Find_Preelaboration_Pragma
7710        (Prag_Nam : Name_Id) return Node_Id
7711      is
7712         Spec : constant Node_Id := Parent (Unit_Id);
7713         Decl : Node_Id;
7714
7715      begin
7716         --  A preelaboration-related pragma comes from source and appears at
7717         --  the top of the visible declarations of a package.
7718
7719         if Nkind (Spec) = N_Package_Specification then
7720            Decl := First (Visible_Declarations (Spec));
7721            while Present (Decl) loop
7722               if Comes_From_Source (Decl) then
7723                  if Nkind (Decl) = N_Pragma
7724                    and then Pragma_Name (Decl) = Prag_Nam
7725                  then
7726                     return Decl;
7727
7728                  --  Otherwise the construct terminates the region where the
7729                  --  preelabortion-related pragma may appear.
7730
7731                  else
7732                     exit;
7733                  end if;
7734               end if;
7735
7736               Next (Decl);
7737            end loop;
7738         end if;
7739
7740         return Empty;
7741      end Find_Preelaboration_Pragma;
7742
7743      --------------------------
7744      -- Info_Requirement_Met --
7745      --------------------------
7746
7747      procedure Info_Requirement_Met (Prag : Node_Id) is
7748      begin
7749         pragma Assert (Present (Prag));
7750
7751         Error_Msg_Name_1 := Req_Nam;
7752         Error_Msg_Sloc   := Sloc (Prag);
7753         Error_Msg_NE
7754           ("\\% requirement for unit & met by pragma #", N, Unit_Id);
7755      end Info_Requirement_Met;
7756
7757      -------------------
7758      -- Info_Scenario --
7759      -------------------
7760
7761      procedure Info_Scenario is
7762      begin
7763         if Is_Suitable_Call (N) then
7764            Info_Call
7765              (Call      => N,
7766               Target_Id => Target_Id,
7767               Info_Msg  => False,
7768               In_SPARK  => True);
7769
7770         elsif Is_Suitable_Instantiation (N) then
7771            Info_Instantiation
7772              (Inst     => N,
7773               Gen_Id   => Target_Id,
7774               Info_Msg => False,
7775               In_SPARK => True);
7776
7777         elsif Is_Suitable_SPARK_Refined_State_Pragma (N) then
7778            Error_Msg_N
7779              ("read of refinement constituents during elaboration in SPARK",
7780               N);
7781
7782         elsif Is_Suitable_Variable_Reference (N) then
7783            Info_Variable_Reference
7784              (Ref      => N,
7785               Var_Id   => Target_Id,
7786               Info_Msg => False,
7787               In_SPARK => True);
7788
7789         --  No other scenario may impose a requirement on the context of the
7790         --  main unit.
7791
7792         else
7793            pragma Assert (False);
7794            null;
7795         end if;
7796      end Info_Scenario;
7797
7798      --  Local variables
7799
7800      Elab_Attrs : Elaboration_Attributes;
7801      Elab_Nam   : Name_Id;
7802      Req_Met    : Boolean;
7803
7804   --  Start of processing for Meet_Elaboration_Requirement
7805
7806   begin
7807      pragma Assert (Nam_In (Req_Nam, Name_Elaborate, Name_Elaborate_All));
7808
7809      --  Assume that the requirement has not been met
7810
7811      Req_Met := False;
7812
7813      --  Elaboration requirements are verified only when the static model is
7814      --  in effect because this diagnostic is graph-dependent.
7815
7816      if not Static_Elaboration_Checks then
7817         return;
7818
7819      --  If the target is within the main unit, either at the source level or
7820      --  through an instantiation, then there is no real requirement to meet
7821      --  because the main unit cannot force its own elaboration by means of an
7822      --  Elaborate[_All] pragma. Treat this case as valid coverage.
7823
7824      elsif In_Extended_Main_Code_Unit (Target_Id) then
7825         Req_Met := True;
7826
7827      --  Otherwise the target resides in an external unit
7828
7829      --  The requirement is met when the target comes from an internal unit
7830      --  because such a unit is elaborated prior to a non-internal unit.
7831
7832      elsif In_Internal_Unit (Unit_Id)
7833        and then not In_Internal_Unit (Main_Id)
7834      then
7835         Req_Met := True;
7836
7837      --  The requirement is met when the target comes from a preelaborated
7838      --  unit. This portion must parallel predicate Is_Preelaborated_Unit.
7839
7840      elsif Is_Preelaborated_Unit (Unit_Id) then
7841         Req_Met := True;
7842
7843         --  Output extra information when switch -gnatel (info messages on
7844         --  implicit Elaborate[_All] pragmas.
7845
7846         if Elab_Info_Messages then
7847            if Is_Preelaborated (Unit_Id) then
7848               Elab_Nam := Name_Preelaborate;
7849
7850            elsif Is_Pure (Unit_Id) then
7851               Elab_Nam := Name_Pure;
7852
7853            elsif Is_Remote_Call_Interface (Unit_Id) then
7854               Elab_Nam := Name_Remote_Call_Interface;
7855
7856            elsif Is_Remote_Types (Unit_Id) then
7857               Elab_Nam := Name_Remote_Types;
7858
7859            else
7860               pragma Assert (Is_Shared_Passive (Unit_Id));
7861               Elab_Nam := Name_Shared_Passive;
7862            end if;
7863
7864            Info_Requirement_Met (Find_Preelaboration_Pragma (Elab_Nam));
7865         end if;
7866
7867      --  Determine whether the context of the main unit has a pragma strong
7868      --  enough to meet the requirement.
7869
7870      else
7871         Elab_Attrs := Elaboration_Status (Unit_Id);
7872
7873         --  The pragma must be either Elaborate_All or be as strong as the
7874         --  requirement.
7875
7876         if Present (Elab_Attrs.Source_Pragma)
7877           and then Nam_In (Pragma_Name (Elab_Attrs.Source_Pragma),
7878                            Name_Elaborate_All,
7879                            Req_Nam)
7880         then
7881            Req_Met := True;
7882
7883            --  Output extra information when switch -gnatel (info messages on
7884            --  implicit Elaborate[_All] pragmas.
7885
7886            if Elab_Info_Messages then
7887               Info_Requirement_Met (Elab_Attrs.Source_Pragma);
7888            end if;
7889         end if;
7890      end if;
7891
7892      --  The requirement was not met by the context of the main unit, issue an
7893      --  error.
7894
7895      if not Req_Met then
7896         Info_Scenario;
7897
7898         Error_Msg_Name_1 := Req_Nam;
7899         Error_Msg_Node_2 := Unit_Id;
7900         Error_Msg_NE ("\\unit & requires pragma % for &", N, Main_Id);
7901
7902         Output_Active_Scenarios (N);
7903      end if;
7904   end Meet_Elaboration_Requirement;
7905
7906   ----------------------
7907   -- Non_Private_View --
7908   ----------------------
7909
7910   function Non_Private_View (Typ : Entity_Id) return Entity_Id is
7911      Result : Entity_Id;
7912
7913   begin
7914      Result := Typ;
7915
7916      if Is_Private_Type (Result) and then Present (Full_View (Result)) then
7917         Result := Full_View (Result);
7918      end if;
7919
7920      return Result;
7921   end Non_Private_View;
7922
7923   -----------------------------
7924   -- Output_Active_Scenarios --
7925   -----------------------------
7926
7927   procedure Output_Active_Scenarios (Error_Nod : Node_Id) is
7928      procedure Output_Access (N : Node_Id);
7929      --  Emit a specific diagnostic message for 'Access denote by N
7930
7931      procedure Output_Activation_Call (N : Node_Id);
7932      --  Emit a specific diagnostic message for task activation N
7933
7934      procedure Output_Call (N : Node_Id; Target_Id : Entity_Id);
7935      --  Emit a specific diagnostic message for call N which invokes target
7936      --  Target_Id.
7937
7938      procedure Output_Header;
7939      --  Emit a specific diagnostic message for the unit of the root scenario
7940
7941      procedure Output_Instantiation (N : Node_Id);
7942      --  Emit a specific diagnostic message for instantiation N
7943
7944      procedure Output_SPARK_Refined_State_Pragma (N : Node_Id);
7945      --  Emit a specific diagnostic message for Refined_State pragma N
7946
7947      procedure Output_Variable_Assignment (N : Node_Id);
7948      --  Emit a specific diagnostic message for assignment statement N
7949
7950      procedure Output_Variable_Reference (N : Node_Id);
7951      --  Emit a specific diagnostic message for reference N which mentions a
7952      --  variable.
7953
7954      -------------------
7955      -- Output_Access --
7956      -------------------
7957
7958      procedure Output_Access (N : Node_Id) is
7959         Subp_Id : constant Entity_Id := Entity (Prefix (N));
7960
7961      begin
7962         Error_Msg_Name_1 := Attribute_Name (N);
7963         Error_Msg_Sloc   := Sloc (N);
7964         Error_Msg_NE ("\\  % of & taken #", Error_Nod, Subp_Id);
7965      end Output_Access;
7966
7967      ----------------------------
7968      -- Output_Activation_Call --
7969      ----------------------------
7970
7971      procedure Output_Activation_Call (N : Node_Id) is
7972         function Find_Activator (Call : Node_Id) return Entity_Id;
7973         --  Find the nearest enclosing construct which houses call Call
7974
7975         --------------------
7976         -- Find_Activator --
7977         --------------------
7978
7979         function Find_Activator (Call : Node_Id) return Entity_Id is
7980            Par : Node_Id;
7981
7982         begin
7983            --  Climb the parent chain looking for a package [body] or a
7984            --  construct with a statement sequence.
7985
7986            Par := Parent (Call);
7987            while Present (Par) loop
7988               if Nkind_In (Par, N_Package_Body, N_Package_Declaration) then
7989                  return Defining_Entity (Par);
7990
7991               elsif Nkind (Par) = N_Handled_Sequence_Of_Statements then
7992                  return Defining_Entity (Parent (Par));
7993               end if;
7994
7995               Par := Parent (Par);
7996            end loop;
7997
7998            return Empty;
7999         end Find_Activator;
8000
8001         --  Local variables
8002
8003         Activator : constant Entity_Id := Find_Activator (N);
8004
8005      --  Start of processing for Output_Activation_Call
8006
8007      begin
8008         pragma Assert (Present (Activator));
8009
8010         Error_Msg_NE ("\\  local tasks of & activated", Error_Nod, Activator);
8011      end Output_Activation_Call;
8012
8013      -----------------
8014      -- Output_Call --
8015      -----------------
8016
8017      procedure Output_Call (N : Node_Id; Target_Id : Entity_Id) is
8018         procedure Output_Accept_Alternative;
8019         pragma Inline (Output_Accept_Alternative);
8020         --  Emit a specific diagnostic message concerning an accept
8021         --  alternative.
8022
8023         procedure Output_Call (Kind : String);
8024         pragma Inline (Output_Call);
8025         --  Emit a specific diagnostic message concerning a call of kind Kind
8026
8027         procedure Output_Type_Actions (Action : String);
8028         pragma Inline (Output_Type_Actions);
8029         --  Emit a specific diagnostic message concerning action Action of a
8030         --  type.
8031
8032         procedure Output_Verification_Call
8033           (Pred    : String;
8034            Id      : Entity_Id;
8035            Id_Kind : String);
8036         pragma Inline (Output_Verification_Call);
8037         --  Emit a specific diagnostic message concerning the verification of
8038         --  predicate Pred applied to related entity Id with kind Id_Kind.
8039
8040         -------------------------------
8041         -- Output_Accept_Alternative --
8042         -------------------------------
8043
8044         procedure Output_Accept_Alternative is
8045            Entry_Id : constant Entity_Id := Receiving_Entry (Target_Id);
8046
8047         begin
8048            pragma Assert (Present (Entry_Id));
8049
8050            Error_Msg_NE ("\\  entry & selected #", Error_Nod, Entry_Id);
8051         end Output_Accept_Alternative;
8052
8053         -----------------
8054         -- Output_Call --
8055         -----------------
8056
8057         procedure Output_Call (Kind : String) is
8058         begin
8059            Error_Msg_NE ("\\  " & Kind & " & called #", Error_Nod, Target_Id);
8060         end Output_Call;
8061
8062         -------------------------
8063         -- Output_Type_Actions --
8064         -------------------------
8065
8066         procedure Output_Type_Actions (Action : String) is
8067            Typ : constant Entity_Id := First_Formal_Type (Target_Id);
8068
8069         begin
8070            pragma Assert (Present (Typ));
8071
8072            Error_Msg_NE
8073              ("\\  " & Action & " actions for type & #", Error_Nod, Typ);
8074         end Output_Type_Actions;
8075
8076         ------------------------------
8077         -- Output_Verification_Call --
8078         ------------------------------
8079
8080         procedure Output_Verification_Call
8081           (Pred    : String;
8082            Id      : Entity_Id;
8083            Id_Kind : String)
8084         is
8085         begin
8086            pragma Assert (Present (Id));
8087
8088            Error_Msg_NE
8089              ("\\  " & Pred & " of " & Id_Kind & " & verified #",
8090               Error_Nod, Id);
8091         end Output_Verification_Call;
8092
8093      --  Start of processing for Output_Call
8094
8095      begin
8096         Error_Msg_Sloc := Sloc (N);
8097
8098         --  Accept alternative
8099
8100         if Is_Accept_Alternative_Proc (Target_Id) then
8101            Output_Accept_Alternative;
8102
8103         --  Adjustment
8104
8105         elsif Is_TSS (Target_Id, TSS_Deep_Adjust) then
8106            Output_Type_Actions ("adjustment");
8107
8108         --  Default_Initial_Condition
8109
8110         elsif Is_Default_Initial_Condition_Proc (Target_Id) then
8111            Output_Verification_Call
8112              (Pred    => "Default_Initial_Condition",
8113               Id      => First_Formal_Type (Target_Id),
8114               Id_Kind => "type");
8115
8116         --  Entries
8117
8118         elsif Is_Protected_Entry (Target_Id) then
8119            Output_Call ("entry");
8120
8121         --  Task entry calls are never processed because the entry being
8122         --  invoked does not have a corresponding "body", it has a select. A
8123         --  task entry call appears in the stack of active scenarios for the
8124         --  sole purpose of checking No_Entry_Calls_In_Elaboration_Code and
8125         --  nothing more.
8126
8127         elsif Is_Task_Entry (Target_Id) then
8128            null;
8129
8130         --  Finalization
8131
8132         elsif Is_TSS (Target_Id, TSS_Deep_Finalize) then
8133            Output_Type_Actions ("finalization");
8134
8135         --  Calls to _Finalizer procedures must not appear in the output
8136         --  because this creates confusing noise.
8137
8138         elsif Is_Finalizer_Proc (Target_Id) then
8139            null;
8140
8141         --  Initial_Condition
8142
8143         elsif Is_Initial_Condition_Proc (Target_Id) then
8144            Output_Verification_Call
8145              (Pred    => "Initial_Condition",
8146               Id      => Find_Enclosing_Scope (N),
8147               Id_Kind => "package");
8148
8149         --  Initialization
8150
8151         elsif Is_Init_Proc (Target_Id)
8152           or else Is_TSS (Target_Id, TSS_Deep_Initialize)
8153         then
8154            Output_Type_Actions ("initialization");
8155
8156         --  Invariant
8157
8158         elsif Is_Invariant_Proc (Target_Id) then
8159            Output_Verification_Call
8160              (Pred    => "invariants",
8161               Id      => First_Formal_Type (Target_Id),
8162               Id_Kind => "type");
8163
8164         --  Partial invariant calls must not appear in the output because this
8165         --  creates confusing noise. Note that a partial invariant is always
8166         --  invoked by the "full" invariant which is already placed on the
8167         --  stack.
8168
8169         elsif Is_Partial_Invariant_Proc (Target_Id) then
8170            null;
8171
8172         --  _Postconditions
8173
8174         elsif Is_Postconditions_Proc (Target_Id) then
8175            Output_Verification_Call
8176              (Pred    => "postconditions",
8177               Id      => Find_Enclosing_Scope (N),
8178               Id_Kind => "subprogram");
8179
8180         --  Subprograms must come last because some of the previous cases fall
8181         --  under this category.
8182
8183         elsif Ekind (Target_Id) = E_Function then
8184            Output_Call ("function");
8185
8186         elsif Ekind (Target_Id) = E_Procedure then
8187            Output_Call ("procedure");
8188
8189         else
8190            pragma Assert (False);
8191            null;
8192         end if;
8193      end Output_Call;
8194
8195      -------------------
8196      -- Output_Header --
8197      -------------------
8198
8199      procedure Output_Header is
8200         Unit_Id : constant Entity_Id := Find_Top_Unit (Root_Scenario);
8201
8202      begin
8203         if Ekind (Unit_Id) = E_Package then
8204            Error_Msg_NE ("\\  spec of unit & elaborated", Error_Nod, Unit_Id);
8205
8206         elsif Ekind (Unit_Id) = E_Package_Body then
8207            Error_Msg_NE ("\\  body of unit & elaborated", Error_Nod, Unit_Id);
8208
8209         else
8210            Error_Msg_NE ("\\  in body of unit &", Error_Nod, Unit_Id);
8211         end if;
8212      end Output_Header;
8213
8214      --------------------------
8215      -- Output_Instantiation --
8216      --------------------------
8217
8218      procedure Output_Instantiation (N : Node_Id) is
8219         procedure Output_Instantiation (Gen_Id : Entity_Id; Kind : String);
8220         pragma Inline (Output_Instantiation);
8221         --  Emit a specific diagnostic message concerning an instantiation of
8222         --  generic unit Gen_Id. Kind denotes the kind of the instantiation.
8223
8224         --------------------------
8225         -- Output_Instantiation --
8226         --------------------------
8227
8228         procedure Output_Instantiation (Gen_Id : Entity_Id; Kind : String) is
8229         begin
8230            Error_Msg_NE
8231              ("\\  " & Kind & " & instantiated as & #", Error_Nod, Gen_Id);
8232         end Output_Instantiation;
8233
8234         --  Local variables
8235
8236         Inst       : Node_Id;
8237         Inst_Attrs : Instantiation_Attributes;
8238         Inst_Id    : Entity_Id;
8239         Gen_Id     : Entity_Id;
8240
8241      --  Start of processing for Output_Instantiation
8242
8243      begin
8244         Extract_Instantiation_Attributes
8245           (Exp_Inst => N,
8246            Inst     => Inst,
8247            Inst_Id  => Inst_Id,
8248            Gen_Id   => Gen_Id,
8249            Attrs    => Inst_Attrs);
8250
8251         Error_Msg_Node_2 := Inst_Id;
8252         Error_Msg_Sloc   := Sloc (Inst);
8253
8254         if Nkind (Inst) = N_Function_Instantiation then
8255            Output_Instantiation (Gen_Id, "function");
8256
8257         elsif Nkind (Inst) = N_Package_Instantiation then
8258            Output_Instantiation (Gen_Id, "package");
8259
8260         elsif Nkind (Inst) = N_Procedure_Instantiation then
8261            Output_Instantiation (Gen_Id, "procedure");
8262
8263         else
8264            pragma Assert (False);
8265            null;
8266         end if;
8267      end Output_Instantiation;
8268
8269      ---------------------------------------
8270      -- Output_SPARK_Refined_State_Pragma --
8271      ---------------------------------------
8272
8273      procedure Output_SPARK_Refined_State_Pragma (N : Node_Id) is
8274      begin
8275         Error_Msg_Sloc := Sloc (N);
8276         Error_Msg_N ("\\  refinement constituents read #", Error_Nod);
8277      end Output_SPARK_Refined_State_Pragma;
8278
8279      --------------------------------
8280      -- Output_Variable_Assignment --
8281      --------------------------------
8282
8283      procedure Output_Variable_Assignment (N : Node_Id) is
8284         Var_Id : constant Entity_Id := Entity (Extract_Assignment_Name (N));
8285
8286      begin
8287         Error_Msg_Sloc := Sloc (N);
8288         Error_Msg_NE ("\\  variable & assigned #", Error_Nod, Var_Id);
8289      end Output_Variable_Assignment;
8290
8291      -------------------------------
8292      -- Output_Variable_Reference --
8293      -------------------------------
8294
8295      procedure Output_Variable_Reference (N : Node_Id) is
8296         Dummy  : Variable_Attributes;
8297         Var_Id : Entity_Id;
8298
8299      begin
8300         Extract_Variable_Reference_Attributes
8301           (Ref    => N,
8302            Var_Id => Var_Id,
8303            Attrs  => Dummy);
8304
8305         Error_Msg_Sloc := Sloc (N);
8306
8307         if Is_Read (N) then
8308            Error_Msg_NE ("\\  variable & read #", Error_Nod, Var_Id);
8309
8310         else
8311            pragma Assert (False);
8312            null;
8313         end if;
8314      end Output_Variable_Reference;
8315
8316      --  Local variables
8317
8318      package Stack renames Scenario_Stack;
8319
8320      Dummy     : Call_Attributes;
8321      N         : Node_Id;
8322      Posted    : Boolean;
8323      Target_Id : Entity_Id;
8324
8325   --  Start of processing for Output_Active_Scenarios
8326
8327   begin
8328      --  Active scenarios are emitted only when the static model is in effect
8329      --  because there is an inherent order by which all these scenarios were
8330      --  reached from the declaration or library level.
8331
8332      if not Static_Elaboration_Checks then
8333         return;
8334      end if;
8335
8336      Posted := False;
8337
8338      for Index in Stack.First .. Stack.Last loop
8339         N := Stack.Table (Index);
8340
8341         if not Posted then
8342            Posted := True;
8343            Output_Header;
8344         end if;
8345
8346         --  'Access
8347
8348         if Nkind (N) = N_Attribute_Reference then
8349            Output_Access (N);
8350
8351         --  Calls
8352
8353         elsif Is_Suitable_Call (N) then
8354            Extract_Call_Attributes
8355              (Call      => N,
8356               Target_Id => Target_Id,
8357               Attrs     => Dummy);
8358
8359            if Is_Activation_Proc (Target_Id) then
8360               Output_Activation_Call (N);
8361            else
8362               Output_Call (N, Target_Id);
8363            end if;
8364
8365         --  Instantiations
8366
8367         elsif Is_Suitable_Instantiation (N) then
8368            Output_Instantiation (N);
8369
8370         --  Pragma Refined_State
8371
8372         elsif Is_Suitable_SPARK_Refined_State_Pragma (N) then
8373            Output_SPARK_Refined_State_Pragma (N);
8374
8375         --  Variable assignments
8376
8377         elsif Nkind (N) = N_Assignment_Statement then
8378            Output_Variable_Assignment (N);
8379
8380         --  Variable references
8381
8382         elsif Is_Suitable_Variable_Reference (N) then
8383            Output_Variable_Reference (N);
8384
8385         else
8386            pragma Assert (False);
8387            null;
8388         end if;
8389      end loop;
8390   end Output_Active_Scenarios;
8391
8392   -------------------------
8393   -- Pop_Active_Scenario --
8394   -------------------------
8395
8396   procedure Pop_Active_Scenario (N : Node_Id) is
8397      Top : Node_Id renames Scenario_Stack.Table (Scenario_Stack.Last);
8398
8399   begin
8400      pragma Assert (Top = N);
8401      Scenario_Stack.Decrement_Last;
8402   end Pop_Active_Scenario;
8403
8404   --------------------------------
8405   -- Process_Activation_Generic --
8406   --------------------------------
8407
8408   procedure Process_Activation_Generic
8409     (Call       : Node_Id;
8410      Call_Attrs : Call_Attributes;
8411      State      : Processing_Attributes)
8412   is
8413      procedure Process_Task_Object (Obj_Id : Entity_Id; Typ : Entity_Id);
8414      --  Perform ABE checks and diagnostics for object Obj_Id with type Typ.
8415      --  Typ may be a task type or a composite type with at least one task
8416      --  component.
8417
8418      procedure Process_Task_Objects (List : List_Id);
8419      --  Perform ABE checks and diagnostics for all task objects found in
8420      --  the list List.
8421
8422      -------------------------
8423      -- Process_Task_Object --
8424      -------------------------
8425
8426      procedure Process_Task_Object (Obj_Id : Entity_Id; Typ : Entity_Id) is
8427         Base_Typ : constant Entity_Id := Base_Type (Typ);
8428
8429         Comp_Id    : Entity_Id;
8430         Task_Attrs : Task_Attributes;
8431
8432      begin
8433         if Is_Task_Type (Typ) then
8434            Extract_Task_Attributes
8435              (Typ   => Base_Typ,
8436               Attrs => Task_Attrs);
8437
8438            Process_Single_Activation
8439              (Call       => Call,
8440               Call_Attrs => Call_Attrs,
8441               Obj_Id     => Obj_Id,
8442               Task_Attrs => Task_Attrs,
8443               State      => State);
8444
8445         --  Examine the component type when the object is an array
8446
8447         elsif Is_Array_Type (Typ) and then Has_Task (Base_Typ) then
8448            Process_Task_Object (Obj_Id, Component_Type (Typ));
8449
8450         --  Examine individual component types when the object is a record
8451
8452         elsif Is_Record_Type (Typ) and then Has_Task (Base_Typ) then
8453            Comp_Id := First_Component (Typ);
8454            while Present (Comp_Id) loop
8455               Process_Task_Object (Obj_Id, Etype (Comp_Id));
8456               Next_Component (Comp_Id);
8457            end loop;
8458         end if;
8459      end Process_Task_Object;
8460
8461      --------------------------
8462      -- Process_Task_Objects --
8463      --------------------------
8464
8465      procedure Process_Task_Objects (List : List_Id) is
8466         Item     : Node_Id;
8467         Item_Id  : Entity_Id;
8468         Item_Typ : Entity_Id;
8469
8470      begin
8471         --  Examine the contents of the list looking for an object declaration
8472         --  of a task type or one that contains a task within.
8473
8474         Item := First (List);
8475         while Present (Item) loop
8476            if Nkind (Item) = N_Object_Declaration then
8477               Item_Id  := Defining_Entity (Item);
8478               Item_Typ := Etype (Item_Id);
8479
8480               if Has_Task (Item_Typ) then
8481                  Process_Task_Object (Item_Id, Item_Typ);
8482               end if;
8483            end if;
8484
8485            Next (Item);
8486         end loop;
8487      end Process_Task_Objects;
8488
8489      --  Local variables
8490
8491      Context : Node_Id;
8492      Spec    : Node_Id;
8493
8494   --  Start of processing for Process_Activation_Generic
8495
8496   begin
8497      --  Nothing to do when the activation is a guaranteed ABE
8498
8499      if Is_Known_Guaranteed_ABE (Call) then
8500         return;
8501      end if;
8502
8503      --  Find the proper context of the activation call where all task objects
8504      --  being activated are declared. This is usually the immediate parent of
8505      --  the call.
8506
8507      Context := Parent (Call);
8508
8509      --  In the case of package bodies, the activation call is in the handled
8510      --  sequence of statements, but the task objects are in the declaration
8511      --  list of the body.
8512
8513      if Nkind (Context) = N_Handled_Sequence_Of_Statements
8514        and then Nkind (Parent (Context)) = N_Package_Body
8515      then
8516         Context := Parent (Context);
8517      end if;
8518
8519      --  Process all task objects defined in both the spec and body when the
8520      --  activation call precedes the "begin" of a package body.
8521
8522      if Nkind (Context) = N_Package_Body then
8523         Spec :=
8524           Specification
8525             (Unit_Declaration_Node (Corresponding_Spec (Context)));
8526
8527         Process_Task_Objects (Visible_Declarations (Spec));
8528         Process_Task_Objects (Private_Declarations (Spec));
8529         Process_Task_Objects (Declarations (Context));
8530
8531      --  Process all task objects defined in the spec when the activation call
8532      --  appears at the end of a package spec.
8533
8534      elsif Nkind (Context) = N_Package_Specification then
8535         Process_Task_Objects (Visible_Declarations (Context));
8536         Process_Task_Objects (Private_Declarations (Context));
8537
8538      --  Otherwise the context of the activation is some construct with a
8539      --  declarative part. Note that the corresponding record type of a task
8540      --  type is controlled. Because of this, the finalization machinery must
8541      --  relocate the task object to the handled statements of the construct
8542      --  to perform proper finalization in case of an exception. Examine the
8543      --  statements of the construct rather than the declarations.
8544
8545      else
8546         pragma Assert (Nkind (Context) = N_Handled_Sequence_Of_Statements);
8547
8548         Process_Task_Objects (Statements (Context));
8549      end if;
8550   end Process_Activation_Generic;
8551
8552   ------------------------------------
8553   -- Process_Conditional_ABE_Access --
8554   ------------------------------------
8555
8556   procedure Process_Conditional_ABE_Access
8557     (Attr  : Node_Id;
8558      State : Processing_Attributes)
8559   is
8560      function Build_Access_Marker (Target_Id : Entity_Id) return Node_Id;
8561      pragma Inline (Build_Access_Marker);
8562      --  Create a suitable call marker which invokes target Target_Id
8563
8564      -------------------------
8565      -- Build_Access_Marker --
8566      -------------------------
8567
8568      function Build_Access_Marker (Target_Id : Entity_Id) return Node_Id is
8569         Marker : Node_Id;
8570
8571      begin
8572         Marker := Make_Call_Marker (Sloc (Attr));
8573
8574         --  Inherit relevant attributes from the attribute
8575
8576         --  Performance note: parent traversal
8577
8578         Set_Target (Marker, Target_Id);
8579         Set_Is_Declaration_Level_Node
8580                    (Marker, Find_Enclosing_Level (Attr) = Declaration_Level);
8581         Set_Is_Dispatching_Call
8582                    (Marker, False);
8583         Set_Is_Elaboration_Checks_OK_Node
8584                    (Marker, Is_Elaboration_Checks_OK_Node (Attr));
8585         Set_Is_Source_Call
8586                    (Marker, Comes_From_Source (Attr));
8587         Set_Is_SPARK_Mode_On_Node
8588                    (Marker, Is_SPARK_Mode_On_Node (Attr));
8589
8590         --  Partially insert the call marker into the tree by setting its
8591         --  parent pointer.
8592
8593         Set_Parent (Marker, Attr);
8594
8595         return Marker;
8596      end Build_Access_Marker;
8597
8598      --  Local variables
8599
8600      Root      : constant Node_Id   := Root_Scenario;
8601      Target_Id : constant Entity_Id := Entity (Prefix (Attr));
8602
8603      Target_Attrs : Target_Attributes;
8604
8605   --  Start of processing for Process_Conditional_ABE_Access
8606
8607   begin
8608      --  Output relevant information when switch -gnatel (info messages on
8609      --  implicit Elaborate[_All] pragmas) is in effect.
8610
8611      if Elab_Info_Messages then
8612         Error_Msg_NE
8613           ("info: access to & during elaboration", Attr, Target_Id);
8614      end if;
8615
8616      Extract_Target_Attributes
8617        (Target_Id => Target_Id,
8618         Attrs     => Target_Attrs);
8619
8620      --  Both the attribute and the corresponding body are in the same unit.
8621      --  The corresponding body must appear prior to the root scenario which
8622      --  started the recursive search. If this is not the case, then there is
8623      --  a potential ABE if the access value is used to call the subprogram.
8624      --  Emit a warning only when switch -gnatw.f (warnings on suspucious
8625      --  'Access) is in effect.
8626
8627      if Warn_On_Elab_Access
8628        and then Present (Target_Attrs.Body_Decl)
8629        and then In_Extended_Main_Code_Unit (Target_Attrs.Body_Decl)
8630        and then Earlier_In_Extended_Unit (Root, Target_Attrs.Body_Decl)
8631      then
8632         Error_Msg_Name_1 := Attribute_Name (Attr);
8633         Error_Msg_NE ("??% attribute of & before body seen", Attr, Target_Id);
8634         Error_Msg_N ("\possible Program_Error on later references", Attr);
8635
8636         Output_Active_Scenarios (Attr);
8637      end if;
8638
8639      --  Treat the attribute as an immediate invocation of the target when
8640      --  switch -gnatd.o (conservative elaboration order for indirect calls)
8641      --  is in effect. Note that the prior elaboration of the unit containing
8642      --  the target is ensured processing the corresponding call marker.
8643
8644      if Debug_Flag_Dot_O then
8645         Process_Conditional_ABE
8646           (N     => Build_Access_Marker (Target_Id),
8647            State => State);
8648
8649      --  Otherwise ensure that the unit with the corresponding body is
8650      --  elaborated prior to the main unit.
8651
8652      else
8653         Ensure_Prior_Elaboration
8654           (N        => Attr,
8655            Unit_Id  => Target_Attrs.Unit_Id,
8656            Prag_Nam => Name_Elaborate_All,
8657            State    => State);
8658      end if;
8659   end Process_Conditional_ABE_Access;
8660
8661   ---------------------------------------------
8662   -- Process_Conditional_ABE_Activation_Impl --
8663   ---------------------------------------------
8664
8665   procedure Process_Conditional_ABE_Activation_Impl
8666     (Call       : Node_Id;
8667      Call_Attrs : Call_Attributes;
8668      Obj_Id     : Entity_Id;
8669      Task_Attrs : Task_Attributes;
8670      State      : Processing_Attributes)
8671   is
8672      Check_OK : constant Boolean :=
8673                   not Is_Ignored_Ghost_Entity (Obj_Id)
8674                     and then not Task_Attrs.Ghost_Mode_Ignore
8675                     and then Is_Elaboration_Checks_OK_Id (Obj_Id)
8676                     and then Task_Attrs.Elab_Checks_OK;
8677      --  A run-time ABE check may be installed only when the object and the
8678      --  task type have active elaboration checks, and both are not ignored
8679      --  Ghost constructs.
8680
8681      Root : constant Node_Id := Root_Scenario;
8682
8683      New_State : Processing_Attributes := State;
8684      --  Each step of the Processing phase constitutes a new state
8685
8686   begin
8687      --  Output relevant information when switch -gnatel (info messages on
8688      --  implicit Elaborate[_All] pragmas) is in effect.
8689
8690      if Elab_Info_Messages then
8691         Error_Msg_NE
8692           ("info: activation of & during elaboration", Call, Obj_Id);
8693      end if;
8694
8695      --  Nothing to do when the call activates a task whose type is defined
8696      --  within an instance and switch -gnatd_i (ignore activations and calls
8697      --  to instances for elaboration) is in effect.
8698
8699      if Debug_Flag_Underscore_I
8700        and then In_External_Instance
8701                   (N           => Call,
8702                    Target_Decl => Task_Attrs.Task_Decl)
8703      then
8704         return;
8705
8706      --  Nothing to do when the activation is a guaranteed ABE
8707
8708      elsif Is_Known_Guaranteed_ABE (Call) then
8709         return;
8710
8711      --  Nothing to do when the root scenario appears at the declaration
8712      --  level and the task is in the same unit, but outside this context.
8713      --
8714      --    task type Task_Typ;                  --  task declaration
8715      --
8716      --    procedure Proc is
8717      --       function A ... is
8718      --       begin
8719      --          if Some_Condition then
8720      --             declare
8721      --                T : Task_Typ;
8722      --             begin
8723      --                <activation call>        --  activation site
8724      --             end;
8725      --          ...
8726      --       end A;
8727      --
8728      --       X : ... := A;                     --  root scenario
8729      --    ...
8730      --
8731      --    task body Task_Typ is
8732      --       ...
8733      --    end Task_Typ;
8734      --
8735      --  In the example above, the context of X is the declarative list of
8736      --  Proc. The "elaboration" of X may reach the activation of T whose body
8737      --  is defined outside of X's context. The task body is relevant only
8738      --  when Proc is invoked, but this happens only in "normal" elaboration,
8739      --  therefore the task body must not be considered if this is not the
8740      --  case.
8741
8742      --  Performance note: parent traversal
8743
8744      elsif Is_Up_Level_Target (Task_Attrs.Task_Decl) then
8745         return;
8746
8747      --  Nothing to do when the activation is ABE-safe
8748      --
8749      --    generic
8750      --    package Gen is
8751      --       task type Task_Typ;
8752      --    end Gen;
8753      --
8754      --    package body Gen is
8755      --       task body Task_Typ is
8756      --       begin
8757      --          ...
8758      --       end Task_Typ;
8759      --    end Gen;
8760      --
8761      --    with Gen;
8762      --    procedure Main is
8763      --       package Nested is
8764      --          package Inst is new Gen;
8765      --          T : Inst.Task_Typ;
8766      --          <activation call>              --  safe activation
8767      --       end Nested;
8768      --    ...
8769
8770      elsif Is_Safe_Activation (Call, Task_Attrs.Task_Decl) then
8771
8772         --  Note that the task body must still be examined for any nested
8773         --  scenarios.
8774
8775         null;
8776
8777      --  The activation call and the task body are both in the main unit
8778
8779      elsif Present (Task_Attrs.Body_Decl)
8780        and then In_Extended_Main_Code_Unit (Task_Attrs.Body_Decl)
8781      then
8782         --  If the root scenario appears prior to the task body, then this is
8783         --  a possible ABE with respect to the root scenario.
8784         --
8785         --    task type Task_Typ;
8786         --
8787         --    function A ... is
8788         --    begin
8789         --       if Some_Condition then
8790         --          declare
8791         --             package Pack is
8792         --                T : Task_Typ;
8793         --             end Pack;                --  activation of T
8794         --       ...
8795         --    end A;
8796         --
8797         --    X : ... := A;                     --  root scenario
8798         --
8799         --    task body Task_Typ is             --  task body
8800         --       ...
8801         --    end Task_Typ;
8802         --
8803         --    Y : ... := A;                     --  root scenario
8804         --
8805         --  IMPORTANT: The activation of T is a possible ABE for X, but
8806         --  not for Y. Intalling an unconditional ABE raise prior to the
8807         --  activation call would be wrong as it will fail for Y as well
8808         --  but in Y's case the activation of T is never an ABE.
8809
8810         if Earlier_In_Extended_Unit (Root, Task_Attrs.Body_Decl) then
8811
8812            --  Do not emit any ABE diagnostics when the activation occurs in
8813            --  a partial finalization context because this leads to confusing
8814            --  noise.
8815
8816            if State.Within_Partial_Finalization then
8817               null;
8818
8819            --  ABE diagnostics are emitted only in the static model because
8820            --  there is a well-defined order to visiting scenarios. Without
8821            --  this order diagnostics appear jumbled and result in unwanted
8822            --  noise.
8823
8824            elsif Static_Elaboration_Checks
8825              and then Call_Attrs.Elab_Warnings_OK
8826            then
8827               Error_Msg_Sloc := Sloc (Call);
8828               Error_Msg_N
8829                 ("??task & will be activated # before elaboration of its "
8830                  & "body", Obj_Id);
8831               Error_Msg_N
8832                 ("\Program_Error may be raised at run time", Obj_Id);
8833
8834               Output_Active_Scenarios (Obj_Id);
8835            end if;
8836
8837            --  Install a conditional run-time ABE check to verify that the
8838            --  task body has been elaborated prior to the activation call.
8839
8840            if Check_OK then
8841               Install_ABE_Check
8842                 (N           => Call,
8843                  Ins_Nod     => Call,
8844                  Target_Id   => Task_Attrs.Spec_Id,
8845                  Target_Decl => Task_Attrs.Task_Decl,
8846                  Target_Body => Task_Attrs.Body_Decl);
8847
8848               --  Update the state of the Processing phase to indicate that
8849               --  no implicit Elaborate[_All] pragmas must be generated from
8850               --  this point on.
8851               --
8852               --    task type Task_Typ;
8853               --
8854               --    function A ... is
8855               --    begin
8856               --       if Some_Condition then
8857               --          declare
8858               --             package Pack is
8859               --                <ABE check>
8860               --                T : Task_Typ;
8861               --             end Pack;          --  activation of T
8862               --       ...
8863               --    end A;
8864               --
8865               --    X : ... := A;
8866               --
8867               --    task body Task_Typ is
8868               --    begin
8869               --       External.Subp;           --  imparts Elaborate_All
8870               --    end Task_Typ;
8871               --
8872               --  If Some_Condition is True, then the ABE check will fail at
8873               --  runtime and the call to External.Subp will never take place,
8874               --  rendering the implicit Elaborate_All useless.
8875               --
8876               --  If Some_Condition is False, then the call to External.Subp
8877               --  will never take place, rendering the implicit Elaborate_All
8878               --  useless.
8879
8880               New_State.Suppress_Implicit_Pragmas := True;
8881            end if;
8882         end if;
8883
8884      --  Otherwise the task body is not available in this compilation or it
8885      --  resides in an external unit. Install a run-time ABE check to verify
8886      --  that the task body has been elaborated prior to the activation call
8887      --  when the dynamic model is in effect.
8888
8889      elsif Dynamic_Elaboration_Checks and then Check_OK then
8890         Install_ABE_Check
8891           (N       => Call,
8892            Ins_Nod => Call,
8893            Id      => Task_Attrs.Unit_Id);
8894      end if;
8895
8896      --  Update the state of the Processing phase to indicate that any further
8897      --  traversal is now within a task body.
8898
8899      New_State.Within_Task_Body := True;
8900
8901      --  Both the activation call and task type are subject to SPARK_Mode
8902      --  On, this triggers the SPARK rules for task activation. Compared to
8903      --  calls and instantiations, task activation in SPARK does not require
8904      --  the presence of Elaborate[_All] pragmas in case the task type is
8905      --  defined outside the main unit. This is because SPARK utilizes a
8906      --  special policy which activates all tasks after the main unit has
8907      --  finished its elaboration.
8908
8909      if Call_Attrs.SPARK_Mode_On and Task_Attrs.SPARK_Mode_On then
8910         null;
8911
8912      --  Otherwise the Ada rules are in effect. Ensure that the unit with the
8913      --  task body is elaborated prior to the main unit.
8914
8915      else
8916         Ensure_Prior_Elaboration
8917           (N        => Call,
8918            Unit_Id  => Task_Attrs.Unit_Id,
8919            Prag_Nam => Name_Elaborate_All,
8920            State    => New_State);
8921      end if;
8922
8923      Traverse_Body
8924        (N     => Task_Attrs.Body_Decl,
8925         State => New_State);
8926   end Process_Conditional_ABE_Activation_Impl;
8927
8928   procedure Process_Conditional_ABE_Activation is
8929     new Process_Activation_Generic (Process_Conditional_ABE_Activation_Impl);
8930
8931   ----------------------------------
8932   -- Process_Conditional_ABE_Call --
8933   ----------------------------------
8934
8935   procedure Process_Conditional_ABE_Call
8936     (Call       : Node_Id;
8937      Call_Attrs : Call_Attributes;
8938      Target_Id  : Entity_Id;
8939      State      : Processing_Attributes)
8940   is
8941      function In_Initialization_Context (N : Node_Id) return Boolean;
8942      --  Determine whether arbitrary node N appears within a type init proc,
8943      --  primitive [Deep_]Initialize, or a block created for initialization
8944      --  purposes.
8945
8946      function Is_Partial_Finalization_Proc return Boolean;
8947      pragma Inline (Is_Partial_Finalization_Proc);
8948      --  Determine whether call Call with target Target_Id invokes a partial
8949      --  finalization procedure.
8950
8951      -------------------------------
8952      -- In_Initialization_Context --
8953      -------------------------------
8954
8955      function In_Initialization_Context (N : Node_Id) return Boolean is
8956         Par     : Node_Id;
8957         Spec_Id : Entity_Id;
8958
8959      begin
8960         --  Climb the parent chain looking for initialization actions
8961
8962         Par := Parent (N);
8963         while Present (Par) loop
8964
8965            --  A block may be part of the initialization actions of a default
8966            --  initialized object.
8967
8968            if Nkind (Par) = N_Block_Statement
8969              and then Is_Initialization_Block (Par)
8970            then
8971               return True;
8972
8973            --  A subprogram body may denote an initialization routine
8974
8975            elsif Nkind (Par) = N_Subprogram_Body then
8976               Spec_Id := Unique_Defining_Entity (Par);
8977
8978               --  The current subprogram body denotes a type init proc or
8979               --  primitive [Deep_]Initialize.
8980
8981               if Is_Init_Proc (Spec_Id)
8982                 or else Is_Controlled_Proc (Spec_Id, Name_Initialize)
8983                 or else Is_TSS (Spec_Id, TSS_Deep_Initialize)
8984               then
8985                  return True;
8986               end if;
8987
8988            --  Prevent the search from going too far
8989
8990            elsif Is_Body_Or_Package_Declaration (Par) then
8991               exit;
8992            end if;
8993
8994            Par := Parent (Par);
8995         end loop;
8996
8997         return False;
8998      end In_Initialization_Context;
8999
9000      ----------------------------------
9001      -- Is_Partial_Finalization_Proc --
9002      ----------------------------------
9003
9004      function Is_Partial_Finalization_Proc return Boolean is
9005      begin
9006         --  To qualify, the target must denote primitive [Deep_]Finalize or a
9007         --  finalizer procedure, and the call must appear in an initialization
9008         --  context.
9009
9010         return
9011           (Is_Controlled_Proc (Target_Id, Name_Finalize)
9012              or else Is_Finalizer_Proc (Target_Id)
9013              or else Is_TSS (Target_Id, TSS_Deep_Finalize))
9014            and then In_Initialization_Context (Call);
9015      end Is_Partial_Finalization_Proc;
9016
9017      --  Local variables
9018
9019      SPARK_Rules_On : Boolean;
9020      Target_Attrs   : Target_Attributes;
9021
9022      New_State : Processing_Attributes := State;
9023      --  Each step of the Processing phase constitutes a new state
9024
9025   --  Start of processing for Process_Conditional_ABE_Call
9026
9027   begin
9028      Extract_Target_Attributes
9029        (Target_Id => Target_Id,
9030         Attrs     => Target_Attrs);
9031
9032      --  The SPARK rules are in effect when both the call and target are
9033      --  subject to SPARK_Mode On.
9034
9035      SPARK_Rules_On :=
9036        Call_Attrs.SPARK_Mode_On and Target_Attrs.SPARK_Mode_On;
9037
9038      --  Output relevant information when switch -gnatel (info messages on
9039      --  implicit Elaborate[_All] pragmas) is in effect.
9040
9041      if Elab_Info_Messages then
9042         Info_Call
9043           (Call      => Call,
9044            Target_Id => Target_Id,
9045            Info_Msg  => True,
9046            In_SPARK  => SPARK_Rules_On);
9047      end if;
9048
9049      --  Check whether the invocation of an entry clashes with an existing
9050      --  restriction.
9051
9052      if Is_Protected_Entry (Target_Id) then
9053         Check_Restriction (No_Entry_Calls_In_Elaboration_Code, Call);
9054
9055      elsif Is_Task_Entry (Target_Id) then
9056         Check_Restriction (No_Entry_Calls_In_Elaboration_Code, Call);
9057
9058         --  Task entry calls are never processed because the entry being
9059         --  invoked does not have a corresponding "body", it has a select.
9060
9061         return;
9062      end if;
9063
9064      --  Nothing to do when the call invokes a target defined within an
9065      --  instance and switch -gnatd_i (ignore activations and calls to
9066      --  instances for elaboration) is in effect.
9067
9068      if Debug_Flag_Underscore_I
9069        and then In_External_Instance
9070                   (N           => Call,
9071                    Target_Decl => Target_Attrs.Spec_Decl)
9072      then
9073         return;
9074
9075      --  Nothing to do when the call is a guaranteed ABE
9076
9077      elsif Is_Known_Guaranteed_ABE (Call) then
9078         return;
9079
9080      --  Nothing to do when the root scenario appears at the declaration level
9081      --  and the target is in the same unit, but outside this context.
9082      --
9083      --    function B ...;                      --  target declaration
9084      --
9085      --    procedure Proc is
9086      --       function A ... is
9087      --       begin
9088      --          if Some_Condition then
9089      --             return B;                   --  call site
9090      --          ...
9091      --       end A;
9092      --
9093      --       X : ... := A;                     --  root scenario
9094      --    ...
9095      --
9096      --    function B ... is
9097      --       ...
9098      --    end B;
9099      --
9100      --  In the example above, the context of X is the declarative region of
9101      --  Proc. The "elaboration" of X may eventually reach B which is defined
9102      --  outside of X's context. B is relevant only when Proc is invoked, but
9103      --  this happens only by means of "normal" elaboration, therefore B must
9104      --  not be considered if this is not the case.
9105
9106      --  Performance note: parent traversal
9107
9108      elsif Is_Up_Level_Target (Target_Attrs.Spec_Decl) then
9109         return;
9110      end if;
9111
9112      --  The call occurs in an initial condition context when a prior scenario
9113      --  is already in that mode, or when the target is an Initial_Condition
9114      --  procedure. Update the state of the Processing phase to reflect this.
9115
9116      New_State.Within_Initial_Condition :=
9117        New_State.Within_Initial_Condition
9118          or else Is_Initial_Condition_Proc (Target_Id);
9119
9120      --  The call occurs in a partial finalization context when a prior
9121      --  scenario is already in that mode, or when the target denotes a
9122      --  [Deep_]Finalize primitive or a finalizer within an initialization
9123      --  context. Update the state of the Processing phase to reflect this.
9124
9125      New_State.Within_Partial_Finalization :=
9126        New_State.Within_Partial_Finalization
9127          or else Is_Partial_Finalization_Proc;
9128
9129      --  The SPARK rules are in effect. Note that -gnatd.v (enforce SPARK
9130      --  elaboration rules in SPARK code) is intentionally not taken into
9131      --  account here because Process_Conditional_ABE_Call_SPARK has two
9132      --  separate modes of operation.
9133
9134      if SPARK_Rules_On then
9135         Process_Conditional_ABE_Call_SPARK
9136           (Call         => Call,
9137            Target_Id    => Target_Id,
9138            Target_Attrs => Target_Attrs,
9139            State        => New_State);
9140
9141      --  Otherwise the Ada rules are in effect
9142
9143      else
9144         Process_Conditional_ABE_Call_Ada
9145           (Call         => Call,
9146            Call_Attrs   => Call_Attrs,
9147            Target_Id    => Target_Id,
9148            Target_Attrs => Target_Attrs,
9149            State        => New_State);
9150      end if;
9151
9152      --  Inspect the target body (and barried function) for other suitable
9153      --  elaboration scenarios.
9154
9155      Traverse_Body
9156        (N     => Target_Attrs.Body_Barf,
9157         State => New_State);
9158
9159      Traverse_Body
9160        (N     => Target_Attrs.Body_Decl,
9161         State => New_State);
9162   end Process_Conditional_ABE_Call;
9163
9164   --------------------------------------
9165   -- Process_Conditional_ABE_Call_Ada --
9166   --------------------------------------
9167
9168   procedure Process_Conditional_ABE_Call_Ada
9169     (Call         : Node_Id;
9170      Call_Attrs   : Call_Attributes;
9171      Target_Id    : Entity_Id;
9172      Target_Attrs : Target_Attributes;
9173      State        : Processing_Attributes)
9174   is
9175      Check_OK : constant Boolean :=
9176                   not Call_Attrs.Ghost_Mode_Ignore
9177                     and then not Target_Attrs.Ghost_Mode_Ignore
9178                     and then Call_Attrs.Elab_Checks_OK
9179                     and then Target_Attrs.Elab_Checks_OK;
9180      --  A run-time ABE check may be installed only when both the call and the
9181      --  target have active elaboration checks, and both are not ignored Ghost
9182      --  constructs.
9183
9184      Root : constant Node_Id := Root_Scenario;
9185
9186      New_State : Processing_Attributes := State;
9187      --  Each step of the Processing phase constitutes a new state
9188
9189   begin
9190      --  Nothing to do for an Ada dispatching call because there are no ABE
9191      --  diagnostics for either models. ABE checks for the dynamic model are
9192      --  handled by Install_Primitive_Elaboration_Check.
9193
9194      if Call_Attrs.Is_Dispatching then
9195         return;
9196
9197      --  Nothing to do when the call is ABE-safe
9198      --
9199      --    generic
9200      --    function Gen ...;
9201      --
9202      --    function Gen ... is
9203      --    begin
9204      --       ...
9205      --    end Gen;
9206      --
9207      --    with Gen;
9208      --    procedure Main is
9209      --       function Inst is new Gen;
9210      --       X : ... := Inst;                  --  safe call
9211      --    ...
9212
9213      elsif Is_Safe_Call (Call, Target_Attrs) then
9214         return;
9215
9216      --  The call and the target body are both in the main unit
9217
9218      elsif Present (Target_Attrs.Body_Decl)
9219        and then In_Extended_Main_Code_Unit (Target_Attrs.Body_Decl)
9220      then
9221         --  If the root scenario appears prior to the target body, then this
9222         --  is a possible ABE with respect to the root scenario.
9223         --
9224         --    function B ...;
9225         --
9226         --    function A ... is
9227         --    begin
9228         --       if Some_Condition then
9229         --          return B;                      --  call site
9230         --       ...
9231         --    end A;
9232         --
9233         --    X : ... := A;                        --  root scenario
9234         --
9235         --    function B ... is                    --  target body
9236         --       ...
9237         --    end B;
9238         --
9239         --    Y : ... := A;                        --  root scenario
9240         --
9241         --  IMPORTANT: The call to B from A is a possible ABE for X, but not
9242         --  for Y. Installing an unconditional ABE raise prior to the call to
9243         --  B would be wrong as it will fail for Y as well, but in Y's case
9244         --  the call to B is never an ABE.
9245
9246         if Earlier_In_Extended_Unit (Root, Target_Attrs.Body_Decl) then
9247
9248            --  Do not emit any ABE diagnostics when the call occurs in a
9249            --  partial finalization context because this leads to confusing
9250            --  noise.
9251
9252            if State.Within_Partial_Finalization then
9253               null;
9254
9255            --  ABE diagnostics are emitted only in the static model because
9256            --  there is a well-defined order to visiting scenarios. Without
9257            --  this order diagnostics appear jumbled and result in unwanted
9258            --  noise.
9259
9260            elsif Static_Elaboration_Checks
9261              and then Call_Attrs.Elab_Warnings_OK
9262            then
9263               Error_Msg_NE
9264                 ("??cannot call & before body seen", Call, Target_Id);
9265               Error_Msg_N ("\Program_Error may be raised at run time", Call);
9266
9267               Output_Active_Scenarios (Call);
9268            end if;
9269
9270            --  Install a conditional run-time ABE check to verify that the
9271            --  target body has been elaborated prior to the call.
9272
9273            if Check_OK then
9274               Install_ABE_Check
9275                 (N           => Call,
9276                  Ins_Nod     => Call,
9277                  Target_Id   => Target_Attrs.Spec_Id,
9278                  Target_Decl => Target_Attrs.Spec_Decl,
9279                  Target_Body => Target_Attrs.Body_Decl);
9280
9281               --  Update the state of the Processing phase to indicate that
9282               --  no implicit Elaborate[_All] pragmas must be generated from
9283               --  this point on.
9284               --
9285               --    function B ...;
9286               --
9287               --    function A ... is
9288               --    begin
9289               --       if Some_Condition then
9290               --          <ABE check>
9291               --          return B;
9292               --       ...
9293               --    end A;
9294               --
9295               --    X : ... := A;
9296               --
9297               --    function B ... is
9298               --       External.Subp;           --  imparts Elaborate_All
9299               --    end B;
9300               --
9301               --  If Some_Condition is True, then the ABE check will fail at
9302               --  runtime and the call to External.Subp will never take place,
9303               --  rendering the implicit Elaborate_All useless.
9304               --
9305               --  If Some_Condition is False, then the call to External.Subp
9306               --  will never take place, rendering the implicit Elaborate_All
9307               --  useless.
9308
9309               New_State.Suppress_Implicit_Pragmas := True;
9310            end if;
9311         end if;
9312
9313      --  Otherwise the target body is not available in this compilation or it
9314      --  resides in an external unit. Install a run-time ABE check to verify
9315      --  that the target body has been elaborated prior to the call site when
9316      --  the dynamic model is in effect.
9317
9318      elsif Dynamic_Elaboration_Checks and then Check_OK then
9319         Install_ABE_Check
9320           (N       => Call,
9321            Ins_Nod => Call,
9322            Id      => Target_Attrs.Unit_Id);
9323      end if;
9324
9325      --  Ensure that the unit with the target body is elaborated prior to the
9326      --  main unit. The implicit Elaborate[_All] is generated only when the
9327      --  call has elaboration checks enabled. This behaviour parallels that of
9328      --  the old ABE mechanism.
9329
9330      if Call_Attrs.Elab_Checks_OK then
9331         Ensure_Prior_Elaboration
9332           (N        => Call,
9333            Unit_Id  => Target_Attrs.Unit_Id,
9334            Prag_Nam => Name_Elaborate_All,
9335            State    => New_State);
9336      end if;
9337   end Process_Conditional_ABE_Call_Ada;
9338
9339   ----------------------------------------
9340   -- Process_Conditional_ABE_Call_SPARK --
9341   ----------------------------------------
9342
9343   procedure Process_Conditional_ABE_Call_SPARK
9344     (Call         : Node_Id;
9345      Target_Id    : Entity_Id;
9346      Target_Attrs : Target_Attributes;
9347      State        : Processing_Attributes)
9348   is
9349      Region : Node_Id;
9350
9351   begin
9352      --  Ensure that a suitable elaboration model is in effect for SPARK rule
9353      --  verification.
9354
9355      Check_SPARK_Model_In_Effect (Call);
9356
9357      --  The call and the target body are both in the main unit
9358
9359      if Present (Target_Attrs.Body_Decl)
9360        and then In_Extended_Main_Code_Unit (Target_Attrs.Body_Decl)
9361      then
9362         --  If the call appears prior to the target body, then the call must
9363         --  appear within the early call region of the target body.
9364         --
9365         --    function B ...;
9366         --
9367         --    X : ... := B;                     --  call site
9368         --
9369         --    <preelaborable construct 1>       --+
9370         --               ...                      | early call region
9371         --    <preelaborable construct N>       --+
9372         --
9373         --    function B ... is                 --  target body
9374         --       ...
9375         --    end B;
9376         --
9377         --  When the call to B is not nested within some other scenario, the
9378         --  call is automatically illegal because it can never appear in the
9379         --  early call region of B's body. This is equivalent to a guaranteed
9380         --  ABE.
9381         --
9382         --    <preelaborable construct 1>       --+
9383         --                                        |
9384         --    function B ...;                     |
9385         --                                        |
9386         --    function A ... is                   |
9387         --    begin                               | early call region
9388         --       if Some_Condition then
9389         --          return B;                   --  call site
9390         --       ...
9391         --    end A;                              |
9392         --                                        |
9393         --    <preelaborable construct N>       --+
9394         --
9395         --    function B ... is                 --  target body
9396         --       ...
9397         --    end B;
9398         --
9399         --  When the call to B is nested within some other scenario, the call
9400         --  is always ABE-safe. It is not immediately obvious why this is the
9401         --  case. The elaboration safety follows from the early call region
9402         --  rule being applied to ALL calls preceding their associated bodies.
9403         --
9404         --  In the example above, the call to B is safe as long as the call to
9405         --  A is safe. There are several cases to consider:
9406         --
9407         --    <call 1 to A>
9408         --    function B ...;
9409         --
9410         --    <call 2 to A>
9411         --    function A ... is
9412         --    begin
9413         --       if Some_Condition then
9414         --          return B;
9415         --       ...
9416         --    end A;
9417         --
9418         --    <call 3 to A>
9419         --    function B ... is
9420         --       ...
9421         --    end B;
9422         --
9423         --  * Call 1 - This call is either nested within some scenario or not,
9424         --    which falls under the two general cases outlined above.
9425         --
9426         --  * Call 2 - This is the same case as Call 1.
9427         --
9428         --  * Call 3 - The placement of this call limits the range of B's
9429         --    early call region unto call 3, therefore the call to B is no
9430         --    longer within the early call region of B's body, making it ABE-
9431         --    unsafe and therefore illegal.
9432
9433         if Earlier_In_Extended_Unit (Call, Target_Attrs.Body_Decl) then
9434
9435            --  Do not emit any ABE diagnostics when the call occurs in an
9436            --  initial condition context because this leads to incorrect
9437            --  diagnostics.
9438
9439            if State.Within_Initial_Condition then
9440               null;
9441
9442            --  Do not emit any ABE diagnostics when the call occurs in a
9443            --  partial finalization context because this leads to confusing
9444            --  noise.
9445
9446            elsif State.Within_Partial_Finalization then
9447               null;
9448
9449            --  ABE diagnostics are emitted only in the static model because
9450            --  there is a well-defined order to visiting scenarios. Without
9451            --  this order diagnostics appear jumbled and result in unwanted
9452            --  noise.
9453
9454            elsif Static_Elaboration_Checks then
9455
9456               --  Ensure that a call which textually precedes the subprogram
9457               --  body it invokes appears within the early call region of the
9458               --  subprogram body.
9459
9460               --  IMPORTANT: This check must always be performed even when
9461               --  -gnatd.v (enforce SPARK elaboration rules in SPARK code) is
9462               --  not specified because the static model cannot guarantee the
9463               --  absence of elaboration issues in the presence of dispatching
9464               --  calls.
9465
9466               Region := Find_Early_Call_Region (Target_Attrs.Body_Decl);
9467
9468               if Earlier_In_Extended_Unit (Call, Region) then
9469                  Error_Msg_NE
9470                    ("call must appear within early call region of subprogram "
9471                     & "body & (SPARK RM 7.7(3))", Call, Target_Id);
9472
9473                  Error_Msg_Sloc := Sloc (Region);
9474                  Error_Msg_N ("\region starts #", Call);
9475
9476                  Error_Msg_Sloc := Sloc (Target_Attrs.Body_Decl);
9477                  Error_Msg_N ("\region ends #", Call);
9478
9479                  Output_Active_Scenarios (Call);
9480               end if;
9481            end if;
9482
9483         --  Otherwise the call appears after the target body. The call is
9484         --  ABE-safe as a consequence of applying the early call region rule
9485         --  to ALL calls preceding their associated bodies.
9486
9487         else
9488            null;
9489         end if;
9490      end if;
9491
9492      --  A call to a source target or to a target which emulates Ada or SPARK
9493      --  semantics imposes an Elaborate_All requirement on the context of the
9494      --  main unit. Determine whether the context has a pragma strong enough
9495      --  to meet the requirement.
9496
9497      --  IMPORTANT: This check must be performed only when -gnatd.v (enforce
9498      --  SPARK elaboration rules in SPARK code) is active because the static
9499      --  model can ensure the prior elaboration of the unit which contains a
9500      --  body by installing an implicit Elaborate[_All] pragma.
9501
9502      if Debug_Flag_Dot_V then
9503         if Target_Attrs.From_Source
9504           or else Is_Ada_Semantic_Target (Target_Id)
9505           or else Is_SPARK_Semantic_Target (Target_Id)
9506         then
9507            Meet_Elaboration_Requirement
9508              (N         => Call,
9509               Target_Id => Target_Id,
9510               Req_Nam   => Name_Elaborate_All);
9511         end if;
9512
9513      --  Otherwise ensure that the unit with the target body is elaborated
9514      --  prior to the main unit.
9515
9516      else
9517         Ensure_Prior_Elaboration
9518           (N        => Call,
9519            Unit_Id  => Target_Attrs.Unit_Id,
9520            Prag_Nam => Name_Elaborate_All,
9521            State    => State);
9522      end if;
9523   end Process_Conditional_ABE_Call_SPARK;
9524
9525   -------------------------------------------
9526   -- Process_Conditional_ABE_Instantiation --
9527   -------------------------------------------
9528
9529   procedure Process_Conditional_ABE_Instantiation
9530     (Exp_Inst : Node_Id;
9531      State    : Processing_Attributes)
9532   is
9533      Gen_Attrs  : Target_Attributes;
9534      Gen_Id     : Entity_Id;
9535      Inst       : Node_Id;
9536      Inst_Attrs : Instantiation_Attributes;
9537      Inst_Id    : Entity_Id;
9538
9539      SPARK_Rules_On : Boolean;
9540      --  This flag is set when the SPARK rules are in effect
9541
9542   begin
9543      Extract_Instantiation_Attributes
9544        (Exp_Inst => Exp_Inst,
9545         Inst     => Inst,
9546         Inst_Id  => Inst_Id,
9547         Gen_Id   => Gen_Id,
9548         Attrs    => Inst_Attrs);
9549
9550      Extract_Target_Attributes (Gen_Id, Gen_Attrs);
9551
9552      --  The SPARK rules are in effect when both the instantiation and generic
9553      --  are subject to SPARK_Mode On.
9554
9555      SPARK_Rules_On := Inst_Attrs.SPARK_Mode_On and Gen_Attrs.SPARK_Mode_On;
9556
9557      --  Output relevant information when switch -gnatel (info messages on
9558      --  implicit Elaborate[_All] pragmas) is in effect.
9559
9560      if Elab_Info_Messages then
9561         Info_Instantiation
9562           (Inst     => Inst,
9563            Gen_Id   => Gen_Id,
9564            Info_Msg => True,
9565            In_SPARK => SPARK_Rules_On);
9566      end if;
9567
9568      --  Nothing to do when the instantiation is a guaranteed ABE
9569
9570      if Is_Known_Guaranteed_ABE (Inst) then
9571         return;
9572
9573      --  Nothing to do when the root scenario appears at the declaration level
9574      --  and the generic is in the same unit, but outside this context.
9575      --
9576      --    generic
9577      --    procedure Gen is ...;                --  generic declaration
9578      --
9579      --    procedure Proc is
9580      --       function A ... is
9581      --       begin
9582      --          if Some_Condition then
9583      --             declare
9584      --                procedure I is new Gen;  --  instantiation site
9585      --             ...
9586      --          ...
9587      --       end A;
9588      --
9589      --       X : ... := A;                     --  root scenario
9590      --    ...
9591      --
9592      --    procedure Gen is
9593      --       ...
9594      --    end Gen;
9595      --
9596      --  In the example above, the context of X is the declarative region of
9597      --  Proc. The "elaboration" of X may eventually reach Gen which appears
9598      --  outside of X's context. Gen is relevant only when Proc is invoked,
9599      --  but this happens only by means of "normal" elaboration, therefore
9600      --  Gen must not be considered if this is not the case.
9601
9602      --  Performance note: parent traversal
9603
9604      elsif Is_Up_Level_Target (Gen_Attrs.Spec_Decl) then
9605         return;
9606
9607      --  The SPARK rules are in effect
9608
9609      elsif SPARK_Rules_On then
9610         Process_Conditional_ABE_Instantiation_SPARK
9611           (Inst      => Inst,
9612            Gen_Id    => Gen_Id,
9613            Gen_Attrs => Gen_Attrs,
9614            State     => State);
9615
9616      --  Otherwise the Ada rules are in effect, or SPARK code is allowed to
9617      --  violate the SPARK rules.
9618
9619      else
9620         Process_Conditional_ABE_Instantiation_Ada
9621           (Exp_Inst   => Exp_Inst,
9622            Inst       => Inst,
9623            Inst_Attrs => Inst_Attrs,
9624            Gen_Id     => Gen_Id,
9625            Gen_Attrs  => Gen_Attrs,
9626            State      => State);
9627      end if;
9628   end Process_Conditional_ABE_Instantiation;
9629
9630   -----------------------------------------------
9631   -- Process_Conditional_ABE_Instantiation_Ada --
9632   -----------------------------------------------
9633
9634   procedure Process_Conditional_ABE_Instantiation_Ada
9635     (Exp_Inst   : Node_Id;
9636      Inst       : Node_Id;
9637      Inst_Attrs : Instantiation_Attributes;
9638      Gen_Id     : Entity_Id;
9639      Gen_Attrs  : Target_Attributes;
9640      State      : Processing_Attributes)
9641   is
9642      Check_OK : constant Boolean :=
9643                   not Inst_Attrs.Ghost_Mode_Ignore
9644                     and then not Gen_Attrs.Ghost_Mode_Ignore
9645                     and then Inst_Attrs.Elab_Checks_OK
9646                     and then Gen_Attrs.Elab_Checks_OK;
9647      --  A run-time ABE check may be installed only when both the instance and
9648      --  the generic have active elaboration checks and both are not ignored
9649      --  Ghost constructs.
9650
9651      New_State : Processing_Attributes := State;
9652      --  Each step of the Processing phase constitutes a new state
9653
9654      Root : constant Node_Id := Root_Scenario;
9655
9656   begin
9657      --  Nothing to do when the instantiation is ABE-safe
9658      --
9659      --    generic
9660      --    package Gen is
9661      --       ...
9662      --    end Gen;
9663      --
9664      --    package body Gen is
9665      --       ...
9666      --    end Gen;
9667      --
9668      --    with Gen;
9669      --    procedure Main is
9670      --       package Inst is new Gen (ABE);    --  safe instantiation
9671      --    ...
9672
9673      if Is_Safe_Instantiation (Inst, Gen_Attrs) then
9674         return;
9675
9676      --  The instantiation and the generic body are both in the main unit
9677
9678      elsif Present (Gen_Attrs.Body_Decl)
9679        and then In_Extended_Main_Code_Unit (Gen_Attrs.Body_Decl)
9680      then
9681         --  If the root scenario appears prior to the generic body, then this
9682         --  is a possible ABE with respect to the root scenario.
9683         --
9684         --    generic
9685         --    package Gen is
9686         --       ...
9687         --    end Gen;
9688         --
9689         --    function A ... is
9690         --    begin
9691         --       if Some_Condition then
9692         --          declare
9693         --             package Inst is new Gen;    --  instantiation site
9694         --       ...
9695         --    end A;
9696         --
9697         --    X : ... := A;                        --  root scenario
9698         --
9699         --    package body Gen is                  --  generic body
9700         --       ...
9701         --    end Gen;
9702         --
9703         --    Y : ... := A;                        --  root scenario
9704         --
9705         --  IMPORTANT: The instantiation of Gen is a possible ABE for X, but
9706         --  not for Y. Installing an unconditional ABE raise prior to the
9707         --  instance site would be wrong as it will fail for Y as well, but in
9708         --  Y's case the instantiation of Gen is never an ABE.
9709
9710         if Earlier_In_Extended_Unit (Root, Gen_Attrs.Body_Decl) then
9711
9712            --  Do not emit any ABE diagnostics when the instantiation occurs
9713            --  in partial finalization context because this leads to unwanted
9714            --  noise.
9715
9716            if State.Within_Partial_Finalization then
9717               null;
9718
9719            --  ABE diagnostics are emitted only in the static model because
9720            --  there is a well-defined order to visiting scenarios. Without
9721            --  this order diagnostics appear jumbled and result in unwanted
9722            --  noise.
9723
9724            elsif Static_Elaboration_Checks
9725              and then Inst_Attrs.Elab_Warnings_OK
9726            then
9727               Error_Msg_NE
9728                 ("??cannot instantiate & before body seen", Inst, Gen_Id);
9729               Error_Msg_N ("\Program_Error may be raised at run time", Inst);
9730
9731               Output_Active_Scenarios (Inst);
9732            end if;
9733
9734            --  Install a conditional run-time ABE check to verify that the
9735            --  generic body has been elaborated prior to the instantiation.
9736
9737            if Check_OK then
9738               Install_ABE_Check
9739                 (N           => Inst,
9740                  Ins_Nod     => Exp_Inst,
9741                  Target_Id   => Gen_Attrs.Spec_Id,
9742                  Target_Decl => Gen_Attrs.Spec_Decl,
9743                  Target_Body => Gen_Attrs.Body_Decl);
9744
9745               --  Update the state of the Processing phase to indicate that
9746               --  no implicit Elaborate[_All] pragmas must be generated from
9747               --  this point on.
9748               --
9749               --    generic
9750               --    package Gen is
9751               --       ...
9752               --    end Gen;
9753               --
9754               --    function A ... is
9755               --    begin
9756               --       if Some_Condition then
9757               --          <ABE check>
9758               --          declare Inst is new Gen;
9759               --       ...
9760               --    end A;
9761               --
9762               --    X : ... := A;
9763               --
9764               --    package body Gen is
9765               --    begin
9766               --       External.Subp;           --  imparts Elaborate_All
9767               --    end Gen;
9768               --
9769               --  If Some_Condition is True, then the ABE check will fail at
9770               --  runtime and the call to External.Subp will never take place,
9771               --  rendering the implicit Elaborate_All useless.
9772               --
9773               --  If Some_Condition is False, then the call to External.Subp
9774               --  will never take place, rendering the implicit Elaborate_All
9775               --  useless.
9776
9777               New_State.Suppress_Implicit_Pragmas := True;
9778            end if;
9779         end if;
9780
9781      --  Otherwise the generic body is not available in this compilation or it
9782      --  resides in an external unit. Install a run-time ABE check to verify
9783      --  that the generic body has been elaborated prior to the instantiation
9784      --  when the dynamic model is in effect.
9785
9786      elsif Dynamic_Elaboration_Checks and then Check_OK then
9787         Install_ABE_Check
9788           (N       => Inst,
9789            Ins_Nod => Exp_Inst,
9790            Id      => Gen_Attrs.Unit_Id);
9791      end if;
9792
9793      --  Ensure that the unit with the generic body is elaborated prior to
9794      --  the main unit. No implicit pragma is generated if the instantiation
9795      --  has elaboration checks suppressed. This behaviour parallels that of
9796      --  the old ABE mechanism.
9797
9798      if Inst_Attrs.Elab_Checks_OK then
9799         Ensure_Prior_Elaboration
9800           (N        => Inst,
9801            Unit_Id  => Gen_Attrs.Unit_Id,
9802            Prag_Nam => Name_Elaborate,
9803            State    => New_State);
9804      end if;
9805   end Process_Conditional_ABE_Instantiation_Ada;
9806
9807   -------------------------------------------------
9808   -- Process_Conditional_ABE_Instantiation_SPARK --
9809   -------------------------------------------------
9810
9811   procedure Process_Conditional_ABE_Instantiation_SPARK
9812     (Inst      : Node_Id;
9813      Gen_Id    : Entity_Id;
9814      Gen_Attrs : Target_Attributes;
9815      State     : Processing_Attributes)
9816   is
9817      Req_Nam : Name_Id;
9818
9819   begin
9820      --  Ensure that a suitable elaboration model is in effect for SPARK rule
9821      --  verification.
9822
9823      Check_SPARK_Model_In_Effect (Inst);
9824
9825      --  A source instantiation imposes an Elaborate[_All] requirement on the
9826      --  context of the main unit. Determine whether the context has a pragma
9827      --  strong enough to meet the requirement. The check is orthogonal to the
9828      --  ABE ramifications of the instantiation.
9829
9830      --  IMPORTANT: This check must be performed only when -gnatd.v (enforce
9831      --  SPARK elaboration rules in SPARK code) is active because the static
9832      --  model can ensure the prior elaboration of the unit which contains a
9833      --  body by installing an implicit Elaborate[_All] pragma.
9834
9835      if Debug_Flag_Dot_V then
9836         if Nkind (Inst) = N_Package_Instantiation then
9837            Req_Nam := Name_Elaborate_All;
9838         else
9839            Req_Nam := Name_Elaborate;
9840         end if;
9841
9842         Meet_Elaboration_Requirement
9843           (N         => Inst,
9844            Target_Id => Gen_Id,
9845            Req_Nam   => Req_Nam);
9846
9847      --  Otherwise ensure that the unit with the target body is elaborated
9848      --  prior to the main unit.
9849
9850      else
9851         Ensure_Prior_Elaboration
9852           (N        => Inst,
9853            Unit_Id  => Gen_Attrs.Unit_Id,
9854            Prag_Nam => Name_Elaborate,
9855            State    => State);
9856      end if;
9857   end Process_Conditional_ABE_Instantiation_SPARK;
9858
9859   -------------------------------------------------
9860   -- Process_Conditional_ABE_Variable_Assignment --
9861   -------------------------------------------------
9862
9863   procedure Process_Conditional_ABE_Variable_Assignment (Asmt : Node_Id) is
9864      Var_Id : constant Entity_Id := Entity (Extract_Assignment_Name (Asmt));
9865      Prag   : constant Node_Id   := SPARK_Pragma (Var_Id);
9866
9867      SPARK_Rules_On : Boolean;
9868      --  This flag is set when the SPARK rules are in effect
9869
9870   begin
9871      --  The SPARK rules are in effect when both the assignment and the
9872      --  variable are subject to SPARK_Mode On.
9873
9874      SPARK_Rules_On :=
9875        Present (Prag)
9876          and then Get_SPARK_Mode_From_Annotation (Prag) = On
9877          and then Is_SPARK_Mode_On_Node (Asmt);
9878
9879      --  Output relevant information when switch -gnatel (info messages on
9880      --  implicit Elaborate[_All] pragmas) is in effect.
9881
9882      if Elab_Info_Messages then
9883         Elab_Msg_NE
9884           (Msg      => "assignment to & during elaboration",
9885            N        => Asmt,
9886            Id       => Var_Id,
9887            Info_Msg => True,
9888            In_SPARK => SPARK_Rules_On);
9889      end if;
9890
9891      --  The SPARK rules are in effect. These rules are applied regardless of
9892      --  whether -gnatd.v (enforce SPARK elaboration rules in SPARK code) is
9893      --  in effect because the static model cannot ensure safe assignment of
9894      --  variables.
9895
9896      if SPARK_Rules_On then
9897         Process_Conditional_ABE_Variable_Assignment_SPARK
9898           (Asmt   => Asmt,
9899            Var_Id => Var_Id);
9900
9901      --  Otherwise the Ada rules are in effect
9902
9903      else
9904         Process_Conditional_ABE_Variable_Assignment_Ada
9905           (Asmt   => Asmt,
9906            Var_Id => Var_Id);
9907      end if;
9908   end Process_Conditional_ABE_Variable_Assignment;
9909
9910   -----------------------------------------------------
9911   -- Process_Conditional_ABE_Variable_Assignment_Ada --
9912   -----------------------------------------------------
9913
9914   procedure Process_Conditional_ABE_Variable_Assignment_Ada
9915     (Asmt   : Node_Id;
9916      Var_Id : Entity_Id)
9917   is
9918      Var_Decl : constant Node_Id   := Declaration_Node (Var_Id);
9919      Spec_Id  : constant Entity_Id := Find_Top_Unit (Var_Decl);
9920
9921   begin
9922      --  Emit a warning when an uninitialized variable declared in a package
9923      --  spec without a pragma Elaborate_Body is initialized by elaboration
9924      --  code within the corresponding body.
9925
9926      if not Warnings_Off (Var_Id)
9927        and then not Is_Initialized (Var_Decl)
9928        and then not Has_Pragma_Elaborate_Body (Spec_Id)
9929      then
9930         Error_Msg_NE
9931           ("??variable & can be accessed by clients before this "
9932            & "initialization", Asmt, Var_Id);
9933
9934         Error_Msg_NE
9935           ("\add pragma ""Elaborate_Body"" to spec & to ensure proper "
9936            & "initialization", Asmt, Spec_Id);
9937
9938         Output_Active_Scenarios (Asmt);
9939
9940         --  Generate an implicit Elaborate_Body in the spec
9941
9942         Set_Elaborate_Body_Desirable (Spec_Id);
9943      end if;
9944   end Process_Conditional_ABE_Variable_Assignment_Ada;
9945
9946   -------------------------------------------------------
9947   -- Process_Conditional_ABE_Variable_Assignment_SPARK --
9948   -------------------------------------------------------
9949
9950   procedure Process_Conditional_ABE_Variable_Assignment_SPARK
9951     (Asmt   : Node_Id;
9952      Var_Id : Entity_Id)
9953   is
9954      Var_Decl : constant Node_Id   := Declaration_Node (Var_Id);
9955      Spec_Id  : constant Entity_Id := Find_Top_Unit (Var_Decl);
9956
9957   begin
9958      --  Ensure that a suitable elaboration model is in effect for SPARK rule
9959      --  verification.
9960
9961      Check_SPARK_Model_In_Effect (Asmt);
9962
9963      --  Emit an error when an initialized variable declared in a package spec
9964      --  without pragma Elaborate_Body is further modified by elaboration code
9965      --  within the corresponding body.
9966
9967      if Is_Initialized (Var_Decl)
9968        and then not Has_Pragma_Elaborate_Body (Spec_Id)
9969      then
9970         Error_Msg_NE
9971           ("variable & modified by elaboration code in package body",
9972            Asmt, Var_Id);
9973
9974         Error_Msg_NE
9975           ("\add pragma ""Elaborate_Body"" to spec & to ensure full "
9976            & "initialization", Asmt, Spec_Id);
9977
9978         Output_Active_Scenarios (Asmt);
9979      end if;
9980   end Process_Conditional_ABE_Variable_Assignment_SPARK;
9981
9982   ------------------------------------------------
9983   -- Process_Conditional_ABE_Variable_Reference --
9984   ------------------------------------------------
9985
9986   procedure Process_Conditional_ABE_Variable_Reference (Ref : Node_Id) is
9987      Var_Attrs : Variable_Attributes;
9988      Var_Id    : Entity_Id;
9989
9990   begin
9991      Extract_Variable_Reference_Attributes
9992        (Ref    => Ref,
9993         Var_Id => Var_Id,
9994         Attrs  => Var_Attrs);
9995
9996      if Is_Read (Ref) then
9997         Process_Conditional_ABE_Variable_Reference_Read
9998           (Ref    => Ref,
9999            Var_Id => Var_Id,
10000            Attrs  => Var_Attrs);
10001      end if;
10002   end Process_Conditional_ABE_Variable_Reference;
10003
10004   -----------------------------------------------------
10005   -- Process_Conditional_ABE_Variable_Reference_Read --
10006   -----------------------------------------------------
10007
10008   procedure Process_Conditional_ABE_Variable_Reference_Read
10009     (Ref    : Node_Id;
10010      Var_Id : Entity_Id;
10011      Attrs  : Variable_Attributes)
10012   is
10013   begin
10014      --  Output relevant information when switch -gnatel (info messages on
10015      --  implicit Elaborate[_All] pragmas) is in effect.
10016
10017      if Elab_Info_Messages then
10018         Elab_Msg_NE
10019           (Msg      => "read of variable & during elaboration",
10020            N        => Ref,
10021            Id       => Var_Id,
10022            Info_Msg => True,
10023            In_SPARK => True);
10024      end if;
10025
10026      --  Nothing to do when the variable appears within the main unit because
10027      --  diagnostics on reads are relevant only for external variables.
10028
10029      if Is_Same_Unit (Attrs.Unit_Id, Cunit_Entity (Main_Unit)) then
10030         null;
10031
10032      --  Nothing to do when the variable is already initialized. Note that the
10033      --  variable may be further modified by the external unit.
10034
10035      elsif Is_Initialized (Declaration_Node (Var_Id)) then
10036         null;
10037
10038      --  Nothing to do when the external unit guarantees the initialization of
10039      --  the variable by means of pragma Elaborate_Body.
10040
10041      elsif Has_Pragma_Elaborate_Body (Attrs.Unit_Id) then
10042         null;
10043
10044      --  A variable read imposes an Elaborate requirement on the context of
10045      --  the main unit. Determine whether the context has a pragma strong
10046      --  enough to meet the requirement.
10047
10048      else
10049         Meet_Elaboration_Requirement
10050           (N         => Ref,
10051            Target_Id => Var_Id,
10052            Req_Nam   => Name_Elaborate);
10053      end if;
10054   end Process_Conditional_ABE_Variable_Reference_Read;
10055
10056   -----------------------------
10057   -- Process_Conditional_ABE --
10058   -----------------------------
10059
10060   --  NOTE: The body of this routine is intentionally out of order because it
10061   --  invokes an instantiated subprogram (Process_Conditional_ABE_Activation).
10062   --  Placing the body in alphabetical order will result in a guaranteed ABE.
10063
10064   procedure Process_Conditional_ABE
10065     (N     : Node_Id;
10066      State : Processing_Attributes := Initial_State)
10067   is
10068      Call_Attrs : Call_Attributes;
10069      Target_Id  : Entity_Id;
10070
10071   begin
10072      --  Add the current scenario to the stack of active scenarios
10073
10074      Push_Active_Scenario (N);
10075
10076      --  'Access
10077
10078      if Is_Suitable_Access (N) then
10079         Process_Conditional_ABE_Access
10080           (Attr  => N,
10081            State => State);
10082
10083      --  Activations and calls
10084
10085      elsif Is_Suitable_Call (N) then
10086
10087         --  In general, only calls found within the main unit are processed
10088         --  because the ALI information supplied to binde is for the main
10089         --  unit only. However, to preserve the consistency of the tree and
10090         --  ensure proper serialization of internal names, external calls
10091         --  also receive corresponding call markers (see Build_Call_Marker).
10092         --  Regardless of the reason, external calls must not be processed.
10093
10094         if In_Main_Context (N) then
10095            Extract_Call_Attributes
10096              (Call      => N,
10097               Target_Id => Target_Id,
10098               Attrs     => Call_Attrs);
10099
10100            if Is_Activation_Proc (Target_Id) then
10101               Process_Conditional_ABE_Activation
10102                 (Call       => N,
10103                  Call_Attrs => Call_Attrs,
10104                  State      => State);
10105
10106            else
10107               Process_Conditional_ABE_Call
10108                 (Call       => N,
10109                  Call_Attrs => Call_Attrs,
10110                  Target_Id  => Target_Id,
10111                  State      => State);
10112            end if;
10113         end if;
10114
10115      --  Instantiations
10116
10117      elsif Is_Suitable_Instantiation (N) then
10118         Process_Conditional_ABE_Instantiation
10119           (Exp_Inst => N,
10120            State    => State);
10121
10122      --  Variable assignments
10123
10124      elsif Is_Suitable_Variable_Assignment (N) then
10125         Process_Conditional_ABE_Variable_Assignment (N);
10126
10127      --  Variable references
10128
10129      elsif Is_Suitable_Variable_Reference (N) then
10130
10131         --  In general, only variable references found within the main unit
10132         --  are processed because the ALI information supplied to binde is for
10133         --  the main unit only. However, to preserve the consistency of the
10134         --  tree and ensure proper serialization of internal names, external
10135         --  variable references also receive corresponding variable reference
10136         --  markers (see Build_Varaible_Reference_Marker). Regardless of the
10137         --  reason, external variable references must not be processed.
10138
10139         if In_Main_Context (N) then
10140            Process_Conditional_ABE_Variable_Reference (N);
10141         end if;
10142      end if;
10143
10144      --  Remove the current scenario from the stack of active scenarios once
10145      --  all ABE diagnostics and checks have been performed.
10146
10147      Pop_Active_Scenario (N);
10148   end Process_Conditional_ABE;
10149
10150   --------------------------------------------
10151   -- Process_Guaranteed_ABE_Activation_Impl --
10152   --------------------------------------------
10153
10154   procedure Process_Guaranteed_ABE_Activation_Impl
10155     (Call       : Node_Id;
10156      Call_Attrs : Call_Attributes;
10157      Obj_Id     : Entity_Id;
10158      Task_Attrs : Task_Attributes;
10159      State      : Processing_Attributes)
10160   is
10161      pragma Unreferenced (State);
10162
10163      Check_OK : constant Boolean :=
10164                   not Is_Ignored_Ghost_Entity (Obj_Id)
10165                     and then not Task_Attrs.Ghost_Mode_Ignore
10166                     and then Is_Elaboration_Checks_OK_Id (Obj_Id)
10167                     and then Task_Attrs.Elab_Checks_OK;
10168      --  A run-time ABE check may be installed only when the object and the
10169      --  task type have active elaboration checks, and both are not ignored
10170      --  Ghost constructs.
10171
10172   begin
10173      --  Nothing to do when the root scenario appears at the declaration
10174      --  level and the task is in the same unit, but outside this context.
10175      --
10176      --    task type Task_Typ;                  --  task declaration
10177      --
10178      --    procedure Proc is
10179      --       function A ... is
10180      --       begin
10181      --          if Some_Condition then
10182      --             declare
10183      --                T : Task_Typ;
10184      --             begin
10185      --                <activation call>        --  activation site
10186      --             end;
10187      --          ...
10188      --       end A;
10189      --
10190      --       X : ... := A;                     --  root scenario
10191      --    ...
10192      --
10193      --    task body Task_Typ is
10194      --       ...
10195      --    end Task_Typ;
10196      --
10197      --  In the example above, the context of X is the declarative list of
10198      --  Proc. The "elaboration" of X may reach the activation of T whose body
10199      --  is defined outside of X's context. The task body is relevant only
10200      --  when Proc is invoked, but this happens only in "normal" elaboration,
10201      --  therefore the task body must not be considered if this is not the
10202      --  case.
10203
10204      --  Performance note: parent traversal
10205
10206      if Is_Up_Level_Target (Task_Attrs.Task_Decl) then
10207         return;
10208
10209      --  Nothing to do when the activation is ABE-safe
10210      --
10211      --    generic
10212      --    package Gen is
10213      --       task type Task_Typ;
10214      --    end Gen;
10215      --
10216      --    package body Gen is
10217      --       task body Task_Typ is
10218      --       begin
10219      --          ...
10220      --       end Task_Typ;
10221      --    end Gen;
10222      --
10223      --    with Gen;
10224      --    procedure Main is
10225      --       package Nested is
10226      --          package Inst is new Gen;
10227      --          T : Inst.Task_Typ;
10228      --       end Nested;                       --  safe activation
10229      --    ...
10230
10231      elsif Is_Safe_Activation (Call, Task_Attrs.Task_Decl) then
10232         return;
10233
10234      --  An activation call leads to a guaranteed ABE when the activation
10235      --  call and the task appear within the same context ignoring library
10236      --  levels, and the body of the task has not been seen yet or appears
10237      --  after the activation call.
10238      --
10239      --    procedure Guaranteed_ABE is
10240      --       task type Task_Typ;
10241      --
10242      --       package Nested is
10243      --          T : Task_Typ;
10244      --          <activation call>              --  guaranteed ABE
10245      --       end Nested;
10246      --
10247      --       task body Task_Typ is
10248      --          ...
10249      --       end Task_Typ;
10250      --    ...
10251
10252      --  Performance note: parent traversal
10253
10254      elsif Is_Guaranteed_ABE
10255              (N           => Call,
10256               Target_Decl => Task_Attrs.Task_Decl,
10257               Target_Body => Task_Attrs.Body_Decl)
10258      then
10259         if Call_Attrs.Elab_Warnings_OK then
10260            Error_Msg_Sloc := Sloc (Call);
10261            Error_Msg_N
10262              ("??task & will be activated # before elaboration of its body",
10263               Obj_Id);
10264            Error_Msg_N ("\Program_Error will be raised at run time", Obj_Id);
10265         end if;
10266
10267         --  Mark the activation call as a guaranteed ABE
10268
10269         Set_Is_Known_Guaranteed_ABE (Call);
10270
10271         --  Install a run-time ABE failue because this activation call will
10272         --  always result in an ABE.
10273
10274         if Check_OK then
10275            Install_ABE_Failure
10276              (N       => Call,
10277               Ins_Nod => Call);
10278         end if;
10279      end if;
10280   end Process_Guaranteed_ABE_Activation_Impl;
10281
10282   procedure Process_Guaranteed_ABE_Activation is
10283     new Process_Activation_Generic (Process_Guaranteed_ABE_Activation_Impl);
10284
10285   ---------------------------------
10286   -- Process_Guaranteed_ABE_Call --
10287   ---------------------------------
10288
10289   procedure Process_Guaranteed_ABE_Call
10290     (Call       : Node_Id;
10291      Call_Attrs : Call_Attributes;
10292      Target_Id  : Entity_Id)
10293   is
10294      Target_Attrs : Target_Attributes;
10295
10296   begin
10297      Extract_Target_Attributes
10298        (Target_Id => Target_Id,
10299         Attrs     => Target_Attrs);
10300
10301      --  Nothing to do when the root scenario appears at the declaration level
10302      --  and the target is in the same unit, but outside this context.
10303      --
10304      --    function B ...;                      --  target declaration
10305      --
10306      --    procedure Proc is
10307      --       function A ... is
10308      --       begin
10309      --          if Some_Condition then
10310      --             return B;                   --  call site
10311      --          ...
10312      --       end A;
10313      --
10314      --       X : ... := A;                     --  root scenario
10315      --    ...
10316      --
10317      --    function B ... is
10318      --       ...
10319      --    end B;
10320      --
10321      --  In the example above, the context of X is the declarative region of
10322      --  Proc. The "elaboration" of X may eventually reach B which is defined
10323      --  outside of X's context. B is relevant only when Proc is invoked, but
10324      --  this happens only by means of "normal" elaboration, therefore B must
10325      --  not be considered if this is not the case.
10326
10327      --  Performance note: parent traversal
10328
10329      if Is_Up_Level_Target (Target_Attrs.Spec_Decl) then
10330         return;
10331
10332      --  Nothing to do when the call is ABE-safe
10333      --
10334      --    generic
10335      --    function Gen ...;
10336      --
10337      --    function Gen ... is
10338      --    begin
10339      --       ...
10340      --    end Gen;
10341      --
10342      --    with Gen;
10343      --    procedure Main is
10344      --       function Inst is new Gen;
10345      --       X : ... := Inst;                  --  safe call
10346      --    ...
10347
10348      elsif Is_Safe_Call (Call, Target_Attrs) then
10349         return;
10350
10351      --  A call leads to a guaranteed ABE when the call and the target appear
10352      --  within the same context ignoring library levels, and the body of the
10353      --  target has not been seen yet or appears after the call.
10354      --
10355      --    procedure Guaranteed_ABE is
10356      --       function Func ...;
10357      --
10358      --       package Nested is
10359      --          Obj : ... := Func;             --  guaranteed ABE
10360      --       end Nested;
10361      --
10362      --       function Func ... is
10363      --          ...
10364      --       end Func;
10365      --    ...
10366
10367      --  Performance note: parent traversal
10368
10369      elsif Is_Guaranteed_ABE
10370              (N           => Call,
10371               Target_Decl => Target_Attrs.Spec_Decl,
10372               Target_Body => Target_Attrs.Body_Decl)
10373      then
10374         if Call_Attrs.Elab_Warnings_OK then
10375            Error_Msg_NE ("??cannot call & before body seen", Call, Target_Id);
10376            Error_Msg_N ("\Program_Error will be raised at run time", Call);
10377         end if;
10378
10379         --  Mark the call as a guarnateed ABE
10380
10381         Set_Is_Known_Guaranteed_ABE (Call);
10382
10383         --  Install a run-time ABE failure because the call will always result
10384         --  in an ABE. The failure is installed when both the call and target
10385         --  have enabled elaboration checks, and both are not ignored Ghost
10386         --  constructs.
10387
10388         if Call_Attrs.Elab_Checks_OK
10389           and then Target_Attrs.Elab_Checks_OK
10390           and then not Call_Attrs.Ghost_Mode_Ignore
10391           and then not Target_Attrs.Ghost_Mode_Ignore
10392         then
10393            Install_ABE_Failure
10394              (N       => Call,
10395               Ins_Nod => Call);
10396         end if;
10397      end if;
10398   end Process_Guaranteed_ABE_Call;
10399
10400   ------------------------------------------
10401   -- Process_Guaranteed_ABE_Instantiation --
10402   ------------------------------------------
10403
10404   procedure Process_Guaranteed_ABE_Instantiation (Exp_Inst : Node_Id) is
10405      Gen_Attrs  : Target_Attributes;
10406      Gen_Id     : Entity_Id;
10407      Inst       : Node_Id;
10408      Inst_Attrs : Instantiation_Attributes;
10409      Inst_Id    : Entity_Id;
10410
10411   begin
10412      Extract_Instantiation_Attributes
10413        (Exp_Inst => Exp_Inst,
10414         Inst     => Inst,
10415         Inst_Id  => Inst_Id,
10416         Gen_Id   => Gen_Id,
10417         Attrs    => Inst_Attrs);
10418
10419      Extract_Target_Attributes (Gen_Id, Gen_Attrs);
10420
10421      --  Nothing to do when the root scenario appears at the declaration level
10422      --  and the generic is in the same unit, but outside this context.
10423      --
10424      --    generic
10425      --    procedure Gen is ...;                --  generic declaration
10426      --
10427      --    procedure Proc is
10428      --       function A ... is
10429      --       begin
10430      --          if Some_Condition then
10431      --             declare
10432      --                procedure I is new Gen;  --  instantiation site
10433      --             ...
10434      --          ...
10435      --       end A;
10436      --
10437      --       X : ... := A;                     --  root scenario
10438      --    ...
10439      --
10440      --    procedure Gen is
10441      --       ...
10442      --    end Gen;
10443      --
10444      --  In the example above, the context of X is the declarative region of
10445      --  Proc. The "elaboration" of X may eventually reach Gen which appears
10446      --  outside of X's context. Gen is relevant only when Proc is invoked,
10447      --  but this happens only by means of "normal" elaboration, therefore
10448      --  Gen must not be considered if this is not the case.
10449
10450      --  Performance note: parent traversal
10451
10452      if Is_Up_Level_Target (Gen_Attrs.Spec_Decl) then
10453         return;
10454
10455      --  Nothing to do when the instantiation is ABE-safe
10456      --
10457      --    generic
10458      --    package Gen is
10459      --       ...
10460      --    end Gen;
10461      --
10462      --    package body Gen is
10463      --       ...
10464      --    end Gen;
10465      --
10466      --    with Gen;
10467      --    procedure Main is
10468      --       package Inst is new Gen (ABE);    --  safe instantiation
10469      --    ...
10470
10471      elsif Is_Safe_Instantiation (Inst, Gen_Attrs) then
10472         return;
10473
10474      --  An instantiation leads to a guaranteed ABE when the instantiation and
10475      --  the generic appear within the same context ignoring library levels,
10476      --  and the body of the generic has not been seen yet or appears after
10477      --  the instantiation.
10478      --
10479      --    procedure Guaranteed_ABE is
10480      --       generic
10481      --       procedure Gen;
10482      --
10483      --       package Nested is
10484      --          procedure Inst is new Gen;     --  guaranteed ABE
10485      --       end Nested;
10486      --
10487      --       procedure Gen is
10488      --          ...
10489      --       end Gen;
10490      --    ...
10491
10492      --  Performance note: parent traversal
10493
10494      elsif Is_Guaranteed_ABE
10495              (N           => Inst,
10496               Target_Decl => Gen_Attrs.Spec_Decl,
10497               Target_Body => Gen_Attrs.Body_Decl)
10498      then
10499         if Inst_Attrs.Elab_Warnings_OK then
10500            Error_Msg_NE
10501              ("??cannot instantiate & before body seen", Inst, Gen_Id);
10502            Error_Msg_N ("\Program_Error will be raised at run time", Inst);
10503         end if;
10504
10505         --  Mark the instantiation as a guarantee ABE. This automatically
10506         --  suppresses the instantiation of the generic body.
10507
10508         Set_Is_Known_Guaranteed_ABE (Inst);
10509
10510         --  Install a run-time ABE failure because the instantiation will
10511         --  always result in an ABE. The failure is installed when both the
10512         --  instance and the generic have enabled elaboration checks, and both
10513         --  are not ignored Ghost constructs.
10514
10515         if Inst_Attrs.Elab_Checks_OK
10516           and then Gen_Attrs.Elab_Checks_OK
10517           and then not Inst_Attrs.Ghost_Mode_Ignore
10518           and then not Gen_Attrs.Ghost_Mode_Ignore
10519         then
10520            Install_ABE_Failure
10521              (N       => Inst,
10522               Ins_Nod => Exp_Inst);
10523         end if;
10524      end if;
10525   end Process_Guaranteed_ABE_Instantiation;
10526
10527   ----------------------------
10528   -- Process_Guaranteed_ABE --
10529   ----------------------------
10530
10531   --  NOTE: The body of this routine is intentionally out of order because it
10532   --  invokes an instantiated subprogram (Process_Guaranteed_ABE_Activation).
10533   --  Placing the body in alphabetical order will result in a guaranteed ABE.
10534
10535   procedure Process_Guaranteed_ABE (N : Node_Id) is
10536      Call_Attrs : Call_Attributes;
10537      Target_Id  : Entity_Id;
10538
10539   begin
10540      --  Add the current scenario to the stack of active scenarios
10541
10542      Push_Active_Scenario (N);
10543
10544      --  Only calls, instantiations, and task activations may result in a
10545      --  guaranteed ABE.
10546
10547      if Is_Suitable_Call (N) then
10548         Extract_Call_Attributes
10549           (Call      => N,
10550            Target_Id => Target_Id,
10551            Attrs     => Call_Attrs);
10552
10553         if Is_Activation_Proc (Target_Id) then
10554            Process_Guaranteed_ABE_Activation
10555              (Call       => N,
10556               Call_Attrs => Call_Attrs,
10557               State      => Initial_State);
10558
10559         else
10560            Process_Guaranteed_ABE_Call
10561              (Call       => N,
10562               Call_Attrs => Call_Attrs,
10563               Target_Id  => Target_Id);
10564         end if;
10565
10566      elsif Is_Suitable_Instantiation (N) then
10567         Process_Guaranteed_ABE_Instantiation (N);
10568      end if;
10569
10570      --  Remove the current scenario from the stack of active scenarios once
10571      --  all ABE diagnostics and checks have been performed.
10572
10573      Pop_Active_Scenario (N);
10574   end Process_Guaranteed_ABE;
10575
10576   --------------------------
10577   -- Push_Active_Scenario --
10578   --------------------------
10579
10580   procedure Push_Active_Scenario (N : Node_Id) is
10581   begin
10582      Scenario_Stack.Append (N);
10583   end Push_Active_Scenario;
10584
10585   ---------------------------------
10586   -- Record_Elaboration_Scenario --
10587   ---------------------------------
10588
10589   procedure Record_Elaboration_Scenario (N : Node_Id) is
10590      Level : Enclosing_Level_Kind;
10591
10592      Any_Level_OK : Boolean;
10593      --  This flag is set when a particular scenario is allowed to appear at
10594      --  any level.
10595
10596      Declaration_Level_OK : Boolean;
10597      --  This flag is set when a particular scenario is allowed to appear at
10598      --  the declaration level.
10599
10600      Library_Level_OK : Boolean;
10601      --  This flag is set when a particular scenario is allowed to appear at
10602      --  the library level.
10603
10604   begin
10605      --  Assume that the scenario cannot appear on any level
10606
10607      Any_Level_OK         := False;
10608      Declaration_Level_OK := False;
10609      Library_Level_OK     := False;
10610
10611      --  Nothing to do when switch -gnatH (legacy elaboration checking mode
10612      --  enabled) is in effect because the legacy ABE mechanism does not need
10613      --  to carry out this action.
10614
10615      if Legacy_Elaboration_Checks then
10616         return;
10617
10618      --  Nothing to do for ASIS. As a result, no ABE checks and diagnostics
10619      --  are performed in this mode.
10620
10621      elsif ASIS_Mode then
10622         return;
10623
10624      --  Nothing to do when the scenario is being preanalyzed
10625
10626      elsif Preanalysis_Active then
10627         return;
10628      end if;
10629
10630      --  Ensure that a library-level call does not appear in a preelaborated
10631      --  unit. The check must come before ignoring scenarios within external
10632      --  units or inside generics because calls in those context must also be
10633      --  verified.
10634
10635      if Is_Suitable_Call (N) then
10636         Check_Preelaborated_Call (N);
10637      end if;
10638
10639      --  Nothing to do when the scenario does not appear within the main unit
10640
10641      if not In_Main_Context (N) then
10642         return;
10643
10644      --  Scenarios within a generic unit are never considered because generics
10645      --  cannot be elaborated.
10646
10647      elsif Inside_A_Generic then
10648         return;
10649
10650      --  Scenarios which do not fall in one of the elaboration categories
10651      --  listed below are not considered. The categories are:
10652
10653      --   'Access for entries, operators, and subprograms
10654      --    Assignments to variables
10655      --    Calls (includes task activation)
10656      --    Derived types
10657      --    Instantiations
10658      --    Pragma Refined_State
10659      --    Reads of variables
10660
10661      elsif Is_Suitable_Access (N) then
10662         Library_Level_OK := True;
10663
10664         --  Signal any enclosing local exception handlers that the 'Access may
10665         --  raise Program_Error due to a failed ABE check when switch -gnatd.o
10666         --  (conservative elaboration order for indirect calls) is in effect.
10667         --  Marking the exception handlers ensures proper expansion by both
10668         --  the front and back end restriction when No_Exception_Propagation
10669         --  is in effect.
10670
10671         if Debug_Flag_Dot_O then
10672            Possible_Local_Raise (N, Standard_Program_Error);
10673         end if;
10674
10675      elsif Is_Suitable_Call (N) or else Is_Suitable_Instantiation (N) then
10676         Declaration_Level_OK := True;
10677         Library_Level_OK     := True;
10678
10679         --  Signal any enclosing local exception handlers that the call or
10680         --  instantiation may raise Program_Error due to a failed ABE check.
10681         --  Marking the exception handlers ensures proper expansion by both
10682         --  the front and back end restriction when No_Exception_Propagation
10683         --  is in effect.
10684
10685         Possible_Local_Raise (N, Standard_Program_Error);
10686
10687      elsif Is_Suitable_SPARK_Derived_Type (N) then
10688         Any_Level_OK := True;
10689
10690      elsif Is_Suitable_SPARK_Refined_State_Pragma (N) then
10691         Library_Level_OK := True;
10692
10693      elsif Is_Suitable_Variable_Assignment (N)
10694        or else Is_Suitable_Variable_Reference (N)
10695      then
10696         Library_Level_OK := True;
10697
10698      --  Otherwise the input does not denote a suitable scenario
10699
10700      else
10701         return;
10702      end if;
10703
10704      --  The static model imposes additional restrictions on the placement of
10705      --  scenarios. In contrast, the dynamic model assumes that every scenario
10706      --  will be elaborated or invoked at some point.
10707
10708      if Static_Elaboration_Checks then
10709
10710         --  Certain scenarios are allowed to appear at any level. This check
10711         --  is performed here in order to save on a parent traversal.
10712
10713         if Any_Level_OK then
10714            null;
10715
10716         --  Otherwise the scenario must appear at a specific level
10717
10718         else
10719            --  Performance note: parent traversal
10720
10721            Level := Find_Enclosing_Level (N);
10722
10723            --  Declaration-level scenario
10724
10725            if Declaration_Level_OK and then Level = Declaration_Level then
10726               null;
10727
10728            --  Library-level or instantiation scenario
10729
10730            elsif Library_Level_OK
10731              and then Level in Library_Or_Instantiation_Level
10732            then
10733               null;
10734
10735            --  Otherwise the scenario does not appear at the proper level and
10736            --  cannot possibly act as a top-level scenario.
10737
10738            else
10739               return;
10740            end if;
10741         end if;
10742      end if;
10743
10744      --  Derived types subject to SPARK_Mode On require elaboration-related
10745      --  checks even though the type may not be declared within elaboration
10746      --  code. The types are recorded in a separate table which is examined
10747      --  during the Processing phase. Note that the checks must be delayed
10748      --  because the bodies of overriding primitives are not available yet.
10749
10750      if Is_Suitable_SPARK_Derived_Type (N) then
10751         Record_SPARK_Elaboration_Scenario (N);
10752
10753         --  Nothing left to do for derived types
10754
10755         return;
10756
10757      --  Instantiations of generics both subject to SPARK_Mode On require
10758      --  elaboration-related checks even though the instantiations may not
10759      --  appear within elaboration code. The instantiations are recored in
10760      --  a separate table which is examined during the Procesing phase. Note
10761      --  that the checks must be delayed because it is not known yet whether
10762      --  the generic unit has a body or not.
10763
10764      --  IMPORTANT: A SPARK instantiation is also a normal instantiation which
10765      --  is subject to common conditional and guaranteed ABE checks.
10766
10767      elsif Is_Suitable_SPARK_Instantiation (N) then
10768         Record_SPARK_Elaboration_Scenario (N);
10769
10770      --  External constituents that refine abstract states which appear in
10771      --  pragma Initializes require elaboration-related checks even though
10772      --  a Refined_State pragma lacks any elaboration semantic.
10773
10774      elsif Is_Suitable_SPARK_Refined_State_Pragma (N) then
10775         Record_SPARK_Elaboration_Scenario (N);
10776
10777         --  Nothing left to do for pragma Refined_State
10778
10779         return;
10780      end if;
10781
10782      --  Perform early detection of guaranteed ABEs in order to suppress the
10783      --  instantiation of generic bodies as gigi cannot handle certain types
10784      --  of premature instantiations.
10785
10786      Process_Guaranteed_ABE (N);
10787
10788      --  At this point all checks have been performed. Record the scenario for
10789      --  later processing by the ABE phase.
10790
10791      Top_Level_Scenarios.Append (N);
10792      Set_Is_Recorded_Top_Level_Scenario (N);
10793   end Record_Elaboration_Scenario;
10794
10795   ---------------------------------------
10796   -- Record_SPARK_Elaboration_Scenario --
10797   ---------------------------------------
10798
10799   procedure Record_SPARK_Elaboration_Scenario (N : Node_Id) is
10800   begin
10801      SPARK_Scenarios.Append (N);
10802      Set_Is_Recorded_SPARK_Scenario (N);
10803   end Record_SPARK_Elaboration_Scenario;
10804
10805   -----------------------------------
10806   -- Recorded_SPARK_Scenarios_Hash --
10807   -----------------------------------
10808
10809   function Recorded_SPARK_Scenarios_Hash
10810     (Key : Node_Id) return Recorded_SPARK_Scenarios_Index
10811   is
10812   begin
10813      return
10814        Recorded_SPARK_Scenarios_Index (Key mod Recorded_SPARK_Scenarios_Max);
10815   end Recorded_SPARK_Scenarios_Hash;
10816
10817   ---------------------------------------
10818   -- Recorded_Top_Level_Scenarios_Hash --
10819   ---------------------------------------
10820
10821   function Recorded_Top_Level_Scenarios_Hash
10822     (Key : Node_Id) return Recorded_Top_Level_Scenarios_Index
10823   is
10824   begin
10825      return
10826        Recorded_Top_Level_Scenarios_Index
10827          (Key mod Recorded_Top_Level_Scenarios_Max);
10828   end Recorded_Top_Level_Scenarios_Hash;
10829
10830   --------------------------
10831   -- Reset_Visited_Bodies --
10832   --------------------------
10833
10834   procedure Reset_Visited_Bodies is
10835   begin
10836      if Visited_Bodies_In_Use then
10837         Visited_Bodies_In_Use := False;
10838         Visited_Bodies.Reset;
10839      end if;
10840   end Reset_Visited_Bodies;
10841
10842   -------------------
10843   -- Root_Scenario --
10844   -------------------
10845
10846   function Root_Scenario return Node_Id is
10847      package Stack renames Scenario_Stack;
10848
10849   begin
10850      --  Ensure that the scenario stack has at least one active scenario in
10851      --  it. The one at the bottom (index First) is the root scenario.
10852
10853      pragma Assert (Stack.Last >= Stack.First);
10854      return Stack.Table (Stack.First);
10855   end Root_Scenario;
10856
10857   ---------------------------
10858   -- Set_Early_Call_Region --
10859   ---------------------------
10860
10861   procedure Set_Early_Call_Region (Body_Id : Entity_Id; Start : Node_Id) is
10862   begin
10863      pragma Assert (Ekind_In (Body_Id, E_Entry,
10864                                        E_Entry_Family,
10865                                        E_Function,
10866                                        E_Procedure,
10867                                        E_Subprogram_Body));
10868
10869      Early_Call_Regions_In_Use := True;
10870      Early_Call_Regions.Set (Body_Id, Start);
10871   end Set_Early_Call_Region;
10872
10873   ----------------------------
10874   -- Set_Elaboration_Status --
10875   ----------------------------
10876
10877   procedure Set_Elaboration_Status
10878     (Unit_Id : Entity_Id;
10879      Val     : Elaboration_Attributes)
10880   is
10881   begin
10882      Elaboration_Statuses_In_Use := True;
10883      Elaboration_Statuses.Set (Unit_Id, Val);
10884   end Set_Elaboration_Status;
10885
10886   ------------------------------------
10887   -- Set_Is_Recorded_SPARK_Scenario --
10888   ------------------------------------
10889
10890   procedure Set_Is_Recorded_SPARK_Scenario
10891     (N   : Node_Id;
10892      Val : Boolean := True)
10893   is
10894   begin
10895      Recorded_SPARK_Scenarios_In_Use := True;
10896      Recorded_SPARK_Scenarios.Set (N, Val);
10897   end Set_Is_Recorded_SPARK_Scenario;
10898
10899   ----------------------------------------
10900   -- Set_Is_Recorded_Top_Level_Scenario --
10901   ----------------------------------------
10902
10903   procedure Set_Is_Recorded_Top_Level_Scenario
10904     (N   : Node_Id;
10905      Val : Boolean := True)
10906   is
10907   begin
10908      Recorded_Top_Level_Scenarios_In_Use := True;
10909      Recorded_Top_Level_Scenarios.Set (N, Val);
10910   end Set_Is_Recorded_Top_Level_Scenario;
10911
10912   -------------------------
10913   -- Set_Is_Visited_Body --
10914   -------------------------
10915
10916   procedure Set_Is_Visited_Body (Subp_Body : Node_Id) is
10917   begin
10918      Visited_Bodies_In_Use := True;
10919      Visited_Bodies.Set (Subp_Body, True);
10920   end Set_Is_Visited_Body;
10921
10922   -------------------------------
10923   -- Static_Elaboration_Checks --
10924   -------------------------------
10925
10926   function Static_Elaboration_Checks return Boolean is
10927   begin
10928      return not Dynamic_Elaboration_Checks;
10929   end Static_Elaboration_Checks;
10930
10931   -------------------
10932   -- Traverse_Body --
10933   -------------------
10934
10935   procedure Traverse_Body (N : Node_Id; State : Processing_Attributes) is
10936      procedure Find_And_Process_Nested_Scenarios;
10937      pragma Inline (Find_And_Process_Nested_Scenarios);
10938      --  Examine the declarations and statements of subprogram body N for
10939      --  suitable scenarios. Save each discovered scenario and process it
10940      --  accordingly.
10941
10942      procedure Process_Nested_Scenarios (Nested : Elist_Id);
10943      pragma Inline (Process_Nested_Scenarios);
10944      --  Invoke Process_Conditional_ABE on each individual scenario found in
10945      --  list Nested.
10946
10947      ---------------------------------------
10948      -- Find_And_Process_Nested_Scenarios --
10949      ---------------------------------------
10950
10951      procedure Find_And_Process_Nested_Scenarios is
10952         Body_Id : constant Entity_Id := Defining_Entity (N);
10953
10954         function Is_Potential_Scenario
10955           (Nod : Node_Id) return Traverse_Result;
10956         --  Determine whether arbitrary node Nod denotes a suitable scenario.
10957         --  If it does, save it in the Nested_Scenarios list of the subprogram
10958         --  body, and process it.
10959
10960         procedure Save_Scenario (Nod : Node_Id);
10961         pragma Inline (Save_Scenario);
10962         --  Save scenario Nod in the Nested_Scenarios list of the subprogram
10963         --  body.
10964
10965         procedure Traverse_List (List : List_Id);
10966         pragma Inline (Traverse_List);
10967         --  Invoke Traverse_Potential_Scenarios on each node in list List
10968
10969         procedure Traverse_Potential_Scenarios is
10970           new Traverse_Proc (Is_Potential_Scenario);
10971
10972         ---------------------------
10973         -- Is_Potential_Scenario --
10974         ---------------------------
10975
10976         function Is_Potential_Scenario
10977           (Nod : Node_Id) return Traverse_Result
10978         is
10979         begin
10980            --  Special cases
10981
10982            --  Skip constructs which do not have elaboration of their own and
10983            --  need to be elaborated by other means such as invocation, task
10984            --  activation, etc.
10985
10986            if Is_Non_Library_Level_Encapsulator (Nod) then
10987               return Skip;
10988
10989            --  Terminate the traversal of a task body with an accept statement
10990            --  when no entry calls in elaboration are allowed because the task
10991            --  will block at run-time and the remaining statements will not be
10992            --  executed.
10993
10994            elsif Nkind_In (Original_Node (Nod), N_Accept_Statement,
10995                                                 N_Selective_Accept)
10996            then
10997               if Restriction_Active (No_Entry_Calls_In_Elaboration_Code) then
10998                  return Abandon;
10999
11000               --  The same behavior is achieved when switch -gnatd_a (stop
11001               --  elabortion checks on accept or select statement) is in
11002               --  effect.
11003
11004               elsif Debug_Flag_Underscore_A then
11005                  return Abandon;
11006               end if;
11007
11008            --  Certain nodes carry semantic lists which act as repositories
11009            --  until expansion transforms the node and relocates the contents.
11010            --  Examine these lists in case expansion is disabled.
11011
11012            elsif Nkind_In (Nod, N_And_Then, N_Or_Else) then
11013               Traverse_List (Actions (Nod));
11014
11015            elsif Nkind_In (Nod, N_Elsif_Part, N_Iteration_Scheme) then
11016               Traverse_List (Condition_Actions (Nod));
11017
11018            elsif Nkind (Nod) = N_If_Expression then
11019               Traverse_List (Then_Actions (Nod));
11020               Traverse_List (Else_Actions (Nod));
11021
11022            elsif Nkind_In (Nod, N_Component_Association,
11023                                 N_Iterated_Component_Association)
11024            then
11025               Traverse_List (Loop_Actions (Nod));
11026
11027            --  General case
11028
11029            --  Save a suitable scenario in the Nested_Scenarios list of the
11030            --  subprogram body. As a result any subsequent traversals of the
11031            --  subprogram body started from a different top-level scenario no
11032            --  longer need to reexamine the tree.
11033
11034            elsif Is_Suitable_Scenario (Nod) then
11035               Save_Scenario (Nod);
11036
11037               Process_Conditional_ABE
11038                 (N     => Nod,
11039                  State => State);
11040            end if;
11041
11042            return OK;
11043         end Is_Potential_Scenario;
11044
11045         -------------------
11046         -- Save_Scenario --
11047         -------------------
11048
11049         procedure Save_Scenario (Nod : Node_Id) is
11050            Nested : Elist_Id;
11051
11052         begin
11053            Nested := Nested_Scenarios (Body_Id);
11054
11055            if No (Nested) then
11056               Nested := New_Elmt_List;
11057               Set_Nested_Scenarios (Body_Id, Nested);
11058            end if;
11059
11060            Append_Elmt (Nod, Nested);
11061         end Save_Scenario;
11062
11063         -------------------
11064         -- Traverse_List --
11065         -------------------
11066
11067         procedure Traverse_List (List : List_Id) is
11068            Item : Node_Id;
11069
11070         begin
11071            Item := First (List);
11072            while Present (Item) loop
11073               Traverse_Potential_Scenarios (Item);
11074               Next (Item);
11075            end loop;
11076         end Traverse_List;
11077
11078      --  Start of processing for Find_And_Process_Nested_Scenarios
11079
11080      begin
11081         --  Examine the declarations for suitable scenarios
11082
11083         Traverse_List (Declarations (N));
11084
11085         --  Examine the handled sequence of statements. This also includes any
11086         --  exceptions handlers.
11087
11088         Traverse_Potential_Scenarios (Handled_Statement_Sequence (N));
11089      end Find_And_Process_Nested_Scenarios;
11090
11091      ------------------------------
11092      -- Process_Nested_Scenarios --
11093      ------------------------------
11094
11095      procedure Process_Nested_Scenarios (Nested : Elist_Id) is
11096         Nested_Elmt : Elmt_Id;
11097
11098      begin
11099         Nested_Elmt := First_Elmt (Nested);
11100         while Present (Nested_Elmt) loop
11101            Process_Conditional_ABE
11102              (N     => Node (Nested_Elmt),
11103               State => State);
11104
11105            Next_Elmt (Nested_Elmt);
11106         end loop;
11107      end Process_Nested_Scenarios;
11108
11109      --  Local variables
11110
11111      Nested : Elist_Id;
11112
11113   --  Start of processing for Traverse_Body
11114
11115   begin
11116      --  Nothing to do when there is no body
11117
11118      if No (N) then
11119         return;
11120
11121      elsif Nkind (N) /= N_Subprogram_Body then
11122         return;
11123      end if;
11124
11125      --  Nothing to do if the body was already traversed during the processing
11126      --  of the same top-level scenario.
11127
11128      if Is_Visited_Body (N) then
11129         return;
11130
11131      --  Otherwise mark the body as traversed
11132
11133      else
11134         Set_Is_Visited_Body (N);
11135      end if;
11136
11137      Nested := Nested_Scenarios (Defining_Entity (N));
11138
11139      --  The subprogram body was already examined as part of the elaboration
11140      --  graph starting from a different top-level scenario. There is no need
11141      --  to traverse the declarations and statements again because this will
11142      --  yield the exact same scenarios. Use the nested scenarios collected
11143      --  during the first inspection of the body.
11144
11145      if Present (Nested) then
11146         Process_Nested_Scenarios (Nested);
11147
11148      --  Otherwise examine the declarations and statements of the subprogram
11149      --  body for suitable scenarios, save and process them accordingly.
11150
11151      else
11152         Find_And_Process_Nested_Scenarios;
11153      end if;
11154   end Traverse_Body;
11155
11156   ---------------------------------
11157   -- Update_Elaboration_Scenario --
11158   ---------------------------------
11159
11160   procedure Update_Elaboration_Scenario (New_N : Node_Id; Old_N : Node_Id) is
11161      procedure Update_SPARK_Scenario;
11162      pragma Inline (Update_SPARK_Scenario);
11163      --  Update the contents of table SPARK_Scenarios if Old_N is recorded
11164      --  there.
11165
11166      procedure Update_Top_Level_Scenario;
11167      pragma Inline (Update_Top_Level_Scenario);
11168      --  Update the contexts of table Top_Level_Scenarios if Old_N is recorded
11169      --  there.
11170
11171      ---------------------------
11172      -- Update_SPARK_Scenario --
11173      ---------------------------
11174
11175      procedure Update_SPARK_Scenario is
11176         package Scenarios renames SPARK_Scenarios;
11177
11178      begin
11179         if Is_Recorded_SPARK_Scenario (Old_N) then
11180
11181            --  Performance note: list traversal
11182
11183            for Index in Scenarios.First .. Scenarios.Last loop
11184               if Scenarios.Table (Index) = Old_N then
11185                  Scenarios.Table (Index) := New_N;
11186
11187                  --  The old SPARK scenario is no longer recorded, but the new
11188                  --  one is.
11189
11190                  Set_Is_Recorded_Top_Level_Scenario (Old_N, False);
11191                  Set_Is_Recorded_Top_Level_Scenario (New_N);
11192                  return;
11193               end if;
11194            end loop;
11195
11196            --  A recorded SPARK scenario must be in the table of recorded
11197            --  SPARK scenarios.
11198
11199            pragma Assert (False);
11200         end if;
11201      end Update_SPARK_Scenario;
11202
11203      -------------------------------
11204      -- Update_Top_Level_Scenario --
11205      -------------------------------
11206
11207      procedure Update_Top_Level_Scenario is
11208         package Scenarios renames Top_Level_Scenarios;
11209
11210      begin
11211         if Is_Recorded_Top_Level_Scenario (Old_N) then
11212
11213            --  Performance note: list traversal
11214
11215            for Index in Scenarios.First .. Scenarios.Last loop
11216               if Scenarios.Table (Index) = Old_N then
11217                  Scenarios.Table (Index) := New_N;
11218
11219                  --  The old top-level scenario is no longer recorded, but the
11220                  --  new one is.
11221
11222                  Set_Is_Recorded_Top_Level_Scenario (Old_N, False);
11223                  Set_Is_Recorded_Top_Level_Scenario (New_N);
11224                  return;
11225               end if;
11226            end loop;
11227
11228            --  A recorded top-level scenario must be in the table of recorded
11229            --  top-level scenarios.
11230
11231            pragma Assert (False);
11232         end if;
11233      end Update_Top_Level_Scenario;
11234
11235   --  Start of processing for Update_Elaboration_Requirement
11236
11237   begin
11238      --  Nothing to do when the old and new scenarios are one and the same
11239
11240      if Old_N = New_N then
11241         return;
11242
11243      --  A scenario is being transformed by Atree.Rewrite. Update all relevant
11244      --  internal data structures to reflect this change. This ensures that a
11245      --  potential run-time conditional ABE check or a guaranteed ABE failure
11246      --  is inserted at the proper place in the tree.
11247
11248      elsif Is_Scenario (Old_N) then
11249         Update_SPARK_Scenario;
11250         Update_Top_Level_Scenario;
11251      end if;
11252   end Update_Elaboration_Scenario;
11253
11254   -------------------------
11255   -- Visited_Bodies_Hash --
11256   -------------------------
11257
11258   function Visited_Bodies_Hash (Key : Node_Id) return Visited_Bodies_Index is
11259   begin
11260      return Visited_Bodies_Index (Key mod Visited_Bodies_Max);
11261   end Visited_Bodies_Hash;
11262
11263   ---------------------------------------------------------------------------
11264   --                                                                       --
11265   --  L E G A C Y    A C C E S S    B E F O R E    E L A B O R A T I O N   --
11266   --                                                                       --
11267   --                          M E C H A N I S M                            --
11268   --                                                                       --
11269   ---------------------------------------------------------------------------
11270
11271   --  This section contains the implementation of the pre-18.x legacy ABE
11272   --  mechanism. The mechanism can be activated using switch -gnatH (legacy
11273   --  elaboration checking mode enabled).
11274
11275   -----------------------------
11276   -- Description of Approach --
11277   -----------------------------
11278
11279   --  Every non-static call that is encountered by Sem_Res results in a call
11280   --  to Check_Elab_Call, with N being the call node, and Outer set to its
11281   --  default value of True. In addition X'Access is treated like a call
11282   --  for the access-to-procedure case, and in SPARK mode only we also
11283   --  check variable references.
11284
11285   --  The goal of Check_Elab_Call is to determine whether or not the reference
11286   --  in question can generate an access before elaboration error (raising
11287   --  Program_Error) either by directly calling a subprogram whose body
11288   --  has not yet been elaborated, or indirectly, by calling a subprogram
11289   --  whose body has been elaborated, but which contains a call to such a
11290   --  subprogram.
11291
11292   --  In addition, in SPARK mode, we are checking for a variable reference in
11293   --  another package, which requires an explicit Elaborate_All pragma.
11294
11295   --  The only references that we need to look at the outer level are
11296   --  references that occur in elaboration code. There are two cases. The
11297   --  reference can be at the outer level of elaboration code, or it can
11298   --  be within another unit, e.g. the elaboration code of a subprogram.
11299
11300   --  In the case of an elaboration call at the outer level, we must trace
11301   --  all calls to outer level routines either within the current unit or to
11302   --  other units that are with'ed. For calls within the current unit, we can
11303   --  determine if the body has been elaborated or not, and if it has not,
11304   --  then a warning is generated.
11305
11306   --  Note that there are two subcases. If the original call directly calls a
11307   --  subprogram whose body has not been elaborated, then we know that an ABE
11308   --  will take place, and we replace the call by a raise of Program_Error.
11309   --  If the call is indirect, then we don't know that the PE will be raised,
11310   --  since the call might be guarded by a conditional. In this case we set
11311   --  Do_Elab_Check on the call so that a dynamic check is generated, and
11312   --  output a warning.
11313
11314   --  For calls to a subprogram in a with'ed unit or a 'Access or variable
11315   --  reference (SPARK mode case), we require that a pragma Elaborate_All
11316   --  or pragma Elaborate be present, or that the referenced unit have a
11317   --  pragma Preelaborate, pragma Pure, or pragma Elaborate_Body. If none
11318   --  of these conditions is met, then a warning is generated that a pragma
11319   --  Elaborate_All may be needed (error in the SPARK case), or an implicit
11320   --  pragma is generated.
11321
11322   --  For the case of an elaboration call at some inner level, we are
11323   --  interested in tracing only calls to subprograms at the same level, i.e.
11324   --  those that can be called during elaboration. Any calls to outer level
11325   --  routines cannot cause ABE's as a result of the original call (there
11326   --  might be an outer level call to the subprogram from outside that causes
11327   --  the ABE, but that gets analyzed separately).
11328
11329   --  Note that we never trace calls to inner level subprograms, since these
11330   --  cannot result in ABE's unless there is an elaboration problem at a lower
11331   --  level, which will be separately detected.
11332
11333   --  Note on pragma Elaborate. The checking here assumes that a pragma
11334   --  Elaborate on a with'ed unit guarantees that subprograms within the unit
11335   --  can be called without causing an ABE. This is not in fact the case since
11336   --  pragma Elaborate does not guarantee the transitive coverage guaranteed
11337   --  by Elaborate_All. However, we decide to trust the user in this case.
11338
11339   --------------------------------------
11340   -- Instantiation Elaboration Errors --
11341   --------------------------------------
11342
11343   --  A special case arises when an instantiation appears in a context that is
11344   --  known to be before the body is elaborated, e.g.
11345
11346   --       generic package x is ...
11347   --       ...
11348   --       package xx is new x;
11349   --       ...
11350   --       package body x is ...
11351
11352   --  In this situation it is certain that an elaboration error will occur,
11353   --  and an unconditional raise Program_Error statement is inserted before
11354   --  the instantiation, and a warning generated.
11355
11356   --  The problem is that in this case we have no place to put the body of
11357   --  the instantiation. We can't put it in the normal place, because it is
11358   --  too early, and will cause errors to occur as a result of referencing
11359   --  entities before they are declared.
11360
11361   --  Our approach in this case is simply to avoid creating the body of the
11362   --  instantiation in such a case. The instantiation spec is modified to
11363   --  include dummy bodies for all subprograms, so that the resulting code
11364   --  does not contain subprogram specs with no corresponding bodies.
11365
11366   --  The following table records the recursive call chain for output in the
11367   --  Output routine. Each entry records the call node and the entity of the
11368   --  called routine. The number of entries in the table (i.e. the value of
11369   --  Elab_Call.Last) indicates the current depth of recursion and is used to
11370   --  identify the outer level.
11371
11372   type Elab_Call_Element is record
11373      Cloc : Source_Ptr;
11374      Ent  : Entity_Id;
11375   end record;
11376
11377   package Elab_Call is new Table.Table
11378     (Table_Component_Type => Elab_Call_Element,
11379      Table_Index_Type     => Int,
11380      Table_Low_Bound      => 1,
11381      Table_Initial        => 50,
11382      Table_Increment      => 100,
11383      Table_Name           => "Elab_Call");
11384
11385   --  The following table records all calls that have been processed starting
11386   --  from an outer level call. The table prevents both infinite recursion and
11387   --  useless reanalysis of calls within the same context. The use of context
11388   --  is important because it allows for proper checks in more complex code:
11389
11390   --    if ... then
11391   --       Call;  --  requires a check
11392   --       Call;  --  does not need a check thanks to the table
11393   --    elsif ... then
11394   --       Call;  --  requires a check, different context
11395   --    end if;
11396
11397   --    Call;     --  requires a check, different context
11398
11399   type Visited_Element is record
11400      Subp_Id : Entity_Id;
11401      --  The entity of the subprogram being called
11402
11403      Context : Node_Id;
11404      --  The context where the call to the subprogram occurs
11405   end record;
11406
11407   package Elab_Visited is new Table.Table
11408     (Table_Component_Type => Visited_Element,
11409      Table_Index_Type     => Int,
11410      Table_Low_Bound      => 1,
11411      Table_Initial        => 200,
11412      Table_Increment      => 100,
11413      Table_Name           => "Elab_Visited");
11414
11415   --  The following table records delayed calls which must be examined after
11416   --  all generic bodies have been instantiated.
11417
11418   type Delay_Element is record
11419      N : Node_Id;
11420      --  The parameter N from the call to Check_Internal_Call. Note that this
11421      --  node may get rewritten over the delay period by expansion in the call
11422      --  case (but not in the instantiation case).
11423
11424      E : Entity_Id;
11425      --  The parameter E from the call to Check_Internal_Call
11426
11427      Orig_Ent : Entity_Id;
11428      --  The parameter Orig_Ent from the call to Check_Internal_Call
11429
11430      Curscop : Entity_Id;
11431      --  The current scope of the call. This is restored when we complete the
11432      --  delayed call, so that we do this in the right scope.
11433
11434      Outer_Scope : Entity_Id;
11435      --  Save scope of outer level call
11436
11437      From_Elab_Code : Boolean;
11438      --  Save indication of whether this call is from elaboration code
11439
11440      In_Task_Activation : Boolean;
11441      --  Save indication of whether this call is from a task body. Tasks are
11442      --  activated at the "begin", which is after all local procedure bodies,
11443      --  so calls to those procedures can't fail, even if they occur after the
11444      --  task body.
11445
11446      From_SPARK_Code : Boolean;
11447      --  Save indication of whether this call is under SPARK_Mode => On
11448   end record;
11449
11450   package Delay_Check is new Table.Table
11451     (Table_Component_Type => Delay_Element,
11452      Table_Index_Type     => Int,
11453      Table_Low_Bound      => 1,
11454      Table_Initial        => 1000,
11455      Table_Increment      => 100,
11456      Table_Name           => "Delay_Check");
11457
11458   C_Scope : Entity_Id;
11459   --  Top-level scope of current scope. Compute this only once at the outer
11460   --  level, i.e. for a call to Check_Elab_Call from outside this unit.
11461
11462   Outer_Level_Sloc : Source_Ptr;
11463   --  Save Sloc value for outer level call node for comparisons of source
11464   --  locations. A body is too late if it appears after the *outer* level
11465   --  call, not the particular call that is being analyzed.
11466
11467   From_Elab_Code : Boolean;
11468   --  This flag shows whether the outer level call currently being examined
11469   --  is or is not in elaboration code. We are only interested in calls to
11470   --  routines in other units if this flag is True.
11471
11472   In_Task_Activation : Boolean := False;
11473   --  This flag indicates whether we are performing elaboration checks on task
11474   --  bodies, at the point of activation. If true, we do not raise
11475   --  Program_Error for calls to local procedures, because all local bodies
11476   --  are known to be elaborated. However, we still need to trace such calls,
11477   --  because a local procedure could call a procedure in another package,
11478   --  so we might need an implicit Elaborate_All.
11479
11480   Delaying_Elab_Checks : Boolean := True;
11481   --  This is set True till the compilation is complete, including the
11482   --  insertion of all instance bodies. Then when Check_Elab_Calls is called,
11483   --  the delay table is used to make the delayed calls and this flag is reset
11484   --  to False, so that the calls are processed.
11485
11486   -----------------------
11487   -- Local Subprograms --
11488   -----------------------
11489
11490   --  Note: Outer_Scope in all following specs represents the scope of
11491   --  interest of the outer level call. If it is set to Standard_Standard,
11492   --  then it means the outer level call was at elaboration level, and that
11493   --  thus all calls are of interest. If it was set to some other scope,
11494   --  then the original call was an inner call, and we are not interested
11495   --  in calls that go outside this scope.
11496
11497   procedure Activate_Elaborate_All_Desirable (N : Node_Id; U : Entity_Id);
11498   --  Analysis of construct N shows that we should set Elaborate_All_Desirable
11499   --  for the WITH clause for unit U (which will always be present). A special
11500   --  case is when N is a function or procedure instantiation, in which case
11501   --  it is sufficient to set Elaborate_Desirable, since in this case there is
11502   --  no possibility of transitive elaboration issues.
11503
11504   procedure Check_A_Call
11505     (N                 : Node_Id;
11506      E                 : Entity_Id;
11507      Outer_Scope       : Entity_Id;
11508      Inter_Unit_Only   : Boolean;
11509      Generate_Warnings : Boolean := True;
11510      In_Init_Proc      : Boolean := False);
11511   --  This is the internal recursive routine that is called to check for
11512   --  possible elaboration error. The argument N is a subprogram call or
11513   --  generic instantiation, or 'Access attribute reference to be checked, and
11514   --  E is the entity of the called subprogram, or instantiated generic unit,
11515   --  or subprogram referenced by 'Access.
11516   --
11517   --  In SPARK mode, N can also be a variable reference, since in SPARK this
11518   --  also triggers a requirement for Elaborate_All, and in this case E is the
11519   --  entity being referenced.
11520   --
11521   --  Outer_Scope is the outer level scope for the original reference.
11522   --  Inter_Unit_Only is set if the call is only to be checked in the
11523   --  case where it is to another unit (and skipped if within a unit).
11524   --  Generate_Warnings is set to False to suppress warning messages about
11525   --  missing pragma Elaborate_All's. These messages are not wanted for
11526   --  inner calls in the dynamic model. Note that an instance of the Access
11527   --  attribute applied to a subprogram also generates a call to this
11528   --  procedure (since the referenced subprogram may be called later
11529   --  indirectly). Flag In_Init_Proc should be set whenever the current
11530   --  context is a type init proc.
11531   --
11532   --  Note: this might better be called Check_A_Reference to recognize the
11533   --  variable case for SPARK, but we prefer to retain the historical name
11534   --  since in practice this is mostly about checking calls for the possible
11535   --  occurrence of an access-before-elaboration exception.
11536
11537   procedure Check_Bad_Instantiation (N : Node_Id);
11538   --  N is a node for an instantiation (if called with any other node kind,
11539   --  Check_Bad_Instantiation ignores the call). This subprogram checks for
11540   --  the special case of a generic instantiation of a generic spec in the
11541   --  same declarative part as the instantiation where a body is present and
11542   --  has not yet been seen. This is an obvious error, but needs to be checked
11543   --  specially at the time of the instantiation, since it is a case where we
11544   --  cannot insert the body anywhere. If this case is detected, warnings are
11545   --  generated, and a raise of Program_Error is inserted. In addition any
11546   --  subprograms in the generic spec are stubbed, and the Bad_Instantiation
11547   --  flag is set on the instantiation node. The caller in Sem_Ch12 uses this
11548   --  flag as an indication that no attempt should be made to insert an
11549   --  instance body.
11550
11551   procedure Check_Internal_Call
11552     (N           : Node_Id;
11553      E           : Entity_Id;
11554      Outer_Scope : Entity_Id;
11555      Orig_Ent    : Entity_Id);
11556   --  N is a function call or procedure statement call node and E is the
11557   --  entity of the called function, which is within the current compilation
11558   --  unit (where subunits count as part of the parent). This call checks if
11559   --  this call, or any call within any accessed body could cause an ABE, and
11560   --  if so, outputs a warning. Orig_Ent differs from E only in the case of
11561   --  renamings, and points to the original name of the entity. This is used
11562   --  for error messages. Outer_Scope is the outer level scope for the
11563   --  original call.
11564
11565   procedure Check_Internal_Call_Continue
11566     (N           : Node_Id;
11567      E           : Entity_Id;
11568      Outer_Scope : Entity_Id;
11569      Orig_Ent    : Entity_Id);
11570   --  The processing for Check_Internal_Call is divided up into two phases,
11571   --  and this represents the second phase. The second phase is delayed if
11572   --  Delaying_Elab_Checks is set to True. In this delayed case, the first
11573   --  phase makes an entry in the Delay_Check table, which is processed when
11574   --  Check_Elab_Calls is called. N, E and Orig_Ent are as for the call to
11575   --  Check_Internal_Call. Outer_Scope is the outer level scope for the
11576   --  original call.
11577
11578   function Get_Referenced_Ent (N : Node_Id) return Entity_Id;
11579   --  N is either a function or procedure call or an access attribute that
11580   --  references a subprogram. This call retrieves the relevant entity. If
11581   --  this is a call to a protected subprogram, the entity is a selected
11582   --  component. The callable entity may be absent, in which case Empty is
11583   --  returned. This happens with non-analyzed calls in nested generics.
11584   --
11585   --  If SPARK_Mode is On, then N can also be a reference to an E_Variable
11586   --  entity, in which case, the value returned is simply this entity.
11587
11588   function Has_Generic_Body (N : Node_Id) return Boolean;
11589   --  N is a generic package instantiation node, and this routine determines
11590   --  if this package spec does in fact have a generic body. If so, then
11591   --  True is returned, otherwise False. Note that this is not at all the
11592   --  same as checking if the unit requires a body, since it deals with
11593   --  the case of optional bodies accurately (i.e. if a body is optional,
11594   --  then it looks to see if a body is actually present). Note: this
11595   --  function can only do a fully correct job if in generating code mode
11596   --  where all bodies have to be present. If we are operating in semantics
11597   --  check only mode, then in some cases of optional bodies, a result of
11598   --  False may incorrectly be given. In practice this simply means that
11599   --  some cases of warnings for incorrect order of elaboration will only
11600   --  be given when generating code, which is not a big problem (and is
11601   --  inevitable, given the optional body semantics of Ada).
11602
11603   procedure Insert_Elab_Check (N : Node_Id; C : Node_Id := Empty);
11604   --  Given code for an elaboration check (or unconditional raise if the check
11605   --  is not needed), inserts the code in the appropriate place. N is the call
11606   --  or instantiation node for which the check code is required. C is the
11607   --  test whose failure triggers the raise.
11608
11609   function Is_Call_Of_Generic_Formal (N : Node_Id) return Boolean;
11610   --  Returns True if node N is a call to a generic formal subprogram
11611
11612   function Is_Finalization_Procedure (Id : Entity_Id) return Boolean;
11613   --  Determine whether entity Id denotes a [Deep_]Finalize procedure
11614
11615   procedure Output_Calls
11616     (N               : Node_Id;
11617      Check_Elab_Flag : Boolean);
11618   --  Outputs chain of calls stored in the Elab_Call table. The caller has
11619   --  already generated the main warning message, so the warnings generated
11620   --  are all continuation messages. The argument is the call node at which
11621   --  the messages are to be placed. When Check_Elab_Flag is set, calls are
11622   --  enumerated only when flag Elab_Warning is set for the dynamic case or
11623   --  when flag Elab_Info_Messages is set for the static case.
11624
11625   function Same_Elaboration_Scope (Scop1, Scop2 : Entity_Id) return Boolean;
11626   --  Given two scopes, determine whether they are the same scope from an
11627   --  elaboration point of view, i.e. packages and blocks are ignored.
11628
11629   procedure Set_C_Scope;
11630   --  On entry C_Scope is set to some scope. On return, C_Scope is reset
11631   --  to be the enclosing compilation unit of this scope.
11632
11633   procedure Set_Elaboration_Constraint
11634    (Call : Node_Id;
11635     Subp : Entity_Id;
11636     Scop : Entity_Id);
11637   --  The current unit U may depend semantically on some unit P that is not
11638   --  in the current context. If there is an elaboration call that reaches P,
11639   --  we need to indicate that P requires an Elaborate_All, but this is not
11640   --  effective in U's ali file, if there is no with_clause for P. In this
11641   --  case we add the Elaborate_All on the unit Q that directly or indirectly
11642   --  makes P available. This can happen in two cases:
11643   --
11644   --    a) Q declares a subtype of a type declared in P, and the call is an
11645   --    initialization call for an object of that subtype.
11646   --
11647   --    b) Q declares an object of some tagged type whose root type is
11648   --    declared in P, and the initialization call uses object notation on
11649   --    that object to reach a primitive operation or a classwide operation
11650   --    declared in P.
11651   --
11652   --  If P appears in the context of U, the current processing is correct.
11653   --  Otherwise we must identify these two cases to retrieve Q and place the
11654   --  Elaborate_All_Desirable on it.
11655
11656   function Spec_Entity (E : Entity_Id) return Entity_Id;
11657   --  Given a compilation unit entity, if it is a spec entity, it is returned
11658   --  unchanged. If it is a body entity, then the spec for the corresponding
11659   --  spec is returned
11660
11661   function Within (E1, E2 : Entity_Id) return Boolean;
11662   --  Given two scopes E1 and E2, returns True if E1 is equal to E2, or is one
11663   --  of its contained scopes, False otherwise.
11664
11665   function Within_Elaborate_All
11666     (Unit : Unit_Number_Type;
11667      E    : Entity_Id) return Boolean;
11668   --  Return True if we are within the scope of an Elaborate_All for E, or if
11669   --  we are within the scope of an Elaborate_All for some other unit U, and U
11670   --  with's E. This prevents spurious warnings when the called entity is
11671   --  renamed within U, or in case of generic instances.
11672
11673   --------------------------------------
11674   -- Activate_Elaborate_All_Desirable --
11675   --------------------------------------
11676
11677   procedure Activate_Elaborate_All_Desirable (N : Node_Id; U : Entity_Id) is
11678      UN  : constant Unit_Number_Type := Get_Code_Unit (N);
11679      CU  : constant Node_Id          := Cunit (UN);
11680      UE  : constant Entity_Id        := Cunit_Entity (UN);
11681      Unm : constant Unit_Name_Type   := Unit_Name (UN);
11682      CI  : constant List_Id          := Context_Items (CU);
11683      Itm : Node_Id;
11684      Ent : Entity_Id;
11685
11686      procedure Add_To_Context_And_Mark (Itm : Node_Id);
11687      --  This procedure is called when the elaborate indication must be
11688      --  applied to a unit not in the context of the referencing unit. The
11689      --  unit gets added to the context as an implicit with.
11690
11691      function In_Withs_Of (UEs : Entity_Id) return Boolean;
11692      --  UEs is the spec entity of a unit. If the unit to be marked is
11693      --  in the context item list of this unit spec, then the call returns
11694      --  True and Itm is left set to point to the relevant N_With_Clause node.
11695
11696      procedure Set_Elab_Flag (Itm : Node_Id);
11697      --  Sets Elaborate_[All_]Desirable as appropriate on Itm
11698
11699      -----------------------------
11700      -- Add_To_Context_And_Mark --
11701      -----------------------------
11702
11703      procedure Add_To_Context_And_Mark (Itm : Node_Id) is
11704         CW : constant Node_Id :=
11705                Make_With_Clause (Sloc (Itm),
11706                  Name => Name (Itm));
11707
11708      begin
11709         Set_Library_Unit  (CW, Library_Unit (Itm));
11710         Set_Implicit_With (CW);
11711
11712         --  Set elaborate all desirable on copy and then append the copy to
11713         --  the list of body with's and we are done.
11714
11715         Set_Elab_Flag (CW);
11716         Append_To (CI, CW);
11717      end Add_To_Context_And_Mark;
11718
11719      -----------------
11720      -- In_Withs_Of --
11721      -----------------
11722
11723      function In_Withs_Of (UEs : Entity_Id) return Boolean is
11724         UNs : constant Unit_Number_Type := Get_Source_Unit (UEs);
11725         CUs : constant Node_Id          := Cunit (UNs);
11726         CIs : constant List_Id          := Context_Items (CUs);
11727
11728      begin
11729         Itm := First (CIs);
11730         while Present (Itm) loop
11731            if Nkind (Itm) = N_With_Clause then
11732               Ent :=
11733                 Cunit_Entity (Get_Cunit_Unit_Number (Library_Unit (Itm)));
11734
11735               if U = Ent then
11736                  return True;
11737               end if;
11738            end if;
11739
11740            Next (Itm);
11741         end loop;
11742
11743         return False;
11744      end In_Withs_Of;
11745
11746      -------------------
11747      -- Set_Elab_Flag --
11748      -------------------
11749
11750      procedure Set_Elab_Flag (Itm : Node_Id) is
11751      begin
11752         if Nkind (N) in N_Subprogram_Instantiation then
11753            Set_Elaborate_Desirable (Itm);
11754         else
11755            Set_Elaborate_All_Desirable (Itm);
11756         end if;
11757      end Set_Elab_Flag;
11758
11759   --  Start of processing for Activate_Elaborate_All_Desirable
11760
11761   begin
11762      --  Do not set binder indication if expansion is disabled, as when
11763      --  compiling a generic unit.
11764
11765      if not Expander_Active then
11766         return;
11767      end if;
11768
11769      --  If an instance of a generic package contains a controlled object (so
11770      --  we're calling Initialize at elaboration time), and the instance is in
11771      --  a package body P that says "with P;", then we need to return without
11772      --  adding "pragma Elaborate_All (P);" to P.
11773
11774      if U = Main_Unit_Entity then
11775         return;
11776      end if;
11777
11778      Itm := First (CI);
11779      while Present (Itm) loop
11780         if Nkind (Itm) = N_With_Clause then
11781            Ent := Cunit_Entity (Get_Cunit_Unit_Number (Library_Unit (Itm)));
11782
11783            --  If we find it, then mark elaborate all desirable and return
11784
11785            if U = Ent then
11786               Set_Elab_Flag (Itm);
11787               return;
11788            end if;
11789         end if;
11790
11791         Next (Itm);
11792      end loop;
11793
11794      --  If we fall through then the with clause is not present in the
11795      --  current unit. One legitimate possibility is that the with clause
11796      --  is present in the spec when we are a body.
11797
11798      if Is_Body_Name (Unm)
11799        and then In_Withs_Of (Spec_Entity (UE))
11800      then
11801         Add_To_Context_And_Mark (Itm);
11802         return;
11803      end if;
11804
11805      --  Similarly, we may be in the spec or body of a child unit, where
11806      --  the unit in question is with'ed by some ancestor of the child unit.
11807
11808      if Is_Child_Name (Unm) then
11809         declare
11810            Pkg : Entity_Id;
11811
11812         begin
11813            Pkg := UE;
11814            loop
11815               Pkg := Scope (Pkg);
11816               exit when Pkg = Standard_Standard;
11817
11818               if In_Withs_Of (Pkg) then
11819                  Add_To_Context_And_Mark (Itm);
11820                  return;
11821               end if;
11822            end loop;
11823         end;
11824      end if;
11825
11826      --  Here if we do not find with clause on spec or body. We just ignore
11827      --  this case; it means that the elaboration involves some other unit
11828      --  than the unit being compiled, and will be caught elsewhere.
11829   end Activate_Elaborate_All_Desirable;
11830
11831   ------------------
11832   -- Check_A_Call --
11833   ------------------
11834
11835   procedure Check_A_Call
11836     (N                 : Node_Id;
11837      E                 : Entity_Id;
11838      Outer_Scope       : Entity_Id;
11839      Inter_Unit_Only   : Boolean;
11840      Generate_Warnings : Boolean := True;
11841      In_Init_Proc      : Boolean := False)
11842   is
11843      Access_Case : constant Boolean := Nkind (N) = N_Attribute_Reference;
11844      --  Indicates if we have Access attribute case
11845
11846      function Call_To_Instance_From_Outside (Id : Entity_Id) return Boolean;
11847      --  True if we're calling an instance of a generic subprogram, or a
11848      --  subprogram in an instance of a generic package, and the call is
11849      --  outside that instance.
11850
11851      procedure Elab_Warning
11852        (Msg_D : String;
11853         Msg_S : String;
11854         Ent   : Node_Or_Entity_Id);
11855       --  Generate a call to Error_Msg_NE with parameters Msg_D or Msg_S (for
11856       --  dynamic or static elaboration model), N and Ent. Msg_D is a real
11857       --  warning (output if Msg_D is non-null and Elab_Warnings is set),
11858       --  Msg_S is an info message (output if Elab_Info_Messages is set).
11859
11860      function Find_W_Scope return Entity_Id;
11861      --  Find top-level scope for called entity (not following renamings
11862      --  or derivations). This is where the Elaborate_All will go if it is
11863      --  needed. We start with the called entity, except in the case of an
11864      --  initialization procedure outside the current package, where the init
11865      --  proc is in the root package, and we start from the entity of the name
11866      --  in the call.
11867
11868      -----------------------------------
11869      -- Call_To_Instance_From_Outside --
11870      -----------------------------------
11871
11872      function Call_To_Instance_From_Outside (Id : Entity_Id) return Boolean is
11873         Scop : Entity_Id := Id;
11874
11875      begin
11876         loop
11877            if Scop = Standard_Standard then
11878               return False;
11879            end if;
11880
11881            if Is_Generic_Instance (Scop) then
11882               return not In_Open_Scopes (Scop);
11883            end if;
11884
11885            Scop := Scope (Scop);
11886         end loop;
11887      end Call_To_Instance_From_Outside;
11888
11889      ------------------
11890      -- Elab_Warning --
11891      ------------------
11892
11893      procedure Elab_Warning
11894        (Msg_D : String;
11895         Msg_S : String;
11896         Ent   : Node_Or_Entity_Id)
11897      is
11898      begin
11899         --  Dynamic elaboration checks, real warning
11900
11901         if Dynamic_Elaboration_Checks then
11902            if not Access_Case then
11903               if Msg_D /= "" and then Elab_Warnings then
11904                  Error_Msg_NE (Msg_D, N, Ent);
11905               end if;
11906
11907            --  In the access case emit first warning message as well,
11908            --  otherwise list of calls will appear as errors.
11909
11910            elsif Elab_Warnings then
11911               Error_Msg_NE (Msg_S, N, Ent);
11912            end if;
11913
11914         --  Static elaboration checks, info message
11915
11916         else
11917            if Elab_Info_Messages then
11918               Error_Msg_NE (Msg_S, N, Ent);
11919            end if;
11920         end if;
11921      end Elab_Warning;
11922
11923      ------------------
11924      -- Find_W_Scope --
11925      ------------------
11926
11927      function Find_W_Scope return Entity_Id is
11928         Refed_Ent : constant Entity_Id := Get_Referenced_Ent (N);
11929         W_Scope   : Entity_Id;
11930
11931      begin
11932         if Is_Init_Proc (Refed_Ent)
11933           and then not In_Same_Extended_Unit (N, Refed_Ent)
11934         then
11935            W_Scope := Scope (Refed_Ent);
11936         else
11937            W_Scope := E;
11938         end if;
11939
11940         --  Now loop through scopes to get to the enclosing compilation unit
11941
11942         while not Is_Compilation_Unit (W_Scope) loop
11943            W_Scope := Scope (W_Scope);
11944         end loop;
11945
11946         return W_Scope;
11947      end Find_W_Scope;
11948
11949      --  Local variables
11950
11951      Inst_Case : constant Boolean := Nkind (N) in N_Generic_Instantiation;
11952      --  Indicates if we have instantiation case
11953
11954      Loc : constant Source_Ptr := Sloc (N);
11955
11956      Variable_Case : constant Boolean :=
11957                        Nkind (N) in N_Has_Entity
11958                          and then Present (Entity (N))
11959                          and then Ekind (Entity (N)) = E_Variable;
11960      --  Indicates if we have variable reference case
11961
11962      W_Scope : constant Entity_Id := Find_W_Scope;
11963      --  Top-level scope of directly called entity for subprogram. This
11964      --  differs from E_Scope in the case where renamings or derivations
11965      --  are involved, since it does not follow these links. W_Scope is
11966      --  generally in a visible unit, and it is this scope that may require
11967      --  an Elaborate_All. However, there are some cases (initialization
11968      --  calls and calls involving object notation) where W_Scope might not
11969      --  be in the context of the current unit, and there is an intermediate
11970      --  package that is, in which case the Elaborate_All has to be placed
11971      --  on this intermediate package. These special cases are handled in
11972      --  Set_Elaboration_Constraint.
11973
11974      Ent                  : Entity_Id;
11975      Callee_Unit_Internal : Boolean;
11976      Caller_Unit_Internal : Boolean;
11977      Decl                 : Node_Id;
11978      Inst_Callee          : Source_Ptr;
11979      Inst_Caller          : Source_Ptr;
11980      Unit_Callee          : Unit_Number_Type;
11981      Unit_Caller          : Unit_Number_Type;
11982
11983      Body_Acts_As_Spec : Boolean;
11984      --  Set to true if call is to body acting as spec (no separate spec)
11985
11986      Cunit_SC : Boolean := False;
11987      --  Set to suppress dynamic elaboration checks where one of the
11988      --  enclosing scopes has Elaboration_Checks_Suppressed set, or else
11989      --  if a pragma Elaborate[_All] applies to that scope, in which case
11990      --  warnings on the scope are also suppressed. For the internal case,
11991      --  we ignore this flag.
11992
11993      E_Scope : Entity_Id;
11994      --  Top-level scope of entity for called subprogram. This value includes
11995      --  following renamings and derivations, so this scope can be in a
11996      --  non-visible unit. This is the scope that is to be investigated to
11997      --  see whether an elaboration check is required.
11998
11999      Is_DIC : Boolean;
12000      --  Flag set when the subprogram being invoked is the procedure generated
12001      --  for pragma Default_Initial_Condition.
12002
12003      SPARK_Elab_Errors : Boolean;
12004      --  Flag set when an entity is called or a variable is read during SPARK
12005      --  dynamic elaboration.
12006
12007   --  Start of processing for Check_A_Call
12008
12009   begin
12010      --  If the call is known to be within a local Suppress Elaboration
12011      --  pragma, nothing to check. This can happen in task bodies. But
12012      --  we ignore this for a call to a generic formal.
12013
12014      if Nkind (N) in N_Subprogram_Call
12015        and then No_Elaboration_Check (N)
12016        and then not Is_Call_Of_Generic_Formal (N)
12017      then
12018         return;
12019
12020      --  If this is a rewrite of a Valid_Scalars attribute, then nothing to
12021      --  check, we don't mind in this case if the call occurs before the body
12022      --  since this is all generated code.
12023
12024      elsif Nkind (Original_Node (N)) = N_Attribute_Reference
12025        and then Attribute_Name (Original_Node (N)) = Name_Valid_Scalars
12026      then
12027         return;
12028
12029      --  Intrinsics such as instances of Unchecked_Deallocation do not have
12030      --  any body, so elaboration checking is not needed, and would be wrong.
12031
12032      elsif Is_Intrinsic_Subprogram (E) then
12033         return;
12034
12035      --  Do not consider references to internal variables for SPARK semantics
12036
12037      elsif Variable_Case and then not Comes_From_Source (E) then
12038         return;
12039      end if;
12040
12041      --  Proceed with check
12042
12043      Ent := E;
12044
12045      --  For a variable reference, just set Body_Acts_As_Spec to False
12046
12047      if Variable_Case then
12048         Body_Acts_As_Spec := False;
12049
12050      --  Additional checks for all other cases
12051
12052      else
12053         --  Go to parent for derived subprogram, or to original subprogram in
12054         --  the case of a renaming (Alias covers both these cases).
12055
12056         loop
12057            if (Suppress_Elaboration_Warnings (Ent)
12058                 or else Elaboration_Checks_Suppressed (Ent))
12059              and then (Inst_Case or else No (Alias (Ent)))
12060            then
12061               return;
12062            end if;
12063
12064            --  Nothing to do for imported entities
12065
12066            if Is_Imported (Ent) then
12067               return;
12068            end if;
12069
12070            exit when Inst_Case or else No (Alias (Ent));
12071            Ent := Alias (Ent);
12072         end loop;
12073
12074         Decl := Unit_Declaration_Node (Ent);
12075
12076         if Nkind (Decl) = N_Subprogram_Body then
12077            Body_Acts_As_Spec := True;
12078
12079         elsif Nkind_In (Decl, N_Subprogram_Declaration,
12080                               N_Subprogram_Body_Stub)
12081           or else Inst_Case
12082         then
12083            Body_Acts_As_Spec := False;
12084
12085         --  If we have none of an instantiation, subprogram body or subprogram
12086         --  declaration, or in the SPARK case, a variable reference, then
12087         --  it is not a case that we want to check. (One case is a call to a
12088         --  generic formal subprogram, where we do not want the check in the
12089         --  template).
12090
12091         else
12092            return;
12093         end if;
12094      end if;
12095
12096      E_Scope := Ent;
12097      loop
12098         if Elaboration_Checks_Suppressed (E_Scope)
12099           or else Suppress_Elaboration_Warnings (E_Scope)
12100         then
12101            Cunit_SC := True;
12102         end if;
12103
12104         --  Exit when we get to compilation unit, not counting subunits
12105
12106         exit when Is_Compilation_Unit (E_Scope)
12107           and then (Is_Child_Unit (E_Scope)
12108                      or else Scope (E_Scope) = Standard_Standard);
12109
12110         pragma Assert (E_Scope /= Standard_Standard);
12111
12112         --  Move up a scope looking for compilation unit
12113
12114         E_Scope := Scope (E_Scope);
12115      end loop;
12116
12117      --  No checks needed for pure or preelaborated compilation units
12118
12119      if Is_Pure (E_Scope) or else Is_Preelaborated (E_Scope) then
12120         return;
12121      end if;
12122
12123      --  If the generic entity is within a deeper instance than we are, then
12124      --  either the instantiation to which we refer itself caused an ABE, in
12125      --  which case that will be handled separately, or else we know that the
12126      --  body we need appears as needed at the point of the instantiation.
12127      --  However, this assumption is only valid if we are in static mode.
12128
12129      if not Dynamic_Elaboration_Checks
12130        and then
12131          Instantiation_Depth (Sloc (Ent)) > Instantiation_Depth (Sloc (N))
12132      then
12133         return;
12134      end if;
12135
12136      --  Do not give a warning for a package with no body
12137
12138      if Ekind (Ent) = E_Generic_Package and then not Has_Generic_Body (N) then
12139         return;
12140      end if;
12141
12142      --  Case of entity is in same unit as call or instantiation. In the
12143      --  instantiation case, W_Scope may be different from E_Scope; we want
12144      --  the unit in which the instantiation occurs, since we're analyzing
12145      --  based on the expansion.
12146
12147      if W_Scope = C_Scope then
12148         if not Inter_Unit_Only then
12149            Check_Internal_Call (N, Ent, Outer_Scope, E);
12150         end if;
12151
12152         return;
12153      end if;
12154
12155      --  Case of entity is not in current unit (i.e. with'ed unit case)
12156
12157      --  We are only interested in such calls if the outer call was from
12158      --  elaboration code, or if we are in Dynamic_Elaboration_Checks mode.
12159
12160      if not From_Elab_Code and then not Dynamic_Elaboration_Checks then
12161         return;
12162      end if;
12163
12164      --  Nothing to do if some scope said that no checks were required
12165
12166      if Cunit_SC then
12167         return;
12168      end if;
12169
12170      --  Nothing to do for a generic instance, because a call to an instance
12171      --  cannot fail the elaboration check, because the body of the instance
12172      --  is always elaborated immediately after the spec.
12173
12174      if Call_To_Instance_From_Outside (Ent) then
12175         return;
12176      end if;
12177
12178      --  Nothing to do if subprogram with no separate spec. However, a call
12179      --  to Deep_Initialize may result in a call to a user-defined Initialize
12180      --  procedure, which imposes a body dependency. This happens only if the
12181      --  type is controlled and the Initialize procedure is not inherited.
12182
12183      if Body_Acts_As_Spec then
12184         if Is_TSS (Ent, TSS_Deep_Initialize) then
12185            declare
12186               Typ  : constant Entity_Id := Etype (First_Formal (Ent));
12187               Init : Entity_Id;
12188
12189            begin
12190               if not Is_Controlled (Typ) then
12191                  return;
12192               else
12193                  Init := Find_Prim_Op (Typ, Name_Initialize);
12194
12195                  if Comes_From_Source (Init) then
12196                     Ent := Init;
12197                  else
12198                     return;
12199                  end if;
12200               end if;
12201            end;
12202
12203         else
12204            return;
12205         end if;
12206      end if;
12207
12208      --  Check cases of internal units
12209
12210      Callee_Unit_Internal := In_Internal_Unit (E_Scope);
12211
12212      --  Do not give a warning if the with'ed unit is internal and this is
12213      --  the generic instantiation case (this saves a lot of hassle dealing
12214      --  with the Text_IO special child units)
12215
12216      if Callee_Unit_Internal and Inst_Case then
12217         return;
12218      end if;
12219
12220      if C_Scope = Standard_Standard then
12221         Caller_Unit_Internal := False;
12222      else
12223         Caller_Unit_Internal := In_Internal_Unit (C_Scope);
12224      end if;
12225
12226      --  Do not give a warning if the with'ed unit is internal and the caller
12227      --  is not internal (since the binder always elaborates internal units
12228      --  first).
12229
12230      if Callee_Unit_Internal and not Caller_Unit_Internal then
12231         return;
12232      end if;
12233
12234      --  For now, if debug flag -gnatdE is not set, do no checking for one
12235      --  internal unit withing another. This fixes the problem with the sgi
12236      --  build and storage errors. To be resolved later ???
12237
12238      if (Callee_Unit_Internal and Caller_Unit_Internal)
12239        and not Debug_Flag_EE
12240      then
12241         return;
12242      end if;
12243
12244      if Is_TSS (E, TSS_Deep_Initialize) then
12245         Ent := E;
12246      end if;
12247
12248      --  If the call is in an instance, and the called entity is not
12249      --  defined in the same instance, then the elaboration issue focuses
12250      --  around the unit containing the template, it is this unit that
12251      --  requires an Elaborate_All.
12252
12253      --  However, if we are doing dynamic elaboration, we need to chase the
12254      --  call in the usual manner.
12255
12256      --  We also need to chase the call in the usual manner if it is a call
12257      --  to a generic formal parameter, since that case was not handled as
12258      --  part of the processing of the template.
12259
12260      Inst_Caller := Instantiation (Get_Source_File_Index (Sloc (N)));
12261      Inst_Callee := Instantiation (Get_Source_File_Index (Sloc (Ent)));
12262
12263      if Inst_Caller = No_Location then
12264         Unit_Caller := No_Unit;
12265      else
12266         Unit_Caller := Get_Source_Unit (N);
12267      end if;
12268
12269      if Inst_Callee = No_Location then
12270         Unit_Callee := No_Unit;
12271      else
12272         Unit_Callee := Get_Source_Unit (Ent);
12273      end if;
12274
12275      if Unit_Caller /= No_Unit
12276        and then Unit_Callee /= Unit_Caller
12277        and then not Dynamic_Elaboration_Checks
12278        and then not Is_Call_Of_Generic_Formal (N)
12279      then
12280         E_Scope := Spec_Entity (Cunit_Entity (Unit_Caller));
12281
12282         --  If we don't get a spec entity, just ignore call. Not quite
12283         --  clear why this check is necessary. ???
12284
12285         if No (E_Scope) then
12286            return;
12287         end if;
12288
12289         --  Otherwise step to enclosing compilation unit
12290
12291         while not Is_Compilation_Unit (E_Scope) loop
12292            E_Scope := Scope (E_Scope);
12293         end loop;
12294
12295      --  For the case where N is not an instance, and is not a call within
12296      --  instance to other than a generic formal, we recompute E_Scope
12297      --  for the error message, since we do NOT want to go to the unit
12298      --  that has the ultimate declaration in the case of renaming and
12299      --  derivation and we also want to go to the generic unit in the
12300      --  case of an instance, and no further.
12301
12302      else
12303         --  Loop to carefully follow renamings and derivations one step
12304         --  outside the current unit, but not further.
12305
12306         if not (Inst_Case or Variable_Case)
12307           and then Present (Alias (Ent))
12308         then
12309            E_Scope := Alias (Ent);
12310         else
12311            E_Scope := Ent;
12312         end if;
12313
12314         loop
12315            while not Is_Compilation_Unit (E_Scope) loop
12316               E_Scope := Scope (E_Scope);
12317            end loop;
12318
12319            --  If E_Scope is the same as C_Scope, it means that there
12320            --  definitely was a local renaming or derivation, and we
12321            --  are not yet out of the current unit.
12322
12323            exit when E_Scope /= C_Scope;
12324            Ent := Alias (Ent);
12325            E_Scope := Ent;
12326
12327            --  If no alias, there could be a previous error, but not if we've
12328            --  already reached the outermost level (Standard).
12329
12330            if No (Ent) then
12331               return;
12332            end if;
12333         end loop;
12334      end if;
12335
12336      if Within_Elaborate_All (Current_Sem_Unit, E_Scope) then
12337         return;
12338      end if;
12339
12340      --  Determine whether the Default_Initial_Condition procedure of some
12341      --  type is being invoked.
12342
12343      Is_DIC := Ekind (Ent) = E_Procedure and then Is_DIC_Procedure (Ent);
12344
12345      --  Checks related to Default_Initial_Condition fall under the SPARK
12346      --  umbrella because this is a SPARK-specific annotation.
12347
12348      SPARK_Elab_Errors :=
12349        SPARK_Mode = On and (Is_DIC or Dynamic_Elaboration_Checks);
12350
12351      --  Now check if an Elaborate_All (or dynamic check) is needed
12352
12353      if (Elab_Info_Messages or Elab_Warnings or SPARK_Elab_Errors)
12354        and then Generate_Warnings
12355        and then not Suppress_Elaboration_Warnings (Ent)
12356        and then not Elaboration_Checks_Suppressed (Ent)
12357        and then not Suppress_Elaboration_Warnings (E_Scope)
12358        and then not Elaboration_Checks_Suppressed (E_Scope)
12359      then
12360         --  Instantiation case
12361
12362         if Inst_Case then
12363            if Comes_From_Source (Ent) and then SPARK_Elab_Errors then
12364               Error_Msg_NE
12365                 ("instantiation of & during elaboration in SPARK", N, Ent);
12366            else
12367               Elab_Warning
12368                 ("instantiation of & may raise Program_Error?l?",
12369                  "info: instantiation of & during elaboration?$?", Ent);
12370            end if;
12371
12372         --  Indirect call case, info message only in static elaboration
12373         --  case, because the attribute reference itself cannot raise an
12374         --  exception. Note that SPARK does not permit indirect calls.
12375
12376         elsif Access_Case then
12377            Elab_Warning ("", "info: access to & during elaboration?$?", Ent);
12378
12379         --  Variable reference in SPARK mode
12380
12381         elsif Variable_Case then
12382            if Comes_From_Source (Ent) and then SPARK_Elab_Errors then
12383               Error_Msg_NE
12384                 ("reference to & during elaboration in SPARK", N, Ent);
12385            end if;
12386
12387         --  Subprogram call case
12388
12389         else
12390            if Nkind (Name (N)) in N_Has_Entity
12391              and then Is_Init_Proc (Entity (Name (N)))
12392              and then Comes_From_Source (Ent)
12393            then
12394               Elab_Warning
12395                 ("implicit call to & may raise Program_Error?l?",
12396                  "info: implicit call to & during elaboration?$?",
12397                  Ent);
12398
12399            elsif SPARK_Elab_Errors then
12400
12401               --  Emit a specialized error message when the elaboration of an
12402               --  object of a private type evaluates the expression of pragma
12403               --  Default_Initial_Condition. This prevents the internal name
12404               --  of the procedure from appearing in the error message.
12405
12406               if Is_DIC then
12407                  Error_Msg_N
12408                    ("call to Default_Initial_Condition during elaboration in "
12409                     & "SPARK", N);
12410               else
12411                  Error_Msg_NE
12412                    ("call to & during elaboration in SPARK", N, Ent);
12413               end if;
12414
12415            else
12416               Elab_Warning
12417                 ("call to & may raise Program_Error?l?",
12418                  "info: call to & during elaboration?$?",
12419                  Ent);
12420            end if;
12421         end if;
12422
12423         Error_Msg_Qual_Level := Nat'Last;
12424
12425         --  Case of Elaborate_All not present and required, for SPARK this
12426         --  is an error, so give an error message.
12427
12428         if SPARK_Elab_Errors then
12429            Error_Msg_NE -- CODEFIX
12430              ("\Elaborate_All pragma required for&", N, W_Scope);
12431
12432         --  Otherwise we generate an implicit pragma. For a subprogram
12433         --  instantiation, Elaborate is good enough, since no transitive
12434         --  call is possible at elaboration time in this case.
12435
12436         elsif Nkind (N) in N_Subprogram_Instantiation then
12437            Elab_Warning
12438              ("\missing pragma Elaborate for&?l?",
12439               "\implicit pragma Elaborate for& generated?$?",
12440               W_Scope);
12441
12442         --  For all other cases, we need an implicit Elaborate_All
12443
12444         else
12445            Elab_Warning
12446              ("\missing pragma Elaborate_All for&?l?",
12447               "\implicit pragma Elaborate_All for & generated?$?",
12448               W_Scope);
12449         end if;
12450
12451         Error_Msg_Qual_Level := 0;
12452
12453         --  Take into account the flags related to elaboration warning
12454         --  messages when enumerating the various calls involved. This
12455         --  ensures the proper pairing of the main warning and the
12456         --  clarification messages generated by Output_Calls.
12457
12458         Output_Calls (N, Check_Elab_Flag => True);
12459
12460         --  Set flag to prevent further warnings for same unit unless in
12461         --  All_Errors_Mode.
12462
12463         if not All_Errors_Mode and not Dynamic_Elaboration_Checks then
12464            Set_Suppress_Elaboration_Warnings (W_Scope);
12465         end if;
12466      end if;
12467
12468      --  Check for runtime elaboration check required
12469
12470      if Dynamic_Elaboration_Checks then
12471         if not Elaboration_Checks_Suppressed (Ent)
12472           and then not Elaboration_Checks_Suppressed (W_Scope)
12473           and then not Elaboration_Checks_Suppressed (E_Scope)
12474           and then not Cunit_SC
12475         then
12476            --  Runtime elaboration check required. Generate check of the
12477            --  elaboration Boolean for the unit containing the entity.
12478
12479            --  Note that for this case, we do check the real unit (the one
12480            --  from following renamings, since that is the issue).
12481
12482            --  Could this possibly miss a useless but required PE???
12483
12484            Insert_Elab_Check (N,
12485              Make_Attribute_Reference (Loc,
12486                Attribute_Name => Name_Elaborated,
12487                Prefix         =>
12488                  New_Occurrence_Of (Spec_Entity (E_Scope), Loc)));
12489
12490            --  Prevent duplicate elaboration checks on the same call, which
12491            --  can happen if the body enclosing the call appears itself in a
12492            --  call whose elaboration check is delayed.
12493
12494            if Nkind (N) in N_Subprogram_Call then
12495               Set_No_Elaboration_Check (N);
12496            end if;
12497         end if;
12498
12499      --  Case of static elaboration model
12500
12501      else
12502         --  Do not do anything if elaboration checks suppressed. Note that
12503         --  we check Ent here, not E, since we want the real entity for the
12504         --  body to see if checks are suppressed for it, not the dummy
12505         --  entry for renamings or derivations.
12506
12507         if Elaboration_Checks_Suppressed (Ent)
12508           or else Elaboration_Checks_Suppressed (E_Scope)
12509           or else Elaboration_Checks_Suppressed (W_Scope)
12510         then
12511            null;
12512
12513         --  Do not generate an Elaborate_All for finalization routines
12514         --  that perform partial clean up as part of initialization.
12515
12516         elsif In_Init_Proc and then Is_Finalization_Procedure (Ent) then
12517            null;
12518
12519         --  Here we need to generate an implicit elaborate all
12520
12521         else
12522            --  Generate Elaborate_All warning unless suppressed
12523
12524            if (Elab_Info_Messages and Generate_Warnings and not Inst_Case)
12525              and then not Suppress_Elaboration_Warnings (Ent)
12526              and then not Suppress_Elaboration_Warnings (E_Scope)
12527              and then not Suppress_Elaboration_Warnings (W_Scope)
12528            then
12529               Error_Msg_Node_2 := W_Scope;
12530               Error_Msg_NE
12531                 ("info: call to& in elaboration code requires pragma "
12532                  & "Elaborate_All on&?$?", N, E);
12533            end if;
12534
12535            --  Set indication for binder to generate Elaborate_All
12536
12537            Set_Elaboration_Constraint (N, E, W_Scope);
12538         end if;
12539      end if;
12540   end Check_A_Call;
12541
12542   -----------------------------
12543   -- Check_Bad_Instantiation --
12544   -----------------------------
12545
12546   procedure Check_Bad_Instantiation (N : Node_Id) is
12547      Ent : Entity_Id;
12548
12549   begin
12550      --  Nothing to do if we do not have an instantiation (happens in some
12551      --  error cases, and also in the formal package declaration case)
12552
12553      if Nkind (N) not in N_Generic_Instantiation then
12554         return;
12555
12556      --  Nothing to do if serious errors detected (avoid cascaded errors)
12557
12558      elsif Serious_Errors_Detected /= 0 then
12559         return;
12560
12561      --  Nothing to do if not in full analysis mode
12562
12563      elsif not Full_Analysis then
12564         return;
12565
12566      --  Nothing to do if inside a generic template
12567
12568      elsif Inside_A_Generic then
12569         return;
12570
12571      --  Nothing to do if a library level instantiation
12572
12573      elsif Nkind (Parent (N)) = N_Compilation_Unit then
12574         return;
12575
12576      --  Nothing to do if we are compiling a proper body for semantic
12577      --  purposes only. The generic body may be in another proper body.
12578
12579      elsif
12580        Nkind (Parent (Unit_Declaration_Node (Main_Unit_Entity))) = N_Subunit
12581      then
12582         return;
12583      end if;
12584
12585      Ent := Get_Generic_Entity (N);
12586
12587      --  The case we are interested in is when the generic spec is in the
12588      --  current declarative part
12589
12590      if not Same_Elaboration_Scope (Current_Scope, Scope (Ent))
12591        or else not In_Same_Extended_Unit (N, Ent)
12592      then
12593         return;
12594      end if;
12595
12596      --  If the generic entity is within a deeper instance than we are, then
12597      --  either the instantiation to which we refer itself caused an ABE, in
12598      --  which case that will be handled separately. Otherwise, we know that
12599      --  the body we need appears as needed at the point of the instantiation.
12600      --  If they are both at the same level but not within the same instance
12601      --  then the body of the generic will be in the earlier instance.
12602
12603      declare
12604         D1 : constant Nat := Instantiation_Depth (Sloc (Ent));
12605         D2 : constant Nat := Instantiation_Depth (Sloc (N));
12606
12607      begin
12608         if D1 > D2 then
12609            return;
12610
12611         elsif D1 = D2
12612           and then Is_Generic_Instance (Scope (Ent))
12613           and then not In_Open_Scopes (Scope (Ent))
12614         then
12615            return;
12616         end if;
12617      end;
12618
12619      --  Now we can proceed, if the entity being called has a completion,
12620      --  then we are definitely OK, since we have already seen the body.
12621
12622      if Has_Completion (Ent) then
12623         return;
12624      end if;
12625
12626      --  If there is no body, then nothing to do
12627
12628      if not Has_Generic_Body (N) then
12629         return;
12630      end if;
12631
12632      --  Here we definitely have a bad instantiation
12633
12634      Error_Msg_Warn := SPARK_Mode /= On;
12635      Error_Msg_NE ("cannot instantiate& before body seen<<", N, Ent);
12636      Error_Msg_N ("\Program_Error [<<", N);
12637
12638      Insert_Elab_Check (N);
12639      Set_Is_Known_Guaranteed_ABE (N);
12640   end Check_Bad_Instantiation;
12641
12642   ---------------------
12643   -- Check_Elab_Call --
12644   ---------------------
12645
12646   procedure Check_Elab_Call
12647     (N            : Node_Id;
12648      Outer_Scope  : Entity_Id := Empty;
12649      In_Init_Proc : Boolean   := False)
12650   is
12651      Ent : Entity_Id;
12652      P   : Node_Id;
12653
12654   begin
12655      pragma Assert (Legacy_Elaboration_Checks);
12656
12657      --  If the reference is not in the main unit, there is nothing to check.
12658      --  Elaboration call from units in the context of the main unit will lead
12659      --  to semantic dependencies when those units are compiled.
12660
12661      if not In_Extended_Main_Code_Unit (N) then
12662         return;
12663      end if;
12664
12665      --  For an entry call, check relevant restriction
12666
12667      if Nkind (N) = N_Entry_Call_Statement
12668        and then not In_Subprogram_Or_Concurrent_Unit
12669      then
12670         Check_Restriction (No_Entry_Calls_In_Elaboration_Code, N);
12671
12672      --  Nothing to do if this is not an expected type of reference (happens
12673      --  in some error conditions, and in some cases where rewriting occurs).
12674
12675      elsif Nkind (N) not in N_Subprogram_Call
12676        and then Nkind (N) /= N_Attribute_Reference
12677        and then (SPARK_Mode /= On
12678                   or else Nkind (N) not in N_Has_Entity
12679                   or else No (Entity (N))
12680                   or else Ekind (Entity (N)) /= E_Variable)
12681      then
12682         return;
12683
12684      --  Nothing to do if this is a call already rewritten for elab checking.
12685      --  Such calls appear as the targets of If_Expressions.
12686
12687      --  This check MUST be wrong, it catches far too much
12688
12689      elsif Nkind (Parent (N)) = N_If_Expression then
12690         return;
12691
12692      --  Nothing to do if inside a generic template
12693
12694      elsif Inside_A_Generic
12695        and then No (Enclosing_Generic_Body (N))
12696      then
12697         return;
12698
12699      --  Nothing to do if call is being pre-analyzed, as when within a
12700      --  pre/postcondition, a predicate, or an invariant.
12701
12702      elsif In_Spec_Expression then
12703         return;
12704      end if;
12705
12706      --  Nothing to do if this is a call to a postcondition, which is always
12707      --  within a subprogram body, even though the current scope may be the
12708      --  enclosing scope of the subprogram.
12709
12710      if Nkind (N) = N_Procedure_Call_Statement
12711        and then Is_Entity_Name (Name (N))
12712        and then Chars (Entity (Name (N))) = Name_uPostconditions
12713      then
12714         return;
12715      end if;
12716
12717      --  Here we have a reference at elaboration time that must be checked
12718
12719      if Debug_Flag_Underscore_LL then
12720         Write_Str ("  Check_Elab_Ref: ");
12721
12722         if Nkind (N) = N_Attribute_Reference then
12723            if not Is_Entity_Name (Prefix (N)) then
12724               Write_Str ("<<not entity name>>");
12725            else
12726               Write_Name (Chars (Entity (Prefix (N))));
12727            end if;
12728
12729            Write_Str ("'Access");
12730
12731         elsif No (Name (N)) or else not Is_Entity_Name (Name (N)) then
12732            Write_Str ("<<not entity name>> ");
12733
12734         else
12735            Write_Name (Chars (Entity (Name (N))));
12736         end if;
12737
12738         Write_Str ("  reference at ");
12739         Write_Location (Sloc (N));
12740         Write_Eol;
12741      end if;
12742
12743      --  Climb up the tree to make sure we are not inside default expression
12744      --  of a parameter specification or a record component, since in both
12745      --  these cases, we will be doing the actual reference later, not now,
12746      --  and it is at the time of the actual reference (statically speaking)
12747      --  that we must do our static check, not at the time of its initial
12748      --  analysis).
12749
12750      --  However, we have to check references within component definitions
12751      --  (e.g. a function call that determines an array component bound),
12752      --  so we terminate the loop in that case.
12753
12754      P := Parent (N);
12755      while Present (P) loop
12756         if Nkind_In (P, N_Parameter_Specification,
12757                         N_Component_Declaration)
12758         then
12759            return;
12760
12761         --  The reference occurs within the constraint of a component,
12762         --  so it must be checked.
12763
12764         elsif Nkind (P) = N_Component_Definition then
12765            exit;
12766
12767         else
12768            P := Parent (P);
12769         end if;
12770      end loop;
12771
12772      --  Stuff that happens only at the outer level
12773
12774      if No (Outer_Scope) then
12775         Elab_Visited.Set_Last (0);
12776
12777         --  Nothing to do if current scope is Standard (this is a bit odd, but
12778         --  it happens in the case of generic instantiations).
12779
12780         C_Scope := Current_Scope;
12781
12782         if C_Scope = Standard_Standard then
12783            return;
12784         end if;
12785
12786         --  First case, we are in elaboration code
12787
12788         From_Elab_Code := not In_Subprogram_Or_Concurrent_Unit;
12789
12790         if From_Elab_Code then
12791
12792            --  Complain if ref that comes from source in preelaborated unit
12793            --  and we are not inside a subprogram (i.e. we are in elab code).
12794
12795            if Comes_From_Source (N)
12796              and then In_Preelaborated_Unit
12797              and then not In_Inlined_Body
12798              and then Nkind (N) /= N_Attribute_Reference
12799            then
12800               --  This is a warning in GNAT mode allowing such calls to be
12801               --  used in the predefined library with appropriate care.
12802
12803               Error_Msg_Warn := GNAT_Mode;
12804               Error_Msg_N
12805                 ("<<non-static call not allowed in preelaborated unit", N);
12806               return;
12807            end if;
12808
12809         --  Second case, we are inside a subprogram or concurrent unit, which
12810         --  means we are not in elaboration code.
12811
12812         else
12813            --  In this case, the issue is whether we are inside the
12814            --  declarative part of the unit in which we live, or inside its
12815            --  statements. In the latter case, there is no issue of ABE calls
12816            --  at this level (a call from outside to the unit in which we live
12817            --  might cause an ABE, but that will be detected when we analyze
12818            --  that outer level call, as it recurses into the called unit).
12819
12820            --  Climb up the tree, doing this test, and also testing for being
12821            --  inside a default expression, which, as discussed above, is not
12822            --  checked at this stage.
12823
12824            declare
12825               P : Node_Id;
12826               L : List_Id;
12827
12828            begin
12829               P := N;
12830               loop
12831                  --  If we find a parentless subtree, it seems safe to assume
12832                  --  that we are not in a declarative part and that no
12833                  --  checking is required.
12834
12835                  if No (P) then
12836                     return;
12837                  end if;
12838
12839                  if Is_List_Member (P) then
12840                     L := List_Containing (P);
12841                     P := Parent (L);
12842                  else
12843                     L := No_List;
12844                     P := Parent (P);
12845                  end if;
12846
12847                  exit when Nkind (P) = N_Subunit;
12848
12849                  --  Filter out case of default expressions, where we do not
12850                  --  do the check at this stage.
12851
12852                  if Nkind_In (P, N_Parameter_Specification,
12853                                  N_Component_Declaration)
12854                  then
12855                     return;
12856                  end if;
12857
12858                  --  A protected body has no elaboration code and contains
12859                  --  only other bodies.
12860
12861                  if Nkind (P) = N_Protected_Body then
12862                     return;
12863
12864                  elsif Nkind_In (P, N_Subprogram_Body,
12865                                     N_Task_Body,
12866                                     N_Block_Statement,
12867                                     N_Entry_Body)
12868                  then
12869                     if L = Declarations (P) then
12870                        exit;
12871
12872                     --  We are not in elaboration code, but we are doing
12873                     --  dynamic elaboration checks, in this case, we still
12874                     --  need to do the reference, since the subprogram we are
12875                     --  in could be called from another unit, also in dynamic
12876                     --  elaboration check mode, at elaboration time.
12877
12878                     elsif Dynamic_Elaboration_Checks then
12879
12880                        --  We provide a debug flag to disable this check. That
12881                        --  way we have an easy work around for regressions
12882                        --  that are caused by this new check. This debug flag
12883                        --  can be removed later.
12884
12885                        if Debug_Flag_DD then
12886                           return;
12887                        end if;
12888
12889                        --  Do the check in this case
12890
12891                        exit;
12892
12893                     elsif Nkind (P) = N_Task_Body then
12894
12895                        --  The check is deferred until Check_Task_Activation
12896                        --  but we need to capture local suppress pragmas
12897                        --  that may inhibit checks on this call.
12898
12899                        Ent := Get_Referenced_Ent (N);
12900
12901                        if No (Ent) then
12902                           return;
12903
12904                        elsif Elaboration_Checks_Suppressed (Current_Scope)
12905                          or else Elaboration_Checks_Suppressed (Ent)
12906                          or else Elaboration_Checks_Suppressed (Scope (Ent))
12907                        then
12908                           if Nkind (N) in N_Subprogram_Call then
12909                              Set_No_Elaboration_Check (N);
12910                           end if;
12911                        end if;
12912
12913                        return;
12914
12915                     --  Static model, call is not in elaboration code, we
12916                     --  never need to worry, because in the static model the
12917                     --  top-level caller always takes care of things.
12918
12919                     else
12920                        return;
12921                     end if;
12922                  end if;
12923               end loop;
12924            end;
12925         end if;
12926      end if;
12927
12928      Ent := Get_Referenced_Ent (N);
12929
12930      if No (Ent) then
12931         return;
12932      end if;
12933
12934      --  Determine whether a prior call to the same subprogram was already
12935      --  examined within the same context. If this is the case, then there is
12936      --  no need to proceed with the various warnings and checks because the
12937      --  work was already done for the previous call.
12938
12939      declare
12940         Self : constant Visited_Element :=
12941                  (Subp_Id => Ent, Context => Parent (N));
12942
12943      begin
12944         for Index in 1 .. Elab_Visited.Last loop
12945            if Self = Elab_Visited.Table (Index) then
12946               return;
12947            end if;
12948         end loop;
12949      end;
12950
12951      --  See if we need to analyze this reference. We analyze it if either of
12952      --  the following conditions is met:
12953
12954      --    It is an inner level call (since in this case it was triggered
12955      --    by an outer level call from elaboration code), but only if the
12956      --    call is within the scope of the original outer level call.
12957
12958      --    It is an outer level reference from elaboration code, or a call to
12959      --    an entity is in the same elaboration scope.
12960
12961      --  And in these cases, we will check both inter-unit calls and
12962      --  intra-unit (within a single unit) calls.
12963
12964      C_Scope := Current_Scope;
12965
12966      --  If not outer level reference, then we follow it if it is within the
12967      --  original scope of the outer reference.
12968
12969      if Present (Outer_Scope)
12970        and then Within (Scope (Ent), Outer_Scope)
12971      then
12972         Set_C_Scope;
12973         Check_A_Call
12974           (N               => N,
12975            E               => Ent,
12976            Outer_Scope     => Outer_Scope,
12977            Inter_Unit_Only => False,
12978            In_Init_Proc    => In_Init_Proc);
12979
12980      --  Nothing to do if elaboration checks suppressed for this scope.
12981      --  However, an interesting exception, the fact that elaboration checks
12982      --  are suppressed within an instance (because we can trace the body when
12983      --  we process the template) does not extend to calls to generic formal
12984      --  subprograms.
12985
12986      elsif Elaboration_Checks_Suppressed (Current_Scope)
12987        and then not Is_Call_Of_Generic_Formal (N)
12988      then
12989         null;
12990
12991      elsif From_Elab_Code then
12992         Set_C_Scope;
12993         Check_A_Call (N, Ent, Standard_Standard, Inter_Unit_Only => False);
12994
12995      elsif Same_Elaboration_Scope (C_Scope, Scope (Ent)) then
12996         Set_C_Scope;
12997         Check_A_Call (N, Ent, Scope (Ent), Inter_Unit_Only => False);
12998
12999      --  If none of those cases holds, but Dynamic_Elaboration_Checks mode
13000      --  is set, then we will do the check, but only in the inter-unit case
13001      --  (this is to accommodate unguarded elaboration calls from other units
13002      --  in which this same mode is set). We don't want warnings in this case,
13003      --  it would generate warnings having nothing to do with elaboration.
13004
13005      elsif Dynamic_Elaboration_Checks then
13006         Set_C_Scope;
13007         Check_A_Call
13008           (N,
13009            Ent,
13010            Standard_Standard,
13011            Inter_Unit_Only   => True,
13012            Generate_Warnings => False);
13013
13014      --  Otherwise nothing to do
13015
13016      else
13017         return;
13018      end if;
13019
13020      --  A call to an Init_Proc in elaboration code may bring additional
13021      --  dependencies, if some of the record components thereof have
13022      --  initializations that are function calls that come from source. We
13023      --  treat the current node as a call to each of these functions, to check
13024      --  their elaboration impact.
13025
13026      if Is_Init_Proc (Ent) and then From_Elab_Code then
13027         Process_Init_Proc : declare
13028            Unit_Decl : constant Node_Id := Unit_Declaration_Node (Ent);
13029
13030            function Check_Init_Call (Nod : Node_Id) return Traverse_Result;
13031            --  Find subprogram calls within body of Init_Proc for Traverse
13032            --  instantiation below.
13033
13034            procedure Traverse_Body is new Traverse_Proc (Check_Init_Call);
13035            --  Traversal procedure to find all calls with body of Init_Proc
13036
13037            ---------------------
13038            -- Check_Init_Call --
13039            ---------------------
13040
13041            function Check_Init_Call (Nod : Node_Id) return Traverse_Result is
13042               Func : Entity_Id;
13043
13044            begin
13045               if Nkind (Nod) in N_Subprogram_Call
13046                 and then Is_Entity_Name (Name (Nod))
13047               then
13048                  Func := Entity (Name (Nod));
13049
13050                  if Comes_From_Source (Func) then
13051                     Check_A_Call
13052                       (N, Func, Standard_Standard, Inter_Unit_Only => True);
13053                  end if;
13054
13055                  return OK;
13056
13057               else
13058                  return OK;
13059               end if;
13060            end Check_Init_Call;
13061
13062         --  Start of processing for Process_Init_Proc
13063
13064         begin
13065            if Nkind (Unit_Decl) = N_Subprogram_Body then
13066               Traverse_Body (Handled_Statement_Sequence (Unit_Decl));
13067            end if;
13068         end Process_Init_Proc;
13069      end if;
13070   end Check_Elab_Call;
13071
13072   -----------------------
13073   -- Check_Elab_Assign --
13074   -----------------------
13075
13076   procedure Check_Elab_Assign (N : Node_Id) is
13077      Ent  : Entity_Id;
13078      Scop : Entity_Id;
13079
13080      Pkg_Spec : Entity_Id;
13081      Pkg_Body : Entity_Id;
13082
13083   begin
13084      pragma Assert (Legacy_Elaboration_Checks);
13085
13086      --  For record or array component, check prefix. If it is an access type,
13087      --  then there is nothing to do (we do not know what is being assigned),
13088      --  but otherwise this is an assignment to the prefix.
13089
13090      if Nkind_In (N, N_Indexed_Component,
13091                      N_Selected_Component,
13092                      N_Slice)
13093      then
13094         if not Is_Access_Type (Etype (Prefix (N))) then
13095            Check_Elab_Assign (Prefix (N));
13096         end if;
13097
13098         return;
13099      end if;
13100
13101      --  For type conversion, check expression
13102
13103      if Nkind (N) = N_Type_Conversion then
13104         Check_Elab_Assign (Expression (N));
13105         return;
13106      end if;
13107
13108      --  Nothing to do if this is not an entity reference otherwise get entity
13109
13110      if Is_Entity_Name (N) then
13111         Ent := Entity (N);
13112      else
13113         return;
13114      end if;
13115
13116      --  What we are looking for is a reference in the body of a package that
13117      --  modifies a variable declared in the visible part of the package spec.
13118
13119      if Present (Ent)
13120        and then Comes_From_Source (N)
13121        and then not Suppress_Elaboration_Warnings (Ent)
13122        and then Ekind (Ent) = E_Variable
13123        and then not In_Private_Part (Ent)
13124        and then Is_Library_Level_Entity (Ent)
13125      then
13126         Scop := Current_Scope;
13127         loop
13128            if No (Scop) or else Scop = Standard_Standard then
13129               return;
13130            elsif Ekind (Scop) = E_Package
13131              and then Is_Compilation_Unit (Scop)
13132            then
13133               exit;
13134            else
13135               Scop := Scope (Scop);
13136            end if;
13137         end loop;
13138
13139         --  Here Scop points to the containing library package
13140
13141         Pkg_Spec := Scop;
13142         Pkg_Body := Body_Entity (Pkg_Spec);
13143
13144         --  All OK if the package has an Elaborate_Body pragma
13145
13146         if Has_Pragma_Elaborate_Body (Scop) then
13147            return;
13148         end if;
13149
13150         --  OK if entity being modified is not in containing package spec
13151
13152         if not In_Same_Source_Unit (Scop, Ent) then
13153            return;
13154         end if;
13155
13156         --  All OK if entity appears in generic package or generic instance.
13157         --  We just get too messed up trying to give proper warnings in the
13158         --  presence of generics. Better no message than a junk one.
13159
13160         Scop := Scope (Ent);
13161         while Present (Scop) and then Scop /= Pkg_Spec loop
13162            if Ekind (Scop) = E_Generic_Package then
13163               return;
13164            elsif Ekind (Scop) = E_Package
13165              and then Is_Generic_Instance (Scop)
13166            then
13167               return;
13168            end if;
13169
13170            Scop := Scope (Scop);
13171         end loop;
13172
13173         --  All OK if in task, don't issue warnings there
13174
13175         if In_Task_Activation then
13176            return;
13177         end if;
13178
13179         --  OK if no package body
13180
13181         if No (Pkg_Body) then
13182            return;
13183         end if;
13184
13185         --  OK if reference is not in package body
13186
13187         if not In_Same_Source_Unit (Pkg_Body, N) then
13188            return;
13189         end if;
13190
13191         --  OK if package body has no handled statement sequence
13192
13193         declare
13194            HSS : constant Node_Id :=
13195                    Handled_Statement_Sequence (Declaration_Node (Pkg_Body));
13196         begin
13197            if No (HSS) or else not Comes_From_Source (HSS) then
13198               return;
13199            end if;
13200         end;
13201
13202         --  We definitely have a case of a modification of an entity in
13203         --  the package spec from the elaboration code of the package body.
13204         --  We may not give the warning (because there are some additional
13205         --  checks to avoid too many false positives), but it would be a good
13206         --  idea for the binder to try to keep the body elaboration close to
13207         --  the spec elaboration.
13208
13209         Set_Elaborate_Body_Desirable (Pkg_Spec);
13210
13211         --  All OK in gnat mode (we know what we are doing)
13212
13213         if GNAT_Mode then
13214            return;
13215         end if;
13216
13217         --  All OK if all warnings suppressed
13218
13219         if Warning_Mode = Suppress then
13220            return;
13221         end if;
13222
13223         --  All OK if elaboration checks suppressed for entity
13224
13225         if Checks_May_Be_Suppressed (Ent)
13226           and then Is_Check_Suppressed (Ent, Elaboration_Check)
13227         then
13228            return;
13229         end if;
13230
13231         --  OK if the entity is initialized. Note that the No_Initialization
13232         --  flag usually means that the initialization has been rewritten into
13233         --  assignments, but that still counts for us.
13234
13235         declare
13236            Decl : constant Node_Id := Declaration_Node (Ent);
13237         begin
13238            if Nkind (Decl) = N_Object_Declaration
13239              and then (Present (Expression (Decl))
13240                         or else No_Initialization (Decl))
13241            then
13242               return;
13243            end if;
13244         end;
13245
13246         --  Here is where we give the warning
13247
13248         --  All OK if warnings suppressed on the entity
13249
13250         if not Has_Warnings_Off (Ent) then
13251            Error_Msg_Sloc := Sloc (Ent);
13252
13253            Error_Msg_NE
13254              ("??& can be accessed by clients before this initialization",
13255               N, Ent);
13256            Error_Msg_NE
13257              ("\??add Elaborate_Body to spec to ensure & is initialized",
13258               N, Ent);
13259         end if;
13260
13261         if not All_Errors_Mode then
13262            Set_Suppress_Elaboration_Warnings (Ent);
13263         end if;
13264      end if;
13265   end Check_Elab_Assign;
13266
13267   ----------------------
13268   -- Check_Elab_Calls --
13269   ----------------------
13270
13271   --  WARNING: This routine manages SPARK regions
13272
13273   procedure Check_Elab_Calls is
13274      Saved_SM  : SPARK_Mode_Type;
13275      Saved_SMP : Node_Id;
13276
13277   begin
13278      pragma Assert (Legacy_Elaboration_Checks);
13279
13280      --  If expansion is disabled, do not generate any checks, unless we
13281      --  are in GNATprove mode, so that errors are issued in GNATprove for
13282      --  violations of static elaboration rules in SPARK code. Also skip
13283      --  checks if any subunits are missing because in either case we lack the
13284      --  full information that we need, and no object file will be created in
13285      --  any case.
13286
13287      if (not Expander_Active and not GNATprove_Mode)
13288        or else Is_Generic_Unit (Cunit_Entity (Main_Unit))
13289        or else Subunits_Missing
13290      then
13291         return;
13292      end if;
13293
13294      --  Skip delayed calls if we had any errors
13295
13296      if Serious_Errors_Detected = 0 then
13297         Delaying_Elab_Checks := False;
13298         Expander_Mode_Save_And_Set (True);
13299
13300         for J in Delay_Check.First .. Delay_Check.Last loop
13301            Push_Scope (Delay_Check.Table (J).Curscop);
13302            From_Elab_Code := Delay_Check.Table (J).From_Elab_Code;
13303            In_Task_Activation := Delay_Check.Table (J).In_Task_Activation;
13304
13305            Saved_SM  := SPARK_Mode;
13306            Saved_SMP := SPARK_Mode_Pragma;
13307
13308            --  Set appropriate value of SPARK_Mode
13309
13310            if Delay_Check.Table (J).From_SPARK_Code then
13311               SPARK_Mode := On;
13312            end if;
13313
13314            Check_Internal_Call_Continue
13315              (N           => Delay_Check.Table (J).N,
13316               E           => Delay_Check.Table (J).E,
13317               Outer_Scope => Delay_Check.Table (J).Outer_Scope,
13318               Orig_Ent    => Delay_Check.Table (J).Orig_Ent);
13319
13320            Restore_SPARK_Mode (Saved_SM, Saved_SMP);
13321            Pop_Scope;
13322         end loop;
13323
13324         --  Set Delaying_Elab_Checks back on for next main compilation
13325
13326         Expander_Mode_Restore;
13327         Delaying_Elab_Checks := True;
13328      end if;
13329   end Check_Elab_Calls;
13330
13331   ------------------------------
13332   -- Check_Elab_Instantiation --
13333   ------------------------------
13334
13335   procedure Check_Elab_Instantiation
13336     (N           : Node_Id;
13337      Outer_Scope : Entity_Id := Empty)
13338   is
13339      Ent : Entity_Id;
13340
13341   begin
13342      pragma Assert (Legacy_Elaboration_Checks);
13343
13344      --  Check for and deal with bad instantiation case. There is some
13345      --  duplicated code here, but we will worry about this later ???
13346
13347      Check_Bad_Instantiation (N);
13348
13349      if Is_Known_Guaranteed_ABE (N) then
13350         return;
13351      end if;
13352
13353      --  Nothing to do if we do not have an instantiation (happens in some
13354      --  error cases, and also in the formal package declaration case)
13355
13356      if Nkind (N) not in N_Generic_Instantiation then
13357         return;
13358      end if;
13359
13360      --  Nothing to do if inside a generic template
13361
13362      if Inside_A_Generic then
13363         return;
13364      end if;
13365
13366      --  Nothing to do if the instantiation is not in the main unit
13367
13368      if not In_Extended_Main_Code_Unit (N) then
13369         return;
13370      end if;
13371
13372      Ent := Get_Generic_Entity (N);
13373      From_Elab_Code := not In_Subprogram_Or_Concurrent_Unit;
13374
13375      --  See if we need to analyze this instantiation. We analyze it if
13376      --  either of the following conditions is met:
13377
13378      --    It is an inner level instantiation (since in this case it was
13379      --    triggered by an outer level call from elaboration code), but
13380      --    only if the instantiation is within the scope of the original
13381      --    outer level call.
13382
13383      --    It is an outer level instantiation from elaboration code, or the
13384      --    instantiated entity is in the same elaboration scope.
13385
13386      --  And in these cases, we will check both the inter-unit case and
13387      --  the intra-unit (within a single unit) case.
13388
13389      C_Scope := Current_Scope;
13390
13391      if Present (Outer_Scope) and then Within (Scope (Ent), Outer_Scope) then
13392         Set_C_Scope;
13393         Check_A_Call (N, Ent, Outer_Scope, Inter_Unit_Only => False);
13394
13395      elsif From_Elab_Code then
13396         Set_C_Scope;
13397         Check_A_Call (N, Ent, Standard_Standard, Inter_Unit_Only => False);
13398
13399      elsif Same_Elaboration_Scope (C_Scope, Scope (Ent)) then
13400         Set_C_Scope;
13401         Check_A_Call (N, Ent, Scope (Ent), Inter_Unit_Only => False);
13402
13403      --  If none of those cases holds, but Dynamic_Elaboration_Checks mode is
13404      --  set, then we will do the check, but only in the inter-unit case (this
13405      --  is to accommodate unguarded elaboration calls from other units in
13406      --  which this same mode is set). We inhibit warnings in this case, since
13407      --  this instantiation is not occurring in elaboration code.
13408
13409      elsif Dynamic_Elaboration_Checks then
13410         Set_C_Scope;
13411         Check_A_Call
13412           (N,
13413            Ent,
13414            Standard_Standard,
13415            Inter_Unit_Only => True,
13416            Generate_Warnings => False);
13417
13418      else
13419         return;
13420      end if;
13421   end Check_Elab_Instantiation;
13422
13423   -------------------------
13424   -- Check_Internal_Call --
13425   -------------------------
13426
13427   procedure Check_Internal_Call
13428     (N           : Node_Id;
13429      E           : Entity_Id;
13430      Outer_Scope : Entity_Id;
13431      Orig_Ent    : Entity_Id)
13432   is
13433      function Within_Initial_Condition (Call : Node_Id) return Boolean;
13434      --  Determine whether call Call occurs within pragma Initial_Condition or
13435      --  pragma Check with check_kind set to Initial_Condition.
13436
13437      ------------------------------
13438      -- Within_Initial_Condition --
13439      ------------------------------
13440
13441      function Within_Initial_Condition (Call : Node_Id) return Boolean is
13442         Args : List_Id;
13443         Nam  : Name_Id;
13444         Par  : Node_Id;
13445
13446      begin
13447         --  Traverse the parent chain looking for an enclosing pragma
13448
13449         Par := Call;
13450         while Present (Par) loop
13451            if Nkind (Par) = N_Pragma then
13452               Nam := Pragma_Name (Par);
13453
13454               --  Pragma Initial_Condition appears in its alternative from as
13455               --  Check (Initial_Condition, ...).
13456
13457               if Nam = Name_Check then
13458                  Args := Pragma_Argument_Associations (Par);
13459
13460                  --  Pragma Check should have at least two arguments
13461
13462                  pragma Assert (Present (Args));
13463
13464                  return
13465                    Chars (Expression (First (Args))) = Name_Initial_Condition;
13466
13467               --  Direct match
13468
13469               elsif Nam = Name_Initial_Condition then
13470                  return True;
13471
13472               --  Since pragmas are never nested within other pragmas, stop
13473               --  the traversal.
13474
13475               else
13476                  return False;
13477               end if;
13478
13479            --  Prevent the search from going too far
13480
13481            elsif Is_Body_Or_Package_Declaration (Par) then
13482               exit;
13483            end if;
13484
13485            Par := Parent (Par);
13486
13487            --  If assertions are not enabled, the check pragma is rewritten
13488            --  as an if_statement in sem_prag, to generate various warnings
13489            --  on boolean expressions. Retrieve the original pragma.
13490
13491            if Nkind (Original_Node (Par)) = N_Pragma then
13492               Par := Original_Node (Par);
13493            end if;
13494         end loop;
13495
13496         return False;
13497      end Within_Initial_Condition;
13498
13499      --  Local variables
13500
13501      Inst_Case : constant Boolean := Nkind (N) in N_Generic_Instantiation;
13502
13503   --  Start of processing for Check_Internal_Call
13504
13505   begin
13506      --  For P'Access, we want to warn if the -gnatw.f switch is set, and the
13507      --  node comes from source.
13508
13509      if Nkind (N) = N_Attribute_Reference
13510        and then ((not Warn_On_Elab_Access and then not Debug_Flag_Dot_O)
13511                    or else not Comes_From_Source (N))
13512      then
13513         return;
13514
13515      --  If not function or procedure call, instantiation, or 'Access, then
13516      --  ignore call (this happens in some error cases and rewriting cases).
13517
13518      elsif not Nkind_In (N, N_Attribute_Reference,
13519                             N_Function_Call,
13520                             N_Procedure_Call_Statement)
13521        and then not Inst_Case
13522      then
13523         return;
13524
13525      --  Nothing to do if this is a call or instantiation that has already
13526      --  been found to be a sure ABE.
13527
13528      elsif Nkind (N) /= N_Attribute_Reference
13529        and then Is_Known_Guaranteed_ABE (N)
13530      then
13531         return;
13532
13533      --  Nothing to do if errors already detected (avoid cascaded errors)
13534
13535      elsif Serious_Errors_Detected /= 0 then
13536         return;
13537
13538      --  Nothing to do if not in full analysis mode
13539
13540      elsif not Full_Analysis then
13541         return;
13542
13543      --  Nothing to do if analyzing in special spec-expression mode, since the
13544      --  call is not actually being made at this time.
13545
13546      elsif In_Spec_Expression then
13547         return;
13548
13549      --  Nothing to do for call to intrinsic subprogram
13550
13551      elsif Is_Intrinsic_Subprogram (E) then
13552         return;
13553
13554      --  Nothing to do if call is within a generic unit
13555
13556      elsif Inside_A_Generic then
13557         return;
13558
13559      --  Nothing to do when the call appears within pragma Initial_Condition.
13560      --  The pragma is part of the elaboration statements of a package body
13561      --  and may only call external subprograms or subprograms whose body is
13562      --  already available.
13563
13564      elsif Within_Initial_Condition (N) then
13565         return;
13566      end if;
13567
13568      --  Delay this call if we are still delaying calls
13569
13570      if Delaying_Elab_Checks then
13571         Delay_Check.Append
13572           ((N                  => N,
13573             E                  => E,
13574             Orig_Ent           => Orig_Ent,
13575             Curscop            => Current_Scope,
13576             Outer_Scope        => Outer_Scope,
13577             From_Elab_Code     => From_Elab_Code,
13578             In_Task_Activation => In_Task_Activation,
13579             From_SPARK_Code    => SPARK_Mode = On));
13580         return;
13581
13582      --  Otherwise, call phase 2 continuation right now
13583
13584      else
13585         Check_Internal_Call_Continue (N, E, Outer_Scope, Orig_Ent);
13586      end if;
13587   end Check_Internal_Call;
13588
13589   ----------------------------------
13590   -- Check_Internal_Call_Continue --
13591   ----------------------------------
13592
13593   procedure Check_Internal_Call_Continue
13594     (N           : Node_Id;
13595      E           : Entity_Id;
13596      Outer_Scope : Entity_Id;
13597      Orig_Ent    : Entity_Id)
13598   is
13599      function Find_Elab_Reference (N : Node_Id) return Traverse_Result;
13600      --  Function applied to each node as we traverse the body. Checks for
13601      --  call or entity reference that needs checking, and if so checks it.
13602      --  Always returns OK, so entire tree is traversed, except that as
13603      --  described below subprogram bodies are skipped for now.
13604
13605      procedure Traverse is new Atree.Traverse_Proc (Find_Elab_Reference);
13606      --  Traverse procedure using above Find_Elab_Reference function
13607
13608      -------------------------
13609      -- Find_Elab_Reference --
13610      -------------------------
13611
13612      function Find_Elab_Reference (N : Node_Id) return Traverse_Result is
13613         Actual : Node_Id;
13614
13615      begin
13616         --  If user has specified that there are no entry calls in elaboration
13617         --  code, do not trace past an accept statement, because the rendez-
13618         --  vous will happen after elaboration.
13619
13620         if Nkind_In (Original_Node (N), N_Accept_Statement,
13621                                         N_Selective_Accept)
13622           and then Restriction_Active (No_Entry_Calls_In_Elaboration_Code)
13623         then
13624            return Abandon;
13625
13626         --  If we have a function call, check it
13627
13628         elsif Nkind (N) = N_Function_Call then
13629            Check_Elab_Call (N, Outer_Scope);
13630            return OK;
13631
13632         --  If we have a procedure call, check the call, and also check
13633         --  arguments that are assignments (OUT or IN OUT mode formals).
13634
13635         elsif Nkind (N) = N_Procedure_Call_Statement then
13636            Check_Elab_Call (N, Outer_Scope, In_Init_Proc => Is_Init_Proc (E));
13637
13638            Actual := First_Actual (N);
13639            while Present (Actual) loop
13640               if Known_To_Be_Assigned (Actual) then
13641                  Check_Elab_Assign (Actual);
13642               end if;
13643
13644               Next_Actual (Actual);
13645            end loop;
13646
13647            return OK;
13648
13649         --  If we have an access attribute for a subprogram, check it.
13650         --  Suppress this behavior under debug flag.
13651
13652         elsif not Debug_Flag_Dot_UU
13653           and then Nkind (N) = N_Attribute_Reference
13654           and then Nam_In (Attribute_Name (N), Name_Access,
13655                                                Name_Unrestricted_Access)
13656           and then Is_Entity_Name (Prefix (N))
13657           and then Is_Subprogram (Entity (Prefix (N)))
13658         then
13659            Check_Elab_Call (N, Outer_Scope);
13660            return OK;
13661
13662         --  In SPARK mode, if we have an entity reference to a variable, then
13663         --  check it. For now we consider any reference.
13664
13665         elsif SPARK_Mode = On
13666           and then Nkind (N) in N_Has_Entity
13667           and then Present (Entity (N))
13668           and then Ekind (Entity (N)) = E_Variable
13669         then
13670            Check_Elab_Call (N, Outer_Scope);
13671            return OK;
13672
13673         --  If we have a generic instantiation, check it
13674
13675         elsif Nkind (N) in N_Generic_Instantiation then
13676            Check_Elab_Instantiation (N, Outer_Scope);
13677            return OK;
13678
13679         --  Skip subprogram bodies that come from source (wait for call to
13680         --  analyze these). The reason for the come from source test is to
13681         --  avoid catching task bodies.
13682
13683         --  For task bodies, we should really avoid these too, waiting for the
13684         --  task activation, but that's too much trouble to catch for now, so
13685         --  we go in unconditionally. This is not so terrible, it means the
13686         --  error backtrace is not quite complete, and we are too eager to
13687         --  scan bodies of tasks that are unused, but this is hardly very
13688         --  significant.
13689
13690         elsif Nkind (N) = N_Subprogram_Body
13691           and then Comes_From_Source (N)
13692         then
13693            return Skip;
13694
13695         elsif Nkind (N) = N_Assignment_Statement
13696           and then Comes_From_Source (N)
13697         then
13698            Check_Elab_Assign (Name (N));
13699            return OK;
13700
13701         else
13702            return OK;
13703         end if;
13704      end Find_Elab_Reference;
13705
13706      Inst_Case : constant Boolean    := Is_Generic_Unit (E);
13707      Loc       : constant Source_Ptr := Sloc (N);
13708
13709      Ebody : Entity_Id;
13710      Sbody : Node_Id;
13711
13712   --  Start of processing for Check_Internal_Call_Continue
13713
13714   begin
13715      --  Save outer level call if at outer level
13716
13717      if Elab_Call.Last = 0 then
13718         Outer_Level_Sloc := Loc;
13719      end if;
13720
13721      --  If the call is to a function that renames a literal, no check needed
13722
13723      if Ekind (E) = E_Enumeration_Literal then
13724         return;
13725      end if;
13726
13727      --  Register the subprogram as examined within this particular context.
13728      --  This ensures that calls to the same subprogram but in different
13729      --  contexts receive warnings and checks of their own since the calls
13730      --  may be reached through different flow paths.
13731
13732      Elab_Visited.Append ((Subp_Id => E, Context => Parent (N)));
13733
13734      Sbody := Unit_Declaration_Node (E);
13735
13736      if not Nkind_In (Sbody, N_Subprogram_Body, N_Package_Body) then
13737         Ebody := Corresponding_Body (Sbody);
13738
13739         if No (Ebody) then
13740            return;
13741         else
13742            Sbody := Unit_Declaration_Node (Ebody);
13743         end if;
13744      end if;
13745
13746      --  If the body appears after the outer level call or instantiation then
13747      --  we have an error case handled below.
13748
13749      if Earlier_In_Extended_Unit (Outer_Level_Sloc, Sloc (Sbody))
13750        and then not In_Task_Activation
13751      then
13752         null;
13753
13754      --  If we have the instantiation case we are done, since we now know that
13755      --  the body of the generic appeared earlier.
13756
13757      elsif Inst_Case then
13758         return;
13759
13760      --  Otherwise we have a call, so we trace through the called body to see
13761      --  if it has any problems.
13762
13763      else
13764         pragma Assert (Nkind (Sbody) = N_Subprogram_Body);
13765
13766         Elab_Call.Append ((Cloc => Loc, Ent => E));
13767
13768         if Debug_Flag_Underscore_LL then
13769            Write_Str ("Elab_Call.Last = ");
13770            Write_Int (Int (Elab_Call.Last));
13771            Write_Str ("   Ent = ");
13772            Write_Name (Chars (E));
13773            Write_Str ("   at ");
13774            Write_Location (Sloc (N));
13775            Write_Eol;
13776         end if;
13777
13778         --  Now traverse declarations and statements of subprogram body. Note
13779         --  that we cannot simply Traverse (Sbody), since traverse does not
13780         --  normally visit subprogram bodies.
13781
13782         declare
13783            Decl : Node_Id;
13784         begin
13785            Decl := First (Declarations (Sbody));
13786            while Present (Decl) loop
13787               Traverse (Decl);
13788               Next (Decl);
13789            end loop;
13790         end;
13791
13792         Traverse (Handled_Statement_Sequence (Sbody));
13793
13794         Elab_Call.Decrement_Last;
13795         return;
13796      end if;
13797
13798      --  Here is the case of calling a subprogram where the body has not yet
13799      --  been encountered. A warning message is needed, except if this is the
13800      --  case of appearing within an aspect specification that results in
13801      --  a check call, we do not really have such a situation, so no warning
13802      --  is needed (e.g. the case of a precondition, where the call appears
13803      --  textually before the body, but in actual fact is moved to the
13804      --  appropriate subprogram body and so does not need a check).
13805
13806      declare
13807         P : Node_Id;
13808         O : Node_Id;
13809
13810      begin
13811         P := Parent (N);
13812         loop
13813            --  Keep looking at parents if we are still in the subexpression
13814
13815            if Nkind (P) in N_Subexpr then
13816               P := Parent (P);
13817
13818            --  Here P is the parent of the expression, check for special case
13819
13820            else
13821               O := Original_Node (P);
13822
13823               --  Definitely not the special case if orig node is not a pragma
13824
13825               exit when Nkind (O) /= N_Pragma;
13826
13827               --  Check we have an If statement or a null statement (happens
13828               --  when the If has been expanded to be True).
13829
13830               exit when not Nkind_In (P, N_If_Statement, N_Null_Statement);
13831
13832               --  Our special case will be indicated either by the pragma
13833               --  coming from an aspect ...
13834
13835               if Present (Corresponding_Aspect (O)) then
13836                  return;
13837
13838               --  Or, in the case of an initial condition, specifically by a
13839               --  Check pragma specifying an Initial_Condition check.
13840
13841               elsif Pragma_Name (O) = Name_Check
13842                 and then
13843                   Chars
13844                     (Expression (First (Pragma_Argument_Associations (O)))) =
13845                                                       Name_Initial_Condition
13846               then
13847                  return;
13848
13849               --  For anything else, we have an error
13850
13851               else
13852                  exit;
13853               end if;
13854            end if;
13855         end loop;
13856      end;
13857
13858      --  Not that special case, warning and dynamic check is required
13859
13860      --  If we have nothing in the call stack, then this is at the outer
13861      --  level, and the ABE is bound to occur, unless it's a 'Access, or
13862      --  it's a renaming.
13863
13864      if Elab_Call.Last = 0 then
13865         Error_Msg_Warn := SPARK_Mode /= On;
13866
13867         declare
13868            Insert_Check : Boolean := True;
13869            --  This flag is set to True if an elaboration check should be
13870            --  inserted.
13871
13872         begin
13873            if In_Task_Activation then
13874               Insert_Check := False;
13875
13876            elsif Inst_Case then
13877               Error_Msg_NE
13878                 ("cannot instantiate& before body seen<<", N, Orig_Ent);
13879
13880            elsif Nkind (N) = N_Attribute_Reference then
13881               Error_Msg_NE
13882                 ("Access attribute of & before body seen<<", N, Orig_Ent);
13883               Error_Msg_N ("\possible Program_Error on later references<", N);
13884               Insert_Check := False;
13885
13886            elsif Nkind (Unit_Declaration_Node (Orig_Ent)) /=
13887                    N_Subprogram_Renaming_Declaration
13888            then
13889               Error_Msg_NE
13890                 ("cannot call& before body seen<<", N, Orig_Ent);
13891
13892            elsif not Is_Generic_Actual_Subprogram (Orig_Ent) then
13893               Insert_Check := False;
13894            end if;
13895
13896            if Insert_Check then
13897               Error_Msg_N ("\Program_Error [<<", N);
13898               Insert_Elab_Check (N);
13899            end if;
13900         end;
13901
13902      --  Call is not at outer level
13903
13904      else
13905         --  Do not generate elaboration checks in GNATprove mode because the
13906         --  elaboration counter and the check are both forms of expansion.
13907
13908         if GNATprove_Mode then
13909            null;
13910
13911         --  Generate an elaboration check
13912
13913         elsif not Elaboration_Checks_Suppressed (E) then
13914            Set_Elaboration_Entity_Required (E);
13915
13916            --  Create a declaration of the elaboration entity, and insert it
13917            --  prior to the subprogram or the generic unit, within the same
13918            --  scope. Since the subprogram may be overloaded, create a unique
13919            --  entity.
13920
13921            if No (Elaboration_Entity (E)) then
13922               declare
13923                  Loce : constant Source_Ptr := Sloc (E);
13924                  Ent  : constant Entity_Id  :=
13925                           Make_Defining_Identifier (Loc,
13926                             New_External_Name (Chars (E), 'E', -1));
13927
13928               begin
13929                  Set_Elaboration_Entity (E, Ent);
13930                  Push_Scope (Scope (E));
13931
13932                  Insert_Action (Declaration_Node (E),
13933                    Make_Object_Declaration (Loce,
13934                      Defining_Identifier => Ent,
13935                      Object_Definition   =>
13936                        New_Occurrence_Of (Standard_Short_Integer, Loce),
13937                      Expression          =>
13938                        Make_Integer_Literal (Loc, Uint_0)));
13939
13940                  --  Set elaboration flag at the point of the body
13941
13942                  Set_Elaboration_Flag (Sbody, E);
13943
13944                  --  Kill current value indication. This is necessary because
13945                  --  the tests of this flag are inserted out of sequence and
13946                  --  must not pick up bogus indications of the wrong constant
13947                  --  value. Also, this is never a true constant, since one way
13948                  --  or another, it gets reset.
13949
13950                  Set_Current_Value    (Ent, Empty);
13951                  Set_Last_Assignment  (Ent, Empty);
13952                  Set_Is_True_Constant (Ent, False);
13953                  Pop_Scope;
13954               end;
13955            end if;
13956
13957            --  Generate:
13958            --    if Enn = 0 then
13959            --       raise Program_Error with "access before elaboration";
13960            --    end if;
13961
13962            Insert_Elab_Check (N,
13963              Make_Attribute_Reference (Loc,
13964                Attribute_Name => Name_Elaborated,
13965                Prefix         => New_Occurrence_Of (E, Loc)));
13966         end if;
13967
13968         --  Generate the warning
13969
13970         if not Suppress_Elaboration_Warnings (E)
13971           and then not Elaboration_Checks_Suppressed (E)
13972
13973           --  Suppress this warning if we have a function call that occurred
13974           --  within an assertion expression, since we can get false warnings
13975           --  in this case, due to the out of order handling in this case.
13976
13977           and then
13978             (Nkind (Original_Node (N)) /= N_Function_Call
13979               or else not In_Assertion_Expression_Pragma (Original_Node (N)))
13980         then
13981            Error_Msg_Warn := SPARK_Mode /= On;
13982
13983            if Inst_Case then
13984               Error_Msg_NE
13985                 ("instantiation of& may occur before body is seen<l<",
13986                  N, Orig_Ent);
13987            else
13988               --  A rather specific check. For Finalize/Adjust/Initialize, if
13989               --  the type has Warnings_Off set, suppress the warning.
13990
13991               if Nam_In (Chars (E), Name_Adjust,
13992                                     Name_Finalize,
13993                                     Name_Initialize)
13994                 and then Present (First_Formal (E))
13995               then
13996                  declare
13997                     T : constant Entity_Id := Etype (First_Formal (E));
13998                  begin
13999                     if Is_Controlled (T) then
14000                        if Warnings_Off (T)
14001                          or else (Ekind (T) = E_Private_Type
14002                                    and then Warnings_Off (Full_View (T)))
14003                        then
14004                           goto Output;
14005                        end if;
14006                     end if;
14007                  end;
14008               end if;
14009
14010               --  Go ahead and give warning if not this special case
14011
14012               Error_Msg_NE
14013                 ("call to& may occur before body is seen<l<", N, Orig_Ent);
14014            end if;
14015
14016            Error_Msg_N ("\Program_Error ]<l<", N);
14017
14018            --  There is no need to query the elaboration warning message flags
14019            --  because the main message is an error, not a warning, therefore
14020            --  all the clarification messages produces by Output_Calls must be
14021            --  emitted unconditionally.
14022
14023            <<Output>>
14024
14025            Output_Calls (N, Check_Elab_Flag => False);
14026         end if;
14027      end if;
14028   end Check_Internal_Call_Continue;
14029
14030   ---------------------------
14031   -- Check_Task_Activation --
14032   ---------------------------
14033
14034   procedure Check_Task_Activation (N : Node_Id) is
14035      Loc         : constant Source_Ptr := Sloc (N);
14036      Inter_Procs : constant Elist_Id   := New_Elmt_List;
14037      Intra_Procs : constant Elist_Id   := New_Elmt_List;
14038      Ent         : Entity_Id;
14039      P           : Entity_Id;
14040      Task_Scope  : Entity_Id;
14041      Cunit_SC    : Boolean := False;
14042      Decl        : Node_Id;
14043      Elmt        : Elmt_Id;
14044      Enclosing   : Entity_Id;
14045
14046      procedure Add_Task_Proc (Typ : Entity_Id);
14047      --  Add to Task_Procs the task body procedure(s) of task types in Typ.
14048      --  For record types, this procedure recurses over component types.
14049
14050      procedure Collect_Tasks (Decls : List_Id);
14051      --  Collect the types of the tasks that are to be activated in the given
14052      --  list of declarations, in order to perform elaboration checks on the
14053      --  corresponding task procedures that are called implicitly here.
14054
14055      function Outer_Unit (E : Entity_Id) return Entity_Id;
14056      --  find enclosing compilation unit of Entity, ignoring subunits, or
14057      --  else enclosing subprogram. If E is not a package, there is no need
14058      --  for inter-unit elaboration checks.
14059
14060      -------------------
14061      -- Add_Task_Proc --
14062      -------------------
14063
14064      procedure Add_Task_Proc (Typ : Entity_Id) is
14065         Comp : Entity_Id;
14066         Proc : Entity_Id := Empty;
14067
14068      begin
14069         if Is_Task_Type (Typ) then
14070            Proc := Get_Task_Body_Procedure (Typ);
14071
14072         elsif Is_Array_Type (Typ)
14073           and then Has_Task (Base_Type (Typ))
14074         then
14075            Add_Task_Proc (Component_Type (Typ));
14076
14077         elsif Is_Record_Type (Typ)
14078           and then Has_Task (Base_Type (Typ))
14079         then
14080            Comp := First_Component (Typ);
14081            while Present (Comp) loop
14082               Add_Task_Proc (Etype (Comp));
14083               Comp := Next_Component (Comp);
14084            end loop;
14085         end if;
14086
14087         --  If the task type is another unit, we will perform the usual
14088         --  elaboration check on its enclosing unit. If the type is in the
14089         --  same unit, we can trace the task body as for an internal call,
14090         --  but we only need to examine other external calls, because at
14091         --  the point the task is activated, internal subprogram bodies
14092         --  will have been elaborated already. We keep separate lists for
14093         --  each kind of task.
14094
14095         --  Skip this test if errors have occurred, since in this case
14096         --  we can get false indications.
14097
14098         if Serious_Errors_Detected /= 0 then
14099            return;
14100         end if;
14101
14102         if Present (Proc) then
14103            if Outer_Unit (Scope (Proc)) = Enclosing then
14104
14105               if No (Corresponding_Body (Unit_Declaration_Node (Proc)))
14106                 and then
14107                   (not Is_Generic_Instance (Scope (Proc))
14108                     or else Scope (Proc) = Scope (Defining_Identifier (Decl)))
14109               then
14110                  Error_Msg_Warn := SPARK_Mode /= On;
14111                  Error_Msg_N
14112                    ("task will be activated before elaboration of its body<<",
14113                      Decl);
14114                  Error_Msg_N ("\Program_Error [<<", Decl);
14115
14116               elsif Present
14117                       (Corresponding_Body (Unit_Declaration_Node (Proc)))
14118               then
14119                  Append_Elmt (Proc, Intra_Procs);
14120               end if;
14121
14122            else
14123               --  No need for multiple entries of the same type
14124
14125               Elmt := First_Elmt (Inter_Procs);
14126               while Present (Elmt) loop
14127                  if Node (Elmt) = Proc then
14128                     return;
14129                  end if;
14130
14131                  Next_Elmt (Elmt);
14132               end loop;
14133
14134               Append_Elmt (Proc, Inter_Procs);
14135            end if;
14136         end if;
14137      end Add_Task_Proc;
14138
14139      -------------------
14140      -- Collect_Tasks --
14141      -------------------
14142
14143      procedure Collect_Tasks (Decls : List_Id) is
14144      begin
14145         if Present (Decls) then
14146            Decl := First (Decls);
14147            while Present (Decl) loop
14148               if Nkind (Decl) = N_Object_Declaration
14149                 and then Has_Task (Etype (Defining_Identifier (Decl)))
14150               then
14151                  Add_Task_Proc (Etype (Defining_Identifier (Decl)));
14152               end if;
14153
14154               Next (Decl);
14155            end loop;
14156         end if;
14157      end Collect_Tasks;
14158
14159      ----------------
14160      -- Outer_Unit --
14161      ----------------
14162
14163      function Outer_Unit (E : Entity_Id) return Entity_Id is
14164         Outer : Entity_Id;
14165
14166      begin
14167         Outer := E;
14168         while Present (Outer) loop
14169            if Elaboration_Checks_Suppressed (Outer) then
14170               Cunit_SC := True;
14171            end if;
14172
14173            exit when Is_Child_Unit (Outer)
14174              or else Scope (Outer) = Standard_Standard
14175              or else Ekind (Outer) /= E_Package;
14176            Outer := Scope (Outer);
14177         end loop;
14178
14179         return Outer;
14180      end Outer_Unit;
14181
14182   --  Start of processing for Check_Task_Activation
14183
14184   begin
14185      pragma Assert (Legacy_Elaboration_Checks);
14186
14187      Enclosing := Outer_Unit (Current_Scope);
14188
14189      --  Find all tasks declared in the current unit
14190
14191      if Nkind (N) = N_Package_Body then
14192         P := Unit_Declaration_Node (Corresponding_Spec (N));
14193
14194         Collect_Tasks (Declarations (N));
14195         Collect_Tasks (Visible_Declarations (Specification (P)));
14196         Collect_Tasks (Private_Declarations (Specification (P)));
14197
14198      elsif Nkind (N) = N_Package_Declaration then
14199         Collect_Tasks (Visible_Declarations (Specification (N)));
14200         Collect_Tasks (Private_Declarations (Specification (N)));
14201
14202      else
14203         Collect_Tasks (Declarations (N));
14204      end if;
14205
14206      --  We only perform detailed checks in all tasks that are library level
14207      --  entities. If the master is a subprogram or task, activation will
14208      --  depend on the activation of the master itself.
14209
14210      --  Should dynamic checks be added in the more general case???
14211
14212      if Ekind (Enclosing) /= E_Package then
14213         return;
14214      end if;
14215
14216      --  For task types defined in other units, we want the unit containing
14217      --  the task body to be elaborated before the current one.
14218
14219      Elmt := First_Elmt (Inter_Procs);
14220      while Present (Elmt) loop
14221         Ent := Node (Elmt);
14222         Task_Scope := Outer_Unit (Scope (Ent));
14223
14224         if not Is_Compilation_Unit (Task_Scope) then
14225            null;
14226
14227         elsif Suppress_Elaboration_Warnings (Task_Scope)
14228           or else Elaboration_Checks_Suppressed (Task_Scope)
14229         then
14230            null;
14231
14232         elsif Dynamic_Elaboration_Checks then
14233            if not Elaboration_Checks_Suppressed (Ent)
14234              and then not Cunit_SC
14235              and then not Restriction_Active
14236                             (No_Entry_Calls_In_Elaboration_Code)
14237            then
14238               --  Runtime elaboration check required. Generate check of the
14239               --  elaboration counter for the unit containing the entity.
14240
14241               Insert_Elab_Check (N,
14242                 Make_Attribute_Reference (Loc,
14243                   Prefix         =>
14244                     New_Occurrence_Of (Spec_Entity (Task_Scope), Loc),
14245                   Attribute_Name => Name_Elaborated));
14246            end if;
14247
14248         else
14249            --  Force the binder to elaborate other unit first
14250
14251            if Elab_Info_Messages
14252              and then not Suppress_Elaboration_Warnings (Ent)
14253              and then not Elaboration_Checks_Suppressed (Ent)
14254              and then not Suppress_Elaboration_Warnings (Task_Scope)
14255              and then not Elaboration_Checks_Suppressed (Task_Scope)
14256            then
14257               Error_Msg_Node_2 := Task_Scope;
14258               Error_Msg_NE
14259                 ("info: activation of an instance of task type & requires "
14260                  & "pragma Elaborate_All on &?$?", N, Ent);
14261            end if;
14262
14263            Activate_Elaborate_All_Desirable (N, Task_Scope);
14264            Set_Suppress_Elaboration_Warnings (Task_Scope);
14265         end if;
14266
14267         Next_Elmt (Elmt);
14268      end loop;
14269
14270      --  For tasks declared in the current unit, trace other calls within the
14271      --  task procedure bodies, which are available.
14272
14273      if not Debug_Flag_Dot_Y then
14274         In_Task_Activation := True;
14275
14276         Elmt := First_Elmt (Intra_Procs);
14277         while Present (Elmt) loop
14278            Ent := Node (Elmt);
14279            Check_Internal_Call_Continue (N, Ent, Enclosing, Ent);
14280            Next_Elmt (Elmt);
14281         end loop;
14282
14283         In_Task_Activation := False;
14284      end if;
14285   end Check_Task_Activation;
14286
14287   ------------------------
14288   -- Get_Referenced_Ent --
14289   ------------------------
14290
14291   function Get_Referenced_Ent (N : Node_Id) return Entity_Id is
14292      Nam : Node_Id;
14293
14294   begin
14295      if Nkind (N) in N_Has_Entity
14296        and then Present (Entity (N))
14297        and then Ekind (Entity (N)) = E_Variable
14298      then
14299         return Entity (N);
14300      end if;
14301
14302      if Nkind (N) = N_Attribute_Reference then
14303         Nam := Prefix (N);
14304      else
14305         Nam := Name (N);
14306      end if;
14307
14308      if No (Nam) then
14309         return Empty;
14310      elsif Nkind (Nam) = N_Selected_Component then
14311         return Entity (Selector_Name (Nam));
14312      elsif not Is_Entity_Name (Nam) then
14313         return Empty;
14314      else
14315         return Entity (Nam);
14316      end if;
14317   end Get_Referenced_Ent;
14318
14319   ----------------------
14320   -- Has_Generic_Body --
14321   ----------------------
14322
14323   function Has_Generic_Body (N : Node_Id) return Boolean is
14324      Ent  : constant Entity_Id := Get_Generic_Entity (N);
14325      Decl : constant Node_Id   := Unit_Declaration_Node (Ent);
14326      Scop : Entity_Id;
14327
14328      function Find_Body_In (E : Entity_Id; N : Node_Id) return Node_Id;
14329      --  Determine if the list of nodes headed by N and linked by Next
14330      --  contains a package body for the package spec entity E, and if so
14331      --  return the package body. If not, then returns Empty.
14332
14333      function Load_Package_Body (Nam : Unit_Name_Type) return Node_Id;
14334      --  This procedure is called load the unit whose name is given by Nam.
14335      --  This unit is being loaded to see whether it contains an optional
14336      --  generic body. The returned value is the loaded unit, which is always
14337      --  a package body (only package bodies can contain other entities in the
14338      --  sense in which Has_Generic_Body is interested). We only attempt to
14339      --  load bodies if we are generating code. If we are in semantics check
14340      --  only mode, then it would be wrong to load bodies that are not
14341      --  required from a semantic point of view, so in this case we return
14342      --  Empty. The result is that the caller may incorrectly decide that a
14343      --  generic spec does not have a body when in fact it does, but the only
14344      --  harm in this is that some warnings on elaboration problems may be
14345      --  lost in semantic checks only mode, which is not big loss. We also
14346      --  return Empty if we go for a body and it is not there.
14347
14348      function Locate_Corresponding_Body (PE : Entity_Id) return Node_Id;
14349      --  PE is the entity for a package spec. This function locates the
14350      --  corresponding package body, returning Empty if none is found. The
14351      --  package body returned is fully parsed but may not yet be analyzed,
14352      --  so only syntactic fields should be referenced.
14353
14354      ------------------
14355      -- Find_Body_In --
14356      ------------------
14357
14358      function Find_Body_In (E : Entity_Id; N : Node_Id) return Node_Id is
14359         Nod : Node_Id;
14360
14361      begin
14362         Nod := N;
14363         while Present (Nod) loop
14364
14365            --  If we found the package body we are looking for, return it
14366
14367            if Nkind (Nod) = N_Package_Body
14368              and then Chars (Defining_Unit_Name (Nod)) = Chars (E)
14369            then
14370               return Nod;
14371
14372            --  If we found the stub for the body, go after the subunit,
14373            --  loading it if necessary.
14374
14375            elsif Nkind (Nod) = N_Package_Body_Stub
14376              and then Chars (Defining_Identifier (Nod)) = Chars (E)
14377            then
14378               if Present (Library_Unit (Nod)) then
14379                  return Unit (Library_Unit (Nod));
14380
14381               else
14382                  return Load_Package_Body (Get_Unit_Name (Nod));
14383               end if;
14384
14385            --  If neither package body nor stub, keep looking on chain
14386
14387            else
14388               Next (Nod);
14389            end if;
14390         end loop;
14391
14392         return Empty;
14393      end Find_Body_In;
14394
14395      -----------------------
14396      -- Load_Package_Body --
14397      -----------------------
14398
14399      function Load_Package_Body (Nam : Unit_Name_Type) return Node_Id is
14400         U : Unit_Number_Type;
14401
14402      begin
14403         if Operating_Mode /= Generate_Code then
14404            return Empty;
14405         else
14406            U :=
14407              Load_Unit
14408                (Load_Name  => Nam,
14409                 Required   => False,
14410                 Subunit    => False,
14411                 Error_Node => N);
14412
14413            if U = No_Unit then
14414               return Empty;
14415            else
14416               return Unit (Cunit (U));
14417            end if;
14418         end if;
14419      end Load_Package_Body;
14420
14421      -------------------------------
14422      -- Locate_Corresponding_Body --
14423      -------------------------------
14424
14425      function Locate_Corresponding_Body (PE : Entity_Id) return Node_Id is
14426         Spec  : constant Node_Id   := Declaration_Node (PE);
14427         Decl  : constant Node_Id   := Parent (Spec);
14428         Scop  : constant Entity_Id := Scope (PE);
14429         PBody : Node_Id;
14430
14431      begin
14432         if Is_Library_Level_Entity (PE) then
14433
14434            --  If package is a library unit that requires a body, we have no
14435            --  choice but to go after that body because it might contain an
14436            --  optional body for the original generic package.
14437
14438            if Unit_Requires_Body (PE) then
14439
14440               --  Load the body. Note that we are a little careful here to use
14441               --  Spec to get the unit number, rather than PE or Decl, since
14442               --  in the case where the package is itself a library level
14443               --  instantiation, Spec will properly reference the generic
14444               --  template, which is what we really want.
14445
14446               return
14447                 Load_Package_Body
14448                   (Get_Body_Name (Unit_Name (Get_Source_Unit (Spec))));
14449
14450            --  But if the package is a library unit that does NOT require
14451            --  a body, then no body is permitted, so we are sure that there
14452            --  is no body for the original generic package.
14453
14454            else
14455               return Empty;
14456            end if;
14457
14458         --  Otherwise look and see if we are embedded in a further package
14459
14460         elsif Is_Package_Or_Generic_Package (Scop) then
14461
14462            --  If so, get the body of the enclosing package, and look in
14463            --  its package body for the package body we are looking for.
14464
14465            PBody := Locate_Corresponding_Body (Scop);
14466
14467            if No (PBody) then
14468               return Empty;
14469            else
14470               return Find_Body_In (PE, First (Declarations (PBody)));
14471            end if;
14472
14473         --  If we are not embedded in a further package, then the body
14474         --  must be in the same declarative part as we are.
14475
14476         else
14477            return Find_Body_In (PE, Next (Decl));
14478         end if;
14479      end Locate_Corresponding_Body;
14480
14481   --  Start of processing for Has_Generic_Body
14482
14483   begin
14484      if Present (Corresponding_Body (Decl)) then
14485         return True;
14486
14487      elsif Unit_Requires_Body (Ent) then
14488         return True;
14489
14490      --  Compilation units cannot have optional bodies
14491
14492      elsif Is_Compilation_Unit (Ent) then
14493         return False;
14494
14495      --  Otherwise look at what scope we are in
14496
14497      else
14498         Scop := Scope (Ent);
14499
14500         --  Case of entity is in other than a package spec, in this case
14501         --  the body, if present, must be in the same declarative part.
14502
14503         if not Is_Package_Or_Generic_Package (Scop) then
14504            declare
14505               P : Node_Id;
14506
14507            begin
14508               --  Declaration node may get us a spec, so if so, go to
14509               --  the parent declaration.
14510
14511               P := Declaration_Node (Ent);
14512               while not Is_List_Member (P) loop
14513                  P := Parent (P);
14514               end loop;
14515
14516               return Present (Find_Body_In (Ent, Next (P)));
14517            end;
14518
14519         --  If the entity is in a package spec, then we have to locate
14520         --  the corresponding package body, and look there.
14521
14522         else
14523            declare
14524               PBody : constant Node_Id := Locate_Corresponding_Body (Scop);
14525
14526            begin
14527               if No (PBody) then
14528                  return False;
14529               else
14530                  return
14531                    Present
14532                      (Find_Body_In (Ent, (First (Declarations (PBody)))));
14533               end if;
14534            end;
14535         end if;
14536      end if;
14537   end Has_Generic_Body;
14538
14539   -----------------------
14540   -- Insert_Elab_Check --
14541   -----------------------
14542
14543   procedure Insert_Elab_Check (N : Node_Id; C : Node_Id := Empty) is
14544      Nod : Node_Id;
14545      Loc : constant Source_Ptr := Sloc (N);
14546
14547      Chk : Node_Id;
14548      --  The check (N_Raise_Program_Error) node to be inserted
14549
14550   begin
14551      --  If expansion is disabled, do not generate any checks. Also
14552      --  skip checks if any subunits are missing because in either
14553      --  case we lack the full information that we need, and no object
14554      --  file will be created in any case.
14555
14556      if not Expander_Active or else Subunits_Missing then
14557         return;
14558      end if;
14559
14560      --  If we have a generic instantiation, where Instance_Spec is set,
14561      --  then this field points to a generic instance spec that has
14562      --  been inserted before the instantiation node itself, so that
14563      --  is where we want to insert a check.
14564
14565      if Nkind (N) in N_Generic_Instantiation
14566        and then Present (Instance_Spec (N))
14567      then
14568         Nod := Instance_Spec (N);
14569      else
14570         Nod := N;
14571      end if;
14572
14573      --  Build check node, possibly with condition
14574
14575      Chk :=
14576        Make_Raise_Program_Error (Loc, Reason => PE_Access_Before_Elaboration);
14577
14578      if Present (C) then
14579         Set_Condition (Chk, Make_Op_Not (Loc, Right_Opnd => C));
14580      end if;
14581
14582      --  If we are inserting at the top level, insert in Aux_Decls
14583
14584      if Nkind (Parent (Nod)) = N_Compilation_Unit then
14585         declare
14586            ADN : constant Node_Id := Aux_Decls_Node (Parent (Nod));
14587
14588         begin
14589            if No (Declarations (ADN)) then
14590               Set_Declarations (ADN, New_List (Chk));
14591            else
14592               Append_To (Declarations (ADN), Chk);
14593            end if;
14594
14595            Analyze (Chk);
14596         end;
14597
14598      --  Otherwise just insert as an action on the node in question
14599
14600      else
14601         Insert_Action (Nod, Chk);
14602      end if;
14603   end Insert_Elab_Check;
14604
14605   -------------------------------
14606   -- Is_Call_Of_Generic_Formal --
14607   -------------------------------
14608
14609   function Is_Call_Of_Generic_Formal (N : Node_Id) return Boolean is
14610   begin
14611      return Nkind_In (N, N_Function_Call, N_Procedure_Call_Statement)
14612
14613        --  Always return False if debug flag -gnatd.G is set
14614
14615        and then not Debug_Flag_Dot_GG
14616
14617      --  For now, we detect this by looking for the strange identifier
14618      --  node, whose Chars reflect the name of the generic formal, but
14619      --  the Chars of the Entity references the generic actual.
14620
14621        and then Nkind (Name (N)) = N_Identifier
14622        and then Chars (Name (N)) /= Chars (Entity (Name (N)));
14623   end Is_Call_Of_Generic_Formal;
14624
14625   -------------------------------
14626   -- Is_Finalization_Procedure --
14627   -------------------------------
14628
14629   function Is_Finalization_Procedure (Id : Entity_Id) return Boolean is
14630   begin
14631      --  Check whether Id is a procedure with at least one parameter
14632
14633      if Ekind (Id) = E_Procedure and then Present (First_Formal (Id)) then
14634         declare
14635            Typ      : constant Entity_Id := Etype (First_Formal (Id));
14636            Deep_Fin : Entity_Id := Empty;
14637            Fin      : Entity_Id := Empty;
14638
14639         begin
14640            --  If the type of the first formal does not require finalization
14641            --  actions, then this is definitely not [Deep_]Finalize.
14642
14643            if not Needs_Finalization (Typ) then
14644               return False;
14645            end if;
14646
14647            --  At this point we have the following scenario:
14648
14649            --    procedure Name (Param1 : [in] [out] Ctrl[; Param2 : ...]);
14650
14651            --  Recover the two possible versions of [Deep_]Finalize using the
14652            --  type of the first parameter and compare with the input.
14653
14654            Deep_Fin := TSS (Typ, TSS_Deep_Finalize);
14655
14656            if Is_Controlled (Typ) then
14657               Fin := Find_Prim_Op (Typ, Name_Finalize);
14658            end if;
14659
14660            return    (Present (Deep_Fin) and then Id = Deep_Fin)
14661              or else (Present (Fin)      and then Id = Fin);
14662         end;
14663      end if;
14664
14665      return False;
14666   end Is_Finalization_Procedure;
14667
14668   ------------------
14669   -- Output_Calls --
14670   ------------------
14671
14672   procedure Output_Calls
14673     (N               : Node_Id;
14674      Check_Elab_Flag : Boolean)
14675   is
14676      function Emit (Flag : Boolean) return Boolean;
14677      --  Determine whether to emit an error message based on the combination
14678      --  of flags Check_Elab_Flag and Flag.
14679
14680      function Is_Printable_Error_Name return Boolean;
14681      --  An internal function, used to determine if a name, stored in the
14682      --  Name_Buffer, is either a non-internal name, or is an internal name
14683      --  that is printable by the error message circuits (i.e. it has a single
14684      --  upper case letter at the end).
14685
14686      ----------
14687      -- Emit --
14688      ----------
14689
14690      function Emit (Flag : Boolean) return Boolean is
14691      begin
14692         if Check_Elab_Flag then
14693            return Flag;
14694         else
14695            return True;
14696         end if;
14697      end Emit;
14698
14699      -----------------------------
14700      -- Is_Printable_Error_Name --
14701      -----------------------------
14702
14703      function Is_Printable_Error_Name return Boolean is
14704      begin
14705         if not Is_Internal_Name then
14706            return True;
14707
14708         elsif Name_Len = 1 then
14709            return False;
14710
14711         else
14712            Name_Len := Name_Len - 1;
14713            return not Is_Internal_Name;
14714         end if;
14715      end Is_Printable_Error_Name;
14716
14717      --  Local variables
14718
14719      Ent : Entity_Id;
14720
14721   --  Start of processing for Output_Calls
14722
14723   begin
14724      for J in reverse 1 .. Elab_Call.Last loop
14725         Error_Msg_Sloc := Elab_Call.Table (J).Cloc;
14726
14727         Ent := Elab_Call.Table (J).Ent;
14728         Get_Name_String (Chars (Ent));
14729
14730         --  Dynamic elaboration model, warnings controlled by -gnatwl
14731
14732         if Dynamic_Elaboration_Checks then
14733            if Emit (Elab_Warnings) then
14734               if Is_Generic_Unit (Ent) then
14735                  Error_Msg_NE ("\\?l?& instantiated #", N, Ent);
14736               elsif Is_Init_Proc (Ent) then
14737                  Error_Msg_N ("\\?l?initialization procedure called #", N);
14738               elsif Is_Printable_Error_Name then
14739                  Error_Msg_NE ("\\?l?& called #", N, Ent);
14740               else
14741                  Error_Msg_N ("\\?l?called #", N);
14742               end if;
14743            end if;
14744
14745         --  Static elaboration model, info messages controlled by -gnatel
14746
14747         else
14748            if Emit (Elab_Info_Messages) then
14749               if Is_Generic_Unit (Ent) then
14750                  Error_Msg_NE ("\\?$?& instantiated #", N, Ent);
14751               elsif Is_Init_Proc (Ent) then
14752                  Error_Msg_N ("\\?$?initialization procedure called #", N);
14753               elsif Is_Printable_Error_Name then
14754                  Error_Msg_NE ("\\?$?& called #", N, Ent);
14755               else
14756                  Error_Msg_N ("\\?$?called #", N);
14757               end if;
14758            end if;
14759         end if;
14760      end loop;
14761   end Output_Calls;
14762
14763   ----------------------------
14764   -- Same_Elaboration_Scope --
14765   ----------------------------
14766
14767   function Same_Elaboration_Scope (Scop1, Scop2 : Entity_Id) return Boolean is
14768      S1 : Entity_Id;
14769      S2 : Entity_Id;
14770
14771   begin
14772      --  Find elaboration scope for Scop1
14773      --  This is either a subprogram or a compilation unit.
14774
14775      S1 := Scop1;
14776      while S1 /= Standard_Standard
14777        and then not Is_Compilation_Unit (S1)
14778        and then Ekind_In (S1, E_Package, E_Protected_Type, E_Block)
14779      loop
14780         S1 := Scope (S1);
14781      end loop;
14782
14783      --  Find elaboration scope for Scop2
14784
14785      S2 := Scop2;
14786      while S2 /= Standard_Standard
14787        and then not Is_Compilation_Unit (S2)
14788        and then Ekind_In (S2, E_Package, E_Protected_Type, E_Block)
14789      loop
14790         S2 := Scope (S2);
14791      end loop;
14792
14793      return S1 = S2;
14794   end Same_Elaboration_Scope;
14795
14796   -----------------
14797   -- Set_C_Scope --
14798   -----------------
14799
14800   procedure Set_C_Scope is
14801   begin
14802      while not Is_Compilation_Unit (C_Scope) loop
14803         C_Scope := Scope (C_Scope);
14804      end loop;
14805   end Set_C_Scope;
14806
14807   --------------------------------
14808   -- Set_Elaboration_Constraint --
14809   --------------------------------
14810
14811   procedure Set_Elaboration_Constraint
14812    (Call : Node_Id;
14813     Subp : Entity_Id;
14814     Scop : Entity_Id)
14815   is
14816      Elab_Unit : Entity_Id;
14817
14818      --  Check whether this is a call to an Initialize subprogram for a
14819      --  controlled type. Note that Call can also be a 'Access attribute
14820      --  reference, which now generates an elaboration check.
14821
14822      Init_Call : constant Boolean :=
14823                    Nkind (Call) = N_Procedure_Call_Statement
14824                      and then Chars (Subp) = Name_Initialize
14825                      and then Comes_From_Source (Subp)
14826                      and then Present (Parameter_Associations (Call))
14827                      and then Is_Controlled (Etype (First_Actual (Call)));
14828
14829   begin
14830      --  If the unit is mentioned in a with_clause of the current unit, it is
14831      --  visible, and we can set the elaboration flag.
14832
14833      if Is_Immediately_Visible (Scop)
14834        or else (Is_Child_Unit (Scop) and then Is_Visible_Lib_Unit (Scop))
14835      then
14836         Activate_Elaborate_All_Desirable (Call, Scop);
14837         Set_Suppress_Elaboration_Warnings (Scop);
14838         return;
14839      end if;
14840
14841      --  If this is not an initialization call or a call using object notation
14842      --  we know that the unit of the called entity is in the context, and we
14843      --  can set the flag as well. The unit need not be visible if the call
14844      --  occurs within an instantiation.
14845
14846      if Is_Init_Proc (Subp)
14847        or else Init_Call
14848        or else Nkind (Original_Node (Call)) = N_Selected_Component
14849      then
14850         null;  --  detailed processing follows.
14851
14852      else
14853         Activate_Elaborate_All_Desirable (Call, Scop);
14854         Set_Suppress_Elaboration_Warnings (Scop);
14855         return;
14856      end if;
14857
14858      --  If the unit is not in the context, there must be an intermediate unit
14859      --  that is, on which we need to place to elaboration flag. This happens
14860      --  with init proc calls.
14861
14862      if Is_Init_Proc (Subp) or else Init_Call then
14863
14864         --  The initialization call is on an object whose type is not declared
14865         --  in the same scope as the subprogram. The type of the object must
14866         --  be a subtype of the type of operation. This object is the first
14867         --  actual in the call.
14868
14869         declare
14870            Typ : constant Entity_Id :=
14871                    Etype (First (Parameter_Associations (Call)));
14872         begin
14873            Elab_Unit := Scope (Typ);
14874            while (Present (Elab_Unit))
14875              and then not Is_Compilation_Unit (Elab_Unit)
14876            loop
14877               Elab_Unit := Scope (Elab_Unit);
14878            end loop;
14879         end;
14880
14881      --  If original node uses selected component notation, the prefix is
14882      --  visible and determines the scope that must be elaborated. After
14883      --  rewriting, the prefix is the first actual in the call.
14884
14885      elsif Nkind (Original_Node (Call)) = N_Selected_Component then
14886         Elab_Unit := Scope (Etype (First (Parameter_Associations (Call))));
14887
14888      --  Not one of special cases above
14889
14890      else
14891         --  Using previously computed scope. If the elaboration check is
14892         --  done after analysis, the scope is not visible any longer, but
14893         --  must still be in the context.
14894
14895         Elab_Unit := Scop;
14896      end if;
14897
14898      Activate_Elaborate_All_Desirable (Call, Elab_Unit);
14899      Set_Suppress_Elaboration_Warnings (Elab_Unit);
14900   end Set_Elaboration_Constraint;
14901
14902   -----------------
14903   -- Spec_Entity --
14904   -----------------
14905
14906   function Spec_Entity (E : Entity_Id) return Entity_Id is
14907      Decl : Node_Id;
14908
14909   begin
14910      --  Check for case of body entity
14911      --  Why is the check for E_Void needed???
14912
14913      if Ekind_In (E, E_Void, E_Subprogram_Body, E_Package_Body) then
14914         Decl := E;
14915
14916         loop
14917            Decl := Parent (Decl);
14918            exit when Nkind (Decl) in N_Proper_Body;
14919         end loop;
14920
14921         return Corresponding_Spec (Decl);
14922
14923      else
14924         return E;
14925      end if;
14926   end Spec_Entity;
14927
14928   ------------
14929   -- Within --
14930   ------------
14931
14932   function Within (E1, E2 : Entity_Id) return Boolean is
14933      Scop : Entity_Id;
14934   begin
14935      Scop := E1;
14936      loop
14937         if Scop = E2 then
14938            return True;
14939         elsif Scop = Standard_Standard then
14940            return False;
14941         else
14942            Scop := Scope (Scop);
14943         end if;
14944      end loop;
14945   end Within;
14946
14947   --------------------------
14948   -- Within_Elaborate_All --
14949   --------------------------
14950
14951   function Within_Elaborate_All
14952     (Unit : Unit_Number_Type;
14953      E    : Entity_Id) return Boolean
14954   is
14955      type Unit_Number_Set is array (Main_Unit .. Last_Unit) of Boolean;
14956      pragma Pack (Unit_Number_Set);
14957
14958      Seen : Unit_Number_Set := (others => False);
14959      --  Seen (X) is True after we have seen unit X in the walk. This is used
14960      --  to prevent processing the same unit more than once.
14961
14962      Result : Boolean := False;
14963
14964      procedure Helper (Unit : Unit_Number_Type);
14965      --  This helper procedure does all the work for Within_Elaborate_All. It
14966      --  walks the dependency graph, and sets Result to True if it finds an
14967      --  appropriate Elaborate_All.
14968
14969      ------------
14970      -- Helper --
14971      ------------
14972
14973      procedure Helper (Unit : Unit_Number_Type) is
14974         CU : constant Node_Id := Cunit (Unit);
14975
14976         Item    : Node_Id;
14977         Item2   : Node_Id;
14978         Elab_Id : Entity_Id;
14979         Par     : Node_Id;
14980
14981      begin
14982         if Seen (Unit) then
14983            return;
14984         else
14985            Seen (Unit) := True;
14986         end if;
14987
14988         --  First, check for Elaborate_Alls on this unit
14989
14990         Item := First (Context_Items (CU));
14991         while Present (Item) loop
14992            if Nkind (Item) = N_Pragma
14993              and then Pragma_Name (Item) = Name_Elaborate_All
14994            then
14995               --  Return if some previous error on the pragma itself. The
14996               --  pragma may be unanalyzed, because of a previous error, or
14997               --  if it is the context of a subunit, inherited by its parent.
14998
14999               if Error_Posted (Item) or else not Analyzed (Item) then
15000                  return;
15001               end if;
15002
15003               Elab_Id :=
15004                 Entity
15005                   (Expression (First (Pragma_Argument_Associations (Item))));
15006
15007               if E = Elab_Id then
15008                  Result := True;
15009                  return;
15010               end if;
15011
15012               Par := Parent (Unit_Declaration_Node (Elab_Id));
15013
15014               Item2 := First (Context_Items (Par));
15015               while Present (Item2) loop
15016                  if Nkind (Item2) = N_With_Clause
15017                    and then Entity (Name (Item2)) = E
15018                    and then not Limited_Present (Item2)
15019                  then
15020                     Result := True;
15021                     return;
15022                  end if;
15023
15024                  Next (Item2);
15025               end loop;
15026            end if;
15027
15028            Next (Item);
15029         end loop;
15030
15031         --  Second, recurse on with's. We could do this as part of the above
15032         --  loop, but it's probably more efficient to have two loops, because
15033         --  the relevant Elaborate_All is likely to be on the initial unit. In
15034         --  other words, we're walking the with's breadth-first. This part is
15035         --  only necessary in the dynamic elaboration model.
15036
15037         if Dynamic_Elaboration_Checks then
15038            Item := First (Context_Items (CU));
15039            while Present (Item) loop
15040               if Nkind (Item) = N_With_Clause
15041                 and then not Limited_Present (Item)
15042               then
15043                  --  Note: the following call to Get_Cunit_Unit_Number does a
15044                  --  linear search, which could be slow, but it's OK because
15045                  --  we're about to give a warning anyway. Also, there might
15046                  --  be hundreds of units, but not millions. If it turns out
15047                  --  to be a problem, we could store the Get_Cunit_Unit_Number
15048                  --  in each N_Compilation_Unit node, but that would involve
15049                  --  rearranging N_Compilation_Unit_Aux to make room.
15050
15051                  Helper (Get_Cunit_Unit_Number (Library_Unit (Item)));
15052
15053                  if Result then
15054                     return;
15055                  end if;
15056               end if;
15057
15058               Next (Item);
15059            end loop;
15060         end if;
15061      end Helper;
15062
15063   --  Start of processing for Within_Elaborate_All
15064
15065   begin
15066      Helper (Unit);
15067      return Result;
15068   end Within_Elaborate_All;
15069
15070end Sem_Elab;
15071