OSDN Git Service

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