OSDN Git Service

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