OSDN Git Service

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