OSDN Git Service

2010-10-21 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch12.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             S E M _ C H 1 2                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, 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
26 with Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Einfo;    use Einfo;
29 with Elists;   use Elists;
30 with Errout;   use Errout;
31 with Expander; use Expander;
32 with Fname;    use Fname;
33 with Fname.UF; use Fname.UF;
34 with Freeze;   use Freeze;
35 with Hostparm;
36 with Itypes;   use Itypes;
37 with Lib;      use Lib;
38 with Lib.Load; use Lib.Load;
39 with Lib.Xref; use Lib.Xref;
40 with Nlists;   use Nlists;
41 with Namet;    use Namet;
42 with Nmake;    use Nmake;
43 with Opt;      use Opt;
44 with Rident;   use Rident;
45 with Restrict; use Restrict;
46 with Rtsfind;  use Rtsfind;
47 with Sem;      use Sem;
48 with Sem_Aux;  use Sem_Aux;
49 with Sem_Cat;  use Sem_Cat;
50 with Sem_Ch3;  use Sem_Ch3;
51 with Sem_Ch6;  use Sem_Ch6;
52 with Sem_Ch7;  use Sem_Ch7;
53 with Sem_Ch8;  use Sem_Ch8;
54 with Sem_Ch10; use Sem_Ch10;
55 with Sem_Ch13; use Sem_Ch13;
56 with Sem_Disp; use Sem_Disp;
57 with Sem_Elab; use Sem_Elab;
58 with Sem_Elim; use Sem_Elim;
59 with Sem_Eval; use Sem_Eval;
60 with Sem_Res;  use Sem_Res;
61 with Sem_Type; use Sem_Type;
62 with Sem_Util; use Sem_Util;
63 with Sem_Warn; use Sem_Warn;
64 with Stand;    use Stand;
65 with Sinfo;    use Sinfo;
66 with Sinfo.CN; use Sinfo.CN;
67 with Sinput;   use Sinput;
68 with Sinput.L; use Sinput.L;
69 with Snames;   use Snames;
70 with Stringt;  use Stringt;
71 with Uname;    use Uname;
72 with Table;
73 with Tbuild;   use Tbuild;
74 with Uintp;    use Uintp;
75 with Urealp;   use Urealp;
76
77 with GNAT.HTable;
78
79 package body Sem_Ch12 is
80
81    ----------------------------------------------------------
82    -- Implementation of Generic Analysis and Instantiation --
83    ----------------------------------------------------------
84
85    --  GNAT implements generics by macro expansion. No attempt is made to share
86    --  generic instantiations (for now). Analysis of a generic definition does
87    --  not perform any expansion action, but the expander must be called on the
88    --  tree for each instantiation, because the expansion may of course depend
89    --  on the generic actuals. All of this is best achieved as follows:
90    --
91    --  a) Semantic analysis of a generic unit is performed on a copy of the
92    --  tree for the generic unit. All tree modifications that follow analysis
93    --  do not affect the original tree. Links are kept between the original
94    --  tree and the copy, in order to recognize non-local references within
95    --  the generic, and propagate them to each instance (recall that name
96    --  resolution is done on the generic declaration: generics are not really
97    --  macros!). This is summarized in the following diagram:
98
99    --              .-----------.               .----------.
100    --              |  semantic |<--------------|  generic |
101    --              |    copy   |               |    unit  |
102    --              |           |==============>|          |
103    --              |___________|    global     |__________|
104    --                             references     |   |  |
105    --                                            |   |  |
106    --                                          .-----|--|.
107    --                                          |  .-----|---.
108    --                                          |  |  .----------.
109    --                                          |  |  |  generic |
110    --                                          |__|  |          |
111    --                                             |__| instance |
112    --                                                |__________|
113
114    --  b) Each instantiation copies the original tree, and inserts into it a
115    --  series of declarations that describe the mapping between generic formals
116    --  and actuals. For example, a generic In OUT parameter is an object
117    --  renaming of the corresponding actual, etc. Generic IN parameters are
118    --  constant declarations.
119
120    --  c) In order to give the right visibility for these renamings, we use
121    --  a different scheme for package and subprogram instantiations. For
122    --  packages, the list of renamings is inserted into the package
123    --  specification, before the visible declarations of the package. The
124    --  renamings are analyzed before any of the text of the instance, and are
125    --  thus visible at the right place. Furthermore, outside of the instance,
126    --  the generic parameters are visible and denote their corresponding
127    --  actuals.
128
129    --  For subprograms, we create a container package to hold the renamings
130    --  and the subprogram instance itself. Analysis of the package makes the
131    --  renaming declarations visible to the subprogram. After analyzing the
132    --  package, the defining entity for the subprogram is touched-up so that
133    --  it appears declared in the current scope, and not inside the container
134    --  package.
135
136    --  If the instantiation is a compilation unit, the container package is
137    --  given the same name as the subprogram instance. This ensures that
138    --  the elaboration procedure called by the binder, using the compilation
139    --  unit name, calls in fact the elaboration procedure for the package.
140
141    --  Not surprisingly, private types complicate this approach. By saving in
142    --  the original generic object the non-local references, we guarantee that
143    --  the proper entities are referenced at the point of instantiation.
144    --  However, for private types, this by itself does not insure that the
145    --  proper VIEW of the entity is used (the full type may be visible at the
146    --  point of generic definition, but not at instantiation, or vice-versa).
147    --  In  order to reference the proper view, we special-case any reference
148    --  to private types in the generic object, by saving both views, one in
149    --  the generic and one in the semantic copy. At time of instantiation, we
150    --  check whether the two views are consistent, and exchange declarations if
151    --  necessary, in order to restore the correct visibility. Similarly, if
152    --  the instance view is private when the generic view was not, we perform
153    --  the exchange. After completing the instantiation, we restore the
154    --  current visibility. The flag Has_Private_View marks identifiers in the
155    --  the generic unit that require checking.
156
157    --  Visibility within nested generic units requires special handling.
158    --  Consider the following scheme:
159
160    --  type Global is ...         --  outside of generic unit.
161    --  generic ...
162    --  package Outer is
163    --     ...
164    --     type Semi_Global is ... --  global to inner.
165
166    --     generic ...                                         -- 1
167    --     procedure inner (X1 : Global;  X2 : Semi_Global);
168
169    --     procedure in2 is new inner (...);                   -- 4
170    --  end Outer;
171
172    --  package New_Outer is new Outer (...);                  -- 2
173    --  procedure New_Inner is new New_Outer.Inner (...);      -- 3
174
175    --  The semantic analysis of Outer captures all occurrences of Global.
176    --  The semantic analysis of Inner (at 1) captures both occurrences of
177    --  Global and Semi_Global.
178
179    --  At point 2 (instantiation of Outer), we also produce a generic copy
180    --  of Inner, even though Inner is, at that point, not being instantiated.
181    --  (This is just part of the semantic analysis of New_Outer).
182
183    --  Critically, references to Global within Inner must be preserved, while
184    --  references to Semi_Global should not preserved, because they must now
185    --  resolve to an entity within New_Outer. To distinguish between these, we
186    --  use a global variable, Current_Instantiated_Parent, which is set when
187    --  performing a generic copy during instantiation (at 2). This variable is
188    --  used when performing a generic copy that is not an instantiation, but
189    --  that is nested within one, as the occurrence of 1 within 2. The analysis
190    --  of a nested generic only preserves references that are global to the
191    --  enclosing Current_Instantiated_Parent. We use the Scope_Depth value to
192    --  determine whether a reference is external to the given parent.
193
194    --  The instantiation at point 3 requires no special treatment. The method
195    --  works as well for further nestings of generic units, but of course the
196    --  variable Current_Instantiated_Parent must be stacked because nested
197    --  instantiations can occur, e.g. the occurrence of 4 within 2.
198
199    --  The instantiation of package and subprogram bodies is handled in a
200    --  similar manner, except that it is delayed until after semantic
201    --  analysis is complete. In this fashion complex cross-dependencies
202    --  between several package declarations and bodies containing generics
203    --  can be compiled which otherwise would diagnose spurious circularities.
204
205    --  For example, it is possible to compile two packages A and B that
206    --  have the following structure:
207
208    --    package A is                         package B is
209    --       generic ...                          generic ...
210    --       package G_A is                       package G_B is
211
212    --    with B;                              with A;
213    --    package body A is                    package body B is
214    --       package N_B is new G_B (..)          package N_A is new G_A (..)
215
216    --  The table Pending_Instantiations in package Inline is used to keep
217    --  track of body instantiations that are delayed in this manner. Inline
218    --  handles the actual calls to do the body instantiations. This activity
219    --  is part of Inline, since the processing occurs at the same point, and
220    --  for essentially the same reason, as the handling of inlined routines.
221
222    ----------------------------------------------
223    -- Detection of Instantiation Circularities --
224    ----------------------------------------------
225
226    --  If we have a chain of instantiations that is circular, this is static
227    --  error which must be detected at compile time. The detection of these
228    --  circularities is carried out at the point that we insert a generic
229    --  instance spec or body. If there is a circularity, then the analysis of
230    --  the offending spec or body will eventually result in trying to load the
231    --  same unit again, and we detect this problem as we analyze the package
232    --  instantiation for the second time.
233
234    --  At least in some cases after we have detected the circularity, we get
235    --  into trouble if we try to keep going. The following flag is set if a
236    --  circularity is detected, and used to abandon compilation after the
237    --  messages have been posted.
238
239    Circularity_Detected : Boolean := False;
240    --  This should really be reset on encountering a new main unit, but in
241    --  practice we are not using multiple main units so it is not critical.
242
243    -------------------------------------------------
244    -- Formal packages and partial parametrization --
245    -------------------------------------------------
246
247    --  When compiling a generic, a formal package is a local instantiation. If
248    --  declared with a box, its generic formals are visible in the enclosing
249    --  generic. If declared with a partial list of actuals, those actuals that
250    --  are defaulted (covered by an Others clause, or given an explicit box
251    --  initialization) are also visible in the enclosing generic, while those
252    --  that have a corresponding actual are not.
253
254    --  In our source model of instantiation, the same visibility must be
255    --  present in the spec and body of an instance: the names of the formals
256    --  that are defaulted must be made visible within the instance, and made
257    --  invisible (hidden) after the instantiation is complete, so that they
258    --  are not accessible outside of the instance.
259
260    --  In a generic, a formal package is treated like a special instantiation.
261    --  Our Ada95 compiler handled formals with and without box in different
262    --  ways. With partial parametrization, we use a single model for both.
263    --  We create a package declaration that consists of the specification of
264    --  the generic package, and a set of declarations that map the actuals
265    --  into local renamings, just as we do for bona fide instantiations. For
266    --  defaulted parameters and formals with a box, we copy directly the
267    --  declarations of the formal into this local package. The result is a
268    --  a package whose visible declarations may include generic formals. This
269    --  package is only used for type checking and visibility analysis, and
270    --  never reaches the back-end, so it can freely violate the placement
271    --  rules for generic formal declarations.
272
273    --  The list of declarations (renamings and copies of formals) is built
274    --  by Analyze_Associations, just as for regular instantiations.
275
276    --  At the point of instantiation, conformance checking must be applied only
277    --  to those parameters that were specified in the formal. We perform this
278    --  checking by creating another internal instantiation, this one including
279    --  only the renamings and the formals (the rest of the package spec is not
280    --  relevant to conformance checking). We can then traverse two lists: the
281    --  list of actuals in the instance that corresponds to the formal package,
282    --  and the list of actuals produced for this bogus instantiation. We apply
283    --  the conformance rules to those actuals that are not defaulted (i.e.
284    --  which still appear as generic formals.
285
286    --  When we compile an instance body we must make the right parameters
287    --  visible again. The predicate Is_Generic_Formal indicates which of the
288    --  formals should have its Is_Hidden flag reset.
289
290    -----------------------
291    -- Local subprograms --
292    -----------------------
293
294    procedure Abandon_Instantiation (N : Node_Id);
295    pragma No_Return (Abandon_Instantiation);
296    --  Posts an error message "instantiation abandoned" at the indicated node
297    --  and then raises the exception Instantiation_Error to do it.
298
299    procedure Analyze_Formal_Array_Type
300      (T   : in out Entity_Id;
301       Def : Node_Id);
302    --  A formal array type is treated like an array type declaration, and
303    --  invokes Array_Type_Declaration (sem_ch3) whose first parameter is
304    --  in-out, because in the case of an anonymous type the entity is
305    --  actually created in the procedure.
306
307    --  The following procedures treat other kinds of formal parameters
308
309    procedure Analyze_Formal_Derived_Interface_Type
310      (N   : Node_Id;
311       T   : Entity_Id;
312       Def : Node_Id);
313
314    procedure Analyze_Formal_Derived_Type
315      (N   : Node_Id;
316       T   : Entity_Id;
317       Def : Node_Id);
318
319    procedure Analyze_Formal_Interface_Type
320      (N   : Node_Id;
321       T   : Entity_Id;
322       Def : Node_Id);
323
324    --  The following subprograms create abbreviated declarations for formal
325    --  scalar types. We introduce an anonymous base of the proper class for
326    --  each of them, and define the formals as constrained first subtypes of
327    --  their bases. The bounds are expressions that are non-static in the
328    --  generic.
329
330    procedure Analyze_Formal_Decimal_Fixed_Point_Type
331                                                 (T : Entity_Id; Def : Node_Id);
332    procedure Analyze_Formal_Discrete_Type       (T : Entity_Id; Def : Node_Id);
333    procedure Analyze_Formal_Floating_Type       (T : Entity_Id; Def : Node_Id);
334    procedure Analyze_Formal_Signed_Integer_Type (T : Entity_Id; Def : Node_Id);
335    procedure Analyze_Formal_Modular_Type        (T : Entity_Id; Def : Node_Id);
336    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
337                                                 (T : Entity_Id; Def : Node_Id);
338
339    procedure Analyze_Formal_Private_Type
340      (N   : Node_Id;
341       T   : Entity_Id;
342       Def : Node_Id);
343    --  Creates a new private type, which does not require completion
344
345    procedure Analyze_Generic_Formal_Part (N : Node_Id);
346
347    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id);
348    --  Create a new access type with the given designated type
349
350    function Analyze_Associations
351      (I_Node  : Node_Id;
352       Formals : List_Id;
353       F_Copy  : List_Id) return List_Id;
354    --  At instantiation time, build the list of associations between formals
355    --  and actuals. Each association becomes a renaming declaration for the
356    --  formal entity. F_Copy is the analyzed list of formals in the generic
357    --  copy. It is used to apply legality checks to the actuals. I_Node is the
358    --  instantiation node itself.
359
360    procedure Analyze_Subprogram_Instantiation
361      (N : Node_Id;
362       K : Entity_Kind);
363
364    procedure Build_Instance_Compilation_Unit_Nodes
365      (N        : Node_Id;
366       Act_Body : Node_Id;
367       Act_Decl : Node_Id);
368    --  This procedure is used in the case where the generic instance of a
369    --  subprogram body or package body is a library unit. In this case, the
370    --  original library unit node for the generic instantiation must be
371    --  replaced by the resulting generic body, and a link made to a new
372    --  compilation unit node for the generic declaration. The argument N is
373    --  the original generic instantiation. Act_Body and Act_Decl are the body
374    --  and declaration of the instance (either package body and declaration
375    --  nodes or subprogram body and declaration nodes depending on the case).
376    --  On return, the node N has been rewritten with the actual body.
377
378    procedure Check_Access_Definition (N : Node_Id);
379    --  Subsidiary routine to null exclusion processing. Perform an assertion
380    --  check on Ada version and the presence of an access definition in N.
381
382    procedure Check_Formal_Packages (P_Id : Entity_Id);
383    --  Apply the following to all formal packages in generic associations
384
385    procedure Check_Formal_Package_Instance
386      (Formal_Pack : Entity_Id;
387       Actual_Pack : Entity_Id);
388    --  Verify that the actuals of the actual instance match the actuals of
389    --  the template for a formal package that is not declared with a box.
390
391    procedure Check_Forward_Instantiation (Decl : Node_Id);
392    --  If the generic is a local entity and the corresponding body has not
393    --  been seen yet, flag enclosing packages to indicate that it will be
394    --  elaborated after the generic body. Subprograms declared in the same
395    --  package cannot be inlined by the front-end because front-end inlining
396    --  requires a strict linear order of elaboration.
397
398    procedure Check_Hidden_Child_Unit
399      (N           : Node_Id;
400       Gen_Unit    : Entity_Id;
401       Act_Decl_Id : Entity_Id);
402    --  If the generic unit is an implicit child instance within a parent
403    --  instance, we need to make an explicit test that it is not hidden by
404    --  a child instance of the same name and parent.
405
406    procedure Check_Generic_Actuals
407      (Instance      : Entity_Id;
408       Is_Formal_Box : Boolean);
409    --  Similar to previous one. Check the actuals in the instantiation,
410    --  whose views can change between the point of instantiation and the point
411    --  of instantiation of the body. In addition, mark the generic renamings
412    --  as generic actuals, so that they are not compatible with other actuals.
413    --  Recurse on an actual that is a formal package whose declaration has
414    --  a box.
415
416    function Contains_Instance_Of
417      (Inner : Entity_Id;
418       Outer : Entity_Id;
419       N     : Node_Id) return Boolean;
420    --  Inner is instantiated within the generic Outer. Check whether Inner
421    --  directly or indirectly contains an instance of Outer or of one of its
422    --  parents, in the case of a subunit. Each generic unit holds a list of
423    --  the entities instantiated within (at any depth). This procedure
424    --  determines whether the set of such lists contains a cycle, i.e. an
425    --  illegal circular instantiation.
426
427    function Denotes_Formal_Package
428      (Pack     : Entity_Id;
429       On_Exit  : Boolean := False;
430       Instance : Entity_Id := Empty) return Boolean;
431    --  Returns True if E is a formal package of an enclosing generic, or
432    --  the actual for such a formal in an enclosing instantiation. If such
433    --  a package is used as a formal in an nested generic, or as an actual
434    --  in a nested instantiation, the visibility of ITS formals should not
435    --  be modified. When called from within Restore_Private_Views, the flag
436    --  On_Exit is true, to indicate that the search for a possible enclosing
437    --  instance should ignore the current one. In that case Instance denotes
438    --  the declaration for which this is an actual. This declaration may be
439    --  an instantiation in the source, or the internal instantiation that
440    --  corresponds to the actual for a formal package.
441
442    function Find_Actual_Type
443      (Typ       : Entity_Id;
444       Gen_Type  : Entity_Id) return Entity_Id;
445    --  When validating the actual types of a child instance, check whether
446    --  the formal is a formal type of the parent unit, and retrieve the current
447    --  actual for it. Typ is the entity in the analyzed formal type declaration
448    --  (component or index type of an array type, or designated type of an
449    --  access formal) and Gen_Type is the enclosing analyzed formal array
450    --  or access type. The desired actual may be a formal of a parent, or may
451    --  be declared in a formal package of a parent. In both cases it is a
452    --  generic actual type because it appears within a visible instance.
453    --  Finally, it may be declared in a parent unit without being a formal
454    --  of that unit, in which case it must be retrieved by visibility.
455    --  Ambiguities may still arise if two homonyms are declared in two formal
456    --  packages, and the prefix of the formal type may be needed to resolve
457    --  the ambiguity in the instance ???
458
459    function In_Same_Declarative_Part
460      (F_Node : Node_Id;
461       Inst   : Node_Id) return Boolean;
462    --  True if the instantiation Inst and the given freeze_node F_Node appear
463    --  within the same declarative part, ignoring subunits, but with no inter-
464    --  vening subprograms or concurrent units. If true, the freeze node
465    --  of the instance can be placed after the freeze node of the parent,
466    --  which it itself an instance.
467
468    function In_Main_Context (E : Entity_Id) return Boolean;
469    --  Check whether an instantiation is in the context of the main unit.
470    --  Used to determine whether its body should be elaborated to allow
471    --  front-end inlining.
472
473    function Is_Generic_Formal (E : Entity_Id) return Boolean;
474    --  Utility to determine whether a given entity is declared by means of
475    --  of a formal parameter declaration. Used to set properly the visibility
476    --  of generic formals of a generic package declared with a box or with
477    --  partial parametrization.
478
479    procedure Set_Instance_Env
480      (Gen_Unit : Entity_Id;
481       Act_Unit : Entity_Id);
482    --  Save current instance on saved environment, to be used to determine
483    --  the global status of entities in nested instances. Part of Save_Env.
484    --  called after verifying that the generic unit is legal for the instance,
485    --  The procedure also examines whether the generic unit is a predefined
486    --  unit, in order to set configuration switches accordingly. As a result
487    --  the procedure must be called after analyzing and freezing the actuals.
488
489    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id);
490    --  Associate analyzed generic parameter with corresponding
491    --  instance. Used for semantic checks at instantiation time.
492
493    function Has_Been_Exchanged (E : Entity_Id) return Boolean;
494    --  Traverse the Exchanged_Views list to see if a type was private
495    --  and has already been flipped during this phase of instantiation.
496
497    procedure Hide_Current_Scope;
498    --  When instantiating a generic child unit, the parent context must be
499    --  present, but the instance and all entities that may be generated
500    --  must be inserted in the current scope. We leave the current scope
501    --  on the stack, but make its entities invisible to avoid visibility
502    --  problems. This is reversed at the end of the instantiation. This is
503    --  not done for the instantiation of the bodies, which only require the
504    --  instances of the generic parents to be in scope.
505
506    procedure Install_Body
507      (Act_Body : Node_Id;
508       N        : Node_Id;
509       Gen_Body : Node_Id;
510       Gen_Decl : Node_Id);
511    --  If the instantiation happens textually before the body of the generic,
512    --  the instantiation of the body must be analyzed after the generic body,
513    --  and not at the point of instantiation. Such early instantiations can
514    --  happen if the generic and the instance appear in  a package declaration
515    --  because the generic body can only appear in the corresponding package
516    --  body. Early instantiations can also appear if generic, instance and
517    --  body are all in the declarative part of a subprogram or entry. Entities
518    --  of packages that are early instantiations are delayed, and their freeze
519    --  node appears after the generic body.
520
521    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id);
522    --  Insert freeze node at the end of the declarative part that includes the
523    --  instance node N. If N is in the visible part of an enclosing package
524    --  declaration, the freeze node has to be inserted at the end of the
525    --  private declarations, if any.
526
527    procedure Freeze_Subprogram_Body
528      (Inst_Node : Node_Id;
529       Gen_Body  : Node_Id;
530       Pack_Id   : Entity_Id);
531    --  The generic body may appear textually after the instance, including
532    --  in the proper body of a stub, or within a different package instance.
533    --  Given that the instance can only be elaborated after the generic, we
534    --  place freeze_nodes for the instance and/or for packages that may enclose
535    --  the instance and the generic, so that the back-end can establish the
536    --  proper order of elaboration.
537
538    procedure Init_Env;
539    --  Establish environment for subsequent instantiation. Separated from
540    --  Save_Env because data-structures for visibility handling must be
541    --  initialized before call to Check_Generic_Child_Unit.
542
543    procedure Install_Formal_Packages (Par : Entity_Id);
544    --  Install the visible part of any formal of the parent that is a formal
545    --  package. Note that for the case of a formal package with a box, this
546    --  includes the formal part of the formal package (12.7(10/2)).
547
548    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False);
549    --  When compiling an instance of a child unit the parent (which is
550    --  itself an instance) is an enclosing scope that must be made
551    --  immediately visible. This procedure is also used to install the non-
552    --  generic parent of a generic child unit when compiling its body, so
553    --  that full views of types in the parent are made visible.
554
555    procedure Remove_Parent (In_Body : Boolean := False);
556    --  Reverse effect after instantiation of child is complete
557
558    procedure Inline_Instance_Body
559      (N        : Node_Id;
560       Gen_Unit : Entity_Id;
561       Act_Decl : Node_Id);
562    --  If front-end inlining is requested, instantiate the package body,
563    --  and preserve the visibility of its compilation unit, to insure
564    --  that successive instantiations succeed.
565
566    --  The functions Instantiate_XXX perform various legality checks and build
567    --  the declarations for instantiated generic parameters. In all of these
568    --  Formal is the entity in the generic unit, Actual is the entity of
569    --  expression in the generic associations, and Analyzed_Formal is the
570    --  formal in the generic copy, which contains the semantic information to
571    --  be used to validate the actual.
572
573    function Instantiate_Object
574      (Formal          : Node_Id;
575       Actual          : Node_Id;
576       Analyzed_Formal : Node_Id) return List_Id;
577
578    function Instantiate_Type
579      (Formal          : Node_Id;
580       Actual          : Node_Id;
581       Analyzed_Formal : Node_Id;
582       Actual_Decls    : List_Id) return List_Id;
583
584    function Instantiate_Formal_Subprogram
585      (Formal          : Node_Id;
586       Actual          : Node_Id;
587       Analyzed_Formal : Node_Id) return Node_Id;
588
589    function Instantiate_Formal_Package
590      (Formal          : Node_Id;
591       Actual          : Node_Id;
592       Analyzed_Formal : Node_Id) return List_Id;
593    --  If the formal package is declared with a box, special visibility rules
594    --  apply to its formals: they are in the visible part of the package. This
595    --  is true in the declarative region of the formal package, that is to say
596    --  in the enclosing generic or instantiation. For an instantiation, the
597    --  parameters of the formal package are made visible in an explicit step.
598    --  Furthermore, if the actual has a visible USE clause, these formals must
599    --  be made potentially use-visible as well. On exit from the enclosing
600    --  instantiation, the reverse must be done.
601
602    --  For a formal package declared without a box, there are conformance rules
603    --  that apply to the actuals in the generic declaration and the actuals of
604    --  the actual package in the enclosing instantiation. The simplest way to
605    --  apply these rules is to repeat the instantiation of the formal package
606    --  in the context of the enclosing instance, and compare the generic
607    --  associations of this instantiation with those of the actual package.
608    --  This internal instantiation only needs to contain the renamings of the
609    --  formals: the visible and private declarations themselves need not be
610    --  created.
611
612    --  In Ada 2005, the formal package may be only partially parameterized.
613    --  In that case the visibility step must make visible those actuals whose
614    --  corresponding formals were given with a box. A final complication
615    --  involves inherited operations from formal derived types, which must
616    --  be visible if the type is.
617
618    function Is_In_Main_Unit (N : Node_Id) return Boolean;
619    --  Test if given node is in the main unit
620
621    procedure Load_Parent_Of_Generic
622      (N             : Node_Id;
623       Spec          : Node_Id;
624       Body_Optional : Boolean := False);
625    --  If the generic appears in a separate non-generic library unit, load the
626    --  corresponding body to retrieve the body of the generic. N is the node
627    --  for the generic instantiation, Spec is the generic package declaration.
628    --
629    --  Body_Optional is a flag that indicates that the body is being loaded to
630    --  ensure that temporaries are generated consistently when there are other
631    --  instances in the current declarative part that precede the one being
632    --  loaded. In that case a missing body is acceptable.
633
634    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id);
635    --  Add the context clause of the unit containing a generic unit to a
636    --  compilation unit that is, or contains, an instantiation.
637
638    function Get_Associated_Node (N : Node_Id) return Node_Id;
639    --  In order to propagate semantic information back from the analyzed copy
640    --  to the original generic, we maintain links between selected nodes in the
641    --  generic and their corresponding copies. At the end of generic analysis,
642    --  the routine Save_Global_References traverses the generic tree, examines
643    --  the semantic information, and preserves the links to those nodes that
644    --  contain global information. At instantiation, the information from the
645    --  associated node is placed on the new copy, so that name resolution is
646    --  not repeated.
647    --
648    --  Three kinds of source nodes have associated nodes:
649    --
650    --    a) those that can reference (denote) entities, that is identifiers,
651    --       character literals, expanded_names, operator symbols, operators,
652    --       and attribute reference nodes. These nodes have an Entity field
653    --       and are the set of nodes that are in N_Has_Entity.
654    --
655    --    b) aggregates (N_Aggregate and N_Extension_Aggregate)
656    --
657    --    c) selected components (N_Selected_Component)
658    --
659    --  For the first class, the associated node preserves the entity if it is
660    --  global. If the generic contains nested instantiations, the associated
661    --  node itself has been recopied, and a chain of them must be followed.
662    --
663    --  For aggregates, the associated node allows retrieval of the type, which
664    --  may otherwise not appear in the generic. The view of this type may be
665    --  different between generic and instantiation, and the full view can be
666    --  installed before the instantiation is analyzed. For aggregates of type
667    --  extensions, the same view exchange may have to be performed for some of
668    --  the ancestor types, if their view is private at the point of
669    --  instantiation.
670    --
671    --  Nodes that are selected components in the parse tree may be rewritten
672    --  as expanded names after resolution, and must be treated as potential
673    --  entity holders, which is why they also have an Associated_Node.
674    --
675    --  Nodes that do not come from source, such as freeze nodes, do not appear
676    --  in the generic tree, and need not have an associated node.
677    --
678    --  The associated node is stored in the Associated_Node field. Note that
679    --  this field overlaps Entity, which is fine, because the whole point is
680    --  that we don't need or want the normal Entity field in this situation.
681
682    procedure Map_Formal_Package_Entities (Form : Entity_Id; Act : Entity_Id);
683    --  Within the generic part, entities in the formal package are
684    --  visible. To validate subsequent type declarations, indicate
685    --  the correspondence between the entities in the analyzed formal,
686    --  and the entities in  the actual package. There are three packages
687    --  involved in the instantiation of a formal package: the parent
688    --  generic P1 which appears in the generic declaration, the fake
689    --  instantiation P2 which appears in the analyzed generic, and whose
690    --  visible entities may be used in subsequent formals, and the actual
691    --  P3 in the instance. To validate subsequent formals, me indicate
692    --  that the entities in P2 are mapped into those of P3. The mapping of
693    --  entities has to be done recursively for nested packages.
694
695    procedure Move_Freeze_Nodes
696      (Out_Of : Entity_Id;
697       After  : Node_Id;
698       L      : List_Id);
699    --  Freeze nodes can be generated in the analysis of a generic unit, but
700    --  will not be seen by the back-end. It is necessary to move those nodes
701    --  to the enclosing scope if they freeze an outer entity. We place them
702    --  at the end of the enclosing generic package, which is semantically
703    --  neutral.
704
705    procedure Preanalyze_Actuals (N : Node_Id);
706    --  Analyze actuals to perform name resolution. Full resolution is done
707    --  later, when the expected types are known, but names have to be captured
708    --  before installing parents of generics, that are not visible for the
709    --  actuals themselves.
710
711    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id);
712    --  Verify that an attribute that appears as the default for a formal
713    --  subprogram is a function or procedure with the correct profile.
714
715    -------------------------------------------
716    -- Data Structures for Generic Renamings --
717    -------------------------------------------
718
719    --  The map Generic_Renamings associates generic entities with their
720    --  corresponding actuals. Currently used to validate type instances. It
721    --  will eventually be used for all generic parameters to eliminate the
722    --  need for overload resolution in the instance.
723
724    type Assoc_Ptr is new Int;
725
726    Assoc_Null : constant Assoc_Ptr := -1;
727
728    type Assoc is record
729       Gen_Id         : Entity_Id;
730       Act_Id         : Entity_Id;
731       Next_In_HTable : Assoc_Ptr;
732    end record;
733
734    package Generic_Renamings is new Table.Table
735      (Table_Component_Type => Assoc,
736       Table_Index_Type     => Assoc_Ptr,
737       Table_Low_Bound      => 0,
738       Table_Initial        => 10,
739       Table_Increment      => 100,
740       Table_Name           => "Generic_Renamings");
741
742    --  Variable to hold enclosing instantiation. When the environment is
743    --  saved for a subprogram inlining, the corresponding Act_Id is empty.
744
745    Current_Instantiated_Parent : Assoc := (Empty, Empty, Assoc_Null);
746
747    --  Hash table for associations
748
749    HTable_Size : constant := 37;
750    type HTable_Range is range 0 .. HTable_Size - 1;
751
752    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr);
753    function  Next_Assoc     (E : Assoc_Ptr) return Assoc_Ptr;
754    function Get_Gen_Id      (E : Assoc_Ptr) return Entity_Id;
755    function Hash            (F : Entity_Id) return HTable_Range;
756
757    package Generic_Renamings_HTable is new GNAT.HTable.Static_HTable (
758       Header_Num => HTable_Range,
759       Element    => Assoc,
760       Elmt_Ptr   => Assoc_Ptr,
761       Null_Ptr   => Assoc_Null,
762       Set_Next   => Set_Next_Assoc,
763       Next       => Next_Assoc,
764       Key        => Entity_Id,
765       Get_Key    => Get_Gen_Id,
766       Hash       => Hash,
767       Equal      => "=");
768
769    Exchanged_Views : Elist_Id;
770    --  This list holds the private views that have been exchanged during
771    --  instantiation to restore the visibility of the generic declaration.
772    --  (see comments above). After instantiation, the current visibility is
773    --  reestablished by means of a traversal of this list.
774
775    Hidden_Entities : Elist_Id;
776    --  This list holds the entities of the current scope that are removed
777    --  from immediate visibility when instantiating a child unit. Their
778    --  visibility is restored in Remove_Parent.
779
780    --  Because instantiations can be recursive, the following must be saved
781    --  on entry and restored on exit from an instantiation (spec or body).
782    --  This is done by the two procedures Save_Env and Restore_Env. For
783    --  package and subprogram instantiations (but not for the body instances)
784    --  the action of Save_Env is done in two steps: Init_Env is called before
785    --  Check_Generic_Child_Unit, because setting the parent instances requires
786    --  that the visibility data structures be properly initialized. Once the
787    --  generic is unit is validated, Set_Instance_Env completes Save_Env.
788
789    Parent_Unit_Visible : Boolean := False;
790    --  Parent_Unit_Visible is used when the generic is a child unit, and
791    --  indicates whether the ultimate parent of the generic is visible in the
792    --  instantiation environment. It is used to reset the visibility of the
793    --  parent at the end of the instantiation (see Remove_Parent).
794
795    Instance_Parent_Unit : Entity_Id := Empty;
796    --  This records the ultimate parent unit of an instance of a generic
797    --  child unit and is used in conjunction with Parent_Unit_Visible to
798    --  indicate the unit to which the Parent_Unit_Visible flag corresponds.
799
800    type Instance_Env is record
801       Instantiated_Parent  : Assoc;
802       Exchanged_Views      : Elist_Id;
803       Hidden_Entities      : Elist_Id;
804       Current_Sem_Unit     : Unit_Number_Type;
805       Parent_Unit_Visible  : Boolean   := False;
806       Instance_Parent_Unit : Entity_Id := Empty;
807       Switches             : Config_Switches_Type;
808    end record;
809
810    package Instance_Envs is new Table.Table (
811      Table_Component_Type => Instance_Env,
812      Table_Index_Type     => Int,
813      Table_Low_Bound      => 0,
814      Table_Initial        => 32,
815      Table_Increment      => 100,
816      Table_Name           => "Instance_Envs");
817
818    procedure Restore_Private_Views
819      (Pack_Id    : Entity_Id;
820       Is_Package : Boolean := True);
821    --  Restore the private views of external types, and unmark the generic
822    --  renamings of actuals, so that they become compatible subtypes again.
823    --  For subprograms, Pack_Id is the package constructed to hold the
824    --  renamings.
825
826    procedure Switch_View (T : Entity_Id);
827    --  Switch the partial and full views of a type and its private
828    --  dependents (i.e. its subtypes and derived types).
829
830    ------------------------------------
831    -- Structures for Error Reporting --
832    ------------------------------------
833
834    Instantiation_Node : Node_Id;
835    --  Used by subprograms that validate instantiation of formal parameters
836    --  where there might be no actual on which to place the error message.
837    --  Also used to locate the instantiation node for generic subunits.
838
839    Instantiation_Error : exception;
840    --  When there is a semantic error in the generic parameter matching,
841    --  there is no point in continuing the instantiation, because the
842    --  number of cascaded errors is unpredictable. This exception aborts
843    --  the instantiation process altogether.
844
845    S_Adjustment : Sloc_Adjustment;
846    --  Offset created for each node in an instantiation, in order to keep
847    --  track of the source position of the instantiation in each of its nodes.
848    --  A subsequent semantic error or warning on a construct of the instance
849    --  points to both places: the original generic node, and the point of
850    --  instantiation. See Sinput and Sinput.L for additional details.
851
852    ------------------------------------------------------------
853    -- Data structure for keeping track when inside a Generic --
854    ------------------------------------------------------------
855
856    --  The following table is used to save values of the Inside_A_Generic
857    --  flag (see spec of Sem) when they are saved by Start_Generic.
858
859    package Generic_Flags is new Table.Table (
860      Table_Component_Type => Boolean,
861      Table_Index_Type     => Int,
862      Table_Low_Bound      => 0,
863      Table_Initial        => 32,
864      Table_Increment      => 200,
865      Table_Name           => "Generic_Flags");
866
867    ---------------------------
868    -- Abandon_Instantiation --
869    ---------------------------
870
871    procedure Abandon_Instantiation (N : Node_Id) is
872    begin
873       Error_Msg_N ("\instantiation abandoned!", N);
874       raise Instantiation_Error;
875    end Abandon_Instantiation;
876
877    --------------------------
878    -- Analyze_Associations --
879    --------------------------
880
881    function Analyze_Associations
882      (I_Node  : Node_Id;
883       Formals : List_Id;
884       F_Copy  : List_Id) return List_Id
885    is
886
887       Actual_Types    : constant Elist_Id  := New_Elmt_List;
888       Assoc           : constant List_Id   := New_List;
889       Default_Actuals : constant Elist_Id  := New_Elmt_List;
890       Gen_Unit        : constant Entity_Id :=
891                           Defining_Entity (Parent (F_Copy));
892
893       Actuals         : List_Id;
894       Actual          : Node_Id;
895       Formal          : Node_Id;
896       Next_Formal     : Node_Id;
897       Temp_Formal     : Node_Id;
898       Analyzed_Formal : Node_Id;
899       Match           : Node_Id;
900       Named           : Node_Id;
901       First_Named     : Node_Id := Empty;
902
903       Default_Formals : constant List_Id := New_List;
904       --  If an Others_Choice is present, some of the formals may be defaulted.
905       --  To simplify the treatment of visibility in an instance, we introduce
906       --  individual defaults for each such formal. These defaults are
907       --  appended to the list of associations and replace the Others_Choice.
908
909       Found_Assoc : Node_Id;
910       --  Association for the current formal being match. Empty if there are
911       --  no remaining actuals, or if there is no named association with the
912       --  name of the formal.
913
914       Is_Named_Assoc : Boolean;
915       Num_Matched    : Int := 0;
916       Num_Actuals    : Int := 0;
917
918       Others_Present : Boolean := False;
919       --  In Ada 2005, indicates partial parametrization of a formal
920       --  package. As usual an other association must be last in the list.
921
922       function Matching_Actual
923         (F   : Entity_Id;
924          A_F : Entity_Id) return Node_Id;
925       --  Find actual that corresponds to a given a formal parameter. If the
926       --  actuals are positional, return the next one, if any. If the actuals
927       --  are named, scan the parameter associations to find the right one.
928       --  A_F is the corresponding entity in the analyzed generic,which is
929       --  placed on the selector name for ASIS use.
930
931       --  In Ada 2005, a named association may be given with a box, in which
932       --  case Matching_Actual sets Found_Assoc to the generic association,
933       --  but return Empty for the actual itself. In this case the code below
934       --  creates a corresponding declaration for the formal.
935
936       function Partial_Parametrization return Boolean;
937       --  Ada 2005: if no match is found for a given formal, check if the
938       --  association for it includes a box, or whether the associations
939       --  include an Others clause.
940
941       procedure Process_Default (F : Entity_Id);
942       --  Add a copy of the declaration of generic formal  F to the list of
943       --  associations, and add an explicit box association for F  if there
944       --  is none yet, and the default comes from an Others_Choice.
945
946       procedure Set_Analyzed_Formal;
947       --  Find the node in the generic copy that corresponds to a given formal.
948       --  The semantic information on this node is used to perform legality
949       --  checks on the actuals. Because semantic analysis can introduce some
950       --  anonymous entities or modify the declaration node itself, the
951       --  correspondence between the two lists is not one-one. In addition to
952       --  anonymous types, the presence a formal equality will introduce an
953       --  implicit declaration for the corresponding inequality.
954
955       ---------------------
956       -- Matching_Actual --
957       ---------------------
958
959       function Matching_Actual
960         (F   : Entity_Id;
961          A_F : Entity_Id) return Node_Id
962       is
963          Prev  : Node_Id;
964          Act   : Node_Id;
965
966       begin
967          Is_Named_Assoc := False;
968
969          --  End of list of purely positional parameters
970
971          if No (Actual) or else Nkind (Actual) = N_Others_Choice then
972             Found_Assoc := Empty;
973             Act         := Empty;
974
975          --  Case of positional parameter corresponding to current formal
976
977          elsif No (Selector_Name (Actual)) then
978             Found_Assoc := Actual;
979             Act :=  Explicit_Generic_Actual_Parameter (Actual);
980             Num_Matched := Num_Matched + 1;
981             Next (Actual);
982
983          --  Otherwise scan list of named actuals to find the one with the
984          --  desired name. All remaining actuals have explicit names.
985
986          else
987             Is_Named_Assoc := True;
988             Found_Assoc := Empty;
989             Act         := Empty;
990             Prev        := Empty;
991
992             while Present (Actual) loop
993                if Chars (Selector_Name (Actual)) = Chars (F) then
994                   Set_Entity (Selector_Name (Actual), A_F);
995                   Set_Etype  (Selector_Name (Actual), Etype (A_F));
996                   Generate_Reference (A_F, Selector_Name (Actual));
997                   Found_Assoc := Actual;
998                   Act :=  Explicit_Generic_Actual_Parameter (Actual);
999                   Num_Matched := Num_Matched + 1;
1000                   exit;
1001                end if;
1002
1003                Prev := Actual;
1004                Next (Actual);
1005             end loop;
1006
1007             --  Reset for subsequent searches. In most cases the named
1008             --  associations are in order. If they are not, we reorder them
1009             --  to avoid scanning twice the same actual. This is not just a
1010             --  question of efficiency: there may be multiple defaults with
1011             --  boxes that have the same name. In a nested instantiation we
1012             --  insert actuals for those defaults, and cannot rely on their
1013             --  names to disambiguate them.
1014
1015             if Actual = First_Named  then
1016                Next (First_Named);
1017
1018             elsif Present (Actual) then
1019                Insert_Before (First_Named, Remove_Next (Prev));
1020             end if;
1021
1022             Actual := First_Named;
1023          end if;
1024
1025          if Is_Entity_Name (Act) and then Present (Entity (Act)) then
1026             Set_Used_As_Generic_Actual (Entity (Act));
1027          end if;
1028
1029          return Act;
1030       end Matching_Actual;
1031
1032       -----------------------------
1033       -- Partial_Parametrization --
1034       -----------------------------
1035
1036       function Partial_Parametrization return Boolean is
1037       begin
1038          return Others_Present
1039           or else (Present (Found_Assoc) and then Box_Present (Found_Assoc));
1040       end Partial_Parametrization;
1041
1042       ---------------------
1043       -- Process_Default --
1044       ---------------------
1045
1046       procedure Process_Default (F : Entity_Id)  is
1047          Loc     : constant Source_Ptr := Sloc (I_Node);
1048          F_Id    : constant Entity_Id  := Defining_Entity (F);
1049          Decl    : Node_Id;
1050          Default : Node_Id;
1051          Id      : Entity_Id;
1052
1053       begin
1054          --  Append copy of formal declaration to associations, and create new
1055          --  defining identifier for it.
1056
1057          Decl := New_Copy_Tree (F);
1058          Id := Make_Defining_Identifier (Sloc (F_Id), Chars => Chars (F_Id));
1059
1060          if Nkind (F) in N_Formal_Subprogram_Declaration then
1061             Set_Defining_Unit_Name (Specification (Decl), Id);
1062
1063          else
1064             Set_Defining_Identifier (Decl, Id);
1065          end if;
1066
1067          Append (Decl, Assoc);
1068
1069          if No (Found_Assoc) then
1070             Default :=
1071                Make_Generic_Association (Loc,
1072                  Selector_Name => New_Occurrence_Of (Id, Loc),
1073                  Explicit_Generic_Actual_Parameter => Empty);
1074             Set_Box_Present (Default);
1075             Append (Default, Default_Formals);
1076          end if;
1077       end Process_Default;
1078
1079       -------------------------
1080       -- Set_Analyzed_Formal --
1081       -------------------------
1082
1083       procedure Set_Analyzed_Formal is
1084          Kind : Node_Kind;
1085
1086       begin
1087          while Present (Analyzed_Formal) loop
1088             Kind := Nkind (Analyzed_Formal);
1089
1090             case Nkind (Formal) is
1091
1092                when N_Formal_Subprogram_Declaration =>
1093                   exit when Kind in N_Formal_Subprogram_Declaration
1094                     and then
1095                       Chars
1096                         (Defining_Unit_Name (Specification (Formal))) =
1097                       Chars
1098                         (Defining_Unit_Name (Specification (Analyzed_Formal)));
1099
1100                when N_Formal_Package_Declaration =>
1101                   exit when Nkind_In (Kind, N_Formal_Package_Declaration,
1102                                             N_Generic_Package_Declaration,
1103                                             N_Package_Declaration);
1104
1105                when N_Use_Package_Clause | N_Use_Type_Clause => exit;
1106
1107                when others =>
1108
1109                   --  Skip freeze nodes, and nodes inserted to replace
1110                   --  unrecognized pragmas.
1111
1112                   exit when
1113                     Kind not in N_Formal_Subprogram_Declaration
1114                       and then not Nkind_In (Kind, N_Subprogram_Declaration,
1115                                                    N_Freeze_Entity,
1116                                                    N_Null_Statement,
1117                                                    N_Itype_Reference)
1118                       and then Chars (Defining_Identifier (Formal)) =
1119                                Chars (Defining_Identifier (Analyzed_Formal));
1120             end case;
1121
1122             Next (Analyzed_Formal);
1123          end loop;
1124       end Set_Analyzed_Formal;
1125
1126    --  Start of processing for Analyze_Associations
1127
1128    begin
1129       Actuals := Generic_Associations (I_Node);
1130
1131       if Present (Actuals) then
1132
1133          --  Check for an Others choice, indicating a partial parametrization
1134          --  for a formal package.
1135
1136          Actual := First (Actuals);
1137          while Present (Actual) loop
1138             if Nkind (Actual) = N_Others_Choice then
1139                Others_Present := True;
1140
1141                if Present (Next (Actual)) then
1142                   Error_Msg_N ("others must be last association", Actual);
1143                end if;
1144
1145                --  This subprogram is used both for formal packages and for
1146                --  instantiations. For the latter, associations must all be
1147                --  explicit.
1148
1149                if Nkind (I_Node) /= N_Formal_Package_Declaration
1150                  and then Comes_From_Source (I_Node)
1151                then
1152                   Error_Msg_N
1153                     ("others association not allowed in an instance",
1154                       Actual);
1155                end if;
1156
1157                --  In any case, nothing to do after the others association
1158
1159                exit;
1160
1161             elsif Box_Present (Actual)
1162               and then Comes_From_Source (I_Node)
1163               and then Nkind (I_Node) /= N_Formal_Package_Declaration
1164             then
1165                Error_Msg_N
1166                  ("box association not allowed in an instance", Actual);
1167             end if;
1168
1169             Next (Actual);
1170          end loop;
1171
1172          --  If named associations are present, save first named association
1173          --  (it may of course be Empty) to facilitate subsequent name search.
1174
1175          First_Named := First (Actuals);
1176          while Present (First_Named)
1177            and then Nkind (First_Named) /= N_Others_Choice
1178            and then No (Selector_Name (First_Named))
1179          loop
1180             Num_Actuals := Num_Actuals + 1;
1181             Next (First_Named);
1182          end loop;
1183       end if;
1184
1185       Named := First_Named;
1186       while Present (Named) loop
1187          if Nkind (Named) /= N_Others_Choice
1188            and then  No (Selector_Name (Named))
1189          then
1190             Error_Msg_N ("invalid positional actual after named one", Named);
1191             Abandon_Instantiation (Named);
1192          end if;
1193
1194          --  A named association may lack an actual parameter, if it was
1195          --  introduced for a default subprogram that turns out to be local
1196          --  to the outer instantiation.
1197
1198          if Nkind (Named) /= N_Others_Choice
1199            and then Present (Explicit_Generic_Actual_Parameter (Named))
1200          then
1201             Num_Actuals := Num_Actuals + 1;
1202          end if;
1203
1204          Next (Named);
1205       end loop;
1206
1207       if Present (Formals) then
1208          Formal := First_Non_Pragma (Formals);
1209          Analyzed_Formal := First_Non_Pragma (F_Copy);
1210
1211          if Present (Actuals) then
1212             Actual := First (Actuals);
1213
1214          --  All formals should have default values
1215
1216          else
1217             Actual := Empty;
1218          end if;
1219
1220          while Present (Formal) loop
1221             Set_Analyzed_Formal;
1222             Next_Formal := Next_Non_Pragma (Formal);
1223
1224             case Nkind (Formal) is
1225                when N_Formal_Object_Declaration =>
1226                   Match :=
1227                     Matching_Actual (
1228                       Defining_Identifier (Formal),
1229                       Defining_Identifier (Analyzed_Formal));
1230
1231                   if No (Match) and then Partial_Parametrization then
1232                      Process_Default (Formal);
1233                   else
1234                      Append_List
1235                        (Instantiate_Object (Formal, Match, Analyzed_Formal),
1236                         Assoc);
1237                   end if;
1238
1239                when N_Formal_Type_Declaration =>
1240                   Match :=
1241                     Matching_Actual (
1242                       Defining_Identifier (Formal),
1243                       Defining_Identifier (Analyzed_Formal));
1244
1245                   if No (Match) then
1246                      if Partial_Parametrization then
1247                         Process_Default (Formal);
1248
1249                      else
1250                         Error_Msg_Sloc := Sloc (Gen_Unit);
1251                         Error_Msg_NE
1252                           ("missing actual&",
1253                             Instantiation_Node,
1254                               Defining_Identifier (Formal));
1255                         Error_Msg_NE ("\in instantiation of & declared#",
1256                             Instantiation_Node, Gen_Unit);
1257                         Abandon_Instantiation (Instantiation_Node);
1258                      end if;
1259
1260                   else
1261                      Analyze (Match);
1262                      Append_List
1263                        (Instantiate_Type
1264                          (Formal, Match, Analyzed_Formal, Assoc),
1265                        Assoc);
1266
1267                      --  An instantiation is a freeze point for the actuals,
1268                      --  unless this is a rewritten formal package.
1269
1270                      if Nkind (I_Node) /= N_Formal_Package_Declaration then
1271                         Append_Elmt (Entity (Match), Actual_Types);
1272                      end if;
1273                   end if;
1274
1275                   --  A remote access-to-class-wide type must not be an
1276                   --  actual parameter for a generic formal of an access
1277                   --  type (E.2.2 (17)).
1278
1279                   if Nkind (Analyzed_Formal) = N_Formal_Type_Declaration
1280                     and then
1281                       Nkind (Formal_Type_Definition (Analyzed_Formal)) =
1282                                             N_Access_To_Object_Definition
1283                   then
1284                      Validate_Remote_Access_To_Class_Wide_Type (Match);
1285                   end if;
1286
1287                when N_Formal_Subprogram_Declaration =>
1288                   Match :=
1289                     Matching_Actual (
1290                       Defining_Unit_Name (Specification (Formal)),
1291                       Defining_Unit_Name (Specification (Analyzed_Formal)));
1292
1293                   --  If the formal subprogram has the same name as another
1294                   --  formal subprogram of the generic, then a named
1295                   --  association is illegal (12.3(9)). Exclude named
1296                   --  associations that are generated for a nested instance.
1297
1298                   if Present (Match)
1299                     and then Is_Named_Assoc
1300                     and then Comes_From_Source (Found_Assoc)
1301                   then
1302                      Temp_Formal := First (Formals);
1303                      while Present (Temp_Formal) loop
1304                         if Nkind (Temp_Formal) in
1305                              N_Formal_Subprogram_Declaration
1306                           and then Temp_Formal /= Formal
1307                           and then
1308                             Chars (Selector_Name (Found_Assoc)) =
1309                               Chars (Defining_Unit_Name
1310                                        (Specification (Temp_Formal)))
1311                         then
1312                            Error_Msg_N
1313                              ("name not allowed for overloaded formal",
1314                               Found_Assoc);
1315                            Abandon_Instantiation (Instantiation_Node);
1316                         end if;
1317
1318                         Next (Temp_Formal);
1319                      end loop;
1320                   end if;
1321
1322                   --  If there is no corresponding actual, this may be case of
1323                   --  partial parametrization, or else the formal has a default
1324                   --  or a box.
1325
1326                   if No (Match)
1327                     and then  Partial_Parametrization
1328                   then
1329                      Process_Default (Formal);
1330                   else
1331                      Append_To (Assoc,
1332                        Instantiate_Formal_Subprogram
1333                          (Formal, Match, Analyzed_Formal));
1334                   end if;
1335
1336                   --  If this is a nested generic, preserve default for later
1337                   --  instantiations.
1338
1339                   if No (Match)
1340                     and then Box_Present (Formal)
1341                   then
1342                      Append_Elmt
1343                        (Defining_Unit_Name (Specification (Last (Assoc))),
1344                         Default_Actuals);
1345                   end if;
1346
1347                when N_Formal_Package_Declaration =>
1348                   Match :=
1349                     Matching_Actual (
1350                       Defining_Identifier (Formal),
1351                       Defining_Identifier (Original_Node (Analyzed_Formal)));
1352
1353                   if No (Match) then
1354                      if Partial_Parametrization then
1355                         Process_Default (Formal);
1356
1357                      else
1358                         Error_Msg_Sloc := Sloc (Gen_Unit);
1359                         Error_Msg_NE
1360                           ("missing actual&",
1361                             Instantiation_Node, Defining_Identifier (Formal));
1362                         Error_Msg_NE ("\in instantiation of & declared#",
1363                             Instantiation_Node, Gen_Unit);
1364
1365                         Abandon_Instantiation (Instantiation_Node);
1366                      end if;
1367
1368                   else
1369                      Analyze (Match);
1370                      Append_List
1371                        (Instantiate_Formal_Package
1372                          (Formal, Match, Analyzed_Formal),
1373                         Assoc);
1374                   end if;
1375
1376                --  For use type and use package appearing in the generic part,
1377                --  we have already copied them, so we can just move them where
1378                --  they belong (we mustn't recopy them since this would mess up
1379                --  the Sloc values).
1380
1381                when N_Use_Package_Clause |
1382                     N_Use_Type_Clause    =>
1383                   if Nkind (Original_Node (I_Node)) =
1384                     N_Formal_Package_Declaration
1385                   then
1386                      Append (New_Copy_Tree (Formal), Assoc);
1387                   else
1388                      Remove (Formal);
1389                      Append (Formal, Assoc);
1390                   end if;
1391
1392                when others =>
1393                   raise Program_Error;
1394
1395             end case;
1396
1397             Formal := Next_Formal;
1398             Next_Non_Pragma (Analyzed_Formal);
1399          end loop;
1400
1401          if Num_Actuals > Num_Matched then
1402             Error_Msg_Sloc := Sloc (Gen_Unit);
1403
1404             if Present (Selector_Name (Actual)) then
1405                Error_Msg_NE
1406                  ("unmatched actual&",
1407                     Actual, Selector_Name (Actual));
1408                Error_Msg_NE ("\in instantiation of& declared#",
1409                     Actual, Gen_Unit);
1410             else
1411                Error_Msg_NE
1412                  ("unmatched actual in instantiation of& declared#",
1413                    Actual, Gen_Unit);
1414             end if;
1415          end if;
1416
1417       elsif Present (Actuals) then
1418          Error_Msg_N
1419            ("too many actuals in generic instantiation", Instantiation_Node);
1420       end if;
1421
1422       declare
1423          Elmt : Elmt_Id := First_Elmt (Actual_Types);
1424       begin
1425          while Present (Elmt) loop
1426             Freeze_Before (I_Node, Node (Elmt));
1427             Next_Elmt (Elmt);
1428          end loop;
1429       end;
1430
1431       --  If there are default subprograms, normalize the tree by adding
1432       --  explicit associations for them. This is required if the instance
1433       --  appears within a generic.
1434
1435       declare
1436          Elmt  : Elmt_Id;
1437          Subp  : Entity_Id;
1438          New_D : Node_Id;
1439
1440       begin
1441          Elmt := First_Elmt (Default_Actuals);
1442          while Present (Elmt) loop
1443             if No (Actuals) then
1444                Actuals := New_List;
1445                Set_Generic_Associations (I_Node, Actuals);
1446             end if;
1447
1448             Subp := Node (Elmt);
1449             New_D :=
1450               Make_Generic_Association (Sloc (Subp),
1451                 Selector_Name => New_Occurrence_Of (Subp, Sloc (Subp)),
1452                   Explicit_Generic_Actual_Parameter =>
1453                     New_Occurrence_Of (Subp, Sloc (Subp)));
1454             Mark_Rewrite_Insertion (New_D);
1455             Append_To (Actuals, New_D);
1456             Next_Elmt (Elmt);
1457          end loop;
1458       end;
1459
1460       --  If this is a formal package, normalize the parameter list by adding
1461       --  explicit box associations for the formals that are covered by an
1462       --  Others_Choice.
1463
1464       if not Is_Empty_List (Default_Formals) then
1465          Append_List (Default_Formals, Formals);
1466       end if;
1467
1468       return Assoc;
1469    end Analyze_Associations;
1470
1471    -------------------------------
1472    -- Analyze_Formal_Array_Type --
1473    -------------------------------
1474
1475    procedure Analyze_Formal_Array_Type
1476      (T   : in out Entity_Id;
1477       Def : Node_Id)
1478    is
1479       DSS : Node_Id;
1480
1481    begin
1482       --  Treated like a non-generic array declaration, with additional
1483       --  semantic checks.
1484
1485       Enter_Name (T);
1486
1487       if Nkind (Def) = N_Constrained_Array_Definition then
1488          DSS := First (Discrete_Subtype_Definitions (Def));
1489          while Present (DSS) loop
1490             if Nkind_In (DSS, N_Subtype_Indication,
1491                               N_Range,
1492                               N_Attribute_Reference)
1493             then
1494                Error_Msg_N ("only a subtype mark is allowed in a formal", DSS);
1495             end if;
1496
1497             Next (DSS);
1498          end loop;
1499       end if;
1500
1501       Array_Type_Declaration (T, Def);
1502       Set_Is_Generic_Type (Base_Type (T));
1503
1504       if Ekind (Component_Type (T)) = E_Incomplete_Type
1505         and then No (Full_View (Component_Type (T)))
1506       then
1507          Error_Msg_N ("premature usage of incomplete type", Def);
1508
1509       --  Check that range constraint is not allowed on the component type
1510       --  of a generic formal array type (AARM 12.5.3(3))
1511
1512       elsif Is_Internal (Component_Type (T))
1513         and then Present (Subtype_Indication (Component_Definition (Def)))
1514         and then Nkind (Original_Node
1515                          (Subtype_Indication (Component_Definition (Def)))) =
1516                                                          N_Subtype_Indication
1517       then
1518          Error_Msg_N
1519            ("in a formal, a subtype indication can only be "
1520              & "a subtype mark (RM 12.5.3(3))",
1521              Subtype_Indication (Component_Definition (Def)));
1522       end if;
1523
1524    end Analyze_Formal_Array_Type;
1525
1526    ---------------------------------------------
1527    -- Analyze_Formal_Decimal_Fixed_Point_Type --
1528    ---------------------------------------------
1529
1530    --  As for other generic types, we create a valid type representation with
1531    --  legal but arbitrary attributes, whose values are never considered
1532    --  static. For all scalar types we introduce an anonymous base type, with
1533    --  the same attributes. We choose the corresponding integer type to be
1534    --  Standard_Integer.
1535
1536    procedure Analyze_Formal_Decimal_Fixed_Point_Type
1537      (T   : Entity_Id;
1538       Def : Node_Id)
1539    is
1540       Loc       : constant Source_Ptr := Sloc (Def);
1541       Base      : constant Entity_Id :=
1542                     New_Internal_Entity
1543                       (E_Decimal_Fixed_Point_Type,
1544                        Current_Scope, Sloc (Def), 'G');
1545       Int_Base  : constant Entity_Id := Standard_Integer;
1546       Delta_Val : constant Ureal := Ureal_1;
1547       Digs_Val  : constant Uint  := Uint_6;
1548
1549    begin
1550       Enter_Name (T);
1551
1552       Set_Etype          (Base, Base);
1553       Set_Size_Info      (Base, Int_Base);
1554       Set_RM_Size        (Base, RM_Size (Int_Base));
1555       Set_First_Rep_Item (Base, First_Rep_Item (Int_Base));
1556       Set_Digits_Value   (Base, Digs_Val);
1557       Set_Delta_Value    (Base, Delta_Val);
1558       Set_Small_Value    (Base, Delta_Val);
1559       Set_Scalar_Range   (Base,
1560         Make_Range (Loc,
1561           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1562           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1563
1564       Set_Is_Generic_Type (Base);
1565       Set_Parent          (Base, Parent (Def));
1566
1567       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
1568       Set_Etype          (T, Base);
1569       Set_Size_Info      (T, Int_Base);
1570       Set_RM_Size        (T, RM_Size (Int_Base));
1571       Set_First_Rep_Item (T, First_Rep_Item (Int_Base));
1572       Set_Digits_Value   (T, Digs_Val);
1573       Set_Delta_Value    (T, Delta_Val);
1574       Set_Small_Value    (T, Delta_Val);
1575       Set_Scalar_Range   (T, Scalar_Range (Base));
1576       Set_Is_Constrained (T);
1577
1578       Check_Restriction (No_Fixed_Point, Def);
1579    end Analyze_Formal_Decimal_Fixed_Point_Type;
1580
1581    -------------------------------------------
1582    -- Analyze_Formal_Derived_Interface_Type --
1583    -------------------------------------------
1584
1585    procedure Analyze_Formal_Derived_Interface_Type
1586      (N   : Node_Id;
1587       T   : Entity_Id;
1588       Def : Node_Id)
1589    is
1590       Loc   : constant Source_Ptr := Sloc (Def);
1591
1592    begin
1593       --  Rewrite as a type declaration of a derived type. This ensures that
1594       --  the interface list and primitive operations are properly captured.
1595
1596       Rewrite (N,
1597         Make_Full_Type_Declaration (Loc,
1598           Defining_Identifier => T,
1599           Type_Definition     => Def));
1600       Analyze (N);
1601       Set_Is_Generic_Type (T);
1602    end Analyze_Formal_Derived_Interface_Type;
1603
1604    ---------------------------------
1605    -- Analyze_Formal_Derived_Type --
1606    ---------------------------------
1607
1608    procedure Analyze_Formal_Derived_Type
1609      (N   : Node_Id;
1610       T   : Entity_Id;
1611       Def : Node_Id)
1612    is
1613       Loc      : constant Source_Ptr := Sloc (Def);
1614       Unk_Disc : constant Boolean    := Unknown_Discriminants_Present (N);
1615       New_N    : Node_Id;
1616
1617    begin
1618       Set_Is_Generic_Type (T);
1619
1620       if Private_Present (Def) then
1621          New_N :=
1622            Make_Private_Extension_Declaration (Loc,
1623              Defining_Identifier           => T,
1624              Discriminant_Specifications   => Discriminant_Specifications (N),
1625              Unknown_Discriminants_Present => Unk_Disc,
1626              Subtype_Indication            => Subtype_Mark (Def),
1627              Interface_List                => Interface_List (Def));
1628
1629          Set_Abstract_Present     (New_N, Abstract_Present     (Def));
1630          Set_Limited_Present      (New_N, Limited_Present      (Def));
1631          Set_Synchronized_Present (New_N, Synchronized_Present (Def));
1632
1633       else
1634          New_N :=
1635            Make_Full_Type_Declaration (Loc,
1636              Defining_Identifier => T,
1637              Discriminant_Specifications =>
1638                Discriminant_Specifications (Parent (T)),
1639              Type_Definition =>
1640                Make_Derived_Type_Definition (Loc,
1641                  Subtype_Indication => Subtype_Mark (Def)));
1642
1643          Set_Abstract_Present
1644            (Type_Definition (New_N), Abstract_Present (Def));
1645          Set_Limited_Present
1646            (Type_Definition (New_N), Limited_Present  (Def));
1647       end if;
1648
1649       Rewrite (N, New_N);
1650       Analyze (N);
1651
1652       if Unk_Disc then
1653          if not Is_Composite_Type (T) then
1654             Error_Msg_N
1655               ("unknown discriminants not allowed for elementary types", N);
1656          else
1657             Set_Has_Unknown_Discriminants (T);
1658             Set_Is_Constrained (T, False);
1659          end if;
1660       end if;
1661
1662       --  If the parent type has a known size, so does the formal, which makes
1663       --  legal representation clauses that involve the formal.
1664
1665       Set_Size_Known_At_Compile_Time
1666         (T, Size_Known_At_Compile_Time (Entity (Subtype_Mark (Def))));
1667    end Analyze_Formal_Derived_Type;
1668
1669    ----------------------------------
1670    -- Analyze_Formal_Discrete_Type --
1671    ----------------------------------
1672
1673    --  The operations defined for a discrete types are those of an enumeration
1674    --  type. The size is set to an arbitrary value, for use in analyzing the
1675    --  generic unit.
1676
1677    procedure Analyze_Formal_Discrete_Type (T : Entity_Id; Def : Node_Id) is
1678       Loc : constant Source_Ptr := Sloc (Def);
1679       Lo  : Node_Id;
1680       Hi  : Node_Id;
1681
1682       Base : constant Entity_Id :=
1683                New_Internal_Entity
1684                  (E_Floating_Point_Type, Current_Scope, Sloc (Def), 'G');
1685    begin
1686       Enter_Name          (T);
1687       Set_Ekind           (T, E_Enumeration_Subtype);
1688       Set_Etype           (T, Base);
1689       Init_Size           (T, 8);
1690       Init_Alignment      (T);
1691       Set_Is_Generic_Type (T);
1692       Set_Is_Constrained  (T);
1693
1694       --  For semantic analysis, the bounds of the type must be set to some
1695       --  non-static value. The simplest is to create attribute nodes for those
1696       --  bounds, that refer to the type itself. These bounds are never
1697       --  analyzed but serve as place-holders.
1698
1699       Lo :=
1700         Make_Attribute_Reference (Loc,
1701           Attribute_Name => Name_First,
1702           Prefix         => New_Reference_To (T, Loc));
1703       Set_Etype (Lo, T);
1704
1705       Hi :=
1706         Make_Attribute_Reference (Loc,
1707           Attribute_Name => Name_Last,
1708           Prefix         => New_Reference_To (T, Loc));
1709       Set_Etype (Hi, T);
1710
1711       Set_Scalar_Range (T,
1712         Make_Range (Loc,
1713           Low_Bound  => Lo,
1714           High_Bound => Hi));
1715
1716       Set_Ekind           (Base, E_Enumeration_Type);
1717       Set_Etype           (Base, Base);
1718       Init_Size           (Base, 8);
1719       Init_Alignment      (Base);
1720       Set_Is_Generic_Type (Base);
1721       Set_Scalar_Range    (Base, Scalar_Range (T));
1722       Set_Parent          (Base, Parent (Def));
1723    end Analyze_Formal_Discrete_Type;
1724
1725    ----------------------------------
1726    -- Analyze_Formal_Floating_Type --
1727    ---------------------------------
1728
1729    procedure Analyze_Formal_Floating_Type (T : Entity_Id; Def : Node_Id) is
1730       Base : constant Entity_Id :=
1731                New_Internal_Entity
1732                  (E_Floating_Point_Type, Current_Scope, Sloc (Def), 'G');
1733
1734    begin
1735       --  The various semantic attributes are taken from the predefined type
1736       --  Float, just so that all of them are initialized. Their values are
1737       --  never used because no constant folding or expansion takes place in
1738       --  the generic itself.
1739
1740       Enter_Name (T);
1741       Set_Ekind          (T, E_Floating_Point_Subtype);
1742       Set_Etype          (T, Base);
1743       Set_Size_Info      (T,              (Standard_Float));
1744       Set_RM_Size        (T, RM_Size      (Standard_Float));
1745       Set_Digits_Value   (T, Digits_Value (Standard_Float));
1746       Set_Scalar_Range   (T, Scalar_Range (Standard_Float));
1747       Set_Is_Constrained (T);
1748
1749       Set_Is_Generic_Type (Base);
1750       Set_Etype           (Base, Base);
1751       Set_Size_Info       (Base,              (Standard_Float));
1752       Set_RM_Size         (Base, RM_Size      (Standard_Float));
1753       Set_Digits_Value    (Base, Digits_Value (Standard_Float));
1754       Set_Scalar_Range    (Base, Scalar_Range (Standard_Float));
1755       Set_Parent          (Base, Parent (Def));
1756
1757       Check_Restriction (No_Floating_Point, Def);
1758    end Analyze_Formal_Floating_Type;
1759
1760    -----------------------------------
1761    -- Analyze_Formal_Interface_Type;--
1762    -----------------------------------
1763
1764    procedure Analyze_Formal_Interface_Type
1765       (N   : Node_Id;
1766        T   : Entity_Id;
1767        Def : Node_Id)
1768    is
1769       Loc   : constant Source_Ptr := Sloc (N);
1770       New_N : Node_Id;
1771
1772    begin
1773       New_N :=
1774         Make_Full_Type_Declaration (Loc,
1775           Defining_Identifier => T,
1776           Type_Definition => Def);
1777
1778       Rewrite (N, New_N);
1779       Analyze (N);
1780       Set_Is_Generic_Type (T);
1781    end Analyze_Formal_Interface_Type;
1782
1783    ---------------------------------
1784    -- Analyze_Formal_Modular_Type --
1785    ---------------------------------
1786
1787    procedure Analyze_Formal_Modular_Type (T : Entity_Id; Def : Node_Id) is
1788    begin
1789       --  Apart from their entity kind, generic modular types are treated like
1790       --  signed integer types, and have the same attributes.
1791
1792       Analyze_Formal_Signed_Integer_Type (T, Def);
1793       Set_Ekind (T, E_Modular_Integer_Subtype);
1794       Set_Ekind (Etype (T), E_Modular_Integer_Type);
1795
1796    end Analyze_Formal_Modular_Type;
1797
1798    ---------------------------------------
1799    -- Analyze_Formal_Object_Declaration --
1800    ---------------------------------------
1801
1802    procedure Analyze_Formal_Object_Declaration (N : Node_Id) is
1803       E  : constant Node_Id := Default_Expression (N);
1804       Id : constant Node_Id := Defining_Identifier (N);
1805       K  : Entity_Kind;
1806       T  : Node_Id;
1807
1808    begin
1809       Enter_Name (Id);
1810
1811       --  Determine the mode of the formal object
1812
1813       if Out_Present (N) then
1814          K := E_Generic_In_Out_Parameter;
1815
1816          if not In_Present (N) then
1817             Error_Msg_N ("formal generic objects cannot have mode OUT", N);
1818          end if;
1819
1820       else
1821          K := E_Generic_In_Parameter;
1822       end if;
1823
1824       if Present (Subtype_Mark (N)) then
1825          Find_Type (Subtype_Mark (N));
1826          T := Entity (Subtype_Mark (N));
1827
1828          --  Verify that there is no redundant null exclusion
1829
1830          if Null_Exclusion_Present (N) then
1831             if not Is_Access_Type (T) then
1832                Error_Msg_N
1833                  ("null exclusion can only apply to an access type", N);
1834
1835             elsif Can_Never_Be_Null (T) then
1836                Error_Msg_NE
1837                  ("`NOT NULL` not allowed (& already excludes null)",
1838                     N, T);
1839             end if;
1840          end if;
1841
1842       --  Ada 2005 (AI-423): Formal object with an access definition
1843
1844       else
1845          Check_Access_Definition (N);
1846          T := Access_Definition
1847                 (Related_Nod => N,
1848                  N           => Access_Definition (N));
1849       end if;
1850
1851       if Ekind (T) = E_Incomplete_Type then
1852          declare
1853             Error_Node : Node_Id;
1854
1855          begin
1856             if Present (Subtype_Mark (N)) then
1857                Error_Node := Subtype_Mark (N);
1858             else
1859                Check_Access_Definition (N);
1860                Error_Node := Access_Definition (N);
1861             end if;
1862
1863             Error_Msg_N ("premature usage of incomplete type", Error_Node);
1864          end;
1865       end if;
1866
1867       if K = E_Generic_In_Parameter then
1868
1869          --  Ada 2005 (AI-287): Limited aggregates allowed in generic formals
1870
1871          if Ada_Version < Ada_2005 and then Is_Limited_Type (T) then
1872             Error_Msg_N
1873               ("generic formal of mode IN must not be of limited type", N);
1874             Explain_Limited_Type (T, N);
1875          end if;
1876
1877          if Is_Abstract_Type (T) then
1878             Error_Msg_N
1879               ("generic formal of mode IN must not be of abstract type", N);
1880          end if;
1881
1882          if Present (E) then
1883             Preanalyze_Spec_Expression (E, T);
1884
1885             if Is_Limited_Type (T) and then not OK_For_Limited_Init (T, E) then
1886                Error_Msg_N
1887                  ("initialization not allowed for limited types", E);
1888                Explain_Limited_Type (T, E);
1889             end if;
1890          end if;
1891
1892          Set_Ekind (Id, K);
1893          Set_Etype (Id, T);
1894
1895       --  Case of generic IN OUT parameter
1896
1897       else
1898          --  If the formal has an unconstrained type, construct its actual
1899          --  subtype, as is done for subprogram formals. In this fashion, all
1900          --  its uses can refer to specific bounds.
1901
1902          Set_Ekind (Id, K);
1903          Set_Etype (Id, T);
1904
1905          if (Is_Array_Type (T)
1906               and then not Is_Constrained (T))
1907            or else
1908             (Ekind (T) = E_Record_Type
1909               and then Has_Discriminants (T))
1910          then
1911             declare
1912                Non_Freezing_Ref : constant Node_Id :=
1913                                     New_Reference_To (Id, Sloc (Id));
1914                Decl : Node_Id;
1915
1916             begin
1917                --  Make sure the actual subtype doesn't generate bogus freezing
1918
1919                Set_Must_Not_Freeze (Non_Freezing_Ref);
1920                Decl := Build_Actual_Subtype (T, Non_Freezing_Ref);
1921                Insert_Before_And_Analyze (N, Decl);
1922                Set_Actual_Subtype (Id, Defining_Identifier (Decl));
1923             end;
1924          else
1925             Set_Actual_Subtype (Id, T);
1926          end if;
1927
1928          if Present (E) then
1929             Error_Msg_N
1930               ("initialization not allowed for `IN OUT` formals", N);
1931          end if;
1932       end if;
1933
1934       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
1935    end Analyze_Formal_Object_Declaration;
1936
1937    ----------------------------------------------
1938    -- Analyze_Formal_Ordinary_Fixed_Point_Type --
1939    ----------------------------------------------
1940
1941    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
1942      (T   : Entity_Id;
1943       Def : Node_Id)
1944    is
1945       Loc  : constant Source_Ptr := Sloc (Def);
1946       Base : constant Entity_Id :=
1947                New_Internal_Entity
1948                  (E_Ordinary_Fixed_Point_Type, Current_Scope, Sloc (Def), 'G');
1949    begin
1950       --  The semantic attributes are set for completeness only, their values
1951       --  will never be used, since all properties of the type are non-static.
1952
1953       Enter_Name (T);
1954       Set_Ekind            (T, E_Ordinary_Fixed_Point_Subtype);
1955       Set_Etype            (T, Base);
1956       Set_Size_Info        (T, Standard_Integer);
1957       Set_RM_Size          (T, RM_Size (Standard_Integer));
1958       Set_Small_Value      (T, Ureal_1);
1959       Set_Delta_Value      (T, Ureal_1);
1960       Set_Scalar_Range     (T,
1961         Make_Range (Loc,
1962           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1963           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1964       Set_Is_Constrained   (T);
1965
1966       Set_Is_Generic_Type (Base);
1967       Set_Etype           (Base, Base);
1968       Set_Size_Info       (Base, Standard_Integer);
1969       Set_RM_Size         (Base, RM_Size (Standard_Integer));
1970       Set_Small_Value     (Base, Ureal_1);
1971       Set_Delta_Value     (Base, Ureal_1);
1972       Set_Scalar_Range    (Base, Scalar_Range (T));
1973       Set_Parent          (Base, Parent (Def));
1974
1975       Check_Restriction (No_Fixed_Point, Def);
1976    end Analyze_Formal_Ordinary_Fixed_Point_Type;
1977
1978    ----------------------------------------
1979    -- Analyze_Formal_Package_Declaration --
1980    ----------------------------------------
1981
1982    procedure Analyze_Formal_Package_Declaration (N : Node_Id) is
1983       Loc              : constant Source_Ptr := Sloc (N);
1984       Pack_Id          : constant Entity_Id  := Defining_Identifier (N);
1985       Formal           : Entity_Id;
1986       Gen_Id           : constant Node_Id    := Name (N);
1987       Gen_Decl         : Node_Id;
1988       Gen_Unit         : Entity_Id;
1989       New_N            : Node_Id;
1990       Parent_Installed : Boolean := False;
1991       Renaming         : Node_Id;
1992       Parent_Instance  : Entity_Id;
1993       Renaming_In_Par  : Entity_Id;
1994       No_Associations  : Boolean := False;
1995
1996       function Build_Local_Package return Node_Id;
1997       --  The formal package is rewritten so that its parameters are replaced
1998       --  with corresponding declarations. For parameters with bona fide
1999       --  associations these declarations are created by Analyze_Associations
2000       --  as for a regular instantiation. For boxed parameters, we preserve
2001       --  the formal declarations and analyze them, in order to introduce
2002       --  entities of the right kind in the environment of the formal.
2003
2004       -------------------------
2005       -- Build_Local_Package --
2006       -------------------------
2007
2008       function Build_Local_Package return Node_Id is
2009          Decls     : List_Id;
2010          Pack_Decl : Node_Id;
2011
2012       begin
2013          --  Within the formal, the name of the generic package is a renaming
2014          --  of the formal (as for a regular instantiation).
2015
2016          Pack_Decl :=
2017            Make_Package_Declaration (Loc,
2018              Specification =>
2019                Copy_Generic_Node
2020                  (Specification (Original_Node (Gen_Decl)),
2021                     Empty, Instantiating => True));
2022
2023          Renaming := Make_Package_Renaming_Declaration (Loc,
2024              Defining_Unit_Name =>
2025                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
2026              Name => New_Occurrence_Of (Formal, Loc));
2027
2028          if Nkind (Gen_Id) = N_Identifier
2029            and then Chars (Gen_Id) = Chars (Pack_Id)
2030          then
2031             Error_Msg_NE
2032               ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
2033          end if;
2034
2035          --  If the formal is declared with a box, or with an others choice,
2036          --  create corresponding declarations for all entities in the formal
2037          --  part, so that names with the proper types are available in the
2038          --  specification of the formal package.
2039
2040          --  On the other hand, if there are no associations, then all the
2041          --  formals must have defaults, and this will be checked by the
2042          --  call to Analyze_Associations.
2043
2044          if Box_Present (N)
2045            or else Nkind (First (Generic_Associations (N))) = N_Others_Choice
2046          then
2047             declare
2048                Formal_Decl : Node_Id;
2049
2050             begin
2051                --  TBA : for a formal package, need to recurse ???
2052
2053                Decls := New_List;
2054                Formal_Decl :=
2055                  First
2056                    (Generic_Formal_Declarations (Original_Node (Gen_Decl)));
2057                while Present (Formal_Decl) loop
2058                   Append_To
2059                     (Decls, Copy_Generic_Node (Formal_Decl, Empty, True));
2060                   Next (Formal_Decl);
2061                end loop;
2062             end;
2063
2064          --  If generic associations are present, use Analyze_Associations to
2065          --  create the proper renaming declarations.
2066
2067          else
2068             declare
2069                Act_Tree : constant Node_Id :=
2070                             Copy_Generic_Node
2071                               (Original_Node (Gen_Decl), Empty,
2072                                Instantiating => True);
2073
2074             begin
2075                Generic_Renamings.Set_Last (0);
2076                Generic_Renamings_HTable.Reset;
2077                Instantiation_Node := N;
2078
2079                Decls :=
2080                  Analyze_Associations
2081                    (Original_Node (N),
2082                       Generic_Formal_Declarations (Act_Tree),
2083                       Generic_Formal_Declarations (Gen_Decl));
2084             end;
2085          end if;
2086
2087          Append (Renaming, To => Decls);
2088
2089          --  Add generated declarations ahead of local declarations in
2090          --  the package.
2091
2092          if No (Visible_Declarations (Specification (Pack_Decl))) then
2093             Set_Visible_Declarations (Specification (Pack_Decl), Decls);
2094          else
2095             Insert_List_Before
2096               (First (Visible_Declarations (Specification (Pack_Decl))),
2097                  Decls);
2098          end if;
2099
2100          return Pack_Decl;
2101       end Build_Local_Package;
2102
2103    --  Start of processing for Analyze_Formal_Package
2104
2105    begin
2106       Text_IO_Kludge (Gen_Id);
2107
2108       Init_Env;
2109       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
2110       Gen_Unit := Entity (Gen_Id);
2111
2112       --  Check for a formal package that is a package renaming
2113
2114       if Present (Renamed_Object (Gen_Unit)) then
2115
2116          --  Indicate that unit is used, before replacing it with renamed
2117          --  entity for use below.
2118
2119          if In_Extended_Main_Source_Unit (N) then
2120             Set_Is_Instantiated (Gen_Unit);
2121             Generate_Reference  (Gen_Unit, N);
2122          end if;
2123
2124          Gen_Unit := Renamed_Object (Gen_Unit);
2125       end if;
2126
2127       if Ekind (Gen_Unit) /= E_Generic_Package then
2128          Error_Msg_N ("expect generic package name", Gen_Id);
2129          Restore_Env;
2130          goto Leave;
2131
2132       elsif  Gen_Unit = Current_Scope then
2133          Error_Msg_N
2134            ("generic package cannot be used as a formal package of itself",
2135              Gen_Id);
2136          Restore_Env;
2137          goto Leave;
2138
2139       elsif In_Open_Scopes (Gen_Unit) then
2140          if Is_Compilation_Unit (Gen_Unit)
2141            and then Is_Child_Unit (Current_Scope)
2142          then
2143             --  Special-case the error when the formal is a parent, and
2144             --  continue analysis to minimize cascaded errors.
2145
2146             Error_Msg_N
2147               ("generic parent cannot be used as formal package "
2148                 & "of a child unit",
2149                 Gen_Id);
2150
2151          else
2152             Error_Msg_N
2153               ("generic package cannot be used as a formal package "
2154                 & "within itself",
2155                 Gen_Id);
2156             Restore_Env;
2157             goto Leave;
2158          end if;
2159       end if;
2160
2161       if Box_Present (N)
2162         or else No (Generic_Associations (N))
2163         or else Nkind (First (Generic_Associations (N))) = N_Others_Choice
2164       then
2165          No_Associations := True;
2166       end if;
2167
2168       --  If there are no generic associations, the generic parameters appear
2169       --  as local entities and are instantiated like them. We copy the generic
2170       --  package declaration as if it were an instantiation, and analyze it
2171       --  like a regular package, except that we treat the formals as
2172       --  additional visible components.
2173
2174       Gen_Decl := Unit_Declaration_Node (Gen_Unit);
2175
2176       if In_Extended_Main_Source_Unit (N) then
2177          Set_Is_Instantiated (Gen_Unit);
2178          Generate_Reference  (Gen_Unit, N);
2179       end if;
2180
2181       Formal := New_Copy (Pack_Id);
2182       Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
2183
2184       begin
2185          --  Make local generic without formals. The formals will be replaced
2186          --  with internal declarations.
2187
2188          New_N := Build_Local_Package;
2189
2190          --  If there are errors in the parameter list, Analyze_Associations
2191          --  raises Instantiation_Error. Patch the declaration to prevent
2192          --  further exception propagation.
2193
2194       exception
2195          when Instantiation_Error =>
2196
2197             Enter_Name (Formal);
2198             Set_Ekind  (Formal, E_Variable);
2199             Set_Etype  (Formal, Any_Type);
2200
2201             if Parent_Installed then
2202                Remove_Parent;
2203             end if;
2204
2205             goto Leave;
2206       end;
2207
2208       Rewrite (N, New_N);
2209       Set_Defining_Unit_Name (Specification (New_N), Formal);
2210       Set_Generic_Parent (Specification (N), Gen_Unit);
2211       Set_Instance_Env (Gen_Unit, Formal);
2212       Set_Is_Generic_Instance (Formal);
2213
2214       Enter_Name (Formal);
2215       Set_Ekind  (Formal, E_Package);
2216       Set_Etype  (Formal, Standard_Void_Type);
2217       Set_Inner_Instances (Formal, New_Elmt_List);
2218       Push_Scope  (Formal);
2219
2220       if Is_Child_Unit (Gen_Unit)
2221         and then Parent_Installed
2222       then
2223          --  Similarly, we have to make the name of the formal visible in the
2224          --  parent instance, to resolve properly fully qualified names that
2225          --  may appear in the generic unit. The parent instance has been
2226          --  placed on the scope stack ahead of the current scope.
2227
2228          Parent_Instance := Scope_Stack.Table (Scope_Stack.Last - 1).Entity;
2229
2230          Renaming_In_Par :=
2231            Make_Defining_Identifier (Loc, Chars (Gen_Unit));
2232          Set_Ekind (Renaming_In_Par, E_Package);
2233          Set_Etype (Renaming_In_Par, Standard_Void_Type);
2234          Set_Scope (Renaming_In_Par, Parent_Instance);
2235          Set_Parent (Renaming_In_Par, Parent (Formal));
2236          Set_Renamed_Object (Renaming_In_Par, Formal);
2237          Append_Entity (Renaming_In_Par, Parent_Instance);
2238       end if;
2239
2240       Analyze (Specification (N));
2241
2242       --  The formals for which associations are provided are not visible
2243       --  outside of the formal package. The others are still declared by a
2244       --  formal parameter declaration.
2245
2246       if not No_Associations then
2247          declare
2248             E : Entity_Id;
2249
2250          begin
2251             E := First_Entity (Formal);
2252             while Present (E) loop
2253                exit when Ekind (E) = E_Package
2254                  and then Renamed_Entity (E) = Formal;
2255
2256                if not Is_Generic_Formal (E) then
2257                   Set_Is_Hidden (E);
2258                end if;
2259
2260                Next_Entity (E);
2261             end loop;
2262          end;
2263       end if;
2264
2265       End_Package_Scope (Formal);
2266
2267       if Parent_Installed then
2268          Remove_Parent;
2269       end if;
2270
2271       Restore_Env;
2272
2273       --  Inside the generic unit, the formal package is a regular package, but
2274       --  no body is needed for it. Note that after instantiation, the defining
2275       --  unit name we need is in the new tree and not in the original (see
2276       --  Package_Instantiation). A generic formal package is an instance, and
2277       --  can be used as an actual for an inner instance.
2278
2279       Set_Has_Completion (Formal, True);
2280
2281       --  Add semantic information to the original defining identifier.
2282       --  for ASIS use.
2283
2284       Set_Ekind (Pack_Id, E_Package);
2285       Set_Etype (Pack_Id, Standard_Void_Type);
2286       Set_Scope (Pack_Id, Scope (Formal));
2287       Set_Has_Completion (Pack_Id, True);
2288
2289       <<Leave>>
2290          Analyze_Aspect_Specifications (N, Pack_Id, Aspect_Specifications (N));
2291    end Analyze_Formal_Package_Declaration;
2292
2293    ---------------------------------
2294    -- Analyze_Formal_Private_Type --
2295    ---------------------------------
2296
2297    procedure Analyze_Formal_Private_Type
2298      (N   : Node_Id;
2299       T   : Entity_Id;
2300       Def : Node_Id)
2301    is
2302    begin
2303       New_Private_Type (N, T, Def);
2304
2305       --  Set the size to an arbitrary but legal value
2306
2307       Set_Size_Info (T, Standard_Integer);
2308       Set_RM_Size   (T, RM_Size (Standard_Integer));
2309    end Analyze_Formal_Private_Type;
2310
2311    ----------------------------------------
2312    -- Analyze_Formal_Signed_Integer_Type --
2313    ----------------------------------------
2314
2315    procedure Analyze_Formal_Signed_Integer_Type
2316      (T   : Entity_Id;
2317       Def : Node_Id)
2318    is
2319       Base : constant Entity_Id :=
2320                New_Internal_Entity
2321                  (E_Signed_Integer_Type, Current_Scope, Sloc (Def), 'G');
2322
2323    begin
2324       Enter_Name (T);
2325
2326       Set_Ekind          (T, E_Signed_Integer_Subtype);
2327       Set_Etype          (T, Base);
2328       Set_Size_Info      (T, Standard_Integer);
2329       Set_RM_Size        (T, RM_Size (Standard_Integer));
2330       Set_Scalar_Range   (T, Scalar_Range (Standard_Integer));
2331       Set_Is_Constrained (T);
2332
2333       Set_Is_Generic_Type (Base);
2334       Set_Size_Info       (Base, Standard_Integer);
2335       Set_RM_Size         (Base, RM_Size (Standard_Integer));
2336       Set_Etype           (Base, Base);
2337       Set_Scalar_Range    (Base, Scalar_Range (Standard_Integer));
2338       Set_Parent          (Base, Parent (Def));
2339    end Analyze_Formal_Signed_Integer_Type;
2340
2341    -------------------------------------------
2342    -- Analyze_Formal_Subprogram_Declaration --
2343    -------------------------------------------
2344
2345    procedure Analyze_Formal_Subprogram_Declaration (N : Node_Id) is
2346       Spec : constant Node_Id   := Specification (N);
2347       Def  : constant Node_Id   := Default_Name (N);
2348       Nam  : constant Entity_Id := Defining_Unit_Name (Spec);
2349       Subp : Entity_Id;
2350
2351    begin
2352       if Nam = Error then
2353          return;
2354       end if;
2355
2356       if Nkind (Nam) = N_Defining_Program_Unit_Name then
2357          Error_Msg_N ("name of formal subprogram must be a direct name", Nam);
2358          goto Leave;
2359       end if;
2360
2361       Analyze_Subprogram_Declaration (N);
2362       Set_Is_Formal_Subprogram (Nam);
2363       Set_Has_Completion (Nam);
2364
2365       if Nkind (N) = N_Formal_Abstract_Subprogram_Declaration then
2366          Set_Is_Abstract_Subprogram (Nam);
2367          Set_Is_Dispatching_Operation (Nam);
2368
2369          declare
2370             Ctrl_Type : constant Entity_Id := Find_Dispatching_Type (Nam);
2371          begin
2372             if No (Ctrl_Type) then
2373                Error_Msg_N
2374                  ("abstract formal subprogram must have a controlling type",
2375                   N);
2376             else
2377                Check_Controlling_Formals (Ctrl_Type, Nam);
2378             end if;
2379          end;
2380       end if;
2381
2382       --  Default name is resolved at the point of instantiation
2383
2384       if Box_Present (N) then
2385          null;
2386
2387       --  Else default is bound at the point of generic declaration
2388
2389       elsif Present (Def) then
2390          if Nkind (Def) = N_Operator_Symbol then
2391             Find_Direct_Name (Def);
2392
2393          elsif Nkind (Def) /= N_Attribute_Reference then
2394             Analyze (Def);
2395
2396          else
2397             --  For an attribute reference, analyze the prefix and verify
2398             --  that it has the proper profile for the subprogram.
2399
2400             Analyze (Prefix (Def));
2401             Valid_Default_Attribute (Nam, Def);
2402             goto Leave;
2403          end if;
2404
2405          --  Default name may be overloaded, in which case the interpretation
2406          --  with the correct profile must be  selected, as for a renaming.
2407          --  If the definition is an indexed component, it must denote a
2408          --  member of an entry family. If it is a selected component, it
2409          --  can be a protected operation.
2410
2411          if Etype (Def) = Any_Type then
2412             goto Leave;
2413
2414          elsif Nkind (Def) = N_Selected_Component then
2415             if not Is_Overloadable (Entity (Selector_Name (Def))) then
2416                Error_Msg_N ("expect valid subprogram name as default", Def);
2417             end if;
2418
2419          elsif Nkind (Def) = N_Indexed_Component then
2420             if Is_Entity_Name (Prefix (Def)) then
2421                if Ekind (Entity (Prefix (Def))) /= E_Entry_Family then
2422                   Error_Msg_N ("expect valid subprogram name as default", Def);
2423                end if;
2424
2425             elsif Nkind (Prefix (Def)) = N_Selected_Component then
2426                if Ekind (Entity (Selector_Name (Prefix (Def)))) /=
2427                                                           E_Entry_Family
2428                then
2429                   Error_Msg_N ("expect valid subprogram name as default", Def);
2430                end if;
2431
2432             else
2433                Error_Msg_N ("expect valid subprogram name as default", Def);
2434                goto Leave;
2435             end if;
2436
2437          elsif Nkind (Def) = N_Character_Literal then
2438
2439             --  Needs some type checks: subprogram should be parameterless???
2440
2441             Resolve (Def, (Etype (Nam)));
2442
2443          elsif not Is_Entity_Name (Def)
2444            or else not Is_Overloadable (Entity (Def))
2445          then
2446             Error_Msg_N ("expect valid subprogram name as default", Def);
2447             goto Leave;
2448
2449          elsif not Is_Overloaded (Def) then
2450             Subp := Entity (Def);
2451
2452             if Subp = Nam then
2453                Error_Msg_N ("premature usage of formal subprogram", Def);
2454
2455             elsif not Entity_Matches_Spec (Subp, Nam) then
2456                Error_Msg_N ("no visible entity matches specification", Def);
2457             end if;
2458
2459          --  More than one interpretation, so disambiguate as for a renaming
2460
2461          else
2462             declare
2463                I   : Interp_Index;
2464                I1  : Interp_Index := 0;
2465                It  : Interp;
2466                It1 : Interp;
2467
2468             begin
2469                Subp := Any_Id;
2470                Get_First_Interp (Def, I, It);
2471                while Present (It.Nam) loop
2472                   if Entity_Matches_Spec (It.Nam, Nam) then
2473                      if Subp /= Any_Id then
2474                         It1 := Disambiguate (Def, I1, I, Etype (Subp));
2475
2476                         if It1 = No_Interp then
2477                            Error_Msg_N ("ambiguous default subprogram", Def);
2478                         else
2479                            Subp := It1.Nam;
2480                         end if;
2481
2482                         exit;
2483
2484                      else
2485                         I1  := I;
2486                         Subp := It.Nam;
2487                      end if;
2488                   end if;
2489
2490                   Get_Next_Interp (I, It);
2491                end loop;
2492             end;
2493
2494             if Subp /= Any_Id then
2495                Set_Entity (Def, Subp);
2496
2497                if Subp = Nam then
2498                   Error_Msg_N ("premature usage of formal subprogram", Def);
2499
2500                elsif Ekind (Subp) /= E_Operator then
2501                   Check_Mode_Conformant (Subp, Nam);
2502                end if;
2503
2504             else
2505                Error_Msg_N ("no visible subprogram matches specification", N);
2506             end if;
2507          end if;
2508       end if;
2509
2510       <<Leave>>
2511          Analyze_Aspect_Specifications (N, Nam, Aspect_Specifications (N));
2512    end Analyze_Formal_Subprogram_Declaration;
2513
2514    -------------------------------------
2515    -- Analyze_Formal_Type_Declaration --
2516    -------------------------------------
2517
2518    procedure Analyze_Formal_Type_Declaration (N : Node_Id) is
2519       Def : constant Node_Id := Formal_Type_Definition (N);
2520       T   : Entity_Id;
2521
2522    begin
2523       T := Defining_Identifier (N);
2524
2525       if Present (Discriminant_Specifications (N))
2526         and then Nkind (Def) /= N_Formal_Private_Type_Definition
2527       then
2528          Error_Msg_N
2529            ("discriminants not allowed for this formal type", T);
2530       end if;
2531
2532       --  Enter the new name, and branch to specific routine
2533
2534       case Nkind (Def) is
2535          when N_Formal_Private_Type_Definition         =>
2536             Analyze_Formal_Private_Type (N, T, Def);
2537
2538          when N_Formal_Derived_Type_Definition         =>
2539             Analyze_Formal_Derived_Type (N, T, Def);
2540
2541          when N_Formal_Discrete_Type_Definition        =>
2542             Analyze_Formal_Discrete_Type (T, Def);
2543
2544          when N_Formal_Signed_Integer_Type_Definition  =>
2545             Analyze_Formal_Signed_Integer_Type (T, Def);
2546
2547          when N_Formal_Modular_Type_Definition         =>
2548             Analyze_Formal_Modular_Type (T, Def);
2549
2550          when N_Formal_Floating_Point_Definition       =>
2551             Analyze_Formal_Floating_Type (T, Def);
2552
2553          when N_Formal_Ordinary_Fixed_Point_Definition =>
2554             Analyze_Formal_Ordinary_Fixed_Point_Type (T, Def);
2555
2556          when N_Formal_Decimal_Fixed_Point_Definition  =>
2557             Analyze_Formal_Decimal_Fixed_Point_Type (T, Def);
2558
2559          when N_Array_Type_Definition =>
2560             Analyze_Formal_Array_Type (T, Def);
2561
2562          when N_Access_To_Object_Definition            |
2563               N_Access_Function_Definition             |
2564               N_Access_Procedure_Definition            =>
2565             Analyze_Generic_Access_Type (T, Def);
2566
2567          --  Ada 2005: a interface declaration is encoded as an abstract
2568          --  record declaration or a abstract type derivation.
2569
2570          when N_Record_Definition                      =>
2571             Analyze_Formal_Interface_Type (N, T, Def);
2572
2573          when N_Derived_Type_Definition                =>
2574             Analyze_Formal_Derived_Interface_Type (N, T, Def);
2575
2576          when N_Error                                  =>
2577             null;
2578
2579          when others                                   =>
2580             raise Program_Error;
2581
2582       end case;
2583
2584       Set_Is_Generic_Type (T);
2585       Analyze_Aspect_Specifications (N, T, Aspect_Specifications (N));
2586    end Analyze_Formal_Type_Declaration;
2587
2588    ------------------------------------
2589    -- Analyze_Function_Instantiation --
2590    ------------------------------------
2591
2592    procedure Analyze_Function_Instantiation (N : Node_Id) is
2593    begin
2594       Analyze_Subprogram_Instantiation (N, E_Function);
2595    end Analyze_Function_Instantiation;
2596
2597    ---------------------------------
2598    -- Analyze_Generic_Access_Type --
2599    ---------------------------------
2600
2601    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id) is
2602    begin
2603       Enter_Name (T);
2604
2605       if Nkind (Def) = N_Access_To_Object_Definition then
2606          Access_Type_Declaration (T, Def);
2607
2608          if Is_Incomplete_Or_Private_Type (Designated_Type (T))
2609            and then No (Full_View (Designated_Type (T)))
2610            and then not Is_Generic_Type (Designated_Type (T))
2611          then
2612             Error_Msg_N ("premature usage of incomplete type", Def);
2613
2614          elsif not Is_Entity_Name (Subtype_Indication (Def)) then
2615             Error_Msg_N
2616               ("only a subtype mark is allowed in a formal", Def);
2617          end if;
2618
2619       else
2620          Access_Subprogram_Declaration (T, Def);
2621       end if;
2622    end Analyze_Generic_Access_Type;
2623
2624    ---------------------------------
2625    -- Analyze_Generic_Formal_Part --
2626    ---------------------------------
2627
2628    procedure Analyze_Generic_Formal_Part (N : Node_Id) is
2629       Gen_Parm_Decl : Node_Id;
2630
2631    begin
2632       --  The generic formals are processed in the scope of the generic unit,
2633       --  where they are immediately visible. The scope is installed by the
2634       --  caller.
2635
2636       Gen_Parm_Decl := First (Generic_Formal_Declarations (N));
2637
2638       while Present (Gen_Parm_Decl) loop
2639          Analyze (Gen_Parm_Decl);
2640          Next (Gen_Parm_Decl);
2641       end loop;
2642
2643       Generate_Reference_To_Generic_Formals (Current_Scope);
2644    end Analyze_Generic_Formal_Part;
2645
2646    ------------------------------------------
2647    -- Analyze_Generic_Package_Declaration  --
2648    ------------------------------------------
2649
2650    procedure Analyze_Generic_Package_Declaration (N : Node_Id) is
2651       Loc         : constant Source_Ptr := Sloc (N);
2652       Id          : Entity_Id;
2653       New_N       : Node_Id;
2654       Save_Parent : Node_Id;
2655       Renaming    : Node_Id;
2656       Decls       : constant List_Id :=
2657                       Visible_Declarations (Specification (N));
2658       Decl        : Node_Id;
2659
2660    begin
2661       --  We introduce a renaming of the enclosing package, to have a usable
2662       --  entity as the prefix of an expanded name for a local entity of the
2663       --  form Par.P.Q, where P is the generic package. This is because a local
2664       --  entity named P may hide it, so that the usual visibility rules in
2665       --  the instance will not resolve properly.
2666
2667       Renaming :=
2668         Make_Package_Renaming_Declaration (Loc,
2669           Defining_Unit_Name =>
2670             Make_Defining_Identifier (Loc,
2671              Chars => New_External_Name (Chars (Defining_Entity (N)), "GH")),
2672           Name => Make_Identifier (Loc, Chars (Defining_Entity (N))));
2673
2674       if Present (Decls) then
2675          Decl := First (Decls);
2676          while Present (Decl)
2677            and then Nkind (Decl) = N_Pragma
2678          loop
2679             Next (Decl);
2680          end loop;
2681
2682          if Present (Decl) then
2683             Insert_Before (Decl, Renaming);
2684          else
2685             Append (Renaming, Visible_Declarations (Specification (N)));
2686          end if;
2687
2688       else
2689          Set_Visible_Declarations (Specification (N), New_List (Renaming));
2690       end if;
2691
2692       --  Create copy of generic unit, and save for instantiation. If the unit
2693       --  is a child unit, do not copy the specifications for the parent, which
2694       --  are not part of the generic tree.
2695
2696       Save_Parent := Parent_Spec (N);
2697       Set_Parent_Spec (N, Empty);
2698
2699       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2700       Set_Parent_Spec (New_N, Save_Parent);
2701       Rewrite (N, New_N);
2702       Id := Defining_Entity (N);
2703       Generate_Definition (Id);
2704
2705       --  Expansion is not applied to generic units
2706
2707       Start_Generic;
2708
2709       Enter_Name (Id);
2710       Set_Ekind (Id, E_Generic_Package);
2711       Set_Etype (Id, Standard_Void_Type);
2712       Push_Scope (Id);
2713       Enter_Generic_Scope (Id);
2714       Set_Inner_Instances (Id, New_Elmt_List);
2715
2716       Set_Categorization_From_Pragmas (N);
2717       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2718
2719       --  Link the declaration of the generic homonym in the generic copy to
2720       --  the package it renames, so that it is always resolved properly.
2721
2722       Set_Generic_Homonym (Id, Defining_Unit_Name (Renaming));
2723       Set_Entity (Associated_Node (Name (Renaming)), Id);
2724
2725       --  For a library unit, we have reconstructed the entity for the unit,
2726       --  and must reset it in the library tables.
2727
2728       if Nkind (Parent (N)) = N_Compilation_Unit then
2729          Set_Cunit_Entity (Current_Sem_Unit, Id);
2730       end if;
2731
2732       Analyze_Generic_Formal_Part (N);
2733
2734       --  After processing the generic formals, analysis proceeds as for a
2735       --  non-generic package.
2736
2737       Analyze (Specification (N));
2738
2739       Validate_Categorization_Dependency (N, Id);
2740
2741       End_Generic;
2742
2743       End_Package_Scope (Id);
2744       Exit_Generic_Scope (Id);
2745
2746       if Nkind (Parent (N)) /= N_Compilation_Unit then
2747          Move_Freeze_Nodes (Id, N, Visible_Declarations (Specification (N)));
2748          Move_Freeze_Nodes (Id, N, Private_Declarations (Specification (N)));
2749          Move_Freeze_Nodes (Id, N, Generic_Formal_Declarations (N));
2750
2751       else
2752          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2753          Validate_RT_RAT_Component (N);
2754
2755          --  If this is a spec without a body, check that generic parameters
2756          --  are referenced.
2757
2758          if not Body_Required (Parent (N)) then
2759             Check_References (Id);
2760          end if;
2761       end if;
2762
2763       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
2764    end Analyze_Generic_Package_Declaration;
2765
2766    --------------------------------------------
2767    -- Analyze_Generic_Subprogram_Declaration --
2768    --------------------------------------------
2769
2770    procedure Analyze_Generic_Subprogram_Declaration (N : Node_Id) is
2771       Spec        : Node_Id;
2772       Id          : Entity_Id;
2773       Formals     : List_Id;
2774       New_N       : Node_Id;
2775       Result_Type : Entity_Id;
2776       Save_Parent : Node_Id;
2777       Typ         : Entity_Id;
2778
2779    begin
2780       --  Create copy of generic unit, and save for instantiation. If the unit
2781       --  is a child unit, do not copy the specifications for the parent, which
2782       --  are not part of the generic tree.
2783
2784       Save_Parent := Parent_Spec (N);
2785       Set_Parent_Spec (N, Empty);
2786
2787       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2788       Set_Parent_Spec (New_N, Save_Parent);
2789       Rewrite (N, New_N);
2790
2791       Spec := Specification (N);
2792       Id := Defining_Entity (Spec);
2793       Generate_Definition (Id);
2794
2795       if Nkind (Id) = N_Defining_Operator_Symbol then
2796          Error_Msg_N
2797            ("operator symbol not allowed for generic subprogram", Id);
2798       end if;
2799
2800       Start_Generic;
2801
2802       Enter_Name (Id);
2803
2804       Set_Scope_Depth_Value (Id, Scope_Depth (Current_Scope) + 1);
2805       Push_Scope (Id);
2806       Enter_Generic_Scope (Id);
2807       Set_Inner_Instances (Id, New_Elmt_List);
2808       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2809
2810       Analyze_Generic_Formal_Part (N);
2811
2812       Formals := Parameter_Specifications (Spec);
2813
2814       if Present (Formals) then
2815          Process_Formals (Formals, Spec);
2816       end if;
2817
2818       if Nkind (Spec) = N_Function_Specification then
2819          Set_Ekind (Id, E_Generic_Function);
2820
2821          if Nkind (Result_Definition (Spec)) = N_Access_Definition then
2822             Result_Type := Access_Definition (Spec, Result_Definition (Spec));
2823             Set_Etype (Id, Result_Type);
2824
2825             --  Check restriction imposed by AI05-073: a generic function
2826             --  cannot return an abstract type or an access to such.
2827
2828             --  This is a binding interpreration should it apply to earlier
2829             --  versions of Ada as well as Ada 2012???
2830
2831             if Is_Abstract_Type (Designated_Type (Result_Type))
2832               and then Ada_Version >= Ada_2012
2833             then
2834                Error_Msg_N ("generic function cannot have an access result"
2835                  & " that designates an abstract type", Spec);
2836             end if;
2837
2838          else
2839             Find_Type (Result_Definition (Spec));
2840             Typ := Entity (Result_Definition (Spec));
2841
2842             if Is_Abstract_Type (Typ)
2843               and then Ada_Version >= Ada_2012
2844             then
2845                Error_Msg_N
2846                  ("generic function cannot have abstract result type", Spec);
2847             end if;
2848
2849             --  If a null exclusion is imposed on the result type, then create
2850             --  a null-excluding itype (an access subtype) and use it as the
2851             --  function's Etype.
2852
2853             if Is_Access_Type (Typ)
2854               and then Null_Exclusion_Present (Spec)
2855             then
2856                Set_Etype  (Id,
2857                  Create_Null_Excluding_Itype
2858                    (T           => Typ,
2859                     Related_Nod => Spec,
2860                     Scope_Id    => Defining_Unit_Name (Spec)));
2861             else
2862                Set_Etype (Id, Typ);
2863             end if;
2864          end if;
2865
2866       else
2867          Set_Ekind (Id, E_Generic_Procedure);
2868          Set_Etype (Id, Standard_Void_Type);
2869       end if;
2870
2871       --  For a library unit, we have reconstructed the entity for the unit,
2872       --  and must reset it in the library tables. We also make sure that
2873       --  Body_Required is set properly in the original compilation unit node.
2874
2875       if Nkind (Parent (N)) = N_Compilation_Unit then
2876          Set_Cunit_Entity (Current_Sem_Unit, Id);
2877          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2878       end if;
2879
2880       Set_Categorization_From_Pragmas (N);
2881       Validate_Categorization_Dependency (N, Id);
2882
2883       Save_Global_References (Original_Node (N));
2884
2885       End_Generic;
2886       End_Scope;
2887       Exit_Generic_Scope (Id);
2888       Generate_Reference_To_Formals (Id);
2889
2890       List_Inherited_Pre_Post_Aspects (Id);
2891       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
2892    end Analyze_Generic_Subprogram_Declaration;
2893
2894    -----------------------------------
2895    -- Analyze_Package_Instantiation --
2896    -----------------------------------
2897
2898    procedure Analyze_Package_Instantiation (N : Node_Id) is
2899       Loc    : constant Source_Ptr := Sloc (N);
2900       Gen_Id : constant Node_Id    := Name (N);
2901
2902       Act_Decl      : Node_Id;
2903       Act_Decl_Name : Node_Id;
2904       Act_Decl_Id   : Entity_Id;
2905       Act_Spec      : Node_Id;
2906       Act_Tree      : Node_Id;
2907
2908       Gen_Decl : Node_Id;
2909       Gen_Unit : Entity_Id;
2910
2911       Is_Actual_Pack : constant Boolean :=
2912                          Is_Internal (Defining_Entity (N));
2913
2914       Env_Installed    : Boolean := False;
2915       Parent_Installed : Boolean := False;
2916       Renaming_List    : List_Id;
2917       Unit_Renaming    : Node_Id;
2918       Needs_Body       : Boolean;
2919       Inline_Now       : Boolean := False;
2920
2921       procedure Delay_Descriptors (E : Entity_Id);
2922       --  Delay generation of subprogram descriptors for given entity
2923
2924       function Might_Inline_Subp return Boolean;
2925       --  If inlining is active and the generic contains inlined subprograms,
2926       --  we instantiate the body. This may cause superfluous instantiations,
2927       --  but it is simpler than detecting the need for the body at the point
2928       --  of inlining, when the context of the instance is not available.
2929
2930       -----------------------
2931       -- Delay_Descriptors --
2932       -----------------------
2933
2934       procedure Delay_Descriptors (E : Entity_Id) is
2935       begin
2936          if not Delay_Subprogram_Descriptors (E) then
2937             Set_Delay_Subprogram_Descriptors (E);
2938             Pending_Descriptor.Append (E);
2939          end if;
2940       end Delay_Descriptors;
2941
2942       -----------------------
2943       -- Might_Inline_Subp --
2944       -----------------------
2945
2946       function Might_Inline_Subp return Boolean is
2947          E : Entity_Id;
2948
2949       begin
2950          if not Inline_Processing_Required then
2951             return False;
2952
2953          else
2954             E := First_Entity (Gen_Unit);
2955             while Present (E) loop
2956                if Is_Subprogram (E)
2957                  and then Is_Inlined (E)
2958                then
2959                   return True;
2960                end if;
2961
2962                Next_Entity (E);
2963             end loop;
2964          end if;
2965
2966          return False;
2967       end Might_Inline_Subp;
2968
2969    --  Start of processing for Analyze_Package_Instantiation
2970
2971    begin
2972       --  Very first thing: apply the special kludge for Text_IO processing
2973       --  in case we are instantiating one of the children of [Wide_]Text_IO.
2974
2975       Text_IO_Kludge (Name (N));
2976
2977       --  Make node global for error reporting
2978
2979       Instantiation_Node := N;
2980
2981       --  Case of instantiation of a generic package
2982
2983       if Nkind (N) = N_Package_Instantiation then
2984          Act_Decl_Id := New_Copy (Defining_Entity (N));
2985          Set_Comes_From_Source (Act_Decl_Id, True);
2986
2987          if Nkind (Defining_Unit_Name (N)) = N_Defining_Program_Unit_Name then
2988             Act_Decl_Name :=
2989               Make_Defining_Program_Unit_Name (Loc,
2990                 Name => New_Copy_Tree (Name (Defining_Unit_Name (N))),
2991                 Defining_Identifier => Act_Decl_Id);
2992          else
2993             Act_Decl_Name :=  Act_Decl_Id;
2994          end if;
2995
2996       --  Case of instantiation of a formal package
2997
2998       else
2999          Act_Decl_Id   := Defining_Identifier (N);
3000          Act_Decl_Name := Act_Decl_Id;
3001       end if;
3002
3003       Generate_Definition (Act_Decl_Id);
3004       Preanalyze_Actuals (N);
3005
3006       Init_Env;
3007       Env_Installed := True;
3008
3009       --  Reset renaming map for formal types. The mapping is established
3010       --  when analyzing the generic associations, but some mappings are
3011       --  inherited from formal packages of parent units, and these are
3012       --  constructed when the parents are installed.
3013
3014       Generic_Renamings.Set_Last (0);
3015       Generic_Renamings_HTable.Reset;
3016
3017       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
3018       Gen_Unit := Entity (Gen_Id);
3019
3020       --  Verify that it is the name of a generic package
3021
3022       --  A visibility glitch: if the instance is a child unit and the generic
3023       --  is the generic unit of a parent instance (i.e. both the parent and
3024       --  the child units are instances of the same package) the name now
3025       --  denotes the renaming within the parent, not the intended generic
3026       --  unit. See if there is a homonym that is the desired generic. The
3027       --  renaming declaration must be visible inside the instance of the
3028       --  child, but not when analyzing the name in the instantiation itself.
3029
3030       if Ekind (Gen_Unit) = E_Package
3031         and then Present (Renamed_Entity (Gen_Unit))
3032         and then In_Open_Scopes (Renamed_Entity (Gen_Unit))
3033         and then Is_Generic_Instance (Renamed_Entity (Gen_Unit))
3034         and then Present (Homonym (Gen_Unit))
3035       then
3036          Gen_Unit := Homonym (Gen_Unit);
3037       end if;
3038
3039       if Etype (Gen_Unit) = Any_Type then
3040          Restore_Env;
3041          goto Leave;
3042
3043       elsif Ekind (Gen_Unit) /= E_Generic_Package then
3044
3045          --  Ada 2005 (AI-50217): Cannot use instance in limited with_clause
3046
3047          if From_With_Type (Gen_Unit) then
3048             Error_Msg_N
3049               ("cannot instantiate a limited withed package", Gen_Id);
3050          else
3051             Error_Msg_N
3052               ("expect name of generic package in instantiation", Gen_Id);
3053          end if;
3054
3055          Restore_Env;
3056          goto Leave;
3057       end if;
3058
3059       if In_Extended_Main_Source_Unit (N) then
3060          Set_Is_Instantiated (Gen_Unit);
3061          Generate_Reference  (Gen_Unit, N);
3062
3063          if Present (Renamed_Object (Gen_Unit)) then
3064             Set_Is_Instantiated (Renamed_Object (Gen_Unit));
3065             Generate_Reference  (Renamed_Object (Gen_Unit), N);
3066          end if;
3067       end if;
3068
3069       if Nkind (Gen_Id) = N_Identifier
3070         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
3071       then
3072          Error_Msg_NE
3073            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
3074
3075       elsif Nkind (Gen_Id) = N_Expanded_Name
3076         and then Is_Child_Unit (Gen_Unit)
3077         and then Nkind (Prefix (Gen_Id)) = N_Identifier
3078         and then Chars (Act_Decl_Id) = Chars (Prefix (Gen_Id))
3079       then
3080          Error_Msg_N
3081            ("& is hidden within declaration of instance ", Prefix (Gen_Id));
3082       end if;
3083
3084       Set_Entity (Gen_Id, Gen_Unit);
3085
3086       --  If generic is a renaming, get original generic unit
3087
3088       if Present (Renamed_Object (Gen_Unit))
3089         and then Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Package
3090       then
3091          Gen_Unit := Renamed_Object (Gen_Unit);
3092       end if;
3093
3094       --  Verify that there are no circular instantiations
3095
3096       if In_Open_Scopes (Gen_Unit) then
3097          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
3098          Restore_Env;
3099          goto Leave;
3100
3101       elsif Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
3102          Error_Msg_Node_2 := Current_Scope;
3103          Error_Msg_NE
3104            ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
3105          Circularity_Detected := True;
3106          Restore_Env;
3107          goto Leave;
3108
3109       else
3110          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
3111
3112          --  Initialize renamings map, for error checking, and the list that
3113          --  holds private entities whose views have changed between generic
3114          --  definition and instantiation. If this is the instance created to
3115          --  validate an actual package, the instantiation environment is that
3116          --  of the enclosing instance.
3117
3118          Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
3119
3120          --  Copy original generic tree, to produce text for instantiation
3121
3122          Act_Tree :=
3123            Copy_Generic_Node
3124              (Original_Node (Gen_Decl), Empty, Instantiating => True);
3125
3126          Act_Spec := Specification (Act_Tree);
3127
3128          --  If this is the instance created to validate an actual package,
3129          --  only the formals matter, do not examine the package spec itself.
3130
3131          if Is_Actual_Pack then
3132             Set_Visible_Declarations (Act_Spec, New_List);
3133             Set_Private_Declarations (Act_Spec, New_List);
3134          end if;
3135
3136          Renaming_List :=
3137            Analyze_Associations
3138              (N,
3139               Generic_Formal_Declarations (Act_Tree),
3140               Generic_Formal_Declarations (Gen_Decl));
3141
3142          Set_Instance_Env (Gen_Unit, Act_Decl_Id);
3143          Set_Defining_Unit_Name (Act_Spec, Act_Decl_Name);
3144          Set_Is_Generic_Instance (Act_Decl_Id);
3145
3146          Set_Generic_Parent (Act_Spec, Gen_Unit);
3147
3148          --  References to the generic in its own declaration or its body are
3149          --  references to the instance. Add a renaming declaration for the
3150          --  generic unit itself. This declaration, as well as the renaming
3151          --  declarations for the generic formals, must remain private to the
3152          --  unit: the formals, because this is the language semantics, and
3153          --  the unit because its use is an artifact of the implementation.
3154
3155          Unit_Renaming :=
3156            Make_Package_Renaming_Declaration (Loc,
3157              Defining_Unit_Name =>
3158                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
3159              Name => New_Reference_To (Act_Decl_Id, Loc));
3160
3161          Append (Unit_Renaming, Renaming_List);
3162
3163          --  The renaming declarations are the first local declarations of
3164          --  the new unit.
3165
3166          if Is_Non_Empty_List (Visible_Declarations (Act_Spec)) then
3167             Insert_List_Before
3168               (First (Visible_Declarations (Act_Spec)), Renaming_List);
3169          else
3170             Set_Visible_Declarations (Act_Spec, Renaming_List);
3171          end if;
3172
3173          Act_Decl :=
3174            Make_Package_Declaration (Loc,
3175              Specification => Act_Spec);
3176
3177          --  Save the instantiation node, for subsequent instantiation of the
3178          --  body, if there is one and we are generating code for the current
3179          --  unit. Mark the unit as having a body, to avoid a premature error
3180          --  message.
3181
3182          --  We instantiate the body if we are generating code, if we are
3183          --  generating cross-reference information, or if we are building
3184          --  trees for ASIS use.
3185
3186          declare
3187             Enclosing_Body_Present : Boolean := False;
3188             --  If the generic unit is not a compilation unit, then a body may
3189             --  be present in its parent even if none is required. We create a
3190             --  tentative pending instantiation for the body, which will be
3191             --  discarded if none is actually present.
3192
3193             Scop : Entity_Id;
3194
3195          begin
3196             if Scope (Gen_Unit) /= Standard_Standard
3197               and then not Is_Child_Unit (Gen_Unit)
3198             then
3199                Scop := Scope (Gen_Unit);
3200
3201                while Present (Scop)
3202                  and then Scop /= Standard_Standard
3203                loop
3204                   if Unit_Requires_Body (Scop) then
3205                      Enclosing_Body_Present := True;
3206                      exit;
3207
3208                   elsif In_Open_Scopes (Scop)
3209                     and then In_Package_Body (Scop)
3210                   then
3211                      Enclosing_Body_Present := True;
3212                      exit;
3213                   end if;
3214
3215                   exit when Is_Compilation_Unit (Scop);
3216                   Scop := Scope (Scop);
3217                end loop;
3218             end if;
3219
3220             --  If front-end inlining is enabled, and this is a unit for which
3221             --  code will be generated, we instantiate the body at once.
3222
3223             --  This is done if the instance is not the main unit, and if the
3224             --  generic is not a child unit of another generic, to avoid scope
3225             --  problems and the reinstallation of parent instances.
3226
3227             if Expander_Active
3228               and then (not Is_Child_Unit (Gen_Unit)
3229                          or else not Is_Generic_Unit (Scope (Gen_Unit)))
3230               and then Might_Inline_Subp
3231               and then not Is_Actual_Pack
3232             then
3233                if Front_End_Inlining
3234                  and then (Is_In_Main_Unit (N)
3235                             or else In_Main_Context (Current_Scope))
3236                  and then Nkind (Parent (N)) /= N_Compilation_Unit
3237                then
3238                   Inline_Now := True;
3239
3240                --  In configurable_run_time mode we force the inlining of
3241                --  predefined subprograms marked Inline_Always, to minimize
3242                --  the use of the run-time library.
3243
3244                elsif Is_Predefined_File_Name
3245                        (Unit_File_Name (Get_Source_Unit (Gen_Decl)))
3246                  and then Configurable_Run_Time_Mode
3247                  and then Nkind (Parent (N)) /= N_Compilation_Unit
3248                then
3249                   Inline_Now := True;
3250                end if;
3251
3252                --  If the current scope is itself an instance within a child
3253                --  unit, there will be duplications in the scope stack, and the
3254                --  unstacking mechanism in Inline_Instance_Body will fail.
3255                --  This loses some rare cases of optimization, and might be
3256                --  improved some day, if we can find a proper abstraction for
3257                --  "the complete compilation context" that can be saved and
3258                --  restored. ???
3259
3260                if Is_Generic_Instance (Current_Scope) then
3261                   declare
3262                      Curr_Unit : constant Entity_Id :=
3263                                    Cunit_Entity (Current_Sem_Unit);
3264                   begin
3265                      if Curr_Unit /= Current_Scope
3266                        and then Is_Child_Unit (Curr_Unit)
3267                      then
3268                         Inline_Now := False;
3269                      end if;
3270                   end;
3271                end if;
3272             end if;
3273
3274             Needs_Body :=
3275               (Unit_Requires_Body (Gen_Unit)
3276                   or else Enclosing_Body_Present
3277                   or else Present (Corresponding_Body (Gen_Decl)))
3278                 and then (Is_In_Main_Unit (N)
3279                            or else Might_Inline_Subp)
3280                 and then not Is_Actual_Pack
3281                 and then not Inline_Now
3282                 and then (Operating_Mode = Generate_Code
3283                             or else (Operating_Mode = Check_Semantics
3284                                       and then ASIS_Mode));
3285
3286             --  If front_end_inlining is enabled, do not instantiate body if
3287             --  within a generic context.
3288
3289             if (Front_End_Inlining
3290                   and then not Expander_Active)
3291               or else Is_Generic_Unit (Cunit_Entity (Main_Unit))
3292             then
3293                Needs_Body := False;
3294             end if;
3295
3296             --  If the current context is generic, and the package being
3297             --  instantiated is declared within a formal package, there is no
3298             --  body to instantiate until the enclosing generic is instantiated
3299             --  and there is an actual for the formal package. If the formal
3300             --  package has parameters, we build a regular package instance for
3301             --  it, that precedes the original formal package declaration.
3302
3303             if In_Open_Scopes (Scope (Scope (Gen_Unit))) then
3304                declare
3305                   Decl : constant Node_Id :=
3306                            Original_Node
3307                              (Unit_Declaration_Node (Scope (Gen_Unit)));
3308                begin
3309                   if Nkind (Decl) = N_Formal_Package_Declaration
3310                     or else (Nkind (Decl) = N_Package_Declaration
3311                                and then Is_List_Member (Decl)
3312                                and then Present (Next (Decl))
3313                                and then
3314                                  Nkind (Next (Decl)) =
3315                                                 N_Formal_Package_Declaration)
3316                   then
3317                      Needs_Body := False;
3318                   end if;
3319                end;
3320             end if;
3321          end;
3322
3323          --  If we are generating the calling stubs from the instantiation of
3324          --  a generic RCI package, we will not use the body of the generic
3325          --  package.
3326
3327          if Distribution_Stub_Mode = Generate_Caller_Stub_Body
3328            and then Is_Compilation_Unit (Defining_Entity (N))
3329          then
3330             Needs_Body := False;
3331          end if;
3332
3333          if Needs_Body then
3334
3335             --  Here is a defence against a ludicrous number of instantiations
3336             --  caused by a circular set of instantiation attempts.
3337
3338             if Pending_Instantiations.Last >
3339                  Hostparm.Max_Instantiations
3340             then
3341                Error_Msg_N ("too many instantiations", N);
3342                raise Unrecoverable_Error;
3343             end if;
3344
3345             --  Indicate that the enclosing scopes contain an instantiation,
3346             --  and that cleanup actions should be delayed until after the
3347             --  instance body is expanded.
3348
3349             Check_Forward_Instantiation (Gen_Decl);
3350             if Nkind (N) = N_Package_Instantiation then
3351                declare
3352                   Enclosing_Master : Entity_Id;
3353
3354                begin
3355                   --  Loop to search enclosing masters
3356
3357                   Enclosing_Master := Current_Scope;
3358                   Scope_Loop : while Enclosing_Master /= Standard_Standard loop
3359                      if Ekind (Enclosing_Master) = E_Package then
3360                         if Is_Compilation_Unit (Enclosing_Master) then
3361                            if In_Package_Body (Enclosing_Master) then
3362                               Delay_Descriptors
3363                                 (Body_Entity (Enclosing_Master));
3364                            else
3365                               Delay_Descriptors
3366                                 (Enclosing_Master);
3367                            end if;
3368
3369                            exit Scope_Loop;
3370
3371                         else
3372                            Enclosing_Master := Scope (Enclosing_Master);
3373                         end if;
3374
3375                      elsif Ekind (Enclosing_Master) = E_Generic_Package then
3376                         Enclosing_Master := Scope (Enclosing_Master);
3377
3378                      elsif Is_Generic_Subprogram (Enclosing_Master)
3379                        or else Ekind (Enclosing_Master) = E_Void
3380                      then
3381                         --  Cleanup actions will eventually be performed on the
3382                         --  enclosing instance, if any. Enclosing scope is void
3383                         --  in the formal part of a generic subprogram.
3384
3385                         exit Scope_Loop;
3386
3387                      else
3388                         if Ekind (Enclosing_Master) = E_Entry
3389                           and then
3390                             Ekind (Scope (Enclosing_Master)) = E_Protected_Type
3391                         then
3392                            if not Expander_Active then
3393                               exit Scope_Loop;
3394                            else
3395                               Enclosing_Master :=
3396                                 Protected_Body_Subprogram (Enclosing_Master);
3397                            end if;
3398                         end if;
3399
3400                         Set_Delay_Cleanups (Enclosing_Master);
3401
3402                         while Ekind (Enclosing_Master) = E_Block loop
3403                            Enclosing_Master := Scope (Enclosing_Master);
3404                         end loop;
3405
3406                         if Is_Subprogram (Enclosing_Master) then
3407                            Delay_Descriptors (Enclosing_Master);
3408
3409                         elsif Is_Task_Type (Enclosing_Master) then
3410                            declare
3411                               TBP : constant Node_Id :=
3412                                       Get_Task_Body_Procedure
3413                                         (Enclosing_Master);
3414                            begin
3415                               if Present (TBP) then
3416                                  Delay_Descriptors  (TBP);
3417                                  Set_Delay_Cleanups (TBP);
3418                               end if;
3419                            end;
3420                         end if;
3421
3422                         exit Scope_Loop;
3423                      end if;
3424                   end loop Scope_Loop;
3425                end;
3426
3427                --  Make entry in table
3428
3429                Pending_Instantiations.Append
3430                  ((Inst_Node                => N,
3431                    Act_Decl                 => Act_Decl,
3432                    Expander_Status          => Expander_Active,
3433                    Current_Sem_Unit         => Current_Sem_Unit,
3434                    Scope_Suppress           => Scope_Suppress,
3435                    Local_Suppress_Stack_Top => Local_Suppress_Stack_Top,
3436                    Version                  => Ada_Version));
3437             end if;
3438          end if;
3439
3440          Set_Categorization_From_Pragmas (Act_Decl);
3441
3442          if Parent_Installed then
3443             Hide_Current_Scope;
3444          end if;
3445
3446          Set_Instance_Spec (N, Act_Decl);
3447
3448          --  If not a compilation unit, insert the package declaration before
3449          --  the original instantiation node.
3450
3451          if Nkind (Parent (N)) /= N_Compilation_Unit then
3452             Mark_Rewrite_Insertion (Act_Decl);
3453             Insert_Before (N, Act_Decl);
3454             Analyze (Act_Decl);
3455
3456          --  For an instantiation that is a compilation unit, place declaration
3457          --  on current node so context is complete for analysis (including
3458          --  nested instantiations). If this is the main unit, the declaration
3459          --  eventually replaces the instantiation node. If the instance body
3460          --  is created later, it replaces the instance node, and the
3461          --  declaration is attached to it (see
3462          --  Build_Instance_Compilation_Unit_Nodes).
3463
3464          else
3465             if Cunit_Entity (Current_Sem_Unit) = Defining_Entity (N) then
3466
3467                --  The entity for the current unit is the newly created one,
3468                --  and all semantic information is attached to it.
3469
3470                Set_Cunit_Entity (Current_Sem_Unit, Act_Decl_Id);
3471
3472                --  If this is the main unit, replace the main entity as well
3473
3474                if Current_Sem_Unit = Main_Unit then
3475                   Main_Unit_Entity := Act_Decl_Id;
3476                end if;
3477             end if;
3478
3479             Set_Unit (Parent (N), Act_Decl);
3480             Set_Parent_Spec (Act_Decl, Parent_Spec (N));
3481             Set_Package_Instantiation (Act_Decl_Id, N);
3482             Analyze (Act_Decl);
3483             Set_Unit (Parent (N), N);
3484             Set_Body_Required (Parent (N), False);
3485
3486             --  We never need elaboration checks on instantiations, since by
3487             --  definition, the body instantiation is elaborated at the same
3488             --  time as the spec instantiation.
3489
3490             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
3491             Set_Kill_Elaboration_Checks       (Act_Decl_Id);
3492          end if;
3493
3494          Check_Elab_Instantiation (N);
3495
3496          if ABE_Is_Certain (N) and then Needs_Body then
3497             Pending_Instantiations.Decrement_Last;
3498          end if;
3499
3500          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
3501
3502          Set_First_Private_Entity (Defining_Unit_Name (Unit_Renaming),
3503            First_Private_Entity (Act_Decl_Id));
3504
3505          --  If the instantiation will receive a body, the unit will be
3506          --  transformed into a package body, and receive its own elaboration
3507          --  entity. Otherwise, the nature of the unit is now a package
3508          --  declaration.
3509
3510          if Nkind (Parent (N)) = N_Compilation_Unit
3511            and then not Needs_Body
3512          then
3513             Rewrite (N, Act_Decl);
3514          end if;
3515
3516          if Present (Corresponding_Body (Gen_Decl))
3517            or else Unit_Requires_Body (Gen_Unit)
3518          then
3519             Set_Has_Completion (Act_Decl_Id);
3520          end if;
3521
3522          Check_Formal_Packages (Act_Decl_Id);
3523
3524          Restore_Private_Views (Act_Decl_Id);
3525
3526          Inherit_Context (Gen_Decl, N);
3527
3528          if Parent_Installed then
3529             Remove_Parent;
3530          end if;
3531
3532          Restore_Env;
3533          Env_Installed := False;
3534       end if;
3535
3536       Validate_Categorization_Dependency (N, Act_Decl_Id);
3537
3538       --  There used to be a check here to prevent instantiations in local
3539       --  contexts if the No_Local_Allocators restriction was active. This
3540       --  check was removed by a binding interpretation in AI-95-00130/07,
3541       --  but we retain the code for documentation purposes.
3542
3543       --  if Ekind (Act_Decl_Id) /= E_Void
3544       --    and then not Is_Library_Level_Entity (Act_Decl_Id)
3545       --  then
3546       --     Check_Restriction (No_Local_Allocators, N);
3547       --  end if;
3548
3549       if Inline_Now then
3550          Inline_Instance_Body (N, Gen_Unit, Act_Decl);
3551       end if;
3552
3553       --  The following is a tree patch for ASIS: ASIS needs separate nodes to
3554       --  be used as defining identifiers for a formal package and for the
3555       --  corresponding expanded package.
3556
3557       if Nkind (N) = N_Formal_Package_Declaration then
3558          Act_Decl_Id := New_Copy (Defining_Entity (N));
3559          Set_Comes_From_Source (Act_Decl_Id, True);
3560          Set_Is_Generic_Instance (Act_Decl_Id, False);
3561          Set_Defining_Identifier (N, Act_Decl_Id);
3562       end if;
3563
3564       <<Leave>>
3565          Analyze_Aspect_Specifications
3566            (N, Act_Decl_Id, Aspect_Specifications (N));
3567
3568    exception
3569       when Instantiation_Error =>
3570          if Parent_Installed then
3571             Remove_Parent;
3572          end if;
3573
3574          if Env_Installed then
3575             Restore_Env;
3576          end if;
3577    end Analyze_Package_Instantiation;
3578
3579    --------------------------
3580    -- Inline_Instance_Body --
3581    --------------------------
3582
3583    procedure Inline_Instance_Body
3584      (N        : Node_Id;
3585       Gen_Unit : Entity_Id;
3586       Act_Decl : Node_Id)
3587    is
3588       Vis          : Boolean;
3589       Gen_Comp     : constant Entity_Id :=
3590                       Cunit_Entity (Get_Source_Unit (Gen_Unit));
3591       Curr_Comp    : constant Node_Id := Cunit (Current_Sem_Unit);
3592       Curr_Scope   : Entity_Id := Empty;
3593       Curr_Unit    : constant Entity_Id := Cunit_Entity (Current_Sem_Unit);
3594       Removed      : Boolean := False;
3595       Num_Scopes   : Int := 0;
3596
3597       Scope_Stack_Depth : constant Int :=
3598                             Scope_Stack.Last - Scope_Stack.First + 1;
3599
3600       Use_Clauses  : array (1 .. Scope_Stack_Depth) of Node_Id;
3601       Instances    : array (1 .. Scope_Stack_Depth) of Entity_Id;
3602       Inner_Scopes : array (1 .. Scope_Stack_Depth) of Entity_Id;
3603       Num_Inner    : Int := 0;
3604       N_Instances  : Int := 0;
3605       S            : Entity_Id;
3606
3607    begin
3608       --  Case of generic unit defined in another unit. We must remove the
3609       --  complete context of the current unit to install that of the generic.
3610
3611       if Gen_Comp /= Cunit_Entity (Current_Sem_Unit) then
3612
3613          --  Add some comments for the following two loops ???
3614
3615          S := Current_Scope;
3616          while Present (S) and then S /= Standard_Standard loop
3617             loop
3618                Num_Scopes := Num_Scopes + 1;
3619
3620                Use_Clauses (Num_Scopes) :=
3621                  (Scope_Stack.Table
3622                     (Scope_Stack.Last - Num_Scopes + 1).
3623                        First_Use_Clause);
3624                End_Use_Clauses (Use_Clauses (Num_Scopes));
3625
3626                exit when Scope_Stack.Last - Num_Scopes + 1 = Scope_Stack.First
3627                  or else Scope_Stack.Table
3628                            (Scope_Stack.Last - Num_Scopes).Entity
3629                              = Scope (S);
3630             end loop;
3631
3632             exit when Is_Generic_Instance (S)
3633               and then (In_Package_Body (S)
3634                           or else Ekind (S) = E_Procedure
3635                           or else Ekind (S) = E_Function);
3636             S := Scope (S);
3637          end loop;
3638
3639          Vis := Is_Immediately_Visible (Gen_Comp);
3640
3641          --  Find and save all enclosing instances
3642
3643          S := Current_Scope;
3644
3645          while Present (S)
3646            and then S /= Standard_Standard
3647          loop
3648             if Is_Generic_Instance (S) then
3649                N_Instances := N_Instances + 1;
3650                Instances (N_Instances) := S;
3651
3652                exit when In_Package_Body (S);
3653             end if;
3654
3655             S := Scope (S);
3656          end loop;
3657
3658          --  Remove context of current compilation unit, unless we are within a
3659          --  nested package instantiation, in which case the context has been
3660          --  removed previously.
3661
3662          --  If current scope is the body of a child unit, remove context of
3663          --  spec as well. If an enclosing scope is an instance body, the
3664          --  context has already been removed, but the entities in the body
3665          --  must be made invisible as well.
3666
3667          S := Current_Scope;
3668
3669          while Present (S)
3670            and then S /= Standard_Standard
3671          loop
3672             if Is_Generic_Instance (S)
3673               and then (In_Package_Body (S)
3674                           or else Ekind (S) = E_Procedure
3675                             or else Ekind (S) = E_Function)
3676             then
3677                --  We still have to remove the entities of the enclosing
3678                --  instance from direct visibility.
3679
3680                declare
3681                   E : Entity_Id;
3682                begin
3683                   E := First_Entity (S);
3684                   while Present (E) loop
3685                      Set_Is_Immediately_Visible (E, False);
3686                      Next_Entity (E);
3687                   end loop;
3688                end;
3689
3690                exit;
3691             end if;
3692
3693             if S = Curr_Unit
3694               or else (Ekind (Curr_Unit) = E_Package_Body
3695                         and then S = Spec_Entity (Curr_Unit))
3696               or else (Ekind (Curr_Unit) = E_Subprogram_Body
3697                         and then S =
3698                           Corresponding_Spec
3699                             (Unit_Declaration_Node (Curr_Unit)))
3700             then
3701                Removed := True;
3702
3703                --  Remove entities in current scopes from visibility, so that
3704                --  instance body is compiled in a clean environment.
3705
3706                Save_Scope_Stack (Handle_Use => False);
3707
3708                if Is_Child_Unit (S) then
3709
3710                   --  Remove child unit from stack, as well as inner scopes.
3711                   --  Removing the context of a child unit removes parent units
3712                   --  as well.
3713
3714                   while Current_Scope /= S loop
3715                      Num_Inner := Num_Inner + 1;
3716                      Inner_Scopes (Num_Inner) := Current_Scope;
3717                      Pop_Scope;
3718                   end loop;
3719
3720                   Pop_Scope;
3721                   Remove_Context (Curr_Comp);
3722                   Curr_Scope := S;
3723
3724                else
3725                   Remove_Context (Curr_Comp);
3726                end if;
3727
3728                if Ekind (Curr_Unit) = E_Package_Body then
3729                   Remove_Context (Library_Unit (Curr_Comp));
3730                end if;
3731             end if;
3732
3733             S := Scope (S);
3734          end loop;
3735          pragma Assert (Num_Inner < Num_Scopes);
3736
3737          Push_Scope (Standard_Standard);
3738          Scope_Stack.Table (Scope_Stack.Last).Is_Active_Stack_Base := True;
3739          Instantiate_Package_Body
3740            (Body_Info =>
3741              ((Inst_Node                => N,
3742                Act_Decl                 => Act_Decl,
3743                Expander_Status          => Expander_Active,
3744                Current_Sem_Unit         => Current_Sem_Unit,
3745                Scope_Suppress           => Scope_Suppress,
3746                Local_Suppress_Stack_Top => Local_Suppress_Stack_Top,
3747                Version                  => Ada_Version)),
3748             Inlined_Body => True);
3749
3750          Pop_Scope;
3751
3752          --  Restore context
3753
3754          Set_Is_Immediately_Visible (Gen_Comp, Vis);
3755
3756          --  Reset Generic_Instance flag so that use clauses can be installed
3757          --  in the proper order. (See Use_One_Package for effect of enclosing
3758          --  instances on processing of use clauses).
3759
3760          for J in 1 .. N_Instances loop
3761             Set_Is_Generic_Instance (Instances (J), False);
3762          end loop;
3763
3764          if Removed then
3765             Install_Context (Curr_Comp);
3766
3767             if Present (Curr_Scope)
3768               and then Is_Child_Unit (Curr_Scope)
3769             then
3770                Push_Scope (Curr_Scope);
3771                Set_Is_Immediately_Visible (Curr_Scope);
3772
3773                --  Finally, restore inner scopes as well
3774
3775                for J in reverse 1 .. Num_Inner loop
3776                   Push_Scope (Inner_Scopes (J));
3777                end loop;
3778             end if;
3779
3780             Restore_Scope_Stack (Handle_Use => False);
3781
3782             if Present (Curr_Scope)
3783               and then
3784                 (In_Private_Part (Curr_Scope)
3785                   or else In_Package_Body (Curr_Scope))
3786             then
3787                --  Install private declaration of ancestor units, which are
3788                --  currently available. Restore_Scope_Stack and Install_Context
3789                --  only install the visible part of parents.
3790
3791                declare
3792                   Par : Entity_Id;
3793                begin
3794                   Par := Scope (Curr_Scope);
3795                   while (Present (Par))
3796                     and then Par /= Standard_Standard
3797                   loop
3798                      Install_Private_Declarations (Par);
3799                      Par := Scope (Par);
3800                   end loop;
3801                end;
3802             end if;
3803          end if;
3804
3805          --  Restore use clauses. For a child unit, use clauses in the parents
3806          --  are restored when installing the context, so only those in inner
3807          --  scopes (and those local to the child unit itself) need to be
3808          --  installed explicitly.
3809
3810          if Is_Child_Unit (Curr_Unit)
3811            and then Removed
3812          then
3813             for J in reverse 1 .. Num_Inner + 1 loop
3814                Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
3815                  Use_Clauses (J);
3816                Install_Use_Clauses (Use_Clauses (J));
3817             end  loop;
3818
3819          else
3820             for J in reverse 1 .. Num_Scopes loop
3821                Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
3822                  Use_Clauses (J);
3823                Install_Use_Clauses (Use_Clauses (J));
3824             end  loop;
3825          end if;
3826
3827          --  Restore status of instances. If one of them is a body, make
3828          --  its local entities visible again.
3829
3830          declare
3831             E    : Entity_Id;
3832             Inst : Entity_Id;
3833
3834          begin
3835             for J in 1 .. N_Instances loop
3836                Inst := Instances (J);
3837                Set_Is_Generic_Instance (Inst, True);
3838
3839                if In_Package_Body (Inst)
3840                  or else Ekind (S) = E_Procedure
3841                  or else Ekind (S) = E_Function
3842                then
3843                   E := First_Entity (Instances (J));
3844                   while Present (E) loop
3845                      Set_Is_Immediately_Visible (E);
3846                      Next_Entity (E);
3847                   end loop;
3848                end if;
3849             end loop;
3850          end;
3851
3852       --  If generic unit is in current unit, current context is correct
3853
3854       else
3855          Instantiate_Package_Body
3856            (Body_Info =>
3857              ((Inst_Node                => N,
3858                Act_Decl                 => Act_Decl,
3859                Expander_Status          => Expander_Active,
3860                Current_Sem_Unit         => Current_Sem_Unit,
3861                Scope_Suppress           => Scope_Suppress,
3862                Local_Suppress_Stack_Top => Local_Suppress_Stack_Top,
3863                Version                  => Ada_Version)),
3864             Inlined_Body => True);
3865       end if;
3866    end Inline_Instance_Body;
3867
3868    -------------------------------------
3869    -- Analyze_Procedure_Instantiation --
3870    -------------------------------------
3871
3872    procedure Analyze_Procedure_Instantiation (N : Node_Id) is
3873    begin
3874       Analyze_Subprogram_Instantiation (N, E_Procedure);
3875    end Analyze_Procedure_Instantiation;
3876
3877    -----------------------------------
3878    -- Need_Subprogram_Instance_Body --
3879    -----------------------------------
3880
3881    function Need_Subprogram_Instance_Body
3882      (N    : Node_Id;
3883       Subp : Entity_Id) return Boolean
3884    is
3885    begin
3886       if (Is_In_Main_Unit (N)
3887             or else Is_Inlined (Subp)
3888             or else Is_Inlined (Alias (Subp)))
3889         and then (Operating_Mode = Generate_Code
3890                     or else (Operating_Mode = Check_Semantics
3891                                and then ASIS_Mode))
3892         and then (Expander_Active or else ASIS_Mode)
3893         and then not ABE_Is_Certain (N)
3894         and then not Is_Eliminated (Subp)
3895       then
3896          Pending_Instantiations.Append
3897            ((Inst_Node                => N,
3898              Act_Decl                 => Unit_Declaration_Node (Subp),
3899              Expander_Status          => Expander_Active,
3900              Current_Sem_Unit         => Current_Sem_Unit,
3901              Scope_Suppress           => Scope_Suppress,
3902              Local_Suppress_Stack_Top => Local_Suppress_Stack_Top,
3903              Version                  => Ada_Version));
3904          return True;
3905       else
3906          return False;
3907       end if;
3908    end Need_Subprogram_Instance_Body;
3909
3910    --------------------------------------
3911    -- Analyze_Subprogram_Instantiation --
3912    --------------------------------------
3913
3914    procedure Analyze_Subprogram_Instantiation
3915      (N : Node_Id;
3916       K : Entity_Kind)
3917    is
3918       Loc    : constant Source_Ptr := Sloc (N);
3919       Gen_Id : constant Node_Id    := Name (N);
3920
3921       Anon_Id : constant Entity_Id :=
3922                   Make_Defining_Identifier (Sloc (Defining_Entity (N)),
3923                     Chars => New_External_Name
3924                                (Chars (Defining_Entity (N)), 'R'));
3925
3926       Act_Decl_Id : Entity_Id;
3927       Act_Decl    : Node_Id;
3928       Act_Spec    : Node_Id;
3929       Act_Tree    : Node_Id;
3930
3931       Env_Installed    : Boolean := False;
3932       Gen_Unit         : Entity_Id;
3933       Gen_Decl         : Node_Id;
3934       Pack_Id          : Entity_Id;
3935       Parent_Installed : Boolean := False;
3936       Renaming_List    : List_Id;
3937
3938       procedure Analyze_Instance_And_Renamings;
3939       --  The instance must be analyzed in a context that includes the mappings
3940       --  of generic parameters into actuals. We create a package declaration
3941       --  for this purpose, and a subprogram with an internal name within the
3942       --  package. The subprogram instance is simply an alias for the internal
3943       --  subprogram, declared in the current scope.
3944
3945       ------------------------------------
3946       -- Analyze_Instance_And_Renamings --
3947       ------------------------------------
3948
3949       procedure Analyze_Instance_And_Renamings is
3950          Def_Ent   : constant Entity_Id := Defining_Entity (N);
3951          Pack_Decl : Node_Id;
3952
3953       begin
3954          if Nkind (Parent (N)) = N_Compilation_Unit then
3955
3956             --  For the case of a compilation unit, the container package has
3957             --  the same name as the instantiation, to insure that the binder
3958             --  calls the elaboration procedure with the right name. Copy the
3959             --  entity of the instance, which may have compilation level flags
3960             --  (e.g. Is_Child_Unit) set.
3961
3962             Pack_Id := New_Copy (Def_Ent);
3963
3964          else
3965             --  Otherwise we use the name of the instantiation concatenated
3966             --  with its source position to ensure uniqueness if there are
3967             --  several instantiations with the same name.
3968
3969             Pack_Id :=
3970               Make_Defining_Identifier (Loc,
3971                 Chars => New_External_Name
3972                            (Related_Id   => Chars (Def_Ent),
3973                             Suffix       => "GP",
3974                             Suffix_Index => Source_Offset (Sloc (Def_Ent))));
3975          end if;
3976
3977          Pack_Decl := Make_Package_Declaration (Loc,
3978            Specification => Make_Package_Specification (Loc,
3979              Defining_Unit_Name   => Pack_Id,
3980              Visible_Declarations => Renaming_List,
3981              End_Label            => Empty));
3982
3983          Set_Instance_Spec (N, Pack_Decl);
3984          Set_Is_Generic_Instance (Pack_Id);
3985          Set_Debug_Info_Needed (Pack_Id);
3986
3987          --  Case of not a compilation unit
3988
3989          if Nkind (Parent (N)) /= N_Compilation_Unit then
3990             Mark_Rewrite_Insertion (Pack_Decl);
3991             Insert_Before (N, Pack_Decl);
3992             Set_Has_Completion (Pack_Id);
3993
3994          --  Case of an instantiation that is a compilation unit
3995
3996          --  Place declaration on current node so context is complete for
3997          --  analysis (including nested instantiations), and for use in a
3998          --  context_clause (see Analyze_With_Clause).
3999
4000          else
4001             Set_Unit (Parent (N), Pack_Decl);
4002             Set_Parent_Spec (Pack_Decl, Parent_Spec (N));
4003          end if;
4004
4005          Analyze (Pack_Decl);
4006          Check_Formal_Packages (Pack_Id);
4007          Set_Is_Generic_Instance (Pack_Id, False);
4008
4009          --  Body of the enclosing package is supplied when instantiating the
4010          --  subprogram body, after semantic analysis is completed.
4011
4012          if Nkind (Parent (N)) = N_Compilation_Unit then
4013
4014             --  Remove package itself from visibility, so it does not
4015             --  conflict with subprogram.
4016
4017             Set_Name_Entity_Id (Chars (Pack_Id), Homonym (Pack_Id));
4018
4019             --  Set name and scope of internal subprogram so that the proper
4020             --  external name will be generated. The proper scope is the scope
4021             --  of the wrapper package. We need to generate debugging info for
4022             --  the internal subprogram, so set flag accordingly.
4023
4024             Set_Chars (Anon_Id, Chars (Defining_Entity (N)));
4025             Set_Scope (Anon_Id, Scope (Pack_Id));
4026
4027             --  Mark wrapper package as referenced, to avoid spurious warnings
4028             --  if the instantiation appears in various with_ clauses of
4029             --  subunits of the main unit.
4030
4031             Set_Referenced (Pack_Id);
4032          end if;
4033
4034          Set_Is_Generic_Instance (Anon_Id);
4035          Set_Debug_Info_Needed   (Anon_Id);
4036          Act_Decl_Id := New_Copy (Anon_Id);
4037
4038          Set_Parent            (Act_Decl_Id, Parent (Anon_Id));
4039          Set_Chars             (Act_Decl_Id, Chars (Defining_Entity (N)));
4040          Set_Sloc              (Act_Decl_Id, Sloc (Defining_Entity (N)));
4041          Set_Comes_From_Source (Act_Decl_Id, True);
4042
4043          --  The signature may involve types that are not frozen yet, but the
4044          --  subprogram will be frozen at the point the wrapper package is
4045          --  frozen, so it does not need its own freeze node. In fact, if one
4046          --  is created, it might conflict with the freezing actions from the
4047          --  wrapper package.
4048
4049          Set_Has_Delayed_Freeze (Anon_Id, False);
4050
4051          --  If the instance is a child unit, mark the Id accordingly. Mark
4052          --  the anonymous entity as well, which is the real subprogram and
4053          --  which is used when the instance appears in a context clause.
4054          --  Similarly, propagate the Is_Eliminated flag to handle properly
4055          --  nested eliminated subprograms.
4056
4057          Set_Is_Child_Unit (Act_Decl_Id, Is_Child_Unit (Defining_Entity (N)));
4058          Set_Is_Child_Unit (Anon_Id, Is_Child_Unit (Defining_Entity (N)));
4059          New_Overloaded_Entity (Act_Decl_Id);
4060          Check_Eliminated  (Act_Decl_Id);
4061          Set_Is_Eliminated (Anon_Id, Is_Eliminated (Act_Decl_Id));
4062
4063          --  In compilation unit case, kill elaboration checks on the
4064          --  instantiation, since they are never needed -- the body is
4065          --  instantiated at the same point as the spec.
4066
4067          if Nkind (Parent (N)) = N_Compilation_Unit then
4068             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
4069             Set_Kill_Elaboration_Checks       (Act_Decl_Id);
4070             Set_Is_Compilation_Unit (Anon_Id);
4071
4072             Set_Cunit_Entity (Current_Sem_Unit, Pack_Id);
4073          end if;
4074
4075          --  The instance is not a freezing point for the new subprogram
4076
4077          Set_Is_Frozen (Act_Decl_Id, False);
4078
4079          if Nkind (Defining_Entity (N)) = N_Defining_Operator_Symbol then
4080             Valid_Operator_Definition (Act_Decl_Id);
4081          end if;
4082
4083          Set_Alias  (Act_Decl_Id, Anon_Id);
4084          Set_Parent (Act_Decl_Id, Parent (Anon_Id));
4085          Set_Has_Completion (Act_Decl_Id);
4086          Set_Related_Instance (Pack_Id, Act_Decl_Id);
4087
4088          if Nkind (Parent (N)) = N_Compilation_Unit then
4089             Set_Body_Required (Parent (N), False);
4090          end if;
4091       end Analyze_Instance_And_Renamings;
4092
4093    --  Start of processing for Analyze_Subprogram_Instantiation
4094
4095    begin
4096       --  Very first thing: apply the special kludge for Text_IO processing
4097       --  in case we are instantiating one of the children of [Wide_]Text_IO.
4098       --  Of course such an instantiation is bogus (these are packages, not
4099       --  subprograms), but we get a better error message if we do this.
4100
4101       Text_IO_Kludge (Gen_Id);
4102
4103       --  Make node global for error reporting
4104
4105       Instantiation_Node := N;
4106       Preanalyze_Actuals (N);
4107
4108       Init_Env;
4109       Env_Installed := True;
4110       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
4111       Gen_Unit := Entity (Gen_Id);
4112
4113       Generate_Reference (Gen_Unit, Gen_Id);
4114
4115       if Nkind (Gen_Id) = N_Identifier
4116         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
4117       then
4118          Error_Msg_NE
4119            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
4120       end if;
4121
4122       if Etype (Gen_Unit) = Any_Type then
4123          Restore_Env;
4124          return;
4125       end if;
4126
4127       --  Verify that it is a generic subprogram of the right kind, and that
4128       --  it does not lead to a circular instantiation.
4129
4130       if not Ekind_In (Gen_Unit, E_Generic_Procedure, E_Generic_Function) then
4131          Error_Msg_N ("expect generic subprogram in instantiation", Gen_Id);
4132
4133       elsif In_Open_Scopes (Gen_Unit) then
4134          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
4135
4136       elsif K = E_Procedure
4137         and then Ekind (Gen_Unit) /= E_Generic_Procedure
4138       then
4139          if Ekind (Gen_Unit) = E_Generic_Function then
4140             Error_Msg_N
4141               ("cannot instantiate generic function as procedure", Gen_Id);
4142          else
4143             Error_Msg_N
4144               ("expect name of generic procedure in instantiation", Gen_Id);
4145          end if;
4146
4147       elsif K = E_Function
4148         and then Ekind (Gen_Unit) /= E_Generic_Function
4149       then
4150          if Ekind (Gen_Unit) = E_Generic_Procedure then
4151             Error_Msg_N
4152               ("cannot instantiate generic procedure as function", Gen_Id);
4153          else
4154             Error_Msg_N
4155               ("expect name of generic function in instantiation", Gen_Id);
4156          end if;
4157
4158       else
4159          Set_Entity (Gen_Id, Gen_Unit);
4160          Set_Is_Instantiated (Gen_Unit);
4161
4162          if In_Extended_Main_Source_Unit (N) then
4163             Generate_Reference (Gen_Unit, N);
4164          end if;
4165
4166          --  If renaming, get original unit
4167
4168          if Present (Renamed_Object (Gen_Unit))
4169            and then (Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Procedure
4170                        or else
4171                      Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Function)
4172          then
4173             Gen_Unit := Renamed_Object (Gen_Unit);
4174             Set_Is_Instantiated (Gen_Unit);
4175             Generate_Reference  (Gen_Unit, N);
4176          end if;
4177
4178          if Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
4179             Error_Msg_Node_2 := Current_Scope;
4180             Error_Msg_NE
4181               ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
4182             Circularity_Detected := True;
4183             goto Leave;
4184          end if;
4185
4186          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
4187
4188          --  Initialize renamings map, for error checking
4189
4190          Generic_Renamings.Set_Last (0);
4191          Generic_Renamings_HTable.Reset;
4192
4193          Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
4194
4195          --  Copy original generic tree, to produce text for instantiation
4196
4197          Act_Tree :=
4198            Copy_Generic_Node
4199              (Original_Node (Gen_Decl), Empty, Instantiating => True);
4200
4201          --  Inherit overriding indicator from instance node
4202
4203          Act_Spec := Specification (Act_Tree);
4204          Set_Must_Override     (Act_Spec, Must_Override (N));
4205          Set_Must_Not_Override (Act_Spec, Must_Not_Override (N));
4206
4207          Renaming_List :=
4208            Analyze_Associations
4209              (N,
4210               Generic_Formal_Declarations (Act_Tree),
4211               Generic_Formal_Declarations (Gen_Decl));
4212
4213          --  The subprogram itself cannot contain a nested instance, so the
4214          --  current parent is left empty.
4215
4216          Set_Instance_Env (Gen_Unit, Empty);
4217
4218          --  Build the subprogram declaration, which does not appear in the
4219          --  generic template, and give it a sloc consistent with that of the
4220          --  template.
4221
4222          Set_Defining_Unit_Name (Act_Spec, Anon_Id);
4223          Set_Generic_Parent (Act_Spec, Gen_Unit);
4224          Act_Decl :=
4225            Make_Subprogram_Declaration (Sloc (Act_Spec),
4226              Specification => Act_Spec);
4227
4228          Set_Categorization_From_Pragmas (Act_Decl);
4229
4230          if Parent_Installed then
4231             Hide_Current_Scope;
4232          end if;
4233
4234          Append (Act_Decl, Renaming_List);
4235          Analyze_Instance_And_Renamings;
4236
4237          --  If the generic is marked Import (Intrinsic), then so is the
4238          --  instance. This indicates that there is no body to instantiate. If
4239          --  generic is marked inline, so it the instance, and the anonymous
4240          --  subprogram it renames. If inlined, or else if inlining is enabled
4241          --  for the compilation, we generate the instance body even if it is
4242          --  not within the main unit.
4243
4244          --  Any other  pragmas might also be inherited ???
4245
4246          if Is_Intrinsic_Subprogram (Gen_Unit) then
4247             Set_Is_Intrinsic_Subprogram (Anon_Id);
4248             Set_Is_Intrinsic_Subprogram (Act_Decl_Id);
4249
4250             if Chars (Gen_Unit) = Name_Unchecked_Conversion then
4251                Validate_Unchecked_Conversion (N, Act_Decl_Id);
4252             end if;
4253          end if;
4254
4255          Generate_Definition (Act_Decl_Id);
4256
4257          Set_Is_Inlined (Act_Decl_Id, Is_Inlined (Gen_Unit));
4258          Set_Is_Inlined (Anon_Id,     Is_Inlined (Gen_Unit));
4259
4260          if not Is_Intrinsic_Subprogram (Gen_Unit) then
4261             Check_Elab_Instantiation (N);
4262          end if;
4263
4264          if Is_Dispatching_Operation (Act_Decl_Id)
4265            and then Ada_Version >= Ada_2005
4266          then
4267             declare
4268                Formal : Entity_Id;
4269
4270             begin
4271                Formal := First_Formal (Act_Decl_Id);
4272                while Present (Formal) loop
4273                   if Ekind (Etype (Formal)) = E_Anonymous_Access_Type
4274                     and then Is_Controlling_Formal (Formal)
4275                     and then not Can_Never_Be_Null (Formal)
4276                   then
4277                      Error_Msg_NE ("access parameter& is controlling,",
4278                        N, Formal);
4279                      Error_Msg_NE
4280                        ("\corresponding parameter of & must be"
4281                        & " explicitly null-excluding", N, Gen_Id);
4282                   end if;
4283
4284                   Next_Formal (Formal);
4285                end loop;
4286             end;
4287          end if;
4288
4289          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
4290
4291          --  Subject to change, pending on if other pragmas are inherited ???
4292
4293          Validate_Categorization_Dependency (N, Act_Decl_Id);
4294
4295          if not Is_Intrinsic_Subprogram (Act_Decl_Id) then
4296             Inherit_Context (Gen_Decl, N);
4297
4298             Restore_Private_Views (Pack_Id, False);
4299
4300             --  If the context requires a full instantiation, mark node for
4301             --  subsequent construction of the body.
4302
4303             if Need_Subprogram_Instance_Body (N, Act_Decl_Id) then
4304
4305                Check_Forward_Instantiation (Gen_Decl);
4306
4307                --  The wrapper package is always delayed, because it does not
4308                --  constitute a freeze point, but to insure that the freeze
4309                --  node is placed properly, it is created directly when
4310                --  instantiating the body (otherwise the freeze node might
4311                --  appear to early for nested instantiations).
4312
4313             elsif Nkind (Parent (N)) = N_Compilation_Unit then
4314
4315                --  For ASIS purposes, indicate that the wrapper package has
4316                --  replaced the instantiation node.
4317
4318                Rewrite (N, Unit (Parent (N)));
4319                Set_Unit (Parent (N), N);
4320             end if;
4321
4322          elsif Nkind (Parent (N)) = N_Compilation_Unit then
4323
4324                --  Replace instance node for library-level instantiations of
4325                --  intrinsic subprograms, for ASIS use.
4326
4327                Rewrite (N, Unit (Parent (N)));
4328                Set_Unit (Parent (N), N);
4329          end if;
4330
4331          if Parent_Installed then
4332             Remove_Parent;
4333          end if;
4334
4335          Restore_Env;
4336          Env_Installed := False;
4337          Generic_Renamings.Set_Last (0);
4338          Generic_Renamings_HTable.Reset;
4339       end if;
4340
4341       <<Leave>>
4342          Analyze_Aspect_Specifications
4343            (N, Act_Decl_Id, Aspect_Specifications (N));
4344
4345    exception
4346       when Instantiation_Error =>
4347          if Parent_Installed then
4348             Remove_Parent;
4349          end if;
4350
4351          if Env_Installed then
4352             Restore_Env;
4353          end if;
4354    end Analyze_Subprogram_Instantiation;
4355
4356    -------------------------
4357    -- Get_Associated_Node --
4358    -------------------------
4359
4360    function Get_Associated_Node (N : Node_Id) return Node_Id is
4361       Assoc : Node_Id;
4362
4363    begin
4364       Assoc := Associated_Node (N);
4365
4366       if Nkind (Assoc) /= Nkind (N) then
4367          return Assoc;
4368
4369       elsif Nkind_In (Assoc, N_Aggregate, N_Extension_Aggregate) then
4370          return Assoc;
4371
4372       else
4373          --  If the node is part of an inner generic, it may itself have been
4374          --  remapped into a further generic copy. Associated_Node is otherwise
4375          --  used for the entity of the node, and will be of a different node
4376          --  kind, or else N has been rewritten as a literal or function call.
4377
4378          while Present (Associated_Node (Assoc))
4379            and then Nkind (Associated_Node (Assoc)) = Nkind (Assoc)
4380          loop
4381             Assoc := Associated_Node (Assoc);
4382          end loop;
4383
4384          --  Follow and additional link in case the final node was rewritten.
4385          --  This can only happen with nested generic units.
4386
4387          if (Nkind (Assoc) = N_Identifier or else Nkind (Assoc) in N_Op)
4388            and then Present (Associated_Node (Assoc))
4389            and then (Nkind_In (Associated_Node (Assoc), N_Function_Call,
4390                                                         N_Explicit_Dereference,
4391                                                         N_Integer_Literal,
4392                                                         N_Real_Literal,
4393                                                         N_String_Literal))
4394          then
4395             Assoc := Associated_Node (Assoc);
4396          end if;
4397
4398          return Assoc;
4399       end if;
4400    end Get_Associated_Node;
4401
4402    -------------------------------------------
4403    -- Build_Instance_Compilation_Unit_Nodes --
4404    -------------------------------------------
4405
4406    procedure Build_Instance_Compilation_Unit_Nodes
4407      (N        : Node_Id;
4408       Act_Body : Node_Id;
4409       Act_Decl : Node_Id)
4410    is
4411       Decl_Cunit : Node_Id;
4412       Body_Cunit : Node_Id;
4413       Citem      : Node_Id;
4414       New_Main   : constant Entity_Id := Defining_Entity (Act_Decl);
4415       Old_Main   : constant Entity_Id := Cunit_Entity (Main_Unit);
4416
4417    begin
4418       --  A new compilation unit node is built for the instance declaration
4419
4420       Decl_Cunit :=
4421         Make_Compilation_Unit (Sloc (N),
4422           Context_Items  => Empty_List,
4423           Unit           => Act_Decl,
4424           Aux_Decls_Node =>
4425             Make_Compilation_Unit_Aux (Sloc (N)));
4426
4427       Set_Parent_Spec   (Act_Decl, Parent_Spec (N));
4428
4429       --  The new compilation unit is linked to its body, but both share the
4430       --  same file, so we do not set Body_Required on the new unit so as not
4431       --  to create a spurious dependency on a non-existent body in the ali.
4432       --  This simplifies CodePeer unit traversal.
4433
4434       --  We use the original instantiation compilation unit as the resulting
4435       --  compilation unit of the instance, since this is the main unit.
4436
4437       Rewrite (N, Act_Body);
4438       Body_Cunit := Parent (N);
4439
4440       --  The two compilation unit nodes are linked by the Library_Unit field
4441
4442       Set_Library_Unit  (Decl_Cunit, Body_Cunit);
4443       Set_Library_Unit  (Body_Cunit, Decl_Cunit);
4444
4445       --  Preserve the private nature of the package if needed
4446
4447       Set_Private_Present (Decl_Cunit, Private_Present (Body_Cunit));
4448
4449       --  If the instance is not the main unit, its context, categorization
4450       --  and elaboration entity are not relevant to the compilation.
4451
4452       if Body_Cunit /= Cunit (Main_Unit) then
4453          Make_Instance_Unit (Body_Cunit, In_Main => False);
4454          return;
4455       end if;
4456
4457       --  The context clause items on the instantiation, which are now attached
4458       --  to the body compilation unit (since the body overwrote the original
4459       --  instantiation node), semantically belong on the spec, so copy them
4460       --  there. It's harmless to leave them on the body as well. In fact one
4461       --  could argue that they belong in both places.
4462
4463       Citem := First (Context_Items (Body_Cunit));
4464       while Present (Citem) loop
4465          Append (New_Copy (Citem), Context_Items (Decl_Cunit));
4466          Next (Citem);
4467       end loop;
4468
4469       --  Propagate categorization flags on packages, so that they appear in
4470       --  the ali file for the spec of the unit.
4471
4472       if Ekind (New_Main) = E_Package then
4473          Set_Is_Pure           (Old_Main, Is_Pure (New_Main));
4474          Set_Is_Preelaborated  (Old_Main, Is_Preelaborated (New_Main));
4475          Set_Is_Remote_Types   (Old_Main, Is_Remote_Types (New_Main));
4476          Set_Is_Shared_Passive (Old_Main, Is_Shared_Passive (New_Main));
4477          Set_Is_Remote_Call_Interface
4478            (Old_Main, Is_Remote_Call_Interface (New_Main));
4479       end if;
4480
4481       --  Make entry in Units table, so that binder can generate call to
4482       --  elaboration procedure for body, if any.
4483
4484       Make_Instance_Unit (Body_Cunit, In_Main => True);
4485       Main_Unit_Entity := New_Main;
4486       Set_Cunit_Entity (Main_Unit, Main_Unit_Entity);
4487
4488       --  Build elaboration entity, since the instance may certainly generate
4489       --  elaboration code requiring a flag for protection.
4490
4491       Build_Elaboration_Entity (Decl_Cunit, New_Main);
4492    end Build_Instance_Compilation_Unit_Nodes;
4493
4494    -----------------------------
4495    -- Check_Access_Definition --
4496    -----------------------------
4497
4498    procedure Check_Access_Definition (N : Node_Id) is
4499    begin
4500       pragma Assert
4501         (Ada_Version >= Ada_2005
4502            and then Present (Access_Definition (N)));
4503       null;
4504    end Check_Access_Definition;
4505
4506    -----------------------------------
4507    -- Check_Formal_Package_Instance --
4508    -----------------------------------
4509
4510    --  If the formal has specific parameters, they must match those of the
4511    --  actual. Both of them are instances, and the renaming declarations for
4512    --  their formal parameters appear in the same order in both. The analyzed
4513    --  formal has been analyzed in the context of the current instance.
4514
4515    procedure Check_Formal_Package_Instance
4516      (Formal_Pack : Entity_Id;
4517       Actual_Pack : Entity_Id)
4518    is
4519       E1 : Entity_Id := First_Entity (Actual_Pack);
4520       E2 : Entity_Id := First_Entity (Formal_Pack);
4521
4522       Expr1 : Node_Id;
4523       Expr2 : Node_Id;
4524
4525       procedure Check_Mismatch (B : Boolean);
4526       --  Common error routine for mismatch between the parameters of the
4527       --  actual instance and those of the formal package.
4528
4529       function Same_Instantiated_Constant (E1, E2 : Entity_Id) return Boolean;
4530       --  The formal may come from a nested formal package, and the actual may
4531       --  have been constant-folded. To determine whether the two denote the
4532       --  same entity we may have to traverse several definitions to recover
4533       --  the ultimate entity that they refer to.
4534
4535       function Same_Instantiated_Variable (E1, E2 : Entity_Id) return Boolean;
4536       --  Similarly, if the formal comes from a nested formal package, the
4537       --  actual may designate the formal through multiple renamings, which
4538       --  have to be followed to determine the original variable in question.
4539
4540       --------------------
4541       -- Check_Mismatch --
4542       --------------------
4543
4544       procedure Check_Mismatch (B : Boolean) is
4545          Kind : constant Node_Kind := Nkind (Parent (E2));
4546
4547       begin
4548          if Kind = N_Formal_Type_Declaration then
4549             return;
4550
4551          elsif Nkind_In (Kind, N_Formal_Object_Declaration,
4552                                N_Formal_Package_Declaration)
4553            or else Kind in N_Formal_Subprogram_Declaration
4554          then
4555             null;
4556
4557          elsif B then
4558             Error_Msg_NE
4559               ("actual for & in actual instance does not match formal",
4560                Parent (Actual_Pack), E1);
4561          end if;
4562       end Check_Mismatch;
4563
4564       --------------------------------
4565       -- Same_Instantiated_Constant --
4566       --------------------------------
4567
4568       function Same_Instantiated_Constant
4569         (E1, E2 : Entity_Id) return Boolean
4570       is
4571          Ent : Entity_Id;
4572
4573       begin
4574          Ent := E2;
4575          while Present (Ent) loop
4576             if E1 = Ent then
4577                return True;
4578
4579             elsif Ekind (Ent) /= E_Constant then
4580                return False;
4581
4582             elsif Is_Entity_Name (Constant_Value (Ent)) then
4583                if  Entity (Constant_Value (Ent)) = E1 then
4584                   return True;
4585                else
4586                   Ent := Entity (Constant_Value (Ent));
4587                end if;
4588
4589             --  The actual may be a constant that has been folded. Recover
4590             --  original name.
4591
4592             elsif Is_Entity_Name (Original_Node (Constant_Value (Ent))) then
4593                   Ent := Entity (Original_Node (Constant_Value (Ent)));
4594             else
4595                return False;
4596             end if;
4597          end loop;
4598
4599          return False;
4600       end Same_Instantiated_Constant;
4601
4602       --------------------------------
4603       -- Same_Instantiated_Variable --
4604       --------------------------------
4605
4606       function Same_Instantiated_Variable
4607         (E1, E2 : Entity_Id) return Boolean
4608       is
4609          function Original_Entity (E : Entity_Id) return Entity_Id;
4610          --  Follow chain of renamings to the ultimate ancestor
4611
4612          ---------------------
4613          -- Original_Entity --
4614          ---------------------
4615
4616          function Original_Entity (E : Entity_Id) return Entity_Id is
4617             Orig : Entity_Id;
4618
4619          begin
4620             Orig := E;
4621             while Nkind (Parent (Orig)) = N_Object_Renaming_Declaration
4622               and then Present (Renamed_Object (Orig))
4623               and then Is_Entity_Name (Renamed_Object (Orig))
4624             loop
4625                Orig := Entity (Renamed_Object (Orig));
4626             end loop;
4627
4628             return Orig;
4629          end Original_Entity;
4630
4631       --  Start of processing for Same_Instantiated_Variable
4632
4633       begin
4634          return Ekind (E1) = Ekind (E2)
4635            and then Original_Entity (E1) = Original_Entity (E2);
4636       end Same_Instantiated_Variable;
4637
4638    --  Start of processing for Check_Formal_Package_Instance
4639
4640    begin
4641       while Present (E1)
4642         and then Present (E2)
4643       loop
4644          exit when Ekind (E1) = E_Package
4645            and then Renamed_Entity (E1) = Renamed_Entity (Actual_Pack);
4646
4647          --  If the formal is the renaming of the formal package, this
4648          --  is the end of its formal part, which may occur before the
4649          --  end of the formal part in the actual in the presence of
4650          --  defaulted parameters in the formal package.
4651
4652          exit when Nkind (Parent (E2)) = N_Package_Renaming_Declaration
4653            and then Renamed_Entity (E2) = Scope (E2);
4654
4655          --  The analysis of the actual may generate additional internal
4656          --  entities. If the formal is defaulted, there is no corresponding
4657          --  analysis and the internal entities must be skipped, until we
4658          --  find corresponding entities again.
4659
4660          if Comes_From_Source (E2)
4661            and then not Comes_From_Source (E1)
4662            and then Chars (E1) /= Chars (E2)
4663          then
4664             while Present (E1)
4665               and then  Chars (E1) /= Chars (E2)
4666             loop
4667                Next_Entity (E1);
4668             end loop;
4669          end if;
4670
4671          if No (E1) then
4672             return;
4673
4674          --  If the formal entity comes from a formal declaration, it was
4675          --  defaulted in the formal package, and no check is needed on it.
4676
4677          elsif Nkind (Parent (E2)) =  N_Formal_Object_Declaration then
4678             goto Next_E;
4679
4680          elsif Is_Type (E1) then
4681
4682             --  Subtypes must statically match. E1, E2 are the local entities
4683             --  that are subtypes of the actuals. Itypes generated for other
4684             --  parameters need not be checked, the check will be performed
4685             --  on the parameters themselves.
4686
4687             --  If E2 is a formal type declaration, it is a defaulted parameter
4688             --  and needs no checking.
4689
4690             if not Is_Itype (E1)
4691               and then not Is_Itype (E2)
4692             then
4693                Check_Mismatch
4694                  (not Is_Type (E2)
4695                    or else Etype (E1) /= Etype (E2)
4696                    or else not Subtypes_Statically_Match (E1, E2));
4697             end if;
4698
4699          elsif Ekind (E1) = E_Constant then
4700
4701             --  IN parameters must denote the same static value, or the same
4702             --  constant, or the literal null.
4703
4704             Expr1 := Expression (Parent (E1));
4705
4706             if Ekind (E2) /= E_Constant then
4707                Check_Mismatch (True);
4708                goto Next_E;
4709             else
4710                Expr2 := Expression (Parent (E2));
4711             end if;
4712
4713             if Is_Static_Expression (Expr1) then
4714
4715                if not Is_Static_Expression (Expr2) then
4716                   Check_Mismatch (True);
4717
4718                elsif Is_Discrete_Type (Etype (E1)) then
4719                   declare
4720                      V1 : constant Uint := Expr_Value (Expr1);
4721                      V2 : constant Uint := Expr_Value (Expr2);
4722                   begin
4723                      Check_Mismatch (V1 /= V2);
4724                   end;
4725
4726                elsif Is_Real_Type (Etype (E1)) then
4727                   declare
4728                      V1 : constant Ureal := Expr_Value_R (Expr1);
4729                      V2 : constant Ureal := Expr_Value_R (Expr2);
4730                   begin
4731                      Check_Mismatch (V1 /= V2);
4732                   end;
4733
4734                elsif Is_String_Type (Etype (E1))
4735                  and then Nkind (Expr1) = N_String_Literal
4736                then
4737                   if Nkind (Expr2) /= N_String_Literal then
4738                      Check_Mismatch (True);
4739                   else
4740                      Check_Mismatch
4741                        (not String_Equal (Strval (Expr1), Strval (Expr2)));
4742                   end if;
4743                end if;
4744
4745             elsif Is_Entity_Name (Expr1) then
4746                if Is_Entity_Name (Expr2) then
4747                   if Entity (Expr1) = Entity (Expr2) then
4748                      null;
4749                   else
4750                      Check_Mismatch
4751                        (not Same_Instantiated_Constant
4752                          (Entity (Expr1), Entity (Expr2)));
4753                   end if;
4754                else
4755                   Check_Mismatch (True);
4756                end if;
4757
4758             elsif Is_Entity_Name (Original_Node (Expr1))
4759               and then Is_Entity_Name (Expr2)
4760             and then
4761               Same_Instantiated_Constant
4762                 (Entity (Original_Node (Expr1)), Entity (Expr2))
4763             then
4764                null;
4765
4766             elsif Nkind (Expr1) = N_Null then
4767                Check_Mismatch (Nkind (Expr1) /= N_Null);
4768
4769             else
4770                Check_Mismatch (True);
4771             end if;
4772
4773          elsif Ekind (E1) = E_Variable then
4774             Check_Mismatch (not Same_Instantiated_Variable (E1, E2));
4775
4776          elsif Ekind (E1) = E_Package then
4777             Check_Mismatch
4778               (Ekind (E1) /= Ekind (E2)
4779                 or else Renamed_Object (E1) /= Renamed_Object (E2));
4780
4781          elsif Is_Overloadable (E1) then
4782
4783             --  Verify that the actual subprograms match. Note that actuals
4784             --  that are attributes are rewritten as subprograms. If the
4785             --  subprogram in the formal package is defaulted, no check is
4786             --  needed. Note that this can only happen in Ada 2005 when the
4787             --  formal package can be partially parameterized.
4788
4789             if Nkind (Unit_Declaration_Node (E1)) =
4790                                            N_Subprogram_Renaming_Declaration
4791               and then From_Default (Unit_Declaration_Node (E1))
4792             then
4793                null;
4794
4795             else
4796                Check_Mismatch
4797                  (Ekind (E2) /= Ekind (E1) or else (Alias (E1)) /= Alias (E2));
4798             end if;
4799
4800          else
4801             raise Program_Error;
4802          end if;
4803
4804          <<Next_E>>
4805             Next_Entity (E1);
4806             Next_Entity (E2);
4807       end loop;
4808    end Check_Formal_Package_Instance;
4809
4810    ---------------------------
4811    -- Check_Formal_Packages --
4812    ---------------------------
4813
4814    procedure Check_Formal_Packages (P_Id : Entity_Id) is
4815       E        : Entity_Id;
4816       Formal_P : Entity_Id;
4817
4818    begin
4819       --  Iterate through the declarations in the instance, looking for package
4820       --  renaming declarations that denote instances of formal packages. Stop
4821       --  when we find the renaming of the current package itself. The
4822       --  declaration for a formal package without a box is followed by an
4823       --  internal entity that repeats the instantiation.
4824
4825       E := First_Entity (P_Id);
4826       while Present (E) loop
4827          if Ekind (E) = E_Package then
4828             if Renamed_Object (E) = P_Id then
4829                exit;
4830
4831             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
4832                null;
4833
4834             elsif not Box_Present (Parent (Associated_Formal_Package (E))) then
4835                Formal_P := Next_Entity (E);
4836                Check_Formal_Package_Instance (Formal_P, E);
4837
4838                --  After checking, remove the internal validating package. It
4839                --  is only needed for semantic checks, and as it may contain
4840                --  generic formal declarations it should not reach gigi.
4841
4842                Remove (Unit_Declaration_Node (Formal_P));
4843             end if;
4844          end if;
4845
4846          Next_Entity (E);
4847       end loop;
4848    end Check_Formal_Packages;
4849
4850    ---------------------------------
4851    -- Check_Forward_Instantiation --
4852    ---------------------------------
4853
4854    procedure Check_Forward_Instantiation (Decl : Node_Id) is
4855       S        : Entity_Id;
4856       Gen_Comp : Entity_Id := Cunit_Entity (Get_Source_Unit (Decl));
4857
4858    begin
4859       --  The instantiation appears before the generic body if we are in the
4860       --  scope of the unit containing the generic, either in its spec or in
4861       --  the package body, and before the generic body.
4862
4863       if Ekind (Gen_Comp) = E_Package_Body then
4864          Gen_Comp := Spec_Entity (Gen_Comp);
4865       end if;
4866
4867       if In_Open_Scopes (Gen_Comp)
4868         and then No (Corresponding_Body (Decl))
4869       then
4870          S := Current_Scope;
4871
4872          while Present (S)
4873            and then not Is_Compilation_Unit (S)
4874            and then not Is_Child_Unit (S)
4875          loop
4876             if Ekind (S) = E_Package then
4877                Set_Has_Forward_Instantiation (S);
4878             end if;
4879
4880             S := Scope (S);
4881          end loop;
4882       end if;
4883    end Check_Forward_Instantiation;
4884
4885    ---------------------------
4886    -- Check_Generic_Actuals --
4887    ---------------------------
4888
4889    --  The visibility of the actuals may be different between the point of
4890    --  generic instantiation and the instantiation of the body.
4891
4892    procedure Check_Generic_Actuals
4893      (Instance      : Entity_Id;
4894       Is_Formal_Box : Boolean)
4895    is
4896       E      : Entity_Id;
4897       Astype : Entity_Id;
4898
4899       function Denotes_Previous_Actual (Typ : Entity_Id) return Boolean;
4900       --  For a formal that is an array type, the component type is often a
4901       --  previous formal in the same unit. The privacy status of the component
4902       --  type will have been examined earlier in the traversal of the
4903       --  corresponding actuals, and this status should not be modified for the
4904       --  array type itself.
4905       --
4906       --  To detect this case we have to rescan the list of formals, which
4907       --  is usually short enough to ignore the resulting inefficiency.
4908
4909       -----------------------------
4910       -- Denotes_Previous_Actual --
4911       -----------------------------
4912
4913       function Denotes_Previous_Actual (Typ : Entity_Id) return Boolean is
4914          Prev : Entity_Id;
4915
4916       begin
4917          Prev := First_Entity (Instance);
4918          while Present (Prev) loop
4919             if Is_Type (Prev)
4920               and then Nkind (Parent (Prev)) = N_Subtype_Declaration
4921               and then Is_Entity_Name (Subtype_Indication (Parent (Prev)))
4922               and then Entity (Subtype_Indication (Parent (Prev))) = Typ
4923             then
4924                return True;
4925
4926             elsif Prev = E then
4927                return False;
4928
4929             else
4930                Next_Entity (Prev);
4931             end if;
4932          end loop;
4933
4934          return False;
4935       end Denotes_Previous_Actual;
4936
4937    --  Start of processing for Check_Generic_Actuals
4938
4939    begin
4940       E := First_Entity (Instance);
4941       while Present (E) loop
4942          if Is_Type (E)
4943            and then Nkind (Parent (E)) = N_Subtype_Declaration
4944            and then Scope (Etype (E)) /= Instance
4945            and then Is_Entity_Name (Subtype_Indication (Parent (E)))
4946          then
4947             if Is_Array_Type (E)
4948               and then Denotes_Previous_Actual (Component_Type (E))
4949             then
4950                null;
4951             else
4952                Check_Private_View (Subtype_Indication (Parent (E)));
4953             end if;
4954             Set_Is_Generic_Actual_Type (E, True);
4955             Set_Is_Hidden (E, False);
4956             Set_Is_Potentially_Use_Visible (E,
4957               In_Use (Instance));
4958
4959             --  We constructed the generic actual type as a subtype of the
4960             --  supplied type. This means that it normally would not inherit
4961             --  subtype specific attributes of the actual, which is wrong for
4962             --  the generic case.
4963
4964             Astype := Ancestor_Subtype (E);
4965
4966             if No (Astype) then
4967
4968                --  This can happen when E is an itype that is the full view of
4969                --  a private type completed, e.g. with a constrained array. In
4970                --  that case, use the first subtype, which will carry size
4971                --  information. The base type itself is unconstrained and will
4972                --  not carry it.
4973
4974                Astype := First_Subtype (E);
4975             end if;
4976
4977             Set_Size_Info      (E,                (Astype));
4978             Set_RM_Size        (E, RM_Size        (Astype));
4979             Set_First_Rep_Item (E, First_Rep_Item (Astype));
4980
4981             if Is_Discrete_Or_Fixed_Point_Type (E) then
4982                Set_RM_Size (E, RM_Size (Astype));
4983
4984             --  In  nested instances, the base type of an access actual
4985             --  may itself be private, and need to be exchanged.
4986
4987             elsif Is_Access_Type (E)
4988               and then Is_Private_Type (Etype (E))
4989             then
4990                Check_Private_View
4991                  (New_Occurrence_Of (Etype (E), Sloc (Instance)));
4992             end if;
4993
4994          elsif Ekind (E) = E_Package then
4995
4996             --  If this is the renaming for the current instance, we're done.
4997             --  Otherwise it is a formal package. If the corresponding formal
4998             --  was declared with a box, the (instantiations of the) generic
4999             --  formal part are also visible. Otherwise, ignore the entity
5000             --  created to validate the actuals.
5001
5002             if Renamed_Object (E) = Instance then
5003                exit;
5004
5005             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
5006                null;
5007
5008             --  The visibility of a formal of an enclosing generic is already
5009             --  correct.
5010
5011             elsif Denotes_Formal_Package (E) then
5012                null;
5013
5014             elsif Present (Associated_Formal_Package (E))
5015               and then not Is_Generic_Formal (E)
5016             then
5017                if Box_Present (Parent (Associated_Formal_Package (E))) then
5018                   Check_Generic_Actuals (Renamed_Object (E), True);
5019
5020                else
5021                   Check_Generic_Actuals (Renamed_Object (E), False);
5022                end if;
5023
5024                Set_Is_Hidden (E, False);
5025             end if;
5026
5027          --  If this is a subprogram instance (in a wrapper package) the
5028          --  actual is fully visible.
5029
5030          elsif Is_Wrapper_Package (Instance) then
5031             Set_Is_Hidden (E, False);
5032
5033          --  If the formal package is declared with a box, or if the formal
5034          --  parameter is defaulted, it is visible in the body.
5035
5036          elsif Is_Formal_Box
5037            or else Is_Visible_Formal (E)
5038          then
5039             Set_Is_Hidden (E, False);
5040          end if;
5041
5042          Next_Entity (E);
5043       end loop;
5044    end Check_Generic_Actuals;
5045
5046    ------------------------------
5047    -- Check_Generic_Child_Unit --
5048    ------------------------------
5049
5050    procedure Check_Generic_Child_Unit
5051      (Gen_Id           : Node_Id;
5052       Parent_Installed : in out Boolean)
5053    is
5054       Loc      : constant Source_Ptr := Sloc (Gen_Id);
5055       Gen_Par  : Entity_Id := Empty;
5056       E        : Entity_Id;
5057       Inst_Par : Entity_Id;
5058       S        : Node_Id;
5059
5060       function Find_Generic_Child
5061         (Scop : Entity_Id;
5062          Id   : Node_Id) return Entity_Id;
5063       --  Search generic parent for possible child unit with the given name
5064
5065       function In_Enclosing_Instance return Boolean;
5066       --  Within an instance of the parent, the child unit may be denoted
5067       --  by a simple name, or an abbreviated expanded name. Examine enclosing
5068       --  scopes to locate a possible parent instantiation.
5069
5070       ------------------------
5071       -- Find_Generic_Child --
5072       ------------------------
5073
5074       function Find_Generic_Child
5075         (Scop : Entity_Id;
5076          Id   : Node_Id) return Entity_Id
5077       is
5078          E : Entity_Id;
5079
5080       begin
5081          --  If entity of name is already set, instance has already been
5082          --  resolved, e.g. in an enclosing instantiation.
5083
5084          if Present (Entity (Id)) then
5085             if Scope (Entity (Id)) = Scop then
5086                return Entity (Id);
5087             else
5088                return Empty;
5089             end if;
5090
5091          else
5092             E := First_Entity (Scop);
5093             while Present (E) loop
5094                if Chars (E) = Chars (Id)
5095                  and then Is_Child_Unit (E)
5096                then
5097                   if Is_Child_Unit (E)
5098                     and then not Is_Visible_Child_Unit (E)
5099                   then
5100                      Error_Msg_NE
5101                        ("generic child unit& is not visible", Gen_Id, E);
5102                   end if;
5103
5104                   Set_Entity (Id, E);
5105                   return E;
5106                end if;
5107
5108                Next_Entity (E);
5109             end loop;
5110
5111             return Empty;
5112          end if;
5113       end Find_Generic_Child;
5114
5115       ---------------------------
5116       -- In_Enclosing_Instance --
5117       ---------------------------
5118
5119       function In_Enclosing_Instance return Boolean is
5120          Enclosing_Instance : Node_Id;
5121          Instance_Decl      : Node_Id;
5122
5123       begin
5124          --  We do not inline any call that contains instantiations, except
5125          --  for instantiations of Unchecked_Conversion, so if we are within
5126          --  an inlined body the current instance does not require parents.
5127
5128          if In_Inlined_Body then
5129             pragma Assert (Chars (Gen_Id) = Name_Unchecked_Conversion);
5130             return False;
5131          end if;
5132
5133          --  Loop to check enclosing scopes
5134
5135          Enclosing_Instance := Current_Scope;
5136          while Present (Enclosing_Instance) loop
5137             Instance_Decl := Unit_Declaration_Node (Enclosing_Instance);
5138
5139             if Ekind (Enclosing_Instance) = E_Package
5140               and then Is_Generic_Instance (Enclosing_Instance)
5141               and then Present
5142                 (Generic_Parent (Specification (Instance_Decl)))
5143             then
5144                --  Check whether the generic we are looking for is a child of
5145                --  this instance.
5146
5147                E := Find_Generic_Child
5148                       (Generic_Parent (Specification (Instance_Decl)), Gen_Id);
5149                exit when Present (E);
5150
5151             else
5152                E := Empty;
5153             end if;
5154
5155             Enclosing_Instance := Scope (Enclosing_Instance);
5156          end loop;
5157
5158          if No (E) then
5159
5160             --  Not a child unit
5161
5162             Analyze (Gen_Id);
5163             return False;
5164
5165          else
5166             Rewrite (Gen_Id,
5167               Make_Expanded_Name (Loc,
5168                 Chars         => Chars (E),
5169                 Prefix        => New_Occurrence_Of (Enclosing_Instance, Loc),
5170                 Selector_Name => New_Occurrence_Of (E, Loc)));
5171
5172             Set_Entity (Gen_Id, E);
5173             Set_Etype  (Gen_Id, Etype (E));
5174             Parent_Installed := False;      -- Already in scope.
5175             return True;
5176          end if;
5177       end In_Enclosing_Instance;
5178
5179    --  Start of processing for Check_Generic_Child_Unit
5180
5181    begin
5182       --  If the name of the generic is given by a selected component, it may
5183       --  be the name of a generic child unit, and the prefix is the name of an
5184       --  instance of the parent, in which case the child unit must be visible.
5185       --  If this instance is not in scope, it must be placed there and removed
5186       --  after instantiation, because what is being instantiated is not the
5187       --  original child, but the corresponding child present in the instance
5188       --  of the parent.
5189
5190       --  If the child is instantiated within the parent, it can be given by
5191       --  a simple name. In this case the instance is already in scope, but
5192       --  the child generic must be recovered from the generic parent as well.
5193
5194       if Nkind (Gen_Id) = N_Selected_Component then
5195          S := Selector_Name (Gen_Id);
5196          Analyze (Prefix (Gen_Id));
5197          Inst_Par := Entity (Prefix (Gen_Id));
5198
5199          if Ekind (Inst_Par) = E_Package
5200            and then Present (Renamed_Object (Inst_Par))
5201          then
5202             Inst_Par := Renamed_Object (Inst_Par);
5203          end if;
5204
5205          if Ekind (Inst_Par) = E_Package then
5206             if Nkind (Parent (Inst_Par)) = N_Package_Specification then
5207                Gen_Par := Generic_Parent (Parent (Inst_Par));
5208
5209             elsif Nkind (Parent (Inst_Par)) = N_Defining_Program_Unit_Name
5210               and then
5211                 Nkind (Parent (Parent (Inst_Par))) = N_Package_Specification
5212             then
5213                Gen_Par := Generic_Parent (Parent (Parent (Inst_Par)));
5214             end if;
5215
5216          elsif Ekind (Inst_Par) = E_Generic_Package
5217            and then Nkind (Parent (Gen_Id)) = N_Formal_Package_Declaration
5218          then
5219             --  A formal package may be a real child package, and not the
5220             --  implicit instance within a parent. In this case the child is
5221             --  not visible and has to be retrieved explicitly as well.
5222
5223             Gen_Par := Inst_Par;
5224          end if;
5225
5226          if Present (Gen_Par) then
5227
5228             --  The prefix denotes an instantiation. The entity itself may be a
5229             --  nested generic, or a child unit.
5230
5231             E := Find_Generic_Child (Gen_Par, S);
5232
5233             if Present (E) then
5234                Change_Selected_Component_To_Expanded_Name (Gen_Id);
5235                Set_Entity (Gen_Id, E);
5236                Set_Etype (Gen_Id, Etype (E));
5237                Set_Entity (S, E);
5238                Set_Etype (S, Etype (E));
5239
5240                --  Indicate that this is a reference to the parent
5241
5242                if In_Extended_Main_Source_Unit (Gen_Id) then
5243                   Set_Is_Instantiated (Inst_Par);
5244                end if;
5245
5246                --  A common mistake is to replicate the naming scheme of a
5247                --  hierarchy by instantiating a generic child directly, rather
5248                --  than the implicit child in a parent instance:
5249
5250                --  generic .. package Gpar is ..
5251                --  generic .. package Gpar.Child is ..
5252                --  package Par is new Gpar ();
5253
5254                --  with Gpar.Child;
5255                --  package Par.Child is new Gpar.Child ();
5256                --                           rather than Par.Child
5257
5258                --  In this case the instantiation is within Par, which is an
5259                --  instance, but Gpar does not denote Par because we are not IN
5260                --  the instance of Gpar, so this is illegal. The test below
5261                --  recognizes this particular case.
5262
5263                if Is_Child_Unit (E)
5264                  and then not Comes_From_Source (Entity (Prefix (Gen_Id)))
5265                  and then (not In_Instance
5266                              or else Nkind (Parent (Parent (Gen_Id))) =
5267                                                          N_Compilation_Unit)
5268                then
5269                   Error_Msg_N
5270                     ("prefix of generic child unit must be instance of parent",
5271                       Gen_Id);
5272                end if;
5273
5274                if not In_Open_Scopes (Inst_Par)
5275                  and then Nkind (Parent (Gen_Id)) not in
5276                                            N_Generic_Renaming_Declaration
5277                then
5278                   Install_Parent (Inst_Par);
5279                   Parent_Installed := True;
5280
5281                elsif In_Open_Scopes (Inst_Par) then
5282
5283                   --  If the parent is already installed, install the actuals
5284                   --  for its formal packages. This is necessary when the
5285                   --  child instance is a child of the parent instance:
5286                   --  in this case, the parent is placed on the scope stack
5287                   --  but the formal packages are not made visible.
5288
5289                   Install_Formal_Packages (Inst_Par);
5290                end if;
5291
5292             else
5293                --  If the generic parent does not contain an entity that
5294                --  corresponds to the selector, the instance doesn't either.
5295                --  Analyzing the node will yield the appropriate error message.
5296                --  If the entity is not a child unit, then it is an inner
5297                --  generic in the parent.
5298
5299                Analyze (Gen_Id);
5300             end if;
5301
5302          else
5303             Analyze (Gen_Id);
5304
5305             if Is_Child_Unit (Entity (Gen_Id))
5306               and then
5307                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
5308               and then not In_Open_Scopes (Inst_Par)
5309             then
5310                Install_Parent (Inst_Par);
5311                Parent_Installed := True;
5312
5313             --  The generic unit may be the renaming of the implicit child
5314             --  present in an instance. In that case the parent instance is
5315             --  obtained from the name of the renamed entity.
5316
5317             elsif Ekind (Entity (Gen_Id)) = E_Generic_Package
5318               and then Present (Renamed_Entity (Entity (Gen_Id)))
5319               and then Is_Child_Unit (Renamed_Entity (Entity (Gen_Id)))
5320             then
5321                declare
5322                   Renamed_Package : constant Node_Id :=
5323                                       Name (Parent (Entity (Gen_Id)));
5324                begin
5325                   if Nkind (Renamed_Package) = N_Expanded_Name then
5326                      Inst_Par := Entity (Prefix (Renamed_Package));
5327                      Install_Parent (Inst_Par);
5328                      Parent_Installed := True;
5329                   end if;
5330                end;
5331             end if;
5332          end if;
5333
5334       elsif Nkind (Gen_Id) = N_Expanded_Name then
5335
5336          --  Entity already present, analyze prefix, whose meaning may be
5337          --  an instance in the current context. If it is an instance of
5338          --  a relative within another, the proper parent may still have
5339          --  to be installed, if they are not of the same generation.
5340
5341          Analyze (Prefix (Gen_Id));
5342
5343          --  In the unlikely case that a local declaration hides the name
5344          --  of the parent package, locate it on the homonym chain. If the
5345          --  context is an instance of the parent, the renaming entity is
5346          --  flagged as such.
5347
5348          Inst_Par := Entity (Prefix (Gen_Id));
5349          while Present (Inst_Par)
5350            and then not Is_Package_Or_Generic_Package (Inst_Par)
5351          loop
5352             Inst_Par := Homonym (Inst_Par);
5353          end loop;
5354
5355          pragma Assert (Present (Inst_Par));
5356          Set_Entity (Prefix (Gen_Id), Inst_Par);
5357
5358          if In_Enclosing_Instance then
5359             null;
5360
5361          elsif Present (Entity (Gen_Id))
5362            and then Is_Child_Unit (Entity (Gen_Id))
5363            and then not In_Open_Scopes (Inst_Par)
5364          then
5365             Install_Parent (Inst_Par);
5366             Parent_Installed := True;
5367          end if;
5368
5369       elsif In_Enclosing_Instance then
5370
5371          --  The child unit is found in some enclosing scope
5372
5373          null;
5374
5375       else
5376          Analyze (Gen_Id);
5377
5378          --  If this is the renaming of the implicit child in a parent
5379          --  instance, recover the parent name and install it.
5380
5381          if Is_Entity_Name (Gen_Id) then
5382             E := Entity (Gen_Id);
5383
5384             if Is_Generic_Unit (E)
5385               and then Nkind (Parent (E)) in N_Generic_Renaming_Declaration
5386               and then Is_Child_Unit (Renamed_Object (E))
5387               and then Is_Generic_Unit (Scope (Renamed_Object (E)))
5388               and then Nkind (Name (Parent (E))) = N_Expanded_Name
5389             then
5390                Rewrite (Gen_Id,
5391                  New_Copy_Tree (Name (Parent (E))));
5392                Inst_Par := Entity (Prefix (Gen_Id));
5393
5394                if not In_Open_Scopes (Inst_Par) then
5395                   Install_Parent (Inst_Par);
5396                   Parent_Installed := True;
5397                end if;
5398
5399             --  If it is a child unit of a non-generic parent, it may be
5400             --  use-visible and given by a direct name. Install parent as
5401             --  for other cases.
5402
5403             elsif Is_Generic_Unit (E)
5404               and then Is_Child_Unit (E)
5405               and then
5406                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
5407               and then not Is_Generic_Unit (Scope (E))
5408             then
5409                if not In_Open_Scopes (Scope (E)) then
5410                   Install_Parent (Scope (E));
5411                   Parent_Installed := True;
5412                end if;
5413             end if;
5414          end if;
5415       end if;
5416    end Check_Generic_Child_Unit;
5417
5418    -----------------------------
5419    -- Check_Hidden_Child_Unit --
5420    -----------------------------
5421
5422    procedure Check_Hidden_Child_Unit
5423      (N           : Node_Id;
5424       Gen_Unit    : Entity_Id;
5425       Act_Decl_Id : Entity_Id)
5426    is
5427       Gen_Id : constant Node_Id := Name (N);
5428
5429    begin
5430       if Is_Child_Unit (Gen_Unit)
5431         and then Is_Child_Unit (Act_Decl_Id)
5432         and then Nkind (Gen_Id) = N_Expanded_Name
5433         and then Entity (Prefix (Gen_Id)) = Scope (Act_Decl_Id)
5434         and then Chars (Gen_Unit) = Chars (Act_Decl_Id)
5435       then
5436          Error_Msg_Node_2 := Scope (Act_Decl_Id);
5437          Error_Msg_NE
5438            ("generic unit & is implicitly declared in &",
5439              Defining_Unit_Name (N), Gen_Unit);
5440          Error_Msg_N ("\instance must have different name",
5441            Defining_Unit_Name (N));
5442       end if;
5443    end Check_Hidden_Child_Unit;
5444
5445    ------------------------
5446    -- Check_Private_View --
5447    ------------------------
5448
5449    procedure Check_Private_View (N : Node_Id) is
5450       T : constant Entity_Id := Etype (N);
5451       BT : Entity_Id;
5452
5453    begin
5454       --  Exchange views if the type was not private in the generic but is
5455       --  private at the point of instantiation. Do not exchange views if
5456       --  the scope of the type is in scope. This can happen if both generic
5457       --  and instance are sibling units, or if type is defined in a parent.
5458       --  In this case the visibility of the type will be correct for all
5459       --  semantic checks.
5460
5461       if Present (T) then
5462          BT := Base_Type (T);
5463
5464          if Is_Private_Type (T)
5465            and then not Has_Private_View (N)
5466            and then Present (Full_View (T))
5467            and then not In_Open_Scopes (Scope (T))
5468          then
5469             --  In the generic, the full type was visible. Save the private
5470             --  entity, for subsequent exchange.
5471
5472             Switch_View (T);
5473
5474          elsif Has_Private_View (N)
5475            and then not Is_Private_Type (T)
5476            and then not Has_Been_Exchanged (T)
5477            and then Etype (Get_Associated_Node (N)) /= T
5478          then
5479             --  Only the private declaration was visible in the generic. If
5480             --  the type appears in a subtype declaration, the subtype in the
5481             --  instance must have a view compatible with that of its parent,
5482             --  which must be exchanged (see corresponding code in Restore_
5483             --  Private_Views). Otherwise, if the type is defined in a parent
5484             --  unit, leave full visibility within instance, which is safe.
5485
5486             if In_Open_Scopes (Scope (Base_Type (T)))
5487               and then not Is_Private_Type (Base_Type (T))
5488               and then Comes_From_Source (Base_Type (T))
5489             then
5490                null;
5491
5492             elsif Nkind (Parent (N)) = N_Subtype_Declaration
5493               or else not In_Private_Part (Scope (Base_Type (T)))
5494             then
5495                Prepend_Elmt (T, Exchanged_Views);
5496                Exchange_Declarations (Etype (Get_Associated_Node (N)));
5497             end if;
5498
5499          --  For composite types with inconsistent representation exchange
5500          --  component types accordingly.
5501
5502          elsif Is_Access_Type (T)
5503            and then Is_Private_Type (Designated_Type (T))
5504            and then not Has_Private_View (N)
5505            and then Present (Full_View (Designated_Type (T)))
5506          then
5507             Switch_View (Designated_Type (T));
5508
5509          elsif Is_Array_Type (T) then
5510             if Is_Private_Type (Component_Type (T))
5511               and then not Has_Private_View (N)
5512               and then Present (Full_View (Component_Type (T)))
5513             then
5514                Switch_View (Component_Type (T));
5515             end if;
5516
5517             --  The normal exchange mechanism relies on the setting of a
5518             --  flag on the reference in the generic. However, an additional
5519             --  mechanism is needed for types that are not explicitly mentioned
5520             --  in the generic, but may be needed in expanded code in the
5521             --  instance. This includes component types of arrays and
5522             --  designated types of access types. This processing must also
5523             --  include the index types of arrays which we take care of here.
5524
5525             declare
5526                Indx : Node_Id;
5527                Typ  : Entity_Id;
5528
5529             begin
5530                Indx := First_Index (T);
5531                Typ  := Base_Type (Etype (Indx));
5532                while Present (Indx) loop
5533                   if Is_Private_Type (Typ)
5534                     and then Present (Full_View (Typ))
5535                   then
5536                      Switch_View (Typ);
5537                   end if;
5538
5539                   Next_Index (Indx);
5540                end loop;
5541             end;
5542
5543          elsif Is_Private_Type (T)
5544            and then Present (Full_View (T))
5545            and then Is_Array_Type (Full_View (T))
5546            and then Is_Private_Type (Component_Type (Full_View (T)))
5547          then
5548             Switch_View (T);
5549
5550          --  Finally, a non-private subtype may have a private base type, which
5551          --  must be exchanged for consistency. This can happen when a package
5552          --  body is instantiated, when the scope stack is empty but in fact
5553          --  the subtype and the base type are declared in an enclosing scope.
5554
5555          --  Note that in this case we introduce an inconsistency in the view
5556          --  set, because we switch the base type BT, but there could be some
5557          --  private dependent subtypes of BT which remain unswitched. Such
5558          --  subtypes might need to be switched at a later point (see specific
5559          --  provision for that case in Switch_View).
5560
5561          elsif not Is_Private_Type (T)
5562            and then not Has_Private_View (N)
5563            and then Is_Private_Type (BT)
5564            and then Present (Full_View (BT))
5565            and then not Is_Generic_Type (BT)
5566            and then not In_Open_Scopes (BT)
5567          then
5568             Prepend_Elmt (Full_View (BT), Exchanged_Views);
5569             Exchange_Declarations (BT);
5570          end if;
5571       end if;
5572    end Check_Private_View;
5573
5574    --------------------------
5575    -- Contains_Instance_Of --
5576    --------------------------
5577
5578    function Contains_Instance_Of
5579      (Inner : Entity_Id;
5580       Outer : Entity_Id;
5581       N     : Node_Id) return Boolean
5582    is
5583       Elmt : Elmt_Id;
5584       Scop : Entity_Id;
5585
5586    begin
5587       Scop := Outer;
5588
5589       --  Verify that there are no circular instantiations. We check whether
5590       --  the unit contains an instance of the current scope or some enclosing
5591       --  scope (in case one of the instances appears in a subunit). Longer
5592       --  circularities involving subunits might seem too pathological to
5593       --  consider, but they were not too pathological for the authors of
5594       --  DEC bc30vsq, so we loop over all enclosing scopes, and mark all
5595       --  enclosing generic scopes as containing an instance.
5596
5597       loop
5598          --  Within a generic subprogram body, the scope is not generic, to
5599          --  allow for recursive subprograms. Use the declaration to determine
5600          --  whether this is a generic unit.
5601
5602          if Ekind (Scop) = E_Generic_Package
5603            or else (Is_Subprogram (Scop)
5604                       and then Nkind (Unit_Declaration_Node (Scop)) =
5605                                         N_Generic_Subprogram_Declaration)
5606          then
5607             Elmt := First_Elmt (Inner_Instances (Inner));
5608
5609             while Present (Elmt) loop
5610                if Node (Elmt) = Scop then
5611                   Error_Msg_Node_2 := Inner;
5612                   Error_Msg_NE
5613                     ("circular Instantiation: & instantiated within &!",
5614                        N, Scop);
5615                   return True;
5616
5617                elsif Node (Elmt) = Inner then
5618                   return True;
5619
5620                elsif Contains_Instance_Of (Node (Elmt), Scop, N) then
5621                   Error_Msg_Node_2 := Inner;
5622                   Error_Msg_NE
5623                     ("circular Instantiation: & instantiated within &!",
5624                       N, Node (Elmt));
5625                   return True;
5626                end if;
5627
5628                Next_Elmt (Elmt);
5629             end loop;
5630
5631             --  Indicate that Inner is being instantiated within Scop
5632
5633             Append_Elmt (Inner, Inner_Instances (Scop));
5634          end if;
5635
5636          if Scop = Standard_Standard then
5637             exit;
5638          else
5639             Scop := Scope (Scop);
5640          end if;
5641       end loop;
5642
5643       return False;
5644    end Contains_Instance_Of;
5645
5646    -----------------------
5647    -- Copy_Generic_Node --
5648    -----------------------
5649
5650    function Copy_Generic_Node
5651      (N             : Node_Id;
5652       Parent_Id     : Node_Id;
5653       Instantiating : Boolean) return Node_Id
5654    is
5655       Ent   : Entity_Id;
5656       New_N : Node_Id;
5657
5658       function Copy_Generic_Descendant (D : Union_Id) return Union_Id;
5659       --  Check the given value of one of the Fields referenced by the
5660       --  current node to determine whether to copy it recursively. The
5661       --  field may hold a Node_Id, a List_Id, or an Elist_Id, or a plain
5662       --  value (Sloc, Uint, Char) in which case it need not be copied.
5663
5664       procedure Copy_Descendants;
5665       --  Common utility for various nodes
5666
5667       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id;
5668       --  Make copy of element list
5669
5670       function Copy_Generic_List
5671         (L         : List_Id;
5672          Parent_Id : Node_Id) return List_Id;
5673       --  Apply Copy_Node recursively to the members of a node list
5674
5675       function In_Defining_Unit_Name (Nam : Node_Id) return Boolean;
5676       --  True if an identifier is part of the defining program unit name
5677       --  of a child unit. The entity of such an identifier must be kept
5678       --  (for ASIS use) even though as the name of an enclosing generic
5679       --   it would otherwise not be preserved in the generic tree.
5680
5681       ----------------------
5682       -- Copy_Descendants --
5683       ----------------------
5684
5685       procedure Copy_Descendants is
5686
5687          use Atree.Unchecked_Access;
5688          --  This code section is part of the implementation of an untyped
5689          --  tree traversal, so it needs direct access to node fields.
5690
5691       begin
5692          Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
5693          Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
5694          Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
5695          Set_Field4 (New_N, Copy_Generic_Descendant (Field4 (N)));
5696          Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
5697       end Copy_Descendants;
5698
5699       -----------------------------
5700       -- Copy_Generic_Descendant --
5701       -----------------------------
5702
5703       function Copy_Generic_Descendant (D : Union_Id) return Union_Id is
5704       begin
5705          if D = Union_Id (Empty) then
5706             return D;
5707
5708          elsif D in Node_Range then
5709             return Union_Id
5710               (Copy_Generic_Node (Node_Id (D), New_N, Instantiating));
5711
5712          elsif D in List_Range then
5713             return Union_Id (Copy_Generic_List (List_Id (D), New_N));
5714
5715          elsif D in Elist_Range then
5716             return Union_Id (Copy_Generic_Elist (Elist_Id (D)));
5717
5718          --  Nothing else is copyable (e.g. Uint values), return as is
5719
5720          else
5721             return D;
5722          end if;
5723       end Copy_Generic_Descendant;
5724
5725       ------------------------
5726       -- Copy_Generic_Elist --
5727       ------------------------
5728
5729       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id is
5730          M : Elmt_Id;
5731          L : Elist_Id;
5732
5733       begin
5734          if Present (E) then
5735             L := New_Elmt_List;
5736             M := First_Elmt (E);
5737             while Present (M) loop
5738                Append_Elmt
5739                  (Copy_Generic_Node (Node (M), Empty, Instantiating), L);
5740                Next_Elmt (M);
5741             end loop;
5742
5743             return L;
5744
5745          else
5746             return No_Elist;
5747          end if;
5748       end Copy_Generic_Elist;
5749
5750       -----------------------
5751       -- Copy_Generic_List --
5752       -----------------------
5753
5754       function Copy_Generic_List
5755         (L         : List_Id;
5756          Parent_Id : Node_Id) return List_Id
5757       is
5758          N     : Node_Id;
5759          New_L : List_Id;
5760
5761       begin
5762          if Present (L) then
5763             New_L := New_List;
5764             Set_Parent (New_L, Parent_Id);
5765
5766             N := First (L);
5767             while Present (N) loop
5768                Append (Copy_Generic_Node (N, Empty, Instantiating), New_L);
5769                Next (N);
5770             end loop;
5771
5772             return New_L;
5773
5774          else
5775             return No_List;
5776          end if;
5777       end Copy_Generic_List;
5778
5779       ---------------------------
5780       -- In_Defining_Unit_Name --
5781       ---------------------------
5782
5783       function In_Defining_Unit_Name (Nam : Node_Id) return Boolean is
5784       begin
5785          return Present (Parent (Nam))
5786            and then (Nkind (Parent (Nam)) = N_Defining_Program_Unit_Name
5787                       or else
5788                         (Nkind (Parent (Nam)) = N_Expanded_Name
5789                           and then In_Defining_Unit_Name (Parent (Nam))));
5790       end In_Defining_Unit_Name;
5791
5792    --  Start of processing for Copy_Generic_Node
5793
5794    begin
5795       if N = Empty then
5796          return N;
5797       end if;
5798
5799       New_N := New_Copy (N);
5800
5801       --  Copy aspects if present
5802
5803       if Has_Aspects (N) then
5804          Set_Has_Aspects (New_N, False);
5805          Set_Aspect_Specifications
5806            (New_N, Copy_Generic_List (Aspect_Specifications (N), Parent_Id));
5807       end if;
5808
5809       if Instantiating then
5810          Adjust_Instantiation_Sloc (New_N, S_Adjustment);
5811       end if;
5812
5813       if not Is_List_Member (N) then
5814          Set_Parent (New_N, Parent_Id);
5815       end if;
5816
5817       --  If defining identifier, then all fields have been copied already
5818
5819       if Nkind (New_N) in N_Entity then
5820          null;
5821
5822       --  Special casing for identifiers and other entity names and operators
5823
5824       elsif Nkind_In (New_N, N_Identifier,
5825                              N_Character_Literal,
5826                              N_Expanded_Name,
5827                              N_Operator_Symbol)
5828         or else Nkind (New_N) in N_Op
5829       then
5830          if not Instantiating then
5831
5832             --  Link both nodes in order to assign subsequently the entity of
5833             --  the copy to the original node, in case this is a global
5834             --  reference.
5835
5836             Set_Associated_Node (N, New_N);
5837
5838             --  If we are within an instantiation, this is a nested generic
5839             --  that has already been analyzed at the point of definition. We
5840             --  must preserve references that were global to the enclosing
5841             --  parent at that point. Other occurrences, whether global or
5842             --  local to the current generic, must be resolved anew, so we
5843             --  reset the entity in the generic copy. A global reference has a
5844             --  smaller depth than the parent, or else the same depth in case
5845             --  both are distinct compilation units.
5846             --  A child unit is implicitly declared within the enclosing parent
5847             --  but is in fact global to it, and must be preserved.
5848
5849             --  It is also possible for Current_Instantiated_Parent to be
5850             --  defined, and for this not to be a nested generic, namely if the
5851             --  unit is loaded through Rtsfind. In that case, the entity of
5852             --  New_N is only a link to the associated node, and not a defining
5853             --  occurrence.
5854
5855             --  The entities for parent units in the defining_program_unit of a
5856             --  generic child unit are established when the context of the unit
5857             --  is first analyzed, before the generic copy is made. They are
5858             --  preserved in the copy for use in ASIS queries.
5859
5860             Ent := Entity (New_N);
5861
5862             if No (Current_Instantiated_Parent.Gen_Id) then
5863                if No (Ent)
5864                  or else Nkind (Ent) /= N_Defining_Identifier
5865                  or else not In_Defining_Unit_Name (N)
5866                then
5867                   Set_Associated_Node (New_N, Empty);
5868                end if;
5869
5870             elsif No (Ent)
5871               or else
5872                 not Nkind_In (Ent, N_Defining_Identifier,
5873                                    N_Defining_Character_Literal,
5874                                    N_Defining_Operator_Symbol)
5875               or else No (Scope (Ent))
5876               or else
5877                 (Scope (Ent) = Current_Instantiated_Parent.Gen_Id
5878                   and then not Is_Child_Unit (Ent))
5879               or else
5880                 (Scope_Depth (Scope (Ent)) >
5881                              Scope_Depth (Current_Instantiated_Parent.Gen_Id)
5882                   and then
5883                     Get_Source_Unit (Ent) =
5884                     Get_Source_Unit (Current_Instantiated_Parent.Gen_Id))
5885             then
5886                Set_Associated_Node (New_N, Empty);
5887             end if;
5888
5889          --  Case of instantiating identifier or some other name or operator
5890
5891          else
5892             --  If the associated node is still defined, the entity in it is
5893             --  global, and must be copied to the instance. If this copy is
5894             --  being made for a body to inline, it is applied to an
5895             --  instantiated tree, and the entity is already present and must
5896             --  be also preserved.
5897
5898             declare
5899                Assoc : constant Node_Id := Get_Associated_Node (N);
5900
5901             begin
5902                if Present (Assoc) then
5903                   if Nkind (Assoc) = Nkind (N) then
5904                      Set_Entity (New_N, Entity (Assoc));
5905                      Check_Private_View (N);
5906
5907                   elsif Nkind (Assoc) = N_Function_Call then
5908                      Set_Entity (New_N, Entity (Name (Assoc)));
5909
5910                   elsif Nkind_In (Assoc, N_Defining_Identifier,
5911                                          N_Defining_Character_Literal,
5912                                          N_Defining_Operator_Symbol)
5913                     and then Expander_Active
5914                   then
5915                      --  Inlining case: we are copying a tree that contains
5916                      --  global entities, which are preserved in the copy to be
5917                      --  used for subsequent inlining.
5918
5919                      null;
5920
5921                   else
5922                      Set_Entity (New_N, Empty);
5923                   end if;
5924                end if;
5925             end;
5926          end if;
5927
5928          --  For expanded name, we must copy the Prefix and Selector_Name
5929
5930          if Nkind (N) = N_Expanded_Name then
5931             Set_Prefix
5932               (New_N, Copy_Generic_Node (Prefix (N), New_N, Instantiating));
5933
5934             Set_Selector_Name (New_N,
5935               Copy_Generic_Node (Selector_Name (N), New_N, Instantiating));
5936
5937          --  For operators, we must copy the right operand
5938
5939          elsif Nkind (N) in N_Op then
5940             Set_Right_Opnd (New_N,
5941               Copy_Generic_Node (Right_Opnd (N), New_N, Instantiating));
5942
5943             --  And for binary operators, the left operand as well
5944
5945             if Nkind (N) in N_Binary_Op then
5946                Set_Left_Opnd (New_N,
5947                  Copy_Generic_Node (Left_Opnd (N), New_N, Instantiating));
5948             end if;
5949          end if;
5950
5951       --  Special casing for stubs
5952
5953       elsif Nkind (N) in N_Body_Stub then
5954
5955          --  In any case, we must copy the specification or defining
5956          --  identifier as appropriate.
5957
5958          if Nkind (N) = N_Subprogram_Body_Stub then
5959             Set_Specification (New_N,
5960               Copy_Generic_Node (Specification (N), New_N, Instantiating));
5961
5962          else
5963             Set_Defining_Identifier (New_N,
5964               Copy_Generic_Node
5965                 (Defining_Identifier (N), New_N, Instantiating));
5966          end if;
5967
5968          --  If we are not instantiating, then this is where we load and
5969          --  analyze subunits, i.e. at the point where the stub occurs. A
5970          --  more permissive system might defer this analysis to the point
5971          --  of instantiation, but this seems to complicated for now.
5972
5973          if not Instantiating then
5974             declare
5975                Subunit_Name : constant Unit_Name_Type := Get_Unit_Name (N);
5976                Subunit      : Node_Id;
5977                Unum         : Unit_Number_Type;
5978                New_Body     : Node_Id;
5979
5980             begin
5981                --  Make sure that, if it is a subunit of the main unit that is
5982                --  preprocessed and if -gnateG is specified, the preprocessed
5983                --  file will be written.
5984
5985                Lib.Analysing_Subunit_Of_Main :=
5986                  Lib.In_Extended_Main_Source_Unit (N);
5987                Unum :=
5988                  Load_Unit
5989                    (Load_Name  => Subunit_Name,
5990                     Required   => False,
5991                     Subunit    => True,
5992                     Error_Node => N);
5993                Lib.Analysing_Subunit_Of_Main := False;
5994
5995                --  If the proper body is not found, a warning message will be
5996                --  emitted when analyzing the stub, or later at the point
5997                --  of instantiation. Here we just leave the stub as is.
5998
5999                if Unum = No_Unit then
6000                   Subunits_Missing := True;
6001                   goto Subunit_Not_Found;
6002                end if;
6003
6004                Subunit := Cunit (Unum);
6005
6006                if Nkind (Unit (Subunit)) /= N_Subunit then
6007                   Error_Msg_N
6008                     ("found child unit instead of expected SEPARATE subunit",
6009                      Subunit);
6010                   Error_Msg_Sloc := Sloc (N);
6011                   Error_Msg_N ("\to complete stub #", Subunit);
6012                   goto Subunit_Not_Found;
6013                end if;
6014
6015                --  We must create a generic copy of the subunit, in order to
6016                --  perform semantic analysis on it, and we must replace the
6017                --  stub in the original generic unit with the subunit, in order
6018                --  to preserve non-local references within.
6019
6020                --  Only the proper body needs to be copied. Library_Unit and
6021                --  context clause are simply inherited by the generic copy.
6022                --  Note that the copy (which may be recursive if there are
6023                --  nested subunits) must be done first, before attaching it to
6024                --  the enclosing generic.
6025
6026                New_Body :=
6027                  Copy_Generic_Node
6028                    (Proper_Body (Unit (Subunit)),
6029                     Empty, Instantiating => False);
6030
6031                --  Now place the original proper body in the original generic
6032                --  unit. This is a body, not a compilation unit.
6033
6034                Rewrite (N, Proper_Body (Unit (Subunit)));
6035                Set_Is_Compilation_Unit (Defining_Entity (N), False);
6036                Set_Was_Originally_Stub (N);
6037
6038                --  Finally replace the body of the subunit with its copy, and
6039                --  make this new subunit into the library unit of the generic
6040                --  copy, which does not have stubs any longer.
6041
6042                Set_Proper_Body (Unit (Subunit), New_Body);
6043                Set_Library_Unit (New_N, Subunit);
6044                Inherit_Context (Unit (Subunit), N);
6045             end;
6046
6047          --  If we are instantiating, this must be an error case, since
6048          --  otherwise we would have replaced the stub node by the proper body
6049          --  that corresponds. So just ignore it in the copy (i.e. we have
6050          --  copied it, and that is good enough).
6051
6052          else
6053             null;
6054          end if;
6055
6056          <<Subunit_Not_Found>> null;
6057
6058       --  If the node is a compilation unit, it is the subunit of a stub, which
6059       --  has been loaded already (see code below). In this case, the library
6060       --  unit field of N points to the parent unit (which is a compilation
6061       --  unit) and need not (and cannot!) be copied.
6062
6063       --  When the proper body of the stub is analyzed, the library_unit link
6064       --  is used to establish the proper context (see sem_ch10).
6065
6066       --  The other fields of a compilation unit are copied as usual
6067
6068       elsif Nkind (N) = N_Compilation_Unit then
6069
6070          --  This code can only be executed when not instantiating, because in
6071          --  the copy made for an instantiation, the compilation unit node has
6072          --  disappeared at the point that a stub is replaced by its proper
6073          --  body.
6074
6075          pragma Assert (not Instantiating);
6076
6077          Set_Context_Items (New_N,
6078            Copy_Generic_List (Context_Items (N), New_N));
6079
6080          Set_Unit (New_N,
6081            Copy_Generic_Node (Unit (N), New_N, False));
6082
6083          Set_First_Inlined_Subprogram (New_N,
6084            Copy_Generic_Node
6085              (First_Inlined_Subprogram (N), New_N, False));
6086
6087          Set_Aux_Decls_Node (New_N,
6088            Copy_Generic_Node (Aux_Decls_Node (N), New_N, False));
6089
6090       --  For an assignment node, the assignment is known to be semantically
6091       --  legal if we are instantiating the template. This avoids incorrect
6092       --  diagnostics in generated code.
6093
6094       elsif Nkind (N) = N_Assignment_Statement then
6095
6096          --  Copy name and expression fields in usual manner
6097
6098          Set_Name (New_N,
6099            Copy_Generic_Node (Name (N), New_N, Instantiating));
6100
6101          Set_Expression (New_N,
6102            Copy_Generic_Node (Expression (N), New_N, Instantiating));
6103
6104          if Instantiating then
6105             Set_Assignment_OK (Name (New_N), True);
6106          end if;
6107
6108       elsif Nkind_In (N, N_Aggregate, N_Extension_Aggregate) then
6109          if not Instantiating then
6110             Set_Associated_Node (N, New_N);
6111
6112          else
6113             if Present (Get_Associated_Node (N))
6114               and then Nkind (Get_Associated_Node (N)) = Nkind (N)
6115             then
6116                --  In the generic the aggregate has some composite type. If at
6117                --  the point of instantiation the type has a private view,
6118                --  install the full view (and that of its ancestors, if any).
6119
6120                declare
6121                   T   : Entity_Id := (Etype (Get_Associated_Node (New_N)));
6122                   Rt  : Entity_Id;
6123
6124                begin
6125                   if Present (T)
6126                     and then Is_Private_Type (T)
6127                   then
6128                      Switch_View (T);
6129                   end if;
6130
6131                   if Present (T)
6132                     and then Is_Tagged_Type (T)
6133                     and then Is_Derived_Type (T)
6134                   then
6135                      Rt := Root_Type (T);
6136
6137                      loop
6138                         T := Etype (T);
6139
6140                         if Is_Private_Type (T) then
6141                            Switch_View (T);
6142                         end if;
6143
6144                         exit when T = Rt;
6145                      end loop;
6146                   end if;
6147                end;
6148             end if;
6149          end if;
6150
6151          --  Do not copy the associated node, which points to
6152          --  the generic copy of the aggregate.
6153
6154          declare
6155             use Atree.Unchecked_Access;
6156             --  This code section is part of the implementation of an untyped
6157             --  tree traversal, so it needs direct access to node fields.
6158
6159          begin
6160             Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
6161             Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
6162             Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
6163             Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
6164          end;
6165
6166       --  Allocators do not have an identifier denoting the access type,
6167       --  so we must locate it through the expression to check whether
6168       --  the views are consistent.
6169
6170       elsif Nkind (N) = N_Allocator
6171         and then Nkind (Expression (N)) = N_Qualified_Expression
6172         and then Is_Entity_Name (Subtype_Mark (Expression (N)))
6173         and then Instantiating
6174       then
6175          declare
6176             T     : constant Node_Id :=
6177                       Get_Associated_Node (Subtype_Mark (Expression (N)));
6178             Acc_T : Entity_Id;
6179
6180          begin
6181             if Present (T) then
6182
6183                --  Retrieve the allocator node in the generic copy
6184
6185                Acc_T := Etype (Parent (Parent (T)));
6186                if Present (Acc_T)
6187                  and then Is_Private_Type (Acc_T)
6188                then
6189                   Switch_View (Acc_T);
6190                end if;
6191             end if;
6192
6193             Copy_Descendants;
6194          end;
6195
6196       --  For a proper body, we must catch the case of a proper body that
6197       --  replaces a stub. This represents the point at which a separate
6198       --  compilation unit, and hence template file, may be referenced, so we
6199       --  must make a new source instantiation entry for the template of the
6200       --  subunit, and ensure that all nodes in the subunit are adjusted using
6201       --  this new source instantiation entry.
6202
6203       elsif Nkind (N) in N_Proper_Body then
6204          declare
6205             Save_Adjustment : constant Sloc_Adjustment := S_Adjustment;
6206
6207          begin
6208             if Instantiating and then Was_Originally_Stub (N) then
6209                Create_Instantiation_Source
6210                  (Instantiation_Node,
6211                   Defining_Entity (N),
6212                   False,
6213                   S_Adjustment);
6214             end if;
6215
6216             --  Now copy the fields of the proper body, using the new
6217             --  adjustment factor if one was needed as per test above.
6218
6219             Copy_Descendants;
6220
6221             --  Restore the original adjustment factor in case changed
6222
6223             S_Adjustment := Save_Adjustment;
6224          end;
6225
6226       --  Don't copy Ident or Comment pragmas, since the comment belongs to the
6227       --  generic unit, not to the instantiating unit.
6228
6229       elsif Nkind (N) = N_Pragma
6230         and then Instantiating
6231       then
6232          declare
6233             Prag_Id : constant Pragma_Id := Get_Pragma_Id (N);
6234          begin
6235             if Prag_Id = Pragma_Ident
6236               or else Prag_Id = Pragma_Comment
6237             then
6238                New_N := Make_Null_Statement (Sloc (N));
6239             else
6240                Copy_Descendants;
6241             end if;
6242          end;
6243
6244       elsif Nkind_In (N, N_Integer_Literal, N_Real_Literal) then
6245
6246          --  No descendant fields need traversing
6247
6248          null;
6249
6250       elsif Nkind (N) = N_String_Literal
6251         and then Present (Etype (N))
6252         and then Instantiating
6253       then
6254          --  If the string is declared in an outer scope, the string_literal
6255          --  subtype created for it may have the wrong scope. We force the
6256          --  reanalysis of the constant to generate a new itype in the proper
6257          --  context.
6258
6259          Set_Etype (New_N, Empty);
6260          Set_Analyzed (New_N, False);
6261
6262       --  For the remaining nodes, copy their descendants recursively
6263
6264       else
6265          Copy_Descendants;
6266
6267          if Instantiating
6268            and then Nkind (N) = N_Subprogram_Body
6269          then
6270             Set_Generic_Parent (Specification (New_N), N);
6271          end if;
6272       end if;
6273
6274       return New_N;
6275    end Copy_Generic_Node;
6276
6277    ----------------------------
6278    -- Denotes_Formal_Package --
6279    ----------------------------
6280
6281    function Denotes_Formal_Package
6282      (Pack     : Entity_Id;
6283       On_Exit  : Boolean := False;
6284       Instance : Entity_Id := Empty) return Boolean
6285    is
6286       Par  : Entity_Id;
6287       Scop : constant Entity_Id := Scope (Pack);
6288       E    : Entity_Id;
6289
6290       function Is_Actual_Of_Previous_Formal (P : Entity_Id) return Boolean;
6291       --  The package in question may be an actual for a previous formal
6292       --  package P of the current instance, so examine its actuals as well.
6293       --  This must be recursive over other formal packages.
6294
6295       ----------------------------------
6296       -- Is_Actual_Of_Previous_Formal --
6297       ----------------------------------
6298
6299       function Is_Actual_Of_Previous_Formal (P : Entity_Id) return Boolean is
6300          E1 : Entity_Id;
6301
6302       begin
6303          E1 := First_Entity (P);
6304          while Present (E1) and then  E1 /= Instance loop
6305             if Ekind (E1) = E_Package
6306               and then Nkind (Parent (E1)) = N_Package_Renaming_Declaration
6307             then
6308                if Renamed_Object (E1) = Pack then
6309                   return True;
6310
6311                elsif E1 = P
6312                  or else  Renamed_Object (E1) = P
6313                then
6314                   return False;
6315
6316                elsif Is_Actual_Of_Previous_Formal (E1) then
6317                   return True;
6318                end if;
6319             end if;
6320
6321             Next_Entity (E1);
6322          end loop;
6323
6324          return False;
6325       end Is_Actual_Of_Previous_Formal;
6326
6327    --  Start of processing for Denotes_Formal_Package
6328
6329    begin
6330       if On_Exit then
6331          Par :=
6332            Instance_Envs.Table
6333              (Instance_Envs.Last).Instantiated_Parent.Act_Id;
6334       else
6335          Par  := Current_Instantiated_Parent.Act_Id;
6336       end if;
6337
6338       if Ekind (Scop) = E_Generic_Package
6339         or else Nkind (Unit_Declaration_Node (Scop)) =
6340                                          N_Generic_Subprogram_Declaration
6341       then
6342          return True;
6343
6344       elsif Nkind (Original_Node (Unit_Declaration_Node (Pack))) =
6345         N_Formal_Package_Declaration
6346       then
6347          return True;
6348
6349       elsif No (Par) then
6350          return False;
6351
6352       else
6353          --  Check whether this package is associated with a formal package of
6354          --  the enclosing instantiation. Iterate over the list of renamings.
6355
6356          E := First_Entity (Par);
6357          while Present (E) loop
6358             if Ekind (E) /= E_Package
6359               or else Nkind (Parent (E)) /= N_Package_Renaming_Declaration
6360             then
6361                null;
6362
6363             elsif Renamed_Object (E) = Par then
6364                return False;
6365
6366             elsif Renamed_Object (E) = Pack then
6367                return True;
6368
6369             elsif Is_Actual_Of_Previous_Formal (E) then
6370                return True;
6371
6372             end if;
6373
6374             Next_Entity (E);
6375          end loop;
6376
6377          return False;
6378       end if;
6379    end Denotes_Formal_Package;
6380
6381    -----------------
6382    -- End_Generic --
6383    -----------------
6384
6385    procedure End_Generic is
6386    begin
6387       --  ??? More things could be factored out in this routine. Should
6388       --  probably be done at a later stage.
6389
6390       Inside_A_Generic := Generic_Flags.Table (Generic_Flags.Last);
6391       Generic_Flags.Decrement_Last;
6392
6393       Expander_Mode_Restore;
6394    end End_Generic;
6395
6396    ----------------------
6397    -- Find_Actual_Type --
6398    ----------------------
6399
6400    function Find_Actual_Type
6401      (Typ      : Entity_Id;
6402       Gen_Type : Entity_Id) return Entity_Id
6403    is
6404       Gen_Scope : constant Entity_Id := Scope (Gen_Type);
6405       T         : Entity_Id;
6406
6407    begin
6408       --  Special processing only applies to child units
6409
6410       if not Is_Child_Unit (Gen_Scope) then
6411          return Get_Instance_Of (Typ);
6412
6413       --  If designated or component type is itself a formal of the child unit,
6414       --  its instance is available.
6415
6416       elsif Scope (Typ) = Gen_Scope then
6417          return Get_Instance_Of (Typ);
6418
6419       --  If the array or access type is not declared in the parent unit,
6420       --  no special processing needed.
6421
6422       elsif not Is_Generic_Type (Typ)
6423         and then Scope (Gen_Scope) /= Scope (Typ)
6424       then
6425          return Get_Instance_Of (Typ);
6426
6427       --  Otherwise, retrieve designated or component type by visibility
6428
6429       else
6430          T := Current_Entity (Typ);
6431          while Present (T) loop
6432             if In_Open_Scopes (Scope (T)) then
6433                return T;
6434
6435             elsif Is_Generic_Actual_Type (T) then
6436                return T;
6437             end if;
6438
6439             T := Homonym (T);
6440          end loop;
6441
6442          return Typ;
6443       end if;
6444    end Find_Actual_Type;
6445
6446    ----------------------------
6447    -- Freeze_Subprogram_Body --
6448    ----------------------------
6449
6450    procedure Freeze_Subprogram_Body
6451      (Inst_Node : Node_Id;
6452       Gen_Body  : Node_Id;
6453       Pack_Id   : Entity_Id)
6454   is
6455       F_Node   : Node_Id;
6456       Gen_Unit : constant Entity_Id := Get_Generic_Entity (Inst_Node);
6457       Par      : constant Entity_Id := Scope (Gen_Unit);
6458       Enc_G    : Entity_Id;
6459       Enc_I    : Node_Id;
6460       E_G_Id   : Entity_Id;
6461
6462       function Earlier (N1, N2 : Node_Id) return Boolean;
6463       --  Yields True if N1 and N2 appear in the same compilation unit,
6464       --  ignoring subunits, and if N1 is to the left of N2 in a left-to-right
6465       --  traversal of the tree for the unit.
6466
6467       function Enclosing_Body (N : Node_Id) return Node_Id;
6468       --  Find innermost package body that encloses the given node, and which
6469       --  is not a compilation unit. Freeze nodes for the instance, or for its
6470       --  enclosing body, may be inserted after the enclosing_body of the
6471       --  generic unit.
6472
6473       function Package_Freeze_Node (B : Node_Id) return Node_Id;
6474       --  Find entity for given package body, and locate or create a freeze
6475       --  node for it.
6476
6477       function True_Parent (N : Node_Id) return Node_Id;
6478       --  For a subunit, return parent of corresponding stub
6479
6480       -------------
6481       -- Earlier --
6482       -------------
6483
6484       function Earlier (N1, N2 : Node_Id) return Boolean is
6485          D1 : Integer := 0;
6486          D2 : Integer := 0;
6487          P1 : Node_Id := N1;
6488          P2 : Node_Id := N2;
6489
6490          procedure Find_Depth (P : in out Node_Id; D : in out Integer);
6491          --  Find distance from given node to enclosing compilation unit
6492
6493          ----------------
6494          -- Find_Depth --
6495          ----------------
6496
6497          procedure Find_Depth (P : in out Node_Id; D : in out Integer) is
6498          begin
6499             while Present (P)
6500               and then Nkind (P) /= N_Compilation_Unit
6501             loop
6502                P := True_Parent (P);
6503                D := D + 1;
6504             end loop;
6505          end Find_Depth;
6506
6507       --  Start of processing for Earlier
6508
6509       begin
6510          Find_Depth (P1, D1);
6511          Find_Depth (P2, D2);
6512
6513          if P1 /= P2 then
6514             return False;
6515          else
6516             P1 := N1;
6517             P2 := N2;
6518          end if;
6519
6520          while D1 > D2 loop
6521             P1 := True_Parent (P1);
6522             D1 := D1 - 1;
6523          end loop;
6524
6525          while D2 > D1 loop
6526             P2 := True_Parent (P2);
6527             D2 := D2 - 1;
6528          end loop;
6529
6530          --  At this point P1 and P2 are at the same distance from the root.
6531          --  We examine their parents until we find a common declarative
6532          --  list, at which point we can establish their relative placement
6533          --  by comparing their ultimate slocs. If we reach the root,
6534          --  N1 and N2 do not descend from the same declarative list (e.g.
6535          --  one is nested in the declarative part and the other is in a block
6536          --  in the statement part) and the earlier one is already frozen.
6537
6538          while not Is_List_Member (P1)
6539            or else not Is_List_Member (P2)
6540            or else List_Containing (P1) /= List_Containing (P2)
6541          loop
6542             P1 := True_Parent (P1);
6543             P2 := True_Parent (P2);
6544
6545             if Nkind (Parent (P1)) = N_Subunit then
6546                P1 := Corresponding_Stub (Parent (P1));
6547             end if;
6548
6549             if Nkind (Parent (P2)) = N_Subunit then
6550                P2 := Corresponding_Stub (Parent (P2));
6551             end if;
6552
6553             if P1 = P2 then
6554                return False;
6555             end if;
6556          end loop;
6557
6558          return
6559            Top_Level_Location (Sloc (P1)) < Top_Level_Location (Sloc (P2));
6560       end Earlier;
6561
6562       --------------------
6563       -- Enclosing_Body --
6564       --------------------
6565
6566       function Enclosing_Body (N : Node_Id) return Node_Id is
6567          P : Node_Id := Parent (N);
6568
6569       begin
6570          while Present (P)
6571            and then Nkind (Parent (P)) /= N_Compilation_Unit
6572          loop
6573             if Nkind (P) = N_Package_Body then
6574
6575                if Nkind (Parent (P)) = N_Subunit then
6576                   return Corresponding_Stub (Parent (P));
6577                else
6578                   return P;
6579                end if;
6580             end if;
6581
6582             P := True_Parent (P);
6583          end loop;
6584
6585          return Empty;
6586       end Enclosing_Body;
6587
6588       -------------------------
6589       -- Package_Freeze_Node --
6590       -------------------------
6591
6592       function Package_Freeze_Node (B : Node_Id) return Node_Id is
6593          Id : Entity_Id;
6594
6595       begin
6596          if Nkind (B) = N_Package_Body then
6597             Id := Corresponding_Spec (B);
6598
6599          else pragma Assert (Nkind (B) = N_Package_Body_Stub);
6600             Id := Corresponding_Spec (Proper_Body (Unit (Library_Unit (B))));
6601          end if;
6602
6603          Ensure_Freeze_Node (Id);
6604          return Freeze_Node (Id);
6605       end Package_Freeze_Node;
6606
6607       -----------------
6608       -- True_Parent --
6609       -----------------
6610
6611       function True_Parent (N : Node_Id) return Node_Id is
6612       begin
6613          if Nkind (Parent (N)) = N_Subunit then
6614             return Parent (Corresponding_Stub (Parent (N)));
6615          else
6616             return Parent (N);
6617          end if;
6618       end True_Parent;
6619
6620    --  Start of processing of Freeze_Subprogram_Body
6621
6622    begin
6623       --  If the instance and the generic body appear within the same unit, and
6624       --  the instance precedes the generic, the freeze node for the instance
6625       --  must appear after that of the generic. If the generic is nested
6626       --  within another instance I2, then current instance must be frozen
6627       --  after I2. In both cases, the freeze nodes are those of enclosing
6628       --  packages. Otherwise, the freeze node is placed at the end of the
6629       --  current declarative part.
6630
6631       Enc_G  := Enclosing_Body (Gen_Body);
6632       Enc_I  := Enclosing_Body (Inst_Node);
6633       Ensure_Freeze_Node (Pack_Id);
6634       F_Node := Freeze_Node (Pack_Id);
6635
6636       if Is_Generic_Instance (Par)
6637         and then Present (Freeze_Node (Par))
6638         and then
6639           In_Same_Declarative_Part (Freeze_Node (Par), Inst_Node)
6640       then
6641          if ABE_Is_Certain (Get_Package_Instantiation_Node (Par)) then
6642
6643             --  The parent was a premature instantiation. Insert freeze node at
6644             --  the end the current declarative part.
6645
6646             Insert_After_Last_Decl (Inst_Node, F_Node);
6647
6648          else
6649             Insert_After (Freeze_Node (Par), F_Node);
6650          end if;
6651
6652       --  The body enclosing the instance should be frozen after the body that
6653       --  includes the generic, because the body of the instance may make
6654       --  references to entities therein. If the two are not in the same
6655       --  declarative part, or if the one enclosing the instance is frozen
6656       --  already, freeze the instance at the end of the current declarative
6657       --  part.
6658
6659       elsif Is_Generic_Instance (Par)
6660         and then Present (Freeze_Node (Par))
6661         and then Present (Enc_I)
6662       then
6663          if In_Same_Declarative_Part (Freeze_Node (Par), Enc_I)
6664            or else
6665              (Nkind (Enc_I) = N_Package_Body
6666                and then
6667                  In_Same_Declarative_Part (Freeze_Node (Par), Parent (Enc_I)))
6668          then
6669             --  The enclosing package may contain several instances. Rather
6670             --  than computing the earliest point at which to insert its
6671             --  freeze node, we place it at the end of the declarative part
6672             --  of the parent of the generic.
6673
6674             Insert_After_Last_Decl
6675               (Freeze_Node (Par), Package_Freeze_Node (Enc_I));
6676          end if;
6677
6678          Insert_After_Last_Decl (Inst_Node, F_Node);
6679
6680       elsif Present (Enc_G)
6681         and then Present (Enc_I)
6682         and then Enc_G /= Enc_I
6683         and then Earlier (Inst_Node, Gen_Body)
6684       then
6685          if Nkind (Enc_G) = N_Package_Body then
6686             E_G_Id := Corresponding_Spec (Enc_G);
6687          else pragma Assert (Nkind (Enc_G) = N_Package_Body_Stub);
6688             E_G_Id :=
6689               Corresponding_Spec (Proper_Body (Unit (Library_Unit (Enc_G))));
6690          end if;
6691
6692          --  Freeze package that encloses instance, and place node after
6693          --  package that encloses generic. If enclosing package is already
6694          --  frozen we have to assume it is at the proper place. This may be
6695          --  a potential ABE that requires dynamic checking. Do not add a
6696          --  freeze node if the package that encloses the generic is inside
6697          --  the body that encloses the instance, because the freeze node
6698          --  would be in the wrong scope. Additional contortions needed if
6699          --  the bodies are within a subunit.
6700
6701          declare
6702             Enclosing_Body : Node_Id;
6703
6704          begin
6705             if Nkind (Enc_I) = N_Package_Body_Stub then
6706                Enclosing_Body := Proper_Body (Unit (Library_Unit (Enc_I)));
6707             else
6708                Enclosing_Body := Enc_I;
6709             end if;
6710
6711             if Parent (List_Containing (Enc_G)) /= Enclosing_Body then
6712                Insert_After_Last_Decl (Enc_G, Package_Freeze_Node (Enc_I));
6713             end if;
6714          end;
6715
6716          --  Freeze enclosing subunit before instance
6717
6718          Ensure_Freeze_Node (E_G_Id);
6719
6720          if not Is_List_Member (Freeze_Node (E_G_Id)) then
6721             Insert_After (Enc_G, Freeze_Node (E_G_Id));
6722          end if;
6723
6724          Insert_After_Last_Decl (Inst_Node, F_Node);
6725
6726       else
6727          --  If none of the above, insert freeze node at the end of the current
6728          --  declarative part.
6729
6730          Insert_After_Last_Decl (Inst_Node, F_Node);
6731       end if;
6732    end Freeze_Subprogram_Body;
6733
6734    ----------------
6735    -- Get_Gen_Id --
6736    ----------------
6737
6738    function Get_Gen_Id (E : Assoc_Ptr) return Entity_Id is
6739    begin
6740       return Generic_Renamings.Table (E).Gen_Id;
6741    end Get_Gen_Id;
6742
6743    ---------------------
6744    -- Get_Instance_Of --
6745    ---------------------
6746
6747    function Get_Instance_Of (A : Entity_Id) return Entity_Id is
6748       Res : constant Assoc_Ptr := Generic_Renamings_HTable.Get (A);
6749
6750    begin
6751       if Res /= Assoc_Null then
6752          return Generic_Renamings.Table (Res).Act_Id;
6753       else
6754          --  On exit, entity is not instantiated: not a generic parameter, or
6755          --  else parameter of an inner generic unit.
6756
6757          return A;
6758       end if;
6759    end Get_Instance_Of;
6760
6761    ------------------------------------
6762    -- Get_Package_Instantiation_Node --
6763    ------------------------------------
6764
6765    function Get_Package_Instantiation_Node (A : Entity_Id) return Node_Id is
6766       Decl : Node_Id := Unit_Declaration_Node (A);
6767       Inst : Node_Id;
6768
6769    begin
6770       --  If the Package_Instantiation attribute has been set on the package
6771       --  entity, then use it directly when it (or its Original_Node) refers
6772       --  to an N_Package_Instantiation node. In principle it should be
6773       --  possible to have this field set in all cases, which should be
6774       --  investigated, and would allow this function to be significantly
6775       --  simplified. ???
6776
6777       if Present (Package_Instantiation (A)) then
6778          if Nkind (Package_Instantiation (A)) = N_Package_Instantiation then
6779             return Package_Instantiation (A);
6780
6781          elsif Nkind (Original_Node (Package_Instantiation (A))) =
6782                                                    N_Package_Instantiation
6783          then
6784             return Original_Node (Package_Instantiation (A));
6785          end if;
6786       end if;
6787
6788       --  If the instantiation is a compilation unit that does not need body
6789       --  then the instantiation node has been rewritten as a package
6790       --  declaration for the instance, and we return the original node.
6791
6792       --  If it is a compilation unit and the instance node has not been
6793       --  rewritten, then it is still the unit of the compilation. Finally, if
6794       --  a body is present, this is a parent of the main unit whose body has
6795       --  been compiled for inlining purposes, and the instantiation node has
6796       --  been rewritten with the instance body.
6797
6798       --  Otherwise the instantiation node appears after the declaration. If
6799       --  the entity is a formal package, the declaration may have been
6800       --  rewritten as a generic declaration (in the case of a formal with box)
6801       --  or left as a formal package declaration if it has actuals, and is
6802       --  found with a forward search.
6803
6804       if Nkind (Parent (Decl)) = N_Compilation_Unit then
6805          if Nkind (Decl) = N_Package_Declaration
6806            and then Present (Corresponding_Body (Decl))
6807          then
6808             Decl := Unit_Declaration_Node (Corresponding_Body (Decl));
6809          end if;
6810
6811          if Nkind (Original_Node (Decl)) = N_Package_Instantiation then
6812             return Original_Node (Decl);
6813          else
6814             return Unit (Parent (Decl));
6815          end if;
6816
6817       elsif Nkind (Decl) = N_Package_Declaration
6818         and then Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration
6819       then
6820          return Original_Node (Decl);
6821
6822       else
6823          Inst := Next (Decl);
6824          while not Nkind_In (Inst, N_Package_Instantiation,
6825                                    N_Formal_Package_Declaration)
6826          loop
6827             Next (Inst);
6828          end loop;
6829
6830          return Inst;
6831       end if;
6832    end Get_Package_Instantiation_Node;
6833
6834    ------------------------
6835    -- Has_Been_Exchanged --
6836    ------------------------
6837
6838    function Has_Been_Exchanged (E : Entity_Id) return Boolean is
6839       Next : Elmt_Id;
6840
6841    begin
6842       Next := First_Elmt (Exchanged_Views);
6843       while Present (Next) loop
6844          if Full_View (Node (Next)) = E then
6845             return True;
6846          end if;
6847
6848          Next_Elmt (Next);
6849       end loop;
6850
6851       return False;
6852    end Has_Been_Exchanged;
6853
6854    ----------
6855    -- Hash --
6856    ----------
6857
6858    function Hash (F : Entity_Id) return HTable_Range is
6859    begin
6860       return HTable_Range (F mod HTable_Size);
6861    end Hash;
6862
6863    ------------------------
6864    -- Hide_Current_Scope --
6865    ------------------------
6866
6867    procedure Hide_Current_Scope is
6868       C : constant Entity_Id := Current_Scope;
6869       E : Entity_Id;
6870
6871    begin
6872       Set_Is_Hidden_Open_Scope (C);
6873
6874       E := First_Entity (C);
6875       while Present (E) loop
6876          if Is_Immediately_Visible (E) then
6877             Set_Is_Immediately_Visible (E, False);
6878             Append_Elmt (E, Hidden_Entities);
6879          end if;
6880
6881          Next_Entity (E);
6882       end loop;
6883
6884       --  Make the scope name invisible as well. This is necessary, but might
6885       --  conflict with calls to Rtsfind later on, in case the scope is a
6886       --  predefined one. There is no clean solution to this problem, so for
6887       --  now we depend on the user not redefining Standard itself in one of
6888       --  the parent units.
6889
6890       if Is_Immediately_Visible (C)
6891         and then C /= Standard_Standard
6892       then
6893          Set_Is_Immediately_Visible (C, False);
6894          Append_Elmt (C, Hidden_Entities);
6895       end if;
6896
6897    end Hide_Current_Scope;
6898
6899    --------------
6900    -- Init_Env --
6901    --------------
6902
6903    procedure Init_Env is
6904       Saved : Instance_Env;
6905
6906    begin
6907       Saved.Instantiated_Parent  := Current_Instantiated_Parent;
6908       Saved.Exchanged_Views      := Exchanged_Views;
6909       Saved.Hidden_Entities      := Hidden_Entities;
6910       Saved.Current_Sem_Unit     := Current_Sem_Unit;
6911       Saved.Parent_Unit_Visible  := Parent_Unit_Visible;
6912       Saved.Instance_Parent_Unit := Instance_Parent_Unit;
6913
6914       --  Save configuration switches. These may be reset if the unit is a
6915       --  predefined unit, and the current mode is not Ada 2005.
6916
6917       Save_Opt_Config_Switches (Saved.Switches);
6918
6919       Instance_Envs.Append (Saved);
6920
6921       Exchanged_Views := New_Elmt_List;
6922       Hidden_Entities := New_Elmt_List;
6923
6924       --  Make dummy entry for Instantiated parent. If generic unit is legal,
6925       --  this is set properly in Set_Instance_Env.
6926
6927       Current_Instantiated_Parent :=
6928         (Current_Scope, Current_Scope, Assoc_Null);
6929    end Init_Env;
6930
6931    ------------------------------
6932    -- In_Same_Declarative_Part --
6933    ------------------------------
6934
6935    function In_Same_Declarative_Part
6936      (F_Node : Node_Id;
6937       Inst   : Node_Id) return Boolean
6938    is
6939       Decls : constant Node_Id := Parent (F_Node);
6940       Nod   : Node_Id := Parent (Inst);
6941
6942    begin
6943       while Present (Nod) loop
6944          if Nod = Decls then
6945             return True;
6946
6947          elsif Nkind_In (Nod, N_Subprogram_Body,
6948                               N_Package_Body,
6949                               N_Task_Body,
6950                               N_Protected_Body,
6951                               N_Block_Statement)
6952          then
6953             return False;
6954
6955          elsif Nkind (Nod) = N_Subunit then
6956             Nod :=  Corresponding_Stub (Nod);
6957
6958          elsif Nkind (Nod) = N_Compilation_Unit then
6959             return False;
6960
6961          else
6962             Nod := Parent (Nod);
6963          end if;
6964       end loop;
6965
6966       return False;
6967    end In_Same_Declarative_Part;
6968
6969    ---------------------
6970    -- In_Main_Context --
6971    ---------------------
6972
6973    function In_Main_Context (E : Entity_Id) return Boolean is
6974       Context : List_Id;
6975       Clause  : Node_Id;
6976       Nam     : Node_Id;
6977
6978    begin
6979       if not Is_Compilation_Unit (E)
6980         or else Ekind (E) /= E_Package
6981         or else In_Private_Part (E)
6982       then
6983          return False;
6984       end if;
6985
6986       Context := Context_Items (Cunit (Main_Unit));
6987
6988       Clause  := First (Context);
6989       while Present (Clause) loop
6990          if Nkind (Clause) = N_With_Clause then
6991             Nam := Name (Clause);
6992
6993             --  If the current scope is part of the context of the main unit,
6994             --  analysis of the corresponding with_clause is not complete, and
6995             --  the entity is not set. We use the Chars field directly, which
6996             --  might produce false positives in rare cases, but guarantees
6997             --  that we produce all the instance bodies we will need.
6998
6999             if (Is_Entity_Name (Nam)
7000                  and then Chars (Nam) = Chars (E))
7001               or else (Nkind (Nam) = N_Selected_Component
7002                         and then Chars (Selector_Name (Nam)) = Chars (E))
7003             then
7004                return True;
7005             end if;
7006          end if;
7007
7008          Next (Clause);
7009       end loop;
7010
7011       return False;
7012    end In_Main_Context;
7013
7014    ---------------------
7015    -- Inherit_Context --
7016    ---------------------
7017
7018    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id) is
7019       Current_Context : List_Id;
7020       Current_Unit    : Node_Id;
7021       Item            : Node_Id;
7022       New_I           : Node_Id;
7023
7024    begin
7025       if Nkind (Parent (Gen_Decl)) = N_Compilation_Unit then
7026
7027          --  The inherited context is attached to the enclosing compilation
7028          --  unit. This is either the main unit, or the declaration for the
7029          --  main unit (in case the instantiation appears within the package
7030          --  declaration and the main unit is its body).
7031
7032          Current_Unit := Parent (Inst);
7033          while Present (Current_Unit)
7034            and then Nkind (Current_Unit) /= N_Compilation_Unit
7035          loop
7036             Current_Unit := Parent (Current_Unit);
7037          end loop;
7038
7039          Current_Context := Context_Items (Current_Unit);
7040
7041          Item := First (Context_Items (Parent (Gen_Decl)));
7042          while Present (Item) loop
7043             if Nkind (Item) = N_With_Clause then
7044
7045                --  Take care to prevent direct cyclic with's, which can happen
7046                --  if the generic body with's the current unit. Such a case
7047                --  would result in binder errors (or run-time errors if the
7048                --  -gnatE switch is in effect), but we want to prevent it here,
7049                --  because Sem.Walk_Library_Items doesn't like cycles. Note
7050                --  that we don't bother to detect indirect cycles.
7051
7052                if Library_Unit (Item) /= Current_Unit then
7053                   New_I := New_Copy (Item);
7054                   Set_Implicit_With (New_I, True);
7055                   Append (New_I, Current_Context);
7056                end if;
7057             end if;
7058
7059             Next (Item);
7060          end loop;
7061       end if;
7062    end Inherit_Context;
7063
7064    ----------------
7065    -- Initialize --
7066    ----------------
7067
7068    procedure Initialize is
7069    begin
7070       Generic_Renamings.Init;
7071       Instance_Envs.Init;
7072       Generic_Flags.Init;
7073       Generic_Renamings_HTable.Reset;
7074       Circularity_Detected := False;
7075       Exchanged_Views      := No_Elist;
7076       Hidden_Entities      := No_Elist;
7077    end Initialize;
7078
7079    ----------------------------
7080    -- Insert_After_Last_Decl --
7081    ----------------------------
7082
7083    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id) is
7084       L : List_Id          := List_Containing (N);
7085       P : constant Node_Id := Parent (L);
7086
7087    begin
7088       if not Is_List_Member (F_Node) then
7089          if Nkind (P) = N_Package_Specification
7090            and then L = Visible_Declarations (P)
7091            and then Present (Private_Declarations (P))
7092            and then not Is_Empty_List (Private_Declarations (P))
7093          then
7094             L := Private_Declarations (P);
7095          end if;
7096
7097          Insert_After (Last (L), F_Node);
7098       end if;
7099    end Insert_After_Last_Decl;
7100
7101    ------------------
7102    -- Install_Body --
7103    ------------------
7104
7105    procedure Install_Body
7106      (Act_Body : Node_Id;
7107       N        : Node_Id;
7108       Gen_Body : Node_Id;
7109       Gen_Decl : Node_Id)
7110    is
7111       Act_Id    : constant Entity_Id := Corresponding_Spec (Act_Body);
7112       Act_Unit  : constant Node_Id   := Unit (Cunit (Get_Source_Unit (N)));
7113       Gen_Id    : constant Entity_Id := Corresponding_Spec (Gen_Body);
7114       Par       : constant Entity_Id := Scope (Gen_Id);
7115       Gen_Unit  : constant Node_Id   :=
7116                     Unit (Cunit (Get_Source_Unit (Gen_Decl)));
7117       Orig_Body : Node_Id := Gen_Body;
7118       F_Node    : Node_Id;
7119       Body_Unit : Node_Id;
7120
7121       Must_Delay : Boolean;
7122
7123       function Enclosing_Subp (Id : Entity_Id) return Entity_Id;
7124       --  Find subprogram (if any) that encloses instance and/or generic body
7125
7126       function True_Sloc (N : Node_Id) return Source_Ptr;
7127       --  If the instance is nested inside a generic unit, the Sloc of the
7128       --  instance indicates the place of the original definition, not the
7129       --  point of the current enclosing instance. Pending a better usage of
7130       --  Slocs to indicate instantiation places, we determine the place of
7131       --  origin of a node by finding the maximum sloc of any ancestor node.
7132       --  Why is this not equivalent to Top_Level_Location ???
7133
7134       --------------------
7135       -- Enclosing_Subp --
7136       --------------------
7137
7138       function Enclosing_Subp (Id : Entity_Id) return Entity_Id is
7139          Scop : Entity_Id := Scope (Id);
7140
7141       begin
7142          while Scop /= Standard_Standard
7143            and then not Is_Overloadable (Scop)
7144          loop
7145             Scop := Scope (Scop);
7146          end loop;
7147
7148          return Scop;
7149       end Enclosing_Subp;
7150
7151       ---------------
7152       -- True_Sloc --
7153       ---------------
7154
7155       function True_Sloc (N : Node_Id) return Source_Ptr is
7156          Res : Source_Ptr;
7157          N1  : Node_Id;
7158
7159       begin
7160          Res := Sloc (N);
7161          N1 := N;
7162          while Present (N1) and then N1 /= Act_Unit loop
7163             if Sloc (N1) > Res then
7164                Res := Sloc (N1);
7165             end if;
7166
7167             N1 := Parent (N1);
7168          end loop;
7169
7170          return Res;
7171       end True_Sloc;
7172
7173    --  Start of processing for Install_Body
7174
7175    begin
7176
7177       --  If the body is a subunit, the freeze point is the corresponding
7178       --  stub in the current compilation, not the subunit itself.
7179
7180       if Nkind (Parent (Gen_Body)) = N_Subunit then
7181          Orig_Body := Corresponding_Stub (Parent (Gen_Body));
7182       else
7183          Orig_Body := Gen_Body;
7184       end if;
7185
7186       Body_Unit := Unit (Cunit (Get_Source_Unit (Orig_Body)));
7187
7188       --  If the instantiation and the generic definition appear in the same
7189       --  package declaration, this is an early instantiation. If they appear
7190       --  in the same declarative part, it is an early instantiation only if
7191       --  the generic body appears textually later, and the generic body is
7192       --  also in the main unit.
7193
7194       --  If instance is nested within a subprogram, and the generic body is
7195       --  not, the instance is delayed because the enclosing body is. If
7196       --  instance and body are within the same scope, or the same sub-
7197       --  program body, indicate explicitly that the instance is delayed.
7198
7199       Must_Delay :=
7200         (Gen_Unit = Act_Unit
7201           and then (Nkind_In (Gen_Unit, N_Package_Declaration,
7202                                         N_Generic_Package_Declaration)
7203                       or else (Gen_Unit = Body_Unit
7204                                 and then True_Sloc (N) < Sloc (Orig_Body)))
7205           and then Is_In_Main_Unit (Gen_Unit)
7206           and then (Scope (Act_Id) = Scope (Gen_Id)
7207                       or else
7208                     Enclosing_Subp (Act_Id) = Enclosing_Subp (Gen_Id)));
7209
7210       --  If this is an early instantiation, the freeze node is placed after
7211       --  the generic body. Otherwise, if the generic appears in an instance,
7212       --  we cannot freeze the current instance until the outer one is frozen.
7213       --  This is only relevant if the current instance is nested within some
7214       --  inner scope not itself within the outer instance. If this scope is
7215       --  a package body in the same declarative part as the outer instance,
7216       --  then that body needs to be frozen after the outer instance. Finally,
7217       --  if no delay is needed, we place the freeze node at the end of the
7218       --  current declarative part.
7219
7220       if Expander_Active then
7221          Ensure_Freeze_Node (Act_Id);
7222          F_Node := Freeze_Node (Act_Id);
7223
7224          if Must_Delay then
7225             Insert_After (Orig_Body, F_Node);
7226
7227          elsif Is_Generic_Instance (Par)
7228            and then Present (Freeze_Node (Par))
7229            and then Scope (Act_Id) /= Par
7230          then
7231             --  Freeze instance of inner generic after instance of enclosing
7232             --  generic.
7233
7234             if In_Same_Declarative_Part (Freeze_Node (Par), N) then
7235                Insert_After (Freeze_Node (Par), F_Node);
7236
7237             --  Freeze package enclosing instance of inner generic after
7238             --  instance of enclosing generic.
7239
7240             elsif Nkind (Parent (N)) = N_Package_Body
7241               and then In_Same_Declarative_Part (Freeze_Node (Par), Parent (N))
7242             then
7243
7244                declare
7245                   Enclosing : constant Entity_Id :=
7246                                 Corresponding_Spec (Parent (N));
7247
7248                begin
7249                   Insert_After_Last_Decl (N, F_Node);
7250                   Ensure_Freeze_Node (Enclosing);
7251
7252                   if not Is_List_Member (Freeze_Node (Enclosing)) then
7253                      Insert_After (Freeze_Node (Par), Freeze_Node (Enclosing));
7254                   end if;
7255                end;
7256
7257             else
7258                Insert_After_Last_Decl (N, F_Node);
7259             end if;
7260
7261          else
7262             Insert_After_Last_Decl (N, F_Node);
7263          end if;
7264       end if;
7265
7266       Set_Is_Frozen (Act_Id);
7267       Insert_Before (N, Act_Body);
7268       Mark_Rewrite_Insertion (Act_Body);
7269    end Install_Body;
7270
7271    -----------------------------
7272    -- Install_Formal_Packages --
7273    -----------------------------
7274
7275    procedure Install_Formal_Packages (Par : Entity_Id) is
7276       E     : Entity_Id;
7277       Gen   : Entity_Id;
7278       Gen_E : Entity_Id := Empty;
7279
7280    begin
7281       E := First_Entity (Par);
7282
7283       --  In we are installing an instance parent, locate the formal packages
7284       --  of its generic parent.
7285
7286       if Is_Generic_Instance (Par) then
7287          Gen   := Generic_Parent (Specification (Unit_Declaration_Node (Par)));
7288          Gen_E := First_Entity (Gen);
7289       end if;
7290
7291       while Present (E) loop
7292          if Ekind (E) = E_Package
7293            and then Nkind (Parent (E)) = N_Package_Renaming_Declaration
7294          then
7295             --  If this is the renaming for the parent instance, done
7296
7297             if Renamed_Object (E) = Par then
7298                exit;
7299
7300             --  The visibility of a formal of an enclosing generic is already
7301             --  correct.
7302
7303             elsif Denotes_Formal_Package (E) then
7304                null;
7305
7306             elsif Present (Associated_Formal_Package (E)) then
7307                Check_Generic_Actuals (Renamed_Object (E), True);
7308                Set_Is_Hidden (E, False);
7309
7310                --  Find formal package in generic unit that corresponds to
7311                --  (instance of) formal package in instance.
7312
7313                while Present (Gen_E) and then Chars (Gen_E) /= Chars (E) loop
7314                   Next_Entity (Gen_E);
7315                end loop;
7316
7317                if Present (Gen_E) then
7318                   Map_Formal_Package_Entities (Gen_E, E);
7319                end if;
7320             end if;
7321          end if;
7322
7323          Next_Entity (E);
7324          if Present (Gen_E) then
7325             Next_Entity (Gen_E);
7326          end if;
7327       end loop;
7328    end Install_Formal_Packages;
7329
7330    --------------------
7331    -- Install_Parent --
7332    --------------------
7333
7334    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False) is
7335       Ancestors : constant Elist_Id  := New_Elmt_List;
7336       S         : constant Entity_Id := Current_Scope;
7337       Inst_Par  : Entity_Id;
7338       First_Par : Entity_Id;
7339       Inst_Node : Node_Id;
7340       Gen_Par   : Entity_Id;
7341       First_Gen : Entity_Id;
7342       Elmt      : Elmt_Id;
7343
7344       procedure Install_Noninstance_Specs (Par : Entity_Id);
7345       --  Install the scopes of noninstance parent units ending with Par
7346
7347       procedure Install_Spec (Par : Entity_Id);
7348       --  The child unit is within the declarative part of the parent, so
7349       --  the declarations within the parent are immediately visible.
7350
7351       -------------------------------
7352       -- Install_Noninstance_Specs --
7353       -------------------------------
7354
7355       procedure Install_Noninstance_Specs (Par : Entity_Id) is
7356       begin
7357          if Present (Par)
7358            and then Par /= Standard_Standard
7359            and then not In_Open_Scopes (Par)
7360          then
7361             Install_Noninstance_Specs (Scope (Par));
7362             Install_Spec (Par);
7363          end if;
7364       end Install_Noninstance_Specs;
7365
7366       ------------------
7367       -- Install_Spec --
7368       ------------------
7369
7370       procedure Install_Spec (Par : Entity_Id) is
7371          Spec : constant Node_Id :=
7372                   Specification (Unit_Declaration_Node (Par));
7373
7374       begin
7375          --  If this parent of the child instance is a top-level unit,
7376          --  then record the unit and its visibility for later resetting
7377          --  in Remove_Parent. We exclude units that are generic instances,
7378          --  as we only want to record this information for the ultimate
7379          --  top-level noninstance parent (is that always correct???).
7380
7381          if Scope (Par) = Standard_Standard
7382            and then not Is_Generic_Instance (Par)
7383          then
7384             Parent_Unit_Visible := Is_Immediately_Visible (Par);
7385             Instance_Parent_Unit := Par;
7386          end if;
7387
7388          --  Open the parent scope and make it and its declarations visible.
7389          --  If this point is not within a body, then only the visible
7390          --  declarations should be made visible, and installation of the
7391          --  private declarations is deferred until the appropriate point
7392          --  within analysis of the spec being instantiated (see the handling
7393          --  of parent visibility in Analyze_Package_Specification). This is
7394          --  relaxed in the case where the parent unit is Ada.Tags, to avoid
7395          --  private view problems that occur when compiling instantiations of
7396          --  a generic child of that package (Generic_Dispatching_Constructor).
7397          --  If the instance freezes a tagged type, inlinings of operations
7398          --  from Ada.Tags may need the full view of type Tag. If inlining took
7399          --  proper account of establishing visibility of inlined subprograms'
7400          --  parents then it should be possible to remove this
7401          --  special check. ???
7402
7403          Push_Scope (Par);
7404          Set_Is_Immediately_Visible   (Par);
7405          Install_Visible_Declarations (Par);
7406          Set_Use (Visible_Declarations (Spec));
7407
7408          if In_Body or else Is_RTU (Par, Ada_Tags) then
7409             Install_Private_Declarations (Par);
7410             Set_Use (Private_Declarations (Spec));
7411          end if;
7412       end Install_Spec;
7413
7414    --  Start of processing for Install_Parent
7415
7416    begin
7417       --  We need to install the parent instance to compile the instantiation
7418       --  of the child, but the child instance must appear in the current
7419       --  scope. Given that we cannot place the parent above the current scope
7420       --  in the scope stack, we duplicate the current scope and unstack both
7421       --  after the instantiation is complete.
7422
7423       --  If the parent is itself the instantiation of a child unit, we must
7424       --  also stack the instantiation of its parent, and so on. Each such
7425       --  ancestor is the prefix of the name in a prior instantiation.
7426
7427       --  If this is a nested instance, the parent unit itself resolves to
7428       --  a renaming of the parent instance, whose declaration we need.
7429
7430       --  Finally, the parent may be a generic (not an instance) when the
7431       --  child unit appears as a formal package.
7432
7433       Inst_Par := P;
7434
7435       if Present (Renamed_Entity (Inst_Par)) then
7436          Inst_Par := Renamed_Entity (Inst_Par);
7437       end if;
7438
7439       First_Par := Inst_Par;
7440
7441       Gen_Par :=
7442         Generic_Parent (Specification (Unit_Declaration_Node (Inst_Par)));
7443
7444       First_Gen := Gen_Par;
7445
7446       while Present (Gen_Par)
7447         and then Is_Child_Unit (Gen_Par)
7448       loop
7449          --  Load grandparent instance as well
7450
7451          Inst_Node := Get_Package_Instantiation_Node (Inst_Par);
7452
7453          if Nkind (Name (Inst_Node)) = N_Expanded_Name then
7454             Inst_Par := Entity (Prefix (Name (Inst_Node)));
7455
7456             if Present (Renamed_Entity (Inst_Par)) then
7457                Inst_Par := Renamed_Entity (Inst_Par);
7458             end if;
7459
7460             Gen_Par :=
7461               Generic_Parent
7462                 (Specification (Unit_Declaration_Node (Inst_Par)));
7463
7464             if Present (Gen_Par) then
7465                Prepend_Elmt (Inst_Par, Ancestors);
7466
7467             else
7468                --  Parent is not the name of an instantiation
7469
7470                Install_Noninstance_Specs (Inst_Par);
7471
7472                exit;
7473             end if;
7474
7475          else
7476             --  Previous error
7477
7478             exit;
7479          end if;
7480       end loop;
7481
7482       if Present (First_Gen) then
7483          Append_Elmt (First_Par, Ancestors);
7484
7485       else
7486          Install_Noninstance_Specs (First_Par);
7487       end if;
7488
7489       if not Is_Empty_Elmt_List (Ancestors) then
7490          Elmt := First_Elmt (Ancestors);
7491
7492          while Present (Elmt) loop
7493             Install_Spec (Node (Elmt));
7494             Install_Formal_Packages (Node (Elmt));
7495
7496             Next_Elmt (Elmt);
7497          end loop;
7498       end if;
7499
7500       if not In_Body then
7501          Push_Scope (S);
7502       end if;
7503    end Install_Parent;
7504
7505    --------------------------------
7506    -- Instantiate_Formal_Package --
7507    --------------------------------
7508
7509    function Instantiate_Formal_Package
7510      (Formal          : Node_Id;
7511       Actual          : Node_Id;
7512       Analyzed_Formal : Node_Id) return List_Id
7513    is
7514       Loc         : constant Source_Ptr := Sloc (Actual);
7515       Actual_Pack : Entity_Id;
7516       Formal_Pack : Entity_Id;
7517       Gen_Parent  : Entity_Id;
7518       Decls       : List_Id;
7519       Nod         : Node_Id;
7520       Parent_Spec : Node_Id;
7521
7522       procedure Find_Matching_Actual
7523        (F    : Node_Id;
7524         Act  : in out Entity_Id);
7525       --  We need to associate each formal entity in the formal package
7526       --  with the corresponding entity in the actual package. The actual
7527       --  package has been analyzed and possibly expanded, and as a result
7528       --  there is no one-to-one correspondence between the two lists (for
7529       --  example, the actual may include subtypes, itypes, and inherited
7530       --  primitive operations, interspersed among the renaming declarations
7531       --  for the actuals) . We retrieve the corresponding actual by name
7532       --  because each actual has the same name as the formal, and they do
7533       --  appear in the same order.
7534
7535       function Get_Formal_Entity (N : Node_Id) return Entity_Id;
7536       --  Retrieve entity of defining entity of  generic formal parameter.
7537       --  Only the declarations of formals need to be considered when
7538       --  linking them to actuals, but the declarative list may include
7539       --  internal entities generated during analysis, and those are ignored.
7540
7541       procedure Match_Formal_Entity
7542         (Formal_Node : Node_Id;
7543          Formal_Ent  : Entity_Id;
7544          Actual_Ent  : Entity_Id);
7545       --  Associates the formal entity with the actual. In the case
7546       --  where Formal_Ent is a formal package, this procedure iterates
7547       --  through all of its formals and enters associations between the
7548       --  actuals occurring in the formal package's corresponding actual
7549       --  package (given by Actual_Ent) and the formal package's formal
7550       --  parameters. This procedure recurses if any of the parameters is
7551       --  itself a package.
7552
7553       function Is_Instance_Of
7554         (Act_Spec : Entity_Id;
7555          Gen_Anc  : Entity_Id) return Boolean;
7556       --  The actual can be an instantiation of a generic within another
7557       --  instance, in which case there is no direct link from it to the
7558       --  original generic ancestor. In that case, we recognize that the
7559       --  ultimate ancestor is the same by examining names and scopes.
7560
7561       procedure Process_Nested_Formal (Formal : Entity_Id);
7562       --  If the current formal is declared with a box, its own formals are
7563       --  visible in the instance, as they were in the generic, and their
7564       --  Hidden flag must be reset. If some of these formals are themselves
7565       --  packages declared with a box, the processing must be recursive.
7566
7567       --------------------------
7568       -- Find_Matching_Actual --
7569       --------------------------
7570
7571       procedure Find_Matching_Actual
7572         (F   : Node_Id;
7573          Act : in out Entity_Id)
7574      is
7575          Formal_Ent : Entity_Id;
7576
7577       begin
7578          case Nkind (Original_Node (F)) is
7579             when N_Formal_Object_Declaration |
7580                  N_Formal_Type_Declaration   =>
7581                Formal_Ent := Defining_Identifier (F);
7582
7583                while Chars (Act) /= Chars (Formal_Ent) loop
7584                   Next_Entity (Act);
7585                end loop;
7586
7587             when N_Formal_Subprogram_Declaration |
7588                  N_Formal_Package_Declaration    |
7589                  N_Package_Declaration           |
7590                  N_Generic_Package_Declaration   =>
7591                Formal_Ent := Defining_Entity (F);
7592
7593                while Chars (Act) /= Chars (Formal_Ent) loop
7594                   Next_Entity (Act);
7595                end loop;
7596
7597             when others =>
7598                raise Program_Error;
7599          end case;
7600       end Find_Matching_Actual;
7601
7602       -------------------------
7603       -- Match_Formal_Entity --
7604       -------------------------
7605
7606       procedure Match_Formal_Entity
7607         (Formal_Node : Node_Id;
7608          Formal_Ent  : Entity_Id;
7609          Actual_Ent  : Entity_Id)
7610       is
7611          Act_Pkg   : Entity_Id;
7612
7613       begin
7614          Set_Instance_Of (Formal_Ent, Actual_Ent);
7615
7616          if Ekind (Actual_Ent) = E_Package then
7617
7618             --  Record associations for each parameter
7619
7620             Act_Pkg := Actual_Ent;
7621
7622             declare
7623                A_Ent  : Entity_Id := First_Entity (Act_Pkg);
7624                F_Ent  : Entity_Id;
7625                F_Node : Node_Id;
7626
7627                Gen_Decl : Node_Id;
7628                Formals  : List_Id;
7629                Actual   : Entity_Id;
7630
7631             begin
7632                --  Retrieve the actual given in the formal package declaration
7633
7634                Actual := Entity (Name (Original_Node (Formal_Node)));
7635
7636                --  The actual in the formal package declaration  may be a
7637                --  renamed generic package, in which case we want to retrieve
7638                --  the original generic in order to traverse its formal part.
7639
7640                if Present (Renamed_Entity (Actual)) then
7641                   Gen_Decl := Unit_Declaration_Node (Renamed_Entity (Actual));
7642                else
7643                   Gen_Decl := Unit_Declaration_Node (Actual);
7644                end if;
7645
7646                Formals := Generic_Formal_Declarations (Gen_Decl);
7647
7648                if Present (Formals) then
7649                   F_Node := First_Non_Pragma (Formals);
7650                else
7651                   F_Node := Empty;
7652                end if;
7653
7654                while Present (A_Ent)
7655                  and then Present (F_Node)
7656                  and then A_Ent /= First_Private_Entity (Act_Pkg)
7657                loop
7658                   F_Ent := Get_Formal_Entity (F_Node);
7659
7660                   if Present (F_Ent) then
7661
7662                      --  This is a formal of the original package. Record
7663                      --  association and recurse.
7664
7665                      Find_Matching_Actual (F_Node, A_Ent);
7666                      Match_Formal_Entity (F_Node, F_Ent, A_Ent);
7667                      Next_Entity (A_Ent);
7668                   end if;
7669
7670                   Next_Non_Pragma (F_Node);
7671                end loop;
7672             end;
7673          end if;
7674       end Match_Formal_Entity;
7675
7676       -----------------------
7677       -- Get_Formal_Entity --
7678       -----------------------
7679
7680       function Get_Formal_Entity (N : Node_Id) return Entity_Id is
7681          Kind : constant Node_Kind := Nkind (Original_Node (N));
7682       begin
7683          case Kind is
7684             when N_Formal_Object_Declaration     =>
7685                return Defining_Identifier (N);
7686
7687             when N_Formal_Type_Declaration       =>
7688                return Defining_Identifier (N);
7689
7690             when N_Formal_Subprogram_Declaration =>
7691                return Defining_Unit_Name (Specification (N));
7692
7693             when N_Formal_Package_Declaration    =>
7694                return Defining_Identifier (Original_Node (N));
7695
7696             when N_Generic_Package_Declaration   =>
7697                return Defining_Identifier (Original_Node (N));
7698
7699             --  All other declarations are introduced by semantic analysis and
7700             --  have no match in the actual.
7701
7702             when others =>
7703                return Empty;
7704          end case;
7705       end Get_Formal_Entity;
7706
7707       --------------------
7708       -- Is_Instance_Of --
7709       --------------------
7710
7711       function Is_Instance_Of
7712         (Act_Spec : Entity_Id;
7713          Gen_Anc  : Entity_Id) return Boolean
7714       is
7715          Gen_Par : constant Entity_Id := Generic_Parent (Act_Spec);
7716
7717       begin
7718          if No (Gen_Par) then
7719             return False;
7720
7721          --  Simplest case: the generic parent of the actual is the formal
7722
7723          elsif Gen_Par = Gen_Anc then
7724             return True;
7725
7726          elsif Chars (Gen_Par) /= Chars (Gen_Anc) then
7727             return False;
7728
7729          --  The actual may be obtained through several instantiations. Its
7730          --  scope must itself be an instance of a generic declared in the
7731          --  same scope as the formal. Any other case is detected above.
7732
7733          elsif not Is_Generic_Instance (Scope (Gen_Par)) then
7734             return False;
7735
7736          else
7737             return Generic_Parent (Parent (Scope (Gen_Par))) = Scope (Gen_Anc);
7738          end if;
7739       end Is_Instance_Of;
7740
7741       ---------------------------
7742       -- Process_Nested_Formal --
7743       ---------------------------
7744
7745       procedure Process_Nested_Formal (Formal : Entity_Id) is
7746          Ent : Entity_Id;
7747
7748       begin
7749          if Present (Associated_Formal_Package (Formal))
7750            and then Box_Present (Parent (Associated_Formal_Package (Formal)))
7751          then
7752             Ent := First_Entity (Formal);
7753             while Present (Ent) loop
7754                Set_Is_Hidden (Ent, False);
7755                Set_Is_Visible_Formal (Ent);
7756                Set_Is_Potentially_Use_Visible
7757                  (Ent, Is_Potentially_Use_Visible (Formal));
7758
7759                if Ekind (Ent) = E_Package then
7760                   exit when Renamed_Entity (Ent) = Renamed_Entity (Formal);
7761                   Process_Nested_Formal (Ent);
7762                end if;
7763
7764                Next_Entity (Ent);
7765             end loop;
7766          end if;
7767       end Process_Nested_Formal;
7768
7769    --  Start of processing for Instantiate_Formal_Package
7770
7771    begin
7772       Analyze (Actual);
7773
7774       if not Is_Entity_Name (Actual)
7775         or else  Ekind (Entity (Actual)) /= E_Package
7776       then
7777          Error_Msg_N
7778            ("expect package instance to instantiate formal", Actual);
7779          Abandon_Instantiation (Actual);
7780          raise Program_Error;
7781
7782       else
7783          Actual_Pack := Entity (Actual);
7784          Set_Is_Instantiated (Actual_Pack);
7785
7786          --  The actual may be a renamed package, or an outer generic formal
7787          --  package whose instantiation is converted into a renaming.
7788
7789          if Present (Renamed_Object (Actual_Pack)) then
7790             Actual_Pack := Renamed_Object (Actual_Pack);
7791          end if;
7792
7793          if Nkind (Analyzed_Formal) = N_Formal_Package_Declaration then
7794             Gen_Parent  := Get_Instance_Of (Entity (Name (Analyzed_Formal)));
7795             Formal_Pack := Defining_Identifier (Analyzed_Formal);
7796          else
7797             Gen_Parent :=
7798               Generic_Parent (Specification (Analyzed_Formal));
7799             Formal_Pack :=
7800               Defining_Unit_Name (Specification (Analyzed_Formal));
7801          end if;
7802
7803          if Nkind (Parent (Actual_Pack)) = N_Defining_Program_Unit_Name then
7804             Parent_Spec := Specification (Unit_Declaration_Node (Actual_Pack));
7805          else
7806             Parent_Spec := Parent (Actual_Pack);
7807          end if;
7808
7809          if Gen_Parent = Any_Id then
7810             Error_Msg_N
7811               ("previous error in declaration of formal package", Actual);
7812             Abandon_Instantiation (Actual);
7813
7814          elsif
7815            Is_Instance_Of (Parent_Spec, Get_Instance_Of (Gen_Parent))
7816          then
7817             null;
7818
7819          else
7820             Error_Msg_NE
7821               ("actual parameter must be instance of&", Actual, Gen_Parent);
7822             Abandon_Instantiation (Actual);
7823          end if;
7824
7825          Set_Instance_Of (Defining_Identifier (Formal), Actual_Pack);
7826          Map_Formal_Package_Entities (Formal_Pack, Actual_Pack);
7827
7828          Nod :=
7829            Make_Package_Renaming_Declaration (Loc,
7830              Defining_Unit_Name => New_Copy (Defining_Identifier (Formal)),
7831              Name               => New_Reference_To (Actual_Pack, Loc));
7832
7833          Set_Associated_Formal_Package (Defining_Unit_Name (Nod),
7834            Defining_Identifier (Formal));
7835          Decls := New_List (Nod);
7836
7837          --  If the formal F has a box, then the generic declarations are
7838          --  visible in the generic G. In an instance of G, the corresponding
7839          --  entities in the actual for F (which are the actuals for the
7840          --  instantiation of the generic that F denotes) must also be made
7841          --  visible for analysis of the current instance. On exit from the
7842          --  current instance, those entities are made private again. If the
7843          --  actual is currently in use, these entities are also use-visible.
7844
7845          --  The loop through the actual entities also steps through the formal
7846          --  entities and enters associations from formals to actuals into the
7847          --  renaming map. This is necessary to properly handle checking of
7848          --  actual parameter associations for later formals that depend on
7849          --  actuals declared in the formal package.
7850
7851          --  In Ada 2005, partial parametrization requires that we make visible
7852          --  the actuals corresponding to formals that were defaulted in the
7853          --  formal package. There formals are identified because they remain
7854          --  formal generics within the formal package, rather than being
7855          --  renamings of the actuals supplied.
7856
7857          declare
7858             Gen_Decl : constant Node_Id :=
7859                          Unit_Declaration_Node (Gen_Parent);
7860             Formals  : constant List_Id :=
7861                          Generic_Formal_Declarations (Gen_Decl);
7862
7863             Actual_Ent       : Entity_Id;
7864             Actual_Of_Formal : Node_Id;
7865             Formal_Node      : Node_Id;
7866             Formal_Ent       : Entity_Id;
7867
7868          begin
7869             if Present (Formals) then
7870                Formal_Node := First_Non_Pragma (Formals);
7871             else
7872                Formal_Node := Empty;
7873             end if;
7874
7875             Actual_Ent := First_Entity (Actual_Pack);
7876             Actual_Of_Formal :=
7877                First (Visible_Declarations (Specification (Analyzed_Formal)));
7878             while Present (Actual_Ent)
7879               and then Actual_Ent /= First_Private_Entity (Actual_Pack)
7880             loop
7881                if Present (Formal_Node) then
7882                   Formal_Ent := Get_Formal_Entity (Formal_Node);
7883
7884                   if Present (Formal_Ent) then
7885                      Find_Matching_Actual (Formal_Node, Actual_Ent);
7886                      Match_Formal_Entity
7887                        (Formal_Node, Formal_Ent, Actual_Ent);
7888
7889                      --  We iterate at the same time over the actuals of the
7890                      --  local package created for the formal, to determine
7891                      --  which one of the formals of the original generic were
7892                      --  defaulted in the formal. The corresponding actual
7893                      --  entities are visible in the enclosing instance.
7894
7895                      if Box_Present (Formal)
7896                        or else
7897                          (Present (Actual_Of_Formal)
7898                            and then
7899                              Is_Generic_Formal
7900                                (Get_Formal_Entity (Actual_Of_Formal)))
7901                      then
7902                         Set_Is_Hidden (Actual_Ent, False);
7903                         Set_Is_Visible_Formal (Actual_Ent);
7904                         Set_Is_Potentially_Use_Visible
7905                           (Actual_Ent, In_Use (Actual_Pack));
7906
7907                         if Ekind (Actual_Ent) = E_Package then
7908                            Process_Nested_Formal (Actual_Ent);
7909                         end if;
7910
7911                      else
7912                         Set_Is_Hidden (Actual_Ent);
7913                         Set_Is_Potentially_Use_Visible (Actual_Ent, False);
7914                      end if;
7915                   end if;
7916
7917                   Next_Non_Pragma (Formal_Node);
7918                   Next (Actual_Of_Formal);
7919
7920                else
7921                   --  No further formals to match, but the generic part may
7922                   --  contain inherited operation that are not hidden in the
7923                   --  enclosing instance.
7924
7925                   Next_Entity (Actual_Ent);
7926                end if;
7927             end loop;
7928
7929             --  Inherited subprograms generated by formal derived types are
7930             --  also visible if the types are.
7931
7932             Actual_Ent := First_Entity (Actual_Pack);
7933             while Present (Actual_Ent)
7934               and then Actual_Ent /= First_Private_Entity (Actual_Pack)
7935             loop
7936                if Is_Overloadable (Actual_Ent)
7937                  and then
7938                    Nkind (Parent (Actual_Ent)) = N_Subtype_Declaration
7939                  and then
7940                    not Is_Hidden (Defining_Identifier (Parent (Actual_Ent)))
7941                then
7942                   Set_Is_Hidden (Actual_Ent, False);
7943                   Set_Is_Potentially_Use_Visible
7944                     (Actual_Ent, In_Use (Actual_Pack));
7945                end if;
7946
7947                Next_Entity (Actual_Ent);
7948             end loop;
7949          end;
7950
7951          --  If the formal is not declared with a box, reanalyze it as an
7952          --  abbreviated instantiation, to verify the matching rules of 12.7.
7953          --  The actual checks are performed after the generic associations
7954          --  have been analyzed, to guarantee the same visibility for this
7955          --  instantiation and for the actuals.
7956
7957          --  In Ada 2005, the generic associations for the formal can include
7958          --  defaulted parameters. These are ignored during check. This
7959          --  internal instantiation is removed from the tree after conformance
7960          --  checking, because it contains formal declarations for those
7961          --  defaulted parameters, and those should not reach the back-end.
7962
7963          if not Box_Present (Formal) then
7964             declare
7965                I_Pack : constant Entity_Id :=
7966                           Make_Temporary (Sloc (Actual), 'P');
7967
7968             begin
7969                Set_Is_Internal (I_Pack);
7970
7971                Append_To (Decls,
7972                  Make_Package_Instantiation (Sloc (Actual),
7973                    Defining_Unit_Name => I_Pack,
7974                    Name =>
7975                      New_Occurrence_Of
7976                        (Get_Instance_Of (Gen_Parent), Sloc (Actual)),
7977                    Generic_Associations =>
7978                      Generic_Associations (Formal)));
7979             end;
7980          end if;
7981
7982          return Decls;
7983       end if;
7984    end Instantiate_Formal_Package;
7985
7986    -----------------------------------
7987    -- Instantiate_Formal_Subprogram --
7988    -----------------------------------
7989
7990    function Instantiate_Formal_Subprogram
7991      (Formal          : Node_Id;
7992       Actual          : Node_Id;
7993       Analyzed_Formal : Node_Id) return Node_Id
7994    is
7995       Loc        : Source_Ptr;
7996       Formal_Sub : constant Entity_Id :=
7997                      Defining_Unit_Name (Specification (Formal));
7998       Analyzed_S : constant Entity_Id :=
7999                      Defining_Unit_Name (Specification (Analyzed_Formal));
8000       Decl_Node  : Node_Id;
8001       Nam        : Node_Id;
8002       New_Spec   : Node_Id;
8003
8004       function From_Parent_Scope (Subp : Entity_Id) return Boolean;
8005       --  If the generic is a child unit, the parent has been installed on the
8006       --  scope stack, but a default subprogram cannot resolve to something on
8007       --  the parent because that parent is not really part of the visible
8008       --  context (it is there to resolve explicit local entities). If the
8009       --  default has resolved in this way, we remove the entity from
8010       --  immediate visibility and analyze the node again to emit an error
8011       --  message or find another visible candidate.
8012
8013       procedure Valid_Actual_Subprogram (Act : Node_Id);
8014       --  Perform legality check and raise exception on failure
8015
8016       -----------------------
8017       -- From_Parent_Scope --
8018       -----------------------
8019
8020       function From_Parent_Scope (Subp : Entity_Id) return Boolean is
8021          Gen_Scope : Node_Id;
8022
8023       begin
8024          Gen_Scope := Scope (Analyzed_S);
8025          while Present (Gen_Scope)
8026            and then  Is_Child_Unit (Gen_Scope)
8027          loop
8028             if Scope (Subp) = Scope (Gen_Scope) then
8029                return True;
8030             end if;
8031
8032             Gen_Scope := Scope (Gen_Scope);
8033          end loop;
8034
8035          return False;
8036       end From_Parent_Scope;
8037
8038       -----------------------------
8039       -- Valid_Actual_Subprogram --
8040       -----------------------------
8041
8042       procedure Valid_Actual_Subprogram (Act : Node_Id) is
8043          Act_E : Entity_Id;
8044
8045       begin
8046          if Is_Entity_Name (Act) then
8047             Act_E := Entity (Act);
8048
8049          elsif Nkind (Act) = N_Selected_Component
8050            and then Is_Entity_Name (Selector_Name (Act))
8051          then
8052             Act_E := Entity (Selector_Name (Act));
8053
8054          else
8055             Act_E := Empty;
8056          end if;
8057
8058          if (Present (Act_E) and then Is_Overloadable (Act_E))
8059            or else Nkind_In (Act, N_Attribute_Reference,
8060                                   N_Indexed_Component,
8061                                   N_Character_Literal,
8062                                   N_Explicit_Dereference)
8063          then
8064             return;
8065          end if;
8066
8067          Error_Msg_NE
8068            ("expect subprogram or entry name in instantiation of&",
8069             Instantiation_Node, Formal_Sub);
8070          Abandon_Instantiation (Instantiation_Node);
8071
8072       end Valid_Actual_Subprogram;
8073
8074    --  Start of processing for Instantiate_Formal_Subprogram
8075
8076    begin
8077       New_Spec := New_Copy_Tree (Specification (Formal));
8078
8079       --  The tree copy has created the proper instantiation sloc for the
8080       --  new specification. Use this location for all other constructed
8081       --  declarations.
8082
8083       Loc := Sloc (Defining_Unit_Name (New_Spec));
8084
8085       --  Create new entity for the actual (New_Copy_Tree does not)
8086
8087       Set_Defining_Unit_Name
8088         (New_Spec, Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
8089
8090       --  Create new entities for the each of the formals in the
8091       --  specification of the renaming declaration built for the actual.
8092
8093       if Present (Parameter_Specifications (New_Spec)) then
8094          declare
8095             F : Node_Id;
8096          begin
8097             F := First (Parameter_Specifications (New_Spec));
8098             while Present (F) loop
8099                Set_Defining_Identifier (F,
8100                   Make_Defining_Identifier (Sloc (F),
8101                     Chars => Chars (Defining_Identifier (F))));
8102                Next (F);
8103             end loop;
8104          end;
8105       end if;
8106
8107       --  Find entity of actual. If the actual is an attribute reference, it
8108       --  cannot be resolved here (its formal is missing) but is handled
8109       --  instead in Attribute_Renaming. If the actual is overloaded, it is
8110       --  fully resolved subsequently, when the renaming declaration for the
8111       --  formal is analyzed. If it is an explicit dereference, resolve the
8112       --  prefix but not the actual itself, to prevent interpretation as call.
8113
8114       if Present (Actual) then
8115          Loc := Sloc (Actual);
8116          Set_Sloc (New_Spec, Loc);
8117
8118          if Nkind (Actual) = N_Operator_Symbol then
8119             Find_Direct_Name (Actual);
8120
8121          elsif Nkind (Actual) = N_Explicit_Dereference then
8122             Analyze (Prefix (Actual));
8123
8124          elsif Nkind (Actual) /= N_Attribute_Reference then
8125             Analyze (Actual);
8126          end if;
8127
8128          Valid_Actual_Subprogram (Actual);
8129          Nam := Actual;
8130
8131       elsif Present (Default_Name (Formal)) then
8132          if not Nkind_In (Default_Name (Formal), N_Attribute_Reference,
8133                                                  N_Selected_Component,
8134                                                  N_Indexed_Component,
8135                                                  N_Character_Literal)
8136            and then Present (Entity (Default_Name (Formal)))
8137          then
8138             Nam := New_Occurrence_Of (Entity (Default_Name (Formal)), Loc);
8139          else
8140             Nam := New_Copy (Default_Name (Formal));
8141             Set_Sloc (Nam, Loc);
8142          end if;
8143
8144       elsif Box_Present (Formal) then
8145
8146          --  Actual is resolved at the point of instantiation. Create an
8147          --  identifier or operator with the same name as the formal.
8148
8149          if Nkind (Formal_Sub) = N_Defining_Operator_Symbol then
8150             Nam := Make_Operator_Symbol (Loc,
8151               Chars =>  Chars (Formal_Sub),
8152               Strval => No_String);
8153          else
8154             Nam := Make_Identifier (Loc, Chars (Formal_Sub));
8155          end if;
8156
8157       elsif Nkind (Specification (Formal)) = N_Procedure_Specification
8158         and then Null_Present (Specification (Formal))
8159       then
8160          --  Generate null body for procedure, for use in the instance
8161
8162          Decl_Node :=
8163            Make_Subprogram_Body (Loc,
8164              Specification              => New_Spec,
8165              Declarations               => New_List,
8166              Handled_Statement_Sequence =>
8167                Make_Handled_Sequence_Of_Statements (Loc,
8168                  Statements => New_List (Make_Null_Statement (Loc))));
8169
8170          Set_Is_Intrinsic_Subprogram (Defining_Unit_Name (New_Spec));
8171          return Decl_Node;
8172
8173       else
8174          Error_Msg_Sloc := Sloc (Scope (Analyzed_S));
8175          Error_Msg_NE
8176            ("missing actual&", Instantiation_Node, Formal_Sub);
8177          Error_Msg_NE
8178            ("\in instantiation of & declared#",
8179               Instantiation_Node, Scope (Analyzed_S));
8180          Abandon_Instantiation (Instantiation_Node);
8181       end if;
8182
8183       Decl_Node :=
8184         Make_Subprogram_Renaming_Declaration (Loc,
8185           Specification => New_Spec,
8186           Name          => Nam);
8187
8188       --  If we do not have an actual and the formal specified <> then set to
8189       --  get proper default.
8190
8191       if No (Actual) and then Box_Present (Formal) then
8192          Set_From_Default (Decl_Node);
8193       end if;
8194
8195       --  Gather possible interpretations for the actual before analyzing the
8196       --  instance. If overloaded, it will be resolved when analyzing the
8197       --  renaming declaration.
8198
8199       if Box_Present (Formal)
8200         and then No (Actual)
8201       then
8202          Analyze (Nam);
8203
8204          if Is_Child_Unit (Scope (Analyzed_S))
8205            and then Present (Entity (Nam))
8206          then
8207             if not Is_Overloaded (Nam) then
8208
8209                if From_Parent_Scope (Entity (Nam)) then
8210                   Set_Is_Immediately_Visible (Entity (Nam), False);
8211                   Set_Entity (Nam, Empty);
8212                   Set_Etype (Nam, Empty);
8213
8214                   Analyze (Nam);
8215
8216                   Set_Is_Immediately_Visible (Entity (Nam));
8217                end if;
8218
8219             else
8220                declare
8221                   I  : Interp_Index;
8222                   It : Interp;
8223
8224                begin
8225                   Get_First_Interp (Nam, I, It);
8226
8227                   while Present (It.Nam) loop
8228                      if From_Parent_Scope (It.Nam) then
8229                         Remove_Interp (I);
8230                      end if;
8231
8232                      Get_Next_Interp (I, It);
8233                   end loop;
8234                end;
8235             end if;
8236          end if;
8237       end if;
8238
8239       --  The generic instantiation freezes the actual. This can only be done
8240       --  once the actual is resolved, in the analysis of the renaming
8241       --  declaration. To make the formal subprogram entity available, we set
8242       --  Corresponding_Formal_Spec to point to the formal subprogram entity.
8243       --  This is also needed in Analyze_Subprogram_Renaming for the processing
8244       --  of formal abstract subprograms.
8245
8246       Set_Corresponding_Formal_Spec (Decl_Node, Analyzed_S);
8247
8248       --  We cannot analyze the renaming declaration, and thus find the actual,
8249       --  until all the actuals are assembled in the instance. For subsequent
8250       --  checks of other actuals, indicate the node that will hold the
8251       --  instance of this formal.
8252
8253       Set_Instance_Of (Analyzed_S, Nam);
8254
8255       if Nkind (Actual) = N_Selected_Component
8256         and then Is_Task_Type (Etype (Prefix (Actual)))
8257         and then not Is_Frozen (Etype (Prefix (Actual)))
8258       then
8259          --  The renaming declaration will create a body, which must appear
8260          --  outside of the instantiation, We move the renaming declaration
8261          --  out of the instance, and create an additional renaming inside,
8262          --  to prevent freezing anomalies.
8263
8264          declare
8265             Anon_Id : constant Entity_Id := Make_Temporary (Loc, 'E');
8266
8267          begin
8268             Set_Defining_Unit_Name (New_Spec, Anon_Id);
8269             Insert_Before (Instantiation_Node, Decl_Node);
8270             Analyze (Decl_Node);
8271
8272             --  Now create renaming within the instance
8273
8274             Decl_Node :=
8275               Make_Subprogram_Renaming_Declaration (Loc,
8276                 Specification => New_Copy_Tree (New_Spec),
8277                 Name => New_Occurrence_Of (Anon_Id, Loc));
8278
8279             Set_Defining_Unit_Name (Specification (Decl_Node),
8280               Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
8281          end;
8282       end if;
8283
8284       return Decl_Node;
8285    end Instantiate_Formal_Subprogram;
8286
8287    ------------------------
8288    -- Instantiate_Object --
8289    ------------------------
8290
8291    function Instantiate_Object
8292      (Formal          : Node_Id;
8293       Actual          : Node_Id;
8294       Analyzed_Formal : Node_Id) return List_Id
8295    is
8296       Gen_Obj     : constant Entity_Id  := Defining_Identifier (Formal);
8297       A_Gen_Obj   : constant Entity_Id  :=
8298                       Defining_Identifier (Analyzed_Formal);
8299       Acc_Def     : Node_Id             := Empty;
8300       Act_Assoc   : constant Node_Id    := Parent (Actual);
8301       Actual_Decl : Node_Id             := Empty;
8302       Decl_Node   : Node_Id;
8303       Def         : Node_Id;
8304       Ftyp        : Entity_Id;
8305       List        : constant List_Id    := New_List;
8306       Loc         : constant Source_Ptr := Sloc (Actual);
8307       Orig_Ftyp   : constant Entity_Id  := Etype (A_Gen_Obj);
8308       Subt_Decl   : Node_Id             := Empty;
8309       Subt_Mark   : Node_Id             := Empty;
8310
8311    begin
8312       if Present (Subtype_Mark (Formal)) then
8313          Subt_Mark := Subtype_Mark (Formal);
8314       else
8315          Check_Access_Definition (Formal);
8316          Acc_Def := Access_Definition (Formal);
8317       end if;
8318
8319       --  Sloc for error message on missing actual
8320
8321       Error_Msg_Sloc := Sloc (Scope (A_Gen_Obj));
8322
8323       if Get_Instance_Of (Gen_Obj) /= Gen_Obj then
8324          Error_Msg_N ("duplicate instantiation of generic parameter", Actual);
8325       end if;
8326
8327       Set_Parent (List, Parent (Actual));
8328
8329       --  OUT present
8330
8331       if Out_Present (Formal) then
8332
8333          --  An IN OUT generic actual must be a name. The instantiation is a
8334          --  renaming declaration. The actual is the name being renamed. We
8335          --  use the actual directly, rather than a copy, because it is not
8336          --  used further in the list of actuals, and because a copy or a use
8337          --  of relocate_node is incorrect if the instance is nested within a
8338          --  generic. In order to simplify ASIS searches, the Generic_Parent
8339          --  field links the declaration to the generic association.
8340
8341          if No (Actual) then
8342             Error_Msg_NE
8343               ("missing actual&",
8344                Instantiation_Node, Gen_Obj);
8345             Error_Msg_NE
8346               ("\in instantiation of & declared#",
8347                  Instantiation_Node, Scope (A_Gen_Obj));
8348             Abandon_Instantiation (Instantiation_Node);
8349          end if;
8350
8351          if Present (Subt_Mark) then
8352             Decl_Node :=
8353               Make_Object_Renaming_Declaration (Loc,
8354                 Defining_Identifier => New_Copy (Gen_Obj),
8355                 Subtype_Mark        => New_Copy_Tree (Subt_Mark),
8356                 Name                => Actual);
8357
8358          else pragma Assert (Present (Acc_Def));
8359             Decl_Node :=
8360               Make_Object_Renaming_Declaration (Loc,
8361                 Defining_Identifier => New_Copy (Gen_Obj),
8362                 Access_Definition   => New_Copy_Tree (Acc_Def),
8363                 Name                => Actual);
8364          end if;
8365
8366          Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
8367
8368          --  The analysis of the actual may produce insert_action nodes, so
8369          --  the declaration must have a context in which to attach them.
8370
8371          Append (Decl_Node, List);
8372          Analyze (Actual);
8373
8374          --  Return if the analysis of the actual reported some error
8375
8376          if Etype (Actual) = Any_Type then
8377             return List;
8378          end if;
8379
8380          --  This check is performed here because Analyze_Object_Renaming will
8381          --  not check it when Comes_From_Source is False. Note though that the
8382          --  check for the actual being the name of an object will be performed
8383          --  in Analyze_Object_Renaming.
8384
8385          if Is_Object_Reference (Actual)
8386            and then Is_Dependent_Component_Of_Mutable_Object (Actual)
8387          then
8388             Error_Msg_N
8389               ("illegal discriminant-dependent component for in out parameter",
8390                Actual);
8391          end if;
8392
8393          --  The actual has to be resolved in order to check that it is a
8394          --  variable (due to cases such as F (1), where F returns access to an
8395          --  array, and for overloaded prefixes).
8396
8397          Ftyp := Get_Instance_Of (Etype (A_Gen_Obj));
8398
8399          --  If the type of the formal is not itself a formal, and the
8400          --  current unit is a child unit, the formal type must be declared
8401          --  in a parent, and must be retrieved by visibility.
8402
8403          if Ftyp = Orig_Ftyp
8404            and then Is_Generic_Unit (Scope (Ftyp))
8405            and then Is_Child_Unit (Scope (A_Gen_Obj))
8406          then
8407             declare
8408                Temp : constant Node_Id :=
8409                         New_Copy_Tree (Subtype_Mark (Analyzed_Formal));
8410             begin
8411                Set_Entity (Temp, Empty);
8412                Find_Type (Temp);
8413                Ftyp := Entity (Temp);
8414             end;
8415          end if;
8416
8417          if Is_Private_Type (Ftyp)
8418            and then not Is_Private_Type (Etype (Actual))
8419            and then (Base_Type (Full_View (Ftyp)) = Base_Type (Etype (Actual))
8420                       or else Base_Type (Etype (Actual)) = Ftyp)
8421          then
8422             --  If the actual has the type of the full view of the formal, or
8423             --  else a non-private subtype of the formal, then the visibility
8424             --  of the formal type has changed. Add to the actuals a subtype
8425             --  declaration that will force the exchange of views in the body
8426             --  of the instance as well.
8427
8428             Subt_Decl :=
8429               Make_Subtype_Declaration (Loc,
8430                  Defining_Identifier => Make_Temporary (Loc, 'P'),
8431                  Subtype_Indication  => New_Occurrence_Of (Ftyp, Loc));
8432
8433             Prepend (Subt_Decl, List);
8434
8435             Prepend_Elmt (Full_View (Ftyp), Exchanged_Views);
8436             Exchange_Declarations (Ftyp);
8437          end if;
8438
8439          Resolve (Actual, Ftyp);
8440
8441          if not Denotes_Variable (Actual) then
8442             Error_Msg_NE
8443               ("actual for& must be a variable", Actual, Gen_Obj);
8444
8445          elsif Base_Type (Ftyp) /= Base_Type (Etype (Actual)) then
8446
8447             --  Ada 2005 (AI-423): For a generic formal object of mode in out,
8448             --  the type of the actual shall resolve to a specific anonymous
8449             --  access type.
8450
8451             if Ada_Version < Ada_2005
8452               or else
8453                 Ekind (Base_Type (Ftyp)) /=
8454                   E_Anonymous_Access_Type
8455               or else
8456                 Ekind (Base_Type (Etype (Actual))) /=
8457                   E_Anonymous_Access_Type
8458             then
8459                Error_Msg_NE ("type of actual does not match type of&",
8460                              Actual, Gen_Obj);
8461             end if;
8462          end if;
8463
8464          Note_Possible_Modification (Actual, Sure => True);
8465
8466          --  Check for instantiation of atomic/volatile actual for
8467          --  non-atomic/volatile formal (RM C.6 (12)).
8468
8469          if Is_Atomic_Object (Actual)
8470            and then not Is_Atomic (Orig_Ftyp)
8471          then
8472             Error_Msg_N
8473               ("cannot instantiate non-atomic formal object " &
8474                "with atomic actual", Actual);
8475
8476          elsif Is_Volatile_Object (Actual)
8477            and then not Is_Volatile (Orig_Ftyp)
8478          then
8479             Error_Msg_N
8480               ("cannot instantiate non-volatile formal object " &
8481                "with volatile actual", Actual);
8482          end if;
8483
8484       --  Formal in-parameter
8485
8486       else
8487          --  The instantiation of a generic formal in-parameter is constant
8488          --  declaration. The actual is the expression for that declaration.
8489
8490          if Present (Actual) then
8491             if Present (Subt_Mark) then
8492                Def := Subt_Mark;
8493             else pragma Assert (Present (Acc_Def));
8494                Def := Acc_Def;
8495             end if;
8496
8497             Decl_Node :=
8498               Make_Object_Declaration (Loc,
8499                 Defining_Identifier    => New_Copy (Gen_Obj),
8500                 Constant_Present       => True,
8501                 Null_Exclusion_Present => Null_Exclusion_Present (Formal),
8502                 Object_Definition      => New_Copy_Tree (Def),
8503                 Expression             => Actual);
8504
8505             Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
8506
8507             --  A generic formal object of a tagged type is defined to be
8508             --  aliased so the new constant must also be treated as aliased.
8509
8510             if Is_Tagged_Type (Etype (A_Gen_Obj)) then
8511                Set_Aliased_Present (Decl_Node);
8512             end if;
8513
8514             Append (Decl_Node, List);
8515
8516             --  No need to repeat (pre-)analysis of some expression nodes
8517             --  already handled in Preanalyze_Actuals.
8518
8519             if Nkind (Actual) /= N_Allocator then
8520                Analyze (Actual);
8521
8522                --  Return if the analysis of the actual reported some error
8523
8524                if Etype (Actual) = Any_Type then
8525                   return List;
8526                end if;
8527             end if;
8528
8529             declare
8530                Formal_Type : constant Entity_Id := Etype (A_Gen_Obj);
8531                Typ         : Entity_Id;
8532
8533             begin
8534                Typ := Get_Instance_Of (Formal_Type);
8535
8536                Freeze_Before (Instantiation_Node, Typ);
8537
8538                --  If the actual is an aggregate, perform name resolution on
8539                --  its components (the analysis of an aggregate does not do it)
8540                --  to capture local names that may be hidden if the generic is
8541                --  a child unit.
8542
8543                if Nkind (Actual) = N_Aggregate then
8544                   Preanalyze_And_Resolve (Actual, Typ);
8545                end if;
8546
8547                if Is_Limited_Type (Typ)
8548                  and then not OK_For_Limited_Init (Typ, Actual)
8549                then
8550                   Error_Msg_N
8551                     ("initialization not allowed for limited types", Actual);
8552                   Explain_Limited_Type (Typ, Actual);
8553                end if;
8554             end;
8555
8556          elsif Present (Default_Expression (Formal)) then
8557
8558             --  Use default to construct declaration
8559
8560             if Present (Subt_Mark) then
8561                Def := Subt_Mark;
8562             else pragma Assert (Present (Acc_Def));
8563                Def := Acc_Def;
8564             end if;
8565
8566             Decl_Node :=
8567               Make_Object_Declaration (Sloc (Formal),
8568                 Defining_Identifier    => New_Copy (Gen_Obj),
8569                 Constant_Present       => True,
8570                 Null_Exclusion_Present => Null_Exclusion_Present (Formal),
8571                 Object_Definition      => New_Copy (Def),
8572                 Expression             => New_Copy_Tree
8573                                             (Default_Expression (Formal)));
8574
8575             Append (Decl_Node, List);
8576             Set_Analyzed (Expression (Decl_Node), False);
8577
8578          else
8579             Error_Msg_NE
8580               ("missing actual&",
8581                 Instantiation_Node, Gen_Obj);
8582             Error_Msg_NE ("\in instantiation of & declared#",
8583               Instantiation_Node, Scope (A_Gen_Obj));
8584
8585             if Is_Scalar_Type (Etype (A_Gen_Obj)) then
8586
8587                --  Create dummy constant declaration so that instance can be
8588                --  analyzed, to minimize cascaded visibility errors.
8589
8590                if Present (Subt_Mark) then
8591                   Def := Subt_Mark;
8592                else pragma Assert (Present (Acc_Def));
8593                   Def := Acc_Def;
8594                end if;
8595
8596                Decl_Node :=
8597                  Make_Object_Declaration (Loc,
8598                    Defining_Identifier    => New_Copy (Gen_Obj),
8599                    Constant_Present       => True,
8600                    Null_Exclusion_Present => Null_Exclusion_Present (Formal),
8601                    Object_Definition      => New_Copy (Def),
8602                    Expression             =>
8603                      Make_Attribute_Reference (Sloc (Gen_Obj),
8604                        Attribute_Name => Name_First,
8605                        Prefix         => New_Copy (Def)));
8606
8607                Append (Decl_Node, List);
8608
8609             else
8610                Abandon_Instantiation (Instantiation_Node);
8611             end if;
8612          end if;
8613       end if;
8614
8615       if Nkind (Actual) in N_Has_Entity then
8616          Actual_Decl := Parent (Entity (Actual));
8617       end if;
8618
8619       --  Ada 2005 (AI-423): For a formal object declaration with a null
8620       --  exclusion or an access definition that has a null exclusion: If the
8621       --  actual matching the formal object declaration denotes a generic
8622       --  formal object of another generic unit G, and the instantiation
8623       --  containing the actual occurs within the body of G or within the body
8624       --  of a generic unit declared within the declarative region of G, then
8625       --  the declaration of the formal object of G must have a null exclusion.
8626       --  Otherwise, the subtype of the actual matching the formal object
8627       --  declaration shall exclude null.
8628
8629       if Ada_Version >= Ada_2005
8630         and then Present (Actual_Decl)
8631         and then
8632           Nkind_In (Actual_Decl, N_Formal_Object_Declaration,
8633                                  N_Object_Declaration)
8634         and then Nkind (Analyzed_Formal) = N_Formal_Object_Declaration
8635         and then not Has_Null_Exclusion (Actual_Decl)
8636         and then Has_Null_Exclusion (Analyzed_Formal)
8637       then
8638          Error_Msg_Sloc := Sloc (Analyzed_Formal);
8639          Error_Msg_N
8640            ("actual must exclude null to match generic formal#", Actual);
8641       end if;
8642
8643       return List;
8644    end Instantiate_Object;
8645
8646    ------------------------------
8647    -- Instantiate_Package_Body --
8648    ------------------------------
8649
8650    procedure Instantiate_Package_Body
8651      (Body_Info     : Pending_Body_Info;
8652       Inlined_Body  : Boolean := False;
8653       Body_Optional : Boolean := False)
8654    is
8655       Act_Decl    : constant Node_Id    := Body_Info.Act_Decl;
8656       Inst_Node   : constant Node_Id    := Body_Info.Inst_Node;
8657       Loc         : constant Source_Ptr := Sloc (Inst_Node);
8658
8659       Gen_Id      : constant Node_Id    := Name (Inst_Node);
8660       Gen_Unit    : constant Entity_Id  := Get_Generic_Entity (Inst_Node);
8661       Gen_Decl    : constant Node_Id    := Unit_Declaration_Node (Gen_Unit);
8662       Act_Spec    : constant Node_Id    := Specification (Act_Decl);
8663       Act_Decl_Id : constant Entity_Id  := Defining_Entity (Act_Spec);
8664
8665       Act_Body_Name : Node_Id;
8666       Gen_Body      : Node_Id;
8667       Gen_Body_Id   : Node_Id;
8668       Act_Body      : Node_Id;
8669       Act_Body_Id   : Entity_Id;
8670
8671       Parent_Installed : Boolean := False;
8672       Save_Style_Check : constant Boolean := Style_Check;
8673
8674       Par_Ent : Entity_Id := Empty;
8675       Par_Vis : Boolean   := False;
8676
8677    begin
8678       Gen_Body_Id := Corresponding_Body (Gen_Decl);
8679
8680       --  The instance body may already have been processed, as the parent of
8681       --  another instance that is inlined (Load_Parent_Of_Generic).
8682
8683       if Present (Corresponding_Body (Instance_Spec (Inst_Node))) then
8684          return;
8685       end if;
8686
8687       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
8688
8689       --  Re-establish the state of information on which checks are suppressed.
8690       --  This information was set in Body_Info at the point of instantiation,
8691       --  and now we restore it so that the instance is compiled using the
8692       --  check status at the instantiation (RM 11.5 (7.2/2), AI95-00224-01).
8693
8694       Local_Suppress_Stack_Top := Body_Info.Local_Suppress_Stack_Top;
8695       Scope_Suppress           := Body_Info.Scope_Suppress;
8696       Opt.Ada_Version          := Body_Info.Version;
8697
8698       if No (Gen_Body_Id) then
8699          Load_Parent_Of_Generic
8700            (Inst_Node, Specification (Gen_Decl), Body_Optional);
8701          Gen_Body_Id := Corresponding_Body (Gen_Decl);
8702       end if;
8703
8704       --  Establish global variable for sloc adjustment and for error recovery
8705
8706       Instantiation_Node := Inst_Node;
8707
8708       if Present (Gen_Body_Id) then
8709          Save_Env (Gen_Unit, Act_Decl_Id);
8710          Style_Check := False;
8711          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
8712
8713          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
8714
8715          Create_Instantiation_Source
8716            (Inst_Node, Gen_Body_Id, False, S_Adjustment);
8717
8718          Act_Body :=
8719            Copy_Generic_Node
8720              (Original_Node (Gen_Body), Empty, Instantiating => True);
8721
8722          --  Build new name (possibly qualified) for body declaration
8723
8724          Act_Body_Id := New_Copy (Act_Decl_Id);
8725
8726          --  Some attributes of spec entity are not inherited by body entity
8727
8728          Set_Handler_Records (Act_Body_Id, No_List);
8729
8730          if Nkind (Defining_Unit_Name (Act_Spec)) =
8731                                            N_Defining_Program_Unit_Name
8732          then
8733             Act_Body_Name :=
8734               Make_Defining_Program_Unit_Name (Loc,
8735                 Name => New_Copy_Tree (Name (Defining_Unit_Name (Act_Spec))),
8736                 Defining_Identifier => Act_Body_Id);
8737          else
8738             Act_Body_Name :=  Act_Body_Id;
8739          end if;
8740
8741          Set_Defining_Unit_Name (Act_Body, Act_Body_Name);
8742
8743          Set_Corresponding_Spec (Act_Body, Act_Decl_Id);
8744          Check_Generic_Actuals (Act_Decl_Id, False);
8745
8746          --  If it is a child unit, make the parent instance (which is an
8747          --  instance of the parent of the generic) visible. The parent
8748          --  instance is the prefix of the name of the generic unit.
8749
8750          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
8751            and then Nkind (Gen_Id) = N_Expanded_Name
8752          then
8753             Par_Ent := Entity (Prefix (Gen_Id));
8754             Par_Vis := Is_Immediately_Visible (Par_Ent);
8755             Install_Parent (Par_Ent, In_Body => True);
8756             Parent_Installed := True;
8757
8758          elsif Is_Child_Unit (Gen_Unit) then
8759             Par_Ent := Scope (Gen_Unit);
8760             Par_Vis := Is_Immediately_Visible (Par_Ent);
8761             Install_Parent (Par_Ent, In_Body => True);
8762             Parent_Installed := True;
8763          end if;
8764
8765          --  If the instantiation is a library unit, and this is the main unit,
8766          --  then build the resulting compilation unit nodes for the instance.
8767          --  If this is a compilation unit but it is not the main unit, then it
8768          --  is the body of a unit in the context, that is being compiled
8769          --  because it is encloses some inlined unit or another generic unit
8770          --  being instantiated. In that case, this body is not part of the
8771          --  current compilation, and is not attached to the tree, but its
8772          --  parent must be set for analysis.
8773
8774          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
8775
8776             --  Replace instance node with body of instance, and create new
8777             --  node for corresponding instance declaration.
8778
8779             Build_Instance_Compilation_Unit_Nodes
8780               (Inst_Node, Act_Body, Act_Decl);
8781             Analyze (Inst_Node);
8782
8783             if Parent (Inst_Node) = Cunit (Main_Unit) then
8784
8785                --  If the instance is a child unit itself, then set the scope
8786                --  of the expanded body to be the parent of the instantiation
8787                --  (ensuring that the fully qualified name will be generated
8788                --  for the elaboration subprogram).
8789
8790                if Nkind (Defining_Unit_Name (Act_Spec)) =
8791                                               N_Defining_Program_Unit_Name
8792                then
8793                   Set_Scope
8794                     (Defining_Entity (Inst_Node), Scope (Act_Decl_Id));
8795                end if;
8796             end if;
8797
8798          --  Case where instantiation is not a library unit
8799
8800          else
8801             --  If this is an early instantiation, i.e. appears textually
8802             --  before the corresponding body and must be elaborated first,
8803             --  indicate that the body instance is to be delayed.
8804
8805             Install_Body (Act_Body, Inst_Node, Gen_Body, Gen_Decl);
8806
8807             --  Now analyze the body. We turn off all checks if this is an
8808             --  internal unit, since there is no reason to have checks on for
8809             --  any predefined run-time library code. All such code is designed
8810             --  to be compiled with checks off.
8811
8812             --  Note that we do NOT apply this criterion to children of GNAT
8813             --  (or on VMS, children of DEC). The latter units must suppress
8814             --  checks explicitly if this is needed.
8815
8816             if Is_Predefined_File_Name
8817                  (Unit_File_Name (Get_Source_Unit (Gen_Decl)))
8818             then
8819                Analyze (Act_Body, Suppress => All_Checks);
8820             else
8821                Analyze (Act_Body);
8822             end if;
8823          end if;
8824
8825          Inherit_Context (Gen_Body, Inst_Node);
8826
8827          --  Remove the parent instances if they have been placed on the scope
8828          --  stack to compile the body.
8829
8830          if Parent_Installed then
8831             Remove_Parent (In_Body => True);
8832
8833             --  Restore the previous visibility of the parent
8834
8835             Set_Is_Immediately_Visible (Par_Ent, Par_Vis);
8836          end if;
8837
8838          Restore_Private_Views (Act_Decl_Id);
8839
8840          --  Remove the current unit from visibility if this is an instance
8841          --  that is not elaborated on the fly for inlining purposes.
8842
8843          if not Inlined_Body then
8844             Set_Is_Immediately_Visible (Act_Decl_Id, False);
8845          end if;
8846
8847          Restore_Env;
8848          Style_Check := Save_Style_Check;
8849
8850       --  If we have no body, and the unit requires a body, then complain. This
8851       --  complaint is suppressed if we have detected other errors (since a
8852       --  common reason for missing the body is that it had errors).
8853       --  In CodePeer mode, a warning has been emitted already, no need for
8854       --  further messages.
8855
8856       elsif Unit_Requires_Body (Gen_Unit)
8857         and then not Body_Optional
8858       then
8859          if CodePeer_Mode then
8860             null;
8861
8862          elsif Serious_Errors_Detected = 0 then
8863             Error_Msg_NE
8864               ("cannot find body of generic package &", Inst_Node, Gen_Unit);
8865
8866          --  Don't attempt to perform any cleanup actions if some other error
8867          --  was already detected, since this can cause blowups.
8868
8869          else
8870             return;
8871          end if;
8872
8873       --  Case of package that does not need a body
8874
8875       else
8876          --  If the instantiation of the declaration is a library unit, rewrite
8877          --  the original package instantiation as a package declaration in the
8878          --  compilation unit node.
8879
8880          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
8881             Set_Parent_Spec (Act_Decl, Parent_Spec (Inst_Node));
8882             Rewrite (Inst_Node, Act_Decl);
8883
8884             --  Generate elaboration entity, in case spec has elaboration code.
8885             --  This cannot be done when the instance is analyzed, because it
8886             --  is not known yet whether the body exists.
8887
8888             Set_Elaboration_Entity_Required (Act_Decl_Id, False);
8889             Build_Elaboration_Entity (Parent (Inst_Node), Act_Decl_Id);
8890
8891          --  If the instantiation is not a library unit, then append the
8892          --  declaration to the list of implicitly generated entities, unless
8893          --  it is already a list member which means that it was already
8894          --  processed
8895
8896          elsif not Is_List_Member (Act_Decl) then
8897             Mark_Rewrite_Insertion (Act_Decl);
8898             Insert_Before (Inst_Node, Act_Decl);
8899          end if;
8900       end if;
8901
8902       Expander_Mode_Restore;
8903    end Instantiate_Package_Body;
8904
8905    ---------------------------------
8906    -- Instantiate_Subprogram_Body --
8907    ---------------------------------
8908
8909    procedure Instantiate_Subprogram_Body
8910      (Body_Info     : Pending_Body_Info;
8911       Body_Optional : Boolean := False)
8912    is
8913       Act_Decl      : constant Node_Id    := Body_Info.Act_Decl;
8914       Inst_Node     : constant Node_Id    := Body_Info.Inst_Node;
8915       Loc           : constant Source_Ptr := Sloc (Inst_Node);
8916       Gen_Id        : constant Node_Id    := Name (Inst_Node);
8917       Gen_Unit      : constant Entity_Id  := Get_Generic_Entity (Inst_Node);
8918       Gen_Decl      : constant Node_Id    := Unit_Declaration_Node (Gen_Unit);
8919       Anon_Id       : constant Entity_Id  :=
8920                         Defining_Unit_Name (Specification (Act_Decl));
8921       Pack_Id       : constant Entity_Id  :=
8922                         Defining_Unit_Name (Parent (Act_Decl));
8923       Decls         : List_Id;
8924       Gen_Body      : Node_Id;
8925       Gen_Body_Id   : Node_Id;
8926       Act_Body      : Node_Id;
8927       Pack_Body     : Node_Id;
8928       Prev_Formal   : Entity_Id;
8929       Ret_Expr      : Node_Id;
8930       Unit_Renaming : Node_Id;
8931
8932       Parent_Installed : Boolean := False;
8933       Save_Style_Check : constant Boolean := Style_Check;
8934
8935       Par_Ent : Entity_Id := Empty;
8936       Par_Vis : Boolean   := False;
8937
8938    begin
8939       Gen_Body_Id := Corresponding_Body (Gen_Decl);
8940
8941       --  Subprogram body may have been created already because of an inline
8942       --  pragma, or because of multiple elaborations of the enclosing package
8943       --  when several instances of the subprogram appear in the main unit.
8944
8945       if Present (Corresponding_Body (Act_Decl)) then
8946          return;
8947       end if;
8948
8949       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
8950
8951       --  Re-establish the state of information on which checks are suppressed.
8952       --  This information was set in Body_Info at the point of instantiation,
8953       --  and now we restore it so that the instance is compiled using the
8954       --  check status at the instantiation (RM 11.5 (7.2/2), AI95-00224-01).
8955
8956       Local_Suppress_Stack_Top := Body_Info.Local_Suppress_Stack_Top;
8957       Scope_Suppress           := Body_Info.Scope_Suppress;
8958       Opt.Ada_Version          := Body_Info.Version;
8959
8960       if No (Gen_Body_Id) then
8961
8962          --  For imported generic subprogram, no body to compile, complete
8963          --  the spec entity appropriately.
8964
8965          if Is_Imported (Gen_Unit) then
8966             Set_Is_Imported (Anon_Id);
8967             Set_First_Rep_Item (Anon_Id, First_Rep_Item (Gen_Unit));
8968             Set_Interface_Name (Anon_Id, Interface_Name (Gen_Unit));
8969             Set_Convention     (Anon_Id, Convention     (Gen_Unit));
8970             Set_Has_Completion (Anon_Id);
8971             return;
8972
8973          --  For other cases, compile the body
8974
8975          else
8976             Load_Parent_Of_Generic
8977               (Inst_Node, Specification (Gen_Decl), Body_Optional);
8978             Gen_Body_Id := Corresponding_Body (Gen_Decl);
8979          end if;
8980       end if;
8981
8982       Instantiation_Node := Inst_Node;
8983
8984       if Present (Gen_Body_Id) then
8985          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
8986
8987          if Nkind (Gen_Body) = N_Subprogram_Body_Stub then
8988
8989             --  Either body is not present, or context is non-expanding, as
8990             --  when compiling a subunit. Mark the instance as completed, and
8991             --  diagnose a missing body when needed.
8992
8993             if Expander_Active
8994               and then Operating_Mode = Generate_Code
8995             then
8996                Error_Msg_N
8997                  ("missing proper body for instantiation", Gen_Body);
8998             end if;
8999
9000             Set_Has_Completion (Anon_Id);
9001             return;
9002          end if;
9003
9004          Save_Env (Gen_Unit, Anon_Id);
9005          Style_Check := False;
9006          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
9007          Create_Instantiation_Source
9008            (Inst_Node,
9009             Gen_Body_Id,
9010             False,
9011             S_Adjustment);
9012
9013          Act_Body :=
9014            Copy_Generic_Node
9015              (Original_Node (Gen_Body), Empty, Instantiating => True);
9016
9017          --  Create proper defining name for the body, to correspond to
9018          --  the one in the spec.
9019
9020          Set_Defining_Unit_Name (Specification (Act_Body),
9021            Make_Defining_Identifier
9022              (Sloc (Defining_Entity (Inst_Node)), Chars (Anon_Id)));
9023          Set_Corresponding_Spec (Act_Body, Anon_Id);
9024          Set_Has_Completion (Anon_Id);
9025          Check_Generic_Actuals (Pack_Id, False);
9026
9027          --  Generate a reference to link the visible subprogram instance to
9028          --  the generic body, which for navigation purposes is the only
9029          --  available source for the instance.
9030
9031          Generate_Reference
9032            (Related_Instance (Pack_Id),
9033              Gen_Body_Id, 'b', Set_Ref => False, Force => True);
9034
9035          --  If it is a child unit, make the parent instance (which is an
9036          --  instance of the parent of the generic) visible. The parent
9037          --  instance is the prefix of the name of the generic unit.
9038
9039          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
9040            and then Nkind (Gen_Id) = N_Expanded_Name
9041          then
9042             Par_Ent := Entity (Prefix (Gen_Id));
9043             Par_Vis := Is_Immediately_Visible (Par_Ent);
9044             Install_Parent (Par_Ent, In_Body => True);
9045             Parent_Installed := True;
9046
9047          elsif Is_Child_Unit (Gen_Unit) then
9048             Par_Ent := Scope (Gen_Unit);
9049             Par_Vis := Is_Immediately_Visible (Par_Ent);
9050             Install_Parent (Par_Ent, In_Body => True);
9051             Parent_Installed := True;
9052          end if;
9053
9054          --  Inside its body, a reference to the generic unit is a reference
9055          --  to the instance. The corresponding renaming is the first
9056          --  declaration in the body.
9057
9058          Unit_Renaming :=
9059            Make_Subprogram_Renaming_Declaration (Loc,
9060              Specification =>
9061                Copy_Generic_Node (
9062                  Specification (Original_Node (Gen_Body)),
9063                  Empty,
9064                  Instantiating => True),
9065              Name => New_Occurrence_Of (Anon_Id, Loc));
9066
9067          --  If there is a formal subprogram with the same name as the unit
9068          --  itself, do not add this renaming declaration. This is a temporary
9069          --  fix for one ACVC test. ???
9070
9071          Prev_Formal := First_Entity (Pack_Id);
9072          while Present (Prev_Formal) loop
9073             if Chars (Prev_Formal) = Chars (Gen_Unit)
9074               and then Is_Overloadable (Prev_Formal)
9075             then
9076                exit;
9077             end if;
9078
9079             Next_Entity (Prev_Formal);
9080          end loop;
9081
9082          if Present (Prev_Formal) then
9083             Decls :=  New_List (Act_Body);
9084          else
9085             Decls :=  New_List (Unit_Renaming, Act_Body);
9086          end if;
9087
9088          --  The subprogram body is placed in the body of a dummy package body,
9089          --  whose spec contains the subprogram declaration as well as the
9090          --  renaming declarations for the generic parameters.
9091
9092          Pack_Body := Make_Package_Body (Loc,
9093            Defining_Unit_Name => New_Copy (Pack_Id),
9094            Declarations       => Decls);
9095
9096          Set_Corresponding_Spec (Pack_Body, Pack_Id);
9097
9098          --  If the instantiation is a library unit, then build resulting
9099          --  compilation unit nodes for the instance. The declaration of
9100          --  the enclosing package is the grandparent of the subprogram
9101          --  declaration. First replace the instantiation node as the unit
9102          --  of the corresponding compilation.
9103
9104          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
9105             if Parent (Inst_Node) = Cunit (Main_Unit) then
9106                Set_Unit (Parent (Inst_Node), Inst_Node);
9107                Build_Instance_Compilation_Unit_Nodes
9108                  (Inst_Node, Pack_Body, Parent (Parent (Act_Decl)));
9109                Analyze (Inst_Node);
9110             else
9111                Set_Parent (Pack_Body, Parent (Inst_Node));
9112                Analyze (Pack_Body);
9113             end if;
9114
9115          else
9116             Insert_Before (Inst_Node, Pack_Body);
9117             Mark_Rewrite_Insertion (Pack_Body);
9118             Analyze (Pack_Body);
9119
9120             if Expander_Active then
9121                Freeze_Subprogram_Body (Inst_Node, Gen_Body, Pack_Id);
9122             end if;
9123          end if;
9124
9125          Inherit_Context (Gen_Body, Inst_Node);
9126
9127          Restore_Private_Views (Pack_Id, False);
9128
9129          if Parent_Installed then
9130             Remove_Parent (In_Body => True);
9131
9132             --  Restore the previous visibility of the parent
9133
9134             Set_Is_Immediately_Visible (Par_Ent, Par_Vis);
9135          end if;
9136
9137          Restore_Env;
9138          Style_Check := Save_Style_Check;
9139
9140       --  Body not found. Error was emitted already. If there were no previous
9141       --  errors, this may be an instance whose scope is a premature instance.
9142       --  In that case we must insure that the (legal) program does raise
9143       --  program error if executed. We generate a subprogram body for this
9144       --  purpose. See DEC ac30vso.
9145
9146       --  Should not reference proprietary DEC tests in comments ???
9147
9148       elsif Serious_Errors_Detected = 0
9149         and then Nkind (Parent (Inst_Node)) /= N_Compilation_Unit
9150       then
9151          if Body_Optional then
9152             return;
9153
9154          elsif Ekind (Anon_Id) = E_Procedure then
9155             Act_Body :=
9156               Make_Subprogram_Body (Loc,
9157                  Specification              =>
9158                    Make_Procedure_Specification (Loc,
9159                      Defining_Unit_Name         =>
9160                        Make_Defining_Identifier (Loc, Chars (Anon_Id)),
9161                        Parameter_Specifications =>
9162                        New_Copy_List
9163                          (Parameter_Specifications (Parent (Anon_Id)))),
9164
9165                  Declarations               => Empty_List,
9166                  Handled_Statement_Sequence =>
9167                    Make_Handled_Sequence_Of_Statements (Loc,
9168                      Statements =>
9169                        New_List (
9170                          Make_Raise_Program_Error (Loc,
9171                            Reason =>
9172                              PE_Access_Before_Elaboration))));
9173
9174          else
9175             Ret_Expr :=
9176               Make_Raise_Program_Error (Loc,
9177                 Reason => PE_Access_Before_Elaboration);
9178
9179             Set_Etype (Ret_Expr, (Etype (Anon_Id)));
9180             Set_Analyzed (Ret_Expr);
9181
9182             Act_Body :=
9183               Make_Subprogram_Body (Loc,
9184                 Specification =>
9185                   Make_Function_Specification (Loc,
9186                      Defining_Unit_Name         =>
9187                        Make_Defining_Identifier (Loc, Chars (Anon_Id)),
9188                        Parameter_Specifications =>
9189                        New_Copy_List
9190                          (Parameter_Specifications (Parent (Anon_Id))),
9191                      Result_Definition =>
9192                        New_Occurrence_Of (Etype (Anon_Id), Loc)),
9193
9194                   Declarations               => Empty_List,
9195                   Handled_Statement_Sequence =>
9196                     Make_Handled_Sequence_Of_Statements (Loc,
9197                       Statements =>
9198                         New_List
9199                           (Make_Simple_Return_Statement (Loc, Ret_Expr))));
9200          end if;
9201
9202          Pack_Body := Make_Package_Body (Loc,
9203            Defining_Unit_Name => New_Copy (Pack_Id),
9204            Declarations       => New_List (Act_Body));
9205
9206          Insert_After (Inst_Node, Pack_Body);
9207          Set_Corresponding_Spec (Pack_Body, Pack_Id);
9208          Analyze (Pack_Body);
9209       end if;
9210
9211       Expander_Mode_Restore;
9212    end Instantiate_Subprogram_Body;
9213
9214    ----------------------
9215    -- Instantiate_Type --
9216    ----------------------
9217
9218    function Instantiate_Type
9219      (Formal          : Node_Id;
9220       Actual          : Node_Id;
9221       Analyzed_Formal : Node_Id;
9222       Actual_Decls    : List_Id) return List_Id
9223    is
9224       Gen_T      : constant Entity_Id  := Defining_Identifier (Formal);
9225       A_Gen_T    : constant Entity_Id  :=
9226                      Defining_Identifier (Analyzed_Formal);
9227       Ancestor   : Entity_Id := Empty;
9228       Def        : constant Node_Id    := Formal_Type_Definition (Formal);
9229       Act_T      : Entity_Id;
9230       Decl_Node  : Node_Id;
9231       Decl_Nodes : List_Id;
9232       Loc        : Source_Ptr;
9233       Subt       : Entity_Id;
9234
9235       procedure Validate_Array_Type_Instance;
9236       procedure Validate_Access_Subprogram_Instance;
9237       procedure Validate_Access_Type_Instance;
9238       procedure Validate_Derived_Type_Instance;
9239       procedure Validate_Derived_Interface_Type_Instance;
9240       procedure Validate_Interface_Type_Instance;
9241       procedure Validate_Private_Type_Instance;
9242       --  These procedures perform validation tests for the named case
9243
9244       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean;
9245       --  Check that base types are the same and that the subtypes match
9246       --  statically. Used in several of the above.
9247
9248       --------------------
9249       -- Subtypes_Match --
9250       --------------------
9251
9252       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean is
9253          T : constant Entity_Id := Get_Instance_Of (Gen_T);
9254
9255       begin
9256          return (Base_Type (T) = Base_Type (Act_T)
9257                   and then Subtypes_Statically_Match (T, Act_T))
9258
9259            or else (Is_Class_Wide_Type (Gen_T)
9260                      and then Is_Class_Wide_Type (Act_T)
9261                      and then
9262                        Subtypes_Match
9263                         (Get_Instance_Of (Root_Type (Gen_T)),
9264                          Root_Type (Act_T)))
9265
9266            or else
9267              ((Ekind (Gen_T) = E_Anonymous_Access_Subprogram_Type
9268                  or else Ekind (Gen_T) = E_Anonymous_Access_Type)
9269                and then Ekind (Act_T) = Ekind (Gen_T)
9270                and then
9271                  Subtypes_Statically_Match
9272                    (Designated_Type (Gen_T), Designated_Type (Act_T)));
9273       end Subtypes_Match;
9274
9275       -----------------------------------------
9276       -- Validate_Access_Subprogram_Instance --
9277       -----------------------------------------
9278
9279       procedure Validate_Access_Subprogram_Instance is
9280       begin
9281          if not Is_Access_Type (Act_T)
9282            or else Ekind (Designated_Type (Act_T)) /= E_Subprogram_Type
9283          then
9284             Error_Msg_NE
9285               ("expect access type in instantiation of &", Actual, Gen_T);
9286             Abandon_Instantiation (Actual);
9287          end if;
9288
9289          Check_Mode_Conformant
9290            (Designated_Type (Act_T),
9291             Designated_Type (A_Gen_T),
9292             Actual,
9293             Get_Inst => True);
9294
9295          if Ekind (Base_Type (Act_T)) = E_Access_Protected_Subprogram_Type then
9296             if Ekind (A_Gen_T) = E_Access_Subprogram_Type then
9297                Error_Msg_NE
9298                  ("protected access type not allowed for formal &",
9299                   Actual, Gen_T);
9300             end if;
9301
9302          elsif Ekind (A_Gen_T) = E_Access_Protected_Subprogram_Type then
9303             Error_Msg_NE
9304               ("expect protected access type for formal &",
9305                Actual, Gen_T);
9306          end if;
9307       end Validate_Access_Subprogram_Instance;
9308
9309       -----------------------------------
9310       -- Validate_Access_Type_Instance --
9311       -----------------------------------
9312
9313       procedure Validate_Access_Type_Instance is
9314          Desig_Type : constant Entity_Id :=
9315                         Find_Actual_Type (Designated_Type (A_Gen_T), A_Gen_T);
9316          Desig_Act  : Entity_Id;
9317
9318       begin
9319          if not Is_Access_Type (Act_T) then
9320             Error_Msg_NE
9321               ("expect access type in instantiation of &", Actual, Gen_T);
9322             Abandon_Instantiation (Actual);
9323          end if;
9324
9325          if Is_Access_Constant (A_Gen_T) then
9326             if not Is_Access_Constant (Act_T) then
9327                Error_Msg_N
9328                  ("actual type must be access-to-constant type", Actual);
9329                Abandon_Instantiation (Actual);
9330             end if;
9331          else
9332             if Is_Access_Constant (Act_T) then
9333                Error_Msg_N
9334                  ("actual type must be access-to-variable type", Actual);
9335                Abandon_Instantiation (Actual);
9336
9337             elsif Ekind (A_Gen_T) = E_General_Access_Type
9338               and then Ekind (Base_Type (Act_T)) /= E_General_Access_Type
9339             then
9340                Error_Msg_N -- CODEFIX
9341                  ("actual must be general access type!", Actual);
9342                Error_Msg_NE -- CODEFIX
9343                  ("add ALL to }!", Actual, Act_T);
9344                Abandon_Instantiation (Actual);
9345             end if;
9346          end if;
9347
9348          --  The designated subtypes, that is to say the subtypes introduced
9349          --  by an access type declaration (and not by a subtype declaration)
9350          --  must match.
9351
9352          Desig_Act := Designated_Type (Base_Type (Act_T));
9353
9354          --  The designated type may have been introduced through a limited_
9355          --  with clause, in which case retrieve the non-limited view. This
9356          --  applies to incomplete types as well as to class-wide types.
9357
9358          if From_With_Type (Desig_Act) then
9359             Desig_Act := Available_View (Desig_Act);
9360          end if;
9361
9362          if not Subtypes_Match
9363            (Desig_Type, Desig_Act) then
9364             Error_Msg_NE
9365               ("designated type of actual does not match that of formal &",
9366                  Actual, Gen_T);
9367             Abandon_Instantiation (Actual);
9368
9369          elsif Is_Access_Type (Designated_Type (Act_T))
9370            and then Is_Constrained (Designated_Type (Designated_Type (Act_T)))
9371                       /=
9372                   Is_Constrained (Designated_Type (Desig_Type))
9373          then
9374             Error_Msg_NE
9375               ("designated type of actual does not match that of formal &",
9376                  Actual, Gen_T);
9377             Abandon_Instantiation (Actual);
9378          end if;
9379
9380          --  Ada 2005: null-exclusion indicators of the two types must agree
9381
9382          if Can_Never_Be_Null (A_Gen_T) /=  Can_Never_Be_Null (Act_T) then
9383             Error_Msg_NE
9384               ("non null exclusion of actual and formal & do not match",
9385                  Actual, Gen_T);
9386          end if;
9387       end Validate_Access_Type_Instance;
9388
9389       ----------------------------------
9390       -- Validate_Array_Type_Instance --
9391       ----------------------------------
9392
9393       procedure Validate_Array_Type_Instance is
9394          I1 : Node_Id;
9395          I2 : Node_Id;
9396          T2 : Entity_Id;
9397
9398          function Formal_Dimensions return Int;
9399          --  Count number of dimensions in array type formal
9400
9401          -----------------------
9402          -- Formal_Dimensions --
9403          -----------------------
9404
9405          function Formal_Dimensions return Int is
9406             Num   : Int := 0;
9407             Index : Node_Id;
9408
9409          begin
9410             if Nkind (Def) = N_Constrained_Array_Definition then
9411                Index := First (Discrete_Subtype_Definitions (Def));
9412             else
9413                Index := First (Subtype_Marks (Def));
9414             end if;
9415
9416             while Present (Index) loop
9417                Num := Num + 1;
9418                Next_Index (Index);
9419             end loop;
9420
9421             return Num;
9422          end Formal_Dimensions;
9423
9424       --  Start of processing for Validate_Array_Type_Instance
9425
9426       begin
9427          if not Is_Array_Type (Act_T) then
9428             Error_Msg_NE
9429               ("expect array type in instantiation of &", Actual, Gen_T);
9430             Abandon_Instantiation (Actual);
9431
9432          elsif Nkind (Def) = N_Constrained_Array_Definition then
9433             if not (Is_Constrained (Act_T)) then
9434                Error_Msg_NE
9435                  ("expect constrained array in instantiation of &",
9436                   Actual, Gen_T);
9437                Abandon_Instantiation (Actual);
9438             end if;
9439
9440          else
9441             if Is_Constrained (Act_T) then
9442                Error_Msg_NE
9443                  ("expect unconstrained array in instantiation of &",
9444                   Actual, Gen_T);
9445                Abandon_Instantiation (Actual);
9446             end if;
9447          end if;
9448
9449          if Formal_Dimensions /= Number_Dimensions (Act_T) then
9450             Error_Msg_NE
9451               ("dimensions of actual do not match formal &", Actual, Gen_T);
9452             Abandon_Instantiation (Actual);
9453          end if;
9454
9455          I1 := First_Index (A_Gen_T);
9456          I2 := First_Index (Act_T);
9457          for J in 1 .. Formal_Dimensions loop
9458
9459             --  If the indexes of the actual were given by a subtype_mark,
9460             --  the index was transformed into a range attribute. Retrieve
9461             --  the original type mark for checking.
9462
9463             if Is_Entity_Name (Original_Node (I2)) then
9464                T2 := Entity (Original_Node (I2));
9465             else
9466                T2 := Etype (I2);
9467             end if;
9468
9469             if not Subtypes_Match
9470                      (Find_Actual_Type (Etype (I1), A_Gen_T), T2)
9471             then
9472                Error_Msg_NE
9473                  ("index types of actual do not match those of formal &",
9474                   Actual, Gen_T);
9475                Abandon_Instantiation (Actual);
9476             end if;
9477
9478             Next_Index (I1);
9479             Next_Index (I2);
9480          end loop;
9481
9482          --  Check matching subtypes. Note that there are complex visibility
9483          --  issues when the generic is a child unit and some aspect of the
9484          --  generic type is declared in a parent unit of the generic. We do
9485          --  the test to handle this special case only after a direct check
9486          --  for static matching has failed.
9487
9488          if Subtypes_Match
9489            (Component_Type (A_Gen_T), Component_Type (Act_T))
9490              or else Subtypes_Match
9491                       (Find_Actual_Type (Component_Type (A_Gen_T), A_Gen_T),
9492                        Component_Type (Act_T))
9493          then
9494             null;
9495          else
9496             Error_Msg_NE
9497               ("component subtype of actual does not match that of formal &",
9498                Actual, Gen_T);
9499             Abandon_Instantiation (Actual);
9500          end if;
9501
9502          if Has_Aliased_Components (A_Gen_T)
9503            and then not Has_Aliased_Components (Act_T)
9504          then
9505             Error_Msg_NE
9506               ("actual must have aliased components to match formal type &",
9507                Actual, Gen_T);
9508          end if;
9509       end Validate_Array_Type_Instance;
9510
9511       -----------------------------------------------
9512       --  Validate_Derived_Interface_Type_Instance --
9513       -----------------------------------------------
9514
9515       procedure Validate_Derived_Interface_Type_Instance is
9516          Par  : constant Entity_Id := Entity (Subtype_Indication (Def));
9517          Elmt : Elmt_Id;
9518
9519       begin
9520          --  First apply interface instance checks
9521
9522          Validate_Interface_Type_Instance;
9523
9524          --  Verify that immediate parent interface is an ancestor of
9525          --  the actual.
9526
9527          if Present (Par)
9528            and then not Interface_Present_In_Ancestor (Act_T, Par)
9529          then
9530             Error_Msg_NE
9531               ("interface actual must include progenitor&", Actual, Par);
9532          end if;
9533
9534          --  Now verify that the actual includes all other ancestors of
9535          --  the formal.
9536
9537          Elmt := First_Elmt (Interfaces (A_Gen_T));
9538          while Present (Elmt) loop
9539             if not Interface_Present_In_Ancestor
9540                      (Act_T, Get_Instance_Of (Node (Elmt)))
9541             then
9542                Error_Msg_NE
9543                  ("interface actual must include progenitor&",
9544                     Actual, Node (Elmt));
9545             end if;
9546
9547             Next_Elmt (Elmt);
9548          end loop;
9549       end Validate_Derived_Interface_Type_Instance;
9550
9551       ------------------------------------
9552       -- Validate_Derived_Type_Instance --
9553       ------------------------------------
9554
9555       procedure Validate_Derived_Type_Instance is
9556          Actual_Discr   : Entity_Id;
9557          Ancestor_Discr : Entity_Id;
9558
9559       begin
9560          --  If the parent type in the generic declaration is itself a previous
9561          --  formal type, then it is local to the generic and absent from the
9562          --  analyzed generic definition. In that case the ancestor is the
9563          --  instance of the formal (which must have been instantiated
9564          --  previously), unless the ancestor is itself a formal derived type.
9565          --  In this latter case (which is the subject of Corrigendum 8652/0038
9566          --  (AI-202) the ancestor of the formals is the ancestor of its
9567          --  parent. Otherwise, the analyzed generic carries the parent type.
9568          --  If the parent type is defined in a previous formal package, then
9569          --  the scope of that formal package is that of the generic type
9570          --  itself, and it has already been mapped into the corresponding type
9571          --  in the actual package.
9572
9573          --  Common case: parent type defined outside of the generic
9574
9575          if Is_Entity_Name (Subtype_Mark (Def))
9576            and then Present (Entity (Subtype_Mark (Def)))
9577          then
9578             Ancestor := Get_Instance_Of (Entity (Subtype_Mark (Def)));
9579
9580          --  Check whether parent is defined in a previous formal package
9581
9582          elsif
9583            Scope (Scope (Base_Type (Etype (A_Gen_T)))) = Scope (A_Gen_T)
9584          then
9585             Ancestor :=
9586               Get_Instance_Of (Base_Type (Etype (A_Gen_T)));
9587
9588          --  The type may be a local derivation, or a type extension of a
9589          --  previous formal, or of a formal of a parent package.
9590
9591          elsif Is_Derived_Type (Get_Instance_Of (A_Gen_T))
9592           or else
9593             Ekind (Get_Instance_Of (A_Gen_T)) = E_Record_Type_With_Private
9594          then
9595             --  Check whether the parent is another derived formal type in the
9596             --  same generic unit.
9597
9598             if Etype (A_Gen_T) /= A_Gen_T
9599               and then Is_Generic_Type (Etype (A_Gen_T))
9600               and then Scope (Etype (A_Gen_T)) = Scope (A_Gen_T)
9601               and then Etype (Etype (A_Gen_T)) /= Etype (A_Gen_T)
9602             then
9603                --  Locate ancestor of parent from the subtype declaration
9604                --  created for the actual.
9605
9606                declare
9607                   Decl : Node_Id;
9608
9609                begin
9610                   Decl := First (Actual_Decls);
9611                   while Present (Decl) loop
9612                      if Nkind (Decl) = N_Subtype_Declaration
9613                        and then Chars (Defining_Identifier (Decl)) =
9614                                                     Chars (Etype (A_Gen_T))
9615                      then
9616                         Ancestor := Generic_Parent_Type (Decl);
9617                         exit;
9618                      else
9619                         Next (Decl);
9620                      end if;
9621                   end loop;
9622                end;
9623
9624                pragma Assert (Present (Ancestor));
9625
9626             else
9627                Ancestor :=
9628                  Get_Instance_Of (Base_Type (Get_Instance_Of (A_Gen_T)));
9629             end if;
9630
9631          else
9632             Ancestor := Get_Instance_Of (Etype (Base_Type (A_Gen_T)));
9633          end if;
9634
9635          --  If the formal derived type has pragma Preelaborable_Initialization
9636          --  then the actual type must have preelaborable initialization.
9637
9638          if Known_To_Have_Preelab_Init (A_Gen_T)
9639            and then not Has_Preelaborable_Initialization (Act_T)
9640          then
9641             Error_Msg_NE
9642               ("actual for & must have preelaborable initialization",
9643                Actual, Gen_T);
9644          end if;
9645
9646          --  Ada 2005 (AI-251)
9647
9648          if Ada_Version >= Ada_2005
9649            and then Is_Interface (Ancestor)
9650          then
9651             if not Interface_Present_In_Ancestor (Act_T, Ancestor) then
9652                Error_Msg_NE
9653                  ("(Ada 2005) expected type implementing & in instantiation",
9654                   Actual, Ancestor);
9655             end if;
9656
9657          elsif not Is_Ancestor (Base_Type (Ancestor), Act_T) then
9658             Error_Msg_NE
9659               ("expect type derived from & in instantiation",
9660                Actual, First_Subtype (Ancestor));
9661             Abandon_Instantiation (Actual);
9662          end if;
9663
9664          --  Ada 2005 (AI-443): Synchronized formal derived type checks. Note
9665          --  that the formal type declaration has been rewritten as a private
9666          --  extension.
9667
9668          if Ada_Version >= Ada_2005
9669            and then Nkind (Parent (A_Gen_T)) = N_Private_Extension_Declaration
9670            and then Synchronized_Present (Parent (A_Gen_T))
9671          then
9672             --  The actual must be a synchronized tagged type
9673
9674             if not Is_Tagged_Type (Act_T) then
9675                Error_Msg_N
9676                  ("actual of synchronized type must be tagged", Actual);
9677                Abandon_Instantiation (Actual);
9678
9679             elsif Nkind (Parent (Act_T)) = N_Full_Type_Declaration
9680               and then Nkind (Type_Definition (Parent (Act_T))) =
9681                          N_Derived_Type_Definition
9682               and then not Synchronized_Present (Type_Definition
9683                              (Parent (Act_T)))
9684             then
9685                Error_Msg_N
9686                  ("actual of synchronized type must be synchronized", Actual);
9687                Abandon_Instantiation (Actual);
9688             end if;
9689          end if;
9690
9691          --  Perform atomic/volatile checks (RM C.6(12))
9692
9693          if Is_Atomic (Act_T) and then not Is_Atomic (Ancestor) then
9694             Error_Msg_N
9695               ("cannot have atomic actual type for non-atomic formal type",
9696                Actual);
9697
9698          elsif Is_Volatile (Act_T)
9699            and then not Is_Volatile (Ancestor)
9700            and then Is_By_Reference_Type (Ancestor)
9701          then
9702             Error_Msg_N
9703               ("cannot have volatile actual type for non-volatile formal type",
9704                Actual);
9705          end if;
9706
9707          --  It should not be necessary to check for unknown discriminants on
9708          --  Formal, but for some reason Has_Unknown_Discriminants is false for
9709          --  A_Gen_T, so Is_Indefinite_Subtype incorrectly returns False. This
9710          --  needs fixing. ???
9711
9712          if not Is_Indefinite_Subtype (A_Gen_T)
9713            and then not Unknown_Discriminants_Present (Formal)
9714            and then Is_Indefinite_Subtype (Act_T)
9715          then
9716             Error_Msg_N
9717               ("actual subtype must be constrained", Actual);
9718             Abandon_Instantiation (Actual);
9719          end if;
9720
9721          if not Unknown_Discriminants_Present (Formal) then
9722             if Is_Constrained (Ancestor) then
9723                if not Is_Constrained (Act_T) then
9724                   Error_Msg_N
9725                     ("actual subtype must be constrained", Actual);
9726                   Abandon_Instantiation (Actual);
9727                end if;
9728
9729             --  Ancestor is unconstrained, Check if generic formal and actual
9730             --  agree on constrainedness. The check only applies to array types
9731             --  and discriminated types.
9732
9733             elsif Is_Constrained (Act_T) then
9734                if Ekind (Ancestor) = E_Access_Type
9735                  or else
9736                    (not Is_Constrained (A_Gen_T)
9737                      and then Is_Composite_Type (A_Gen_T))
9738                then
9739                   Error_Msg_N
9740                     ("actual subtype must be unconstrained", Actual);
9741                   Abandon_Instantiation (Actual);
9742                end if;
9743
9744             --  A class-wide type is only allowed if the formal has unknown
9745             --  discriminants.
9746
9747             elsif Is_Class_Wide_Type (Act_T)
9748               and then not Has_Unknown_Discriminants (Ancestor)
9749             then
9750                Error_Msg_NE
9751                  ("actual for & cannot be a class-wide type", Actual, Gen_T);
9752                Abandon_Instantiation (Actual);
9753
9754             --  Otherwise, the formal and actual shall have the same number
9755             --  of discriminants and each discriminant of the actual must
9756             --  correspond to a discriminant of the formal.
9757
9758             elsif Has_Discriminants (Act_T)
9759               and then not Has_Unknown_Discriminants (Act_T)
9760               and then Has_Discriminants (Ancestor)
9761             then
9762                Actual_Discr   := First_Discriminant (Act_T);
9763                Ancestor_Discr := First_Discriminant (Ancestor);
9764                while Present (Actual_Discr)
9765                  and then Present (Ancestor_Discr)
9766                loop
9767                   if Base_Type (Act_T) /= Base_Type (Ancestor) and then
9768                     No (Corresponding_Discriminant (Actual_Discr))
9769                   then
9770                      Error_Msg_NE
9771                        ("discriminant & does not correspond " &
9772                         "to ancestor discriminant", Actual, Actual_Discr);
9773                      Abandon_Instantiation (Actual);
9774                   end if;
9775
9776                   Next_Discriminant (Actual_Discr);
9777                   Next_Discriminant (Ancestor_Discr);
9778                end loop;
9779
9780                if Present (Actual_Discr) or else Present (Ancestor_Discr) then
9781                   Error_Msg_NE
9782                     ("actual for & must have same number of discriminants",
9783                      Actual, Gen_T);
9784                   Abandon_Instantiation (Actual);
9785                end if;
9786
9787             --  This case should be caught by the earlier check for
9788             --  constrainedness, but the check here is added for completeness.
9789
9790             elsif Has_Discriminants (Act_T)
9791               and then not Has_Unknown_Discriminants (Act_T)
9792             then
9793                Error_Msg_NE
9794                  ("actual for & must not have discriminants", Actual, Gen_T);
9795                Abandon_Instantiation (Actual);
9796
9797             elsif Has_Discriminants (Ancestor) then
9798                Error_Msg_NE
9799                  ("actual for & must have known discriminants", Actual, Gen_T);
9800                Abandon_Instantiation (Actual);
9801             end if;
9802
9803             if not Subtypes_Statically_Compatible (Act_T, Ancestor) then
9804                Error_Msg_N
9805                  ("constraint on actual is incompatible with formal", Actual);
9806                Abandon_Instantiation (Actual);
9807             end if;
9808          end if;
9809
9810          --  If the formal and actual types are abstract, check that there
9811          --  are no abstract primitives of the actual type that correspond to
9812          --  nonabstract primitives of the formal type (second sentence of
9813          --  RM95-3.9.3(9)).
9814
9815          if Is_Abstract_Type (A_Gen_T) and then Is_Abstract_Type (Act_T) then
9816             Check_Abstract_Primitives : declare
9817                Gen_Prims  : constant Elist_Id :=
9818                              Primitive_Operations (A_Gen_T);
9819                Gen_Elmt   : Elmt_Id;
9820                Gen_Subp   : Entity_Id;
9821                Anc_Subp   : Entity_Id;
9822                Anc_Formal : Entity_Id;
9823                Anc_F_Type : Entity_Id;
9824
9825                Act_Prims  : constant Elist_Id  := Primitive_Operations (Act_T);
9826                Act_Elmt   : Elmt_Id;
9827                Act_Subp   : Entity_Id;
9828                Act_Formal : Entity_Id;
9829                Act_F_Type : Entity_Id;
9830
9831                Subprograms_Correspond : Boolean;
9832
9833                function Is_Tagged_Ancestor (T1, T2 : Entity_Id) return Boolean;
9834                --  Returns true if T2 is derived directly or indirectly from
9835                --  T1, including derivations from interfaces. T1 and T2 are
9836                --  required to be specific tagged base types.
9837
9838                ------------------------
9839                -- Is_Tagged_Ancestor --
9840                ------------------------
9841
9842                function Is_Tagged_Ancestor (T1, T2 : Entity_Id) return Boolean
9843                is
9844                   Intfc_Elmt : Elmt_Id;
9845
9846                begin
9847                   --  The predicate is satisfied if the types are the same
9848
9849                   if T1 = T2 then
9850                      return True;
9851
9852                   --  If we've reached the top of the derivation chain then
9853                   --  we know that T1 is not an ancestor of T2.
9854
9855                   elsif Etype (T2) = T2 then
9856                      return False;
9857
9858                   --  Proceed to check T2's immediate parent
9859
9860                   elsif Is_Ancestor (T1, Base_Type (Etype (T2))) then
9861                      return True;
9862
9863                   --  Finally, check to see if T1 is an ancestor of any of T2's
9864                   --  progenitors.
9865
9866                   else
9867                      Intfc_Elmt := First_Elmt (Interfaces (T2));
9868                      while Present (Intfc_Elmt) loop
9869                         if Is_Ancestor (T1, Node (Intfc_Elmt)) then
9870                            return True;
9871                         end if;
9872
9873                         Next_Elmt (Intfc_Elmt);
9874                      end loop;
9875                   end if;
9876
9877                   return False;
9878                end Is_Tagged_Ancestor;
9879
9880             --  Start of processing for Check_Abstract_Primitives
9881
9882             begin
9883                --  Loop over all of the formal derived type's primitives
9884
9885                Gen_Elmt := First_Elmt (Gen_Prims);
9886                while Present (Gen_Elmt) loop
9887                   Gen_Subp := Node (Gen_Elmt);
9888
9889                   --  If the primitive of the formal is not abstract, then
9890                   --  determine whether there is a corresponding primitive of
9891                   --  the actual type that's abstract.
9892
9893                   if not Is_Abstract_Subprogram (Gen_Subp) then
9894                      Act_Elmt := First_Elmt (Act_Prims);
9895                      while Present (Act_Elmt) loop
9896                         Act_Subp := Node (Act_Elmt);
9897
9898                         --  If we find an abstract primitive of the actual,
9899                         --  then we need to test whether it corresponds to the
9900                         --  subprogram from which the generic formal primitive
9901                         --  is inherited.
9902
9903                         if Is_Abstract_Subprogram (Act_Subp) then
9904                            Anc_Subp := Alias (Gen_Subp);
9905
9906                            --  Test whether we have a corresponding primitive
9907                            --  by comparing names, kinds, formal types, and
9908                            --  result types.
9909
9910                            if Chars (Anc_Subp) = Chars (Act_Subp)
9911                              and then Ekind (Anc_Subp) = Ekind (Act_Subp)
9912                            then
9913                               Anc_Formal := First_Formal (Anc_Subp);
9914                               Act_Formal := First_Formal (Act_Subp);
9915                               while Present (Anc_Formal)
9916                                 and then Present (Act_Formal)
9917                               loop
9918                                  Anc_F_Type := Etype (Anc_Formal);
9919                                  Act_F_Type := Etype (Act_Formal);
9920
9921                                  if Ekind (Anc_F_Type)
9922                                       = E_Anonymous_Access_Type
9923                                  then
9924                                     Anc_F_Type := Designated_Type (Anc_F_Type);
9925
9926                                     if Ekind (Act_F_Type)
9927                                          = E_Anonymous_Access_Type
9928                                     then
9929                                        Act_F_Type :=
9930                                          Designated_Type (Act_F_Type);
9931                                     else
9932                                        exit;
9933                                     end if;
9934
9935                                  elsif
9936                                    Ekind (Act_F_Type) = E_Anonymous_Access_Type
9937                                  then
9938                                     exit;
9939                                  end if;
9940
9941                                  Anc_F_Type := Base_Type (Anc_F_Type);
9942                                  Act_F_Type := Base_Type (Act_F_Type);
9943
9944                                  --  If the formal is controlling, then the
9945                                  --  the type of the actual primitive's formal
9946                                  --  must be derived directly or indirectly
9947                                  --  from the type of the ancestor primitive's
9948                                  --  formal.
9949
9950                                  if Is_Controlling_Formal (Anc_Formal) then
9951                                     if not Is_Tagged_Ancestor
9952                                              (Anc_F_Type, Act_F_Type)
9953                                     then
9954                                        exit;
9955                                     end if;
9956
9957                                  --  Otherwise the types of the formals must
9958                                  --  be the same.
9959
9960                                  elsif Anc_F_Type /= Act_F_Type then
9961                                     exit;
9962                                  end if;
9963
9964                                  Next_Entity (Anc_Formal);
9965                                  Next_Entity (Act_Formal);
9966                               end loop;
9967
9968                               --  If we traversed through all of the formals
9969                               --  then so far the subprograms correspond, so
9970                               --  now check that any result types correspond.
9971
9972                               if No (Anc_Formal) and then No (Act_Formal) then
9973                                  Subprograms_Correspond := True;
9974
9975                                  if Ekind (Act_Subp) = E_Function then
9976                                     Anc_F_Type := Etype (Anc_Subp);
9977                                     Act_F_Type := Etype (Act_Subp);
9978
9979                                     if Ekind (Anc_F_Type)
9980                                          = E_Anonymous_Access_Type
9981                                     then
9982                                        Anc_F_Type :=
9983                                          Designated_Type (Anc_F_Type);
9984
9985                                        if Ekind (Act_F_Type)
9986                                             = E_Anonymous_Access_Type
9987                                        then
9988                                           Act_F_Type :=
9989                                             Designated_Type (Act_F_Type);
9990                                        else
9991                                           Subprograms_Correspond := False;
9992                                        end if;
9993
9994                                     elsif
9995                                       Ekind (Act_F_Type)
9996                                         = E_Anonymous_Access_Type
9997                                     then
9998                                        Subprograms_Correspond := False;
9999                                     end if;
10000
10001                                     Anc_F_Type := Base_Type (Anc_F_Type);
10002                                     Act_F_Type := Base_Type (Act_F_Type);
10003
10004                                     --  Now either the result types must be
10005                                     --  the same or, if the result type is
10006                                     --  controlling, the result type of the
10007                                     --  actual primitive must descend from the
10008                                     --  result type of the ancestor primitive.
10009
10010                                     if Subprograms_Correspond
10011                                       and then Anc_F_Type /= Act_F_Type
10012                                       and then
10013                                         Has_Controlling_Result (Anc_Subp)
10014                                       and then
10015                                         not Is_Tagged_Ancestor
10016                                               (Anc_F_Type, Act_F_Type)
10017                                     then
10018                                        Subprograms_Correspond := False;
10019                                     end if;
10020                                  end if;
10021
10022                                  --  Found a matching subprogram belonging to
10023                                  --  formal ancestor type, so actual subprogram
10024                                  --  corresponds and this violates 3.9.3(9).
10025
10026                                  if Subprograms_Correspond then
10027                                     Error_Msg_NE
10028                                       ("abstract subprogram & overrides " &
10029                                        "nonabstract subprogram of ancestor",
10030                                        Actual,
10031                                        Act_Subp);
10032                                  end if;
10033                               end if;
10034                            end if;
10035                         end if;
10036
10037                         Next_Elmt (Act_Elmt);
10038                      end loop;
10039                   end if;
10040
10041                   Next_Elmt (Gen_Elmt);
10042                end loop;
10043             end Check_Abstract_Primitives;
10044          end if;
10045
10046          --  Verify that limitedness matches. If parent is a limited
10047          --  interface then  the generic formal is not unless declared
10048          --  explicitly so. If not declared limited, the actual cannot be
10049          --  limited (see AI05-0087).
10050
10051          --  Even though this AI is a binding interpretation, we enable the
10052          --  check only in Ada 2012 mode, because this improper construct
10053          --  shows up in user code and in existing B-tests.
10054
10055          if Is_Limited_Type (Act_T)
10056            and then not Is_Limited_Type (A_Gen_T)
10057            and then Ada_Version >= Ada_2012
10058          then
10059             Error_Msg_NE
10060               ("actual for non-limited & cannot be a limited type", Actual,
10061                Gen_T);
10062             Explain_Limited_Type (Act_T, Actual);
10063             Abandon_Instantiation (Actual);
10064          end if;
10065       end Validate_Derived_Type_Instance;
10066
10067       --------------------------------------
10068       -- Validate_Interface_Type_Instance --
10069       --------------------------------------
10070
10071       procedure Validate_Interface_Type_Instance is
10072       begin
10073          if not Is_Interface (Act_T) then
10074             Error_Msg_NE
10075               ("actual for formal interface type must be an interface",
10076                 Actual, Gen_T);
10077
10078          elsif Is_Limited_Type (Act_T) /= Is_Limited_Type (A_Gen_T)
10079            or else
10080              Is_Task_Interface (A_Gen_T) /= Is_Task_Interface (Act_T)
10081            or else
10082              Is_Protected_Interface (A_Gen_T) /=
10083                Is_Protected_Interface (Act_T)
10084            or else
10085              Is_Synchronized_Interface (A_Gen_T) /=
10086                Is_Synchronized_Interface (Act_T)
10087          then
10088             Error_Msg_NE
10089               ("actual for interface& does not match (RM 12.5.5(4))",
10090                Actual, Gen_T);
10091          end if;
10092       end Validate_Interface_Type_Instance;
10093
10094       ------------------------------------
10095       -- Validate_Private_Type_Instance --
10096       ------------------------------------
10097
10098       procedure Validate_Private_Type_Instance is
10099          Formal_Discr : Entity_Id;
10100          Actual_Discr : Entity_Id;
10101          Formal_Subt  : Entity_Id;
10102
10103       begin
10104          if Is_Limited_Type (Act_T)
10105            and then not Is_Limited_Type (A_Gen_T)
10106          then
10107             Error_Msg_NE
10108               ("actual for non-limited & cannot be a limited type", Actual,
10109                Gen_T);
10110             Explain_Limited_Type (Act_T, Actual);
10111             Abandon_Instantiation (Actual);
10112
10113          elsif Known_To_Have_Preelab_Init (A_Gen_T)
10114            and then not Has_Preelaborable_Initialization (Act_T)
10115          then
10116             Error_Msg_NE
10117               ("actual for & must have preelaborable initialization", Actual,
10118                Gen_T);
10119
10120          elsif Is_Indefinite_Subtype (Act_T)
10121             and then not Is_Indefinite_Subtype (A_Gen_T)
10122             and then Ada_Version >= Ada_95
10123          then
10124             Error_Msg_NE
10125               ("actual for & must be a definite subtype", Actual, Gen_T);
10126
10127          elsif not Is_Tagged_Type (Act_T)
10128            and then Is_Tagged_Type (A_Gen_T)
10129          then
10130             Error_Msg_NE
10131               ("actual for & must be a tagged type", Actual, Gen_T);
10132
10133          elsif Has_Discriminants (A_Gen_T) then
10134             if not Has_Discriminants (Act_T) then
10135                Error_Msg_NE
10136                  ("actual for & must have discriminants", Actual, Gen_T);
10137                Abandon_Instantiation (Actual);
10138
10139             elsif Is_Constrained (Act_T) then
10140                Error_Msg_NE
10141                  ("actual for & must be unconstrained", Actual, Gen_T);
10142                Abandon_Instantiation (Actual);
10143
10144             else
10145                Formal_Discr := First_Discriminant (A_Gen_T);
10146                Actual_Discr := First_Discriminant (Act_T);
10147                while Formal_Discr /= Empty loop
10148                   if Actual_Discr = Empty then
10149                      Error_Msg_NE
10150                        ("discriminants on actual do not match formal",
10151                         Actual, Gen_T);
10152                      Abandon_Instantiation (Actual);
10153                   end if;
10154
10155                   Formal_Subt := Get_Instance_Of (Etype (Formal_Discr));
10156
10157                   --  Access discriminants match if designated types do
10158
10159                   if Ekind (Base_Type (Formal_Subt)) = E_Anonymous_Access_Type
10160                     and then (Ekind (Base_Type (Etype (Actual_Discr)))) =
10161                                 E_Anonymous_Access_Type
10162                     and then
10163                       Get_Instance_Of
10164                         (Designated_Type (Base_Type (Formal_Subt))) =
10165                            Designated_Type (Base_Type (Etype (Actual_Discr)))
10166                   then
10167                      null;
10168
10169                   elsif Base_Type (Formal_Subt) /=
10170                           Base_Type (Etype (Actual_Discr))
10171                   then
10172                      Error_Msg_NE
10173                        ("types of actual discriminants must match formal",
10174                         Actual, Gen_T);
10175                      Abandon_Instantiation (Actual);
10176
10177                   elsif not Subtypes_Statically_Match
10178                               (Formal_Subt, Etype (Actual_Discr))
10179                     and then Ada_Version >= Ada_95
10180                   then
10181                      Error_Msg_NE
10182                        ("subtypes of actual discriminants must match formal",
10183                         Actual, Gen_T);
10184                      Abandon_Instantiation (Actual);
10185                   end if;
10186
10187                   Next_Discriminant (Formal_Discr);
10188                   Next_Discriminant (Actual_Discr);
10189                end loop;
10190
10191                if Actual_Discr /= Empty then
10192                   Error_Msg_NE
10193                     ("discriminants on actual do not match formal",
10194                      Actual, Gen_T);
10195                   Abandon_Instantiation (Actual);
10196                end if;
10197             end if;
10198
10199          end if;
10200
10201          Ancestor := Gen_T;
10202       end Validate_Private_Type_Instance;
10203
10204    --  Start of processing for Instantiate_Type
10205
10206    begin
10207       if Get_Instance_Of (A_Gen_T) /= A_Gen_T then
10208          Error_Msg_N ("duplicate instantiation of generic type", Actual);
10209          return New_List (Error);
10210
10211       elsif not Is_Entity_Name (Actual)
10212         or else not Is_Type (Entity (Actual))
10213       then
10214          Error_Msg_NE
10215            ("expect valid subtype mark to instantiate &", Actual, Gen_T);
10216          Abandon_Instantiation (Actual);
10217
10218       else
10219          Act_T := Entity (Actual);
10220
10221          --  Ada 2005 (AI-216): An Unchecked_Union subtype shall only be passed
10222          --  as a generic actual parameter if the corresponding formal type
10223          --  does not have a known_discriminant_part, or is a formal derived
10224          --  type that is an Unchecked_Union type.
10225
10226          if Is_Unchecked_Union (Base_Type (Act_T)) then
10227             if not Has_Discriminants (A_Gen_T)
10228                      or else
10229                    (Is_Derived_Type (A_Gen_T)
10230                      and then
10231                     Is_Unchecked_Union (A_Gen_T))
10232             then
10233                null;
10234             else
10235                Error_Msg_N ("Unchecked_Union cannot be the actual for a" &
10236                  " discriminated formal type", Act_T);
10237
10238             end if;
10239          end if;
10240
10241          --  Deal with fixed/floating restrictions
10242
10243          if Is_Floating_Point_Type (Act_T) then
10244             Check_Restriction (No_Floating_Point, Actual);
10245          elsif Is_Fixed_Point_Type (Act_T) then
10246             Check_Restriction (No_Fixed_Point, Actual);
10247          end if;
10248
10249          --  Deal with error of using incomplete type as generic actual.
10250          --  This includes limited views of a type, even if the non-limited
10251          --  view may be available.
10252
10253          if Ekind (Act_T) = E_Incomplete_Type
10254            or else (Is_Class_Wide_Type (Act_T)
10255                       and then
10256                          Ekind (Root_Type (Act_T)) = E_Incomplete_Type)
10257          then
10258             if Is_Class_Wide_Type (Act_T)
10259               or else No (Full_View (Act_T))
10260             then
10261                Error_Msg_N ("premature use of incomplete type", Actual);
10262                Abandon_Instantiation (Actual);
10263             else
10264                Act_T := Full_View (Act_T);
10265                Set_Entity (Actual, Act_T);
10266
10267                if Has_Private_Component (Act_T) then
10268                   Error_Msg_N
10269                     ("premature use of type with private component", Actual);
10270                end if;
10271             end if;
10272
10273          --  Deal with error of premature use of private type as generic actual
10274
10275          elsif Is_Private_Type (Act_T)
10276            and then Is_Private_Type (Base_Type (Act_T))
10277            and then not Is_Generic_Type (Act_T)
10278            and then not Is_Derived_Type (Act_T)
10279            and then No (Full_View (Root_Type (Act_T)))
10280          then
10281             Error_Msg_N ("premature use of private type", Actual);
10282
10283          elsif Has_Private_Component (Act_T) then
10284             Error_Msg_N
10285               ("premature use of type with private component", Actual);
10286          end if;
10287
10288          Set_Instance_Of (A_Gen_T, Act_T);
10289
10290          --  If the type is generic, the class-wide type may also be used
10291
10292          if Is_Tagged_Type (A_Gen_T)
10293            and then Is_Tagged_Type (Act_T)
10294            and then not Is_Class_Wide_Type (A_Gen_T)
10295          then
10296             Set_Instance_Of (Class_Wide_Type (A_Gen_T),
10297               Class_Wide_Type (Act_T));
10298          end if;
10299
10300          if not Is_Abstract_Type (A_Gen_T)
10301            and then Is_Abstract_Type (Act_T)
10302          then
10303             Error_Msg_N
10304               ("actual of non-abstract formal cannot be abstract", Actual);
10305          end if;
10306
10307          --  A generic scalar type is a first subtype for which we generate
10308          --  an anonymous base type. Indicate that the instance of this base
10309          --  is the base type of the actual.
10310
10311          if Is_Scalar_Type (A_Gen_T) then
10312             Set_Instance_Of (Etype (A_Gen_T), Etype (Act_T));
10313          end if;
10314       end if;
10315
10316       if Error_Posted (Act_T) then
10317          null;
10318       else
10319          case Nkind (Def) is
10320             when N_Formal_Private_Type_Definition =>
10321                Validate_Private_Type_Instance;
10322
10323             when N_Formal_Derived_Type_Definition =>
10324                Validate_Derived_Type_Instance;
10325
10326             when N_Formal_Discrete_Type_Definition =>
10327                if not Is_Discrete_Type (Act_T) then
10328                   Error_Msg_NE
10329                     ("expect discrete type in instantiation of&",
10330                        Actual, Gen_T);
10331                   Abandon_Instantiation (Actual);
10332                end if;
10333
10334             when N_Formal_Signed_Integer_Type_Definition =>
10335                if not Is_Signed_Integer_Type (Act_T) then
10336                   Error_Msg_NE
10337                     ("expect signed integer type in instantiation of&",
10338                      Actual, Gen_T);
10339                   Abandon_Instantiation (Actual);
10340                end if;
10341
10342             when N_Formal_Modular_Type_Definition =>
10343                if not Is_Modular_Integer_Type (Act_T) then
10344                   Error_Msg_NE
10345                     ("expect modular type in instantiation of &",
10346                        Actual, Gen_T);
10347                   Abandon_Instantiation (Actual);
10348                end if;
10349
10350             when N_Formal_Floating_Point_Definition =>
10351                if not Is_Floating_Point_Type (Act_T) then
10352                   Error_Msg_NE
10353                     ("expect float type in instantiation of &", Actual, Gen_T);
10354                   Abandon_Instantiation (Actual);
10355                end if;
10356
10357             when N_Formal_Ordinary_Fixed_Point_Definition =>
10358                if not Is_Ordinary_Fixed_Point_Type (Act_T) then
10359                   Error_Msg_NE
10360                     ("expect ordinary fixed point type in instantiation of &",
10361                      Actual, Gen_T);
10362                   Abandon_Instantiation (Actual);
10363                end if;
10364
10365             when N_Formal_Decimal_Fixed_Point_Definition =>
10366                if not Is_Decimal_Fixed_Point_Type (Act_T) then
10367                   Error_Msg_NE
10368                     ("expect decimal type in instantiation of &",
10369                      Actual, Gen_T);
10370                   Abandon_Instantiation (Actual);
10371                end if;
10372
10373             when N_Array_Type_Definition =>
10374                Validate_Array_Type_Instance;
10375
10376             when N_Access_To_Object_Definition =>
10377                Validate_Access_Type_Instance;
10378
10379             when N_Access_Function_Definition |
10380                  N_Access_Procedure_Definition =>
10381                Validate_Access_Subprogram_Instance;
10382
10383             when N_Record_Definition           =>
10384                Validate_Interface_Type_Instance;
10385
10386             when N_Derived_Type_Definition     =>
10387                Validate_Derived_Interface_Type_Instance;
10388
10389             when others =>
10390                raise Program_Error;
10391
10392          end case;
10393       end if;
10394
10395       Subt := New_Copy (Gen_T);
10396
10397       --  Use adjusted sloc of subtype name as the location for other nodes in
10398       --  the subtype declaration.
10399
10400       Loc  := Sloc (Subt);
10401
10402       Decl_Node :=
10403         Make_Subtype_Declaration (Loc,
10404           Defining_Identifier => Subt,
10405           Subtype_Indication  => New_Reference_To (Act_T, Loc));
10406
10407       if Is_Private_Type (Act_T) then
10408          Set_Has_Private_View (Subtype_Indication (Decl_Node));
10409
10410       elsif Is_Access_Type (Act_T)
10411         and then Is_Private_Type (Designated_Type (Act_T))
10412       then
10413          Set_Has_Private_View (Subtype_Indication (Decl_Node));
10414       end if;
10415
10416       Decl_Nodes := New_List (Decl_Node);
10417
10418       --  Flag actual derived types so their elaboration produces the
10419       --  appropriate renamings for the primitive operations of the ancestor.
10420       --  Flag actual for formal private types as well, to determine whether
10421       --  operations in the private part may override inherited operations.
10422       --  If the formal has an interface list, the ancestor is not the
10423       --  parent, but the analyzed formal that includes the interface
10424       --  operations of all its progenitors.
10425
10426       --  Same treatment for formal private types, so we can check whether the
10427       --  type is tagged limited when validating derivations in the private
10428       --  part. (See AI05-096).
10429
10430       if Nkind (Def) = N_Formal_Derived_Type_Definition then
10431          if Present (Interface_List (Def)) then
10432             Set_Generic_Parent_Type (Decl_Node, A_Gen_T);
10433          else
10434             Set_Generic_Parent_Type (Decl_Node, Ancestor);
10435          end if;
10436
10437       elsif Nkind (Def) = N_Formal_Private_Type_Definition then
10438          Set_Generic_Parent_Type (Decl_Node, A_Gen_T);
10439       end if;
10440
10441       --  If the actual is a synchronized type that implements an interface,
10442       --  the primitive operations are attached to the corresponding record,
10443       --  and we have to treat it as an additional generic actual, so that its
10444       --  primitive operations become visible in the instance. The task or
10445       --  protected type itself does not carry primitive operations.
10446
10447       if Is_Concurrent_Type (Act_T)
10448         and then Is_Tagged_Type (Act_T)
10449         and then Present (Corresponding_Record_Type (Act_T))
10450         and then Present (Ancestor)
10451         and then Is_Interface (Ancestor)
10452       then
10453          declare
10454             Corr_Rec  : constant Entity_Id :=
10455                           Corresponding_Record_Type (Act_T);
10456             New_Corr  : Entity_Id;
10457             Corr_Decl : Node_Id;
10458
10459          begin
10460             New_Corr := Make_Temporary (Loc, 'S');
10461             Corr_Decl :=
10462               Make_Subtype_Declaration (Loc,
10463                 Defining_Identifier => New_Corr,
10464                 Subtype_Indication  =>
10465                   New_Reference_To (Corr_Rec, Loc));
10466             Append_To (Decl_Nodes, Corr_Decl);
10467
10468             if Ekind (Act_T) = E_Task_Type then
10469                Set_Ekind (Subt, E_Task_Subtype);
10470             else
10471                Set_Ekind (Subt, E_Protected_Subtype);
10472             end if;
10473
10474             Set_Corresponding_Record_Type (Subt, Corr_Rec);
10475             Set_Generic_Parent_Type (Corr_Decl, Ancestor);
10476             Set_Generic_Parent_Type (Decl_Node, Empty);
10477          end;
10478       end if;
10479
10480       return Decl_Nodes;
10481    end Instantiate_Type;
10482
10483    -----------------------
10484    -- Is_Generic_Formal --
10485    -----------------------
10486
10487    function Is_Generic_Formal (E : Entity_Id) return Boolean is
10488       Kind : Node_Kind;
10489    begin
10490       if No (E) then
10491          return False;
10492       else
10493          Kind := Nkind (Parent (E));
10494          return
10495            Nkind_In (Kind, N_Formal_Object_Declaration,
10496                            N_Formal_Package_Declaration,
10497                            N_Formal_Type_Declaration)
10498              or else
10499                (Is_Formal_Subprogram (E)
10500                  and then
10501                    Nkind (Parent (Parent (E))) in
10502                      N_Formal_Subprogram_Declaration);
10503       end if;
10504    end Is_Generic_Formal;
10505
10506    ---------------------
10507    -- Is_In_Main_Unit --
10508    ---------------------
10509
10510    function Is_In_Main_Unit (N : Node_Id) return Boolean is
10511       Unum         : constant Unit_Number_Type := Get_Source_Unit (N);
10512       Current_Unit : Node_Id;
10513
10514    begin
10515       if Unum = Main_Unit then
10516          return True;
10517
10518       --  If the current unit is a subunit then it is either the main unit or
10519       --  is being compiled as part of the main unit.
10520
10521       elsif Nkind (N) = N_Compilation_Unit then
10522          return Nkind (Unit (N)) = N_Subunit;
10523       end if;
10524
10525       Current_Unit := Parent (N);
10526       while Present (Current_Unit)
10527         and then Nkind (Current_Unit) /= N_Compilation_Unit
10528       loop
10529          Current_Unit := Parent (Current_Unit);
10530       end loop;
10531
10532       --  The instantiation node is in the main unit, or else the current node
10533       --  (perhaps as the result of nested instantiations) is in the main unit,
10534       --  or in the declaration of the main unit, which in this last case must
10535       --  be a body.
10536
10537       return Unum = Main_Unit
10538         or else Current_Unit = Cunit (Main_Unit)
10539         or else Current_Unit = Library_Unit (Cunit (Main_Unit))
10540         or else (Present (Library_Unit (Current_Unit))
10541                   and then Is_In_Main_Unit (Library_Unit (Current_Unit)));
10542    end Is_In_Main_Unit;
10543
10544    ----------------------------
10545    -- Load_Parent_Of_Generic --
10546    ----------------------------
10547
10548    procedure Load_Parent_Of_Generic
10549      (N             : Node_Id;
10550       Spec          : Node_Id;
10551       Body_Optional : Boolean := False)
10552    is
10553       Comp_Unit          : constant Node_Id := Cunit (Get_Source_Unit (Spec));
10554       Save_Style_Check   : constant Boolean := Style_Check;
10555       True_Parent        : Node_Id;
10556       Inst_Node          : Node_Id;
10557       OK                 : Boolean;
10558       Previous_Instances : constant Elist_Id := New_Elmt_List;
10559
10560       procedure Collect_Previous_Instances (Decls : List_Id);
10561       --  Collect all instantiations in the given list of declarations, that
10562       --  precede the generic that we need to load. If the bodies of these
10563       --  instantiations are available, we must analyze them, to ensure that
10564       --  the public symbols generated are the same when the unit is compiled
10565       --  to generate code, and when it is compiled in the context of a unit
10566       --  that needs a particular nested instance. This process is applied to
10567       --  both package and subprogram instances.
10568
10569       --------------------------------
10570       -- Collect_Previous_Instances --
10571       --------------------------------
10572
10573       procedure Collect_Previous_Instances (Decls : List_Id) is
10574          Decl : Node_Id;
10575
10576       begin
10577          Decl := First (Decls);
10578          while Present (Decl) loop
10579             if Sloc (Decl) >= Sloc (Inst_Node) then
10580                return;
10581
10582             --  If Decl is an instantiation, then record it as requiring
10583             --  instantiation of the corresponding body, except if it is an
10584             --  abbreviated instantiation generated internally for conformance
10585             --  checking purposes only for the case of a formal package
10586             --  declared without a box (see Instantiate_Formal_Package). Such
10587             --  an instantiation does not generate any code (the actual code
10588             --  comes from actual) and thus does not need to be analyzed here.
10589             --  If the instantiation appears with a generic package body it is
10590             --  not analyzed here either.
10591
10592             elsif Nkind (Decl) = N_Package_Instantiation
10593               and then not Is_Internal (Defining_Entity (Decl))
10594             then
10595                Append_Elmt (Decl, Previous_Instances);
10596
10597             --  For a subprogram instantiation, omit instantiations intrinsic
10598             --  operations (Unchecked_Conversions, etc.) that have no bodies.
10599
10600             elsif Nkind_In (Decl, N_Function_Instantiation,
10601                                   N_Procedure_Instantiation)
10602               and then not Is_Intrinsic_Subprogram (Entity (Name (Decl)))
10603             then
10604                Append_Elmt (Decl, Previous_Instances);
10605
10606             elsif Nkind (Decl) = N_Package_Declaration then
10607                Collect_Previous_Instances
10608                  (Visible_Declarations (Specification (Decl)));
10609                Collect_Previous_Instances
10610                  (Private_Declarations (Specification (Decl)));
10611
10612             --  Previous non-generic bodies may contain instances as well
10613
10614             elsif Nkind (Decl) = N_Package_Body
10615               and then Ekind (Corresponding_Spec (Decl)) /= E_Generic_Package
10616             then
10617                Collect_Previous_Instances (Declarations (Decl));
10618
10619             elsif Nkind (Decl) = N_Subprogram_Body
10620               and then not Acts_As_Spec (Decl)
10621               and then not Is_Generic_Subprogram (Corresponding_Spec (Decl))
10622             then
10623                Collect_Previous_Instances (Declarations (Decl));
10624             end if;
10625
10626             Next (Decl);
10627          end loop;
10628       end Collect_Previous_Instances;
10629
10630    --  Start of processing for Load_Parent_Of_Generic
10631
10632    begin
10633       if not In_Same_Source_Unit (N, Spec)
10634         or else Nkind (Unit (Comp_Unit)) = N_Package_Declaration
10635         or else (Nkind (Unit (Comp_Unit)) = N_Package_Body
10636                    and then not Is_In_Main_Unit (Spec))
10637       then
10638          --  Find body of parent of spec, and analyze it. A special case arises
10639          --  when the parent is an instantiation, that is to say when we are
10640          --  currently instantiating a nested generic. In that case, there is
10641          --  no separate file for the body of the enclosing instance. Instead,
10642          --  the enclosing body must be instantiated as if it were a pending
10643          --  instantiation, in order to produce the body for the nested generic
10644          --  we require now. Note that in that case the generic may be defined
10645          --  in a package body, the instance defined in the same package body,
10646          --  and the original enclosing body may not be in the main unit.
10647
10648          Inst_Node := Empty;
10649
10650          True_Parent := Parent (Spec);
10651          while Present (True_Parent)
10652            and then Nkind (True_Parent) /= N_Compilation_Unit
10653          loop
10654             if Nkind (True_Parent) = N_Package_Declaration
10655                  and then
10656                Nkind (Original_Node (True_Parent)) = N_Package_Instantiation
10657             then
10658                --  Parent is a compilation unit that is an instantiation.
10659                --  Instantiation node has been replaced with package decl.
10660
10661                Inst_Node := Original_Node (True_Parent);
10662                exit;
10663
10664             elsif Nkind (True_Parent) = N_Package_Declaration
10665               and then Present (Generic_Parent (Specification (True_Parent)))
10666               and then Nkind (Parent (True_Parent)) /= N_Compilation_Unit
10667             then
10668                --  Parent is an instantiation within another specification.
10669                --  Declaration for instance has been inserted before original
10670                --  instantiation node. A direct link would be preferable?
10671
10672                Inst_Node := Next (True_Parent);
10673                while Present (Inst_Node)
10674                  and then Nkind (Inst_Node) /= N_Package_Instantiation
10675                loop
10676                   Next (Inst_Node);
10677                end loop;
10678
10679                --  If the instance appears within a generic, and the generic
10680                --  unit is defined within a formal package of the enclosing
10681                --  generic, there is no generic body available, and none
10682                --  needed. A more precise test should be used ???
10683
10684                if No (Inst_Node) then
10685                   return;
10686                end if;
10687
10688                exit;
10689
10690             else
10691                True_Parent := Parent (True_Parent);
10692             end if;
10693          end loop;
10694
10695          --  Case where we are currently instantiating a nested generic
10696
10697          if Present (Inst_Node) then
10698             if Nkind (Parent (True_Parent)) = N_Compilation_Unit then
10699
10700                --  Instantiation node and declaration of instantiated package
10701                --  were exchanged when only the declaration was needed.
10702                --  Restore instantiation node before proceeding with body.
10703
10704                Set_Unit (Parent (True_Parent), Inst_Node);
10705             end if;
10706
10707             --  Now complete instantiation of enclosing body, if it appears in
10708             --  some other unit. If it appears in the current unit, the body
10709             --  will have been instantiated already.
10710
10711             if No (Corresponding_Body (Instance_Spec (Inst_Node))) then
10712
10713                --  We need to determine the expander mode to instantiate the
10714                --  enclosing body. Because the generic body we need may use
10715                --  global entities declared in the enclosing package (including
10716                --  aggregates) it is in general necessary to compile this body
10717                --  with expansion enabled, except if we are within a generic
10718                --  package, in which case the usual generic rule applies.
10719
10720                declare
10721                   Exp_Status         : Boolean := True;
10722                   Scop               : Entity_Id;
10723
10724                begin
10725                   --  Loop through scopes looking for generic package
10726
10727                   Scop := Scope (Defining_Entity (Instance_Spec (Inst_Node)));
10728                   while Present (Scop)
10729                     and then Scop /= Standard_Standard
10730                   loop
10731                      if Ekind (Scop) = E_Generic_Package then
10732                         Exp_Status := False;
10733                         exit;
10734                      end if;
10735
10736                      Scop := Scope (Scop);
10737                   end loop;
10738
10739                   --  Collect previous instantiations in the unit that contains
10740                   --  the desired generic.
10741
10742                   if Nkind (Parent (True_Parent)) /= N_Compilation_Unit
10743                     and then not Body_Optional
10744                   then
10745                      declare
10746                         Decl : Elmt_Id;
10747                         Info : Pending_Body_Info;
10748                         Par  : Node_Id;
10749
10750                      begin
10751                         Par := Parent (Inst_Node);
10752                         while Present (Par) loop
10753                            exit when Nkind (Parent (Par)) = N_Compilation_Unit;
10754                            Par := Parent (Par);
10755                         end loop;
10756
10757                         pragma Assert (Present (Par));
10758
10759                         if Nkind (Par) = N_Package_Body then
10760                            Collect_Previous_Instances (Declarations (Par));
10761
10762                         elsif Nkind (Par) = N_Package_Declaration then
10763                            Collect_Previous_Instances
10764                              (Visible_Declarations (Specification (Par)));
10765                            Collect_Previous_Instances
10766                              (Private_Declarations (Specification (Par)));
10767
10768                         else
10769                            --  Enclosing unit is a subprogram body. In this
10770                            --  case all instance bodies are processed in order
10771                            --  and there is no need to collect them separately.
10772
10773                            null;
10774                         end if;
10775
10776                         Decl := First_Elmt (Previous_Instances);
10777                         while Present (Decl) loop
10778                            Info :=
10779                              (Inst_Node                => Node (Decl),
10780                               Act_Decl                 =>
10781                                 Instance_Spec (Node (Decl)),
10782                               Expander_Status          => Exp_Status,
10783                               Current_Sem_Unit         =>
10784                                 Get_Code_Unit (Sloc (Node (Decl))),
10785                               Scope_Suppress           => Scope_Suppress,
10786                               Local_Suppress_Stack_Top =>
10787                                 Local_Suppress_Stack_Top,
10788                               Version                  => Ada_Version);
10789
10790                            --  Package instance
10791
10792                            if
10793                              Nkind (Node (Decl)) = N_Package_Instantiation
10794                            then
10795                               Instantiate_Package_Body
10796                                 (Info, Body_Optional => True);
10797
10798                            --  Subprogram instance
10799
10800                            else
10801                               --  The instance_spec is the wrapper package,
10802                               --  and the subprogram declaration is the last
10803                               --  declaration in the wrapper.
10804
10805                               Info.Act_Decl :=
10806                                 Last
10807                                   (Visible_Declarations
10808                                     (Specification (Info.Act_Decl)));
10809
10810                               Instantiate_Subprogram_Body
10811                                 (Info, Body_Optional => True);
10812                            end if;
10813
10814                            Next_Elmt (Decl);
10815                         end loop;
10816                      end;
10817                   end if;
10818
10819                   Instantiate_Package_Body
10820                     (Body_Info =>
10821                        ((Inst_Node                => Inst_Node,
10822                          Act_Decl                 => True_Parent,
10823                          Expander_Status          => Exp_Status,
10824                          Current_Sem_Unit         =>
10825                            Get_Code_Unit (Sloc (Inst_Node)),
10826                          Scope_Suppress           => Scope_Suppress,
10827                          Local_Suppress_Stack_Top =>
10828                            Local_Suppress_Stack_Top,
10829                            Version                => Ada_Version)),
10830                      Body_Optional => Body_Optional);
10831                end;
10832             end if;
10833
10834          --  Case where we are not instantiating a nested generic
10835
10836          else
10837             Opt.Style_Check := False;
10838             Expander_Mode_Save_And_Set (True);
10839             Load_Needed_Body (Comp_Unit, OK);
10840             Opt.Style_Check := Save_Style_Check;
10841             Expander_Mode_Restore;
10842
10843             if not OK
10844               and then Unit_Requires_Body (Defining_Entity (Spec))
10845               and then not Body_Optional
10846             then
10847                declare
10848                   Bname : constant Unit_Name_Type :=
10849                             Get_Body_Name (Get_Unit_Name (Unit (Comp_Unit)));
10850
10851                begin
10852                   --  In CodePeer mode, the missing body may make the analysis
10853                   --  incomplete, but we do not treat it as fatal.
10854
10855                   if CodePeer_Mode then
10856                      return;
10857
10858                   else
10859                      Error_Msg_Unit_1 := Bname;
10860                      Error_Msg_N ("this instantiation requires$!", N);
10861                      Error_Msg_File_1 :=
10862                        Get_File_Name (Bname, Subunit => False);
10863                      Error_Msg_N ("\but file{ was not found!", N);
10864                      raise Unrecoverable_Error;
10865                   end if;
10866                end;
10867             end if;
10868          end if;
10869       end if;
10870
10871       --  If loading parent of the generic caused an instantiation circularity,
10872       --  we abandon compilation at this point, because otherwise in some cases
10873       --  we get into trouble with infinite recursions after this point.
10874
10875       if Circularity_Detected then
10876          raise Unrecoverable_Error;
10877       end if;
10878    end Load_Parent_Of_Generic;
10879
10880    ---------------------------------
10881    -- Map_Formal_Package_Entities --
10882    ---------------------------------
10883
10884    procedure Map_Formal_Package_Entities (Form : Entity_Id; Act : Entity_Id) is
10885       E1 : Entity_Id;
10886       E2 : Entity_Id;
10887
10888    begin
10889       Set_Instance_Of (Form, Act);
10890
10891       --  Traverse formal and actual package to map the corresponding entities.
10892       --  We skip over internal entities that may be generated during semantic
10893       --  analysis, and find the matching entities by name, given that they
10894       --  must appear in the same order.
10895
10896       E1 := First_Entity (Form);
10897       E2 := First_Entity (Act);
10898       while Present (E1) and then E1 /= First_Private_Entity (Form) loop
10899          --  Could this test be a single condition???
10900          --  Seems like it could, and isn't FPE (Form) a constant anyway???
10901
10902          if not Is_Internal (E1)
10903            and then Present (Parent (E1))
10904            and then not Is_Class_Wide_Type (E1)
10905            and then not Is_Internal_Name (Chars (E1))
10906          then
10907             while Present (E2) and then Chars (E2) /= Chars (E1) loop
10908                Next_Entity (E2);
10909             end loop;
10910
10911             if No (E2) then
10912                exit;
10913             else
10914                Set_Instance_Of (E1, E2);
10915
10916                if Is_Type (E1) and then Is_Tagged_Type (E2) then
10917                   Set_Instance_Of (Class_Wide_Type (E1), Class_Wide_Type (E2));
10918                end if;
10919
10920                if Is_Constrained (E1) then
10921                   Set_Instance_Of (Base_Type (E1), Base_Type (E2));
10922                end if;
10923
10924                if Ekind (E1) = E_Package and then No (Renamed_Object (E1)) then
10925                   Map_Formal_Package_Entities (E1, E2);
10926                end if;
10927             end if;
10928          end if;
10929
10930          Next_Entity (E1);
10931       end loop;
10932    end Map_Formal_Package_Entities;
10933
10934    -----------------------
10935    -- Move_Freeze_Nodes --
10936    -----------------------
10937
10938    procedure Move_Freeze_Nodes
10939      (Out_Of : Entity_Id;
10940       After  : Node_Id;
10941       L      : List_Id)
10942    is
10943       Decl      : Node_Id;
10944       Next_Decl : Node_Id;
10945       Next_Node : Node_Id := After;
10946       Spec      : Node_Id;
10947
10948       function Is_Outer_Type (T : Entity_Id) return Boolean;
10949       --  Check whether entity is declared in a scope external to that of the
10950       --  generic unit.
10951
10952       -------------------
10953       -- Is_Outer_Type --
10954       -------------------
10955
10956       function Is_Outer_Type (T : Entity_Id) return Boolean is
10957          Scop : Entity_Id := Scope (T);
10958
10959       begin
10960          if Scope_Depth (Scop) < Scope_Depth (Out_Of) then
10961             return True;
10962
10963          else
10964             while Scop /= Standard_Standard loop
10965                if Scop = Out_Of then
10966                   return False;
10967                else
10968                   Scop := Scope (Scop);
10969                end if;
10970             end loop;
10971
10972             return True;
10973          end if;
10974       end Is_Outer_Type;
10975
10976    --  Start of processing for Move_Freeze_Nodes
10977
10978    begin
10979       if No (L) then
10980          return;
10981       end if;
10982
10983       --  First remove the freeze nodes that may appear before all other
10984       --  declarations.
10985
10986       Decl := First (L);
10987       while Present (Decl)
10988         and then Nkind (Decl) = N_Freeze_Entity
10989         and then Is_Outer_Type (Entity (Decl))
10990       loop
10991          Decl := Remove_Head (L);
10992          Insert_After (Next_Node, Decl);
10993          Set_Analyzed (Decl, False);
10994          Next_Node := Decl;
10995          Decl := First (L);
10996       end loop;
10997
10998       --  Next scan the list of declarations and remove each freeze node that
10999       --  appears ahead of the current node.
11000
11001       while Present (Decl) loop
11002          while Present (Next (Decl))
11003            and then Nkind (Next (Decl)) = N_Freeze_Entity
11004            and then Is_Outer_Type (Entity (Next (Decl)))
11005          loop
11006             Next_Decl := Remove_Next (Decl);
11007             Insert_After (Next_Node, Next_Decl);
11008             Set_Analyzed (Next_Decl, False);
11009             Next_Node := Next_Decl;
11010          end loop;
11011
11012          --  If the declaration is a nested package or concurrent type, then
11013          --  recurse. Nested generic packages will have been processed from the
11014          --  inside out.
11015
11016          case Nkind (Decl) is
11017             when N_Package_Declaration =>
11018                Spec := Specification (Decl);
11019
11020             when N_Task_Type_Declaration =>
11021                Spec := Task_Definition (Decl);
11022
11023             when N_Protected_Type_Declaration =>
11024                Spec := Protected_Definition (Decl);
11025
11026             when others =>
11027                Spec := Empty;
11028          end case;
11029
11030          if Present (Spec) then
11031             Move_Freeze_Nodes (Out_Of, Next_Node, Visible_Declarations (Spec));
11032             Move_Freeze_Nodes (Out_Of, Next_Node, Private_Declarations (Spec));
11033          end if;
11034
11035          Next (Decl);
11036       end loop;
11037    end Move_Freeze_Nodes;
11038
11039    ----------------
11040    -- Next_Assoc --
11041    ----------------
11042
11043    function Next_Assoc (E : Assoc_Ptr) return Assoc_Ptr is
11044    begin
11045       return Generic_Renamings.Table (E).Next_In_HTable;
11046    end Next_Assoc;
11047
11048    ------------------------
11049    -- Preanalyze_Actuals --
11050    ------------------------
11051
11052    procedure Preanalyze_Actuals (N : Node_Id) is
11053       Assoc : Node_Id;
11054       Act   : Node_Id;
11055       Errs  : constant Int := Serious_Errors_Detected;
11056
11057       Cur : Entity_Id := Empty;
11058       --  Current homograph of the instance name
11059
11060       Vis : Boolean;
11061       --  Saved visibility status of the current homograph
11062
11063    begin
11064       Assoc := First (Generic_Associations (N));
11065
11066       --  If the instance is a child unit, its name may hide an outer homonym,
11067       --  so make it invisible to perform name resolution on the actuals.
11068
11069       if Nkind (Defining_Unit_Name (N)) = N_Defining_Program_Unit_Name
11070         and then Present
11071           (Current_Entity (Defining_Identifier (Defining_Unit_Name (N))))
11072       then
11073          Cur := Current_Entity (Defining_Identifier (Defining_Unit_Name (N)));
11074
11075          if Is_Compilation_Unit (Cur) then
11076             Vis := Is_Immediately_Visible (Cur);
11077             Set_Is_Immediately_Visible (Cur, False);
11078          else
11079             Cur := Empty;
11080          end if;
11081       end if;
11082
11083       while Present (Assoc) loop
11084          if Nkind (Assoc) /= N_Others_Choice then
11085             Act := Explicit_Generic_Actual_Parameter (Assoc);
11086
11087             --  Within a nested instantiation, a defaulted actual is an empty
11088             --  association, so nothing to analyze. If the subprogram actual
11089             --  is an attribute, analyze prefix only, because actual is not a
11090             --  complete attribute reference.
11091
11092             --  If actual is an allocator, analyze expression only. The full
11093             --  analysis can generate code, and if instance is a compilation
11094             --  unit we have to wait until the package instance is installed
11095             --  to have a proper place to insert this code.
11096
11097             --  String literals may be operators, but at this point we do not
11098             --  know whether the actual is a formal subprogram or a string.
11099
11100             if No (Act) then
11101                null;
11102
11103             elsif Nkind (Act) = N_Attribute_Reference then
11104                Analyze (Prefix (Act));
11105
11106             elsif Nkind (Act) = N_Explicit_Dereference then
11107                Analyze (Prefix (Act));
11108
11109             elsif Nkind (Act) = N_Allocator then
11110                declare
11111                   Expr : constant Node_Id := Expression (Act);
11112
11113                begin
11114                   if Nkind (Expr) = N_Subtype_Indication then
11115                      Analyze (Subtype_Mark (Expr));
11116
11117                      --  Analyze separately each discriminant constraint, when
11118                      --  given with a named association.
11119
11120                      declare
11121                         Constr : Node_Id;
11122
11123                      begin
11124                         Constr := First (Constraints (Constraint (Expr)));
11125                         while Present (Constr) loop
11126                            if Nkind (Constr) = N_Discriminant_Association then
11127                               Analyze (Expression (Constr));
11128                            else
11129                               Analyze (Constr);
11130                            end if;
11131
11132                            Next (Constr);
11133                         end loop;
11134                      end;
11135
11136                   else
11137                      Analyze (Expr);
11138                   end if;
11139                end;
11140
11141             elsif Nkind (Act) /= N_Operator_Symbol then
11142                Analyze (Act);
11143             end if;
11144
11145             if Errs /= Serious_Errors_Detected then
11146
11147                --  Do a minimal analysis of the generic, to prevent spurious
11148                --  warnings complaining about the generic being unreferenced,
11149                --  before abandoning the instantiation.
11150
11151                Analyze (Name (N));
11152
11153                if Is_Entity_Name (Name (N))
11154                  and then Etype (Name (N)) /= Any_Type
11155                then
11156                   Generate_Reference  (Entity (Name (N)), Name (N));
11157                   Set_Is_Instantiated (Entity (Name (N)));
11158                end if;
11159
11160                if Present (Cur) then
11161
11162                   --  For the case of a child instance hiding an outer homonym,
11163                   --  provide additional warning which might explain the error.
11164
11165                   Set_Is_Immediately_Visible (Cur, Vis);
11166                   Error_Msg_NE ("& hides outer unit with the same name?",
11167                     N, Defining_Unit_Name (N));
11168                end if;
11169
11170                Abandon_Instantiation (Act);
11171             end if;
11172          end if;
11173
11174          Next (Assoc);
11175       end loop;
11176
11177       if Present (Cur) then
11178          Set_Is_Immediately_Visible (Cur, Vis);
11179       end if;
11180    end Preanalyze_Actuals;
11181
11182    -------------------
11183    -- Remove_Parent --
11184    -------------------
11185
11186    procedure Remove_Parent (In_Body : Boolean := False) is
11187       S : Entity_Id := Current_Scope;
11188       --  S is the scope containing the instantiation just completed. The scope
11189       --  stack contains the parent instances of the instantiation, followed by
11190       --  the original S.
11191
11192       Cur_P  : Entity_Id;
11193       E      : Entity_Id;
11194       P      : Entity_Id;
11195       Hidden : Elmt_Id;
11196
11197    begin
11198       --  After child instantiation is complete, remove from scope stack the
11199       --  extra copy of the current scope, and then remove parent instances.
11200
11201       if not In_Body then
11202          Pop_Scope;
11203
11204          while Current_Scope /= S loop
11205             P := Current_Scope;
11206             End_Package_Scope (Current_Scope);
11207
11208             if In_Open_Scopes (P) then
11209                E := First_Entity (P);
11210                while Present (E) loop
11211                   Set_Is_Immediately_Visible (E, True);
11212                   Next_Entity (E);
11213                end loop;
11214
11215                --  If instantiation is declared in a block, it is the enclosing
11216                --  scope that might be a parent instance. Note that only one
11217                --  block can be involved, because the parent instances have
11218                --  been installed within it.
11219
11220                if Ekind (P) = E_Block then
11221                   Cur_P := Scope (P);
11222                else
11223                   Cur_P := P;
11224                end if;
11225
11226                if Is_Generic_Instance (Cur_P) and then P /= Current_Scope then
11227                   --  We are within an instance of some sibling. Retain
11228                   --  visibility of parent, for proper subsequent cleanup, and
11229                   --  reinstall private declarations as well.
11230
11231                   Set_In_Private_Part (P);
11232                   Install_Private_Declarations (P);
11233                end if;
11234
11235             --  If the ultimate parent is a top-level unit recorded in
11236             --  Instance_Parent_Unit, then reset its visibility to what it was
11237             --  before instantiation. (It's not clear what the purpose is of
11238             --  testing whether Scope (P) is In_Open_Scopes, but that test was
11239             --  present before the ultimate parent test was added.???)
11240
11241             elsif not In_Open_Scopes (Scope (P))
11242               or else (P = Instance_Parent_Unit
11243                         and then not Parent_Unit_Visible)
11244             then
11245                Set_Is_Immediately_Visible (P, False);
11246
11247             --  If the current scope is itself an instantiation of a generic
11248             --  nested within P, and we are in the private part of body of this
11249             --  instantiation, restore the full views of P, that were removed
11250             --  in End_Package_Scope above. This obscure case can occur when a
11251             --  subunit of a generic contains an instance of a child unit of
11252             --  its generic parent unit.
11253
11254             elsif S = Current_Scope and then Is_Generic_Instance (S) then
11255                declare
11256                   Par : constant Entity_Id :=
11257                           Generic_Parent
11258                             (Specification (Unit_Declaration_Node (S)));
11259                begin
11260                   if Present (Par)
11261                     and then P = Scope (Par)
11262                     and then (In_Package_Body (S) or else In_Private_Part (S))
11263                   then
11264                      Set_In_Private_Part (P);
11265                      Install_Private_Declarations (P);
11266                   end if;
11267                end;
11268             end if;
11269          end loop;
11270
11271          --  Reset visibility of entities in the enclosing scope
11272
11273          Set_Is_Hidden_Open_Scope (Current_Scope, False);
11274
11275          Hidden := First_Elmt (Hidden_Entities);
11276          while Present (Hidden) loop
11277             Set_Is_Immediately_Visible (Node (Hidden), True);
11278             Next_Elmt (Hidden);
11279          end loop;
11280
11281       else
11282          --  Each body is analyzed separately, and there is no context that
11283          --  needs preserving from one body instance to the next, so remove all
11284          --  parent scopes that have been installed.
11285
11286          while Present (S) loop
11287             End_Package_Scope (S);
11288             Set_Is_Immediately_Visible (S, False);
11289             S := Current_Scope;
11290             exit when S = Standard_Standard;
11291          end loop;
11292       end if;
11293    end Remove_Parent;
11294
11295    -----------------
11296    -- Restore_Env --
11297    -----------------
11298
11299    procedure Restore_Env is
11300       Saved : Instance_Env renames Instance_Envs.Table (Instance_Envs.Last);
11301
11302    begin
11303       if No (Current_Instantiated_Parent.Act_Id) then
11304          --  Restore environment after subprogram inlining
11305
11306          Restore_Private_Views (Empty);
11307       end if;
11308
11309       Current_Instantiated_Parent := Saved.Instantiated_Parent;
11310       Exchanged_Views             := Saved.Exchanged_Views;
11311       Hidden_Entities             := Saved.Hidden_Entities;
11312       Current_Sem_Unit            := Saved.Current_Sem_Unit;
11313       Parent_Unit_Visible         := Saved.Parent_Unit_Visible;
11314       Instance_Parent_Unit        := Saved.Instance_Parent_Unit;
11315
11316       Restore_Opt_Config_Switches (Saved.Switches);
11317
11318       Instance_Envs.Decrement_Last;
11319    end Restore_Env;
11320
11321    ---------------------------
11322    -- Restore_Private_Views --
11323    ---------------------------
11324
11325    procedure Restore_Private_Views
11326      (Pack_Id    : Entity_Id;
11327       Is_Package : Boolean := True)
11328    is
11329       M        : Elmt_Id;
11330       E        : Entity_Id;
11331       Typ      : Entity_Id;
11332       Dep_Elmt : Elmt_Id;
11333       Dep_Typ  : Node_Id;
11334
11335       procedure Restore_Nested_Formal (Formal : Entity_Id);
11336       --  Hide the generic formals of formal packages declared with box which
11337       --  were reachable in the current instantiation.
11338
11339       ---------------------------
11340       -- Restore_Nested_Formal --
11341       ---------------------------
11342
11343       procedure Restore_Nested_Formal (Formal : Entity_Id) is
11344          Ent : Entity_Id;
11345
11346       begin
11347          if Present (Renamed_Object (Formal))
11348            and then Denotes_Formal_Package (Renamed_Object (Formal), True)
11349          then
11350             return;
11351
11352          elsif Present (Associated_Formal_Package (Formal)) then
11353             Ent := First_Entity (Formal);
11354             while Present (Ent) loop
11355                exit when Ekind (Ent) = E_Package
11356                  and then Renamed_Entity (Ent) = Renamed_Entity (Formal);
11357
11358                Set_Is_Hidden (Ent);
11359                Set_Is_Potentially_Use_Visible (Ent, False);
11360
11361                --  If package, then recurse
11362
11363                if Ekind (Ent) = E_Package then
11364                   Restore_Nested_Formal (Ent);
11365                end if;
11366
11367                Next_Entity (Ent);
11368             end loop;
11369          end if;
11370       end Restore_Nested_Formal;
11371
11372    --  Start of processing for Restore_Private_Views
11373
11374    begin
11375       M := First_Elmt (Exchanged_Views);
11376       while Present (M) loop
11377          Typ := Node (M);
11378
11379          --  Subtypes of types whose views have been exchanged, and that are
11380          --  defined within the instance, were not on the Private_Dependents
11381          --  list on entry to the instance, so they have to be exchanged
11382          --  explicitly now, in order to remain consistent with the view of the
11383          --  parent type.
11384
11385          if Ekind_In (Typ, E_Private_Type,
11386                            E_Limited_Private_Type,
11387                            E_Record_Type_With_Private)
11388          then
11389             Dep_Elmt := First_Elmt (Private_Dependents (Typ));
11390             while Present (Dep_Elmt) loop
11391                Dep_Typ := Node (Dep_Elmt);
11392
11393                if Scope (Dep_Typ) = Pack_Id
11394                  and then Present (Full_View (Dep_Typ))
11395                then
11396                   Replace_Elmt (Dep_Elmt, Full_View (Dep_Typ));
11397                   Exchange_Declarations (Dep_Typ);
11398                end if;
11399
11400                Next_Elmt (Dep_Elmt);
11401             end loop;
11402          end if;
11403
11404          Exchange_Declarations (Node (M));
11405          Next_Elmt (M);
11406       end loop;
11407
11408       if No (Pack_Id) then
11409          return;
11410       end if;
11411
11412       --  Make the generic formal parameters private, and make the formal types
11413       --  into subtypes of the actuals again.
11414
11415       E := First_Entity (Pack_Id);
11416       while Present (E) loop
11417          Set_Is_Hidden (E, True);
11418
11419          if Is_Type (E)
11420            and then Nkind (Parent (E)) = N_Subtype_Declaration
11421          then
11422             Set_Is_Generic_Actual_Type (E, False);
11423
11424             --  An unusual case of aliasing: the actual may also be directly
11425             --  visible in the generic, and be private there, while it is fully
11426             --  visible in the context of the instance. The internal subtype
11427             --  is private in the instance but has full visibility like its
11428             --  parent in the enclosing scope. This enforces the invariant that
11429             --  the privacy status of all private dependents of a type coincide
11430             --  with that of the parent type. This can only happen when a
11431             --  generic child unit is instantiated within a sibling.
11432
11433             if Is_Private_Type (E)
11434               and then not Is_Private_Type (Etype (E))
11435             then
11436                Exchange_Declarations (E);
11437             end if;
11438
11439          elsif Ekind (E) = E_Package then
11440
11441             --  The end of the renaming list is the renaming of the generic
11442             --  package itself. If the instance is a subprogram, all entities
11443             --  in the corresponding package are renamings. If this entity is
11444             --  a formal package, make its own formals private as well. The
11445             --  actual in this case is itself the renaming of an instantiation.
11446             --  If the entity is not a package renaming, it is the entity
11447             --  created to validate formal package actuals: ignore it.
11448
11449             --  If the actual is itself a formal package for the enclosing
11450             --  generic, or the actual for such a formal package, it remains
11451             --  visible on exit from the instance, and therefore nothing needs
11452             --  to be done either, except to keep it accessible.
11453
11454             if Is_Package and then Renamed_Object (E) = Pack_Id then
11455                exit;
11456
11457             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
11458                null;
11459
11460             elsif
11461               Denotes_Formal_Package (Renamed_Object (E), True, Pack_Id)
11462             then
11463                Set_Is_Hidden (E, False);
11464
11465             else
11466                declare
11467                   Act_P : constant Entity_Id := Renamed_Object (E);
11468                   Id    : Entity_Id;
11469
11470                begin
11471                   Id := First_Entity (Act_P);
11472                   while Present (Id)
11473                     and then Id /= First_Private_Entity (Act_P)
11474                   loop
11475                      exit when Ekind (Id) = E_Package
11476                                  and then Renamed_Object (Id) = Act_P;
11477
11478                      Set_Is_Hidden (Id, True);
11479                      Set_Is_Potentially_Use_Visible (Id, In_Use (Act_P));
11480
11481                      if Ekind (Id) = E_Package then
11482                         Restore_Nested_Formal (Id);
11483                      end if;
11484
11485                      Next_Entity (Id);
11486                   end loop;
11487                end;
11488             end if;
11489          end if;
11490
11491          Next_Entity (E);
11492       end loop;
11493    end Restore_Private_Views;
11494
11495    --------------
11496    -- Save_Env --
11497    --------------
11498
11499    procedure Save_Env
11500      (Gen_Unit : Entity_Id;
11501       Act_Unit : Entity_Id)
11502    is
11503    begin
11504       Init_Env;
11505       Set_Instance_Env (Gen_Unit, Act_Unit);
11506    end Save_Env;
11507
11508    ----------------------------
11509    -- Save_Global_References --
11510    ----------------------------
11511
11512    procedure Save_Global_References (N : Node_Id) is
11513       Gen_Scope : Entity_Id;
11514       E         : Entity_Id;
11515       N2        : Node_Id;
11516
11517       function Is_Global (E : Entity_Id) return Boolean;
11518       --  Check whether entity is defined outside of generic unit. Examine the
11519       --  scope of an entity, and the scope of the scope, etc, until we find
11520       --  either Standard, in which case the entity is global, or the generic
11521       --  unit itself, which indicates that the entity is local. If the entity
11522       --  is the generic unit itself, as in the case of a recursive call, or
11523       --  the enclosing generic unit, if different from the current scope, then
11524       --  it is local as well, because it will be replaced at the point of
11525       --  instantiation. On the other hand, if it is a reference to a child
11526       --  unit of a common ancestor, which appears in an instantiation, it is
11527       --  global because it is used to denote a specific compilation unit at
11528       --  the time the instantiations will be analyzed.
11529
11530       procedure Reset_Entity (N : Node_Id);
11531       --  Save semantic information on global entity so that it is not resolved
11532       --  again at instantiation time.
11533
11534       procedure Save_Entity_Descendants (N : Node_Id);
11535       --  Apply Save_Global_References to the two syntactic descendants of
11536       --  non-terminal nodes that carry an Associated_Node and are processed
11537       --  through Reset_Entity. Once the global entity (if any) has been
11538       --  captured together with its type, only two syntactic descendants need
11539       --  to be traversed to complete the processing of the tree rooted at N.
11540       --  This applies to Selected_Components, Expanded_Names, and to Operator
11541       --  nodes. N can also be a character literal, identifier, or operator
11542       --  symbol node, but the call has no effect in these cases.
11543
11544       procedure Save_Global_Defaults (N1, N2 : Node_Id);
11545       --  Default actuals in nested instances must be handled specially
11546       --  because there is no link to them from the original tree. When an
11547       --  actual subprogram is given by a default, we add an explicit generic
11548       --  association for it in the instantiation node. When we save the
11549       --  global references on the name of the instance, we recover the list
11550       --  of generic associations, and add an explicit one to the original
11551       --  generic tree, through which a global actual can be preserved.
11552       --  Similarly, if a child unit is instantiated within a sibling, in the
11553       --  context of the parent, we must preserve the identifier of the parent
11554       --  so that it can be properly resolved in a subsequent instantiation.
11555
11556       procedure Save_Global_Descendant (D : Union_Id);
11557       --  Apply Save_Global_References recursively to the descendents of the
11558       --  current node.
11559
11560       procedure Save_References (N : Node_Id);
11561       --  This is the recursive procedure that does the work, once the
11562       --  enclosing generic scope has been established.
11563
11564       ---------------
11565       -- Is_Global --
11566       ---------------
11567
11568       function Is_Global (E : Entity_Id) return Boolean is
11569          Se : Entity_Id;
11570
11571          function Is_Instance_Node (Decl : Node_Id) return Boolean;
11572          --  Determine whether the parent node of a reference to a child unit
11573          --  denotes an instantiation or a formal package, in which case the
11574          --  reference to the child unit is global, even if it appears within
11575          --  the current scope (e.g. when the instance appears within the body
11576          --  of an ancestor).
11577
11578          ----------------------
11579          -- Is_Instance_Node --
11580          ----------------------
11581
11582          function Is_Instance_Node (Decl : Node_Id) return Boolean is
11583          begin
11584             return Nkind (Decl) in N_Generic_Instantiation
11585                      or else
11586                    Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration;
11587          end Is_Instance_Node;
11588
11589       --  Start of processing for Is_Global
11590
11591       begin
11592          if E = Gen_Scope then
11593             return False;
11594
11595          elsif E = Standard_Standard then
11596             return True;
11597
11598          elsif Is_Child_Unit (E)
11599            and then (Is_Instance_Node (Parent (N2))
11600                       or else (Nkind (Parent (N2)) = N_Expanded_Name
11601                                 and then N2 = Selector_Name (Parent (N2))
11602                                 and then
11603                                   Is_Instance_Node (Parent (Parent (N2)))))
11604          then
11605             return True;
11606
11607          else
11608             Se := Scope (E);
11609             while Se /= Gen_Scope loop
11610                if Se = Standard_Standard then
11611                   return True;
11612                else
11613                   Se := Scope (Se);
11614                end if;
11615             end loop;
11616
11617             return False;
11618          end if;
11619       end Is_Global;
11620
11621       ------------------
11622       -- Reset_Entity --
11623       ------------------
11624
11625       procedure Reset_Entity (N : Node_Id) is
11626
11627          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id);
11628          --  If the type of N2 is global to the generic unit. Save the type in
11629          --  the generic node.
11630          --  What does this comment mean???
11631
11632          function Top_Ancestor (E : Entity_Id) return Entity_Id;
11633          --  Find the ultimate ancestor of the current unit. If it is not a
11634          --  generic unit, then the name of the current unit in the prefix of
11635          --  an expanded name must be replaced with its generic homonym to
11636          --  ensure that it will be properly resolved in an instance.
11637
11638          ---------------------
11639          -- Set_Global_Type --
11640          ---------------------
11641
11642          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id) is
11643             Typ : constant Entity_Id := Etype (N2);
11644
11645          begin
11646             Set_Etype (N, Typ);
11647
11648             if Entity (N) /= N2
11649               and then Has_Private_View (Entity (N))
11650             then
11651                --  If the entity of N is not the associated node, this is a
11652                --  nested generic and it has an associated node as well, whose
11653                --  type is already the full view (see below). Indicate that the
11654                --  original node has a private view.
11655
11656                Set_Has_Private_View (N);
11657             end if;
11658
11659             --  If not a private type, nothing else to do
11660
11661             if not Is_Private_Type (Typ) then
11662                if Is_Array_Type (Typ)
11663                  and then Is_Private_Type (Component_Type (Typ))
11664                then
11665                   Set_Has_Private_View (N);
11666                end if;
11667
11668             --  If it is a derivation of a private type in a context where no
11669             --  full view is needed, nothing to do either.
11670
11671             elsif No (Full_View (Typ)) and then Typ /= Etype (Typ) then
11672                null;
11673
11674             --  Otherwise mark the type for flipping and use the full view when
11675             --  available.
11676
11677             else
11678                Set_Has_Private_View (N);
11679
11680                if Present (Full_View (Typ)) then
11681                   Set_Etype (N2, Full_View (Typ));
11682                end if;
11683             end if;
11684          end Set_Global_Type;
11685
11686          ------------------
11687          -- Top_Ancestor --
11688          ------------------
11689
11690          function Top_Ancestor (E : Entity_Id) return Entity_Id is
11691             Par : Entity_Id;
11692
11693          begin
11694             Par := E;
11695             while Is_Child_Unit (Par) loop
11696                Par := Scope (Par);
11697             end loop;
11698
11699             return Par;
11700          end Top_Ancestor;
11701
11702       --  Start of processing for Reset_Entity
11703
11704       begin
11705          N2 := Get_Associated_Node (N);
11706          E := Entity (N2);
11707
11708          --  If the entity is an itype created as a subtype of an access type
11709          --  with a null exclusion restore source entity for proper visibility.
11710          --  The itype will be created anew in the instance.
11711
11712          if Present (E) then
11713             if Is_Itype (E)
11714               and then Ekind (E) = E_Access_Subtype
11715               and then Is_Entity_Name (N)
11716               and then Chars (Etype (E)) = Chars (N)
11717             then
11718                E := Etype (E);
11719                Set_Entity (N2, E);
11720                Set_Etype  (N2, E);
11721             end if;
11722
11723             if Is_Global (E) then
11724                Set_Global_Type (N, N2);
11725
11726             elsif Nkind (N) = N_Op_Concat
11727               and then Is_Generic_Type (Etype (N2))
11728               and then (Base_Type (Etype (Right_Opnd (N2))) = Etype (N2)
11729                          or else
11730                         Base_Type (Etype (Left_Opnd (N2)))  = Etype (N2))
11731               and then Is_Intrinsic_Subprogram (E)
11732             then
11733                null;
11734
11735             else
11736                --  Entity is local. Mark generic node as unresolved.
11737                --  Note that now it does not have an entity.
11738
11739                Set_Associated_Node (N, Empty);
11740                Set_Etype  (N, Empty);
11741             end if;
11742
11743             if Nkind (Parent (N)) in N_Generic_Instantiation
11744               and then N = Name (Parent (N))
11745             then
11746                Save_Global_Defaults (Parent (N), Parent (N2));
11747             end if;
11748
11749          elsif Nkind (Parent (N)) = N_Selected_Component
11750            and then Nkind (Parent (N2)) = N_Expanded_Name
11751          then
11752             if Is_Global (Entity (Parent (N2))) then
11753                Change_Selected_Component_To_Expanded_Name (Parent (N));
11754                Set_Associated_Node (Parent (N), Parent (N2));
11755                Set_Global_Type (Parent (N), Parent (N2));
11756                Save_Entity_Descendants (N);
11757
11758             --  If this is a reference to the current generic entity, replace
11759             --  by the name of the generic homonym of the current package. This
11760             --  is because in an instantiation Par.P.Q will not resolve to the
11761             --  name of the instance, whose enclosing scope is not necessarily
11762             --  Par. We use the generic homonym rather that the name of the
11763             --  generic itself because it may be hidden by a local declaration.
11764
11765             elsif In_Open_Scopes (Entity (Parent (N2)))
11766               and then not
11767                 Is_Generic_Unit (Top_Ancestor (Entity (Prefix (Parent (N2)))))
11768             then
11769                if Ekind (Entity (Parent (N2))) = E_Generic_Package then
11770                   Rewrite (Parent (N),
11771                     Make_Identifier (Sloc (N),
11772                       Chars =>
11773                         Chars (Generic_Homonym (Entity (Parent (N2))))));
11774                else
11775                   Rewrite (Parent (N),
11776                     Make_Identifier (Sloc (N),
11777                       Chars => Chars (Selector_Name (Parent (N2)))));
11778                end if;
11779             end if;
11780
11781             if Nkind (Parent (Parent (N))) in N_Generic_Instantiation
11782               and then Parent (N) = Name (Parent (Parent (N)))
11783             then
11784                Save_Global_Defaults
11785                  (Parent (Parent (N)), Parent (Parent ((N2))));
11786             end if;
11787
11788          --  A selected component may denote a static constant that has been
11789          --  folded. If the static constant is global to the generic, capture
11790          --  its value. Otherwise the folding will happen in any instantiation.
11791
11792          elsif Nkind (Parent (N)) = N_Selected_Component
11793            and then Nkind_In (Parent (N2), N_Integer_Literal, N_Real_Literal)
11794          then
11795             if Present (Entity (Original_Node (Parent (N2))))
11796               and then Is_Global (Entity (Original_Node (Parent (N2))))
11797             then
11798                Rewrite (Parent (N), New_Copy (Parent (N2)));
11799                Set_Analyzed (Parent (N), False);
11800
11801             else
11802                null;
11803             end if;
11804
11805          --  A selected component may be transformed into a parameterless
11806          --  function call. If the called entity is global, rewrite the node
11807          --  appropriately, i.e. as an extended name for the global entity.
11808
11809          elsif Nkind (Parent (N)) = N_Selected_Component
11810            and then Nkind (Parent (N2)) = N_Function_Call
11811            and then N = Selector_Name (Parent (N))
11812          then
11813             if No (Parameter_Associations (Parent (N2))) then
11814                if Is_Global (Entity (Name (Parent (N2)))) then
11815                   Change_Selected_Component_To_Expanded_Name (Parent (N));
11816                   Set_Associated_Node (Parent (N), Name (Parent (N2)));
11817                   Set_Global_Type (Parent (N), Name (Parent (N2)));
11818                   Save_Entity_Descendants (N);
11819
11820                else
11821                   Set_Associated_Node (N, Empty);
11822                   Set_Etype (N, Empty);
11823                end if;
11824
11825             --  In Ada 2005, X.F may be a call to a primitive operation,
11826             --  rewritten as F (X). This rewriting will be done again in an
11827             --  instance, so keep the original node. Global entities will be
11828             --  captured as for other constructs.
11829
11830             else
11831                null;
11832             end if;
11833
11834          --  Entity is local. Reset in generic unit, so that node is resolved
11835          --  anew at the point of instantiation.
11836
11837          else
11838             Set_Associated_Node (N, Empty);
11839             Set_Etype (N, Empty);
11840          end if;
11841       end Reset_Entity;
11842
11843       -----------------------------
11844       -- Save_Entity_Descendants --
11845       -----------------------------
11846
11847       procedure Save_Entity_Descendants (N : Node_Id) is
11848       begin
11849          case Nkind (N) is
11850             when N_Binary_Op =>
11851                Save_Global_Descendant (Union_Id (Left_Opnd (N)));
11852                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
11853
11854             when N_Unary_Op =>
11855                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
11856
11857             when N_Expanded_Name | N_Selected_Component =>
11858                Save_Global_Descendant (Union_Id (Prefix (N)));
11859                Save_Global_Descendant (Union_Id (Selector_Name (N)));
11860
11861             when N_Identifier | N_Character_Literal | N_Operator_Symbol =>
11862                null;
11863
11864             when others =>
11865                raise Program_Error;
11866          end case;
11867       end Save_Entity_Descendants;
11868
11869       --------------------------
11870       -- Save_Global_Defaults --
11871       --------------------------
11872
11873       procedure Save_Global_Defaults (N1, N2 : Node_Id) is
11874          Loc    : constant Source_Ptr := Sloc (N1);
11875          Assoc2 : constant List_Id    := Generic_Associations (N2);
11876          Gen_Id : constant Entity_Id  := Get_Generic_Entity (N2);
11877          Assoc1 : List_Id;
11878          Act1   : Node_Id;
11879          Act2   : Node_Id;
11880          Def    : Node_Id;
11881          Ndec   : Node_Id;
11882          Subp   : Entity_Id;
11883          Actual : Entity_Id;
11884
11885       begin
11886          Assoc1 := Generic_Associations (N1);
11887
11888          if Present (Assoc1) then
11889             Act1 := First (Assoc1);
11890          else
11891             Act1 := Empty;
11892             Set_Generic_Associations (N1, New_List);
11893             Assoc1 := Generic_Associations (N1);
11894          end if;
11895
11896          if Present (Assoc2) then
11897             Act2 := First (Assoc2);
11898          else
11899             return;
11900          end if;
11901
11902          while Present (Act1) and then Present (Act2) loop
11903             Next (Act1);
11904             Next (Act2);
11905          end loop;
11906
11907          --  Find the associations added for default subprograms
11908
11909          if Present (Act2) then
11910             while Nkind (Act2) /= N_Generic_Association
11911               or else No (Entity (Selector_Name (Act2)))
11912               or else not Is_Overloadable (Entity (Selector_Name (Act2)))
11913             loop
11914                Next (Act2);
11915             end loop;
11916
11917             --  Add a similar association if the default is global. The
11918             --  renaming declaration for the actual has been analyzed, and
11919             --  its alias is the program it renames. Link the actual in the
11920             --  original generic tree with the node in the analyzed tree.
11921
11922             while Present (Act2) loop
11923                Subp := Entity (Selector_Name (Act2));
11924                Def  := Explicit_Generic_Actual_Parameter (Act2);
11925
11926                --  Following test is defence against rubbish errors
11927
11928                if No (Alias (Subp)) then
11929                   return;
11930                end if;
11931
11932                --  Retrieve the resolved actual from the renaming declaration
11933                --  created for the instantiated formal.
11934
11935                Actual := Entity (Name (Parent (Parent (Subp))));
11936                Set_Entity (Def, Actual);
11937                Set_Etype (Def, Etype (Actual));
11938
11939                if Is_Global (Actual) then
11940                   Ndec :=
11941                     Make_Generic_Association (Loc,
11942                       Selector_Name => New_Occurrence_Of (Subp, Loc),
11943                         Explicit_Generic_Actual_Parameter =>
11944                           New_Occurrence_Of (Actual, Loc));
11945
11946                   Set_Associated_Node
11947                     (Explicit_Generic_Actual_Parameter (Ndec), Def);
11948
11949                   Append (Ndec, Assoc1);
11950
11951                --  If there are other defaults, add a dummy association in case
11952                --  there are other defaulted formals with the same name.
11953
11954                elsif Present (Next (Act2)) then
11955                   Ndec :=
11956                     Make_Generic_Association (Loc,
11957                       Selector_Name => New_Occurrence_Of (Subp, Loc),
11958                         Explicit_Generic_Actual_Parameter => Empty);
11959
11960                   Append (Ndec, Assoc1);
11961                end if;
11962
11963                Next (Act2);
11964             end loop;
11965          end if;
11966
11967          if Nkind (Name (N1)) = N_Identifier
11968            and then Is_Child_Unit (Gen_Id)
11969            and then Is_Global (Gen_Id)
11970            and then Is_Generic_Unit (Scope (Gen_Id))
11971            and then In_Open_Scopes (Scope (Gen_Id))
11972          then
11973             --  This is an instantiation of a child unit within a sibling, so
11974             --  that the generic parent is in scope. An eventual instance must
11975             --  occur within the scope of an instance of the parent. Make name
11976             --  in instance into an expanded name, to preserve the identifier
11977             --  of the parent, so it can be resolved subsequently.
11978
11979             Rewrite (Name (N2),
11980               Make_Expanded_Name (Loc,
11981                 Chars         => Chars (Gen_Id),
11982                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
11983                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
11984             Set_Entity (Name (N2), Gen_Id);
11985
11986             Rewrite (Name (N1),
11987                Make_Expanded_Name (Loc,
11988                 Chars         => Chars (Gen_Id),
11989                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
11990                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
11991
11992             Set_Associated_Node (Name (N1), Name (N2));
11993             Set_Associated_Node (Prefix (Name (N1)), Empty);
11994             Set_Associated_Node
11995               (Selector_Name (Name (N1)), Selector_Name (Name (N2)));
11996             Set_Etype (Name (N1), Etype (Gen_Id));
11997          end if;
11998
11999       end Save_Global_Defaults;
12000
12001       ----------------------------
12002       -- Save_Global_Descendant --
12003       ----------------------------
12004
12005       procedure Save_Global_Descendant (D : Union_Id) is
12006          N1 : Node_Id;
12007
12008       begin
12009          if D in Node_Range then
12010             if D = Union_Id (Empty) then
12011                null;
12012
12013             elsif Nkind (Node_Id (D)) /= N_Compilation_Unit then
12014                Save_References (Node_Id (D));
12015             end if;
12016
12017          elsif D in List_Range then
12018             if D = Union_Id (No_List)
12019               or else Is_Empty_List (List_Id (D))
12020             then
12021                null;
12022
12023             else
12024                N1 := First (List_Id (D));
12025                while Present (N1) loop
12026                   Save_References (N1);
12027                   Next (N1);
12028                end loop;
12029             end if;
12030
12031          --  Element list or other non-node field, nothing to do
12032
12033          else
12034             null;
12035          end if;
12036       end Save_Global_Descendant;
12037
12038       ---------------------
12039       -- Save_References --
12040       ---------------------
12041
12042       --  This is the recursive procedure that does the work once the enclosing
12043       --  generic scope has been established. We have to treat specially a
12044       --  number of node rewritings that are required by semantic processing
12045       --  and which change the kind of nodes in the generic copy: typically
12046       --  constant-folding, replacing an operator node by a string literal, or
12047       --  a selected component by an expanded name. In each of those cases, the
12048       --  transformation is propagated to the generic unit.
12049
12050       procedure Save_References (N : Node_Id) is
12051          Loc : constant Source_Ptr := Sloc (N);
12052
12053       begin
12054          if N = Empty then
12055             null;
12056
12057          elsif Nkind_In (N, N_Character_Literal, N_Operator_Symbol) then
12058             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
12059                Reset_Entity (N);
12060
12061             elsif Nkind (N) = N_Operator_Symbol
12062               and then Nkind (Get_Associated_Node (N)) = N_String_Literal
12063             then
12064                Change_Operator_Symbol_To_String_Literal (N);
12065             end if;
12066
12067          elsif Nkind (N) in N_Op then
12068             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
12069                if Nkind (N) = N_Op_Concat then
12070                   Set_Is_Component_Left_Opnd (N,
12071                     Is_Component_Left_Opnd (Get_Associated_Node (N)));
12072
12073                   Set_Is_Component_Right_Opnd (N,
12074                     Is_Component_Right_Opnd (Get_Associated_Node (N)));
12075                end if;
12076
12077                Reset_Entity (N);
12078
12079             else
12080                --  Node may be transformed into call to a user-defined operator
12081
12082                N2 := Get_Associated_Node (N);
12083
12084                if Nkind (N2) = N_Function_Call then
12085                   E := Entity (Name (N2));
12086
12087                   if Present (E)
12088                     and then Is_Global (E)
12089                   then
12090                      Set_Etype (N, Etype (N2));
12091                   else
12092                      Set_Associated_Node (N, Empty);
12093                      Set_Etype (N, Empty);
12094                   end if;
12095
12096                elsif Nkind_In (N2, N_Integer_Literal,
12097                                    N_Real_Literal,
12098                                    N_String_Literal)
12099                then
12100                   if Present (Original_Node (N2))
12101                     and then Nkind (Original_Node (N2)) = Nkind (N)
12102                   then
12103
12104                      --  Operation was constant-folded. Whenever possible,
12105                      --  recover semantic information from unfolded node,
12106                      --  for ASIS use.
12107
12108                      Set_Associated_Node (N, Original_Node (N2));
12109
12110                      if Nkind (N) = N_Op_Concat then
12111                         Set_Is_Component_Left_Opnd (N,
12112                           Is_Component_Left_Opnd  (Get_Associated_Node (N)));
12113                         Set_Is_Component_Right_Opnd (N,
12114                           Is_Component_Right_Opnd (Get_Associated_Node (N)));
12115                      end if;
12116
12117                      Reset_Entity (N);
12118
12119                   else
12120                      --  If original node is already modified, propagate
12121                      --  constant-folding to template.
12122
12123                      Rewrite (N, New_Copy (N2));
12124                      Set_Analyzed (N, False);
12125                   end if;
12126
12127                elsif Nkind (N2) = N_Identifier
12128                  and then Ekind (Entity (N2)) = E_Enumeration_Literal
12129                then
12130                   --  Same if call was folded into a literal, but in this case
12131                   --  retain the entity to avoid spurious ambiguities if it is
12132                   --  overloaded at the point of instantiation or inlining.
12133
12134                   Rewrite (N, New_Copy (N2));
12135                   Set_Analyzed (N, False);
12136                end if;
12137             end if;
12138
12139             --  Complete operands check if node has not been constant-folded
12140
12141             if Nkind (N) in N_Op then
12142                Save_Entity_Descendants (N);
12143             end if;
12144
12145          elsif Nkind (N) = N_Identifier then
12146             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
12147
12148                --  If this is a discriminant reference, always save it. It is
12149                --  used in the instance to find the corresponding discriminant
12150                --  positionally rather than by name.
12151
12152                Set_Original_Discriminant
12153                  (N, Original_Discriminant (Get_Associated_Node (N)));
12154                Reset_Entity (N);
12155
12156             else
12157                N2 := Get_Associated_Node (N);
12158
12159                if Nkind (N2) = N_Function_Call then
12160                   E := Entity (Name (N2));
12161
12162                   --  Name resolves to a call to parameterless function. If
12163                   --  original entity is global, mark node as resolved.
12164
12165                   if Present (E)
12166                     and then Is_Global (E)
12167                   then
12168                      Set_Etype (N, Etype (N2));
12169                   else
12170                      Set_Associated_Node (N, Empty);
12171                      Set_Etype (N, Empty);
12172                   end if;
12173
12174                elsif Nkind_In (N2, N_Integer_Literal, N_Real_Literal)
12175                  and then Is_Entity_Name (Original_Node (N2))
12176                then
12177                   --  Name resolves to named number that is constant-folded,
12178                   --  We must preserve the original name for ASIS use, and
12179                   --  undo the constant-folding, which will be repeated in
12180                   --  each instance.
12181
12182                   Set_Associated_Node (N, Original_Node (N2));
12183                   Reset_Entity (N);
12184
12185                elsif Nkind (N2) = N_String_Literal then
12186
12187                   --  Name resolves to string literal. Perform the same
12188                   --  replacement in generic.
12189
12190                   Rewrite (N, New_Copy (N2));
12191
12192                elsif Nkind (N2) = N_Explicit_Dereference then
12193
12194                   --  An identifier is rewritten as a dereference if it is the
12195                   --  prefix in an implicit dereference (call or attribute).
12196                   --  The analysis of an instantiation will expand the node
12197                   --  again, so we preserve the original tree but link it to
12198                   --  the resolved entity in case it is global.
12199
12200                   if Is_Entity_Name (Prefix (N2))
12201                     and then Present (Entity (Prefix (N2)))
12202                     and then Is_Global (Entity (Prefix (N2)))
12203                   then
12204                      Set_Associated_Node (N, Prefix (N2));
12205
12206                   elsif Nkind (Prefix (N2)) = N_Function_Call
12207                     and then Is_Global (Entity (Name (Prefix (N2))))
12208                   then
12209                      Rewrite (N,
12210                        Make_Explicit_Dereference (Loc,
12211                           Prefix => Make_Function_Call (Loc,
12212                             Name =>
12213                               New_Occurrence_Of (Entity (Name (Prefix (N2))),
12214                                                  Loc))));
12215
12216                   else
12217                      Set_Associated_Node (N, Empty);
12218                      Set_Etype (N, Empty);
12219                   end if;
12220
12221                --  The subtype mark of a nominally unconstrained object is
12222                --  rewritten as a subtype indication using the bounds of the
12223                --  expression. Recover the original subtype mark.
12224
12225                elsif Nkind (N2) = N_Subtype_Indication
12226                  and then Is_Entity_Name (Original_Node (N2))
12227                then
12228                   Set_Associated_Node (N, Original_Node (N2));
12229                   Reset_Entity (N);
12230
12231                else
12232                   null;
12233                end if;
12234             end if;
12235
12236          elsif Nkind (N) in N_Entity then
12237             null;
12238
12239          else
12240             declare
12241                Qual : Node_Id := Empty;
12242                Typ  : Entity_Id := Empty;
12243                Nam  : Node_Id;
12244
12245                use Atree.Unchecked_Access;
12246                --  This code section is part of implementing an untyped tree
12247                --  traversal, so it needs direct access to node fields.
12248
12249             begin
12250                if Nkind_In (N, N_Aggregate, N_Extension_Aggregate) then
12251                   N2 := Get_Associated_Node (N);
12252
12253                   if No (N2) then
12254                      Typ := Empty;
12255                   else
12256                      Typ := Etype (N2);
12257
12258                      --  In an instance within a generic, use the name of the
12259                      --  actual and not the original generic parameter. If the
12260                      --  actual is global in the current generic it must be
12261                      --  preserved for its instantiation.
12262
12263                      if Nkind (Parent (Typ)) = N_Subtype_Declaration
12264                        and then
12265                          Present (Generic_Parent_Type (Parent (Typ)))
12266                      then
12267                         Typ := Base_Type (Typ);
12268                         Set_Etype (N2, Typ);
12269                      end if;
12270                   end if;
12271
12272                   if No (N2)
12273                     or else No (Typ)
12274                     or else not Is_Global (Typ)
12275                   then
12276                      Set_Associated_Node (N, Empty);
12277
12278                      --  If the aggregate is an actual in a call, it has been
12279                      --  resolved in the current context, to some local type.
12280                      --  The enclosing call may have been disambiguated by the
12281                      --  aggregate, and this disambiguation might fail at
12282                      --  instantiation time because the type to which the
12283                      --  aggregate did resolve is not preserved. In order to
12284                      --  preserve some of this information, we wrap the
12285                      --  aggregate in a qualified expression, using the id of
12286                      --  its type. For further disambiguation we qualify the
12287                      --  type name with its scope (if visible) because both
12288                      --  id's will have corresponding entities in an instance.
12289                      --  This resolves most of the problems with missing type
12290                      --  information on aggregates in instances.
12291
12292                      if Nkind (N2) = Nkind (N)
12293                        and then
12294                          Nkind_In (Parent (N2), N_Procedure_Call_Statement,
12295                                                 N_Function_Call)
12296                        and then Comes_From_Source (Typ)
12297                      then
12298                         if Is_Immediately_Visible (Scope (Typ)) then
12299                            Nam := Make_Selected_Component (Loc,
12300                              Prefix =>
12301                                Make_Identifier (Loc, Chars (Scope (Typ))),
12302                              Selector_Name =>
12303                                Make_Identifier (Loc, Chars (Typ)));
12304                         else
12305                            Nam := Make_Identifier (Loc, Chars (Typ));
12306                         end if;
12307
12308                         Qual :=
12309                           Make_Qualified_Expression (Loc,
12310                             Subtype_Mark => Nam,
12311                             Expression => Relocate_Node (N));
12312                      end if;
12313                   end if;
12314
12315                   Save_Global_Descendant (Field1 (N));
12316                   Save_Global_Descendant (Field2 (N));
12317                   Save_Global_Descendant (Field3 (N));
12318                   Save_Global_Descendant (Field5 (N));
12319
12320                   if Present (Qual) then
12321                      Rewrite (N, Qual);
12322                   end if;
12323
12324                --  All other cases than aggregates
12325
12326                else
12327                   --  For pragmas, we propagate the Enabled status for the
12328                   --  relevant pragmas to the original generic tree. This was
12329                   --  originally needed for SCO generation. It is no longer
12330                   --  needed there (since we use the Sloc value in calls to
12331                   --  Set_SCO_Pragma_Enabled), but it seems a generally good
12332                   --  idea to have this flag set properly.
12333
12334                   if Nkind (N) = N_Pragma
12335                     and then
12336                       (Pragma_Name (N) = Name_Assert       or else
12337                        Pragma_Name (N) = Name_Check        or else
12338                        Pragma_Name (N) = Name_Precondition or else
12339                        Pragma_Name (N) = Name_Postcondition)
12340                     and then Present (Associated_Node (Pragma_Identifier (N)))
12341                   then
12342                      Set_Pragma_Enabled (N,
12343                        Pragma_Enabled
12344                          (Parent (Associated_Node (Pragma_Identifier (N)))));
12345                   end if;
12346
12347                   Save_Global_Descendant (Field1 (N));
12348                   Save_Global_Descendant (Field2 (N));
12349                   Save_Global_Descendant (Field3 (N));
12350                   Save_Global_Descendant (Field4 (N));
12351                   Save_Global_Descendant (Field5 (N));
12352                end if;
12353             end;
12354          end if;
12355       end Save_References;
12356
12357    --  Start of processing for Save_Global_References
12358
12359    begin
12360       Gen_Scope := Current_Scope;
12361
12362       --  If the generic unit is a child unit, references to entities in the
12363       --  parent are treated as local, because they will be resolved anew in
12364       --  the context of the instance of the parent.
12365
12366       while Is_Child_Unit (Gen_Scope)
12367         and then Ekind (Scope (Gen_Scope)) = E_Generic_Package
12368       loop
12369          Gen_Scope := Scope (Gen_Scope);
12370       end loop;
12371
12372       Save_References (N);
12373    end Save_Global_References;
12374
12375    --------------------------------------
12376    -- Set_Copied_Sloc_For_Inlined_Body --
12377    --------------------------------------
12378
12379    procedure Set_Copied_Sloc_For_Inlined_Body (N : Node_Id; E : Entity_Id) is
12380    begin
12381       Create_Instantiation_Source (N, E, True, S_Adjustment);
12382    end Set_Copied_Sloc_For_Inlined_Body;
12383
12384    ---------------------
12385    -- Set_Instance_Of --
12386    ---------------------
12387
12388    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id) is
12389    begin
12390       Generic_Renamings.Table (Generic_Renamings.Last) := (A, B, Assoc_Null);
12391       Generic_Renamings_HTable.Set (Generic_Renamings.Last);
12392       Generic_Renamings.Increment_Last;
12393    end Set_Instance_Of;
12394
12395    --------------------
12396    -- Set_Next_Assoc --
12397    --------------------
12398
12399    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr) is
12400    begin
12401       Generic_Renamings.Table (E).Next_In_HTable := Next;
12402    end Set_Next_Assoc;
12403
12404    -------------------
12405    -- Start_Generic --
12406    -------------------
12407
12408    procedure Start_Generic is
12409    begin
12410       --  ??? More things could be factored out in this routine.
12411       --  Should probably be done at a later stage.
12412
12413       Generic_Flags.Append (Inside_A_Generic);
12414       Inside_A_Generic := True;
12415
12416       Expander_Mode_Save_And_Set (False);
12417    end Start_Generic;
12418
12419    ----------------------
12420    -- Set_Instance_Env --
12421    ----------------------
12422
12423    procedure Set_Instance_Env
12424      (Gen_Unit : Entity_Id;
12425       Act_Unit : Entity_Id)
12426    is
12427    begin
12428       --  Regardless of the current mode, predefined units are analyzed in the
12429       --  most current Ada mode, and earlier version Ada checks do not apply
12430       --  to predefined units. Nothing needs to be done for non-internal units.
12431       --  These are always analyzed in the current mode.
12432
12433       if Is_Internal_File_Name
12434            (Fname              => Unit_File_Name (Get_Source_Unit (Gen_Unit)),
12435             Renamings_Included => True)
12436       then
12437          Set_Opt_Config_Switches (True, Current_Sem_Unit = Main_Unit);
12438       end if;
12439
12440       Current_Instantiated_Parent :=
12441         (Gen_Id         => Gen_Unit,
12442          Act_Id         => Act_Unit,
12443          Next_In_HTable => Assoc_Null);
12444    end Set_Instance_Env;
12445
12446    -----------------
12447    -- Switch_View --
12448    -----------------
12449
12450    procedure Switch_View (T : Entity_Id) is
12451       BT        : constant Entity_Id := Base_Type (T);
12452       Priv_Elmt : Elmt_Id := No_Elmt;
12453       Priv_Sub  : Entity_Id;
12454
12455    begin
12456       --  T may be private but its base type may have been exchanged through
12457       --  some other occurrence, in which case there is nothing to switch
12458       --  besides T itself. Note that a private dependent subtype of a private
12459       --  type might not have been switched even if the base type has been,
12460       --  because of the last branch of Check_Private_View (see comment there).
12461
12462       if not Is_Private_Type (BT) then
12463          Prepend_Elmt (Full_View (T), Exchanged_Views);
12464          Exchange_Declarations (T);
12465          return;
12466       end if;
12467
12468       Priv_Elmt := First_Elmt (Private_Dependents (BT));
12469
12470       if Present (Full_View (BT)) then
12471          Prepend_Elmt (Full_View (BT), Exchanged_Views);
12472          Exchange_Declarations (BT);
12473       end if;
12474
12475       while Present (Priv_Elmt) loop
12476          Priv_Sub := (Node (Priv_Elmt));
12477
12478          --  We avoid flipping the subtype if the Etype of its full view is
12479          --  private because this would result in a malformed subtype. This
12480          --  occurs when the Etype of the subtype full view is the full view of
12481          --  the base type (and since the base types were just switched, the
12482          --  subtype is pointing to the wrong view). This is currently the case
12483          --  for tagged record types, access types (maybe more?) and needs to
12484          --  be resolved. ???
12485
12486          if Present (Full_View (Priv_Sub))
12487            and then not Is_Private_Type (Etype (Full_View (Priv_Sub)))
12488          then
12489             Prepend_Elmt (Full_View (Priv_Sub), Exchanged_Views);
12490             Exchange_Declarations (Priv_Sub);
12491          end if;
12492
12493          Next_Elmt (Priv_Elmt);
12494       end loop;
12495    end Switch_View;
12496
12497    -----------------------------
12498    -- Valid_Default_Attribute --
12499    -----------------------------
12500
12501    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id) is
12502       Attr_Id : constant Attribute_Id :=
12503                   Get_Attribute_Id (Attribute_Name (Def));
12504       T       : constant Entity_Id := Entity (Prefix (Def));
12505       Is_Fun  : constant Boolean := (Ekind (Nam) = E_Function);
12506       F       : Entity_Id;
12507       Num_F   : Int;
12508       OK      : Boolean;
12509
12510    begin
12511       if No (T)
12512         or else T = Any_Id
12513       then
12514          return;
12515       end if;
12516
12517       Num_F := 0;
12518       F := First_Formal (Nam);
12519       while Present (F) loop
12520          Num_F := Num_F + 1;
12521          Next_Formal (F);
12522       end loop;
12523
12524       case Attr_Id is
12525          when Attribute_Adjacent |  Attribute_Ceiling   | Attribute_Copy_Sign |
12526               Attribute_Floor    |  Attribute_Fraction  | Attribute_Machine   |
12527               Attribute_Model    |  Attribute_Remainder | Attribute_Rounding  |
12528               Attribute_Unbiased_Rounding  =>
12529             OK := Is_Fun
12530                     and then Num_F = 1
12531                     and then Is_Floating_Point_Type (T);
12532
12533          when Attribute_Image    | Attribute_Pred       | Attribute_Succ |
12534               Attribute_Value    | Attribute_Wide_Image |
12535               Attribute_Wide_Value  =>
12536             OK := (Is_Fun and then Num_F = 1 and then Is_Scalar_Type (T));
12537
12538          when Attribute_Max      |  Attribute_Min  =>
12539             OK := (Is_Fun and then Num_F = 2 and then Is_Scalar_Type (T));
12540
12541          when Attribute_Input =>
12542             OK := (Is_Fun and then Num_F = 1);
12543
12544          when Attribute_Output | Attribute_Read | Attribute_Write =>
12545             OK := (not Is_Fun and then Num_F = 2);
12546
12547          when others =>
12548             OK := False;
12549       end case;
12550
12551       if not OK then
12552          Error_Msg_N ("attribute reference has wrong profile for subprogram",
12553            Def);
12554       end if;
12555    end Valid_Default_Attribute;
12556
12557 end Sem_Ch12;