OSDN Git Service

2011-08-03 Yannick Moy <moy@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch9.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 9                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Einfo;    use Einfo;
29 with Elists;   use Elists;
30 with Errout;   use Errout;
31 with Exp_Ch3;  use Exp_Ch3;
32 with Exp_Ch6;  use Exp_Ch6;
33 with Exp_Ch11; use Exp_Ch11;
34 with Exp_Dbug; use Exp_Dbug;
35 with Exp_Disp; use Exp_Disp;
36 with Exp_Sel;  use Exp_Sel;
37 with Exp_Smem; use Exp_Smem;
38 with Exp_Tss;  use Exp_Tss;
39 with Exp_Util; use Exp_Util;
40 with Freeze;   use Freeze;
41 with Hostparm;
42 with Itypes;   use Itypes;
43 with Namet;    use Namet;
44 with Nlists;   use Nlists;
45 with Nmake;    use Nmake;
46 with Opt;      use Opt;
47 with Restrict; use Restrict;
48 with Rident;   use Rident;
49 with Rtsfind;  use Rtsfind;
50 with Sem;      use Sem;
51 with Sem_Aux;  use Sem_Aux;
52 with Sem_Ch6;  use Sem_Ch6;
53 with Sem_Ch8;  use Sem_Ch8;
54 with Sem_Ch11; use Sem_Ch11;
55 with Sem_Elab; use Sem_Elab;
56 with Sem_Eval; use Sem_Eval;
57 with Sem_Res;  use Sem_Res;
58 with Sem_Util; use Sem_Util;
59 with Sinfo;    use Sinfo;
60 with Snames;   use Snames;
61 with Stand;    use Stand;
62 with Stringt;  use Stringt;
63 with Targparm; use Targparm;
64 with Tbuild;   use Tbuild;
65 with Uintp;    use Uintp;
66
67 package body Exp_Ch9 is
68
69    --  The following constant establishes the upper bound for the index of
70    --  an entry family. It is used to limit the allocated size of protected
71    --  types with defaulted discriminant of an integer type, when the bound
72    --  of some entry family depends on a discriminant. The limitation to
73    --  entry families of 128K should be reasonable in all cases, and is a
74    --  documented implementation restriction. It will be lifted when protected
75    --  entry families are re-implemented as a single ordered queue.
76
77    Entry_Family_Bound : constant Int := 2**16;
78
79    -----------------------
80    -- Local Subprograms --
81    -----------------------
82
83    function Actual_Index_Expression
84      (Sloc  : Source_Ptr;
85       Ent   : Entity_Id;
86       Index : Node_Id;
87       Tsk   : Entity_Id) return Node_Id;
88    --  Compute the index position for an entry call. Tsk is the target task. If
89    --  the bounds of some entry family depend on discriminants, the expression
90    --  computed by this function uses the discriminants of the target task.
91
92    procedure Add_Object_Pointer
93      (Loc      : Source_Ptr;
94       Conc_Typ : Entity_Id;
95       Decls    : List_Id);
96    --  Prepend an object pointer declaration to the declaration list Decls.
97    --  This object pointer is initialized to a type conversion of the System.
98    --  Address pointer passed to entry barrier functions and entry body
99    --  procedures.
100
101    procedure Add_Formal_Renamings
102      (Spec  : Node_Id;
103       Decls : List_Id;
104       Ent   : Entity_Id;
105       Loc   : Source_Ptr);
106    --  Create renaming declarations for the formals, inside the procedure that
107    --  implements an entry body. The renamings make the original names of the
108    --  formals accessible to gdb, and serve no other purpose.
109    --    Spec is the specification of the procedure being built.
110    --    Decls is the list of declarations to be enhanced.
111    --    Ent is the entity for the original entry body.
112
113    function Build_Accept_Body (Astat : Node_Id) return Node_Id;
114    --  Transform accept statement into a block with added exception handler.
115    --  Used both for simple accept statements and for accept alternatives in
116    --  select statements. Astat is the accept statement.
117
118    function Build_Barrier_Function
119      (N   : Node_Id;
120       Ent : Entity_Id;
121       Pid : Node_Id) return Node_Id;
122    --  Build the function body returning the value of the barrier expression
123    --  for the specified entry body.
124
125    function Build_Barrier_Function_Specification
126      (Loc    : Source_Ptr;
127       Def_Id : Entity_Id) return Node_Id;
128    --  Build a specification for a function implementing the protected entry
129    --  barrier of the specified entry body.
130
131    function Build_Corresponding_Record
132      (N    : Node_Id;
133       Ctyp : Node_Id;
134       Loc  : Source_Ptr) return Node_Id;
135    --  Common to tasks and protected types. Copy discriminant specifications,
136    --  build record declaration. N is the type declaration, Ctyp is the
137    --  concurrent entity (task type or protected type).
138
139    function Build_Entry_Count_Expression
140      (Concurrent_Type : Node_Id;
141       Component_List  : List_Id;
142       Loc             : Source_Ptr) return Node_Id;
143    --  Compute number of entries for concurrent object. This is a count of
144    --  simple entries, followed by an expression that computes the length
145    --  of the range of each entry family. A single array with that size is
146    --  allocated for each concurrent object of the type.
147
148    function Build_Parameter_Block
149      (Loc     : Source_Ptr;
150       Actuals : List_Id;
151       Formals : List_Id;
152       Decls   : List_Id) return Entity_Id;
153    --  Generate an access type for each actual parameter in the list Actuals.
154    --  Create an encapsulating record that contains all the actuals and return
155    --  its type. Generate:
156    --    type Ann1 is access all <actual1-type>
157    --    ...
158    --    type AnnN is access all <actualN-type>
159    --    type Pnn is record
160    --       <formal1> : Ann1;
161    --       ...
162    --       <formalN> : AnnN;
163    --    end record;
164
165    procedure Build_PPC_Wrapper (E : Entity_Id; Decl : Node_Id);
166    --  Build body of wrapper procedure for an entry or entry family that has
167    --  pre/postconditions. The body gathers the PPC's and expands them in the
168    --  usual way, and performs the entry call itself. This way preconditions
169    --  are evaluated before the call is queued. E is the entry in question,
170    --  and Decl is the enclosing synchronized type declaration at whose
171    --  freeze point the generated body is analyzed.
172
173    function Build_Renamed_Formal_Declaration
174      (New_F          : Entity_Id;
175       Formal         : Entity_Id;
176       Comp           : Entity_Id;
177       Renamed_Formal : Node_Id) return Node_Id;
178    --  Create a renaming declaration for a formal, within a protected entry
179    --  body or an accept body. The renamed object is a component of the
180    --  parameter block that is a parameter in the entry call.
181
182    --  In Ada2012,  If the formal is an incomplete tagged type, the renaming
183    --  does not dereference the corresponding component to prevent an illegal
184    --  use of the incomplete type (AI05-0151).
185
186    procedure Build_Wrapper_Bodies
187      (Loc : Source_Ptr;
188       Typ : Entity_Id;
189       N   : Node_Id);
190    --  Ada 2005 (AI-345): Typ is either a concurrent type or the corresponding
191    --  record of a concurrent type. N is the insertion node where all bodies
192    --  will be placed. This routine builds the bodies of the subprograms which
193    --  serve as an indirection mechanism to overriding primitives of concurrent
194    --  types, entries and protected procedures. Any new body is analyzed.
195
196    procedure Build_Wrapper_Specs
197      (Loc : Source_Ptr;
198       Typ : Entity_Id;
199       N   : in out Node_Id);
200    --  Ada 2005 (AI-345): Typ is either a concurrent type or the corresponding
201    --  record of a concurrent type. N is the insertion node where all specs
202    --  will be placed. This routine builds the specs of the subprograms which
203    --  serve as an indirection mechanism to overriding primitives of concurrent
204    --  types, entries and protected procedures. Any new spec is analyzed.
205
206    function Build_Find_Body_Index (Typ : Entity_Id) return Node_Id;
207    --  Build the function that translates the entry index in the call
208    --  (which depends on the size of entry families) into an index into the
209    --  Entry_Bodies_Array, to determine the body and barrier function used
210    --  in a protected entry call. A pointer to this function appears in every
211    --  protected object.
212
213    function Build_Find_Body_Index_Spec (Typ : Entity_Id) return Node_Id;
214    --  Build subprogram declaration for previous one
215
216    function Build_Protected_Entry
217      (N   : Node_Id;
218       Ent : Entity_Id;
219       Pid : Node_Id) return Node_Id;
220    --  Build the procedure implementing the statement sequence of the specified
221    --  entry body.
222
223    function Build_Protected_Entry_Specification
224      (Loc    : Source_Ptr;
225       Def_Id : Entity_Id;
226       Ent_Id : Entity_Id) return Node_Id;
227    --  Build a specification for the procedure implementing the statements of
228    --  the specified entry body. Add attributes associating it with the entry
229    --  defining identifier Ent_Id.
230
231    function Build_Protected_Spec
232      (N           : Node_Id;
233       Obj_Type    : Entity_Id;
234       Ident       : Entity_Id;
235       Unprotected : Boolean := False) return List_Id;
236    --  Utility shared by Build_Protected_Sub_Spec and Expand_Access_Protected_
237    --  Subprogram_Type. Builds signature of protected subprogram, adding the
238    --  formal that corresponds to the object itself. For an access to protected
239    --  subprogram, there is no object type to specify, so the parameter has
240    --  type Address and mode In. An indirect call through such a pointer will
241    --  convert the address to a reference to the actual object. The object is
242    --  a limited record and therefore a by_reference type.
243
244    function Build_Protected_Subprogram_Body
245      (N         : Node_Id;
246       Pid       : Node_Id;
247       N_Op_Spec : Node_Id) return Node_Id;
248    --  This function is used to construct the protected version of a protected
249    --  subprogram. Its statement sequence first defers abort, then locks
250    --  the associated protected object, and then enters a block that contains
251    --  a call to the unprotected version of the subprogram (for details, see
252    --  Build_Unprotected_Subprogram_Body). This block statement requires
253    --  a cleanup handler that unlocks the object in all cases.
254    --  (see Exp_Ch7.Expand_Cleanup_Actions).
255
256    function Build_Selected_Name
257      (Prefix      : Entity_Id;
258       Selector    : Entity_Id;
259       Append_Char : Character := ' ') return Name_Id;
260    --  Build a name in the form of Prefix__Selector, with an optional
261    --  character appended. This is used for internal subprograms generated
262    --  for operations of protected types, including barrier functions.
263    --  For the subprograms generated for entry bodies and entry barriers,
264    --  the generated name includes a sequence number that makes names
265    --  unique in the presence of entry overloading. This is necessary
266    --  because entry body procedures and barrier functions all have the
267    --  same signature.
268
269    procedure Build_Simple_Entry_Call
270      (N       : Node_Id;
271       Concval : Node_Id;
272       Ename   : Node_Id;
273       Index   : Node_Id);
274    --  Some comments here would be useful ???
275
276    function Build_Task_Proc_Specification (T : Entity_Id) return Node_Id;
277    --  This routine constructs a specification for the procedure that we will
278    --  build for the task body for task type T. The spec has the form:
279    --
280    --    procedure tnameB (_Task : access tnameV);
281    --
282    --  where name is the character name taken from the task type entity that
283    --  is passed as the argument to the procedure, and tnameV is the task
284    --  value type that is associated with the task type.
285
286    function Build_Unprotected_Subprogram_Body
287      (N   : Node_Id;
288       Pid : Node_Id) return Node_Id;
289    --  This routine constructs the unprotected version of a protected
290    --  subprogram body, which is contains all of the code in the
291    --  original, unexpanded body. This is the version of the protected
292    --  subprogram that is called from all protected operations on the same
293    --  object, including the protected version of the same subprogram.
294
295    procedure Collect_Entry_Families
296      (Loc          : Source_Ptr;
297       Cdecls       : List_Id;
298       Current_Node : in out Node_Id;
299       Conctyp      : Entity_Id);
300    --  For each entry family in a concurrent type, create an anonymous array
301    --  type of the right size, and add a component to the corresponding_record.
302
303    function Concurrent_Object
304      (Spec_Id  : Entity_Id;
305       Conc_Typ : Entity_Id) return Entity_Id;
306    --  Given a subprogram entity Spec_Id and concurrent type Conc_Typ, return
307    --  the entity associated with the concurrent object in the Protected_Body_
308    --  Subprogram or the Task_Body_Procedure of Spec_Id. The returned entity
309    --  denotes formal parameter _O, _object or _task.
310
311    function Copy_Result_Type (Res : Node_Id) return Node_Id;
312    --  Copy the result type of a function specification, when building the
313    --  internal operation corresponding to a protected function, or when
314    --  expanding an access to protected function. If the result is an anonymous
315    --  access to subprogram itself, we need to create a new signature with the
316    --  same parameter names and the same resolved types, but with new entities
317    --  for the formals.
318
319    procedure Debug_Private_Data_Declarations (Decls : List_Id);
320    --  Decls is a list which may contain the declarations created by Install_
321    --  Private_Data_Declarations. All generated entities are marked as needing
322    --  debug info and debug nodes are manually generation where necessary. This
323    --  step of the expansion must to be done after private data has been moved
324    --  to its final resting scope to ensure proper visibility of debug objects.
325
326    function Family_Offset
327      (Loc  : Source_Ptr;
328       Hi   : Node_Id;
329       Lo   : Node_Id;
330       Ttyp : Entity_Id;
331       Cap  : Boolean) return Node_Id;
332    --  Compute (Hi - Lo) for two entry family indexes. Hi is the index in
333    --  an accept statement, or the upper bound in the discrete subtype of
334    --  an entry declaration. Lo is the corresponding lower bound. Ttyp is
335    --  the concurrent type of the entry. If Cap is true, the result is
336    --  capped according to Entry_Family_Bound.
337
338    function Family_Size
339      (Loc  : Source_Ptr;
340       Hi   : Node_Id;
341       Lo   : Node_Id;
342       Ttyp : Entity_Id;
343       Cap  : Boolean) return Node_Id;
344    --  Compute (Hi - Lo) + 1 Max 0, to determine the number of entries in
345    --  a family, and handle properly the superflat case. This is equivalent
346    --  to the use of 'Length on the index type, but must use Family_Offset
347    --  to handle properly the case of bounds that depend on discriminants.
348    --  If Cap is true, the result is capped according to Entry_Family_Bound.
349
350    procedure Extract_Dispatching_Call
351      (N        : Node_Id;
352       Call_Ent : out Entity_Id;
353       Object   : out Entity_Id;
354       Actuals  : out List_Id;
355       Formals  : out List_Id);
356    --  Given a dispatching call, extract the entity of the name of the call,
357    --  its actual dispatching object, its actual parameters and the formal
358    --  parameters of the overridden interface-level version. If the type of
359    --  the dispatching object is an access type then an explicit dereference
360    --  is returned in Object.
361
362    procedure Extract_Entry
363      (N       : Node_Id;
364       Concval : out Node_Id;
365       Ename   : out Node_Id;
366       Index   : out Node_Id);
367    --  Given an entry call, returns the associated concurrent object,
368    --  the entry name, and the entry family index.
369
370    function Find_Task_Or_Protected_Pragma
371      (T : Node_Id;
372       P : Name_Id) return Node_Id;
373    --  Searches the task or protected definition T for the first occurrence
374    --  of the pragma whose name is given by P. The caller has ensured that
375    --  the pragma is present in the task definition. A special case is that
376    --  when P is Name_uPriority, the call will also find Interrupt_Priority.
377    --  ??? Should be implemented with the rep item chain mechanism.
378
379    function Index_Object (Spec_Id : Entity_Id) return Entity_Id;
380    --  Given a subprogram identifier, return the entity which is associated
381    --  with the protection entry index in the Protected_Body_Subprogram or the
382    --  Task_Body_Procedure of Spec_Id. The returned entity denotes formal
383    --  parameter _E.
384
385    function Is_Potentially_Large_Family
386      (Base_Index : Entity_Id;
387       Conctyp    : Entity_Id;
388       Lo         : Node_Id;
389       Hi         : Node_Id) return Boolean;
390
391    function Is_Private_Primitive_Subprogram (Id : Entity_Id) return Boolean;
392    --  Determine whether Id is a function or a procedure and is marked as a
393    --  private primitive.
394
395    function Null_Statements (Stats : List_Id) return Boolean;
396    --  Used to check DO-END sequence. Checks for equivalent of DO NULL; END.
397    --  Allows labels, and pragma Warnings/Unreferenced in the sequence as
398    --  well to still count as null. Returns True for a null sequence. The
399    --  argument is the list of statements from the DO-END sequence.
400
401    function Parameter_Block_Pack
402      (Loc     : Source_Ptr;
403       Blk_Typ : Entity_Id;
404       Actuals : List_Id;
405       Formals : List_Id;
406       Decls   : List_Id;
407       Stmts   : List_Id) return Entity_Id;
408    --  Set the components of the generated parameter block with the values of
409    --  the actual parameters. Generate aliased temporaries to capture the
410    --  values for types that are passed by copy. Otherwise generate a reference
411    --  to the actual's value. Return the address of the aggregate block.
412    --  Generate:
413    --    Jnn1 : alias <formal-type1>;
414    --    Jnn1 := <actual1>;
415    --    ...
416    --    P : Blk_Typ := (
417    --      Jnn1'unchecked_access;
418    --      <actual2>'reference;
419    --      ...);
420
421    function Parameter_Block_Unpack
422      (Loc     : Source_Ptr;
423       P       : Entity_Id;
424       Actuals : List_Id;
425       Formals : List_Id) return List_Id;
426    --  Retrieve the values of the components from the parameter block and
427    --  assign then to the original actual parameters. Generate:
428    --    <actual1> := P.<formal1>;
429    --    ...
430    --    <actualN> := P.<formalN>;
431
432    function Trivial_Accept_OK return Boolean;
433    --  If there is no DO-END block for an accept, or if the DO-END block has
434    --  only null statements, then it is possible to do the Rendezvous with much
435    --  less overhead using the Accept_Trivial routine in the run-time library.
436    --  However, this is not always a valid optimization. Whether it is valid or
437    --  not depends on the Task_Dispatching_Policy. The issue is whether a full
438    --  rescheduling action is required or not. In FIFO_Within_Priorities, such
439    --  a rescheduling is required, so this optimization is not allowed. This
440    --  function returns True if the optimization is permitted.
441
442    -----------------------------
443    -- Actual_Index_Expression --
444    -----------------------------
445
446    function Actual_Index_Expression
447      (Sloc  : Source_Ptr;
448       Ent   : Entity_Id;
449       Index : Node_Id;
450       Tsk   : Entity_Id) return Node_Id
451    is
452       Ttyp : constant Entity_Id := Etype (Tsk);
453       Expr : Node_Id;
454       Num  : Node_Id;
455       Lo   : Node_Id;
456       Hi   : Node_Id;
457       Prev : Entity_Id;
458       S    : Node_Id;
459
460       function Actual_Family_Offset (Hi, Lo : Node_Id) return Node_Id;
461       --  Compute difference between bounds of entry family
462
463       --------------------------
464       -- Actual_Family_Offset --
465       --------------------------
466
467       function Actual_Family_Offset (Hi, Lo : Node_Id) return Node_Id is
468
469          function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id;
470          --  Replace a reference to a discriminant with a selected component
471          --  denoting the discriminant of the target task.
472
473          -----------------------------
474          -- Actual_Discriminant_Ref --
475          -----------------------------
476
477          function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id is
478             Typ : constant Entity_Id := Etype (Bound);
479             B   : Node_Id;
480
481          begin
482             if not Is_Entity_Name (Bound)
483               or else Ekind (Entity (Bound)) /= E_Discriminant
484             then
485                if Nkind (Bound) = N_Attribute_Reference then
486                   return Bound;
487                else
488                   B := New_Copy_Tree (Bound);
489                end if;
490
491             else
492                B :=
493                  Make_Selected_Component (Sloc,
494                    Prefix => New_Copy_Tree (Tsk),
495                    Selector_Name => New_Occurrence_Of (Entity (Bound), Sloc));
496
497                Analyze_And_Resolve (B, Typ);
498             end if;
499
500             return
501               Make_Attribute_Reference (Sloc,
502                 Attribute_Name => Name_Pos,
503                 Prefix => New_Occurrence_Of (Etype (Bound), Sloc),
504                 Expressions => New_List (B));
505          end Actual_Discriminant_Ref;
506
507       --  Start of processing for Actual_Family_Offset
508
509       begin
510          return
511            Make_Op_Subtract (Sloc,
512              Left_Opnd  => Actual_Discriminant_Ref (Hi),
513              Right_Opnd => Actual_Discriminant_Ref (Lo));
514       end Actual_Family_Offset;
515
516    --  Start of processing for Actual_Index_Expression
517
518    begin
519       --  The queues of entries and entry families appear in textual order in
520       --  the associated record. The entry index is computed as the sum of the
521       --  number of queues for all entries that precede the designated one, to
522       --  which is added the index expression, if this expression denotes a
523       --  member of a family.
524
525       --  The following is a place holder for the count of simple entries
526
527       Num := Make_Integer_Literal (Sloc, 1);
528
529       --  We construct an expression which is a series of addition operations.
530       --  See comments in Entry_Index_Expression, which is identical in
531       --  structure.
532
533       if Present (Index) then
534          S := Etype (Discrete_Subtype_Definition (Declaration_Node (Ent)));
535
536          Expr :=
537            Make_Op_Add (Sloc,
538              Left_Opnd  => Num,
539
540              Right_Opnd =>
541                Actual_Family_Offset (
542                  Make_Attribute_Reference (Sloc,
543                    Attribute_Name => Name_Pos,
544                    Prefix => New_Reference_To (Base_Type (S), Sloc),
545                    Expressions => New_List (Relocate_Node (Index))),
546                  Type_Low_Bound (S)));
547       else
548          Expr := Num;
549       end if;
550
551       --  Now add lengths of preceding entries and entry families
552
553       Prev := First_Entity (Ttyp);
554
555       while Chars (Prev) /= Chars (Ent)
556         or else (Ekind (Prev) /= Ekind (Ent))
557         or else not Sem_Ch6.Type_Conformant (Ent, Prev)
558       loop
559          if Ekind (Prev) = E_Entry then
560             Set_Intval (Num, Intval (Num) + 1);
561
562          elsif Ekind (Prev) = E_Entry_Family then
563             S :=
564               Etype (Discrete_Subtype_Definition (Declaration_Node (Prev)));
565
566             --  The need for the following full view retrieval stems from
567             --  this complex case of nested generics and tasking:
568
569             --     generic
570             --        type Formal_Index is range <>;
571             --        ...
572             --     package Outer is
573             --        type Index is private;
574             --        generic
575             --           ...
576             --        package Inner is
577             --           procedure P;
578             --        end Inner;
579             --     private
580             --        type Index is new Formal_Index range 1 .. 10;
581             --     end Outer;
582
583             --     package body Outer is
584             --        task type T is
585             --           entry Fam (Index);  --  (2)
586             --           entry E;
587             --        end T;
588             --        package body Inner is  --  (3)
589             --           procedure P is
590             --           begin
591             --              T.E;             --  (1)
592             --           end P;
593             --       end Inner;
594             --       ...
595
596             --  We are currently building the index expression for the entry
597             --  call "T.E" (1). Part of the expansion must mention the range
598             --  of the discrete type "Index" (2) of entry family "Fam".
599             --  However only the private view of type "Index" is available to
600             --  the inner generic (3) because there was no prior mention of
601             --  the type inside "Inner". This visibility requirement is
602             --  implicit and cannot be detected during the construction of
603             --  the generic trees and needs special handling.
604
605             if In_Instance_Body
606               and then Is_Private_Type (S)
607               and then Present (Full_View (S))
608             then
609                S := Full_View (S);
610             end if;
611
612             Lo := Type_Low_Bound  (S);
613             Hi := Type_High_Bound (S);
614
615             Expr :=
616               Make_Op_Add (Sloc,
617               Left_Opnd  => Expr,
618               Right_Opnd =>
619                 Make_Op_Add (Sloc,
620                   Left_Opnd =>
621                     Actual_Family_Offset (Hi, Lo),
622                   Right_Opnd =>
623                     Make_Integer_Literal (Sloc, 1)));
624
625          --  Other components are anonymous types to be ignored
626
627          else
628             null;
629          end if;
630
631          Next_Entity (Prev);
632       end loop;
633
634       return Expr;
635    end Actual_Index_Expression;
636
637    --------------------------
638    -- Add_Formal_Renamings --
639    --------------------------
640
641    procedure Add_Formal_Renamings
642      (Spec  : Node_Id;
643       Decls : List_Id;
644       Ent   : Entity_Id;
645       Loc   : Source_Ptr)
646    is
647       Ptr : constant Entity_Id :=
648               Defining_Identifier
649                 (Next (First (Parameter_Specifications (Spec))));
650       --  The name of the formal that holds the address of the parameter block
651       --  for the call.
652
653       Comp            : Entity_Id;
654       Decl            : Node_Id;
655       Formal          : Entity_Id;
656       New_F           : Entity_Id;
657       Renamed_Formal  : Node_Id;
658
659    begin
660       Formal := First_Formal (Ent);
661       while Present (Formal) loop
662          Comp := Entry_Component (Formal);
663          New_F :=
664            Make_Defining_Identifier (Sloc (Formal),
665              Chars => Chars (Formal));
666          Set_Etype (New_F, Etype (Formal));
667          Set_Scope (New_F, Ent);
668
669          --  Now we set debug info needed on New_F even though it does not
670          --  come from source, so that the debugger will get the right
671          --  information for these generated names.
672
673          Set_Debug_Info_Needed (New_F);
674
675          if Ekind (Formal) = E_In_Parameter then
676             Set_Ekind (New_F, E_Constant);
677          else
678             Set_Ekind (New_F, E_Variable);
679             Set_Extra_Constrained (New_F, Extra_Constrained (Formal));
680          end if;
681
682          Set_Actual_Subtype (New_F, Actual_Subtype (Formal));
683
684          Renamed_Formal :=
685            Make_Selected_Component (Loc,
686              Prefix        =>
687                Unchecked_Convert_To (Entry_Parameters_Type (Ent),
688                  Make_Identifier (Loc, Chars (Ptr))),
689              Selector_Name => New_Reference_To (Comp, Loc));
690
691          Decl :=
692            Build_Renamed_Formal_Declaration
693              (New_F, Formal, Comp, Renamed_Formal);
694
695          Append (Decl, Decls);
696          Set_Renamed_Object (Formal, New_F);
697          Next_Formal (Formal);
698       end loop;
699    end Add_Formal_Renamings;
700
701    ------------------------
702    -- Add_Object_Pointer --
703    ------------------------
704
705    procedure Add_Object_Pointer
706      (Loc      : Source_Ptr;
707       Conc_Typ : Entity_Id;
708       Decls    : List_Id)
709    is
710       Rec_Typ : constant Entity_Id := Corresponding_Record_Type (Conc_Typ);
711       Decl    : Node_Id;
712       Obj_Ptr : Node_Id;
713
714    begin
715       --  Create the renaming declaration for the Protection object of a
716       --  protected type. _Object is used by Complete_Entry_Body.
717       --  ??? An attempt to make this a renaming was unsuccessful.
718
719       --  Build the entity for the access type
720
721       Obj_Ptr :=
722         Make_Defining_Identifier (Loc,
723           New_External_Name (Chars (Rec_Typ), 'P'));
724
725       --  Generate:
726       --    _object : poVP := poVP!O;
727
728       Decl :=
729         Make_Object_Declaration (Loc,
730           Defining_Identifier =>
731             Make_Defining_Identifier (Loc, Name_uObject),
732           Object_Definition =>
733             New_Reference_To (Obj_Ptr, Loc),
734           Expression =>
735             Unchecked_Convert_To (Obj_Ptr, Make_Identifier (Loc, Name_uO)));
736       Set_Debug_Info_Needed (Defining_Identifier (Decl));
737       Prepend_To (Decls, Decl);
738
739       --  Generate:
740       --    type poVP is access poV;
741
742       Decl :=
743         Make_Full_Type_Declaration (Loc,
744           Defining_Identifier =>
745             Obj_Ptr,
746           Type_Definition =>
747             Make_Access_To_Object_Definition (Loc,
748           Subtype_Indication =>
749             New_Reference_To (Rec_Typ, Loc)));
750       Set_Debug_Info_Needed (Defining_Identifier (Decl));
751       Prepend_To (Decls, Decl);
752    end Add_Object_Pointer;
753
754    -----------------------
755    -- Build_Accept_Body --
756    -----------------------
757
758    function Build_Accept_Body (Astat : Node_Id) return  Node_Id is
759       Loc     : constant Source_Ptr := Sloc (Astat);
760       Stats   : constant Node_Id    := Handled_Statement_Sequence (Astat);
761       New_S   : Node_Id;
762       Hand    : Node_Id;
763       Call    : Node_Id;
764       Ohandle : Node_Id;
765
766    begin
767       --  At the end of the statement sequence, Complete_Rendezvous is called.
768       --  A label skipping the Complete_Rendezvous, and all other accept
769       --  processing, has already been added for the expansion of requeue
770       --  statements. The Sloc is copied from the last statement since it
771       --  is really part of this last statement.
772
773       Call :=
774         Build_Runtime_Call
775           (Sloc (Last (Statements (Stats))), RE_Complete_Rendezvous);
776       Insert_Before (Last (Statements (Stats)), Call);
777       Analyze (Call);
778
779       --  If exception handlers are present, then append Complete_Rendezvous
780       --  calls to the handlers, and construct the required outer block. As
781       --  above, the Sloc is copied from the last statement in the sequence.
782
783       if Present (Exception_Handlers (Stats)) then
784          Hand := First (Exception_Handlers (Stats));
785          while Present (Hand) loop
786             Call :=
787               Build_Runtime_Call
788                 (Sloc (Last (Statements (Hand))), RE_Complete_Rendezvous);
789             Append (Call, Statements (Hand));
790             Analyze (Call);
791             Next (Hand);
792          end loop;
793
794          New_S :=
795            Make_Handled_Sequence_Of_Statements (Loc,
796              Statements => New_List (
797                Make_Block_Statement (Loc,
798                  Handled_Statement_Sequence => Stats)));
799
800       else
801          New_S := Stats;
802       end if;
803
804       --  At this stage we know that the new statement sequence does not
805       --  have an exception handler part, so we supply one to call
806       --  Exceptional_Complete_Rendezvous. This handler is
807
808       --    when all others =>
809       --       Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
810
811       --  We handle Abort_Signal to make sure that we properly catch the abort
812       --  case and wake up the caller.
813
814       Ohandle := Make_Others_Choice (Loc);
815       Set_All_Others (Ohandle);
816
817       Set_Exception_Handlers (New_S,
818         New_List (
819           Make_Implicit_Exception_Handler (Loc,
820             Exception_Choices => New_List (Ohandle),
821
822             Statements =>  New_List (
823               Make_Procedure_Call_Statement (Sloc (Stats),
824                 Name => New_Reference_To (
825                   RTE (RE_Exceptional_Complete_Rendezvous), Sloc (Stats)),
826                 Parameter_Associations => New_List (
827                   Make_Function_Call (Sloc (Stats),
828                     Name => New_Reference_To (
829                       RTE (RE_Get_GNAT_Exception), Sloc (Stats)))))))));
830
831       Set_Parent (New_S, Astat); -- temp parent for Analyze call
832       Analyze_Exception_Handlers (Exception_Handlers (New_S));
833       Expand_Exception_Handlers (New_S);
834
835       --  Exceptional_Complete_Rendezvous must be called with abort
836       --  still deferred, which is the case for a "when all others" handler.
837
838       return New_S;
839    end Build_Accept_Body;
840
841    -----------------------------------
842    -- Build_Activation_Chain_Entity --
843    -----------------------------------
844
845    procedure Build_Activation_Chain_Entity (N : Node_Id) is
846       P     : Node_Id;
847       Decls : List_Id;
848       Chain : Entity_Id;
849
850    begin
851       --  Loop to find enclosing construct containing activation chain variable
852       --  The construct is a body, a block, or an extended return.
853
854       P := Parent (N);
855
856       while not Nkind_In (P, N_Subprogram_Body,
857                              N_Entry_Body,
858                              N_Package_Declaration,
859                              N_Package_Body,
860                              N_Block_Statement,
861                              N_Task_Body,
862                              N_Extended_Return_Statement)
863       loop
864          P := Parent (P);
865       end loop;
866
867       --  If we are in a package body, the activation chain variable is
868       --  declared in the body, but the Activation_Chain_Entity is attached
869       --  to the spec.
870
871       if Nkind (P) = N_Package_Body then
872          Decls := Declarations (P);
873          P := Unit_Declaration_Node (Corresponding_Spec (P));
874
875       elsif Nkind (P) = N_Package_Declaration then
876          Decls := Visible_Declarations (Specification (P));
877
878       elsif Nkind (P) = N_Extended_Return_Statement then
879          Decls := Return_Object_Declarations (P);
880
881       else
882          Decls := Declarations (P);
883       end if;
884
885       --  If activation chain entity not already declared, declare it
886
887       if Nkind (P) = N_Extended_Return_Statement
888         or else No (Activation_Chain_Entity (P))
889       then
890          Chain := Make_Defining_Identifier (Sloc (N), Name_uChain);
891
892          --  Note: An extended return statement is not really a task activator,
893          --  but it does have an activation chain on which to store the tasks
894          --  temporarily. On successful return, the tasks on this chain are
895          --  moved to the chain passed in by the caller. We do not build an
896          --  Activation_Chain_Entity for an N_Extended_Return_Statement,
897          --  because we do not want to build a call to Activate_Tasks. Task
898          --  activation is the responsibility of the caller.
899
900          if Nkind (P) /= N_Extended_Return_Statement then
901             Set_Activation_Chain_Entity (P, Chain);
902          end if;
903
904          Prepend_To (Decls,
905            Make_Object_Declaration (Sloc (P),
906              Defining_Identifier => Chain,
907              Aliased_Present => True,
908              Object_Definition =>
909                New_Reference_To (RTE (RE_Activation_Chain), Sloc (P))));
910
911          Analyze (First (Decls));
912       end if;
913    end Build_Activation_Chain_Entity;
914
915    ----------------------------
916    -- Build_Barrier_Function --
917    ----------------------------
918
919    function Build_Barrier_Function
920      (N   : Node_Id;
921       Ent : Entity_Id;
922       Pid : Node_Id) return Node_Id
923    is
924       Loc         : constant Source_Ptr := Sloc (N);
925       Func_Id     : constant Entity_Id  := Barrier_Function (Ent);
926       Ent_Formals : constant Node_Id    := Entry_Body_Formal_Part (N);
927       Op_Decls    : constant List_Id    := New_List;
928       Func_Body   : Node_Id;
929
930    begin
931       --  Add a declaration for the Protection object, renaming declarations
932       --  for the discriminals and privals and finally a declaration for the
933       --  entry family index (if applicable).
934
935       Install_Private_Data_Declarations
936         (Loc, Func_Id, Pid, N, Op_Decls, True, Ekind (Ent) = E_Entry_Family);
937
938       --  Note: the condition in the barrier function needs to be properly
939       --  processed for the C/Fortran boolean possibility, but this happens
940       --  automatically since the return statement does this normalization.
941
942       Func_Body :=
943         Make_Subprogram_Body (Loc,
944           Specification =>
945             Build_Barrier_Function_Specification (Loc,
946               Make_Defining_Identifier (Loc, Chars (Func_Id))),
947           Declarations => Op_Decls,
948           Handled_Statement_Sequence =>
949             Make_Handled_Sequence_Of_Statements (Loc,
950               Statements => New_List (
951                 Make_Simple_Return_Statement (Loc,
952                   Expression => Condition (Ent_Formals)))));
953       Set_Is_Entry_Barrier_Function (Func_Body);
954
955       return Func_Body;
956    end Build_Barrier_Function;
957
958    ------------------------------------------
959    -- Build_Barrier_Function_Specification --
960    ------------------------------------------
961
962    function Build_Barrier_Function_Specification
963      (Loc    : Source_Ptr;
964       Def_Id : Entity_Id) return Node_Id
965    is
966    begin
967       Set_Debug_Info_Needed (Def_Id);
968
969       return Make_Function_Specification (Loc,
970         Defining_Unit_Name => Def_Id,
971         Parameter_Specifications => New_List (
972           Make_Parameter_Specification (Loc,
973             Defining_Identifier =>
974               Make_Defining_Identifier (Loc, Name_uO),
975             Parameter_Type =>
976               New_Reference_To (RTE (RE_Address), Loc)),
977
978           Make_Parameter_Specification (Loc,
979             Defining_Identifier =>
980               Make_Defining_Identifier (Loc, Name_uE),
981             Parameter_Type =>
982               New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))),
983
984         Result_Definition =>
985           New_Reference_To (Standard_Boolean, Loc));
986    end Build_Barrier_Function_Specification;
987
988    --------------------------
989    -- Build_Call_With_Task --
990    --------------------------
991
992    function Build_Call_With_Task
993      (N : Node_Id;
994       E : Entity_Id) return Node_Id
995    is
996       Loc : constant Source_Ptr := Sloc (N);
997    begin
998       return
999         Make_Function_Call (Loc,
1000           Name => New_Reference_To (E, Loc),
1001           Parameter_Associations => New_List (Concurrent_Ref (N)));
1002    end Build_Call_With_Task;
1003
1004    --------------------------------
1005    -- Build_Corresponding_Record --
1006    --------------------------------
1007
1008    function Build_Corresponding_Record
1009     (N    : Node_Id;
1010      Ctyp : Entity_Id;
1011      Loc  : Source_Ptr) return Node_Id
1012    is
1013       Rec_Ent  : constant Entity_Id :=
1014                    Make_Defining_Identifier
1015                      (Loc, New_External_Name (Chars (Ctyp), 'V'));
1016       Disc     : Entity_Id;
1017       Dlist    : List_Id;
1018       New_Disc : Entity_Id;
1019       Cdecls   : List_Id;
1020
1021    begin
1022       Set_Corresponding_Record_Type     (Ctyp, Rec_Ent);
1023       Set_Ekind                         (Rec_Ent, E_Record_Type);
1024       Set_Has_Delayed_Freeze            (Rec_Ent, Has_Delayed_Freeze (Ctyp));
1025       Set_Is_Concurrent_Record_Type     (Rec_Ent, True);
1026       Set_Corresponding_Concurrent_Type (Rec_Ent, Ctyp);
1027       Set_Stored_Constraint             (Rec_Ent, No_Elist);
1028       Cdecls := New_List;
1029
1030       --  Use discriminals to create list of discriminants for record, and
1031       --  create new discriminals for use in default expressions, etc. It is
1032       --  worth noting that a task discriminant gives rise to 5 entities;
1033
1034       --  a) The original discriminant.
1035       --  b) The discriminal for use in the task.
1036       --  c) The discriminant of the corresponding record.
1037       --  d) The discriminal for the init proc of the corresponding record.
1038       --  e) The local variable that renames the discriminant in the procedure
1039       --     for the task body.
1040
1041       --  In fact the discriminals b) are used in the renaming declarations
1042       --  for e). See details in  einfo (Handling of Discriminants).
1043
1044       if Present (Discriminant_Specifications (N)) then
1045          Dlist := New_List;
1046          Disc := First_Discriminant (Ctyp);
1047
1048          while Present (Disc) loop
1049             New_Disc := CR_Discriminant (Disc);
1050
1051             Append_To (Dlist,
1052               Make_Discriminant_Specification (Loc,
1053                 Defining_Identifier => New_Disc,
1054                 Discriminant_Type =>
1055                   New_Occurrence_Of (Etype (Disc), Loc),
1056                 Expression =>
1057                   New_Copy (Discriminant_Default_Value (Disc))));
1058
1059             Next_Discriminant (Disc);
1060          end loop;
1061
1062       else
1063          Dlist := No_List;
1064       end if;
1065
1066       --  Now we can construct the record type declaration. Note that this
1067       --  record is "limited tagged". It is "limited" to reflect the underlying
1068       --  limitedness of the task or protected object that it represents, and
1069       --  ensuring for example that it is properly passed by reference. It is
1070       --  "tagged" to give support to dispatching calls through interfaces. We
1071       --  propagate here the list of interfaces covered by the concurrent type
1072       --  (Ada 2005: AI-345).
1073
1074       return
1075         Make_Full_Type_Declaration (Loc,
1076           Defining_Identifier => Rec_Ent,
1077           Discriminant_Specifications => Dlist,
1078           Type_Definition =>
1079             Make_Record_Definition (Loc,
1080               Component_List =>
1081                 Make_Component_List (Loc,
1082                   Component_Items => Cdecls),
1083               Tagged_Present  =>
1084                  Ada_Version >= Ada_2005 and then Is_Tagged_Type (Ctyp),
1085               Interface_List  => Interface_List (N),
1086               Limited_Present => True));
1087    end Build_Corresponding_Record;
1088
1089    ----------------------------------
1090    -- Build_Entry_Count_Expression --
1091    ----------------------------------
1092
1093    function Build_Entry_Count_Expression
1094      (Concurrent_Type : Node_Id;
1095       Component_List  : List_Id;
1096       Loc             : Source_Ptr) return Node_Id
1097    is
1098       Eindx  : Nat;
1099       Ent    : Entity_Id;
1100       Ecount : Node_Id;
1101       Comp   : Node_Id;
1102       Lo     : Node_Id;
1103       Hi     : Node_Id;
1104       Typ    : Entity_Id;
1105       Large  : Boolean;
1106
1107    begin
1108       --  Count number of non-family entries
1109
1110       Eindx := 0;
1111       Ent := First_Entity (Concurrent_Type);
1112       while Present (Ent) loop
1113          if Ekind (Ent) = E_Entry then
1114             Eindx := Eindx + 1;
1115          end if;
1116
1117          Next_Entity (Ent);
1118       end loop;
1119
1120       Ecount := Make_Integer_Literal (Loc, Eindx);
1121
1122       --  Loop through entry families building the addition nodes
1123
1124       Ent := First_Entity (Concurrent_Type);
1125       Comp := First (Component_List);
1126       while Present (Ent) loop
1127          if Ekind (Ent) = E_Entry_Family then
1128             while Chars (Ent) /= Chars (Defining_Identifier (Comp)) loop
1129                Next (Comp);
1130             end loop;
1131
1132             Typ := Etype (Discrete_Subtype_Definition (Parent (Ent)));
1133             Hi := Type_High_Bound (Typ);
1134             Lo := Type_Low_Bound  (Typ);
1135             Large := Is_Potentially_Large_Family
1136                        (Base_Type (Typ), Concurrent_Type, Lo, Hi);
1137             Ecount :=
1138               Make_Op_Add (Loc,
1139                 Left_Opnd  => Ecount,
1140                 Right_Opnd => Family_Size
1141                                 (Loc, Hi, Lo, Concurrent_Type, Large));
1142          end if;
1143
1144          Next_Entity (Ent);
1145       end loop;
1146
1147       return Ecount;
1148    end Build_Entry_Count_Expression;
1149
1150    -----------------------
1151    -- Build_Entry_Names --
1152    -----------------------
1153
1154    function Build_Entry_Names (Conc_Typ : Entity_Id) return Node_Id is
1155       Loc       : constant Source_Ptr := Sloc (Conc_Typ);
1156       B_Decls   : List_Id;
1157       B_Stmts   : List_Id;
1158       Comp      : Node_Id;
1159       Index     : Entity_Id;
1160       Index_Typ : RE_Id;
1161       Typ       : Entity_Id := Conc_Typ;
1162
1163       procedure Build_Entry_Family_Name (Id : Entity_Id);
1164       --  Generate:
1165       --    for Lnn in Family_Low .. Family_High loop
1166       --       Inn := Inn + 1;
1167       --       Set_Entry_Name
1168       --         (_init._object <or> _init._task_id,
1169       --          Inn,
1170       --          new String ("<Entry name>(" & Lnn'Img & ")"));
1171       --    end loop;
1172       --  Note that the bounds of the range may reference discriminants. The
1173       --  above construct is added directly to the statements of the block.
1174
1175       procedure Build_Entry_Name (Id : Entity_Id);
1176       --  Generate:
1177       --    Inn := Inn + 1;
1178       --    Set_Entry_Name
1179       --      (_init._object <or>_init._task_id,
1180       --       Inn,
1181       --       new String ("<Entry name>");
1182       --  The above construct is added directly to the statements of the block.
1183
1184       function Build_Set_Entry_Name_Call (Arg3 : Node_Id) return Node_Id;
1185       --  Generate the call to the runtime routine Set_Entry_Name with actuals
1186       --  _init._task_id or _init._object, Inn and Arg3.
1187
1188       function Find_Protection_Type (Conc_Typ : Entity_Id) return Entity_Id;
1189       --  Given a protected type or its corresponding record, find the type of
1190       --  field _object.
1191
1192       procedure Increment_Index (Stmts : List_Id);
1193       --  Generate the following and add it to Stmts
1194       --    Inn := Inn + 1;
1195
1196       -----------------------------
1197       -- Build_Entry_Family_Name --
1198       -----------------------------
1199
1200       procedure Build_Entry_Family_Name (Id : Entity_Id) is
1201          Def     : constant Node_Id :=
1202                      Discrete_Subtype_Definition (Parent (Id));
1203          L_Id    : constant Entity_Id := Make_Temporary (Loc, 'L');
1204          L_Stmts : constant List_Id := New_List;
1205          Val     : Node_Id;
1206
1207          function Build_Range (Def : Node_Id) return Node_Id;
1208          --  Given a discrete subtype definition of an entry family, generate a
1209          --  range node which covers the range of Def's type.
1210
1211          -----------------
1212          -- Build_Range --
1213          -----------------
1214
1215          function Build_Range (Def : Node_Id) return Node_Id is
1216             High : Node_Id := Type_High_Bound (Etype (Def));
1217             Low  : Node_Id := Type_Low_Bound  (Etype (Def));
1218
1219          begin
1220             --  If a bound references a discriminant, generate an identifier
1221             --  with the same name. Resolution will map it to the formals of
1222             --  the init proc.
1223
1224             if Is_Entity_Name (Low)
1225               and then Ekind (Entity (Low)) = E_Discriminant
1226             then
1227                Low := Make_Identifier (Loc, Chars (Low));
1228             else
1229                Low := New_Copy_Tree (Low);
1230             end if;
1231
1232             if Is_Entity_Name (High)
1233               and then Ekind (Entity (High)) = E_Discriminant
1234             then
1235                High := Make_Identifier (Loc, Chars (High));
1236             else
1237                High := New_Copy_Tree (High);
1238             end if;
1239
1240             return
1241               Make_Range (Loc,
1242                 Low_Bound  => Low,
1243                 High_Bound => High);
1244          end Build_Range;
1245
1246       --  Start of processing for Build_Entry_Family_Name
1247
1248       begin
1249          Get_Name_String (Chars (Id));
1250
1251          --  Add a leading '('
1252
1253          Add_Char_To_Name_Buffer ('(');
1254
1255          --  Generate:
1256          --    new String'("<Entry name>(" & Lnn'Img & ")");
1257
1258          --  This is an implicit heap allocation, and Comes_From_Source is
1259          --  False, which ensures that it will get flagged as a violation of
1260          --  No_Implicit_Heap_Allocations when that restriction applies.
1261
1262          Val :=
1263            Make_Allocator (Loc,
1264              Make_Qualified_Expression (Loc,
1265                Subtype_Mark =>
1266                  New_Reference_To (Standard_String, Loc),
1267                Expression =>
1268                  Make_Op_Concat (Loc,
1269                    Left_Opnd =>
1270                      Make_Op_Concat (Loc,
1271                        Left_Opnd =>
1272                          Make_String_Literal (Loc,
1273                            Strval => String_From_Name_Buffer),
1274                        Right_Opnd =>
1275                          Make_Attribute_Reference (Loc,
1276                            Prefix =>
1277                              New_Reference_To (L_Id, Loc),
1278                                Attribute_Name => Name_Img)),
1279                    Right_Opnd =>
1280                      Make_String_Literal (Loc,
1281                        Strval => ")"))));
1282
1283          Increment_Index (L_Stmts);
1284          Append_To (L_Stmts, Build_Set_Entry_Name_Call (Val));
1285
1286          --  Generate:
1287          --    for Lnn in Family_Low .. Family_High loop
1288          --       Inn := Inn + 1;
1289          --       Set_Entry_Name
1290          --         (_init._object <or> _init._task_id, Inn, <Val>);
1291          --    end loop;
1292
1293          Append_To (B_Stmts,
1294            Make_Loop_Statement (Loc,
1295              Iteration_Scheme =>
1296                Make_Iteration_Scheme (Loc,
1297                  Loop_Parameter_Specification =>
1298                    Make_Loop_Parameter_Specification (Loc,
1299                     Defining_Identifier         => L_Id,
1300                     Discrete_Subtype_Definition => Build_Range (Def))),
1301              Statements => L_Stmts,
1302              End_Label => Empty));
1303       end Build_Entry_Family_Name;
1304
1305       ----------------------
1306       -- Build_Entry_Name --
1307       ----------------------
1308
1309       procedure Build_Entry_Name (Id : Entity_Id) is
1310          Val : Node_Id;
1311
1312       begin
1313          Get_Name_String (Chars (Id));
1314
1315          --  This is an implicit heap allocation, and Comes_From_Source is
1316          --  False, which ensures that it will get flagged as a violation of
1317          --  No_Implicit_Heap_Allocations when that restriction applies.
1318
1319          Val :=
1320            Make_Allocator (Loc,
1321              Make_Qualified_Expression (Loc,
1322                Subtype_Mark =>
1323                  New_Reference_To (Standard_String, Loc),
1324                Expression =>
1325                  Make_String_Literal (Loc,
1326                    String_From_Name_Buffer)));
1327
1328          Increment_Index (B_Stmts);
1329          Append_To (B_Stmts, Build_Set_Entry_Name_Call (Val));
1330       end Build_Entry_Name;
1331
1332       -------------------------------
1333       -- Build_Set_Entry_Name_Call --
1334       -------------------------------
1335
1336       function Build_Set_Entry_Name_Call (Arg3 : Node_Id) return Node_Id is
1337          Arg1 : Name_Id;
1338          Proc : RE_Id;
1339
1340       begin
1341          --  Determine the proper name for the first argument and the RTS
1342          --  routine to call.
1343
1344          if Is_Protected_Type (Typ) then
1345             Arg1 := Name_uObject;
1346             Proc := RO_PE_Set_Entry_Name;
1347
1348          else pragma Assert (Is_Task_Type (Typ));
1349             Arg1 := Name_uTask_Id;
1350             Proc := RO_TS_Set_Entry_Name;
1351          end if;
1352
1353          --  Generate:
1354          --    Set_Entry_Name (_init.Arg1, Inn, Arg3);
1355
1356          return
1357            Make_Procedure_Call_Statement (Loc,
1358              Name =>
1359                New_Reference_To (RTE (Proc), Loc),
1360              Parameter_Associations => New_List (
1361                Make_Selected_Component (Loc,              --  _init._object
1362                  Prefix =>                                --  _init._task_id
1363                    Make_Identifier (Loc, Name_uInit),
1364                  Selector_Name =>
1365                    Make_Identifier (Loc, Arg1)),
1366                New_Reference_To (Index, Loc),             --  Inn
1367                Arg3));                                    --  Val
1368       end Build_Set_Entry_Name_Call;
1369
1370       --------------------------
1371       -- Find_Protection_Type --
1372       --------------------------
1373
1374       function Find_Protection_Type (Conc_Typ : Entity_Id) return Entity_Id is
1375          Comp : Entity_Id;
1376          Typ  : Entity_Id := Conc_Typ;
1377
1378       begin
1379          if Is_Concurrent_Type (Typ) then
1380             Typ := Corresponding_Record_Type (Typ);
1381          end if;
1382
1383          Comp := First_Component (Typ);
1384          while Present (Comp) loop
1385             if Chars (Comp) = Name_uObject then
1386                return Base_Type (Etype (Comp));
1387             end if;
1388
1389             Next_Component (Comp);
1390          end loop;
1391
1392          --  The corresponding record of a protected type should always have an
1393          --  _object field.
1394
1395          raise Program_Error;
1396       end Find_Protection_Type;
1397
1398       ---------------------
1399       -- Increment_Index --
1400       ---------------------
1401
1402       procedure Increment_Index (Stmts : List_Id) is
1403       begin
1404          --  Generate:
1405          --    Inn := Inn + 1;
1406
1407          Append_To (Stmts,
1408            Make_Assignment_Statement (Loc,
1409              Name =>
1410                New_Reference_To (Index, Loc),
1411              Expression =>
1412                Make_Op_Add (Loc,
1413                  Left_Opnd =>
1414                    New_Reference_To (Index, Loc),
1415                  Right_Opnd =>
1416                    Make_Integer_Literal (Loc, 1))));
1417       end Increment_Index;
1418
1419    --  Start of processing for Build_Entry_Names
1420
1421    begin
1422       --  Retrieve the original concurrent type
1423
1424       if Is_Concurrent_Record_Type (Typ) then
1425          Typ := Corresponding_Concurrent_Type (Typ);
1426       end if;
1427
1428       pragma Assert (Is_Protected_Type (Typ) or else Is_Task_Type (Typ));
1429
1430       --  Nothing to do if the type has no entries
1431
1432       if not Has_Entries (Typ) then
1433          return Empty;
1434       end if;
1435
1436       --  Avoid generating entry names for a protected type with only one entry
1437
1438       if Is_Protected_Type (Typ)
1439         and then Find_Protection_Type (Typ) /= RTE (RE_Protection_Entries)
1440       then
1441          return Empty;
1442       end if;
1443
1444       Index := Make_Temporary (Loc, 'I');
1445
1446       --  Step 1: Generate the declaration of the index variable:
1447       --    Inn : Protected_Entry_Index := 0;
1448       --      or
1449       --    Inn : Task_Entry_Index := 0;
1450
1451       if Is_Protected_Type (Typ) then
1452          Index_Typ := RE_Protected_Entry_Index;
1453       else
1454          Index_Typ := RE_Task_Entry_Index;
1455       end if;
1456
1457       B_Decls := New_List;
1458       Append_To (B_Decls,
1459         Make_Object_Declaration (Loc,
1460           Defining_Identifier => Index,
1461           Object_Definition   => New_Reference_To (RTE (Index_Typ), Loc),
1462           Expression          => Make_Integer_Literal (Loc, 0)));
1463
1464       B_Stmts := New_List;
1465
1466       --  Step 2: Generate a call to Set_Entry_Name for each entry and entry
1467       --  family member.
1468
1469       Comp := First_Entity (Typ);
1470       while Present (Comp) loop
1471          if Ekind (Comp) = E_Entry then
1472             Build_Entry_Name (Comp);
1473
1474          elsif Ekind (Comp) = E_Entry_Family then
1475             Build_Entry_Family_Name (Comp);
1476          end if;
1477
1478          Next_Entity (Comp);
1479       end loop;
1480
1481       --  Step 3: Wrap the statements in a block
1482
1483       return
1484         Make_Block_Statement (Loc,
1485           Declarations => B_Decls,
1486           Handled_Statement_Sequence =>
1487             Make_Handled_Sequence_Of_Statements (Loc,
1488               Statements => B_Stmts));
1489    end Build_Entry_Names;
1490
1491    ---------------------------
1492    -- Build_Parameter_Block --
1493    ---------------------------
1494
1495    function Build_Parameter_Block
1496      (Loc     : Source_Ptr;
1497       Actuals : List_Id;
1498       Formals : List_Id;
1499       Decls   : List_Id) return Entity_Id
1500    is
1501       Actual   : Entity_Id;
1502       Comp_Nam : Node_Id;
1503       Comps    : List_Id;
1504       Formal   : Entity_Id;
1505       Has_Comp : Boolean := False;
1506       Rec_Nam  : Node_Id;
1507
1508    begin
1509       Actual := First (Actuals);
1510       Comps  := New_List;
1511       Formal := Defining_Identifier (First (Formals));
1512
1513       while Present (Actual) loop
1514          if not Is_Controlling_Actual (Actual) then
1515
1516             --  Generate:
1517             --    type Ann is access all <actual-type>
1518
1519             Comp_Nam := Make_Temporary (Loc, 'A');
1520
1521             Append_To (Decls,
1522               Make_Full_Type_Declaration (Loc,
1523                 Defining_Identifier => Comp_Nam,
1524                 Type_Definition     =>
1525                   Make_Access_To_Object_Definition (Loc,
1526                     All_Present        => True,
1527                     Constant_Present   => Ekind (Formal) = E_In_Parameter,
1528                     Subtype_Indication =>
1529                       New_Reference_To (Etype (Actual), Loc))));
1530
1531             --  Generate:
1532             --    Param : Ann;
1533
1534             Append_To (Comps,
1535               Make_Component_Declaration (Loc,
1536                 Defining_Identifier =>
1537                   Make_Defining_Identifier (Loc, Chars (Formal)),
1538                 Component_Definition =>
1539                   Make_Component_Definition (Loc,
1540                     Aliased_Present =>
1541                       False,
1542                     Subtype_Indication =>
1543                       New_Reference_To (Comp_Nam, Loc))));
1544
1545             Has_Comp := True;
1546          end if;
1547
1548          Next_Actual (Actual);
1549          Next_Formal_With_Extras (Formal);
1550       end loop;
1551
1552       Rec_Nam := Make_Temporary (Loc, 'P');
1553
1554       if Has_Comp then
1555
1556          --  Generate:
1557          --    type Pnn is record
1558          --       Param1 : Ann1;
1559          --       ...
1560          --       ParamN : AnnN;
1561
1562          --  where Pnn is a parameter wrapping record, Param1 .. ParamN are
1563          --  the original parameter names and Ann1 .. AnnN are the access to
1564          --  actual types.
1565
1566          Append_To (Decls,
1567            Make_Full_Type_Declaration (Loc,
1568              Defining_Identifier =>
1569                Rec_Nam,
1570              Type_Definition =>
1571                Make_Record_Definition (Loc,
1572                  Component_List =>
1573                    Make_Component_List (Loc, Comps))));
1574       else
1575          --  Generate:
1576          --    type Pnn is null record;
1577
1578          Append_To (Decls,
1579            Make_Full_Type_Declaration (Loc,
1580              Defining_Identifier =>
1581                Rec_Nam,
1582              Type_Definition =>
1583                Make_Record_Definition (Loc,
1584                  Null_Present   => True,
1585                  Component_List => Empty)));
1586       end if;
1587
1588       return Rec_Nam;
1589    end Build_Parameter_Block;
1590
1591    --------------------------------------
1592    -- Build_Renamed_Formal_Declaration --
1593    --------------------------------------
1594
1595    function Build_Renamed_Formal_Declaration
1596      (New_F          : Entity_Id;
1597       Formal         : Entity_Id;
1598       Comp           : Entity_Id;
1599       Renamed_Formal : Node_Id) return Node_Id
1600    is
1601       Loc  : constant Source_Ptr := Sloc (New_F);
1602       Decl : Node_Id;
1603
1604    begin
1605       --  If the formal is a tagged incomplete type, it is already passed
1606       --  by reference, so it is sufficient to rename the pointer component
1607       --  that corresponds to the actual. Otherwise we need to dereference
1608       --  the pointer component to obtain the actual.
1609
1610       if Is_Incomplete_Type (Etype (Formal))
1611         and then Is_Tagged_Type (Etype (Formal))
1612       then
1613          Decl :=
1614            Make_Object_Renaming_Declaration (Loc,
1615              Defining_Identifier => New_F,
1616              Subtype_Mark        => New_Reference_To (Etype (Comp), Loc),
1617              Name                => Renamed_Formal);
1618
1619       else
1620          Decl :=
1621            Make_Object_Renaming_Declaration (Loc,
1622              Defining_Identifier => New_F,
1623              Subtype_Mark        => New_Reference_To (Etype (Formal), Loc),
1624              Name                =>
1625                Make_Explicit_Dereference (Loc, Renamed_Formal));
1626       end if;
1627
1628       return Decl;
1629    end Build_Renamed_Formal_Declaration;
1630
1631    -----------------------
1632    -- Build_PPC_Wrapper --
1633    -----------------------
1634
1635    procedure Build_PPC_Wrapper (E : Entity_Id; Decl : Node_Id) is
1636       Loc        : constant Source_Ptr := Sloc (E);
1637       Synch_Type : constant Entity_Id := Scope (E);
1638
1639       Wrapper_Id : constant Entity_Id :=
1640                      Make_Defining_Identifier (Loc,
1641                        Chars => New_External_Name (Chars (E), 'E'));
1642       --  the wrapper procedure name
1643
1644       Wrapper_Body : Node_Id;
1645
1646       Synch_Id : constant Entity_Id :=
1647                    Make_Defining_Identifier (Loc,
1648                      Chars => New_External_Name (Chars (Scope (E)), 'A'));
1649       --  The parameter that designates the synchronized object in the call
1650
1651       Actuals : constant List_Id := New_List;
1652       --  the actuals in the entry call.
1653
1654       Decls : constant List_Id := New_List;
1655
1656       Entry_Call : Node_Id;
1657       Entry_Name : Node_Id;
1658
1659       Specs : List_Id;
1660       --  The specification of the wrapper procedure
1661
1662    begin
1663
1664       --  Only build the wrapper if entry has pre/postconditions.
1665       --  Should this be done unconditionally instead ???
1666
1667       declare
1668          P : Node_Id;
1669
1670       begin
1671          P := Spec_PPC_List (E);
1672          if No (P) then
1673             return;
1674          end if;
1675
1676          --  Transfer ppc pragmas to the declarations of the wrapper
1677
1678          while Present (P) loop
1679             if Pragma_Name (P) = Name_Precondition
1680               or else Pragma_Name (P) = Name_Postcondition
1681             then
1682                Append (Relocate_Node (P), Decls);
1683                Set_Analyzed (Last (Decls), False);
1684             end if;
1685
1686             P := Next_Pragma (P);
1687          end loop;
1688       end;
1689
1690       --  First formal is synchronized object
1691
1692       Specs := New_List (
1693         Make_Parameter_Specification (Loc,
1694           Defining_Identifier => Synch_Id,
1695           Out_Present         =>  True,
1696           In_Present          =>  True,
1697           Parameter_Type      => New_Occurrence_Of (Scope (E), Loc)));
1698
1699       Entry_Name :=
1700         Make_Selected_Component (Loc,
1701           Prefix        => New_Occurrence_Of (Synch_Id, Loc),
1702           Selector_Name => New_Occurrence_Of (E, Loc));
1703
1704       --  If entity is entry family, second formal is the corresponding index,
1705       --  and entry name is an indexed component.
1706
1707       if Ekind (E) = E_Entry_Family then
1708          declare
1709             Index : constant Entity_Id :=
1710                       Make_Defining_Identifier (Loc, Name_I);
1711          begin
1712             Append_To (Specs,
1713               Make_Parameter_Specification (Loc,
1714                 Defining_Identifier => Index,
1715                 Parameter_Type      =>
1716                   New_Occurrence_Of (Entry_Index_Type (E), Loc)));
1717
1718             Entry_Name :=
1719               Make_Indexed_Component (Loc,
1720                 Prefix      => Entry_Name,
1721                 Expressions => New_List (New_Occurrence_Of (Index, Loc)));
1722          end;
1723       end if;
1724
1725       Entry_Call :=
1726         Make_Procedure_Call_Statement (Loc,
1727           Name                   => Entry_Name,
1728           Parameter_Associations => Actuals);
1729
1730       --  Now add formals that match those of the entry, and build actuals for
1731       --  the nested entry call.
1732
1733       declare
1734          Form      : Entity_Id;
1735          New_Form  : Entity_Id;
1736          Parm_Spec : Node_Id;
1737
1738       begin
1739          Form := First_Formal (E);
1740          while Present (Form) loop
1741             New_Form := Make_Defining_Identifier (Loc, Chars (Form));
1742             Parm_Spec :=
1743               Make_Parameter_Specification (Loc,
1744                 Defining_Identifier => New_Form,
1745                 Out_Present         => Out_Present (Parent (Form)),
1746                 In_Present          => In_Present  (Parent (Form)),
1747                 Parameter_Type      => New_Occurrence_Of (Etype (Form), Loc));
1748
1749             Append (Parm_Spec, Specs);
1750             Append (New_Occurrence_Of (New_Form, Loc), Actuals);
1751             Next_Formal (Form);
1752          end loop;
1753       end;
1754
1755       --  Add renaming declarations for the discriminants of the enclosing
1756       --  type, which may be visible in the preconditions.
1757
1758       if Has_Discriminants (Synch_Type) then
1759          declare
1760             D : Entity_Id;
1761             Decl : Node_Id;
1762
1763          begin
1764             D := First_Discriminant (Synch_Type);
1765             while Present (D) loop
1766                Decl :=
1767                  Make_Object_Renaming_Declaration (Loc,
1768                    Defining_Identifier =>
1769                      Make_Defining_Identifier (Loc, Chars (D)),
1770                    Subtype_Mark        => New_Reference_To (Etype (D), Loc),
1771                    Name                =>
1772                      Make_Selected_Component (Loc,
1773                        Prefix        => New_Reference_To (Synch_Id, Loc),
1774                        Selector_Name => Make_Identifier (Loc, Chars (D))));
1775                Prepend (Decl, Decls);
1776                Next_Discriminant (D);
1777             end loop;
1778          end;
1779       end if;
1780
1781       Set_PPC_Wrapper (E, Wrapper_Id);
1782       Wrapper_Body :=
1783         Make_Subprogram_Body (Loc,
1784           Specification              =>
1785             Make_Procedure_Specification (Loc,
1786               Defining_Unit_Name       => Wrapper_Id,
1787               Parameter_Specifications => Specs),
1788           Declarations               => Decls,
1789           Handled_Statement_Sequence =>
1790             Make_Handled_Sequence_Of_Statements (Loc,
1791               Statements => New_List (Entry_Call)));
1792
1793       --  The wrapper body is analyzed when the enclosing type is frozen
1794
1795       Append_Freeze_Action (Defining_Entity (Decl), Wrapper_Body);
1796    end Build_PPC_Wrapper;
1797
1798    --------------------------
1799    -- Build_Wrapper_Bodies --
1800    --------------------------
1801
1802    procedure Build_Wrapper_Bodies
1803      (Loc : Source_Ptr;
1804       Typ : Entity_Id;
1805       N   : Node_Id)
1806    is
1807       Rec_Typ : Entity_Id;
1808
1809       function Build_Wrapper_Body
1810         (Loc     : Source_Ptr;
1811          Subp_Id : Entity_Id;
1812          Obj_Typ : Entity_Id;
1813          Formals : List_Id) return Node_Id;
1814       --  Ada 2005 (AI-345): Build the body that wraps a primitive operation
1815       --  associated with a protected or task type. Subp_Id is the subprogram
1816       --  name which will be wrapped. Obj_Typ is the type of the new formal
1817       --  parameter which handles dispatching and object notation. Formals are
1818       --  the original formals of Subp_Id which will be explicitly replicated.
1819
1820       ------------------------
1821       -- Build_Wrapper_Body --
1822       ------------------------
1823
1824       function Build_Wrapper_Body
1825         (Loc     : Source_Ptr;
1826          Subp_Id : Entity_Id;
1827          Obj_Typ : Entity_Id;
1828          Formals : List_Id) return Node_Id
1829       is
1830          Body_Spec : Node_Id;
1831
1832       begin
1833          Body_Spec := Build_Wrapper_Spec (Subp_Id, Obj_Typ, Formals);
1834
1835          --  The subprogram is not overriding or is not a primitive declared
1836          --  between two views.
1837
1838          if No (Body_Spec) then
1839             return Empty;
1840          end if;
1841
1842          declare
1843             Actuals    : List_Id := No_List;
1844             Conv_Id    : Node_Id;
1845             First_Form : Node_Id;
1846             Formal     : Node_Id;
1847             Nam        : Node_Id;
1848
1849          begin
1850             --  Map formals to actuals. Use the list built for the wrapper
1851             --  spec, skipping the object notation parameter.
1852
1853             First_Form := First (Parameter_Specifications (Body_Spec));
1854
1855             Formal := First_Form;
1856             Next (Formal);
1857
1858             if Present (Formal) then
1859                Actuals := New_List;
1860                while Present (Formal) loop
1861                   Append_To (Actuals,
1862                     Make_Identifier (Loc,
1863                       Chars => Chars (Defining_Identifier (Formal))));
1864                   Next (Formal);
1865                end loop;
1866             end if;
1867
1868             --  Special processing for primitives declared between a private
1869             --  type and its completion: the wrapper needs a properly typed
1870             --  parameter if the wrapped operation has a controlling first
1871             --  parameter. Note that this might not be the case for a function
1872             --  with a controlling result.
1873
1874             if Is_Private_Primitive_Subprogram (Subp_Id) then
1875                if No (Actuals) then
1876                   Actuals := New_List;
1877                end if;
1878
1879                if Is_Controlling_Formal (First_Formal (Subp_Id)) then
1880                   Prepend_To (Actuals,
1881                     Unchecked_Convert_To
1882                       (Corresponding_Concurrent_Type (Obj_Typ),
1883                        Make_Identifier (Loc, Name_uO)));
1884
1885                else
1886                   Prepend_To (Actuals,
1887                     Make_Identifier (Loc,
1888                       Chars => Chars (Defining_Identifier (First_Form))));
1889                end if;
1890
1891                Nam := New_Reference_To (Subp_Id, Loc);
1892             else
1893                --  An access-to-variable object parameter requires an explicit
1894                --  dereference in the unchecked conversion. This case occurs
1895                --  when a protected entry wrapper must override an interface
1896                --  level procedure with interface access as first parameter.
1897
1898                --     O.all.Subp_Id (Formal_1, ..., Formal_N)
1899
1900                if Nkind (Parameter_Type (First_Form)) =
1901                     N_Access_Definition
1902                then
1903                   Conv_Id :=
1904                     Make_Explicit_Dereference (Loc,
1905                       Prefix => Make_Identifier (Loc, Name_uO));
1906                else
1907                   Conv_Id := Make_Identifier (Loc, Name_uO);
1908                end if;
1909
1910                Nam :=
1911                  Make_Selected_Component (Loc,
1912                    Prefix        =>
1913                      Unchecked_Convert_To
1914                        (Corresponding_Concurrent_Type (Obj_Typ), Conv_Id),
1915                    Selector_Name => New_Reference_To (Subp_Id, Loc));
1916             end if;
1917
1918             --  Create the subprogram body. For a function, the call to the
1919             --  actual subprogram has to be converted to the corresponding
1920             --  record if it is a controlling result.
1921
1922             if Ekind (Subp_Id) = E_Function then
1923                declare
1924                   Res : Node_Id;
1925
1926                begin
1927                   Res :=
1928                      Make_Function_Call (Loc,
1929                        Name                   => Nam,
1930                        Parameter_Associations => Actuals);
1931
1932                   if Has_Controlling_Result (Subp_Id) then
1933                      Res :=
1934                        Unchecked_Convert_To
1935                          (Corresponding_Record_Type (Etype (Subp_Id)), Res);
1936                   end if;
1937
1938                   return
1939                     Make_Subprogram_Body (Loc,
1940                       Specification              => Body_Spec,
1941                       Declarations               => Empty_List,
1942                       Handled_Statement_Sequence =>
1943                         Make_Handled_Sequence_Of_Statements (Loc,
1944                           Statements => New_List (
1945                             Make_Simple_Return_Statement (Loc, Res))));
1946                end;
1947
1948             else
1949                return
1950                  Make_Subprogram_Body (Loc,
1951                    Specification              => Body_Spec,
1952                    Declarations               => Empty_List,
1953                    Handled_Statement_Sequence =>
1954                      Make_Handled_Sequence_Of_Statements (Loc,
1955                        Statements => New_List (
1956                          Make_Procedure_Call_Statement (Loc,
1957                            Name                   => Nam,
1958                            Parameter_Associations => Actuals))));
1959             end if;
1960          end;
1961       end Build_Wrapper_Body;
1962
1963    --  Start of processing for Build_Wrapper_Bodies
1964
1965    begin
1966       if Is_Concurrent_Type (Typ) then
1967          Rec_Typ := Corresponding_Record_Type (Typ);
1968       else
1969          Rec_Typ := Typ;
1970       end if;
1971
1972       --  Generate wrapper bodies for a concurrent type which implements an
1973       --  interface.
1974
1975       if Present (Interfaces (Rec_Typ)) then
1976          declare
1977             Insert_Nod : Node_Id;
1978             Prim       : Entity_Id;
1979             Prim_Elmt  : Elmt_Id;
1980             Prim_Decl  : Node_Id;
1981             Subp       : Entity_Id;
1982             Wrap_Body  : Node_Id;
1983             Wrap_Id    : Entity_Id;
1984
1985          begin
1986             Insert_Nod := N;
1987
1988             --  Examine all primitive operations of the corresponding record
1989             --  type, looking for wrapper specs. Generate bodies in order to
1990             --  complete them.
1991
1992             Prim_Elmt := First_Elmt (Primitive_Operations (Rec_Typ));
1993             while Present (Prim_Elmt) loop
1994                Prim := Node (Prim_Elmt);
1995
1996                if (Ekind (Prim) = E_Function
1997                      or else Ekind (Prim) = E_Procedure)
1998                  and then Is_Primitive_Wrapper (Prim)
1999                then
2000                   Subp := Wrapped_Entity (Prim);
2001                   Prim_Decl := Parent (Parent (Prim));
2002
2003                   Wrap_Body :=
2004                     Build_Wrapper_Body (Loc,
2005                       Subp_Id => Subp,
2006                       Obj_Typ => Rec_Typ,
2007                       Formals => Parameter_Specifications (Parent (Subp)));
2008                   Wrap_Id := Defining_Unit_Name (Specification (Wrap_Body));
2009
2010                   Set_Corresponding_Spec (Wrap_Body, Prim);
2011                   Set_Corresponding_Body (Prim_Decl, Wrap_Id);
2012
2013                   Insert_After (Insert_Nod, Wrap_Body);
2014                   Insert_Nod := Wrap_Body;
2015
2016                   Analyze (Wrap_Body);
2017                end if;
2018
2019                Next_Elmt (Prim_Elmt);
2020             end loop;
2021          end;
2022       end if;
2023    end Build_Wrapper_Bodies;
2024
2025    ------------------------
2026    -- Build_Wrapper_Spec --
2027    ------------------------
2028
2029    function Build_Wrapper_Spec
2030      (Subp_Id : Entity_Id;
2031       Obj_Typ : Entity_Id;
2032       Formals : List_Id) return Node_Id
2033    is
2034       Loc           : constant Source_Ptr := Sloc (Subp_Id);
2035       First_Param   : Node_Id;
2036       Iface         : Entity_Id;
2037       Iface_Elmt    : Elmt_Id;
2038       Iface_Op      : Entity_Id;
2039       Iface_Op_Elmt : Elmt_Id;
2040
2041       function Overriding_Possible
2042         (Iface_Op : Entity_Id;
2043          Wrapper  : Entity_Id) return Boolean;
2044       --  Determine whether a primitive operation can be overridden by Wrapper.
2045       --  Iface_Op is the candidate primitive operation of an interface type,
2046       --  Wrapper is the generated entry wrapper.
2047
2048       function Replicate_Formals
2049         (Loc     : Source_Ptr;
2050          Formals : List_Id) return List_Id;
2051       --  An explicit parameter replication is required due to the Is_Entry_
2052       --  Formal flag being set for all the formals of an entry. The explicit
2053       --  replication removes the flag that would otherwise cause a different
2054       --  path of analysis.
2055
2056       -------------------------
2057       -- Overriding_Possible --
2058       -------------------------
2059
2060       function Overriding_Possible
2061         (Iface_Op : Entity_Id;
2062          Wrapper  : Entity_Id) return Boolean
2063       is
2064          Iface_Op_Spec : constant Node_Id := Parent (Iface_Op);
2065          Wrapper_Spec  : constant Node_Id := Parent (Wrapper);
2066
2067          function Type_Conformant_Parameters
2068            (Iface_Op_Params : List_Id;
2069             Wrapper_Params  : List_Id) return Boolean;
2070          --  Determine whether the parameters of the generated entry wrapper
2071          --  and those of a primitive operation are type conformant. During
2072          --  this check, the first parameter of the primitive operation is
2073          --  skipped if it is a controlling argument: protected functions
2074          --  may have a controlling result.
2075
2076          --------------------------------
2077          -- Type_Conformant_Parameters --
2078          --------------------------------
2079
2080          function Type_Conformant_Parameters
2081            (Iface_Op_Params : List_Id;
2082             Wrapper_Params  : List_Id) return Boolean
2083          is
2084             Iface_Op_Param : Node_Id;
2085             Iface_Op_Typ   : Entity_Id;
2086             Wrapper_Param  : Node_Id;
2087             Wrapper_Typ    : Entity_Id;
2088
2089          begin
2090             --  Skip the first (controlling) parameter of primitive operation
2091
2092             Iface_Op_Param := First (Iface_Op_Params);
2093
2094             if Present (First_Formal (Iface_Op))
2095               and then Is_Controlling_Formal (First_Formal (Iface_Op))
2096             then
2097                Iface_Op_Param := Next (Iface_Op_Param);
2098             end if;
2099
2100             Wrapper_Param  := First (Wrapper_Params);
2101             while Present (Iface_Op_Param)
2102               and then Present (Wrapper_Param)
2103             loop
2104                Iface_Op_Typ := Find_Parameter_Type (Iface_Op_Param);
2105                Wrapper_Typ  := Find_Parameter_Type (Wrapper_Param);
2106
2107                --  The two parameters must be mode conformant
2108
2109                if not Conforming_Types
2110                         (Iface_Op_Typ, Wrapper_Typ, Mode_Conformant)
2111                then
2112                   return False;
2113                end if;
2114
2115                Next (Iface_Op_Param);
2116                Next (Wrapper_Param);
2117             end loop;
2118
2119             --  One of the lists is longer than the other
2120
2121             if Present (Iface_Op_Param) or else Present (Wrapper_Param) then
2122                return False;
2123             end if;
2124
2125             return True;
2126          end Type_Conformant_Parameters;
2127
2128       --  Start of processing for Overriding_Possible
2129
2130       begin
2131          if Chars (Iface_Op) /= Chars (Wrapper) then
2132             return False;
2133          end if;
2134
2135          --  If an inherited subprogram is implemented by a protected procedure
2136          --  or an entry, then the first parameter of the inherited subprogram
2137          --  shall be of mode OUT or IN OUT, or access-to-variable parameter.
2138
2139          if Ekind (Iface_Op) = E_Procedure
2140            and then Present (Parameter_Specifications (Iface_Op_Spec))
2141          then
2142             declare
2143                Obj_Param : constant Node_Id :=
2144                              First (Parameter_Specifications (Iface_Op_Spec));
2145             begin
2146                if not Out_Present (Obj_Param)
2147                  and then Nkind (Parameter_Type (Obj_Param)) /=
2148                                                          N_Access_Definition
2149                then
2150                   return False;
2151                end if;
2152             end;
2153          end if;
2154
2155          return
2156            Type_Conformant_Parameters (
2157              Parameter_Specifications (Iface_Op_Spec),
2158              Parameter_Specifications (Wrapper_Spec));
2159       end Overriding_Possible;
2160
2161       -----------------------
2162       -- Replicate_Formals --
2163       -----------------------
2164
2165       function Replicate_Formals
2166         (Loc     : Source_Ptr;
2167          Formals : List_Id) return List_Id
2168       is
2169          New_Formals : constant List_Id := New_List;
2170          Formal      : Node_Id;
2171          Param_Type  : Node_Id;
2172
2173       begin
2174          Formal := First (Formals);
2175
2176          --  Skip the object parameter when dealing with primitives declared
2177          --  between two views.
2178
2179          if Is_Private_Primitive_Subprogram (Subp_Id)
2180            and then not Has_Controlling_Result (Subp_Id)
2181          then
2182             Formal := Next (Formal);
2183          end if;
2184
2185          while Present (Formal) loop
2186
2187             --  Create an explicit copy of the entry parameter
2188
2189             --  When creating the wrapper subprogram for a primitive operation
2190             --  of a protected interface we must construct an equivalent
2191             --  signature to that of the overriding operation. For regular
2192             --  parameters we can just use the type of the formal, but for
2193             --  access to subprogram parameters we need to reanalyze the
2194             --  parameter type to create local entities for the signature of
2195             --  the subprogram type. Using the entities of the overriding
2196             --  subprogram will result in out-of-scope errors in the back-end.
2197
2198             if Nkind (Parameter_Type (Formal)) = N_Access_Definition then
2199                Param_Type := Copy_Separate_Tree (Parameter_Type (Formal));
2200             else
2201                Param_Type :=
2202                  New_Reference_To (Etype (Parameter_Type (Formal)), Loc);
2203             end if;
2204
2205             Append_To (New_Formals,
2206               Make_Parameter_Specification (Loc,
2207                 Defining_Identifier =>
2208                   Make_Defining_Identifier (Loc,
2209                     Chars          => Chars (Defining_Identifier (Formal))),
2210                     In_Present     => In_Present  (Formal),
2211                     Out_Present    => Out_Present (Formal),
2212                     Parameter_Type => Param_Type));
2213
2214             Next (Formal);
2215          end loop;
2216
2217          return New_Formals;
2218       end Replicate_Formals;
2219
2220    --  Start of processing for Build_Wrapper_Spec
2221
2222    begin
2223       --  There is no point in building wrappers for non-tagged concurrent
2224       --  types.
2225
2226       pragma Assert (Is_Tagged_Type (Obj_Typ));
2227
2228       --  An entry or a protected procedure can override a routine where the
2229       --  controlling formal is either IN OUT, OUT or is of access-to-variable
2230       --  type. Since the wrapper must have the exact same signature as that of
2231       --  the overridden subprogram, we try to find the overriding candidate
2232       --  and use its controlling formal.
2233
2234       First_Param := Empty;
2235
2236       --  Check every implemented interface
2237
2238       if Present (Interfaces (Obj_Typ)) then
2239          Iface_Elmt := First_Elmt (Interfaces (Obj_Typ));
2240          Search : while Present (Iface_Elmt) loop
2241             Iface := Node (Iface_Elmt);
2242
2243             --  Check every interface primitive
2244
2245             if Present (Primitive_Operations (Iface)) then
2246                Iface_Op_Elmt := First_Elmt (Primitive_Operations (Iface));
2247                while Present (Iface_Op_Elmt) loop
2248                   Iface_Op := Node (Iface_Op_Elmt);
2249
2250                   --  Ignore predefined primitives
2251
2252                   if not Is_Predefined_Dispatching_Operation (Iface_Op) then
2253                      Iface_Op := Ultimate_Alias (Iface_Op);
2254
2255                      --  The current primitive operation can be overridden by
2256                      --  the generated entry wrapper.
2257
2258                      if Overriding_Possible (Iface_Op, Subp_Id) then
2259                         First_Param :=
2260                           First (Parameter_Specifications (Parent (Iface_Op)));
2261
2262                         exit Search;
2263                      end if;
2264                   end if;
2265
2266                   Next_Elmt (Iface_Op_Elmt);
2267                end loop;
2268             end if;
2269
2270             Next_Elmt (Iface_Elmt);
2271          end loop Search;
2272       end if;
2273
2274       --  If the subprogram to be wrapped is not overriding anything or is not
2275       --  a primitive declared between two views, do not produce anything. This
2276       --  avoids spurious errors involving overriding.
2277
2278       if No (First_Param)
2279         and then not Is_Private_Primitive_Subprogram (Subp_Id)
2280       then
2281          return Empty;
2282       end if;
2283
2284       declare
2285          Wrapper_Id    : constant Entity_Id :=
2286                            Make_Defining_Identifier (Loc, Chars (Subp_Id));
2287          New_Formals   : List_Id;
2288          Obj_Param     : Node_Id;
2289          Obj_Param_Typ : Entity_Id;
2290
2291       begin
2292          --  Minimum decoration is needed to catch the entity in
2293          --  Sem_Ch6.Override_Dispatching_Operation.
2294
2295          if Ekind (Subp_Id) = E_Function then
2296             Set_Ekind (Wrapper_Id, E_Function);
2297          else
2298             Set_Ekind (Wrapper_Id, E_Procedure);
2299          end if;
2300
2301          Set_Is_Primitive_Wrapper (Wrapper_Id);
2302          Set_Wrapped_Entity       (Wrapper_Id, Subp_Id);
2303          Set_Is_Private_Primitive (Wrapper_Id,
2304            Is_Private_Primitive_Subprogram (Subp_Id));
2305
2306          --  Process the formals
2307
2308          New_Formals := Replicate_Formals (Loc, Formals);
2309
2310          --  A function with a controlling result and no first controlling
2311          --  formal needs no additional parameter.
2312
2313          if Has_Controlling_Result (Subp_Id)
2314            and then
2315              (No (First_Formal (Subp_Id))
2316                or else not Is_Controlling_Formal (First_Formal (Subp_Id)))
2317          then
2318             null;
2319
2320          --  Routine Subp_Id has been found to override an interface primitive.
2321          --  If the interface operation has an access parameter, create a copy
2322          --  of it, with the same null exclusion indicator if present.
2323
2324          elsif Present (First_Param) then
2325             if Nkind (Parameter_Type (First_Param)) = N_Access_Definition then
2326                Obj_Param_Typ :=
2327                  Make_Access_Definition (Loc,
2328                    Subtype_Mark =>
2329                      New_Reference_To (Obj_Typ, Loc));
2330                Set_Null_Exclusion_Present (Obj_Param_Typ,
2331                  Null_Exclusion_Present (Parameter_Type (First_Param)));
2332
2333             else
2334                Obj_Param_Typ := New_Reference_To (Obj_Typ, Loc);
2335             end if;
2336
2337             Obj_Param :=
2338               Make_Parameter_Specification (Loc,
2339                 Defining_Identifier =>
2340                   Make_Defining_Identifier (Loc,
2341                     Chars => Name_uO),
2342                 In_Present          => In_Present  (First_Param),
2343                 Out_Present         => Out_Present (First_Param),
2344                 Parameter_Type      => Obj_Param_Typ);
2345
2346             Prepend_To (New_Formals, Obj_Param);
2347
2348          --  If we are dealing with a primitive declared between two views,
2349          --  implemented by a synchronized operation, we need to create
2350          --  a default parameter. The mode of the parameter must match that
2351          --  of the primitive operation.
2352
2353          else
2354             pragma Assert (Is_Private_Primitive_Subprogram (Subp_Id));
2355             Obj_Param :=
2356               Make_Parameter_Specification (Loc,
2357                 Defining_Identifier =>
2358                   Make_Defining_Identifier (Loc, Name_uO),
2359                 In_Present  => In_Present (Parent (First_Entity (Subp_Id))),
2360                 Out_Present => Ekind (Subp_Id) /= E_Function,
2361                   Parameter_Type => New_Reference_To (Obj_Typ, Loc));
2362             Prepend_To (New_Formals, Obj_Param);
2363          end if;
2364
2365          --  Build the final spec. If it is a function with a controlling
2366          --  result, it is a primitive operation of the corresponding
2367          --  record type, so mark the spec accordingly.
2368
2369          if Ekind (Subp_Id) = E_Function then
2370             declare
2371                Res_Def : Node_Id;
2372
2373             begin
2374                if Has_Controlling_Result (Subp_Id) then
2375                   Res_Def :=
2376                     New_Occurrence_Of
2377                       (Corresponding_Record_Type (Etype (Subp_Id)), Loc);
2378                else
2379                   Res_Def := New_Copy (Result_Definition (Parent (Subp_Id)));
2380                end if;
2381
2382                return
2383                  Make_Function_Specification (Loc,
2384                    Defining_Unit_Name       => Wrapper_Id,
2385                    Parameter_Specifications => New_Formals,
2386                    Result_Definition        => Res_Def);
2387             end;
2388          else
2389             return
2390               Make_Procedure_Specification (Loc,
2391                 Defining_Unit_Name       => Wrapper_Id,
2392                 Parameter_Specifications => New_Formals);
2393          end if;
2394       end;
2395    end Build_Wrapper_Spec;
2396
2397    -------------------------
2398    -- Build_Wrapper_Specs --
2399    -------------------------
2400
2401    procedure Build_Wrapper_Specs
2402      (Loc : Source_Ptr;
2403       Typ : Entity_Id;
2404       N   : in out Node_Id)
2405    is
2406       Def     : Node_Id;
2407       Rec_Typ : Entity_Id;
2408       procedure Scan_Declarations (L : List_Id);
2409       --  Common processing for visible and private declarations
2410       --  of a protected type.
2411
2412       procedure Scan_Declarations (L : List_Id) is
2413          Decl      : Node_Id;
2414          Wrap_Decl : Node_Id;
2415          Wrap_Spec : Node_Id;
2416
2417       begin
2418          if No (L) then
2419             return;
2420          end if;
2421
2422          Decl := First (L);
2423          while Present (Decl) loop
2424             Wrap_Spec := Empty;
2425
2426             if Nkind (Decl) = N_Entry_Declaration
2427               and then Ekind (Defining_Identifier (Decl)) = E_Entry
2428             then
2429                Wrap_Spec :=
2430                  Build_Wrapper_Spec
2431                    (Subp_Id => Defining_Identifier (Decl),
2432                     Obj_Typ => Rec_Typ,
2433                     Formals => Parameter_Specifications (Decl));
2434
2435             elsif Nkind (Decl) = N_Subprogram_Declaration then
2436                Wrap_Spec :=
2437                  Build_Wrapper_Spec
2438                    (Subp_Id => Defining_Unit_Name (Specification (Decl)),
2439                     Obj_Typ => Rec_Typ,
2440                     Formals =>
2441                       Parameter_Specifications (Specification (Decl)));
2442             end if;
2443
2444             if Present (Wrap_Spec) then
2445                Wrap_Decl :=
2446                  Make_Subprogram_Declaration (Loc,
2447                    Specification => Wrap_Spec);
2448
2449                Insert_After (N, Wrap_Decl);
2450                N := Wrap_Decl;
2451
2452                Analyze (Wrap_Decl);
2453             end if;
2454
2455             Next (Decl);
2456          end loop;
2457       end Scan_Declarations;
2458
2459       --  start of processing for Build_Wrapper_Specs
2460
2461    begin
2462       if Is_Protected_Type (Typ) then
2463          Def := Protected_Definition (Parent (Typ));
2464       else pragma Assert (Is_Task_Type (Typ));
2465          Def := Task_Definition (Parent (Typ));
2466       end if;
2467
2468       Rec_Typ := Corresponding_Record_Type (Typ);
2469
2470       --  Generate wrapper specs for a concurrent type which implements an
2471       --  interface. Operations in both the visible and private parts may
2472       --  implement progenitor operations.
2473
2474       if Present (Interfaces (Rec_Typ))
2475         and then Present (Def)
2476       then
2477          Scan_Declarations (Visible_Declarations (Def));
2478          Scan_Declarations (Private_Declarations (Def));
2479       end if;
2480    end Build_Wrapper_Specs;
2481
2482    ---------------------------
2483    -- Build_Find_Body_Index --
2484    ---------------------------
2485
2486    function Build_Find_Body_Index (Typ : Entity_Id) return Node_Id is
2487       Loc   : constant Source_Ptr := Sloc (Typ);
2488       Ent   : Entity_Id;
2489       E_Typ : Entity_Id;
2490       Has_F : Boolean := False;
2491       Index : Nat;
2492       If_St : Node_Id := Empty;
2493       Lo    : Node_Id;
2494       Hi    : Node_Id;
2495       Decls : List_Id := New_List;
2496       Ret   : Node_Id;
2497       Spec  : Node_Id;
2498       Siz   : Node_Id := Empty;
2499
2500       procedure Add_If_Clause (Expr : Node_Id);
2501       --  Add test for range of current entry
2502
2503       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id;
2504       --  If a bound of an entry is given by a discriminant, retrieve the
2505       --  actual value of the discriminant from the enclosing object.
2506
2507       -------------------
2508       -- Add_If_Clause --
2509       -------------------
2510
2511       procedure Add_If_Clause (Expr : Node_Id) is
2512          Cond  : Node_Id;
2513          Stats : constant List_Id :=
2514                    New_List (
2515                      Make_Simple_Return_Statement (Loc,
2516                        Expression => Make_Integer_Literal (Loc, Index + 1)));
2517
2518       begin
2519          --  Index for current entry body
2520
2521          Index := Index + 1;
2522
2523          --  Compute total length of entry queues so far
2524
2525          if No (Siz) then
2526             Siz := Expr;
2527          else
2528             Siz :=
2529               Make_Op_Add (Loc,
2530                 Left_Opnd => Siz,
2531                 Right_Opnd => Expr);
2532          end if;
2533
2534          Cond :=
2535            Make_Op_Le (Loc,
2536              Left_Opnd  => Make_Identifier (Loc, Name_uE),
2537              Right_Opnd => Siz);
2538
2539          --  Map entry queue indexes in the range of the current family
2540          --  into the current index, that designates the entry body.
2541
2542          if No (If_St) then
2543             If_St :=
2544               Make_Implicit_If_Statement (Typ,
2545                 Condition => Cond,
2546                 Then_Statements => Stats,
2547                 Elsif_Parts   => New_List);
2548
2549             Ret := If_St;
2550
2551          else
2552             Append (
2553               Make_Elsif_Part (Loc,
2554                 Condition => Cond,
2555                 Then_Statements => Stats),
2556               Elsif_Parts (If_St));
2557          end if;
2558       end Add_If_Clause;
2559
2560       ------------------------------
2561       -- Convert_Discriminant_Ref --
2562       ------------------------------
2563
2564       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id is
2565          B   : Node_Id;
2566
2567       begin
2568          if Is_Entity_Name (Bound)
2569            and then Ekind (Entity (Bound)) = E_Discriminant
2570          then
2571             B :=
2572               Make_Selected_Component (Loc,
2573                Prefix =>
2574                  Unchecked_Convert_To (Corresponding_Record_Type (Typ),
2575                    Make_Explicit_Dereference (Loc,
2576                      Make_Identifier (Loc, Name_uObject))),
2577                Selector_Name => Make_Identifier (Loc, Chars (Bound)));
2578             Set_Etype (B, Etype (Entity (Bound)));
2579          else
2580             B := New_Copy_Tree (Bound);
2581          end if;
2582
2583          return B;
2584       end Convert_Discriminant_Ref;
2585
2586    --  Start of processing for Build_Find_Body_Index
2587
2588    begin
2589       Spec := Build_Find_Body_Index_Spec (Typ);
2590
2591       Ent := First_Entity (Typ);
2592       while Present (Ent) loop
2593          if Ekind (Ent) = E_Entry_Family then
2594             Has_F := True;
2595             exit;
2596          end if;
2597
2598          Next_Entity (Ent);
2599       end loop;
2600
2601       if not Has_F then
2602
2603          --  If the protected type has no entry families, there is a one-one
2604          --  correspondence between entry queue and entry body.
2605
2606          Ret :=
2607            Make_Simple_Return_Statement (Loc,
2608              Expression => Make_Identifier (Loc, Name_uE));
2609
2610       else
2611          --  Suppose entries e1, e2, ... have size l1, l2, ... we generate
2612          --  the following:
2613          --
2614          --  if E <= l1 then return 1;
2615          --  elsif E <= l1 + l2 then return 2;
2616          --  ...
2617
2618          Index := 0;
2619          Siz   := Empty;
2620          Ent   := First_Entity (Typ);
2621
2622          Add_Object_Pointer (Loc, Typ, Decls);
2623
2624          while Present (Ent) loop
2625             if Ekind (Ent) = E_Entry then
2626                Add_If_Clause (Make_Integer_Literal (Loc, 1));
2627
2628             elsif Ekind (Ent) = E_Entry_Family then
2629                E_Typ := Etype (Discrete_Subtype_Definition (Parent (Ent)));
2630                Hi := Convert_Discriminant_Ref (Type_High_Bound (E_Typ));
2631                Lo := Convert_Discriminant_Ref (Type_Low_Bound  (E_Typ));
2632                Add_If_Clause (Family_Size (Loc, Hi, Lo, Typ, False));
2633             end if;
2634
2635             Next_Entity (Ent);
2636          end loop;
2637
2638          if Index = 1 then
2639             Decls := New_List;
2640             Ret :=
2641               Make_Simple_Return_Statement (Loc,
2642                 Expression => Make_Integer_Literal (Loc, 1));
2643
2644          elsif Nkind (Ret) = N_If_Statement then
2645
2646             --  Ranges are in increasing order, so last one doesn't need guard
2647
2648             declare
2649                Nod : constant Node_Id := Last (Elsif_Parts (Ret));
2650             begin
2651                Remove (Nod);
2652                Set_Else_Statements (Ret, Then_Statements (Nod));
2653             end;
2654          end if;
2655       end if;
2656
2657       return
2658         Make_Subprogram_Body (Loc,
2659           Specification => Spec,
2660           Declarations  => Decls,
2661           Handled_Statement_Sequence =>
2662             Make_Handled_Sequence_Of_Statements (Loc,
2663               Statements => New_List (Ret)));
2664    end Build_Find_Body_Index;
2665
2666    --------------------------------
2667    -- Build_Find_Body_Index_Spec --
2668    --------------------------------
2669
2670    function Build_Find_Body_Index_Spec (Typ : Entity_Id) return Node_Id is
2671       Loc   : constant Source_Ptr := Sloc (Typ);
2672       Id    : constant Entity_Id :=
2673                Make_Defining_Identifier (Loc,
2674                  Chars => New_External_Name (Chars (Typ), 'F'));
2675       Parm1 : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uO);
2676       Parm2 : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uE);
2677
2678    begin
2679       return
2680         Make_Function_Specification (Loc,
2681           Defining_Unit_Name => Id,
2682           Parameter_Specifications => New_List (
2683             Make_Parameter_Specification (Loc,
2684               Defining_Identifier => Parm1,
2685               Parameter_Type =>
2686                 New_Reference_To (RTE (RE_Address), Loc)),
2687
2688             Make_Parameter_Specification (Loc,
2689               Defining_Identifier => Parm2,
2690               Parameter_Type =>
2691                 New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))),
2692           Result_Definition => New_Occurrence_Of (
2693             RTE (RE_Protected_Entry_Index), Loc));
2694    end Build_Find_Body_Index_Spec;
2695
2696    -------------------------
2697    -- Build_Master_Entity --
2698    -------------------------
2699
2700    procedure Build_Master_Entity (E : Entity_Id) is
2701       Loc  : constant Source_Ptr := Sloc (E);
2702       P    : Node_Id;
2703       Decl : Node_Id;
2704       S    : Entity_Id;
2705
2706    begin
2707       S := Find_Master_Scope (E);
2708
2709       --  Nothing to do if we already built a master entity for this scope
2710       --  or if there is no task hierarchy.
2711
2712       if Has_Master_Entity (S)
2713         or else Restriction_Active (No_Task_Hierarchy)
2714       then
2715          return;
2716       end if;
2717
2718       --  Otherwise first build the master entity
2719       --    _Master : constant Master_Id := Current_Master.all;
2720       --  and insert it just before the current declaration
2721
2722       Decl :=
2723         Make_Object_Declaration (Loc,
2724           Defining_Identifier =>
2725             Make_Defining_Identifier (Loc, Name_uMaster),
2726           Constant_Present => True,
2727           Object_Definition => New_Reference_To (RTE (RE_Master_Id), Loc),
2728           Expression =>
2729             Make_Explicit_Dereference (Loc,
2730               New_Reference_To (RTE (RE_Current_Master), Loc)));
2731
2732       P := Parent (E);
2733       Insert_Before (P, Decl);
2734       Analyze (Decl);
2735
2736       Set_Has_Master_Entity (S);
2737
2738       --  Now mark the containing scope as a task master
2739
2740       while Nkind (P) /= N_Compilation_Unit loop
2741          P := Parent (P);
2742
2743          --  If we fall off the top, we are at the outer level, and the
2744          --  environment task is our effective master, so nothing to mark.
2745
2746          if Nkind_In
2747               (P, N_Task_Body, N_Block_Statement, N_Subprogram_Body)
2748          then
2749             Set_Is_Task_Master (P, True);
2750             return;
2751
2752          elsif Nkind (Parent (P)) = N_Subunit then
2753             P := Corresponding_Stub (Parent (P));
2754          end if;
2755       end loop;
2756    end Build_Master_Entity;
2757
2758    -----------------------------------------
2759    -- Build_Private_Protected_Declaration --
2760    -----------------------------------------
2761
2762    function Build_Private_Protected_Declaration
2763      (N : Node_Id) return Entity_Id
2764    is
2765       Loc      : constant Source_Ptr := Sloc (N);
2766       Body_Id  : constant Entity_Id := Defining_Entity (N);
2767       Decl     : Node_Id;
2768       Plist    : List_Id;
2769       Formal   : Entity_Id;
2770       New_Spec : Node_Id;
2771       Spec_Id  : Entity_Id;
2772
2773    begin
2774       Formal := First_Formal (Body_Id);
2775
2776       --  The protected operation always has at least one formal, namely the
2777       --  object itself, but it is only placed in the parameter list if
2778       --  expansion is enabled.
2779
2780       if Present (Formal) or else Expander_Active then
2781          Plist := Copy_Parameter_List (Body_Id);
2782       else
2783          Plist := No_List;
2784       end if;
2785
2786       if Nkind (Specification (N)) = N_Procedure_Specification then
2787          New_Spec :=
2788            Make_Procedure_Specification (Loc,
2789               Defining_Unit_Name       =>
2790                 Make_Defining_Identifier (Sloc (Body_Id),
2791                   Chars => Chars (Body_Id)),
2792               Parameter_Specifications =>
2793                 Plist);
2794       else
2795          New_Spec :=
2796            Make_Function_Specification (Loc,
2797              Defining_Unit_Name       =>
2798                Make_Defining_Identifier (Sloc (Body_Id),
2799                  Chars => Chars (Body_Id)),
2800              Parameter_Specifications => Plist,
2801              Result_Definition        =>
2802                New_Occurrence_Of (Etype (Body_Id), Loc));
2803       end if;
2804
2805       Decl := Make_Subprogram_Declaration (Loc, Specification => New_Spec);
2806       Insert_Before (N, Decl);
2807       Spec_Id := Defining_Unit_Name (New_Spec);
2808
2809       --  Indicate that the entity comes from source, to ensure that cross-
2810       --  reference information is properly generated. The body itself is
2811       --  rewritten during expansion, and the body entity will not appear in
2812       --  calls to the operation.
2813
2814       Set_Comes_From_Source (Spec_Id, True);
2815       Analyze (Decl);
2816       Set_Has_Completion (Spec_Id);
2817       Set_Convention (Spec_Id, Convention_Protected);
2818       return Spec_Id;
2819    end Build_Private_Protected_Declaration;
2820
2821    ---------------------------
2822    -- Build_Protected_Entry --
2823    ---------------------------
2824
2825    function Build_Protected_Entry
2826      (N   : Node_Id;
2827       Ent : Entity_Id;
2828       Pid : Node_Id) return Node_Id
2829    is
2830       Loc : constant Source_Ptr := Sloc (N);
2831
2832       Decls   : constant List_Id := Declarations (N);
2833       End_Lab : constant Node_Id :=
2834                   End_Label (Handled_Statement_Sequence (N));
2835       End_Loc : constant Source_Ptr :=
2836                   Sloc (Last (Statements (Handled_Statement_Sequence (N))));
2837       --  Used for the generated call to Complete_Entry_Body
2838
2839       Han_Loc : Source_Ptr;
2840       --  Used for the exception handler, inserted at end of the body
2841
2842       Op_Decls : constant List_Id := New_List;
2843       Complete : Node_Id;
2844       Edef     : Entity_Id;
2845       Espec    : Node_Id;
2846       Ohandle  : Node_Id;
2847       Op_Stats : List_Id;
2848
2849    begin
2850       --  Set the source location on the exception handler only when debugging
2851       --  the expanded code (see Make_Implicit_Exception_Handler).
2852
2853       if Debug_Generated_Code then
2854          Han_Loc := End_Loc;
2855
2856       --  Otherwise the inserted code should not be visible to the debugger
2857
2858       else
2859          Han_Loc := No_Location;
2860       end if;
2861
2862       Edef :=
2863         Make_Defining_Identifier (Loc,
2864           Chars => Chars (Protected_Body_Subprogram (Ent)));
2865       Espec :=
2866         Build_Protected_Entry_Specification (Loc, Edef, Empty);
2867
2868       --  Add the following declarations:
2869       --    type poVP is access poV;
2870       --    _object : poVP := poVP (_O);
2871       --
2872       --  where _O is the formal parameter associated with the concurrent
2873       --  object. These declarations are needed for Complete_Entry_Body.
2874
2875       Add_Object_Pointer (Loc, Pid, Op_Decls);
2876
2877       --  Add renamings for all formals, the Protection object, discriminals,
2878       --  privals and the entry index constant for use by debugger.
2879
2880       Add_Formal_Renamings (Espec, Op_Decls, Ent, Loc);
2881       Debug_Private_Data_Declarations (Decls);
2882
2883       case Corresponding_Runtime_Package (Pid) is
2884          when System_Tasking_Protected_Objects_Entries =>
2885             Complete :=
2886               New_Reference_To (RTE (RE_Complete_Entry_Body), Loc);
2887
2888          when System_Tasking_Protected_Objects_Single_Entry =>
2889             Complete :=
2890               New_Reference_To (RTE (RE_Complete_Single_Entry_Body), Loc);
2891
2892          when others =>
2893             raise Program_Error;
2894       end case;
2895
2896       Op_Stats := New_List (
2897         Make_Block_Statement (Loc,
2898           Declarations => Decls,
2899           Handled_Statement_Sequence =>
2900             Handled_Statement_Sequence (N)),
2901
2902         Make_Procedure_Call_Statement (End_Loc,
2903           Name => Complete,
2904           Parameter_Associations => New_List (
2905             Make_Attribute_Reference (End_Loc,
2906               Prefix =>
2907                 Make_Selected_Component (End_Loc,
2908                   Prefix        => Make_Identifier (End_Loc, Name_uObject),
2909                   Selector_Name => Make_Identifier (End_Loc, Name_uObject)),
2910               Attribute_Name => Name_Unchecked_Access))));
2911
2912       --  When exceptions can not be propagated, we never need to call
2913       --  Exception_Complete_Entry_Body
2914
2915       if No_Exception_Handlers_Set then
2916          return
2917            Make_Subprogram_Body (Loc,
2918              Specification => Espec,
2919              Declarations => Op_Decls,
2920              Handled_Statement_Sequence =>
2921                Make_Handled_Sequence_Of_Statements (Loc,
2922                  Statements => Op_Stats,
2923                  End_Label  => End_Lab));
2924
2925       else
2926          Ohandle := Make_Others_Choice (Loc);
2927          Set_All_Others (Ohandle);
2928
2929          case Corresponding_Runtime_Package (Pid) is
2930             when System_Tasking_Protected_Objects_Entries =>
2931                Complete :=
2932                  New_Reference_To
2933                    (RTE (RE_Exceptional_Complete_Entry_Body), Loc);
2934
2935             when System_Tasking_Protected_Objects_Single_Entry =>
2936                Complete :=
2937                  New_Reference_To
2938                    (RTE (RE_Exceptional_Complete_Single_Entry_Body), Loc);
2939
2940             when others =>
2941                raise Program_Error;
2942          end case;
2943
2944          --  Establish link between subprogram body entity and source entry.
2945
2946          Set_Corresponding_Protected_Entry (Edef, Ent);
2947
2948          --  Create body of entry procedure. The renaming declarations are
2949          --  placed ahead of the block that contains the actual entry body.
2950
2951          return
2952            Make_Subprogram_Body (Loc,
2953              Specification => Espec,
2954              Declarations => Op_Decls,
2955              Handled_Statement_Sequence =>
2956                Make_Handled_Sequence_Of_Statements (Loc,
2957                  Statements => Op_Stats,
2958                  End_Label  => End_Lab,
2959                  Exception_Handlers => New_List (
2960                    Make_Implicit_Exception_Handler (Han_Loc,
2961                      Exception_Choices => New_List (Ohandle),
2962
2963                      Statements =>  New_List (
2964                        Make_Procedure_Call_Statement (Han_Loc,
2965                          Name => Complete,
2966                          Parameter_Associations => New_List (
2967                            Make_Attribute_Reference (Han_Loc,
2968                              Prefix =>
2969                                Make_Selected_Component (Han_Loc,
2970                                  Prefix        =>
2971                                    Make_Identifier (Han_Loc, Name_uObject),
2972                                  Selector_Name =>
2973                                    Make_Identifier (Han_Loc, Name_uObject)),
2974                                Attribute_Name => Name_Unchecked_Access),
2975
2976                            Make_Function_Call (Han_Loc,
2977                              Name => New_Reference_To (
2978                                RTE (RE_Get_GNAT_Exception), Loc)))))))));
2979       end if;
2980    end Build_Protected_Entry;
2981
2982    -----------------------------------------
2983    -- Build_Protected_Entry_Specification --
2984    -----------------------------------------
2985
2986    function Build_Protected_Entry_Specification
2987      (Loc    : Source_Ptr;
2988       Def_Id : Entity_Id;
2989       Ent_Id : Entity_Id) return Node_Id
2990    is
2991       P : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uP);
2992
2993    begin
2994       Set_Debug_Info_Needed (Def_Id);
2995
2996       if Present (Ent_Id) then
2997          Append_Elmt (P, Accept_Address (Ent_Id));
2998       end if;
2999
3000       return
3001         Make_Procedure_Specification (Loc,
3002           Defining_Unit_Name => Def_Id,
3003           Parameter_Specifications => New_List (
3004             Make_Parameter_Specification (Loc,
3005               Defining_Identifier =>
3006                 Make_Defining_Identifier (Loc, Name_uO),
3007               Parameter_Type =>
3008                 New_Reference_To (RTE (RE_Address), Loc)),
3009
3010             Make_Parameter_Specification (Loc,
3011               Defining_Identifier => P,
3012               Parameter_Type =>
3013                 New_Reference_To (RTE (RE_Address), Loc)),
3014
3015             Make_Parameter_Specification (Loc,
3016               Defining_Identifier =>
3017                 Make_Defining_Identifier (Loc, Name_uE),
3018               Parameter_Type =>
3019                 New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))));
3020    end Build_Protected_Entry_Specification;
3021
3022    --------------------------
3023    -- Build_Protected_Spec --
3024    --------------------------
3025
3026    function Build_Protected_Spec
3027      (N           : Node_Id;
3028       Obj_Type    : Entity_Id;
3029       Ident       : Entity_Id;
3030       Unprotected : Boolean := False) return List_Id
3031    is
3032       Loc       : constant Source_Ptr := Sloc (N);
3033       Decl      : Node_Id;
3034       Formal    : Entity_Id;
3035       New_Plist : List_Id;
3036       New_Param : Node_Id;
3037
3038    begin
3039       New_Plist := New_List;
3040
3041       Formal := First_Formal (Ident);
3042       while Present (Formal) loop
3043          New_Param :=
3044            Make_Parameter_Specification (Loc,
3045              Defining_Identifier =>
3046                Make_Defining_Identifier (Sloc (Formal), Chars (Formal)),
3047              In_Present          => In_Present (Parent (Formal)),
3048              Out_Present         => Out_Present (Parent (Formal)),
3049              Parameter_Type      => New_Reference_To (Etype (Formal), Loc));
3050
3051          if Unprotected then
3052             Set_Protected_Formal (Formal, Defining_Identifier (New_Param));
3053          end if;
3054
3055          Append (New_Param, New_Plist);
3056          Next_Formal (Formal);
3057       end loop;
3058
3059       --  If the subprogram is a procedure and the context is not an access
3060       --  to protected subprogram, the parameter is in-out. Otherwise it is
3061       --  an in parameter.
3062
3063       Decl :=
3064         Make_Parameter_Specification (Loc,
3065           Defining_Identifier =>
3066             Make_Defining_Identifier (Loc, Name_uObject),
3067           In_Present => True,
3068           Out_Present =>
3069             (Etype (Ident) = Standard_Void_Type
3070                and then not Is_RTE (Obj_Type, RE_Address)),
3071           Parameter_Type =>
3072             New_Reference_To (Obj_Type, Loc));
3073       Set_Debug_Info_Needed (Defining_Identifier (Decl));
3074       Prepend_To (New_Plist, Decl);
3075
3076       return New_Plist;
3077    end Build_Protected_Spec;
3078
3079    ---------------------------------------
3080    -- Build_Protected_Sub_Specification --
3081    ---------------------------------------
3082
3083    function Build_Protected_Sub_Specification
3084      (N        : Node_Id;
3085       Prot_Typ : Entity_Id;
3086       Mode     : Subprogram_Protection_Mode) return Node_Id
3087    is
3088       Loc       : constant Source_Ptr := Sloc (N);
3089       Decl      : Node_Id;
3090       Def_Id    : Entity_Id;
3091       New_Id    : Entity_Id;
3092       New_Plist : List_Id;
3093       New_Spec  : Node_Id;
3094
3095       Append_Chr : constant array (Subprogram_Protection_Mode) of Character :=
3096                      (Dispatching_Mode => ' ',
3097                       Protected_Mode   => 'P',
3098                       Unprotected_Mode => 'N');
3099
3100    begin
3101       if Ekind (Defining_Unit_Name (Specification (N))) =
3102            E_Subprogram_Body
3103       then
3104          Decl := Unit_Declaration_Node (Corresponding_Spec (N));
3105       else
3106          Decl := N;
3107       end if;
3108
3109       Def_Id := Defining_Unit_Name (Specification (Decl));
3110
3111       New_Plist :=
3112         Build_Protected_Spec
3113           (Decl, Corresponding_Record_Type (Prot_Typ), Def_Id,
3114            Mode = Unprotected_Mode);
3115       New_Id :=
3116         Make_Defining_Identifier (Loc,
3117           Chars => Build_Selected_Name (Prot_Typ, Def_Id, Append_Chr (Mode)));
3118
3119       --  The unprotected operation carries the user code, and debugging
3120       --  information must be generated for it, even though this spec does
3121       --  not come from source. It is also convenient to allow gdb to step
3122       --  into the protected operation, even though it only contains lock/
3123       --  unlock calls.
3124
3125       Set_Debug_Info_Needed (New_Id);
3126
3127       --  If a pragma Eliminate applies to the source entity, the internal
3128       --  subprograms will be eliminated as well.
3129
3130       Set_Is_Eliminated (New_Id, Is_Eliminated (Def_Id));
3131
3132       if Nkind (Specification (Decl)) = N_Procedure_Specification then
3133          New_Spec :=
3134            Make_Procedure_Specification (Loc,
3135              Defining_Unit_Name => New_Id,
3136              Parameter_Specifications => New_Plist);
3137
3138       --  Create a new specification for the anonymous subprogram type
3139
3140       else
3141          New_Spec :=
3142            Make_Function_Specification (Loc,
3143              Defining_Unit_Name => New_Id,
3144              Parameter_Specifications => New_Plist,
3145              Result_Definition =>
3146                Copy_Result_Type (Result_Definition (Specification (Decl))));
3147
3148          Set_Return_Present (Defining_Unit_Name (New_Spec));
3149       end if;
3150
3151       return New_Spec;
3152    end Build_Protected_Sub_Specification;
3153
3154    -------------------------------------
3155    -- Build_Protected_Subprogram_Body --
3156    -------------------------------------
3157
3158    function Build_Protected_Subprogram_Body
3159      (N         : Node_Id;
3160       Pid       : Node_Id;
3161       N_Op_Spec : Node_Id) return Node_Id
3162    is
3163       Loc          : constant Source_Ptr := Sloc (N);
3164       Op_Spec      : Node_Id;
3165       P_Op_Spec    : Node_Id;
3166       Uactuals     : List_Id;
3167       Pformal      : Node_Id;
3168       Unprot_Call  : Node_Id;
3169       Sub_Body     : Node_Id;
3170       Lock_Name    : Node_Id;
3171       Lock_Stmt    : Node_Id;
3172       Service_Name : Node_Id;
3173       R            : Node_Id;
3174       Return_Stmt  : Node_Id := Empty;    -- init to avoid gcc 3 warning
3175       Pre_Stmts    : List_Id := No_List;  -- init to avoid gcc 3 warning
3176       Stmts        : List_Id;
3177       Object_Parm  : Node_Id;
3178       Exc_Safe     : Boolean;
3179
3180       function Is_Exception_Safe (Subprogram : Node_Id) return Boolean;
3181       --  Tell whether a given subprogram cannot raise an exception
3182
3183       -----------------------
3184       -- Is_Exception_Safe --
3185       -----------------------
3186
3187       function Is_Exception_Safe (Subprogram : Node_Id) return Boolean is
3188
3189          function Has_Side_Effect (N : Node_Id) return Boolean;
3190          --  Return True whenever encountering a subprogram call or raise
3191          --  statement of any kind in the sequence of statements
3192
3193          ---------------------
3194          -- Has_Side_Effect --
3195          ---------------------
3196
3197          --  What is this doing buried two levels down in exp_ch9. It seems
3198          --  like a generally useful function, and indeed there may be code
3199          --  duplication going on here ???
3200
3201          function Has_Side_Effect (N : Node_Id) return Boolean is
3202             Stmt : Node_Id;
3203             Expr : Node_Id;
3204
3205             function Is_Call_Or_Raise (N : Node_Id) return Boolean;
3206             --  Indicate whether N is a subprogram call or a raise statement
3207
3208             ----------------------
3209             -- Is_Call_Or_Raise --
3210             ----------------------
3211
3212             function Is_Call_Or_Raise (N : Node_Id) return Boolean is
3213             begin
3214                return Nkind_In (N, N_Procedure_Call_Statement,
3215                                    N_Function_Call,
3216                                    N_Raise_Statement,
3217                                    N_Raise_Constraint_Error,
3218                                    N_Raise_Program_Error,
3219                                    N_Raise_Storage_Error);
3220             end Is_Call_Or_Raise;
3221
3222          --  Start of processing for Has_Side_Effect
3223
3224          begin
3225             Stmt := N;
3226             while Present (Stmt) loop
3227                if Is_Call_Or_Raise (Stmt) then
3228                   return True;
3229                end if;
3230
3231                --  An object declaration can also contain a function call
3232                --  or a raise statement
3233
3234                if Nkind (Stmt) = N_Object_Declaration then
3235                   Expr := Expression (Stmt);
3236
3237                   if Present (Expr) and then Is_Call_Or_Raise (Expr) then
3238                      return True;
3239                   end if;
3240                end if;
3241
3242                Next (Stmt);
3243             end loop;
3244
3245             return False;
3246          end Has_Side_Effect;
3247
3248       --  Start of processing for Is_Exception_Safe
3249
3250       begin
3251          --  If the checks handled by the back end are not disabled, we cannot
3252          --  ensure that no exception will be raised.
3253
3254          if not Access_Checks_Suppressed (Empty)
3255            or else not Discriminant_Checks_Suppressed (Empty)
3256            or else not Range_Checks_Suppressed (Empty)
3257            or else not Index_Checks_Suppressed (Empty)
3258            or else Opt.Stack_Checking_Enabled
3259          then
3260             return False;
3261          end if;
3262
3263          if Has_Side_Effect (First (Declarations (Subprogram)))
3264            or else
3265               Has_Side_Effect (
3266                 First (Statements (Handled_Statement_Sequence (Subprogram))))
3267          then
3268             return False;
3269          else
3270             return True;
3271          end if;
3272       end Is_Exception_Safe;
3273
3274    --  Start of processing for Build_Protected_Subprogram_Body
3275
3276    begin
3277       Op_Spec := Specification (N);
3278       Exc_Safe := Is_Exception_Safe (N);
3279
3280       P_Op_Spec :=
3281         Build_Protected_Sub_Specification (N, Pid, Protected_Mode);
3282
3283       --  Build a list of the formal parameters of the protected version of
3284       --  the subprogram to use as the actual parameters of the unprotected
3285       --  version.
3286
3287       Uactuals := New_List;
3288       Pformal := First (Parameter_Specifications (P_Op_Spec));
3289       while Present (Pformal) loop
3290          Append_To (Uactuals,
3291            Make_Identifier (Loc, Chars (Defining_Identifier (Pformal))));
3292          Next (Pformal);
3293       end loop;
3294
3295       --  Make a call to the unprotected version of the subprogram built above
3296       --  for use by the protected version built below.
3297
3298       if Nkind (Op_Spec) = N_Function_Specification then
3299          if Exc_Safe then
3300             R := Make_Temporary (Loc, 'R');
3301             Unprot_Call :=
3302               Make_Object_Declaration (Loc,
3303                 Defining_Identifier => R,
3304                 Constant_Present => True,
3305                 Object_Definition => New_Copy (Result_Definition (N_Op_Spec)),
3306                 Expression =>
3307                   Make_Function_Call (Loc,
3308                     Name => Make_Identifier (Loc,
3309                       Chars => Chars (Defining_Unit_Name (N_Op_Spec))),
3310                     Parameter_Associations => Uactuals));
3311
3312             Return_Stmt :=
3313               Make_Simple_Return_Statement (Loc,
3314                 Expression => New_Reference_To (R, Loc));
3315
3316          else
3317             Unprot_Call := Make_Simple_Return_Statement (Loc,
3318               Expression => Make_Function_Call (Loc,
3319                 Name =>
3320                   Make_Identifier (Loc,
3321                     Chars => Chars (Defining_Unit_Name (N_Op_Spec))),
3322                 Parameter_Associations => Uactuals));
3323          end if;
3324
3325       else
3326          Unprot_Call :=
3327            Make_Procedure_Call_Statement (Loc,
3328              Name =>
3329                Make_Identifier (Loc, Chars (Defining_Unit_Name (N_Op_Spec))),
3330              Parameter_Associations => Uactuals);
3331       end if;
3332
3333       --  Wrap call in block that will be covered by an at_end handler
3334
3335       if not Exc_Safe then
3336          Unprot_Call := Make_Block_Statement (Loc,
3337            Handled_Statement_Sequence =>
3338              Make_Handled_Sequence_Of_Statements (Loc,
3339                Statements => New_List (Unprot_Call)));
3340       end if;
3341
3342       --  Make the protected subprogram body. This locks the protected
3343       --  object and calls the unprotected version of the subprogram.
3344
3345       case Corresponding_Runtime_Package (Pid) is
3346          when System_Tasking_Protected_Objects_Entries =>
3347             Lock_Name := New_Reference_To (RTE (RE_Lock_Entries), Loc);
3348             Service_Name := New_Reference_To (RTE (RE_Service_Entries), Loc);
3349
3350          when System_Tasking_Protected_Objects_Single_Entry =>
3351             Lock_Name := New_Reference_To (RTE (RE_Lock_Entry), Loc);
3352             Service_Name := New_Reference_To (RTE (RE_Service_Entry), Loc);
3353
3354          when System_Tasking_Protected_Objects =>
3355             Lock_Name := New_Reference_To (RTE (RE_Lock), Loc);
3356             Service_Name := New_Reference_To (RTE (RE_Unlock), Loc);
3357
3358          when others =>
3359             raise Program_Error;
3360       end case;
3361
3362       Object_Parm :=
3363         Make_Attribute_Reference (Loc,
3364            Prefix =>
3365              Make_Selected_Component (Loc,
3366                Prefix        => Make_Identifier (Loc, Name_uObject),
3367                Selector_Name => Make_Identifier (Loc, Name_uObject)),
3368            Attribute_Name => Name_Unchecked_Access);
3369
3370       Lock_Stmt := Make_Procedure_Call_Statement (Loc,
3371         Name => Lock_Name,
3372         Parameter_Associations => New_List (Object_Parm));
3373
3374       if Abort_Allowed then
3375          Stmts := New_List (
3376            Make_Procedure_Call_Statement (Loc,
3377              Name => New_Reference_To (RTE (RE_Abort_Defer), Loc),
3378              Parameter_Associations => Empty_List),
3379            Lock_Stmt);
3380
3381       else
3382          Stmts := New_List (Lock_Stmt);
3383       end if;
3384
3385       if not Exc_Safe then
3386          Append (Unprot_Call, Stmts);
3387       else
3388          if Nkind (Op_Spec) = N_Function_Specification then
3389             Pre_Stmts := Stmts;
3390             Stmts     := Empty_List;
3391          else
3392             Append (Unprot_Call, Stmts);
3393          end if;
3394
3395          Append (
3396            Make_Procedure_Call_Statement (Loc,
3397              Name => Service_Name,
3398              Parameter_Associations =>
3399                New_List (New_Copy_Tree (Object_Parm))),
3400            Stmts);
3401
3402          if Abort_Allowed then
3403             Append (
3404               Make_Procedure_Call_Statement (Loc,
3405                 Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc),
3406                 Parameter_Associations => Empty_List),
3407               Stmts);
3408          end if;
3409
3410          if Nkind (Op_Spec) = N_Function_Specification then
3411             Append (Return_Stmt, Stmts);
3412             Append (Make_Block_Statement (Loc,
3413               Declarations => New_List (Unprot_Call),
3414               Handled_Statement_Sequence =>
3415                 Make_Handled_Sequence_Of_Statements (Loc,
3416                   Statements => Stmts)), Pre_Stmts);
3417             Stmts := Pre_Stmts;
3418          end if;
3419       end if;
3420
3421       Sub_Body :=
3422         Make_Subprogram_Body (Loc,
3423           Declarations => Empty_List,
3424           Specification => P_Op_Spec,
3425           Handled_Statement_Sequence =>
3426             Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts));
3427
3428       if not Exc_Safe then
3429          Set_Is_Protected_Subprogram_Body (Sub_Body);
3430       end if;
3431
3432       return Sub_Body;
3433    end Build_Protected_Subprogram_Body;
3434
3435    -------------------------------------
3436    -- Build_Protected_Subprogram_Call --
3437    -------------------------------------
3438
3439    procedure Build_Protected_Subprogram_Call
3440      (N        : Node_Id;
3441       Name     : Node_Id;
3442       Rec      : Node_Id;
3443       External : Boolean := True)
3444    is
3445       Loc     : constant Source_Ptr := Sloc (N);
3446       Sub     : constant Entity_Id  := Entity (Name);
3447       New_Sub : Node_Id;
3448       Params  : List_Id;
3449
3450    begin
3451       if External then
3452          New_Sub := New_Occurrence_Of (External_Subprogram (Sub), Loc);
3453       else
3454          New_Sub :=
3455            New_Occurrence_Of (Protected_Body_Subprogram (Sub), Loc);
3456       end if;
3457
3458       if Present (Parameter_Associations (N)) then
3459          Params := New_Copy_List_Tree (Parameter_Associations (N));
3460       else
3461          Params := New_List;
3462       end if;
3463
3464       --  If the type is an untagged derived type, convert to the root type,
3465       --  which is the one on which the operations are defined.
3466
3467       if Nkind (Rec) = N_Unchecked_Type_Conversion
3468         and then not Is_Tagged_Type (Etype (Rec))
3469         and then Is_Derived_Type (Etype (Rec))
3470       then
3471          Set_Etype (Rec, Root_Type (Etype (Rec)));
3472          Set_Subtype_Mark (Rec,
3473            New_Occurrence_Of (Root_Type (Etype (Rec)), Sloc (N)));
3474       end if;
3475
3476       Prepend (Rec, Params);
3477
3478       if Ekind (Sub) = E_Procedure then
3479          Rewrite (N,
3480            Make_Procedure_Call_Statement (Loc,
3481              Name => New_Sub,
3482              Parameter_Associations => Params));
3483
3484       else
3485          pragma Assert (Ekind (Sub) = E_Function);
3486          Rewrite (N,
3487            Make_Function_Call (Loc,
3488              Name => New_Sub,
3489              Parameter_Associations => Params));
3490       end if;
3491
3492       if External
3493         and then Nkind (Rec) = N_Unchecked_Type_Conversion
3494         and then Is_Entity_Name (Expression (Rec))
3495         and then Is_Shared_Passive (Entity (Expression (Rec)))
3496       then
3497          Add_Shared_Var_Lock_Procs (N);
3498       end if;
3499    end Build_Protected_Subprogram_Call;
3500
3501    -------------------------
3502    -- Build_Selected_Name --
3503    -------------------------
3504
3505    function Build_Selected_Name
3506      (Prefix      : Entity_Id;
3507       Selector    : Entity_Id;
3508       Append_Char : Character := ' ') return Name_Id
3509    is
3510       Select_Buffer : String (1 .. Hostparm.Max_Name_Length);
3511       Select_Len    : Natural;
3512
3513    begin
3514       Get_Name_String (Chars (Selector));
3515       Select_Len := Name_Len;
3516       Select_Buffer (1 .. Select_Len) := Name_Buffer (1 .. Name_Len);
3517       Get_Name_String (Chars (Prefix));
3518
3519       --  If scope is anonymous type, discard suffix to recover name of
3520       --  single protected object. Otherwise use protected type name.
3521
3522       if Name_Buffer (Name_Len) = 'T' then
3523          Name_Len := Name_Len - 1;
3524       end if;
3525
3526       Add_Str_To_Name_Buffer ("__");
3527       for J in 1 .. Select_Len loop
3528          Add_Char_To_Name_Buffer (Select_Buffer (J));
3529       end loop;
3530
3531       --  Now add the Append_Char if specified. The encoding to follow
3532       --  depends on the type of entity. If Append_Char is either 'N' or 'P',
3533       --  then the entity is associated to a protected type subprogram.
3534       --  Otherwise, it is a protected type entry. For each case, the
3535       --  encoding to follow for the suffix is documented in exp_dbug.ads.
3536
3537       --  It would be better to encapsulate this as a routine in Exp_Dbug ???
3538
3539       if Append_Char /= ' ' then
3540          if Append_Char = 'P' or Append_Char = 'N' then
3541             Add_Char_To_Name_Buffer (Append_Char);
3542             return Name_Find;
3543          else
3544             Add_Str_To_Name_Buffer ((1 => '_', 2 => Append_Char));
3545             return New_External_Name (Name_Find, ' ', -1);
3546          end if;
3547       else
3548          return Name_Find;
3549       end if;
3550    end Build_Selected_Name;
3551
3552    -----------------------------
3553    -- Build_Simple_Entry_Call --
3554    -----------------------------
3555
3556    --  A task entry call is converted to a call to Call_Simple
3557
3558    --    declare
3559    --       P : parms := (parm, parm, parm);
3560    --    begin
3561    --       Call_Simple (acceptor-task, entry-index, P'Address);
3562    --       parm := P.param;
3563    --       parm := P.param;
3564    --       ...
3565    --    end;
3566
3567    --  Here Pnn is an aggregate of the type constructed for the entry to hold
3568    --  the parameters, and the constructed aggregate value contains either the
3569    --  parameters or, in the case of non-elementary types, references to these
3570    --  parameters. Then the address of this aggregate is passed to the runtime
3571    --  routine, along with the task id value and the task entry index value.
3572    --  Pnn is only required if parameters are present.
3573
3574    --  The assignments after the call are present only in the case of in-out
3575    --  or out parameters for elementary types, and are used to assign back the
3576    --  resulting values of such parameters.
3577
3578    --  Note: the reason that we insert a block here is that in the context
3579    --  of selects, conditional entry calls etc. the entry call statement
3580    --  appears on its own, not as an element of a list.
3581
3582    --  A protected entry call is converted to a Protected_Entry_Call:
3583
3584    --  declare
3585    --     P   : E1_Params := (param, param, param);
3586    --     Pnn : Boolean;
3587    --     Bnn : Communications_Block;
3588
3589    --  declare
3590    --     P   : E1_Params := (param, param, param);
3591    --     Bnn : Communications_Block;
3592
3593    --  begin
3594    --     Protected_Entry_Call (
3595    --       Object => po._object'Access,
3596    --       E => <entry index>;
3597    --       Uninterpreted_Data => P'Address;
3598    --       Mode => Simple_Call;
3599    --       Block => Bnn);
3600    --     parm := P.param;
3601    --     parm := P.param;
3602    --       ...
3603    --  end;
3604
3605    procedure Build_Simple_Entry_Call
3606      (N       : Node_Id;
3607       Concval : Node_Id;
3608       Ename   : Node_Id;
3609       Index   : Node_Id)
3610    is
3611    begin
3612       Expand_Call (N);
3613
3614       --  If call has been inlined, nothing left to do
3615
3616       if Nkind (N) = N_Block_Statement then
3617          return;
3618       end if;
3619
3620       --  Convert entry call to Call_Simple call
3621
3622       declare
3623          Loc       : constant Source_Ptr := Sloc (N);
3624          Parms     : constant List_Id    := Parameter_Associations (N);
3625          Stats     : constant List_Id    := New_List;
3626          Actual    : Node_Id;
3627          Call      : Node_Id;
3628          Comm_Name : Entity_Id;
3629          Conctyp   : Node_Id;
3630          Decls     : List_Id;
3631          Ent       : Entity_Id;
3632          Ent_Acc   : Entity_Id;
3633          Formal    : Node_Id;
3634          Iface_Tag : Entity_Id;
3635          Iface_Typ : Entity_Id;
3636          N_Node    : Node_Id;
3637          N_Var     : Node_Id;
3638          P         : Entity_Id;
3639          Parm1     : Node_Id;
3640          Parm2     : Node_Id;
3641          Parm3     : Node_Id;
3642          Pdecl     : Node_Id;
3643          Plist     : List_Id;
3644          X         : Entity_Id;
3645          Xdecl     : Node_Id;
3646
3647       begin
3648          --  Simple entry and entry family cases merge here
3649
3650          Ent     := Entity (Ename);
3651          Ent_Acc := Entry_Parameters_Type (Ent);
3652          Conctyp := Etype (Concval);
3653
3654          --  If prefix is an access type, dereference to obtain the task type
3655
3656          if Is_Access_Type (Conctyp) then
3657             Conctyp := Designated_Type (Conctyp);
3658          end if;
3659
3660          --  Special case for protected subprogram calls
3661
3662          if Is_Protected_Type (Conctyp)
3663            and then Is_Subprogram (Entity (Ename))
3664          then
3665             if not Is_Eliminated (Entity (Ename)) then
3666                Build_Protected_Subprogram_Call
3667                  (N, Ename, Convert_Concurrent (Concval, Conctyp));
3668                Analyze (N);
3669             end if;
3670
3671             return;
3672          end if;
3673
3674          --  First parameter is the Task_Id value from the task value or the
3675          --  Object from the protected object value, obtained by selecting
3676          --  the _Task_Id or _Object from the result of doing an unchecked
3677          --  conversion to convert the value to the corresponding record type.
3678
3679          if Nkind (Concval) = N_Function_Call
3680            and then Is_Task_Type (Conctyp)
3681            and then Ada_Version >= Ada_2005
3682          then
3683             declare
3684                ExpR : constant Node_Id   := Relocate_Node (Concval);
3685                Obj  : constant Entity_Id := Make_Temporary (Loc, 'F', ExpR);
3686                Decl : Node_Id;
3687
3688             begin
3689                Decl :=
3690                  Make_Object_Declaration (Loc,
3691                    Defining_Identifier => Obj,
3692                    Object_Definition   => New_Occurrence_Of (Conctyp, Loc),
3693                    Expression          => ExpR);
3694                Set_Etype (Obj, Conctyp);
3695                Decls := New_List (Decl);
3696                Rewrite (Concval, New_Occurrence_Of (Obj, Loc));
3697             end;
3698
3699          else
3700             Decls := New_List;
3701          end if;
3702
3703          Parm1 := Concurrent_Ref (Concval);
3704
3705          --  Second parameter is the entry index, computed by the routine
3706          --  provided for this purpose. The value of this expression is
3707          --  assigned to an intermediate variable to assure that any entry
3708          --  family index expressions are evaluated before the entry
3709          --  parameters.
3710
3711          if Abort_Allowed
3712            or else Restriction_Active (No_Entry_Queue) = False
3713            or else not Is_Protected_Type (Conctyp)
3714            or else Number_Entries (Conctyp) > 1
3715            or else (Has_Attach_Handler (Conctyp)
3716                      and then not Restricted_Profile)
3717          then
3718             X := Make_Defining_Identifier (Loc, Name_uX);
3719
3720             Xdecl :=
3721               Make_Object_Declaration (Loc,
3722                 Defining_Identifier => X,
3723                 Object_Definition =>
3724                   New_Reference_To (RTE (RE_Task_Entry_Index), Loc),
3725                 Expression => Actual_Index_Expression (
3726                   Loc, Entity (Ename), Index, Concval));
3727
3728             Append_To (Decls, Xdecl);
3729             Parm2 := New_Reference_To (X, Loc);
3730
3731          else
3732             Xdecl := Empty;
3733             Parm2 := Empty;
3734          end if;
3735
3736          --  The third parameter is the packaged parameters. If there are
3737          --  none, then it is just the null address, since nothing is passed.
3738
3739          if No (Parms) then
3740             Parm3 := New_Reference_To (RTE (RE_Null_Address), Loc);
3741             P := Empty;
3742
3743          --  Case of parameters present, where third argument is the address
3744          --  of a packaged record containing the required parameter values.
3745
3746          else
3747             --  First build a list of parameter values, which are references to
3748             --  objects of the parameter types.
3749
3750             Plist := New_List;
3751
3752             Actual := First_Actual (N);
3753             Formal := First_Formal (Ent);
3754
3755             while Present (Actual) loop
3756
3757                --  If it is a by_copy_type, copy it to a new variable. The
3758                --  packaged record has a field that points to this variable.
3759
3760                if Is_By_Copy_Type (Etype (Actual)) then
3761                   N_Node :=
3762                     Make_Object_Declaration (Loc,
3763                       Defining_Identifier => Make_Temporary (Loc, 'J'),
3764                       Aliased_Present     => True,
3765                       Object_Definition   =>
3766                         New_Reference_To (Etype (Formal), Loc));
3767
3768                   --  Mark the object as not needing initialization since the
3769                   --  initialization is performed separately, avoiding errors
3770                   --  on cases such as formals of null-excluding access types.
3771
3772                   Set_No_Initialization (N_Node);
3773
3774                   --  We must make an assignment statement separate for the
3775                   --  case of limited type. We cannot assign it unless the
3776                   --  Assignment_OK flag is set first. An out formal of an
3777                   --  access type must also be initialized from the actual,
3778                   --  as stated in RM 6.4.1 (13).
3779
3780                   if Ekind (Formal) /= E_Out_Parameter
3781                     or else Is_Access_Type (Etype (Formal))
3782                   then
3783                      N_Var :=
3784                        New_Reference_To (Defining_Identifier (N_Node), Loc);
3785                      Set_Assignment_OK (N_Var);
3786                      Append_To (Stats,
3787                        Make_Assignment_Statement (Loc,
3788                          Name => N_Var,
3789                          Expression => Relocate_Node (Actual)));
3790                   end if;
3791
3792                   Append (N_Node, Decls);
3793
3794                   Append_To (Plist,
3795                     Make_Attribute_Reference (Loc,
3796                       Attribute_Name => Name_Unchecked_Access,
3797                     Prefix =>
3798                       New_Reference_To (Defining_Identifier (N_Node), Loc)));
3799
3800                --  If it is a vm_by_copy_actual, copy it to a new variable
3801
3802                elsif Is_VM_By_Copy_Actual (Actual) then
3803                   N_Node :=
3804                     Make_Object_Declaration (Loc,
3805                       Defining_Identifier => Make_Temporary (Loc, 'J'),
3806                       Aliased_Present     => True,
3807                       Object_Definition   =>
3808                         New_Reference_To (Etype (Formal), Loc),
3809                       Expression => New_Copy_Tree (Actual));
3810                   Set_Assignment_OK (N_Node);
3811
3812                   Append (N_Node, Decls);
3813
3814                   Append_To (Plist,
3815                     Make_Attribute_Reference (Loc,
3816                       Attribute_Name => Name_Unchecked_Access,
3817                     Prefix =>
3818                       New_Reference_To (Defining_Identifier (N_Node), Loc)));
3819
3820                else
3821                   --  Interface class-wide formal
3822
3823                   if Ada_Version >= Ada_2005
3824                     and then Ekind (Etype (Formal)) = E_Class_Wide_Type
3825                     and then Is_Interface (Etype (Formal))
3826                   then
3827                      Iface_Typ := Etype (Etype (Formal));
3828
3829                      --  Generate:
3830                      --    formal_iface_type! (actual.iface_tag)'reference
3831
3832                      Iface_Tag :=
3833                        Find_Interface_Tag (Etype (Actual), Iface_Typ);
3834                      pragma Assert (Present (Iface_Tag));
3835
3836                      Append_To (Plist,
3837                        Make_Reference (Loc,
3838                          Unchecked_Convert_To (Iface_Typ,
3839                            Make_Selected_Component (Loc,
3840                              Prefix =>
3841                                Relocate_Node (Actual),
3842                              Selector_Name =>
3843                                New_Reference_To (Iface_Tag, Loc)))));
3844                   else
3845                      --  Generate:
3846                      --    actual'reference
3847
3848                      Append_To (Plist,
3849                        Make_Reference (Loc, Relocate_Node (Actual)));
3850                   end if;
3851                end if;
3852
3853                Next_Actual (Actual);
3854                Next_Formal_With_Extras (Formal);
3855             end loop;
3856
3857             --  Now build the declaration of parameters initialized with the
3858             --  aggregate containing this constructed parameter list.
3859
3860             P := Make_Defining_Identifier (Loc, Name_uP);
3861
3862             Pdecl :=
3863               Make_Object_Declaration (Loc,
3864                 Defining_Identifier => P,
3865                 Object_Definition =>
3866                   New_Reference_To (Designated_Type (Ent_Acc), Loc),
3867                 Expression =>
3868                   Make_Aggregate (Loc, Expressions => Plist));
3869
3870             Parm3 :=
3871               Make_Attribute_Reference (Loc,
3872                 Prefix => New_Reference_To (P, Loc),
3873                 Attribute_Name => Name_Address);
3874
3875             Append (Pdecl, Decls);
3876          end if;
3877
3878          --  Now we can create the call, case of protected type
3879
3880          if Is_Protected_Type (Conctyp) then
3881             case Corresponding_Runtime_Package (Conctyp) is
3882                when System_Tasking_Protected_Objects_Entries =>
3883
3884                   --  Change the type of the index declaration
3885
3886                   Set_Object_Definition (Xdecl,
3887                     New_Reference_To (RTE (RE_Protected_Entry_Index), Loc));
3888
3889                   --  Some additional declarations for protected entry calls
3890
3891                   if No (Decls) then
3892                      Decls := New_List;
3893                   end if;
3894
3895                   --  Bnn : Communications_Block;
3896
3897                   Comm_Name := Make_Temporary (Loc, 'B');
3898
3899                   Append_To (Decls,
3900                     Make_Object_Declaration (Loc,
3901                       Defining_Identifier => Comm_Name,
3902                       Object_Definition   =>
3903                         New_Reference_To (RTE (RE_Communication_Block), Loc)));
3904
3905                   --  Some additional statements for protected entry calls
3906
3907                   --     Protected_Entry_Call (
3908                   --       Object => po._object'Access,
3909                   --       E => <entry index>;
3910                   --       Uninterpreted_Data => P'Address;
3911                   --       Mode => Simple_Call;
3912                   --       Block => Bnn);
3913
3914                   Call :=
3915                     Make_Procedure_Call_Statement (Loc,
3916                       Name =>
3917                         New_Reference_To (RTE (RE_Protected_Entry_Call), Loc),
3918
3919                       Parameter_Associations => New_List (
3920                         Make_Attribute_Reference (Loc,
3921                           Attribute_Name => Name_Unchecked_Access,
3922                           Prefix         => Parm1),
3923                         Parm2,
3924                         Parm3,
3925                         New_Reference_To (RTE (RE_Simple_Call), Loc),
3926                         New_Occurrence_Of (Comm_Name, Loc)));
3927
3928                when System_Tasking_Protected_Objects_Single_Entry =>
3929                   --     Protected_Single_Entry_Call (
3930                   --       Object => po._object'Access,
3931                   --       Uninterpreted_Data => P'Address;
3932                   --       Mode => Simple_Call);
3933
3934                   Call :=
3935                     Make_Procedure_Call_Statement (Loc,
3936                       Name => New_Reference_To (
3937                         RTE (RE_Protected_Single_Entry_Call), Loc),
3938
3939                       Parameter_Associations => New_List (
3940                         Make_Attribute_Reference (Loc,
3941                           Attribute_Name => Name_Unchecked_Access,
3942                           Prefix         => Parm1),
3943                         Parm3,
3944                         New_Reference_To (RTE (RE_Simple_Call), Loc)));
3945
3946                when others =>
3947                   raise Program_Error;
3948             end case;
3949
3950          --  Case of task type
3951
3952          else
3953             Call :=
3954               Make_Procedure_Call_Statement (Loc,
3955                 Name => New_Reference_To (RTE (RE_Call_Simple), Loc),
3956                 Parameter_Associations => New_List (Parm1, Parm2, Parm3));
3957
3958          end if;
3959
3960          Append_To (Stats, Call);
3961
3962          --  If there are out or in/out parameters by copy add assignment
3963          --  statements for the result values.
3964
3965          if Present (Parms) then
3966             Actual := First_Actual (N);
3967             Formal := First_Formal (Ent);
3968
3969             Set_Assignment_OK (Actual);
3970             while Present (Actual) loop
3971                if (Is_By_Copy_Type (Etype (Actual))
3972                      or else Is_VM_By_Copy_Actual (Actual))
3973                  and then Ekind (Formal) /= E_In_Parameter
3974                then
3975                   N_Node :=
3976                     Make_Assignment_Statement (Loc,
3977                       Name => New_Copy (Actual),
3978                       Expression =>
3979                         Make_Explicit_Dereference (Loc,
3980                           Make_Selected_Component (Loc,
3981                             Prefix => New_Reference_To (P, Loc),
3982                             Selector_Name =>
3983                               Make_Identifier (Loc, Chars (Formal)))));
3984
3985                   --  In all cases (including limited private types) we want
3986                   --  the assignment to be valid.
3987
3988                   Set_Assignment_OK (Name (N_Node));
3989
3990                   --  If the call is the triggering alternative in an
3991                   --  asynchronous select, or the entry_call alternative of a
3992                   --  conditional entry call, the assignments for in-out
3993                   --  parameters are incorporated into the statement list that
3994                   --  follows, so that there are executed only if the entry
3995                   --  call succeeds.
3996
3997                   if (Nkind (Parent (N)) = N_Triggering_Alternative
3998                        and then N = Triggering_Statement (Parent (N)))
3999                     or else
4000                      (Nkind (Parent (N)) = N_Entry_Call_Alternative
4001                        and then N = Entry_Call_Statement (Parent (N)))
4002                   then
4003                      if No (Statements (Parent (N))) then
4004                         Set_Statements (Parent (N), New_List);
4005                      end if;
4006
4007                      Prepend (N_Node, Statements (Parent (N)));
4008
4009                   else
4010                      Insert_After (Call, N_Node);
4011                   end if;
4012                end if;
4013
4014                Next_Actual (Actual);
4015                Next_Formal_With_Extras (Formal);
4016             end loop;
4017          end if;
4018
4019          --  Finally, create block and analyze it
4020
4021          Rewrite (N,
4022            Make_Block_Statement (Loc,
4023              Declarations => Decls,
4024              Handled_Statement_Sequence =>
4025                Make_Handled_Sequence_Of_Statements (Loc,
4026                  Statements => Stats)));
4027
4028          Analyze (N);
4029       end;
4030    end Build_Simple_Entry_Call;
4031
4032    --------------------------------
4033    -- Build_Task_Activation_Call --
4034    --------------------------------
4035
4036    procedure Build_Task_Activation_Call (N : Node_Id) is
4037       Loc   : constant Source_Ptr := Sloc (N);
4038       Chain : Entity_Id;
4039       Call  : Node_Id;
4040       Name  : Node_Id;
4041       P     : Node_Id;
4042
4043    begin
4044       --  Get the activation chain entity. Except in the case of a package
4045       --  body, this is in the node that was passed. For a package body, we
4046       --  have to find the corresponding package declaration node.
4047
4048       if Nkind (N) = N_Package_Body then
4049          P := Corresponding_Spec (N);
4050          loop
4051             P := Parent (P);
4052             exit when Nkind (P) = N_Package_Declaration;
4053          end loop;
4054
4055          Chain := Activation_Chain_Entity (P);
4056
4057       else
4058          Chain := Activation_Chain_Entity (N);
4059       end if;
4060
4061       if Present (Chain) then
4062          if Restricted_Profile then
4063             Name := New_Reference_To (RTE (RE_Activate_Restricted_Tasks), Loc);
4064          else
4065             Name := New_Reference_To (RTE (RE_Activate_Tasks), Loc);
4066          end if;
4067
4068          Call :=
4069            Make_Procedure_Call_Statement (Loc,
4070              Name => Name,
4071              Parameter_Associations =>
4072                New_List (Make_Attribute_Reference (Loc,
4073                  Prefix => New_Occurrence_Of (Chain, Loc),
4074                  Attribute_Name => Name_Unchecked_Access)));
4075
4076          if Nkind (N) = N_Package_Declaration then
4077             if Present (Corresponding_Body (N)) then
4078                null;
4079
4080             elsif Present (Private_Declarations (Specification (N))) then
4081                Append (Call, Private_Declarations (Specification (N)));
4082
4083             else
4084                Append (Call, Visible_Declarations (Specification (N)));
4085             end if;
4086
4087          else
4088             if Present (Handled_Statement_Sequence (N)) then
4089
4090                --  The call goes at the start of the statement sequence
4091                --  after the start of exception range label if one is present.
4092
4093                declare
4094                   Stm : Node_Id;
4095
4096                begin
4097                   Stm := First (Statements (Handled_Statement_Sequence (N)));
4098
4099                   --  A special case, skip exception range label if one is
4100                   --  present (from front end zcx processing).
4101
4102                   if Nkind (Stm) = N_Label and then Exception_Junk (Stm) then
4103                      Next (Stm);
4104                   end if;
4105
4106                   --  Another special case, if the first statement is a block
4107                   --  from optimization of a local raise to a goto, then the
4108                   --  call goes inside this block.
4109
4110                   if Nkind (Stm) = N_Block_Statement
4111                     and then Exception_Junk (Stm)
4112                   then
4113                      Stm :=
4114                        First (Statements (Handled_Statement_Sequence (Stm)));
4115                   end if;
4116
4117                   --  Insertion point is after any exception label pushes,
4118                   --  since we want it covered by any local handlers.
4119
4120                   while Nkind (Stm) in N_Push_xxx_Label loop
4121                      Next (Stm);
4122                   end loop;
4123
4124                   --  Now we have the proper insertion point
4125
4126                   Insert_Before (Stm, Call);
4127                end;
4128
4129             else
4130                Set_Handled_Statement_Sequence (N,
4131                   Make_Handled_Sequence_Of_Statements (Loc,
4132                      Statements => New_List (Call)));
4133             end if;
4134          end if;
4135
4136          Analyze (Call);
4137          Check_Task_Activation (N);
4138       end if;
4139    end Build_Task_Activation_Call;
4140
4141    -------------------------------
4142    -- Build_Task_Allocate_Block --
4143    -------------------------------
4144
4145    procedure Build_Task_Allocate_Block
4146      (Actions : List_Id;
4147       N       : Node_Id;
4148       Args    : List_Id)
4149    is
4150       T      : constant Entity_Id  := Entity (Expression (N));
4151       Init   : constant Entity_Id  := Base_Init_Proc (T);
4152       Loc    : constant Source_Ptr := Sloc (N);
4153       Chain  : constant Entity_Id  :=
4154                  Make_Defining_Identifier (Loc, Name_uChain);
4155       Blkent : constant Entity_Id  := Make_Temporary (Loc, 'A');
4156       Block  : Node_Id;
4157
4158    begin
4159       Block :=
4160         Make_Block_Statement (Loc,
4161           Identifier   => New_Reference_To (Blkent, Loc),
4162           Declarations => New_List (
4163
4164             --  _Chain  : Activation_Chain;
4165
4166             Make_Object_Declaration (Loc,
4167               Defining_Identifier => Chain,
4168               Aliased_Present => True,
4169               Object_Definition   =>
4170                 New_Reference_To (RTE (RE_Activation_Chain), Loc))),
4171
4172           Handled_Statement_Sequence =>
4173             Make_Handled_Sequence_Of_Statements (Loc,
4174
4175               Statements => New_List (
4176
4177                --  Init (Args);
4178
4179                 Make_Procedure_Call_Statement (Loc,
4180                   Name => New_Reference_To (Init, Loc),
4181                   Parameter_Associations => Args),
4182
4183                --  Activate_Tasks (_Chain);
4184
4185                 Make_Procedure_Call_Statement (Loc,
4186                   Name => New_Reference_To (RTE (RE_Activate_Tasks), Loc),
4187                   Parameter_Associations => New_List (
4188                     Make_Attribute_Reference (Loc,
4189                       Prefix => New_Reference_To (Chain, Loc),
4190                       Attribute_Name => Name_Unchecked_Access))))),
4191
4192           Has_Created_Identifier => True,
4193           Is_Task_Allocation_Block => True);
4194
4195       Append_To (Actions,
4196         Make_Implicit_Label_Declaration (Loc,
4197           Defining_Identifier => Blkent,
4198           Label_Construct     => Block));
4199
4200       Append_To (Actions, Block);
4201
4202       Set_Activation_Chain_Entity (Block, Chain);
4203    end Build_Task_Allocate_Block;
4204
4205    -----------------------------------------------
4206    -- Build_Task_Allocate_Block_With_Init_Stmts --
4207    -----------------------------------------------
4208
4209    procedure Build_Task_Allocate_Block_With_Init_Stmts
4210      (Actions    : List_Id;
4211       N          : Node_Id;
4212       Init_Stmts : List_Id)
4213    is
4214       Loc    : constant Source_Ptr := Sloc (N);
4215       Chain  : constant Entity_Id  :=
4216                  Make_Defining_Identifier (Loc, Name_uChain);
4217       Blkent : constant Entity_Id  := Make_Temporary (Loc, 'A');
4218       Block  : Node_Id;
4219
4220    begin
4221       Append_To (Init_Stmts,
4222         Make_Procedure_Call_Statement (Loc,
4223           Name => New_Reference_To (RTE (RE_Activate_Tasks), Loc),
4224           Parameter_Associations => New_List (
4225             Make_Attribute_Reference (Loc,
4226               Prefix => New_Reference_To (Chain, Loc),
4227               Attribute_Name => Name_Unchecked_Access))));
4228
4229       Block :=
4230         Make_Block_Statement (Loc,
4231           Identifier => New_Reference_To (Blkent, Loc),
4232           Declarations => New_List (
4233
4234             --  _Chain  : Activation_Chain;
4235
4236             Make_Object_Declaration (Loc,
4237               Defining_Identifier => Chain,
4238               Aliased_Present => True,
4239               Object_Definition   =>
4240                 New_Reference_To (RTE (RE_Activation_Chain), Loc))),
4241
4242           Handled_Statement_Sequence =>
4243             Make_Handled_Sequence_Of_Statements (Loc, Init_Stmts),
4244
4245           Has_Created_Identifier => True,
4246           Is_Task_Allocation_Block => True);
4247
4248       Append_To (Actions,
4249         Make_Implicit_Label_Declaration (Loc,
4250           Defining_Identifier => Blkent,
4251           Label_Construct     => Block));
4252
4253       Append_To (Actions, Block);
4254
4255       Set_Activation_Chain_Entity (Block, Chain);
4256    end Build_Task_Allocate_Block_With_Init_Stmts;
4257
4258    -----------------------------------
4259    -- Build_Task_Proc_Specification --
4260    -----------------------------------
4261
4262    function Build_Task_Proc_Specification (T : Entity_Id) return Node_Id is
4263       Loc     : constant Source_Ptr := Sloc (T);
4264       Spec_Id : Entity_Id;
4265
4266    begin
4267       --  Case of explicit task type, suffix TB
4268
4269       if Comes_From_Source (T) then
4270          Spec_Id :=
4271            Make_Defining_Identifier (Loc,
4272              Chars => New_External_Name (Chars (T), "TB"));
4273
4274       --  Case of anonymous task type, suffix B
4275
4276       else
4277          Spec_Id :=
4278            Make_Defining_Identifier (Loc,
4279              Chars => New_External_Name (Chars (T), 'B'));
4280       end if;
4281
4282       Set_Is_Internal (Spec_Id);
4283
4284       --  Associate the procedure with the task, if this is the declaration
4285       --  (and not the body) of the procedure.
4286
4287       if No (Task_Body_Procedure (T)) then
4288          Set_Task_Body_Procedure (T, Spec_Id);
4289       end if;
4290
4291       return
4292         Make_Procedure_Specification (Loc,
4293           Defining_Unit_Name       => Spec_Id,
4294           Parameter_Specifications => New_List (
4295             Make_Parameter_Specification (Loc,
4296               Defining_Identifier =>
4297                 Make_Defining_Identifier (Loc, Name_uTask),
4298               Parameter_Type      =>
4299                 Make_Access_Definition (Loc,
4300                   Subtype_Mark =>
4301                     New_Reference_To (Corresponding_Record_Type (T), Loc)))));
4302    end Build_Task_Proc_Specification;
4303
4304    ---------------------------------------
4305    -- Build_Unprotected_Subprogram_Body --
4306    ---------------------------------------
4307
4308    function Build_Unprotected_Subprogram_Body
4309      (N   : Node_Id;
4310       Pid : Node_Id) return Node_Id
4311    is
4312       Decls : constant List_Id := Declarations (N);
4313
4314    begin
4315       --  Add renamings for the Protection object, discriminals, privals and
4316       --  the entry index constant for use by debugger.
4317
4318       Debug_Private_Data_Declarations (Decls);
4319
4320       --  Make an unprotected version of the subprogram for use within the same
4321       --  object, with a new name and an additional parameter representing the
4322       --  object.
4323
4324       return
4325         Make_Subprogram_Body (Sloc (N),
4326           Specification              =>
4327             Build_Protected_Sub_Specification (N, Pid, Unprotected_Mode),
4328           Declarations               => Decls,
4329           Handled_Statement_Sequence => Handled_Statement_Sequence (N));
4330    end Build_Unprotected_Subprogram_Body;
4331
4332    ----------------------------
4333    -- Collect_Entry_Families --
4334    ----------------------------
4335
4336    procedure Collect_Entry_Families
4337      (Loc          : Source_Ptr;
4338       Cdecls       : List_Id;
4339       Current_Node : in out Node_Id;
4340       Conctyp      : Entity_Id)
4341    is
4342       Efam      : Entity_Id;
4343       Efam_Decl : Node_Id;
4344       Efam_Type : Entity_Id;
4345
4346    begin
4347       Efam := First_Entity (Conctyp);
4348       while Present (Efam) loop
4349          if Ekind (Efam) = E_Entry_Family then
4350             Efam_Type := Make_Temporary (Loc, 'F');
4351
4352             declare
4353                Bas : Entity_Id :=
4354                        Base_Type
4355                         (Etype (Discrete_Subtype_Definition (Parent (Efam))));
4356
4357                Bas_Decl : Node_Id := Empty;
4358                Lo, Hi   : Node_Id;
4359
4360             begin
4361                Get_Index_Bounds
4362                  (Discrete_Subtype_Definition (Parent (Efam)), Lo, Hi);
4363
4364                if Is_Potentially_Large_Family (Bas, Conctyp, Lo, Hi) then
4365                   Bas := Make_Temporary (Loc, 'B');
4366
4367                   Bas_Decl :=
4368                     Make_Subtype_Declaration (Loc,
4369                        Defining_Identifier => Bas,
4370                        Subtype_Indication  =>
4371                          Make_Subtype_Indication (Loc,
4372                            Subtype_Mark =>
4373                              New_Occurrence_Of (Standard_Integer, Loc),
4374                            Constraint   =>
4375                              Make_Range_Constraint (Loc,
4376                                Range_Expression => Make_Range (Loc,
4377                                  Make_Integer_Literal
4378                                    (Loc, -Entry_Family_Bound),
4379                                  Make_Integer_Literal
4380                                    (Loc, Entry_Family_Bound - 1)))));
4381
4382                   Insert_After (Current_Node, Bas_Decl);
4383                   Current_Node := Bas_Decl;
4384                   Analyze (Bas_Decl);
4385                end if;
4386
4387                Efam_Decl :=
4388                  Make_Full_Type_Declaration (Loc,
4389                    Defining_Identifier => Efam_Type,
4390                    Type_Definition =>
4391                      Make_Unconstrained_Array_Definition (Loc,
4392                        Subtype_Marks =>
4393                          (New_List (New_Occurrence_Of (Bas, Loc))),
4394
4395                     Component_Definition =>
4396                       Make_Component_Definition (Loc,
4397                         Aliased_Present    => False,
4398                         Subtype_Indication =>
4399                           New_Reference_To (Standard_Character, Loc))));
4400             end;
4401
4402             Insert_After (Current_Node, Efam_Decl);
4403             Current_Node := Efam_Decl;
4404             Analyze (Efam_Decl);
4405
4406             Append_To (Cdecls,
4407               Make_Component_Declaration (Loc,
4408                 Defining_Identifier =>
4409                   Make_Defining_Identifier (Loc, Chars (Efam)),
4410
4411                 Component_Definition =>
4412                   Make_Component_Definition (Loc,
4413                     Aliased_Present    => False,
4414                     Subtype_Indication =>
4415                       Make_Subtype_Indication (Loc,
4416                         Subtype_Mark =>
4417                           New_Occurrence_Of (Efam_Type, Loc),
4418
4419                         Constraint  =>
4420                           Make_Index_Or_Discriminant_Constraint (Loc,
4421                             Constraints => New_List (
4422                               New_Occurrence_Of
4423                                 (Etype (Discrete_Subtype_Definition
4424                                   (Parent (Efam))), Loc)))))));
4425
4426          end if;
4427
4428          Next_Entity (Efam);
4429       end loop;
4430    end Collect_Entry_Families;
4431
4432    -----------------------
4433    -- Concurrent_Object --
4434    -----------------------
4435
4436    function Concurrent_Object
4437      (Spec_Id  : Entity_Id;
4438       Conc_Typ : Entity_Id) return Entity_Id
4439    is
4440    begin
4441       --  Parameter _O or _object
4442
4443       if Is_Protected_Type (Conc_Typ) then
4444          return First_Formal (Protected_Body_Subprogram (Spec_Id));
4445
4446       --  Parameter _task
4447
4448       else
4449          pragma Assert (Is_Task_Type (Conc_Typ));
4450          return First_Formal (Task_Body_Procedure (Conc_Typ));
4451       end if;
4452    end Concurrent_Object;
4453
4454    ----------------------
4455    -- Copy_Result_Type --
4456    ----------------------
4457
4458    function Copy_Result_Type (Res : Node_Id) return Node_Id is
4459       New_Res  : constant Node_Id := New_Copy_Tree (Res);
4460       Par_Spec : Node_Id;
4461       Formal   : Entity_Id;
4462
4463    begin
4464       --  If the result type is an access_to_subprogram, we must create
4465       --  new entities for its spec.
4466
4467       if Nkind (New_Res) = N_Access_Definition
4468         and then Present (Access_To_Subprogram_Definition (New_Res))
4469       then
4470          --  Provide new entities for the formals
4471
4472          Par_Spec := First (Parameter_Specifications
4473                               (Access_To_Subprogram_Definition (New_Res)));
4474          while Present (Par_Spec) loop
4475             Formal := Defining_Identifier (Par_Spec);
4476             Set_Defining_Identifier (Par_Spec,
4477               Make_Defining_Identifier (Sloc (Formal), Chars (Formal)));
4478             Next (Par_Spec);
4479          end loop;
4480       end if;
4481
4482       return New_Res;
4483    end Copy_Result_Type;
4484
4485    --------------------
4486    -- Concurrent_Ref --
4487    --------------------
4488
4489    --  The expression returned for a reference to a concurrent object has the
4490    --  form:
4491
4492    --    taskV!(name)._Task_Id
4493
4494    --  for a task, and
4495
4496    --    objectV!(name)._Object
4497
4498    --  for a protected object. For the case of an access to a concurrent
4499    --  object, there is an extra explicit dereference:
4500
4501    --    taskV!(name.all)._Task_Id
4502    --    objectV!(name.all)._Object
4503
4504    --  here taskV and objectV are the types for the associated records, which
4505    --  contain the required _Task_Id and _Object fields for tasks and protected
4506    --  objects, respectively.
4507
4508    --  For the case of a task type name, the expression is
4509
4510    --    Self;
4511
4512    --  i.e. a call to the Self function which returns precisely this Task_Id
4513
4514    --  For the case of a protected type name, the expression is
4515
4516    --    objectR
4517
4518    --  which is a renaming of the _object field of the current object
4519    --  record, passed into protected operations as a parameter.
4520
4521    function Concurrent_Ref (N : Node_Id) return Node_Id is
4522       Loc  : constant Source_Ptr := Sloc (N);
4523       Ntyp : constant Entity_Id  := Etype (N);
4524       Dtyp : Entity_Id;
4525       Sel  : Name_Id;
4526
4527       function Is_Current_Task (T : Entity_Id) return Boolean;
4528       --  Check whether the reference is to the immediately enclosing task
4529       --  type, or to an outer one (rare but legal).
4530
4531       ---------------------
4532       -- Is_Current_Task --
4533       ---------------------
4534
4535       function Is_Current_Task (T : Entity_Id) return Boolean is
4536          Scop : Entity_Id;
4537
4538       begin
4539          Scop := Current_Scope;
4540          while Present (Scop)
4541            and then Scop /= Standard_Standard
4542          loop
4543
4544             if Scop = T then
4545                return True;
4546
4547             elsif Is_Task_Type (Scop) then
4548                return False;
4549
4550             --  If this is a procedure nested within the task type, we must
4551             --  assume that it can be called from an inner task, and therefore
4552             --  cannot treat it as a local reference.
4553
4554             elsif Is_Overloadable (Scop)
4555               and then In_Open_Scopes (T)
4556             then
4557                return False;
4558
4559             else
4560                Scop := Scope (Scop);
4561             end if;
4562          end loop;
4563
4564          --  We know that we are within the task body, so should have found it
4565          --  in scope.
4566
4567          raise Program_Error;
4568       end Is_Current_Task;
4569
4570    --  Start of processing for Concurrent_Ref
4571
4572    begin
4573       if Is_Access_Type (Ntyp) then
4574          Dtyp := Designated_Type (Ntyp);
4575
4576          if Is_Protected_Type (Dtyp) then
4577             Sel := Name_uObject;
4578          else
4579             Sel := Name_uTask_Id;
4580          end if;
4581
4582          return
4583            Make_Selected_Component (Loc,
4584              Prefix =>
4585                Unchecked_Convert_To (Corresponding_Record_Type (Dtyp),
4586                  Make_Explicit_Dereference (Loc, N)),
4587              Selector_Name => Make_Identifier (Loc, Sel));
4588
4589       elsif Is_Entity_Name (N)
4590         and then Is_Concurrent_Type (Entity (N))
4591       then
4592          if Is_Task_Type (Entity (N)) then
4593
4594             if Is_Current_Task (Entity (N)) then
4595                return
4596                  Make_Function_Call (Loc,
4597                    Name => New_Reference_To (RTE (RE_Self), Loc));
4598
4599             else
4600                declare
4601                   Decl   : Node_Id;
4602                   T_Self : constant Entity_Id := Make_Temporary (Loc, 'T');
4603                   T_Body : constant Node_Id :=
4604                              Parent (Corresponding_Body (Parent (Entity (N))));
4605
4606                begin
4607                   Decl :=
4608                     Make_Object_Declaration (Loc,
4609                       Defining_Identifier => T_Self,
4610                       Object_Definition   =>
4611                         New_Occurrence_Of (RTE (RO_ST_Task_Id), Loc),
4612                       Expression          =>
4613                         Make_Function_Call (Loc,
4614                           Name => New_Reference_To (RTE (RE_Self), Loc)));
4615                   Prepend (Decl, Declarations (T_Body));
4616                   Analyze (Decl);
4617                   Set_Scope (T_Self, Entity (N));
4618                   return New_Occurrence_Of (T_Self,  Loc);
4619                end;
4620             end if;
4621
4622          else
4623             pragma Assert (Is_Protected_Type (Entity (N)));
4624
4625             return
4626               New_Reference_To (Find_Protection_Object (Current_Scope), Loc);
4627          end if;
4628
4629       else
4630          if Is_Protected_Type (Ntyp) then
4631             Sel := Name_uObject;
4632
4633          elsif Is_Task_Type (Ntyp) then
4634             Sel := Name_uTask_Id;
4635
4636          else
4637             raise Program_Error;
4638          end if;
4639
4640          return
4641            Make_Selected_Component (Loc,
4642              Prefix        =>
4643                Unchecked_Convert_To (Corresponding_Record_Type (Ntyp),
4644                  New_Copy_Tree (N)),
4645              Selector_Name => Make_Identifier (Loc, Sel));
4646       end if;
4647    end Concurrent_Ref;
4648
4649    ------------------------
4650    -- Convert_Concurrent --
4651    ------------------------
4652
4653    function Convert_Concurrent
4654      (N   : Node_Id;
4655       Typ : Entity_Id) return Node_Id
4656    is
4657    begin
4658       if not Is_Concurrent_Type (Typ) then
4659          return N;
4660       else
4661          return
4662            Unchecked_Convert_To
4663              (Corresponding_Record_Type (Typ), New_Copy_Tree (N));
4664       end if;
4665    end Convert_Concurrent;
4666
4667    -------------------------------------
4668    -- Debug_Private_Data_Declarations --
4669    -------------------------------------
4670
4671    procedure Debug_Private_Data_Declarations (Decls : List_Id) is
4672       Debug_Nod : Node_Id;
4673       Decl      : Node_Id;
4674
4675    begin
4676       Decl := First (Decls);
4677       while Present (Decl)
4678         and then not Comes_From_Source (Decl)
4679       loop
4680          --  Declaration for concurrent entity _object and its access type,
4681          --  along with the entry index subtype:
4682          --    type prot_typVP is access prot_typV;
4683          --    _object : prot_typVP := prot_typV (_O);
4684          --    subtype Jnn is <Type of Index> range Low .. High;
4685
4686          if Nkind_In (Decl, N_Full_Type_Declaration, N_Object_Declaration) then
4687             Set_Debug_Info_Needed (Defining_Identifier (Decl));
4688
4689          --  Declaration for the Protection object, discriminals, privals and
4690          --  entry index constant:
4691          --    conc_typR   : protection_typ renames _object._object;
4692          --    discr_nameD : discr_typ renames _object.discr_name;
4693          --    discr_nameD : discr_typ renames _task.discr_name;
4694          --    prival_name : comp_typ  renames _object.comp_name;
4695          --    J : constant Jnn :=
4696          --          Jnn'Val (_E - <Index expression> + Jnn'Pos (Jnn'First));
4697
4698          elsif Nkind (Decl) = N_Object_Renaming_Declaration then
4699             Set_Debug_Info_Needed (Defining_Identifier (Decl));
4700             Debug_Nod := Debug_Renaming_Declaration (Decl);
4701
4702             if Present (Debug_Nod) then
4703                Insert_After (Decl, Debug_Nod);
4704             end if;
4705          end if;
4706
4707          Next (Decl);
4708       end loop;
4709    end Debug_Private_Data_Declarations;
4710
4711    ----------------------------
4712    -- Entry_Index_Expression --
4713    ----------------------------
4714
4715    function Entry_Index_Expression
4716      (Sloc  : Source_Ptr;
4717       Ent   : Entity_Id;
4718       Index : Node_Id;
4719       Ttyp  : Entity_Id) return Node_Id
4720    is
4721       Expr : Node_Id;
4722       Num  : Node_Id;
4723       Lo   : Node_Id;
4724       Hi   : Node_Id;
4725       Prev : Entity_Id;
4726       S    : Node_Id;
4727
4728    begin
4729       --  The queues of entries and entry families appear in textual order in
4730       --  the associated record. The entry index is computed as the sum of the
4731       --  number of queues for all entries that precede the designated one, to
4732       --  which is added the index expression, if this expression denotes a
4733       --  member of a family.
4734
4735       --  The following is a place holder for the count of simple entries
4736
4737       Num := Make_Integer_Literal (Sloc, 1);
4738
4739       --  We construct an expression which is a series of addition operations.
4740       --  The first operand is the number of single entries that precede this
4741       --  one, the second operand is the index value relative to the start of
4742       --  the referenced family, and the remaining operands are the lengths of
4743       --  the entry families that precede this entry, i.e. the constructed
4744       --  expression is:
4745
4746       --    number_simple_entries +
4747       --      (s'pos (index-value) - s'pos (family'first)) + 1 +
4748       --      family'length + ...
4749
4750       --  where index-value is the given index value, and s is the index
4751       --  subtype (we have to use pos because the subtype might be an
4752       --  enumeration type preventing direct subtraction). Note that the task
4753       --  entry array is one-indexed.
4754
4755       --  The upper bound of the entry family may be a discriminant, so we
4756       --  retrieve the lower bound explicitly to compute offset, rather than
4757       --  using the index subtype which may mention a discriminant.
4758
4759       if Present (Index) then
4760          S := Etype (Discrete_Subtype_Definition (Declaration_Node (Ent)));
4761
4762          Expr :=
4763            Make_Op_Add (Sloc,
4764              Left_Opnd  => Num,
4765
4766              Right_Opnd =>
4767                Family_Offset (
4768                  Sloc,
4769                  Make_Attribute_Reference (Sloc,
4770                    Attribute_Name => Name_Pos,
4771                    Prefix => New_Reference_To (Base_Type (S), Sloc),
4772                    Expressions => New_List (Relocate_Node (Index))),
4773                  Type_Low_Bound (S),
4774                  Ttyp,
4775                  False));
4776       else
4777          Expr := Num;
4778       end if;
4779
4780       --  Now add lengths of preceding entries and entry families
4781
4782       Prev := First_Entity (Ttyp);
4783
4784       while Chars (Prev) /= Chars (Ent)
4785         or else (Ekind (Prev) /= Ekind (Ent))
4786         or else not Sem_Ch6.Type_Conformant (Ent, Prev)
4787       loop
4788          if Ekind (Prev) = E_Entry then
4789             Set_Intval (Num, Intval (Num) + 1);
4790
4791          elsif Ekind (Prev) = E_Entry_Family then
4792             S :=
4793               Etype (Discrete_Subtype_Definition (Declaration_Node (Prev)));
4794             Lo := Type_Low_Bound  (S);
4795             Hi := Type_High_Bound (S);
4796
4797             Expr :=
4798               Make_Op_Add (Sloc,
4799               Left_Opnd  => Expr,
4800               Right_Opnd => Family_Size (Sloc, Hi, Lo, Ttyp, False));
4801
4802          --  Other components are anonymous types to be ignored
4803
4804          else
4805             null;
4806          end if;
4807
4808          Next_Entity (Prev);
4809       end loop;
4810
4811       return Expr;
4812    end Entry_Index_Expression;
4813
4814    ---------------------------
4815    -- Establish_Task_Master --
4816    ---------------------------
4817
4818    procedure Establish_Task_Master (N : Node_Id) is
4819       Call : Node_Id;
4820    begin
4821       if Restriction_Active (No_Task_Hierarchy) = False then
4822          Call := Build_Runtime_Call (Sloc (N), RE_Enter_Master);
4823          Prepend_To (Declarations (N), Call);
4824          Analyze (Call);
4825       end if;
4826    end Establish_Task_Master;
4827
4828    --------------------------------
4829    -- Expand_Accept_Declarations --
4830    --------------------------------
4831
4832    --  Part of the expansion of an accept statement involves the creation of
4833    --  a declaration that can be referenced from the statement sequence of
4834    --  the accept:
4835
4836    --    Ann : Address;
4837
4838    --  This declaration is inserted immediately before the accept statement
4839    --  and it is important that it be inserted before the statements of the
4840    --  statement sequence are analyzed. Thus it would be too late to create
4841    --  this declaration in the Expand_N_Accept_Statement routine, which is
4842    --  why there is a separate procedure to be called directly from Sem_Ch9.
4843
4844    --  Ann is used to hold the address of the record containing the parameters
4845    --  (see Expand_N_Entry_Call for more details on how this record is built).
4846    --  References to the parameters do an unchecked conversion of this address
4847    --  to a pointer to the required record type, and then access the field that
4848    --  holds the value of the required parameter. The entity for the address
4849    --  variable is held as the top stack element (i.e. the last element) of the
4850    --  Accept_Address stack in the corresponding entry entity, and this element
4851    --  must be set in place  before the statements are processed.
4852
4853    --  The above description applies to the case of a stand alone accept
4854    --  statement, i.e. one not appearing as part of a select alternative.
4855
4856    --  For the case of an accept that appears as part of a select alternative
4857    --  of a selective accept, we must still create the declaration right away,
4858    --  since Ann is needed immediately, but there is an important difference:
4859
4860    --    The declaration is inserted before the selective accept, not before
4861    --    the accept statement (which is not part of a list anyway, and so would
4862    --    not accommodate inserted declarations)
4863
4864    --    We only need one address variable for the entire selective accept. So
4865    --    the Ann declaration is created only for the first accept alternative,
4866    --    and subsequent accept alternatives reference the same Ann variable.
4867
4868    --  We can distinguish the two cases by seeing whether the accept statement
4869    --  is part of a list. If not, then it must be in an accept alternative.
4870
4871    --  To expand the requeue statement, a label is provided at the end of the
4872    --  accept statement or alternative of which it is a part, so that the
4873    --  statement can be skipped after the requeue is complete. This label is
4874    --  created here rather than during the expansion of the accept statement,
4875    --  because it will be needed by any requeue statements within the accept,
4876    --  which are expanded before the accept.
4877
4878    procedure Expand_Accept_Declarations (N : Node_Id; Ent : Entity_Id) is
4879       Loc    : constant Source_Ptr := Sloc (N);
4880       Stats  : constant Node_Id    := Handled_Statement_Sequence (N);
4881       Ann    : Entity_Id           := Empty;
4882       Adecl  : Node_Id;
4883       Lab_Id : Node_Id;
4884       Lab    : Node_Id;
4885       Ldecl  : Node_Id;
4886       Ldecl2 : Node_Id;
4887
4888    begin
4889       if Expander_Active then
4890
4891          --  If we have no handled statement sequence, we may need to build
4892          --  a dummy sequence consisting of a null statement. This can be
4893          --  skipped if the trivial accept optimization is permitted.
4894
4895          if not Trivial_Accept_OK
4896            and then
4897              (No (Stats) or else Null_Statements (Statements (Stats)))
4898          then
4899             Set_Handled_Statement_Sequence (N,
4900               Make_Handled_Sequence_Of_Statements (Loc,
4901                 New_List (Make_Null_Statement (Loc))));
4902          end if;
4903
4904          --  Create and declare two labels to be placed at the end of the
4905          --  accept statement. The first label is used to allow requeues to
4906          --  skip the remainder of entry processing. The second label is used
4907          --  to skip the remainder of entry processing if the rendezvous
4908          --  completes in the middle of the accept body.
4909
4910          if Present (Handled_Statement_Sequence (N)) then
4911             declare
4912                Ent : Entity_Id;
4913
4914             begin
4915                Ent := Make_Temporary (Loc, 'L');
4916                Lab_Id := New_Reference_To (Ent, Loc);
4917                Lab := Make_Label (Loc, Lab_Id);
4918                Ldecl :=
4919                  Make_Implicit_Label_Declaration (Loc,
4920                    Defining_Identifier  => Ent,
4921                    Label_Construct      => Lab);
4922                Append (Lab, Statements (Handled_Statement_Sequence (N)));
4923
4924                Ent := Make_Temporary (Loc, 'L');
4925                Lab_Id := New_Reference_To (Ent, Loc);
4926                Lab := Make_Label (Loc, Lab_Id);
4927                Ldecl2 :=
4928                  Make_Implicit_Label_Declaration (Loc,
4929                    Defining_Identifier  => Ent,
4930                    Label_Construct      => Lab);
4931                Append (Lab, Statements (Handled_Statement_Sequence (N)));
4932             end;
4933
4934          else
4935             Ldecl := Empty;
4936             Ldecl2 := Empty;
4937          end if;
4938
4939          --  Case of stand alone accept statement
4940
4941          if Is_List_Member (N) then
4942
4943             if Present (Handled_Statement_Sequence (N)) then
4944                Ann := Make_Temporary (Loc, 'A');
4945
4946                Adecl :=
4947                  Make_Object_Declaration (Loc,
4948                    Defining_Identifier => Ann,
4949                    Object_Definition =>
4950                      New_Reference_To (RTE (RE_Address), Loc));
4951
4952                Insert_Before (N, Adecl);
4953                Analyze (Adecl);
4954
4955                Insert_Before (N, Ldecl);
4956                Analyze (Ldecl);
4957
4958                Insert_Before (N, Ldecl2);
4959                Analyze (Ldecl2);
4960             end if;
4961
4962          --  Case of accept statement which is in an accept alternative
4963
4964          else
4965             declare
4966                Acc_Alt : constant Node_Id := Parent (N);
4967                Sel_Acc : constant Node_Id := Parent (Acc_Alt);
4968                Alt     : Node_Id;
4969
4970             begin
4971                pragma Assert (Nkind (Acc_Alt) = N_Accept_Alternative);
4972                pragma Assert (Nkind (Sel_Acc) = N_Selective_Accept);
4973
4974                --  ??? Consider a single label for select statements
4975
4976                if Present (Handled_Statement_Sequence (N)) then
4977                   Prepend (Ldecl2,
4978                      Statements (Handled_Statement_Sequence (N)));
4979                   Analyze (Ldecl2);
4980
4981                   Prepend (Ldecl,
4982                      Statements (Handled_Statement_Sequence (N)));
4983                   Analyze (Ldecl);
4984                end if;
4985
4986                --  Find first accept alternative of the selective accept. A
4987                --  valid selective accept must have at least one accept in it.
4988
4989                Alt := First (Select_Alternatives (Sel_Acc));
4990
4991                while Nkind (Alt) /= N_Accept_Alternative loop
4992                   Next (Alt);
4993                end loop;
4994
4995                --  If we are the first accept statement, then we have to create
4996                --  the Ann variable, as for the stand alone case, except that
4997                --  it is inserted before the selective accept. Similarly, a
4998                --  label for requeue expansion must be declared.
4999
5000                if N = Accept_Statement (Alt) then
5001                   Ann := Make_Temporary (Loc, 'A');
5002                   Adecl :=
5003                     Make_Object_Declaration (Loc,
5004                       Defining_Identifier => Ann,
5005                       Object_Definition =>
5006                         New_Reference_To (RTE (RE_Address), Loc));
5007
5008                   Insert_Before (Sel_Acc, Adecl);
5009                   Analyze (Adecl);
5010
5011                --  If we are not the first accept statement, then find the Ann
5012                --  variable allocated by the first accept and use it.
5013
5014                else
5015                   Ann :=
5016                     Node (Last_Elmt (Accept_Address
5017                       (Entity (Entry_Direct_Name (Accept_Statement (Alt))))));
5018                end if;
5019             end;
5020          end if;
5021
5022          --  Merge here with Ann either created or referenced, and Adecl
5023          --  pointing to the corresponding declaration. Remaining processing
5024          --  is the same for the two cases.
5025
5026          if Present (Ann) then
5027             Append_Elmt (Ann, Accept_Address (Ent));
5028             Set_Debug_Info_Needed (Ann);
5029          end if;
5030
5031          --  Create renaming declarations for the entry formals. Each reference
5032          --  to a formal becomes a dereference of a component of the parameter
5033          --  block, whose address is held in Ann. These declarations are
5034          --  eventually inserted into the accept block, and analyzed there so
5035          --  that they have the proper scope for gdb and do not conflict with
5036          --  other declarations.
5037
5038          if Present (Parameter_Specifications (N))
5039            and then Present (Handled_Statement_Sequence (N))
5040          then
5041             declare
5042                Comp           : Entity_Id;
5043                Decl           : Node_Id;
5044                Formal         : Entity_Id;
5045                New_F          : Entity_Id;
5046                Renamed_Formal : Node_Id;
5047
5048             begin
5049                Push_Scope (Ent);
5050                Formal := First_Formal (Ent);
5051
5052                while Present (Formal) loop
5053                   Comp  := Entry_Component (Formal);
5054                   New_F :=
5055                     Make_Defining_Identifier (Loc, Chars (Formal));
5056
5057                   Set_Etype (New_F, Etype (Formal));
5058                   Set_Scope (New_F, Ent);
5059
5060                   --  Now we set debug info needed on New_F even though it does
5061                   --  not come from source, so that the debugger will get the
5062                   --  right information for these generated names.
5063
5064                   Set_Debug_Info_Needed (New_F);
5065
5066                   if Ekind (Formal) = E_In_Parameter then
5067                      Set_Ekind (New_F, E_Constant);
5068                   else
5069                      Set_Ekind (New_F, E_Variable);
5070                      Set_Extra_Constrained (New_F, Extra_Constrained (Formal));
5071                   end if;
5072
5073                   Set_Actual_Subtype (New_F, Actual_Subtype (Formal));
5074
5075                   Renamed_Formal :=
5076                      Make_Selected_Component (Loc,
5077                        Prefix        =>
5078                          Unchecked_Convert_To (
5079                            Entry_Parameters_Type (Ent),
5080                            New_Reference_To (Ann, Loc)),
5081                        Selector_Name =>
5082                          New_Reference_To (Comp, Loc));
5083
5084                   Decl :=
5085                     Build_Renamed_Formal_Declaration
5086                       (New_F, Formal, Comp, Renamed_Formal);
5087
5088                   if No (Declarations (N)) then
5089                      Set_Declarations (N, New_List);
5090                   end if;
5091
5092                   Append (Decl, Declarations (N));
5093                   Set_Renamed_Object (Formal, New_F);
5094                   Next_Formal (Formal);
5095                end loop;
5096
5097                End_Scope;
5098             end;
5099          end if;
5100       end if;
5101    end Expand_Accept_Declarations;
5102
5103    ---------------------------------------------
5104    -- Expand_Access_Protected_Subprogram_Type --
5105    ---------------------------------------------
5106
5107    procedure Expand_Access_Protected_Subprogram_Type (N : Node_Id) is
5108       Loc    : constant Source_Ptr := Sloc (N);
5109       Comps  : List_Id;
5110       T      : constant Entity_Id  := Defining_Identifier (N);
5111       D_T    : constant Entity_Id  := Designated_Type (T);
5112       D_T2   : constant Entity_Id  := Make_Temporary (Loc, 'D');
5113       E_T    : constant Entity_Id  := Make_Temporary (Loc, 'E');
5114       P_List : constant List_Id    := Build_Protected_Spec
5115                                         (N, RTE (RE_Address), D_T, False);
5116       Decl1  : Node_Id;
5117       Decl2  : Node_Id;
5118       Def1   : Node_Id;
5119
5120    begin
5121       --  Create access to subprogram with full signature
5122
5123       if Etype (D_T) /= Standard_Void_Type then
5124          Def1 :=
5125            Make_Access_Function_Definition (Loc,
5126              Parameter_Specifications => P_List,
5127              Result_Definition =>
5128                Copy_Result_Type (Result_Definition (Type_Definition (N))));
5129
5130       else
5131          Def1 :=
5132            Make_Access_Procedure_Definition (Loc,
5133              Parameter_Specifications => P_List);
5134       end if;
5135
5136       Decl1 :=
5137         Make_Full_Type_Declaration (Loc,
5138           Defining_Identifier => D_T2,
5139           Type_Definition => Def1);
5140
5141       Insert_After (N, Decl1);
5142       Analyze (Decl1);
5143
5144       --  Associate the access to subprogram with its original access to
5145       --  protected subprogram type. Needed by the backend to know that this
5146       --  type corresponds with an access to protected subprogram type.
5147
5148       Set_Original_Access_Type (D_T2, T);
5149
5150       --  Create Equivalent_Type, a record with two components for an access to
5151       --  object and an access to subprogram.
5152
5153       Comps := New_List (
5154         Make_Component_Declaration (Loc,
5155           Defining_Identifier => Make_Temporary (Loc, 'P'),
5156           Component_Definition =>
5157             Make_Component_Definition (Loc,
5158               Aliased_Present => False,
5159               Subtype_Indication =>
5160                 New_Occurrence_Of (RTE (RE_Address), Loc))),
5161
5162         Make_Component_Declaration (Loc,
5163           Defining_Identifier  => Make_Temporary (Loc, 'S'),
5164           Component_Definition =>
5165             Make_Component_Definition (Loc,
5166               Aliased_Present    => False,
5167               Subtype_Indication => New_Occurrence_Of (D_T2, Loc))));
5168
5169       Decl2 :=
5170         Make_Full_Type_Declaration (Loc,
5171           Defining_Identifier => E_T,
5172           Type_Definition =>
5173             Make_Record_Definition (Loc,
5174               Component_List =>
5175                 Make_Component_List (Loc,
5176                   Component_Items => Comps)));
5177
5178       Insert_After (Decl1, Decl2);
5179       Analyze (Decl2);
5180       Set_Equivalent_Type (T, E_T);
5181    end Expand_Access_Protected_Subprogram_Type;
5182
5183    --------------------------
5184    -- Expand_Entry_Barrier --
5185    --------------------------
5186
5187    procedure Expand_Entry_Barrier (N : Node_Id; Ent : Entity_Id) is
5188       Cond      : constant Node_Id   :=
5189                     Condition (Entry_Body_Formal_Part (N));
5190       Prot      : constant Entity_Id := Scope (Ent);
5191       Spec_Decl : constant Node_Id   := Parent (Prot);
5192       Func      : Node_Id;
5193       B_F       : Node_Id;
5194       Body_Decl : Node_Id;
5195
5196    begin
5197       if No_Run_Time_Mode then
5198          Error_Msg_CRT ("entry barrier", N);
5199          return;
5200       end if;
5201
5202       --  The body of the entry barrier must be analyzed in the context of the
5203       --  protected object, but its scope is external to it, just as any other
5204       --  unprotected version of a protected operation. The specification has
5205       --  been produced when the protected type declaration was elaborated. We
5206       --  build the body, insert it in the enclosing scope, but analyze it in
5207       --  the current context. A more uniform approach would be to treat the
5208       --  barrier just as a protected function, and discard the protected
5209       --  version of it because it is never called.
5210
5211       if Expander_Active then
5212          B_F := Build_Barrier_Function (N, Ent, Prot);
5213          Func := Barrier_Function (Ent);
5214          Set_Corresponding_Spec (B_F, Func);
5215
5216          Body_Decl := Parent (Corresponding_Body (Spec_Decl));
5217
5218          if Nkind (Parent (Body_Decl)) = N_Subunit then
5219             Body_Decl := Corresponding_Stub (Parent (Body_Decl));
5220          end if;
5221
5222          Insert_Before_And_Analyze (Body_Decl, B_F);
5223
5224          Set_Discriminals (Spec_Decl);
5225          Set_Scope (Func, Scope (Prot));
5226
5227       else
5228          Analyze_And_Resolve (Cond, Any_Boolean);
5229       end if;
5230
5231       --  The Ravenscar profile restricts barriers to simple variables declared
5232       --  within the protected object. We also allow Boolean constants, since
5233       --  these appear in several published examples and are also allowed by
5234       --  the Aonix compiler.
5235
5236       --  Note that after analysis variables in this context will be replaced
5237       --  by the corresponding prival, that is to say a renaming of a selected
5238       --  component of the form _Object.Var. If expansion is disabled, as
5239       --  within a generic, we check that the entity appears in the current
5240       --  scope.
5241
5242       if Is_Entity_Name (Cond) then
5243
5244          --  A small optimization of useless renamings. If the scope of the
5245          --  entity of the condition is not the barrier function, then the
5246          --  condition does not reference any of the generated renamings
5247          --  within the function.
5248
5249          if Expander_Active
5250            and then Scope (Entity (Cond)) /= Func
5251          then
5252             Set_Declarations (B_F, Empty_List);
5253          end if;
5254
5255          if Entity (Cond) = Standard_False
5256               or else
5257             Entity (Cond) = Standard_True
5258          then
5259             return;
5260
5261          elsif not Expander_Active
5262            and then Scope (Entity (Cond)) = Current_Scope
5263          then
5264             return;
5265
5266          --  Check for case of _object.all.field (note that the explicit
5267          --  dereference gets inserted by analyze/expand of _object.field)
5268
5269          elsif Present (Renamed_Object (Entity (Cond)))
5270            and then
5271              Nkind (Renamed_Object (Entity (Cond))) = N_Selected_Component
5272            and then
5273              Chars
5274                (Prefix
5275                  (Prefix (Renamed_Object (Entity (Cond))))) = Name_uObject
5276          then
5277             return;
5278          end if;
5279       end if;
5280
5281       --  It is not a boolean variable or literal, so check the restriction
5282
5283       Check_Restriction (Simple_Barriers, Cond);
5284    end Expand_Entry_Barrier;
5285
5286    ------------------------------
5287    -- Expand_N_Abort_Statement --
5288    ------------------------------
5289
5290    --  Expand abort T1, T2, .. Tn; into:
5291    --    Abort_Tasks (Task_List'(1 => T1.Task_Id, 2 => T2.Task_Id ...))
5292
5293    procedure Expand_N_Abort_Statement (N : Node_Id) is
5294       Loc    : constant Source_Ptr := Sloc (N);
5295       Tlist  : constant List_Id    := Names (N);
5296       Count  : Nat;
5297       Aggr   : Node_Id;
5298       Tasknm : Node_Id;
5299
5300    begin
5301       Aggr := Make_Aggregate (Loc, Component_Associations => New_List);
5302       Count := 0;
5303
5304       Tasknm := First (Tlist);
5305
5306       while Present (Tasknm) loop
5307          Count := Count + 1;
5308
5309          --  A task interface class-wide type object is being aborted.
5310          --  Retrieve its _task_id by calling a dispatching routine.
5311
5312          if Ada_Version >= Ada_2005
5313            and then Ekind (Etype (Tasknm)) = E_Class_Wide_Type
5314            and then Is_Interface (Etype (Tasknm))
5315            and then Is_Task_Interface (Etype (Tasknm))
5316          then
5317             Append_To (Component_Associations (Aggr),
5318               Make_Component_Association (Loc,
5319                 Choices => New_List (
5320                   Make_Integer_Literal (Loc, Count)),
5321                 Expression =>
5322
5323                   --  Task_Id (Tasknm._disp_get_task_id)
5324
5325                   Make_Unchecked_Type_Conversion (Loc,
5326                     Subtype_Mark =>
5327                       New_Reference_To (RTE (RO_ST_Task_Id), Loc),
5328                     Expression =>
5329                       Make_Selected_Component (Loc,
5330                         Prefix        => New_Copy_Tree (Tasknm),
5331                         Selector_Name =>
5332                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id)))));
5333
5334          else
5335             Append_To (Component_Associations (Aggr),
5336               Make_Component_Association (Loc,
5337                 Choices => New_List (
5338                   Make_Integer_Literal (Loc, Count)),
5339                 Expression => Concurrent_Ref (Tasknm)));
5340          end if;
5341
5342          Next (Tasknm);
5343       end loop;
5344
5345       Rewrite (N,
5346         Make_Procedure_Call_Statement (Loc,
5347           Name => New_Reference_To (RTE (RE_Abort_Tasks), Loc),
5348           Parameter_Associations => New_List (
5349             Make_Qualified_Expression (Loc,
5350               Subtype_Mark => New_Reference_To (RTE (RE_Task_List), Loc),
5351               Expression => Aggr))));
5352
5353       Analyze (N);
5354    end Expand_N_Abort_Statement;
5355
5356    -------------------------------
5357    -- Expand_N_Accept_Statement --
5358    -------------------------------
5359
5360    --  This procedure handles expansion of accept statements that stand
5361    --  alone, i.e. they are not part of an accept alternative. The expansion
5362    --  of accept statement in accept alternatives is handled by the routines
5363    --  Expand_N_Accept_Alternative and Expand_N_Selective_Accept. The
5364    --  following description applies only to stand alone accept statements.
5365
5366    --  If there is no handled statement sequence, or only null statements,
5367    --  then this is called a trivial accept, and the expansion is:
5368
5369    --    Accept_Trivial (entry-index)
5370
5371    --  If there is a handled statement sequence, then the expansion is:
5372
5373    --    Ann : Address;
5374    --    {Lnn : Label}
5375
5376    --    begin
5377    --       begin
5378    --          Accept_Call (entry-index, Ann);
5379    --          Renaming_Declarations for formals
5380    --          <statement sequence from N_Accept_Statement node>
5381    --          Complete_Rendezvous;
5382    --          <<Lnn>>
5383    --
5384    --       exception
5385    --          when ... =>
5386    --             <exception handler from N_Accept_Statement node>
5387    --             Complete_Rendezvous;
5388    --          when ... =>
5389    --             <exception handler from N_Accept_Statement node>
5390    --             Complete_Rendezvous;
5391    --          ...
5392    --       end;
5393
5394    --    exception
5395    --       when all others =>
5396    --          Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
5397    --    end;
5398
5399    --  The first three declarations were already inserted ahead of the accept
5400    --  statement by the Expand_Accept_Declarations procedure, which was called
5401    --  directly from the semantics during analysis of the accept statement,
5402    --  before analyzing its contained statements.
5403
5404    --  The declarations from the N_Accept_Statement, as noted in Sinfo, come
5405    --  from possible expansion activity (the original source of course does
5406    --  not have any declarations associated with the accept statement, since
5407    --  an accept statement has no declarative part). In particular, if the
5408    --  expander is active, the first such declaration is the declaration of
5409    --  the Accept_Params_Ptr entity (see Sem_Ch9.Analyze_Accept_Statement).
5410    --
5411    --  The two blocks are merged into a single block if the inner block has
5412    --  no exception handlers, but otherwise two blocks are required, since
5413    --  exceptions might be raised in the exception handlers of the inner
5414    --  block, and Exceptional_Complete_Rendezvous must be called.
5415
5416    procedure Expand_N_Accept_Statement (N : Node_Id) is
5417       Loc     : constant Source_Ptr := Sloc (N);
5418       Stats   : constant Node_Id    := Handled_Statement_Sequence (N);
5419       Ename   : constant Node_Id    := Entry_Direct_Name (N);
5420       Eindx   : constant Node_Id    := Entry_Index (N);
5421       Eent    : constant Entity_Id  := Entity (Ename);
5422       Acstack : constant Elist_Id   := Accept_Address (Eent);
5423       Ann     : constant Entity_Id  := Node (Last_Elmt (Acstack));
5424       Ttyp    : constant Entity_Id  := Etype (Scope (Eent));
5425       Blkent  : Entity_Id;
5426       Call    : Node_Id;
5427       Block   : Node_Id;
5428
5429    --  Start of processing for Expand_N_Accept_Statement
5430
5431    begin
5432       --  If accept statement is not part of a list, then its parent must be
5433       --  an accept alternative, and, as described above, we do not do any
5434       --  expansion for such accept statements at this level.
5435
5436       if not Is_List_Member (N) then
5437          pragma Assert (Nkind (Parent (N)) = N_Accept_Alternative);
5438          return;
5439
5440       --  Trivial accept case (no statement sequence, or null statements).
5441       --  If the accept statement has declarations, then just insert them
5442       --  before the procedure call.
5443
5444       elsif Trivial_Accept_OK
5445         and then (No (Stats) or else Null_Statements (Statements (Stats)))
5446       then
5447          --  Remove declarations for renamings, because the parameter block
5448          --  will not be assigned.
5449
5450          declare
5451             D      : Node_Id;
5452             Next_D : Node_Id;
5453
5454          begin
5455             D := First (Declarations (N));
5456
5457             while Present (D) loop
5458                Next_D := Next (D);
5459                if Nkind (D) = N_Object_Renaming_Declaration then
5460                   Remove (D);
5461                end if;
5462
5463                D := Next_D;
5464             end loop;
5465          end;
5466
5467          if Present (Declarations (N)) then
5468             Insert_Actions (N, Declarations (N));
5469          end if;
5470
5471          Rewrite (N,
5472            Make_Procedure_Call_Statement (Loc,
5473              Name => New_Reference_To (RTE (RE_Accept_Trivial), Loc),
5474              Parameter_Associations => New_List (
5475                Entry_Index_Expression (Loc, Entity (Ename), Eindx, Ttyp))));
5476
5477          Analyze (N);
5478
5479          --  Discard Entry_Address that was created for it, so it will not be
5480          --  emitted if this accept statement is in the statement part of a
5481          --  delay alternative.
5482
5483          if Present (Stats) then
5484             Remove_Last_Elmt (Acstack);
5485          end if;
5486
5487       --  Case of statement sequence present
5488
5489       else
5490          --  Construct the block, using the declarations from the accept
5491          --  statement if any to initialize the declarations of the block.
5492
5493          Blkent := Make_Temporary (Loc, 'A');
5494          Set_Ekind (Blkent, E_Block);
5495          Set_Etype (Blkent, Standard_Void_Type);
5496          Set_Scope (Blkent, Current_Scope);
5497
5498          Block :=
5499            Make_Block_Statement (Loc,
5500              Identifier                 => New_Reference_To (Blkent, Loc),
5501              Declarations               => Declarations (N),
5502              Handled_Statement_Sequence => Build_Accept_Body (N));
5503
5504          --  For the analysis of the generated declarations, the parent node
5505          --  must be properly set.
5506
5507          Set_Parent (Block, Parent (N));
5508
5509          --  Prepend call to Accept_Call to main statement sequence If the
5510          --  accept has exception handlers, the statement sequence is wrapped
5511          --  in a block. Insert call and renaming declarations in the
5512          --  declarations of the block, so they are elaborated before the
5513          --  handlers.
5514
5515          Call :=
5516            Make_Procedure_Call_Statement (Loc,
5517              Name => New_Reference_To (RTE (RE_Accept_Call), Loc),
5518              Parameter_Associations => New_List (
5519                Entry_Index_Expression (Loc, Entity (Ename), Eindx, Ttyp),
5520                New_Reference_To (Ann, Loc)));
5521
5522          if Parent (Stats) = N then
5523             Prepend (Call, Statements (Stats));
5524          else
5525             Set_Declarations
5526               (Parent (Stats),
5527                 New_List (Call));
5528          end if;
5529
5530          Analyze (Call);
5531
5532          Push_Scope (Blkent);
5533
5534          declare
5535             D      : Node_Id;
5536             Next_D : Node_Id;
5537             Typ    : Entity_Id;
5538
5539          begin
5540             D := First (Declarations (N));
5541             while Present (D) loop
5542                Next_D := Next (D);
5543
5544                if Nkind (D) = N_Object_Renaming_Declaration then
5545
5546                   --  The renaming declarations for the formals were created
5547                   --  during analysis of the accept statement, and attached to
5548                   --  the list of declarations. Place them now in the context
5549                   --  of the accept block or subprogram.
5550
5551                   Remove (D);
5552                   Typ := Entity (Subtype_Mark (D));
5553                   Insert_After (Call, D);
5554                   Analyze (D);
5555
5556                   --  If the formal is class_wide, it does not have an actual
5557                   --  subtype. The analysis of the renaming declaration creates
5558                   --  one, but we need to retain the class-wide nature of the
5559                   --  entity.
5560
5561                   if Is_Class_Wide_Type (Typ) then
5562                      Set_Etype (Defining_Identifier (D), Typ);
5563                   end if;
5564
5565                end if;
5566
5567                D := Next_D;
5568             end loop;
5569          end;
5570
5571          End_Scope;
5572
5573          --  Replace the accept statement by the new block
5574
5575          Rewrite (N, Block);
5576          Analyze (N);
5577
5578          --  Last step is to unstack the Accept_Address value
5579
5580          Remove_Last_Elmt (Acstack);
5581       end if;
5582    end Expand_N_Accept_Statement;
5583
5584    ----------------------------------
5585    -- Expand_N_Asynchronous_Select --
5586    ----------------------------------
5587
5588    --  This procedure assumes that the trigger statement is an entry call or
5589    --  a dispatching procedure call. A delay alternative should already have
5590    --  been expanded into an entry call to the appropriate delay object Wait
5591    --  entry.
5592
5593    --  If the trigger is a task entry call, the select is implemented with
5594    --  a Task_Entry_Call:
5595
5596    --    declare
5597    --       B : Boolean;
5598    --       C : Boolean;
5599    --       P : parms := (parm, parm, parm);
5600
5601    --        --  Clean is added by Exp_Ch7.Expand_Cleanup_Actions
5602
5603    --       procedure _clean is
5604    --       begin
5605    --          ...
5606    --          Cancel_Task_Entry_Call (C);
5607    --          ...
5608    --       end _clean;
5609
5610    --    begin
5611    --       Abort_Defer;
5612    --       Task_Entry_Call
5613    --         (<acceptor-task>,    --  Acceptor
5614    --          <entry-index>,      --  E
5615    --          P'Address,          --  Uninterpreted_Data
5616    --          Asynchronous_Call,  --  Mode
5617    --          B);                 --  Rendezvous_Successful
5618
5619    --       begin
5620    --          begin
5621    --             Abort_Undefer;
5622    --             <abortable-part>
5623    --          at end
5624    --             _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5625    --          end;
5626    --       exception
5627    --          when Abort_Signal => Abort_Undefer;
5628    --       end;
5629
5630    --       parm := P.param;
5631    --       parm := P.param;
5632    --       ...
5633    --       if not C then
5634    --          <triggered-statements>
5635    --       end if;
5636    --    end;
5637
5638    --  Note that Build_Simple_Entry_Call is used to expand the entry of the
5639    --  asynchronous entry call (by Expand_N_Entry_Call_Statement procedure)
5640    --  as follows:
5641
5642    --    declare
5643    --       P : parms := (parm, parm, parm);
5644    --    begin
5645    --       Call_Simple (acceptor-task, entry-index, P'Address);
5646    --       parm := P.param;
5647    --       parm := P.param;
5648    --       ...
5649    --    end;
5650
5651    --  so the task at hand is to convert the latter expansion into the former
5652
5653    --  If the trigger is a protected entry call, the select is implemented
5654    --  with Protected_Entry_Call:
5655
5656    --  declare
5657    --     P   : E1_Params := (param, param, param);
5658    --     Bnn : Communications_Block;
5659
5660    --  begin
5661    --     declare
5662
5663    --        --  Clean is added by Exp_Ch7.Expand_Cleanup_Actions
5664
5665    --        procedure _clean is
5666    --        begin
5667    --           ...
5668    --           if Enqueued (Bnn) then
5669    --              Cancel_Protected_Entry_Call (Bnn);
5670    --           end if;
5671    --           ...
5672    --        end _clean;
5673
5674    --     begin
5675    --        begin
5676    --           Protected_Entry_Call
5677    --             (po._object'Access,  --  Object
5678    --              <entry index>,      --  E
5679    --              P'Address,          --  Uninterpreted_Data
5680    --              Asynchronous_Call,  --  Mode
5681    --              Bnn);               --  Block
5682
5683    --           if Enqueued (Bnn) then
5684    --              <abortable-part>
5685    --           end if;
5686    --        at end
5687    --           _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5688    --        end;
5689    --     exception
5690    --        when Abort_Signal => Abort_Undefer;
5691    --     end;
5692
5693    --     if not Cancelled (Bnn) then
5694    --        <triggered-statements>
5695    --     end if;
5696    --  end;
5697
5698    --  Build_Simple_Entry_Call is used to expand the all to a simple protected
5699    --  entry call:
5700
5701    --  declare
5702    --     P   : E1_Params := (param, param, param);
5703    --     Bnn : Communications_Block;
5704
5705    --  begin
5706    --     Protected_Entry_Call
5707    --       (po._object'Access,  --  Object
5708    --        <entry index>,      --  E
5709    --        P'Address,          --  Uninterpreted_Data
5710    --        Simple_Call,        --  Mode
5711    --        Bnn);               --  Block
5712    --     parm := P.param;
5713    --     parm := P.param;
5714    --       ...
5715    --  end;
5716
5717    --  Ada 2005 (AI-345): If the trigger is a dispatching call, the select is
5718    --  expanded into:
5719
5720    --    declare
5721    --       B   : Boolean := False;
5722    --       Bnn : Communication_Block;
5723    --       C   : Ada.Tags.Prim_Op_Kind;
5724    --       D   : System.Storage_Elements.Dummy_Communication_Block;
5725    --       K   : Ada.Tags.Tagged_Kind :=
5726    --               Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
5727    --       P   : Parameters := (Param1 .. ParamN);
5728    --       S   : Integer;
5729    --       U   : Boolean;
5730
5731    --    begin
5732    --       if K = Ada.Tags.TK_Limited_Tagged then
5733    --          <dispatching-call>;
5734    --          <triggering-statements>;
5735
5736    --       else
5737    --          S :=
5738    --            Ada.Tags.Get_Offset_Index
5739    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
5740
5741    --          _Disp_Get_Prim_Op_Kind (<object>, S, C);
5742
5743    --          if C = POK_Protected_Entry then
5744    --             declare
5745    --                procedure _clean is
5746    --                begin
5747    --                   if Enqueued (Bnn) then
5748    --                      Cancel_Protected_Entry_Call (Bnn);
5749    --                   end if;
5750    --                end _clean;
5751
5752    --             begin
5753    --                begin
5754    --                   _Disp_Asynchronous_Select
5755    --                     (<object>, S, P'Address, D, B);
5756    --                   Bnn := Communication_Block (D);
5757
5758    --                   Param1 := P.Param1;
5759    --                   ...
5760    --                   ParamN := P.ParamN;
5761
5762    --                   if Enqueued (Bnn) then
5763    --                      <abortable-statements>
5764    --                   end if;
5765    --                at end
5766    --                   _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5767    --                end;
5768    --             exception
5769    --                when Abort_Signal => Abort_Undefer;
5770    --             end;
5771
5772    --             if not Cancelled (Bnn) then
5773    --                <triggering-statements>
5774    --             end if;
5775
5776    --          elsif C = POK_Task_Entry then
5777    --             declare
5778    --                procedure _clean is
5779    --                begin
5780    --                   Cancel_Task_Entry_Call (U);
5781    --                end _clean;
5782
5783    --             begin
5784    --                Abort_Defer;
5785
5786    --                _Disp_Asynchronous_Select
5787    --                  (<object>, S, P'Address, D, B);
5788    --                Bnn := Communication_Bloc (D);
5789
5790    --                Param1 := P.Param1;
5791    --                ...
5792    --                ParamN := P.ParamN;
5793
5794    --                begin
5795    --                   begin
5796    --                      Abort_Undefer;
5797    --                      <abortable-statements>
5798    --                   at end
5799    --                      _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5800    --                   end;
5801    --                exception
5802    --                   when Abort_Signal => Abort_Undefer;
5803    --                end;
5804
5805    --                if not U then
5806    --                   <triggering-statements>
5807    --                end if;
5808    --             end;
5809
5810    --          else
5811    --             <dispatching-call>;
5812    --             <triggering-statements>
5813    --          end if;
5814    --       end if;
5815    --    end;
5816
5817    --  The job is to convert this to the asynchronous form
5818
5819    --  If the trigger is a delay statement, it will have been expanded into a
5820    --  call to one of the GNARL delay procedures. This routine will convert
5821    --  this into a protected entry call on a delay object and then continue
5822    --  processing as for a protected entry call trigger. This requires
5823    --  declaring a Delay_Block object and adding a pointer to this object to
5824    --  the parameter list of the delay procedure to form the parameter list of
5825    --  the entry call. This object is used by the runtime to queue the delay
5826    --  request.
5827
5828    --  For a description of the use of P and the assignments after the call,
5829    --  see Expand_N_Entry_Call_Statement.
5830
5831    procedure Expand_N_Asynchronous_Select (N : Node_Id) is
5832       Loc    : constant Source_Ptr := Sloc (N);
5833       Abrt   : constant Node_Id    := Abortable_Part (N);
5834       Astats : constant List_Id    := Statements (Abrt);
5835       Trig   : constant Node_Id    := Triggering_Alternative (N);
5836       Tstats : constant List_Id    := Statements (Trig);
5837
5838       Abort_Block_Ent   : Entity_Id;
5839       Abortable_Block   : Node_Id;
5840       Actuals           : List_Id;
5841       Blk_Ent           : Entity_Id;
5842       Blk_Typ           : Entity_Id;
5843       Call              : Node_Id;
5844       Call_Ent          : Entity_Id;
5845       Cancel_Param      : Entity_Id;
5846       Cleanup_Block     : Node_Id;
5847       Cleanup_Block_Ent : Entity_Id;
5848       Cleanup_Stmts     : List_Id;
5849       Conc_Typ_Stmts    : List_Id;
5850       Concval           : Node_Id;
5851       Dblock_Ent        : Entity_Id;
5852       Decl              : Node_Id;
5853       Decls             : List_Id;
5854       Ecall             : Node_Id;
5855       Ename             : Node_Id;
5856       Enqueue_Call      : Node_Id;
5857       Formals           : List_Id;
5858       Hdle              : List_Id;
5859       Index             : Node_Id;
5860       Lim_Typ_Stmts     : List_Id;
5861       N_Orig            : Node_Id;
5862       Obj               : Entity_Id;
5863       Param             : Node_Id;
5864       Params            : List_Id;
5865       Pdef              : Entity_Id;
5866       ProtE_Stmts       : List_Id;
5867       ProtP_Stmts       : List_Id;
5868       Stmt              : Node_Id;
5869       Stmts             : List_Id;
5870       Target_Undefer    : RE_Id;
5871       TaskE_Stmts       : List_Id;
5872       Undefer_Args      : List_Id := No_List;
5873
5874       B   : Entity_Id;  --  Call status flag
5875       Bnn : Entity_Id;  --  Communication block
5876       C   : Entity_Id;  --  Call kind
5877       K   : Entity_Id;  --  Tagged kind
5878       P   : Entity_Id;  --  Parameter block
5879       S   : Entity_Id;  --  Primitive operation slot
5880       T   : Entity_Id;  --  Additional status flag
5881
5882    begin
5883       Blk_Ent := Make_Temporary (Loc, 'A');
5884       Ecall   := Triggering_Statement (Trig);
5885
5886       --  The arguments in the call may require dynamic allocation, and the
5887       --  call statement may have been transformed into a block. The block
5888       --  may contain additional declarations for internal entities, and the
5889       --  original call is found by sequential search.
5890
5891       if Nkind (Ecall) = N_Block_Statement then
5892          Ecall := First (Statements (Handled_Statement_Sequence (Ecall)));
5893          while not Nkind_In (Ecall, N_Procedure_Call_Statement,
5894                                     N_Entry_Call_Statement)
5895          loop
5896             Next (Ecall);
5897          end loop;
5898       end if;
5899
5900       --  This is either a dispatching call or a delay statement used as a
5901       --  trigger which was expanded into a procedure call.
5902
5903       if Nkind (Ecall) = N_Procedure_Call_Statement then
5904          if Ada_Version >= Ada_2005
5905            and then
5906              (No (Original_Node (Ecall))
5907                 or else not Nkind_In (Original_Node (Ecall),
5908                                         N_Delay_Relative_Statement,
5909                                         N_Delay_Until_Statement))
5910          then
5911             Extract_Dispatching_Call (Ecall, Call_Ent, Obj, Actuals, Formals);
5912
5913             Decls := New_List;
5914             Stmts := New_List;
5915
5916             --  Call status flag processing, generate:
5917             --    B : Boolean := False;
5918
5919             B := Build_B (Loc, Decls);
5920
5921             --  Communication block processing, generate:
5922             --    Bnn : Communication_Block;
5923
5924             Bnn := Make_Temporary (Loc, 'B');
5925             Append_To (Decls,
5926               Make_Object_Declaration (Loc,
5927                 Defining_Identifier => Bnn,
5928                 Object_Definition   =>
5929                   New_Reference_To (RTE (RE_Communication_Block), Loc)));
5930
5931             --  Call kind processing, generate:
5932             --    C : Ada.Tags.Prim_Op_Kind;
5933
5934             C := Build_C (Loc, Decls);
5935
5936             --  Tagged kind processing, generate:
5937             --    K : Ada.Tags.Tagged_Kind :=
5938             --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
5939
5940             --  Dummy communication block, generate:
5941             --    D : Dummy_Communication_Block;
5942
5943             Append_To (Decls,
5944               Make_Object_Declaration (Loc,
5945                 Defining_Identifier =>
5946                   Make_Defining_Identifier (Loc, Name_uD),
5947                 Object_Definition =>
5948                   New_Reference_To (
5949                     RTE (RE_Dummy_Communication_Block), Loc)));
5950
5951             K := Build_K (Loc, Decls, Obj);
5952
5953             --  Parameter block processing
5954
5955             Blk_Typ := Build_Parameter_Block
5956                          (Loc, Actuals, Formals, Decls);
5957             P       := Parameter_Block_Pack
5958                          (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
5959
5960             --  Dispatch table slot processing, generate:
5961             --    S : Integer;
5962
5963             S := Build_S (Loc, Decls);
5964
5965             --  Additional status flag processing, generate:
5966             --    Tnn : Boolean;
5967
5968             T := Make_Temporary (Loc, 'T');
5969             Append_To (Decls,
5970               Make_Object_Declaration (Loc,
5971                 Defining_Identifier => T,
5972                 Object_Definition   =>
5973                   New_Reference_To (Standard_Boolean, Loc)));
5974
5975             ------------------------------
5976             -- Protected entry handling --
5977             ------------------------------
5978
5979             --  Generate:
5980             --    Param1 := P.Param1;
5981             --    ...
5982             --    ParamN := P.ParamN;
5983
5984             Cleanup_Stmts := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
5985
5986             --  Generate:
5987             --    Bnn := Communication_Block (D);
5988
5989             Prepend_To (Cleanup_Stmts,
5990               Make_Assignment_Statement (Loc,
5991                 Name =>
5992                   New_Reference_To (Bnn, Loc),
5993                 Expression =>
5994                   Make_Unchecked_Type_Conversion (Loc,
5995                     Subtype_Mark =>
5996                       New_Reference_To (RTE (RE_Communication_Block), Loc),
5997                     Expression   => Make_Identifier (Loc, Name_uD))));
5998
5999             --  Generate:
6000             --    _Disp_Asynchronous_Select (<object>, S, P'Address, D, B);
6001
6002             Prepend_To (Cleanup_Stmts,
6003               Make_Procedure_Call_Statement (Loc,
6004                 Name =>
6005                   New_Reference_To (
6006                     Find_Prim_Op (Etype (Etype (Obj)),
6007                       Name_uDisp_Asynchronous_Select),
6008                     Loc),
6009                 Parameter_Associations =>
6010                   New_List (
6011                     New_Copy_Tree (Obj),             --  <object>
6012                     New_Reference_To (S, Loc),       --  S
6013                     Make_Attribute_Reference (Loc,   --  P'Address
6014                       Prefix =>
6015                         New_Reference_To (P, Loc),
6016                       Attribute_Name =>
6017                         Name_Address),
6018                     Make_Identifier (Loc, Name_uD),  --  D
6019                     New_Reference_To (B, Loc))));    --  B
6020
6021             --  Generate:
6022             --    if Enqueued (Bnn) then
6023             --       <abortable-statements>
6024             --    end if;
6025
6026             Append_To (Cleanup_Stmts,
6027               Make_If_Statement (Loc,
6028                 Condition =>
6029                   Make_Function_Call (Loc,
6030                     Name =>
6031                       New_Reference_To (RTE (RE_Enqueued), Loc),
6032                     Parameter_Associations =>
6033                       New_List (
6034                         New_Reference_To (Bnn, Loc))),
6035
6036                 Then_Statements =>
6037                   New_Copy_List_Tree (Astats)));
6038
6039             --  Wrap the statements in a block. Exp_Ch7.Expand_Cleanup_Actions
6040             --  will then generate a _clean for the communication block Bnn.
6041
6042             --  Generate:
6043             --    declare
6044             --       procedure _clean is
6045             --       begin
6046             --          if Enqueued (Bnn) then
6047             --             Cancel_Protected_Entry_Call (Bnn);
6048             --          end if;
6049             --       end _clean;
6050             --    begin
6051             --       Cleanup_Stmts
6052             --    at end
6053             --       _clean;
6054             --    end;
6055
6056             Cleanup_Block_Ent := Make_Temporary (Loc, 'C');
6057             Cleanup_Block :=
6058               Build_Cleanup_Block (Loc, Cleanup_Block_Ent, Cleanup_Stmts, Bnn);
6059
6060             --  Wrap the cleanup block in an exception handling block
6061
6062             --  Generate:
6063             --    begin
6064             --       Cleanup_Block
6065             --    exception
6066             --       when Abort_Signal => Abort_Undefer;
6067             --    end;
6068
6069             Abort_Block_Ent := Make_Temporary (Loc, 'A');
6070             ProtE_Stmts :=
6071               New_List (
6072                 Make_Implicit_Label_Declaration (Loc,
6073                   Defining_Identifier =>
6074                     Abort_Block_Ent),
6075
6076                 Build_Abort_Block
6077                   (Loc, Abort_Block_Ent, Cleanup_Block_Ent, Cleanup_Block));
6078
6079             --  Generate:
6080             --    if not Cancelled (Bnn) then
6081             --       <triggering-statements>
6082             --    end if;
6083
6084             Append_To (ProtE_Stmts,
6085               Make_If_Statement (Loc,
6086                 Condition =>
6087                   Make_Op_Not (Loc,
6088                     Right_Opnd =>
6089                       Make_Function_Call (Loc,
6090                         Name =>
6091                           New_Reference_To (RTE (RE_Cancelled), Loc),
6092                         Parameter_Associations =>
6093                           New_List (
6094                             New_Reference_To (Bnn, Loc)))),
6095
6096                 Then_Statements =>
6097                   New_Copy_List_Tree (Tstats)));
6098
6099             -------------------------
6100             -- Task entry handling --
6101             -------------------------
6102
6103             --  Generate:
6104             --    Param1 := P.Param1;
6105             --    ...
6106             --    ParamN := P.ParamN;
6107
6108             TaskE_Stmts := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
6109
6110             --  Generate:
6111             --    Bnn := Communication_Block (D);
6112
6113             Append_To (TaskE_Stmts,
6114               Make_Assignment_Statement (Loc,
6115                 Name =>
6116                   New_Reference_To (Bnn, Loc),
6117                 Expression =>
6118                   Make_Unchecked_Type_Conversion (Loc,
6119                     Subtype_Mark =>
6120                       New_Reference_To (RTE (RE_Communication_Block), Loc),
6121                     Expression   => Make_Identifier (Loc, Name_uD))));
6122
6123             --  Generate:
6124             --    _Disp_Asynchronous_Select (<object>, S, P'Address, D, B);
6125
6126             Prepend_To (TaskE_Stmts,
6127               Make_Procedure_Call_Statement (Loc,
6128                 Name =>
6129                   New_Reference_To (
6130                     Find_Prim_Op (Etype (Etype (Obj)),
6131                       Name_uDisp_Asynchronous_Select),
6132                     Loc),
6133                 Parameter_Associations =>
6134                   New_List (
6135                     New_Copy_Tree (Obj),             --  <object>
6136                     New_Reference_To (S, Loc),       --  S
6137                     Make_Attribute_Reference (Loc,   --  P'Address
6138                       Prefix =>
6139                         New_Reference_To (P, Loc),
6140                       Attribute_Name =>
6141                         Name_Address),
6142                     Make_Identifier (Loc, Name_uD),  --  D
6143                     New_Reference_To (B, Loc))));    --  B
6144
6145             --  Generate:
6146             --    Abort_Defer;
6147
6148             Prepend_To (TaskE_Stmts,
6149               Make_Procedure_Call_Statement (Loc,
6150                 Name =>
6151                   New_Reference_To (RTE (RE_Abort_Defer), Loc),
6152                 Parameter_Associations =>
6153                   No_List));
6154
6155             --  Generate:
6156             --    Abort_Undefer;
6157             --    <abortable-statements>
6158
6159             Cleanup_Stmts := New_Copy_List_Tree (Astats);
6160
6161             Prepend_To (Cleanup_Stmts,
6162               Make_Procedure_Call_Statement (Loc,
6163                 Name =>
6164                   New_Reference_To (RTE (RE_Abort_Undefer), Loc),
6165                 Parameter_Associations =>
6166                   No_List));
6167
6168             --  Wrap the statements in a block. Exp_Ch7.Expand_Cleanup_Actions
6169             --  will generate a _clean for the additional status flag.
6170
6171             --  Generate:
6172             --    declare
6173             --       procedure _clean is
6174             --       begin
6175             --          Cancel_Task_Entry_Call (U);
6176             --       end _clean;
6177             --    begin
6178             --       Cleanup_Stmts
6179             --    at end
6180             --       _clean;
6181             --    end;
6182
6183             Cleanup_Block_Ent := Make_Temporary (Loc, 'C');
6184             Cleanup_Block :=
6185               Build_Cleanup_Block (Loc, Cleanup_Block_Ent, Cleanup_Stmts, T);
6186
6187             --  Wrap the cleanup block in an exception handling block
6188
6189             --  Generate:
6190             --    begin
6191             --       Cleanup_Block
6192             --    exception
6193             --       when Abort_Signal => Abort_Undefer;
6194             --    end;
6195
6196             Abort_Block_Ent := Make_Temporary (Loc, 'A');
6197
6198             Append_To (TaskE_Stmts,
6199               Make_Implicit_Label_Declaration (Loc,
6200                 Defining_Identifier => Abort_Block_Ent));
6201
6202             Append_To (TaskE_Stmts,
6203               Build_Abort_Block
6204                 (Loc, Abort_Block_Ent, Cleanup_Block_Ent, Cleanup_Block));
6205
6206             --  Generate:
6207             --    if not T then
6208             --       <triggering-statements>
6209             --    end if;
6210
6211             Append_To (TaskE_Stmts,
6212               Make_If_Statement (Loc,
6213                 Condition =>
6214                   Make_Op_Not (Loc,
6215                     Right_Opnd =>
6216                       New_Reference_To (T, Loc)),
6217
6218                 Then_Statements =>
6219                   New_Copy_List_Tree (Tstats)));
6220
6221             ----------------------------------
6222             -- Protected procedure handling --
6223             ----------------------------------
6224
6225             --  Generate:
6226             --    <dispatching-call>;
6227             --    <triggering-statements>
6228
6229             ProtP_Stmts := New_Copy_List_Tree (Tstats);
6230             Prepend_To (ProtP_Stmts, New_Copy_Tree (Ecall));
6231
6232             --  Generate:
6233             --    S := Ada.Tags.Get_Offset_Index
6234             --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
6235
6236             Conc_Typ_Stmts :=
6237               New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
6238
6239             --  Generate:
6240             --    _Disp_Get_Prim_Op_Kind (<object>, S, C);
6241
6242             Append_To (Conc_Typ_Stmts,
6243               Make_Procedure_Call_Statement (Loc,
6244                 Name =>
6245                   New_Reference_To (
6246                     Find_Prim_Op (Etype (Etype (Obj)),
6247                       Name_uDisp_Get_Prim_Op_Kind),
6248                     Loc),
6249                 Parameter_Associations =>
6250                   New_List (
6251                     New_Copy_Tree (Obj),
6252                     New_Reference_To (S, Loc),
6253                     New_Reference_To (C, Loc))));
6254
6255             --  Generate:
6256             --    if C = POK_Procedure_Entry then
6257             --       ProtE_Stmts
6258             --    elsif C = POK_Task_Entry then
6259             --       TaskE_Stmts
6260             --    else
6261             --       ProtP_Stmts
6262             --    end if;
6263
6264             Append_To (Conc_Typ_Stmts,
6265               Make_If_Statement (Loc,
6266                 Condition =>
6267                   Make_Op_Eq (Loc,
6268                     Left_Opnd =>
6269                       New_Reference_To (C, Loc),
6270                     Right_Opnd =>
6271                       New_Reference_To (RTE (RE_POK_Protected_Entry), Loc)),
6272
6273                 Then_Statements =>
6274                   ProtE_Stmts,
6275
6276                 Elsif_Parts =>
6277                   New_List (
6278                     Make_Elsif_Part (Loc,
6279                       Condition =>
6280                         Make_Op_Eq (Loc,
6281                           Left_Opnd =>
6282                             New_Reference_To (C, Loc),
6283                           Right_Opnd =>
6284                             New_Reference_To (RTE (RE_POK_Task_Entry), Loc)),
6285
6286                       Then_Statements =>
6287                         TaskE_Stmts)),
6288
6289                 Else_Statements =>
6290                   ProtP_Stmts));
6291
6292             --  Generate:
6293             --    <dispatching-call>;
6294             --    <triggering-statements>
6295
6296             Lim_Typ_Stmts := New_Copy_List_Tree (Tstats);
6297             Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (Ecall));
6298
6299             --  Generate:
6300             --    if K = Ada.Tags.TK_Limited_Tagged then
6301             --       Lim_Typ_Stmts
6302             --    else
6303             --       Conc_Typ_Stmts
6304             --    end if;
6305
6306             Append_To (Stmts,
6307               Make_If_Statement (Loc,
6308                 Condition =>
6309                    Make_Op_Eq (Loc,
6310                      Left_Opnd =>
6311                        New_Reference_To (K, Loc),
6312                      Right_Opnd =>
6313                        New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
6314
6315                 Then_Statements =>
6316                   Lim_Typ_Stmts,
6317
6318                 Else_Statements =>
6319                   Conc_Typ_Stmts));
6320
6321             Rewrite (N,
6322               Make_Block_Statement (Loc,
6323                 Declarations =>
6324                   Decls,
6325                 Handled_Statement_Sequence =>
6326                   Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6327
6328             Analyze (N);
6329             return;
6330
6331          --  Delay triggering statement processing
6332
6333          else
6334             --  Add a Delay_Block object to the parameter list of the delay
6335             --  procedure to form the parameter list of the Wait entry call.
6336
6337             Dblock_Ent := Make_Temporary (Loc, 'D');
6338
6339             Pdef := Entity (Name (Ecall));
6340
6341             if Is_RTE (Pdef, RO_CA_Delay_For) then
6342                Enqueue_Call :=
6343                  New_Reference_To (RTE (RE_Enqueue_Duration), Loc);
6344
6345             elsif Is_RTE (Pdef, RO_CA_Delay_Until) then
6346                Enqueue_Call :=
6347                  New_Reference_To (RTE (RE_Enqueue_Calendar), Loc);
6348
6349             else pragma Assert (Is_RTE (Pdef, RO_RT_Delay_Until));
6350                Enqueue_Call := New_Reference_To (RTE (RE_Enqueue_RT), Loc);
6351             end if;
6352
6353             Append_To (Parameter_Associations (Ecall),
6354               Make_Attribute_Reference (Loc,
6355                 Prefix => New_Reference_To (Dblock_Ent, Loc),
6356                 Attribute_Name => Name_Unchecked_Access));
6357
6358             --  Create the inner block to protect the abortable part
6359
6360             Hdle := New_List (
6361               Make_Implicit_Exception_Handler (Loc,
6362                 Exception_Choices =>
6363                   New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
6364                 Statements => New_List (
6365                   Make_Procedure_Call_Statement (Loc,
6366                     Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)))));
6367
6368             Prepend_To (Astats,
6369               Make_Procedure_Call_Statement (Loc,
6370                 Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)));
6371
6372             Abortable_Block :=
6373               Make_Block_Statement (Loc,
6374                 Identifier => New_Reference_To (Blk_Ent, Loc),
6375                 Handled_Statement_Sequence =>
6376                   Make_Handled_Sequence_Of_Statements (Loc,
6377                     Statements => Astats),
6378                 Has_Created_Identifier => True,
6379                 Is_Asynchronous_Call_Block => True);
6380
6381             --  Append call to if Enqueue (When, DB'Unchecked_Access) then
6382
6383             Rewrite (Ecall,
6384               Make_Implicit_If_Statement (N,
6385                 Condition => Make_Function_Call (Loc,
6386                   Name => Enqueue_Call,
6387                   Parameter_Associations => Parameter_Associations (Ecall)),
6388                 Then_Statements =>
6389                   New_List (Make_Block_Statement (Loc,
6390                     Handled_Statement_Sequence =>
6391                       Make_Handled_Sequence_Of_Statements (Loc,
6392                         Statements => New_List (
6393                           Make_Implicit_Label_Declaration (Loc,
6394                             Defining_Identifier => Blk_Ent,
6395                             Label_Construct     => Abortable_Block),
6396                           Abortable_Block),
6397                         Exception_Handlers => Hdle)))));
6398
6399             Stmts := New_List (Ecall);
6400
6401             --  Construct statement sequence for new block
6402
6403             Append_To (Stmts,
6404               Make_Implicit_If_Statement (N,
6405                 Condition => Make_Function_Call (Loc,
6406                   Name => New_Reference_To (
6407                     RTE (RE_Timed_Out), Loc),
6408                   Parameter_Associations => New_List (
6409                     Make_Attribute_Reference (Loc,
6410                       Prefix => New_Reference_To (Dblock_Ent, Loc),
6411                       Attribute_Name => Name_Unchecked_Access))),
6412                 Then_Statements => Tstats));
6413
6414             --  The result is the new block
6415
6416             Set_Entry_Cancel_Parameter (Blk_Ent, Dblock_Ent);
6417
6418             Rewrite (N,
6419               Make_Block_Statement (Loc,
6420                 Declarations => New_List (
6421                   Make_Object_Declaration (Loc,
6422                     Defining_Identifier => Dblock_Ent,
6423                     Aliased_Present => True,
6424                     Object_Definition => New_Reference_To (
6425                       RTE (RE_Delay_Block), Loc))),
6426
6427                 Handled_Statement_Sequence =>
6428                   Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6429
6430             Analyze (N);
6431             return;
6432          end if;
6433
6434       else
6435          N_Orig := N;
6436       end if;
6437
6438       Extract_Entry (Ecall, Concval, Ename, Index);
6439       Build_Simple_Entry_Call (Ecall, Concval, Ename, Index);
6440
6441       Stmts := Statements (Handled_Statement_Sequence (Ecall));
6442       Decls := Declarations (Ecall);
6443
6444       if Is_Protected_Type (Etype (Concval)) then
6445
6446          --  Get the declarations of the block expanded from the entry call
6447
6448          Decl := First (Decls);
6449          while Present (Decl)
6450            and then
6451              (Nkind (Decl) /= N_Object_Declaration
6452                or else not Is_RTE (Etype (Object_Definition (Decl)),
6453                                    RE_Communication_Block))
6454          loop
6455             Next (Decl);
6456          end loop;
6457
6458          pragma Assert (Present (Decl));
6459          Cancel_Param := Defining_Identifier (Decl);
6460
6461          --  Change the mode of the Protected_Entry_Call call
6462
6463          --  Protected_Entry_Call (
6464          --    Object => po._object'Access,
6465          --    E => <entry index>;
6466          --    Uninterpreted_Data => P'Address;
6467          --    Mode => Asynchronous_Call;
6468          --    Block => Bnn);
6469
6470          Stmt := First (Stmts);
6471
6472          --  Skip assignments to temporaries created for in-out parameters
6473
6474          --  This makes unwarranted assumptions about the shape of the expanded
6475          --  tree for the call, and should be cleaned up ???
6476
6477          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
6478             Next (Stmt);
6479          end loop;
6480
6481          Call := Stmt;
6482
6483          Param := First (Parameter_Associations (Call));
6484          while Present (Param)
6485            and then not Is_RTE (Etype (Param), RE_Call_Modes)
6486          loop
6487             Next (Param);
6488          end loop;
6489
6490          pragma Assert (Present (Param));
6491          Rewrite (Param, New_Reference_To (RTE (RE_Asynchronous_Call), Loc));
6492          Analyze (Param);
6493
6494          --  Append an if statement to execute the abortable part
6495
6496          --  Generate:
6497          --    if Enqueued (Bnn) then
6498
6499          Append_To (Stmts,
6500            Make_Implicit_If_Statement (N,
6501              Condition => Make_Function_Call (Loc,
6502                Name => New_Reference_To (
6503                  RTE (RE_Enqueued), Loc),
6504                Parameter_Associations => New_List (
6505                  New_Reference_To (Cancel_Param, Loc))),
6506              Then_Statements => Astats));
6507
6508          Abortable_Block :=
6509            Make_Block_Statement (Loc,
6510              Identifier => New_Reference_To (Blk_Ent, Loc),
6511              Handled_Statement_Sequence =>
6512                Make_Handled_Sequence_Of_Statements (Loc,
6513                  Statements => Stmts),
6514              Has_Created_Identifier => True,
6515              Is_Asynchronous_Call_Block => True);
6516
6517          --  For the VM call Update_Exception instead of Abort_Undefer.
6518          --  See 4jexcept.ads for an explanation.
6519
6520          if VM_Target = No_VM then
6521             Target_Undefer := RE_Abort_Undefer;
6522          else
6523             Target_Undefer := RE_Update_Exception;
6524             Undefer_Args :=
6525               New_List (Make_Function_Call (Loc,
6526                           Name => New_Occurrence_Of
6527                                     (RTE (RE_Current_Target_Exception), Loc)));
6528          end if;
6529
6530          Stmts := New_List (
6531            Make_Block_Statement (Loc,
6532              Handled_Statement_Sequence =>
6533                Make_Handled_Sequence_Of_Statements (Loc,
6534                  Statements => New_List (
6535                    Make_Implicit_Label_Declaration (Loc,
6536                      Defining_Identifier => Blk_Ent,
6537                      Label_Construct     => Abortable_Block),
6538                    Abortable_Block),
6539
6540                --  exception
6541
6542                  Exception_Handlers => New_List (
6543                    Make_Implicit_Exception_Handler (Loc,
6544
6545                --  when Abort_Signal =>
6546                --     Abort_Undefer.all;
6547
6548                      Exception_Choices =>
6549                        New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
6550                      Statements => New_List (
6551                        Make_Procedure_Call_Statement (Loc,
6552                          Name => New_Reference_To (
6553                            RTE (Target_Undefer), Loc),
6554                          Parameter_Associations => Undefer_Args)))))),
6555
6556          --  if not Cancelled (Bnn) then
6557          --     triggered statements
6558          --  end if;
6559
6560            Make_Implicit_If_Statement (N,
6561              Condition => Make_Op_Not (Loc,
6562                Right_Opnd =>
6563                  Make_Function_Call (Loc,
6564                    Name => New_Occurrence_Of (RTE (RE_Cancelled), Loc),
6565                    Parameter_Associations => New_List (
6566                      New_Occurrence_Of (Cancel_Param, Loc)))),
6567              Then_Statements => Tstats));
6568
6569       --  Asynchronous task entry call
6570
6571       else
6572          if No (Decls) then
6573             Decls := New_List;
6574          end if;
6575
6576          B := Make_Defining_Identifier (Loc, Name_uB);
6577
6578          --  Insert declaration of B in declarations of existing block
6579
6580          Prepend_To (Decls,
6581            Make_Object_Declaration (Loc,
6582              Defining_Identifier => B,
6583              Object_Definition => New_Reference_To (Standard_Boolean, Loc)));
6584
6585          Cancel_Param := Make_Defining_Identifier (Loc, Name_uC);
6586
6587          --  Insert declaration of C in declarations of existing block
6588
6589          Prepend_To (Decls,
6590            Make_Object_Declaration (Loc,
6591              Defining_Identifier => Cancel_Param,
6592              Object_Definition => New_Reference_To (Standard_Boolean, Loc)));
6593
6594          --  Remove and save the call to Call_Simple
6595
6596          Stmt := First (Stmts);
6597
6598          --  Skip assignments to temporaries created for in-out parameters.
6599          --  This makes unwarranted assumptions about the shape of the expanded
6600          --  tree for the call, and should be cleaned up ???
6601
6602          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
6603             Next (Stmt);
6604          end loop;
6605
6606          Call := Stmt;
6607
6608          --  Create the inner block to protect the abortable part
6609
6610          Hdle :=  New_List (
6611            Make_Implicit_Exception_Handler (Loc,
6612              Exception_Choices =>
6613                New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
6614              Statements =>
6615                New_List (
6616                  Make_Procedure_Call_Statement (Loc,
6617                    Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)))));
6618
6619          Prepend_To (Astats,
6620            Make_Procedure_Call_Statement (Loc,
6621              Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)));
6622
6623          Abortable_Block :=
6624            Make_Block_Statement (Loc,
6625              Identifier => New_Reference_To (Blk_Ent, Loc),
6626              Handled_Statement_Sequence =>
6627                Make_Handled_Sequence_Of_Statements (Loc,
6628                  Statements => Astats),
6629              Has_Created_Identifier => True,
6630              Is_Asynchronous_Call_Block => True);
6631
6632          Insert_After (Call,
6633            Make_Block_Statement (Loc,
6634              Handled_Statement_Sequence =>
6635                Make_Handled_Sequence_Of_Statements (Loc,
6636                  Statements => New_List (
6637                    Make_Implicit_Label_Declaration (Loc,
6638                      Defining_Identifier =>
6639                        Blk_Ent,
6640                      Label_Construct =>
6641                        Abortable_Block),
6642                    Abortable_Block),
6643                  Exception_Handlers => Hdle)));
6644
6645          --  Create new call statement
6646
6647          Params := Parameter_Associations (Call);
6648
6649          Append_To (Params,
6650            New_Reference_To (RTE (RE_Asynchronous_Call), Loc));
6651          Append_To (Params,
6652            New_Reference_To (B, Loc));
6653
6654          Rewrite (Call,
6655            Make_Procedure_Call_Statement (Loc,
6656              Name =>
6657                New_Reference_To (RTE (RE_Task_Entry_Call), Loc),
6658              Parameter_Associations => Params));
6659
6660          --  Construct statement sequence for new block
6661
6662          Append_To (Stmts,
6663            Make_Implicit_If_Statement (N,
6664              Condition =>
6665                Make_Op_Not (Loc,
6666                  New_Reference_To (Cancel_Param, Loc)),
6667              Then_Statements => Tstats));
6668
6669          --  Protected the call against abort
6670
6671          Prepend_To (Stmts,
6672            Make_Procedure_Call_Statement (Loc,
6673              Name => New_Reference_To (RTE (RE_Abort_Defer), Loc),
6674              Parameter_Associations => Empty_List));
6675       end if;
6676
6677       Set_Entry_Cancel_Parameter (Blk_Ent, Cancel_Param);
6678
6679       --  The result is the new block
6680
6681       Rewrite (N_Orig,
6682         Make_Block_Statement (Loc,
6683           Declarations => Decls,
6684           Handled_Statement_Sequence =>
6685             Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6686
6687       Analyze (N_Orig);
6688    end Expand_N_Asynchronous_Select;
6689
6690    -------------------------------------
6691    -- Expand_N_Conditional_Entry_Call --
6692    -------------------------------------
6693
6694    --  The conditional task entry call is converted to a call to
6695    --  Task_Entry_Call:
6696
6697    --    declare
6698    --       B : Boolean;
6699    --       P : parms := (parm, parm, parm);
6700
6701    --    begin
6702    --       Task_Entry_Call
6703    --         (<acceptor-task>,   --  Acceptor
6704    --          <entry-index>,     --  E
6705    --          P'Address,         --  Uninterpreted_Data
6706    --          Conditional_Call,  --  Mode
6707    --          B);                --  Rendezvous_Successful
6708    --       parm := P.param;
6709    --       parm := P.param;
6710    --       ...
6711    --       if B then
6712    --          normal-statements
6713    --       else
6714    --          else-statements
6715    --       end if;
6716    --    end;
6717
6718    --  For a description of the use of P and the assignments after the call,
6719    --  see Expand_N_Entry_Call_Statement. Note that the entry call of the
6720    --  conditional entry call has already been expanded (by the Expand_N_Entry
6721    --  _Call_Statement procedure) as follows:
6722
6723    --    declare
6724    --       P : parms := (parm, parm, parm);
6725    --    begin
6726    --       ... info for in-out parameters
6727    --       Call_Simple (acceptor-task, entry-index, P'Address);
6728    --       parm := P.param;
6729    --       parm := P.param;
6730    --       ...
6731    --    end;
6732
6733    --  so the task at hand is to convert the latter expansion into the former
6734
6735    --  The conditional protected entry call is converted to a call to
6736    --  Protected_Entry_Call:
6737
6738    --    declare
6739    --       P : parms := (parm, parm, parm);
6740    --       Bnn : Communications_Block;
6741
6742    --    begin
6743    --       Protected_Entry_Call
6744    --         (po._object'Access,  --  Object
6745    --          <entry index>,      --  E
6746    --          P'Address,          --  Uninterpreted_Data
6747    --          Conditional_Call,   --  Mode
6748    --          Bnn);               --  Block
6749    --       parm := P.param;
6750    --       parm := P.param;
6751    --       ...
6752    --       if Cancelled (Bnn) then
6753    --          else-statements
6754    --       else
6755    --          normal-statements
6756    --       end if;
6757    --    end;
6758
6759    --  Ada 2005 (AI-345): A dispatching conditional entry call is converted
6760    --  into:
6761
6762    --    declare
6763    --       B : Boolean := False;
6764    --       C : Ada.Tags.Prim_Op_Kind;
6765    --       K : Ada.Tags.Tagged_Kind :=
6766    --             Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
6767    --       P : Parameters := (Param1 .. ParamN);
6768    --       S : Integer;
6769
6770    --    begin
6771    --       if K = Ada.Tags.TK_Limited_Tagged then
6772    --          <dispatching-call>;
6773    --          <triggering-statements>
6774
6775    --       else
6776    --          S :=
6777    --            Ada.Tags.Get_Offset_Index
6778    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
6779
6780    --          _Disp_Conditional_Select (<object>, S, P'Address, C, B);
6781
6782    --          if C = POK_Protected_Entry
6783    --            or else C = POK_Task_Entry
6784    --          then
6785    --             Param1 := P.Param1;
6786    --             ...
6787    --             ParamN := P.ParamN;
6788    --          end if;
6789
6790    --          if B then
6791    --             if C = POK_Procedure
6792    --               or else C = POK_Protected_Procedure
6793    --               or else C = POK_Task_Procedure
6794    --             then
6795    --                <dispatching-call>;
6796    --             end if;
6797
6798    --             <triggering-statements>
6799    --          else
6800    --             <else-statements>
6801    --          end if;
6802    --       end if;
6803    --    end;
6804
6805    procedure Expand_N_Conditional_Entry_Call (N : Node_Id) is
6806       Loc : constant Source_Ptr := Sloc (N);
6807       Alt : constant Node_Id    := Entry_Call_Alternative (N);
6808       Blk : Node_Id             := Entry_Call_Statement (Alt);
6809
6810       Actuals        : List_Id;
6811       Blk_Typ        : Entity_Id;
6812       Call           : Node_Id;
6813       Call_Ent       : Entity_Id;
6814       Conc_Typ_Stmts : List_Id;
6815       Decl           : Node_Id;
6816       Decls          : List_Id;
6817       Formals        : List_Id;
6818       Lim_Typ_Stmts  : List_Id;
6819       N_Stats        : List_Id;
6820       Obj            : Entity_Id;
6821       Param          : Node_Id;
6822       Params         : List_Id;
6823       Stmt           : Node_Id;
6824       Stmts          : List_Id;
6825       Transient_Blk  : Node_Id;
6826       Unpack         : List_Id;
6827
6828       B : Entity_Id;  --  Call status flag
6829       C : Entity_Id;  --  Call kind
6830       K : Entity_Id;  --  Tagged kind
6831       P : Entity_Id;  --  Parameter block
6832       S : Entity_Id;  --  Primitive operation slot
6833
6834    begin
6835       if Ada_Version >= Ada_2005
6836         and then Nkind (Blk) = N_Procedure_Call_Statement
6837       then
6838          Extract_Dispatching_Call (Blk, Call_Ent, Obj, Actuals, Formals);
6839
6840          Decls := New_List;
6841          Stmts := New_List;
6842
6843          --  Call status flag processing, generate:
6844          --    B : Boolean := False;
6845
6846          B := Build_B (Loc, Decls);
6847
6848          --  Call kind processing, generate:
6849          --    C : Ada.Tags.Prim_Op_Kind;
6850
6851          C := Build_C (Loc, Decls);
6852
6853          --  Tagged kind processing, generate:
6854          --    K : Ada.Tags.Tagged_Kind :=
6855          --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
6856
6857          K := Build_K (Loc, Decls, Obj);
6858
6859          --  Parameter block processing
6860
6861          Blk_Typ := Build_Parameter_Block (Loc, Actuals, Formals, Decls);
6862          P       := Parameter_Block_Pack
6863                       (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
6864
6865          --  Dispatch table slot processing, generate:
6866          --    S : Integer;
6867
6868          S := Build_S (Loc, Decls);
6869
6870          --  Generate:
6871          --    S := Ada.Tags.Get_Offset_Index
6872          --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
6873
6874          Conc_Typ_Stmts :=
6875            New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
6876
6877          --  Generate:
6878          --    _Disp_Conditional_Select (<object>, S, P'Address, C, B);
6879
6880          Append_To (Conc_Typ_Stmts,
6881            Make_Procedure_Call_Statement (Loc,
6882              Name =>
6883                New_Reference_To (
6884                  Find_Prim_Op (Etype (Etype (Obj)),
6885                    Name_uDisp_Conditional_Select),
6886                  Loc),
6887              Parameter_Associations =>
6888                New_List (
6889                  New_Copy_Tree (Obj),            --  <object>
6890                  New_Reference_To (S, Loc),      --  S
6891                  Make_Attribute_Reference (Loc,  --  P'Address
6892                    Prefix =>
6893                      New_Reference_To (P, Loc),
6894                    Attribute_Name =>
6895                      Name_Address),
6896                  New_Reference_To (C, Loc),      --  C
6897                  New_Reference_To (B, Loc))));   --  B
6898
6899          --  Generate:
6900          --    if C = POK_Protected_Entry
6901          --      or else C = POK_Task_Entry
6902          --    then
6903          --       Param1 := P.Param1;
6904          --       ...
6905          --       ParamN := P.ParamN;
6906          --    end if;
6907
6908          Unpack := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
6909
6910          --  Generate the if statement only when the packed parameters need
6911          --  explicit assignments to their corresponding actuals.
6912
6913          if Present (Unpack) then
6914             Append_To (Conc_Typ_Stmts,
6915               Make_If_Statement (Loc,
6916
6917                 Condition =>
6918                   Make_Or_Else (Loc,
6919                     Left_Opnd =>
6920                       Make_Op_Eq (Loc,
6921                         Left_Opnd =>
6922                           New_Reference_To (C, Loc),
6923                         Right_Opnd =>
6924                           New_Reference_To (RTE (
6925                             RE_POK_Protected_Entry), Loc)),
6926                     Right_Opnd =>
6927                       Make_Op_Eq (Loc,
6928                         Left_Opnd =>
6929                           New_Reference_To (C, Loc),
6930                         Right_Opnd =>
6931                           New_Reference_To (RTE (RE_POK_Task_Entry), Loc))),
6932
6933                  Then_Statements =>
6934                    Unpack));
6935          end if;
6936
6937          --  Generate:
6938          --    if B then
6939          --       if C = POK_Procedure
6940          --         or else C = POK_Protected_Procedure
6941          --         or else C = POK_Task_Procedure
6942          --       then
6943          --          <dispatching-call>
6944          --       end if;
6945          --       <normal-statements>
6946          --    else
6947          --       <else-statements>
6948          --    end if;
6949
6950          N_Stats := New_Copy_List_Tree (Statements (Alt));
6951
6952          Prepend_To (N_Stats,
6953            Make_If_Statement (Loc,
6954              Condition =>
6955                Make_Or_Else (Loc,
6956                  Left_Opnd =>
6957                    Make_Op_Eq (Loc,
6958                      Left_Opnd =>
6959                        New_Reference_To (C, Loc),
6960                      Right_Opnd =>
6961                        New_Reference_To (RTE (RE_POK_Procedure), Loc)),
6962
6963                  Right_Opnd =>
6964                    Make_Or_Else (Loc,
6965                      Left_Opnd =>
6966                        Make_Op_Eq (Loc,
6967                          Left_Opnd =>
6968                            New_Reference_To (C, Loc),
6969                          Right_Opnd =>
6970                            New_Reference_To (RTE (
6971                              RE_POK_Protected_Procedure), Loc)),
6972
6973                      Right_Opnd =>
6974                        Make_Op_Eq (Loc,
6975                          Left_Opnd =>
6976                            New_Reference_To (C, Loc),
6977                          Right_Opnd =>
6978                            New_Reference_To (RTE (
6979                              RE_POK_Task_Procedure), Loc)))),
6980
6981              Then_Statements =>
6982                New_List (Blk)));
6983
6984          Append_To (Conc_Typ_Stmts,
6985            Make_If_Statement (Loc,
6986              Condition => New_Reference_To (B, Loc),
6987              Then_Statements => N_Stats,
6988              Else_Statements => Else_Statements (N)));
6989
6990          --  Generate:
6991          --    <dispatching-call>;
6992          --    <triggering-statements>
6993
6994          Lim_Typ_Stmts := New_Copy_List_Tree (Statements (Alt));
6995          Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (Blk));
6996
6997          --  Generate:
6998          --    if K = Ada.Tags.TK_Limited_Tagged then
6999          --       Lim_Typ_Stmts
7000          --    else
7001          --       Conc_Typ_Stmts
7002          --    end if;
7003
7004          Append_To (Stmts,
7005            Make_If_Statement (Loc,
7006              Condition =>
7007                Make_Op_Eq (Loc,
7008                  Left_Opnd =>
7009                    New_Reference_To (K, Loc),
7010                  Right_Opnd =>
7011                    New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
7012
7013              Then_Statements =>
7014                Lim_Typ_Stmts,
7015
7016              Else_Statements =>
7017                Conc_Typ_Stmts));
7018
7019          Rewrite (N,
7020            Make_Block_Statement (Loc,
7021              Declarations =>
7022                Decls,
7023              Handled_Statement_Sequence =>
7024                Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
7025
7026       --  As described above, The entry alternative is transformed into a
7027       --  block that contains the gnulli call, and possibly assignment
7028       --  statements for in-out parameters. The gnulli call may itself be
7029       --  rewritten into a transient block if some unconstrained parameters
7030       --  require it. We need to retrieve the call to complete its parameter
7031       --  list.
7032
7033       else
7034          Transient_Blk :=
7035            First_Real_Statement (Handled_Statement_Sequence (Blk));
7036
7037          if Present (Transient_Blk)
7038            and then Nkind (Transient_Blk) = N_Block_Statement
7039          then
7040             Blk := Transient_Blk;
7041          end if;
7042
7043          Stmts := Statements (Handled_Statement_Sequence (Blk));
7044          Stmt  := First (Stmts);
7045          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
7046             Next (Stmt);
7047          end loop;
7048
7049          Call   := Stmt;
7050          Params := Parameter_Associations (Call);
7051
7052          if Is_RTE (Entity (Name (Call)), RE_Protected_Entry_Call) then
7053
7054             --  Substitute Conditional_Entry_Call for Simple_Call parameter
7055
7056             Param := First (Params);
7057             while Present (Param)
7058               and then not Is_RTE (Etype (Param), RE_Call_Modes)
7059             loop
7060                Next (Param);
7061             end loop;
7062
7063             pragma Assert (Present (Param));
7064             Rewrite (Param, New_Reference_To (RTE (RE_Conditional_Call), Loc));
7065
7066             Analyze (Param);
7067
7068             --  Find the Communication_Block parameter for the call to the
7069             --  Cancelled function.
7070
7071             Decl := First (Declarations (Blk));
7072             while Present (Decl)
7073               and then not Is_RTE (Etype (Object_Definition (Decl)),
7074                              RE_Communication_Block)
7075             loop
7076                Next (Decl);
7077             end loop;
7078
7079             --  Add an if statement to execute the else part if the call
7080             --  does not succeed (as indicated by the Cancelled predicate).
7081
7082             Append_To (Stmts,
7083               Make_Implicit_If_Statement (N,
7084                 Condition => Make_Function_Call (Loc,
7085                   Name => New_Reference_To (RTE (RE_Cancelled), Loc),
7086                   Parameter_Associations => New_List (
7087                     New_Reference_To (Defining_Identifier (Decl), Loc))),
7088                 Then_Statements => Else_Statements (N),
7089                 Else_Statements => Statements (Alt)));
7090
7091          else
7092             B := Make_Defining_Identifier (Loc, Name_uB);
7093
7094             --  Insert declaration of B in declarations of existing block
7095
7096             if No (Declarations (Blk)) then
7097                Set_Declarations (Blk, New_List);
7098             end if;
7099
7100             Prepend_To (Declarations (Blk),
7101               Make_Object_Declaration (Loc,
7102                 Defining_Identifier => B,
7103                 Object_Definition =>
7104                   New_Reference_To (Standard_Boolean, Loc)));
7105
7106             --  Create new call statement
7107
7108             Append_To (Params,
7109               New_Reference_To (RTE (RE_Conditional_Call), Loc));
7110             Append_To (Params, New_Reference_To (B, Loc));
7111
7112             Rewrite (Call,
7113               Make_Procedure_Call_Statement (Loc,
7114                 Name => New_Reference_To (RTE (RE_Task_Entry_Call), Loc),
7115                 Parameter_Associations => Params));
7116
7117             --  Construct statement sequence for new block
7118
7119             Append_To (Stmts,
7120               Make_Implicit_If_Statement (N,
7121                 Condition => New_Reference_To (B, Loc),
7122                 Then_Statements => Statements (Alt),
7123                 Else_Statements => Else_Statements (N)));
7124          end if;
7125
7126          --  The result is the new block
7127
7128          Rewrite (N,
7129            Make_Block_Statement (Loc,
7130              Declarations => Declarations (Blk),
7131              Handled_Statement_Sequence =>
7132                Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
7133       end if;
7134
7135       Analyze (N);
7136    end Expand_N_Conditional_Entry_Call;
7137
7138    ---------------------------------------
7139    -- Expand_N_Delay_Relative_Statement --
7140    ---------------------------------------
7141
7142    --  Delay statement is implemented as a procedure call to Delay_For
7143    --  defined in Ada.Calendar.Delays in order to reduce the overhead of
7144    --  simple delays imposed by the use of Protected Objects.
7145
7146    procedure Expand_N_Delay_Relative_Statement (N : Node_Id) is
7147       Loc : constant Source_Ptr := Sloc (N);
7148    begin
7149       Rewrite (N,
7150         Make_Procedure_Call_Statement (Loc,
7151           Name => New_Reference_To (RTE (RO_CA_Delay_For), Loc),
7152           Parameter_Associations => New_List (Expression (N))));
7153       Analyze (N);
7154    end Expand_N_Delay_Relative_Statement;
7155
7156    ------------------------------------
7157    -- Expand_N_Delay_Until_Statement --
7158    ------------------------------------
7159
7160    --  Delay Until statement is implemented as a procedure call to
7161    --  Delay_Until defined in Ada.Calendar.Delays and Ada.Real_Time.Delays.
7162
7163    procedure Expand_N_Delay_Until_Statement (N : Node_Id) is
7164       Loc : constant Source_Ptr := Sloc (N);
7165       Typ : Entity_Id;
7166
7167    begin
7168       if Is_RTE (Base_Type (Etype (Expression (N))), RO_CA_Time) then
7169          Typ := RTE (RO_CA_Delay_Until);
7170       else
7171          Typ := RTE (RO_RT_Delay_Until);
7172       end if;
7173
7174       Rewrite (N,
7175         Make_Procedure_Call_Statement (Loc,
7176           Name => New_Reference_To (Typ, Loc),
7177           Parameter_Associations => New_List (Expression (N))));
7178
7179       Analyze (N);
7180    end Expand_N_Delay_Until_Statement;
7181
7182    -------------------------
7183    -- Expand_N_Entry_Body --
7184    -------------------------
7185
7186    procedure Expand_N_Entry_Body (N : Node_Id) is
7187    begin
7188       --  Associate discriminals with the next protected operation body to be
7189       --  expanded.
7190
7191       if Present (Next_Protected_Operation (N)) then
7192          Set_Discriminals (Parent (Current_Scope));
7193       end if;
7194    end Expand_N_Entry_Body;
7195
7196    -----------------------------------
7197    -- Expand_N_Entry_Call_Statement --
7198    -----------------------------------
7199
7200    --  An entry call is expanded into GNARLI calls to implement a simple entry
7201    --  call (see Build_Simple_Entry_Call).
7202
7203    procedure Expand_N_Entry_Call_Statement (N : Node_Id) is
7204       Concval : Node_Id;
7205       Ename   : Node_Id;
7206       Index   : Node_Id;
7207
7208    begin
7209       if No_Run_Time_Mode then
7210          Error_Msg_CRT ("entry call", N);
7211          return;
7212       end if;
7213
7214       --  If this entry call is part of an asynchronous select, don't expand it
7215       --  here; it will be expanded with the select statement. Don't expand
7216       --  timed entry calls either, as they are translated into asynchronous
7217       --  entry calls.
7218
7219       --  ??? This whole approach is questionable; it may be better to go back
7220       --  to allowing the expansion to take place and then attempting to fix it
7221       --  up in Expand_N_Asynchronous_Select. The tricky part is figuring out
7222       --  whether the expanded call is on a task or protected entry.
7223
7224       if (Nkind (Parent (N)) /= N_Triggering_Alternative
7225            or else N /= Triggering_Statement (Parent (N)))
7226         and then (Nkind (Parent (N)) /= N_Entry_Call_Alternative
7227                    or else N /= Entry_Call_Statement (Parent (N))
7228                    or else Nkind (Parent (Parent (N))) /= N_Timed_Entry_Call)
7229       then
7230          Extract_Entry (N, Concval, Ename, Index);
7231          Build_Simple_Entry_Call (N, Concval, Ename, Index);
7232       end if;
7233    end Expand_N_Entry_Call_Statement;
7234
7235    --------------------------------
7236    -- Expand_N_Entry_Declaration --
7237    --------------------------------
7238
7239    --  If there are parameters, then first, each of the formals is marked by
7240    --  setting Is_Entry_Formal. Next a record type is built which is used to
7241    --  hold the parameter values. The name of this record type is entryP where
7242    --  entry is the name of the entry, with an additional corresponding access
7243    --  type called entryPA. The record type has matching components for each
7244    --  formal (the component names are the same as the formal names). For
7245    --  elementary types, the component type matches the formal type. For
7246    --  composite types, an access type is declared (with the name formalA)
7247    --  which designates the formal type, and the type of the component is this
7248    --  access type. Finally the Entry_Component of each formal is set to
7249    --  reference the corresponding record component.
7250
7251    procedure Expand_N_Entry_Declaration (N : Node_Id) is
7252       Loc        : constant Source_Ptr := Sloc (N);
7253       Entry_Ent  : constant Entity_Id  := Defining_Identifier (N);
7254       Components : List_Id;
7255       Formal     : Node_Id;
7256       Ftype      : Entity_Id;
7257       Last_Decl  : Node_Id;
7258       Component  : Entity_Id;
7259       Ctype      : Entity_Id;
7260       Decl       : Node_Id;
7261       Rec_Ent    : Entity_Id;
7262       Acc_Ent    : Entity_Id;
7263
7264    begin
7265       Formal := First_Formal (Entry_Ent);
7266       Last_Decl := N;
7267
7268       --  Most processing is done only if parameters are present
7269
7270       if Present (Formal) then
7271          Components := New_List;
7272
7273          --  Loop through formals
7274
7275          while Present (Formal) loop
7276             Set_Is_Entry_Formal (Formal);
7277             Component :=
7278               Make_Defining_Identifier (Sloc (Formal), Chars (Formal));
7279             Set_Entry_Component (Formal, Component);
7280             Set_Entry_Formal (Component, Formal);
7281             Ftype := Etype (Formal);
7282
7283             --  Declare new access type and then append
7284
7285             Ctype := Make_Temporary (Loc, 'A');
7286
7287             Decl :=
7288               Make_Full_Type_Declaration (Loc,
7289                 Defining_Identifier => Ctype,
7290                 Type_Definition     =>
7291                   Make_Access_To_Object_Definition (Loc,
7292                     All_Present        => True,
7293                     Constant_Present   => Ekind (Formal) = E_In_Parameter,
7294                     Subtype_Indication => New_Reference_To (Ftype, Loc)));
7295
7296             Insert_After (Last_Decl, Decl);
7297             Last_Decl := Decl;
7298
7299             Append_To (Components,
7300               Make_Component_Declaration (Loc,
7301                 Defining_Identifier => Component,
7302                 Component_Definition =>
7303                   Make_Component_Definition (Loc,
7304                     Aliased_Present    => False,
7305                     Subtype_Indication => New_Reference_To (Ctype, Loc))));
7306
7307             Next_Formal_With_Extras (Formal);
7308          end loop;
7309
7310          --  Create the Entry_Parameter_Record declaration
7311
7312          Rec_Ent := Make_Temporary (Loc, 'P');
7313
7314          Decl :=
7315            Make_Full_Type_Declaration (Loc,
7316              Defining_Identifier => Rec_Ent,
7317              Type_Definition     =>
7318                Make_Record_Definition (Loc,
7319                  Component_List =>
7320                    Make_Component_List (Loc,
7321                      Component_Items => Components)));
7322
7323          Insert_After (Last_Decl, Decl);
7324          Last_Decl := Decl;
7325
7326          --  Construct and link in the corresponding access type
7327
7328          Acc_Ent := Make_Temporary (Loc, 'A');
7329
7330          Set_Entry_Parameters_Type (Entry_Ent, Acc_Ent);
7331
7332          Decl :=
7333            Make_Full_Type_Declaration (Loc,
7334              Defining_Identifier => Acc_Ent,
7335              Type_Definition     =>
7336                Make_Access_To_Object_Definition (Loc,
7337                  All_Present        => True,
7338                  Subtype_Indication => New_Reference_To (Rec_Ent, Loc)));
7339
7340          Insert_After (Last_Decl, Decl);
7341          Last_Decl := Decl;
7342       end if;
7343    end Expand_N_Entry_Declaration;
7344
7345    -----------------------------
7346    -- Expand_N_Protected_Body --
7347    -----------------------------
7348
7349    --  Protected bodies are expanded to the completion of the subprograms
7350    --  created for the corresponding protected type. These are a protected and
7351    --  unprotected version of each protected subprogram in the object, a
7352    --  function to calculate each entry barrier, and a procedure to execute the
7353    --  sequence of statements of each protected entry body. For example, for
7354    --  protected type ptype:
7355
7356    --  function entB
7357    --    (O : System.Address;
7358    --     E : Protected_Entry_Index)
7359    --     return Boolean
7360    --  is
7361    --     <discriminant renamings>
7362    --     <private object renamings>
7363    --  begin
7364    --     return <barrier expression>;
7365    --  end entB;
7366
7367    --  procedure pprocN (_object : in out poV;...) is
7368    --     <discriminant renamings>
7369    --     <private object renamings>
7370    --  begin
7371    --     <sequence of statements>
7372    --  end pprocN;
7373
7374    --  procedure pprocP (_object : in out poV;...) is
7375    --     procedure _clean is
7376    --       Pn : Boolean;
7377    --     begin
7378    --       ptypeS (_object, Pn);
7379    --       Unlock (_object._object'Access);
7380    --       Abort_Undefer.all;
7381    --     end _clean;
7382
7383    --  begin
7384    --     Abort_Defer.all;
7385    --     Lock (_object._object'Access);
7386    --     pprocN (_object;...);
7387    --  at end
7388    --     _clean;
7389    --  end pproc;
7390
7391    --  function pfuncN (_object : poV;...) return Return_Type is
7392    --     <discriminant renamings>
7393    --     <private object renamings>
7394    --  begin
7395    --     <sequence of statements>
7396    --  end pfuncN;
7397
7398    --  function pfuncP (_object : poV) return Return_Type is
7399    --     procedure _clean is
7400    --     begin
7401    --        Unlock (_object._object'Access);
7402    --        Abort_Undefer.all;
7403    --     end _clean;
7404
7405    --  begin
7406    --     Abort_Defer.all;
7407    --     Lock (_object._object'Access);
7408    --     return pfuncN (_object);
7409
7410    --  at end
7411    --     _clean;
7412    --  end pfunc;
7413
7414    --  procedure entE
7415    --    (O : System.Address;
7416    --     P : System.Address;
7417    --     E : Protected_Entry_Index)
7418    --  is
7419    --     <discriminant renamings>
7420    --     <private object renamings>
7421    --     type poVP is access poV;
7422    --     _Object : ptVP := ptVP!(O);
7423
7424    --  begin
7425    --     begin
7426    --        <statement sequence>
7427    --        Complete_Entry_Body (_Object._Object);
7428    --     exception
7429    --        when all others =>
7430    --           Exceptional_Complete_Entry_Body (
7431    --             _Object._Object, Get_GNAT_Exception);
7432    --     end;
7433    --  end entE;
7434
7435    --  The type poV is the record created for the protected type to hold
7436    --  the state of the protected object.
7437
7438    procedure Expand_N_Protected_Body (N : Node_Id) is
7439       Loc          : constant Source_Ptr := Sloc (N);
7440       Pid          : constant Entity_Id  := Corresponding_Spec (N);
7441
7442       Current_Node : Node_Id;
7443       Disp_Op_Body : Node_Id;
7444       New_Op_Body  : Node_Id;
7445       Num_Entries  : Natural := 0;
7446       Op_Body      : Node_Id;
7447       Op_Id        : Entity_Id;
7448
7449       Chain        : Entity_Id := Empty;
7450       --  Finalization chain that may be attached to new body
7451
7452       function Build_Dispatching_Subprogram_Body
7453         (N        : Node_Id;
7454          Pid      : Node_Id;
7455          Prot_Bod : Node_Id) return Node_Id;
7456       --  Build a dispatching version of the protected subprogram body. The
7457       --  newly generated subprogram contains a call to the original protected
7458       --  body. The following code is generated:
7459       --
7460       --  function <protected-function-name> (Param1 .. ParamN) return
7461       --    <return-type> is
7462       --  begin
7463       --     return <protected-function-name>P (Param1 .. ParamN);
7464       --  end <protected-function-name>;
7465       --
7466       --  or
7467       --
7468       --  procedure <protected-procedure-name> (Param1 .. ParamN) is
7469       --  begin
7470       --     <protected-procedure-name>P (Param1 .. ParamN);
7471       --  end <protected-procedure-name>
7472
7473       ---------------------------------------
7474       -- Build_Dispatching_Subprogram_Body --
7475       ---------------------------------------
7476
7477       function Build_Dispatching_Subprogram_Body
7478         (N        : Node_Id;
7479          Pid      : Node_Id;
7480          Prot_Bod : Node_Id) return Node_Id
7481       is
7482          Loc     : constant Source_Ptr := Sloc (N);
7483          Actuals : List_Id;
7484          Formal  : Node_Id;
7485          Spec    : Node_Id;
7486          Stmts   : List_Id;
7487
7488       begin
7489          --  Generate a specification without a letter suffix in order to
7490          --  override an interface function or procedure.
7491
7492          Spec := Build_Protected_Sub_Specification (N, Pid, Dispatching_Mode);
7493
7494          --  The formal parameters become the actuals of the protected function
7495          --  or procedure call.
7496
7497          Actuals := New_List;
7498          Formal  := First (Parameter_Specifications (Spec));
7499          while Present (Formal) loop
7500             Append_To (Actuals,
7501               Make_Identifier (Loc, Chars (Defining_Identifier (Formal))));
7502
7503             Next (Formal);
7504          end loop;
7505
7506          if Nkind (Spec) = N_Procedure_Specification then
7507             Stmts :=
7508               New_List (
7509                 Make_Procedure_Call_Statement (Loc,
7510                   Name =>
7511                     New_Reference_To (Corresponding_Spec (Prot_Bod), Loc),
7512                   Parameter_Associations => Actuals));
7513          else
7514             pragma Assert (Nkind (Spec) = N_Function_Specification);
7515
7516             Stmts :=
7517               New_List (
7518                 Make_Simple_Return_Statement (Loc,
7519                   Expression =>
7520                     Make_Function_Call (Loc,
7521                       Name =>
7522                         New_Reference_To (Corresponding_Spec (Prot_Bod), Loc),
7523                       Parameter_Associations => Actuals)));
7524          end if;
7525
7526          return
7527            Make_Subprogram_Body (Loc,
7528              Declarations               => Empty_List,
7529              Specification              => Spec,
7530              Handled_Statement_Sequence =>
7531                Make_Handled_Sequence_Of_Statements (Loc, Stmts));
7532       end Build_Dispatching_Subprogram_Body;
7533
7534    --  Start of processing for Expand_N_Protected_Body
7535
7536    begin
7537       if No_Run_Time_Mode then
7538          Error_Msg_CRT ("protected body", N);
7539          return;
7540       end if;
7541
7542       --  This is the proper body corresponding to a stub. The declarations
7543       --  must be inserted at the point of the stub, which in turn is in the
7544       --  declarative part of the parent unit.
7545
7546       if Nkind (Parent (N)) = N_Subunit then
7547          Current_Node := Corresponding_Stub (Parent (N));
7548       else
7549          Current_Node := N;
7550       end if;
7551
7552       Op_Body := First (Declarations (N));
7553
7554       --  The protected body is replaced with the bodies of its
7555       --  protected operations, and the declarations for internal objects
7556       --  that may have been created for entry family bounds.
7557
7558       Rewrite (N, Make_Null_Statement (Sloc (N)));
7559       Analyze (N);
7560
7561       while Present (Op_Body) loop
7562          case Nkind (Op_Body) is
7563             when N_Subprogram_Declaration =>
7564                null;
7565
7566             when N_Subprogram_Body =>
7567
7568                --  Do not create bodies for eliminated operations
7569
7570                if not Is_Eliminated (Defining_Entity (Op_Body))
7571                  and then not Is_Eliminated (Corresponding_Spec (Op_Body))
7572                then
7573                   New_Op_Body :=
7574                     Build_Unprotected_Subprogram_Body (Op_Body, Pid);
7575
7576                   --  Propagate the finalization chain to the new body. In the
7577                   --  unlikely event that the subprogram contains a declaration
7578                   --  or allocator for an object that requires finalization,
7579                   --  the corresponding chain is created when analyzing the
7580                   --  body, and attached to its entity. This entity is not
7581                   --  further elaborated, and so the chain properly belongs to
7582                   --  the newly created subprogram body.
7583
7584                   Chain :=
7585                     Finalization_Chain_Entity (Defining_Entity (Op_Body));
7586
7587                   if Present (Chain) then
7588                      Set_Finalization_Chain_Entity
7589                        (Protected_Body_Subprogram
7590                          (Corresponding_Spec (Op_Body)), Chain);
7591                      Set_Analyzed
7592                          (Handled_Statement_Sequence (New_Op_Body), False);
7593                   end if;
7594
7595                   Insert_After (Current_Node, New_Op_Body);
7596                   Current_Node := New_Op_Body;
7597                   Analyze (New_Op_Body);
7598
7599                   --  Build the corresponding protected operation. It may
7600                   --  appear that this is needed only if this is a visible
7601                   --  operation of the type, or if it is an interrupt handler,
7602                   --  and this was the strategy used previously in GNAT.
7603                   --  However, the operation may be exported through a 'Access
7604                   --  to an external caller. This is the common idiom in code
7605                   --  that uses the Ada 2005 Timing_Events package. As a result
7606                   --  we need to produce the protected body for both visible
7607                   --  and private operations, as well as operations that only
7608                   --  have a body in the source, and for which we create a
7609                   --  declaration in the protected body itself.
7610
7611                   if Present (Corresponding_Spec (Op_Body)) then
7612                      New_Op_Body :=
7613                        Build_Protected_Subprogram_Body (
7614                          Op_Body, Pid, Specification (New_Op_Body));
7615
7616                      Insert_After (Current_Node, New_Op_Body);
7617                      Analyze (New_Op_Body);
7618
7619                      Current_Node := New_Op_Body;
7620
7621                      --  Generate an overriding primitive operation body for
7622                      --  this subprogram if the protected type implements an
7623                      --  interface.
7624
7625                      if Ada_Version >= Ada_2005
7626                           and then
7627                         Present (Interfaces (Corresponding_Record_Type (Pid)))
7628                      then
7629                         Disp_Op_Body :=
7630                           Build_Dispatching_Subprogram_Body
7631                             (Op_Body, Pid, New_Op_Body);
7632
7633                         Insert_After (Current_Node, Disp_Op_Body);
7634                         Analyze (Disp_Op_Body);
7635
7636                         Current_Node := Disp_Op_Body;
7637                      end if;
7638                   end if;
7639                end if;
7640
7641             when N_Entry_Body =>
7642                Op_Id := Defining_Identifier (Op_Body);
7643                Num_Entries := Num_Entries + 1;
7644
7645                New_Op_Body := Build_Protected_Entry (Op_Body, Op_Id, Pid);
7646
7647                Insert_After (Current_Node, New_Op_Body);
7648                Current_Node := New_Op_Body;
7649                Analyze (New_Op_Body);
7650
7651             when N_Implicit_Label_Declaration =>
7652                null;
7653
7654             when N_Itype_Reference =>
7655                Insert_After (Current_Node, New_Copy (Op_Body));
7656
7657             when N_Freeze_Entity =>
7658                New_Op_Body := New_Copy (Op_Body);
7659
7660                if Present (Entity (Op_Body))
7661                  and then Freeze_Node (Entity (Op_Body)) = Op_Body
7662                then
7663                   Set_Freeze_Node (Entity (Op_Body), New_Op_Body);
7664                end if;
7665
7666                Insert_After (Current_Node, New_Op_Body);
7667                Current_Node := New_Op_Body;
7668                Analyze (New_Op_Body);
7669
7670             when N_Pragma =>
7671                New_Op_Body := New_Copy (Op_Body);
7672                Insert_After (Current_Node, New_Op_Body);
7673                Current_Node := New_Op_Body;
7674                Analyze (New_Op_Body);
7675
7676             when N_Object_Declaration =>
7677                pragma Assert (not Comes_From_Source (Op_Body));
7678                New_Op_Body := New_Copy (Op_Body);
7679                Insert_After (Current_Node, New_Op_Body);
7680                Current_Node := New_Op_Body;
7681                Analyze (New_Op_Body);
7682
7683             when others =>
7684                raise Program_Error;
7685
7686          end case;
7687
7688          Next (Op_Body);
7689       end loop;
7690
7691       --  Finally, create the body of the function that maps an entry index
7692       --  into the corresponding body index, except when there is no entry, or
7693       --  in a Ravenscar-like profile.
7694
7695       if Corresponding_Runtime_Package (Pid) =
7696            System_Tasking_Protected_Objects_Entries
7697       then
7698          New_Op_Body := Build_Find_Body_Index (Pid);
7699          Insert_After (Current_Node, New_Op_Body);
7700          Current_Node := New_Op_Body;
7701          Analyze (New_Op_Body);
7702       end if;
7703
7704       --  Ada 2005 (AI-345): Construct the primitive wrapper bodies after the
7705       --  protected body. At this point all wrapper specs have been created,
7706       --  frozen and included in the dispatch table for the protected type.
7707
7708       if Ada_Version >= Ada_2005 then
7709          Build_Wrapper_Bodies (Loc, Pid, Current_Node);
7710       end if;
7711    end Expand_N_Protected_Body;
7712
7713    -----------------------------------------
7714    -- Expand_N_Protected_Type_Declaration --
7715    -----------------------------------------
7716
7717    --  First we create a corresponding record type declaration used to
7718    --  represent values of this protected type.
7719    --  The general form of this type declaration is
7720
7721    --    type poV (discriminants) is record
7722    --      _Object       : aliased <kind>Protection
7723    --         [(<entry count> [, <handler count>])];
7724    --      [entry_family  : array (bounds) of Void;]
7725    --      <private data fields>
7726    --    end record;
7727
7728    --  The discriminants are present only if the corresponding protected type
7729    --  has discriminants, and they exactly mirror the protected type
7730    --  discriminants. The private data fields similarly mirror the private
7731    --  declarations of the protected type.
7732
7733    --  The Object field is always present. It contains RTS specific data used
7734    --  to control the protected object. It is declared as Aliased so that it
7735    --  can be passed as a pointer to the RTS. This allows the protected record
7736    --  to be referenced within RTS data structures. An appropriate Protection
7737    --  type and discriminant are generated.
7738
7739    --  The Service field is present for protected objects with entries. It
7740    --  contains sufficient information to allow the entry service procedure for
7741    --  this object to be called when the object is not known till runtime.
7742
7743    --  One entry_family component is present for each entry family in the
7744    --  task definition (see Expand_N_Task_Type_Declaration).
7745
7746    --  When a protected object is declared, an instance of the protected type
7747    --  value record is created. The elaboration of this declaration creates the
7748    --  correct bounds for the entry families, and also evaluates the priority
7749    --  expression if needed. The initialization routine for the protected type
7750    --  itself then calls Initialize_Protection with appropriate parameters to
7751    --  initialize the value of the Task_Id field. Install_Handlers may be also
7752    --  called if a pragma Attach_Handler applies.
7753
7754    --  Note: this record is passed to the subprograms created by the expansion
7755    --  of protected subprograms and entries. It is an in parameter to protected
7756    --  functions and an in out parameter to procedures and entry bodies. The
7757    --  Entity_Id for this created record type is placed in the
7758    --  Corresponding_Record_Type field of the associated protected type entity.
7759
7760    --  Next we create a procedure specifications for protected subprograms and
7761    --  entry bodies. For each protected subprograms two subprograms are
7762    --  created, an unprotected and a protected version. The unprotected version
7763    --  is called from within other operations of the same protected object.
7764
7765    --  We also build the call to register the procedure if a pragma
7766    --  Interrupt_Handler applies.
7767
7768    --  A single subprogram is created to service all entry bodies; it has an
7769    --  additional boolean out parameter indicating that the previous entry call
7770    --  made by the current task was serviced immediately, i.e. not by proxy.
7771    --  The O parameter contains a pointer to a record object of the type
7772    --  described above. An untyped interface is used here to allow this
7773    --  procedure to be called in places where the type of the object to be
7774    --  serviced is not known. This must be done, for example, when a call that
7775    --  may have been requeued is cancelled; the corresponding object must be
7776    --  serviced, but which object that is not known till runtime.
7777
7778    --  procedure ptypeS
7779    --    (O : System.Address; P : out Boolean);
7780    --  procedure pprocN (_object : in out poV);
7781    --  procedure pproc (_object : in out poV);
7782    --  function pfuncN (_object : poV);
7783    --  function pfunc (_object : poV);
7784    --  ...
7785
7786    --  Note that this must come after the record type declaration, since
7787    --  the specs refer to this type.
7788
7789    procedure Expand_N_Protected_Type_Declaration (N : Node_Id) is
7790       Loc      : constant Source_Ptr := Sloc (N);
7791       Prot_Typ : constant Entity_Id  := Defining_Identifier (N);
7792
7793       Pdef : constant Node_Id := Protected_Definition (N);
7794       --  This contains two lists; one for visible and one for private decls
7795
7796       Rec_Decl     : Node_Id;
7797       Cdecls       : List_Id;
7798       Discr_Map    : constant Elist_Id := New_Elmt_List;
7799       Priv         : Node_Id;
7800       New_Priv     : Node_Id;
7801       Comp         : Node_Id;
7802       Comp_Id      : Entity_Id;
7803       Sub          : Node_Id;
7804       Current_Node : Node_Id := N;
7805       Bdef         : Entity_Id := Empty; -- avoid uninit warning
7806       Edef         : Entity_Id := Empty; -- avoid uninit warning
7807       Entries_Aggr : Node_Id;
7808       Body_Id      : Entity_Id;
7809       Body_Arr     : Node_Id;
7810       E_Count      : Int;
7811       Object_Comp  : Node_Id;
7812
7813       procedure Check_Inlining (Subp : Entity_Id);
7814       --  If the original operation has a pragma Inline, propagate the flag
7815       --  to the internal body, for possible inlining later on. The source
7816       --  operation is invisible to the back-end and is never actually called.
7817
7818       function Static_Component_Size (Comp : Entity_Id) return Boolean;
7819       --  When compiling under the Ravenscar profile, private components must
7820       --  have a static size, or else a protected object  will require heap
7821       --  allocation, violating the corresponding restriction. It is preferable
7822       --  to make this check here, because it provides a better error message
7823       --  than the back-end, which refers to the object as a whole.
7824
7825       procedure Register_Handler;
7826       --  For a protected operation that is an interrupt handler, add the
7827       --  freeze action that will register it as such.
7828
7829       --------------------
7830       -- Check_Inlining --
7831       --------------------
7832
7833       procedure Check_Inlining (Subp : Entity_Id) is
7834       begin
7835          if Is_Inlined (Subp) then
7836             Set_Is_Inlined (Protected_Body_Subprogram (Subp));
7837             Set_Is_Inlined (Subp, False);
7838          end if;
7839       end Check_Inlining;
7840
7841       ---------------------------------
7842       -- Check_Static_Component_Size --
7843       ---------------------------------
7844
7845       function Static_Component_Size (Comp : Entity_Id) return Boolean is
7846          Typ : constant Entity_Id := Etype (Comp);
7847          C   : Entity_Id;
7848
7849       begin
7850          if Is_Scalar_Type (Typ) then
7851             return True;
7852
7853          elsif Is_Array_Type (Typ) then
7854             return Compile_Time_Known_Bounds (Typ);
7855
7856          elsif Is_Record_Type (Typ) then
7857             C := First_Component (Typ);
7858             while Present (C) loop
7859                if not Static_Component_Size (C) then
7860                   return False;
7861                end if;
7862
7863                Next_Component (C);
7864             end loop;
7865
7866             return True;
7867
7868          --  Any other types will be checked by the back-end
7869
7870          else
7871             return True;
7872          end if;
7873       end Static_Component_Size;
7874
7875       ----------------------
7876       -- Register_Handler --
7877       ----------------------
7878
7879       procedure Register_Handler is
7880
7881          --  All semantic checks already done in Sem_Prag
7882
7883          Prot_Proc    : constant Entity_Id :=
7884                        Defining_Unit_Name
7885                          (Specification (Current_Node));
7886
7887          Proc_Address : constant Node_Id :=
7888                           Make_Attribute_Reference (Loc,
7889                           Prefix => New_Reference_To (Prot_Proc, Loc),
7890                           Attribute_Name => Name_Address);
7891
7892          RTS_Call     : constant Entity_Id :=
7893                           Make_Procedure_Call_Statement (Loc,
7894                             Name =>
7895                               New_Reference_To (
7896                                 RTE (RE_Register_Interrupt_Handler), Loc),
7897                             Parameter_Associations =>
7898                               New_List (Proc_Address));
7899       begin
7900          Append_Freeze_Action (Prot_Proc, RTS_Call);
7901       end Register_Handler;
7902
7903    --  Start of processing for Expand_N_Protected_Type_Declaration
7904
7905    begin
7906       if Present (Corresponding_Record_Type (Prot_Typ)) then
7907          return;
7908       else
7909          Rec_Decl := Build_Corresponding_Record (N, Prot_Typ, Loc);
7910       end if;
7911
7912       Cdecls := Component_Items (Component_List (Type_Definition (Rec_Decl)));
7913
7914       Qualify_Entity_Names (N);
7915
7916       --  If the type has discriminants, their occurrences in the declaration
7917       --  have been replaced by the corresponding discriminals. For components
7918       --  that are constrained by discriminants, their homologues in the
7919       --  corresponding record type must refer to the discriminants of that
7920       --  record, so we must apply a new renaming to subtypes_indications:
7921
7922       --     protected discriminant => discriminal => record discriminant
7923
7924       --  This replacement is not applied to default expressions, for which
7925       --  the discriminal is correct.
7926
7927       if Has_Discriminants (Prot_Typ) then
7928          declare
7929             Disc : Entity_Id;
7930             Decl : Node_Id;
7931
7932          begin
7933             Disc := First_Discriminant (Prot_Typ);
7934             Decl := First (Discriminant_Specifications (Rec_Decl));
7935             while Present (Disc) loop
7936                Append_Elmt (Discriminal (Disc), Discr_Map);
7937                Append_Elmt (Defining_Identifier (Decl), Discr_Map);
7938                Next_Discriminant (Disc);
7939                Next (Decl);
7940             end loop;
7941          end;
7942       end if;
7943
7944       --  Fill in the component declarations
7945
7946       --  Add components for entry families. For each entry family, create an
7947       --  anonymous type declaration with the same size, and analyze the type.
7948
7949       Collect_Entry_Families (Loc, Cdecls, Current_Node, Prot_Typ);
7950
7951       --  Prepend the _Object field with the right type to the component list.
7952       --  We need to compute the number of entries, and in some cases the
7953       --  number of Attach_Handler pragmas.
7954
7955       declare
7956          Ritem              : Node_Id;
7957          Num_Attach_Handler : Int := 0;
7958          Protection_Subtype : Node_Id;
7959          Entry_Count_Expr   : constant Node_Id :=
7960                                 Build_Entry_Count_Expression
7961                                   (Prot_Typ, Cdecls, Loc);
7962
7963       begin
7964          --  Could this be simplified using Corresponding_Runtime_Package???
7965
7966          if Has_Attach_Handler (Prot_Typ) then
7967             Ritem := First_Rep_Item (Prot_Typ);
7968             while Present (Ritem) loop
7969                if Nkind (Ritem) = N_Pragma
7970                  and then Pragma_Name (Ritem) = Name_Attach_Handler
7971                then
7972                   Num_Attach_Handler := Num_Attach_Handler + 1;
7973                end if;
7974
7975                Next_Rep_Item (Ritem);
7976             end loop;
7977
7978             if Restricted_Profile then
7979                if Has_Entries (Prot_Typ) then
7980                   Protection_Subtype :=
7981                     New_Reference_To (RTE (RE_Protection_Entry), Loc);
7982                else
7983                   Protection_Subtype :=
7984                     New_Reference_To (RTE (RE_Protection), Loc);
7985                end if;
7986             else
7987                Protection_Subtype :=
7988                  Make_Subtype_Indication
7989                    (Sloc => Loc,
7990                     Subtype_Mark =>
7991                       New_Reference_To
7992                         (RTE (RE_Static_Interrupt_Protection), Loc),
7993                     Constraint =>
7994                       Make_Index_Or_Discriminant_Constraint (
7995                         Sloc => Loc,
7996                         Constraints => New_List (
7997                           Entry_Count_Expr,
7998                           Make_Integer_Literal (Loc, Num_Attach_Handler))));
7999             end if;
8000
8001          elsif Has_Interrupt_Handler (Prot_Typ) then
8002             Protection_Subtype :=
8003                Make_Subtype_Indication (
8004                  Sloc => Loc,
8005                  Subtype_Mark => New_Reference_To
8006                    (RTE (RE_Dynamic_Interrupt_Protection), Loc),
8007                  Constraint =>
8008                    Make_Index_Or_Discriminant_Constraint (
8009                      Sloc => Loc,
8010                      Constraints => New_List (Entry_Count_Expr)));
8011
8012          --  Type has explicit entries or generated primitive entry wrappers
8013
8014          elsif Has_Entries (Prot_Typ)
8015            or else (Ada_Version >= Ada_2005
8016                       and then Present (Interface_List (N)))
8017          then
8018             case Corresponding_Runtime_Package (Prot_Typ) is
8019                when System_Tasking_Protected_Objects_Entries =>
8020                   Protection_Subtype :=
8021                      Make_Subtype_Indication (Loc,
8022                        Subtype_Mark =>
8023                          New_Reference_To (RTE (RE_Protection_Entries), Loc),
8024                        Constraint =>
8025                          Make_Index_Or_Discriminant_Constraint (
8026                            Sloc => Loc,
8027                            Constraints => New_List (Entry_Count_Expr)));
8028
8029                when System_Tasking_Protected_Objects_Single_Entry =>
8030                   Protection_Subtype :=
8031                     New_Reference_To (RTE (RE_Protection_Entry), Loc);
8032
8033                when others =>
8034                   raise Program_Error;
8035             end case;
8036
8037          else
8038             Protection_Subtype := New_Reference_To (RTE (RE_Protection), Loc);
8039          end if;
8040
8041          Object_Comp :=
8042            Make_Component_Declaration (Loc,
8043              Defining_Identifier =>
8044                Make_Defining_Identifier (Loc, Name_uObject),
8045              Component_Definition =>
8046                Make_Component_Definition (Loc,
8047                  Aliased_Present    => True,
8048                  Subtype_Indication => Protection_Subtype));
8049       end;
8050
8051       pragma Assert (Present (Pdef));
8052
8053       --  Add private field components
8054
8055       if Present (Private_Declarations (Pdef)) then
8056          Priv := First (Private_Declarations (Pdef));
8057
8058          while Present (Priv) loop
8059
8060             if Nkind (Priv) = N_Component_Declaration then
8061                if not Static_Component_Size (Defining_Identifier (Priv)) then
8062
8063                   --  When compiling for a restricted profile, the private
8064                   --  components must have a static size. If not, this is an
8065                   --  error for a single protected declaration, and rates a
8066                   --  warning on a protected type declaration.
8067
8068                   if not Comes_From_Source (Prot_Typ) then
8069                      Check_Restriction (No_Implicit_Heap_Allocations, Priv);
8070
8071                   elsif Restriction_Active (No_Implicit_Heap_Allocations) then
8072                      Error_Msg_N ("component has non-static size?", Priv);
8073                      Error_Msg_NE
8074                        ("\creation of protected object of type& will violate"
8075                         & " restriction No_Implicit_Heap_Allocations?",
8076                         Priv, Prot_Typ);
8077                   end if;
8078                end if;
8079
8080                --  The component definition consists of a subtype indication,
8081                --  or (in Ada 2005) an access definition. Make a copy of the
8082                --  proper definition.
8083
8084                declare
8085                   Old_Comp : constant Node_Id   := Component_Definition (Priv);
8086                   Oent     : constant Entity_Id := Defining_Identifier (Priv);
8087                   New_Comp : Node_Id;
8088                   Nent     : constant Entity_Id :=
8089                                Make_Defining_Identifier (Sloc (Oent),
8090                                  Chars => Chars (Oent));
8091
8092                begin
8093                   if Present (Subtype_Indication (Old_Comp)) then
8094                      New_Comp :=
8095                        Make_Component_Definition (Sloc (Oent),
8096                          Aliased_Present    => False,
8097                          Subtype_Indication =>
8098                            New_Copy_Tree (Subtype_Indication (Old_Comp),
8099                                            Discr_Map));
8100                   else
8101                      New_Comp :=
8102                        Make_Component_Definition (Sloc (Oent),
8103                          Aliased_Present    => False,
8104                          Access_Definition  =>
8105                            New_Copy_Tree (Access_Definition (Old_Comp),
8106                                            Discr_Map));
8107                   end if;
8108
8109                   New_Priv :=
8110                     Make_Component_Declaration (Loc,
8111                       Defining_Identifier  => Nent,
8112                       Component_Definition => New_Comp,
8113                       Expression           => Expression (Priv));
8114
8115                   Set_Has_Per_Object_Constraint (Nent,
8116                     Has_Per_Object_Constraint (Oent));
8117
8118                   Append_To (Cdecls, New_Priv);
8119                end;
8120
8121             elsif Nkind (Priv) = N_Subprogram_Declaration then
8122
8123                --  Make the unprotected version of the subprogram available
8124                --  for expansion of intra object calls. There is need for
8125                --  a protected version only if the subprogram is an interrupt
8126                --  handler, otherwise  this operation can only be called from
8127                --  within the body.
8128
8129                Sub :=
8130                  Make_Subprogram_Declaration (Loc,
8131                    Specification =>
8132                      Build_Protected_Sub_Specification
8133                        (Priv, Prot_Typ, Unprotected_Mode));
8134
8135                Insert_After (Current_Node, Sub);
8136                Analyze (Sub);
8137
8138                Set_Protected_Body_Subprogram
8139                  (Defining_Unit_Name (Specification (Priv)),
8140                   Defining_Unit_Name (Specification (Sub)));
8141                Check_Inlining (Defining_Unit_Name (Specification (Priv)));
8142                Current_Node := Sub;
8143
8144                Sub :=
8145                  Make_Subprogram_Declaration (Loc,
8146                    Specification =>
8147                      Build_Protected_Sub_Specification
8148                        (Priv, Prot_Typ, Protected_Mode));
8149
8150                Insert_After (Current_Node, Sub);
8151                Analyze (Sub);
8152                Current_Node := Sub;
8153
8154                if Is_Interrupt_Handler
8155                  (Defining_Unit_Name (Specification (Priv)))
8156                then
8157                   if not Restricted_Profile then
8158                      Register_Handler;
8159                   end if;
8160                end if;
8161             end if;
8162
8163             Next (Priv);
8164          end loop;
8165       end if;
8166
8167       --  Put the _Object component after the private component so that it
8168       --  be finalized early as required by 9.4 (20)
8169
8170       Append_To (Cdecls, Object_Comp);
8171
8172       Insert_After (Current_Node, Rec_Decl);
8173       Current_Node := Rec_Decl;
8174
8175       --  Analyze the record declaration immediately after construction,
8176       --  because the initialization procedure is needed for single object
8177       --  declarations before the next entity is analyzed (the freeze call
8178       --  that generates this initialization procedure is found below).
8179
8180       Analyze (Rec_Decl, Suppress => All_Checks);
8181
8182       --  Ada 2005 (AI-345): Construct the primitive entry wrappers before
8183       --  the corresponding record is frozen. If any wrappers are generated,
8184       --  Current_Node is updated accordingly.
8185
8186       if Ada_Version >= Ada_2005 then
8187          Build_Wrapper_Specs (Loc, Prot_Typ, Current_Node);
8188       end if;
8189
8190       --  Collect pointers to entry bodies and their barriers, to be placed
8191       --  in the Entry_Bodies_Array for the type. For each entry/family we
8192       --  add an expression to the aggregate which is the initial value of
8193       --  this array. The array is declared after all protected subprograms.
8194
8195       if Has_Entries (Prot_Typ) then
8196          Entries_Aggr := Make_Aggregate (Loc, Expressions => New_List);
8197       else
8198          Entries_Aggr := Empty;
8199       end if;
8200
8201       --  Build two new procedure specifications for each protected subprogram;
8202       --  one to call from outside the object and one to call from inside.
8203       --  Build a barrier function and an entry body action procedure
8204       --  specification for each protected entry. Initialize the entry body
8205       --  array. If subprogram is flagged as eliminated, do not generate any
8206       --  internal operations.
8207
8208       E_Count := 0;
8209
8210       Comp := First (Visible_Declarations (Pdef));
8211
8212       while Present (Comp) loop
8213          if Nkind (Comp) = N_Subprogram_Declaration then
8214             Sub :=
8215               Make_Subprogram_Declaration (Loc,
8216                 Specification =>
8217                   Build_Protected_Sub_Specification
8218                     (Comp, Prot_Typ, Unprotected_Mode));
8219
8220             Insert_After (Current_Node, Sub);
8221             Analyze (Sub);
8222
8223             Set_Protected_Body_Subprogram
8224               (Defining_Unit_Name (Specification (Comp)),
8225                Defining_Unit_Name (Specification (Sub)));
8226                Check_Inlining (Defining_Unit_Name (Specification (Comp)));
8227
8228             --  Make the protected version of the subprogram available for
8229             --  expansion of external calls.
8230
8231             Current_Node := Sub;
8232
8233             Sub :=
8234               Make_Subprogram_Declaration (Loc,
8235                 Specification =>
8236                   Build_Protected_Sub_Specification
8237                     (Comp, Prot_Typ, Protected_Mode));
8238
8239             Insert_After (Current_Node, Sub);
8240             Analyze (Sub);
8241
8242             Current_Node := Sub;
8243
8244             --  Generate an overriding primitive operation specification for
8245             --  this subprogram if the protected type implements an interface.
8246
8247             if Ada_Version >= Ada_2005
8248               and then
8249                 Present (Interfaces (Corresponding_Record_Type (Prot_Typ)))
8250             then
8251                Sub :=
8252                  Make_Subprogram_Declaration (Loc,
8253                    Specification =>
8254                      Build_Protected_Sub_Specification
8255                        (Comp, Prot_Typ, Dispatching_Mode));
8256
8257                Insert_After (Current_Node, Sub);
8258                Analyze (Sub);
8259
8260                Current_Node := Sub;
8261             end if;
8262
8263             --  If a pragma Interrupt_Handler applies, build and add a call to
8264             --  Register_Interrupt_Handler to the freezing actions of the
8265             --  protected version (Current_Node) of the subprogram:
8266
8267             --    system.interrupts.register_interrupt_handler
8268             --       (prot_procP'address);
8269
8270             if not Restricted_Profile
8271               and then Is_Interrupt_Handler
8272                          (Defining_Unit_Name (Specification (Comp)))
8273             then
8274                Register_Handler;
8275             end if;
8276
8277          elsif Nkind (Comp) = N_Entry_Declaration then
8278             E_Count := E_Count + 1;
8279             Comp_Id := Defining_Identifier (Comp);
8280
8281             Edef :=
8282               Make_Defining_Identifier (Loc,
8283                 Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
8284             Sub :=
8285               Make_Subprogram_Declaration (Loc,
8286                 Specification =>
8287                   Build_Protected_Entry_Specification (Loc, Edef, Comp_Id));
8288
8289             Insert_After (Current_Node, Sub);
8290             Analyze (Sub);
8291
8292             --  build wrapper procedure for pre/postconditions.
8293
8294             Build_PPC_Wrapper (Comp_Id, N);
8295
8296             Set_Protected_Body_Subprogram
8297               (Defining_Identifier (Comp),
8298                Defining_Unit_Name (Specification (Sub)));
8299
8300             Current_Node := Sub;
8301
8302             Bdef :=
8303               Make_Defining_Identifier (Loc,
8304                 Chars => Build_Selected_Name (Prot_Typ, Comp_Id, 'B'));
8305             Sub :=
8306               Make_Subprogram_Declaration (Loc,
8307                 Specification =>
8308                   Build_Barrier_Function_Specification (Loc, Bdef));
8309
8310             Insert_After (Current_Node, Sub);
8311             Analyze (Sub);
8312             Set_Protected_Body_Subprogram (Bdef, Bdef);
8313             Set_Barrier_Function (Comp_Id, Bdef);
8314             Set_Scope (Bdef, Scope (Comp_Id));
8315             Current_Node := Sub;
8316
8317             --  Collect pointers to the protected subprogram and the barrier
8318             --  of the current entry, for insertion into Entry_Bodies_Array.
8319
8320             Append (
8321               Make_Aggregate (Loc,
8322                 Expressions => New_List (
8323                   Make_Attribute_Reference (Loc,
8324                     Prefix => New_Reference_To (Bdef, Loc),
8325                     Attribute_Name => Name_Unrestricted_Access),
8326                   Make_Attribute_Reference (Loc,
8327                     Prefix => New_Reference_To (Edef, Loc),
8328                     Attribute_Name => Name_Unrestricted_Access))),
8329               Expressions (Entries_Aggr));
8330
8331          end if;
8332
8333          Next (Comp);
8334       end loop;
8335
8336       --  If there are some private entry declarations, expand it as if they
8337       --  were visible entries.
8338
8339       if Present (Private_Declarations (Pdef)) then
8340          Comp := First (Private_Declarations (Pdef));
8341          while Present (Comp) loop
8342             if Nkind (Comp) = N_Entry_Declaration then
8343                E_Count := E_Count + 1;
8344                Comp_Id := Defining_Identifier (Comp);
8345
8346                Edef :=
8347                  Make_Defining_Identifier (Loc,
8348                   Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
8349                Sub :=
8350                  Make_Subprogram_Declaration (Loc,
8351                    Specification =>
8352                      Build_Protected_Entry_Specification (Loc, Edef, Comp_Id));
8353
8354                Insert_After (Current_Node, Sub);
8355                Analyze (Sub);
8356
8357                Set_Protected_Body_Subprogram
8358                  (Defining_Identifier (Comp),
8359                   Defining_Unit_Name (Specification (Sub)));
8360
8361                Current_Node := Sub;
8362
8363                Bdef :=
8364                  Make_Defining_Identifier (Loc,
8365                    Chars => Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
8366
8367                Sub :=
8368                  Make_Subprogram_Declaration (Loc,
8369                    Specification =>
8370                      Build_Barrier_Function_Specification (Loc, Bdef));
8371
8372                Insert_After (Current_Node, Sub);
8373                Analyze (Sub);
8374                Set_Protected_Body_Subprogram (Bdef, Bdef);
8375                Set_Barrier_Function (Comp_Id, Bdef);
8376                Set_Scope (Bdef, Scope (Comp_Id));
8377                Current_Node := Sub;
8378
8379                --  Collect pointers to the protected subprogram and the barrier
8380                --  of the current entry, for insertion into Entry_Bodies_Array.
8381
8382                Append_To (Expressions (Entries_Aggr),
8383                  Make_Aggregate (Loc,
8384                    Expressions => New_List (
8385                      Make_Attribute_Reference (Loc,
8386                        Prefix => New_Reference_To (Bdef, Loc),
8387                        Attribute_Name => Name_Unrestricted_Access),
8388                      Make_Attribute_Reference (Loc,
8389                        Prefix => New_Reference_To (Edef, Loc),
8390                        Attribute_Name => Name_Unrestricted_Access))));
8391             end if;
8392
8393             Next (Comp);
8394          end loop;
8395       end if;
8396
8397       --  Emit declaration for Entry_Bodies_Array, now that the addresses of
8398       --  all protected subprograms have been collected.
8399
8400       if Has_Entries (Prot_Typ) then
8401          Body_Id :=
8402            Make_Defining_Identifier (Sloc (Prot_Typ),
8403              Chars => New_External_Name (Chars (Prot_Typ), 'A'));
8404
8405          case Corresponding_Runtime_Package (Prot_Typ) is
8406             when System_Tasking_Protected_Objects_Entries =>
8407                Body_Arr := Make_Object_Declaration (Loc,
8408                  Defining_Identifier => Body_Id,
8409                  Aliased_Present => True,
8410                  Object_Definition =>
8411                    Make_Subtype_Indication (Loc,
8412                      Subtype_Mark => New_Reference_To (
8413                        RTE (RE_Protected_Entry_Body_Array), Loc),
8414                      Constraint =>
8415                        Make_Index_Or_Discriminant_Constraint (Loc,
8416                          Constraints => New_List (
8417                             Make_Range (Loc,
8418                               Make_Integer_Literal (Loc, 1),
8419                               Make_Integer_Literal (Loc, E_Count))))),
8420                  Expression => Entries_Aggr);
8421
8422             when System_Tasking_Protected_Objects_Single_Entry =>
8423                Body_Arr := Make_Object_Declaration (Loc,
8424                  Defining_Identifier => Body_Id,
8425                  Aliased_Present => True,
8426                  Object_Definition => New_Reference_To
8427                                         (RTE (RE_Entry_Body), Loc),
8428                  Expression =>
8429                    Make_Aggregate (Loc,
8430                      Expressions => New_List (
8431                        Make_Attribute_Reference (Loc,
8432                          Prefix => New_Reference_To (Bdef, Loc),
8433                          Attribute_Name => Name_Unrestricted_Access),
8434                        Make_Attribute_Reference (Loc,
8435                          Prefix => New_Reference_To (Edef, Loc),
8436                          Attribute_Name => Name_Unrestricted_Access))));
8437
8438             when others =>
8439                raise Program_Error;
8440          end case;
8441
8442          --  A pointer to this array will be placed in the corresponding record
8443          --  by its initialization procedure so this needs to be analyzed here.
8444
8445          Insert_After (Current_Node, Body_Arr);
8446          Current_Node := Body_Arr;
8447          Analyze (Body_Arr);
8448
8449          Set_Entry_Bodies_Array (Prot_Typ, Body_Id);
8450
8451          --  Finally, build the function that maps an entry index into the
8452          --  corresponding body. A pointer to this function is placed in each
8453          --  object of the type. Except for a ravenscar-like profile (no abort,
8454          --  no entry queue, 1 entry)
8455
8456          if Corresponding_Runtime_Package (Prot_Typ) =
8457               System_Tasking_Protected_Objects_Entries
8458          then
8459             Sub :=
8460               Make_Subprogram_Declaration (Loc,
8461                 Specification => Build_Find_Body_Index_Spec (Prot_Typ));
8462             Insert_After (Current_Node, Sub);
8463             Analyze (Sub);
8464          end if;
8465       end if;
8466    end Expand_N_Protected_Type_Declaration;
8467
8468    --------------------------------
8469    -- Expand_N_Requeue_Statement --
8470    --------------------------------
8471
8472    --  A non-dispatching requeue statement is expanded into one of four GNARLI
8473    --  operations, depending on the source and destination (task or protected
8474    --  object). A dispatching requeue statement is expanded into a call to the
8475    --  predefined primitive _Disp_Requeue. In addition, code is generated to
8476    --  jump around the remainder of processing for the original entry and, if
8477    --  the destination is (different) protected object, to attempt to service
8478    --  it. The following illustrates the various cases:
8479
8480    --  procedure entE
8481    --    (O : System.Address;
8482    --     P : System.Address;
8483    --     E : Protected_Entry_Index)
8484    --  is
8485    --     <discriminant renamings>
8486    --     <private object renamings>
8487    --     type poVP is access poV;
8488    --     _object : ptVP := ptVP!(O);
8489
8490    --  begin
8491    --     begin
8492    --        <start of statement sequence for entry>
8493
8494    --        -- Requeue from one protected entry body to another protected
8495    --        -- entry.
8496
8497    --        Requeue_Protected_Entry (
8498    --          _object._object'Access,
8499    --          new._object'Access,
8500    --          E,
8501    --          Abort_Present);
8502    --        return;
8503
8504    --        <some more of the statement sequence for entry>
8505
8506    --        --  Requeue from an entry body to a task entry
8507
8508    --        Requeue_Protected_To_Task_Entry (
8509    --          New._task_id,
8510    --          E,
8511    --          Abort_Present);
8512    --        return;
8513
8514    --        <rest of statement sequence for entry>
8515    --        Complete_Entry_Body (_object._object);
8516
8517    --     exception
8518    --        when all others =>
8519    --           Exceptional_Complete_Entry_Body (
8520    --             _object._object, Get_GNAT_Exception);
8521    --     end;
8522    --  end entE;
8523
8524    --  Requeue of a task entry call to a task entry
8525
8526    --  Accept_Call (E, Ann);
8527    --     <start of statement sequence for accept statement>
8528    --     Requeue_Task_Entry (New._task_id, E, Abort_Present);
8529    --     goto Lnn;
8530    --     <rest of statement sequence for accept statement>
8531    --     <<Lnn>>
8532    --     Complete_Rendezvous;
8533
8534    --  exception
8535    --     when all others =>
8536    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8537
8538    --  Requeue of a task entry call to a protected entry
8539
8540    --  Accept_Call (E, Ann);
8541    --     <start of statement sequence for accept statement>
8542    --     Requeue_Task_To_Protected_Entry (
8543    --       new._object'Access,
8544    --       E,
8545    --       Abort_Present);
8546    --     newS (new, Pnn);
8547    --     goto Lnn;
8548    --     <rest of statement sequence for accept statement>
8549    --     <<Lnn>>
8550    --     Complete_Rendezvous;
8551
8552    --  exception
8553    --     when all others =>
8554    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8555
8556    --  Ada 2012 (AI05-0030): Dispatching requeue to an interface primitive
8557    --  marked by pragma Implemented (XXX, By_Entry).
8558
8559    --  The requeue is inside a protected entry:
8560
8561    --  procedure entE
8562    --    (O : System.Address;
8563    --     P : System.Address;
8564    --     E : Protected_Entry_Index)
8565    --  is
8566    --     <discriminant renamings>
8567    --     <private object renamings>
8568    --     type poVP is access poV;
8569    --     _object : ptVP := ptVP!(O);
8570
8571    --  begin
8572    --     begin
8573    --        <start of statement sequence for entry>
8574
8575    --        _Disp_Requeue
8576    --          (<interface class-wide object>,
8577    --           True,
8578    --           _object'Address,
8579    --           Ada.Tags.Get_Offset_Index
8580    --             (Tag (_object),
8581    --              <interface dispatch table index of target entry>),
8582    --           Abort_Present);
8583    --        return;
8584
8585    --        <rest of statement sequence for entry>
8586    --        Complete_Entry_Body (_object._object);
8587
8588    --     exception
8589    --        when all others =>
8590    --           Exceptional_Complete_Entry_Body (
8591    --             _object._object, Get_GNAT_Exception);
8592    --     end;
8593    --  end entE;
8594
8595    --  The requeue is inside a task entry:
8596
8597    --    Accept_Call (E, Ann);
8598    --     <start of statement sequence for accept statement>
8599    --     _Disp_Requeue
8600    --       (<interface class-wide object>,
8601    --        False,
8602    --        null,
8603    --        Ada.Tags.Get_Offset_Index
8604    --          (Tag (_object),
8605    --           <interface dispatch table index of target entrt>),
8606    --        Abort_Present);
8607    --     newS (new, Pnn);
8608    --     goto Lnn;
8609    --     <rest of statement sequence for accept statement>
8610    --     <<Lnn>>
8611    --     Complete_Rendezvous;
8612
8613    --  exception
8614    --     when all others =>
8615    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8616
8617    --  Ada 2012 (AI05-0030): Dispatching requeue to an interface primitive
8618    --  marked by pragma Implemented (XXX, By_Protected_Procedure). The requeue
8619    --  statement is replaced by a dispatching call with actual parameters taken
8620    --  from the inner-most accept statement or entry body.
8621
8622    --    Target.Primitive (Param1, ..., ParamN);
8623
8624    --  Ada 2012 (AI05-0030): Dispatching requeue to an interface primitive
8625    --  marked by pragma Implemented (XXX, By_Any) or not marked at all.
8626
8627    --    declare
8628    --       S : constant Offset_Index :=
8629    --             Get_Offset_Index (Tag (Concval), DT_Position (Ename));
8630    --       C : constant Prim_Op_Kind := Get_Prim_Op_Kind (Tag (Concval), S);
8631
8632    --    begin
8633    --       if C = POK_Protected_Entry
8634    --         or else C = POK_Task_Entry
8635    --       then
8636    --          <statements for dispatching requeue>
8637
8638    --       elsif C = POK_Protected_Procedure then
8639    --          <dispatching call equivalent>
8640
8641    --       else
8642    --          raise Program_Error;
8643    --       end if;
8644    --    end;
8645
8646    procedure Expand_N_Requeue_Statement (N : Node_Id) is
8647       Loc      : constant Source_Ptr := Sloc (N);
8648       Conc_Typ : Entity_Id;
8649       Concval  : Node_Id;
8650       Ename    : Node_Id;
8651       Index    : Node_Id;
8652       Old_Typ  : Entity_Id;
8653
8654       function Build_Dispatching_Call_Equivalent return Node_Id;
8655       --  Ada 2012 (AI05-0030): N denotes a dispatching requeue statement of
8656       --  the form Concval.Ename. It is statically known that Ename is allowed
8657       --  to be implemented by a protected procedure. Create a dispatching call
8658       --  equivalent of Concval.Ename taking the actual parameters from the
8659       --  inner-most accept statement or entry body.
8660
8661       function Build_Dispatching_Requeue return Node_Id;
8662       --  Ada 2012 (AI05-0030): N denotes a dispatching requeue statement of
8663       --  the form Concval.Ename. It is statically known that Ename is allowed
8664       --  to be implemented by a protected or a task entry. Create a call to
8665       --  primitive _Disp_Requeue which handles the low-level actions.
8666
8667       function Build_Dispatching_Requeue_To_Any return Node_Id;
8668       --  Ada 2012 (AI05-0030): N denotes a dispatching requeue statement of
8669       --  the form Concval.Ename. Ename is either marked by pragma Implemented
8670       --  (XXX, By_Any) or not marked at all. Create a block which determines
8671       --  at runtime whether Ename denotes an entry or a procedure and perform
8672       --  the appropriate kind of dispatching select.
8673
8674       function Build_Normal_Requeue return Node_Id;
8675       --  N denotes a non-dispatching requeue statement to either a task or a
8676       --  protected entry. Build the appropriate runtime call to perform the
8677       --  action.
8678
8679       function Build_Skip_Statement (Search : Node_Id) return Node_Id;
8680       --  For a protected entry, create a return statement to skip the rest of
8681       --  the entry body. Otherwise, create a goto statement to skip the rest
8682       --  of a task accept statement. The lookup for the enclosing entry body
8683       --  or accept statement starts from Search.
8684
8685       ---------------------------------------
8686       -- Build_Dispatching_Call_Equivalent --
8687       ---------------------------------------
8688
8689       function Build_Dispatching_Call_Equivalent return Node_Id is
8690          Call_Ent : constant Entity_Id := Entity (Ename);
8691          Obj      : constant Node_Id   := Original_Node (Concval);
8692          Acc_Ent  : Node_Id;
8693          Actuals  : List_Id;
8694          Formal   : Node_Id;
8695          Formals  : List_Id;
8696
8697       begin
8698          --  Climb the parent chain looking for the inner-most entry body or
8699          --  accept statement.
8700
8701          Acc_Ent := N;
8702          while Present (Acc_Ent)
8703            and then not Nkind_In (Acc_Ent, N_Accept_Statement,
8704                                            N_Entry_Body)
8705          loop
8706             Acc_Ent := Parent (Acc_Ent);
8707          end loop;
8708
8709          --  A requeue statement should be housed inside an entry body or an
8710          --  accept statement at some level. If this is not the case, then the
8711          --  tree is malformed.
8712
8713          pragma Assert (Present (Acc_Ent));
8714
8715          --  Recover the list of formal parameters
8716
8717          if Nkind (Acc_Ent) = N_Entry_Body then
8718             Acc_Ent := Entry_Body_Formal_Part (Acc_Ent);
8719          end if;
8720
8721          Formals := Parameter_Specifications (Acc_Ent);
8722
8723          --  Create the actual parameters for the dispatching call. These are
8724          --  simply copies of the entry body or accept statement formals in the
8725          --  same order as they appear.
8726
8727          Actuals := No_List;
8728
8729          if Present (Formals) then
8730             Actuals := New_List;
8731             Formal  := First (Formals);
8732             while Present (Formal) loop
8733                Append_To (Actuals,
8734                  Make_Identifier (Loc, Chars (Defining_Identifier (Formal))));
8735                Next (Formal);
8736             end loop;
8737          end if;
8738
8739          --  Generate:
8740          --    Obj.Call_Ent (Actuals);
8741
8742          return
8743            Make_Procedure_Call_Statement (Loc,
8744              Name =>
8745                Make_Selected_Component (Loc,
8746                  Prefix        => Make_Identifier (Loc, Chars (Obj)),
8747                  Selector_Name => Make_Identifier (Loc, Chars (Call_Ent))),
8748
8749              Parameter_Associations => Actuals);
8750       end Build_Dispatching_Call_Equivalent;
8751
8752       -------------------------------
8753       -- Build_Dispatching_Requeue --
8754       -------------------------------
8755
8756       function Build_Dispatching_Requeue return Node_Id is
8757          Params : constant List_Id := New_List;
8758
8759       begin
8760          --  Process the "with abort" parameter
8761
8762          Prepend_To (Params,
8763            New_Reference_To (Boolean_Literals (Abort_Present (N)), Loc));
8764
8765          --  Process the entry wrapper's position in the primary dispatch
8766          --  table parameter. Generate:
8767
8768          --    Ada.Tags.Get_Offset_Index
8769          --      (Ada.Tags.Tag (Concval),
8770          --       <interface dispatch table position of Ename>)
8771
8772          if Tagged_Type_Expansion then
8773             Prepend_To (Params,
8774               Make_Function_Call (Loc,
8775                 Name => New_Reference_To (RTE (RE_Get_Offset_Index), Loc),
8776                 Parameter_Associations => New_List (
8777                   Unchecked_Convert_To (RTE (RE_Tag), Concval),
8778                   Make_Integer_Literal (Loc, DT_Position (Entity (Ename))))));
8779
8780          --  VM targets
8781
8782          else
8783             Prepend_To (Params,
8784               Make_Function_Call (Loc,
8785                 Name => New_Reference_To (RTE (RE_Get_Offset_Index), Loc),
8786
8787                 Parameter_Associations => New_List (
8788
8789                   --  Obj_Typ
8790
8791                   Make_Attribute_Reference (Loc,
8792                     Prefix         => Concval,
8793                     Attribute_Name => Name_Tag),
8794
8795                   --  Tag_Typ
8796
8797                   Make_Attribute_Reference (Loc,
8798                     Prefix         => New_Reference_To (Etype (Concval), Loc),
8799                     Attribute_Name => Name_Tag),
8800
8801                   --  Position
8802
8803                   Make_Integer_Literal (Loc, DT_Position (Entity (Ename))))));
8804          end if;
8805
8806          --  Specific actuals for protected to XXX requeue
8807
8808          if Is_Protected_Type (Old_Typ) then
8809             Prepend_To (Params,
8810               Make_Attribute_Reference (Loc,        --  _object'Address
8811                 Prefix =>
8812                   Concurrent_Ref (New_Occurrence_Of (Old_Typ, Loc)),
8813                 Attribute_Name => Name_Address));
8814
8815             Prepend_To (Params,                     --  True
8816               New_Reference_To (Standard_True, Loc));
8817
8818          --  Specific actuals for task to XXX requeue
8819
8820          else
8821             pragma Assert (Is_Task_Type (Old_Typ));
8822
8823             Prepend_To (Params,                     --  null
8824               New_Reference_To (RTE (RE_Null_Address), Loc));
8825
8826             Prepend_To (Params,                     --  False
8827               New_Reference_To (Standard_False, Loc));
8828          end if;
8829
8830          --  Add the object parameter
8831
8832          Prepend_To (Params, New_Copy_Tree (Concval));
8833
8834          --  Generate:
8835          --    _Disp_Requeue (<Params>);
8836
8837          return
8838            Make_Procedure_Call_Statement (Loc,
8839              Name => Make_Identifier (Loc, Name_uDisp_Requeue),
8840              Parameter_Associations => Params);
8841       end Build_Dispatching_Requeue;
8842
8843       --------------------------------------
8844       -- Build_Dispatching_Requeue_To_Any --
8845       --------------------------------------
8846
8847       function Build_Dispatching_Requeue_To_Any return Node_Id is
8848          Call_Ent : constant Entity_Id := Entity (Ename);
8849          Obj      : constant Node_Id   := Original_Node (Concval);
8850          Skip     : constant Node_Id   := Build_Skip_Statement (N);
8851          C        : Entity_Id;
8852          Decls    : List_Id;
8853          S        : Entity_Id;
8854          Stmts    : List_Id;
8855
8856       begin
8857          Decls := New_List;
8858          Stmts := New_List;
8859
8860          --  Dispatch table slot processing, generate:
8861          --    S : Integer;
8862
8863          S := Build_S (Loc, Decls);
8864
8865          --  Call kind processing, generate:
8866          --    C : Ada.Tags.Prim_Op_Kind;
8867
8868          C := Build_C (Loc, Decls);
8869
8870          --  Generate:
8871          --    S := Ada.Tags.Get_Offset_Index
8872          --           (Ada.Tags.Tag (Obj), DT_Position (Call_Ent));
8873
8874          Append_To (Stmts, Build_S_Assignment (Loc, S, Obj, Call_Ent));
8875
8876          --  Generate:
8877          --    _Disp_Get_Prim_Op_Kind (Obj, S, C);
8878
8879          Append_To (Stmts,
8880            Make_Procedure_Call_Statement (Loc,
8881              Name =>
8882                New_Reference_To (
8883                  Find_Prim_Op (Etype (Etype (Obj)),
8884                    Name_uDisp_Get_Prim_Op_Kind),
8885                  Loc),
8886              Parameter_Associations => New_List (
8887                New_Copy_Tree (Obj),
8888                New_Reference_To (S, Loc),
8889                New_Reference_To (C, Loc))));
8890
8891          Append_To (Stmts,
8892
8893             --  if C = POK_Protected_Entry
8894             --    or else C = POK_Task_Entry
8895             --  then
8896
8897            Make_If_Statement (Loc,
8898              Condition =>
8899                Make_Op_Or (Loc,
8900                  Left_Opnd =>
8901                    Make_Op_Eq (Loc,
8902                      Left_Opnd =>
8903                        New_Reference_To (C, Loc),
8904                      Right_Opnd =>
8905                        New_Reference_To (RTE (RE_POK_Protected_Entry), Loc)),
8906
8907                  Right_Opnd =>
8908                    Make_Op_Eq (Loc,
8909                      Left_Opnd =>
8910                        New_Reference_To (C, Loc),
8911                      Right_Opnd =>
8912                        New_Reference_To (RTE (RE_POK_Task_Entry), Loc))),
8913
8914                --  Dispatching requeue equivalent
8915
8916              Then_Statements => New_List (
8917                Build_Dispatching_Requeue,
8918                Skip),
8919
8920                --  elsif C = POK_Protected_Procedure then
8921
8922              Elsif_Parts => New_List (
8923                Make_Elsif_Part (Loc,
8924                  Condition =>
8925                    Make_Op_Eq (Loc,
8926                      Left_Opnd =>
8927                        New_Reference_To (C, Loc),
8928                      Right_Opnd =>
8929                        New_Reference_To (
8930                          RTE (RE_POK_Protected_Procedure), Loc)),
8931
8932                   --  Dispatching call equivalent
8933
8934                  Then_Statements => New_List (
8935                    Build_Dispatching_Call_Equivalent))),
8936
8937             --  else
8938             --     raise Program_Error;
8939             --  end if;
8940
8941              Else_Statements => New_List (
8942                Make_Raise_Program_Error (Loc,
8943                  Reason => PE_Explicit_Raise))));
8944
8945          --  Wrap everything into a block
8946
8947          return
8948            Make_Block_Statement (Loc,
8949              Declarations => Decls,
8950              Handled_Statement_Sequence =>
8951                Make_Handled_Sequence_Of_Statements (Loc,
8952                  Statements => Stmts));
8953       end Build_Dispatching_Requeue_To_Any;
8954
8955       --------------------------
8956       -- Build_Normal_Requeue --
8957       --------------------------
8958
8959       function Build_Normal_Requeue return Node_Id is
8960          Params  : constant List_Id := New_List;
8961          Param   : Node_Id;
8962          RT_Call : Node_Id;
8963
8964       begin
8965          --  Process the "with abort" parameter
8966
8967          Prepend_To (Params,
8968            New_Reference_To (Boolean_Literals (Abort_Present (N)), Loc));
8969
8970          --  Add the index expression to the parameters. It is common among all
8971          --  four cases.
8972
8973          Prepend_To (Params,
8974            Entry_Index_Expression (Loc, Entity (Ename), Index, Conc_Typ));
8975
8976          if Is_Protected_Type (Old_Typ) then
8977             declare
8978                Self_Param : Node_Id;
8979
8980             begin
8981                Self_Param :=
8982                  Make_Attribute_Reference (Loc,
8983                    Prefix =>
8984                      Concurrent_Ref (New_Occurrence_Of (Old_Typ, Loc)),
8985                    Attribute_Name =>
8986                      Name_Unchecked_Access);
8987
8988                --  Protected to protected requeue
8989
8990                if Is_Protected_Type (Conc_Typ) then
8991                   RT_Call :=
8992                     New_Reference_To (
8993                       RTE (RE_Requeue_Protected_Entry), Loc);
8994
8995                   Param :=
8996                     Make_Attribute_Reference (Loc,
8997                       Prefix =>
8998                         Concurrent_Ref (Concval),
8999                       Attribute_Name =>
9000                         Name_Unchecked_Access);
9001
9002                --  Protected to task requeue
9003
9004                else pragma Assert (Is_Task_Type (Conc_Typ));
9005                   RT_Call :=
9006                     New_Reference_To (
9007                       RTE (RE_Requeue_Protected_To_Task_Entry), Loc);
9008
9009                   Param := Concurrent_Ref (Concval);
9010                end if;
9011
9012                Prepend_To (Params, Param);
9013                Prepend_To (Params, Self_Param);
9014             end;
9015
9016          else pragma Assert (Is_Task_Type (Old_Typ));
9017
9018             --  Task to protected requeue
9019
9020             if Is_Protected_Type (Conc_Typ) then
9021                RT_Call :=
9022                  New_Reference_To (
9023                    RTE (RE_Requeue_Task_To_Protected_Entry), Loc);
9024
9025                Param :=
9026                  Make_Attribute_Reference (Loc,
9027                    Prefix =>
9028                      Concurrent_Ref (Concval),
9029                    Attribute_Name =>
9030                      Name_Unchecked_Access);
9031
9032             --  Task to task requeue
9033
9034             else pragma Assert (Is_Task_Type (Conc_Typ));
9035                RT_Call :=
9036                  New_Reference_To (RTE (RE_Requeue_Task_Entry), Loc);
9037
9038                Param := Concurrent_Ref (Concval);
9039             end if;
9040
9041             Prepend_To (Params, Param);
9042          end if;
9043
9044          return
9045             Make_Procedure_Call_Statement (Loc,
9046               Name => RT_Call,
9047               Parameter_Associations => Params);
9048       end Build_Normal_Requeue;
9049
9050       --------------------------
9051       -- Build_Skip_Statement --
9052       --------------------------
9053
9054       function Build_Skip_Statement (Search : Node_Id) return Node_Id is
9055          Skip_Stmt : Node_Id;
9056
9057       begin
9058          --  Build a return statement to skip the rest of the entire body
9059
9060          if Is_Protected_Type (Old_Typ) then
9061             Skip_Stmt := Make_Simple_Return_Statement (Loc);
9062
9063          --  If the requeue is within a task, find the end label of the
9064          --  enclosing accept statement and create a goto statement to it.
9065
9066          else
9067             declare
9068                Acc   : Node_Id;
9069                Label : Node_Id;
9070
9071             begin
9072                --  Climb the parent chain looking for the enclosing accept
9073                --  statement.
9074
9075                Acc := Parent (Search);
9076                while Present (Acc)
9077                  and then Nkind (Acc) /= N_Accept_Statement
9078                loop
9079                   Acc := Parent (Acc);
9080                end loop;
9081
9082                --  The last statement is the second label used for completing
9083                --  the rendezvous the usual way. The label we are looking for
9084                --  is right before it.
9085
9086                Label :=
9087                  Prev (Last (Statements (Handled_Statement_Sequence (Acc))));
9088
9089                pragma Assert (Nkind (Label) = N_Label);
9090
9091                --  Generate a goto statement to skip the rest of the accept
9092
9093                Skip_Stmt :=
9094                  Make_Goto_Statement (Loc,
9095                    Name =>
9096                      New_Occurrence_Of (Entity (Identifier (Label)), Loc));
9097             end;
9098          end if;
9099
9100          Set_Analyzed (Skip_Stmt);
9101
9102          return Skip_Stmt;
9103       end Build_Skip_Statement;
9104
9105    --  Start of processing for Expand_N_Requeue_Statement
9106
9107    begin
9108       --  Extract the components of the entry call
9109
9110       Extract_Entry (N, Concval, Ename, Index);
9111       Conc_Typ := Etype (Concval);
9112
9113       --  Examine the scope stack in order to find nearest enclosing protected
9114       --  or task type. This will constitute our invocation source.
9115
9116       Old_Typ := Current_Scope;
9117       while Present (Old_Typ)
9118         and then not Is_Protected_Type (Old_Typ)
9119         and then not Is_Task_Type (Old_Typ)
9120       loop
9121          Old_Typ := Scope (Old_Typ);
9122       end loop;
9123
9124       --  Ada 2012 (AI05-0030): We have a dispatching requeue of the form
9125       --  Concval.Ename where the type of Concval is class-wide concurrent
9126       --  interface.
9127
9128       if Ada_Version >= Ada_2012
9129         and then Present (Concval)
9130         and then Is_Class_Wide_Type (Conc_Typ)
9131         and then Is_Concurrent_Interface (Conc_Typ)
9132       then
9133          declare
9134             Has_Impl  : Boolean := False;
9135             Impl_Kind : Name_Id := No_Name;
9136
9137          begin
9138             --  Check whether the Ename is flagged by pragma Implemented
9139
9140             if Has_Rep_Pragma (Entity (Ename), Name_Implemented) then
9141                Has_Impl  := True;
9142                Impl_Kind := Implementation_Kind (Entity (Ename));
9143             end if;
9144
9145             --  The procedure_or_entry_NAME is guaranteed to be overridden by
9146             --  an entry. Create a call to predefined primitive _Disp_Requeue.
9147
9148             if Has_Impl
9149               and then Impl_Kind = Name_By_Entry
9150             then
9151                Rewrite (N, Build_Dispatching_Requeue);
9152                Analyze (N);
9153                Insert_After (N, Build_Skip_Statement (N));
9154
9155             --  The procedure_or_entry_NAME is guaranteed to be overridden by
9156             --  a protected procedure. In this case the requeue is transformed
9157             --  into a dispatching call.
9158
9159             elsif Has_Impl
9160               and then Impl_Kind = Name_By_Protected_Procedure
9161             then
9162                Rewrite (N, Build_Dispatching_Call_Equivalent);
9163                Analyze (N);
9164
9165             --  The procedure_or_entry_NAME's implementation kind is either
9166             --  By_Any or pragma Implemented was not applied at all. In this
9167             --  case a runtime test determines whether Ename denotes an entry
9168             --  or a protected procedure and performs the appropriate call.
9169
9170             else
9171                Rewrite (N, Build_Dispatching_Requeue_To_Any);
9172                Analyze (N);
9173             end if;
9174          end;
9175
9176       --  Processing for regular (non-dispatching) requeues
9177
9178       else
9179          Rewrite (N, Build_Normal_Requeue);
9180          Analyze (N);
9181          Insert_After (N, Build_Skip_Statement (N));
9182       end if;
9183    end Expand_N_Requeue_Statement;
9184
9185    -------------------------------
9186    -- Expand_N_Selective_Accept --
9187    -------------------------------
9188
9189    procedure Expand_N_Selective_Accept (N : Node_Id) is
9190       Loc            : constant Source_Ptr := Sloc (N);
9191       Alts           : constant List_Id    := Select_Alternatives (N);
9192
9193       --  Note: in the below declarations a lot of new lists are allocated
9194       --  unconditionally which may well not end up being used. That's
9195       --  not a good idea since it wastes space gratuitously ???
9196
9197       Accept_Case    : List_Id;
9198       Accept_List    : constant List_Id := New_List;
9199
9200       Alt            : Node_Id;
9201       Alt_List       : constant List_Id := New_List;
9202       Alt_Stats      : List_Id;
9203       Ann            : Entity_Id := Empty;
9204
9205       Block          : Node_Id;
9206       Check_Guard    : Boolean := True;
9207
9208       Decls          : constant List_Id := New_List;
9209       Stats          : constant List_Id := New_List;
9210       Body_List      : constant List_Id := New_List;
9211       Trailing_List  : constant List_Id := New_List;
9212
9213       Choices        : List_Id;
9214       Else_Present   : Boolean := False;
9215       Terminate_Alt  : Node_Id := Empty;
9216       Select_Mode    : Node_Id;
9217
9218       Delay_Case     : List_Id;
9219       Delay_Count    : Integer := 0;
9220       Delay_Val      : Entity_Id;
9221       Delay_Index    : Entity_Id;
9222       Delay_Min      : Entity_Id;
9223       Delay_Num      : Int := 1;
9224       Delay_Alt_List : List_Id := New_List;
9225       Delay_List     : constant List_Id := New_List;
9226       D              : Entity_Id;
9227       M              : Entity_Id;
9228
9229       First_Delay    : Boolean := True;
9230       Guard_Open     : Entity_Id;
9231
9232       End_Lab        : Node_Id;
9233       Index          : Int := 1;
9234       Lab            : Node_Id;
9235       Num_Alts       : Int;
9236       Num_Accept     : Nat := 0;
9237       Proc           : Node_Id;
9238       Q              : Node_Id;
9239       Time_Type      : Entity_Id;
9240       X              : Node_Id;
9241       Select_Call    : Node_Id;
9242
9243       Qnam : constant Entity_Id :=
9244                Make_Defining_Identifier (Loc, New_External_Name ('S', 0));
9245
9246       Xnam : constant Entity_Id :=
9247                Make_Defining_Identifier (Loc, New_External_Name ('J', 1));
9248
9249       -----------------------
9250       -- Local subprograms --
9251       -----------------------
9252
9253       function Accept_Or_Raise return List_Id;
9254       --  For the rare case where delay alternatives all have guards, and
9255       --  all of them are closed, it is still possible that there were open
9256       --  accept alternatives with no callers. We must reexamine the
9257       --  Accept_List, and execute a selective wait with no else if some
9258       --  accept is open. If none, we raise program_error.
9259
9260       procedure Add_Accept (Alt : Node_Id);
9261       --  Process a single accept statement in a select alternative. Build
9262       --  procedure for body of accept, and add entry to dispatch table with
9263       --  expression for guard, in preparation for call to run time select.
9264
9265       function Make_And_Declare_Label (Num : Int) return Node_Id;
9266       --  Manufacture a label using Num as a serial number and declare it.
9267       --  The declaration is appended to Decls. The label marks the trailing
9268       --  statements of an accept or delay alternative.
9269
9270       function Make_Select_Call (Select_Mode : Entity_Id) return Node_Id;
9271       --  Build call to Selective_Wait runtime routine
9272
9273       procedure Process_Delay_Alternative (Alt : Node_Id; Index : Int);
9274       --  Add code to compare value of delay with previous values, and
9275       --  generate case entry for trailing statements.
9276
9277       procedure Process_Accept_Alternative
9278         (Alt   : Node_Id;
9279          Index : Int;
9280          Proc  : Node_Id);
9281       --  Add code to call corresponding procedure, and branch to
9282       --  trailing statements, if any.
9283
9284       ---------------------
9285       -- Accept_Or_Raise --
9286       ---------------------
9287
9288       function Accept_Or_Raise return List_Id is
9289          Cond  : Node_Id;
9290          Stats : List_Id;
9291          J     : constant Entity_Id := Make_Temporary (Loc, 'J');
9292
9293       begin
9294          --  We generate the following:
9295
9296          --    for J in q'range loop
9297          --       if q(J).S /=null_task_entry then
9298          --          selective_wait (simple_mode,...);
9299          --          done := True;
9300          --          exit;
9301          --       end if;
9302          --    end loop;
9303          --
9304          --    if no rendez_vous then
9305          --       raise program_error;
9306          --    end if;
9307
9308          --    Note that the code needs to know that the selector name
9309          --    in an Accept_Alternative is named S.
9310
9311          Cond := Make_Op_Ne (Loc,
9312            Left_Opnd =>
9313              Make_Selected_Component (Loc,
9314                Prefix        =>
9315                  Make_Indexed_Component (Loc,
9316                    Prefix => New_Reference_To (Qnam, Loc),
9317                      Expressions => New_List (New_Reference_To (J, Loc))),
9318                Selector_Name => Make_Identifier (Loc, Name_S)),
9319            Right_Opnd =>
9320              New_Reference_To (RTE (RE_Null_Task_Entry), Loc));
9321
9322          Stats := New_List (
9323            Make_Implicit_Loop_Statement (N,
9324              Identifier => Empty,
9325              Iteration_Scheme =>
9326                Make_Iteration_Scheme (Loc,
9327                  Loop_Parameter_Specification =>
9328                    Make_Loop_Parameter_Specification (Loc,
9329                      Defining_Identifier => J,
9330                      Discrete_Subtype_Definition =>
9331                        Make_Attribute_Reference (Loc,
9332                          Prefix => New_Reference_To (Qnam, Loc),
9333                          Attribute_Name => Name_Range,
9334                          Expressions => New_List (
9335                            Make_Integer_Literal (Loc, 1))))),
9336
9337              Statements => New_List (
9338                Make_Implicit_If_Statement (N,
9339                  Condition =>  Cond,
9340                  Then_Statements => New_List (
9341                    Make_Select_Call (
9342                     New_Reference_To (RTE (RE_Simple_Mode), Loc)),
9343                    Make_Exit_Statement (Loc))))));
9344
9345          Append_To (Stats,
9346            Make_Raise_Program_Error (Loc,
9347              Condition => Make_Op_Eq (Loc,
9348                Left_Opnd  => New_Reference_To (Xnam, Loc),
9349                Right_Opnd =>
9350                  New_Reference_To (RTE (RE_No_Rendezvous), Loc)),
9351              Reason => PE_All_Guards_Closed));
9352
9353          return Stats;
9354       end Accept_Or_Raise;
9355
9356       ----------------
9357       -- Add_Accept --
9358       ----------------
9359
9360       procedure Add_Accept (Alt : Node_Id) is
9361          Acc_Stm   : constant Node_Id    := Accept_Statement (Alt);
9362          Ename     : constant Node_Id    := Entry_Direct_Name (Acc_Stm);
9363          Eloc      : constant Source_Ptr := Sloc (Ename);
9364          Eent      : constant Entity_Id  := Entity (Ename);
9365          Index     : constant Node_Id    := Entry_Index (Acc_Stm);
9366          Null_Body : Node_Id;
9367          Proc_Body : Node_Id;
9368          PB_Ent    : Entity_Id;
9369          Expr      : Node_Id;
9370          Call      : Node_Id;
9371
9372       begin
9373          if No (Ann) then
9374             Ann := Node (Last_Elmt (Accept_Address (Eent)));
9375          end if;
9376
9377          if Present (Condition (Alt)) then
9378             Expr :=
9379               Make_Conditional_Expression (Eloc, New_List (
9380                 Condition (Alt),
9381                 Entry_Index_Expression (Eloc, Eent, Index, Scope (Eent)),
9382                 New_Reference_To (RTE (RE_Null_Task_Entry), Eloc)));
9383          else
9384             Expr :=
9385               Entry_Index_Expression
9386                 (Eloc, Eent, Index, Scope (Eent));
9387          end if;
9388
9389          if Present (Handled_Statement_Sequence (Accept_Statement (Alt))) then
9390             Null_Body := New_Reference_To (Standard_False, Eloc);
9391
9392             if Abort_Allowed then
9393                Call := Make_Procedure_Call_Statement (Eloc,
9394                  Name => New_Reference_To (RTE (RE_Abort_Undefer), Eloc));
9395                Insert_Before (First (Statements (Handled_Statement_Sequence (
9396                  Accept_Statement (Alt)))), Call);
9397                Analyze (Call);
9398             end if;
9399
9400             PB_Ent :=
9401               Make_Defining_Identifier (Eloc,
9402                 New_External_Name (Chars (Ename), 'A', Num_Accept));
9403
9404             if Comes_From_Source (Alt) then
9405                Set_Debug_Info_Needed (PB_Ent);
9406             end if;
9407
9408             Proc_Body :=
9409               Make_Subprogram_Body (Eloc,
9410                 Specification =>
9411                   Make_Procedure_Specification (Eloc,
9412                     Defining_Unit_Name => PB_Ent),
9413                Declarations => Declarations (Acc_Stm),
9414                Handled_Statement_Sequence =>
9415                  Build_Accept_Body (Accept_Statement (Alt)));
9416
9417             --  During the analysis of the body of the accept statement, any
9418             --  zero cost exception handler records were collected in the
9419             --  Accept_Handler_Records field of the N_Accept_Alternative node.
9420             --  This is where we move them to where they belong, namely the
9421             --  newly created procedure.
9422
9423             Set_Handler_Records (PB_Ent, Accept_Handler_Records (Alt));
9424             Append (Proc_Body, Body_List);
9425
9426          else
9427             Null_Body := New_Reference_To (Standard_True,  Eloc);
9428
9429             --  if accept statement has declarations, insert above, given that
9430             --  we are not creating a body for the accept.
9431
9432             if Present (Declarations (Acc_Stm)) then
9433                Insert_Actions (N, Declarations (Acc_Stm));
9434             end if;
9435          end if;
9436
9437          Append_To (Accept_List,
9438            Make_Aggregate (Eloc, Expressions => New_List (Null_Body, Expr)));
9439
9440          Num_Accept := Num_Accept + 1;
9441       end Add_Accept;
9442
9443       ----------------------------
9444       -- Make_And_Declare_Label --
9445       ----------------------------
9446
9447       function Make_And_Declare_Label (Num : Int) return Node_Id is
9448          Lab_Id : Node_Id;
9449
9450       begin
9451          Lab_Id := Make_Identifier (Loc, New_External_Name ('L', Num));
9452          Lab :=
9453            Make_Label (Loc, Lab_Id);
9454
9455          Append_To (Decls,
9456            Make_Implicit_Label_Declaration (Loc,
9457              Defining_Identifier  =>
9458                Make_Defining_Identifier (Loc, Chars (Lab_Id)),
9459              Label_Construct => Lab));
9460
9461          return Lab;
9462       end Make_And_Declare_Label;
9463
9464       ----------------------
9465       -- Make_Select_Call --
9466       ----------------------
9467
9468       function Make_Select_Call (Select_Mode : Entity_Id) return Node_Id is
9469          Params : constant List_Id := New_List;
9470
9471       begin
9472          Append (
9473            Make_Attribute_Reference (Loc,
9474              Prefix => New_Reference_To (Qnam, Loc),
9475              Attribute_Name => Name_Unchecked_Access),
9476            Params);
9477          Append (Select_Mode, Params);
9478          Append (New_Reference_To (Ann, Loc), Params);
9479          Append (New_Reference_To (Xnam, Loc), Params);
9480
9481          return
9482            Make_Procedure_Call_Statement (Loc,
9483              Name => New_Reference_To (RTE (RE_Selective_Wait), Loc),
9484              Parameter_Associations => Params);
9485       end Make_Select_Call;
9486
9487       --------------------------------
9488       -- Process_Accept_Alternative --
9489       --------------------------------
9490
9491       procedure Process_Accept_Alternative
9492         (Alt   : Node_Id;
9493          Index : Int;
9494          Proc  : Node_Id)
9495       is
9496          Choices   : List_Id := No_List;
9497          Alt_Stats : List_Id;
9498
9499       begin
9500          Adjust_Condition (Condition (Alt));
9501          Alt_Stats := No_List;
9502
9503          if Present (Handled_Statement_Sequence (Accept_Statement (Alt))) then
9504             Choices := New_List (
9505               Make_Integer_Literal (Loc, Index));
9506
9507             Alt_Stats := New_List (
9508               Make_Procedure_Call_Statement (Sloc (Proc),
9509                 Name => New_Reference_To (
9510                   Defining_Unit_Name (Specification (Proc)), Sloc (Proc))));
9511          end if;
9512
9513          if Statements (Alt) /= Empty_List then
9514
9515             if No (Alt_Stats) then
9516
9517                --  Accept with no body, followed by trailing statements
9518
9519                Choices := New_List (
9520                  Make_Integer_Literal (Loc, Index));
9521
9522                Alt_Stats := New_List;
9523             end if;
9524
9525             --  After the call, if any, branch to trailing statements. We
9526             --  create a label for each, as well as the corresponding label
9527             --  declaration.
9528
9529             Lab := Make_And_Declare_Label (Index);
9530             Append_To (Alt_Stats,
9531               Make_Goto_Statement (Loc,
9532                 Name => New_Copy (Identifier (Lab))));
9533
9534             Append (Lab, Trailing_List);
9535             Append_List (Statements (Alt), Trailing_List);
9536             Append_To (Trailing_List,
9537               Make_Goto_Statement (Loc,
9538                 Name => New_Copy (Identifier (End_Lab))));
9539          end if;
9540
9541          if Present (Alt_Stats) then
9542
9543             --  Procedure call. and/or trailing statements
9544
9545             Append_To (Alt_List,
9546               Make_Case_Statement_Alternative (Loc,
9547                 Discrete_Choices => Choices,
9548                 Statements => Alt_Stats));
9549          end if;
9550       end Process_Accept_Alternative;
9551
9552       -------------------------------
9553       -- Process_Delay_Alternative --
9554       -------------------------------
9555
9556       procedure Process_Delay_Alternative (Alt : Node_Id; Index : Int) is
9557          Choices   : List_Id;
9558          Cond      : Node_Id;
9559          Delay_Alt : List_Id;
9560
9561       begin
9562          --  Deal with C/Fortran boolean as delay condition
9563
9564          Adjust_Condition (Condition (Alt));
9565
9566          --  Determine the smallest specified delay
9567
9568          --  for each delay alternative generate:
9569
9570          --    if guard-expression then
9571          --       Delay_Val  := delay-expression;
9572          --       Guard_Open := True;
9573          --       if Delay_Val < Delay_Min then
9574          --          Delay_Min   := Delay_Val;
9575          --          Delay_Index := Index;
9576          --       end if;
9577          --    end if;
9578
9579          --  The enclosing if-statement is omitted if there is no guard
9580
9581          if Delay_Count = 1
9582            or else First_Delay
9583          then
9584             First_Delay := False;
9585
9586             Delay_Alt := New_List (
9587               Make_Assignment_Statement (Loc,
9588                 Name => New_Reference_To (Delay_Min, Loc),
9589                 Expression => Expression (Delay_Statement (Alt))));
9590
9591             if Delay_Count > 1 then
9592                Append_To (Delay_Alt,
9593                  Make_Assignment_Statement (Loc,
9594                    Name       => New_Reference_To (Delay_Index, Loc),
9595                    Expression => Make_Integer_Literal (Loc, Index)));
9596             end if;
9597
9598          else
9599             Delay_Alt := New_List (
9600               Make_Assignment_Statement (Loc,
9601                 Name => New_Reference_To (Delay_Val, Loc),
9602                 Expression => Expression (Delay_Statement (Alt))));
9603
9604             if Time_Type = Standard_Duration then
9605                Cond :=
9606                   Make_Op_Lt (Loc,
9607                     Left_Opnd  => New_Reference_To (Delay_Val, Loc),
9608                     Right_Opnd => New_Reference_To (Delay_Min, Loc));
9609
9610             else
9611                --  The scope of the time type must define a comparison
9612                --  operator. The scope itself may not be visible, so we
9613                --  construct a node with entity information to insure that
9614                --  semantic analysis can find the proper operator.
9615
9616                Cond :=
9617                  Make_Function_Call (Loc,
9618                    Name => Make_Selected_Component (Loc,
9619                      Prefix => New_Reference_To (Scope (Time_Type), Loc),
9620                      Selector_Name =>
9621                        Make_Operator_Symbol (Loc,
9622                          Chars => Name_Op_Lt,
9623                          Strval => No_String)),
9624                     Parameter_Associations =>
9625                       New_List (
9626                         New_Reference_To (Delay_Val, Loc),
9627                         New_Reference_To (Delay_Min, Loc)));
9628
9629                Set_Entity (Prefix (Name (Cond)), Scope (Time_Type));
9630             end if;
9631
9632             Append_To (Delay_Alt,
9633               Make_Implicit_If_Statement (N,
9634                 Condition => Cond,
9635                 Then_Statements => New_List (
9636                   Make_Assignment_Statement (Loc,
9637                     Name       => New_Reference_To (Delay_Min, Loc),
9638                     Expression => New_Reference_To (Delay_Val, Loc)),
9639
9640                   Make_Assignment_Statement (Loc,
9641                     Name       => New_Reference_To (Delay_Index, Loc),
9642                     Expression => Make_Integer_Literal (Loc, Index)))));
9643          end if;
9644
9645          if Check_Guard then
9646             Append_To (Delay_Alt,
9647               Make_Assignment_Statement (Loc,
9648                 Name => New_Reference_To (Guard_Open, Loc),
9649                 Expression => New_Reference_To (Standard_True, Loc)));
9650          end if;
9651
9652          if Present (Condition (Alt)) then
9653             Delay_Alt := New_List (
9654               Make_Implicit_If_Statement (N,
9655                 Condition => Condition (Alt),
9656                 Then_Statements => Delay_Alt));
9657          end if;
9658
9659          Append_List (Delay_Alt, Delay_List);
9660
9661          --  If the delay alternative has a statement part, add choice to the
9662          --  case statements for delays.
9663
9664          if Present (Statements (Alt)) then
9665
9666             if Delay_Count = 1 then
9667                Append_List (Statements (Alt), Delay_Alt_List);
9668
9669             else
9670                Choices := New_List (
9671                  Make_Integer_Literal (Loc, Index));
9672
9673                Append_To (Delay_Alt_List,
9674                  Make_Case_Statement_Alternative (Loc,
9675                    Discrete_Choices => Choices,
9676                    Statements => Statements (Alt)));
9677             end if;
9678
9679          elsif Delay_Count = 1 then
9680
9681             --  If the single delay has no trailing statements, add a branch
9682             --  to the exit label to the selective wait.
9683
9684             Delay_Alt_List := New_List (
9685               Make_Goto_Statement (Loc,
9686                 Name => New_Copy (Identifier (End_Lab))));
9687
9688          end if;
9689       end Process_Delay_Alternative;
9690
9691    --  Start of processing for Expand_N_Selective_Accept
9692
9693    begin
9694       --  First insert some declarations before the select. The first is:
9695
9696       --    Ann : Address
9697
9698       --  This variable holds the parameters passed to the accept body. This
9699       --  declaration has already been inserted by the time we get here by
9700       --  a call to Expand_Accept_Declarations made from the semantics when
9701       --  processing the first accept statement contained in the select. We
9702       --  can find this entity as Accept_Address (E), where E is any of the
9703       --  entries references by contained accept statements.
9704
9705       --  The first step is to scan the list of Selective_Accept_Statements
9706       --  to find this entity, and also count the number of accepts, and
9707       --  determine if terminated, delay or else is present:
9708
9709       Num_Alts := 0;
9710
9711       Alt := First (Alts);
9712       while Present (Alt) loop
9713
9714          if Nkind (Alt) = N_Accept_Alternative then
9715             Add_Accept (Alt);
9716
9717          elsif Nkind (Alt) = N_Delay_Alternative then
9718             Delay_Count := Delay_Count + 1;
9719
9720             --  If the delays are relative delays, the delay expressions have
9721             --  type Standard_Duration. Otherwise they must have some time type
9722             --  recognized by GNAT.
9723
9724             if Nkind (Delay_Statement (Alt)) = N_Delay_Relative_Statement then
9725                Time_Type := Standard_Duration;
9726             else
9727                Time_Type := Etype (Expression (Delay_Statement (Alt)));
9728
9729                if Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time)
9730                  or else Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time)
9731                then
9732                   null;
9733                else
9734                   Error_Msg_NE (
9735                     "& is not a time type (RM 9.6(6))",
9736                        Expression (Delay_Statement (Alt)), Time_Type);
9737                   Time_Type := Standard_Duration;
9738                   Set_Etype (Expression (Delay_Statement (Alt)), Any_Type);
9739                end if;
9740             end if;
9741
9742             if No (Condition (Alt)) then
9743
9744                --  This guard will always be open
9745
9746                Check_Guard := False;
9747             end if;
9748
9749          elsif Nkind (Alt) = N_Terminate_Alternative then
9750             Adjust_Condition (Condition (Alt));
9751             Terminate_Alt := Alt;
9752          end if;
9753
9754          Num_Alts := Num_Alts + 1;
9755          Next (Alt);
9756       end loop;
9757
9758       Else_Present := Present (Else_Statements (N));
9759
9760       --  At the same time (see procedure Add_Accept) we build the accept list:
9761
9762       --    Qnn : Accept_List (1 .. num-select) := (
9763       --          (null-body, entry-index),
9764       --          (null-body, entry-index),
9765       --          ..
9766       --          (null_body, entry-index));
9767
9768       --  In the above declaration, null-body is True if the corresponding
9769       --  accept has no body, and false otherwise. The entry is either the
9770       --  entry index expression if there is no guard, or if a guard is
9771       --  present, then a conditional expression of the form:
9772
9773       --    (if guard then entry-index else Null_Task_Entry)
9774
9775       --  If a guard is statically known to be false, the entry can simply
9776       --  be omitted from the accept list.
9777
9778       Q :=
9779         Make_Object_Declaration (Loc,
9780           Defining_Identifier => Qnam,
9781           Object_Definition =>
9782             New_Reference_To (RTE (RE_Accept_List), Loc),
9783           Aliased_Present => True,
9784
9785           Expression =>
9786              Make_Qualified_Expression (Loc,
9787                Subtype_Mark =>
9788                  New_Reference_To (RTE (RE_Accept_List), Loc),
9789                Expression =>
9790                  Make_Aggregate (Loc, Expressions => Accept_List)));
9791
9792       Append (Q, Decls);
9793
9794       --  Then we declare the variable that holds the index for the accept
9795       --  that will be selected for service:
9796
9797       --    Xnn : Select_Index;
9798
9799       X :=
9800         Make_Object_Declaration (Loc,
9801           Defining_Identifier => Xnam,
9802           Object_Definition =>
9803             New_Reference_To (RTE (RE_Select_Index), Loc),
9804           Expression =>
9805             New_Reference_To (RTE (RE_No_Rendezvous), Loc));
9806
9807       Append (X, Decls);
9808
9809       --  After this follow procedure declarations for each accept body
9810
9811       --    procedure Pnn is
9812       --    begin
9813       --       ...
9814       --    end;
9815
9816       --  where the ... are statements from the corresponding procedure body.
9817       --  No parameters are involved, since the parameters are passed via Ann
9818       --  and the parameter references have already been expanded to be direct
9819       --  references to Ann (see Exp_Ch2.Expand_Entry_Parameter). Furthermore,
9820       --  any embedded tasking statements (which would normally be illegal in
9821       --  procedures), have been converted to calls to the tasking runtime so
9822       --  there is no problem in putting them into procedures.
9823
9824       --  The original accept statement has been expanded into a block in
9825       --  the same fashion as for simple accepts (see Build_Accept_Body).
9826
9827       --  Note: we don't really need to build these procedures for the case
9828       --  where no delay statement is present, but it is just as easy to
9829       --  build them unconditionally, and not significantly inefficient,
9830       --  since if they are short they will be inlined anyway.
9831
9832       --  The procedure declarations have been assembled in Body_List
9833
9834       --  If delays are present, we must compute the required delay.
9835       --  We first generate the declarations:
9836
9837       --    Delay_Index : Boolean := 0;
9838       --    Delay_Min   : Some_Time_Type.Time;
9839       --    Delay_Val   : Some_Time_Type.Time;
9840
9841       --  Delay_Index will be set to the index of the minimum delay, i.e. the
9842       --  active delay that is actually chosen as the basis for the possible
9843       --  delay if an immediate rendez-vous is not possible.
9844
9845       --  In the most common case there is a single delay statement, and this
9846       --  is handled specially.
9847
9848       if Delay_Count > 0 then
9849
9850          --  Generate the required declarations
9851
9852          Delay_Val :=
9853            Make_Defining_Identifier (Loc, New_External_Name ('D', 1));
9854          Delay_Index :=
9855            Make_Defining_Identifier (Loc, New_External_Name ('D', 2));
9856          Delay_Min :=
9857            Make_Defining_Identifier (Loc, New_External_Name ('D', 3));
9858
9859          Append_To (Decls,
9860            Make_Object_Declaration (Loc,
9861              Defining_Identifier => Delay_Val,
9862              Object_Definition   => New_Reference_To (Time_Type, Loc)));
9863
9864          Append_To (Decls,
9865            Make_Object_Declaration (Loc,
9866              Defining_Identifier => Delay_Index,
9867              Object_Definition   => New_Reference_To (Standard_Integer, Loc),
9868              Expression          => Make_Integer_Literal (Loc, 0)));
9869
9870          Append_To (Decls,
9871            Make_Object_Declaration (Loc,
9872              Defining_Identifier => Delay_Min,
9873              Object_Definition   => New_Reference_To (Time_Type, Loc),
9874              Expression          =>
9875                Unchecked_Convert_To (Time_Type,
9876                  Make_Attribute_Reference (Loc,
9877                    Prefix =>
9878                      New_Occurrence_Of (Underlying_Type (Time_Type), Loc),
9879                    Attribute_Name => Name_Last))));
9880
9881          --  Create Duration and Delay_Mode objects used for passing a delay
9882          --  value to RTS
9883
9884          D := Make_Temporary (Loc, 'D');
9885          M := Make_Temporary (Loc, 'M');
9886
9887          declare
9888             Discr : Entity_Id;
9889
9890          begin
9891             --  Note that these values are defined in s-osprim.ads and must
9892             --  be kept in sync:
9893             --
9894             --     Relative          : constant := 0;
9895             --     Absolute_Calendar : constant := 1;
9896             --     Absolute_RT       : constant := 2;
9897
9898             if Time_Type = Standard_Duration then
9899                Discr := Make_Integer_Literal (Loc, 0);
9900
9901             elsif Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time) then
9902                Discr := Make_Integer_Literal (Loc, 1);
9903
9904             else
9905                pragma Assert
9906                  (Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time));
9907                Discr := Make_Integer_Literal (Loc, 2);
9908             end if;
9909
9910             Append_To (Decls,
9911               Make_Object_Declaration (Loc,
9912                 Defining_Identifier => D,
9913                 Object_Definition =>
9914                   New_Reference_To (Standard_Duration, Loc)));
9915
9916             Append_To (Decls,
9917               Make_Object_Declaration (Loc,
9918                 Defining_Identifier => M,
9919                 Object_Definition   =>
9920                   New_Reference_To (Standard_Integer, Loc),
9921                 Expression          => Discr));
9922          end;
9923
9924          if Check_Guard then
9925             Guard_Open :=
9926               Make_Defining_Identifier (Loc, New_External_Name ('G', 1));
9927
9928             Append_To (Decls,
9929               Make_Object_Declaration (Loc,
9930                  Defining_Identifier => Guard_Open,
9931                  Object_Definition => New_Reference_To (Standard_Boolean, Loc),
9932                  Expression        => New_Reference_To (Standard_False, Loc)));
9933          end if;
9934
9935       --  Delay_Count is zero, don't need M and D set (suppress warning)
9936
9937       else
9938          M := Empty;
9939          D := Empty;
9940       end if;
9941
9942       if Present (Terminate_Alt) then
9943
9944          --  If the terminate alternative guard is False, use
9945          --  Simple_Mode; otherwise use Terminate_Mode.
9946
9947          if Present (Condition (Terminate_Alt)) then
9948             Select_Mode := Make_Conditional_Expression (Loc,
9949               New_List (Condition (Terminate_Alt),
9950                         New_Reference_To (RTE (RE_Terminate_Mode), Loc),
9951                         New_Reference_To (RTE (RE_Simple_Mode), Loc)));
9952          else
9953             Select_Mode := New_Reference_To (RTE (RE_Terminate_Mode), Loc);
9954          end if;
9955
9956       elsif Else_Present or Delay_Count > 0 then
9957          Select_Mode := New_Reference_To (RTE (RE_Else_Mode), Loc);
9958
9959       else
9960          Select_Mode := New_Reference_To (RTE (RE_Simple_Mode), Loc);
9961       end if;
9962
9963       Select_Call := Make_Select_Call (Select_Mode);
9964       Append (Select_Call, Stats);
9965
9966       --  Now generate code to act on the result. There is an entry
9967       --  in this case for each accept statement with a non-null body,
9968       --  followed by a branch to the statements that follow the Accept.
9969       --  In the absence of delay alternatives, we generate:
9970
9971       --    case X is
9972       --      when No_Rendezvous =>  --  omitted if simple mode
9973       --         goto Lab0;
9974
9975       --      when 1 =>
9976       --         P1n;
9977       --         goto Lab1;
9978
9979       --      when 2 =>
9980       --         P2n;
9981       --         goto Lab2;
9982
9983       --      when others =>
9984       --         goto Exit;
9985       --    end case;
9986       --
9987       --    Lab0: Else_Statements;
9988       --    goto exit;
9989
9990       --    Lab1:  Trailing_Statements1;
9991       --    goto Exit;
9992       --
9993       --    Lab2:  Trailing_Statements2;
9994       --    goto Exit;
9995       --    ...
9996       --    Exit:
9997
9998       --  Generate label for common exit
9999
10000       End_Lab := Make_And_Declare_Label (Num_Alts + 1);
10001
10002       --  First entry is the default case, when no rendezvous is possible
10003
10004       Choices := New_List (New_Reference_To (RTE (RE_No_Rendezvous), Loc));
10005
10006       if Else_Present then
10007
10008          --  If no rendezvous is possible, the else part is executed
10009
10010          Lab := Make_And_Declare_Label (0);
10011          Alt_Stats := New_List (
10012            Make_Goto_Statement (Loc,
10013              Name => New_Copy (Identifier (Lab))));
10014
10015          Append (Lab, Trailing_List);
10016          Append_List (Else_Statements (N), Trailing_List);
10017          Append_To (Trailing_List,
10018            Make_Goto_Statement (Loc,
10019              Name => New_Copy (Identifier (End_Lab))));
10020       else
10021          Alt_Stats := New_List (
10022            Make_Goto_Statement (Loc,
10023              Name => New_Copy (Identifier (End_Lab))));
10024       end if;
10025
10026       Append_To (Alt_List,
10027         Make_Case_Statement_Alternative (Loc,
10028           Discrete_Choices => Choices,
10029           Statements => Alt_Stats));
10030
10031       --  We make use of the fact that Accept_Index is an integer type, and
10032       --  generate successive literals for entries for each accept. Only those
10033       --  for which there is a body or trailing statements get a case entry.
10034
10035       Alt := First (Select_Alternatives (N));
10036       Proc := First (Body_List);
10037       while Present (Alt) loop
10038
10039          if Nkind (Alt) = N_Accept_Alternative then
10040             Process_Accept_Alternative (Alt, Index, Proc);
10041             Index := Index + 1;
10042
10043             if Present
10044               (Handled_Statement_Sequence (Accept_Statement (Alt)))
10045             then
10046                Next (Proc);
10047             end if;
10048
10049          elsif Nkind (Alt) = N_Delay_Alternative then
10050             Process_Delay_Alternative (Alt, Delay_Num);
10051             Delay_Num := Delay_Num + 1;
10052          end if;
10053
10054          Next (Alt);
10055       end loop;
10056
10057       --  An others choice is always added to the main case, as well
10058       --  as the delay case (to satisfy the compiler).
10059
10060       Append_To (Alt_List,
10061         Make_Case_Statement_Alternative (Loc,
10062           Discrete_Choices =>
10063             New_List (Make_Others_Choice (Loc)),
10064           Statements       =>
10065             New_List (Make_Goto_Statement (Loc,
10066               Name => New_Copy (Identifier (End_Lab))))));
10067
10068       Accept_Case := New_List (
10069         Make_Case_Statement (Loc,
10070           Expression   => New_Reference_To (Xnam, Loc),
10071           Alternatives => Alt_List));
10072
10073       Append_List (Trailing_List, Accept_Case);
10074       Append (End_Lab, Accept_Case);
10075       Append_List (Body_List, Decls);
10076
10077       --  Construct case statement for trailing statements of delay
10078       --  alternatives, if there are several of them.
10079
10080       if Delay_Count > 1 then
10081          Append_To (Delay_Alt_List,
10082            Make_Case_Statement_Alternative (Loc,
10083              Discrete_Choices =>
10084                New_List (Make_Others_Choice (Loc)),
10085              Statements       =>
10086                New_List (Make_Null_Statement (Loc))));
10087
10088          Delay_Case := New_List (
10089            Make_Case_Statement (Loc,
10090              Expression   => New_Reference_To (Delay_Index, Loc),
10091              Alternatives => Delay_Alt_List));
10092       else
10093          Delay_Case := Delay_Alt_List;
10094       end if;
10095
10096       --  If there are no delay alternatives, we append the case statement
10097       --  to the statement list.
10098
10099       if Delay_Count = 0 then
10100          Append_List (Accept_Case, Stats);
10101
10102       --  Delay alternatives present
10103
10104       else
10105          --  If delay alternatives are present we generate:
10106
10107          --    find minimum delay.
10108          --    DX := minimum delay;
10109          --    M := <delay mode>;
10110          --    Timed_Selective_Wait (Q'Unchecked_Access, Delay_Mode, P,
10111          --      DX, MX, X);
10112          --
10113          --    if X = No_Rendezvous then
10114          --      case statement for delay statements.
10115          --    else
10116          --      case statement for accept alternatives.
10117          --    end if;
10118
10119          declare
10120             Cases : Node_Id;
10121             Stmt  : Node_Id;
10122             Parms : List_Id;
10123             Parm  : Node_Id;
10124             Conv  : Node_Id;
10125
10126          begin
10127             --  The type of the delay expression is known to be legal
10128
10129             if Time_Type = Standard_Duration then
10130                Conv := New_Reference_To (Delay_Min, Loc);
10131
10132             elsif Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time) then
10133                Conv := Make_Function_Call (Loc,
10134                  New_Reference_To (RTE (RO_CA_To_Duration), Loc),
10135                  New_List (New_Reference_To (Delay_Min, Loc)));
10136
10137             else
10138                pragma Assert
10139                  (Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time));
10140
10141                Conv := Make_Function_Call (Loc,
10142                  New_Reference_To (RTE (RO_RT_To_Duration), Loc),
10143                  New_List (New_Reference_To (Delay_Min, Loc)));
10144             end if;
10145
10146             Stmt := Make_Assignment_Statement (Loc,
10147               Name => New_Reference_To (D, Loc),
10148               Expression => Conv);
10149
10150             --  Change the value for Accept_Modes. (Else_Mode -> Delay_Mode)
10151
10152             Parms := Parameter_Associations (Select_Call);
10153             Parm := First (Parms);
10154
10155             while Present (Parm)
10156               and then Parm /= Select_Mode
10157             loop
10158                Next (Parm);
10159             end loop;
10160
10161             pragma Assert (Present (Parm));
10162             Rewrite (Parm, New_Reference_To (RTE (RE_Delay_Mode), Loc));
10163             Analyze (Parm);
10164
10165             --  Prepare two new parameters of Duration and Delay_Mode type
10166             --  which represent the value and the mode of the minimum delay.
10167
10168             Next (Parm);
10169             Insert_After (Parm, New_Reference_To (M, Loc));
10170             Insert_After (Parm, New_Reference_To (D, Loc));
10171
10172             --  Create a call to RTS
10173
10174             Rewrite (Select_Call,
10175               Make_Procedure_Call_Statement (Loc,
10176                 Name => New_Reference_To (RTE (RE_Timed_Selective_Wait), Loc),
10177                 Parameter_Associations => Parms));
10178
10179             --  This new call should follow the calculation of the minimum
10180             --  delay.
10181
10182             Insert_List_Before (Select_Call, Delay_List);
10183
10184             if Check_Guard then
10185                Stmt :=
10186                  Make_Implicit_If_Statement (N,
10187                    Condition => New_Reference_To (Guard_Open, Loc),
10188                    Then_Statements =>
10189                      New_List (New_Copy_Tree (Stmt),
10190                        New_Copy_Tree (Select_Call)),
10191                    Else_Statements => Accept_Or_Raise);
10192                Rewrite (Select_Call, Stmt);
10193             else
10194                Insert_Before (Select_Call, Stmt);
10195             end if;
10196
10197             Cases :=
10198               Make_Implicit_If_Statement (N,
10199                 Condition => Make_Op_Eq (Loc,
10200                   Left_Opnd  => New_Reference_To (Xnam, Loc),
10201                   Right_Opnd =>
10202                     New_Reference_To (RTE (RE_No_Rendezvous), Loc)),
10203
10204                 Then_Statements => Delay_Case,
10205                 Else_Statements => Accept_Case);
10206
10207             Append (Cases, Stats);
10208          end;
10209       end if;
10210
10211       --  Replace accept statement with appropriate block
10212
10213       Block :=
10214         Make_Block_Statement (Loc,
10215           Declarations => Decls,
10216           Handled_Statement_Sequence =>
10217             Make_Handled_Sequence_Of_Statements (Loc,
10218               Statements => Stats));
10219
10220       Rewrite (N, Block);
10221       Analyze (N);
10222
10223       --  Note: have to worry more about abort deferral in above code ???
10224
10225       --  Final step is to unstack the Accept_Address entries for all accept
10226       --  statements appearing in accept alternatives in the select statement
10227
10228       Alt := First (Alts);
10229       while Present (Alt) loop
10230          if Nkind (Alt) = N_Accept_Alternative then
10231             Remove_Last_Elmt (Accept_Address
10232               (Entity (Entry_Direct_Name (Accept_Statement (Alt)))));
10233          end if;
10234
10235          Next (Alt);
10236       end loop;
10237    end Expand_N_Selective_Accept;
10238
10239    --------------------------------------
10240    -- Expand_N_Single_Task_Declaration --
10241    --------------------------------------
10242
10243    --  Single task declarations should never be present after semantic
10244    --  analysis, since we expect them to be replaced by a declaration of an
10245    --  anonymous task type, followed by a declaration of the task object. We
10246    --  include this routine to make sure that is happening!
10247
10248    procedure Expand_N_Single_Task_Declaration (N : Node_Id) is
10249    begin
10250       raise Program_Error;
10251    end Expand_N_Single_Task_Declaration;
10252
10253    ------------------------
10254    -- Expand_N_Task_Body --
10255    ------------------------
10256
10257    --  Given a task body
10258
10259    --    task body tname is
10260    --       <declarations>
10261    --    begin
10262    --       <statements>
10263    --    end x;
10264
10265    --  This expansion routine converts it into a procedure and sets the
10266    --  elaboration flag for the procedure to true, to represent the fact
10267    --  that the task body is now elaborated:
10268
10269    --    procedure tnameB (_Task : access tnameV) is
10270    --       discriminal : dtype renames _Task.discriminant;
10271
10272    --       procedure _clean is
10273    --       begin
10274    --          Abort_Defer.all;
10275    --          Complete_Task;
10276    --          Abort_Undefer.all;
10277    --          return;
10278    --       end _clean;
10279
10280    --    begin
10281    --       Abort_Undefer.all;
10282    --       <declarations>
10283    --       System.Task_Stages.Complete_Activation;
10284    --       <statements>
10285    --    at end
10286    --       _clean;
10287    --    end tnameB;
10288
10289    --    tnameE := True;
10290
10291    --  In addition, if the task body is an activator, then a call to activate
10292    --  tasks is added at the start of the statements, before the call to
10293    --  Complete_Activation, and if in addition the task is a master then it
10294    --  must be established as a master. These calls are inserted and analyzed
10295    --  in Expand_Cleanup_Actions, when the Handled_Sequence_Of_Statements is
10296    --  expanded.
10297
10298    --  There is one discriminal declaration line generated for each
10299    --  discriminant that is present to provide an easy reference point for
10300    --  discriminant references inside the body (see Exp_Ch2.Expand_Name).
10301
10302    --  Note on relationship to GNARLI definition. In the GNARLI definition,
10303    --  task body procedures have a profile (Arg : System.Address). That is
10304    --  needed because GNARLI has to use the same access-to-subprogram type
10305    --  for all task types. We depend here on knowing that in GNAT, passing
10306    --  an address argument by value is identical to passing a record value
10307    --  by access (in either case a single pointer is passed), so even though
10308    --  this procedure has the wrong profile. In fact it's all OK, since the
10309    --  callings sequence is identical.
10310
10311    procedure Expand_N_Task_Body (N : Node_Id) is
10312       Loc   : constant Source_Ptr := Sloc (N);
10313       Ttyp  : constant Entity_Id  := Corresponding_Spec (N);
10314       Call  : Node_Id;
10315       New_N : Node_Id;
10316
10317       Insert_Nod : Node_Id;
10318       --  Used to determine the proper location of wrapper body insertions
10319
10320    begin
10321       --  Add renaming declarations for discriminals and a declaration for the
10322       --  entry family index (if applicable).
10323
10324       Install_Private_Data_Declarations
10325         (Loc, Task_Body_Procedure (Ttyp), Ttyp, N, Declarations (N));
10326
10327       --  Add a call to Abort_Undefer at the very beginning of the task
10328       --  body since this body is called with abort still deferred.
10329
10330       if Abort_Allowed then
10331          Call := Build_Runtime_Call (Loc, RE_Abort_Undefer);
10332          Insert_Before
10333            (First (Statements (Handled_Statement_Sequence (N))), Call);
10334          Analyze (Call);
10335       end if;
10336
10337       --  The statement part has already been protected with an at_end and
10338       --  cleanup actions. The call to Complete_Activation must be placed
10339       --  at the head of the sequence of statements of that block. The
10340       --  declarations have been merged in this sequence of statements but
10341       --  the first real statement is accessible from the First_Real_Statement
10342       --  field (which was set for exactly this purpose).
10343
10344       if Restricted_Profile then
10345          Call := Build_Runtime_Call (Loc, RE_Complete_Restricted_Activation);
10346       else
10347          Call := Build_Runtime_Call (Loc, RE_Complete_Activation);
10348       end if;
10349
10350       Insert_Before
10351         (First_Real_Statement (Handled_Statement_Sequence (N)), Call);
10352       Analyze (Call);
10353
10354       New_N :=
10355         Make_Subprogram_Body (Loc,
10356           Specification              => Build_Task_Proc_Specification (Ttyp),
10357           Declarations               => Declarations (N),
10358           Handled_Statement_Sequence => Handled_Statement_Sequence (N));
10359
10360       --  If the task contains generic instantiations, cleanup actions are
10361       --  delayed until after instantiation. Transfer the activation chain to
10362       --  the subprogram, to insure that the activation call is properly
10363       --  generated. It the task body contains inner tasks, indicate that the
10364       --  subprogram is a task master.
10365
10366       if Delay_Cleanups (Ttyp) then
10367          Set_Activation_Chain_Entity (New_N, Activation_Chain_Entity (N));
10368          Set_Is_Task_Master  (New_N, Is_Task_Master (N));
10369       end if;
10370
10371       Rewrite (N, New_N);
10372       Analyze (N);
10373
10374       --  Set elaboration flag immediately after task body. If the body is a
10375       --  subunit, the flag is set in the declarative part containing the stub.
10376
10377       if Nkind (Parent (N)) /= N_Subunit then
10378          Insert_After (N,
10379            Make_Assignment_Statement (Loc,
10380              Name =>
10381                Make_Identifier (Loc, New_External_Name (Chars (Ttyp), 'E')),
10382              Expression => New_Reference_To (Standard_True, Loc)));
10383       end if;
10384
10385       --  Ada 2005 (AI-345): Construct the primitive entry wrapper bodies after
10386       --  the task body. At this point all wrapper specs have been created,
10387       --  frozen and included in the dispatch table for the task type.
10388
10389       if Ada_Version >= Ada_2005 then
10390          if Nkind (Parent (N)) = N_Subunit then
10391             Insert_Nod := Corresponding_Stub (Parent (N));
10392          else
10393             Insert_Nod := N;
10394          end if;
10395
10396          Build_Wrapper_Bodies (Loc, Ttyp, Insert_Nod);
10397       end if;
10398    end Expand_N_Task_Body;
10399
10400    ------------------------------------
10401    -- Expand_N_Task_Type_Declaration --
10402    ------------------------------------
10403
10404    --  We have several things to do. First we must create a Boolean flag used
10405    --  to mark if the body is elaborated yet. This variable gets set to True
10406    --  when the body of the task is elaborated (we can't rely on the normal
10407    --  ABE mechanism for the task body, since we need to pass an access to
10408    --  this elaboration boolean to the runtime routines).
10409
10410    --    taskE : aliased Boolean := False;
10411
10412    --  Next a variable is declared to hold the task stack size (either the
10413    --  default : Unspecified_Size, or a value that is set by a pragma
10414    --  Storage_Size). If the value of the pragma Storage_Size is static, then
10415    --  the variable is initialized with this value:
10416
10417    --    taskZ : Size_Type := Unspecified_Size;
10418    --  or
10419    --    taskZ : Size_Type := Size_Type (size_expression);
10420
10421    --  Note: No variable is needed to hold the task relative deadline since
10422    --  its value would never be static because the parameter is of a private
10423    --  type (Ada.Real_Time.Time_Span).
10424
10425    --  Next we create a corresponding record type declaration used to represent
10426    --  values of this task. The general form of this type declaration is
10427
10428    --    type taskV (discriminants) is record
10429    --      _Task_Id     : Task_Id;
10430    --      entry_family : array (bounds) of Void;
10431    --      _Priority    : Integer         := priority_expression;
10432    --      _Size        : Size_Type       := Size_Type (size_expression);
10433    --      _Task_Info   : Task_Info_Type  := task_info_expression;
10434    --      _CPU         : Integer         := cpu_range_expression;
10435    --    end record;
10436
10437    --  The discriminants are present only if the corresponding task type has
10438    --  discriminants, and they exactly mirror the task type discriminants.
10439
10440    --  The Id field is always present. It contains the Task_Id value, as set by
10441    --  the call to Create_Task. Note that although the task is limited, the
10442    --  task value record type is not limited, so there is no problem in passing
10443    --  this field as an out parameter to Create_Task.
10444
10445    --  One entry_family component is present for each entry family in the task
10446    --  definition. The bounds correspond to the bounds of the entry family
10447    --  (which may depend on discriminants). The element type is void, since we
10448    --  only need the bounds information for determining the entry index. Note
10449    --  that the use of an anonymous array would normally be illegal in this
10450    --  context, but this is a parser check, and the semantics is quite prepared
10451    --  to handle such a case.
10452
10453    --  The _Size field is present only if a Storage_Size pragma appears in the
10454    --  task definition. The expression captures the argument that was present
10455    --  in the pragma, and is used to override the task stack size otherwise
10456    --  associated with the task type.
10457
10458    --  The _Priority field is present only if a Priority or Interrupt_Priority
10459    --  pragma appears in the task definition. The expression captures the
10460    --  argument that was present in the pragma, and is used to provide the Size
10461    --  parameter to the call to Create_Task.
10462
10463    --  The _Task_Info field is present only if a Task_Info pragma appears in
10464    --  the task definition. The expression captures the argument that was
10465    --  present in the pragma, and is used to provide the Task_Image parameter
10466    --  to the call to Create_Task.
10467
10468    --  The _CPU field is present only if a CPU pragma appears in the task
10469    --  definition. The expression captures the argument that was present in
10470    --  the pragma, and is used to provide the CPU parameter to the call to
10471    --  Create_Task.
10472
10473    --  The _Relative_Deadline field is present only if a Relative_Deadline
10474    --  pragma appears in the task definition. The expression captures the
10475    --  argument that was present in the pragma, and is used to provide the
10476    --  Relative_Deadline parameter to the call to Create_Task.
10477
10478    --  When a task is declared, an instance of the task value record is
10479    --  created. The elaboration of this declaration creates the correct bounds
10480    --  for the entry families, and also evaluates the size, priority, and
10481    --  task_Info expressions if needed. The initialization routine for the task
10482    --  type itself then calls Create_Task with appropriate parameters to
10483    --  initialize the value of the Task_Id field.
10484
10485    --  Note: the address of this record is passed as the "Discriminants"
10486    --  parameter for Create_Task. Since Create_Task merely passes this onto the
10487    --  body procedure, it does not matter that it does not quite match the
10488    --  GNARLI model of what is being passed (the record contains more than just
10489    --  the discriminants, but the discriminants can be found from the record
10490    --  value).
10491
10492    --  The Entity_Id for this created record type is placed in the
10493    --  Corresponding_Record_Type field of the associated task type entity.
10494
10495    --  Next we create a procedure specification for the task body procedure:
10496
10497    --    procedure taskB (_Task : access taskV);
10498
10499    --  Note that this must come after the record type declaration, since
10500    --  the spec refers to this type. It turns out that the initialization
10501    --  procedure for the value type references the task body spec, but that's
10502    --  fine, since it won't be generated till the freeze point for the type,
10503    --  which is certainly after the task body spec declaration.
10504
10505    --  Finally, we set the task index value field of the entry attribute in
10506    --  the case of a simple entry.
10507
10508    procedure Expand_N_Task_Type_Declaration (N : Node_Id) is
10509       Loc     : constant Source_Ptr := Sloc (N);
10510       Tasktyp : constant Entity_Id  := Etype (Defining_Identifier (N));
10511       Tasknm  : constant Name_Id    := Chars (Tasktyp);
10512       Taskdef : constant Node_Id    := Task_Definition (N);
10513
10514       Proc_Spec  : Node_Id;
10515       Rec_Decl   : Node_Id;
10516       Rec_Ent    : Entity_Id;
10517       Cdecls     : List_Id;
10518       Elab_Decl  : Node_Id;
10519       Size_Decl  : Node_Id;
10520       Body_Decl  : Node_Id;
10521       Task_Size  : Node_Id;
10522       Ent_Stack  : Entity_Id;
10523       Decl_Stack : Node_Id;
10524
10525    begin
10526       --  If already expanded, nothing to do
10527
10528       if Present (Corresponding_Record_Type (Tasktyp)) then
10529          return;
10530       end if;
10531
10532       --  Here we will do the expansion
10533
10534       Rec_Decl := Build_Corresponding_Record (N, Tasktyp, Loc);
10535
10536       Rec_Ent  := Defining_Identifier (Rec_Decl);
10537       Cdecls   := Component_Items (Component_List
10538                                      (Type_Definition (Rec_Decl)));
10539
10540       Qualify_Entity_Names (N);
10541
10542       --  First create the elaboration variable
10543
10544       Elab_Decl :=
10545         Make_Object_Declaration (Loc,
10546           Defining_Identifier =>
10547             Make_Defining_Identifier (Sloc (Tasktyp),
10548               Chars => New_External_Name (Tasknm, 'E')),
10549           Aliased_Present      => True,
10550           Object_Definition    => New_Reference_To (Standard_Boolean, Loc),
10551           Expression           => New_Reference_To (Standard_False, Loc));
10552       Insert_After (N, Elab_Decl);
10553
10554       --  Next create the declaration of the size variable (tasknmZ)
10555
10556       Set_Storage_Size_Variable (Tasktyp,
10557         Make_Defining_Identifier (Sloc (Tasktyp),
10558           Chars => New_External_Name (Tasknm, 'Z')));
10559
10560       if Present (Taskdef) and then Has_Storage_Size_Pragma (Taskdef) and then
10561         Is_Static_Expression (Expression (First (
10562           Pragma_Argument_Associations (Find_Task_Or_Protected_Pragma (
10563             Taskdef, Name_Storage_Size)))))
10564       then
10565          Size_Decl :=
10566            Make_Object_Declaration (Loc,
10567              Defining_Identifier => Storage_Size_Variable (Tasktyp),
10568              Object_Definition => New_Reference_To (RTE (RE_Size_Type), Loc),
10569              Expression =>
10570                Convert_To (RTE (RE_Size_Type),
10571                  Relocate_Node (
10572                    Expression (First (
10573                      Pragma_Argument_Associations (
10574                        Find_Task_Or_Protected_Pragma
10575                          (Taskdef, Name_Storage_Size)))))));
10576
10577       else
10578          Size_Decl :=
10579            Make_Object_Declaration (Loc,
10580              Defining_Identifier => Storage_Size_Variable (Tasktyp),
10581              Object_Definition => New_Reference_To (RTE (RE_Size_Type), Loc),
10582              Expression => New_Reference_To (RTE (RE_Unspecified_Size), Loc));
10583       end if;
10584
10585       Insert_After (Elab_Decl, Size_Decl);
10586
10587       --  Next build the rest of the corresponding record declaration. This is
10588       --  done last, since the corresponding record initialization procedure
10589       --  will reference the previously created entities.
10590
10591       --  Fill in the component declarations -- first the _Task_Id field
10592
10593       Append_To (Cdecls,
10594         Make_Component_Declaration (Loc,
10595           Defining_Identifier =>
10596             Make_Defining_Identifier (Loc, Name_uTask_Id),
10597           Component_Definition =>
10598             Make_Component_Definition (Loc,
10599               Aliased_Present    => False,
10600               Subtype_Indication => New_Reference_To (RTE (RO_ST_Task_Id),
10601                                     Loc))));
10602
10603       --  Declare static ATCB (that is, created by the expander) if we are
10604       --  using the Restricted run time.
10605
10606       if Restricted_Profile then
10607          Append_To (Cdecls,
10608            Make_Component_Declaration (Loc,
10609              Defining_Identifier  =>
10610                Make_Defining_Identifier (Loc, Name_uATCB),
10611
10612              Component_Definition =>
10613                Make_Component_Definition (Loc,
10614                  Aliased_Present     => True,
10615                  Subtype_Indication  => Make_Subtype_Indication (Loc,
10616                    Subtype_Mark => New_Occurrence_Of
10617                      (RTE (RE_Ada_Task_Control_Block), Loc),
10618
10619                    Constraint   =>
10620                      Make_Index_Or_Discriminant_Constraint (Loc,
10621                        Constraints =>
10622                          New_List (Make_Integer_Literal (Loc, 0)))))));
10623
10624       end if;
10625
10626       --  Declare static stack (that is, created by the expander) if we are
10627       --  using the Restricted run time on a bare board configuration.
10628
10629       if Restricted_Profile
10630         and then Preallocated_Stacks_On_Target
10631       then
10632          --  First we need to extract the appropriate stack size
10633
10634          Ent_Stack := Make_Defining_Identifier (Loc, Name_uStack);
10635
10636          if Present (Taskdef) and then Has_Storage_Size_Pragma (Taskdef) then
10637             declare
10638                Expr_N : constant Node_Id :=
10639                           Expression (First (
10640                             Pragma_Argument_Associations (
10641                               Find_Task_Or_Protected_Pragma
10642                                 (Taskdef, Name_Storage_Size))));
10643                Etyp   : constant Entity_Id := Etype (Expr_N);
10644                P      : constant Node_Id   := Parent (Expr_N);
10645
10646             begin
10647                --  The stack is defined inside the corresponding record.
10648                --  Therefore if the size of the stack is set by means of
10649                --  a discriminant, we must reference the discriminant of the
10650                --  corresponding record type.
10651
10652                if Nkind (Expr_N) in N_Has_Entity
10653                  and then Present (Discriminal_Link (Entity (Expr_N)))
10654                then
10655                   Task_Size :=
10656                     New_Reference_To
10657                       (CR_Discriminant (Discriminal_Link (Entity (Expr_N))),
10658                        Loc);
10659                   Set_Parent   (Task_Size, P);
10660                   Set_Etype    (Task_Size, Etyp);
10661                   Set_Analyzed (Task_Size);
10662
10663                else
10664                   Task_Size := Relocate_Node (Expr_N);
10665                end if;
10666             end;
10667
10668          else
10669             Task_Size :=
10670               New_Reference_To (RTE (RE_Default_Stack_Size), Loc);
10671          end if;
10672
10673          Decl_Stack := Make_Component_Declaration (Loc,
10674            Defining_Identifier  => Ent_Stack,
10675
10676            Component_Definition =>
10677              Make_Component_Definition (Loc,
10678                Aliased_Present     => True,
10679                Subtype_Indication  => Make_Subtype_Indication (Loc,
10680                  Subtype_Mark =>
10681                    New_Occurrence_Of (RTE (RE_Storage_Array), Loc),
10682
10683                  Constraint   =>
10684                    Make_Index_Or_Discriminant_Constraint (Loc,
10685                      Constraints  => New_List (Make_Range (Loc,
10686                        Low_Bound  => Make_Integer_Literal (Loc, 1),
10687                        High_Bound => Convert_To (RTE (RE_Storage_Offset),
10688                          Task_Size)))))));
10689
10690          Append_To (Cdecls, Decl_Stack);
10691
10692          --  The appropriate alignment for the stack is ensured by the run-time
10693          --  code in charge of task creation.
10694
10695       end if;
10696
10697       --  Add components for entry families
10698
10699       Collect_Entry_Families (Loc, Cdecls, Size_Decl, Tasktyp);
10700
10701       --  Add the _Priority component if a Priority pragma is present
10702
10703       if Present (Taskdef) and then Has_Pragma_Priority (Taskdef) then
10704          declare
10705             Prag : constant Node_Id :=
10706                      Find_Task_Or_Protected_Pragma (Taskdef, Name_Priority);
10707             Expr : Node_Id;
10708
10709          begin
10710             Expr := First (Pragma_Argument_Associations (Prag));
10711
10712             if Nkind (Expr) = N_Pragma_Argument_Association then
10713                Expr := Expression (Expr);
10714             end if;
10715
10716             Expr := New_Copy_Tree (Expr);
10717
10718             --  Add conversion to proper type to do range check if required
10719             --  Note that for runtime units, we allow out of range interrupt
10720             --  priority values to be used in a priority pragma. This is for
10721             --  the benefit of some versions of System.Interrupts which use
10722             --  a special server task with maximum interrupt priority.
10723
10724             if Pragma_Name (Prag) = Name_Priority
10725               and then not GNAT_Mode
10726             then
10727                Rewrite (Expr, Convert_To (RTE (RE_Priority), Expr));
10728             else
10729                Rewrite (Expr, Convert_To (RTE (RE_Any_Priority), Expr));
10730             end if;
10731
10732             Append_To (Cdecls,
10733               Make_Component_Declaration (Loc,
10734                 Defining_Identifier =>
10735                   Make_Defining_Identifier (Loc, Name_uPriority),
10736                 Component_Definition =>
10737                   Make_Component_Definition (Loc,
10738                     Aliased_Present    => False,
10739                     Subtype_Indication => New_Reference_To (Standard_Integer,
10740                                                             Loc)),
10741                 Expression => Expr));
10742          end;
10743       end if;
10744
10745       --  Add the _Task_Size component if a Storage_Size pragma is present
10746
10747       if Present (Taskdef)
10748         and then Has_Storage_Size_Pragma (Taskdef)
10749       then
10750          Append_To (Cdecls,
10751            Make_Component_Declaration (Loc,
10752              Defining_Identifier =>
10753                Make_Defining_Identifier (Loc, Name_uSize),
10754
10755              Component_Definition =>
10756                Make_Component_Definition (Loc,
10757                  Aliased_Present    => False,
10758                  Subtype_Indication => New_Reference_To (RTE (RE_Size_Type),
10759                                                          Loc)),
10760
10761              Expression =>
10762                Convert_To (RTE (RE_Size_Type),
10763                  Relocate_Node (
10764                    Expression (First (
10765                      Pragma_Argument_Associations (
10766                        Find_Task_Or_Protected_Pragma
10767                          (Taskdef, Name_Storage_Size))))))));
10768       end if;
10769
10770       --  Add the _Task_Info component if a Task_Info pragma is present
10771
10772       if Present (Taskdef) and then Has_Task_Info_Pragma (Taskdef) then
10773          Append_To (Cdecls,
10774            Make_Component_Declaration (Loc,
10775              Defining_Identifier =>
10776                Make_Defining_Identifier (Loc, Name_uTask_Info),
10777
10778              Component_Definition =>
10779                Make_Component_Definition (Loc,
10780                  Aliased_Present    => False,
10781                  Subtype_Indication =>
10782                    New_Reference_To (RTE (RE_Task_Info_Type), Loc)),
10783
10784              Expression => New_Copy (
10785                Expression (First (
10786                  Pragma_Argument_Associations (
10787                    Find_Task_Or_Protected_Pragma
10788                      (Taskdef, Name_Task_Info)))))));
10789       end if;
10790
10791       --  Add the _CPU component if a CPU pragma is present
10792
10793       if Present (Taskdef) and then Has_Pragma_CPU (Taskdef) then
10794          Append_To (Cdecls,
10795            Make_Component_Declaration (Loc,
10796              Defining_Identifier =>
10797                Make_Defining_Identifier (Loc, Name_uCPU),
10798
10799              Component_Definition =>
10800                Make_Component_Definition (Loc,
10801                  Aliased_Present    => False,
10802                  Subtype_Indication =>
10803                    New_Reference_To (RTE (RE_CPU_Range), Loc)),
10804
10805              Expression => New_Copy (
10806                Expression (First (
10807                  Pragma_Argument_Associations (
10808                    Find_Task_Or_Protected_Pragma
10809                      (Taskdef, Name_CPU)))))));
10810       end if;
10811
10812       --  Add the _Relative_Deadline component if a Relative_Deadline pragma is
10813       --  present. If we are using a restricted run time this component will
10814       --  not be added (deadlines are not allowed by the Ravenscar profile).
10815
10816       if not Restricted_Profile
10817         and then Present (Taskdef)
10818         and then Has_Relative_Deadline_Pragma (Taskdef)
10819       then
10820          Append_To (Cdecls,
10821            Make_Component_Declaration (Loc,
10822              Defining_Identifier =>
10823                Make_Defining_Identifier (Loc, Name_uRelative_Deadline),
10824
10825              Component_Definition =>
10826                Make_Component_Definition (Loc,
10827                  Aliased_Present    => False,
10828                  Subtype_Indication =>
10829                    New_Reference_To (RTE (RE_Time_Span), Loc)),
10830
10831              Expression =>
10832                Convert_To (RTE (RE_Time_Span),
10833                  Relocate_Node (
10834                    Expression (First (
10835                      Pragma_Argument_Associations (
10836                        Find_Task_Or_Protected_Pragma
10837                          (Taskdef, Name_Relative_Deadline))))))));
10838       end if;
10839
10840       Insert_After (Size_Decl, Rec_Decl);
10841
10842       --  Analyze the record declaration immediately after construction,
10843       --  because the initialization procedure is needed for single task
10844       --  declarations before the next entity is analyzed.
10845
10846       Analyze (Rec_Decl);
10847
10848       --  Create the declaration of the task body procedure
10849
10850       Proc_Spec := Build_Task_Proc_Specification (Tasktyp);
10851       Body_Decl :=
10852         Make_Subprogram_Declaration (Loc,
10853           Specification => Proc_Spec);
10854
10855       Insert_After (Rec_Decl, Body_Decl);
10856
10857       --  The subprogram does not comes from source, so we have to indicate the
10858       --  need for debugging information explicitly.
10859
10860       if Comes_From_Source (Original_Node (N)) then
10861          Set_Debug_Info_Needed (Defining_Entity (Proc_Spec));
10862       end if;
10863
10864       --  Ada 2005 (AI-345): Construct the primitive entry wrapper specs before
10865       --  the corresponding record has been frozen.
10866
10867       if Ada_Version >= Ada_2005 then
10868          Build_Wrapper_Specs (Loc, Tasktyp, Rec_Decl);
10869       end if;
10870
10871       --  Ada 2005 (AI-345): We must defer freezing to allow further
10872       --  declaration of primitive subprograms covering task interfaces
10873
10874       if Ada_Version <= Ada_95 then
10875
10876          --  Now we can freeze the corresponding record. This needs manually
10877          --  freezing, since it is really part of the task type, and the task
10878          --  type is frozen at this stage. We of course need the initialization
10879          --  procedure for this corresponding record type and we won't get it
10880          --  in time if we don't freeze now.
10881
10882          declare
10883             L : constant List_Id := Freeze_Entity (Rec_Ent, N);
10884          begin
10885             if Is_Non_Empty_List (L) then
10886                Insert_List_After (Body_Decl, L);
10887             end if;
10888          end;
10889       end if;
10890
10891       --  Complete the expansion of access types to the current task type, if
10892       --  any were declared.
10893
10894       Expand_Previous_Access_Type (Tasktyp);
10895
10896       --  Create wrappers for entries that have pre/postconditions
10897
10898       declare
10899          Ent : Entity_Id;
10900
10901       begin
10902          Ent := First_Entity (Tasktyp);
10903          while Present (Ent) loop
10904             if Ekind_In (Ent, E_Entry, E_Entry_Family)
10905               and then Present (Spec_PPC_List (Ent))
10906             then
10907                Build_PPC_Wrapper (Ent, N);
10908             end if;
10909
10910             Next_Entity (Ent);
10911          end loop;
10912       end;
10913    end Expand_N_Task_Type_Declaration;
10914
10915    -------------------------------
10916    -- Expand_N_Timed_Entry_Call --
10917    -------------------------------
10918
10919    --  A timed entry call in normal case is not implemented using ATC mechanism
10920    --  anymore for efficiency reason.
10921
10922    --     select
10923    --        T.E;
10924    --        S1;
10925    --     or
10926    --        Delay D;
10927    --        S2;
10928    --     end select;
10929
10930    --  is expanded as follow:
10931
10932    --  1) When T.E is a task entry_call;
10933
10934    --    declare
10935    --       B  : Boolean;
10936    --       X  : Task_Entry_Index := <entry index>;
10937    --       DX : Duration := To_Duration (D);
10938    --       M  : Delay_Mode := <discriminant>;
10939    --       P  : parms := (parm, parm, parm);
10940
10941    --    begin
10942    --       Timed_Protected_Entry_Call
10943    --         (<acceptor-task>, X, P'Address, DX, M, B);
10944    --       if B then
10945    --          S1;
10946    --       else
10947    --          S2;
10948    --       end if;
10949    --    end;
10950
10951    --  2) When T.E is a protected entry_call;
10952
10953    --    declare
10954    --       B  : Boolean;
10955    --       X  : Protected_Entry_Index := <entry index>;
10956    --       DX : Duration := To_Duration (D);
10957    --       M  : Delay_Mode := <discriminant>;
10958    --       P  : parms := (parm, parm, parm);
10959
10960    --    begin
10961    --       Timed_Protected_Entry_Call
10962    --         (<object>'unchecked_access, X, P'Address, DX, M, B);
10963    --       if B then
10964    --          S1;
10965    --       else
10966    --          S2;
10967    --       end if;
10968    --    end;
10969
10970    --  3) Ada 2005 (AI-345): When T.E is a dispatching procedure call;
10971
10972    --    declare
10973    --       B  : Boolean := False;
10974    --       C  : Ada.Tags.Prim_Op_Kind;
10975    --       DX : Duration := To_Duration (D)
10976    --       K  : Ada.Tags.Tagged_Kind :=
10977    --              Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
10978    --       M  : Integer :=...;
10979    --       P  : Parameters := (Param1 .. ParamN);
10980    --       S  : Integer;
10981
10982    --    begin
10983    --       if K = Ada.Tags.TK_Limited_Tagged then
10984    --          <dispatching-call>;
10985    --          <triggering-statements>
10986
10987    --       else
10988    --          S :=
10989    --            Ada.Tags.Get_Offset_Index
10990    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
10991
10992    --          _Disp_Timed_Select (<object>, S, P'Address, DX, M, C, B);
10993
10994    --          if C = POK_Protected_Entry
10995    --            or else C = POK_Task_Entry
10996    --          then
10997    --             Param1 := P.Param1;
10998    --             ...
10999    --             ParamN := P.ParamN;
11000    --          end if;
11001
11002    --          if B then
11003    --             if C = POK_Procedure
11004    --               or else C = POK_Protected_Procedure
11005    --               or else C = POK_Task_Procedure
11006    --             then
11007    --                <dispatching-call>;
11008    --             end if;
11009
11010    --             <triggering-statements>
11011    --          else
11012    --             <timed-statements>
11013    --          end if;
11014    --       end if;
11015    --    end;
11016
11017    procedure Expand_N_Timed_Entry_Call (N : Node_Id) is
11018       Loc : constant Source_Ptr := Sloc (N);
11019
11020       E_Call  : Node_Id :=
11021                   Entry_Call_Statement (Entry_Call_Alternative (N));
11022       E_Stats : constant List_Id :=
11023                   Statements (Entry_Call_Alternative (N));
11024       D_Stat  : Node_Id :=
11025                   Delay_Statement (Delay_Alternative (N));
11026       D_Stats : constant List_Id :=
11027                   Statements (Delay_Alternative (N));
11028
11029       Actuals        : List_Id;
11030       Blk_Typ        : Entity_Id;
11031       Call           : Node_Id;
11032       Call_Ent       : Entity_Id;
11033       Conc_Typ_Stmts : List_Id;
11034       Concval        : Node_Id;
11035       D_Conv         : Node_Id;
11036       D_Disc         : Node_Id;
11037       D_Type         : Entity_Id;
11038       Decls          : List_Id;
11039       Dummy          : Node_Id;
11040       Ename          : Node_Id;
11041       Formals        : List_Id;
11042       Index          : Node_Id;
11043       Is_Disp_Select : Boolean;
11044       Lim_Typ_Stmts  : List_Id;
11045       N_Stats        : List_Id;
11046       Obj            : Entity_Id;
11047       Param          : Node_Id;
11048       Params         : List_Id;
11049       Stmt           : Node_Id;
11050       Stmts          : List_Id;
11051       Unpack         : List_Id;
11052
11053       B : Entity_Id;  --  Call status flag
11054       C : Entity_Id;  --  Call kind
11055       D : Entity_Id;  --  Delay
11056       K : Entity_Id;  --  Tagged kind
11057       M : Entity_Id;  --  Delay mode
11058       P : Entity_Id;  --  Parameter block
11059       S : Entity_Id;  --  Primitive operation slot
11060
11061    begin
11062       --  Under the Ravenscar profile, timed entry calls are excluded. An error
11063       --  was already reported on spec, so do not attempt to expand the call.
11064
11065       if Restriction_Active (No_Select_Statements) then
11066          return;
11067       end if;
11068
11069       --  The arguments in the call may require dynamic allocation, and the
11070       --  call statement may have been transformed into a block. The block
11071       --  may contain additional declarations for internal entities, and the
11072       --  original call is found by sequential search.
11073
11074       if Nkind (E_Call) = N_Block_Statement then
11075          E_Call := First (Statements (Handled_Statement_Sequence (E_Call)));
11076          while not Nkind_In (E_Call, N_Procedure_Call_Statement,
11077                                      N_Entry_Call_Statement)
11078          loop
11079             Next (E_Call);
11080          end loop;
11081       end if;
11082
11083       Is_Disp_Select :=
11084         Ada_Version >= Ada_2005
11085           and then Nkind (E_Call) = N_Procedure_Call_Statement;
11086
11087       if Is_Disp_Select then
11088          Extract_Dispatching_Call (E_Call, Call_Ent, Obj, Actuals, Formals);
11089
11090          Decls := New_List;
11091          Stmts := New_List;
11092
11093          --  Generate:
11094          --    B : Boolean := False;
11095
11096          B := Build_B (Loc, Decls);
11097
11098          --  Generate:
11099          --    C : Ada.Tags.Prim_Op_Kind;
11100
11101          C := Build_C (Loc, Decls);
11102
11103          --  Because the analysis of all statements was disabled, manually
11104          --  analyze the delay statement.
11105
11106          Analyze (D_Stat);
11107          D_Stat := Original_Node (D_Stat);
11108
11109       else
11110          --  Build an entry call using Simple_Entry_Call
11111
11112          Extract_Entry (E_Call, Concval, Ename, Index);
11113          Build_Simple_Entry_Call (E_Call, Concval, Ename, Index);
11114
11115          Decls := Declarations (E_Call);
11116          Stmts := Statements (Handled_Statement_Sequence (E_Call));
11117
11118          if No (Decls) then
11119             Decls := New_List;
11120          end if;
11121
11122          --  Generate:
11123          --    B : Boolean;
11124
11125          B := Make_Defining_Identifier (Loc, Name_uB);
11126
11127          Prepend_To (Decls,
11128            Make_Object_Declaration (Loc,
11129              Defining_Identifier =>
11130                B,
11131              Object_Definition =>
11132                New_Reference_To (Standard_Boolean, Loc)));
11133       end if;
11134
11135       --  Duration and mode processing
11136
11137       D_Type := Base_Type (Etype (Expression (D_Stat)));
11138
11139       --  Use the type of the delay expression (Calendar or Real_Time) to
11140       --  generate the appropriate conversion.
11141
11142       if Nkind (D_Stat) = N_Delay_Relative_Statement then
11143          D_Disc := Make_Integer_Literal (Loc, 0);
11144          D_Conv := Relocate_Node (Expression (D_Stat));
11145
11146       elsif Is_RTE (D_Type, RO_CA_Time) then
11147          D_Disc := Make_Integer_Literal (Loc, 1);
11148          D_Conv := Make_Function_Call (Loc,
11149            New_Reference_To (RTE (RO_CA_To_Duration), Loc),
11150            New_List (New_Copy (Expression (D_Stat))));
11151
11152       else pragma Assert (Is_RTE (D_Type, RO_RT_Time));
11153          D_Disc := Make_Integer_Literal (Loc, 2);
11154          D_Conv := Make_Function_Call (Loc,
11155            New_Reference_To (RTE (RO_RT_To_Duration), Loc),
11156            New_List (New_Copy (Expression (D_Stat))));
11157       end if;
11158
11159       D := Make_Temporary (Loc, 'D');
11160
11161       --  Generate:
11162       --    D : Duration;
11163
11164       Append_To (Decls,
11165         Make_Object_Declaration (Loc,
11166           Defining_Identifier =>
11167             D,
11168           Object_Definition =>
11169             New_Reference_To (Standard_Duration, Loc)));
11170
11171       M := Make_Temporary (Loc, 'M');
11172
11173       --  Generate:
11174       --    M : Integer := (0 | 1 | 2);
11175
11176       Append_To (Decls,
11177         Make_Object_Declaration (Loc,
11178           Defining_Identifier =>
11179             M,
11180           Object_Definition =>
11181             New_Reference_To (Standard_Integer, Loc),
11182           Expression =>
11183             D_Disc));
11184
11185       --  Do the assignment at this stage only because the evaluation of the
11186       --  expression must not occur before (see ACVC C97302A).
11187
11188       Append_To (Stmts,
11189         Make_Assignment_Statement (Loc,
11190           Name =>
11191             New_Reference_To (D, Loc),
11192           Expression =>
11193             D_Conv));
11194
11195       --  Parameter block processing
11196
11197       --  Manually create the parameter block for dispatching calls. In the
11198       --  case of entries, the block has already been created during the call
11199       --  to Build_Simple_Entry_Call.
11200
11201       if Is_Disp_Select then
11202
11203          --  Tagged kind processing, generate:
11204          --    K : Ada.Tags.Tagged_Kind :=
11205          --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag <object>));
11206
11207          K := Build_K (Loc, Decls, Obj);
11208
11209          Blk_Typ := Build_Parameter_Block (Loc, Actuals, Formals, Decls);
11210          P := Parameter_Block_Pack
11211                 (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
11212
11213          --  Dispatch table slot processing, generate:
11214          --    S : Integer;
11215
11216          S := Build_S (Loc, Decls);
11217
11218          --  Generate:
11219          --    S := Ada.Tags.Get_Offset_Index
11220          --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
11221
11222          Conc_Typ_Stmts :=
11223            New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
11224
11225          --  Generate:
11226          --    _Disp_Timed_Select (<object>, S, P'Address, D, M, C, B);
11227
11228          --  where Obj is the controlling formal parameter, S is the dispatch
11229          --  table slot number of the dispatching operation, P is the wrapped
11230          --  parameter block, D is the duration, M is the duration mode, C is
11231          --  the call kind and B is the call status.
11232
11233          Params := New_List;
11234
11235          Append_To (Params, New_Copy_Tree (Obj));
11236          Append_To (Params, New_Reference_To (S, Loc));
11237          Append_To (Params, Make_Attribute_Reference (Loc,
11238                               Prefix => New_Reference_To (P, Loc),
11239                               Attribute_Name => Name_Address));
11240          Append_To (Params, New_Reference_To (D, Loc));
11241          Append_To (Params, New_Reference_To (M, Loc));
11242          Append_To (Params, New_Reference_To (C, Loc));
11243          Append_To (Params, New_Reference_To (B, Loc));
11244
11245          Append_To (Conc_Typ_Stmts,
11246            Make_Procedure_Call_Statement (Loc,
11247              Name =>
11248                New_Reference_To (
11249                  Find_Prim_Op (Etype (Etype (Obj)),
11250                    Name_uDisp_Timed_Select),
11251                  Loc),
11252              Parameter_Associations =>
11253                Params));
11254
11255          --  Generate:
11256          --    if C = POK_Protected_Entry
11257          --      or else C = POK_Task_Entry
11258          --    then
11259          --       Param1 := P.Param1;
11260          --       ...
11261          --       ParamN := P.ParamN;
11262          --    end if;
11263
11264          Unpack := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
11265
11266          --  Generate the if statement only when the packed parameters need
11267          --  explicit assignments to their corresponding actuals.
11268
11269          if Present (Unpack) then
11270             Append_To (Conc_Typ_Stmts,
11271               Make_If_Statement (Loc,
11272
11273                 Condition =>
11274                   Make_Or_Else (Loc,
11275                     Left_Opnd =>
11276                       Make_Op_Eq (Loc,
11277                         Left_Opnd =>
11278                           New_Reference_To (C, Loc),
11279                         Right_Opnd =>
11280                           New_Reference_To (RTE (
11281                             RE_POK_Protected_Entry), Loc)),
11282                     Right_Opnd =>
11283                       Make_Op_Eq (Loc,
11284                         Left_Opnd =>
11285                           New_Reference_To (C, Loc),
11286                         Right_Opnd =>
11287                           New_Reference_To (RTE (RE_POK_Task_Entry), Loc))),
11288
11289                 Then_Statements =>
11290                   Unpack));
11291          end if;
11292
11293          --  Generate:
11294
11295          --    if B then
11296          --       if C = POK_Procedure
11297          --         or else C = POK_Protected_Procedure
11298          --         or else C = POK_Task_Procedure
11299          --       then
11300          --          <dispatching-call>
11301          --       end if;
11302          --       <triggering-statements>
11303          --    else
11304          --       <timed-statements>
11305          --    end if;
11306
11307          N_Stats := New_Copy_List_Tree (E_Stats);
11308
11309          Prepend_To (N_Stats,
11310            Make_If_Statement (Loc,
11311
11312              Condition =>
11313                Make_Or_Else (Loc,
11314                  Left_Opnd =>
11315                    Make_Op_Eq (Loc,
11316                      Left_Opnd =>
11317                        New_Reference_To (C, Loc),
11318                      Right_Opnd =>
11319                        New_Reference_To (RTE (RE_POK_Procedure), Loc)),
11320                  Right_Opnd =>
11321                    Make_Or_Else (Loc,
11322                      Left_Opnd =>
11323                        Make_Op_Eq (Loc,
11324                          Left_Opnd =>
11325                            New_Reference_To (C, Loc),
11326                          Right_Opnd =>
11327                            New_Reference_To (RTE (
11328                              RE_POK_Protected_Procedure), Loc)),
11329                      Right_Opnd =>
11330                        Make_Op_Eq (Loc,
11331                          Left_Opnd =>
11332                            New_Reference_To (C, Loc),
11333                          Right_Opnd =>
11334                            New_Reference_To (RTE (
11335                              RE_POK_Task_Procedure), Loc)))),
11336
11337              Then_Statements =>
11338                New_List (E_Call)));
11339
11340          Append_To (Conc_Typ_Stmts,
11341            Make_If_Statement (Loc,
11342              Condition => New_Reference_To (B, Loc),
11343              Then_Statements => N_Stats,
11344              Else_Statements => D_Stats));
11345
11346          --  Generate:
11347          --    <dispatching-call>;
11348          --    <triggering-statements>
11349
11350          Lim_Typ_Stmts := New_Copy_List_Tree (E_Stats);
11351          Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (E_Call));
11352
11353          --  Generate:
11354          --    if K = Ada.Tags.TK_Limited_Tagged then
11355          --       Lim_Typ_Stmts
11356          --    else
11357          --       Conc_Typ_Stmts
11358          --    end if;
11359
11360          Append_To (Stmts,
11361            Make_If_Statement (Loc,
11362              Condition =>
11363                Make_Op_Eq (Loc,
11364                  Left_Opnd =>
11365                    New_Reference_To (K, Loc),
11366                  Right_Opnd =>
11367                    New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
11368
11369              Then_Statements =>
11370                Lim_Typ_Stmts,
11371
11372              Else_Statements =>
11373                Conc_Typ_Stmts));
11374
11375       else
11376          --  Skip assignments to temporaries created for in-out parameters.
11377          --  This makes unwarranted assumptions about the shape of the expanded
11378          --  tree for the call, and should be cleaned up ???
11379
11380          Stmt := First (Stmts);
11381          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
11382             Next (Stmt);
11383          end loop;
11384
11385          --  Do the assignment at this stage only because the evaluation
11386          --  of the expression must not occur before (see ACVC C97302A).
11387
11388          Insert_Before (Stmt,
11389            Make_Assignment_Statement (Loc,
11390              Name => New_Reference_To (D, Loc),
11391              Expression => D_Conv));
11392
11393          Call   := Stmt;
11394          Params := Parameter_Associations (Call);
11395
11396          --  For a protected type, we build a Timed_Protected_Entry_Call
11397
11398          if Is_Protected_Type (Etype (Concval)) then
11399
11400             --  Create a new call statement
11401
11402             Param := First (Params);
11403             while Present (Param)
11404               and then not Is_RTE (Etype (Param), RE_Call_Modes)
11405             loop
11406                Next (Param);
11407             end loop;
11408
11409             Dummy := Remove_Next (Next (Param));
11410
11411             --  Remove garbage is following the Cancel_Param if present
11412
11413             Dummy := Next (Param);
11414
11415             --  Remove the mode of the Protected_Entry_Call call, then remove
11416             --  the Communication_Block of the Protected_Entry_Call call, and
11417             --  finally add Duration and a Delay_Mode parameter
11418
11419             pragma Assert (Present (Param));
11420             Rewrite (Param, New_Reference_To (D, Loc));
11421
11422             Rewrite (Dummy, New_Reference_To (M, Loc));
11423
11424             --  Add a Boolean flag for successful entry call
11425
11426             Append_To (Params, New_Reference_To (B, Loc));
11427
11428             case Corresponding_Runtime_Package (Etype (Concval)) is
11429                when System_Tasking_Protected_Objects_Entries =>
11430                   Rewrite (Call,
11431                     Make_Procedure_Call_Statement (Loc,
11432                       Name =>
11433                         New_Reference_To
11434                           (RTE (RE_Timed_Protected_Entry_Call), Loc),
11435                       Parameter_Associations => Params));
11436
11437                when System_Tasking_Protected_Objects_Single_Entry =>
11438                   Param := First (Params);
11439                   while Present (Param)
11440                     and then not
11441                       Is_RTE (Etype (Param), RE_Protected_Entry_Index)
11442                   loop
11443                      Next (Param);
11444                   end loop;
11445
11446                   Remove (Param);
11447
11448                   Rewrite (Call,
11449                     Make_Procedure_Call_Statement (Loc,
11450                       Name => New_Reference_To (
11451                         RTE (RE_Timed_Protected_Single_Entry_Call), Loc),
11452                       Parameter_Associations => Params));
11453
11454                when others =>
11455                   raise Program_Error;
11456             end case;
11457
11458          --  For the task case, build a Timed_Task_Entry_Call
11459
11460          else
11461             --  Create a new call statement
11462
11463             Append_To (Params, New_Reference_To (D, Loc));
11464             Append_To (Params, New_Reference_To (M, Loc));
11465             Append_To (Params, New_Reference_To (B, Loc));
11466
11467             Rewrite (Call,
11468               Make_Procedure_Call_Statement (Loc,
11469                 Name =>
11470                   New_Reference_To (RTE (RE_Timed_Task_Entry_Call), Loc),
11471                 Parameter_Associations => Params));
11472          end if;
11473
11474          Append_To (Stmts,
11475            Make_Implicit_If_Statement (N,
11476              Condition => New_Reference_To (B, Loc),
11477              Then_Statements => E_Stats,
11478              Else_Statements => D_Stats));
11479       end if;
11480
11481       Rewrite (N,
11482         Make_Block_Statement (Loc,
11483           Declarations => Decls,
11484           Handled_Statement_Sequence =>
11485             Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
11486
11487       Analyze (N);
11488    end Expand_N_Timed_Entry_Call;
11489
11490    ----------------------------------------
11491    -- Expand_Protected_Body_Declarations --
11492    ----------------------------------------
11493
11494    procedure Expand_Protected_Body_Declarations
11495      (N       : Node_Id;
11496       Spec_Id : Entity_Id)
11497    is
11498    begin
11499       if No_Run_Time_Mode then
11500          Error_Msg_CRT ("protected body", N);
11501          return;
11502
11503       elsif Expander_Active then
11504
11505          --  Associate discriminals with the first subprogram or entry body to
11506          --  be expanded.
11507
11508          if Present (First_Protected_Operation (Declarations (N))) then
11509             Set_Discriminals (Parent (Spec_Id));
11510          end if;
11511       end if;
11512    end Expand_Protected_Body_Declarations;
11513
11514    -------------------------
11515    -- External_Subprogram --
11516    -------------------------
11517
11518    function External_Subprogram (E : Entity_Id) return Entity_Id is
11519       Subp : constant Entity_Id := Protected_Body_Subprogram (E);
11520
11521    begin
11522       --  The internal and external subprograms follow each other on the entity
11523       --  chain. Note that previously private operations had no separate
11524       --  external subprogram. We now create one in all cases, because a
11525       --  private operation may actually appear in an external call, through
11526       --  a 'Access reference used for a callback.
11527
11528       --  If the operation is a function that returns an anonymous access type,
11529       --  the corresponding itype appears before the operation, and must be
11530       --  skipped.
11531
11532       --  This mechanism is fragile, there should be a real link between the
11533       --  two versions of the operation, but there is no place to put it ???
11534
11535       if Is_Access_Type (Next_Entity (Subp)) then
11536          return Next_Entity (Next_Entity (Subp));
11537       else
11538          return Next_Entity (Subp);
11539       end if;
11540    end External_Subprogram;
11541
11542    ------------------------------
11543    -- Extract_Dispatching_Call --
11544    ------------------------------
11545
11546    procedure Extract_Dispatching_Call
11547      (N        : Node_Id;
11548       Call_Ent : out Entity_Id;
11549       Object   : out Entity_Id;
11550       Actuals  : out List_Id;
11551       Formals  : out List_Id)
11552    is
11553       Call_Nam : Node_Id;
11554
11555    begin
11556       pragma Assert (Nkind (N) = N_Procedure_Call_Statement);
11557
11558       if Present (Original_Node (N)) then
11559          Call_Nam := Name (Original_Node (N));
11560       else
11561          Call_Nam := Name (N);
11562       end if;
11563
11564       --  Retrieve the name of the dispatching procedure. It contains the
11565       --  dispatch table slot number.
11566
11567       loop
11568          case Nkind (Call_Nam) is
11569             when N_Identifier =>
11570                exit;
11571
11572             when N_Selected_Component =>
11573                Call_Nam := Selector_Name (Call_Nam);
11574
11575             when others =>
11576                raise Program_Error;
11577
11578          end case;
11579       end loop;
11580
11581       Actuals  := Parameter_Associations (N);
11582       Call_Ent := Entity (Call_Nam);
11583       Formals  := Parameter_Specifications (Parent (Call_Ent));
11584       Object   := First (Actuals);
11585
11586       if Present (Original_Node (Object)) then
11587          Object := Original_Node (Object);
11588       end if;
11589
11590       --  If the type of the dispatching object is an access type then return
11591       --  an explicit dereference.
11592
11593       if Is_Access_Type (Etype (Object)) then
11594          Object := Make_Explicit_Dereference (Sloc (N), Object);
11595          Analyze (Object);
11596       end if;
11597    end Extract_Dispatching_Call;
11598
11599    -------------------
11600    -- Extract_Entry --
11601    -------------------
11602
11603    procedure Extract_Entry
11604      (N       : Node_Id;
11605       Concval : out Node_Id;
11606       Ename   : out Node_Id;
11607       Index   : out Node_Id)
11608    is
11609       Nam : constant Node_Id := Name (N);
11610
11611    begin
11612       --  For a simple entry, the name is a selected component, with the
11613       --  prefix being the task value, and the selector being the entry.
11614
11615       if Nkind (Nam) = N_Selected_Component then
11616          Concval := Prefix (Nam);
11617          Ename   := Selector_Name (Nam);
11618          Index   := Empty;
11619
11620       --  For a member of an entry family, the name is an indexed component
11621       --  where the prefix is a selected component, whose prefix in turn is
11622       --  the task value, and whose selector is the entry family. The single
11623       --  expression in the expressions list of the indexed component is the
11624       --  subscript for the family.
11625
11626       else pragma Assert (Nkind (Nam) = N_Indexed_Component);
11627          Concval := Prefix (Prefix (Nam));
11628          Ename   := Selector_Name (Prefix (Nam));
11629          Index   := First (Expressions (Nam));
11630       end if;
11631    end Extract_Entry;
11632
11633    -------------------
11634    -- Family_Offset --
11635    -------------------
11636
11637    function Family_Offset
11638      (Loc  : Source_Ptr;
11639       Hi   : Node_Id;
11640       Lo   : Node_Id;
11641       Ttyp : Entity_Id;
11642       Cap  : Boolean) return Node_Id
11643    is
11644       Ityp : Entity_Id;
11645       Real_Hi : Node_Id;
11646       Real_Lo : Node_Id;
11647
11648       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id;
11649       --  If one of the bounds is a reference to a discriminant, replace with
11650       --  corresponding discriminal of type. Within the body of a task retrieve
11651       --  the renamed discriminant by simple visibility, using its generated
11652       --  name. Within a protected object, find the original discriminant and
11653       --  replace it with the discriminal of the current protected operation.
11654
11655       ------------------------------
11656       -- Convert_Discriminant_Ref --
11657       ------------------------------
11658
11659       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id is
11660          Loc : constant Source_Ptr := Sloc (Bound);
11661          B   : Node_Id;
11662          D   : Entity_Id;
11663
11664       begin
11665          if Is_Entity_Name (Bound)
11666            and then Ekind (Entity (Bound)) = E_Discriminant
11667          then
11668             if Is_Task_Type (Ttyp)
11669               and then Has_Completion (Ttyp)
11670             then
11671                B := Make_Identifier (Loc, Chars (Entity (Bound)));
11672                Find_Direct_Name (B);
11673
11674             elsif Is_Protected_Type (Ttyp) then
11675                D := First_Discriminant (Ttyp);
11676                while Chars (D) /= Chars (Entity (Bound)) loop
11677                   Next_Discriminant (D);
11678                end loop;
11679
11680                B := New_Reference_To  (Discriminal (D), Loc);
11681
11682             else
11683                B := New_Reference_To (Discriminal (Entity (Bound)), Loc);
11684             end if;
11685
11686          elsif Nkind (Bound) = N_Attribute_Reference then
11687             return Bound;
11688
11689          else
11690             B := New_Copy_Tree (Bound);
11691          end if;
11692
11693          return
11694            Make_Attribute_Reference (Loc,
11695              Attribute_Name => Name_Pos,
11696              Prefix => New_Occurrence_Of (Etype (Bound), Loc),
11697              Expressions    => New_List (B));
11698       end Convert_Discriminant_Ref;
11699
11700    --  Start of processing for Family_Offset
11701
11702    begin
11703       Real_Hi := Convert_Discriminant_Ref (Hi);
11704       Real_Lo := Convert_Discriminant_Ref (Lo);
11705
11706       if Cap then
11707          if Is_Task_Type (Ttyp) then
11708             Ityp := RTE (RE_Task_Entry_Index);
11709          else
11710             Ityp := RTE (RE_Protected_Entry_Index);
11711          end if;
11712
11713          Real_Hi :=
11714            Make_Attribute_Reference (Loc,
11715              Prefix         => New_Reference_To (Ityp, Loc),
11716              Attribute_Name => Name_Min,
11717              Expressions    => New_List (
11718                Real_Hi,
11719                Make_Integer_Literal (Loc, Entry_Family_Bound - 1)));
11720
11721          Real_Lo :=
11722            Make_Attribute_Reference (Loc,
11723              Prefix         => New_Reference_To (Ityp, Loc),
11724              Attribute_Name => Name_Max,
11725              Expressions    => New_List (
11726                Real_Lo,
11727                Make_Integer_Literal (Loc, -Entry_Family_Bound)));
11728       end if;
11729
11730       return Make_Op_Subtract (Loc, Real_Hi, Real_Lo);
11731    end Family_Offset;
11732
11733    -----------------
11734    -- Family_Size --
11735    -----------------
11736
11737    function Family_Size
11738      (Loc  : Source_Ptr;
11739       Hi   : Node_Id;
11740       Lo   : Node_Id;
11741       Ttyp : Entity_Id;
11742       Cap  : Boolean) return Node_Id
11743    is
11744       Ityp : Entity_Id;
11745
11746    begin
11747       if Is_Task_Type (Ttyp) then
11748          Ityp := RTE (RE_Task_Entry_Index);
11749       else
11750          Ityp := RTE (RE_Protected_Entry_Index);
11751       end if;
11752
11753       return
11754         Make_Attribute_Reference (Loc,
11755           Prefix         => New_Reference_To (Ityp, Loc),
11756           Attribute_Name => Name_Max,
11757           Expressions    => New_List (
11758             Make_Op_Add (Loc,
11759               Left_Opnd  =>
11760                 Family_Offset (Loc, Hi, Lo, Ttyp, Cap),
11761               Right_Opnd =>
11762                 Make_Integer_Literal (Loc, 1)),
11763             Make_Integer_Literal (Loc, 0)));
11764    end Family_Size;
11765
11766    -----------------------
11767    -- Find_Master_Scope --
11768    -----------------------
11769
11770    function Find_Master_Scope (E : Entity_Id) return Entity_Id is
11771       S : Entity_Id;
11772
11773    begin
11774       --  In Ada2005, the master is the innermost enclosing scope that is not
11775       --  transient. If the enclosing block is the rewriting of a call or the
11776       --  scope is an extended return statement this is valid master. The
11777       --  master in an extended return is only used within the return, and is
11778       --  subsequently overwritten in Move_Activation_Chain, but it must exist
11779       --  now before that overwriting occurs.
11780
11781       S := Scope (E);
11782
11783       if Ada_Version >= Ada_2005 then
11784          while Is_Internal (S) loop
11785             if Nkind (Parent (S)) = N_Block_Statement
11786               and then
11787                 Nkind (Original_Node (Parent (S))) = N_Procedure_Call_Statement
11788             then
11789                exit;
11790
11791             elsif Ekind (S) = E_Return_Statement then
11792                exit;
11793
11794             else
11795                S := Scope (S);
11796             end if;
11797          end loop;
11798       end if;
11799
11800       return S;
11801    end Find_Master_Scope;
11802
11803    -----------------------------------
11804    -- Find_Task_Or_Protected_Pragma --
11805    -----------------------------------
11806
11807    function Find_Task_Or_Protected_Pragma
11808      (T : Node_Id;
11809       P : Name_Id) return Node_Id
11810    is
11811       N : Node_Id;
11812
11813    begin
11814       N := First (Visible_Declarations (T));
11815       while Present (N) loop
11816          if Nkind (N) = N_Pragma then
11817             if Pragma_Name (N) = P then
11818                return N;
11819
11820             elsif P = Name_Priority
11821               and then Pragma_Name (N) = Name_Interrupt_Priority
11822             then
11823                return N;
11824
11825             else
11826                Next (N);
11827             end if;
11828
11829          else
11830             Next (N);
11831          end if;
11832       end loop;
11833
11834       N := First (Private_Declarations (T));
11835       while Present (N) loop
11836          if Nkind (N) = N_Pragma then
11837             if Pragma_Name (N) = P then
11838                return N;
11839
11840             elsif P = Name_Priority
11841               and then Pragma_Name (N) = Name_Interrupt_Priority
11842             then
11843                return N;
11844
11845             else
11846                Next (N);
11847             end if;
11848
11849          else
11850             Next (N);
11851          end if;
11852       end loop;
11853
11854       raise Program_Error;
11855    end Find_Task_Or_Protected_Pragma;
11856
11857    -------------------------------
11858    -- First_Protected_Operation --
11859    -------------------------------
11860
11861    function First_Protected_Operation (D : List_Id) return Node_Id is
11862       First_Op : Node_Id;
11863
11864    begin
11865       First_Op := First (D);
11866       while Present (First_Op)
11867         and then not Nkind_In (First_Op, N_Subprogram_Body, N_Entry_Body)
11868       loop
11869          Next (First_Op);
11870       end loop;
11871
11872       return First_Op;
11873    end First_Protected_Operation;
11874
11875    ---------------------------------------
11876    -- Install_Private_Data_Declarations --
11877    ---------------------------------------
11878
11879    procedure Install_Private_Data_Declarations
11880      (Loc      : Source_Ptr;
11881       Spec_Id  : Entity_Id;
11882       Conc_Typ : Entity_Id;
11883       Body_Nod : Node_Id;
11884       Decls    : List_Id;
11885       Barrier  : Boolean := False;
11886       Family   : Boolean := False)
11887    is
11888       Is_Protected : constant Boolean := Is_Protected_Type (Conc_Typ);
11889       Decl         : Node_Id;
11890       Def          : Node_Id;
11891       Insert_Node  : Node_Id := Empty;
11892       Obj_Ent      : Entity_Id;
11893
11894       procedure Add (Decl : Node_Id);
11895       --  Add a single declaration after Insert_Node. If this is the first
11896       --  addition, Decl is added to the front of Decls and it becomes the
11897       --  insertion node.
11898
11899       function Replace_Bound (Bound : Node_Id) return Node_Id;
11900       --  The bounds of an entry index may depend on discriminants, create a
11901       --  reference to the corresponding prival. Otherwise return a duplicate
11902       --  of the original bound.
11903
11904       ---------
11905       -- Add --
11906       ---------
11907
11908       procedure Add (Decl : Node_Id) is
11909       begin
11910          if No (Insert_Node) then
11911             Prepend_To (Decls, Decl);
11912          else
11913             Insert_After (Insert_Node, Decl);
11914          end if;
11915
11916          Insert_Node := Decl;
11917       end Add;
11918
11919       --------------------------
11920       -- Replace_Discriminant --
11921       --------------------------
11922
11923       function Replace_Bound (Bound : Node_Id) return Node_Id is
11924       begin
11925          if Nkind (Bound) = N_Identifier
11926            and then Is_Discriminal (Entity (Bound))
11927          then
11928             return Make_Identifier (Loc, Chars (Entity (Bound)));
11929          else
11930             return Duplicate_Subexpr (Bound);
11931          end if;
11932       end Replace_Bound;
11933
11934    --  Start of processing for Install_Private_Data_Declarations
11935
11936    begin
11937       --  Step 1: Retrieve the concurrent object entity. Obj_Ent can denote
11938       --  formal parameter _O, _object or _task depending on the context.
11939
11940       Obj_Ent := Concurrent_Object (Spec_Id, Conc_Typ);
11941
11942       --  Special processing of _O for barrier functions, protected entries
11943       --  and families.
11944
11945       if Barrier
11946         or else
11947           (Is_Protected
11948              and then
11949                (Ekind (Spec_Id) = E_Entry
11950                   or else Ekind (Spec_Id) = E_Entry_Family))
11951       then
11952          declare
11953             Conc_Rec : constant Entity_Id :=
11954                          Corresponding_Record_Type (Conc_Typ);
11955             Typ_Id   : constant Entity_Id :=
11956                          Make_Defining_Identifier (Loc,
11957                            New_External_Name (Chars (Conc_Rec), 'P'));
11958          begin
11959             --  Generate:
11960             --    type prot_typVP is access prot_typV;
11961
11962             Decl :=
11963               Make_Full_Type_Declaration (Loc,
11964                 Defining_Identifier => Typ_Id,
11965                 Type_Definition     =>
11966                   Make_Access_To_Object_Definition (Loc,
11967                     Subtype_Indication =>
11968                       New_Reference_To (Conc_Rec, Loc)));
11969             Add (Decl);
11970
11971             --  Generate:
11972             --    _object : prot_typVP := prot_typV (_O);
11973
11974             Decl :=
11975               Make_Object_Declaration (Loc,
11976                 Defining_Identifier =>
11977                   Make_Defining_Identifier (Loc, Name_uObject),
11978                 Object_Definition   => New_Reference_To (Typ_Id, Loc),
11979                 Expression          =>
11980                   Unchecked_Convert_To (Typ_Id,
11981                     New_Reference_To (Obj_Ent, Loc)));
11982             Add (Decl);
11983
11984             --  Set the reference to the concurrent object
11985
11986             Obj_Ent := Defining_Identifier (Decl);
11987          end;
11988       end if;
11989
11990       --  Step 2: Create the Protection object and build its declaration for
11991       --  any protected entry (family) of subprogram.
11992
11993       if Is_Protected then
11994          declare
11995             Prot_Ent : constant Entity_Id := Make_Temporary (Loc, 'R');
11996             Prot_Typ : RE_Id;
11997
11998          begin
11999             Set_Protection_Object (Spec_Id, Prot_Ent);
12000
12001             --  Determine the proper protection type
12002
12003             if Has_Attach_Handler (Conc_Typ)
12004               and then not Restricted_Profile
12005             then
12006                Prot_Typ := RE_Static_Interrupt_Protection;
12007
12008             elsif Has_Interrupt_Handler (Conc_Typ) then
12009                Prot_Typ := RE_Dynamic_Interrupt_Protection;
12010
12011             --  The type has explicit entries or generated primitive entry
12012             --  wrappers.
12013
12014             elsif Has_Entries (Conc_Typ)
12015               or else
12016                 (Ada_Version >= Ada_2005
12017                    and then Present (Interface_List (Parent (Conc_Typ))))
12018             then
12019                case Corresponding_Runtime_Package (Conc_Typ) is
12020                   when System_Tasking_Protected_Objects_Entries =>
12021                      Prot_Typ := RE_Protection_Entries;
12022
12023                   when System_Tasking_Protected_Objects_Single_Entry =>
12024                      Prot_Typ := RE_Protection_Entry;
12025
12026                   when others =>
12027                      raise Program_Error;
12028                end case;
12029
12030             else
12031                Prot_Typ := RE_Protection;
12032             end if;
12033
12034             --  Generate:
12035             --    conc_typR : protection_typ renames _object._object;
12036
12037             Decl :=
12038               Make_Object_Renaming_Declaration (Loc,
12039                 Defining_Identifier => Prot_Ent,
12040                 Subtype_Mark =>
12041                   New_Reference_To (RTE (Prot_Typ), Loc),
12042                 Name =>
12043                   Make_Selected_Component (Loc,
12044                     Prefix        => New_Reference_To (Obj_Ent, Loc),
12045                     Selector_Name => Make_Identifier (Loc, Name_uObject)));
12046             Add (Decl);
12047          end;
12048       end if;
12049
12050       --  Step 3: Add discriminant renamings (if any)
12051
12052       if Has_Discriminants (Conc_Typ) then
12053          declare
12054             D : Entity_Id;
12055
12056          begin
12057             D := First_Discriminant (Conc_Typ);
12058             while Present (D) loop
12059
12060                --  Adjust the source location
12061
12062                Set_Sloc (Discriminal (D), Loc);
12063
12064                --  Generate:
12065                --    discr_name : discr_typ renames _object.discr_name;
12066                --      or
12067                --    discr_name : discr_typ renames _task.discr_name;
12068
12069                Decl :=
12070                  Make_Object_Renaming_Declaration (Loc,
12071                    Defining_Identifier => Discriminal (D),
12072                    Subtype_Mark        => New_Reference_To (Etype (D), Loc),
12073                    Name                =>
12074                      Make_Selected_Component (Loc,
12075                        Prefix        => New_Reference_To (Obj_Ent, Loc),
12076                        Selector_Name => Make_Identifier (Loc, Chars (D))));
12077                Add (Decl);
12078
12079                Next_Discriminant (D);
12080             end loop;
12081          end;
12082       end if;
12083
12084       --  Step 4: Add private component renamings (if any)
12085
12086       if Is_Protected then
12087          Def := Protected_Definition (Parent (Conc_Typ));
12088
12089          if Present (Private_Declarations (Def)) then
12090             declare
12091                Comp    : Node_Id;
12092                Comp_Id : Entity_Id;
12093                Decl_Id : Entity_Id;
12094
12095             begin
12096                Comp := First (Private_Declarations (Def));
12097                while Present (Comp) loop
12098                   if Nkind (Comp) = N_Component_Declaration then
12099                      Comp_Id := Defining_Identifier (Comp);
12100                      Decl_Id :=
12101                        Make_Defining_Identifier (Loc, Chars (Comp_Id));
12102
12103                      --  Minimal decoration
12104
12105                      if Ekind (Spec_Id) = E_Function then
12106                         Set_Ekind (Decl_Id, E_Constant);
12107                      else
12108                         Set_Ekind (Decl_Id, E_Variable);
12109                      end if;
12110
12111                      Set_Prival      (Comp_Id, Decl_Id);
12112                      Set_Prival_Link (Decl_Id, Comp_Id);
12113                      Set_Is_Aliased  (Decl_Id, Is_Aliased (Comp_Id));
12114
12115                      --  Generate:
12116                      --    comp_name : comp_typ renames _object.comp_name;
12117
12118                      Decl :=
12119                        Make_Object_Renaming_Declaration (Loc,
12120                          Defining_Identifier => Decl_Id,
12121                          Subtype_Mark =>
12122                            New_Reference_To (Etype (Comp_Id), Loc),
12123                          Name =>
12124                            Make_Selected_Component (Loc,
12125                              Prefix =>
12126                                New_Reference_To (Obj_Ent, Loc),
12127                              Selector_Name =>
12128                                Make_Identifier (Loc, Chars (Comp_Id))));
12129                      Add (Decl);
12130                   end if;
12131
12132                   Next (Comp);
12133                end loop;
12134             end;
12135          end if;
12136       end if;
12137
12138       --  Step 5: Add the declaration of the entry index and the associated
12139       --  type for barrier functions and entry families.
12140
12141       if (Barrier and then Family)
12142         or else Ekind (Spec_Id) = E_Entry_Family
12143       then
12144          declare
12145             E         : constant Entity_Id := Index_Object (Spec_Id);
12146             Index     : constant Entity_Id :=
12147                           Defining_Identifier (
12148                             Entry_Index_Specification (
12149                               Entry_Body_Formal_Part (Body_Nod)));
12150             Index_Con : constant Entity_Id :=
12151                           Make_Defining_Identifier (Loc, Chars (Index));
12152             High      : Node_Id;
12153             Index_Typ : Entity_Id;
12154             Low       : Node_Id;
12155
12156          begin
12157             --  Minimal decoration
12158
12159             Set_Ekind                (Index_Con, E_Constant);
12160             Set_Entry_Index_Constant (Index, Index_Con);
12161             Set_Discriminal_Link     (Index_Con, Index);
12162
12163             --  Retrieve the bounds of the entry family
12164
12165             High := Type_High_Bound (Etype (Index));
12166             Low  := Type_Low_Bound  (Etype (Index));
12167
12168             --  In the simple case the entry family is given by a subtype
12169             --  mark and the index constant has the same type.
12170
12171             if Is_Entity_Name (Original_Node (
12172                  Discrete_Subtype_Definition (Parent (Index))))
12173             then
12174                Index_Typ := Etype (Index);
12175
12176             --  Otherwise a new subtype declaration is required
12177
12178             else
12179                High := Replace_Bound (High);
12180                Low  := Replace_Bound (Low);
12181
12182                Index_Typ := Make_Temporary (Loc, 'J');
12183
12184                --  Generate:
12185                --    subtype Jnn is <Etype of Index> range Low .. High;
12186
12187                Decl :=
12188                  Make_Subtype_Declaration (Loc,
12189                    Defining_Identifier => Index_Typ,
12190                    Subtype_Indication =>
12191                      Make_Subtype_Indication (Loc,
12192                        Subtype_Mark =>
12193                          New_Reference_To (Base_Type (Etype (Index)), Loc),
12194                        Constraint =>
12195                          Make_Range_Constraint (Loc,
12196                            Range_Expression =>
12197                              Make_Range (Loc, Low, High))));
12198                Add (Decl);
12199             end if;
12200
12201             Set_Etype (Index_Con, Index_Typ);
12202
12203             --  Create the object which designates the index:
12204             --    J : constant Jnn :=
12205             --          Jnn'Val (_E - <index expr> + Jnn'Pos (Jnn'First));
12206             --
12207             --  where Jnn is the subtype created above or the original type of
12208             --  the index, _E is a formal of the protected body subprogram and
12209             --  <index expr> is the index of the first family member.
12210
12211             Decl :=
12212               Make_Object_Declaration (Loc,
12213                 Defining_Identifier => Index_Con,
12214                 Constant_Present => True,
12215                 Object_Definition =>
12216                   New_Reference_To (Index_Typ, Loc),
12217
12218                 Expression =>
12219                   Make_Attribute_Reference (Loc,
12220                     Prefix =>
12221                       New_Reference_To (Index_Typ, Loc),
12222                     Attribute_Name => Name_Val,
12223
12224                     Expressions => New_List (
12225
12226                       Make_Op_Add (Loc,
12227                         Left_Opnd =>
12228                           Make_Op_Subtract (Loc,
12229                             Left_Opnd =>
12230                               New_Reference_To (E, Loc),
12231                             Right_Opnd =>
12232                               Entry_Index_Expression (Loc,
12233                                 Defining_Identifier (Body_Nod),
12234                                 Empty, Conc_Typ)),
12235
12236                         Right_Opnd =>
12237                           Make_Attribute_Reference (Loc,
12238                             Prefix =>
12239                               New_Reference_To (Index_Typ, Loc),
12240                             Attribute_Name => Name_Pos,
12241                             Expressions => New_List (
12242                               Make_Attribute_Reference (Loc,
12243                                 Prefix =>
12244                                   New_Reference_To (Index_Typ, Loc),
12245                                 Attribute_Name => Name_First)))))));
12246             Add (Decl);
12247          end;
12248       end if;
12249    end Install_Private_Data_Declarations;
12250
12251    ---------------------------------
12252    -- Is_Potentially_Large_Family --
12253    ---------------------------------
12254
12255    function Is_Potentially_Large_Family
12256      (Base_Index : Entity_Id;
12257       Conctyp    : Entity_Id;
12258       Lo         : Node_Id;
12259       Hi         : Node_Id) return Boolean
12260    is
12261    begin
12262       return Scope (Base_Index) = Standard_Standard
12263         and then Base_Index = Base_Type (Standard_Integer)
12264         and then Has_Discriminants (Conctyp)
12265         and then Present
12266           (Discriminant_Default_Value (First_Discriminant (Conctyp)))
12267         and then
12268           (Denotes_Discriminant (Lo, True)
12269             or else Denotes_Discriminant (Hi, True));
12270    end Is_Potentially_Large_Family;
12271
12272    -------------------------------------
12273    -- Is_Private_Primitive_Subprogram --
12274    -------------------------------------
12275
12276    function Is_Private_Primitive_Subprogram (Id : Entity_Id) return Boolean is
12277    begin
12278       return
12279         (Ekind (Id) = E_Function or else Ekind (Id) = E_Procedure)
12280           and then Is_Private_Primitive (Id);
12281    end Is_Private_Primitive_Subprogram;
12282
12283    ------------------
12284    -- Index_Object --
12285    ------------------
12286
12287    function Index_Object (Spec_Id : Entity_Id) return Entity_Id is
12288       Bod_Subp : constant Entity_Id := Protected_Body_Subprogram (Spec_Id);
12289       Formal   : Entity_Id;
12290
12291    begin
12292       Formal := First_Formal (Bod_Subp);
12293       while Present (Formal) loop
12294
12295          --  Look for formal parameter _E
12296
12297          if Chars (Formal) = Name_uE then
12298             return Formal;
12299          end if;
12300
12301          Next_Formal (Formal);
12302       end loop;
12303
12304       --  A protected body subprogram should always have the parameter in
12305       --  question.
12306
12307       raise Program_Error;
12308    end Index_Object;
12309
12310    --------------------------------
12311    -- Make_Initialize_Protection --
12312    --------------------------------
12313
12314    function Make_Initialize_Protection
12315      (Protect_Rec : Entity_Id) return List_Id
12316    is
12317       Loc         : constant Source_Ptr := Sloc (Protect_Rec);
12318       P_Arr       : Entity_Id;
12319       Pdef        : Node_Id;
12320       Pdec        : Node_Id;
12321       Ptyp        : constant Node_Id :=
12322                       Corresponding_Concurrent_Type (Protect_Rec);
12323       Args        : List_Id;
12324       L           : constant List_Id := New_List;
12325       Has_Entry   : constant Boolean := Has_Entries (Ptyp);
12326       Restricted  : constant Boolean := Restricted_Profile;
12327
12328    begin
12329       --  We may need two calls to properly initialize the object, one to
12330       --  Initialize_Protection, and possibly one to Install_Handlers if we
12331       --  have a pragma Attach_Handler.
12332
12333       --  Get protected declaration. In the case of a task type declaration,
12334       --  this is simply the parent of the protected type entity. In the single
12335       --  protected object declaration, this parent will be the implicit type,
12336       --  and we can find the corresponding single protected object declaration
12337       --  by searching forward in the declaration list in the tree.
12338
12339       --  Is the test for N_Single_Protected_Declaration needed here??? Nodes
12340       --  of this type should have been removed during semantic analysis.
12341
12342       Pdec := Parent (Ptyp);
12343       while not Nkind_In (Pdec, N_Protected_Type_Declaration,
12344                                 N_Single_Protected_Declaration)
12345       loop
12346          Next (Pdec);
12347       end loop;
12348
12349       --  Now we can find the object definition from this declaration
12350
12351       Pdef := Protected_Definition (Pdec);
12352
12353       --  Build the parameter list for the call. Note that _Init is the name
12354       --  of the formal for the object to be initialized, which is the task
12355       --  value record itself.
12356
12357       Args := New_List;
12358
12359       --  Object parameter. This is a pointer to the object of type
12360       --  Protection used by the GNARL to control the protected object.
12361
12362       Append_To (Args,
12363         Make_Attribute_Reference (Loc,
12364           Prefix =>
12365             Make_Selected_Component (Loc,
12366               Prefix        => Make_Identifier (Loc, Name_uInit),
12367               Selector_Name => Make_Identifier (Loc, Name_uObject)),
12368           Attribute_Name => Name_Unchecked_Access));
12369
12370       --  Priority parameter. Set to Unspecified_Priority unless there is a
12371       --  priority pragma, in which case we take the value from the pragma,
12372       --  or there is an interrupt pragma and no priority pragma, and we
12373       --  set the ceiling to Interrupt_Priority'Last, an implementation-
12374       --  defined value, see D.3(10).
12375
12376       if Present (Pdef)
12377         and then Has_Pragma_Priority (Pdef)
12378       then
12379          declare
12380             Prio : constant Node_Id :=
12381                      Expression
12382                        (First
12383                           (Pragma_Argument_Associations
12384                              (Find_Task_Or_Protected_Pragma
12385                                 (Pdef, Name_Priority))));
12386             Temp : Entity_Id;
12387
12388          begin
12389             --  If priority is a static expression, then we can duplicate it
12390             --  with no problem and simply append it to the argument list.
12391
12392             if Is_Static_Expression (Prio) then
12393                Append_To (Args,
12394                           Duplicate_Subexpr_No_Checks (Prio));
12395
12396             --  Otherwise, the priority may be a per-object expression, if it
12397             --  depends on a discriminant of the type. In this case, create
12398             --  local variable to capture the expression. Note that it is
12399             --  really necessary to create this variable explicitly. It might
12400             --  be thought that removing side effects would the appropriate
12401             --  approach, but that could generate declarations improperly
12402             --  placed in the enclosing scope.
12403
12404             --  Note: Use System.Any_Priority as the expected type for the
12405             --  non-static priority expression, in case the expression has not
12406             --  been analyzed yet (as occurs for example with pragma
12407             --  Interrupt_Priority).
12408
12409             else
12410                Temp := Make_Temporary (Loc, 'R', Prio);
12411                Append_To (L,
12412                   Make_Object_Declaration (Loc,
12413                      Defining_Identifier => Temp,
12414                      Object_Definition   =>
12415                        New_Occurrence_Of (RTE (RE_Any_Priority), Loc),
12416                      Expression          => Relocate_Node (Prio)));
12417
12418                Append_To (Args, New_Occurrence_Of (Temp, Loc));
12419             end if;
12420          end;
12421
12422       --  When no priority is specified but an xx_Handler pragma is, we default
12423       --  to System.Interrupts.Default_Interrupt_Priority, see D.3(10).
12424
12425       elsif Has_Interrupt_Handler (Ptyp)
12426         or else Has_Attach_Handler (Ptyp)
12427       then
12428          Append_To (Args,
12429            New_Reference_To (RTE (RE_Default_Interrupt_Priority), Loc));
12430
12431       --  Normal case, no priority or xx_Handler specified, default priority
12432
12433       else
12434          Append_To (Args,
12435            New_Reference_To (RTE (RE_Unspecified_Priority), Loc));
12436       end if;
12437
12438       --  Test for Compiler_Info parameter. This parameter allows entry body
12439       --  procedures and barrier functions to be called from the runtime. It
12440       --  is a pointer to the record generated by the compiler to represent
12441       --  the protected object.
12442
12443       --  A protected type without entries that covers an interface and
12444       --  overrides the abstract routines with protected procedures is
12445       --  considered equivalent to a protected type with entries in the
12446       --  context of dispatching select statements.
12447
12448       if Has_Entry
12449         or else Has_Interrupt_Handler (Ptyp)
12450         or else Has_Attach_Handler (Ptyp)
12451         or else Has_Interfaces (Protect_Rec)
12452       then
12453          declare
12454             Pkg_Id      : constant RTU_Id  :=
12455                             Corresponding_Runtime_Package (Ptyp);
12456             Called_Subp : RE_Id;
12457
12458          begin
12459             case Pkg_Id is
12460                when System_Tasking_Protected_Objects_Entries =>
12461                   Called_Subp := RE_Initialize_Protection_Entries;
12462
12463                when System_Tasking_Protected_Objects =>
12464                   Called_Subp := RE_Initialize_Protection;
12465
12466                when System_Tasking_Protected_Objects_Single_Entry =>
12467                   Called_Subp := RE_Initialize_Protection_Entry;
12468
12469                when others =>
12470                   raise Program_Error;
12471             end case;
12472
12473             if Has_Entry
12474               or else not Restricted
12475               or else Has_Interfaces (Protect_Rec)
12476             then
12477                Append_To (Args,
12478                  Make_Attribute_Reference (Loc,
12479                    Prefix         => Make_Identifier (Loc, Name_uInit),
12480                    Attribute_Name => Name_Address));
12481             end if;
12482
12483             --  Entry_Bodies parameter. This is a pointer to an array of
12484             --  pointers to the entry body procedures and barrier functions of
12485             --  the object. If the protected type has no entries this object
12486             --  will not exist, in this case, pass a null.
12487
12488             if Has_Entry then
12489                P_Arr := Entry_Bodies_Array (Ptyp);
12490
12491                Append_To (Args,
12492                  Make_Attribute_Reference (Loc,
12493                    Prefix => New_Reference_To (P_Arr, Loc),
12494                    Attribute_Name => Name_Unrestricted_Access));
12495
12496                if Pkg_Id = System_Tasking_Protected_Objects_Entries then
12497
12498                   --  Find index mapping function (clumsy but ok for now)
12499
12500                   while Ekind (P_Arr) /= E_Function loop
12501                      Next_Entity (P_Arr);
12502                   end loop;
12503
12504                   Append_To (Args,
12505                     Make_Attribute_Reference (Loc,
12506                       Prefix =>
12507                         New_Reference_To (P_Arr, Loc),
12508                       Attribute_Name => Name_Unrestricted_Access));
12509
12510                   --  Build_Entry_Names generation flag. When set to true, the
12511                   --  runtime will allocate an array to hold the string names
12512                   --  of protected entries.
12513
12514                   if not Restricted_Profile then
12515                      if Entry_Names_OK then
12516                         Append_To (Args,
12517                           New_Reference_To (Standard_True, Loc));
12518                      else
12519                         Append_To (Args,
12520                           New_Reference_To (Standard_False, Loc));
12521                      end if;
12522                   end if;
12523                end if;
12524
12525             elsif Pkg_Id = System_Tasking_Protected_Objects_Single_Entry then
12526                Append_To (Args, Make_Null (Loc));
12527
12528             elsif Pkg_Id = System_Tasking_Protected_Objects_Entries then
12529                Append_To (Args, Make_Null (Loc));
12530                Append_To (Args, Make_Null (Loc));
12531                Append_To (Args, New_Reference_To (Standard_False, Loc));
12532             end if;
12533
12534             Append_To (L,
12535               Make_Procedure_Call_Statement (Loc,
12536                 Name => New_Reference_To (RTE (Called_Subp), Loc),
12537                 Parameter_Associations => Args));
12538          end;
12539       else
12540          Append_To (L,
12541            Make_Procedure_Call_Statement (Loc,
12542              Name => New_Reference_To (RTE (RE_Initialize_Protection), Loc),
12543              Parameter_Associations => Args));
12544       end if;
12545
12546       if Has_Attach_Handler (Ptyp) then
12547
12548          --  We have a list of N Attach_Handler (ProcI, ExprI), and we have to
12549          --  make the following call:
12550
12551          --  Install_Handlers (_object,
12552          --    ((Expr1, Proc1'access), ...., (ExprN, ProcN'access));
12553
12554          --  or, in the case of Ravenscar:
12555
12556          --  Install_Restricted_Handlers
12557          --    ((Expr1, Proc1'access), ...., (ExprN, ProcN'access));
12558
12559          declare
12560             Args  : constant List_Id := New_List;
12561             Table : constant List_Id := New_List;
12562             Ritem : Node_Id          := First_Rep_Item (Ptyp);
12563
12564          begin
12565             --  Build the Attach_Handler table argument
12566
12567             while Present (Ritem) loop
12568                if Nkind (Ritem) = N_Pragma
12569                  and then Pragma_Name (Ritem) = Name_Attach_Handler
12570                then
12571                   declare
12572                      Handler : constant Node_Id :=
12573                                  First (Pragma_Argument_Associations (Ritem));
12574
12575                      Interrupt : constant Node_Id := Next (Handler);
12576                      Expr      : constant Node_Id := Expression (Interrupt);
12577
12578                   begin
12579                      Append_To (Table,
12580                        Make_Aggregate (Loc, Expressions => New_List (
12581                          Unchecked_Convert_To
12582                           (RTE (RE_System_Interrupt_Id), Expr),
12583                          Make_Attribute_Reference (Loc,
12584                            Prefix => Make_Selected_Component (Loc,
12585                               Make_Identifier (Loc, Name_uInit),
12586                               Duplicate_Subexpr_No_Checks
12587                                 (Expression (Handler))),
12588                            Attribute_Name => Name_Access))));
12589                   end;
12590                end if;
12591
12592                Next_Rep_Item (Ritem);
12593             end loop;
12594
12595             --  Append the table argument we just built
12596
12597             Append_To (Args, Make_Aggregate (Loc, Table));
12598
12599             --  Append the Install_Handlers (or Install_Restricted_Handlers)
12600             --  call to the statements.
12601
12602             if Restricted then
12603                --  Call a simplified version of Install_Handlers to be used
12604                --  when the Ravenscar restrictions are in effect
12605                --  (Install_Restricted_Handlers).
12606
12607                Append_To (L,
12608                  Make_Procedure_Call_Statement (Loc,
12609                    Name =>
12610                      New_Reference_To
12611                         (RTE (RE_Install_Restricted_Handlers), Loc),
12612                    Parameter_Associations => Args));
12613
12614             else
12615                --  First, prepends the _object argument
12616
12617                Prepend_To (Args,
12618                  Make_Attribute_Reference (Loc,
12619                    Prefix =>
12620                      Make_Selected_Component (Loc,
12621                        Prefix        => Make_Identifier (Loc, Name_uInit),
12622                        Selector_Name => Make_Identifier (Loc, Name_uObject)),
12623                    Attribute_Name => Name_Unchecked_Access));
12624
12625                --  Then, insert call to Install_Handlers
12626
12627                Append_To (L,
12628                  Make_Procedure_Call_Statement (Loc,
12629                    Name => New_Reference_To (RTE (RE_Install_Handlers), Loc),
12630                    Parameter_Associations => Args));
12631             end if;
12632          end;
12633       end if;
12634
12635       return L;
12636    end Make_Initialize_Protection;
12637
12638    ---------------------------
12639    -- Make_Task_Create_Call --
12640    ---------------------------
12641
12642    function Make_Task_Create_Call (Task_Rec : Entity_Id) return Node_Id is
12643       Loc    : constant Source_Ptr := Sloc (Task_Rec);
12644       Args   : List_Id;
12645       Ecount : Node_Id;
12646       Name   : Node_Id;
12647       Tdec   : Node_Id;
12648       Tdef   : Node_Id;
12649       Tnam   : Name_Id;
12650       Ttyp   : Node_Id;
12651
12652    begin
12653       Ttyp := Corresponding_Concurrent_Type (Task_Rec);
12654       Tnam := Chars (Ttyp);
12655
12656       --  Get task declaration. In the case of a task type declaration, this is
12657       --  simply the parent of the task type entity. In the single task
12658       --  declaration, this parent will be the implicit type, and we can find
12659       --  the corresponding single task declaration by searching forward in the
12660       --  declaration list in the tree.
12661
12662       --  Is the test for N_Single_Task_Declaration needed here??? Nodes of
12663       --  this type should have been removed during semantic analysis.
12664
12665       Tdec := Parent (Ttyp);
12666       while not Nkind_In (Tdec, N_Task_Type_Declaration,
12667                                 N_Single_Task_Declaration)
12668       loop
12669          Next (Tdec);
12670       end loop;
12671
12672       --  Now we can find the task definition from this declaration
12673
12674       Tdef := Task_Definition (Tdec);
12675
12676       --  Build the parameter list for the call. Note that _Init is the name
12677       --  of the formal for the object to be initialized, which is the task
12678       --  value record itself.
12679
12680       Args := New_List;
12681
12682       --  Priority parameter. Set to Unspecified_Priority unless there is a
12683       --  priority pragma, in which case we take the value from the pragma.
12684
12685       if Present (Tdef) and then Has_Pragma_Priority (Tdef) then
12686          Append_To (Args,
12687            Make_Selected_Component (Loc,
12688              Prefix        => Make_Identifier (Loc, Name_uInit),
12689              Selector_Name => Make_Identifier (Loc, Name_uPriority)));
12690       else
12691          Append_To (Args,
12692            New_Reference_To (RTE (RE_Unspecified_Priority), Loc));
12693       end if;
12694
12695       --  Optional Stack parameter
12696
12697       if Restricted_Profile then
12698
12699          --  If the stack has been preallocated by the expander then
12700          --  pass its address. Otherwise, pass a null address.
12701
12702          if Preallocated_Stacks_On_Target then
12703             Append_To (Args,
12704               Make_Attribute_Reference (Loc,
12705                 Prefix         =>
12706                   Make_Selected_Component (Loc,
12707                     Prefix        => Make_Identifier (Loc, Name_uInit),
12708                     Selector_Name => Make_Identifier (Loc, Name_uStack)),
12709                 Attribute_Name => Name_Address));
12710
12711          else
12712             Append_To (Args,
12713               New_Reference_To (RTE (RE_Null_Address), Loc));
12714          end if;
12715       end if;
12716
12717       --  Size parameter. If no Storage_Size pragma is present, then
12718       --  the size is taken from the taskZ variable for the type, which
12719       --  is either Unspecified_Size, or has been reset by the use of
12720       --  a Storage_Size attribute definition clause. If a pragma is
12721       --  present, then the size is taken from the _Size field of the
12722       --  task value record, which was set from the pragma value.
12723
12724       if Present (Tdef)
12725         and then Has_Storage_Size_Pragma (Tdef)
12726       then
12727          Append_To (Args,
12728            Make_Selected_Component (Loc,
12729              Prefix        => Make_Identifier (Loc, Name_uInit),
12730              Selector_Name => Make_Identifier (Loc, Name_uSize)));
12731
12732       else
12733          Append_To (Args,
12734            New_Reference_To (Storage_Size_Variable (Ttyp), Loc));
12735       end if;
12736
12737       --  Task_Info parameter. Set to Unspecified_Task_Info unless there is a
12738       --  Task_Info pragma, in which case we take the value from the pragma.
12739
12740       if Present (Tdef)
12741         and then Has_Task_Info_Pragma (Tdef)
12742       then
12743          Append_To (Args,
12744            Make_Selected_Component (Loc,
12745              Prefix        => Make_Identifier (Loc, Name_uInit),
12746              Selector_Name => Make_Identifier (Loc, Name_uTask_Info)));
12747
12748       else
12749          Append_To (Args,
12750            New_Reference_To (RTE (RE_Unspecified_Task_Info), Loc));
12751       end if;
12752
12753       --  CPU parameter. Set to Unspecified_CPU unless there is a CPU pragma,
12754       --  in which case we take the value from the pragma. The parameter is
12755       --  passed as an Integer because in the case of unspecified CPU the
12756       --  value is not in the range of CPU_Range.
12757
12758       if Present (Tdef) and then Has_Pragma_CPU (Tdef) then
12759          Append_To (Args,
12760            Convert_To (Standard_Integer,
12761              Make_Selected_Component (Loc,
12762                Prefix        => Make_Identifier (Loc, Name_uInit),
12763                Selector_Name => Make_Identifier (Loc, Name_uCPU))));
12764
12765       else
12766          Append_To (Args,
12767            New_Reference_To (RTE (RE_Unspecified_CPU), Loc));
12768       end if;
12769
12770       if not Restricted_Profile then
12771
12772          --  Deadline parameter. If no Relative_Deadline pragma is present,
12773          --  then the deadline is Time_Span_Zero. If a pragma is present, then
12774          --  the deadline is taken from the _Relative_Deadline field of the
12775          --  task value record, which was set from the pragma value. Note that
12776          --  this parameter must not be generated for the restricted profiles
12777          --  since Ravenscar does not allow deadlines.
12778
12779          --  Case where pragma Relative_Deadline applies: use given value
12780
12781          if Present (Tdef) and then Has_Relative_Deadline_Pragma (Tdef) then
12782             Append_To (Args,
12783               Make_Selected_Component (Loc,
12784                 Prefix        =>
12785                   Make_Identifier (Loc, Name_uInit),
12786                 Selector_Name =>
12787                   Make_Identifier (Loc, Name_uRelative_Deadline)));
12788
12789          --  No pragma Relative_Deadline apply to the task
12790
12791          else
12792             Append_To (Args,
12793               New_Reference_To (RTE (RE_Time_Span_Zero), Loc));
12794          end if;
12795
12796          --  Number of entries. This is an expression of the form:
12797
12798          --    n + _Init.a'Length + _Init.a'B'Length + ...
12799
12800          --  where a,b... are the entry family names for the task definition
12801
12802          Ecount :=
12803            Build_Entry_Count_Expression
12804              (Ttyp,
12805               Component_Items
12806                 (Component_List
12807                    (Type_Definition
12808                       (Parent (Corresponding_Record_Type (Ttyp))))),
12809               Loc);
12810          Append_To (Args, Ecount);
12811
12812          --  Master parameter. This is a reference to the _Master parameter of
12813          --  the initialization procedure, except in the case of the pragma
12814          --  Restrictions (No_Task_Hierarchy) where the value is fixed to
12815          --  System.Tasking.Library_Task_Level.
12816
12817          if Restriction_Active (No_Task_Hierarchy) = False then
12818             Append_To (Args, Make_Identifier (Loc, Name_uMaster));
12819          else
12820             Append_To (Args,
12821               New_Occurrence_Of (RTE (RE_Library_Task_Level), Loc));
12822          end if;
12823       end if;
12824
12825       --  State parameter. This is a pointer to the task body procedure. The
12826       --  required value is obtained by taking 'Unrestricted_Access of the task
12827       --  body procedure and converting it (with an unchecked conversion) to
12828       --  the type required by the task kernel. For further details, see the
12829       --  description of Expand_N_Task_Body. We use 'Unrestricted_Access rather
12830       --  than 'Address in order to avoid creating trampolines.
12831
12832       declare
12833          Body_Proc    : constant Node_Id := Get_Task_Body_Procedure (Ttyp);
12834          Subp_Ptr_Typ : constant Node_Id :=
12835                           Create_Itype (E_Access_Subprogram_Type, Tdec);
12836          Ref          : constant Node_Id := Make_Itype_Reference (Loc);
12837
12838       begin
12839          Set_Directly_Designated_Type (Subp_Ptr_Typ, Body_Proc);
12840          Set_Etype (Subp_Ptr_Typ, Subp_Ptr_Typ);
12841
12842          --  Be sure to freeze a reference to the access-to-subprogram type,
12843          --  otherwise gigi will complain that it's in the wrong scope, because
12844          --  it's actually inside the init procedure for the record type that
12845          --  corresponds to the task type.
12846
12847          --  This processing is causing a crash in the .NET/JVM back ends that
12848          --  is not yet understood, so skip it in these cases ???
12849
12850          if VM_Target = No_VM then
12851             Set_Itype (Ref, Subp_Ptr_Typ);
12852             Append_Freeze_Action (Task_Rec, Ref);
12853
12854             Append_To (Args,
12855               Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
12856                 Make_Qualified_Expression (Loc,
12857                   Subtype_Mark => New_Reference_To (Subp_Ptr_Typ, Loc),
12858                   Expression   =>
12859                     Make_Attribute_Reference (Loc,
12860                       Prefix =>
12861                         New_Occurrence_Of (Body_Proc, Loc),
12862                       Attribute_Name => Name_Unrestricted_Access))));
12863
12864          --  For the .NET/JVM cases revert to the original code below ???
12865
12866          else
12867             Append_To (Args,
12868               Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
12869                 Make_Attribute_Reference (Loc,
12870                   Prefix =>
12871                     New_Occurrence_Of (Body_Proc, Loc),
12872                   Attribute_Name => Name_Address)));
12873          end if;
12874       end;
12875
12876       --  Discriminants parameter. This is just the address of the task
12877       --  value record itself (which contains the discriminant values
12878
12879       Append_To (Args,
12880         Make_Attribute_Reference (Loc,
12881           Prefix => Make_Identifier (Loc, Name_uInit),
12882           Attribute_Name => Name_Address));
12883
12884       --  Elaborated parameter. This is an access to the elaboration Boolean
12885
12886       Append_To (Args,
12887         Make_Attribute_Reference (Loc,
12888           Prefix => Make_Identifier (Loc, New_External_Name (Tnam, 'E')),
12889           Attribute_Name => Name_Unchecked_Access));
12890
12891       --  Chain parameter. This is a reference to the _Chain parameter of
12892       --  the initialization procedure.
12893
12894       Append_To (Args, Make_Identifier (Loc, Name_uChain));
12895
12896       --  Task name parameter. Take this from the _Task_Id parameter to the
12897       --  init call unless there is a Task_Name pragma, in which case we take
12898       --  the value from the pragma.
12899
12900       if Present (Tdef)
12901         and then Has_Task_Name_Pragma (Tdef)
12902       then
12903          --  Copy expression in full, because it may be dynamic and have
12904          --  side effects.
12905
12906          Append_To (Args,
12907            New_Copy_Tree
12908              (Expression (First
12909                            (Pragma_Argument_Associations
12910                              (Find_Task_Or_Protected_Pragma
12911                                (Tdef, Name_Task_Name))))));
12912
12913       else
12914          Append_To (Args, Make_Identifier (Loc, Name_uTask_Name));
12915       end if;
12916
12917       --  Created_Task parameter. This is the _Task_Id field of the task
12918       --  record value
12919
12920       Append_To (Args,
12921         Make_Selected_Component (Loc,
12922           Prefix        => Make_Identifier (Loc, Name_uInit),
12923           Selector_Name => Make_Identifier (Loc, Name_uTask_Id)));
12924
12925       --  Build_Entry_Names generation flag. When set to true, the runtime
12926       --  will allocate an array to hold the string names of task entries.
12927
12928       if not Restricted_Profile then
12929          if Has_Entries (Ttyp)
12930            and then Entry_Names_OK
12931          then
12932             Append_To (Args, New_Reference_To (Standard_True, Loc));
12933          else
12934             Append_To (Args, New_Reference_To (Standard_False, Loc));
12935          end if;
12936       end if;
12937
12938       if Restricted_Profile then
12939          Name := New_Reference_To (RTE (RE_Create_Restricted_Task), Loc);
12940       else
12941          Name := New_Reference_To (RTE (RE_Create_Task), Loc);
12942       end if;
12943
12944       return
12945         Make_Procedure_Call_Statement (Loc,
12946           Name => Name,
12947           Parameter_Associations => Args);
12948    end Make_Task_Create_Call;
12949
12950    ------------------------------
12951    -- Next_Protected_Operation --
12952    ------------------------------
12953
12954    function Next_Protected_Operation (N : Node_Id) return Node_Id is
12955       Next_Op : Node_Id;
12956
12957    begin
12958       Next_Op := Next (N);
12959       while Present (Next_Op)
12960         and then not Nkind_In (Next_Op, N_Subprogram_Body, N_Entry_Body)
12961       loop
12962          Next (Next_Op);
12963       end loop;
12964
12965       return Next_Op;
12966    end Next_Protected_Operation;
12967
12968    ---------------------
12969    -- Null_Statements --
12970    ---------------------
12971
12972    function Null_Statements (Stats : List_Id) return Boolean is
12973       Stmt : Node_Id;
12974
12975    begin
12976       Stmt := First (Stats);
12977       while Nkind (Stmt) /= N_Empty
12978         and then (Nkind_In (Stmt, N_Null_Statement, N_Label)
12979                     or else
12980                       (Nkind (Stmt) = N_Pragma
12981                          and then (Pragma_Name (Stmt) = Name_Unreferenced
12982                                      or else
12983                                    Pragma_Name (Stmt) = Name_Unmodified
12984                                      or else
12985                                    Pragma_Name (Stmt) = Name_Warnings)))
12986       loop
12987          Next (Stmt);
12988       end loop;
12989
12990       return Nkind (Stmt) = N_Empty;
12991    end Null_Statements;
12992
12993    --------------------------
12994    -- Parameter_Block_Pack --
12995    --------------------------
12996
12997    function Parameter_Block_Pack
12998      (Loc     : Source_Ptr;
12999       Blk_Typ : Entity_Id;
13000       Actuals : List_Id;
13001       Formals : List_Id;
13002       Decls   : List_Id;
13003       Stmts   : List_Id) return Node_Id
13004    is
13005       Actual    : Entity_Id;
13006       Expr      : Node_Id := Empty;
13007       Formal    : Entity_Id;
13008       Has_Param : Boolean := False;
13009       P         : Entity_Id;
13010       Params    : List_Id;
13011       Temp_Asn  : Node_Id;
13012       Temp_Nam  : Node_Id;
13013
13014    begin
13015       Actual := First (Actuals);
13016       Formal := Defining_Identifier (First (Formals));
13017       Params := New_List;
13018
13019       while Present (Actual) loop
13020          if Is_By_Copy_Type (Etype (Actual)) then
13021             --  Generate:
13022             --    Jnn : aliased <formal-type>
13023
13024             Temp_Nam := Make_Temporary (Loc, 'J');
13025
13026             Append_To (Decls,
13027               Make_Object_Declaration (Loc,
13028                 Aliased_Present =>
13029                   True,
13030                 Defining_Identifier =>
13031                   Temp_Nam,
13032                 Object_Definition =>
13033                   New_Reference_To (Etype (Formal), Loc)));
13034
13035             if Ekind (Formal) /= E_Out_Parameter then
13036
13037                --  Generate:
13038                --    Jnn := <actual>
13039
13040                Temp_Asn :=
13041                  New_Reference_To (Temp_Nam, Loc);
13042
13043                Set_Assignment_OK (Temp_Asn);
13044
13045                Append_To (Stmts,
13046                  Make_Assignment_Statement (Loc,
13047                    Name =>
13048                      Temp_Asn,
13049                    Expression =>
13050                      New_Copy_Tree (Actual)));
13051             end if;
13052
13053             --  Generate:
13054             --    Jnn'unchecked_access
13055
13056             Append_To (Params,
13057               Make_Attribute_Reference (Loc,
13058                 Attribute_Name =>
13059                   Name_Unchecked_Access,
13060                 Prefix =>
13061                   New_Reference_To (Temp_Nam, Loc)));
13062
13063             Has_Param := True;
13064
13065          --  The controlling parameter is omitted
13066
13067          else
13068             if not Is_Controlling_Actual (Actual) then
13069                Append_To (Params,
13070                  Make_Reference (Loc, New_Copy_Tree (Actual)));
13071
13072                Has_Param := True;
13073             end if;
13074          end if;
13075
13076          Next_Actual (Actual);
13077          Next_Formal_With_Extras (Formal);
13078       end loop;
13079
13080       if Has_Param then
13081          Expr := Make_Aggregate (Loc, Params);
13082       end if;
13083
13084       --  Generate:
13085       --    P : Ann := (
13086       --      J1'unchecked_access;
13087       --      <actual2>'reference;
13088       --      ...);
13089
13090       P := Make_Temporary (Loc, 'P');
13091
13092       Append_To (Decls,
13093         Make_Object_Declaration (Loc,
13094           Defining_Identifier =>
13095             P,
13096           Object_Definition =>
13097             New_Reference_To (Blk_Typ, Loc),
13098           Expression =>
13099             Expr));
13100
13101       return P;
13102    end Parameter_Block_Pack;
13103
13104    ----------------------------
13105    -- Parameter_Block_Unpack --
13106    ----------------------------
13107
13108    function Parameter_Block_Unpack
13109      (Loc     : Source_Ptr;
13110       P       : Entity_Id;
13111       Actuals : List_Id;
13112       Formals : List_Id) return List_Id
13113    is
13114       Actual    : Entity_Id;
13115       Asnmt     : Node_Id;
13116       Formal    : Entity_Id;
13117       Has_Asnmt : Boolean := False;
13118       Result    : constant List_Id := New_List;
13119
13120    begin
13121       Actual := First (Actuals);
13122       Formal := Defining_Identifier (First (Formals));
13123       while Present (Actual) loop
13124          if Is_By_Copy_Type (Etype (Actual))
13125            and then Ekind (Formal) /= E_In_Parameter
13126          then
13127             --  Generate:
13128             --    <actual> := P.<formal>;
13129
13130             Asnmt :=
13131               Make_Assignment_Statement (Loc,
13132                 Name =>
13133                   New_Copy (Actual),
13134                 Expression =>
13135                   Make_Explicit_Dereference (Loc,
13136                     Make_Selected_Component (Loc,
13137                       Prefix        =>
13138                         New_Reference_To (P, Loc),
13139                       Selector_Name =>
13140                         Make_Identifier (Loc, Chars (Formal)))));
13141
13142             Set_Assignment_OK (Name (Asnmt));
13143             Append_To (Result, Asnmt);
13144
13145             Has_Asnmt := True;
13146          end if;
13147
13148          Next_Actual (Actual);
13149          Next_Formal_With_Extras (Formal);
13150       end loop;
13151
13152       if Has_Asnmt then
13153          return Result;
13154       else
13155          return New_List (Make_Null_Statement (Loc));
13156       end if;
13157    end Parameter_Block_Unpack;
13158
13159    ----------------------
13160    -- Set_Discriminals --
13161    ----------------------
13162
13163    procedure Set_Discriminals (Dec : Node_Id) is
13164       D       : Entity_Id;
13165       Pdef    : Entity_Id;
13166       D_Minal : Entity_Id;
13167
13168    begin
13169       pragma Assert (Nkind (Dec) = N_Protected_Type_Declaration);
13170       Pdef := Defining_Identifier (Dec);
13171
13172       if Has_Discriminants (Pdef) then
13173          D := First_Discriminant (Pdef);
13174          while Present (D) loop
13175             D_Minal :=
13176               Make_Defining_Identifier (Sloc (D),
13177                 Chars => New_External_Name (Chars (D), 'D'));
13178
13179             Set_Ekind (D_Minal, E_Constant);
13180             Set_Etype (D_Minal, Etype (D));
13181             Set_Scope (D_Minal, Pdef);
13182             Set_Discriminal (D, D_Minal);
13183             Set_Discriminal_Link (D_Minal, D);
13184
13185             Next_Discriminant (D);
13186          end loop;
13187       end if;
13188    end Set_Discriminals;
13189
13190    -----------------------
13191    -- Trivial_Accept_OK --
13192    -----------------------
13193
13194    function Trivial_Accept_OK return Boolean is
13195    begin
13196       case Opt.Task_Dispatching_Policy is
13197
13198          --  If we have the default task dispatching policy in effect, we can
13199          --  definitely do the optimization (one way of looking at this is to
13200          --  think of the formal definition of the default policy being allowed
13201          --  to run any task it likes after a rendezvous, so even if notionally
13202          --  a full rescheduling occurs, we can say that our dispatching policy
13203          --  (i.e. the default dispatching policy) reorders the queue to be the
13204          --  same as just before the call.
13205
13206          when ' ' =>
13207             return True;
13208
13209          --  FIFO_Within_Priorities certainly does not permit this
13210          --  optimization since the Rendezvous is a scheduling action that may
13211          --  require some other task to be run.
13212
13213          when 'F' =>
13214             return False;
13215
13216          --  For now, disallow the optimization for all other policies. This
13217          --  may be over-conservative, but it is certainly not incorrect.
13218
13219          when others =>
13220             return False;
13221
13222       end case;
13223    end Trivial_Accept_OK;
13224
13225 end Exp_Ch9;