OSDN Git Service

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