OSDN Git Service

2008-04-08 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch4.adb
index ac3c389..ee440f1 100644 (file)
@@ -6,18 +6,17 @@
 --                                                                          --
 --                                 B o d y                                  --
 --                                                                          --
---          Copyright (C) 1992-2004, 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,  59 Temple Place - Suite 330,  Boston, --
--- MA 02111-1307, 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.      --
@@ -30,7 +29,9 @@ with Einfo;    use Einfo;
 with Elists;   use Elists;
 with Errout;   use Errout;
 with Exp_Aggr; use Exp_Aggr;
+with Exp_Atag; use Exp_Atag;
 with Exp_Ch3;  use Exp_Ch3;
+with Exp_Ch6;  use Exp_Ch6;
 with Exp_Ch7;  use Exp_Ch7;
 with Exp_Ch9;  use Exp_Ch9;
 with Exp_Disp; use Exp_Disp;
@@ -39,15 +40,19 @@ with Exp_Pakd; use Exp_Pakd;
 with Exp_Tss;  use Exp_Tss;
 with Exp_Util; use Exp_Util;
 with Exp_VFpt; use Exp_VFpt;
-with Hostparm; use Hostparm;
+with Freeze;   use Freeze;
 with Inline;   use Inline;
+with Namet;    use Namet;
 with Nlists;   use Nlists;
 with Nmake;    use Nmake;
 with Opt;      use Opt;
+with Restrict; use Restrict;
+with Rident;   use Rident;
 with Rtsfind;  use Rtsfind;
 with Sem;      use Sem;
 with Sem_Cat;  use Sem_Cat;
 with Sem_Ch3;  use Sem_Ch3;
+with Sem_Ch8;  use Sem_Ch8;
 with Sem_Ch13; use Sem_Ch13;
 with Sem_Eval; use Sem_Eval;
 with Sem_Res;  use Sem_Res;
@@ -78,9 +83,15 @@ package body Exp_Ch4 is
      (N   : Node_Id;
       Op1 : Node_Id;
       Op2 : Node_Id);
-   --  If an boolean array assignment can be done in place, build call to
+   --  If a boolean array assignment can be done in place, build call to
    --  corresponding library procedure.
 
+   procedure Displace_Allocator_Pointer (N : Node_Id);
+   --  Ada 2005 (AI-251): Subsidiary procedure to Expand_N_Allocator and
+   --  Expand_Allocator_Expression. Allocating class-wide interface objects
+   --  this routine displaces the pointer to the allocated object to reference
+   --  the component referencing the corresponding secondary dispatch table.
+
    procedure Expand_Allocator_Expression (N : Node_Id);
    --  Subsidiary to Expand_N_Allocator, for the case when the expression
    --  is a qualified expression or an aggregate.
@@ -123,7 +134,7 @@ package body Exp_Ch4 is
    --  Local recursive function used to expand equality for nested
    --  composite types. Used by Expand_Record/Array_Equality, Bodies
    --  is a list on which to attach bodies of local functions that are
-   --  created in the process. This is the responsability of the caller
+   --  created in the process. This is the responsibility of the caller
    --  to insert those bodies at the right place. Nod provides the Sloc
    --  value for generated code. Lhs and Rhs are the left and right sides
    --  for the comparison, and Typ is the type of the arrays to compare.
@@ -136,7 +147,7 @@ package body Exp_Ch4 is
 
    procedure Expand_Concatenate_String (Cnode : Node_Id; Opnds : List_Id);
    --  Routine to expand concatenation of 2-5 operands (in the list Operands)
-   --  and replace node Cnode with the result of the contatenation. If there
+   --  and replace node Cnode with the result of the concatenation. If there
    --  are two operands, they can be string or character. If there are more
    --  than two operands, then are always of type string (i.e. the caller has
    --  already converted character operands to strings in this case).
@@ -192,10 +203,12 @@ package body Exp_Ch4 is
    --  this by using Convert_To_Actual_Subtype if necessary).
 
    procedure Rewrite_Comparison (N : Node_Id);
-   --  N is the node for a compile time comparison. If this outcome of this
-   --  comparison can be determined at compile time, then the node N can be
-   --  rewritten with True or False. If the outcome cannot be determined at
-   --  compile time, the call has no effect.
+   --  If N is the node for a comparison whose outcome can be determined at
+   --  compile time, then the node N can be rewritten with True or False. If
+   --  the outcome cannot be determined at compile time, the call has no
+   --  effect. If N is a type conversion, then this processing is applied to
+   --  its expression. If N is neither comparison nor a type conversion, the
+   --  call has no effect.
 
    function Tagged_Membership (N : Node_Id) return Node_Id;
    --  Construct the expression corresponding to the tagged membership test.
@@ -250,7 +263,7 @@ package body Exp_Ch4 is
       if Kind = N_Op_Not then
          if Nkind (Op1) in N_Binary_Op then
 
-            --  Use negated version of the binary operators.
+            --  Use negated version of the binary operators
 
             if Nkind (Op1) = N_Op_And then
                Proc_Name := RTE (RE_Vector_Nand);
@@ -357,28 +370,228 @@ package body Exp_Ch4 is
          return;
    end Build_Boolean_Array_Proc_Call;
 
+   --------------------------------
+   -- Displace_Allocator_Pointer --
+   --------------------------------
+
+   procedure Displace_Allocator_Pointer (N : Node_Id) is
+      Loc       : constant Source_Ptr := Sloc (N);
+      Orig_Node : constant Node_Id := Original_Node (N);
+      Dtyp      : Entity_Id;
+      Etyp      : Entity_Id;
+      PtrT      : Entity_Id;
+
+   begin
+      --  Do nothing in case of VM targets: the virtual machine will handle
+      --  interfaces directly.
+
+      if VM_Target /= No_VM then
+         return;
+      end if;
+
+      pragma Assert (Nkind (N) = N_Identifier
+        and then Nkind (Orig_Node) = N_Allocator);
+
+      PtrT := Etype (Orig_Node);
+      Dtyp := Designated_Type (PtrT);
+      Etyp := Etype (Expression (Orig_Node));
+
+      if Is_Class_Wide_Type (Dtyp)
+        and then Is_Interface (Dtyp)
+      then
+         --  If the type of the allocator expression is not an interface type
+         --  we can generate code to reference the record component containing
+         --  the pointer to the secondary dispatch table.
+
+         if not Is_Interface (Etyp) then
+            declare
+               Saved_Typ : constant Entity_Id := Etype (Orig_Node);
+
+            begin
+               --  1) Get access to the allocated object
+
+               Rewrite (N,
+                 Make_Explicit_Dereference (Loc,
+                   Relocate_Node (N)));
+               Set_Etype (N, Etyp);
+               Set_Analyzed (N);
+
+               --  2) Add the conversion to displace the pointer to reference
+               --     the secondary dispatch table.
+
+               Rewrite (N, Convert_To (Dtyp, Relocate_Node (N)));
+               Analyze_And_Resolve (N, Dtyp);
+
+               --  3) The 'access to the secondary dispatch table will be used
+               --     as the value returned by the allocator.
+
+               Rewrite (N,
+                 Make_Attribute_Reference (Loc,
+                   Prefix         => Relocate_Node (N),
+                   Attribute_Name => Name_Access));
+               Set_Etype (N, Saved_Typ);
+               Set_Analyzed (N);
+            end;
+
+         --  If the type of the allocator expression is an interface type we
+         --  generate a run-time call to displace "this" to reference the
+         --  component containing the pointer to the secondary dispatch table
+         --  or else raise Constraint_Error if the actual object does not
+         --  implement the target interface. This case corresponds with the
+         --  following example:
+
+         --   function Op (Obj : Iface_1'Class) return access Iface_2'Class is
+         --   begin
+         --      return new Iface_2'Class'(Obj);
+         --   end Op;
+
+         else
+            Rewrite (N,
+              Unchecked_Convert_To (PtrT,
+                Make_Function_Call (Loc,
+                  Name => New_Reference_To (RTE (RE_Displace), Loc),
+                  Parameter_Associations => New_List (
+                    Unchecked_Convert_To (RTE (RE_Address),
+                      Relocate_Node (N)),
+
+                    New_Occurrence_Of
+                      (Elists.Node
+                        (First_Elmt
+                          (Access_Disp_Table (Etype (Base_Type (Dtyp))))),
+                       Loc)))));
+            Analyze_And_Resolve (N, PtrT);
+         end if;
+      end if;
+   end Displace_Allocator_Pointer;
+
    ---------------------------------
    -- Expand_Allocator_Expression --
    ---------------------------------
 
    procedure Expand_Allocator_Expression (N : Node_Id) is
-      Loc   : constant Source_Ptr := Sloc (N);
-      Exp   : constant Node_Id    := Expression (Expression (N));
-      Indic : constant Node_Id    := Subtype_Mark (Expression (N));
-      PtrT  : constant Entity_Id  := Etype (N);
-      T     : constant Entity_Id  := Entity (Indic);
+      Loc    : constant Source_Ptr := Sloc (N);
+      Exp    : constant Node_Id    := Expression (Expression (N));
+      PtrT   : constant Entity_Id  := Etype (N);
+      DesigT : constant Entity_Id  := Designated_Type (PtrT);
+
+      procedure Apply_Accessibility_Check
+        (Ref            : Node_Id;
+         Built_In_Place : Boolean := False);
+      --  Ada 2005 (AI-344): For an allocator with a class-wide designated
+      --  type, generate an accessibility check to verify that the level of
+      --  the type of the created object is not deeper than the level of the
+      --  access type. If the type of the qualified expression is class-
+      --  wide, then always generate the check (except in the case where it
+      --  is known to be unnecessary, see comment below). Otherwise, only
+      --  generate the check if the level of the qualified expression type
+      --  is statically deeper than the access type. Although the static
+      --  accessibility will generally have been performed as a legality
+      --  check, it won't have been done in cases where the allocator
+      --  appears in generic body, so a run-time check is needed in general.
+      --  One special case is when the access type is declared in the same
+      --  scope as the class-wide allocator, in which case the check can
+      --  never fail, so it need not be generated. As an open issue, there
+      --  seem to be cases where the static level associated with the
+      --  class-wide object's underlying type is not sufficient to perform
+      --  the proper accessibility check, such as for allocators in nested
+      --  subprograms or accept statements initialized by class-wide formals
+      --  when the actual originates outside at a deeper static level. The
+      --  nested subprogram case might require passing accessibility levels
+      --  along with class-wide parameters, and the task case seems to be
+      --  an actual gap in the language rules that needs to be fixed by the
+      --  ARG. ???
+
+      -------------------------------
+      -- Apply_Accessibility_Check --
+      -------------------------------
+
+      procedure Apply_Accessibility_Check
+        (Ref            : Node_Id;
+         Built_In_Place : Boolean := False)
+      is
+         Ref_Node : Node_Id;
+
+      begin
+         --  Note: we skip the accessibility check for the VM case, since
+         --  there does not seem to be any practical way of implementing it.
+
+         if Ada_Version >= Ada_05
+           and then VM_Target = No_VM
+           and then Is_Class_Wide_Type (DesigT)
+           and then not Scope_Suppress (Accessibility_Check)
+           and then
+             (Type_Access_Level (Etype (Exp)) > Type_Access_Level (PtrT)
+               or else
+                 (Is_Class_Wide_Type (Etype (Exp))
+                   and then Scope (PtrT) /= Current_Scope))
+         then
+            --  If the allocator was built in place Ref is already a reference
+            --  to the access object initialized to the result of the allocator
+            --  (see Exp_Ch6.Make_Build_In_Place_Call_In_Allocator). Otherwise
+            --  it is the entity associated with the object containing the
+            --  address of the allocated object.
+
+            if Built_In_Place then
+               Ref_Node := New_Copy (Ref);
+            else
+               Ref_Node := New_Reference_To (Ref, Loc);
+            end if;
+
+            Insert_Action (N,
+               Make_Raise_Program_Error (Loc,
+                 Condition =>
+                   Make_Op_Gt (Loc,
+                     Left_Opnd  =>
+                       Build_Get_Access_Level (Loc,
+                         Make_Attribute_Reference (Loc,
+                           Prefix => Ref_Node,
+                           Attribute_Name => Name_Tag)),
+                     Right_Opnd =>
+                       Make_Integer_Literal (Loc,
+                         Type_Access_Level (PtrT))),
+                 Reason => PE_Accessibility_Check_Failed));
+         end if;
+      end Apply_Accessibility_Check;
+
+      --  Local variables
+
+      Indic : constant Node_Id   := Subtype_Mark (Expression (N));
+      T     : constant Entity_Id := Entity (Indic);
       Flist : Node_Id;
       Node  : Node_Id;
       Temp  : Entity_Id;
 
+      TagT : Entity_Id := Empty;
+      --  Type used as source for tag assignment
+
+      TagR : Node_Id := Empty;
+      --  Target reference for tag assignment
+
       Aggr_In_Place : constant Boolean := Is_Delayed_Aggregate (Exp);
 
       Tag_Assign : Node_Id;
       Tmp_Node   : Node_Id;
 
+   --  Start of processing for Expand_Allocator_Expression
+
    begin
       if Is_Tagged_Type (T) or else Controlled_Type (T) then
 
+         --  Ada 2005 (AI-318-02): If the initialization expression is a
+         --  call to a build-in-place function, then access to the allocated
+         --  object must be passed to the function. Currently we limit such
+         --  functions to those with constrained limited result subtypes,
+         --  but eventually we plan to expand the allowed forms of functions
+         --  that are treated as build-in-place.
+
+         if Ada_Version >= Ada_05
+           and then Is_Build_In_Place_Function_Call (Exp)
+         then
+            Make_Build_In_Place_Call_In_Allocator (N, Exp);
+            Apply_Accessibility_Check (N, Built_In_Place => True);
+            return;
+         end if;
+
          --    Actions inserted before:
          --              Temp : constant ptr_T := new T'(Expression);
          --   <no CW>    Temp._tag := T'tag;
@@ -388,6 +601,11 @@ package body Exp_Ch4 is
          --  We analyze by hand the new internal allocator to avoid
          --  any recursion and inappropriate call to Initialize
 
+         --  We don't want to remove side effects when the expression must be
+         --  built in place. In the case of a build-in-place function call,
+         --  that could lead to a duplication of the call, which was already
+         --  substituted for the allocator.
+
          if not Aggr_In_Place then
             Remove_Side_Effects (Exp);
          end if;
@@ -404,102 +622,221 @@ package body Exp_Ch4 is
          if Is_Class_Wide_Type (T) then
             Expand_Subtype_From_Expr (Empty, T, Indic, Exp);
 
-            Set_Expression (Expression (N),
-              Unchecked_Convert_To (Entity (Indic), Exp));
+            --  Ada 2005 (AI-251): If the expression is a class-wide interface
+            --  object we generate code to move up "this" to reference the
+            --  base of the object before allocating the new object.
+
+            --  Note that Exp'Address is recursively expanded into a call
+            --  to Base_Address (Exp.Tag)
+
+            if Is_Class_Wide_Type (Etype (Exp))
+              and then Is_Interface (Etype (Exp))
+              and then VM_Target = No_VM
+            then
+               Set_Expression
+                 (Expression (N),
+                  Unchecked_Convert_To (Entity (Indic),
+                    Make_Explicit_Dereference (Loc,
+                      Unchecked_Convert_To (RTE (RE_Tag_Ptr),
+                        Make_Attribute_Reference (Loc,
+                          Prefix         => Exp,
+                          Attribute_Name => Name_Address)))));
+
+            else
+               Set_Expression
+                 (Expression (N),
+                  Unchecked_Convert_To (Entity (Indic), Exp));
+            end if;
 
             Analyze_And_Resolve (Expression (N), Entity (Indic));
          end if;
 
-         if Aggr_In_Place then
-            Tmp_Node :=
-              Make_Object_Declaration (Loc,
-                Defining_Identifier => Temp,
-                Object_Definition   => New_Reference_To (PtrT, Loc),
-                Expression          =>
-                  Make_Allocator (Loc,
-                    New_Reference_To (Etype (Exp), Loc)));
+         --  Keep separate the management of allocators returning interfaces
+
+         if not Is_Interface (Directly_Designated_Type (PtrT)) then
+            if Aggr_In_Place then
+               Tmp_Node :=
+                 Make_Object_Declaration (Loc,
+                   Defining_Identifier => Temp,
+                   Object_Definition   => New_Reference_To (PtrT, Loc),
+                   Expression          =>
+                     Make_Allocator (Loc,
+                       New_Reference_To (Etype (Exp), Loc)));
 
-            Set_Comes_From_Source
-              (Expression (Tmp_Node), Comes_From_Source (N));
+               Set_Comes_From_Source
+                 (Expression (Tmp_Node), Comes_From_Source (N));
 
-            Set_No_Initialization (Expression (Tmp_Node));
-            Insert_Action (N, Tmp_Node);
+               Set_No_Initialization (Expression (Tmp_Node));
+               Insert_Action (N, Tmp_Node);
 
-            if Controlled_Type (T)
-              and then Ekind (PtrT) = E_Anonymous_Access_Type
-            then
-               --  Create local finalization list for access parameter.
+               if Controlled_Type (T)
+                 and then Ekind (PtrT) = E_Anonymous_Access_Type
+               then
+                  --  Create local finalization list for access parameter
 
-               Flist := Get_Allocator_Final_List (N, Base_Type (T), PtrT);
+                  Flist := Get_Allocator_Final_List (N, Base_Type (T), PtrT);
+               end if;
+
+               Convert_Aggr_In_Allocator (N, Tmp_Node, Exp);
+            else
+               Node := Relocate_Node (N);
+               Set_Analyzed (Node);
+               Insert_Action (N,
+                 Make_Object_Declaration (Loc,
+                   Defining_Identifier => Temp,
+                   Constant_Present    => True,
+                   Object_Definition   => New_Reference_To (PtrT, Loc),
+                   Expression          => Node));
             end if;
 
-            Convert_Aggr_In_Allocator (Tmp_Node, Exp);
+         --  Ada 2005 (AI-251): Handle allocators whose designated type is an
+         --  interface type. In this case we use the type of the qualified
+         --  expression to allocate the object.
+
          else
-            Node := Relocate_Node (N);
-            Set_Analyzed (Node);
-            Insert_Action (N,
-              Make_Object_Declaration (Loc,
-                Defining_Identifier => Temp,
-                Constant_Present    => True,
-                Object_Definition   => New_Reference_To (PtrT, Loc),
-                Expression          => Node));
+            declare
+               Def_Id   : constant Entity_Id :=
+                            Make_Defining_Identifier (Loc,
+                              New_Internal_Name ('T'));
+               New_Decl : Node_Id;
+
+            begin
+               New_Decl :=
+                 Make_Full_Type_Declaration (Loc,
+                   Defining_Identifier => Def_Id,
+                   Type_Definition =>
+                     Make_Access_To_Object_Definition (Loc,
+                       All_Present            => True,
+                       Null_Exclusion_Present => False,
+                       Constant_Present       => False,
+                       Subtype_Indication     =>
+                         New_Reference_To (Etype (Exp), Loc)));
+
+               Insert_Action (N, New_Decl);
+
+               --  Inherit the final chain to ensure that the expansion of the
+               --  aggregate is correct in case of controlled types
+
+               if Controlled_Type (Directly_Designated_Type (PtrT)) then
+                  Set_Associated_Final_Chain (Def_Id,
+                    Associated_Final_Chain (PtrT));
+               end if;
+
+               --  Declare the object using the previous type declaration
+
+               if Aggr_In_Place then
+                  Tmp_Node :=
+                    Make_Object_Declaration (Loc,
+                      Defining_Identifier => Temp,
+                      Object_Definition   => New_Reference_To (Def_Id, Loc),
+                      Expression          =>
+                        Make_Allocator (Loc,
+                          New_Reference_To (Etype (Exp), Loc)));
+
+                  Set_Comes_From_Source
+                    (Expression (Tmp_Node), Comes_From_Source (N));
+
+                  Set_No_Initialization (Expression (Tmp_Node));
+                  Insert_Action (N, Tmp_Node);
+
+                  if Controlled_Type (T)
+                    and then Ekind (PtrT) = E_Anonymous_Access_Type
+                  then
+                     --  Create local finalization list for access parameter
+
+                     Flist :=
+                       Get_Allocator_Final_List (N, Base_Type (T), PtrT);
+                  end if;
+
+                  Convert_Aggr_In_Allocator (N, Tmp_Node, Exp);
+               else
+                  Node := Relocate_Node (N);
+                  Set_Analyzed (Node);
+                  Insert_Action (N,
+                    Make_Object_Declaration (Loc,
+                      Defining_Identifier => Temp,
+                      Constant_Present    => True,
+                      Object_Definition   => New_Reference_To (Def_Id, Loc),
+                      Expression          => Node));
+               end if;
+
+               --  Generate an additional object containing the address of the
+               --  returned object. The type of this second object declaration
+               --  is the correct type required for the common processing
+               --  that is still performed by this subprogram. The displacement
+               --  of this pointer to reference the component associated with
+               --  the interface type will be done at the end of the common
+               --  processing.
+
+               New_Decl :=
+                 Make_Object_Declaration (Loc,
+                   Defining_Identifier => Make_Defining_Identifier (Loc,
+                                             New_Internal_Name ('P')),
+                   Object_Definition   => New_Reference_To (PtrT, Loc),
+                   Expression          => Unchecked_Convert_To (PtrT,
+                                            New_Reference_To (Temp, Loc)));
+
+               Insert_Action (N, New_Decl);
+
+               Tmp_Node := New_Decl;
+               Temp     := Defining_Identifier (New_Decl);
+            end;
          end if;
 
-         --  Suppress the tag assignment when Java_VM because JVM tags
-         --  are represented implicitly in objects.
+         Apply_Accessibility_Check (Temp);
+
+         --  Generate the tag assignment
 
-         if Is_Tagged_Type (T)
-           and then not Is_Class_Wide_Type (T)
-           and then not Java_VM
+         --  Suppress the tag assignment when VM_Target because VM tags are
+         --  represented implicitly in objects.
+
+         if VM_Target /= No_VM then
+            null;
+
+         --  Ada 2005 (AI-251): Suppress the tag assignment with class-wide
+         --  interface objects because in this case the tag does not change.
+
+         elsif Is_Interface (Directly_Designated_Type (Etype (N))) then
+            pragma Assert (Is_Class_Wide_Type
+                            (Directly_Designated_Type (Etype (N))));
+            null;
+
+         elsif Is_Tagged_Type (T) and then not Is_Class_Wide_Type (T) then
+            TagT := T;
+            TagR := New_Reference_To (Temp, Loc);
+
+         elsif Is_Private_Type (T)
+           and then Is_Tagged_Type (Underlying_Type (T))
          then
+            TagT := Underlying_Type (T);
+            TagR :=
+              Unchecked_Convert_To (Underlying_Type (T),
+                Make_Explicit_Dereference (Loc,
+                  Prefix => New_Reference_To (Temp, Loc)));
+         end if;
+
+         if Present (TagT) then
             Tag_Assign :=
               Make_Assignment_Statement (Loc,
                 Name =>
                   Make_Selected_Component (Loc,
-                    Prefix => New_Reference_To (Temp, Loc),
+                    Prefix => TagR,
                     Selector_Name =>
-                      New_Reference_To (Tag_Component (T), Loc)),
+                      New_Reference_To (First_Tag_Component (TagT), Loc)),
 
                 Expression =>
                   Unchecked_Convert_To (RTE (RE_Tag),
-                    New_Reference_To (Access_Disp_Table (T), Loc)));
+                    New_Reference_To
+                      (Elists.Node (First_Elmt (Access_Disp_Table (TagT))),
+                       Loc)));
 
             --  The previous assignment has to be done in any case
 
             Set_Assignment_OK (Name (Tag_Assign));
             Insert_Action (N, Tag_Assign);
-
-         elsif Is_Private_Type (T)
-           and then Is_Tagged_Type (Underlying_Type (T))
-           and then not Java_VM
-         then
-            declare
-               Utyp : constant Entity_Id := Underlying_Type (T);
-               Ref  : constant Node_Id :=
-                        Unchecked_Convert_To (Utyp,
-                          Make_Explicit_Dereference (Loc,
-                            New_Reference_To (Temp, Loc)));
-
-            begin
-               Tag_Assign :=
-                 Make_Assignment_Statement (Loc,
-                   Name =>
-                     Make_Selected_Component (Loc,
-                       Prefix => Ref,
-                       Selector_Name =>
-                         New_Reference_To (Tag_Component (Utyp), Loc)),
-
-                   Expression =>
-                     Unchecked_Convert_To (RTE (RE_Tag),
-                       New_Reference_To (
-                         Access_Disp_Table (Utyp), Loc)));
-
-               Set_Assignment_OK (Name (Tag_Assign));
-               Insert_Action (N, Tag_Assign);
-            end;
          end if;
 
-         if Controlled_Type (Designated_Type (PtrT))
+         if Controlled_Type (DesigT)
             and then Controlled_Type (T)
          then
             declare
@@ -535,7 +872,7 @@ package body Exp_Ch4 is
                   if Controlled_Type (T)
                     and then Ekind (PtrT) = E_Anonymous_Access_Type
                   then
-                     --  Create local finalization list for access parameter.
+                     --  Create local finalization list for access parameter
 
                      Flist :=
                        Get_Allocator_Final_List (N, Base_Type (T), PtrT);
@@ -546,7 +883,18 @@ package body Exp_Ch4 is
                   Attach :=  Make_Integer_Literal (Loc, 2);
                end if;
 
-               if not Aggr_In_Place then
+               --  Generate an Adjust call if the object will be moved. In Ada
+               --  2005, the object may be inherently limited, in which case
+               --  there is no Adjust procedure, and the object is built in
+               --  place. In Ada 95, the object can be limited but not
+               --  inherently limited if this allocator came from a return
+               --  statement (we're allocating the result on the secondary
+               --  stack). In that case, the object will be moved, so we _do_
+               --  want to Adjust.
+
+               if not Aggr_In_Place
+                 and then not Is_Inherently_Limited_Type (T)
+               then
                   Insert_Actions (N,
                     Make_Adjust_Call (
                       Ref          =>
@@ -558,11 +906,12 @@ package body Exp_Ch4 is
 
                       Unchecked_Convert_To (T,
                         Make_Explicit_Dereference (Loc,
-                          New_Reference_To (Temp, Loc))),
+                          Prefix => New_Reference_To (Temp, Loc))),
 
                       Typ          => T,
                       Flist_Ref    => Flist,
-                      With_Attach  => Attach));
+                      With_Attach  => Attach,
+                      Allocator    => True));
                end if;
             end;
          end if;
@@ -570,6 +919,14 @@ package body Exp_Ch4 is
          Rewrite (N, New_Reference_To (Temp, Loc));
          Analyze_And_Resolve (N, PtrT);
 
+         --  Ada 2005 (AI-251): Displace the pointer to reference the
+         --  record component containing the secondary dispatch table
+         --  of the interface type.
+
+         if Is_Interface (Directly_Designated_Type (PtrT)) then
+            Displace_Allocator_Pointer (N);
+         end if;
+
       elsif Aggr_In_Place then
          Temp :=
            Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
@@ -585,18 +942,18 @@ package body Exp_Ch4 is
 
          Set_No_Initialization (Expression (Tmp_Node));
          Insert_Action (N, Tmp_Node);
-         Convert_Aggr_In_Allocator (Tmp_Node, Exp);
+         Convert_Aggr_In_Allocator (N, Tmp_Node, Exp);
          Rewrite (N, New_Reference_To (Temp, Loc));
          Analyze_And_Resolve (N, PtrT);
 
-      elsif Is_Access_Type (Designated_Type (PtrT))
+      elsif Is_Access_Type (DesigT)
         and then Nkind (Exp) = N_Allocator
         and then Nkind (Expression (Exp)) /= N_Qualified_Expression
       then
          --  Apply constraint to designated subtype indication
 
          Apply_Constraint_Check (Expression (Exp),
-           Designated_Type (Designated_Type (PtrT)),
+           Designated_Type (DesigT),
            No_Sliding => True);
 
          if Nkind (Expression (Exp)) = N_Raise_Constraint_Error then
@@ -623,12 +980,12 @@ package body Exp_Ch4 is
          --  on the qualified expression does not allow sliding,
          --  but this check does (a relaxation from Ada 83).
 
-         if Is_Constrained (Designated_Type (PtrT))
+         if Is_Constrained (DesigT)
            and then not Subtypes_Statically_Match
-                          (T, Designated_Type (PtrT))
+                          (T, DesigT)
          then
             Apply_Constraint_Check
-              (Exp, Designated_Type (PtrT), No_Sliding => False);
+              (Exp, DesigT, No_Sliding => False);
 
          --  The nonsliding check should really be performed
          --  (unconditionally) against the subtype of the
@@ -637,7 +994,44 @@ package body Exp_Ch4 is
 
          else
             Apply_Constraint_Check
-              (Exp, Designated_Type (PtrT), No_Sliding => True);
+              (Exp, DesigT, No_Sliding => True);
+         end if;
+
+         --  For an access to unconstrained packed array, GIGI needs
+         --  to see an expression with a constrained subtype in order
+         --  to compute the proper size for the allocator.
+
+         if Is_Array_Type (T)
+           and then not Is_Constrained (T)
+           and then Is_Packed (T)
+         then
+            declare
+               ConstrT      : constant Entity_Id :=
+                                Make_Defining_Identifier (Loc,
+                                  Chars => New_Internal_Name ('A'));
+               Internal_Exp : constant Node_Id   := Relocate_Node (Exp);
+            begin
+               Insert_Action (Exp,
+                 Make_Subtype_Declaration (Loc,
+                   Defining_Identifier => ConstrT,
+                   Subtype_Indication  =>
+                     Make_Subtype_From_Expr (Exp, T)));
+               Freeze_Itype (ConstrT, Exp);
+               Rewrite (Exp, OK_Convert_To (ConstrT, Internal_Exp));
+            end;
+         end if;
+
+         --  Ada 2005 (AI-318-02): If the initialization expression is a
+         --  call to a build-in-place function, then access to the allocated
+         --  object must be passed to the function. Currently we limit such
+         --  functions to those with constrained limited result subtypes,
+         --  but eventually we plan to expand the allowed forms of functions
+         --  that are treated as build-in-place.
+
+         if Ada_Version >= Ada_05
+           and then Is_Build_In_Place_Function_Call (Exp)
+         then
+            Make_Build_In_Place_Call_In_Allocator (N, Exp);
          end if;
       end if;
 
@@ -723,12 +1117,12 @@ package body Exp_Ch4 is
    begin
       --  Deal first with unpacked case, where we can call a runtime routine
       --  except that we avoid this for targets for which are not addressable
-      --  by bytes, and for the JVM, since the JVM does not support direct
+      --  by bytes, and for the JVM/CIL, since they do not support direct
       --  addressing of array components.
 
       if not Is_Bit_Packed_Array (Typ1)
         and then Byte_Addressable
-        and then not Java_VM
+        and then VM_Target = No_VM
       then
          --  The call we generate is:
 
@@ -964,7 +1358,7 @@ package body Exp_Ch4 is
         (Arr : Entity_Id;
          Nam : Name_Id;
          Num : Int) return Node_Id;
-      --  This builds the attribute reference Arr'Nam (Expr).
+      --  This builds the attribute reference Arr'Nam (Expr)
 
       function Component_Equality (Typ : Entity_Id) return Node_Id;
       --  Create one statement to compare corresponding components,
@@ -1063,12 +1457,26 @@ package body Exp_Ch4 is
          Test := Expand_Composite_Equality
                    (Nod, Component_Type (Typ), L, R, Decls);
 
-         return
-           Make_Implicit_If_Statement (Nod,
-             Condition => Make_Op_Not (Loc, Right_Opnd => Test),
-             Then_Statements => New_List (
-               Make_Return_Statement (Loc,
-                 Expression => New_Occurrence_Of (Standard_False, Loc))));
+         --  If some (sub)component is an unchecked_union, the whole operation
+         --  will raise program error.
+
+         if Nkind (Test) = N_Raise_Program_Error then
+
+            --  This node is going to be inserted at a location where a
+            --  statement is expected: clear its Etype so analysis will
+            --  set it to the expected Standard_Void_Type.
+
+            Set_Etype (Test, Empty);
+            return Test;
+
+         else
+            return
+              Make_Implicit_If_Statement (Nod,
+                Condition => Make_Op_Not (Loc, Right_Opnd => Test),
+                Then_Statements => New_List (
+                  Make_Simple_Return_Statement (Loc,
+                    Expression => New_Occurrence_Of (Standard_False, Loc))));
+         end if;
       end Component_Equality;
 
       ------------------
@@ -1152,7 +1560,8 @@ package body Exp_Ch4 is
            Handle_One_Dimension (N + 1, Next_Index (Index)));
 
          if Need_Separate_Indexes then
-            --  Generate guard for loop, followed by increments of indices.
+
+            --  Generate guard for loop, followed by increments of indices
 
             Append_To (Stm_List,
                Make_Exit_Statement (Loc,
@@ -1180,8 +1589,8 @@ package body Exp_Ch4 is
                     Expressions    => New_List (New_Reference_To (Bn, Loc)))));
          end if;
 
-         --  If separate indexes, we need a declare block for An and Bn,
-         --  and a loop without an iteration scheme.
+         --  If separate indexes, we need a declare block for An and Bn, and a
+         --  loop without an iteration scheme.
 
          if Need_Separate_Indexes then
             Loop_Stm :=
@@ -1336,7 +1745,7 @@ package body Exp_Ch4 is
             Make_Function_Specification (Loc,
               Defining_Unit_Name       => Func_Name,
               Parameter_Specifications => Formals,
-              Subtype_Mark => New_Reference_To (Standard_Boolean, Loc)),
+              Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
 
           Declarations =>  Decls,
 
@@ -1347,20 +1756,20 @@ package body Exp_Ch4 is
                 Make_Implicit_If_Statement (Nod,
                   Condition => Test_Empty_Arrays,
                   Then_Statements => New_List (
-                    Make_Return_Statement (Loc,
+                    Make_Simple_Return_Statement (Loc,
                       Expression =>
                         New_Occurrence_Of (Standard_True, Loc)))),
 
                 Make_Implicit_If_Statement (Nod,
                   Condition => Test_Lengths_Correspond,
                   Then_Statements => New_List (
-                    Make_Return_Statement (Loc,
+                    Make_Simple_Return_Statement (Loc,
                       Expression =>
                         New_Occurrence_Of (Standard_False, Loc)))),
 
                 Handle_One_Dimension (1, First_Index (Ltyp)),
 
-                Make_Return_Statement (Loc,
+                Make_Simple_Return_Statement (Loc,
                   Expression => New_Occurrence_Of (Standard_True, Loc)))));
 
          Set_Has_Completion (Func_Name, True);
@@ -1411,61 +1820,73 @@ package body Exp_Ch4 is
       Typ : constant Entity_Id  := Etype (N);
 
    begin
-      if Is_Bit_Packed_Array (Typ) then
+      --  Special case of bit packed array where both operands are known
+      --  to be properly aligned. In this case we use an efficient run time
+      --  routine to carry out the operation (see System.Bit_Ops).
+
+      if Is_Bit_Packed_Array (Typ)
+        and then not Is_Possibly_Unaligned_Object (Left_Opnd (N))
+        and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
+      then
          Expand_Packed_Boolean_Operator (N);
+         return;
+      end if;
 
-      else
-         --  For the normal non-packed case, the general expansion is
-         --  to build a function for carrying out the comparison (using
-         --  Make_Boolean_Array_Op) and then inserting it into the tree.
-         --  The original operator node is then rewritten as a call to
-         --  this function.
+      --  For the normal non-packed case, the general expansion is to build
+      --  function for carrying out the comparison (use Make_Boolean_Array_Op)
+      --  and then inserting it into the tree. The original operator node is
+      --  then rewritten as a call to this function. We also use this in the
+      --  packed case if either operand is a possibly unaligned object.
 
-         declare
-            Loc       : constant Source_Ptr := Sloc (N);
-            L         : constant Node_Id    := Relocate_Node (Left_Opnd  (N));
-            R         : constant Node_Id    := Relocate_Node (Right_Opnd (N));
-            Func_Body : Node_Id;
-            Func_Name : Entity_Id;
+      declare
+         Loc       : constant Source_Ptr := Sloc (N);
+         L         : constant Node_Id    := Relocate_Node (Left_Opnd  (N));
+         R         : constant Node_Id    := Relocate_Node (Right_Opnd (N));
+         Func_Body : Node_Id;
+         Func_Name : Entity_Id;
 
-         begin
-            Convert_To_Actual_Subtype (L);
-            Convert_To_Actual_Subtype (R);
-            Ensure_Defined (Etype (L), N);
-            Ensure_Defined (Etype (R), N);
-            Apply_Length_Check (R, Etype (L));
-
-            if Nkind (Parent (N)) = N_Assignment_Statement
-               and then Safe_In_Place_Array_Op (Name (Parent (N)), L, R)
-            then
-               Build_Boolean_Array_Proc_Call (Parent (N), L, R);
+      begin
+         Convert_To_Actual_Subtype (L);
+         Convert_To_Actual_Subtype (R);
+         Ensure_Defined (Etype (L), N);
+         Ensure_Defined (Etype (R), N);
+         Apply_Length_Check (R, Etype (L));
+
+         if Nkind (N) = N_Op_Xor then
+            Silly_Boolean_Array_Xor_Test (N, Etype (L));
+         end if;
 
-            elsif Nkind (Parent (N)) = N_Op_Not
-               and then Nkind (N) = N_Op_And
-               and then
-                 Safe_In_Place_Array_Op (Name (Parent (Parent (N))), L, R)
-            then
-               return;
-            else
+         if Nkind (Parent (N)) = N_Assignment_Statement
+           and then Safe_In_Place_Array_Op (Name (Parent (N)), L, R)
+         then
+            Build_Boolean_Array_Proc_Call (Parent (N), L, R);
+
+         elsif Nkind (Parent (N)) = N_Op_Not
+           and then Nkind (N) = N_Op_And
+           and then
+             Safe_In_Place_Array_Op (Name (Parent (Parent (N))), L, R)
+         then
+            return;
+         else
 
-               Func_Body := Make_Boolean_Array_Op (Etype (L), N);
-               Func_Name := Defining_Unit_Name (Specification (Func_Body));
-               Insert_Action (N, Func_Body);
+            Func_Body := Make_Boolean_Array_Op (Etype (L), N);
+            Func_Name := Defining_Unit_Name (Specification (Func_Body));
+            Insert_Action (N, Func_Body);
 
-               --  Now rewrite the expression with a call
+            --  Now rewrite the expression with a call
 
-               Rewrite (N,
-                 Make_Function_Call (Loc,
-                   Name => New_Reference_To (Func_Name, Loc),
-                   Parameter_Associations =>
-                     New_List
-                       (L, Make_Type_Conversion
-                          (Loc, New_Reference_To (Etype (L), Loc), R))));
+            Rewrite (N,
+              Make_Function_Call (Loc,
+                Name                   => New_Reference_To (Func_Name, Loc),
+                Parameter_Associations =>
+                  New_List (
+                    L,
+                    Make_Type_Conversion
+                      (Loc, New_Reference_To (Etype (L), Loc), R))));
 
-               Analyze_And_Resolve (N, Typ);
-            end if;
-         end;
-      end if;
+            Analyze_And_Resolve (N, Typ);
+         end if;
+      end;
    end Expand_Boolean_Operator;
 
    -------------------------------
@@ -1650,14 +2071,9 @@ package body Exp_Ch4 is
                         --  It is not possible to infer the discriminant since
                         --  the subtype is not constrained.
 
-                        Insert_Action (Nod,
+                        return
                           Make_Raise_Program_Error (Loc,
-                            Reason => PE_Unchecked_Union_Restriction));
-
-                        --  Prevent Gigi from generating illegal code, change
-                        --  the equality to a standard False.
-
-                        return New_Occurrence_Of (Standard_False, Loc);
+                            Reason => PE_Unchecked_Union_Restriction);
                      end if;
 
                      --  Rhs of the composite equality
@@ -1686,11 +2102,9 @@ package body Exp_Ch4 is
 
                         end if;
                      else
-                        Insert_Action (Nod,
+                        return
                           Make_Raise_Program_Error (Loc,
-                            Reason => PE_Unchecked_Union_Restriction));
-
-                        return Empty;
+                            Reason => PE_Unchecked_Union_Restriction);
                      end if;
 
                      --  Call the TSS equality function with the inferred
@@ -1733,7 +2147,7 @@ package body Exp_Ch4 is
 
    --  Let n be the number of array operands to be concatenated, Base_Typ
    --  their base type, Ind_Typ their index type, and Arr_Typ the original
-   --  array type to which the concatenantion operator applies, then the
+   --  array type to which the concatenation operator applies, then the
    --  following subprogram is constructed:
 
    --  [function Cnn (S1 : Base_Typ; ...; Sn : Base_Typ) return Base_Typ is
@@ -1852,48 +2266,48 @@ package body Exp_Ch4 is
       --    L := Si'First;       otherwise (where I is the input param given)
 
       function H return Node_Id;
-      --  Builds reference to identifier H.
+      --  Builds reference to identifier H
 
       function Ind_Val (E : Node_Id) return Node_Id;
       --  Builds expression Ind_Typ'Val (E);
 
       function L return Node_Id;
-      --  Builds reference to identifier L.
+      --  Builds reference to identifier L
 
       function L_Pos return Node_Id;
-      --  Builds expression Integer_Type'(Ind_Typ'Pos (L)).
-      --  We qualify the expression to avoid universal_integer computations
-      --  whenever possible, in the expression for the upper bound H.
+      --  Builds expression Integer_Type'(Ind_Typ'Pos (L)). We qualify the
+      --  expression to avoid universal_integer computations whenever possible,
+      --  in the expression for the upper bound H.
 
       function L_Succ return Node_Id;
-      --  Builds expression Ind_Typ'Succ (L).
+      --  Builds expression Ind_Typ'Succ (L)
 
       function One return Node_Id;
-      --  Builds integer literal one.
+      --  Builds integer literal one
 
       function P return Node_Id;
-      --  Builds reference to identifier P.
+      --  Builds reference to identifier P
 
       function P_Succ return Node_Id;
-      --  Builds expression Ind_Typ'Succ (P).
+      --  Builds expression Ind_Typ'Succ (P)
 
       function R return Node_Id;
-      --  Builds reference to identifier R.
+      --  Builds reference to identifier R
 
       function S (I : Nat) return Node_Id;
-      --  Builds reference to identifier Si, where I is the value given.
+      --  Builds reference to identifier Si, where I is the value given
 
       function S_First (I : Nat) return Node_Id;
-      --  Builds expression Si'First, where I is the value given.
+      --  Builds expression Si'First, where I is the value given
 
       function S_Last (I : Nat) return Node_Id;
-      --  Builds expression Si'Last, where I is the value given.
+      --  Builds expression Si'Last, where I is the value given
 
       function S_Length (I : Nat) return Node_Id;
-      --  Builds expression Si'Length, where I is the value given.
+      --  Builds expression Si'Length, where I is the value given
 
       function S_Length_Test (I : Nat) return Node_Id;
-      --  Builds expression Si'Length /= 0, where I is the value given.
+      --  Builds expression Si'Length /= 0, where I is the value given
 
       -------------------
       -- Copy_Into_R_S --
@@ -2162,7 +2576,7 @@ package body Exp_Ch4 is
         Make_Function_Specification (Loc,
           Defining_Unit_Name       => Func_Id,
           Parameter_Specifications => Param_Specs,
-          Subtype_Mark             => New_Reference_To (Base_Typ, Loc));
+          Result_Definition        => New_Reference_To (Base_Typ, Loc));
 
       --  Construct L's object declaration
 
@@ -2187,7 +2601,7 @@ package body Exp_Ch4 is
           Condition       => S_Length_Test (1),
           Then_Statements => New_List (Init_L (1)),
           Elsif_Parts     => Elsif_List,
-          Else_Statements => New_List (Make_Return_Statement (Loc,
+          Else_Statements => New_List (Make_Simple_Return_Statement (Loc,
                                          Expression => S (Nb_Opnds))));
 
       --  Construct the declaration for H
@@ -2238,7 +2652,8 @@ package body Exp_Ch4 is
                       Then_Statements => Copy_Into_R_S (I, I = Nb_Opnds)));
       end loop;
 
-      Append_To (Declare_Stmts, Make_Return_Statement (Loc, Expression => R));
+      Append_To
+        (Declare_Stmts, Make_Simple_Return_Statement (Loc, Expression => R));
 
       --  Construct the declare block
 
@@ -2265,7 +2680,7 @@ package body Exp_Ch4 is
 
       --  Note that this does *not* fix the array concatenation bug when the
       --  low bound is Integer'first sibce that bug comes from the pointer
-      --  dereferencing an unconstrained array. An there we need a constraint
+      --  dereferencing an unconstrained array. And there we need a constraint
       --  check to make sure the length of the concatenated array is ok. ???
 
       Insert_Action (Cnode, Func_Body, Suppress => All_Checks);
@@ -2371,10 +2786,248 @@ package body Exp_Ch4 is
    procedure Expand_N_Allocator (N : Node_Id) is
       PtrT  : constant Entity_Id  := Etype (N);
       Dtyp  : constant Entity_Id  := Designated_Type (PtrT);
-      Desig : Entity_Id;
+      Etyp  : constant Entity_Id  := Etype (Expression (N));
       Loc   : constant Source_Ptr := Sloc (N);
+      Desig : Entity_Id;
       Temp  : Entity_Id;
-      Node  : Node_Id;
+      Nod   : Node_Id;
+
+      procedure Complete_Coextension_Finalization;
+      --  Generate finalization calls for all nested coextensions of N. This
+      --  routine may allocate list controllers if necessary.
+
+      procedure Rewrite_Coextension (N : Node_Id);
+      --  Static coextensions have the same lifetime as the entity they
+      --  constrain. Such occurrences can be rewritten as aliased objects
+      --  and their unrestricted access used instead of the coextension.
+
+      ---------------------------------------
+      -- Complete_Coextension_Finalization --
+      ---------------------------------------
+
+      procedure Complete_Coextension_Finalization is
+         Coext      : Node_Id;
+         Coext_Elmt : Elmt_Id;
+         Flist      : Node_Id;
+         Ref        : Node_Id;
+
+         function Inside_A_Return_Statement (N : Node_Id) return Boolean;
+         --  Determine whether node N is part of a return statement
+
+         function Needs_Initialization_Call (N : Node_Id) return Boolean;
+         --  Determine whether node N is a subtype indicator allocator which
+         --  acts a coextension. Such coextensions need initialization.
+
+         -------------------------------
+         -- Inside_A_Return_Statement --
+         -------------------------------
+
+         function Inside_A_Return_Statement (N : Node_Id) return Boolean is
+            P : Node_Id;
+
+         begin
+            P := Parent (N);
+            while Present (P) loop
+               if Nkind_In
+                   (P, N_Extended_Return_Statement, N_Simple_Return_Statement)
+               then
+                  return True;
+
+               --  Stop the traversal when we reach a subprogram body
+
+               elsif Nkind (P) = N_Subprogram_Body then
+                  return False;
+               end if;
+
+               P := Parent (P);
+            end loop;
+
+            return False;
+         end Inside_A_Return_Statement;
+
+         -------------------------------
+         -- Needs_Initialization_Call --
+         -------------------------------
+
+         function Needs_Initialization_Call (N : Node_Id) return Boolean is
+            Obj_Decl : Node_Id;
+
+         begin
+            if Nkind (N) = N_Explicit_Dereference
+              and then Nkind (Prefix (N)) = N_Identifier
+              and then Nkind (Parent (Entity (Prefix (N)))) =
+                         N_Object_Declaration
+            then
+               Obj_Decl := Parent (Entity (Prefix (N)));
+
+               return
+                 Present (Expression (Obj_Decl))
+                   and then Nkind (Expression (Obj_Decl)) = N_Allocator
+                   and then Nkind (Expression (Expression (Obj_Decl))) /=
+                              N_Qualified_Expression;
+            end if;
+
+            return False;
+         end Needs_Initialization_Call;
+
+      --  Start of processing for Complete_Coextension_Finalization
+
+      begin
+         --  When a coextension root is inside a return statement, we need to
+         --  use the finalization chain of the function's scope. This does not
+         --  apply for controlled named access types because in those cases we
+         --  can use the finalization chain of the type itself.
+
+         if Inside_A_Return_Statement (N)
+           and then
+             (Ekind (PtrT) = E_Anonymous_Access_Type
+                or else
+                  (Ekind (PtrT) = E_Access_Type
+                     and then No (Associated_Final_Chain (PtrT))))
+         then
+            declare
+               Decl    : Node_Id;
+               Outer_S : Entity_Id;
+               S       : Entity_Id := Current_Scope;
+
+            begin
+               while Present (S) and then S /= Standard_Standard loop
+                  if Ekind (S) = E_Function then
+                     Outer_S := Scope (S);
+
+                     --  Retrieve the declaration of the body
+
+                     Decl := Parent (Parent (
+                               Corresponding_Body (Parent (Parent (S)))));
+                     exit;
+                  end if;
+
+                  S := Scope (S);
+               end loop;
+
+               --  Push the scope of the function body since we are inserting
+               --  the list before the body, but we are currently in the body
+               --  itself. Override the finalization list of PtrT since the
+               --  finalization context is now different.
+
+               Push_Scope (Outer_S);
+               Build_Final_List (Decl, PtrT);
+               Pop_Scope;
+            end;
+
+         --  The root allocator may not be controlled, but it still needs a
+         --  finalization list for all nested coextensions.
+
+         elsif No (Associated_Final_Chain (PtrT)) then
+            Build_Final_List (N, PtrT);
+         end if;
+
+         Flist :=
+           Make_Selected_Component (Loc,
+             Prefix =>
+               New_Reference_To (Associated_Final_Chain (PtrT), Loc),
+             Selector_Name =>
+               Make_Identifier (Loc, Name_F));
+
+         Coext_Elmt := First_Elmt (Coextensions (N));
+         while Present (Coext_Elmt) loop
+            Coext := Node (Coext_Elmt);
+
+            --  Generate:
+            --    typ! (coext.all)
+
+            if Nkind (Coext) = N_Identifier then
+               Ref := Make_Unchecked_Type_Conversion (Loc,
+                        Subtype_Mark =>
+                          New_Reference_To (Etype (Coext), Loc),
+                        Expression =>
+                          Make_Explicit_Dereference (Loc,
+                            New_Copy_Tree (Coext)));
+            else
+               Ref := New_Copy_Tree (Coext);
+            end if;
+
+            --  No initialization call if not allowed
+
+            Check_Restriction (No_Default_Initialization, N);
+
+            if not Restriction_Active (No_Default_Initialization) then
+
+               --  Generate:
+               --    initialize (Ref)
+               --    attach_to_final_list (Ref, Flist, 2)
+
+               if Needs_Initialization_Call (Coext) then
+                  Insert_Actions (N,
+                    Make_Init_Call (
+                      Ref         => Ref,
+                      Typ         => Etype (Coext),
+                      Flist_Ref   => Flist,
+                      With_Attach => Make_Integer_Literal (Loc, Uint_2)));
+
+               --  Generate:
+               --    attach_to_final_list (Ref, Flist, 2)
+
+               else
+                  Insert_Action (N,
+                    Make_Attach_Call (
+                      Obj_Ref     => Ref,
+                      Flist_Ref   => New_Copy_Tree (Flist),
+                      With_Attach => Make_Integer_Literal (Loc, Uint_2)));
+               end if;
+            end if;
+
+            Next_Elmt (Coext_Elmt);
+         end loop;
+      end Complete_Coextension_Finalization;
+
+      -------------------------
+      -- Rewrite_Coextension --
+      -------------------------
+
+      procedure Rewrite_Coextension (N : Node_Id) is
+         Temp : constant Node_Id :=
+                  Make_Defining_Identifier (Loc,
+                    New_Internal_Name ('C'));
+
+         --  Generate:
+         --    Cnn : aliased Etyp;
+
+         Decl : constant Node_Id :=
+                  Make_Object_Declaration (Loc,
+                    Defining_Identifier => Temp,
+                    Aliased_Present     => True,
+                    Object_Definition   =>
+                      New_Occurrence_Of (Etyp, Loc));
+         Nod  : Node_Id;
+
+      begin
+         if Nkind (Expression (N)) = N_Qualified_Expression then
+            Set_Expression (Decl, Expression (Expression (N)));
+         end if;
+
+         --  Find the proper insertion node for the declaration
+
+         Nod := Parent (N);
+         while Present (Nod) loop
+            exit when Nkind (Nod) in N_Statement_Other_Than_Procedure_Call
+              or else Nkind (Nod) = N_Procedure_Call_Statement
+              or else Nkind (Nod) in N_Declaration;
+            Nod := Parent (Nod);
+         end loop;
+
+         Insert_Before (Nod, Decl);
+         Analyze (Decl);
+
+         Rewrite (N,
+           Make_Attribute_Reference (Loc,
+             Prefix         => New_Occurrence_Of (Temp, Loc),
+             Attribute_Name => Name_Unrestricted_Access));
+
+         Analyze_And_Resolve (N, PtrT);
+      end Rewrite_Coextension;
+
+   --  Start of processing for Expand_N_Allocator
 
    begin
       --  RM E.2.3(22). We enforce that the expected type of an allocator
@@ -2390,7 +3043,7 @@ package body Exp_Ch4 is
 
       if Present (Storage_Pool (N)) then
          if Is_RTE (Storage_Pool (N), RE_SS_Pool) then
-            if not Java_VM then
+            if VM_Target = No_VM then
                Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
             end if;
 
@@ -2439,7 +3092,7 @@ package body Exp_Ch4 is
          Desig := Subtype_Mark (Expression (N));
 
          --  If context is constrained, use constrained subtype directly,
-         --  so that the constant is not labelled as having a nomimally
+         --  so that the constant is not labelled as having a nominally
          --  unconstrained subtype.
 
          if Entity (Desig) = Base_Type (Dtyp) then
@@ -2468,105 +3121,119 @@ package body Exp_Ch4 is
          return;
       end if;
 
+      --  Same if the allocator is an access discriminant for a local object:
+      --  instead of an allocator we create a local value and constrain the
+      --  the enclosing object with the corresponding access attribute.
+
+      if Is_Static_Coextension (N) then
+         Rewrite_Coextension (N);
+         return;
+      end if;
+
+      --  The current allocator creates an object which may contain nested
+      --  coextensions. Use the current allocator's finalization list to
+      --  generate finalization call for all nested coextensions.
+
+      if Is_Coextension_Root (N) then
+         Complete_Coextension_Finalization;
+      end if;
+
       --  Handle case of qualified expression (other than optimization above)
 
       if Nkind (Expression (N)) = N_Qualified_Expression then
          Expand_Allocator_Expression (N);
+         return;
+      end if;
 
-         --  If the allocator is for a type which requires initialization, and
-         --  there is no initial value (i.e. operand is a subtype indication
-         --  rather than a qualifed expression), then we must generate a call
-         --  to the initialization routine. This is done using an expression
-         --  actions node:
-         --
-         --     [Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn]
-         --
-         --  Here ptr_T is the pointer type for the allocator, and T is the
-         --  subtype of the allocator. A special case arises if the designated
-         --  type of the access type is a task or contains tasks. In this case
-         --  the call to Init (Temp.all ...) is replaced by code that ensures
-         --  that tasks get activated (see Exp_Ch9.Build_Task_Allocate_Block
-         --  for details). In addition, if the type T is a task T, then the
-         --  first argument to Init must be converted to the task record type.
+      --  If the allocator is for a type which requires initialization, and
+      --  there is no initial value (i.e. operand is a subtype indication
+      --  rather than a qualified expression), then we must generate a call
+      --  to the initialization routine. This is done using an expression
+      --  actions node:
 
-      else
-         declare
-            T            : constant Entity_Id  := Entity (Expression (N));
-            Init         : Entity_Id;
-            Arg1         : Node_Id;
-            Args         : List_Id;
-            Decls        : List_Id;
-            Decl         : Node_Id;
-            Discr        : Elmt_Id;
-            Flist        : Node_Id;
-            Temp_Decl    : Node_Id;
-            Temp_Type    : Entity_Id;
-            Attach_Level : Uint;
+      --     [Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn]
 
-         begin
-            if No_Initialization (N) then
-               null;
+      --  Here ptr_T is the pointer type for the allocator, and T is the
+      --  subtype of the allocator. A special case arises if the designated
+      --  type of the access type is a task or contains tasks. In this case
+      --  the call to Init (Temp.all ...) is replaced by code that ensures
+      --  that tasks get activated (see Exp_Ch9.Build_Task_Allocate_Block
+      --  for details). In addition, if the type T is a task T, then the
+      --  first argument to Init must be converted to the task record type.
 
-            --  Case of no initialization procedure present
+      declare
+         T            : constant Entity_Id := Entity (Expression (N));
+         Init         : Entity_Id;
+         Arg1         : Node_Id;
+         Args         : List_Id;
+         Decls        : List_Id;
+         Decl         : Node_Id;
+         Discr        : Elmt_Id;
+         Flist        : Node_Id;
+         Temp_Decl    : Node_Id;
+         Temp_Type    : Entity_Id;
+         Attach_Level : Uint;
 
-            elsif not Has_Non_Null_Base_Init_Proc (T) then
+      begin
+         if No_Initialization (N) then
+            null;
 
-               --  Case of simple initialization required
+         --  Case of no initialization procedure present
 
-               if Needs_Simple_Initialization (T) then
-                  Rewrite (Expression (N),
-                    Make_Qualified_Expression (Loc,
-                      Subtype_Mark => New_Occurrence_Of (T, Loc),
-                      Expression   => Get_Simple_Init_Val (T, Loc)));
+         elsif not Has_Non_Null_Base_Init_Proc (T) then
 
-                  Analyze_And_Resolve (Expression (Expression (N)), T);
-                  Analyze_And_Resolve (Expression (N), T);
-                  Set_Paren_Count (Expression (Expression (N)), 1);
-                  Expand_N_Allocator (N);
+            --  Case of simple initialization required
 
-               --  No initialization required
+            if Needs_Simple_Initialization (T) then
+               Check_Restriction (No_Default_Initialization, N);
+               Rewrite (Expression (N),
+                 Make_Qualified_Expression (Loc,
+                   Subtype_Mark => New_Occurrence_Of (T, Loc),
+                   Expression   => Get_Simple_Init_Val (T, N)));
 
-               else
-                  null;
-               end if;
+               Analyze_And_Resolve (Expression (Expression (N)), T);
+               Analyze_And_Resolve (Expression (N), T);
+               Set_Paren_Count     (Expression (Expression (N)), 1);
+               Expand_N_Allocator  (N);
 
-            --  Case of initialization procedure present, must be called
+            --  No initialization required
 
             else
+               null;
+            end if;
+
+         --  Case of initialization procedure present, must be called
+
+         else
+            Check_Restriction (No_Default_Initialization, N);
+
+            if not Restriction_Active (No_Default_Initialization) then
                Init := Base_Init_Proc (T);
-               Node := N;
-               Temp :=
-                 Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
+               Nod  := N;
+               Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
 
                --  Construct argument list for the initialization routine call
-               --  The CPP constructor needs the address directly
-
-               if Is_CPP_Class (T) then
-                  Arg1 := New_Reference_To (Temp, Loc);
-                  Temp_Type := T;
 
-               else
-                  Arg1 :=
-                    Make_Explicit_Dereference (Loc,
-                      Prefix => New_Reference_To (Temp, Loc));
-                  Set_Assignment_OK (Arg1);
-                  Temp_Type := PtrT;
+               Arg1 :=
+                 Make_Explicit_Dereference (Loc,
+                   Prefix => New_Reference_To (Temp, Loc));
+               Set_Assignment_OK (Arg1);
+               Temp_Type := PtrT;
 
-                  --  The initialization procedure expects a specific type.
-                  --  if the context is access to class wide, indicate that
-                  --  the object being allocated has the right specific type.
+               --  The initialization procedure expects a specific type. if the
+               --  context is access to class wide, indicate that the object
+               --  being allocated has the right specific type.
 
-                  if Is_Class_Wide_Type (Dtyp) then
-                     Arg1 := Unchecked_Convert_To (T, Arg1);
-                  end if;
+               if Is_Class_Wide_Type (Dtyp) then
+                  Arg1 := Unchecked_Convert_To (T, Arg1);
                end if;
 
-               --  If designated type is a concurrent type or if it is a
-               --  private type whose definition is a concurrent type,
-               --  the first argument in the Init routine has to be
-               --  unchecked conversion to the corresponding record type.
-               --  If the designated type is a derived type, we also
-               --  convert the argument to its root type.
+               --  If designated type is a concurrent type or if it is private
+               --  type whose definition is a concurrent type, the first
+               --  argument in the Init routine has to be unchecked conversion
+               --  to the corresponding record type. If the designated type is
+               --  a derived type, we also convert the argument to its root
+               --  type.
 
                if Is_Concurrent_Type (T) then
                   Arg1 :=
@@ -2581,10 +3248,8 @@ package body Exp_Ch4 is
                       (Corresponding_Record_Type (Full_View (T)), Arg1);
 
                elsif Etype (First_Formal (Init)) /= Base_Type (T) then
-
                   declare
                      Ftyp : constant Entity_Id := Etype (First_Formal (Init));
-
                   begin
                      Arg1 := OK_Convert_To (Etype (Ftyp), Arg1);
                      Set_Etype (Arg1, Ftyp);
@@ -2593,29 +3258,41 @@ package body Exp_Ch4 is
 
                Args := New_List (Arg1);
 
-               --  For the task case, pass the Master_Id of the access type
-               --  as the value of the _Master parameter, and _Chain as the
-               --  value of the _Chain parameter (_Chain will be defined as
-               --  part of the generated code for the allocator).
+               --  For the task case, pass the Master_Id of the access type as
+               --  the value of the _Master parameter, and _Chain as the value
+               --  of the _Chain parameter (_Chain will be defined as part of
+               --  the generated code for the allocator).
+
+               --  In Ada 2005, the context may be a function that returns an
+               --  anonymous access type. In that case the Master_Id has been
+               --  created when expanding the function declaration.
 
                if Has_Task (T) then
                   if No (Master_Id (Base_Type (PtrT))) then
 
-                     --  The designated type was an incomplete type, and
-                     --  the access type did not get expanded. Salvage
-                     --  it now.
+                     --  If we have a non-library level task with restriction
+                     --  No_Task_Hierarchy set, then no point in expanding.
 
+                     if not Is_Library_Level_Entity (T)
+                       and then Restriction_Active (No_Task_Hierarchy)
+                     then
+                        return;
+                     end if;
+
+                     --  The designated type was an incomplete type, and the
+                     --  access type did not get expanded. Salvage it now.
+
+                     pragma Assert (Present (Parent (Base_Type (PtrT))));
                      Expand_N_Full_Type_Declaration
                        (Parent (Base_Type (PtrT)));
                   end if;
 
-                  --  If the context of the allocator is a declaration or
-                  --  an assignment, we can generate a meaningful image for
-                  --  it, even though subsequent assignments might remove
-                  --  the connection between task and entity. We build this
-                  --  image when the left-hand side is a simple variable,
-                  --  a simple indexed assignment or a simple selected
-                  --  component.
+                  --  If the context of the allocator is a declaration or an
+                  --  assignment, we can generate a meaningful image for it,
+                  --  even though subsequent assignments might remove the
+                  --  connection between task and entity. We build this image
+                  --  when the left-hand side is a simple variable, a simple
+                  --  indexed assignment or a simple selected component.
 
                   if Nkind (Parent (N)) = N_Assignment_Statement then
                      declare
@@ -2624,13 +3301,13 @@ package body Exp_Ch4 is
                      begin
                         if Is_Entity_Name (Nam) then
                            Decls :=
-                             Build_Task_Image_Decls (
-                               Loc,
-                                 New_Occurrence_Of
-                                   (Entity (Nam), Sloc (Nam)), T);
+                             Build_Task_Image_Decls
+                               (Loc,
+                                New_Occurrence_Of
+                                  (Entity (Nam), Sloc (Nam)), T);
 
-                        elsif (Nkind (Nam) = N_Indexed_Component
-                                or else Nkind (Nam) = N_Selected_Component)
+                        elsif Nkind_In
+                          (Nam, N_Indexed_Component, N_Selected_Component)
                           and then Is_Entity_Name (Prefix (Nam))
                         then
                            Decls :=
@@ -2643,8 +3320,8 @@ package body Exp_Ch4 is
 
                   elsif Nkind (Parent (N)) = N_Object_Declaration then
                      Decls :=
-                       Build_Task_Image_Decls (
-                          Loc, Defining_Identifier (Parent (N)), T);
+                       Build_Task_Image_Decls
+                         (Loc, Defining_Identifier (Parent (N)), T);
 
                   else
                      Decls := Build_Task_Image_Decls (Loc, T, T);
@@ -2659,7 +3336,7 @@ package body Exp_Ch4 is
                   Append_To (Args,
                     New_Occurrence_Of (Defining_Identifier (Decl), Loc));
 
-               --  Has_Task is false, Decls not used
+                  --  Has_Task is false, Decls not used
 
                else
                   Decls := No_List;
@@ -2667,33 +3344,69 @@ package body Exp_Ch4 is
 
                --  Add discriminants if discriminated type
 
-               if Has_Discriminants (T) then
-                  Discr := First_Elmt (Discriminant_Constraint (T));
+               declare
+                  Dis : Boolean := False;
+                  Typ : Entity_Id;
 
-                  while Present (Discr) loop
-                     Append (New_Copy_Tree (Elists.Node (Discr)), Args);
-                     Next_Elmt (Discr);
-                  end loop;
+               begin
+                  if Has_Discriminants (T) then
+                     Dis := True;
+                     Typ := T;
 
-               elsif Is_Private_Type (T)
-                 and then Present (Full_View (T))
-                 and then Has_Discriminants (Full_View (T))
-               then
-                  Discr :=
-                    First_Elmt (Discriminant_Constraint (Full_View (T)));
+                  elsif Is_Private_Type (T)
+                    and then Present (Full_View (T))
+                    and then Has_Discriminants (Full_View (T))
+                  then
+                     Dis := True;
+                     Typ := Full_View (T);
+                  end if;
 
-                  while Present (Discr) loop
-                     Append (New_Copy_Tree (Elists.Node (Discr)), Args);
-                     Next_Elmt (Discr);
-                  end loop;
-               end if;
+                  if Dis then
+
+                     --  If the allocated object will be constrained by the
+                     --  default values for discriminants, then build a
+                     --  subtype with those defaults, and change the allocated
+                     --  subtype to that. Note that this happens in fewer
+                     --  cases in Ada 2005 (AI-363).
+
+                     if not Is_Constrained (Typ)
+                       and then Present (Discriminant_Default_Value
+                                         (First_Discriminant (Typ)))
+                       and then (Ada_Version < Ada_05
+                                  or else
+                                    not Has_Constrained_Partial_View (Typ))
+                     then
+                        Typ := Build_Default_Subtype (Typ, N);
+                        Set_Expression (N, New_Reference_To (Typ, Loc));
+                     end if;
+
+                     Discr := First_Elmt (Discriminant_Constraint (Typ));
+                     while Present (Discr) loop
+                        Nod := Node (Discr);
+                        Append (New_Copy_Tree (Node (Discr)), Args);
+
+                        --  AI-416: when the discriminant constraint is an
+                        --  anonymous access type make sure an accessibility
+                        --  check is inserted if necessary (3.10.2(22.q/2))
+
+                        if Ada_Version >= Ada_05
+                          and then
+                            Ekind (Etype (Nod)) = E_Anonymous_Access_Type
+                        then
+                           Apply_Accessibility_Check (Nod, Typ);
+                        end if;
+
+                        Next_Elmt (Discr);
+                     end loop;
+                  end if;
+               end;
 
                --  We set the allocator as analyzed so that when we analyze the
                --  expression actions node, we do not get an unwanted recursive
                --  expansion of the allocator expression.
 
                Set_Analyzed (N, True);
-               Node := Relocate_Node (N);
+               Nod := Relocate_Node (N);
 
                --  Here is the transformation:
                --    input:  new T
@@ -2702,37 +3415,30 @@ package body Exp_Ch4 is
                --    <CTRL>  Attach_To_Final_List (Finalizable (Temp.all));
                --    <CTRL>  Initialize (Finalizable (Temp.all));
 
-               --  Here ptr_T is the pointer type for the allocator, and T
-               --  is the subtype of the allocator.
+               --  Here ptr_T is the pointer type for the allocator, and is the
+               --  subtype of the allocator.
 
                Temp_Decl :=
                  Make_Object_Declaration (Loc,
                    Defining_Identifier => Temp,
                    Constant_Present    => True,
                    Object_Definition   => New_Reference_To (Temp_Type, Loc),
-                   Expression          => Node);
+                   Expression          => Nod);
 
                Set_Assignment_OK (Temp_Decl);
-
-               if Is_CPP_Class (T) then
-                  Set_Aliased_Present (Temp_Decl);
-               end if;
-
                Insert_Action (N, Temp_Decl, Suppress => All_Checks);
 
-               --  If the designated type is task type or contains tasks,
-               --  Create block to activate created tasks, and insert
+               --  If the designated type is task type or contains tasks,
+               --  create block to activate created tasks, and insert
                --  declaration for Task_Image variable ahead of call.
 
                if Has_Task (T) then
                   declare
                      L   : constant List_Id := New_List;
                      Blk : Node_Id;
-
                   begin
-                     Build_Task_Allocate_Block (L, Node, Args);
+                     Build_Task_Allocate_Block (L, Nod, Args);
                      Blk := Last (L);
-
                      Insert_List_Before (First (Declarations (Blk)), Decls);
                      Insert_Actions (N, L);
                   end;
@@ -2740,38 +3446,69 @@ package body Exp_Ch4 is
                else
                   Insert_Action (N,
                     Make_Procedure_Call_Statement (Loc,
-                      Name => New_Reference_To (Init, Loc),
+                      Name                   => New_Reference_To (Init, Loc),
                       Parameter_Associations => Args));
                end if;
 
                if Controlled_Type (T) then
-                  Flist := Get_Allocator_Final_List (N, Base_Type (T), PtrT);
-                  if Ekind (PtrT) = E_Anonymous_Access_Type then
-                     Attach_Level := Uint_1;
+
+                  --  Postpone the generation of a finalization call for the
+                  --  current allocator if it acts as a coextension.
+
+                  if Is_Dynamic_Coextension (N) then
+                     if No (Coextensions (N)) then
+                        Set_Coextensions (N, New_Elmt_List);
+                     end if;
+
+                     Append_Elmt (New_Copy_Tree (Arg1), Coextensions (N));
+
                   else
-                     Attach_Level := Uint_2;
-                  end if;
-                  Insert_Actions (N,
-                    Make_Init_Call (
-                      Ref          => New_Copy_Tree (Arg1),
-                      Typ          => T,
-                      Flist_Ref    => Flist,
-                      With_Attach  => Make_Integer_Literal (Loc,
-                        Attach_Level)));
-               end if;
+                     Flist :=
+                       Get_Allocator_Final_List (N, Base_Type (T), PtrT);
 
-               if Is_CPP_Class (T) then
-                  Rewrite (N,
-                    Make_Attribute_Reference (Loc,
-                      Prefix => New_Reference_To (Temp, Loc),
-                      Attribute_Name => Name_Unchecked_Access));
-               else
-                  Rewrite (N, New_Reference_To (Temp, Loc));
+                     --  Anonymous access types created for access parameters
+                     --  are attached to an explicitly constructed controller,
+                     --  which ensures that they can be finalized properly,
+                     --  even if their deallocation might not happen. The list
+                     --  associated with the controller is doubly-linked. For
+                     --  other anonymous access types, the object may end up
+                     --  on the global final list which is singly-linked.
+                     --  Work needed for access discriminants in Ada 2005 ???
+
+                     if Ekind (PtrT) = E_Anonymous_Access_Type
+                       and then
+                         Nkind (Associated_Node_For_Itype (PtrT))
+                     not in N_Subprogram_Specification
+                     then
+                        Attach_Level := Uint_1;
+                     else
+                        Attach_Level := Uint_2;
+                     end if;
+
+                     Insert_Actions (N,
+                       Make_Init_Call (
+                         Ref          => New_Copy_Tree (Arg1),
+                         Typ          => T,
+                         Flist_Ref    => Flist,
+                         With_Attach  => Make_Integer_Literal (Loc,
+                                           Intval => Attach_Level)));
+                  end if;
                end if;
 
+               Rewrite (N, New_Reference_To (Temp, Loc));
                Analyze_And_Resolve (N, PtrT);
             end if;
-         end;
+         end if;
+      end;
+
+      --  Ada 2005 (AI-251): If the allocator is for a class-wide interface
+      --  object that has been rewritten as a reference, we displace "this"
+      --  to reference properly its secondary dispatch table.
+
+      if Nkind (N) = N_Identifier
+        and then Is_Interface (Dtyp)
+      then
+         Displace_Allocator_Pointer (N);
       end if;
 
    exception
@@ -2783,8 +3520,8 @@ package body Exp_Ch4 is
    -- Expand_N_And_Then --
    -----------------------
 
-   --  Expand into conditional expression if Actions present, and also
-   --  deal with optimizing case of arguments being True or False.
+   --  Expand into conditional expression if Actions present, and also deal
+   --  with optimizing case of arguments being True or False.
 
    procedure Expand_N_And_Then (N : Node_Id) is
       Loc     : constant Source_Ptr := Sloc (N);
@@ -2819,9 +3556,9 @@ package body Exp_Ch4 is
             Adjust_Result_Type (N, Typ);
             return;
 
-         --  If left argument is False, change (False and then Right) to
-         --  False. In this case we can forget the actions associated with
-         --  Right, since they will never be executed.
+         --  If left argument is False, change (False and then Right) to False.
+         --  In this case we can forget the actions associated with Right,
+         --  since they will never be executed.
 
          elsif Entity (Left) = Standard_False then
             Kill_Dead_Code (Right);
@@ -2914,7 +3651,7 @@ package body Exp_Ch4 is
       --         Cnn := else-expr
       --      end if;
 
-      --  and replace the conditional expression by a reference to Cnn.
+      --  and replace the conditional expression by a reference to Cnn
 
       if Present (Then_Actions (N)) or else Present (Else_Actions (N)) then
          Cnn := Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
@@ -2964,8 +3701,7 @@ package body Exp_Ch4 is
 
    procedure Expand_N_Explicit_Dereference (N : Node_Id) is
    begin
-      --  The only processing required is an insertion of an explicit
-      --  dereference call for the checked storage pool case.
+      --  Insert explicit dereference call for the checked storage pool case
 
       Insert_Dereference_Action (Prefix (N));
    end Expand_N_Explicit_Dereference;
@@ -2981,62 +3717,190 @@ package body Exp_Ch4 is
       Rop    : constant Node_Id    := Right_Opnd (N);
       Static : constant Boolean    := Is_OK_Static_Expression (N);
 
+      procedure Substitute_Valid_Check;
+      --  Replaces node N by Lop'Valid. This is done when we have an explicit
+      --  test for the left operand being in range of its subtype.
+
+      ----------------------------
+      -- Substitute_Valid_Check --
+      ----------------------------
+
+      procedure Substitute_Valid_Check is
+      begin
+         Rewrite (N,
+           Make_Attribute_Reference (Loc,
+             Prefix         => Relocate_Node (Lop),
+             Attribute_Name => Name_Valid));
+
+         Analyze_And_Resolve (N, Rtyp);
+
+         Error_Msg_N ("?explicit membership test may be optimized away", N);
+         Error_Msg_N ("\?use ''Valid attribute instead", N);
+         return;
+      end Substitute_Valid_Check;
+
+   --  Start of processing for Expand_N_In
+
    begin
-      --  If we have an explicit range, do a bit of optimization based
-      --  on range analysis (we may be able to kill one or both checks).
+      --  Check case of explicit test for an expression in range of its
+      --  subtype. This is suspicious usage and we replace it with a 'Valid
+      --  test and give a warning.
+
+      if Is_Scalar_Type (Etype (Lop))
+        and then Nkind (Rop) in N_Has_Entity
+        and then Etype (Lop) = Entity (Rop)
+        and then Comes_From_Source (N)
+        and then VM_Target = No_VM
+      then
+         Substitute_Valid_Check;
+         return;
+      end if;
+
+      --  Do validity check on operands
+
+      if Validity_Checks_On and Validity_Check_Operands then
+         Ensure_Valid (Left_Opnd (N));
+         Validity_Check_Range (Right_Opnd (N));
+      end if;
+
+      --  Case of explicit range
 
       if Nkind (Rop) = N_Range then
          declare
-            Lcheck : constant Compare_Result :=
-                       Compile_Time_Compare (Lop, Low_Bound (Rop));
-            Ucheck : constant Compare_Result :=
-                       Compile_Time_Compare (Lop, High_Bound (Rop));
+            Lo : constant Node_Id := Low_Bound (Rop);
+            Hi : constant Node_Id := High_Bound (Rop);
+
+            Ltyp : constant Entity_Id := Etype (Lop);
+
+            Lo_Orig : constant Node_Id := Original_Node (Lo);
+            Hi_Orig : constant Node_Id := Original_Node (Hi);
+
+            Lcheck : constant Compare_Result := Compile_Time_Compare (Lop, Lo);
+            Ucheck : constant Compare_Result := Compile_Time_Compare (Lop, Hi);
+
+            Warn1 : constant Boolean :=
+                      Constant_Condition_Warnings
+                        and then Comes_From_Source (N);
+            --  This must be true for any of the optimization warnings, we
+            --  clearly want to give them only for source with the flag on.
+
+            Warn2 : constant Boolean :=
+                      Warn1
+                        and then Nkind (Original_Node (Rop)) = N_Range
+                        and then Is_Integer_Type (Etype (Lo));
+            --  For the case where only one bound warning is elided, we also
+            --  insist on an explicit range and an integer type. The reason is
+            --  that the use of enumeration ranges including an end point is
+            --  common, as is the use of a subtype name, one of whose bounds
+            --  is the same as the type of the expression.
 
          begin
-            --  If either check is known to fail, replace result
-            --  by False, since the other check does not matter.
-            --  Preserve the static flag for legality checks, because
-            --  we are constant-folding beyond RM 4.9.
+            --  If test is explicit x'first .. x'last, replace by valid check
+
+            if Is_Scalar_Type (Ltyp)
+              and then Nkind (Lo_Orig) = N_Attribute_Reference
+              and then Attribute_Name (Lo_Orig) = Name_First
+              and then Nkind (Prefix (Lo_Orig)) in N_Has_Entity
+              and then Entity (Prefix (Lo_Orig)) = Ltyp
+              and then Nkind (Hi_Orig) = N_Attribute_Reference
+              and then Attribute_Name (Hi_Orig) = Name_Last
+              and then Nkind (Prefix (Hi_Orig)) in N_Has_Entity
+              and then Entity (Prefix (Hi_Orig)) = Ltyp
+              and then Comes_From_Source (N)
+              and then VM_Target = No_VM
+            then
+               Substitute_Valid_Check;
+               return;
+            end if;
+
+            --  If bounds of type are known at compile time, and the end points
+            --  are known at compile time and identical, this is another case
+            --  for substituting a valid test. We only do this for discrete
+            --  types, since it won't arise in practice for float types.
+
+            if Comes_From_Source (N)
+              and then Is_Discrete_Type (Ltyp)
+              and then Compile_Time_Known_Value (Type_High_Bound (Ltyp))
+              and then Compile_Time_Known_Value (Type_Low_Bound  (Ltyp))
+              and then Compile_Time_Known_Value (Lo)
+              and then Compile_Time_Known_Value (Hi)
+              and then Expr_Value (Type_High_Bound (Ltyp)) = Expr_Value (Hi)
+              and then Expr_Value (Type_Low_Bound  (Ltyp)) = Expr_Value (Lo)
+            then
+               Substitute_Valid_Check;
+               return;
+            end if;
+
+            --  If we have an explicit range, do a bit of optimization based
+            --  on range analysis (we may be able to kill one or both checks).
+
+            --  If either check is known to fail, replace result by False since
+            --  the other check does not matter. Preserve the static flag for
+            --  legality checks, because we are constant-folding beyond RM 4.9.
 
             if Lcheck = LT or else Ucheck = GT then
+               if Warn1 then
+                  Error_Msg_N ("?range test optimized away", N);
+                  Error_Msg_N ("\?value is known to be out of range", N);
+               end if;
+
                Rewrite (N,
                  New_Reference_To (Standard_False, Loc));
                Analyze_And_Resolve (N, Rtyp);
                Set_Is_Static_Expression (N, Static);
+
                return;
 
             --  If both checks are known to succeed, replace result
             --  by True, since we know we are in range.
 
             elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
+               if Warn1 then
+                  Error_Msg_N ("?range test optimized away", N);
+                  Error_Msg_N ("\?value is known to be in range", N);
+               end if;
+
                Rewrite (N,
                  New_Reference_To (Standard_True, Loc));
                Analyze_And_Resolve (N, Rtyp);
                Set_Is_Static_Expression (N, Static);
+
                return;
 
-            --  If lower bound check succeeds and upper bound check is
-            --  not known to succeed or fail, then replace the range check
-            --  with a comparison against the upper bound.
+            --  If lower bound check succeeds and upper bound check is not
+            --  known to succeed or fail, then replace the range check with
+            --  a comparison against the upper bound.
 
             elsif Lcheck in Compare_GE then
+               if Warn2 then
+                  Error_Msg_N ("?lower bound test optimized away", Lo);
+                  Error_Msg_N ("\?value is known to be in range", Lo);
+               end if;
+
                Rewrite (N,
                  Make_Op_Le (Loc,
                    Left_Opnd  => Lop,
                    Right_Opnd => High_Bound (Rop)));
                Analyze_And_Resolve (N, Rtyp);
+
                return;
 
-            --  If upper bound check succeeds and lower bound check is
-            --  not known to succeed or fail, then replace the range check
-            --  with a comparison against the lower bound.
+            --  If upper bound check succeeds and lower bound check is not
+            --  known to succeed or fail, then replace the range check with
+            --  a comparison against the lower bound.
 
             elsif Ucheck in Compare_LE then
+               if Warn2 then
+                  Error_Msg_N ("?upper bound test optimized away", Hi);
+                  Error_Msg_N ("\?value is known to be in range", Hi);
+               end if;
+
                Rewrite (N,
                  Make_Op_Ge (Loc,
                    Left_Opnd  => Lop,
                    Right_Opnd => Low_Bound (Rop)));
                Analyze_And_Resolve (N, Rtyp);
+
                return;
             end if;
          end;
@@ -3061,20 +3925,19 @@ package body Exp_Ch4 is
 
             if Is_Tagged_Type (Typ) then
 
-               --  No expansion will be performed when Java_VM, as the
-               --  JVM back end will handle the membership tests directly
-               --  (tags are not explicitly represented in Java objects,
-               --  so the normal tagged membership expansion is not what
-               --  we want).
+               --  No expansion will be performed when VM_Target, as the VM
+               --  back-ends will handle the membership tests directly (tags
+               --  are not explicitly represented in Java objects, so the
+               --  normal tagged membership expansion is not what we want).
 
-               if not Java_VM then
+               if VM_Target = No_VM then
                   Rewrite (N, Tagged_Membership (N));
                   Analyze_And_Resolve (N, Rtyp);
                end if;
 
                return;
 
-            --  If type is scalar type, rewrite as x in t'first .. t'last
+            --  If type is scalar type, rewrite as x in t'first .. t'last.
             --  This reason we do this is that the bounds may have the wrong
             --  type if they come from the original type definition.
 
@@ -3266,6 +4129,15 @@ package body Exp_Ch4 is
          return;
       end if;
 
+      --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
+      --  function, then additional actuals must be passed.
+
+      if Ada_Version >= Ada_05
+        and then Is_Build_In_Place_Function_Call (P)
+      then
+         Make_Build_In_Place_Call_In_Anonymous_Context (P);
+      end if;
+
       --  If the prefix is an access type, then we unconditionally rewrite
       --  if as an explicit deference. This simplifies processing for several
       --  cases, including packed array cases and certain cases in which
@@ -3273,9 +4145,7 @@ package body Exp_Ch4 is
       --  was necessary, but it cleans up the code to do it all the time.
 
       if Is_Access_Type (T) then
-         Rewrite (P,
-           Make_Explicit_Dereference (Sloc (N),
-             Prefix => Relocate_Node (P)));
+         Insert_Explicit_Dereference (P);
          Analyze_And_Resolve (P, Designated_Type (T));
       end if;
 
@@ -3294,7 +4164,7 @@ package body Exp_Ch4 is
       end if;
 
       --  For packed arrays that are not bit-packed (i.e. the case of an array
-      --  with one or more index types with a non-coniguous enumeration type),
+      --  with one or more index types with a non-contiguous enumeration type),
       --  we can always use the normal packed element get circuit.
 
       if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
@@ -3331,8 +4201,8 @@ package body Exp_Ch4 is
             if Nkind (Parnt) = N_Unchecked_Expression then
                null;
 
-            elsif Nkind (Parnt) = N_Object_Renaming_Declaration
-              or else Nkind (Parnt) = N_Procedure_Call_Statement
+            elsif Nkind_In (Parnt, N_Object_Renaming_Declaration,
+                                   N_Procedure_Call_Statement)
               or else (Nkind (Parnt) = N_Parameter_Association
                         and then
                           Nkind (Parent (Parnt)) =  N_Procedure_Call_Statement)
@@ -3372,8 +4242,7 @@ package body Exp_Ch4 is
             then
                return;
 
-            elsif (Nkind (Parnt) = N_Indexed_Component
-                    or else Nkind (Parnt) = N_Selected_Component)
+            elsif Nkind_In (Parnt, N_Indexed_Component, N_Selected_Component)
                and then Prefix (Parnt) = Child
             then
                null;
@@ -3390,7 +4259,6 @@ package body Exp_Ch4 is
             Parnt := Parent (Child);
          end loop;
       end;
-
    end Expand_N_Indexed_Component;
 
    ---------------------
@@ -3401,8 +4269,9 @@ package body Exp_Ch4 is
    --  can be done. This avoids needing to duplicate this expansion code.
 
    procedure Expand_N_Not_In (N : Node_Id) is
-      Loc  : constant Source_Ptr := Sloc (N);
-      Typ  : constant Entity_Id  := Etype (N);
+      Loc : constant Source_Ptr := Sloc (N);
+      Typ : constant Entity_Id  := Etype (N);
+      Cfs : constant Boolean    := Comes_From_Source (N);
 
    begin
       Rewrite (N,
@@ -3411,6 +4280,15 @@ package body Exp_Ch4 is
             Make_In (Loc,
               Left_Opnd  => Left_Opnd (N),
               Right_Opnd => Right_Opnd (N))));
+
+      --  We want this to appear as coming from source if original does (see
+      --  transformations in Expand_N_In).
+
+      Set_Comes_From_Source (N, Cfs);
+      Set_Comes_From_Source (Right_Opnd (N), Cfs);
+
+      --  Now analyze transformed node
+
       Analyze_And_Resolve (N, Typ);
    end Expand_N_Not_In;
 
@@ -3430,7 +4308,7 @@ package body Exp_Ch4 is
       Agg : Node_Id;
 
    begin
-      if Ekind (Typ) = E_Access_Protected_Subprogram_Type then
+      if Is_Access_Protected_Subprogram_Type (Typ) then
          Agg :=
            Make_Aggregate (Loc,
              Expressions => New_List (
@@ -3600,14 +4478,22 @@ package body Exp_Ch4 is
       --  Initialize global variables showing run-time status
 
       if Max_Available_String_Operands < 1 then
+
+         --  See what routines are available and set max operand count
+         --  according to the highest count available in the run-time.
+
          if not RTE_Available (RE_Str_Concat) then
             Max_Available_String_Operands := 0;
+
          elsif not RTE_Available (RE_Str_Concat_3) then
             Max_Available_String_Operands := 2;
+
          elsif not RTE_Available (RE_Str_Concat_4) then
             Max_Available_String_Operands := 3;
+
          elsif not RTE_Available (RE_Str_Concat_5) then
             Max_Available_String_Operands := 4;
+
          else
             Max_Available_String_Operands := 5;
          end if;
@@ -3723,28 +4609,28 @@ package body Exp_Ch4 is
    ------------------------
 
    procedure Expand_N_Op_Divide (N : Node_Id) is
-      Loc  : constant Source_Ptr := Sloc (N);
-      Ltyp : constant Entity_Id  := Etype (Left_Opnd (N));
-      Rtyp : constant Entity_Id  := Etype (Right_Opnd (N));
-      Typ  : Entity_Id           := Etype (N);
+      Loc   : constant Source_Ptr := Sloc (N);
+      Lopnd : constant Node_Id    := Left_Opnd (N);
+      Ropnd : constant Node_Id    := Right_Opnd (N);
+      Ltyp  : constant Entity_Id  := Etype (Lopnd);
+      Rtyp  : constant Entity_Id  := Etype (Ropnd);
+      Typ   : Entity_Id           := Etype (N);
+      Rknow : constant Boolean    := Is_Integer_Type (Typ)
+                                       and then
+                                         Compile_Time_Known_Value (Ropnd);
+      Rval  : Uint;
 
    begin
       Binary_Op_Validity_Checks (N);
 
-      --  Vax_Float is a special case
-
-      if Vax_Float (Typ) then
-         Expand_Vax_Arith (N);
-         return;
+      if Rknow then
+         Rval := Expr_Value (Ropnd);
       end if;
 
       --  N / 1 = N for integer types
 
-      if Is_Integer_Type (Typ)
-        and then Compile_Time_Known_Value (Right_Opnd (N))
-        and then Expr_Value (Right_Opnd (N)) = Uint_1
-      then
-         Rewrite (N, Left_Opnd (N));
+      if Rknow and then Rval = Uint_1 then
+         Rewrite (N, Lopnd);
          return;
       end if;
 
@@ -3752,8 +4638,8 @@ package body Exp_Ch4 is
       --  Is_Power_Of_2_For_Shift is set means that we know that our left
       --  operand is an unsigned integer, as required for this to work.
 
-      if Nkind (Right_Opnd (N)) = N_Op_Expon
-        and then Is_Power_Of_2_For_Shift (Right_Opnd (N))
+      if Nkind (Ropnd) = N_Op_Expon
+        and then Is_Power_Of_2_For_Shift (Ropnd)
 
       --  We cannot do this transformation in configurable run time mode if we
       --  have 64-bit --  integers and long shifts are not available.
@@ -3764,9 +4650,9 @@ package body Exp_Ch4 is
       then
          Rewrite (N,
            Make_Op_Shift_Right (Loc,
-             Left_Opnd  => Left_Opnd (N),
+             Left_Opnd  => Lopnd,
              Right_Opnd =>
-               Convert_To (Standard_Natural, Right_Opnd (Right_Opnd (N)))));
+               Convert_To (Standard_Natural, Right_Opnd (Ropnd))));
          Analyze_And_Resolve (N, Typ);
          return;
       end if;
@@ -3815,31 +4701,48 @@ package body Exp_Ch4 is
       elsif Typ = Universal_Real
         and then Is_Integer_Type (Rtyp)
       then
-         Rewrite (Right_Opnd (N),
-           Convert_To (Universal_Real, Relocate_Node (Right_Opnd (N))));
+         Rewrite (Ropnd,
+           Convert_To (Universal_Real, Relocate_Node (Ropnd)));
 
-         Analyze_And_Resolve (Right_Opnd (N), Universal_Real);
+         Analyze_And_Resolve (Ropnd, Universal_Real);
 
       elsif Typ = Universal_Real
         and then Is_Integer_Type (Ltyp)
       then
-         Rewrite (Left_Opnd (N),
-           Convert_To (Universal_Real, Relocate_Node (Left_Opnd (N))));
+         Rewrite (Lopnd,
+           Convert_To (Universal_Real, Relocate_Node (Lopnd)));
 
-         Analyze_And_Resolve (Left_Opnd (N), Universal_Real);
+         Analyze_And_Resolve (Lopnd, Universal_Real);
 
-      --  Non-fixed point cases, do zero divide and overflow checks
+      --  Non-fixed point cases, do integer zero divide and overflow checks
 
       elsif Is_Integer_Type (Typ) then
          Apply_Divide_Check (N);
 
-         --  Check for 64-bit division available
+         --  Check for 64-bit division available, or long shifts if the divisor
+         --  is a small power of 2 (since such divides will be converted into
+         --  long shifts.
 
          if Esize (Ltyp) > 32
            and then not Support_64_Bit_Divides_On_Target
+           and then
+             (not Rknow
+                or else not Support_Long_Shifts_On_Target
+                or else (Rval /= Uint_2  and then
+                         Rval /= Uint_4  and then
+                         Rval /= Uint_8  and then
+                         Rval /= Uint_16 and then
+                         Rval /= Uint_32 and then
+                         Rval /= Uint_64))
          then
             Error_Msg_CRT ("64-bit division", N);
          end if;
+
+      --  Deal with Vax_Float
+
+      elsif Vax_Float (Typ) then
+         Expand_Vax_Arith (N);
+         return;
       end if;
    end Expand_N_Op_Divide;
 
@@ -3865,7 +4768,7 @@ package body Exp_Ch4 is
       --  inherited.
 
       function Has_Unconstrained_UU_Component (Typ : Node_Id) return Boolean;
-      --  Determines whether a type has a subcompoment of an unconstrained
+      --  Determines whether a type has a subcomponent of an unconstrained
       --  Unchecked_Union subtype. Typ is a record type.
 
       -------------------------
@@ -3900,7 +4803,7 @@ package body Exp_Ch4 is
             begin
                --  Per-object constrained selected components require special
                --  attention. If the enclosing scope of the component is an
-               --  Unchecked_Union, we can not reference its discriminants
+               --  Unchecked_Union, we cannot reference its discriminants
                --  directly. This is why we use the two extra parameters of
                --  the equality function of the enclosing Unchecked_Union.
 
@@ -3921,7 +4824,7 @@ package body Exp_Ch4 is
                --     Obj1 : Enclosing_UU_Type;
                --     Obj2 : Enclosing_UU_Type (1);
 
-               --     . . . Obj1 = Obj2 . . .
+               --     [. . .] Obj1 = Obj2 [. . .]
 
                --     Generated code:
 
@@ -3944,7 +4847,7 @@ package body Exp_Ch4 is
                --     Obj1 : Enclosing_Non_UU_Type;
                --     Obj2 : Enclosing_Non_UU_Type (1);
 
-               --     . . . Obj1 = Obj2 . . .
+               --     ...  Obj1 = Obj2 ...
 
                --     Generated code:
 
@@ -3957,8 +4860,8 @@ package body Exp_Ch4 is
                --  Lhs of equality
 
                if Nkind (Lhs) = N_Selected_Component
-                 and then Has_Per_Object_Constraint (
-                            Entity (Selector_Name (Lhs)))
+                 and then Has_Per_Object_Constraint
+                            (Entity (Selector_Name (Lhs)))
                then
                   --  Enclosing record is an Unchecked_Union, use formal A
 
@@ -3977,11 +4880,11 @@ package body Exp_Ch4 is
                        Make_Selected_Component (Loc,
                          Prefix => Prefix (Lhs),
                          Selector_Name =>
-                           New_Copy (Get_Discriminant_Value (
-                             First_Discriminant (Lhs_Type),
-                             Lhs_Type,
-                             Stored_Constraint (Lhs_Type))));
-
+                           New_Copy
+                             (Get_Discriminant_Value
+                                (First_Discriminant (Lhs_Type),
+                                 Lhs_Type,
+                                 Stored_Constraint (Lhs_Type))));
                   end if;
 
                --  Comment needed here ???
@@ -3990,21 +4893,21 @@ package body Exp_Ch4 is
                   --  Infer the discriminant value
 
                   Lhs_Discr_Val :=
-                    New_Copy (Get_Discriminant_Value (
-                      First_Discriminant (Lhs_Type),
-                      Lhs_Type,
-                      Stored_Constraint (Lhs_Type)));
-
+                    New_Copy
+                      (Get_Discriminant_Value
+                         (First_Discriminant (Lhs_Type),
+                          Lhs_Type,
+                          Stored_Constraint (Lhs_Type)));
                end if;
 
                --  Rhs of equality
 
                if Nkind (Rhs) = N_Selected_Component
-                  and then Has_Per_Object_Constraint (
-                             Entity (Selector_Name (Rhs)))
+                 and then Has_Per_Object_Constraint
+                            (Entity (Selector_Name (Rhs)))
                then
-                  if Is_Unchecked_Union (Scope
-                       (Entity (Selector_Name (Rhs))))
+                  if Is_Unchecked_Union
+                       (Scope (Entity (Selector_Name (Rhs))))
                   then
                      Rhs_Discr_Val :=
                        Make_Identifier (Loc,
@@ -4060,7 +4963,7 @@ package body Exp_Ch4 is
         (Typ : Node_Id) return Boolean
       is
          Tdef  : constant Node_Id :=
-                   Type_Definition (Declaration_Node (Typ));
+                   Type_Definition (Declaration_Node (Base_Type (Typ)));
          Clist : Node_Id;
          Vpart : Node_Id;
 
@@ -4116,14 +5019,13 @@ package body Exp_Ch4 is
                return False;
             end if;
 
+            --  We only need to test one component
+
             declare
                Comp : Node_Id := First (Component_Items (Clist));
 
             begin
                while Present (Comp) loop
-
-                  --  One component is sufficent
-
                   if Component_Is_Unconstrained_UU (Comp) then
                      return True;
                   end if;
@@ -4157,7 +5059,7 @@ package body Exp_Ch4 is
             begin
                while Present (Comp) loop
 
-                  --  One component is sufficent
+                  --  One component is sufficient
 
                   if Component_Is_Unconstrained_UU (Comp) then
                      return True;
@@ -4177,7 +5079,7 @@ package body Exp_Ch4 is
             begin
                while Present (Variant) loop
 
-                  --  One component within a variant is sufficent
+                  --  One component within a variant is sufficient
 
                   if Variant_Is_Unconstrained_UU (Variant) then
                      return True;
@@ -4201,9 +5103,10 @@ package body Exp_Ch4 is
 
       if Ekind (Typl) = E_Private_Type then
          Typl := Underlying_Type (Typl);
-
       elsif Ekind (Typl) = E_Private_Subtype then
          Typl := Underlying_Type (Base_Type (Typl));
+      else
+         null;
       end if;
 
       --  It may happen in error situations that the underlying type is not
@@ -4216,15 +5119,9 @@ package body Exp_Ch4 is
 
       Typl := Base_Type (Typl);
 
-      --  Vax float types
-
-      if Vax_Float (Typl) then
-         Expand_Vax_Comparison (N);
-         return;
-
       --  Boolean types (requiring handling of non-standard case)
 
-      elsif Is_Boolean_Type (Typl) then
+      if Is_Boolean_Type (Typl) then
          Adjust_Condition (Left_Opnd (N));
          Adjust_Condition (Right_Opnd (N));
          Set_Etype (N, Standard_Boolean);
@@ -4234,10 +5131,13 @@ package body Exp_Ch4 is
 
       elsif Is_Array_Type (Typl) then
 
-         --  If we are doing full validity checking, then expand out array
-         --  comparisons to make sure that we check the array elements.
+         --  If we are doing full validity checking, and it is possible for the
+         --  array elements to be invalid then expand out array comparisons to
+         --  make sure that we check the array elements.
 
-         if Validity_Check_Operands then
+         if Validity_Check_Operands
+           and then not Is_Known_Valid (Component_Type (Typl))
+         then
             declare
                Save_Force_Validity_Checks : constant Boolean :=
                                               Force_Validity_Checks;
@@ -4255,17 +5155,25 @@ package body Exp_Ch4 is
                Force_Validity_Checks := Save_Force_Validity_Checks;
             end;
 
-         --  Packed case
+         --  Packed case where both operands are known aligned
 
-         elsif Is_Bit_Packed_Array (Typl) then
+         elsif Is_Bit_Packed_Array (Typl)
+           and then not Is_Possibly_Unaligned_Object (Lhs)
+           and then not Is_Possibly_Unaligned_Object (Rhs)
+         then
             Expand_Packed_Eq (N);
 
-         --  For non-floating-point elementary types, the primitive equality
-         --  always applies, and block-bit comparison is fine. Floating-point
-         --  is an exception because of negative zeroes.
+         --  Where the component type is elementary we can use a block bit
+         --  comparison (if supported on the target) exception in the case
+         --  of floating-point (negative zero issues require element by
+         --  element comparison), and atomic types (where we must be sure
+         --  to load elements independently) and possibly unaligned arrays.
 
          elsif Is_Elementary_Type (Component_Type (Typl))
            and then not Is_Floating_Point_Type (Component_Type (Typl))
+           and then not Is_Atomic (Component_Type (Typl))
+           and then not Is_Possibly_Unaligned_Object (Lhs)
+           and then not Is_Possibly_Unaligned_Object (Rhs)
            and then Support_Composite_Compare_On_Target
          then
             null;
@@ -4294,6 +5202,14 @@ package body Exp_Ch4 is
 
          if Is_Tagged_Type (Typl) then
 
+            --  No need to do anything else compiling under restriction
+            --  No_Dispatching_Calls. During the semantic analysis we
+            --  already notified such violation.
+
+            if Restriction_Active (No_Dispatching_Calls) then
+               return;
+            end if;
+
             --  If this is derived from an untagged private type completed
             --  with a tagged type, it does not have a full view, so we
             --  use the primitive operations of the private type.
@@ -4337,7 +5253,6 @@ package body Exp_Ch4 is
                end if;
 
                Prim := First_Elmt (Primitive_Operations (Typl));
-
                while Present (Prim) loop
                   exit when Chars (Node (Prim)) = Name_Op_Eq
                     and then Etype (First_Formal (Node (Prim))) =
@@ -4405,7 +5320,7 @@ package body Exp_Ch4 is
               (TSS (Root_Type (Typl), TSS_Composite_Equality));
 
          --  Otherwise expand the component by component equality. Note that
-         --  we never use block-bit coparisons for records, because of the
+         --  we never use block-bit comparisons for records, because of the
          --  problems with gaps. The backend will often be able to recombine
          --  the separate comparisons that we generate here.
 
@@ -4420,11 +5335,15 @@ package body Exp_Ch4 is
          end if;
       end if;
 
-      --  If we still have an equality comparison (i.e. it was not rewritten
-      --  in some way), then we can test if result is needed at compile time).
+      --  Test if result is known at compile time
 
-      if Nkind (N) = N_Op_Eq then
-         Rewrite_Comparison (N);
+      Rewrite_Comparison (N);
+
+      --  If we still have comparison for Vax_Float, process it
+
+      if Vax_Float (Typl) and then Nkind (N) in N_Op_Compare  then
+         Expand_Vax_Comparison (N);
+         return;
       end if;
    end Expand_N_Op_Eq;
 
@@ -4652,11 +5571,11 @@ package body Exp_Ch4 is
       --  Signed integer cases, done using either Integer or Long_Long_Integer.
       --  It is not worth having routines for Short_[Short_]Integer, since for
       --  most machines it would not help, and it would generate more code that
-      --  might need certification in the HI-E case.
+      --  might need certification when a certified run time is required.
 
       --  In the integer cases, we have two routines, one for when overflow
-      --  checks are required, and one when they are not required, since
-      --  there is a real gain in ommitting checks on many machines.
+      --  checks are required, and one when they are not required, since there
+      --  is a real gain in omitting checks on many machines.
 
       elsif Rtyp = Base_Type (Standard_Long_Long_Integer)
         or else (Rtyp = Base_Type (Standard_Long_Integer)
@@ -4740,11 +5659,7 @@ package body Exp_Ch4 is
    begin
       Binary_Op_Validity_Checks (N);
 
-      if Vax_Float (Typ1) then
-         Expand_Vax_Comparison (N);
-         return;
-
-      elsif Is_Array_Type (Typ1) then
+      if Is_Array_Type (Typ1) then
          Expand_Array_Comparison (N);
          return;
       end if;
@@ -4757,6 +5672,13 @@ package body Exp_Ch4 is
       end if;
 
       Rewrite_Comparison (N);
+
+      --  If we still have comparison, and Vax_Float type, process it
+
+      if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
+         Expand_Vax_Comparison (N);
+         return;
+      end if;
    end Expand_N_Op_Ge;
 
    --------------------
@@ -4772,11 +5694,7 @@ package body Exp_Ch4 is
    begin
       Binary_Op_Validity_Checks (N);
 
-      if Vax_Float (Typ1) then
-         Expand_Vax_Comparison (N);
-         return;
-
-      elsif Is_Array_Type (Typ1) then
+      if Is_Array_Type (Typ1) then
          Expand_Array_Comparison (N);
          return;
       end if;
@@ -4789,6 +5707,13 @@ package body Exp_Ch4 is
       end if;
 
       Rewrite_Comparison (N);
+
+      --  If we still have comparison, and Vax_Float type, process it
+
+      if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
+         Expand_Vax_Comparison (N);
+         return;
+      end if;
    end Expand_N_Op_Gt;
 
    --------------------
@@ -4804,11 +5729,7 @@ package body Exp_Ch4 is
    begin
       Binary_Op_Validity_Checks (N);
 
-      if Vax_Float (Typ1) then
-         Expand_Vax_Comparison (N);
-         return;
-
-      elsif Is_Array_Type (Typ1) then
+      if Is_Array_Type (Typ1) then
          Expand_Array_Comparison (N);
          return;
       end if;
@@ -4821,6 +5742,13 @@ package body Exp_Ch4 is
       end if;
 
       Rewrite_Comparison (N);
+
+      --  If we still have comparison, and Vax_Float type, process it
+
+      if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
+         Expand_Vax_Comparison (N);
+         return;
+      end if;
    end Expand_N_Op_Le;
 
    --------------------
@@ -4836,11 +5764,7 @@ package body Exp_Ch4 is
    begin
       Binary_Op_Validity_Checks (N);
 
-      if Vax_Float (Typ1) then
-         Expand_Vax_Comparison (N);
-         return;
-
-      elsif Is_Array_Type (Typ1) then
+      if Is_Array_Type (Typ1) then
          Expand_Array_Comparison (N);
          return;
       end if;
@@ -4853,6 +5777,13 @@ package body Exp_Ch4 is
       end if;
 
       Rewrite_Comparison (N);
+
+      --  If we still have comparison, and Vax_Float type, process it
+
+      if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
+         Expand_Vax_Comparison (N);
+         return;
+      end if;
    end Expand_N_Op_Lt;
 
    -----------------------
@@ -4906,6 +5837,8 @@ package body Exp_Ch4 is
       Rhi : Uint;
       ROK : Boolean;
 
+      pragma Warnings (Off, Lhi);
+
    begin
       Binary_Op_Validity_Checks (N);
 
@@ -5057,13 +5990,6 @@ package body Exp_Ch4 is
          end if;
       end if;
 
-      --  Deal with VAX float case
-
-      if Vax_Float (Typ) then
-         Expand_Vax_Arith (N);
-         return;
-      end if;
-
       --  Convert x * 2 ** y to Shift_Left (x, y). Note that the fact that
       --  Is_Power_Of_2_For_Shift is set means that we know that our left
       --  operand is an integer, as required for this to work.
@@ -5174,6 +6100,12 @@ package body Exp_Ch4 is
 
       elsif Is_Signed_Integer_Type (Etype (N)) then
          Apply_Arithmetic_Overflow_Check (N);
+
+      --  Deal with VAX float case
+
+      elsif Vax_Float (Typ) then
+         Expand_Vax_Arith (N);
+         return;
       end if;
    end Expand_N_Op_Multiply;
 
@@ -5181,39 +6113,74 @@ package body Exp_Ch4 is
    -- Expand_N_Op_Ne --
    --------------------
 
-   --  Rewrite node as the negation of an equality operation, and reanalyze.
-   --  The equality to be used is defined in the same scope and has the same
-   --  signature. It must be set explicitly because in an instance it may not
-   --  have the same visibility as in the generic unit.
-
    procedure Expand_N_Op_Ne (N : Node_Id) is
-      Loc : constant Source_Ptr := Sloc (N);
-      Neg : Node_Id;
-      Ne  : constant Entity_Id := Entity (N);
+      Typ : constant Entity_Id := Etype (Left_Opnd (N));
 
    begin
-      Binary_Op_Validity_Checks (N);
+      --  Case of elementary type with standard operator
 
-      Neg :=
-        Make_Op_Not (Loc,
-          Right_Opnd =>
-            Make_Op_Eq (Loc,
-              Left_Opnd =>  Left_Opnd (N),
-              Right_Opnd => Right_Opnd (N)));
-      Set_Paren_Count (Right_Opnd (Neg), 1);
+      if Is_Elementary_Type (Typ)
+        and then Sloc (Entity (N)) = Standard_Location
+      then
+         Binary_Op_Validity_Checks (N);
 
-      if Scope (Ne) /= Standard_Standard then
-         Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
-      end if;
+         --  Boolean types (requiring handling of non-standard case)
 
-      --  For navigation purposes, the inequality is treated as an implicit
-      --  reference to the corresponding equality. Preserve the Comes_From_
-      --  source flag so that the proper Xref entry is generated.
+         if Is_Boolean_Type (Typ) then
+            Adjust_Condition (Left_Opnd (N));
+            Adjust_Condition (Right_Opnd (N));
+            Set_Etype (N, Standard_Boolean);
+            Adjust_Result_Type (N, Typ);
+         end if;
 
-      Preserve_Comes_From_Source (Neg, N);
-      Preserve_Comes_From_Source (Right_Opnd (Neg), N);
-      Rewrite (N, Neg);
-      Analyze_And_Resolve (N, Standard_Boolean);
+         Rewrite_Comparison (N);
+
+         --  If we still have comparison for Vax_Float, process it
+
+         if Vax_Float (Typ) and then Nkind (N) in N_Op_Compare  then
+            Expand_Vax_Comparison (N);
+            return;
+         end if;
+
+      --  For all cases other than elementary types, we rewrite node as the
+      --  negation of an equality operation, and reanalyze. The equality to be
+      --  used is defined in the same scope and has the same signature. This
+      --  signature must be set explicitly since in an instance it may not have
+      --  the same visibility as in the generic unit. This avoids duplicating
+      --  or factoring the complex code for record/array equality tests etc.
+
+      else
+         declare
+            Loc : constant Source_Ptr := Sloc (N);
+            Neg : Node_Id;
+            Ne  : constant Entity_Id := Entity (N);
+
+         begin
+            Binary_Op_Validity_Checks (N);
+
+            Neg :=
+              Make_Op_Not (Loc,
+                Right_Opnd =>
+                  Make_Op_Eq (Loc,
+                    Left_Opnd =>  Left_Opnd (N),
+                    Right_Opnd => Right_Opnd (N)));
+            Set_Paren_Count (Right_Opnd (Neg), 1);
+
+            if Scope (Ne) /= Standard_Standard then
+               Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
+            end if;
+
+            --  For navigation purposes, the inequality is treated as an
+            --  implicit reference to the corresponding equality. Preserve the
+            --  Comes_From_ source flag so that the proper Xref entry is
+            --  generated.
+
+            Preserve_Comes_From_Source (Neg, N);
+            Preserve_Comes_From_Source (Right_Opnd (Neg), N);
+            Rewrite (N, Neg);
+            Analyze_And_Resolve (N, Standard_Boolean);
+         end;
+      end if;
    end Expand_N_Op_Ne;
 
    ---------------------
@@ -5277,9 +6244,13 @@ package body Exp_Ch4 is
          return;
       end if;
 
-      --  Case of array operand. If bit packed, handle it in Exp_Pakd
+      --  Case of array operand. If bit packed with a component size of 1,
+      --  handle it in Exp_Pakd if the operand is known to be aligned.
 
-      if Is_Bit_Packed_Array (Typ) and then Component_Size (Typ) = 1 then
+      if Is_Bit_Packed_Array (Typ)
+        and then Component_Size (Typ) = 1
+        and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
+      then
          Expand_Packed_Not (N);
          return;
       end if;
@@ -5293,19 +6264,18 @@ package body Exp_Ch4 is
       Convert_To_Actual_Subtype (Opnd);
       Arr := Etype (Opnd);
       Ensure_Defined (Arr, N);
+      Silly_Boolean_Array_Not_Test (N, Arr);
 
       if Nkind (Parent (N)) = N_Assignment_Statement then
          if Safe_In_Place_Array_Op (Name (Parent (N)), N, Empty) then
             Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
             return;
 
-         --  Special case the negation of a binary operation.
+         --  Special case the negation of a binary operation
 
-         elsif (Nkind (Opnd) = N_Op_And
-                 or else Nkind (Opnd) = N_Op_Or
-                 or else Nkind (Opnd) = N_Op_Xor)
+         elsif Nkind_In (Opnd, N_Op_And, N_Op_Or, N_Op_Xor)
            and then Safe_In_Place_Array_Op
-             (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
+                      (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
          then
             Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
             return;
@@ -5324,14 +6294,14 @@ package body Exp_Ch4 is
                if N = Op1
                  and then Nkind (Op2) = N_Op_Not
                then
-                  --  (not A) op (not B) can be reduced to a single call.
+                  --  (not A) op (not B) can be reduced to a single call
 
                   return;
 
                elsif N = Op2
                  and then Nkind (Parent (N)) = N_Op_Xor
                then
-                  --  A xor (not B) can also be special-cased.
+                  --  A xor (not B) can also be special-cased
 
                   return;
                end if;
@@ -5384,7 +6354,7 @@ package body Exp_Ch4 is
                 Make_Parameter_Specification (Loc,
                   Defining_Identifier => A,
                   Parameter_Type      => New_Reference_To (Typ, Loc))),
-              Subtype_Mark => New_Reference_To (Typ, Loc)),
+              Result_Definition => New_Reference_To (Typ, Loc)),
 
           Declarations => New_List (
             Make_Object_Declaration (Loc,
@@ -5395,7 +6365,7 @@ package body Exp_Ch4 is
             Make_Handled_Sequence_Of_Statements (Loc,
               Statements => New_List (
                 Loop_Statement,
-                Make_Return_Statement (Loc,
+                Make_Simple_Return_Statement (Loc,
                   Expression =>
                     Make_Identifier (Loc, Chars (B)))))));
 
@@ -5456,6 +6426,8 @@ package body Exp_Ch4 is
       Rhi : Uint;
       ROK : Boolean;
 
+      pragma Warnings (Off, Lhi);
+
    begin
       Binary_Op_Validity_Checks (N);
 
@@ -5585,7 +6557,7 @@ package body Exp_Ch4 is
          return;
       end if;
 
-      --  Arithemtic overflow checks for signed integer/fixed point types
+      --  Arithmetic overflow checks for signed integer/fixed point types
 
       if Is_Signed_Integer_Type (Typ)
         or else Is_Fixed_Point_Type (Typ)
@@ -5733,6 +6705,16 @@ package body Exp_Ch4 is
       Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
 
    begin
+      --  Do validity check if validity checking operands
+
+      if Validity_Checks_On
+        and then Validity_Check_Operands
+      then
+         Ensure_Valid (Operand);
+      end if;
+
+      --  Apply possible constraint check
+
       Apply_Constraint_Check (Operand, Target_Type, No_Sliding => True);
    end Expand_N_Qualified_Expression;
 
@@ -5792,7 +6774,7 @@ package body Exp_Ch4 is
 
       if Do_Discriminant_Check (N) then
 
-         --  Present the discrminant checking function to the backend,
+         --  Present the discriminant checking function to the backend,
          --  so that it can inline the call to the function.
 
          Add_Inlined_Body
@@ -5805,6 +6787,15 @@ package body Exp_Ch4 is
          Generate_Discriminant_Check (N);
       end if;
 
+      --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
+      --  function, then additional actuals must be passed.
+
+      if Ada_Version >= Ada_05
+        and then Is_Build_In_Place_Function_Call (P)
+      then
+         Make_Build_In_Place_Call_In_Anonymous_Context (P);
+      end if;
+
       --  Gigi cannot handle unchecked conversions that are the prefix of a
       --  selected component with discriminants. This must be checked during
       --  expansion, because during analysis the type of the selector is not
@@ -5886,7 +6877,7 @@ package body Exp_Ch4 is
 
                      if
                        Denotes_Discriminant
-                        (Node (Dcon), Check_Protected => True)
+                        (Node (Dcon), Check_Concurrent => True)
                      then
                         exit Discr_Loop;
 
@@ -5898,22 +6889,13 @@ package body Exp_Ch4 is
                      elsif Nkind (Parent (N)) = N_Case_Statement
                        and then Etype (Node (Dcon)) /= Etype (Disc)
                      then
-                        --  RBKD is suspicious of the following code. The
-                        --  call to New_Copy instead of New_Copy_Tree is
-                        --  suspicious, and the call to Analyze instead
-                        --  of Analyze_And_Resolve is also suspicious ???
-
-                        --  Wouldn't it be good enough to do a perfectly
-                        --  normal Analyze_And_Resolve call using the
-                        --  subtype of the discriminant here???
-
                         Rewrite (N,
                           Make_Qualified_Expression (Loc,
                             Subtype_Mark =>
                               New_Occurrence_Of (Etype (Disc), Loc),
                             Expression   =>
-                              New_Copy (Node (Dcon))));
-                        Analyze (N);
+                              New_Copy_Tree (Node (Dcon))));
+                        Analyze_And_Resolve (N, Etype (Disc));
 
                         --  In case that comes out as a static expression,
                         --  reset it (a selected component is never static).
@@ -5922,13 +6904,15 @@ package body Exp_Ch4 is
                         return;
 
                      --  Otherwise we can just copy the constraint, but the
-                     --  result is certainly not static!
-
-                     --  Again the New_Copy here and the failure to even
-                     --  to an analyze call is uneasy ???
+                     --  result is certainly not static! In some cases the
+                     --  discriminant constraint has been analyzed in the
+                     --  context of the original subtype indication, but for
+                     --  itypes the constraint might not have been analyzed
+                     --  yet, and this must be done now.
 
                      else
-                        Rewrite (N, New_Copy (Node (Dcon)));
+                        Rewrite (N, New_Copy_Tree (Node (Dcon)));
+                        Analyze_And_Resolve (N);
                         Set_Is_Static_Expression (N, False);
                         return;
                      end if;
@@ -6023,9 +7007,9 @@ package body Exp_Ch4 is
             --  expression, since these are additional cases that do can
             --  appear on procedure actuals.
 
-            elsif Nkind (Par) = N_Type_Conversion
-              or else Nkind (Par) = N_Parameter_Association
-              or else Nkind (Par) = N_Qualified_Expression
+            elsif Nkind_In (Par, N_Type_Conversion,
+                                 N_Parameter_Association,
+                                 N_Qualified_Expression)
             then
                Par := Parent (Par);
 
@@ -6079,6 +7063,15 @@ package body Exp_Ch4 is
          Analyze_And_Resolve (Pfx, Ptp);
       end if;
 
+      --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
+      --  function, then additional actuals must be passed.
+
+      if Ada_Version >= Ada_05
+        and then Is_Build_In_Place_Function_Call (Pfx)
+      then
+         Make_Build_In_Place_Call_In_Anonymous_Context (Pfx);
+      end if;
+
       --  Range checks are potentially also needed for cases involving
       --  a slice indexed by a subtype indication, but Do_Range_Check
       --  can currently only be set for expressions ???
@@ -6087,6 +7080,20 @@ package body Exp_Ch4 is
         and then (not Is_Entity_Name (Pfx)
                    or else not Index_Checks_Suppressed (Entity (Pfx)))
         and then Nkind (Discrete_Range (N)) /= N_Subtype_Indication
+
+         --  Do not enable range check to nodes associated with the frontend
+         --  expansion of the dispatch table. We first check if Ada.Tags is
+         --  already loaded to avoid the addition of an undesired dependence
+         --  on such run-time unit.
+
+        and then
+          (VM_Target /= No_VM
+            or else not
+             (RTU_Loaded (Ada_Tags)
+               and then Nkind (Prefix (N)) = N_Selected_Component
+               and then Present (Entity (Selector_Name (Prefix (N))))
+               and then Entity (Selector_Name (Prefix (N))) =
+                                  RTE_Record_Component (RE_Prims_Ptr)))
       then
          Enable_Range_Check (Discrete_Range (N));
       end if;
@@ -6098,7 +7105,7 @@ package body Exp_Ch4 is
       --       situation correctly in the assignment statement expansion).
 
       --    2. Prefix of indexed component (the slide is optimized away
-      --       in this case, see the start of Expand_N_Slice.
+      --       in this case, see the start of Expand_N_Slice.)
 
       --    3. Object renaming declaration, since we want the name of
       --       the slice, not the value.
@@ -6108,7 +7115,7 @@ package body Exp_Ch4 is
       --       call itself.
 
       --    5. Prefix of an address attribute (this is an error which
-      --       is caught elsewhere, and the expansion would intefere
+      --       is caught elsewhere, and the expansion would interfere
       --       with generating the error message).
 
       if not Is_Packed (Typ) then
@@ -6178,7 +7185,7 @@ package body Exp_Ch4 is
          Cons : List_Id;
 
       begin
-         --  Nothing to do if no change of representation
+         --  Nothing else to do if no change of representation
 
          if Same_Representation (Operand_Type, Target_Type) then
             return;
@@ -6353,8 +7360,8 @@ package body Exp_Ch4 is
          --  then we do not trust it to be in range (might be infinite)
 
          declare
-            S_Lo : constant Node_Id   := Type_Low_Bound (Xtyp);
-            S_Hi : constant Node_Id   := Type_High_Bound (Xtyp);
+            S_Lo : constant Node_Id := Type_Low_Bound (Xtyp);
+            S_Hi : constant Node_Id := Type_High_Bound (Xtyp);
 
          begin
             if (not Is_Floating_Point_Type (Xtyp)
@@ -6406,9 +7413,9 @@ package body Exp_Ch4 is
            (Subtype_Mark (Conv), New_Occurrence_Of (Btyp, Loc));
          Set_Etype (Conv, Btyp);
 
-         --  Enable overflow except in the case of integer to float
-         --  conversions, where it is never required, since we can
-         --  never have overflow in this case.
+         --  Enable overflow except for case of integer to float conversions,
+         --  where it is never required, since we can never have overflow in
+         --  this case.
 
          if not Is_Integer_Type (Etype (Operand)) then
             Enable_Overflow_Check (Conv);
@@ -6461,13 +7468,6 @@ package body Exp_Ch4 is
          return;
       end if;
 
-      --  Deal with Vax floating-point cases
-
-      if Vax_Float (Operand_Type) or else Vax_Float (Target_Type) then
-         Expand_Vax_Conversion (N);
-         return;
-      end if;
-
       --  Nothing to do if this is the second argument of read. This
       --  is a "backwards" conversion that will be handled by the
       --  specialized code in attribute processing.
@@ -6481,6 +7481,14 @@ package body Exp_Ch4 is
 
       --  Here if we may need to expand conversion
 
+      --  Do validity check if validity checking operands
+
+      if Validity_Checks_On
+        and then Validity_Check_Operands
+      then
+         Ensure_Valid (Operand);
+      end if;
+
       --  Special case of converting from non-standard boolean type
 
       if Is_Boolean_Type (Operand_Type)
@@ -6495,13 +7503,23 @@ package body Exp_Ch4 is
 
       if Is_Access_Type (Target_Type) then
 
-         --  Apply an accessibility check if the operand is an
-         --  access parameter. Note that other checks may still
-         --  need to be applied below (such as tagged type checks).
+         --  Apply an accessibility check when the conversion operand is an
+         --  access parameter (or a renaming thereof), unless conversion was
+         --  expanded from an unchecked or unrestricted access attribute. Note
+         --  that other checks may still need to be applied below (such as
+         --  tagged type checks).
 
          if Is_Entity_Name (Operand)
-           and then Ekind (Entity (Operand)) in Formal_Kind
+           and then
+             (Is_Formal (Entity (Operand))
+               or else
+                 (Present (Renamed_Object (Entity (Operand)))
+                   and then Is_Entity_Name (Renamed_Object (Entity (Operand)))
+                   and then Is_Formal
+                              (Entity (Renamed_Object (Entity (Operand))))))
            and then Ekind (Etype (Operand)) = E_Anonymous_Access_Type
+           and then (Nkind (Original_Node (N)) /= N_Attribute_Reference
+                      or else Attribute_Name (Original_Node (N)) = Name_Access)
          then
             Apply_Accessibility_Check (Operand, Target_Type);
 
@@ -6564,7 +7582,7 @@ package body Exp_Ch4 is
          --  Do not do any expansion in the access type case if the
          --  parent is a renaming, since this is an error situation
          --  which will be caught by Sem_Ch8, and the expansion can
-         --  intefere with this error check.
+         --  interfere with this error check.
 
          if Is_Access_Type (Target_Type)
            and then Is_Renamed_Object (N)
@@ -6572,7 +7590,7 @@ package body Exp_Ch4 is
             return;
          end if;
 
-         --  Oherwise, proceed with processing tagged conversion
+         --  Otherwise, proceed with processing tagged conversion
 
          declare
             Actual_Operand_Type : Entity_Id;
@@ -6590,6 +7608,13 @@ package body Exp_Ch4 is
                Actual_Target_Type  := Target_Type;
             end if;
 
+            --  Ada 2005 (AI-251): Handle interface type conversion
+
+            if Is_Interface (Actual_Operand_Type) then
+               Expand_Interface_Conversion (N, Is_Static => False);
+               return;
+            end if;
+
             if Is_Class_Wide_Type (Actual_Operand_Type)
               and then Root_Type (Actual_Operand_Type) /=  Actual_Target_Type
               and then Is_Ancestor
@@ -6731,42 +7756,26 @@ package body Exp_Ch4 is
             or else
           (Is_Fixed_Point_Type (Target_Type) and then Conversion_OK (N)))
       then
-         --  Special processing required if the conversion is the expression
-         --  of a Truncation attribute reference. In this case we replace:
-
-         --     ityp (ftyp'Truncation (x))
-
-         --  by
-
-         --     ityp (x)
-
-         --  with the Float_Truncate flag set. This is clearly more efficient.
-
-         if Nkind (Operand) = N_Attribute_Reference
-           and then Attribute_Name (Operand) = Name_Truncation
-         then
-            Rewrite (Operand,
-              Relocate_Node (First (Expressions (Operand))));
-            Set_Float_Truncate (N, True);
-         end if;
-
          --  One more check here, gcc is still not able to do conversions of
          --  this type with proper overflow checking, and so gigi is doing an
          --  approximation of what is required by doing floating-point compares
          --  with the end-point. But that can lose precision in some cases, and
-         --  give a wrong result. Converting the operand to Long_Long_Float is
+         --  give a wrong result. Converting the operand to Universal_Real is
          --  helpful, but still does not catch all cases with 64-bit integers
-         --  on targets with only 64-bit floats ???
+         --  on targets with only 64-bit floats
+
+         --  The above comment seems obsoleted by Apply_Float_Conversion_Check
+         --  Can this code be removed ???
 
          if Do_Range_Check (Operand) then
             Rewrite (Operand,
               Make_Type_Conversion (Loc,
                 Subtype_Mark =>
-                  New_Occurrence_Of (Standard_Long_Long_Float, Loc),
+                  New_Occurrence_Of (Universal_Real, Loc),
                 Expression =>
                   Relocate_Node (Operand)));
 
-            Set_Etype (Operand, Standard_Long_Long_Float);
+            Set_Etype (Operand, Universal_Real);
             Enable_Range_Check (Operand);
             Set_Do_Range_Check (Expression (Operand), False);
          end if;
@@ -6859,11 +7868,6 @@ package body Exp_Ch4 is
 
       elsif Is_Floating_Point_Type (Target_Type) then
          Real_Range_Check;
-
-      --  The remaining cases require no front end processing
-
-      else
-         null;
       end if;
 
       --  At this stage, either the conversion node has been transformed
@@ -6878,7 +7882,9 @@ package body Exp_Ch4 is
       --    only if Conversion_OK is set, i.e. if the fixed-point values
       --    are to be treated as integers.
 
-      --  No other conversions should be passed to Gigi.
+      --  No other conversions should be passed to Gigi
+
+      --  Check: are these rules stated in sinfo??? if so, why restate here???
 
       --  The only remaining step is to generate a range check if we still
       --  have a type conversion at this stage and Do_Range_Check is set.
@@ -6936,6 +7942,16 @@ package body Exp_Ch4 is
             end if;
          end;
       end if;
+
+      --  Final step, if the result is a type conversion involving Vax_Float
+      --  types, then it is subject for further special processing.
+
+      if Nkind (N) = N_Type_Conversion
+        and then (Vax_Float (Operand_Type) or else Vax_Float (Target_Type))
+      then
+         Expand_Vax_Conversion (N);
+         return;
+      end if;
    end Expand_N_Type_Conversion;
 
    -----------------------------------
@@ -6978,8 +7994,14 @@ package body Exp_Ch4 is
       --  flag is set, since then the value may be outside the expected range.
       --  This happens in the Normalize_Scalars case.
 
+      --  We also skip this if either the target or operand type is biased
+      --  because in this case, the unchecked conversion is supposed to
+      --  preserve the bit pattern, not the integer value.
+
       if Is_Integer_Type (Target_Type)
+        and then not Has_Biased_Representation (Target_Type)
         and then Is_Integer_Type (Operand_Type)
+        and then not Has_Biased_Representation (Operand_Type)
         and then Compile_Time_Known_Value (Operand)
         and then not Kill_Range_Check (N)
       then
@@ -7088,6 +8110,9 @@ package body Exp_Ch4 is
          then
             return Suitable_Element (Next_Entity (C));
 
+         elsif Is_Interface (Etype (C)) then
+            return Suitable_Element (Next_Entity (C));
+
          else
             return C;
          end if;
@@ -7113,6 +8138,7 @@ package body Exp_Ch4 is
          declare
             New_Lhs : Node_Id;
             New_Rhs : Node_Id;
+            Check   : Node_Id;
 
          begin
             if First_Time then
@@ -7124,20 +8150,31 @@ package body Exp_Ch4 is
                New_Rhs := New_Copy_Tree (Rhs);
             end if;
 
-            Result :=
-              Make_And_Then (Loc,
-                Left_Opnd  => Result,
-                Right_Opnd =>
-                  Expand_Composite_Equality (Nod, Etype (C),
-                    Lhs =>
-                      Make_Selected_Component (Loc,
-                        Prefix => New_Lhs,
-                        Selector_Name => New_Reference_To (C, Loc)),
-                    Rhs =>
-                      Make_Selected_Component (Loc,
-                        Prefix => New_Rhs,
-                        Selector_Name => New_Reference_To (C, Loc)),
-                    Bodies => Bodies));
+            Check :=
+              Expand_Composite_Equality (Nod, Etype (C),
+               Lhs =>
+                 Make_Selected_Component (Loc,
+                   Prefix => New_Lhs,
+                   Selector_Name => New_Reference_To (C, Loc)),
+               Rhs =>
+                 Make_Selected_Component (Loc,
+                   Prefix => New_Rhs,
+                   Selector_Name => New_Reference_To (C, Loc)),
+               Bodies => Bodies);
+
+            --  If some (sub)component is an unchecked_union, the whole
+            --  operation will raise program error.
+
+            if Nkind (Check) = N_Raise_Program_Error then
+               Result := Check;
+               Set_Etype (Result, Standard_Boolean);
+               exit;
+            else
+               Result :=
+                 Make_And_Then (Loc,
+                   Left_Opnd  => Result,
+                   Right_Opnd => Check);
+            end if;
          end;
 
          C := Suitable_Element (Next_Entity (C));
@@ -7188,22 +8225,28 @@ package body Exp_Ch4 is
       Loc : constant Source_Ptr := Sloc (N);
 
       Owner : Entity_Id := PtrT;
-      --  The entity whose finalisation list must be used to attach the
+      --  The entity whose finalization list must be used to attach the
       --  allocated object.
 
    begin
       if Ekind (PtrT) = E_Anonymous_Access_Type then
+
+         --  If the context is an access parameter, we need to create a
+         --  non-anonymous access type in order to have a usable final list,
+         --  because there is otherwise no pool to which the allocated object
+         --  can belong. We create both the type and the finalization chain
+         --  here, because freezing an internal type does not create such a
+         --  chain. The Final_Chain that is thus created is shared by the
+         --  access parameter. The access type is tested against the result
+         --  type of the function to exclude allocators whose type is an
+         --  anonymous access result type.
+
          if Nkind (Associated_Node_For_Itype (PtrT))
               in N_Subprogram_Specification
+           and then
+             PtrT /=
+               Etype (Defining_Unit_Name (Associated_Node_For_Itype (PtrT)))
          then
-            --  If the context is an access parameter, we need to create
-            --  a non-anonymous access type in order to have a usable
-            --  final list, because there is otherwise no pool to which
-            --  the allocated object can belong. We create both the type
-            --  and the finalization chain here, because freezing an
-            --  internal type does not create such a chain. The Final_Chain
-            --  that is thus created is shared by the access parameter.
-
             Owner := Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
             Insert_Action (N,
               Make_Full_Type_Declaration (Loc,
@@ -7216,11 +8259,25 @@ package body Exp_Ch4 is
             Build_Final_List (N, Owner);
             Set_Associated_Final_Chain (PtrT, Associated_Final_Chain (Owner));
 
-         else
-            --  Case of an access discriminant, or (Ada 2005) of
-            --  an anonymous access component: find the final list
-            --  associated with the scope of the type.
+         --  Ada 2005 (AI-318-02): If the context is a return object
+         --  declaration, then the anonymous return subtype is defined to have
+         --  the same accessibility level as that of the function's result
+         --  subtype, which means that we want the scope where the function is
+         --  declared.
+
+         elsif Nkind (Associated_Node_For_Itype (PtrT)) = N_Object_Declaration
+           and then Ekind (Scope (PtrT)) = E_Return_Statement
+         then
+            Owner := Scope (Return_Applies_To (Scope (PtrT)));
 
+         --  Case of an access discriminant, or (Ada 2005), of an anonymous
+         --  access component or anonymous access function result: find the
+         --  final list associated with the scope of the type. (In the
+         --  anonymous access component kind, a list controller will have
+         --  been allocated when freezing the record type, and PtrT has an
+         --  Associated_Final_Chain attribute designating it.)
+
+         elsif No (Associated_Final_Chain (PtrT)) then
             Owner := Scope (PtrT);
          end if;
       end if;
@@ -7260,13 +8317,10 @@ package body Exp_Ch4 is
    --  Start of processing for Has_Inferable_Discriminants
 
    begin
-      --  For identifiers and indexed components, it is sufficent to have a
+      --  For identifiers and indexed components, it is sufficient to have a
       --  constrained Unchecked_Union nominal subtype.
 
-      if Nkind (N) = N_Identifier
-           or else
-         Nkind (N) = N_Indexed_Component
-      then
+      if Nkind_In (N, N_Identifier, N_Indexed_Component) then
          return Is_Unchecked_Union (Base_Type (Etype (N)))
                   and then
                 Is_Constrained (Etype (N));
@@ -7416,17 +8470,17 @@ package body Exp_Ch4 is
    --    type elem is  (<>);
    --    type index is (<>);
    --    type a is array (index range <>) of elem;
-   --
+
    --  function Gnnn (X : a; Y: a) return boolean is
    --    J : index := Y'first;
-   --
+
    --  begin
    --    if X'length = 0 then
    --       return false;
-   --
+
    --    elsif Y'length = 0 then
    --       return true;
-   --
+
    --    else
    --      for I in X'range loop
    --        if X (I) = Y (J) then
@@ -7435,12 +8489,12 @@ package body Exp_Ch4 is
    --          else
    --            J := index'succ (J);
    --          end if;
-   --
+
    --        else
    --           return X (I) > Y (J);
    --        end if;
    --      end loop;
-   --
+
    --      return X'length > Y'length;
    --    end if;
    --  end Gnnn;
@@ -7526,7 +8580,7 @@ package body Exp_Ch4 is
           Then_Statements => New_List (Inner_If),
 
           Else_Statements => New_List (
-            Make_Return_Statement (Loc,
+            Make_Simple_Return_Statement (Loc,
               Expression =>
                 Make_Op_Gt (Loc,
                   Left_Opnd =>
@@ -7597,7 +8651,7 @@ package body Exp_Ch4 is
 
           Then_Statements =>
             New_List (
-              Make_Return_Statement (Loc,
+              Make_Simple_Return_Statement (Loc,
                 Expression => New_Reference_To (Standard_False, Loc))),
 
           Elsif_Parts => New_List (
@@ -7613,12 +8667,12 @@ package body Exp_Ch4 is
 
               Then_Statements =>
                 New_List (
-                  Make_Return_Statement (Loc,
+                  Make_Simple_Return_Statement (Loc,
                      Expression => New_Reference_To (Standard_True, Loc))))),
 
           Else_Statements => New_List (
             Loop_Statement,
-            Make_Return_Statement (Loc,
+            Make_Simple_Return_Statement (Loc,
               Expression => Final_Expr)));
 
       --  (X : a; Y: a)
@@ -7646,7 +8700,7 @@ package body Exp_Ch4 is
             Make_Function_Specification (Loc,
               Defining_Unit_Name       => Func_Name,
               Parameter_Specifications => Formals,
-              Subtype_Mark => New_Reference_To (Standard_Boolean, Loc)),
+              Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
 
           Declarations => New_List (
             Make_Object_Declaration (Loc,
@@ -7662,7 +8716,6 @@ package body Exp_Ch4 is
               Statements => New_List (If_Stat)));
 
       return Func_Body;
-
    end Make_Array_Comparison_Op;
 
    ---------------------------
@@ -7777,7 +8830,7 @@ package body Exp_Ch4 is
             Make_Function_Specification (Loc,
               Defining_Unit_Name       => Func_Name,
               Parameter_Specifications => Formals,
-              Subtype_Mark             => New_Reference_To (Typ, Loc)),
+              Result_Definition        => New_Reference_To (Typ, Loc)),
 
           Declarations => New_List (
             Make_Object_Declaration (Loc,
@@ -7788,7 +8841,7 @@ package body Exp_Ch4 is
             Make_Handled_Sequence_Of_Statements (Loc,
               Statements => New_List (
                 Loop_Statement,
-                Make_Return_Statement (Loc,
+                Make_Simple_Return_Statement (Loc,
                   Expression => New_Reference_To (C, Loc)))));
 
       return Func_Body;
@@ -7799,55 +8852,92 @@ package body Exp_Ch4 is
    ------------------------
 
    procedure Rewrite_Comparison (N : Node_Id) is
-      Typ : constant Entity_Id := Etype (N);
-      Op1 : constant Node_Id   := Left_Opnd (N);
-      Op2 : constant Node_Id   := Right_Opnd (N);
+   begin
+      if Nkind (N) = N_Type_Conversion then
+         Rewrite_Comparison (Expression (N));
+         return;
 
-      Res : constant Compare_Result := Compile_Time_Compare (Op1, Op2);
-      --  Res indicates if compare outcome can be determined at compile time
+      elsif Nkind (N) not in N_Op_Compare then
+         return;
+      end if;
 
-      True_Result  : Boolean;
-      False_Result : Boolean;
+      declare
+         Typ : constant Entity_Id := Etype (N);
+         Op1 : constant Node_Id   := Left_Opnd (N);
+         Op2 : constant Node_Id   := Right_Opnd (N);
 
-   begin
-      case N_Op_Compare (Nkind (N)) is
-         when N_Op_Eq =>
-            True_Result  := Res = EQ;
-            False_Result := Res = LT or else Res = GT or else Res = NE;
-
-         when N_Op_Ge =>
-            True_Result  := Res in Compare_GE;
-            False_Result := Res = LT;
-
-         when N_Op_Gt =>
-            True_Result  := Res = GT;
-            False_Result := Res in Compare_LE;
-
-         when N_Op_Lt =>
-            True_Result  := Res = LT;
-            False_Result := Res in Compare_GE;
-
-         when N_Op_Le =>
-            True_Result  := Res in Compare_LE;
-            False_Result := Res = GT;
-
-         when N_Op_Ne =>
-            True_Result  := Res = NE;
-            False_Result := Res = LT or else Res = GT or else Res = EQ;
-      end case;
+         Res : constant Compare_Result := Compile_Time_Compare (Op1, Op2);
+         --  Res indicates if compare outcome can be compile time determined
 
-      if True_Result then
-         Rewrite (N,
-           Convert_To (Typ, New_Occurrence_Of (Standard_True, Sloc (N))));
-         Analyze_And_Resolve (N, Typ);
-         Warn_On_Known_Condition (N);
+         True_Result  : Boolean;
+         False_Result : Boolean;
 
-      elsif False_Result then
-         Rewrite (N,
-           Convert_To (Typ, New_Occurrence_Of (Standard_False, Sloc (N))));
-         Analyze_And_Resolve (N, Typ);
-         Warn_On_Known_Condition (N);
-      end if;
+      begin
+         case N_Op_Compare (Nkind (N)) is
+            when N_Op_Eq =>
+               True_Result  := Res = EQ;
+               False_Result := Res = LT or else Res = GT or else Res = NE;
+
+            when N_Op_Ge =>
+               True_Result  := Res in Compare_GE;
+               False_Result := Res = LT;
+
+               if Res = LE
+                 and then Constant_Condition_Warnings
+                 and then Comes_From_Source (Original_Node (N))
+                 and then Nkind (Original_Node (N)) = N_Op_Ge
+                 and then not In_Instance
+                 and then Is_Integer_Type (Etype (Left_Opnd (N)))
+                 and then not Has_Warnings_Off (Etype (Left_Opnd (N)))
+               then
+                  Error_Msg_N
+                    ("can never be greater than, could replace by ""'=""?", N);
+               end if;
+
+            when N_Op_Gt =>
+               True_Result  := Res = GT;
+               False_Result := Res in Compare_LE;
+
+            when N_Op_Lt =>
+               True_Result  := Res = LT;
+               False_Result := Res in Compare_GE;
+
+            when N_Op_Le =>
+               True_Result  := Res in Compare_LE;
+               False_Result := Res = GT;
+
+               if Res = GE
+                 and then Constant_Condition_Warnings
+                 and then Comes_From_Source (Original_Node (N))
+                 and then Nkind (Original_Node (N)) = N_Op_Le
+                 and then not In_Instance
+                 and then Is_Integer_Type (Etype (Left_Opnd (N)))
+                 and then not Has_Warnings_Off (Etype (Left_Opnd (N)))
+               then
+                  Error_Msg_N
+                    ("can never be less than, could replace by ""'=""?", N);
+               end if;
+
+            when N_Op_Ne =>
+               True_Result  := Res = NE or else Res = GT or else Res = LT;
+               False_Result := Res = EQ;
+         end case;
+
+         if True_Result then
+            Rewrite (N,
+              Convert_To (Typ,
+                New_Occurrence_Of (Standard_True, Sloc (N))));
+            Analyze_And_Resolve (N, Typ);
+            Warn_On_Known_Condition (N);
+
+         elsif False_Result then
+            Rewrite (N,
+              Convert_To (Typ,
+                New_Occurrence_Of (Standard_False, Sloc (N))));
+            Analyze_And_Resolve (N, Typ);
+            Warn_On_Known_Condition (N);
+         end if;
+      end;
    end Rewrite_Comparison;
 
    ----------------------------
@@ -7867,7 +8957,7 @@ package body Exp_Ch4 is
       --  is safe. The operand can be empty in the case of negation.
 
       function Is_Unaliased (N : Node_Id) return Boolean;
-      --  Check that N is a stand-alone entity.
+      --  Check that N is a stand-alone entity
 
       ------------------
       -- Is_Unaliased --
@@ -7893,9 +8983,7 @@ package body Exp_Ch4 is
          elsif Is_Entity_Name (Op) then
             return Is_Unaliased (Op);
 
-         elsif Nkind (Op) = N_Indexed_Component
-           or else Nkind (Op) = N_Selected_Component
-         then
+         elsif Nkind_In (Op, N_Indexed_Component, N_Selected_Component) then
             return Is_Unaliased (Prefix (Op));
 
          elsif Nkind (Op) = N_Slice then
@@ -7921,9 +9009,9 @@ package body Exp_Ch4 is
       if Component_Size (Etype (Lhs)) /= System_Storage_Unit then
          return False;
 
-      --  Cannot do in place stuff on Java_VM since cannot pass addresses
+      --  Cannot do in place stuff on VM_Target since cannot pass addresses
 
-      elsif Java_VM then
+      elsif VM_Target /= No_VM then
          return False;
 
       --  Cannot do in place stuff if non-standard Boolean representation
@@ -7956,6 +9044,11 @@ package body Exp_Ch4 is
    --  is usually implemented by looking in the ancestor tables contained in
    --  the dispatch table pointed by Left_Expr.Tag for Typ'Tag
 
+   --  Ada 2005 (AI-251): If it is a class-wide interface type we use the RT
+   --  function IW_Membership which is usually implemented by looking in the
+   --  table of abstract interface types plus the ancestor table contained in
+   --  the dispatch table pointed by Left_Expr.Tag for Typ'Tag
+
    function Tagged_Membership (N : Node_Id) return Node_Id is
       Left  : constant Node_Id    := Left_Opnd  (N);
       Right : constant Node_Id    := Right_Opnd (N);
@@ -7976,24 +9069,103 @@ package body Exp_Ch4 is
       Obj_Tag :=
         Make_Selected_Component (Loc,
           Prefix        => Relocate_Node (Left),
-          Selector_Name => New_Reference_To (Tag_Component (Left_Type), Loc));
+          Selector_Name =>
+            New_Reference_To (First_Tag_Component (Left_Type), Loc));
 
       if Is_Class_Wide_Type (Right_Type) then
-         return
-           Make_DT_Access_Action (Left_Type,
-             Action => CW_Membership,
-             Args   => New_List (
-               Obj_Tag,
-               New_Reference_To (
-                 Access_Disp_Table (Root_Type (Right_Type)), Loc)));
+
+         --  No need to issue a run-time check if we statically know that the
+         --  result of this membership test is always true. For example,
+         --  considering the following declarations:
+
+         --    type Iface is interface;
+         --    type T     is tagged null record;
+         --    type DT    is new T and Iface with null record;
+
+         --    Obj1 : T;
+         --    Obj2 : DT;
+
+         --  These membership tests are always true:
+
+         --    Obj1 in T'Class
+         --    Obj2 in T'Class;
+         --    Obj2 in Iface'Class;
+
+         --  We do not need to handle cases where the membership is illegal.
+         --  For example:
+
+         --    Obj1 in DT'Class;     --  Compile time error
+         --    Obj1 in Iface'Class;  --  Compile time error
+
+         if not Is_Class_Wide_Type (Left_Type)
+           and then (Is_Parent (Etype (Right_Type), Left_Type)
+                       or else (Is_Interface (Etype (Right_Type))
+                                 and then Interface_Present_In_Ancestor
+                                           (Typ   => Left_Type,
+                                            Iface => Etype (Right_Type))))
+         then
+            return New_Reference_To (Standard_True, Loc);
+         end if;
+
+         --  Ada 2005 (AI-251): Class-wide applied to interfaces
+
+         if Is_Interface (Etype (Class_Wide_Type (Right_Type)))
+
+            --   Support to: "Iface_CW_Typ in Typ'Class"
+
+           or else Is_Interface (Left_Type)
+         then
+            --  Issue error if IW_Membership operation not available in a
+            --  configurable run time setting.
+
+            if not RTE_Available (RE_IW_Membership) then
+               Error_Msg_CRT
+                 ("dynamic membership test on interface types", N);
+               return Empty;
+            end if;
+
+            return
+              Make_Function_Call (Loc,
+                 Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
+                 Parameter_Associations => New_List (
+                   Make_Attribute_Reference (Loc,
+                     Prefix => Obj_Tag,
+                     Attribute_Name => Name_Address),
+                   New_Reference_To (
+                     Node (First_Elmt
+                            (Access_Disp_Table (Root_Type (Right_Type)))),
+                     Loc)));
+
+         --  Ada 95: Normal case
+
+         else
+            return
+              Build_CW_Membership (Loc,
+                Obj_Tag_Node => Obj_Tag,
+                Typ_Tag_Node =>
+                   New_Reference_To (
+                     Node (First_Elmt
+                            (Access_Disp_Table (Root_Type (Right_Type)))),
+                     Loc));
+         end if;
+
+      --  Right_Type is not a class-wide type
+
       else
-         return
-           Make_Op_Eq (Loc,
-           Left_Opnd  => Obj_Tag,
-           Right_Opnd =>
-             New_Reference_To (Access_Disp_Table (Right_Type), Loc));
-      end if;
+         --  No need to check the tag of the object if Right_Typ is abstract
+
+         if Is_Abstract_Type (Right_Type) then
+            return New_Reference_To (Standard_False, Loc);
 
+         else
+            return
+              Make_Op_Eq (Loc,
+                Left_Opnd  => Obj_Tag,
+                Right_Opnd =>
+                  New_Reference_To
+                    (Node (First_Elmt (Access_Disp_Table (Right_Type))), Loc));
+         end if;
+      end if;
    end Tagged_Membership;
 
    ------------------------------