OSDN Git Service

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