OSDN Git Service

2008-04-08 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch9.adb
index 75b9b80..b999bfa 100644 (file)
@@ -6,18 +6,17 @@
 --                                                                          --
 --                                 B o d y                                  --
 --                                                                          --
---          Copyright (C) 1992-2006, Free Software Foundation, Inc.         --
+--          Copyright (C) 1992-2008, Free Software Foundation, Inc.         --
 --                                                                          --
 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
 -- terms of the  GNU General Public License as published  by the Free Soft- --
--- ware  Foundation;  either version 2,  or (at your option) any later ver- --
+-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
 -- for  more details.  You should have  received  a copy of the GNU General --
--- Public License  distributed with GNAT;  see file COPYING.  If not, write --
--- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
--- Boston, MA 02110-1301, USA.                                              --
+-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
+-- http://www.gnu.org/licenses for a complete copy of the license.          --
 --                                                                          --
 -- GNAT was originally developed  by the GNAT team at  New York University. --
 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
@@ -39,6 +38,7 @@ with Exp_Tss;  use Exp_Tss;
 with Exp_Util; use Exp_Util;
 with Freeze;   use Freeze;
 with Hostparm;
+with Itypes;   use Itypes;
 with Namet;    use Namet;
 with Nlists;   use Nlists;
 with Nmake;    use Nmake;
@@ -81,28 +81,27 @@ package body Exp_Ch9 is
       Ent   : Entity_Id;
       Index : Node_Id;
       Tsk   : Entity_Id) return Node_Id;
-   --  Compute the index position for an entry call. Tsk is the target
-   --  task. If the bounds of some entry family depend on discriminants,
-   --  the expression computed by this function uses the discriminants
-   --  of the target task.
+   --  Compute the index position for an entry call. Tsk is the target task. If
+   --  the bounds of some entry family depend on discriminants, the expression
+   --  computed by this function uses the discriminants of the target task.
 
    procedure Add_Object_Pointer
-     (Decls : List_Id;
-      Pid   : Entity_Id;
-      Loc   : Source_Ptr);
-   --  Prepend an object pointer declaration to the declaration list
-   --  Decls. This object pointer is initialized to a type conversion
-   --  of the System.Address pointer passed to entry barrier functions
-   --  and entry body procedures.
+     (Loc      : Source_Ptr;
+      Conc_Typ : Entity_Id;
+      Decls    : List_Id);
+   --  Prepend an object pointer declaration to the declaration list Decls.
+   --  This object pointer is initialized to a type conversion of the System.
+   --  Address pointer passed to entry barrier functions and entry body
+   --  procedures.
 
    procedure Add_Formal_Renamings
      (Spec  : Node_Id;
       Decls : List_Id;
       Ent   : Entity_Id;
       Loc   : Source_Ptr);
-   --  Create renaming declarations for the formals, inside the procedure
-   --  that implements an entry body. The renamings make the original names
-   --  of the formals accessible to gdb, and serve no other purpose.
+   --  Create renaming declarations for the formals, inside the procedure that
+   --  implements an entry body. The renamings make the original names of the
+   --  formals accessible to gdb, and serve no other purpose.
    --    Spec is the specification of the procedure being built.
    --    Decls is the list of declarations to be enhanced.
    --    Ent is the entity for the original entry body.
@@ -120,18 +119,10 @@ package body Exp_Ch9 is
    --  for the specified entry body.
 
    function Build_Barrier_Function_Specification
-     (Def_Id : Entity_Id;
-      Loc    : Source_Ptr) return Node_Id;
-   --  Build a specification for a function implementing
-   --  the protected entry barrier of the specified entry body.
-
-   function Build_Corresponding_Record
-     (N    : Node_Id;
-      Ctyp : Node_Id;
-      Loc  : Source_Ptr) return Node_Id;
-   --  Common to tasks and protected types. Copy discriminant specifications,
-   --  build record declaration. N is the type declaration, Ctyp is the
-   --  concurrent entity (task type or protected type).
+     (Loc    : Source_Ptr;
+      Def_Id : Entity_Id) return Node_Id;
+   --  Build a specification for a function implementing the protected entry
+   --  barrier of the specified entry body.
 
    function Build_Entry_Count_Expression
      (Concurrent_Type : Node_Id;
@@ -148,7 +139,7 @@ package body Exp_Ch9 is
       Formals : List_Id;
       Decls   : List_Id) return Entity_Id;
    --  Generate an access type for each actual parameter in the list Actuals.
-   --  Cleate an encapsulating record that contains all the actuals and return
+   --  Create an encapsulating record that contains all the actuals and return
    --  its type. Generate:
    --    type Ann1 is access all <actual1-type>
    --    ...
@@ -197,17 +188,29 @@ package body Exp_Ch9 is
      (N   : Node_Id;
       Ent : Entity_Id;
       Pid : Node_Id) return Node_Id;
-   --  Build the procedure implementing the statement sequence of
-   --  the specified entry body.
+   --  Build the procedure implementing the statement sequence of the specified
+   --  entry body.
 
    function Build_Protected_Entry_Specification
-     (Def_Id : Entity_Id;
-      Ent_Id : Entity_Id;
-      Loc    : Source_Ptr) return Node_Id;
-   --  Build a specification for a procedure implementing
-   --  the statement sequence of the specified entry body.
-   --  Add attributes associating it with the entry defining identifier
-   --  Ent_Id.
+     (Loc    : Source_Ptr;
+      Def_Id : Entity_Id;
+      Ent_Id : Entity_Id) return Node_Id;
+   --  Build a specification for the procedure implementing the statemens of
+   --  the specified entry body. Add attributes associating it with the entry
+   --  defining identifier Ent_Id.
+
+   function Build_Protected_Spec
+     (N           : Node_Id;
+      Obj_Type    : Entity_Id;
+      Ident       : Entity_Id;
+      Unprotected : Boolean := False) return List_Id;
+   --  Utility shared by Build_Protected_Sub_Spec and Expand_Access_Protected_
+   --  Subprogram_Type. Builds signature of protected subprogram, adding the
+   --  formal that corresponds to the object itself. For an access to protected
+   --  subprogram, there is no object type to specify, so the parameter has
+   --  type Address and mode In. An indirect call through such a pointer will
+   --  convert the address to a reference to the actual object. The object is
+   --  a limited record and therefore a by_reference type.
 
    function Build_Protected_Subprogram_Body
      (N         : Node_Id;
@@ -221,19 +224,6 @@ package body Exp_Ch9 is
    --  a cleanup handler that unlocks the object in all cases.
    --  (see Exp_Ch7.Expand_Cleanup_Actions).
 
-   function Build_Protected_Spec
-     (N           : Node_Id;
-      Obj_Type    : Entity_Id;
-      Unprotected : Boolean := False;
-      Ident       : Entity_Id) return List_Id;
-   --  Utility shared by Build_Protected_Sub_Spec and Expand_Access_Protected_
-   --  Subprogram_Type. Builds signature of protected subprogram, adding the
-   --  formal that corresponds to the object itself. For an access to protected
-   --  subprogram, there is no object type to specify, so the additional
-   --  parameter has type Address and mode In. An indirect call through such
-   --  a pointer converts the address to a reference to the actual object.
-   --  The object is a limited record and therefore a by_reference type.
-
    function Build_Selected_Name
      (Prefix      : Entity_Id;
       Selector    : Entity_Id;
@@ -281,6 +271,29 @@ package body Exp_Ch9 is
    --  For each entry family in a concurrent type, create an anonymous array
    --  type of the right size, and add a component to the corresponding_record.
 
+   function Concurrent_Object
+     (Spec_Id  : Entity_Id;
+      Conc_Typ : Entity_Id) return Entity_Id;
+   --  Given a subprogram entity Spec_Id and concurrent type Conc_Typ, return
+   --  the entity associated with the concurrent object in the Protected_Body_
+   --  Subprogram or the Task_Body_Procedure of Spec_Id. The returned entity
+   --  denotes formal parameter _O, _object or _task.
+
+   function Copy_Result_Type (Res : Node_Id) return Node_Id;
+   --  Copy the result type of a function specification, when building the
+   --  internal operation corresponding to a protected function, or when
+   --  expanding an access to protected function. If the result is an anonymous
+   --  access to subprogram itself, we need to create a new signature with the
+   --  same parameter names and the same resolved types, but with new entities
+   --  for the formals.
+
+   procedure Debug_Private_Data_Declarations (Decls : List_Id);
+   --  Decls is a list which may contain the declarations created by Install_
+   --  Private_Data_Declarations. All generated entities are marked as needing
+   --  debug info and debug nodes are manually generation where necessary. This
+   --  step of the expansion must to be done after private data has been moved
+   --  to its final resting scope to ensure proper visibility of debug objects.
+
    function Family_Offset
      (Loc  : Source_Ptr;
       Hi   : Node_Id;
@@ -313,7 +326,7 @@ package body Exp_Ch9 is
       Formals  : out List_Id);
    --  Given a dispatching call, extract the entity of the name of the call,
    --  its object parameter, its actual parameters and the formal parameters
-   --  of the overriden interface-level version.
+   --  of the overridden interface-level version.
 
    procedure Extract_Entry
      (N       : Node_Id;
@@ -332,16 +345,11 @@ package body Exp_Ch9 is
    --  when P is Name_uPriority, the call will also find Interrupt_Priority.
    --  ??? Should be implemented with the rep item chain mechanism.
 
-   function Index_Constant_Declaration
-     (N        : Node_Id;
-      Index_Id : Entity_Id;
-      Prot     : Entity_Id) return List_Id;
-   --  For an entry family and its barrier function, we define a local entity
-   --  that maps the index in the call into the entry index into the object:
-   --
-   --     I : constant Index_Type := Index_Type'Val (
-   --       E - <<index of first family member>> +
-   --       Protected_Entry_Index (Index_Type'Pos (Index_Type'First)));
+   function Index_Object (Spec_Id : Entity_Id) return Entity_Id;
+   --  Given a subprogram identifier, return the entity which is associated
+   --  with the protection entry index in the Protected_Body_Subprogram or the
+   --  Task_Body_Procedure of Spec_Id. The returned entity denotes formal
+   --  parameter _E.
 
    function Is_Potentially_Large_Family
      (Base_Index : Entity_Id;
@@ -349,6 +357,12 @@ package body Exp_Ch9 is
       Lo         : Node_Id;
       Hi         : Node_Id) return Boolean;
 
+   function Null_Statements (Stats : List_Id) return Boolean;
+   --  Used to check DO-END sequence. Checks for equivalent of DO NULL; END.
+   --  Allows labels, and pragma Warnings/Unreferenced in the sequence as
+   --  well to still count as null. Returns True for a null sequence. The
+   --  argument is the list of statements from the DO-END sequence.
+
    function Parameter_Block_Pack
      (Loc     : Source_Ptr;
       Blk_Typ : Entity_Id;
@@ -380,15 +394,15 @@ package body Exp_Ch9 is
    --    ...
    --    <actualN> := P.<formalN>;
 
-   procedure Update_Prival_Subtypes (N : Node_Id);
-   --  The actual subtypes of the privals will differ from the type of the
-   --  private declaration in the original protected type, if the protected
-   --  type has discriminants or if the prival has constrained components.
-   --  This is because the privals are generated out of sequence w.r.t. the
-   --  analysis of a protected body. After generating the bodies for protected
-   --  operations, we set correctly the type of all references to privals, by
-   --  means of a recursive tree traversal, which is heavy-handed but
-   --  correct.
+   function Trivial_Accept_OK return Boolean;
+   --  If there is no DO-END block for an accept, or if the DO-END block has
+   --  only null statements, then it is possible to do the Rendezvous with much
+   --  less overhead using the Accept_Trivial routine in the run-time library.
+   --  However, this is not always a valid optimization. Whether it is valid or
+   --  not depends on the Task_Dispatching_Policy. The issue is whether a full
+   --  rescheduling action is required or not. In FIFO_Within_Priorities, such
+   --  a rescheduling is required, so this optimization is not allowed. This
+   --  function returns True if the optimization is permitted.
 
    -----------------------------
    -- Actual_Index_Expression --
@@ -513,6 +527,53 @@ package body Exp_Ch9 is
          elsif Ekind (Prev) = E_Entry_Family then
             S :=
               Etype (Discrete_Subtype_Definition (Declaration_Node (Prev)));
+
+            --  The need for the following full view retrieval stems from
+            --  this complex case of nested generics and tasking:
+
+            --     generic
+            --        type Formal_Index is range <>;
+            --        ...
+            --     package Outer is
+            --        type Index is private;
+            --        generic
+            --           ...
+            --        package Inner is
+            --           procedure P;
+            --        end Inner;
+            --     private
+            --        type Index is new Formal_Index range 1 .. 10;
+            --     end Outer;
+
+            --     package body Outer is
+            --        task type T is
+            --           entry Fam (Index);  --  (2)
+            --           entry E;
+            --        end T;
+            --        package body Inner is  --  (3)
+            --           procedure P is
+            --           begin
+            --              T.E;             --  (1)
+            --           end P;
+            --       end Inner;
+            --       ...
+
+            --  We are currently building the index expression for the entry
+            --  call "T.E" (1). Part of the expansion must mention the range
+            --  of the discrete type "Index" (2) of entry family "Fam".
+            --  However only the private view of type "Index" is available to
+            --  the inner generic (3) because there was no prior mention of
+            --  the type inside "Inner". This visibility requirement is
+            --  implicit and cannot be detected during the construction of
+            --  the generic trees and needs special handling.
+
+            if In_Instance_Body
+              and then Is_Private_Type (S)
+              and then Present (Full_View (S))
+            then
+               S := Full_View (S);
+            end if;
+
             Lo := Type_Low_Bound  (S);
             Hi := Type_High_Bound (S);
 
@@ -538,84 +599,6 @@ package body Exp_Ch9 is
       return Expr;
    end Actual_Index_Expression;
 
-   ----------------------------------
-   -- Add_Discriminal_Declarations --
-   ----------------------------------
-
-   procedure Add_Discriminal_Declarations
-     (Decls : List_Id;
-      Typ   : Entity_Id;
-      Name  : Name_Id;
-      Loc   : Source_Ptr)
-   is
-      D     : Entity_Id;
-
-   begin
-      if Has_Discriminants (Typ) then
-         D := First_Discriminant (Typ);
-
-         while Present (D) loop
-
-            Prepend_To (Decls,
-              Make_Object_Renaming_Declaration (Loc,
-                Defining_Identifier => Discriminal (D),
-                Subtype_Mark => New_Reference_To (Etype (D), Loc),
-                Name =>
-                  Make_Selected_Component (Loc,
-                    Prefix        => Make_Identifier (Loc, Name),
-                    Selector_Name => Make_Identifier (Loc, Chars (D)))));
-
-            Next_Discriminant (D);
-         end loop;
-      end if;
-   end Add_Discriminal_Declarations;
-
-   ------------------------
-   -- Add_Object_Pointer --
-   ------------------------
-
-   procedure Add_Object_Pointer
-     (Decls : List_Id;
-      Pid   : Entity_Id;
-      Loc   : Source_Ptr)
-   is
-      Decl    : Node_Id;
-      Obj_Ptr : Node_Id;
-
-   begin
-      --  Prepend the declaration of _object. This must be first in the
-      --  declaration list, since it is used by the discriminal and
-      --  prival declarations.
-      --  ??? An attempt to make this a renaming was unsuccessful.
-      --
-      --     type poVP is access poV;
-      --     _object : poVP := poVP!O;
-
-      Obj_Ptr :=
-        Make_Defining_Identifier (Loc,
-          Chars =>
-            New_External_Name
-              (Chars (Corresponding_Record_Type (Pid)), 'P'));
-
-      Decl :=
-        Make_Object_Declaration (Loc,
-          Defining_Identifier =>
-            Make_Defining_Identifier (Loc, Name_uObject),
-          Object_Definition => New_Reference_To (Obj_Ptr, Loc),
-          Expression =>
-            Unchecked_Convert_To (Obj_Ptr,
-              Make_Identifier (Loc, Name_uO)));
-      Set_Needs_Debug_Info (Defining_Identifier (Decl));
-      Prepend_To (Decls, Decl);
-
-      Prepend_To (Decls,
-        Make_Full_Type_Declaration (Loc,
-          Defining_Identifier => Obj_Ptr,
-          Type_Definition => Make_Access_To_Object_Definition (Loc,
-            Subtype_Indication =>
-              New_Reference_To (Corresponding_Record_Type (Pid), Loc))));
-   end Add_Object_Pointer;
-
    --------------------------
    -- Add_Formal_Renamings --
    --------------------------
@@ -640,12 +623,18 @@ package body Exp_Ch9 is
    begin
       Formal := First_Formal (Ent);
       while Present (Formal) loop
-         Comp   := Entry_Component (Formal);
-         New_F  :=
-           Make_Defining_Identifier (Sloc (Formal), Chars (Formal));
+         Comp := Entry_Component (Formal);
+         New_F :=
+           Make_Defining_Identifier (Sloc (Formal),
+             Chars => Chars (Formal));
          Set_Etype (New_F, Etype (Formal));
          Set_Scope (New_F, Ent);
-         Set_Needs_Debug_Info (New_F);   --  That's the whole point.
+
+         --  Now we set debug info needed on New_F even though it does not
+         --  come from source, so that the debugger will get the right
+         --  information for these generated names.
+
+         Set_Debug_Info_Needed (New_F);
 
          if Ekind (Formal) = E_In_Parameter then
             Set_Ekind (New_F, E_Constant);
@@ -659,7 +648,8 @@ package body Exp_Ch9 is
          Decl :=
            Make_Object_Renaming_Declaration (Loc,
            Defining_Identifier => New_F,
-           Subtype_Mark => New_Reference_To (Etype (Formal), Loc),
+           Subtype_Mark =>
+             New_Reference_To (Etype (Formal), Loc),
            Name =>
              Make_Explicit_Dereference (Loc,
                Make_Selected_Component (Loc,
@@ -675,98 +665,59 @@ package body Exp_Ch9 is
       end loop;
    end Add_Formal_Renamings;
 
-   ------------------------------
-   -- Add_Private_Declarations --
-   ------------------------------
+   ------------------------
+   -- Add_Object_Pointer --
+   ------------------------
 
-   procedure Add_Private_Declarations
-     (Decls : List_Id;
-      Typ   : Entity_Id;
-      Name  : Name_Id;
-      Loc   : Source_Ptr)
+   procedure Add_Object_Pointer
+     (Loc      : Source_Ptr;
+      Conc_Typ : Entity_Id;
+      Decls    : List_Id)
    is
-      Def      : constant Node_Id   := Protected_Definition (Parent (Typ));
-      Decl     : Node_Id;
-      Body_Ent : constant Entity_Id := Corresponding_Body   (Parent (Typ));
-      P        : Node_Id;
-      Pdef     : Entity_Id;
+      Rec_Typ : constant Entity_Id := Corresponding_Record_Type (Conc_Typ);
+      Decl    : Node_Id;
+      Obj_Ptr : Node_Id;
 
    begin
-      pragma Assert (Nkind (Def) = N_Protected_Definition);
-
-      if Present (Private_Declarations (Def)) then
-         P := First (Private_Declarations (Def));
-         while Present (P) loop
-            if Nkind (P) = N_Component_Declaration then
-               Pdef := Defining_Identifier (P);
-               Decl :=
-                 Make_Object_Renaming_Declaration (Loc,
-                   Defining_Identifier => Prival (Pdef),
-                   Subtype_Mark => New_Reference_To (Etype (Pdef), Loc),
-                   Name =>
-                     Make_Selected_Component (Loc,
-                       Prefix        => Make_Identifier (Loc, Name),
-                       Selector_Name => Make_Identifier (Loc, Chars (Pdef))));
-               Set_Needs_Debug_Info (Defining_Identifier (Decl));
-               Prepend_To (Decls, Decl);
-            end if;
-
-            Next (P);
-         end loop;
-      end if;
-
-      --  One more "prival" for object itself, with the right protection type
-
-      declare
-         Protection_Type : RE_Id;
+      --  Create the renaming declaration for the Protection object of a
+      --  protected type. _Object is used by Complete_Entry_Body.
+      --  ??? An attempt to make this a renaming was unsuccessful.
 
-      begin
-         if Has_Attach_Handler (Typ) then
-            if Restricted_Profile then
-               if Has_Entries (Typ) then
-                  Protection_Type := RE_Protection_Entry;
-               else
-                  Protection_Type := RE_Protection;
-               end if;
-            else
-               Protection_Type := RE_Static_Interrupt_Protection;
-            end if;
+      --  Build the entity for the access type
 
-         elsif Has_Interrupt_Handler (Typ) then
-            Protection_Type := RE_Dynamic_Interrupt_Protection;
+      Obj_Ptr :=
+        Make_Defining_Identifier (Loc,
+          New_External_Name (Chars (Rec_Typ), 'P'));
 
-         --  The type has explicit entries or generated primitive entry
-         --  wrappers.
+      --  Generate:
+      --    _object : poVP := poVP!O;
 
-         elsif Has_Entries (Typ)
-            or else (Ada_Version >= Ada_05
-                       and then Present (Interface_List (Parent (Typ))))
-         then
-            if Abort_Allowed
-              or else Restriction_Active (No_Entry_Queue) = False
-              or else Number_Entries (Typ) > 1
-            then
-               Protection_Type := RE_Protection_Entries;
-            else
-               Protection_Type := RE_Protection_Entry;
-            end if;
+      Decl :=
+        Make_Object_Declaration (Loc,
+          Defining_Identifier =>
+            Make_Defining_Identifier (Loc, Name_uObject),
+          Object_Definition =>
+            New_Reference_To (Obj_Ptr, Loc),
+          Expression =>
+            Unchecked_Convert_To (Obj_Ptr,
+              Make_Identifier (Loc, Name_uO)));
+      Set_Debug_Info_Needed (Defining_Identifier (Decl));
+      Prepend_To (Decls, Decl);
 
-         else
-            Protection_Type := RE_Protection;
-         end if;
+      --  Generate:
+      --    type poVP is access poV;
 
-         Decl :=
-           Make_Object_Renaming_Declaration (Loc,
-             Defining_Identifier => Object_Ref (Body_Ent),
-             Subtype_Mark => New_Reference_To (RTE (Protection_Type), Loc),
-             Name =>
-               Make_Selected_Component (Loc,
-                 Prefix        => Make_Identifier (Loc, Name),
-                 Selector_Name => Make_Identifier (Loc, Name_uObject)));
-         Set_Needs_Debug_Info (Defining_Identifier (Decl));
-         Prepend_To (Decls, Decl);
-      end;
-   end Add_Private_Declarations;
+      Decl :=
+        Make_Full_Type_Declaration (Loc,
+          Defining_Identifier =>
+            Obj_Ptr,
+          Type_Definition =>
+            Make_Access_To_Object_Definition (Loc,
+          Subtype_Indication =>
+            New_Reference_To (Rec_Typ, Loc)));
+      Set_Debug_Info_Needed (Defining_Identifier (Decl));
+      Prepend_To (Decls, Decl);
+   end Add_Object_Pointer;
 
    -----------------------
    -- Build_Accept_Body --
@@ -864,12 +815,12 @@ package body Exp_Ch9 is
 
       P := Parent (N);
 
-      while Nkind (P) /= N_Subprogram_Body
-        and then Nkind (P) /= N_Package_Declaration
-        and then Nkind (P) /= N_Package_Body
-        and then Nkind (P) /= N_Block_Statement
-        and then Nkind (P) /= N_Task_Body
-        and then Nkind (P) /= N_Extended_Return_Statement
+      while not Nkind_In (P, N_Subprogram_Body,
+                             N_Package_Declaration,
+                             N_Package_Body,
+                             N_Block_Statement,
+                             N_Task_Body,
+                             N_Extended_Return_Statement)
       loop
          P := Parent (P);
       end loop;
@@ -899,14 +850,13 @@ package body Exp_Ch9 is
       then
          Chain := Make_Defining_Identifier (Sloc (N), Name_uChain);
 
-         --  An extended return statement is not really a task activator, but
-         --  it does have an activation chain on which to store the tasks
+         --  Note: An extended return statement is not really a task activator,
+         --  but it does have an activation chain on which to store the tasks
          --  temporarily. On successful return, the tasks on this chain are
-         --  moved to the chain passed in by the
-         --  caller. N_Extended_Return_Statement does not have an
-         --  Activation_Chain_Entity, because we do not want to build a call
-         --  to Activate_Tasks; task activation is the responsibility of the
-         --  caller.
+         --  moved to the chain passed in by the caller. We do not build an
+         --  Activation_Chain_Entity for an N_Extended_Return_Statement,
+         --  because we do not want to build a call to Activate_Tasks. Task
+         --  activation is the responsibility of the caller.
 
          if Nkind (P) /= N_Extended_Return_Statement then
             Set_Activation_Chain_Entity (P, Chain);
@@ -933,67 +883,37 @@ package body Exp_Ch9 is
       Pid : Node_Id) return Node_Id
    is
       Loc         : constant Source_Ptr := Sloc (N);
+      Func_Id     : constant Entity_Id  := Barrier_Function (Ent);
       Ent_Formals : constant Node_Id    := Entry_Body_Formal_Part (N);
-      Index_Spec  : constant Node_Id    := Entry_Index_Specification
-                                                           (Ent_Formals);
-      Op_Decls : constant List_Id := New_List;
-      Bdef     : Entity_Id;
-      Bspec    : Node_Id;
-      EBF      : Node_Id;
+      Op_Decls    : constant List_Id    := New_List;
+      Func_Body   : Node_Id;
 
    begin
-      Bdef :=
-        Make_Defining_Identifier (Loc,
-          Chars => Chars (Barrier_Function (Ent)));
-      Bspec := Build_Barrier_Function_Specification (Bdef, Loc);
-
-      --  <object pointer declaration>
-      --  <discriminant renamings>
-      --  <private object renamings>
-      --  Add discriminal and private renamings. These names have
-      --  already been used to expand references to discriminants
-      --  and private data.
-
-      Add_Discriminal_Declarations (Op_Decls, Pid, Name_uObject, Loc);
-      Add_Private_Declarations (Op_Decls, Pid, Name_uObject, Loc);
-      Add_Object_Pointer (Op_Decls, Pid, Loc);
-
-      --  If this is the barrier for an entry family, the entry index is
-      --  visible in the body of the barrier. Create a local variable that
-      --  converts the entry index (which is the last formal of the barrier
-      --  function) into the appropriate offset into the entry array. The
-      --  entry index constant must be set, as for the entry body, so that
-      --  local references to the entry index are correctly replaced with
-      --  the local variable. This parallels what is done for entry bodies.
-
-      if Present (Index_Spec) then
-         declare
-            Index_Id  : constant Entity_Id := Defining_Identifier (Index_Spec);
-            Index_Con : constant Entity_Id :=
-                          Make_Defining_Identifier (Loc,
-                            Chars => New_Internal_Name ('J'));
-         begin
-            Set_Entry_Index_Constant (Index_Id, Index_Con);
-            Append_List_To (Op_Decls,
-              Index_Constant_Declaration (N, Index_Id, Pid));
-         end;
-      end if;
+      --  Add a declaration for the Protection object, renaming declarations
+      --  for the discriminals and privals and finally a declaration for the
+      --  entry family index (if applicable).
+
+      Install_Private_Data_Declarations
+        (Loc, Func_Id, Pid, N, Op_Decls, True, Ekind (Ent) = E_Entry_Family);
 
       --  Note: the condition in the barrier function needs to be properly
       --  processed for the C/Fortran boolean possibility, but this happens
       --  automatically since the return statement does this normalization.
 
-      EBF :=
+      Func_Body :=
         Make_Subprogram_Body (Loc,
-          Specification => Bspec,
+          Specification =>
+            Build_Barrier_Function_Specification (Loc,
+              Make_Defining_Identifier (Loc, Chars (Func_Id))),
           Declarations => Op_Decls,
           Handled_Statement_Sequence =>
             Make_Handled_Sequence_Of_Statements (Loc,
               Statements => New_List (
-                Make_Return_Statement (Loc,
+                Make_Simple_Return_Statement (Loc,
                   Expression => Condition (Ent_Formals)))));
-      Set_Is_Entry_Barrier_Function (EBF);
-      return EBF;
+      Set_Is_Entry_Barrier_Function (Func_Body);
+
+      return Func_Body;
    end Build_Barrier_Function;
 
    ------------------------------------------
@@ -1001,25 +921,29 @@ package body Exp_Ch9 is
    ------------------------------------------
 
    function Build_Barrier_Function_Specification
-     (Def_Id : Entity_Id;
-      Loc    : Source_Ptr) return Node_Id
+     (Loc    : Source_Ptr;
+      Def_Id : Entity_Id) return Node_Id
    is
    begin
-      Set_Needs_Debug_Info (Def_Id);
+      Set_Debug_Info_Needed (Def_Id);
+
       return Make_Function_Specification (Loc,
         Defining_Unit_Name => Def_Id,
         Parameter_Specifications => New_List (
           Make_Parameter_Specification (Loc,
-            Defining_Identifier => Make_Defining_Identifier (Loc, Name_uO),
+            Defining_Identifier =>
+              Make_Defining_Identifier (Loc, Name_uO),
             Parameter_Type =>
               New_Reference_To (RTE (RE_Address), Loc)),
 
           Make_Parameter_Specification (Loc,
-            Defining_Identifier => Make_Defining_Identifier (Loc, Name_uE),
+            Defining_Identifier =>
+              Make_Defining_Identifier (Loc, Name_uE),
             Parameter_Type =>
               New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))),
 
-        Result_Definition => New_Reference_To (Standard_Boolean, Loc));
+        Result_Definition =>
+          New_Reference_To (Standard_Boolean, Loc));
    end Build_Barrier_Function_Specification;
 
    --------------------------
@@ -1358,7 +1282,7 @@ package body Exp_Ch9 is
                Make_Handled_Sequence_Of_Statements (Loc,
                  Statements =>
                    New_List (
-                     Make_Return_Statement (Loc,
+                     Make_Simple_Return_Statement (Loc,
                         Make_Function_Call (Loc,
                           Name =>
                             Make_Selected_Component (Loc,
@@ -1416,7 +1340,7 @@ package body Exp_Ch9 is
       function Overriding_Possible
         (Iface_Prim_Op : Entity_Id;
          Proc_Nam      : Entity_Id) return Boolean;
-      --  Determine whether a primitive operation can be overriden by the
+      --  Determine whether a primitive operation can be overridden by the
       --  wrapper. Iface_Prim_Op is the candidate primitive operation of an
       --  abstract interface type, Proc_Nam is the generated entry wrapper.
 
@@ -1459,7 +1383,9 @@ package body Exp_Ch9 is
             Proc_Param_Specs    : List_Id) return Boolean
          is
             Prim_Op_Param : Node_Id;
+            Prim_Op_Typ   : Entity_Id;
             Proc_Param    : Node_Id;
+            Proc_Typ      : Entity_Id;
 
          begin
             --  Skip the first parameter of the primitive operation
@@ -1469,12 +1395,13 @@ package body Exp_Ch9 is
             while Present (Prim_Op_Param)
               and then Present (Proc_Param)
             loop
+               Prim_Op_Typ := Find_Parameter_Type (Prim_Op_Param);
+               Proc_Typ    := Find_Parameter_Type (Proc_Param);
+
                --  The two parameters must be mode conformant
 
-               if not Conforming_Types (
-                 Etype (Parameter_Type (Prim_Op_Param)),
-                 Etype (Parameter_Type (Proc_Param)),
-                 Mode_Conformant)
+               if not Conforming_Types
+                        (Prim_Op_Typ, Proc_Typ, Mode_Conformant)
                then
                   return False;
                end if;
@@ -1515,9 +1442,9 @@ package body Exp_Ch9 is
               Present (Parameter_Specifications (Prim_Op_Spec))
                 and then
               Nkind (Parameter_Type
-                     (First
-                      (Parameter_Specifications (Prim_Op_Spec))))
-                        = N_Access_Definition;
+                      (First
+                        (Parameter_Specifications (Prim_Op_Spec)))) =
+                                                          N_Access_Definition;
 
             if not Is_Out_Present
               and then not Is_Access_To_Variable
@@ -1541,6 +1468,7 @@ package body Exp_Ch9 is
       is
          New_Formals : constant List_Id := New_List;
          Formal      : Node_Id;
+         Param_Type  : Node_Id;
 
       begin
          Formal := First (Formals);
@@ -1548,6 +1476,22 @@ package body Exp_Ch9 is
 
             --  Create an explicit copy of the entry parameter
 
+            --  When creating the wrapper subprogram for a primitive operation
+            --  of a protected interface we must construct an equivalent
+            --  signature to that of the overriding operation. For regular
+            --  parameters we can just use the type of the formal, but for
+            --  access to subprogram parameters we need to reanalyze the
+            --  parameter type to create local entities for the signature of
+            --  the subprogram type. Using the entities of the overriding
+            --  subprogram will result in out-of-scope errors in the back-end.
+
+            if Nkind (Parameter_Type (Formal)) = N_Access_Definition then
+               Param_Type := Copy_Separate_Tree (Parameter_Type (Formal));
+            else
+               Param_Type :=
+                 New_Reference_To (Etype (Parameter_Type (Formal)), Loc);
+            end if;
+
             Append_To (New_Formals,
               Make_Parameter_Specification (Loc,
                 Defining_Identifier =>
@@ -1555,8 +1499,7 @@ package body Exp_Ch9 is
                     Chars          => Chars (Defining_Identifier (Formal))),
                     In_Present     => In_Present  (Formal),
                     Out_Present    => Out_Present (Formal),
-                    Parameter_Type => New_Reference_To (Etype (
-                                        Parameter_Type (Formal)), Loc)));
+                    Parameter_Type => Param_Type));
 
             Next (Formal);
          end loop;
@@ -1588,7 +1531,7 @@ package body Exp_Ch9 is
                      Iface_Prim_Op := Alias (Iface_Prim_Op);
                   end loop;
 
-                  --  The current primitive operation can be overriden by the
+                  --  The current primitive operation can be overridden by the
                   --  generated entry wrapper.
 
                   if Overriding_Possible (Iface_Prim_Op, Proc_Nam) then
@@ -1629,7 +1572,7 @@ package body Exp_Ch9 is
                         Iface_Prim_Op := Alias (Iface_Prim_Op);
                      end loop;
 
-                     --  The current primitive operation can be overriden by
+                     --  The current primitive operation can be overridden by
                      --  the generated entry wrapper.
 
                      if Overriding_Possible (Iface_Prim_Op, Proc_Nam) then
@@ -1648,7 +1591,7 @@ package body Exp_Ch9 is
          end loop Examine_Interfaces;
       end if;
 
-      --  Return if no interface primitive can be overriden
+      --  Return if no interface primitive can be overridden
 
       return Empty;
 
@@ -1660,12 +1603,18 @@ package body Exp_Ch9 is
       --  not implement any interfaces and are compiled with the -gnat05
       --  switch.  In this case, a default first parameter is created.
 
+      --  If the interface operation has an access parameter, create a copy
+      --  of it, with the same null exclusion indicator if present.
+
       if Present (First_Param) then
          if Nkind (Parameter_Type (First_Param)) = N_Access_Definition then
             Obj_Param_Typ :=
               Make_Access_Definition (Loc,
                 Subtype_Mark =>
                   New_Reference_To (Obj_Typ, Loc));
+            Set_Null_Exclusion_Present (Obj_Param_Typ,
+               Null_Exclusion_Present (Parameter_Type (First_Param)));
+
          else
             Obj_Param_Typ := New_Reference_To (Obj_Typ, Loc);
          end if;
@@ -1750,7 +1699,7 @@ package body Exp_Ch9 is
          Cond  : Node_Id;
          Stats : constant List_Id :=
                    New_List (
-                     Make_Return_Statement (Loc,
+                     Make_Simple_Return_Statement (Loc,
                        Expression => Make_Integer_Literal (Loc, Index + 1)));
 
       begin
@@ -1842,7 +1791,7 @@ package body Exp_Ch9 is
          --  correspondence between entry queue and entry body.
 
          Ret :=
-           Make_Return_Statement (Loc,
+           Make_Simple_Return_Statement (Loc,
              Expression => Make_Identifier (Loc, Name_uE));
 
       else
@@ -1857,7 +1806,7 @@ package body Exp_Ch9 is
          Siz   := Empty;
          Ent   := First_Entity (Typ);
 
-         Add_Object_Pointer (Decls, Typ, Loc);
+         Add_Object_Pointer (Loc, Typ, Decls);
 
          while Present (Ent) loop
 
@@ -1878,7 +1827,7 @@ package body Exp_Ch9 is
          if Index = 1 then
             Decls := New_List;
             Ret :=
-              Make_Return_Statement (Loc,
+              Make_Simple_Return_Statement (Loc,
                 Expression => Make_Integer_Literal (Loc, 1));
 
          elsif Nkind (Ret) = N_If_Statement then
@@ -1948,11 +1897,20 @@ package body Exp_Ch9 is
 
       --  Ada 2005 (AI-287): Do not set/get the has_master_entity reminder
       --  in internal scopes, unless present already.. Required for nested
-      --  limited aggregates. This could use some more explanation ????
+      --  limited aggregates, where the expansion of task components may
+      --  generate inner blocks. If the block is the rewriting of a call
+      --  this is valid master.
 
       if Ada_Version >= Ada_05 then
          while Is_Internal (S) loop
-            S := Scope (S);
+            if Nkind (Parent (S)) = N_Block_Statement
+              and then
+                Nkind (Original_Node (Parent (S))) = N_Procedure_Call_Statement
+            then
+               exit;
+            else
+               S := Scope (S);
+            end if;
          end loop;
       end if;
 
@@ -2000,9 +1958,8 @@ package body Exp_Ch9 is
          --  If we fall off the top, we are at the outer level, and the
          --  environment task is our effective master, so nothing to mark.
 
-         if Nkind (P) = N_Task_Body
-           or else Nkind (P) = N_Block_Statement
-           or else Nkind (P) = N_Subprogram_Body
+         if Nkind_In
+              (P, N_Task_Body, N_Block_Statement, N_Subprogram_Body)
          then
             Set_Is_Task_Master (P, True);
             return;
@@ -2022,86 +1979,121 @@ package body Exp_Ch9 is
       Ent : Entity_Id;
       Pid : Node_Id) return Node_Id
    is
-      Loc      : constant Source_Ptr := Sloc (N);
-      Op_Decls : constant List_Id    := New_List;
+      Loc : constant Source_Ptr := Sloc (N);
+
+      Decls   : constant List_Id := Declarations (N);
+      End_Lab : constant Node_Id :=
+                  End_Label (Handled_Statement_Sequence (N));
+      End_Loc : constant Source_Ptr :=
+                  Sloc (Last (Statements (Handled_Statement_Sequence (N))));
+      --  Used for the generated call to Complete_Entry_Body
+
+      Han_Loc : Source_Ptr;
+      --  Used for the exception handler, inserted at end of the body
+
+      Op_Decls : constant List_Id := New_List;
+      Complete : Node_Id;
       Edef     : Entity_Id;
       Espec    : Node_Id;
-      Op_Stats : List_Id;
       Ohandle  : Node_Id;
-      Complete : Node_Id;
+      Op_Stats : List_Id;
 
    begin
+      --  Set the source location on the exception handler only when debugging
+      --  the expanded code (see Make_Implicit_Exception_Handler).
+
+      if Debug_Generated_Code then
+         Han_Loc := End_Loc;
+
+      --  Otherwise the inserted code should not be visible to the debugger
+
+      else
+         Han_Loc := No_Location;
+      end if;
+
       Edef :=
         Make_Defining_Identifier (Loc,
           Chars => Chars (Protected_Body_Subprogram (Ent)));
-      Espec := Build_Protected_Entry_Specification (Edef, Empty, Loc);
-
-      --  <object pointer declaration>
+      Espec :=
+        Build_Protected_Entry_Specification (Loc, Edef, Empty);
 
-      --  Add object pointer declaration. This is needed by the discriminal and
-      --  prival renamings, which should already have been inserted into the
-      --  declaration list.
+      --  Add the following declarations:
+      --    type poVP is access poV;
+      --    _object : poVP := poVP (_O);
+      --
+      --  where _O is the formal parameter associated with the concurrent
+      --  object. These declarations are needed for Complete_Entry_Body.
 
-      Add_Object_Pointer (Op_Decls, Pid, Loc);
+      Add_Object_Pointer (Loc, Pid, Op_Decls);
 
-      --  Add renamings for formals for use by debugger
+      --  Add renamings for all formals, the Protection object, discriminals,
+      --  privals and the entry indix constant for use by debugger.
 
       Add_Formal_Renamings (Espec, Op_Decls, Ent, Loc);
+      Debug_Private_Data_Declarations (Decls);
 
-      if Abort_Allowed
-        or else Restriction_Active (No_Entry_Queue) = False
-        or else Number_Entries (Pid) > 1
-        or else (Has_Attach_Handler (Pid) and then not Restricted_Profile)
-      then
-         Complete := New_Reference_To (RTE (RE_Complete_Entry_Body), Loc);
-      else
-         Complete :=
-           New_Reference_To (RTE (RE_Complete_Single_Entry_Body), Loc);
-      end if;
+      case Corresponding_Runtime_Package (Pid) is
+         when System_Tasking_Protected_Objects_Entries =>
+            Complete :=
+              New_Reference_To (RTE (RE_Complete_Entry_Body), Loc);
+
+         when System_Tasking_Protected_Objects_Single_Entry =>
+            Complete :=
+              New_Reference_To (RTE (RE_Complete_Single_Entry_Body), Loc);
+
+         when others =>
+            raise Program_Error;
+      end case;
 
       Op_Stats := New_List (
-         Make_Block_Statement (Loc,
-           Declarations => Declarations (N),
-           Handled_Statement_Sequence =>
-             Handled_Statement_Sequence (N)),
+        Make_Block_Statement (Loc,
+          Declarations => Decls,
+          Handled_Statement_Sequence =>
+            Handled_Statement_Sequence (N)),
 
-         Make_Procedure_Call_Statement (Loc,
-           Name => Complete,
-           Parameter_Associations => New_List (
-             Make_Attribute_Reference (Loc,
-               Prefix =>
-                 Make_Selected_Component (Loc,
-                   Prefix =>
-                     Make_Identifier (Loc, Name_uObject),
+        Make_Procedure_Call_Statement (End_Loc,
+          Name => Complete,
+          Parameter_Associations => New_List (
+            Make_Attribute_Reference (End_Loc,
+              Prefix =>
+                Make_Selected_Component (End_Loc,
+                  Prefix =>
+                    Make_Identifier (End_Loc, Name_uObject),
+                  Selector_Name =>
+                    Make_Identifier (End_Loc, Name_uObject)),
+              Attribute_Name => Name_Unchecked_Access))));
 
-                   Selector_Name =>
-                     Make_Identifier (Loc, Name_uObject)),
-                 Attribute_Name => Name_Unchecked_Access))));
+      --  When exceptions can not be propagated, we never need to call
+      --  Exception_Complete_Entry_Body
 
-      if Restriction_Active (No_Exception_Handlers) then
+      if No_Exception_Handlers_Set then
          return
            Make_Subprogram_Body (Loc,
              Specification => Espec,
              Declarations => Op_Decls,
              Handled_Statement_Sequence =>
-               Make_Handled_Sequence_Of_Statements (Loc, Op_Stats));
+               Make_Handled_Sequence_Of_Statements (Loc,
+                 Statements => Op_Stats,
+                 End_Label  => End_Lab));
 
       else
          Ohandle := Make_Others_Choice (Loc);
          Set_All_Others (Ohandle);
 
-         if Abort_Allowed
-           or else Restriction_Active (No_Entry_Queue) = False
-           or else Number_Entries (Pid) > 1
-           or else (Has_Attach_Handler (Pid) and then not Restricted_Profile)
-         then
-            Complete :=
-              New_Reference_To (RTE (RE_Exceptional_Complete_Entry_Body), Loc);
+         case Corresponding_Runtime_Package (Pid) is
+            when System_Tasking_Protected_Objects_Entries =>
+               Complete :=
+                 New_Reference_To
+                   (RTE (RE_Exceptional_Complete_Entry_Body), Loc);
 
-         else
-            Complete := New_Reference_To (
-              RTE (RE_Exceptional_Complete_Single_Entry_Body), Loc);
-         end if;
+            when System_Tasking_Protected_Objects_Single_Entry =>
+               Complete :=
+                 New_Reference_To
+                   (RTE (RE_Exceptional_Complete_Single_Entry_Body), Loc);
+
+            when others =>
+               raise Program_Error;
+         end case;
 
          --  Create body of entry procedure. The renaming declarations are
          --  placed ahead of the block that contains the actual entry body.
@@ -2113,24 +2105,25 @@ package body Exp_Ch9 is
              Handled_Statement_Sequence =>
                Make_Handled_Sequence_Of_Statements (Loc,
                  Statements => Op_Stats,
+                 End_Label  => End_Lab,
                  Exception_Handlers => New_List (
-                   Make_Implicit_Exception_Handler (Loc,
+                   Make_Implicit_Exception_Handler (Han_Loc,
                      Exception_Choices => New_List (Ohandle),
 
                      Statements =>  New_List (
-                       Make_Procedure_Call_Statement (Loc,
+                       Make_Procedure_Call_Statement (Han_Loc,
                          Name => Complete,
                          Parameter_Associations => New_List (
-                           Make_Attribute_Reference (Loc,
+                           Make_Attribute_Reference (Han_Loc,
                              Prefix =>
-                               Make_Selected_Component (Loc,
+                               Make_Selected_Component (Han_Loc,
                                  Prefix =>
-                                   Make_Identifier (Loc, Name_uObject),
+                                   Make_Identifier (Han_Loc, Name_uObject),
                                  Selector_Name =>
-                                   Make_Identifier (Loc, Name_uObject)),
+                                   Make_Identifier (Han_Loc, Name_uObject)),
                                Attribute_Name => Name_Unchecked_Access),
 
-                           Make_Function_Call (Loc,
+                           Make_Function_Call (Han_Loc,
                              Name => New_Reference_To (
                                RTE (RE_Get_GNAT_Exception), Loc)))))))));
       end if;
@@ -2141,37 +2134,39 @@ package body Exp_Ch9 is
    -----------------------------------------
 
    function Build_Protected_Entry_Specification
-     (Def_Id : Entity_Id;
-      Ent_Id : Entity_Id;
-      Loc    : Source_Ptr) return Node_Id
+     (Loc    : Source_Ptr;
+      Def_Id : Entity_Id;
+      Ent_Id : Entity_Id) return Node_Id
    is
-      P : Entity_Id;
+      P : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uP);
 
    begin
-      Set_Needs_Debug_Info (Def_Id);
-      P := Make_Defining_Identifier (Loc, Name_uP);
+      Set_Debug_Info_Needed (Def_Id);
 
       if Present (Ent_Id) then
          Append_Elmt (P, Accept_Address (Ent_Id));
       end if;
 
-      return Make_Procedure_Specification (Loc,
-        Defining_Unit_Name => Def_Id,
-        Parameter_Specifications => New_List (
-          Make_Parameter_Specification (Loc,
-            Defining_Identifier => Make_Defining_Identifier (Loc, Name_uO),
-            Parameter_Type =>
-              New_Reference_To (RTE (RE_Address), Loc)),
+      return
+        Make_Procedure_Specification (Loc,
+          Defining_Unit_Name => Def_Id,
+          Parameter_Specifications => New_List (
+            Make_Parameter_Specification (Loc,
+              Defining_Identifier =>
+                Make_Defining_Identifier (Loc, Name_uO),
+              Parameter_Type =>
+                New_Reference_To (RTE (RE_Address), Loc)),
 
-          Make_Parameter_Specification (Loc,
-            Defining_Identifier => P,
-            Parameter_Type =>
-              New_Reference_To (RTE (RE_Address), Loc)),
+            Make_Parameter_Specification (Loc,
+              Defining_Identifier => P,
+              Parameter_Type =>
+                New_Reference_To (RTE (RE_Address), Loc)),
 
-          Make_Parameter_Specification (Loc,
-            Defining_Identifier => Make_Defining_Identifier (Loc, Name_uE),
-            Parameter_Type =>
-              New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))));
+            Make_Parameter_Specification (Loc,
+              Defining_Identifier =>
+                Make_Defining_Identifier (Loc, Name_uE),
+              Parameter_Type =>
+                New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))));
    end Build_Protected_Entry_Specification;
 
    --------------------------
@@ -2181,27 +2176,27 @@ package body Exp_Ch9 is
    function Build_Protected_Spec
      (N           : Node_Id;
       Obj_Type    : Entity_Id;
-      Unprotected : Boolean := False;
-      Ident       : Entity_Id) return List_Id
+      Ident       : Entity_Id;
+      Unprotected : Boolean := False) return List_Id
    is
-      Loc         : constant Source_Ptr := Sloc (N);
-      Decl        : Node_Id;
-      Formal      : Entity_Id;
-      New_Plist   : List_Id;
-      New_Param   : Node_Id;
+      Loc       : constant Source_Ptr := Sloc (N);
+      Decl      : Node_Id;
+      Formal    : Entity_Id;
+      New_Plist : List_Id;
+      New_Param : Node_Id;
 
    begin
       New_Plist := New_List;
+
       Formal := First_Formal (Ident);
       while Present (Formal) loop
          New_Param :=
            Make_Parameter_Specification (Loc,
              Defining_Identifier =>
                Make_Defining_Identifier (Sloc (Formal), Chars (Formal)),
-             In_Present => In_Present (Parent (Formal)),
-             Out_Present => Out_Present (Parent (Formal)),
-             Parameter_Type =>
-               New_Reference_To (Etype (Formal), Loc));
+             In_Present          => In_Present (Parent (Formal)),
+             Out_Present         => Out_Present (Parent (Formal)),
+             Parameter_Type      => New_Reference_To (Etype (Formal), Loc));
 
          if Unprotected then
             Set_Protected_Formal (Formal, Defining_Identifier (New_Param));
@@ -2221,10 +2216,11 @@ package body Exp_Ch9 is
             Make_Defining_Identifier (Loc, Name_uObject),
           In_Present => True,
           Out_Present =>
-           (Etype (Ident) = Standard_Void_Type
-              and then not Is_RTE (Obj_Type, RE_Address)),
-          Parameter_Type => New_Reference_To (Obj_Type, Loc));
-      Set_Needs_Debug_Info (Defining_Identifier (Decl));
+            (Etype (Ident) = Standard_Void_Type
+               and then not Is_RTE (Obj_Type, RE_Address)),
+          Parameter_Type =>
+            New_Reference_To (Obj_Type, Loc));
+      Set_Debug_Info_Needed (Defining_Identifier (Decl));
       Prepend_To (New_Plist, Decl);
 
       return New_Plist;
@@ -2235,13 +2231,13 @@ package body Exp_Ch9 is
    ---------------------------------------
 
    function Build_Protected_Sub_Specification
-     (N       : Node_Id;
-      Prottyp : Entity_Id;
-      Mode    : Subprogram_Protection_Mode) return Node_Id
+     (N        : Node_Id;
+      Prot_Typ : Entity_Id;
+      Mode     : Subprogram_Protection_Mode) return Node_Id
    is
       Loc       : constant Source_Ptr := Sloc (N);
       Decl      : Node_Id;
-      Ident     : Entity_Id;
+      Def_Id    : Entity_Id;
       New_Id    : Entity_Id;
       New_Plist : List_Id;
       New_Spec  : Node_Id;
@@ -2252,24 +2248,23 @@ package body Exp_Ch9 is
                       Unprotected_Mode => 'N');
 
    begin
-      if Ekind
-         (Defining_Unit_Name (Specification (N))) = E_Subprogram_Body
+      if Ekind (Defining_Unit_Name (Specification (N))) =
+           E_Subprogram_Body
       then
          Decl := Unit_Declaration_Node (Corresponding_Spec (N));
       else
          Decl := N;
       end if;
 
-      Ident := Defining_Unit_Name (Specification (Decl));
+      Def_Id := Defining_Unit_Name (Specification (Decl));
 
       New_Plist :=
-        Build_Protected_Spec (Decl,
-          Corresponding_Record_Type (Prottyp),
-                              Mode = Unprotected_Mode, Ident);
-
+        Build_Protected_Spec
+          (Decl, Corresponding_Record_Type (Prot_Typ), Def_Id,
+           Mode = Unprotected_Mode);
       New_Id :=
         Make_Defining_Identifier (Loc,
-          Chars => Build_Selected_Name (Prottyp, Ident, Append_Chr (Mode)));
+          Chars => Build_Selected_Name (Prot_Typ, Def_Id, Append_Chr (Mode)));
 
       --  The unprotected operation carries the user code, and debugging
       --  information must be generated for it, even though this spec does
@@ -2277,24 +2272,28 @@ package body Exp_Ch9 is
       --  into the protected operation, even though it only contains lock/
       --  unlock calls.
 
-      Set_Needs_Debug_Info (New_Id);
+      Set_Debug_Info_Needed (New_Id);
 
       if Nkind (Specification (Decl)) = N_Procedure_Specification then
-         return
+         New_Spec :=
            Make_Procedure_Specification (Loc,
              Defining_Unit_Name => New_Id,
              Parameter_Specifications => New_Plist);
 
+      --  Create a new specification for the anonymous subprogram type
+
       else
          New_Spec :=
            Make_Function_Specification (Loc,
              Defining_Unit_Name => New_Id,
              Parameter_Specifications => New_Plist,
              Result_Definition =>
-               New_Copy (Result_Definition (Specification (Decl))));
+               Copy_Result_Type (Result_Definition (Specification (Decl))));
+
          Set_Return_Present (Defining_Unit_Name (New_Spec));
-         return New_Spec;
       end if;
+
+      return New_Spec;
    end Build_Protected_Sub_Specification;
 
    -------------------------------------
@@ -2357,12 +2356,12 @@ package body Exp_Ch9 is
 
             function Is_Call_Or_Raise (N : Node_Id) return Boolean is
             begin
-               return Nkind (N) = N_Procedure_Call_Statement
-                 or else Nkind (N) = N_Function_Call
-                 or else Nkind (N) = N_Raise_Statement
-                 or else Nkind (N) = N_Raise_Constraint_Error
-                 or else Nkind (N) = N_Raise_Program_Error
-                 or else Nkind (N) = N_Raise_Storage_Error;
+               return Nkind_In (N, N_Procedure_Call_Statement,
+                                   N_Function_Call,
+                                   N_Raise_Statement,
+                                   N_Raise_Constraint_Error,
+                                   N_Raise_Program_Error,
+                                   N_Raise_Storage_Error);
             end Is_Call_Or_Raise;
 
          --  Start of processing for Has_Side_Effect
@@ -2455,11 +2454,11 @@ package body Exp_Ch9 is
                     Name => Make_Identifier (Loc,
                       Chars (Defining_Unit_Name (N_Op_Spec))),
                     Parameter_Associations => Uactuals));
-            Return_Stmt := Make_Return_Statement (Loc,
+            Return_Stmt := Make_Simple_Return_Statement (Loc,
               Expression => New_Reference_To (R, Loc));
 
          else
-            Unprot_Call := Make_Return_Statement (Loc,
+            Unprot_Call := Make_Simple_Return_Statement (Loc,
               Expression => Make_Function_Call (Loc,
                 Name =>
                   Make_Identifier (Loc,
@@ -2468,11 +2467,12 @@ package body Exp_Ch9 is
          end if;
 
       else
-         Unprot_Call := Make_Procedure_Call_Statement (Loc,
-           Name =>
-             Make_Identifier (Loc,
-               Chars (Defining_Unit_Name (N_Op_Spec))),
-           Parameter_Associations => Uactuals);
+         Unprot_Call :=
+           Make_Procedure_Call_Statement (Loc,
+             Name =>
+               Make_Identifier (Loc,
+                 Chars (Defining_Unit_Name (N_Op_Spec))),
+             Parameter_Associations => Uactuals);
       end if;
 
       --  Wrap call in block that will be covered by an at_end handler
@@ -2487,36 +2487,22 @@ package body Exp_Ch9 is
       --  Make the protected subprogram body. This locks the protected
       --  object and calls the unprotected version of the subprogram.
 
-      --  If the protected object is controlled (i.e it has entries or
-      --  needs finalization for interrupt handling), call Lock_Entries,
-      --  except if the protected object follows the Ravenscar profile, in
-      --  which case call Lock_Entry, otherwise call the simplified version,
-      --  Lock.
-
-      if Has_Entries (Pid)
-        or else Has_Interrupt_Handler (Pid)
-        or else (Has_Attach_Handler (Pid)
-                  and then not Restricted_Profile)
-        or else (Ada_Version >= Ada_05
-                  and then Present (Interface_List (Parent (Pid))))
-      then
-         if Abort_Allowed
-           or else Restriction_Active (No_Entry_Queue) = False
-           or else Number_Entries (Pid) > 1
-           or else (Has_Attach_Handler (Pid) and then not Restricted_Profile)
-         then
+      case Corresponding_Runtime_Package (Pid) is
+         when System_Tasking_Protected_Objects_Entries =>
             Lock_Name := New_Reference_To (RTE (RE_Lock_Entries), Loc);
             Service_Name := New_Reference_To (RTE (RE_Service_Entries), Loc);
 
-         else
+         when System_Tasking_Protected_Objects_Single_Entry =>
             Lock_Name := New_Reference_To (RTE (RE_Lock_Entry), Loc);
             Service_Name := New_Reference_To (RTE (RE_Service_Entry), Loc);
-         end if;
 
-      else
-         Lock_Name := New_Reference_To (RTE (RE_Lock), Loc);
-         Service_Name := New_Reference_To (RTE (RE_Unlock), Loc);
-      end if;
+         when System_Tasking_Protected_Objects =>
+            Lock_Name := New_Reference_To (RTE (RE_Lock), Loc);
+            Service_Name := New_Reference_To (RTE (RE_Unlock), Loc);
+
+         when others =>
+            raise Program_Error;
+      end case;
 
       Object_Parm :=
         Make_Attribute_Reference (Loc,
@@ -2832,11 +2818,35 @@ package body Exp_Ch9 is
          --  the _Task_Id or _Object from the result of doing an unchecked
          --  conversion to convert the value to the corresponding record type.
 
-         Parm1 := Concurrent_Ref (Concval);
+         if Nkind (Concval) = N_Function_Call
+           and then Is_Task_Type (Conctyp)
+           and then Ada_Version >= Ada_05
+         then
+            declare
+               Obj : constant Entity_Id :=
+                  Make_Defining_Identifier (Loc, New_Internal_Name ('F'));
+               Decl : Node_Id;
 
-         --  Second parameter is the entry index, computed by the routine
-         --  provided for this purpose. The value of this expression is
-         --  assigned to an intermediate variable to assure that any entry
+            begin
+               Decl :=
+                 Make_Object_Declaration (Loc,
+                   Defining_Identifier => Obj,
+                   Object_Definition   => New_Occurrence_Of (Conctyp, Loc),
+                   Expression          => Relocate_Node (Concval));
+               Set_Etype (Obj, Conctyp);
+               Decls := New_List (Decl);
+               Rewrite (Concval, New_Occurrence_Of (Obj, Loc));
+            end;
+
+         else
+            Decls := New_List;
+         end if;
+
+         Parm1 := Concurrent_Ref (Concval);
+
+         --  Second parameter is the entry index, computed by the routine
+         --  provided for this purpose. The value of this expression is
+         --  assigned to an intermediate variable to assure that any entry
          --  family index expressions are evaluated before the entry
          --  parameters.
 
@@ -2857,12 +2867,11 @@ package body Exp_Ch9 is
                 Expression => Actual_Index_Expression (
                   Loc, Entity (Ename), Index, Concval));
 
-            Decls := New_List (Xdecl);
+            Append_To (Decls, Xdecl);
             Parm2 := New_Reference_To (X, Loc);
 
          else
             Xdecl := Empty;
-            Decls := New_List;
             Parm2 := Empty;
          end if;
 
@@ -2906,11 +2915,15 @@ package body Exp_Ch9 is
 
                   Set_No_Initialization (N_Node);
 
-                  --  We have to make an assignment statement separate for the
+                  --  We must make an assignment statement separate for the
                   --  case of limited type. We cannot assign it unless the
-                  --  Assignment_OK flag is set first.
+                  --  Assignment_OK flag is set first. An out formal of an
+                  --  access type must also be initialized from the actual,
+                  --  as stated in RM 6.4.1 (13).
 
-                  if Ekind (Formal) /= E_Out_Parameter then
+                  if Ekind (Formal) /= E_Out_Parameter
+                    or else Is_Access_Type (Etype (Formal))
+                  then
                      N_Var :=
                        New_Reference_To (Defining_Identifier (N_Node), Loc);
                      Set_Assignment_OK (N_Var);
@@ -2979,8 +2992,8 @@ package body Exp_Ch9 is
 
             Parm3 :=
               Make_Attribute_Reference (Loc,
-                Attribute_Name => Name_Address,
-                Prefix => New_Reference_To (P, Loc));
+                Prefix => New_Reference_To (P, Loc),
+                Attribute_Name => Name_Address);
 
             Append (Pdecl, Decls);
          end if;
@@ -2988,75 +3001,75 @@ package body Exp_Ch9 is
          --  Now we can create the call, case of protected type
 
          if Is_Protected_Type (Conctyp) then
-            if Abort_Allowed
-              or else Restriction_Active (No_Entry_Queue) = False
-              or else Number_Entries (Conctyp) > 1
-              or else (Has_Attach_Handler (Conctyp)
-                        and then not Restricted_Profile)
-            then
-               --  Change the type of the index declaration
-
-               Set_Object_Definition (Xdecl,
-                 New_Reference_To (RTE (RE_Protected_Entry_Index), Loc));
+            case Corresponding_Runtime_Package (Conctyp) is
+               when System_Tasking_Protected_Objects_Entries =>
 
-               --  Some additional declarations for protected entry calls
+                  --  Change the type of the index declaration
 
-               if No (Decls) then
-                  Decls := New_List;
-               end if;
+                  Set_Object_Definition (Xdecl,
+                    New_Reference_To (RTE (RE_Protected_Entry_Index), Loc));
 
-               --  Bnn : Communications_Block;
+                  --  Some additional declarations for protected entry calls
 
-               Comm_Name :=
-                 Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
+                  if No (Decls) then
+                     Decls := New_List;
+                  end if;
 
-               Append_To (Decls,
-                 Make_Object_Declaration (Loc,
-                   Defining_Identifier => Comm_Name,
-                   Object_Definition =>
-                     New_Reference_To (RTE (RE_Communication_Block), Loc)));
+                  --  Bnn : Communications_Block;
 
-               --  Some additional statements for protected entry calls
+                  Comm_Name :=
+                    Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
 
-               --     Protected_Entry_Call (
-               --       Object => po._object'Access,
-               --       E => <entry index>;
-               --       Uninterpreted_Data => P'Address;
-               --       Mode => Simple_Call;
-               --       Block => Bnn);
+                  Append_To (Decls,
+                    Make_Object_Declaration (Loc,
+                      Defining_Identifier => Comm_Name,
+                      Object_Definition =>
+                        New_Reference_To (RTE (RE_Communication_Block), Loc)));
 
-               Call :=
-                 Make_Procedure_Call_Statement (Loc,
-                   Name =>
-                     New_Reference_To (RTE (RE_Protected_Entry_Call), Loc),
+                  --  Some additional statements for protected entry calls
 
-                   Parameter_Associations => New_List (
-                     Make_Attribute_Reference (Loc,
-                       Attribute_Name => Name_Unchecked_Access,
-                       Prefix         => Parm1),
-                     Parm2,
-                     Parm3,
-                     New_Reference_To (RTE (RE_Simple_Call), Loc),
-                     New_Occurrence_Of (Comm_Name, Loc)));
+                  --     Protected_Entry_Call (
+                  --       Object => po._object'Access,
+                  --       E => <entry index>;
+                  --       Uninterpreted_Data => P'Address;
+                  --       Mode => Simple_Call;
+                  --       Block => Bnn);
 
-            else
-               --     Protected_Single_Entry_Call (
-               --       Object => po._object'Access,
-               --       Uninterpreted_Data => P'Address;
-               --       Mode => Simple_Call);
+                  Call :=
+                    Make_Procedure_Call_Statement (Loc,
+                      Name =>
+                        New_Reference_To (RTE (RE_Protected_Entry_Call), Loc),
 
-               Call :=
-                 Make_Procedure_Call_Statement (Loc,
-                   Name => New_Reference_To (
-                     RTE (RE_Protected_Single_Entry_Call), Loc),
+                      Parameter_Associations => New_List (
+                        Make_Attribute_Reference (Loc,
+                          Attribute_Name => Name_Unchecked_Access,
+                          Prefix         => Parm1),
+                        Parm2,
+                        Parm3,
+                        New_Reference_To (RTE (RE_Simple_Call), Loc),
+                        New_Occurrence_Of (Comm_Name, Loc)));
+
+               when System_Tasking_Protected_Objects_Single_Entry =>
+                  --     Protected_Single_Entry_Call (
+                  --       Object => po._object'Access,
+                  --       Uninterpreted_Data => P'Address;
+                  --       Mode => Simple_Call);
+
+                  Call :=
+                    Make_Procedure_Call_Statement (Loc,
+                      Name => New_Reference_To (
+                        RTE (RE_Protected_Single_Entry_Call), Loc),
+
+                      Parameter_Associations => New_List (
+                        Make_Attribute_Reference (Loc,
+                          Attribute_Name => Name_Unchecked_Access,
+                          Prefix         => Parm1),
+                        Parm3,
+                        New_Reference_To (RTE (RE_Simple_Call), Loc)));
 
-                   Parameter_Associations => New_List (
-                     Make_Attribute_Reference (Loc,
-                       Attribute_Name => Name_Unchecked_Access,
-                       Prefix         => Parm1),
-                     Parm3,
-                     New_Reference_To (RTE (RE_Simple_Call), Loc)));
-            end if;
+               when others =>
+                  raise Program_Error;
+            end case;
 
          --  Case of task type
 
@@ -3144,11 +3157,11 @@ package body Exp_Ch9 is
    --------------------------------
 
    procedure Build_Task_Activation_Call (N : Node_Id) is
-      Loc        : constant Source_Ptr := Sloc (N);
-      Chain      : Entity_Id;
-      Call       : Node_Id;
-      Name       : Node_Id;
-      P          : Node_Id;
+      Loc   : constant Source_Ptr := Sloc (N);
+      Chain : Entity_Id;
+      Call  : Node_Id;
+      Name  : Node_Id;
+      P     : Node_Id;
 
    begin
       --  Get the activation chain entity. Except in the case of a package
@@ -3157,7 +3170,6 @@ package body Exp_Ch9 is
 
       if Nkind (N) = N_Package_Body then
          P := Corresponding_Spec (N);
-
          loop
             P := Parent (P);
             exit when Nkind (P) = N_Package_Declaration;
@@ -3198,7 +3210,7 @@ package body Exp_Ch9 is
          else
             if Present (Handled_Statement_Sequence (N)) then
 
-               --  The call goes at the start of the statement sequence, but
+               --  The call goes at the start of the statement sequence
                --  after the start of exception range label if one is present.
 
                declare
@@ -3207,10 +3219,33 @@ package body Exp_Ch9 is
                begin
                   Stm := First (Statements (Handled_Statement_Sequence (N)));
 
+                  --  A special case, skip exception range label if one is
+                  --  present (from front end zcx processing).
+
                   if Nkind (Stm) = N_Label and then Exception_Junk (Stm) then
                      Next (Stm);
                   end if;
 
+                  --  Another special case, if the first statement is a block
+                  --  from optimization of a local raise to a goto, then the
+                  --  call goes inside this block.
+
+                  if Nkind (Stm) = N_Block_Statement
+                    and then Exception_Junk (Stm)
+                  then
+                     Stm :=
+                       First (Statements (Handled_Statement_Sequence (Stm)));
+                  end if;
+
+                  --  Insertion point is after any exception label pushes,
+                  --  since we want it covered by any local handlers.
+
+                  while Nkind (Stm) in N_Push_xxx_Label loop
+                     Next (Stm);
+                  end loop;
+
+                  --  Now we have the proper insertion point
+
                   Insert_Before (Stm, Call);
                end;
 
@@ -3353,36 +3388,33 @@ package body Exp_Ch9 is
    -----------------------------------
 
    function Build_Task_Proc_Specification (T : Entity_Id) return Node_Id is
-      Loc : constant Source_Ptr := Sloc (T);
-      Nam : constant Name_Id    := Chars (T);
-      Ent : Entity_Id;
+      Loc     : constant Source_Ptr := Sloc (T);
+      Spec_Id : Entity_Id;
 
    begin
-      Ent :=
+      Spec_Id :=
         Make_Defining_Identifier (Loc,
-          Chars => New_External_Name (Nam, 'B'));
-      Set_Is_Internal (Ent);
+          Chars => New_External_Name (Chars (T), 'B'));
+      Set_Is_Internal (Spec_Id);
 
       --  Associate the procedure with the task, if this is the declaration
       --  (and not the body) of the procedure.
 
       if No (Task_Body_Procedure (T)) then
-         Set_Task_Body_Procedure (T, Ent);
+         Set_Task_Body_Procedure (T, Spec_Id);
       end if;
 
       return
         Make_Procedure_Specification (Loc,
-          Defining_Unit_Name       => Ent,
-          Parameter_Specifications =>
-            New_List (
-              Make_Parameter_Specification (Loc,
-                Defining_Identifier =>
-                  Make_Defining_Identifier (Loc, Name_uTask),
-                Parameter_Type =>
-                  Make_Access_Definition (Loc,
-                    Subtype_Mark =>
-                      New_Reference_To
-                        (Corresponding_Record_Type (T), Loc)))));
+          Defining_Unit_Name       => Spec_Id,
+          Parameter_Specifications => New_List (
+            Make_Parameter_Specification (Loc,
+              Defining_Identifier =>
+                Make_Defining_Identifier (Loc, Name_uTask),
+              Parameter_Type      =>
+                Make_Access_Definition (Loc,
+                  Subtype_Mark =>
+                    New_Reference_To (Corresponding_Record_Type (T), Loc)))));
    end Build_Task_Proc_Specification;
 
    ---------------------------------------
@@ -3393,25 +3425,24 @@ package body Exp_Ch9 is
      (N   : Node_Id;
       Pid : Node_Id) return Node_Id
    is
-      Loc       : constant Source_Ptr := Sloc (N);
-      N_Op_Spec : Node_Id;
-      Op_Decls  : List_Id;
+      Decls : constant List_Id := Declarations (N);
 
    begin
+      --  Add renamings for the Protection object, discriminals, privals and
+      --  the entry indix constant for use by debugger.
+
+      Debug_Private_Data_Declarations (Decls);
+
       --  Make an unprotected version of the subprogram for use within the same
       --  object, with a new name and an additional parameter representing the
       --  object.
 
-      Op_Decls := Declarations (N);
-      N_Op_Spec :=
-        Build_Protected_Sub_Specification (N, Pid, Unprotected_Mode);
-
       return
-        Make_Subprogram_Body (Loc,
-          Specification => N_Op_Spec,
-          Declarations => Op_Decls,
-          Handled_Statement_Sequence =>
-            Handled_Statement_Sequence (N));
+        Make_Subprogram_Body (Sloc (N),
+          Specification              =>
+            Build_Protected_Sub_Specification (N, Pid, Unprotected_Mode),
+          Declarations               => Decls,
+          Handled_Statement_Sequence => Handled_Statement_Sequence (N));
    end Build_Unprotected_Subprogram_Body;
 
    ----------------------------
@@ -3430,9 +3461,7 @@ package body Exp_Ch9 is
 
    begin
       Efam := First_Entity (Conctyp);
-
       while Present (Efam) loop
-
          if Ekind (Efam) = E_Entry_Family then
             Efam_Type :=
               Make_Defining_Identifier (Loc,
@@ -3442,6 +3471,7 @@ package body Exp_Ch9 is
                Bas : Entity_Id :=
                        Base_Type
                         (Etype (Discrete_Subtype_Definition (Parent (Efam))));
+
                Bas_Decl : Node_Id := Empty;
                Lo, Hi   : Node_Id;
 
@@ -3451,15 +3481,17 @@ package body Exp_Ch9 is
 
                if Is_Potentially_Large_Family (Bas, Conctyp, Lo, Hi) then
                   Bas :=
-                    Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
+                    Make_Defining_Identifier (Loc,
+                      Chars => New_Internal_Name ('B'));
+
                   Bas_Decl :=
                     Make_Subtype_Declaration (Loc,
                        Defining_Identifier => Bas,
-                       Subtype_Indication =>
+                       Subtype_Indication  =>
                          Make_Subtype_Indication (Loc,
                            Subtype_Mark =>
                              New_Occurrence_Of (Standard_Integer, Loc),
-                           Constraint =>
+                           Constraint   =>
                              Make_Range_Constraint (Loc,
                                Range_Expression => Make_Range (Loc,
                                  Make_Integer_Literal
@@ -3517,6 +3549,59 @@ package body Exp_Ch9 is
       end loop;
    end Collect_Entry_Families;
 
+   -----------------------
+   -- Concurrent_Object --
+   -----------------------
+
+   function Concurrent_Object
+     (Spec_Id  : Entity_Id;
+      Conc_Typ : Entity_Id) return Entity_Id
+   is
+   begin
+      --  Parameter _O or _object
+
+      if Is_Protected_Type (Conc_Typ) then
+         return First_Formal (Protected_Body_Subprogram (Spec_Id));
+
+      --  Parameter _task
+
+      else
+         pragma Assert (Is_Task_Type (Conc_Typ));
+         return First_Formal (Task_Body_Procedure (Conc_Typ));
+      end if;
+   end Concurrent_Object;
+
+   ----------------------
+   -- Copy_Result_Type --
+   ----------------------
+
+   function Copy_Result_Type (Res : Node_Id) return Node_Id is
+      New_Res  : constant Node_Id := New_Copy_Tree (Res);
+      Par_Spec : Node_Id;
+      Formal   : Entity_Id;
+
+   begin
+      --  If the result type is an access_to_subprogram, we must create
+      --  new entities for its spec.
+
+      if Nkind (New_Res) = N_Access_Definition
+        and then Present (Access_To_Subprogram_Definition (New_Res))
+      then
+         --  Provide new entities for the formals
+
+         Par_Spec := First (Parameter_Specifications
+                              (Access_To_Subprogram_Definition (New_Res)));
+         while Present (Par_Spec) loop
+            Formal := Defining_Identifier (Par_Spec);
+            Set_Defining_Identifier (Par_Spec,
+              Make_Defining_Identifier (Sloc (Formal), Chars (Formal)));
+            Next (Par_Spec);
+         end loop;
+      end if;
+
+      return New_Res;
+   end Copy_Result_Type;
+
    --------------------
    -- Concurrent_Ref --
    --------------------
@@ -3657,19 +3742,20 @@ package body Exp_Ch9 is
 
          else
             pragma Assert (Is_Protected_Type (Entity (N)));
+
             return
-              New_Reference_To (
-                Object_Ref (Corresponding_Body (Parent (Base_Type (Ntyp)))),
-                Loc);
+              New_Reference_To (Find_Protection_Object (Current_Scope), Loc);
          end if;
 
       else
-         pragma Assert (Is_Concurrent_Type (Ntyp));
-
          if Is_Protected_Type (Ntyp) then
             Sel := Name_uObject;
-         else
+
+         elsif Is_Task_Type (Ntyp) then
             Sel := Name_uTask_Id;
+
+         else
+            raise Program_Error;
          end if;
 
          return
@@ -3699,6 +3785,50 @@ package body Exp_Ch9 is
       end if;
    end Convert_Concurrent;
 
+   -------------------------------------
+   -- Debug_Private_Data_Declarations --
+   -------------------------------------
+
+   procedure Debug_Private_Data_Declarations (Decls : List_Id) is
+      Debug_Nod : Node_Id;
+      Decl      : Node_Id;
+
+   begin
+      Decl := First (Decls);
+      while Present (Decl)
+        and then not Comes_From_Source (Decl)
+      loop
+         --  Declaration for concurrent entity _object and its access type,
+         --  along with the entry index subtype:
+         --    type prot_typVP is access prot_typV;
+         --    _object : prot_typVP := prot_typV (_O);
+         --    subtype Jnn is <Type of Index> range Low .. High;
+
+         if Nkind_In (Decl, N_Full_Type_Declaration, N_Object_Declaration) then
+            Set_Debug_Info_Needed (Defining_Identifier (Decl));
+
+         --  Declaration for the Protection object, discriminals, privals and
+         --  entry index constant:
+         --    conc_typR   : protection_typ renames _object._object;
+         --    discr_nameD : discr_typ renames _object.discr_name;
+         --    discr_nameD : discr_typ renames _task.discr_name;
+         --    prival_name : comp_typ  renames _object.comp_name;
+         --    J : constant Jnn :=
+         --          Jnn'Val (_E - <Index expression> + Jnn'Pos (Jnn'First));
+
+         elsif Nkind (Decl) = N_Object_Renaming_Declaration then
+            Set_Debug_Info_Needed (Defining_Identifier (Decl));
+            Debug_Nod := Debug_Renaming_Declaration (Decl);
+
+            if Present (Debug_Nod) then
+               Insert_After (Decl, Debug_Nod);
+            end if;
+         end if;
+
+         Next (Decl);
+      end loop;
+   end Debug_Private_Data_Declarations;
+
    ----------------------------
    -- Entry_Index_Expression --
    ----------------------------
@@ -3868,7 +3998,8 @@ package body Exp_Ch9 is
 
    procedure Expand_Accept_Declarations (N : Node_Id; Ent : Entity_Id) is
       Loc    : constant Source_Ptr := Sloc (N);
-      Ann    : Entity_Id := Empty;
+      Stats  : constant Node_Id    := Handled_Statement_Sequence (N);
+      Ann    : Entity_Id           := Empty;
       Adecl  : Node_Id;
       Lab_Id : Node_Id;
       Lab    : Node_Id;
@@ -3878,20 +4009,13 @@ package body Exp_Ch9 is
    begin
       if Expander_Active then
 
-         --  If we have no handled statement sequence, then build a dummy
-         --  sequence consisting of a null statement. This is only done if
-         --  pragma FIFO_Within_Priorities is specified. The issue here is
-         --  that even a null accept body has an effect on the called task
-         --  in terms of its position in the queue, so we cannot optimize
-         --  the context switch away. However, if FIFO_Within_Priorities
-         --  is not active, the optimization is legitimate, since we can
-         --  say that our dispatching policy (i.e. the default dispatching
-         --  policy) reorders the queue to be the same as just before the
-         --  call. In the absence of a specified dispatching policy, we are
-         --  allowed to modify queue orders for a given priority at will!
-
-         if Opt.Task_Dispatching_Policy = 'F' and then
-           No (Handled_Statement_Sequence (N))
+         --  If we have no handled statement sequence, we may need to build
+         --  a dummy sequence consisting of a null statement. This can be
+         --  skipped if the trivial accept optimization is permitted.
+
+         if not Trivial_Accept_OK
+           and then
+             (No (Stats) or else Null_Statements (Statements (Stats)))
          then
             Set_Handled_Statement_Sequence (N,
               Make_Handled_Sequence_Of_Statements (Loc,
@@ -4023,7 +4147,7 @@ package body Exp_Ch9 is
 
          if Present (Ann) then
             Append_Elmt (Ann, Accept_Address (Ent));
-            Set_Needs_Debug_Info (Ann);
+            Set_Debug_Info_Needed (Ann);
          end if;
 
          --  Create renaming declarations for the entry formals. Each reference
@@ -4043,7 +4167,7 @@ package body Exp_Ch9 is
                New_F  : Entity_Id;
 
             begin
-               New_Scope (Ent);
+               Push_Scope (Ent);
                Formal := First_Formal (Ent);
 
                while Present (Formal) loop
@@ -4053,7 +4177,12 @@ package body Exp_Ch9 is
 
                   Set_Etype (New_F, Etype (Formal));
                   Set_Scope (New_F, Ent);
-                  Set_Needs_Debug_Info (New_F);   --  That's the whole point.
+
+               --  Now we set debug info needed on New_F even though it does
+               --  not come from source, so that the debugger will get the
+               --  right information for these generated names.
+
+                  Set_Debug_Info_Needed (New_F);
 
                   if Ekind (Formal) = E_In_Parameter then
                      Set_Ekind (New_F, E_Constant);
@@ -4109,7 +4238,7 @@ package body Exp_Ch9 is
       E_T    : constant Entity_Id  := Make_Defining_Identifier (Loc,
                                         Chars => New_Internal_Name ('E'));
       P_List : constant List_Id    := Build_Protected_Spec
-                                        (N, RTE (RE_Address), False, D_T);
+                                        (N, RTE (RE_Address), D_T, False);
       Decl1  : Node_Id;
       Decl2  : Node_Id;
       Def1   : Node_Id;
@@ -4122,7 +4251,7 @@ package body Exp_Ch9 is
            Make_Access_Function_Definition (Loc,
              Parameter_Specifications => P_List,
              Result_Definition =>
-               New_Copy (Result_Definition (Type_Definition (N))));
+               Copy_Result_Type (Result_Definition (Type_Definition (N))));
 
       else
          Def1 :=
@@ -4147,7 +4276,7 @@ package body Exp_Ch9 is
             Make_Defining_Identifier (Loc, New_Internal_Name ('P')),
           Component_Definition =>
             Make_Component_Definition (Loc,
-              Aliased_Present    => False,
+              Aliased_Present => False,
               Subtype_Indication =>
                 New_Occurrence_Of (RTE (RE_Address), Loc))),
 
@@ -4156,13 +4285,13 @@ package body Exp_Ch9 is
             Make_Defining_Identifier (Loc, New_Internal_Name ('S')),
           Component_Definition =>
             Make_Component_Definition (Loc,
-              Aliased_Present    => False,
+              Aliased_Present => False,
               Subtype_Indication => New_Occurrence_Of (D_T2, Loc))));
 
       Decl2 :=
         Make_Full_Type_Declaration (Loc,
           Defining_Identifier => E_T,
-          Type_Definition     =>
+          Type_Definition =>
             Make_Record_Definition (Loc,
               Component_List =>
                 Make_Component_List (Loc,
@@ -4178,11 +4307,10 @@ package body Exp_Ch9 is
    --------------------------
 
    procedure Expand_Entry_Barrier (N : Node_Id; Ent : Entity_Id) is
-      Loc       : constant Source_Ptr := Sloc (N);
-      Prot      : constant Entity_Id  := Scope (Ent);
-      Spec_Decl : constant Node_Id    := Parent (Prot);
-      Cond      : constant Node_Id    :=
+      Cond      : constant Node_Id   :=
                     Condition (Entry_Body_Formal_Part (N));
+      Prot      : constant Entity_Id := Scope (Ent);
+      Spec_Decl : constant Node_Id   := Parent (Prot);
       Func      : Node_Id;
       B_F       : Node_Id;
       Body_Decl : Node_Id;
@@ -4198,7 +4326,7 @@ package body Exp_Ch9 is
       --  unprotected version of a protected operation. The specification has
       --  been produced when the protected type declaration was elaborated. We
       --  build the body, insert it in the enclosing scope, but analyze it in
-      --  the current context. A more uniform approach would be to treat
+      --  the current context. A more uniform approach would be to treat the
       --  barrier just as a protected function, and discard the protected
       --  version of it because it is never called.
 
@@ -4215,9 +4343,6 @@ package body Exp_Ch9 is
 
          Insert_Before_And_Analyze (Body_Decl, B_F);
 
-         Update_Prival_Subtypes (B_F);
-
-         Set_Privals (Spec_Decl, N, Loc, After_Barrier => True);
          Set_Discriminals (Spec_Decl);
          Set_Scope (Func, Scope (Prot));
 
@@ -4237,6 +4362,18 @@ package body Exp_Ch9 is
       --  scope.
 
       if Is_Entity_Name (Cond) then
+
+         --  A small optimization of useless renamings. If the scope of the
+         --  entity of the condition is not the barrier function, then the
+         --  condition does not reference any of the generated renamings
+         --  within the function.
+
+         if Expander_Active
+           and then Scope (Entity (Cond)) /= Func
+         then
+            Set_Declarations (B_F, Empty_List);
+         end if;
+
          if Entity (Cond) = Standard_False
               or else
             Entity (Cond) = Standard_True
@@ -4268,32 +4405,6 @@ package body Exp_Ch9 is
       Check_Restriction (Simple_Barriers, Cond);
    end Expand_Entry_Barrier;
 
-   ------------------------------------
-   -- Expand_Entry_Body_Declarations --
-   ------------------------------------
-
-   procedure Expand_Entry_Body_Declarations (N : Node_Id) is
-      Loc        : constant Source_Ptr := Sloc (N);
-      Index_Spec : Node_Id;
-
-   begin
-      if Expander_Active then
-
-         --  Expand entry bodies corresponding to entry families
-         --  by assigning a placeholder for the constant that will
-         --  be used to expand references to the entry index parameter.
-
-         Index_Spec :=
-           Entry_Index_Specification (Entry_Body_Formal_Part (N));
-
-         if Present (Index_Spec) then
-            Set_Entry_Index_Constant (
-              Defining_Identifier (Index_Spec),
-              Make_Defining_Identifier (Loc, New_Internal_Name ('J')));
-         end if;
-      end if;
-   end Expand_Entry_Body_Declarations;
-
    ------------------------------
    -- Expand_N_Abort_Statement --
    ------------------------------
@@ -4322,7 +4433,7 @@ package body Exp_Ch9 is
 
          if Ada_Version >= Ada_05
            and then Ekind (Etype (Tasknm)) = E_Class_Wide_Type
-           and then Is_Interface      (Etype (Tasknm))
+           and then Is_Interface (Etype (Tasknm))
            and then Is_Task_Interface (Etype (Tasknm))
          then
             Append_To (Component_Associations (Aggr),
@@ -4331,13 +4442,17 @@ package body Exp_Ch9 is
                   Make_Integer_Literal (Loc, Count)),
                 Expression =>
 
-                  --  Tasknm._disp_get_task_id
+                  --  Task_Id (Tasknm._disp_get_task_id)
 
-                    Make_Selected_Component (Loc,
-                      Prefix =>
-                        New_Copy_Tree (Tasknm),
-                      Selector_Name =>
-                        Make_Identifier (Loc, Name_uDisp_Get_Task_Id))));
+                  Make_Unchecked_Type_Conversion (Loc,
+                    Subtype_Mark =>
+                      New_Reference_To (RTE (RO_ST_Task_Id), Loc),
+                    Expression =>
+                      Make_Selected_Component (Loc,
+                        Prefix =>
+                          New_Copy_Tree (Tasknm),
+                        Selector_Name =>
+                          Make_Identifier (Loc, Name_uDisp_Get_Task_Id)))));
 
          else
             Append_To (Component_Associations (Aggr),
@@ -4406,7 +4521,7 @@ package body Exp_Ch9 is
 
    --  The first three declarations were already inserted ahead of the accept
    --  statement by the Expand_Accept_Declarations procedure, which was called
-   --  directly from the semantics during analysis of the accept. statement,
+   --  directly from the semantics during analysis of the accept statement,
    --  before analyzing its contained statements.
 
    --  The declarations from the N_Accept_Statement, as noted in Sinfo, come
@@ -4434,30 +4549,6 @@ package body Exp_Ch9 is
       Call    : Node_Id;
       Block   : Node_Id;
 
-      function Null_Statements (Stats : List_Id) return Boolean;
-      --  Check for null statement sequence (i.e a list of labels and
-      --  null statements).
-
-      ---------------------
-      -- Null_Statements --
-      ---------------------
-
-      function Null_Statements (Stats : List_Id) return Boolean is
-         Stmt : Node_Id;
-
-      begin
-         Stmt := First (Stats);
-         while Nkind (Stmt) /= N_Empty
-           and then (Nkind (Stmt) = N_Null_Statement
-                       or else
-                     Nkind (Stmt) = N_Label)
-         loop
-            Next (Stmt);
-         end loop;
-
-         return Nkind (Stmt) = N_Empty;
-      end Null_Statements;
-
    --  Start of processing for Expand_N_Accept_Statement
 
    begin
@@ -4473,17 +4564,7 @@ package body Exp_Ch9 is
       --  If the accept statement has declarations, then just insert them
       --  before the procedure call.
 
-      --  We avoid this optimization when FIFO_Within_Priorities is active,
-      --  since it is not correct according to annex D semantics. The problem
-      --  is that the call is required to reorder the acceptors position on
-      --  its ready queue, even though there is nothing to be done. However,
-      --  if no policy is specified, then we decide that our dispatching
-      --  policy always reorders the queue right after the RV to look the
-      --  way they were just before the RV. Since we are allowed to freely
-      --  reorder same-priority queues (this is part of what dispatching
-      --  policies are all about), the optimization is legitimate.
-
-      elsif Opt.Task_Dispatching_Policy /= 'F'
+      elsif Trivial_Accept_OK
         and then (No (Stats) or else Null_Statements (Statements (Stats)))
       then
          --  Remove declarations for renamings, because the parameter block
@@ -4566,7 +4647,7 @@ package body Exp_Ch9 is
 
          Analyze (Call);
 
-         New_Scope (Blkent);
+         Push_Scope (Blkent);
 
          declare
             D      : Node_Id;
@@ -4647,18 +4728,18 @@ package body Exp_Ch9 is
    --    begin
    --       Abort_Defer;
    --       Task_Entry_Call
-   --         (acceptor-task,
-   --          entry-index,
-   --          P'Address,
-   --          Asynchronous_Call,
-   --          B);
+   --         (<acceptor-task>,    --  Acceptor
+   --          <entry-index>,      --  E
+   --          P'Address,          --  Uninterpreted_Data
+   --          Asynchronous_Call,  --  Mode
+   --          B);                 --  Rendezvous_Successful
 
    --       begin
    --          begin
    --             Abort_Undefer;
    --             <abortable-part>
    --          at end
-   --             _clean;        --  Added by Exp_Ch7.Expand_Cleanup_Actions.
+   --             _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
    --          end;
    --       exception
    --          when Abort_Signal => Abort_Undefer;
@@ -4672,9 +4753,9 @@ package body Exp_Ch9 is
    --       end if;
    --    end;
 
-   --  Note that Build_Simple_Entry_Call is used to expand the entry
-   --  of the asynchronous entry call (by the
-   --  Expand_N_Entry_Call_Statement procedure) as follows:
+   --  Note that Build_Simple_Entry_Call is used to expand the entry of the
+   --  asynchronous entry call (by Expand_N_Entry_Call_Statement procedure)
+   --  as follows:
 
    --    declare
    --       P : parms := (parm, parm, parm);
@@ -4687,8 +4768,8 @@ package body Exp_Ch9 is
 
    --  so the task at hand is to convert the latter expansion into the former
 
-   --  If the trigger is a protected entry call, the select is
-   --  implemented with Protected_Entry_Call:
+   --  If the trigger is a protected entry call, the select is implemented
+   --  with Protected_Entry_Call:
 
    --  declare
    --     P   : E1_Params := (param, param, param);
@@ -4696,7 +4777,9 @@ package body Exp_Ch9 is
 
    --  begin
    --     declare
-   --        --  Clean is added by Exp_Ch7.Expand_Cleanup_Actions.
+
+   --        --  Clean is added by Exp_Ch7.Expand_Cleanup_Actions
+
    --        procedure _clean is
    --        begin
    --           ...
@@ -4708,17 +4791,18 @@ package body Exp_Ch9 is
 
    --     begin
    --        begin
-   --           Protected_Entry_Call (
-   --             Object => po._object'Access,
-   --             E => <entry index>;
-   --             Uninterpreted_Data => P'Address;
-   --             Mode => Asynchronous_Call;
-   --             Block => Bnn);
+   --           Protected_Entry_Call
+   --             (po._object'Access,  --  Object
+   --              <entry index>,      --  E
+   --              P'Address,          --  Uninterpreted_Data
+   --              Asynchronous_Call,  --  Mode
+   --              Bnn);               --  Block
+
    --           if Enqueued (Bnn) then
    --              <abortable-part>
    --           end if;
    --        at end
-   --           _clean;        --  Added by Exp_Ch7.Expand_Cleanup_Actions.
+   --           _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
    --        end;
    --     exception
    --        when Abort_Signal => Abort_Undefer;
@@ -4729,20 +4813,20 @@ package body Exp_Ch9 is
    --     end if;
    --  end;
 
-   --  Build_Simple_Entry_Call is used to expand the all to a simple
-   --  protected entry call:
+   --  Build_Simple_Entry_Call is used to expand the all to a simple protected
+   --  entry call:
 
    --  declare
    --     P   : E1_Params := (param, param, param);
    --     Bnn : Communications_Block;
 
    --  begin
-   --     Protected_Entry_Call (
-   --       Object => po._object'Access,
-   --       E => <entry index>;
-   --       Uninterpreted_Data => P'Address;
-   --       Mode => Simple_Call;
-   --       Block => Bnn);
+   --     Protected_Entry_Call
+   --       (po._object'Access,  --  Object
+   --        <entry index>,      --  E
+   --        P'Address,          --  Uninterpreted_Data
+   --        Simple_Call,        --  Mode
+   --        Bnn);               --  Block
    --     parm := P.param;
    --     parm := P.param;
    --       ...
@@ -4755,6 +4839,7 @@ package body Exp_Ch9 is
    --       B   : Boolean := False;
    --       Bnn : Communication_Block;
    --       C   : Ada.Tags.Prim_Op_Kind;
+   --       D   : System.Storage_Elements.Dummy_Communication_Block;
    --       K   : Ada.Tags.Tagged_Kind :=
    --               Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
    --       P   : Parameters := (Param1 .. ParamN);
@@ -4767,8 +4852,9 @@ package body Exp_Ch9 is
    --          <triggering-statements>;
 
    --       else
-   --          S := Ada.Tags.Get_Offset_Index (Ada.Tags.Tag (<object>),
-   --                 DT_Position (<dispatching-call>));
+   --          S :=
+   --            Ada.Tags.Get_Offset_Index
+   --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
 
    --          _Disp_Get_Prim_Op_Kind (<object>, S, C);
 
@@ -4784,7 +4870,8 @@ package body Exp_Ch9 is
    --             begin
    --                begin
    --                   _Disp_Asynchronous_Select
-   --                     (<object>, S, P'address, Bnn, B);
+   --                     (<object>, S, P'Address, D, B);
+   --                   Bnn := Communication_Block (D);
 
    --                   Param1 := P.Param1;
    --                   ...
@@ -4794,7 +4881,7 @@ package body Exp_Ch9 is
    --                      <abortable-statements>
    --                   end if;
    --                at end
-   --                   _clean;
+   --                   _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
    --                end;
    --             exception
    --                when Abort_Signal => Abort_Undefer;
@@ -4815,7 +4902,8 @@ package body Exp_Ch9 is
    --                Abort_Defer;
 
    --                _Disp_Asynchronous_Select
-   --                  (<object>, S, P'address, Bnn, B);
+   --                  (<object>, S, P'Address, D, B);
+   --                Bnn := Communication_Bloc (D);
 
    --                Param1 := P.Param1;
    --                ...
@@ -4826,7 +4914,7 @@ package body Exp_Ch9 is
    --                      Abort_Undefer;
    --                      <abortable-statements>
    --                   at end
-   --                      _clean;
+   --                      _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
    --                   end;
    --                exception
    --                   when Abort_Signal => Abort_Undefer;
@@ -4855,8 +4943,8 @@ package body Exp_Ch9 is
    --  the entry call. This object is used by the runtime to queue the delay
    --  request.
 
-   --  For a description of the use of P and the assignments after the
-   --  call, see Expand_N_Entry_Call_Statement.
+   --  For a description of the use of P and the assignments after the call,
+   --  see Expand_N_Entry_Call_Statement.
 
    procedure Expand_N_Asynchronous_Select (N : Node_Id) is
       Loc    : constant Source_Ptr := Sloc (N);
@@ -4920,8 +5008,8 @@ package body Exp_Ch9 is
 
       if Nkind (Ecall) = N_Block_Statement then
          Ecall := First (Statements (Handled_Statement_Sequence (Ecall)));
-         while Nkind (Ecall) /= N_Procedure_Call_Statement
-           and then Nkind (Ecall) /= N_Entry_Call_Statement
+         while not Nkind_In (Ecall, N_Procedure_Call_Statement,
+                                    N_Entry_Call_Statement)
          loop
             Next (Ecall);
          end loop;
@@ -4934,10 +5022,9 @@ package body Exp_Ch9 is
          if Ada_Version >= Ada_05
            and then
              (No (Original_Node (Ecall))
-                or else
-                  (Nkind (Original_Node (Ecall)) /= N_Delay_Relative_Statement
-                     and then
-                   Nkind (Original_Node (Ecall)) /= N_Delay_Until_Statement))
+                or else not Nkind_In (Original_Node (Ecall),
+                                        N_Delay_Relative_Statement,
+                                        N_Delay_Until_Statement))
          then
             Extract_Dispatching_Call (Ecall, Call_Ent, Obj, Actuals, Formals);
 
@@ -4970,6 +5057,17 @@ package body Exp_Ch9 is
             --    K : Ada.Tags.Tagged_Kind :=
             --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
 
+            --  Dummy communication block, generate:
+            --    D : Dummy_Communication_Block;
+
+            Append_To (Decls,
+              Make_Object_Declaration (Loc,
+                Defining_Identifier =>
+                  Make_Defining_Identifier (Loc, Name_uD),
+                Object_Definition =>
+                  New_Reference_To (
+                    RTE (RE_Dummy_Communication_Block), Loc)));
+
             K := Build_K (Loc, Decls, Obj);
 
             --  Parameter block processing
@@ -4995,8 +5093,9 @@ package body Exp_Ch9 is
                 Object_Definition =>
                   New_Reference_To (Standard_Boolean, Loc)));
 
-            --  ---------------------------------------------------------------
-            --  Protected entry handling
+            ------------------------------
+            -- Protected entry handling --
+            ------------------------------
 
             --  Generate:
             --    Param1 := P.Param1;
@@ -5006,7 +5105,21 @@ package body Exp_Ch9 is
             Cleanup_Stmts := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
 
             --  Generate:
-            --    _Disp_Asynchronous_Select (<object>, S, P'address, Bnn, B);
+            --    Bnn := Communication_Block (D);
+
+            Prepend_To (Cleanup_Stmts,
+              Make_Assignment_Statement (Loc,
+                Name =>
+                  New_Reference_To (Bnn, Loc),
+                Expression =>
+                  Make_Unchecked_Type_Conversion (Loc,
+                    Subtype_Mark =>
+                      New_Reference_To (RTE (RE_Communication_Block), Loc),
+                    Expression =>
+                      Make_Identifier (Loc, Name_uD))));
+
+            --  Generate:
+            --    _Disp_Asynchronous_Select (<object>, S, P'Address, D, B);
 
             Prepend_To (Cleanup_Stmts,
               Make_Procedure_Call_Statement (Loc,
@@ -5017,13 +5130,15 @@ package body Exp_Ch9 is
                     Loc),
                 Parameter_Associations =>
                   New_List (
-                    New_Copy_Tree    (Obj),
-                    New_Reference_To (S, Loc),
-                    Make_Attribute_Reference (Loc,
-                      Prefix => New_Reference_To (P, Loc),
-                      Attribute_Name => Name_Address),
-                    New_Reference_To (Bnn, Loc),
-                    New_Reference_To (B, Loc))));
+                    New_Copy_Tree (Obj),             --  <object>
+                    New_Reference_To (S, Loc),       --  S
+                    Make_Attribute_Reference (Loc,   --  P'Address
+                      Prefix =>
+                        New_Reference_To (P, Loc),
+                      Attribute_Name =>
+                        Name_Address),
+                    Make_Identifier (Loc, Name_uD),  --  D
+                    New_Reference_To (B, Loc))));    --  B
 
             --  Generate:
             --    if Enqueued (Bnn) then
@@ -5081,7 +5196,8 @@ package body Exp_Ch9 is
             ProtE_Stmts :=
               New_List (
                 Make_Implicit_Label_Declaration (Loc,
-                  Defining_Identifier => Abort_Block_Ent),
+                  Defining_Identifier =>
+                    Abort_Block_Ent),
 
                 Build_Abort_Block
                   (Loc, Abort_Block_Ent, Cleanup_Block_Ent, Cleanup_Block));
@@ -5106,8 +5222,9 @@ package body Exp_Ch9 is
                 Then_Statements =>
                   New_Copy_List_Tree (Tstats)));
 
-            --  ---------------------------------------------------------------
-            --  Task entry handling
+            -------------------------
+            -- Task entry handling --
+            -------------------------
 
             --  Generate:
             --    Param1 := P.Param1;
@@ -5117,7 +5234,21 @@ package body Exp_Ch9 is
             TaskE_Stmts := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
 
             --  Generate:
-            --    _Disp_Asynchronous_Select (<object>, S, P'address, Bnn, B);
+            --    Bnn := Communication_Block (D);
+
+            Append_To (TaskE_Stmts,
+              Make_Assignment_Statement (Loc,
+                Name =>
+                  New_Reference_To (Bnn, Loc),
+                Expression =>
+                  Make_Unchecked_Type_Conversion (Loc,
+                    Subtype_Mark =>
+                      New_Reference_To (RTE (RE_Communication_Block), Loc),
+                    Expression =>
+                      Make_Identifier (Loc, Name_uD))));
+
+            --  Generate:
+            --    _Disp_Asynchronous_Select (<object>, S, P'Address, D, B);
 
             Prepend_To (TaskE_Stmts,
               Make_Procedure_Call_Statement (Loc,
@@ -5128,13 +5259,15 @@ package body Exp_Ch9 is
                     Loc),
                 Parameter_Associations =>
                   New_List (
-                    New_Copy_Tree    (Obj),
-                    New_Reference_To (S, Loc),
-                    Make_Attribute_Reference (Loc,
-                      Prefix => New_Reference_To (P, Loc),
-                      Attribute_Name => Name_Address),
-                    New_Reference_To (Bnn, Loc),
-                    New_Reference_To (B, Loc))));
+                    New_Copy_Tree (Obj),             --  <object>
+                    New_Reference_To (S, Loc),       --  S
+                    Make_Attribute_Reference (Loc,   --  P'Address
+                      Prefix =>
+                        New_Reference_To (P, Loc),
+                      Attribute_Name =>
+                        Name_Address),
+                    Make_Identifier (Loc, Name_uD),  --  D
+                    New_Reference_To (B, Loc))));    --  B
 
             --  Generate:
             --    Abort_Defer;
@@ -5194,7 +5327,8 @@ package body Exp_Ch9 is
 
             Append_To (TaskE_Stmts,
               Make_Implicit_Label_Declaration (Loc,
-                Defining_Identifier => Abort_Block_Ent));
+                Defining_Identifier =>
+                  Abort_Block_Ent));
 
             Append_To (TaskE_Stmts,
               Build_Abort_Block
@@ -5215,8 +5349,9 @@ package body Exp_Ch9 is
                 Then_Statements =>
                   New_Copy_List_Tree (Tstats)));
 
-            -------------------------------------------------------------------
-            --  Protected procedure handling
+            ----------------------------------
+            -- Protected procedure handling --
+            ----------------------------------
 
             --  Generate:
             --    <dispatching-call>;
@@ -5226,11 +5361,11 @@ package body Exp_Ch9 is
             Prepend_To (ProtP_Stmts, New_Copy_Tree (Ecall));
 
             --  Generate:
-            --    S := Ada.Tags.Get_Offset_Index (
-            --           Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
+            --    S := Ada.Tags.Get_Offset_Index
+            --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
 
-            Conc_Typ_Stmts := New_List (
-              Build_S_Assignment (Loc, S, Obj, Call_Ent));
+            Conc_Typ_Stmts :=
+              New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
 
             --  Generate:
             --    _Disp_Get_Prim_Op_Kind (<object>, S, C);
@@ -5244,7 +5379,7 @@ package body Exp_Ch9 is
                     Loc),
                 Parameter_Associations =>
                   New_List (
-                    New_Copy_Tree    (Obj),
+                    New_Copy_Tree (Obj),
                     New_Reference_To (S, Loc),
                     New_Reference_To (C, Loc))));
 
@@ -5511,17 +5646,17 @@ package body Exp_Ch9 is
              Has_Created_Identifier => True,
              Is_Asynchronous_Call_Block => True);
 
-         --  For the JVM call Update_Exception instead of Abort_Undefer.
+         --  For the VM call Update_Exception instead of Abort_Undefer.
          --  See 4jexcept.ads for an explanation.
 
-         if Hostparm.Java_VM then
+         if VM_Target = No_VM then
+            Target_Undefer := RE_Abort_Undefer;
+         else
             Target_Undefer := RE_Update_Exception;
             Undefer_Args :=
               New_List (Make_Function_Call (Loc,
                           Name => New_Occurrence_Of
                                     (RTE (RE_Current_Target_Exception), Loc)));
-         else
-            Target_Undefer := RE_Abort_Undefer;
          end if;
 
          Stmts := New_List (
@@ -5608,9 +5743,10 @@ package body Exp_Ch9 is
            Make_Implicit_Exception_Handler (Loc,
              Exception_Choices =>
                New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
-             Statements => New_List (
-               Make_Procedure_Call_Statement (Loc,
-                 Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)))));
+             Statements =>
+               New_List (
+                 Make_Procedure_Call_Statement (Loc,
+                   Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)))));
 
          Prepend_To (Astats,
            Make_Procedure_Call_Statement (Loc,
@@ -5631,8 +5767,10 @@ package body Exp_Ch9 is
                Make_Handled_Sequence_Of_Statements (Loc,
                  Statements => New_List (
                    Make_Implicit_Label_Declaration (Loc,
-                     Defining_Identifier => Blk_Ent,
-                     Label_Construct     => Abortable_Block),
+                     Defining_Identifier =>
+                       Blk_Ent,
+                     Label_Construct =>
+                       Abortable_Block),
                    Abortable_Block),
                  Exception_Handlers => Hdle)));
 
@@ -5694,11 +5832,11 @@ package body Exp_Ch9 is
 
    --    begin
    --       Task_Entry_Call
-   --         (acceptor-task,
-   --          entry-index,
-   --          P'Address,
-   --          Conditional_Call,
-   --          B);
+   --         (<acceptor-task>,   --  Acceptor
+   --          <entry-index>,     --  E
+   --          P'Address,         --  Uninterpreted_Data
+   --          Conditional_Call,  --  Mode
+   --          B);                --  Rendezvous_Successful
    --       parm := P.param;
    --       parm := P.param;
    --       ...
@@ -5709,10 +5847,10 @@ package body Exp_Ch9 is
    --       end if;
    --    end;
 
-   --  For a description of the use of P and the assignments after the
-   --  call, see Expand_N_Entry_Call_Statement. Note that the entry call
-   --  of the conditional entry call has already been expanded (by the
-   --  Expand_N_Entry_Call_Statement procedure) as follows:
+   --  For a description of the use of P and the assignments after the call,
+   --  see Expand_N_Entry_Call_Statement. Note that the entry call of the
+   --  conditional entry call has already been expanded (by the Expand_N_Entry
+   --  _Call_Statement procedure) as follows:
 
    --    declare
    --       P : parms := (parm, parm, parm);
@@ -5734,12 +5872,12 @@ package body Exp_Ch9 is
    --       Bnn : Communications_Block;
 
    --    begin
-   --       Protected_Entry_Call (
-   --         Object => po._object'Access,
-   --         E => <entry index>;
-   --         Uninterpreted_Data => P'Address;
-   --         Mode => Conditional_Call;
-   --         Block => Bnn);
+   --       Protected_Entry_Call
+   --         (po._object'Access,  --  Object
+   --          <entry index>,      --  E
+   --          P'Address,          --  Uninterpreted_Data
+   --          Conditional_Call,   --  Mode
+   --          Bnn);               --  Block
    --       parm := P.param;
    --       parm := P.param;
    --       ...
@@ -5750,26 +5888,6 @@ package body Exp_Ch9 is
    --       end if;
    --    end;
 
-   --  As for tasks, the entry call of the conditional entry call has
-   --  already been expanded (by the Expand_N_Entry_Call_Statement procedure)
-   --  as follows:
-
-   --    declare
-   --       P   : E1_Params := (param, param, param);
-   --       Bnn : Communications_Block;
-
-   --    begin
-   --       Protected_Entry_Call (
-   --         Object => po._object'Access,
-   --         E => <entry index>;
-   --         Uninterpreted_Data => P'Address;
-   --         Mode => Simple_Call;
-   --         Block => Bnn);
-   --       parm := P.param;
-   --       parm := P.param;
-   --         ...
-   --    end;
-
    --  Ada 2005 (AI-345): A dispatching conditional entry call is converted
    --  into:
 
@@ -5787,10 +5905,11 @@ package body Exp_Ch9 is
    --          <triggering-statements>
 
    --       else
-   --          S := Ada.Tags.Get_Offset_Index (Ada.Tags.Tag (<object>),
-   --                 DT_Position (<dispatching-call>));
+   --          S :=
+   --            Ada.Tags.Get_Offset_Index
+   --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
 
-   --          _Disp_Conditional_Select (<object>, S, P'address, C, B);
+   --          _Disp_Conditional_Select (<object>, S, P'Address, C, B);
 
    --          if C = POK_Protected_Entry
    --            or else C = POK_Task_Entry
@@ -5819,7 +5938,6 @@ package body Exp_Ch9 is
       Loc : constant Source_Ptr := Sloc (N);
       Alt : constant Node_Id    := Entry_Call_Alternative (N);
       Blk : Node_Id             := Entry_Call_Statement (Alt);
-      Transient_Blk : Node_Id;
 
       Actuals        : List_Id;
       Blk_Typ        : Entity_Id;
@@ -5836,6 +5954,7 @@ package body Exp_Ch9 is
       Params         : List_Id;
       Stmt           : Node_Id;
       Stmts          : List_Id;
+      Transient_Blk  : Node_Id;
       Unpack         : List_Id;
 
       B : Entity_Id;  --  Call status flag
@@ -5881,14 +6000,14 @@ package body Exp_Ch9 is
          S := Build_S (Loc, Decls);
 
          --  Generate:
-         --    S := Ada.Tags.Get_Offset_Index (
-         --           Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
+         --    S := Ada.Tags.Get_Offset_Index
+         --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
 
-         Conc_Typ_Stmts := New_List (
-           Build_S_Assignment (Loc, S, Obj, Call_Ent));
+         Conc_Typ_Stmts :=
+           New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
 
          --  Generate:
-         --    _Disp_Conditional_Select (<object>, S, P'address, C, B);
+         --    _Disp_Conditional_Select (<object>, S, P'Address, C, B);
 
          Append_To (Conc_Typ_Stmts,
            Make_Procedure_Call_Statement (Loc,
@@ -5899,13 +6018,15 @@ package body Exp_Ch9 is
                  Loc),
              Parameter_Associations =>
                New_List (
-                 New_Copy_Tree    (Obj),
-                 New_Reference_To (S, Loc),
-                 Make_Attribute_Reference (Loc,
-                   Prefix => New_Reference_To (P, Loc),
-                   Attribute_Name => Name_Address),
-                 New_Reference_To (C, Loc),
-                 New_Reference_To (B, Loc))));
+                 New_Copy_Tree (Obj),            --  <object>
+                 New_Reference_To (S, Loc),      --  S
+                 Make_Attribute_Reference (Loc,  --  P'Address
+                   Prefix =>
+                     New_Reference_To (P, Loc),
+                   Attribute_Name =>
+                     Name_Address),
+                 New_Reference_To (C, Loc),      --  C
+                 New_Reference_To (B, Loc))));   --  B
 
          --  Generate:
          --    if C = POK_Protected_Entry
@@ -5994,7 +6115,7 @@ package body Exp_Ch9 is
 
          Append_To (Conc_Typ_Stmts,
            Make_If_Statement (Loc,
-             Condition       => New_Reference_To (B, Loc),
+             Condition => New_Reference_To (B, Loc),
              Then_Statements => N_Stats,
              Else_Statements => Else_Statements (N)));
 
@@ -6029,7 +6150,8 @@ package body Exp_Ch9 is
 
          Rewrite (N,
            Make_Block_Statement (Loc,
-             Declarations               => Decls,
+             Declarations =>
+               Decls,
              Handled_Statement_Sequence =>
                Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
 
@@ -6042,7 +6164,7 @@ package body Exp_Ch9 is
 
       else
          Transient_Blk :=
-            First_Real_Statement (Handled_Statement_Sequence (Blk));
+           First_Real_Statement (Handled_Statement_Sequence (Blk));
 
          if Present (Transient_Blk)
            and then Nkind (Transient_Blk) = N_Block_Statement
@@ -6194,48 +6316,12 @@ package body Exp_Ch9 is
    -------------------------
 
    procedure Expand_N_Entry_Body (N : Node_Id) is
-      Loc         : constant Source_Ptr := Sloc (N);
-      Dec         : constant Node_Id    := Parent (Current_Scope);
-      Ent_Formals : constant Node_Id    := Entry_Body_Formal_Part (N);
-      Index_Spec  : constant Node_Id    :=
-                      Entry_Index_Specification (Ent_Formals);
-      Next_Op     : Node_Id;
-      First_Decl  : constant Node_Id := First (Declarations (N));
-      Index_Decl  : List_Id;
-
    begin
-      --  Add the renamings for private declarations and discriminants
-
-      Add_Discriminal_Declarations
-        (Declarations (N), Defining_Identifier (Dec), Name_uObject, Loc);
-      Add_Private_Declarations
-        (Declarations (N), Defining_Identifier (Dec), Name_uObject, Loc);
-
-      if Present (Index_Spec) then
-         Index_Decl :=
-           Index_Constant_Declaration
-             (N,
-               Defining_Identifier (Index_Spec), Defining_Identifier (Dec));
-
-         --  If the entry has local declarations, insert index declaration
-         --  before them, because the index may be used therein.
-
-         if Present (First_Decl) then
-            Insert_List_Before (First_Decl, Index_Decl);
-         else
-            Append_List_To (Declarations (N), Index_Decl);
-         end if;
-      end if;
+      --  Associate discriminals with the next protected operation body to be
+      --  expanded.
 
-      --  Associate privals and discriminals with the next protected operation
-      --  body to be expanded. These are used to expand references to private
-      --  data objects and discriminants, respectively.
-
-      Next_Op := Next_Protected_Operation (N);
-
-      if Present (Next_Op) then
-         Set_Privals (Dec, Next_Op, Loc);
-         Set_Discriminals (Dec);
+      if Present (Next_Protected_Operation (N)) then
+         Set_Discriminals (Parent (Current_Scope));
       end if;
    end Expand_N_Entry_Body;
 
@@ -6243,8 +6329,8 @@ package body Exp_Ch9 is
    -- Expand_N_Entry_Call_Statement --
    -----------------------------------
 
-   --  An entry call is expanded into GNARLI calls to implement
-   --  a simple entry call (see Build_Simple_Entry_Call).
+   --  An entry call is expanded into GNARLI calls to implement a simple entry
+   --  call (see Build_Simple_Entry_Call).
 
    procedure Expand_N_Entry_Call_Statement (N : Node_Id) is
       Concval : Node_Id;
@@ -6487,7 +6573,6 @@ package body Exp_Ch9 is
    procedure Expand_N_Protected_Body (N : Node_Id) is
       Loc          : constant Source_Ptr := Sloc (N);
       Pid          : constant Entity_Id  := Corresponding_Spec (N);
-      Has_Entries  : Boolean := False;
       Op_Body      : Node_Id;
       Op_Decl      : Node_Id;
       Op_Id        : Entity_Id;
@@ -6563,7 +6648,7 @@ package body Exp_Ch9 is
 
             Stmts :=
               New_List (
-                Make_Return_Statement (Loc,
+                Make_Simple_Return_Statement (Loc,
                   Expression =>
                     Make_Function_Call (Loc,
                       Name =>
@@ -6646,10 +6731,8 @@ package body Exp_Ch9 is
                   Current_Node := New_Op_Body;
                   Analyze (New_Op_Body);
 
-                  Update_Prival_Subtypes (New_Op_Body);
-
                   --  Build the corresponding protected operation. It may
-                  --  appear that this is needed only this is a visible
+                  --  appear that this is needed only if this is a visible
                   --  operation of the type, or if it is an interrupt handler,
                   --  and this was the strategy used previously in GNAT.
                   --  However, the operation may be exported through a
@@ -6660,14 +6743,14 @@ package body Exp_Ch9 is
 
                   if Present (Corresponding_Spec (Op_Body)) then
                      Op_Decl :=
-                        Unit_Declaration_Node (Corresponding_Spec (Op_Body));
+                       Unit_Declaration_Node (Corresponding_Spec (Op_Body));
 
-                     if
-                       Nkind (Parent (Op_Decl)) = N_Protected_Definition
+                     if Nkind (Parent (Op_Decl)) =
+                          N_Protected_Definition
                      then
                         New_Op_Body :=
-                           Build_Protected_Subprogram_Body (
-                             Op_Body, Pid, Specification (New_Op_Body));
+                          Build_Protected_Subprogram_Body (
+                            Op_Body, Pid, Specification (New_Op_Body));
 
                         Insert_After (Current_Node, New_Op_Body);
                         Analyze (New_Op_Body);
@@ -6697,7 +6780,6 @@ package body Exp_Ch9 is
 
             when N_Entry_Body =>
                Op_Id := Defining_Identifier (Op_Body);
-               Has_Entries := True;
                Num_Entries := Num_Entries + 1;
 
                New_Op_Body := Build_Protected_Entry (Op_Body, Op_Id, Pid);
@@ -6706,8 +6788,6 @@ package body Exp_Ch9 is
                Current_Node := New_Op_Body;
                Analyze (New_Op_Body);
 
-               Update_Prival_Subtypes (New_Op_Body);
-
             when N_Implicit_Label_Declaration =>
                null;
 
@@ -6750,14 +6830,10 @@ package body Exp_Ch9 is
 
       --  Finally, create the body of the function that maps an entry index
       --  into the corresponding body index, except when there is no entry,
-      --  or in a ravenscar-like profile (no abort, no entry queue, 1 entry)
-
-      if Has_Entries
-        and then (Abort_Allowed
-                  or else Restriction_Active (No_Entry_Queue) = False
-                  or else Num_Entries > 1
-                  or else (Has_Attach_Handler (Pid)
-                            and then not Restricted_Profile))
+      --  or in a ravenscar-like profile.
+
+      if Corresponding_Runtime_Package (Pid) =
+           System_Tasking_Protected_Objects_Entries
       then
          New_Op_Body := Build_Find_Body_Index (Pid);
          Insert_After (Current_Node, New_Op_Body);
@@ -6774,12 +6850,12 @@ package body Exp_Ch9 is
       if Ada_Version >= Ada_05
         and then Present (Protected_Definition (Parent (Pid)))
         and then Present (Abstract_Interfaces
-                          (Corresponding_Record_Type (Pid)))
+                           (Corresponding_Record_Type (Pid)))
       then
          declare
             Vis_Decl  : Node_Id :=
                           First (Visible_Declarations
-                                 (Protected_Definition (Parent (Pid))));
+                                  (Protected_Definition (Parent (Pid))));
             Wrap_Body : Node_Id;
 
          begin
@@ -6903,10 +6979,10 @@ package body Exp_Ch9 is
    --  the specs refer to this type.
 
    procedure Expand_N_Protected_Type_Declaration (N : Node_Id) is
-      Loc     : constant Source_Ptr := Sloc (N);
-      Prottyp : constant Entity_Id  := Defining_Identifier (N);
+      Loc      : constant Source_Ptr := Sloc (N);
+      Prot_Typ : constant Entity_Id  := Defining_Identifier (N);
 
-      Pdef : constant Node_Id := Protected_Definition (N);
+      Pdef     : constant Node_Id    := Protected_Definition (N);
       --  This contains two lists; one for visible and one for private decls
 
       Rec_Decl     : Node_Id;
@@ -6961,14 +7037,14 @@ package body Exp_Ch9 is
    --  Start of processing for Expand_N_Protected_Type_Declaration
 
    begin
-      if Present (Corresponding_Record_Type (Prottyp)) then
+      if Present (Corresponding_Record_Type (Prot_Typ)) then
          return;
       else
-         Rec_Decl := Build_Corresponding_Record (N, Prottyp, Loc);
-         Cdecls   := Component_Items
-                      (Component_List (Type_Definition (Rec_Decl)));
+         Rec_Decl := Build_Corresponding_Record (N, Prot_Typ, Loc);
       end if;
 
+      Cdecls := Component_Items (Component_List (Type_Definition (Rec_Decl)));
+
       --  Ada 2005 (AI-345): Propagate the attribute that contains the list
       --  of implemented interfaces.
 
@@ -6987,12 +7063,13 @@ package body Exp_Ch9 is
       --  This replacement is not applied to default expressions, for which
       --  the discriminal is correct.
 
-      if Has_Discriminants (Prottyp) then
+      if Has_Discriminants (Prot_Typ) then
          declare
             Disc : Entity_Id;
             Decl : Node_Id;
+
          begin
-            Disc := First_Discriminant (Prottyp);
+            Disc := First_Discriminant (Prot_Typ);
             Decl := First (Discriminant_Specifications (Rec_Decl));
             while Present (Disc) loop
                Append_Elmt (Discriminal (Disc), Discr_Map);
@@ -7008,7 +7085,7 @@ package body Exp_Ch9 is
       --  Add components for entry families. For each entry family, create an
       --  anonymous type declaration with the same size, and analyze the type.
 
-      Collect_Entry_Families (Loc, Cdecls, Current_Node, Prottyp);
+      Collect_Entry_Families (Loc, Cdecls, Current_Node, Prot_Typ);
 
       --  Prepend the _Object field with the right type to the component list.
       --  We need to compute the number of entries, and in some cases the
@@ -7020,14 +7097,16 @@ package body Exp_Ch9 is
          Protection_Subtype : Node_Id;
          Entry_Count_Expr   : constant Node_Id :=
                                 Build_Entry_Count_Expression
-                                  (Prottyp, Cdecls, Loc);
+                                  (Prot_Typ, Cdecls, Loc);
 
       begin
-         if Has_Attach_Handler (Prottyp) then
-            Ritem := First_Rep_Item (Prottyp);
+         --  Could this be simplified using Corresponding_Runtime_Package???
+
+         if Has_Attach_Handler (Prot_Typ) then
+            Ritem := First_Rep_Item (Prot_Typ);
             while Present (Ritem) loop
                if Nkind (Ritem) = N_Pragma
-                 and then Chars (Ritem) = Name_Attach_Handler
+                 and then Pragma_Name (Ritem) = Name_Attach_Handler
                then
                   Num_Attach_Handler := Num_Attach_Handler + 1;
                end if;
@@ -7036,7 +7115,7 @@ package body Exp_Ch9 is
             end loop;
 
             if Restricted_Profile then
-               if Has_Entries (Prottyp) then
+               if Has_Entries (Prot_Typ) then
                   Protection_Subtype :=
                     New_Reference_To (RTE (RE_Protection_Entry), Loc);
                else
@@ -7058,7 +7137,7 @@ package body Exp_Ch9 is
                           Make_Integer_Literal (Loc, Num_Attach_Handler))));
             end if;
 
-         elsif Has_Interrupt_Handler (Prottyp) then
+         elsif Has_Interrupt_Handler (Prot_Typ) then
             Protection_Subtype :=
                Make_Subtype_Indication (
                  Sloc => Loc,
@@ -7071,28 +7150,28 @@ package body Exp_Ch9 is
 
          --  Type has explicit entries or generated primitive entry wrappers
 
-         elsif Has_Entries (Prottyp)
+         elsif Has_Entries (Prot_Typ)
            or else (Ada_Version >= Ada_05
                       and then Present (Interface_List (N)))
          then
-            if Abort_Allowed
-              or else Restriction_Active (No_Entry_Queue) = False
-              or else Number_Entries (Prottyp) > 1
-            then
-               Protection_Subtype :=
-                  Make_Subtype_Indication (
-                    Sloc => Loc,
-                    Subtype_Mark =>
-                      New_Reference_To (RTE (RE_Protection_Entries), Loc),
-                    Constraint =>
-                      Make_Index_Or_Discriminant_Constraint (
-                        Sloc => Loc,
-                        Constraints => New_List (Entry_Count_Expr)));
+            case Corresponding_Runtime_Package (Prot_Typ) is
+               when System_Tasking_Protected_Objects_Entries =>
+                  Protection_Subtype :=
+                     Make_Subtype_Indication (Loc,
+                       Subtype_Mark =>
+                         New_Reference_To (RTE (RE_Protection_Entries), Loc),
+                       Constraint =>
+                         Make_Index_Or_Discriminant_Constraint (
+                           Sloc => Loc,
+                           Constraints => New_List (Entry_Count_Expr)));
+
+               when System_Tasking_Protected_Objects_Single_Entry =>
+                  Protection_Subtype :=
+                    New_Reference_To (RTE (RE_Protection_Entry), Loc);
 
-            else
-               Protection_Subtype :=
-                 New_Reference_To (RTE (RE_Protection_Entry), Loc);
-            end if;
+               when others =>
+                  raise Program_Error;
+            end case;
 
          else
             Protection_Subtype := New_Reference_To (RTE (RE_Protection), Loc);
@@ -7167,7 +7246,7 @@ package body Exp_Ch9 is
                  Make_Subprogram_Declaration (Loc,
                    Specification =>
                      Build_Protected_Sub_Specification
-                       (Priv, Prottyp, Unprotected_Mode));
+                       (Priv, Prot_Typ, Unprotected_Mode));
 
                Insert_After (Current_Node, Sub);
                Analyze (Sub);
@@ -7182,7 +7261,7 @@ package body Exp_Ch9 is
                  Make_Subprogram_Declaration (Loc,
                    Specification =>
                      Build_Protected_Sub_Specification
-                       (Priv, Prottyp, Protected_Mode));
+                       (Priv, Prot_Typ, Protected_Mode));
 
                Insert_After (Current_Node, Sub);
                Analyze (Sub);
@@ -7285,7 +7364,7 @@ package body Exp_Ch9 is
       --  add an expression to the aggregate which is the initial value of
       --  this array. The array is declared after all protected subprograms.
 
-      if Has_Entries (Prottyp) then
+      if Has_Entries (Prot_Typ) then
          Entries_Aggr :=
            Make_Aggregate (Loc, Expressions => New_List);
 
@@ -7312,7 +7391,7 @@ package body Exp_Ch9 is
               Make_Subprogram_Declaration (Loc,
                 Specification =>
                   Build_Protected_Sub_Specification
-                    (Comp, Prottyp, Unprotected_Mode));
+                    (Comp, Prot_Typ, Unprotected_Mode));
 
             Insert_After (Current_Node, Sub);
             Analyze (Sub);
@@ -7330,7 +7409,7 @@ package body Exp_Ch9 is
               Make_Subprogram_Declaration (Loc,
                 Specification =>
                   Build_Protected_Sub_Specification
-                    (Comp, Prottyp, Protected_Mode));
+                    (Comp, Prot_Typ, Protected_Mode));
 
             Insert_After (Current_Node, Sub);
             Analyze (Sub);
@@ -7338,18 +7417,18 @@ package body Exp_Ch9 is
             Current_Node := Sub;
 
             --  Generate an overriding primitive operation specification for
-            --  this subprogram if the protected type implements an inerface.
+            --  this subprogram if the protected type implements an interface.
 
             if Ada_Version >= Ada_05
               and then
                 Present (Abstract_Interfaces
-                          (Corresponding_Record_Type (Prottyp)))
+                          (Corresponding_Record_Type (Prot_Typ)))
             then
                Sub :=
                  Make_Subprogram_Declaration (Loc,
                    Specification =>
                      Build_Protected_Sub_Specification
-                       (Comp, Prottyp, Dispatching_Mode));
+                       (Comp, Prot_Typ, Dispatching_Mode));
 
                Insert_After (Current_Node, Sub);
                Analyze (Sub);
@@ -7374,31 +7453,31 @@ package body Exp_Ch9 is
          elsif Nkind (Comp) = N_Entry_Declaration then
             E_Count := E_Count + 1;
             Comp_Id := Defining_Identifier (Comp);
-            Set_Privals_Chain (Comp_Id, New_Elmt_List);
+
             Edef :=
               Make_Defining_Identifier (Loc,
-                Build_Selected_Name (Prottyp, Comp_Id, 'E'));
+                Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
             Sub :=
               Make_Subprogram_Declaration (Loc,
                 Specification =>
-                  Build_Protected_Entry_Specification (Edef, Comp_Id, Loc));
+                  Build_Protected_Entry_Specification (Loc, Edef, Comp_Id));
 
             Insert_After (Current_Node, Sub);
             Analyze (Sub);
 
-            Set_Protected_Body_Subprogram (
-              Defining_Identifier (Comp),
-              Defining_Unit_Name (Specification (Sub)));
-
+            Set_Protected_Body_Subprogram
+              (Defining_Identifier (Comp),
+               Defining_Unit_Name (Specification (Sub)));
+
             Current_Node := Sub;
 
             Bdef :=
               Make_Defining_Identifier (Loc,
-                Build_Selected_Name (Prottyp, Comp_Id, 'B'));
+                Chars => Build_Selected_Name (Prot_Typ, Comp_Id, 'B'));
             Sub :=
               Make_Subprogram_Declaration (Loc,
                 Specification =>
-                  Build_Barrier_Function_Specification (Bdef, Loc));
+                  Build_Barrier_Function_Specification (Loc, Bdef));
 
             Insert_After (Current_Node, Sub);
             Analyze (Sub);
@@ -7435,33 +7514,32 @@ package body Exp_Ch9 is
             if Nkind (Comp) = N_Entry_Declaration then
                E_Count := E_Count + 1;
                Comp_Id := Defining_Identifier (Comp);
-               Set_Privals_Chain (Comp_Id, New_Elmt_List);
+
                Edef :=
                  Make_Defining_Identifier (Loc,
-                  Build_Selected_Name (Prottyp, Comp_Id, 'E'));
-
+                  Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
                Sub :=
                  Make_Subprogram_Declaration (Loc,
                    Specification =>
-                     Build_Protected_Entry_Specification (Edef, Comp_Id, Loc));
+                     Build_Protected_Entry_Specification (Loc, Edef, Comp_Id));
 
                Insert_After (Current_Node, Sub);
                Analyze (Sub);
 
-               Set_Protected_Body_Subprogram (
-                 Defining_Identifier (Comp),
-                 Defining_Unit_Name (Specification (Sub)));
+               Set_Protected_Body_Subprogram
+                 (Defining_Identifier (Comp),
+                  Defining_Unit_Name (Specification (Sub)));
 
                Current_Node := Sub;
 
                Bdef :=
                  Make_Defining_Identifier (Loc,
-                    Build_Selected_Name (Prottyp, Comp_Id, 'E'));
+                   Chars => Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
 
                Sub :=
                  Make_Subprogram_Declaration (Loc,
                    Specification =>
-                     Build_Barrier_Function_Specification (Bdef, Loc));
+                     Build_Barrier_Function_Specification (Loc, Bdef));
 
                Insert_After (Current_Node, Sub);
                Analyze (Sub);
@@ -7473,7 +7551,7 @@ package body Exp_Ch9 is
                --  Collect pointers to the protected subprogram and the barrier
                --  of the current entry, for insertion into Entry_Bodies_Array.
 
-               Append (
+               Append_To (Expressions (Entries_Aggr),
                  Make_Aggregate (Loc,
                    Expressions => New_List (
                      Make_Attribute_Reference (Loc,
@@ -7481,8 +7559,7 @@ package body Exp_Ch9 is
                        Attribute_Name => Name_Unrestricted_Access),
                      Make_Attribute_Reference (Loc,
                        Prefix => New_Reference_To (Edef, Loc),
-                       Attribute_Name => Name_Unrestricted_Access))),
-                 Expressions (Entries_Aggr));
+                       Attribute_Name => Name_Unrestricted_Access))));
             end if;
 
             Next (Comp);
@@ -7492,46 +7569,47 @@ package body Exp_Ch9 is
       --  Emit declaration for Entry_Bodies_Array, now that the addresses of
       --  all protected subprograms have been collected.
 
-      if Has_Entries (Prottyp) then
-         Body_Id := Make_Defining_Identifier (Sloc (Prottyp),
-           New_External_Name (Chars (Prottyp), 'A'));
-
-         if Abort_Allowed
-           or else Restriction_Active (No_Entry_Queue) = False
-           or else E_Count > 1
-           or else (Has_Attach_Handler (Prottyp)
-                     and then not Restricted_Profile)
-         then
-            Body_Arr := Make_Object_Declaration (Loc,
-              Defining_Identifier => Body_Id,
-              Aliased_Present => True,
-              Object_Definition =>
-                Make_Subtype_Indication (Loc,
-                  Subtype_Mark => New_Reference_To (
-                    RTE (RE_Protected_Entry_Body_Array), Loc),
-                  Constraint =>
-                    Make_Index_Or_Discriminant_Constraint (Loc,
-                      Constraints => New_List (
-                         Make_Range (Loc,
-                           Make_Integer_Literal (Loc, 1),
-                           Make_Integer_Literal (Loc, E_Count))))),
-              Expression => Entries_Aggr);
+      if Has_Entries (Prot_Typ) then
+         Body_Id :=
+           Make_Defining_Identifier (Sloc (Prot_Typ),
+             Chars => New_External_Name (Chars (Prot_Typ), 'A'));
+
+         case Corresponding_Runtime_Package (Prot_Typ) is
+            when System_Tasking_Protected_Objects_Entries =>
+               Body_Arr := Make_Object_Declaration (Loc,
+                 Defining_Identifier => Body_Id,
+                 Aliased_Present => True,
+                 Object_Definition =>
+                   Make_Subtype_Indication (Loc,
+                     Subtype_Mark => New_Reference_To (
+                       RTE (RE_Protected_Entry_Body_Array), Loc),
+                     Constraint =>
+                       Make_Index_Or_Discriminant_Constraint (Loc,
+                         Constraints => New_List (
+                            Make_Range (Loc,
+                              Make_Integer_Literal (Loc, 1),
+                              Make_Integer_Literal (Loc, E_Count))))),
+                 Expression => Entries_Aggr);
+
+            when System_Tasking_Protected_Objects_Single_Entry =>
+               Body_Arr := Make_Object_Declaration (Loc,
+                 Defining_Identifier => Body_Id,
+                 Aliased_Present => True,
+                 Object_Definition => New_Reference_To
+                                        (RTE (RE_Entry_Body), Loc),
+                 Expression =>
+                   Make_Aggregate (Loc,
+                     Expressions => New_List (
+                       Make_Attribute_Reference (Loc,
+                         Prefix => New_Reference_To (Bdef, Loc),
+                         Attribute_Name => Name_Unrestricted_Access),
+                       Make_Attribute_Reference (Loc,
+                         Prefix => New_Reference_To (Edef, Loc),
+                         Attribute_Name => Name_Unrestricted_Access))));
 
-         else
-            Body_Arr := Make_Object_Declaration (Loc,
-              Defining_Identifier => Body_Id,
-              Aliased_Present => True,
-              Object_Definition => New_Reference_To (RTE (RE_Entry_Body), Loc),
-              Expression =>
-                Make_Aggregate (Loc,
-                  Expressions => New_List (
-                    Make_Attribute_Reference (Loc,
-                      Prefix => New_Reference_To (Bdef, Loc),
-                      Attribute_Name => Name_Unrestricted_Access),
-                    Make_Attribute_Reference (Loc,
-                      Prefix => New_Reference_To (Edef, Loc),
-                      Attribute_Name => Name_Unrestricted_Access))));
-         end if;
+            when others =>
+               raise Program_Error;
+         end case;
 
          --  A pointer to this array will be placed in the corresponding record
          --  by its initialization procedure so this needs to be analyzed here.
@@ -7540,22 +7618,19 @@ package body Exp_Ch9 is
          Current_Node := Body_Arr;
          Analyze (Body_Arr);
 
-         Set_Entry_Bodies_Array (Prottyp, Body_Id);
+         Set_Entry_Bodies_Array (Prot_Typ, Body_Id);
 
          --  Finally, build the function that maps an entry index into the
          --  corresponding body. A pointer to this function is placed in each
          --  object of the type. Except for a ravenscar-like profile (no abort,
          --  no entry queue, 1 entry)
 
-         if Abort_Allowed
-           or else Restriction_Active (No_Entry_Queue) = False
-           or else E_Count > 1
-           or else (Has_Attach_Handler (Prottyp)
-                     and then not Restricted_Profile)
+         if Corresponding_Runtime_Package (Prot_Typ) =
+              System_Tasking_Protected_Objects_Entries
          then
             Sub :=
               Make_Subprogram_Declaration (Loc,
-                Specification => Build_Find_Body_Index_Spec (Prottyp));
+                Specification => Build_Find_Body_Index_Spec (Prot_Typ));
             Insert_After (Current_Node, Sub);
             Analyze (Sub);
          end if;
@@ -7566,12 +7641,13 @@ package body Exp_Ch9 is
    -- Expand_N_Requeue_Statement --
    --------------------------------
 
-   --  A requeue statement is expanded into one of four GNARLI operations,
-   --  depending on the source and destination (task or protected object). In
-   --  addition, code must be generated to jump around the remainder of
-   --  processing for the original entry and, if the destination is (different)
-   --  protected object, to attempt to service it. The following illustrates
-   --  the various cases:
+   --  A non-dispatching requeue statement is expanded into one of four GNARLI
+   --  operations, depending on the source and destination (task or protected
+   --  object). A dispatching requeue statement is expanded into a call to the
+   --  predefined primitive _Disp_Requeue. In addition, code is generated to
+   --  jump around the remainder of processing for the original entry and, if
+   --  the destination is (different) protected object, to attempt to service
+   --  it. The following illustrates the various cases:
 
    --  procedure entE
    --    (O : System.Address;
@@ -7581,7 +7657,7 @@ package body Exp_Ch9 is
    --     <discriminant renamings>
    --     <private object renamings>
    --     type poVP is access poV;
-   --     _Object : ptVP := ptVP!(O);
+   --     _object : ptVP := ptVP!(O);
 
    --  begin
    --     begin
@@ -7608,12 +7684,12 @@ package body Exp_Ch9 is
    --        return;
 
    --        <rest of statement sequence for entry>
-   --        Complete_Entry_Body (_Object._Object);
+   --        Complete_Entry_Body (_object._object);
 
    --     exception
    --        when all others =>
    --           Exceptional_Complete_Entry_Body (
-   --             _Object._Object, Get_GNAT_Exception);
+   --             _object._object, Get_GNAT_Exception);
    --     end;
    --  end entE;
 
@@ -7649,108 +7725,251 @@ package body Exp_Ch9 is
    --     when all others =>
    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
 
-   --  Further details on these expansions can be found in
-   --  Expand_N_Protected_Body and Expand_N_Accept_Statement.
+   --  Ada 2005 (AI05-0030): Dispatching requeue from protected to interface
+   --  class-wide type:
+
+   --  procedure entE
+   --    (O : System.Address;
+   --     P : System.Address;
+   --     E : Protected_Entry_Index)
+   --  is
+   --     <discriminant renamings>
+   --     <private object renamings>
+   --     type poVP is access poV;
+   --     _object : ptVP := ptVP!(O);
+
+   --  begin
+   --     begin
+   --        <start of statement sequence for entry>
+
+   --        _Disp_Requeue
+   --          (<interface class-wide object>,
+   --           True,
+   --           _object'Address,
+   --           Ada.Tags.Get_Offset_Index
+   --             (Tag (_object),
+   --              <interface dispatch table index of target entry>),
+   --           Abort_Present);
+   --        return;
+
+   --        <rest of statement sequence for entry>
+   --        Complete_Entry_Body (_object._object);
+
+   --     exception
+   --        when all others =>
+   --           Exceptional_Complete_Entry_Body (
+   --             _object._object, Get_GNAT_Exception);
+   --     end;
+   --  end entE;
+
+   --  Ada 2005 (AI05-0030): Dispatching requeue from task to interface
+   --  class-wide type:
+
+   --  Accept_Call (E, Ann);
+   --     <start of statement sequence for accept statement>
+   --     _Disp_Requeue
+   --       (<interface class-wide object>,
+   --        False,
+   --        null,
+   --        Ada.Tags.Get_Offset_Index
+   --          (Tag (_object),
+   --           <interface dispatch table index of target entrt>),
+   --        Abort_Present);
+   --     newS (new, Pnn);
+   --     goto Lnn;
+   --     <rest of statement sequence for accept statement>
+   --     <<Lnn>>
+   --     Complete_Rendezvous;
+
+   --  exception
+   --     when all others =>
+   --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
+
+   --  Further details on these expansions can be found in Expand_N_Protected_
+   --  Body and Expand_N_Accept_Statement.
 
    procedure Expand_N_Requeue_Statement (N : Node_Id) is
       Loc        : constant Source_Ptr := Sloc (N);
+      Abortable  : Node_Id;
       Acc_Stat   : Node_Id;
+      Conc_Typ   : Entity_Id;
       Concval    : Node_Id;
       Ename      : Node_Id;
       Index      : Node_Id;
-      Conctyp    : Entity_Id;
-      Oldtyp     : Entity_Id;
       Lab_Node   : Node_Id;
-      Rcall      : Node_Id;
-      Abortable  : Node_Id;
-      Skip_Stat  : Node_Id;
-      Self_Param : Node_Id;
       New_Param  : Node_Id;
+      Old_Typ    : Entity_Id;
       Params     : List_Id;
+      Rcall      : Node_Id;
       RTS_Call   : Entity_Id;
+      Self_Param : Node_Id;
+      Skip_Stat  : Node_Id;
 
    begin
       Abortable :=
         New_Occurrence_Of (Boolean_Literals (Abort_Present (N)), Loc);
 
-      --  Set up the target object
+      --  Extract the components of the entry call
 
       Extract_Entry (N, Concval, Ename, Index);
-      Conctyp := Etype (Concval);
-      New_Param := Concurrent_Ref (Concval);
+      Conc_Typ := Etype (Concval);
 
-      --  The target entry index and abortable flag are the same for all cases
+      --  Examine the scope stack in order to find nearest enclosing protected
+      --  or task type. This will constitute our invocation source.
 
-      Params := New_List (
-        Entry_Index_Expression (Loc, Entity (Ename), Index, Conctyp),
-        Abortable);
+      Old_Typ := Current_Scope;
+      while Present (Old_Typ)
+        and then not Is_Protected_Type (Old_Typ)
+        and then not Is_Task_Type (Old_Typ)
+      loop
+         Old_Typ := Scope (Old_Typ);
+      end loop;
 
-      --  Determine proper GNARLI call and required additional parameters
-      --  Loop to find nearest enclosing task type or protected type
+      --  Generate the parameter list for all cases. The abortable flag is
+      --  common among dispatching and regular requeue.
 
-      Oldtyp := Current_Scope;
-      loop
-         if Is_Task_Type (Oldtyp) then
-            if Is_Task_Type (Conctyp) then
-               RTS_Call := RTE (RE_Requeue_Task_Entry);
+      Params := New_List (Abortable);
 
-            else
-               pragma Assert (Is_Protected_Type (Conctyp));
-               RTS_Call := RTE (RE_Requeue_Task_To_Protected_Entry);
-               New_Param :=
-                 Make_Attribute_Reference (Loc,
-                   Prefix => New_Param,
-                   Attribute_Name => Name_Unchecked_Access);
-            end if;
+      --  Ada 2005 (AI05-0030): We have a dispatching requeue of the form
+      --  Concval.Ename where the type of Concval is class-wide concurrent
+      --  interface.
 
-            Prepend (New_Param, Params);
-            exit;
+      if Ada_Version >= Ada_05
+        and then Present (Concval)
+        and then Is_Class_Wide_Type (Conc_Typ)
+        and then Is_Concurrent_Interface (Conc_Typ)
+      then
+         RTS_Call := Make_Identifier (Loc, Name_uDisp_Requeue);
+
+         --  Generate:
+         --    Ada.Tags.Get_Offset_Index
+         --      (Ada.Tags.Tag (Concval),
+         --       <interface dispatch table position of Ename>)
+
+         Prepend_To (Params,
+           Make_Function_Call (Loc,
+             Name =>
+               New_Reference_To (RTE (RE_Get_Offset_Index), Loc),
+             Parameter_Associations =>
+               New_List (
+                 Unchecked_Convert_To (RTE (RE_Tag), Concval),
+                 Make_Integer_Literal (Loc, DT_Position (Entity (Ename))))));
+
+         --  Specific actuals for protected to interface class-wide type
+         --  requeue.
+
+         if Is_Protected_Type (Old_Typ) then
+            Prepend_To (Params,
+              Make_Attribute_Reference (Loc,        --  _object'Address
+                Prefix =>
+                  Concurrent_Ref (New_Occurrence_Of (Old_Typ, Loc)),
+                Attribute_Name =>
+                  Name_Address));
+            Prepend_To (Params,                     --  True
+              New_Reference_To (Standard_True, Loc));
+
+         --  Specific actuals for task to interface class-wide type requeue
+
+         else
+            pragma Assert (Is_Task_Type (Old_Typ));
+
+            Prepend_To (Params,                     --  null
+              New_Reference_To (RTE (RE_Null_Address), Loc));
+            Prepend_To (Params,                     --  False
+              New_Reference_To (Standard_False, Loc));
+         end if;
 
-         elsif Is_Protected_Type (Oldtyp) then
+         --  Finally, add the common object parameter
+
+         Prepend_To (Params, New_Copy_Tree (Concval));
+
+      --  Regular requeue processing
+
+      else
+         New_Param := Concurrent_Ref (Concval);
+
+         --  The index expression is common among all four cases
+
+         Prepend_To (Params,
+           Entry_Index_Expression (Loc, Entity (Ename), Index, Conc_Typ));
+
+         if Is_Protected_Type (Old_Typ) then
             Self_Param :=
               Make_Attribute_Reference (Loc,
-                Prefix => Concurrent_Ref (New_Occurrence_Of (Oldtyp, Loc)),
-                Attribute_Name => Name_Unchecked_Access);
+                Prefix =>
+                  Concurrent_Ref (New_Occurrence_Of (Old_Typ, Loc)),
+                Attribute_Name =>
+                  Name_Unchecked_Access);
 
-            if Is_Task_Type (Conctyp) then
-               RTS_Call := RTE (RE_Requeue_Protected_To_Task_Entry);
+            --  Protected to protected requeue
+
+            if Is_Protected_Type (Conc_Typ) then
+               RTS_Call :=
+                 New_Reference_To (RTE (RE_Requeue_Protected_Entry), Loc);
 
-            else
-               pragma Assert (Is_Protected_Type (Conctyp));
-               RTS_Call := RTE (RE_Requeue_Protected_Entry);
                New_Param :=
                  Make_Attribute_Reference (Loc,
-                   Prefix => New_Param,
-                   Attribute_Name => Name_Unchecked_Access);
+                   Prefix =>
+                     New_Param,
+                   Attribute_Name =>
+                     Name_Unchecked_Access);
+
+            --  Protected to task requeue
+
+            else
+               pragma Assert (Is_Task_Type (Conc_Typ));
+               RTS_Call :=
+                 New_Reference_To (
+                   RTE (RE_Requeue_Protected_To_Task_Entry), Loc);
             end if;
 
             Prepend (New_Param, Params);
             Prepend (Self_Param, Params);
-            exit;
-
-         --  If neither task type or protected type, must be in some inner
-         --  enclosing block, so move on out
 
          else
-            Oldtyp := Scope (Oldtyp);
+            pragma Assert (Is_Task_Type (Old_Typ));
+
+            --  Task to protected requeue
+
+            if Is_Protected_Type (Conc_Typ) then
+               RTS_Call :=
+                 New_Reference_To (
+                   RTE (RE_Requeue_Task_To_Protected_Entry), Loc);
+
+               New_Param :=
+                 Make_Attribute_Reference (Loc,
+                   Prefix =>
+                     New_Param,
+                   Attribute_Name =>
+                     Name_Unchecked_Access);
+
+            --  Task to task requeue
+
+            else
+               pragma Assert (Is_Task_Type (Conc_Typ));
+               RTS_Call :=
+                 New_Reference_To (RTE (RE_Requeue_Task_Entry), Loc);
+            end if;
+
+            Prepend (New_Param, Params);
          end if;
-      end loop;
+      end if;
 
-      --  Create the GNARLI call
+      --  Create the GNARLI or predefined primitive call
 
-      Rcall := Make_Procedure_Call_Statement (Loc,
-        Name =>
-          New_Occurrence_Of (RTS_Call, Loc),
-        Parameter_Associations => Params);
+      Rcall :=
+        Make_Procedure_Call_Statement (Loc,
+          Name => RTS_Call,
+          Parameter_Associations => Params);
 
       Rewrite (N, Rcall);
       Analyze (N);
 
-      if Is_Protected_Type (Oldtyp) then
+      if Is_Protected_Type (Old_Typ) then
 
          --  Build the return statement to skip the rest of the entry body
 
-         Skip_Stat := Make_Return_Statement (Loc);
+         Skip_Stat := Make_Simple_Return_Statement (Loc);
 
       else
          --  If the requeue is within a task, find the end label of the
@@ -8001,7 +8220,9 @@ package body Exp_Ch9 is
               Make_Defining_Identifier (Sloc (Ename),
                 New_External_Name (Chars (Ename), 'A', Num_Accept));
 
-            Set_Needs_Debug_Info (PB_Ent, Comes_From_Source (Alt));
+            if Comes_From_Source (Alt) then
+               Set_Debug_Info_Needed (PB_Ent);
+            end if;
 
             Proc_Body :=
               Make_Subprogram_Body (Loc,
@@ -8313,7 +8534,7 @@ package body Exp_Ch9 is
             Add_Accept (Alt);
 
          elsif Nkind (Alt) = N_Delay_Alternative then
-            Delay_Count   := Delay_Count + 1;
+            Delay_Count := Delay_Count + 1;
 
             --  If the delays are relative delays, the delay expressions have
             --  type Standard_Duration. Otherwise they must have some time type
@@ -8330,7 +8551,7 @@ package body Exp_Ch9 is
                   null;
                else
                   Error_Msg_NE (
-                    "& is not a time type ('R'M 9.6(6))",
+                    "& is not a time type (RM 9.6(6))",
                        Expression (Delay_Statement (Alt)), Time_Type);
                   Time_Type := Standard_Duration;
                   Set_Etype (Expression (Delay_Statement (Alt)), Any_Type);
@@ -8913,9 +9134,11 @@ package body Exp_Ch9 is
       New_N : Node_Id;
 
    begin
-      --  Here we start the expansion by generating discriminal declarations
+      --  Add renaming declarations for discriminals and a declaration for the
+      --  entry family index (if applicable).
 
-      Add_Discriminal_Declarations (Declarations (N), Ttyp, Name_uTask, Loc);
+      Install_Private_Data_Declarations
+        (Loc, Task_Body_Procedure (Ttyp), Ttyp, N, Declarations (N));
 
       --  Add a call to Abort_Undefer at the very beginning of the task
       --  body since this body is called with abort still deferred.
@@ -8946,15 +9169,15 @@ package body Exp_Ch9 is
 
       New_N :=
         Make_Subprogram_Body (Loc,
-          Specification => Build_Task_Proc_Specification (Ttyp),
-          Declarations  => Declarations (N),
+          Specification              => Build_Task_Proc_Specification (Ttyp),
+          Declarations               => Declarations (N),
           Handled_Statement_Sequence => Handled_Statement_Sequence (N));
 
-      --  If the task contains generic instantiations, cleanup actions
-      --  are delayed until after instantiation. Transfer the activation
-      --  chain to the subprogram, to insure that the activation call is
-      --  properly generated. It the task body contains inner tasks, indicate
-      --  that the subprogram is a task master.
+      --  If the task contains generic instantiations, cleanup actions are
+      --  delayed until after instantiation. Transfer the activation chain to
+      --  the subprogram, to insure that the activation call is properly
+      --  generated. It the task body contains inner tasks, indicate that the
+      --  subprogram is a task master.
 
       if Delay_Cleanups (Ttyp) then
          Set_Activation_Chain_Entity (New_N, Activation_Chain_Entity (N));
@@ -9008,7 +9231,6 @@ package body Exp_Ch9 is
                if Nkind (Vis_Decl) = N_Entry_Declaration
                  and then Ekind (Defining_Identifier (Vis_Decl)) = E_Entry
                then
-
                   --  Create the specification of the wrapper
 
                   Wrap_Body :=
@@ -9052,6 +9274,10 @@ package body Exp_Ch9 is
    --  or
    --    taskZ : Size_Type := Size_Type (size_expression);
 
+   --  Note: No variable is needed to hold the task relative deadline since
+   --  its value would never be static because the parameter is of a private
+   --  type (Ada.Real_Time.Time_Span).
+
    --  Next we create a corresponding record type declaration used to represent
    --  values of this task. The general form of this type declaration is
 
@@ -9094,6 +9320,11 @@ package body Exp_Ch9 is
    --  present in the pragma, and is used to provide the Task_Image parameter
    --  to the call to Create_Task.
 
+   --  The _Relative_Deadline field is present only if a Relative_Deadline
+   --  pragma appears in the task definition. The expression captures the
+   --  argument that was present in the pragma, and is used to provide the
+   --  Relative_Deadline parameter to the call to Create_Task.
+
    --  When a task is declared, an instance of the task value record is
    --  created. The elaboration of this declaration creates the correct bounds
    --  for the entry families, and also evaluates the size, priority, and
@@ -9125,10 +9356,10 @@ package body Exp_Ch9 is
    --  the case of a simple entry.
 
    procedure Expand_N_Task_Type_Declaration (N : Node_Id) is
-      Loc       : constant Source_Ptr := Sloc (N);
-      Tasktyp   : constant Entity_Id  := Etype (Defining_Identifier (N));
-      Tasknm    : constant Name_Id    := Chars (Tasktyp);
-      Taskdef   : constant Node_Id    := Task_Definition (N);
+      Loc     : constant Source_Ptr := Sloc (N);
+      Tasktyp : constant Entity_Id  := Etype (Defining_Identifier (N));
+      Tasknm  : constant Name_Id    := Chars (Tasktyp);
+      Taskdef : constant Node_Id    := Task_Definition (N);
 
       Proc_Spec  : Node_Id;
       Rec_Decl   : Node_Id;
@@ -9345,7 +9576,7 @@ package body Exp_Ch9 is
             --  the benefit of some versions of System.Interrupts which use
             --  a special server task with maximum interrupt priority.
 
-            if Chars (Prag) = Name_Priority
+            if Pragma_Name (Prag) = Name_Priority
               and then not GNAT_Mode
             then
                Rewrite (Expr, Convert_To (RTE (RE_Priority), Expr));
@@ -9412,6 +9643,34 @@ package body Exp_Ch9 is
                      (Taskdef, Name_Task_Info)))))));
       end if;
 
+      --  Add the _Relative_Deadline component if a Relative_Deadline pragma is
+      --  present. If we are using a restricted run time this component will
+      --  not be added (deadlines are not allowed by the Ravenscar profile).
+
+      if not Restricted_Profile
+        and then Present (Taskdef)
+        and then Has_Relative_Deadline_Pragma (Taskdef)
+      then
+         Append_To (Cdecls,
+           Make_Component_Declaration (Loc,
+             Defining_Identifier =>
+               Make_Defining_Identifier (Loc, Name_uRelative_Deadline),
+
+             Component_Definition =>
+               Make_Component_Definition (Loc,
+                 Aliased_Present    => False,
+                 Subtype_Indication =>
+                   New_Reference_To (RTE (RE_Time_Span), Loc)),
+
+             Expression =>
+               Convert_To (RTE (RE_Time_Span),
+                 Relocate_Node (
+                   Expression (First (
+                     Pragma_Argument_Associations (
+                       Find_Task_Or_Protected_Pragma
+                         (Taskdef, Name_Relative_Deadline))))))));
+      end if;
+
       Insert_After (Size_Decl, Rec_Decl);
 
       --  Analyze the record declaration immediately after construction,
@@ -9432,8 +9691,9 @@ package body Exp_Ch9 is
       --  The subprogram does not comes from source, so we have to indicate the
       --  need for debugging information explicitly.
 
-      Set_Needs_Debug_Info
-        (Defining_Entity (Proc_Spec), Comes_From_Source (Original_Node (N)));
+      if Comes_From_Source (Original_Node (N)) then
+         Set_Debug_Info_Needed (Defining_Entity (Proc_Spec));
+      end if;
 
       --  Ada 2005 (AI-345): Construct the primitive entry wrapper specs before
       --  the corresponding record has been frozen.
@@ -9539,8 +9799,8 @@ package body Exp_Ch9 is
    --       P  : parms := (parm, parm, parm);
 
    --    begin
-   --       Timed_Protected_Entry_Call (<acceptor-task>, X, P'Address,
-   --         DX, M, B);
+   --       Timed_Protected_Entry_Call
+   --         (<acceptor-task>, X, P'Address, DX, M, B);
    --       if B then
    --          S1;
    --       else
@@ -9558,8 +9818,8 @@ package body Exp_Ch9 is
    --       P  : parms := (parm, parm, parm);
 
    --    begin
-   --       Timed_Protected_Entry_Call (<object>'unchecked_access, X,
-   --         P'Address, DX, M, B);
+   --       Timed_Protected_Entry_Call
+   --         (<object>'unchecked_access, X, P'Address, DX, M, B);
    --       if B then
    --          S1;
    --       else
@@ -9573,8 +9833,8 @@ package body Exp_Ch9 is
    --       B  : Boolean := False;
    --       C  : Ada.Tags.Prim_Op_Kind;
    --       DX : Duration := To_Duration (D)
-   --       K : Ada.Tags.Tagged_Kind :=
-   --             Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
+   --       K  : Ada.Tags.Tagged_Kind :=
+   --              Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
    --       M  : Integer :=...;
    --       P  : Parameters := (Param1 .. ParamN);
    --       S  : Iteger;
@@ -9585,8 +9845,9 @@ package body Exp_Ch9 is
    --          <triggering-statements>
 
    --       else
-   --          S := Ada.Tags.Get_Offset_Index (Ada.Tags.Tag (<object>),
-   --                 DT_Position (<dispatching-call>));
+   --          S :=
+   --            Ada.Tags.Get_Offset_Index
+   --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
 
    --          _Disp_Timed_Select (<object>, S, P'Address, DX, M, C, B);
 
@@ -9620,7 +9881,7 @@ package body Exp_Ch9 is
                   Entry_Call_Statement (Entry_Call_Alternative (N));
       E_Stats : constant List_Id :=
                   Statements (Entry_Call_Alternative (N));
-      D_Stat  : constant Node_Id :=
+      D_Stat  : Node_Id :=
                   Delay_Statement (Delay_Alternative (N));
       D_Stats : constant List_Id :=
                   Statements (Delay_Alternative (N));
@@ -9639,6 +9900,7 @@ package body Exp_Ch9 is
       Ename          : Node_Id;
       Formals        : List_Id;
       Index          : Node_Id;
+      Is_Disp_Select : Boolean;
       Lim_Typ_Stmts  : List_Id;
       N_Stats        : List_Id;
       Obj            : Entity_Id;
@@ -9664,21 +9926,39 @@ package body Exp_Ch9 is
 
       if Nkind (E_Call) = N_Block_Statement then
          E_Call := First (Statements (Handled_Statement_Sequence (E_Call)));
-         while Nkind (E_Call) /= N_Procedure_Call_Statement
-           and then Nkind (E_Call) /= N_Entry_Call_Statement
+         while not Nkind_In (E_Call, N_Procedure_Call_Statement,
+                                     N_Entry_Call_Statement)
          loop
             Next (E_Call);
          end loop;
       end if;
 
-      if Ada_Version >= Ada_05
-        and then Nkind (E_Call) = N_Procedure_Call_Statement
-      then
+      Is_Disp_Select :=
+        Ada_Version >= Ada_05
+          and then Nkind (E_Call) = N_Procedure_Call_Statement;
+
+      if Is_Disp_Select then
          Extract_Dispatching_Call (E_Call, Call_Ent, Obj, Actuals, Formals);
 
          Decls := New_List;
          Stmts := New_List;
 
+         --  Generate:
+         --    B : Boolean := False;
+
+         B := Build_B (Loc, Decls);
+
+         --  Generate:
+         --    C : Ada.Tags.Prim_Op_Kind;
+
+         C := Build_C (Loc, Decls);
+
+         --  Because the analysis of all statements was disabled, manually
+         --  analyze the delay statement.
+
+         Analyze (D_Stat);
+         D_Stat := Original_Node (D_Stat);
+
       else
          --  Build an entry call using Simple_Entry_Call
 
@@ -9691,19 +9971,7 @@ package body Exp_Ch9 is
          if No (Decls) then
             Decls := New_List;
          end if;
-      end if;
-
-      --  Call status flag processing
-
-      if Ada_Version >= Ada_05
-        and then Nkind (E_Call) = N_Procedure_Call_Statement
-      then
-         --  Generate:
-         --    B : Boolean := False;
-
-         B := Build_B (Loc, Decls);
 
-      else
          --  Generate:
          --    B : Boolean;
 
@@ -9717,23 +9985,12 @@ package body Exp_Ch9 is
                New_Reference_To (Standard_Boolean, Loc)));
       end if;
 
-      --  Call kind processing
-
-      if Ada_Version >= Ada_05
-        and then Nkind (E_Call) = N_Procedure_Call_Statement
-      then
-         --  Generate:
-         --    C : Ada.Tags.Prim_Op_Kind;
-
-         C := Build_C (Loc, Decls);
-      end if;
-
       --  Duration and mode processing
 
       D_Type := Base_Type (Etype (Expression (D_Stat)));
 
-      --  Use the type of the delay expression (Calendar or Real_Time)
-      --  to generate the appropriate conversion.
+      --  Use the type of the delay expression (Calendar or Real_Time) to
+      --  generate the appropriate conversion.
 
       if Nkind (D_Stat) = N_Delay_Relative_Statement then
          D_Disc := Make_Integer_Literal (Loc, 0);
@@ -9778,7 +10035,7 @@ package body Exp_Ch9 is
           Expression =>
             D_Disc));
 
-      --  Do the assignement at this stage only because the evaluation of the
+      --  Do the assignment at this stage only because the evaluation of the
       --  expression must not occur before (see ACVC C97302A).
 
       Append_To (Stmts,
@@ -9794,9 +10051,8 @@ package body Exp_Ch9 is
       --  case of entries, the block has already been created during the call
       --  to Build_Simple_Entry_Call.
 
-      if Ada_Version >= Ada_05
-        and then Nkind (E_Call) = N_Procedure_Call_Statement
-      then
+      if Is_Disp_Select then
+
          --  Tagged kind processing, generate:
          --    K : Ada.Tags.Tagged_Kind :=
          --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag <object>));
@@ -9804,8 +10060,8 @@ package body Exp_Ch9 is
          K := Build_K (Loc, Decls, Obj);
 
          Blk_Typ := Build_Parameter_Block (Loc, Actuals, Formals, Decls);
-         P       := Parameter_Block_Pack  (Loc, Blk_Typ, Actuals, Formals,
-                      Decls, Stmts);
+         P := Parameter_Block_Pack
+                (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
 
          --  Dispatch table slot processing, generate:
          --    S : Integer;
@@ -9813,14 +10069,14 @@ package body Exp_Ch9 is
          S := Build_S (Loc, Decls);
 
          --  Generate:
-         --    S := Ada.Tags.Get_Offset_Index (
-         --           Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
+         --    S := Ada.Tags.Get_Offset_Index
+         --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
 
-         Conc_Typ_Stmts := New_List (
-           Build_S_Assignment (Loc, S, Obj, Call_Ent));
+         Conc_Typ_Stmts :=
+           New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
 
          --  Generate:
-         --    _Disp_Timed_Select (<object>, S, P'address, D, M, C, B);
+         --    _Disp_Timed_Select (<object>, S, P'Address, D, M, C, B);
 
          --  where Obj is the controlling formal parameter, S is the dispatch
          --  table slot number of the dispatching operation, P is the wrapped
@@ -9829,7 +10085,7 @@ package body Exp_Ch9 is
 
          Params := New_List;
 
-         Append_To (Params, New_Copy_Tree    (Obj));
+         Append_To (Params, New_Copy_Tree (Obj));
          Append_To (Params, New_Reference_To (S, Loc));
          Append_To (Params, Make_Attribute_Reference (Loc,
                               Prefix => New_Reference_To (P, Loc),
@@ -9936,7 +10192,7 @@ package body Exp_Ch9 is
 
          Append_To (Conc_Typ_Stmts,
            Make_If_Statement (Loc,
-             Condition       => New_Reference_To (B, Loc),
+             Condition => New_Reference_To (B, Loc),
              Then_Statements => N_Stats,
              Else_Statements => D_Stats));
 
@@ -9979,7 +10235,7 @@ package body Exp_Ch9 is
             Next (Stmt);
          end loop;
 
-         --  Do the assignement at this stage only because the evaluation
+         --  Do the assignment at this stage only because the evaluation
          --  of the expression must not occur before (see ACVC C97302A).
 
          Insert_Before (Stmt,
@@ -10022,32 +10278,35 @@ package body Exp_Ch9 is
 
             Append_To (Params, New_Reference_To (B, Loc));
 
-            if Abort_Allowed
-              or else Restriction_Active (No_Entry_Queue) = False
-              or else Number_Entries (Etype (Concval)) > 1
-            then
-               Rewrite (Call,
-                 Make_Procedure_Call_Statement (Loc,
-                   Name =>
-                     New_Reference_To (RTE (
-                       RE_Timed_Protected_Entry_Call), Loc),
-                   Parameter_Associations => Params));
-            else
-               Param := First (Params);
-               while Present (Param)
-                 and then not Is_RTE (Etype (Param), RE_Protected_Entry_Index)
-               loop
-                  Next (Param);
-               end loop;
+            case Corresponding_Runtime_Package (Etype (Concval)) is
+               when System_Tasking_Protected_Objects_Entries =>
+                  Rewrite (Call,
+                    Make_Procedure_Call_Statement (Loc,
+                      Name =>
+                        New_Reference_To
+                          (RTE (RE_Timed_Protected_Entry_Call), Loc),
+                      Parameter_Associations => Params));
+
+               when System_Tasking_Protected_Objects_Single_Entry =>
+                  Param := First (Params);
+                  while Present (Param)
+                    and then not
+                      Is_RTE (Etype (Param), RE_Protected_Entry_Index)
+                  loop
+                     Next (Param);
+                  end loop;
 
-               Remove (Param);
+                  Remove (Param);
 
-               Rewrite (Call,
-                 Make_Procedure_Call_Statement (Loc,
-                   Name => New_Reference_To (
-                     RTE (RE_Timed_Protected_Single_Entry_Call), Loc),
-                   Parameter_Associations => Params));
-            end if;
+                  Rewrite (Call,
+                    Make_Procedure_Call_Statement (Loc,
+                      Name => New_Reference_To (
+                        RTE (RE_Timed_Protected_Single_Entry_Call), Loc),
+                      Parameter_Associations => Params));
+
+               when others =>
+                  raise Program_Error;
+            end case;
 
          --  For the task case, build a Timed_Task_Entry_Call
 
@@ -10085,56 +10344,10 @@ package body Exp_Ch9 is
    -- Expand_Protected_Body_Declarations --
    ----------------------------------------
 
-   --  Part of the expansion of a protected body involves the creation of a
-   --  declaration that can be referenced from the statement sequences of the
-   --  entry bodies:
-
-   --    A : Address;
-
-   --  This declaration is inserted in the declarations of the service entries
-   --  procedure for the protected body, and it is important that it be
-   --  inserted before the statements of the entry body statement sequences are
-   --  analyzed. Thus it would be too late to create this declaration in the
-   --  Expand_N_Protected_Body routine, which is why there is a separate
-   --  procedure to be called directly from Sem_Ch9.
-
-   --  Ann is used to hold the address of the record containing the parameters
-   --  (see Expand_N_Entry_Call for more details on how this record is built).
-   --  References to the parameters do an unchecked conversion of this address
-   --  to a pointer to the required record type, and then access the field that
-   --  holds the value of the required parameter. The entity for the address
-   --  variable is held as the top stack element (i.e. the last element) of the
-   --  Accept_Address stack in the corresponding entry entity, and this element
-   --  must be set in place  before the statements are processed.
-
-   --  No stack is needed for entry bodies, since they cannot be nested, but it
-   --  is kept for consistency between protected and task entries. The stack
-   --  will never contain more than one element. There is also only one such
-   --  variable for a given protected body, but this is placed on the
-   --  Accept_Address stack of all of the entries, again for consistency.
-
-   --  To expand the requeue statement, a label is provided at the end of the
-   --  loop in the entry service routine created by the expander (see
-   --  Expand_N_Protected_Body for details), so that the statement can be
-   --  skipped after the requeue is complete. This label is created during the
-   --  expansion of the entry body, which will take place after the expansion
-   --  of the requeue statements that it contains, so a placeholder defining
-   --  identifier is associated with the task type here.
-
-   --  Another label is provided following case statement created by the
-   --  expander. This label is need for implementing return statement from
-   --  entry body so that a return can be expanded as a goto to this label.
-   --  This label is created during the expansion of the entry body, which
-   --  will take place after the expansion of the return statements that it
-   --  contains. Therefore, just like the label for expanding requeues, we
-   --  need another placeholder for the label.
-
    procedure Expand_Protected_Body_Declarations
      (N       : Node_Id;
       Spec_Id : Entity_Id)
    is
-      Op : Node_Id;
-
    begin
       if No_Run_Time_Mode then
          Error_Msg_CRT ("protected body", N);
@@ -10142,15 +10355,11 @@ package body Exp_Ch9 is
 
       elsif Expander_Active then
 
-         --  Associate privals with the first subprogram or entry body to be
-         --  expanded. These are used to expand references to private data
-         --  objects.
-
-         Op := First_Protected_Operation (Declarations (N));
+         --  Associate discriminals with the first subprogram or entry body to
+         --  be expanded.
 
-         if Present (Op) then
+         if Present (First_Protected_Operation (Declarations (N))) then
             Set_Discriminals (Parent (Spec_Id));
-            Set_Privals (Parent (Spec_Id), Op, Sloc (N));
          end if;
       end if;
    end Expand_Protected_Body_Declarations;
@@ -10163,13 +10372,24 @@ package body Exp_Ch9 is
       Subp : constant Entity_Id := Protected_Body_Subprogram (E);
 
    begin
-      --  The internal and external subprograms follow each other on the
-      --  entity chain. Note that previously private operations had no
-      --  separate external subprogram. We now create one in all cases,
-      --  because a private operation may actually appear in an external
-      --  call, through a 'Access reference used for a callback.
+      --  The internal and external subprograms follow each other on the entity
+      --  chain. Note that previously private operations had no separate
+      --  external subprogram. We now create one in all cases, because a
+      --  private operation may actually appear in an external call, through
+      --  a 'Access reference used for a callback.
+
+      --  If the operation is a function that returns an anonymous access type,
+      --  the corresponding itype appears before the operation, and must be
+      --  skipped.
+
+      --  This mechanism is fragile, there should be a real link between the
+      --  two versions of the operation, but there is no place to put it ???
 
-      return Next_Entity (Subp);
+      if Is_Access_Type (Next_Entity (Subp)) then
+         return Next_Entity (Next_Entity (Subp));
+      else
+         return Next_Entity (Subp);
+      end if;
    end External_Subprogram;
 
    ------------------------------
@@ -10402,11 +10622,11 @@ package body Exp_Ch9 is
       N := First (Visible_Declarations (T));
       while Present (N) loop
          if Nkind (N) = N_Pragma then
-            if Chars (N) = P then
+            if Pragma_Name (N) = P then
                return N;
 
             elsif P = Name_Priority
-              and then Chars (N) = Name_Interrupt_Priority
+              and then Pragma_Name (N) = Name_Interrupt_Priority
             then
                return N;
 
@@ -10422,11 +10642,11 @@ package body Exp_Ch9 is
       N := First (Private_Declarations (T));
       while Present (N) loop
          if Nkind (N) = N_Pragma then
-            if  Chars (N) = P then
+            if Pragma_Name (N) = P then
                return N;
 
             elsif P = Name_Priority
-              and then Chars (N) = Name_Interrupt_Priority
+              and then Pragma_Name (N) = Name_Interrupt_Priority
             then
                return N;
 
@@ -10452,8 +10672,7 @@ package body Exp_Ch9 is
    begin
       First_Op := First (D);
       while Present (First_Op)
-        and then Nkind (First_Op) /= N_Subprogram_Body
-        and then Nkind (First_Op) /= N_Entry_Body
+        and then not Nkind_In (First_Op, N_Subprogram_Body, N_Entry_Body)
       loop
          Next (First_Op);
       end loop;
@@ -10461,131 +10680,434 @@ package body Exp_Ch9 is
       return First_Op;
    end First_Protected_Operation;
 
-   ---------------------------------
-   -- Is_Potentially_Large_Family --
-   ---------------------------------
+   ---------------------------------------
+   -- Install_Private_Data_Declarations --
+   ---------------------------------------
 
-   function Is_Potentially_Large_Family
-     (Base_Index : Entity_Id;
-      Conctyp    : Entity_Id;
-      Lo         : Node_Id;
-      Hi         : Node_Id) return Boolean
+   procedure Install_Private_Data_Declarations
+     (Loc      : Source_Ptr;
+      Spec_Id  : Entity_Id;
+      Conc_Typ : Entity_Id;
+      Body_Nod : Node_Id;
+      Decls    : List_Id;
+      Barrier  : Boolean := False;
+      Family   : Boolean := False)
    is
-   begin
-      return Scope (Base_Index) = Standard_Standard
-        and then Base_Index = Base_Type (Standard_Integer)
-        and then Has_Discriminants (Conctyp)
-        and then Present
-          (Discriminant_Default_Value (First_Discriminant (Conctyp)))
-        and then
-          (Denotes_Discriminant (Lo, True)
-            or else Denotes_Discriminant (Hi, True));
-   end Is_Potentially_Large_Family;
-
-   --------------------------------
-   -- Index_Constant_Declaration --
-   --------------------------------
-
-   function Index_Constant_Declaration
-     (N        : Node_Id;
-      Index_Id : Entity_Id;
-      Prot     : Entity_Id) return List_Id
-   is
-      Loc       : constant Source_Ptr := Sloc (N);
-      Decls     : constant List_Id    := New_List;
-      Index_Con : constant Entity_Id  := Entry_Index_Constant (Index_Id);
-      Index_Typ : Entity_Id;
-
-      Hi : Node_Id := Type_High_Bound (Etype (Index_Id));
-      Lo : Node_Id := Type_Low_Bound  (Etype (Index_Id));
+      Is_Protected : constant Boolean := Is_Protected_Type (Conc_Typ);
+      Decl         : Node_Id;
+      Def          : Node_Id;
+      Insert_Node  : Node_Id := Empty;
+      Obj_Ent      : Entity_Id;
+
+      procedure Add (Decl : Node_Id);
+      --  Add a single declaration after Insert_Node. If this is the first
+      --  addition, Decl is added to the front of Decls and it becomes the
+      --  insertion node.
+
+      function Replace_Bound (Bound : Node_Id) return Node_Id;
+      --  The bounds of an entry index may depend on discriminants, create a
+      --  reference to the corresponding prival. Otherwise return a duplicate
+      --  of the original bound.
+
+      ---------
+      -- Add --
+      ---------
+
+      procedure Add (Decl : Node_Id) is
+      begin
+         if No (Insert_Node) then
+            Prepend_To (Decls, Decl);
+         else
+            Insert_After (Insert_Node, Decl);
+         end if;
 
-      function Replace_Discriminant (Bound : Node_Id) return Node_Id;
-      --  The bounds of the entry index may depend on discriminants, so each
-      --  declaration of an entry_index_constant must have its own subtype
-      --  declaration, using the local renaming of the object discriminant.
+         Insert_Node := Decl;
+      end Add;
 
       --------------------------
       -- Replace_Discriminant --
       --------------------------
 
-      function Replace_Discriminant (Bound : Node_Id) return Node_Id is
+      function Replace_Bound (Bound : Node_Id) return Node_Id is
       begin
          if Nkind (Bound) = N_Identifier
-           and then Ekind (Entity (Bound)) = E_Constant
-           and then Present (Discriminal_Link (Entity (Bound)))
+           and then Is_Discriminal (Entity (Bound))
          then
             return Make_Identifier (Loc, Chars (Entity (Bound)));
          else
             return Duplicate_Subexpr (Bound);
          end if;
-      end Replace_Discriminant;
+      end Replace_Bound;
 
-   --  Start of processing for Index_Constant_Declaration
+   --  Start of processing for Install_Private_Data_Declarations
 
    begin
-      Set_Discriminal_Link (Index_Con, Index_Id);
+      --  Step 1: Retrieve the concurrent object entity. Obj_Ent can denote
+      --  formal parameter _O, _object or _task depending on the context.
+
+      Obj_Ent := Concurrent_Object (Spec_Id, Conc_Typ);
+
+      --  Special processing of _O for barrier functions, protected entries
+      --  and families.
 
-      if Is_Entity_Name (
-        Original_Node (Discrete_Subtype_Definition (Parent (Index_Id))))
+      if Barrier
+        or else
+          (Is_Protected
+             and then
+               (Ekind (Spec_Id) = E_Entry
+                  or else Ekind (Spec_Id) = E_Entry_Family))
       then
-         --  Simple case: entry family is given by a subtype mark, and index
-         --  constant has the same type, no replacement needed.
+         declare
+            Conc_Rec : constant Entity_Id :=
+                         Corresponding_Record_Type (Conc_Typ);
+            Typ_Id   : constant Entity_Id :=
+                         Make_Defining_Identifier (Loc,
+                           New_External_Name (Chars (Conc_Rec), 'P'));
+         begin
+            --  Generate:
+            --    type prot_typVP is access prot_typV;
 
-         Index_Typ := Etype (Index_Id);
+            Decl :=
+              Make_Full_Type_Declaration (Loc,
+                Defining_Identifier => Typ_Id,
+                Type_Definition     =>
+                  Make_Access_To_Object_Definition (Loc,
+                    Subtype_Indication =>
+                      New_Reference_To (Conc_Rec, Loc)));
+            Add (Decl);
 
-      else
-         Hi := Replace_Discriminant (Hi);
-         Lo := Replace_Discriminant (Lo);
+            --  Generate:
+            --    _object : prot_typVP := prot_typV (_O);
 
-         Index_Typ := Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
+            Decl :=
+              Make_Object_Declaration (Loc,
+                Defining_Identifier =>
+                  Make_Defining_Identifier (Loc, Name_uObject),
+                Object_Definition   => New_Reference_To (Typ_Id, Loc),
+                Expression          =>
+                  Unchecked_Convert_To (Typ_Id,
+                    New_Reference_To (Obj_Ent, Loc)));
+            Add (Decl);
 
-         Append (
-           Make_Subtype_Declaration (Loc,
-             Defining_Identifier => Index_Typ,
-             Subtype_Indication =>
-               Make_Subtype_Indication (Loc,
-                 Subtype_Mark =>
-                   New_Occurrence_Of (Base_Type (Etype (Index_Id)), Loc),
-                 Constraint =>
-                   Make_Range_Constraint (Loc,
-                     Range_Expression => Make_Range (Loc, Lo, Hi)))),
-           Decls);
+            --  Set the reference to the concurrent object
 
+            Obj_Ent := Defining_Identifier (Decl);
+         end;
       end if;
 
-      Append (
-        Make_Object_Declaration (Loc,
-          Defining_Identifier => Index_Con,
-          Constant_Present => True,
-          Object_Definition => New_Occurrence_Of (Index_Typ, Loc),
+      --  Step 2: Create the Protection object and build its declaration for
+      --  any protected entry (family) of subprogram.
 
-          Expression =>
-            Make_Attribute_Reference (Loc,
-              Prefix => New_Reference_To (Index_Typ, Loc),
-              Attribute_Name => Name_Val,
+      if Is_Protected then
+         declare
+            Prot_Ent : constant Entity_Id :=
+                         Make_Defining_Identifier (Loc,
+                           New_Internal_Name ('R'));
+            Prot_Typ : RE_Id;
 
-              Expressions => New_List (
+         begin
+            Set_Protection_Object (Spec_Id, Prot_Ent);
 
-                Make_Op_Add (Loc,
-                  Left_Opnd =>
-                    Make_Op_Subtract (Loc,
-                      Left_Opnd => Make_Identifier (Loc, Name_uE),
-                      Right_Opnd =>
-                        Entry_Index_Expression (Loc,
-                          Defining_Identifier (N), Empty, Prot)),
+            --  Determine the proper protection type
 
-                  Right_Opnd =>
-                    Make_Attribute_Reference (Loc,
-                      Prefix => New_Reference_To (Index_Typ, Loc),
-                      Attribute_Name => Name_Pos,
-                      Expressions => New_List (
-                        Make_Attribute_Reference (Loc,
-                          Prefix => New_Reference_To (Index_Typ, Loc),
-                    Attribute_Name => Name_First))))))),
-      Decls);
+            if Has_Attach_Handler (Conc_Typ)
+              and then not Restricted_Profile
+            then
+               Prot_Typ := RE_Static_Interrupt_Protection;
+
+            elsif Has_Interrupt_Handler (Conc_Typ) then
+               Prot_Typ := RE_Dynamic_Interrupt_Protection;
+
+            --  The type has explicit entries or generated primitive entry
+            --  wrappers.
+
+            elsif Has_Entries (Conc_Typ)
+              or else
+                (Ada_Version >= Ada_05
+                   and then Present (Interface_List (Parent (Conc_Typ))))
+            then
+               case Corresponding_Runtime_Package (Conc_Typ) is
+                  when System_Tasking_Protected_Objects_Entries =>
+                     Prot_Typ := RE_Protection_Entries;
+
+                  when System_Tasking_Protected_Objects_Single_Entry =>
+                     Prot_Typ := RE_Protection_Entry;
+
+                  when others =>
+                     raise Program_Error;
+               end case;
+
+            else
+               Prot_Typ := RE_Protection;
+            end if;
+
+            --  Generate:
+            --    conc_typR : protection_typ renames _object._object;
+
+            Decl :=
+              Make_Object_Renaming_Declaration (Loc,
+                Defining_Identifier => Prot_Ent,
+                Subtype_Mark =>
+                  New_Reference_To (RTE (Prot_Typ), Loc),
+                Name =>
+                  Make_Selected_Component (Loc,
+                    Prefix =>
+                      New_Reference_To (Obj_Ent, Loc),
+                    Selector_Name =>
+                      Make_Identifier (Loc, Name_uObject)));
+            Add (Decl);
+         end;
+      end if;
+
+      --  Step 3: Add discriminant renamings (if any)
+
+      if Has_Discriminants (Conc_Typ) then
+         declare
+            D : Entity_Id;
+
+         begin
+            D := First_Discriminant (Conc_Typ);
+            while Present (D) loop
+
+               --  Adjust the source location
+
+               Set_Sloc (Discriminal (D), Loc);
+
+               --  Generate:
+               --    discr_name : discr_typ renames _object.discr_name;
+               --      or
+               --    discr_name : discr_typ renames _task.discr_name;
+
+               Decl :=
+                 Make_Object_Renaming_Declaration (Loc,
+                   Defining_Identifier => Discriminal (D),
+                   Subtype_Mark        => New_Reference_To (Etype (D), Loc),
+                   Name                =>
+                     Make_Selected_Component (Loc,
+                       Prefix        => New_Reference_To (Obj_Ent, Loc),
+                       Selector_Name => Make_Identifier (Loc, Chars (D))));
+               Add (Decl);
+
+               Next_Discriminant (D);
+            end loop;
+         end;
+      end if;
+
+      --  Step 4: Add private component renamings (if any)
+
+      if Is_Protected then
+         Def := Protected_Definition (Parent (Conc_Typ));
+
+         if Present (Private_Declarations (Def)) then
+            declare
+               Comp    : Node_Id;
+               Comp_Id : Entity_Id;
+               Decl_Id : Entity_Id;
+
+            begin
+               Comp := First (Private_Declarations (Def));
+               while Present (Comp) loop
+                  if Nkind (Comp) = N_Component_Declaration then
+                     Comp_Id := Defining_Identifier (Comp);
+                     Decl_Id :=
+                       Make_Defining_Identifier (Loc, Chars (Comp_Id));
+
+                     --  Minimal decoration
+
+                     if Ekind (Spec_Id) = E_Function then
+                        Set_Ekind (Decl_Id, E_Constant);
+                     else
+                        Set_Ekind (Decl_Id, E_Variable);
+                     end if;
+
+                     Set_Prival      (Comp_Id, Decl_Id);
+                     Set_Prival_Link (Decl_Id, Comp_Id);
+                     Set_Is_Aliased  (Decl_Id, Is_Aliased (Comp_Id));
+
+                     --  Generate:
+                     --    comp_name : comp_typ renames _object.comp_name;
+
+                     Decl :=
+                       Make_Object_Renaming_Declaration (Loc,
+                         Defining_Identifier => Decl_Id,
+                         Subtype_Mark =>
+                           New_Reference_To (Etype (Comp_Id), Loc),
+                         Name =>
+                           Make_Selected_Component (Loc,
+                             Prefix =>
+                               New_Reference_To (Obj_Ent, Loc),
+                             Selector_Name =>
+                               Make_Identifier (Loc, Chars (Comp_Id))));
+                     Add (Decl);
+                  end if;
+
+                  Next (Comp);
+               end loop;
+            end;
+         end if;
+      end if;
+
+      --  Step 5: Add the declaration of the entry index and the associated
+      --  type for barrier functions and entry families.
+
+      if (Barrier and then Family)
+        or else Ekind (Spec_Id) = E_Entry_Family
+      then
+         declare
+            E         : constant Entity_Id := Index_Object (Spec_Id);
+            Index     : constant Entity_Id :=
+                          Defining_Identifier (
+                            Entry_Index_Specification (
+                              Entry_Body_Formal_Part (Body_Nod)));
+            Index_Con : constant Entity_Id :=
+                          Make_Defining_Identifier (Loc, Chars (Index));
+            High      : Node_Id;
+            Index_Typ : Entity_Id;
+            Low       : Node_Id;
+
+         begin
+            --  Minimal decoration
+
+            Set_Ekind                (Index_Con, E_Constant);
+            Set_Entry_Index_Constant (Index, Index_Con);
+            Set_Discriminal_Link     (Index_Con, Index);
+
+            --  Retrieve the bounds of the entry family
+
+            High := Type_High_Bound (Etype (Index));
+            Low  := Type_Low_Bound  (Etype (Index));
+
+            --  In the simple case the entry family is given by a subtype
+            --  mark and the index constant has the same type.
+
+            if Is_Entity_Name (Original_Node (
+                 Discrete_Subtype_Definition (Parent (Index))))
+            then
+               Index_Typ := Etype (Index);
+
+            --  Otherwise a new subtype declaration is required
+
+            else
+               High := Replace_Bound (High);
+               Low  := Replace_Bound (Low);
+
+               Index_Typ :=
+                 Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
+
+               --  Generate:
+               --    subtype Jnn is <Etype of Index> range Low .. High;
+
+               Decl :=
+                 Make_Subtype_Declaration (Loc,
+                   Defining_Identifier => Index_Typ,
+                   Subtype_Indication =>
+                     Make_Subtype_Indication (Loc,
+                       Subtype_Mark =>
+                         New_Reference_To (Base_Type (Etype (Index)), Loc),
+                       Constraint =>
+                         Make_Range_Constraint (Loc,
+                           Range_Expression =>
+                             Make_Range (Loc, Low, High))));
+               Add (Decl);
+            end if;
+
+            Set_Etype (Index_Con, Index_Typ);
+
+            --  Create the object which designates the index:
+            --    J : constant Jnn :=
+            --          Jnn'Val (_E - <index expr> + Jnn'Pos (Jnn'First));
+            --
+            --  where Jnn is the subtype created above or the original type of
+            --  the index, _E is a formal of the protected body subprogram and
+            --  <index expr> is the index of the first family member.
+
+            Decl :=
+              Make_Object_Declaration (Loc,
+                Defining_Identifier => Index_Con,
+                Constant_Present => True,
+                Object_Definition =>
+                  New_Reference_To (Index_Typ, Loc),
+
+                Expression =>
+                  Make_Attribute_Reference (Loc,
+                    Prefix =>
+                      New_Reference_To (Index_Typ, Loc),
+                    Attribute_Name => Name_Val,
+
+                    Expressions => New_List (
+
+                      Make_Op_Add (Loc,
+                        Left_Opnd =>
+                          Make_Op_Subtract (Loc,
+                            Left_Opnd =>
+                              New_Reference_To (E, Loc),
+                            Right_Opnd =>
+                              Entry_Index_Expression (Loc,
+                                Defining_Identifier (Body_Nod),
+                                Empty, Conc_Typ)),
 
-      return Decls;
-   end Index_Constant_Declaration;
+                        Right_Opnd =>
+                          Make_Attribute_Reference (Loc,
+                            Prefix =>
+                              New_Reference_To (Index_Typ, Loc),
+                            Attribute_Name => Name_Pos,
+                            Expressions => New_List (
+                              Make_Attribute_Reference (Loc,
+                                Prefix =>
+                                  New_Reference_To (Index_Typ, Loc),
+                                Attribute_Name => Name_First)))))));
+            Add (Decl);
+         end;
+      end if;
+   end Install_Private_Data_Declarations;
+
+   ---------------------------------
+   -- Is_Potentially_Large_Family --
+   ---------------------------------
+
+   function Is_Potentially_Large_Family
+     (Base_Index : Entity_Id;
+      Conctyp    : Entity_Id;
+      Lo         : Node_Id;
+      Hi         : Node_Id) return Boolean
+   is
+   begin
+      return Scope (Base_Index) = Standard_Standard
+        and then Base_Index = Base_Type (Standard_Integer)
+        and then Has_Discriminants (Conctyp)
+        and then Present
+          (Discriminant_Default_Value (First_Discriminant (Conctyp)))
+        and then
+          (Denotes_Discriminant (Lo, True)
+            or else Denotes_Discriminant (Hi, True));
+   end Is_Potentially_Large_Family;
+
+   ------------------
+   -- Index_Object --
+   ------------------
+
+   function Index_Object (Spec_Id : Entity_Id) return Entity_Id is
+      Bod_Subp : constant Entity_Id := Protected_Body_Subprogram (Spec_Id);
+      Formal   : Entity_Id;
+
+   begin
+      Formal := First_Formal (Bod_Subp);
+      while Present (Formal) loop
+
+         --  Look for formal parameter _E
+
+         if Chars (Formal) = Name_uE then
+            return Formal;
+         end if;
+
+         Next_Formal (Formal);
+      end loop;
+
+      --  A protected body subprogram should always have the parameter in
+      --  question.
+
+      raise Program_Error;
+   end Index_Object;
 
    --------------------------------
    -- Make_Initialize_Protection --
@@ -10620,8 +11142,8 @@ package body Exp_Ch9 is
       --  of this type should have been removed during semantic analysis.
 
       Pdec := Parent (Ptyp);
-      while Nkind (Pdec) /= N_Protected_Type_Declaration
-        and then Nkind (Pdec) /= N_Single_Protected_Declaration
+      while not Nkind_In (Pdec, N_Protected_Type_Declaration,
+                                N_Single_Protected_Declaration)
       loop
          Next (Pdec);
       end loop;
@@ -10725,79 +11247,76 @@ package body Exp_Ch9 is
       if Has_Entry
         or else Has_Interrupt_Handler (Ptyp)
         or else Has_Attach_Handler (Ptyp)
-        or else (Ada_Version >= Ada_05
-                   and then Present (Interface_List (Parent (Ptyp))))
+        or else Has_Abstract_Interfaces (Protect_Rec)
       then
-         if Has_Entry or else not Restricted then
-            Append_To (Args,
-               Make_Attribute_Reference (Loc,
-                 Prefix => Make_Identifier (Loc, Name_uInit),
-                 Attribute_Name => Name_Address));
-         end if;
+         declare
+            Pkg_Id : constant RTU_Id := Corresponding_Runtime_Package (Ptyp);
 
-         --  Entry_Bodies parameter. This is a pointer to an array of pointers
-         --  to the entry body procedures and barrier functions of the object.
-         --  If the protected type has no entries this object will not exist;
-         --  in this case, pass a null.
+            Called_Subp : RE_Id;
 
-         if Has_Entry then
-            P_Arr := Entry_Bodies_Array (Ptyp);
+         begin
+            case Pkg_Id is
+               when System_Tasking_Protected_Objects_Entries =>
+                  Called_Subp := RE_Initialize_Protection_Entries;
 
-            Append_To (Args,
-              Make_Attribute_Reference (Loc,
-                Prefix => New_Reference_To (P_Arr, Loc),
-                Attribute_Name => Name_Unrestricted_Access));
+               when System_Tasking_Protected_Objects =>
+                  Called_Subp := RE_Initialize_Protection;
 
-            if Abort_Allowed
-              or else Restriction_Active (No_Entry_Queue) = False
-              or else Number_Entries (Ptyp) > 1
-              or else (Has_Attach_Handler (Ptyp) and then not Restricted)
-            then
-               --  Find index mapping function (clumsy but ok for now)
+               when System_Tasking_Protected_Objects_Single_Entry =>
+                  Called_Subp := RE_Initialize_Protection_Entry;
 
-               while Ekind (P_Arr) /= E_Function loop
-                  Next_Entity (P_Arr);
-               end loop;
+               when others =>
+                  raise Program_Error;
+            end case;
 
+            if Has_Entry or else not Restricted then
                Append_To (Args,
-                  Make_Attribute_Reference (Loc,
-                    Prefix =>
-                      New_Reference_To (P_Arr, Loc),
-                    Attribute_Name => Name_Unrestricted_Access));
+                 Make_Attribute_Reference (Loc,
+                   Prefix => Make_Identifier (Loc, Name_uInit),
+                   Attribute_Name => Name_Address));
             end if;
 
-         elsif not Restricted then
-            Append_To (Args, Make_Null (Loc));
-            Append_To (Args, Make_Null (Loc));
-         end if;
+            --  Entry_Bodies parameter. This is a pointer to an array of
+            --  pointers to the entry body procedures and barrier functions of
+            --  the object. If the protected type has no entries this object
+            --  will not exist, in this case, pass a null.
 
-         if Abort_Allowed
-           or else Restriction_Active (No_Entry_Queue) = False
-           or else Number_Entries (Ptyp) > 1
-           or else (Has_Attach_Handler (Ptyp)
-                     and then not Restricted)
-         then
-            Append_To (L,
-              Make_Procedure_Call_Statement (Loc,
-                Name => New_Reference_To (
-                  RTE (RE_Initialize_Protection_Entries), Loc),
-                Parameter_Associations => Args));
+            if Has_Entry then
+               P_Arr := Entry_Bodies_Array (Ptyp);
 
-         elsif not Has_Entry and then Restricted then
-            Append_To (L,
-              Make_Procedure_Call_Statement (Loc,
-                Name => New_Reference_To (
-                  RTE (RE_Initialize_Protection), Loc),
-                Parameter_Associations => Args));
+               Append_To (Args,
+                 Make_Attribute_Reference (Loc,
+                   Prefix => New_Reference_To (P_Arr, Loc),
+                   Attribute_Name => Name_Unrestricted_Access));
+
+               if Pkg_Id = System_Tasking_Protected_Objects_Entries then
+
+                  --  Find index mapping function (clumsy but ok for now)
+
+                  while Ekind (P_Arr) /= E_Function loop
+                     Next_Entity (P_Arr);
+                  end loop;
+
+                  Append_To (Args,
+                    Make_Attribute_Reference (Loc,
+                      Prefix =>
+                        New_Reference_To (P_Arr, Loc),
+                      Attribute_Name => Name_Unrestricted_Access));
+               end if;
+
+            elsif Pkg_Id = System_Tasking_Protected_Objects_Single_Entry then
+               Append_To (Args, Make_Null (Loc));
+
+            elsif Pkg_Id = System_Tasking_Protected_Objects_Entries then
+               Append_To (Args, Make_Null (Loc));
+               Append_To (Args, Make_Null (Loc));
+            end if;
 
-         else
             Append_To (L,
               Make_Procedure_Call_Statement (Loc,
-                Name => New_Reference_To (
-                  RTE (RE_Initialize_Protection_Entry), Loc),
+                Name => New_Reference_To (RTE (Called_Subp), Loc),
                 Parameter_Associations => Args));
-         end if;
-
+         end;
       else
          Append_To (L,
            Make_Procedure_Call_Statement (Loc,
@@ -10815,40 +11334,27 @@ package body Exp_Ch9 is
 
          --  or, in the case of Ravenscar:
 
-         --  Install_Handlers
+         --  Install_Restricted_Handlers
          --    ((Expr1, Proc1'access), ...., (ExprN, ProcN'access));
 
          declare
             Args  : constant List_Id := New_List;
             Table : constant List_Id := New_List;
-            Ritem : Node_Id := First_Rep_Item (Ptyp);
+            Ritem : Node_Id          := First_Rep_Item (Ptyp);
 
          begin
-            if not Restricted then
-
-               --  Appends the _object argument
-
-               Append_To (Args,
-                 Make_Attribute_Reference (Loc,
-                   Prefix =>
-                     Make_Selected_Component (Loc,
-                       Prefix => Make_Identifier (Loc, Name_uInit),
-                       Selector_Name => Make_Identifier (Loc, Name_uObject)),
-                   Attribute_Name => Name_Unchecked_Access));
-            end if;
-
             --  Build the Attach_Handler table argument
 
             while Present (Ritem) loop
                if Nkind (Ritem) = N_Pragma
-                 and then Chars (Ritem) = Name_Attach_Handler
+                 and then Pragma_Name (Ritem) = Name_Attach_Handler
                then
                   declare
                      Handler : constant Node_Id :=
                                  First (Pragma_Argument_Associations (Ritem));
 
-                     Interrupt : constant Node_Id  := Next (Handler);
-                     Expr      : constant  Node_Id := Expression (Interrupt);
+                     Interrupt : constant Node_Id := Next (Handler);
+                     Expr      : constant Node_Id := Expression (Interrupt);
 
                   begin
                      Append_To (Table,
@@ -10871,12 +11377,39 @@ package body Exp_Ch9 is
 
             Append_To (Args, Make_Aggregate (Loc, Table));
 
-            --  Append the Install_Handler call to the statements
+            --  Append the Install_Handlers (or Install_Restricted_Handlers)
+            --  call to the statements.
 
-            Append_To (L,
-              Make_Procedure_Call_Statement (Loc,
-                Name => New_Reference_To (RTE (RE_Install_Handlers), Loc),
-                Parameter_Associations => Args));
+            if Restricted then
+               --  Call a simplified version of Install_Handlers to be used
+               --  when the Ravenscar restrictions are in effect
+               --  (Install_Restricted_Handlers).
+
+               Append_To (L,
+                 Make_Procedure_Call_Statement (Loc,
+                   Name =>
+                     New_Reference_To
+                        (RTE (RE_Install_Restricted_Handlers), Loc),
+                   Parameter_Associations => Args));
+
+            else
+               --  First, prepends the _object argument
+
+               Prepend_To (Args,
+                 Make_Attribute_Reference (Loc,
+                   Prefix =>
+                     Make_Selected_Component (Loc,
+                       Prefix => Make_Identifier (Loc, Name_uInit),
+                       Selector_Name => Make_Identifier (Loc, Name_uObject)),
+                   Attribute_Name => Name_Unchecked_Access));
+
+               --  Then, insert call to Install_Handlers
+
+               Append_To (L,
+                 Make_Procedure_Call_Statement (Loc,
+                   Name => New_Reference_To (RTE (RE_Install_Handlers), Loc),
+                   Parameter_Associations => Args));
+            end if;
          end;
       end if;
 
@@ -10911,8 +11444,8 @@ package body Exp_Ch9 is
       --  this type should have been removed during semantic analysis.
 
       Tdec := Parent (Ttyp);
-      while Nkind (Tdec) /= N_Task_Type_Declaration
-        and then Nkind (Tdec) /= N_Single_Task_Declaration
+      while not Nkind_In (Tdec, N_Task_Type_Declaration,
+                                N_Single_Task_Declaration)
       loop
          Next (Tdec);
       end loop;
@@ -11000,18 +11533,43 @@ package body Exp_Ch9 is
 
       if not Restricted_Profile then
 
+         --  Deadline parameter. If no Relative_Deadline pragma is present,
+         --  then the deadline is Time_Span_Zero. If a pragma is present, then
+         --  the deadline is taken from the _Relative_Deadline field of the
+         --  task value record, which was set from the pragma value. Note that
+         --  this parameter must not be generated for the restricted profiles
+         --  since Ravenscar does not allow deadlines.
+
+         --  Case where pragma Relative_Deadline applies: use given value
+
+         if Present (Tdef) and then Has_Relative_Deadline_Pragma (Tdef) then
+            Append_To (Args,
+              Make_Selected_Component (Loc,
+                Prefix => Make_Identifier (Loc, Name_uInit),
+                Selector_Name =>
+                  Make_Identifier (Loc, Name_uRelative_Deadline)));
+
+         --  No pragma Relative_Deadline apply to the task
+
+         else
+            Append_To (Args,
+              New_Reference_To (RTE (RE_Time_Span_Zero), Loc));
+         end if;
+
          --  Number of entries. This is an expression of the form:
-         --
+
          --    n + _Init.a'Length + _Init.a'B'Length + ...
-         --
+
          --  where a,b... are the entry family names for the task definition
 
-         Ecount := Build_Entry_Count_Expression (
-           Ttyp,
-           Component_Items (Component_List (
-             Type_Definition (Parent (
-               Corresponding_Record_Type (Ttyp))))),
-           Loc);
+         Ecount :=
+           Build_Entry_Count_Expression
+             (Ttyp,
+              Component_Items
+                (Component_List
+                   (Type_Definition
+                      (Parent (Corresponding_Record_Type (Ttyp))))),
+              Loc);
          Append_To (Args, Ecount);
 
          --  Master parameter. This is a reference to the _Master parameter of
@@ -11028,17 +11586,55 @@ package body Exp_Ch9 is
       end if;
 
       --  State parameter. This is a pointer to the task body procedure. The
-      --  required value is obtained by taking the address of the task body
-      --  procedure and converting it (with an unchecked conversion) to the
-      --  type required by the task kernel. For further details, see the
-      --  description of Expand_Task_Body
+      --  required value is obtained by taking 'Unrestricted_Access of the task
+      --  body procedure and converting it (with an unchecked conversion) to
+      --  the type required by the task kernel. For further details, see the
+      --  description of Expand_N_Task_Body. We use 'Unrestricted_Access rather
+      --  than 'Address in order to avoid creating trampolines.
 
-      Append_To (Args,
-        Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
-          Make_Attribute_Reference (Loc,
-            Prefix =>
-              New_Occurrence_Of (Get_Task_Body_Procedure (Ttyp), Loc),
-            Attribute_Name => Name_Address)));
+      declare
+         Body_Proc    : constant Node_Id := Get_Task_Body_Procedure (Ttyp);
+         Subp_Ptr_Typ : constant Node_Id :=
+                          Create_Itype (E_Access_Subprogram_Type, Tdec);
+         Ref          : constant Node_Id := Make_Itype_Reference (Loc);
+
+      begin
+         Set_Directly_Designated_Type (Subp_Ptr_Typ, Body_Proc);
+         Set_Etype (Subp_Ptr_Typ, Subp_Ptr_Typ);
+
+         --  Be sure to freeze a reference to the access-to-subprogram type,
+         --  otherwise gigi will complain that it's in the wrong scope, because
+         --  it's actually inside the init procedure for the record type that
+         --  corresponds to the task type.
+
+         --  This processing is causing a crash in the .NET/JVM back ends that
+         --  is not yet understood, so skip it in these cases ???
+
+         if VM_Target = No_VM then
+            Set_Itype (Ref, Subp_Ptr_Typ);
+            Append_Freeze_Action (Task_Rec, Ref);
+
+            Append_To (Args,
+              Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
+                Make_Qualified_Expression (Loc,
+                  Subtype_Mark => New_Reference_To (Subp_Ptr_Typ, Loc),
+                  Expression   =>
+                    Make_Attribute_Reference (Loc,
+                      Prefix =>
+                        New_Occurrence_Of (Body_Proc, Loc),
+                      Attribute_Name => Name_Unrestricted_Access))));
+
+         --  For the .NET/JVM cases revert to the original code below ???
+
+         else
+            Append_To (Args,
+              Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
+                Make_Attribute_Reference (Loc,
+                  Prefix =>
+                    New_Occurrence_Of (Body_Proc, Loc),
+                  Attribute_Name => Name_Address)));
+         end if;
+      end;
 
       --  Discriminants parameter. This is just the address of the task
       --  value record itself (which contains the discriminant values
@@ -11106,8 +11702,7 @@ package body Exp_Ch9 is
    begin
       Next_Op := Next (N);
       while Present (Next_Op)
-        and then Nkind (Next_Op) /= N_Subprogram_Body
-        and then Nkind (Next_Op) /= N_Entry_Body
+        and then not Nkind_In (Next_Op, N_Subprogram_Body, N_Entry_Body)
       loop
          Next (Next_Op);
       end loop;
@@ -11115,6 +11710,31 @@ package body Exp_Ch9 is
       return Next_Op;
    end Next_Protected_Operation;
 
+   ---------------------
+   -- Null_Statements --
+   ---------------------
+
+   function Null_Statements (Stats : List_Id) return Boolean is
+      Stmt : Node_Id;
+
+   begin
+      Stmt := First (Stats);
+      while Nkind (Stmt) /= N_Empty
+        and then (Nkind_In (Stmt, N_Null_Statement, N_Label)
+                    or else
+                      (Nkind (Stmt) = N_Pragma
+                         and then (Pragma_Name (Stmt) = Name_Unreferenced
+                                     or else
+                                   Pragma_Name (Stmt) = Name_Unmodified
+                                     or else
+                                   Pragma_Name (Stmt) = Name_Warnings)))
+      loop
+         Next (Stmt);
+      end loop;
+
+      return Nkind (Stmt) = N_Empty;
+   end Null_Statements;
+
    --------------------------
    -- Parameter_Block_Pack --
    --------------------------
@@ -11313,287 +11933,39 @@ package body Exp_Ch9 is
       end if;
    end Set_Discriminals;
 
-   -----------------
-   -- Set_Privals --
-   -----------------
-
-   procedure Set_Privals
-      (Dec           : Node_Id;
-       Op            : Node_Id;
-       Loc           : Source_Ptr;
-       After_Barrier : Boolean := False)
-   is
-      P_Decl      : Node_Id;
-      P_Id        : Entity_Id;
-      Priv        : Entity_Id;
-      Def         : Node_Id;
-      Body_Ent    : Entity_Id;
-      For_Barrier : constant Boolean :=
-                      Nkind (Op) = N_Entry_Body and then not After_Barrier;
-
-      Prec_Decl : constant Node_Id :=
-                    Parent (Corresponding_Record_Type
-                             (Defining_Identifier (Dec)));
-      Prec_Def  : constant Entity_Id := Type_Definition (Prec_Decl);
-      Obj_Decl  : Node_Id;
-      P_Subtype : Entity_Id;
-      Assoc_L   : constant Elist_Id := New_Elmt_List;
-      Op_Id     : Entity_Id;
+   -----------------------
+   -- Trivial_Accept_OK --
+   -----------------------
 
+   function Trivial_Accept_OK return Boolean is
    begin
-      pragma Assert (Nkind (Dec) = N_Protected_Type_Declaration);
-      pragma Assert
-        (Nkind (Op) = N_Subprogram_Body or else Nkind (Op) = N_Entry_Body);
-
-      Def := Protected_Definition (Dec);
-
-      if Present (Private_Declarations (Def)) then
-         P_Decl := First (Private_Declarations (Def));
-         while Present (P_Decl) loop
-            if Nkind (P_Decl) = N_Component_Declaration then
-               P_Id := Defining_Identifier (P_Decl);
-
-               if For_Barrier then
-                  Priv :=
-                    Make_Defining_Identifier (Loc,
-                      Chars => New_External_Name (Chars (P_Id), 'P'));
-               else
-                  Priv :=
-                    Make_Defining_Identifier (Loc,
-                      Chars => New_External_Name (Chars (P_Id)));
-               end if;
-
-               Set_Ekind     (Priv, E_Variable);
-               Set_Etype     (Priv, Etype (P_Id));
-               Set_Scope     (Priv, Scope (P_Id));
-               Set_Esize     (Priv, Esize (Etype (P_Id)));
-               Set_Alignment (Priv, Alignment (Etype (P_Id)));
-
-               --  If the type of the component is an itype, we must create a
-               --  new itype for the corresponding prival in each protected
-               --  operation, to avoid scoping problems. We create new itypes
-               --  by copying the tree for the component definition.
-               --  (Ada 2005) If the itype is an anonymous access type created
-               --  for an access definition for a component, it is declared in
-               --  the enclosing scope, and we do no create a local version of
-               --  it, to prevent scoping anomalies in gigi.
-
-               if Is_Itype (Etype (P_Id))
-                  and then not
-                    (Is_Access_Type (Etype (P_Id))
-                      and then Is_Local_Anonymous_Access (Etype (P_Id)))
-               then
-                  Append_Elmt (P_Id, Assoc_L);
-                  Append_Elmt (Priv, Assoc_L);
-
-                  if Nkind (Op) = N_Entry_Body then
-                     Op_Id := Defining_Identifier (Op);
-                  else
-                     Op_Id := Defining_Unit_Name (Specification (Op));
-                  end if;
-
-                  Discard_Node
-                    (New_Copy_Tree (P_Decl, Assoc_L, New_Scope => Op_Id));
-               end if;
-
-               Set_Protected_Operation (P_Id, Op);
-               Set_Prival (P_Id, Priv);
-            end if;
-
-            Next (P_Decl);
-         end loop;
-      end if;
-
-      --  There is one more implicit private decl: the object itself. "prival"
-      --  for this is attached to the protected body defining identifier.
-
-      Body_Ent := Corresponding_Body (Dec);
-
-      Priv :=
-        Make_Defining_Identifier (Sloc (Body_Ent),
-          Chars => New_External_Name (Chars (Body_Ent), 'R'));
-
-      --  Set the Etype to the implicit subtype of Protection created when
-      --  the protected type declaration was expanded. This node will not
-      --  be analyzed until it is used as the defining identifier for the
-      --  renaming declaration in the protected operation body, and it will
-      --  be needed in the references expanded before that body is expanded.
-      --  Since the Protection field is aliased, set Is_Aliased as well.
-
-      Obj_Decl := First (Component_Items (Component_List (Prec_Def)));
-      while Chars (Defining_Identifier (Obj_Decl)) /= Name_uObject loop
-         Next (Obj_Decl);
-      end loop;
+      case Opt.Task_Dispatching_Policy is
 
-      P_Subtype  := Etype (Defining_Identifier (Obj_Decl));
-      Set_Ekind (Priv, E_Variable);
-      Set_Etype (Priv, P_Subtype);
-      Set_Is_Aliased (Priv);
-      Set_Object_Ref (Body_Ent, Priv);
-   end Set_Privals;
+         --  If we have the default task dispatching policy in effect, we can
+         --  definitely do the optimization (one way of looking at this is to
+         --  think of the formal definition of the default policy being allowed
+         --  to run any task it likes after a rendezvous, so even if notionally
+         --  a full rescheduling occurs, we can say that our dispatching policy
+         --  (i.e. the default dispatching policy) reorders the queue to be the
+         --  same as just before the call.
 
-   ----------------------------
-   -- Update_Prival_Subtypes --
-   ----------------------------
-
-   procedure Update_Prival_Subtypes (N : Node_Id) is
-
-      function Process (N : Node_Id) return Traverse_Result;
-      --  Update the etype of occurrences of privals whose etype does not
-      --  match the current Etype of the prival entity itself.
-
-      procedure Update_Array_Bounds (E : Entity_Id);
-      --  Itypes generated for array expressions may depend on the
-      --  determinants of the protected object, and need to be processed
-      --  separately because they are not attached to the tree.
-
-      procedure Update_Index_Types (N : Node_Id);
-      --  Similarly, update the types of expressions in indexed components
-      --  which may depend on other discriminants.
-
-      -------------
-      -- Process --
-      -------------
-
-      function Process (N : Node_Id) return Traverse_Result is
-      begin
-         if Is_Entity_Name (N)  then
-            declare
-               E : constant Entity_Id := Entity (N);
-            begin
-               if Present (E)
-                 and then (Ekind (E) = E_Constant
-                            or else Ekind (E) = E_Variable)
-                 and then Nkind (Parent (E)) = N_Object_Renaming_Declaration
-                 and then not Is_Scalar_Type (Etype (E))
-                 and then Etype (N) /= Etype (E)
-               then
-
-                  --  Ensure that reference and entity have the same Etype,
-                  --  to prevent back-end inconsistencies.
-
-                  Set_Etype (N, Etype (E));
-                  Update_Index_Types (N);
-
-               elsif Present (E)
-                 and then Ekind (E) = E_Constant
-                 and then Present (Discriminal_Link (E))
-               then
-                  Set_Etype (N, Etype (E));
-               end if;
-            end;
-
-            return OK;
-
-         elsif Nkind (N) = N_Defining_Identifier
-           or else Nkind (N) = N_Defining_Operator_Symbol
-           or else Nkind (N) = N_Defining_Character_Literal
-         then
-            return Skip;
-
-         elsif Nkind (N) = N_String_Literal then
-
-            --  Array type, but bounds are constant
-
-            return OK;
-
-         elsif Nkind (N) = N_Object_Declaration
-           and then Is_Itype (Etype (Defining_Identifier (N)))
-           and then Is_Array_Type (Etype (Defining_Identifier (N)))
-         then
-            Update_Array_Bounds (Etype (Defining_Identifier (N)));
-            return OK;
-
-         --  For array components of discriminated records, use the base type
-         --  directly, because it may depend indirectly on the discriminants of
-         --  the protected type.
-
-         --  Cleaner would be a systematic mechanism to compute actual subtypes
-         --  of private components???
-
-         elsif Nkind (N) in N_Has_Etype
-           and then Present (Etype (N))
-           and then Is_Array_Type (Etype (N))
-           and then Nkind (N) = N_Selected_Component
-           and then Has_Discriminants (Etype (Prefix (N)))
-         then
-            Set_Etype (N, Base_Type (Etype (N)));
-            Update_Index_Types (N);
-            return OK;
-
-         else
-            if Nkind (N) in N_Has_Etype
-              and then Present (Etype (N))
-              and then Is_Itype (Etype (N)) then
-
-               if Is_Array_Type (Etype (N)) then
-                  Update_Array_Bounds (Etype (N));
-
-               elsif Is_Scalar_Type (Etype (N)) then
-                  Update_Prival_Subtypes (Type_Low_Bound  (Etype (N)));
-                  Update_Prival_Subtypes (Type_High_Bound (Etype (N)));
-               end if;
-            end if;
-
-            return OK;
-         end if;
-      end Process;
-
-      -------------------------
-      -- Update_Array_Bounds --
-      -------------------------
-
-      procedure Update_Array_Bounds (E : Entity_Id) is
-         Ind : Node_Id;
-      begin
-         Ind := First_Index (E);
-         while Present (Ind) loop
-            Update_Prival_Subtypes (Type_Low_Bound  (Etype (Ind)));
-            Update_Prival_Subtypes (Type_High_Bound (Etype (Ind)));
-            Next_Index (Ind);
-         end loop;
-      end Update_Array_Bounds;
-
-      ------------------------
-      -- Update_Index_Types --
-      ------------------------
-
-      procedure Update_Index_Types (N : Node_Id) is
-         Indx1 : Node_Id;
-         I_Typ : Node_Id;
-
-      begin
-         --  If the prefix has an actual subtype that is different from the
-         --  nominal one, update the types of the indices, so that the proper
-         --  constraints are applied. Do not apply this transformation to a
-         --  packed array, where the index type is computed for a byte array
-         --  and is different from the source index.
-
-         if Nkind (Parent (N)) = N_Indexed_Component
-           and then
-             not Is_Bit_Packed_Array (Etype (Prefix (Parent (N))))
-         then
-            Indx1 := First (Expressions (Parent (N)));
-            I_Typ := First_Index (Etype (N));
-
-            while Present (Indx1) and then Present (I_Typ) loop
+         when ' ' =>
+            return True;
 
-               if not Is_Entity_Name (Indx1) then
-                  Set_Etype (Indx1, Base_Type (Etype (I_Typ)));
-               end if;
+         --  FIFO_Within_Priorities certainly certainly does not permit this
+         --  optimization since the Rendezvous is a scheduling action that may
+         --  require some other task to be run.
 
-               Next (Indx1);
-               Next_Index (I_Typ);
-            end loop;
-         end if;
-      end Update_Index_Types;
+         when 'F' =>
+            return False;
 
-      procedure Traverse is new Traverse_Proc (Process);
+         --  For now, disallow the optimization for all other policies. This
+         --  may be over-conservative, but it is certainly not incorrect.
 
-   --  Start of processing for Update_Prival_Subtypes
+         when others =>
+            return False;
 
-   begin
-      Traverse (N);
-   end Update_Prival_Subtypes;
+      end case;
+   end Trivial_Accept_OK;
 
 end Exp_Ch9;