OSDN Git Service

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