OSDN Git Service

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