OSDN Git Service

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