OSDN Git Service

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