OSDN Git Service

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