OSDN Git Service

2009-10-19 Andreas Krebbel <Andreas.Krebbel@de.ibm.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch5.adb
index d95634f..1f6806b 100644 (file)
@@ -6,18 +6,17 @@
 --                                                                          --
 --                                 B o d y                                  --
 --                                                                          --
---          Copyright (C) 1992-2006, Free Software Foundation, Inc.         --
+--          Copyright (C) 1992-2009, Free Software Foundation, Inc.         --
 --                                                                          --
 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
 -- terms of the  GNU General Public License as published  by the Free Soft- --
--- ware  Foundation;  either version 2,  or (at your option) any later ver- --
+-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
 -- for  more details.  You should have  received  a copy of the GNU General --
--- Public License  distributed with GNAT;  see file COPYING.  If not, write --
--- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
--- Boston, MA 02110-1301, USA.                                              --
+-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
+-- http://www.gnu.org/licenses for a complete copy of the license.          --
 --                                                                          --
 -- GNAT was originally developed  by the GNAT team at  New York University. --
 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
@@ -26,7 +25,6 @@
 
 with Atree;    use Atree;
 with Checks;   use Checks;
-with Debug;    use Debug;
 with Einfo;    use Einfo;
 with Errout;   use Errout;
 with Expander; use Expander;
@@ -34,11 +32,13 @@ with Exp_Util; use Exp_Util;
 with Freeze;   use Freeze;
 with Lib;      use Lib;
 with Lib.Xref; use Lib.Xref;
+with Namet;    use Namet;
 with Nlists;   use Nlists;
 with Nmake;    use Nmake;
 with Opt;      use Opt;
 with Rtsfind;  use Rtsfind;
 with Sem;      use Sem;
+with Sem_Aux;  use Sem_Aux;
 with Sem_Case; use Sem_Case;
 with Sem_Ch3;  use Sem_Ch3;
 with Sem_Ch8;  use Sem_Ch8;
@@ -46,6 +46,7 @@ with Sem_Disp; use Sem_Disp;
 with Sem_Elab; use Sem_Elab;
 with Sem_Eval; use Sem_Eval;
 with Sem_Res;  use Sem_Res;
+with Sem_SCIL; use Sem_SCIL;
 with Sem_Type; use Sem_Type;
 with Sem_Util; use Sem_Util;
 with Sem_Warn; use Sem_Warn;
@@ -60,15 +61,15 @@ package body Sem_Ch5 is
 
    Unblocked_Exit_Count : Nat := 0;
    --  This variable is used when processing if statements, case statements,
-   --  and block statements. It counts the number of exit points that are
-   --  not blocked by unconditional transfer instructions: for IF and CASE,
-   --  these are the branches of the conditional; for a block, they are the
-   --  statement sequence of the block, and the statement sequences of any
-   --  exception handlers that are part of the block. When processing is
-   --  complete, if this count is zero, it means that control cannot fall
-   --  through the IF, CASE or block statement. This is used for the
-   --  generation of warning messages. This variable is recursively saved
-   --  on entry to processing the construct, and restored on exit.
+   --  and block statements. It counts the number of exit points that are not
+   --  blocked by unconditional transfer instructions: for IF and CASE, these
+   --  are the branches of the conditional; for a block, they are the statement
+   --  sequence of the block, and the statement sequences of any exception
+   --  handlers that are part of the block. When processing is complete, if
+   --  this count is zero, it means that control cannot fall through the IF,
+   --  CASE or block statement. This is used for the generation of warning
+   --  messages. This variable is recursively saved on entry to processing the
+   --  construct, and restored on exit.
 
    -----------------------
    -- Local Subprograms --
@@ -88,8 +89,8 @@ package body Sem_Ch5 is
       Decl : Node_Id;
 
       procedure Diagnose_Non_Variable_Lhs (N : Node_Id);
-      --  N is the node for the left hand side of an assignment, and it
-      --  is not a variable. This routine issues an appropriate diagnostic.
+      --  N is the node for the left hand side of an assignment, and it is not
+      --  a variable. This routine issues an appropriate diagnostic.
 
       procedure Kill_Lhs;
       --  This is called to kill current value settings of a simple variable
@@ -111,7 +112,7 @@ package body Sem_Ch5 is
       procedure Diagnose_Non_Variable_Lhs (N : Node_Id) is
       begin
          --  Not worth posting another error if left hand side already
-         --  flagged as being illegal in some respect
+         --  flagged as being illegal in some respect.
 
          if Error_Posted (N) then
             return;
@@ -119,31 +120,40 @@ package body Sem_Ch5 is
          --  Some special bad cases of entity names
 
          elsif Is_Entity_Name (N) then
-            if Ekind (Entity (N)) = E_In_Parameter then
-               Error_Msg_N
-                 ("assignment to IN mode parameter not allowed", N);
-
-            --  Private declarations in a protected object are turned into
-            --  constants when compiling a protected function.
+            declare
+               Ent : constant Entity_Id := Entity (N);
 
-            elsif Present (Scope (Entity (N)))
-              and then Is_Protected_Type (Scope (Entity (N)))
-              and then
-                (Ekind (Current_Scope) = E_Function
-                  or else
-                 Ekind (Enclosing_Dynamic_Scope (Current_Scope)) = E_Function)
-            then
-               Error_Msg_N
-                 ("protected function cannot modify protected object", N);
+            begin
+               if Ekind (Ent) = E_In_Parameter then
+                  Error_Msg_N
+                    ("assignment to IN mode parameter not allowed", N);
+
+               --  Renamings of protected private components are turned into
+               --  constants when compiling a protected function. In the case
+               --  of single protected types, the private component appears
+               --  directly.
+
+               elsif (Is_Prival (Ent)
+                        and then
+                          (Ekind (Current_Scope) = E_Function
+                             or else Ekind (Enclosing_Dynamic_Scope (
+                                       Current_Scope)) = E_Function))
+                   or else
+                     (Ekind (Ent) = E_Component
+                        and then Is_Protected_Type (Scope (Ent)))
+               then
+                  Error_Msg_N
+                    ("protected function cannot modify protected object", N);
 
-            elsif Ekind (Entity (N)) = E_Loop_Parameter then
-               Error_Msg_N
-                 ("assignment to loop parameter not allowed", N);
+               elsif Ekind (Ent) = E_Loop_Parameter then
+                  Error_Msg_N
+                    ("assignment to loop parameter not allowed", N);
 
-            else
-               Error_Msg_N
-                 ("left hand side of assignment must be a variable", N);
-            end if;
+               else
+                  Error_Msg_N
+                    ("left hand side of assignment must be a variable", N);
+               end if;
+            end;
 
          --  For indexed components or selected components, test prefix
 
@@ -221,9 +231,7 @@ package body Sem_Ch5 is
          --  If assignment operand is a component reference, then we get the
          --  actual subtype of the component for the unconstrained case.
 
-         elsif
-           (Nkind (Opnd) = N_Selected_Component
-             or else Nkind (Opnd) = N_Explicit_Dereference)
+         elsif Nkind_In (Opnd, N_Selected_Component, N_Explicit_Dereference)
            and then not Is_Unchecked_Union (Opnd_Type)
          then
             Decl := Build_Actual_Subtype_Of_Component (Opnd_Type, Opnd);
@@ -250,6 +258,8 @@ package body Sem_Ch5 is
    --  Start of processing for Analyze_Assignment
 
    begin
+      Mark_Coextensions (N, Rhs);
+
       Analyze (Rhs);
       Analyze (Lhs);
 
@@ -340,8 +350,13 @@ package body Sem_Ch5 is
          end if;
       end if;
 
+      --  The resulting assignment type is T1, so now we will resolve the
+      --  left hand side of the assignment using this determined type.
+
       Resolve (Lhs, T1);
 
+      --  Cases where Lhs is not a variable
+
       if not Is_Variable (Lhs) then
 
          --  Ada 2005 (AI-327): Check assignment to the attribute Priority of
@@ -414,13 +429,32 @@ package body Sem_Ch5 is
          Diagnose_Non_Variable_Lhs (Lhs);
          return;
 
+      --  Error of assigning to limited type. We do however allow this in
+      --  certain cases where the front end generates the assignments.
+
       elsif Is_Limited_Type (T1)
         and then not Assignment_OK (Lhs)
         and then not Assignment_OK (Original_Node (Lhs))
+        and then not Is_Value_Type (T1)
+      then
+         --  CPP constructors can only be called in declarations
+
+         if Is_CPP_Constructor_Call (Rhs) then
+            Error_Msg_N ("invalid use of 'C'P'P constructor", Rhs);
+         else
+            Error_Msg_N
+              ("left hand of assignment must not be limited type", Lhs);
+            Explain_Limited_Type (T1, Lhs);
+         end if;
+         return;
+
+      --  Enforce RM 3.9.3 (8): left-hand side cannot be abstract
+
+      elsif Is_Interface (T1)
+        and then not Is_Class_Wide_Type (T1)
       then
          Error_Msg_N
-           ("left hand of assignment must not be limited type", Lhs);
-         Explain_Limited_Type (T1, Lhs);
+           ("target of assignment operation may not be abstract", Lhs);
          return;
       end if;
 
@@ -453,10 +487,15 @@ package body Sem_Ch5 is
          return;
       end if;
 
-      Set_Assignment_Type (Lhs, T1);
+      --  Now we can complete the resolution of the right hand side
 
+      Set_Assignment_Type (Lhs, T1);
       Resolve (Rhs, T1);
+
+      --  This is the point at which we check for an unset reference
+
       Check_Unset_Reference (Rhs);
+      Check_Unprotected_Access (Lhs, Rhs);
 
       --  Remaining steps are skipped if Rhs was syntactically in error
 
@@ -501,7 +540,15 @@ package body Sem_Ch5 is
          return;
       end if;
 
-      if (Is_Class_Wide_Type (T2) or else Is_Dynamically_Tagged (Rhs))
+      --  If the rhs is class-wide or dynamically tagged, then require the lhs
+      --  to be class-wide. The case where the rhs is a dynamically tagged call
+      --  to a dispatching operation with a controlling access result is
+      --  excluded from this check, since the target has an access type (and
+      --  no tag propagation occurs in that case).
+
+      if (Is_Class_Wide_Type (T2)
+           or else (Is_Dynamically_Tagged (Rhs)
+                     and then not Is_Access_Type (T1)))
         and then not Is_Class_Wide_Type (T1)
       then
          Error_Msg_N ("dynamically tagged expression not allowed!", Rhs);
@@ -540,33 +587,48 @@ package body Sem_Ch5 is
          end if;
       end if;
 
-      --  Ada 2005 (AI-230 and AI-385): When the lhs type is an anonymous
-      --  access type, apply an implicit conversion of the rhs to that type
-      --  to force appropriate static and run-time accessibility checks.
+      --  Ada 2005 (AI-385): When the lhs type is an anonymous access type,
+      --  apply an implicit conversion of the rhs to that type to force
+      --  appropriate static and run-time accessibility checks. This applies
+      --  as well to anonymous access-to-subprogram types that are component
+      --  subtypes or formal parameters.
 
       if Ada_Version >= Ada_05
-        and then Ekind (T1) = E_Anonymous_Access_Type
+        and then Is_Access_Type (T1)
       then
-         Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
-         Analyze_And_Resolve (Rhs, T1);
+         if Is_Local_Anonymous_Access (T1)
+           or else Ekind (T2) = E_Anonymous_Access_Subprogram_Type
+         then
+            Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
+            Analyze_And_Resolve (Rhs, T1);
+         end if;
       end if;
 
-      --  Ada 2005 (AI-231)
+      --  Ada 2005 (AI-231): Assignment to not null variable
 
       if Ada_Version >= Ada_05
         and then Can_Never_Be_Null (T1)
         and then not Assignment_OK (Lhs)
       then
-         if Nkind (Rhs) = N_Null then
+         --  Case where we know the right hand side is null
+
+         if Known_Null (Rhs) then
             Apply_Compile_Time_Constraint_Error
               (N   => Rhs,
-               Msg => "(Ada 2005) NULL not allowed in null-excluding objects?",
+               Msg => "(Ada 2005) null not allowed in null-excluding objects?",
                Reason => CE_Null_Not_Allowed);
+
+            --  We still mark this as a possible modification, that's necessary
+            --  to reset Is_True_Constant, and desirable for xref purposes.
+
+            Note_Possible_Modification (Lhs, Sure => True);
             return;
 
+         --  If we know the right hand side is non-null, then we convert to the
+         --  target type, since we don't need a run time check in that case.
+
          elsif not Can_Never_Be_Null (T2) then
-            Rewrite (Rhs,
-              Convert_To (T1, Relocate_Node (Rhs)));
+            Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
             Analyze_And_Resolve (Rhs, T1);
          end if;
       end if;
@@ -606,7 +668,7 @@ package body Sem_Ch5 is
       --  Note: modifications of the Lhs may only be recorded after
       --  checks have been applied.
 
-      Note_Possible_Modification (Lhs);
+      Note_Possible_Modification (Lhs, Sure => True);
 
       --  ??? a real accessibility check is needed when ???
 
@@ -618,11 +680,9 @@ package body Sem_Ch5 is
 
          and then Comes_From_Source (N)
 
-         --  Where the entity is the same on both sides
+         --  Where the object is the same on both sides
 
-         and then Is_Entity_Name (Lhs)
-         and then Is_Entity_Name (Original_Node (Rhs))
-         and then Entity (Lhs) = Entity (Original_Node (Rhs))
+         and then Same_Object (Lhs, Original_Node (Rhs))
 
          --  But exclude the case where the right side was an operation
          --  that got rewritten (e.g. JUNK + K, where K was known to be
@@ -632,8 +692,13 @@ package body Sem_Ch5 is
 
         and then Nkind (Original_Node (Rhs)) not in N_Op
       then
-         Error_Msg_NE
-           ("?useless assignment of & to itself", N, Entity (Lhs));
+         if Nkind (Lhs) in N_Has_Entity then
+            Error_Msg_NE
+              ("?useless assignment of & to itself!", N, Entity (Lhs));
+         else
+            Error_Msg_N
+              ("?useless assignment of object to itself!", N);
+         end if;
       end if;
 
       --  Check for non-allowed composite assignment
@@ -651,6 +716,17 @@ package body Sem_Ch5 is
          Check_Elab_Assign (Lhs);
       end if;
 
+      --  Set Referenced_As_LHS if appropriate. We only set this flag if the
+      --  assignment is a source assignment in the extended main source unit.
+      --  We are not interested in any reference information outside this
+      --  context, or in compiler generated assignment statements.
+
+      if Comes_From_Source (N)
+        and then In_Extended_Main_Source_Unit (Lhs)
+      then
+         Set_Referenced_Modified (Lhs, Out_Param => False);
+      end if;
+
       --  Final step. If left side is an entity, then we may be able to
       --  reset the current tracked values to new safe values. We only have
       --  something to do if the left side is an entity name, and expansion
@@ -673,12 +749,15 @@ package body Sem_Ch5 is
                --  generate bogus warnings when an assignment is rewritten as
                --  another assignment, and gets tied up with itself.
 
+               --  Note: we don't use Record_Last_Assignment here, because we
+               --  have lots of other stuff to do under control of this test.
+
                if Warn_On_Modified_Unread
-                 and then Ekind (Ent) = E_Variable
+                 and then Is_Assignable (Ent)
                  and then Comes_From_Source (N)
                  and then In_Extended_Main_Source_Unit (Ent)
                then
-                  Warn_On_Useless_Assignment (Ent, Sloc (N));
+                  Warn_On_Useless_Assignment (Ent, N);
                   Set_Last_Assignment (Ent, Lhs);
                end if;
 
@@ -753,7 +832,7 @@ package body Sem_Ch5 is
 
       begin
          --  Initialize unblocked exit count for statements of begin block
-         --  plus one for each excption handler that is present.
+         --  plus one for each exception handler that is present.
 
          Unblocked_Exit_Count := 1;
 
@@ -800,11 +879,12 @@ package body Sem_Ch5 is
 
          Set_Etype (Ent, Standard_Void_Type);
          Set_Block_Node (Ent, Identifier (N));
-         New_Scope (Ent);
+         Push_Scope (Ent);
 
          if Present (Decls) then
             Analyze_Declarations (Decls);
             Check_Completion;
+            Inspect_Deferred_Constant_Completion (Decls);
          end if;
 
          Analyze (HSS);
@@ -850,6 +930,10 @@ package body Sem_Ch5 is
       Dont_Care      : Boolean;
       Others_Present : Boolean;
 
+      pragma Warnings (Off, Last_Choice);
+      pragma Warnings (Off, Dont_Care);
+      --  Don't care about assigned values
+
       Statements_Analyzed : Boolean := False;
       --  Set True if at least some statement sequences get analyzed.
       --  If False on exit, means we had a serious error that prevented
@@ -861,7 +945,7 @@ package body Sem_Ch5 is
 
       procedure Non_Static_Choice_Error (Choice : Node_Id);
       --  Error routine invoked by the generic instantiation below when
-      --  the case statment has a non static choice.
+      --  the case statement has a non static choice.
 
       procedure Process_Statements (Alternative : Node_Id);
       --  Analyzes all the statements associated to a case alternative.
@@ -947,6 +1031,7 @@ package body Sem_Ch5 is
       --  a call to Number_Of_Choices to get the right number of entries.
 
       Case_Table : Choice_Table_Type (1 .. Number_Of_Choices (N));
+      pragma Warnings (Off, Case_Table);
 
    --  Start of processing for Analyze_Case_Statement
 
@@ -1049,7 +1134,6 @@ package body Sem_Ch5 is
 
          begin
             Alt := First (Alternatives (N));
-
             while Present (Alt) loop
                if Alt /= Chosen then
                   Remove_Warning_Messages (Statements (Alt));
@@ -1124,6 +1208,13 @@ package body Sem_Ch5 is
          Analyze_And_Resolve (Cond, Any_Boolean);
          Check_Unset_Reference (Cond);
       end if;
+
+      --  Since the exit may take us out of a loop, any previous assignment
+      --  statement is not useless, so clear last assignment indications. It
+      --  is OK to keep other current values, since if the exit statement
+      --  does not exit, then the current values are still valid.
+
+      Kill_Current_Values (Last_Assignment_Only => True);
    end Analyze_Exit_Statement;
 
    ----------------------------
@@ -1138,6 +1229,7 @@ package body Sem_Ch5 is
 
    begin
       Check_Unreachable_Code (N);
+      Kill_Current_Values (Last_Assignment_Only => True);
 
       Analyze (Label);
       Label_Ent := Entity (Label);
@@ -1319,7 +1411,6 @@ package body Sem_Ch5 is
 
             if Present (Elsif_Parts (N)) then
                E := First (Elsif_Parts (N));
-
                while Present (E) loop
                   Remove_Warning_Messages (Then_Statements (E));
                   Next (E);
@@ -1389,10 +1480,7 @@ package body Sem_Ch5 is
          function One_Bound
            (Original_Bound : Node_Id;
             Analyzed_Bound : Node_Id) return Node_Id;
-         --  Create one declaration followed by one assignment statement
-         --  to capture the value of bound. We create a separate assignment
-         --  in order to force the creation of a block in case the bound
-         --  contains a call that uses the secondary stack.
+         --  Capture value of bound and return captured value
 
          ---------------
          -- One_Bound --
@@ -1417,20 +1505,59 @@ package body Sem_Ch5 is
             if Analyzed (Original_Bound) then
                return Original_Bound;
 
-            elsif Nkind (Analyzed_Bound) = N_Integer_Literal
+            elsif Nkind_In (Analyzed_Bound, N_Integer_Literal,
+                                            N_Character_Literal)
               or else Is_Entity_Name (Analyzed_Bound)
             then
                Analyze_And_Resolve (Original_Bound, Typ);
                return Original_Bound;
-
-            else
-               Analyze_And_Resolve (Original_Bound, Typ);
             end if;
 
+            --  Here we need to capture the value
+
+            Analyze_And_Resolve (Original_Bound, Typ);
+
             Id :=
               Make_Defining_Identifier (Loc,
                 Chars => New_Internal_Name ('S'));
 
+            --  Normally, the best approach is simply to generate a constant
+            --  declaration that captures the bound. However, there is a nasty
+            --  case where this is wrong. If the bound is complex, and has a
+            --  possible use of the secondary stack, we need to generate a
+            --  separate assignment statement to ensure the creation of a block
+            --  which will release the secondary stack.
+
+            --  We prefer the constant declaration, since it leaves us with a
+            --  proper trace of the value, useful in optimizations that get rid
+            --  of junk range checks.
+
+            --  Probably we want something like the Side_Effect_Free routine
+            --  in Exp_Util, but for now, we just optimize the cases of 'Last
+            --  and 'First applied to an entity, since these are the important
+            --  cases for range check optimizations.
+
+            if Nkind (Original_Bound) = N_Attribute_Reference
+              and then (Attribute_Name (Original_Bound) = Name_First
+                          or else
+                        Attribute_Name (Original_Bound) = Name_Last)
+              and then Is_Entity_Name (Prefix (Original_Bound))
+            then
+               Decl :=
+                 Make_Object_Declaration (Loc,
+                   Defining_Identifier => Id,
+                   Constant_Present    => True,
+                   Object_Definition   => New_Occurrence_Of (Typ, Loc),
+                   Expression          => Relocate_Node (Original_Bound));
+
+               Insert_Before (Parent (N), Decl);
+               Analyze (Decl);
+               Rewrite (Original_Bound, New_Occurrence_Of (Id, Loc));
+               return Expression (Decl);
+            end if;
+
+            --  Here we make a declaration with a separate assignment statement
+
             Decl :=
               Make_Object_Declaration (Loc,
                 Defining_Identifier => Id,
@@ -1444,6 +1571,15 @@ package body Sem_Ch5 is
                 Name        => New_Occurrence_Of (Id, Loc),
                 Expression  => Relocate_Node (Original_Bound));
 
+            --  If the relocated node is a function call then check if some
+            --  SCIL node references it and needs readjustment.
+
+            if Generate_SCIL
+              and then Nkind (Original_Bound) = N_Function_Call
+            then
+               Adjust_SCIL_Node (Original_Bound, Expression (Assign));
+            end if;
+
             Insert_Before (Parent (N), Assign);
             Analyze (Assign);
 
@@ -1706,6 +1842,11 @@ package body Sem_Ch5 is
 
                   Set_Ekind          (Id, E_Loop_Parameter);
                   Set_Etype          (Id, Etype (DS));
+
+                  --  Treat a range as an implicit reference to the type, to
+                  --  inhibit spurious warnings.
+
+                  Generate_Reference (Base_Type (Etype (DS)), N, ' ');
                   Set_Is_Known_Valid (Id, True);
 
                   --  The loop is not a declarative part, so the only entity
@@ -1731,21 +1872,12 @@ package body Sem_Ch5 is
                         L : constant Node_Id := Low_Bound  (DS);
                         H : constant Node_Id := High_Bound (DS);
 
-                        Llo : Uint;
-                        Lhi : Uint;
-                        LOK : Boolean;
-                        Hlo : Uint;
-                        Hhi : Uint;
-                        HOK : Boolean;
-
                      begin
-                        Determine_Range (L, LOK, Llo, Lhi);
-                        Determine_Range (H, HOK, Hlo, Hhi);
-
                         --  If range of loop is null, issue warning
 
-                        if (LOK and HOK) and then Llo > Hhi then
-
+                        if Compile_Time_Compare
+                            (L, H, Assume_Valid => True) = GT
+                        then
                            --  Suppress the warning if inside a generic
                            --  template or instance, since in practice
                            --  they tend to be dubious in these cases since
@@ -1754,21 +1886,46 @@ package body Sem_Ch5 is
                            if not Inside_A_Generic
                               and then not In_Instance
                            then
-                              Error_Msg_N
-                                ("?loop range is null, loop will not execute",
-                                 DS);
+                              --  Specialize msg if invalid values could make
+                              --  the loop non-null after all.
+
+                              if Compile_Time_Compare
+                                   (L, H, Assume_Valid => False) = GT
+                              then
+                                 Error_Msg_N
+                                   ("?loop range is null, "
+                                    & "loop will not execute",
+                                    DS);
+
+                                 --  Since we know the range of the loop is
+                                 --  null, set the appropriate flag to remove
+                                 --  the loop entirely during expansion.
+
+                                 Set_Is_Null_Loop (Parent (N));
+
+                              --  Here is where the loop could execute because
+                              --  of invalid values, so issue appropriate
+                              --  message and in this case we do not set the
+                              --  Is_Null_Loop flag since the loop may execute.
+
+                              else
+                                 Error_Msg_N
+                                   ("?loop range may be null, "
+                                    & "loop may not execute",
+                                    DS);
+                                 Error_Msg_N
+                                   ("?can only execute if invalid values "
+                                    & "are present",
+                                    DS);
+                              end if;
                            end if;
 
-                           --  Since we know the range of the loop is null,
-                           --  set the appropriate flag to suppress any
-                           --  warnings that would otherwise be issued in
-                           --  the body of the loop that will not execute.
-                           --  We do this even in the generic case, since
-                           --  if it is dubious to warn on the null loop
-                           --  itself, it is certainly dubious to warn for
-                           --  conditions that occur inside it!
+                           --  In either case, suppress warnings in the body of
+                           --  the loop, since it is likely that these warnings
+                           --  will be inappropriate if the loop never actually
+                           --  executes, which is unlikely.
 
-                           Set_Is_Null_Loop (Parent (N));
+                           Set_Suppress_Loop_Warnings (Parent (N));
 
                         --  The other case for a warning is a reverse loop
                         --  where the upper bound is the integer literal
@@ -1784,10 +1941,9 @@ package body Sem_Ch5 is
                         elsif Reverse_Present (LP)
                           and then Nkind (Original_Node (H)) =
                                                           N_Integer_Literal
-                          and then (Intval (H) = Uint_0
+                          and then (Intval (Original_Node (H)) = Uint_0
                                       or else
-                                    Intval (H) = Uint_1)
-                          and then Lhi > Hhi
+                                    Intval (Original_Node (H)) = Uint_1)
                         then
                            Error_Msg_N ("?loop range may be null", DS);
                            Error_Msg_N ("\?bounds may be wrong way round", DS);
@@ -1834,8 +1990,10 @@ package body Sem_Ch5 is
    ----------------------------
 
    procedure Analyze_Loop_Statement (N : Node_Id) is
-      Id   : constant Node_Id := Identifier (N);
-      Iter : constant Node_Id := Iteration_Scheme (N);
+      Loop_Statement : constant Node_Id := N;
+
+      Id   : constant Node_Id := Identifier (Loop_Statement);
+      Iter : constant Node_Id := Iteration_Scheme (Loop_Statement);
       Ent  : Entity_Id;
 
    begin
@@ -1846,296 +2004,75 @@ package body Sem_Ch5 is
 
          Analyze (Id);
          Ent := Entity (Id);
-         Generate_Reference  (Ent, N, ' ');
-         Generate_Definition (Ent);
 
-         --  If we found a label, mark its type. If not, ignore it, since it
-         --  means we have a conflicting declaration, which would already have
-         --  been diagnosed at declaration time. Set Label_Construct of the
-         --  implicit label declaration, which is not created by the parser
-         --  for generic units.
+         --  Guard against serious error (typically, a scope mismatch when
+         --  semantic analysis is requested) by creating loop entity to
+         --  continue analysis.
+
+         if No (Ent) then
+            if Total_Errors_Detected /= 0 then
+               Ent :=
+                 New_Internal_Entity
+                   (E_Loop, Current_Scope, Sloc (Loop_Statement), 'L');
+            else
+               raise Program_Error;
+            end if;
+
+         else
+            Generate_Reference  (Ent, Loop_Statement, ' ');
+            Generate_Definition (Ent);
+
+            --  If we found a label, mark its type. If not, ignore it, since it
+            --  means we have a conflicting declaration, which would already
+            --  have been diagnosed at declaration time. Set Label_Construct
+            --  of the implicit label declaration, which is not created by the
+            --  parser for generic units.
 
-         if Ekind (Ent) = E_Label then
-            Set_Ekind (Ent, E_Loop);
+            if Ekind (Ent) = E_Label then
+               Set_Ekind (Ent, E_Loop);
 
-            if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
-               Set_Label_Construct (Parent (Ent), N);
+               if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
+                  Set_Label_Construct (Parent (Ent), Loop_Statement);
+               end if;
             end if;
          end if;
 
       --  Case of no identifier present
 
       else
-         Ent := New_Internal_Entity (E_Loop, Current_Scope, Sloc (N), 'L');
+         Ent :=
+           New_Internal_Entity
+             (E_Loop, Current_Scope, Sloc (Loop_Statement), 'L');
          Set_Etype (Ent,  Standard_Void_Type);
-         Set_Parent (Ent, N);
+         Set_Parent (Ent, Loop_Statement);
       end if;
 
-      --  Kill current values on entry to loop, since statements in body
-      --  of loop may have been executed before the loop is entered.
-      --  Similarly we kill values after the loop, since we do not know
-      --  that the body of the loop was executed.
+      --  Kill current values on entry to loop, since statements in body of
+      --  loop may have been executed before the loop is entered. Similarly we
+      --  kill values after the loop, since we do not know that the body of the
+      --  loop was executed.
 
       Kill_Current_Values;
-      New_Scope (Ent);
+      Push_Scope (Ent);
       Analyze_Iteration_Scheme (Iter);
-      Analyze_Statements (Statements (N));
-      Process_End_Label (N, 'e', Ent);
+      Analyze_Statements (Statements (Loop_Statement));
+      Process_End_Label (Loop_Statement, 'e', Ent);
       End_Scope;
       Kill_Current_Values;
 
-      --  Check for possible infinite loop which we can diagnose successfully.
-      --  The case we look for is a while loop which tests a local variable,
-      --  where there is no obvious direct or indirect update of the variable
-      --  within the body of the loop.
+      --  Check for infinite loop. We skip this check for generated code, since
+      --  it justs waste time and makes debugging the routine called harder.
 
-      --  Note: we don't try to give a warning if condition actions are
-      --  present, since the loop structure can be very complex in this case.
-
-      if No (Iter)
-        or else No (Condition (Iter))
-        or else Present (Condition_Actions (Iter))
-        or else Debug_Flag_Dot_W
-      then
-         return;
+      if Comes_From_Source (N) then
+         Check_Infinite_Loop_Warning (N);
       end if;
 
-      --  Initial conditions met, see if condition is of right form
-
-      declare
-         Loc  : Node_Id := Empty;
-         Var  : Entity_Id := Empty;
-
-         function Has_Indirection (T : Entity_Id) return Boolean;
-         --  If the controlling variable is an access type, or is a record type
-         --  with access components, assume that it is changed indirectly and
-         --  suppress the warning. As a concession to low-level programming, in
-         --  particular within Declib, we also suppress warnings on a record
-         --  type that contains components of type Address or Short_Address.
-
-         procedure Find_Var (N : Node_Id);
-         --  Find whether the condition in a while-loop can be reduced to
-         --  a test on a single variable. Recurse if condition is negation.
-
-         ---------------------
-         -- Has_Indirection --
-         ---------------------
-
-         function Has_Indirection (T : Entity_Id) return Boolean is
-            Comp : Entity_Id;
-            Rec  : Entity_Id;
+      --  Code after loop is unreachable if the loop has no WHILE or FOR
+      --  and contains no EXIT statements within the body of the loop.
 
-         begin
-            if Is_Access_Type (T) then
-               return True;
-
-            elsif Is_Private_Type (T)
-              and then Present (Full_View (T))
-              and then Is_Access_Type (Full_View (T))
-            then
-               return True;
-
-            elsif Is_Record_Type (T) then
-               Rec := T;
-
-            elsif Is_Private_Type (T)
-              and then Present (Full_View (T))
-              and then Is_Record_Type (Full_View (T))
-            then
-               Rec := Full_View (T);
-            else
-               return False;
-            end if;
-
-            Comp := First_Component (Rec);
-            while Present (Comp) loop
-               if Is_Access_Type (Etype (Comp))
-                 or else Is_Descendent_Of_Address (Etype (Comp))
-               then
-                  return True;
-               end if;
-
-               Next_Component (Comp);
-            end loop;
-
-            return False;
-         end Has_Indirection;
-
-         --------------
-         -- Find_Var --
-         --------------
-
-         procedure Find_Var (N : Node_Id) is
-         begin
-            --  Condition is a direct variable reference
-
-            if Is_Entity_Name (N)
-              and then not Is_Library_Level_Entity (Entity (N))
-            then
-               Loc := N;
-
-            --  Case of condition is a comparison with compile time known value
-
-            elsif Nkind (N) in N_Op_Compare then
-               if Is_Entity_Name (Left_Opnd (N))
-                 and then Compile_Time_Known_Value (Right_Opnd (N))
-               then
-                  Loc := Left_Opnd (N);
-
-               elsif Is_Entity_Name (Right_Opnd (N))
-                 and then Compile_Time_Known_Value (Left_Opnd (N))
-               then
-                  Loc :=  Right_Opnd (N);
-
-               else
-                  return;
-               end if;
-
-            --  If condition is a negation, check whether the operand has the
-            --  proper form.
-
-            elsif Nkind (N) = N_Op_Not then
-               Find_Var (Right_Opnd (N));
-
-            --  Case of condition is function call with one parameter
-
-            elsif Nkind (N) = N_Function_Call then
-               declare
-                  PA : constant List_Id := Parameter_Associations (N);
-               begin
-                  if Present (PA)
-                    and then List_Length (PA) = 1
-                    and then Is_Entity_Name (First (PA))
-                  then
-                     Loc := First (PA);
-                  else
-                     return;
-                  end if;
-               end;
-
-            else
-               return;
-            end if;
-         end Find_Var;
-
-      begin
-         Find_Var (Condition (Iter));
-
-         if Present (Loc) then
-            Var := Entity (Loc);
-         end if;
-
-         if Present (Var)
-           and then Ekind (Var) = E_Variable
-           and then not Is_Library_Level_Entity (Var)
-           and then Comes_From_Source (Var)
-         then
-            if Has_Indirection (Etype (Var)) then
-
-               --  Assume that the designated object is modified in some
-               --  other way, to avoid false positives.
-
-               return;
-
-            elsif Is_Volatile (Var) then
-
-               --  If the variable is marked as volatile, we assume that
-               --  the condition may be affected by other tasks.
-
-               return;
-
-            elsif Nkind (Original_Node (First (Statements (N))))
-                 = N_Delay_Relative_Statement
-              or else Nkind (Original_Node (First (Statements (N))))
-                 = N_Delay_Until_Statement
-            then
-
-               --  Assume that this is a multitasking program, and the
-               --  condition is affected by other threads.
-
-               return;
-
-            end if;
-
-         --  There no identifiable single variable in the condition
-
-         else
-            return;
-         end if;
-
-         --  Search for reference to variable in loop
-
-         Ref_Search : declare
-            function Test_Ref (N : Node_Id) return Traverse_Result;
-            --  Test for reference to variable in question. Returns Abandon
-            --  if matching reference found.
-
-            function Find_Ref is new Traverse_Func (Test_Ref);
-            --  Function to traverse body of procedure. Returns Abandon if
-            --  matching reference found.
-
-            --------------
-            -- Test_Ref --
-            --------------
-
-            function Test_Ref (N : Node_Id) return Traverse_Result is
-            begin
-               --  Waste of time to look at iteration scheme
-
-               if N = Iter then
-                  return Skip;
-
-               --  Direct reference to variable in question
-
-               elsif Is_Entity_Name (N)
-                 and then Present (Entity (N))
-                 and then Entity (N) = Var
-                 and then May_Be_Lvalue (N)
-               then
-                  return Abandon;
-
-                  --  Reference to variable renaming variable in question
-
-               elsif Is_Entity_Name (N)
-                 and then Present (Entity (N))
-                 and then Ekind (Entity (N)) = E_Variable
-                 and then Present (Renamed_Object (Entity (N)))
-                 and then Is_Entity_Name (Renamed_Object (Entity (N)))
-                 and then Entity (Renamed_Object (Entity (N))) = Var
-                 and then May_Be_Lvalue (N)
-               then
-                  return Abandon;
-
-               --  Calls to subprograms are OK, unless the subprogram is
-               --  within the scope of the entity in question and could
-               --  therefore possibly modify it
-
-               elsif Nkind (N) = N_Procedure_Call_Statement
-                 or else Nkind (N) = N_Function_Call
-               then
-                  if not Is_Entity_Name (Name (N))
-                    or else Scope_Within (Entity (Name (N)), Scope (Var))
-                  then
-                     return Abandon;
-                  end if;
-               end if;
-
-               --  All OK, continue scan
-
-               return OK;
-            end Test_Ref;
-
-         --  Start of processing for Ref_Search
-
-         begin
-            if Find_Ref (N) = OK then
-               Error_Msg_NE
-                 ("variable& is not modified in loop body?", Loc, Var);
-               Error_Msg_N
-                 ("\possible infinite loop", Loc);
-            end if;
-         end Ref_Search;
-      end;
+      if No (Iter) and then not Has_Exit (Ent) then
+         Check_Unreachable_Code (N);
+      end if;
    end Analyze_Loop_Statement;
 
    ----------------------------
@@ -2260,12 +2197,12 @@ package body Sem_Ch5 is
                --  the Ada RM annoyingly requires a useless return here!
 
                if Nkind (Original_Node (N)) /= N_Raise_Statement
-                 or else Nkind (Nxt) /= N_Return_Statement
+                 or else Nkind (Nxt) /= N_Simple_Return_Statement
                then
                   --  The rather strange shenanigans with the warning message
                   --  here reflects the fact that Kill_Dead_Code is very good
                   --  at removing warnings in deleted code, and this is one
-                  --  warning we would prefer NOT to have removed :-)
+                  --  warning we would prefer NOT to have removed.
 
                   Error_Loc := Sloc (Nxt);
 
@@ -2302,7 +2239,7 @@ package body Sem_Ch5 is
 
                   --  Now issue the warning
 
-                  Error_Msg ("?unreachable code", Error_Loc);
+                  Error_Msg ("?unreachable code!", Error_Loc);
                end if;
 
             --  If the unconditional transfer of control instruction is