OSDN Git Service

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