657a0e45dfadfb7956fade394bd384c22cd906bf
[platform/upstream/gcc.git] / gcc / ada / sem_ch5.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              S E M _ C H 5                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2015, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Einfo;    use Einfo;
30 with Errout;   use Errout;
31 with Expander; use Expander;
32 with Exp_Ch6;  use Exp_Ch6;
33 with Exp_Ch7;  use Exp_Ch7;
34 with Exp_Util; use Exp_Util;
35 with Freeze;   use Freeze;
36 with Ghost;    use Ghost;
37 with Lib;      use Lib;
38 with Lib.Xref; use Lib.Xref;
39 with Namet;    use Namet;
40 with Nlists;   use Nlists;
41 with Nmake;    use Nmake;
42 with Opt;      use Opt;
43 with Restrict; use Restrict;
44 with Rident;   use Rident;
45 with Rtsfind;  use Rtsfind;
46 with Sem;      use Sem;
47 with Sem_Aux;  use Sem_Aux;
48 with Sem_Case; use Sem_Case;
49 with Sem_Ch3;  use Sem_Ch3;
50 with Sem_Ch6;  use Sem_Ch6;
51 with Sem_Ch8;  use Sem_Ch8;
52 with Sem_Dim;  use Sem_Dim;
53 with Sem_Disp; use Sem_Disp;
54 with Sem_Elab; use Sem_Elab;
55 with Sem_Eval; use Sem_Eval;
56 with Sem_Res;  use Sem_Res;
57 with Sem_Type; use Sem_Type;
58 with Sem_Util; use Sem_Util;
59 with Sem_Warn; use Sem_Warn;
60 with Snames;   use Snames;
61 with Stand;    use Stand;
62 with Sinfo;    use Sinfo;
63 with Targparm; use Targparm;
64 with Tbuild;   use Tbuild;
65 with Uintp;    use Uintp;
66
67 package body Sem_Ch5 is
68
69    Unblocked_Exit_Count : Nat := 0;
70    --  This variable is used when processing if statements, case statements,
71    --  and block statements. It counts the number of exit points that are not
72    --  blocked by unconditional transfer instructions: for IF and CASE, these
73    --  are the branches of the conditional; for a block, they are the statement
74    --  sequence of the block, and the statement sequences of any exception
75    --  handlers that are part of the block. When processing is complete, if
76    --  this count is zero, it means that control cannot fall through the IF,
77    --  CASE or block statement. This is used for the generation of warning
78    --  messages. This variable is recursively saved on entry to processing the
79    --  construct, and restored on exit.
80
81    procedure Preanalyze_Range (R_Copy : Node_Id);
82    --  Determine expected type of range or domain of iteration of Ada 2012
83    --  loop by analyzing separate copy. Do the analysis and resolution of the
84    --  copy of the bound(s) with expansion disabled, to prevent the generation
85    --  of finalization actions. This prevents memory leaks when the bounds
86    --  contain calls to functions returning controlled arrays or when the
87    --  domain of iteration is a container.
88
89    ------------------------
90    -- Analyze_Assignment --
91    ------------------------
92
93    procedure Analyze_Assignment (N : Node_Id) is
94       Lhs  : constant Node_Id := Name (N);
95       Rhs  : constant Node_Id := Expression (N);
96       T1   : Entity_Id;
97       T2   : Entity_Id;
98       Decl : Node_Id;
99
100       procedure Diagnose_Non_Variable_Lhs (N : Node_Id);
101       --  N is the node for the left hand side of an assignment, and it is not
102       --  a variable. This routine issues an appropriate diagnostic.
103
104       procedure Kill_Lhs;
105       --  This is called to kill current value settings of a simple variable
106       --  on the left hand side. We call it if we find any error in analyzing
107       --  the assignment, and at the end of processing before setting any new
108       --  current values in place.
109
110       procedure Set_Assignment_Type
111         (Opnd      : Node_Id;
112          Opnd_Type : in out Entity_Id);
113       --  Opnd is either the Lhs or Rhs of the assignment, and Opnd_Type is the
114       --  nominal subtype. This procedure is used to deal with cases where the
115       --  nominal subtype must be replaced by the actual subtype.
116
117       -------------------------------
118       -- Diagnose_Non_Variable_Lhs --
119       -------------------------------
120
121       procedure Diagnose_Non_Variable_Lhs (N : Node_Id) is
122       begin
123          --  Not worth posting another error if left hand side already flagged
124          --  as being illegal in some respect.
125
126          if Error_Posted (N) then
127             return;
128
129          --  Some special bad cases of entity names
130
131          elsif Is_Entity_Name (N) then
132             declare
133                Ent : constant Entity_Id := Entity (N);
134
135             begin
136                if Ekind (Ent) = E_In_Parameter then
137                   Error_Msg_N
138                     ("assignment to IN mode parameter not allowed", N);
139                   return;
140
141                --  Renamings of protected private components are turned into
142                --  constants when compiling a protected function. In the case
143                --  of single protected types, the private component appears
144                --  directly.
145
146                elsif (Is_Prival (Ent)
147                        and then
148                          (Ekind (Current_Scope) = E_Function
149                            or else Ekind (Enclosing_Dynamic_Scope
150                                             (Current_Scope)) = E_Function))
151                    or else
152                      (Ekind (Ent) = E_Component
153                        and then Is_Protected_Type (Scope (Ent)))
154                then
155                   Error_Msg_N
156                     ("protected function cannot modify protected object", N);
157                   return;
158
159                elsif Ekind (Ent) = E_Loop_Parameter then
160                   Error_Msg_N ("assignment to loop parameter not allowed", N);
161                   return;
162                end if;
163             end;
164
165          --  For indexed components, test prefix if it is in array. We do not
166          --  want to recurse for cases where the prefix is a pointer, since we
167          --  may get a message confusing the pointer and what it references.
168
169          elsif Nkind (N) = N_Indexed_Component
170            and then Is_Array_Type (Etype (Prefix (N)))
171          then
172             Diagnose_Non_Variable_Lhs (Prefix (N));
173             return;
174
175          --  Another special case for assignment to discriminant
176
177          elsif Nkind (N) = N_Selected_Component then
178             if Present (Entity (Selector_Name (N)))
179               and then Ekind (Entity (Selector_Name (N))) = E_Discriminant
180             then
181                Error_Msg_N ("assignment to discriminant not allowed", N);
182                return;
183
184             --  For selection from record, diagnose prefix, but note that again
185             --  we only do this for a record, not e.g. for a pointer.
186
187             elsif Is_Record_Type (Etype (Prefix (N))) then
188                Diagnose_Non_Variable_Lhs (Prefix (N));
189                return;
190             end if;
191          end if;
192
193          --  If we fall through, we have no special message to issue
194
195          Error_Msg_N ("left hand side of assignment must be a variable", N);
196       end Diagnose_Non_Variable_Lhs;
197
198       --------------
199       -- Kill_Lhs --
200       --------------
201
202       procedure Kill_Lhs is
203       begin
204          if Is_Entity_Name (Lhs) then
205             declare
206                Ent : constant Entity_Id := Entity (Lhs);
207             begin
208                if Present (Ent) then
209                   Kill_Current_Values (Ent);
210                end if;
211             end;
212          end if;
213       end Kill_Lhs;
214
215       -------------------------
216       -- Set_Assignment_Type --
217       -------------------------
218
219       procedure Set_Assignment_Type
220         (Opnd      : Node_Id;
221          Opnd_Type : in out Entity_Id)
222       is
223       begin
224          Require_Entity (Opnd);
225
226          --  If the assignment operand is an in-out or out parameter, then we
227          --  get the actual subtype (needed for the unconstrained case). If the
228          --  operand is the actual in an entry declaration, then within the
229          --  accept statement it is replaced with a local renaming, which may
230          --  also have an actual subtype.
231
232          if Is_Entity_Name (Opnd)
233            and then (Ekind (Entity (Opnd)) = E_Out_Parameter
234                       or else Ekind_In (Entity (Opnd),
235                                         E_In_Out_Parameter,
236                                         E_Generic_In_Out_Parameter)
237                       or else
238                         (Ekind (Entity (Opnd)) = E_Variable
239                           and then Nkind (Parent (Entity (Opnd))) =
240                                             N_Object_Renaming_Declaration
241                           and then Nkind (Parent (Parent (Entity (Opnd)))) =
242                                             N_Accept_Statement))
243          then
244             Opnd_Type := Get_Actual_Subtype (Opnd);
245
246          --  If assignment operand is a component reference, then we get the
247          --  actual subtype of the component for the unconstrained case.
248
249          elsif Nkind_In (Opnd, N_Selected_Component, N_Explicit_Dereference)
250            and then not Is_Unchecked_Union (Opnd_Type)
251          then
252             Decl := Build_Actual_Subtype_Of_Component (Opnd_Type, Opnd);
253
254             if Present (Decl) then
255                Insert_Action (N, Decl);
256                Mark_Rewrite_Insertion (Decl);
257                Analyze (Decl);
258                Opnd_Type := Defining_Identifier (Decl);
259                Set_Etype (Opnd, Opnd_Type);
260                Freeze_Itype (Opnd_Type, N);
261
262             elsif Is_Constrained (Etype (Opnd)) then
263                Opnd_Type := Etype (Opnd);
264             end if;
265
266          --  For slice, use the constrained subtype created for the slice
267
268          elsif Nkind (Opnd) = N_Slice then
269             Opnd_Type := Etype (Opnd);
270          end if;
271       end Set_Assignment_Type;
272
273       --  Local variables
274
275       Save_Ghost_Mode : constant Ghost_Mode_Type := Ghost_Mode;
276
277    --  Start of processing for Analyze_Assignment
278
279    begin
280       Mark_Coextensions (N, Rhs);
281
282       --  Analyze the target of the assignment first in case the expression
283       --  contains references to Ghost entities. The checks that verify the
284       --  proper use of a Ghost entity need to know the enclosing context.
285
286       Analyze (Lhs);
287
288       --  An assignment statement is Ghost when the left hand side denotes a
289       --  Ghost entity. Set the mode now to ensure that any nodes generated
290       --  during analysis and expansion are properly marked as Ghost.
291
292       Set_Ghost_Mode (N);
293       Analyze (Rhs);
294
295       --  Ensure that we never do an assignment on a variable marked as
296       --  as Safe_To_Reevaluate.
297
298       pragma Assert (not Is_Entity_Name (Lhs)
299         or else Ekind (Entity (Lhs)) /= E_Variable
300         or else not Is_Safe_To_Reevaluate (Entity (Lhs)));
301
302       --  Start type analysis for assignment
303
304       T1 := Etype (Lhs);
305
306       --  In the most general case, both Lhs and Rhs can be overloaded, and we
307       --  must compute the intersection of the possible types on each side.
308
309       if Is_Overloaded (Lhs) then
310          declare
311             I  : Interp_Index;
312             It : Interp;
313
314          begin
315             T1 := Any_Type;
316             Get_First_Interp (Lhs, I, It);
317
318             while Present (It.Typ) loop
319
320                --  An indexed component with generalized indexing is always
321                --  overloaded with the corresponding dereference. Discard the
322                --  interpretation that yields a reference type, which is not
323                --  assignable.
324
325                if Nkind (Lhs) = N_Indexed_Component
326                  and then Present (Generalized_Indexing (Lhs))
327                  and then Has_Implicit_Dereference (It.Typ)
328                then
329                   null;
330
331                elsif Has_Compatible_Type (Rhs, It.Typ) then
332                   if T1 /= Any_Type then
333
334                      --  An explicit dereference is overloaded if the prefix
335                      --  is. Try to remove the ambiguity on the prefix, the
336                      --  error will be posted there if the ambiguity is real.
337
338                      if Nkind (Lhs) = N_Explicit_Dereference then
339                         declare
340                            PI    : Interp_Index;
341                            PI1   : Interp_Index := 0;
342                            PIt   : Interp;
343                            Found : Boolean;
344
345                         begin
346                            Found := False;
347                            Get_First_Interp (Prefix (Lhs), PI, PIt);
348
349                            while Present (PIt.Typ) loop
350                               if Is_Access_Type (PIt.Typ)
351                                 and then Has_Compatible_Type
352                                            (Rhs, Designated_Type (PIt.Typ))
353                               then
354                                  if Found then
355                                     PIt :=
356                                       Disambiguate (Prefix (Lhs),
357                                         PI1, PI, Any_Type);
358
359                                     if PIt = No_Interp then
360                                        Error_Msg_N
361                                          ("ambiguous left-hand side"
362                                             & " in assignment", Lhs);
363                                        exit;
364                                     else
365                                        Resolve (Prefix (Lhs), PIt.Typ);
366                                     end if;
367
368                                     exit;
369                                  else
370                                     Found := True;
371                                     PI1 := PI;
372                                  end if;
373                               end if;
374
375                               Get_Next_Interp (PI, PIt);
376                            end loop;
377                         end;
378
379                      else
380                         Error_Msg_N
381                           ("ambiguous left-hand side in assignment", Lhs);
382                         exit;
383                      end if;
384                   else
385                      T1 := It.Typ;
386                   end if;
387                end if;
388
389                Get_Next_Interp (I, It);
390             end loop;
391          end;
392
393          if T1 = Any_Type then
394             Error_Msg_N
395               ("no valid types for left-hand side for assignment", Lhs);
396             Kill_Lhs;
397             Ghost_Mode := Save_Ghost_Mode;
398             return;
399          end if;
400       end if;
401
402       --  The resulting assignment type is T1, so now we will resolve the left
403       --  hand side of the assignment using this determined type.
404
405       Resolve (Lhs, T1);
406
407       --  Cases where Lhs is not a variable
408
409       --  Cases where Lhs is not a variable. In an instance or an inlined body
410       --  no need for further check because assignment was legal in template.
411
412       if In_Inlined_Body then
413          null;
414
415       elsif not Is_Variable (Lhs) then
416
417          --  Ada 2005 (AI-327): Check assignment to the attribute Priority of a
418          --  protected object.
419
420          declare
421             Ent : Entity_Id;
422             S   : Entity_Id;
423
424          begin
425             if Ada_Version >= Ada_2005 then
426
427                --  Handle chains of renamings
428
429                Ent := Lhs;
430                while Nkind (Ent) in N_Has_Entity
431                  and then Present (Entity (Ent))
432                  and then Present (Renamed_Object (Entity (Ent)))
433                loop
434                   Ent := Renamed_Object (Entity (Ent));
435                end loop;
436
437                if (Nkind (Ent) = N_Attribute_Reference
438                     and then Attribute_Name (Ent) = Name_Priority)
439
440                   --  Renamings of the attribute Priority applied to protected
441                   --  objects have been previously expanded into calls to the
442                   --  Get_Ceiling run-time subprogram.
443
444                  or else
445                   (Nkind (Ent) = N_Function_Call
446                     and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
447                                or else
448                               Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling)))
449                then
450                   --  The enclosing subprogram cannot be a protected function
451
452                   S := Current_Scope;
453                   while not (Is_Subprogram (S)
454                               and then Convention (S) = Convention_Protected)
455                      and then S /= Standard_Standard
456                   loop
457                      S := Scope (S);
458                   end loop;
459
460                   if Ekind (S) = E_Function
461                     and then Convention (S) = Convention_Protected
462                   then
463                      Error_Msg_N
464                        ("protected function cannot modify protected object",
465                         Lhs);
466                   end if;
467
468                   --  Changes of the ceiling priority of the protected object
469                   --  are only effective if the Ceiling_Locking policy is in
470                   --  effect (AARM D.5.2 (5/2)).
471
472                   if Locking_Policy /= 'C' then
473                      Error_Msg_N ("assignment to the attribute PRIORITY has " &
474                                   "no effect??", Lhs);
475                      Error_Msg_N ("\since no Locking_Policy has been " &
476                                   "specified??", Lhs);
477                   end if;
478
479                   Ghost_Mode := Save_Ghost_Mode;
480                   return;
481                end if;
482             end if;
483          end;
484
485          Diagnose_Non_Variable_Lhs (Lhs);
486          Ghost_Mode := Save_Ghost_Mode;
487          return;
488
489       --  Error of assigning to limited type. We do however allow this in
490       --  certain cases where the front end generates the assignments.
491
492       elsif Is_Limited_Type (T1)
493         and then not Assignment_OK (Lhs)
494         and then not Assignment_OK (Original_Node (Lhs))
495       then
496          --  CPP constructors can only be called in declarations
497
498          if Is_CPP_Constructor_Call (Rhs) then
499             Error_Msg_N ("invalid use of 'C'P'P constructor", Rhs);
500          else
501             Error_Msg_N
502               ("left hand of assignment must not be limited type", Lhs);
503             Explain_Limited_Type (T1, Lhs);
504          end if;
505
506          Ghost_Mode := Save_Ghost_Mode;
507          return;
508
509       --  A class-wide type may be a limited view. This illegal case is not
510       --  caught by previous checks.
511
512       elsif Ekind (T1) = E_Class_Wide_Type
513         and then From_Limited_With (T1)
514       then
515          Error_Msg_NE ("invalid use of limited view of&", Lhs, T1);
516          return;
517
518       --  Enforce RM 3.9.3 (8): the target of an assignment operation cannot be
519       --  abstract. This is only checked when the assignment Comes_From_Source,
520       --  because in some cases the expander generates such assignments (such
521       --  in the _assign operation for an abstract type).
522
523       elsif Is_Abstract_Type (T1) and then Comes_From_Source (N) then
524          Error_Msg_N
525            ("target of assignment operation must not be abstract", Lhs);
526       end if;
527
528       --  Resolution may have updated the subtype, in case the left-hand side
529       --  is a private protected component. Use the correct subtype to avoid
530       --  scoping issues in the back-end.
531
532       T1 := Etype (Lhs);
533
534       --  Ada 2005 (AI-50217, AI-326): Check wrong dereference of incomplete
535       --  type. For example:
536
537       --    limited with P;
538       --    package Pkg is
539       --      type Acc is access P.T;
540       --    end Pkg;
541
542       --    with Pkg; use Acc;
543       --    procedure Example is
544       --       A, B : Acc;
545       --    begin
546       --       A.all := B.all;  -- ERROR
547       --    end Example;
548
549       if Nkind (Lhs) = N_Explicit_Dereference
550         and then Ekind (T1) = E_Incomplete_Type
551       then
552          Error_Msg_N ("invalid use of incomplete type", Lhs);
553          Kill_Lhs;
554          Ghost_Mode := Save_Ghost_Mode;
555          return;
556       end if;
557
558       --  Now we can complete the resolution of the right hand side
559
560       Set_Assignment_Type (Lhs, T1);
561       Resolve (Rhs, T1);
562
563       --  This is the point at which we check for an unset reference
564
565       Check_Unset_Reference (Rhs);
566       Check_Unprotected_Access (Lhs, Rhs);
567
568       --  Remaining steps are skipped if Rhs was syntactically in error
569
570       if Rhs = Error then
571          Kill_Lhs;
572          Ghost_Mode := Save_Ghost_Mode;
573          return;
574       end if;
575
576       T2 := Etype (Rhs);
577
578       if not Covers (T1, T2) then
579          Wrong_Type (Rhs, Etype (Lhs));
580          Kill_Lhs;
581          Ghost_Mode := Save_Ghost_Mode;
582          return;
583       end if;
584
585       --  Ada 2005 (AI-326): In case of explicit dereference of incomplete
586       --  types, use the non-limited view if available
587
588       if Nkind (Rhs) = N_Explicit_Dereference
589         and then Is_Tagged_Type (T2)
590         and then Has_Non_Limited_View (T2)
591       then
592          T2 := Non_Limited_View (T2);
593       end if;
594
595       Set_Assignment_Type (Rhs, T2);
596
597       if Total_Errors_Detected /= 0 then
598          if No (T1) then
599             T1 := Any_Type;
600          end if;
601
602          if No (T2) then
603             T2 := Any_Type;
604          end if;
605       end if;
606
607       if T1 = Any_Type or else T2 = Any_Type then
608          Kill_Lhs;
609          Ghost_Mode := Save_Ghost_Mode;
610          return;
611       end if;
612
613       --  If the rhs is class-wide or dynamically tagged, then require the lhs
614       --  to be class-wide. The case where the rhs is a dynamically tagged call
615       --  to a dispatching operation with a controlling access result is
616       --  excluded from this check, since the target has an access type (and
617       --  no tag propagation occurs in that case).
618
619       if (Is_Class_Wide_Type (T2)
620            or else (Is_Dynamically_Tagged (Rhs)
621                      and then not Is_Access_Type (T1)))
622         and then not Is_Class_Wide_Type (T1)
623       then
624          Error_Msg_N ("dynamically tagged expression not allowed!", Rhs);
625
626       elsif Is_Class_Wide_Type (T1)
627         and then not Is_Class_Wide_Type (T2)
628         and then not Is_Tag_Indeterminate (Rhs)
629         and then not Is_Dynamically_Tagged (Rhs)
630       then
631          Error_Msg_N ("dynamically tagged expression required!", Rhs);
632       end if;
633
634       --  Propagate the tag from a class-wide target to the rhs when the rhs
635       --  is a tag-indeterminate call.
636
637       if Is_Tag_Indeterminate (Rhs) then
638          if Is_Class_Wide_Type (T1) then
639             Propagate_Tag (Lhs, Rhs);
640
641          elsif Nkind (Rhs) = N_Function_Call
642            and then Is_Entity_Name (Name (Rhs))
643            and then Is_Abstract_Subprogram (Entity (Name (Rhs)))
644          then
645             Error_Msg_N
646               ("call to abstract function must be dispatching", Name (Rhs));
647
648          elsif Nkind (Rhs) = N_Qualified_Expression
649            and then Nkind (Expression (Rhs)) = N_Function_Call
650               and then Is_Entity_Name (Name (Expression (Rhs)))
651               and then
652                 Is_Abstract_Subprogram (Entity (Name (Expression (Rhs))))
653          then
654             Error_Msg_N
655               ("call to abstract function must be dispatching",
656                 Name (Expression (Rhs)));
657          end if;
658       end if;
659
660       --  Ada 2005 (AI-385): When the lhs type is an anonymous access type,
661       --  apply an implicit conversion of the rhs to that type to force
662       --  appropriate static and run-time accessibility checks. This applies
663       --  as well to anonymous access-to-subprogram types that are component
664       --  subtypes or formal parameters.
665
666       if Ada_Version >= Ada_2005 and then Is_Access_Type (T1) then
667          if Is_Local_Anonymous_Access (T1)
668            or else Ekind (T2) = E_Anonymous_Access_Subprogram_Type
669
670            --  Handle assignment to an Ada 2012 stand-alone object
671            --  of an anonymous access type.
672
673            or else (Ekind (T1) = E_Anonymous_Access_Type
674                      and then Nkind (Associated_Node_For_Itype (T1)) =
675                                                        N_Object_Declaration)
676
677          then
678             Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
679             Analyze_And_Resolve (Rhs, T1);
680          end if;
681       end if;
682
683       --  Ada 2005 (AI-231): Assignment to not null variable
684
685       if Ada_Version >= Ada_2005
686         and then Can_Never_Be_Null (T1)
687         and then not Assignment_OK (Lhs)
688       then
689          --  Case where we know the right hand side is null
690
691          if Known_Null (Rhs) then
692             Apply_Compile_Time_Constraint_Error
693               (N      => Rhs,
694                Msg    =>
695                  "(Ada 2005) null not allowed in null-excluding objects??",
696                Reason => CE_Null_Not_Allowed);
697
698             --  We still mark this as a possible modification, that's necessary
699             --  to reset Is_True_Constant, and desirable for xref purposes.
700
701             Note_Possible_Modification (Lhs, Sure => True);
702             Ghost_Mode := Save_Ghost_Mode;
703             return;
704
705          --  If we know the right hand side is non-null, then we convert to the
706          --  target type, since we don't need a run time check in that case.
707
708          elsif not Can_Never_Be_Null (T2) then
709             Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
710             Analyze_And_Resolve (Rhs, T1);
711          end if;
712       end if;
713
714       if Is_Scalar_Type (T1) then
715          Apply_Scalar_Range_Check (Rhs, Etype (Lhs));
716
717       --  For array types, verify that lengths match. If the right hand side
718       --  is a function call that has been inlined, the assignment has been
719       --  rewritten as a block, and the constraint check will be applied to the
720       --  assignment within the block.
721
722       elsif Is_Array_Type (T1)
723         and then (Nkind (Rhs) /= N_Type_Conversion
724                    or else Is_Constrained (Etype (Rhs)))
725         and then (Nkind (Rhs) /= N_Function_Call
726                    or else Nkind (N) /= N_Block_Statement)
727       then
728          --  Assignment verifies that the length of the Lsh and Rhs are equal,
729          --  but of course the indexes do not have to match. If the right-hand
730          --  side is a type conversion to an unconstrained type, a length check
731          --  is performed on the expression itself during expansion. In rare
732          --  cases, the redundant length check is computed on an index type
733          --  with a different representation, triggering incorrect code in the
734          --  back end.
735
736          Apply_Length_Check (Rhs, Etype (Lhs));
737
738       else
739          --  Discriminant checks are applied in the course of expansion
740
741          null;
742       end if;
743
744       --  Note: modifications of the Lhs may only be recorded after
745       --  checks have been applied.
746
747       Note_Possible_Modification (Lhs, Sure => True);
748
749       --  ??? a real accessibility check is needed when ???
750
751       --  Post warning for redundant assignment or variable to itself
752
753       if Warn_On_Redundant_Constructs
754
755          --  We only warn for source constructs
756
757          and then Comes_From_Source (N)
758
759          --  Where the object is the same on both sides
760
761          and then Same_Object (Lhs, Original_Node (Rhs))
762
763          --  But exclude the case where the right side was an operation that
764          --  got rewritten (e.g. JUNK + K, where K was known to be zero). We
765          --  don't want to warn in such a case, since it is reasonable to write
766          --  such expressions especially when K is defined symbolically in some
767          --  other package.
768
769         and then Nkind (Original_Node (Rhs)) not in N_Op
770       then
771          if Nkind (Lhs) in N_Has_Entity then
772             Error_Msg_NE -- CODEFIX
773               ("?r?useless assignment of & to itself!", N, Entity (Lhs));
774          else
775             Error_Msg_N -- CODEFIX
776               ("?r?useless assignment of object to itself!", N);
777          end if;
778       end if;
779
780       --  Check for non-allowed composite assignment
781
782       if not Support_Composite_Assign_On_Target
783         and then (Is_Array_Type (T1) or else Is_Record_Type (T1))
784         and then (not Has_Size_Clause (T1) or else Esize (T1) > 64)
785       then
786          Error_Msg_CRT ("composite assignment", N);
787       end if;
788
789       --  Check elaboration warning for left side if not in elab code
790
791       if not In_Subprogram_Or_Concurrent_Unit then
792          Check_Elab_Assign (Lhs);
793       end if;
794
795       --  Set Referenced_As_LHS if appropriate. We only set this flag if the
796       --  assignment is a source assignment in the extended main source unit.
797       --  We are not interested in any reference information outside this
798       --  context, or in compiler generated assignment statements.
799
800       if Comes_From_Source (N)
801         and then In_Extended_Main_Source_Unit (Lhs)
802       then
803          Set_Referenced_Modified (Lhs, Out_Param => False);
804       end if;
805
806       --  RM 7.3.2 (12/3): An assignment to a view conversion (from a type
807       --  to one of its ancestors) requires an invariant check. Apply check
808       --  only if expression comes from source, otherwise it will be applied
809       --  when value is assigned to source entity.
810
811       if Nkind (Lhs) = N_Type_Conversion
812         and then Has_Invariants (Etype (Expression (Lhs)))
813         and then Comes_From_Source (Expression (Lhs))
814       then
815          Insert_After (N, Make_Invariant_Call (Expression (Lhs)));
816       end if;
817
818       --  Final step. If left side is an entity, then we may be able to reset
819       --  the current tracked values to new safe values. We only have something
820       --  to do if the left side is an entity name, and expansion has not
821       --  modified the node into something other than an assignment, and of
822       --  course we only capture values if it is safe to do so.
823
824       if Is_Entity_Name (Lhs)
825         and then Nkind (N) = N_Assignment_Statement
826       then
827          declare
828             Ent : constant Entity_Id := Entity (Lhs);
829
830          begin
831             if Safe_To_Capture_Value (N, Ent) then
832
833                --  If simple variable on left side, warn if this assignment
834                --  blots out another one (rendering it useless). We only do
835                --  this for source assignments, otherwise we can generate bogus
836                --  warnings when an assignment is rewritten as another
837                --  assignment, and gets tied up with itself.
838
839                if Warn_On_Modified_Unread
840                  and then Is_Assignable (Ent)
841                  and then Comes_From_Source (N)
842                  and then In_Extended_Main_Source_Unit (Ent)
843                then
844                   Warn_On_Useless_Assignment (Ent, N);
845                end if;
846
847                --  If we are assigning an access type and the left side is an
848                --  entity, then make sure that the Is_Known_[Non_]Null flags
849                --  properly reflect the state of the entity after assignment.
850
851                if Is_Access_Type (T1) then
852                   if Known_Non_Null (Rhs) then
853                      Set_Is_Known_Non_Null (Ent, True);
854
855                   elsif Known_Null (Rhs)
856                     and then not Can_Never_Be_Null (Ent)
857                   then
858                      Set_Is_Known_Null (Ent, True);
859
860                   else
861                      Set_Is_Known_Null (Ent, False);
862
863                      if not Can_Never_Be_Null (Ent) then
864                         Set_Is_Known_Non_Null (Ent, False);
865                      end if;
866                   end if;
867
868                --  For discrete types, we may be able to set the current value
869                --  if the value is known at compile time.
870
871                elsif Is_Discrete_Type (T1)
872                  and then Compile_Time_Known_Value (Rhs)
873                then
874                   Set_Current_Value (Ent, Rhs);
875                else
876                   Set_Current_Value (Ent, Empty);
877                end if;
878
879             --  If not safe to capture values, kill them
880
881             else
882                Kill_Lhs;
883             end if;
884          end;
885       end if;
886
887       --  If assigning to an object in whole or in part, note location of
888       --  assignment in case no one references value. We only do this for
889       --  source assignments, otherwise we can generate bogus warnings when an
890       --  assignment is rewritten as another assignment, and gets tied up with
891       --  itself.
892
893       declare
894          Ent : constant Entity_Id := Get_Enclosing_Object (Lhs);
895       begin
896          if Present (Ent)
897            and then Safe_To_Capture_Value (N, Ent)
898            and then Nkind (N) = N_Assignment_Statement
899            and then Warn_On_Modified_Unread
900            and then Is_Assignable (Ent)
901            and then Comes_From_Source (N)
902            and then In_Extended_Main_Source_Unit (Ent)
903          then
904             Set_Last_Assignment (Ent, Lhs);
905          end if;
906       end;
907
908       Analyze_Dimension (N);
909       Ghost_Mode := Save_Ghost_Mode;
910    end Analyze_Assignment;
911
912    -----------------------------
913    -- Analyze_Block_Statement --
914    -----------------------------
915
916    procedure Analyze_Block_Statement (N : Node_Id) is
917       procedure Install_Return_Entities (Scop : Entity_Id);
918       --  Install all entities of return statement scope Scop in the visibility
919       --  chain except for the return object since its entity is reused in a
920       --  renaming.
921
922       -----------------------------
923       -- Install_Return_Entities --
924       -----------------------------
925
926       procedure Install_Return_Entities (Scop : Entity_Id) is
927          Id : Entity_Id;
928
929       begin
930          Id := First_Entity (Scop);
931          while Present (Id) loop
932
933             --  Do not install the return object
934
935             if not Ekind_In (Id, E_Constant, E_Variable)
936               or else not Is_Return_Object (Id)
937             then
938                Install_Entity (Id);
939             end if;
940
941             Next_Entity (Id);
942          end loop;
943       end Install_Return_Entities;
944
945       --  Local constants and variables
946
947       Decls : constant List_Id := Declarations (N);
948       Id    : constant Node_Id := Identifier (N);
949       HSS   : constant Node_Id := Handled_Statement_Sequence (N);
950
951       Is_BIP_Return_Statement : Boolean;
952
953    --  Start of processing for Analyze_Block_Statement
954
955    begin
956       --  In SPARK mode, we reject block statements. Note that the case of
957       --  block statements generated by the expander is fine.
958
959       if Nkind (Original_Node (N)) = N_Block_Statement then
960          Check_SPARK_05_Restriction ("block statement is not allowed", N);
961       end if;
962
963       --  If no handled statement sequence is present, things are really messed
964       --  up, and we just return immediately (defence against previous errors).
965
966       if No (HSS) then
967          Check_Error_Detected;
968          return;
969       end if;
970
971       --  Detect whether the block is actually a rewritten return statement of
972       --  a build-in-place function.
973
974       Is_BIP_Return_Statement :=
975         Present (Id)
976           and then Present (Entity (Id))
977           and then Ekind (Entity (Id)) = E_Return_Statement
978           and then Is_Build_In_Place_Function
979                      (Return_Applies_To (Entity (Id)));
980
981       --  Normal processing with HSS present
982
983       declare
984          EH  : constant List_Id := Exception_Handlers (HSS);
985          Ent : Entity_Id        := Empty;
986          S   : Entity_Id;
987
988          Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
989          --  Recursively save value of this global, will be restored on exit
990
991       begin
992          --  Initialize unblocked exit count for statements of begin block
993          --  plus one for each exception handler that is present.
994
995          Unblocked_Exit_Count := 1;
996
997          if Present (EH) then
998             Unblocked_Exit_Count := Unblocked_Exit_Count + List_Length (EH);
999          end if;
1000
1001          --  If a label is present analyze it and mark it as referenced
1002
1003          if Present (Id) then
1004             Analyze (Id);
1005             Ent := Entity (Id);
1006
1007             --  An error defense. If we have an identifier, but no entity, then
1008             --  something is wrong. If previous errors, then just remove the
1009             --  identifier and continue, otherwise raise an exception.
1010
1011             if No (Ent) then
1012                Check_Error_Detected;
1013                Set_Identifier (N, Empty);
1014
1015             else
1016                Set_Ekind (Ent, E_Block);
1017                Generate_Reference (Ent, N, ' ');
1018                Generate_Definition (Ent);
1019
1020                if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
1021                   Set_Label_Construct (Parent (Ent), N);
1022                end if;
1023             end if;
1024          end if;
1025
1026          --  If no entity set, create a label entity
1027
1028          if No (Ent) then
1029             Ent := New_Internal_Entity (E_Block, Current_Scope, Sloc (N), 'B');
1030             Set_Identifier (N, New_Occurrence_Of (Ent, Sloc (N)));
1031             Set_Parent (Ent, N);
1032          end if;
1033
1034          Set_Etype (Ent, Standard_Void_Type);
1035          Set_Block_Node (Ent, Identifier (N));
1036          Push_Scope (Ent);
1037
1038          --  The block served as an extended return statement. Ensure that any
1039          --  entities created during the analysis and expansion of the return
1040          --  object declaration are once again visible.
1041
1042          if Is_BIP_Return_Statement then
1043             Install_Return_Entities (Ent);
1044          end if;
1045
1046          if Present (Decls) then
1047             Analyze_Declarations (Decls);
1048             Check_Completion;
1049             Inspect_Deferred_Constant_Completion (Decls);
1050          end if;
1051
1052          Analyze (HSS);
1053          Process_End_Label (HSS, 'e', Ent);
1054
1055          --  If exception handlers are present, then we indicate that enclosing
1056          --  scopes contain a block with handlers. We only need to mark non-
1057          --  generic scopes.
1058
1059          if Present (EH) then
1060             S := Scope (Ent);
1061             loop
1062                Set_Has_Nested_Block_With_Handler (S);
1063                exit when Is_Overloadable (S)
1064                  or else Ekind (S) = E_Package
1065                  or else Is_Generic_Unit (S);
1066                S := Scope (S);
1067             end loop;
1068          end if;
1069
1070          Check_References (Ent);
1071          Warn_On_Useless_Assignments (Ent);
1072          End_Scope;
1073
1074          if Unblocked_Exit_Count = 0 then
1075             Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1076             Check_Unreachable_Code (N);
1077          else
1078             Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1079          end if;
1080       end;
1081    end Analyze_Block_Statement;
1082
1083    --------------------------------
1084    -- Analyze_Compound_Statement --
1085    --------------------------------
1086
1087    procedure Analyze_Compound_Statement (N : Node_Id) is
1088    begin
1089       Analyze_List (Actions (N));
1090    end Analyze_Compound_Statement;
1091
1092    ----------------------------
1093    -- Analyze_Case_Statement --
1094    ----------------------------
1095
1096    procedure Analyze_Case_Statement (N : Node_Id) is
1097       Exp            : Node_Id;
1098       Exp_Type       : Entity_Id;
1099       Exp_Btype      : Entity_Id;
1100       Last_Choice    : Nat;
1101
1102       Others_Present : Boolean;
1103       --  Indicates if Others was present
1104
1105       pragma Warnings (Off, Last_Choice);
1106       --  Don't care about assigned value
1107
1108       Statements_Analyzed : Boolean := False;
1109       --  Set True if at least some statement sequences get analyzed. If False
1110       --  on exit, means we had a serious error that prevented full analysis of
1111       --  the case statement, and as a result it is not a good idea to output
1112       --  warning messages about unreachable code.
1113
1114       Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1115       --  Recursively save value of this global, will be restored on exit
1116
1117       procedure Non_Static_Choice_Error (Choice : Node_Id);
1118       --  Error routine invoked by the generic instantiation below when the
1119       --  case statement has a non static choice.
1120
1121       procedure Process_Statements (Alternative : Node_Id);
1122       --  Analyzes the statements associated with a case alternative. Needed
1123       --  by instantiation below.
1124
1125       package Analyze_Case_Choices is new
1126         Generic_Analyze_Choices
1127           (Process_Associated_Node   => Process_Statements);
1128       use Analyze_Case_Choices;
1129       --  Instantiation of the generic choice analysis package
1130
1131       package Check_Case_Choices is new
1132         Generic_Check_Choices
1133           (Process_Empty_Choice      => No_OP,
1134            Process_Non_Static_Choice => Non_Static_Choice_Error,
1135            Process_Associated_Node   => No_OP);
1136       use Check_Case_Choices;
1137       --  Instantiation of the generic choice processing package
1138
1139       -----------------------------
1140       -- Non_Static_Choice_Error --
1141       -----------------------------
1142
1143       procedure Non_Static_Choice_Error (Choice : Node_Id) is
1144       begin
1145          Flag_Non_Static_Expr
1146            ("choice given in case statement is not static!", Choice);
1147       end Non_Static_Choice_Error;
1148
1149       ------------------------
1150       -- Process_Statements --
1151       ------------------------
1152
1153       procedure Process_Statements (Alternative : Node_Id) is
1154          Choices : constant List_Id := Discrete_Choices (Alternative);
1155          Ent     : Entity_Id;
1156
1157       begin
1158          Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1159          Statements_Analyzed := True;
1160
1161          --  An interesting optimization. If the case statement expression
1162          --  is a simple entity, then we can set the current value within an
1163          --  alternative if the alternative has one possible value.
1164
1165          --    case N is
1166          --      when 1      => alpha
1167          --      when 2 | 3  => beta
1168          --      when others => gamma
1169
1170          --  Here we know that N is initially 1 within alpha, but for beta and
1171          --  gamma, we do not know anything more about the initial value.
1172
1173          if Is_Entity_Name (Exp) then
1174             Ent := Entity (Exp);
1175
1176             if Ekind_In (Ent, E_Variable,
1177                               E_In_Out_Parameter,
1178                               E_Out_Parameter)
1179             then
1180                if List_Length (Choices) = 1
1181                  and then Nkind (First (Choices)) in N_Subexpr
1182                  and then Compile_Time_Known_Value (First (Choices))
1183                then
1184                   Set_Current_Value (Entity (Exp), First (Choices));
1185                end if;
1186
1187                Analyze_Statements (Statements (Alternative));
1188
1189                --  After analyzing the case, set the current value to empty
1190                --  since we won't know what it is for the next alternative
1191                --  (unless reset by this same circuit), or after the case.
1192
1193                Set_Current_Value (Entity (Exp), Empty);
1194                return;
1195             end if;
1196          end if;
1197
1198          --  Case where expression is not an entity name of a variable
1199
1200          Analyze_Statements (Statements (Alternative));
1201       end Process_Statements;
1202
1203    --  Start of processing for Analyze_Case_Statement
1204
1205    begin
1206       Unblocked_Exit_Count := 0;
1207       Exp := Expression (N);
1208       Analyze (Exp);
1209
1210       --  The expression must be of any discrete type. In rare cases, the
1211       --  expander constructs a case statement whose expression has a private
1212       --  type whose full view is discrete. This can happen when generating
1213       --  a stream operation for a variant type after the type is frozen,
1214       --  when the partial of view of the type of the discriminant is private.
1215       --  In that case, use the full view to analyze case alternatives.
1216
1217       if not Is_Overloaded (Exp)
1218         and then not Comes_From_Source (N)
1219         and then Is_Private_Type (Etype (Exp))
1220         and then Present (Full_View (Etype (Exp)))
1221         and then Is_Discrete_Type (Full_View (Etype (Exp)))
1222       then
1223          Resolve (Exp, Etype (Exp));
1224          Exp_Type := Full_View (Etype (Exp));
1225
1226       else
1227          Analyze_And_Resolve (Exp, Any_Discrete);
1228          Exp_Type := Etype (Exp);
1229       end if;
1230
1231       Check_Unset_Reference (Exp);
1232       Exp_Btype := Base_Type (Exp_Type);
1233
1234       --  The expression must be of a discrete type which must be determinable
1235       --  independently of the context in which the expression occurs, but
1236       --  using the fact that the expression must be of a discrete type.
1237       --  Moreover, the type this expression must not be a character literal
1238       --  (which is always ambiguous) or, for Ada-83, a generic formal type.
1239
1240       --  If error already reported by Resolve, nothing more to do
1241
1242       if Exp_Btype = Any_Discrete or else Exp_Btype = Any_Type then
1243          return;
1244
1245       elsif Exp_Btype = Any_Character then
1246          Error_Msg_N
1247            ("character literal as case expression is ambiguous", Exp);
1248          return;
1249
1250       elsif Ada_Version = Ada_83
1251         and then (Is_Generic_Type (Exp_Btype)
1252                    or else Is_Generic_Type (Root_Type (Exp_Btype)))
1253       then
1254          Error_Msg_N
1255            ("(Ada 83) case expression cannot be of a generic type", Exp);
1256          return;
1257       end if;
1258
1259       --  If the case expression is a formal object of mode in out, then treat
1260       --  it as having a nonstatic subtype by forcing use of the base type
1261       --  (which has to get passed to Check_Case_Choices below). Also use base
1262       --  type when the case expression is parenthesized.
1263
1264       if Paren_Count (Exp) > 0
1265         or else (Is_Entity_Name (Exp)
1266                   and then Ekind (Entity (Exp)) = E_Generic_In_Out_Parameter)
1267       then
1268          Exp_Type := Exp_Btype;
1269       end if;
1270
1271       --  Call instantiated procedures to analyzwe and check discrete choices
1272
1273       Analyze_Choices (Alternatives (N), Exp_Type);
1274       Check_Choices (N, Alternatives (N), Exp_Type, Others_Present);
1275
1276       --  Case statement with single OTHERS alternative not allowed in SPARK
1277
1278       if Others_Present and then List_Length (Alternatives (N)) = 1 then
1279          Check_SPARK_05_Restriction
1280            ("OTHERS as unique case alternative is not allowed", N);
1281       end if;
1282
1283       if Exp_Type = Universal_Integer and then not Others_Present then
1284          Error_Msg_N ("case on universal integer requires OTHERS choice", Exp);
1285       end if;
1286
1287       --  If all our exits were blocked by unconditional transfers of control,
1288       --  then the entire CASE statement acts as an unconditional transfer of
1289       --  control, so treat it like one, and check unreachable code. Skip this
1290       --  test if we had serious errors preventing any statement analysis.
1291
1292       if Unblocked_Exit_Count = 0 and then Statements_Analyzed then
1293          Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1294          Check_Unreachable_Code (N);
1295       else
1296          Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1297       end if;
1298
1299       --  If the expander is active it will detect the case of a statically
1300       --  determined single alternative and remove warnings for the case, but
1301       --  if we are not doing expansion, that circuit won't be active. Here we
1302       --  duplicate the effect of removing warnings in the same way, so that
1303       --  we will get the same set of warnings in -gnatc mode.
1304
1305       if not Expander_Active
1306         and then Compile_Time_Known_Value (Expression (N))
1307         and then Serious_Errors_Detected = 0
1308       then
1309          declare
1310             Chosen : constant Node_Id := Find_Static_Alternative (N);
1311             Alt    : Node_Id;
1312
1313          begin
1314             Alt := First (Alternatives (N));
1315             while Present (Alt) loop
1316                if Alt /= Chosen then
1317                   Remove_Warning_Messages (Statements (Alt));
1318                end if;
1319
1320                Next (Alt);
1321             end loop;
1322          end;
1323       end if;
1324    end Analyze_Case_Statement;
1325
1326    ----------------------------
1327    -- Analyze_Exit_Statement --
1328    ----------------------------
1329
1330    --  If the exit includes a name, it must be the name of a currently open
1331    --  loop. Otherwise there must be an innermost open loop on the stack, to
1332    --  which the statement implicitly refers.
1333
1334    --  Additionally, in SPARK mode:
1335
1336    --    The exit can only name the closest enclosing loop;
1337
1338    --    An exit with a when clause must be directly contained in a loop;
1339
1340    --    An exit without a when clause must be directly contained in an
1341    --    if-statement with no elsif or else, which is itself directly contained
1342    --    in a loop. The exit must be the last statement in the if-statement.
1343
1344    procedure Analyze_Exit_Statement (N : Node_Id) is
1345       Target   : constant Node_Id := Name (N);
1346       Cond     : constant Node_Id := Condition (N);
1347       Scope_Id : Entity_Id;
1348       U_Name   : Entity_Id;
1349       Kind     : Entity_Kind;
1350
1351    begin
1352       if No (Cond) then
1353          Check_Unreachable_Code (N);
1354       end if;
1355
1356       if Present (Target) then
1357          Analyze (Target);
1358          U_Name := Entity (Target);
1359
1360          if not In_Open_Scopes (U_Name) or else Ekind (U_Name) /= E_Loop then
1361             Error_Msg_N ("invalid loop name in exit statement", N);
1362             return;
1363
1364          else
1365             if Has_Loop_In_Inner_Open_Scopes (U_Name) then
1366                Check_SPARK_05_Restriction
1367                  ("exit label must name the closest enclosing loop", N);
1368             end if;
1369
1370             Set_Has_Exit (U_Name);
1371          end if;
1372
1373       else
1374          U_Name := Empty;
1375       end if;
1376
1377       for J in reverse 0 .. Scope_Stack.Last loop
1378          Scope_Id := Scope_Stack.Table (J).Entity;
1379          Kind := Ekind (Scope_Id);
1380
1381          if Kind = E_Loop and then (No (Target) or else Scope_Id = U_Name) then
1382             Set_Has_Exit (Scope_Id);
1383             exit;
1384
1385          elsif Kind = E_Block
1386            or else Kind = E_Loop
1387            or else Kind = E_Return_Statement
1388          then
1389             null;
1390
1391          else
1392             Error_Msg_N
1393               ("cannot exit from program unit or accept statement", N);
1394             return;
1395          end if;
1396       end loop;
1397
1398       --  Verify that if present the condition is a Boolean expression
1399
1400       if Present (Cond) then
1401          Analyze_And_Resolve (Cond, Any_Boolean);
1402          Check_Unset_Reference (Cond);
1403       end if;
1404
1405       --  In SPARK mode, verify that the exit statement respects the SPARK
1406       --  restrictions.
1407
1408       if Present (Cond) then
1409          if Nkind (Parent (N)) /= N_Loop_Statement then
1410             Check_SPARK_05_Restriction
1411               ("exit with when clause must be directly in loop", N);
1412          end if;
1413
1414       else
1415          if Nkind (Parent (N)) /= N_If_Statement then
1416             if Nkind (Parent (N)) = N_Elsif_Part then
1417                Check_SPARK_05_Restriction
1418                  ("exit must be in IF without ELSIF", N);
1419             else
1420                Check_SPARK_05_Restriction ("exit must be directly in IF", N);
1421             end if;
1422
1423          elsif Nkind (Parent (Parent (N))) /= N_Loop_Statement then
1424             Check_SPARK_05_Restriction
1425               ("exit must be in IF directly in loop", N);
1426
1427          --  First test the presence of ELSE, so that an exit in an ELSE leads
1428          --  to an error mentioning the ELSE.
1429
1430          elsif Present (Else_Statements (Parent (N))) then
1431             Check_SPARK_05_Restriction ("exit must be in IF without ELSE", N);
1432
1433          --  An exit in an ELSIF does not reach here, as it would have been
1434          --  detected in the case (Nkind (Parent (N)) /= N_If_Statement).
1435
1436          elsif Present (Elsif_Parts (Parent (N))) then
1437             Check_SPARK_05_Restriction ("exit must be in IF without ELSIF", N);
1438          end if;
1439       end if;
1440
1441       --  Chain exit statement to associated loop entity
1442
1443       Set_Next_Exit_Statement  (N, First_Exit_Statement (Scope_Id));
1444       Set_First_Exit_Statement (Scope_Id, N);
1445
1446       --  Since the exit may take us out of a loop, any previous assignment
1447       --  statement is not useless, so clear last assignment indications. It
1448       --  is OK to keep other current values, since if the exit statement
1449       --  does not exit, then the current values are still valid.
1450
1451       Kill_Current_Values (Last_Assignment_Only => True);
1452    end Analyze_Exit_Statement;
1453
1454    ----------------------------
1455    -- Analyze_Goto_Statement --
1456    ----------------------------
1457
1458    procedure Analyze_Goto_Statement (N : Node_Id) is
1459       Label       : constant Node_Id := Name (N);
1460       Scope_Id    : Entity_Id;
1461       Label_Scope : Entity_Id;
1462       Label_Ent   : Entity_Id;
1463
1464    begin
1465       Check_SPARK_05_Restriction ("goto statement is not allowed", N);
1466
1467       --  Actual semantic checks
1468
1469       Check_Unreachable_Code (N);
1470       Kill_Current_Values (Last_Assignment_Only => True);
1471
1472       Analyze (Label);
1473       Label_Ent := Entity (Label);
1474
1475       --  Ignore previous error
1476
1477       if Label_Ent = Any_Id then
1478          Check_Error_Detected;
1479          return;
1480
1481       --  We just have a label as the target of a goto
1482
1483       elsif Ekind (Label_Ent) /= E_Label then
1484          Error_Msg_N ("target of goto statement must be a label", Label);
1485          return;
1486
1487       --  Check that the target of the goto is reachable according to Ada
1488       --  scoping rules. Note: the special gotos we generate for optimizing
1489       --  local handling of exceptions would violate these rules, but we mark
1490       --  such gotos as analyzed when built, so this code is never entered.
1491
1492       elsif not Reachable (Label_Ent) then
1493          Error_Msg_N ("target of goto statement is not reachable", Label);
1494          return;
1495       end if;
1496
1497       --  Here if goto passes initial validity checks
1498
1499       Label_Scope := Enclosing_Scope (Label_Ent);
1500
1501       for J in reverse 0 .. Scope_Stack.Last loop
1502          Scope_Id := Scope_Stack.Table (J).Entity;
1503
1504          if Label_Scope = Scope_Id
1505            or else not Ekind_In (Scope_Id, E_Block, E_Loop, E_Return_Statement)
1506          then
1507             if Scope_Id /= Label_Scope then
1508                Error_Msg_N
1509                  ("cannot exit from program unit or accept statement", N);
1510             end if;
1511
1512             return;
1513          end if;
1514       end loop;
1515
1516       raise Program_Error;
1517    end Analyze_Goto_Statement;
1518
1519    --------------------------
1520    -- Analyze_If_Statement --
1521    --------------------------
1522
1523    --  A special complication arises in the analysis of if statements
1524
1525    --  The expander has circuitry to completely delete code that it can tell
1526    --  will not be executed (as a result of compile time known conditions). In
1527    --  the analyzer, we ensure that code that will be deleted in this manner
1528    --  is analyzed but not expanded. This is obviously more efficient, but
1529    --  more significantly, difficulties arise if code is expanded and then
1530    --  eliminated (e.g. exception table entries disappear). Similarly, itypes
1531    --  generated in deleted code must be frozen from start, because the nodes
1532    --  on which they depend will not be available at the freeze point.
1533
1534    procedure Analyze_If_Statement (N : Node_Id) is
1535       E : Node_Id;
1536
1537       Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1538       --  Recursively save value of this global, will be restored on exit
1539
1540       Save_In_Deleted_Code : Boolean;
1541
1542       Del : Boolean := False;
1543       --  This flag gets set True if a True condition has been found, which
1544       --  means that remaining ELSE/ELSIF parts are deleted.
1545
1546       procedure Analyze_Cond_Then (Cnode : Node_Id);
1547       --  This is applied to either the N_If_Statement node itself or to an
1548       --  N_Elsif_Part node. It deals with analyzing the condition and the THEN
1549       --  statements associated with it.
1550
1551       -----------------------
1552       -- Analyze_Cond_Then --
1553       -----------------------
1554
1555       procedure Analyze_Cond_Then (Cnode : Node_Id) is
1556          Cond : constant Node_Id := Condition (Cnode);
1557          Tstm : constant List_Id := Then_Statements (Cnode);
1558
1559       begin
1560          Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1561          Analyze_And_Resolve (Cond, Any_Boolean);
1562          Check_Unset_Reference (Cond);
1563          Set_Current_Value_Condition (Cnode);
1564
1565          --  If already deleting, then just analyze then statements
1566
1567          if Del then
1568             Analyze_Statements (Tstm);
1569
1570          --  Compile time known value, not deleting yet
1571
1572          elsif Compile_Time_Known_Value (Cond) then
1573             Save_In_Deleted_Code := In_Deleted_Code;
1574
1575             --  If condition is True, then analyze the THEN statements and set
1576             --  no expansion for ELSE and ELSIF parts.
1577
1578             if Is_True (Expr_Value (Cond)) then
1579                Analyze_Statements (Tstm);
1580                Del := True;
1581                Expander_Mode_Save_And_Set (False);
1582                In_Deleted_Code := True;
1583
1584             --  If condition is False, analyze THEN with expansion off
1585
1586             else -- Is_False (Expr_Value (Cond))
1587                Expander_Mode_Save_And_Set (False);
1588                In_Deleted_Code := True;
1589                Analyze_Statements (Tstm);
1590                Expander_Mode_Restore;
1591                In_Deleted_Code := Save_In_Deleted_Code;
1592             end if;
1593
1594          --  Not known at compile time, not deleting, normal analysis
1595
1596          else
1597             Analyze_Statements (Tstm);
1598          end if;
1599       end Analyze_Cond_Then;
1600
1601    --  Start of processing for Analyze_If_Statement
1602
1603    begin
1604       --  Initialize exit count for else statements. If there is no else part,
1605       --  this count will stay non-zero reflecting the fact that the uncovered
1606       --  else case is an unblocked exit.
1607
1608       Unblocked_Exit_Count := 1;
1609       Analyze_Cond_Then (N);
1610
1611       --  Now to analyze the elsif parts if any are present
1612
1613       if Present (Elsif_Parts (N)) then
1614          E := First (Elsif_Parts (N));
1615          while Present (E) loop
1616             Analyze_Cond_Then (E);
1617             Next (E);
1618          end loop;
1619       end if;
1620
1621       if Present (Else_Statements (N)) then
1622          Analyze_Statements (Else_Statements (N));
1623       end if;
1624
1625       --  If all our exits were blocked by unconditional transfers of control,
1626       --  then the entire IF statement acts as an unconditional transfer of
1627       --  control, so treat it like one, and check unreachable code.
1628
1629       if Unblocked_Exit_Count = 0 then
1630          Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1631          Check_Unreachable_Code (N);
1632       else
1633          Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1634       end if;
1635
1636       if Del then
1637          Expander_Mode_Restore;
1638          In_Deleted_Code := Save_In_Deleted_Code;
1639       end if;
1640
1641       if not Expander_Active
1642         and then Compile_Time_Known_Value (Condition (N))
1643         and then Serious_Errors_Detected = 0
1644       then
1645          if Is_True (Expr_Value (Condition (N))) then
1646             Remove_Warning_Messages (Else_Statements (N));
1647
1648             if Present (Elsif_Parts (N)) then
1649                E := First (Elsif_Parts (N));
1650                while Present (E) loop
1651                   Remove_Warning_Messages (Then_Statements (E));
1652                   Next (E);
1653                end loop;
1654             end if;
1655
1656          else
1657             Remove_Warning_Messages (Then_Statements (N));
1658          end if;
1659       end if;
1660
1661       --  Warn on redundant if statement that has no effect
1662
1663       --  Note, we could also check empty ELSIF parts ???
1664
1665       if Warn_On_Redundant_Constructs
1666
1667         --  If statement must be from source
1668
1669         and then Comes_From_Source (N)
1670
1671         --  Condition must not have obvious side effect
1672
1673         and then Has_No_Obvious_Side_Effects (Condition (N))
1674
1675         --  No elsif parts of else part
1676
1677         and then No (Elsif_Parts (N))
1678         and then No (Else_Statements (N))
1679
1680         --  Then must be a single null statement
1681
1682         and then List_Length (Then_Statements (N)) = 1
1683       then
1684          --  Go to original node, since we may have rewritten something as
1685          --  a null statement (e.g. a case we could figure the outcome of).
1686
1687          declare
1688             T : constant Node_Id := First (Then_Statements (N));
1689             S : constant Node_Id := Original_Node (T);
1690
1691          begin
1692             if Comes_From_Source (S) and then Nkind (S) = N_Null_Statement then
1693                Error_Msg_N ("if statement has no effect?r?", N);
1694             end if;
1695          end;
1696       end if;
1697    end Analyze_If_Statement;
1698
1699    ----------------------------------------
1700    -- Analyze_Implicit_Label_Declaration --
1701    ----------------------------------------
1702
1703    --  An implicit label declaration is generated in the innermost enclosing
1704    --  declarative part. This is done for labels, and block and loop names.
1705
1706    --  Note: any changes in this routine may need to be reflected in
1707    --  Analyze_Label_Entity.
1708
1709    procedure Analyze_Implicit_Label_Declaration (N : Node_Id) is
1710       Id : constant Node_Id := Defining_Identifier (N);
1711    begin
1712       Enter_Name          (Id);
1713       Set_Ekind           (Id, E_Label);
1714       Set_Etype           (Id, Standard_Void_Type);
1715       Set_Enclosing_Scope (Id, Current_Scope);
1716    end Analyze_Implicit_Label_Declaration;
1717
1718    ------------------------------
1719    -- Analyze_Iteration_Scheme --
1720    ------------------------------
1721
1722    procedure Analyze_Iteration_Scheme (N : Node_Id) is
1723       Cond      : Node_Id;
1724       Iter_Spec : Node_Id;
1725       Loop_Spec : Node_Id;
1726
1727    begin
1728       --  For an infinite loop, there is no iteration scheme
1729
1730       if No (N) then
1731          return;
1732       end if;
1733
1734       Cond      := Condition (N);
1735       Iter_Spec := Iterator_Specification (N);
1736       Loop_Spec := Loop_Parameter_Specification (N);
1737
1738       if Present (Cond) then
1739          Analyze_And_Resolve (Cond, Any_Boolean);
1740          Check_Unset_Reference (Cond);
1741          Set_Current_Value_Condition (N);
1742
1743       elsif Present (Iter_Spec) then
1744          Analyze_Iterator_Specification (Iter_Spec);
1745
1746       else
1747          Analyze_Loop_Parameter_Specification (Loop_Spec);
1748       end if;
1749    end Analyze_Iteration_Scheme;
1750
1751    ------------------------------------
1752    -- Analyze_Iterator_Specification --
1753    ------------------------------------
1754
1755    procedure Analyze_Iterator_Specification (N : Node_Id) is
1756       Loc       : constant Source_Ptr := Sloc (N);
1757       Def_Id    : constant Node_Id    := Defining_Identifier (N);
1758       Subt      : constant Node_Id    := Subtype_Indication (N);
1759       Iter_Name : constant Node_Id    := Name (N);
1760
1761       Typ : Entity_Id;
1762       Bas : Entity_Id;
1763
1764       procedure Check_Reverse_Iteration (Typ : Entity_Id);
1765       --  For an iteration over a container, if the loop carries the Reverse
1766       --  indicator, verify that the container type has an Iterate aspect that
1767       --  implements the reversible iterator interface.
1768
1769       function Get_Cursor_Type (Typ : Entity_Id) return Entity_Id;
1770       --  For containers with Iterator and related aspects, the cursor is
1771       --  obtained by locating an entity with the proper name in the scope
1772       --  of the type.
1773
1774       -----------------------------
1775       -- Check_Reverse_Iteration --
1776       -----------------------------
1777
1778       procedure Check_Reverse_Iteration (Typ : Entity_Id) is
1779       begin
1780          if Reverse_Present (N)
1781            and then not Is_Array_Type (Typ)
1782            and then not Is_Reversible_Iterator (Typ)
1783          then
1784             Error_Msg_NE
1785               ("container type does not support reverse iteration", N, Typ);
1786          end if;
1787       end Check_Reverse_Iteration;
1788
1789       ---------------------
1790       -- Get_Cursor_Type --
1791       ---------------------
1792
1793       function Get_Cursor_Type (Typ : Entity_Id) return Entity_Id is
1794          Ent : Entity_Id;
1795
1796       begin
1797          --  If iterator type is derived, the cursor is declared in the scope
1798          --  of the parent type.
1799
1800          if Is_Derived_Type (Typ) then
1801             Ent := First_Entity (Scope (Etype (Typ)));
1802          else
1803             Ent := First_Entity (Scope (Typ));
1804          end if;
1805
1806          while Present (Ent) loop
1807             exit when Chars (Ent) = Name_Cursor;
1808             Next_Entity (Ent);
1809          end loop;
1810
1811          if No (Ent) then
1812             return Any_Type;
1813          end if;
1814
1815          --  The cursor is the target of generated assignments in the
1816          --  loop, and cannot have a limited type.
1817
1818          if Is_Limited_Type (Etype (Ent)) then
1819             Error_Msg_N ("cursor type cannot be limited", N);
1820          end if;
1821
1822          return Etype (Ent);
1823       end Get_Cursor_Type;
1824
1825    --   Start of processing for Analyze_iterator_Specification
1826
1827    begin
1828       Enter_Name (Def_Id);
1829
1830       --  AI12-0151 specifies that when the subtype indication is present, it
1831       --  must statically match the type of the array or container element.
1832       --  To simplify this check, we introduce a subtype declaration with the
1833       --  given subtype indication when it carries a constraint, and rewrite
1834       --  the original as a reference to the created subtype entity.
1835
1836       if Present (Subt) then
1837          if Nkind (Subt) = N_Subtype_Indication then
1838             declare
1839                S    : constant Entity_Id := Make_Temporary (Sloc (Subt), 'S');
1840                Decl : constant Node_Id :=
1841                         Make_Subtype_Declaration (Loc,
1842                           Defining_Identifier => S,
1843                           Subtype_Indication  => New_Copy_Tree (Subt));
1844             begin
1845                Insert_Before (Parent (Parent (N)), Decl);
1846                Analyze (Decl);
1847                Rewrite (Subt, New_Occurrence_Of (S, Sloc (Subt)));
1848             end;
1849          else
1850             Analyze (Subt);
1851          end if;
1852
1853          --  Save entity of subtype indication for subsequent check
1854
1855          Bas := Entity (Subt);
1856       end if;
1857
1858       Preanalyze_Range (Iter_Name);
1859
1860       --  Set the kind of the loop variable, which is not visible within
1861       --  the iterator name.
1862
1863       Set_Ekind (Def_Id, E_Variable);
1864
1865       --  Provide a link between the iterator variable and the container, for
1866       --  subsequent use in cross-reference and modification information.
1867
1868       if Of_Present (N) then
1869          Set_Related_Expression (Def_Id, Iter_Name);
1870
1871          --  For a container, the iterator is specified through the aspect
1872
1873          if not Is_Array_Type (Etype (Iter_Name)) then
1874             declare
1875                Iterator : constant Entity_Id :=
1876                             Find_Value_Of_Aspect
1877                               (Etype (Iter_Name), Aspect_Default_Iterator);
1878
1879                I  : Interp_Index;
1880                It : Interp;
1881
1882             begin
1883                if No (Iterator) then
1884                   null;   --  error reported below.
1885
1886                elsif not Is_Overloaded (Iterator) then
1887                   Check_Reverse_Iteration (Etype (Iterator));
1888
1889                --  If Iterator is overloaded, use reversible iterator if
1890                --  one is available.
1891
1892                elsif Is_Overloaded (Iterator) then
1893                   Get_First_Interp (Iterator, I, It);
1894                   while Present (It.Nam) loop
1895                      if Ekind (It.Nam) = E_Function
1896                        and then Is_Reversible_Iterator (Etype (It.Nam))
1897                      then
1898                         Set_Etype (Iterator, It.Typ);
1899                         Set_Entity (Iterator, It.Nam);
1900                         exit;
1901                      end if;
1902
1903                      Get_Next_Interp (I, It);
1904                   end loop;
1905
1906                   Check_Reverse_Iteration (Etype (Iterator));
1907                end if;
1908             end;
1909          end if;
1910       end if;
1911
1912       --  If the domain of iteration is an expression, create a declaration for
1913       --  it, so that finalization actions are introduced outside of the loop.
1914       --  The declaration must be a renaming because the body of the loop may
1915       --  assign to elements.
1916
1917       if not Is_Entity_Name (Iter_Name)
1918
1919         --  When the context is a quantified expression, the renaming
1920         --  declaration is delayed until the expansion phase if we are
1921         --  doing expansion.
1922
1923         and then (Nkind (Parent (N)) /= N_Quantified_Expression
1924                    or else Operating_Mode = Check_Semantics)
1925
1926         --  Do not perform this expansion in SPARK mode, since the formal
1927         --  verification directly deals with the source form of the iterator.
1928         --  Ditto for ASIS, where the temporary may hide the transformation
1929         --  of a selected component into a prefixed function call.
1930
1931         and then not GNATprove_Mode
1932         and then not ASIS_Mode
1933       then
1934          declare
1935             Id    : constant Entity_Id := Make_Temporary (Loc, 'R', Iter_Name);
1936             Decl  : Node_Id;
1937             Act_S : Node_Id;
1938
1939          begin
1940
1941             --  If the domain of iteration is an array component that depends
1942             --  on a discriminant, create actual subtype for it. Pre-analysis
1943             --  does not generate the actual subtype of a selected component.
1944
1945             if Nkind (Iter_Name) = N_Selected_Component
1946               and then Is_Array_Type (Etype (Iter_Name))
1947             then
1948                Act_S :=
1949                  Build_Actual_Subtype_Of_Component
1950                    (Etype (Selector_Name (Iter_Name)), Iter_Name);
1951                Insert_Action (N, Act_S);
1952
1953                if Present (Act_S) then
1954                   Typ := Defining_Identifier (Act_S);
1955                else
1956                   Typ := Etype (Iter_Name);
1957                end if;
1958
1959             else
1960                Typ := Etype (Iter_Name);
1961
1962                --  Verify that the expression produces an iterator
1963
1964                if not Of_Present (N) and then not Is_Iterator (Typ)
1965                  and then not Is_Array_Type (Typ)
1966                  and then No (Find_Aspect (Typ, Aspect_Iterable))
1967                then
1968                   Error_Msg_N
1969                     ("expect object that implements iterator interface",
1970                      Iter_Name);
1971                end if;
1972             end if;
1973
1974             --  Protect against malformed iterator
1975
1976             if Typ = Any_Type then
1977                Error_Msg_N ("invalid expression in loop iterator", Iter_Name);
1978                return;
1979             end if;
1980
1981             if not Of_Present (N) then
1982                Check_Reverse_Iteration (Typ);
1983             end if;
1984
1985             --  The name in the renaming declaration may be a function call.
1986             --  Indicate that it does not come from source, to suppress
1987             --  spurious warnings on renamings of parameterless functions,
1988             --  a common enough idiom in user-defined iterators.
1989
1990             Decl :=
1991               Make_Object_Renaming_Declaration (Loc,
1992                 Defining_Identifier => Id,
1993                 Subtype_Mark        => New_Occurrence_Of (Typ, Loc),
1994                 Name                =>
1995                   New_Copy_Tree (Iter_Name, New_Sloc => Loc));
1996
1997             --  Create a transient scope to ensure that all the temporaries
1998             --  generated by Remove_Side_Effects as part of processing this
1999             --  renaming declaration (if any) are attached by Insert_Actions
2000             --  to it. It has no effect on the generated code if no actions
2001             --  are added to it (see Wrap_Transient_Declaration).
2002
2003             if Expander_Active then
2004                Establish_Transient_Scope (Name (Decl), Sec_Stack => True);
2005             end if;
2006
2007             Insert_Actions (Parent (Parent (N)), New_List (Decl));
2008             Rewrite (Name (N), New_Occurrence_Of (Id, Loc));
2009             Set_Etype (Id, Typ);
2010             Set_Etype (Name (N), Typ);
2011          end;
2012
2013       --  Container is an entity or an array with uncontrolled components, or
2014       --  else it is a container iterator given by a function call, typically
2015       --  called Iterate in the case of predefined containers, even though
2016       --  Iterate is not a reserved name. What matters is that the return type
2017       --  of the function is an iterator type.
2018
2019       elsif Is_Entity_Name (Iter_Name) then
2020          Analyze (Iter_Name);
2021
2022          if Nkind (Iter_Name) = N_Function_Call then
2023             declare
2024                C  : constant Node_Id := Name (Iter_Name);
2025                I  : Interp_Index;
2026                It : Interp;
2027
2028             begin
2029                if not Is_Overloaded (Iter_Name) then
2030                   Resolve (Iter_Name, Etype (C));
2031
2032                else
2033                   Get_First_Interp (C, I, It);
2034                   while It.Typ /= Empty loop
2035                      if Reverse_Present (N) then
2036                         if Is_Reversible_Iterator (It.Typ) then
2037                            Resolve (Iter_Name, It.Typ);
2038                            exit;
2039                         end if;
2040
2041                      elsif Is_Iterator (It.Typ) then
2042                         Resolve (Iter_Name, It.Typ);
2043                         exit;
2044                      end if;
2045
2046                      Get_Next_Interp (I, It);
2047                   end loop;
2048                end if;
2049             end;
2050
2051          --  Domain of iteration is not overloaded
2052
2053          else
2054             Resolve (Iter_Name, Etype (Iter_Name));
2055          end if;
2056
2057          if not Of_Present (N) then
2058             Check_Reverse_Iteration (Etype (Iter_Name));
2059          end if;
2060       end if;
2061
2062       --  Get base type of container, for proper retrieval of Cursor type
2063       --  and primitive operations.
2064
2065       Typ := Base_Type (Etype (Iter_Name));
2066
2067       if Is_Array_Type (Typ) then
2068          if Of_Present (N) then
2069             Set_Etype (Def_Id, Component_Type (Typ));
2070
2071             --  The loop variable is aliased if the array components are
2072             --  aliased.
2073
2074             Set_Is_Aliased (Def_Id, Has_Aliased_Components (Typ));
2075
2076             --  AI12-0047 stipulates that the domain (array or container)
2077             --  cannot be a component that depends on a discriminant if the
2078             --  enclosing object is mutable, to prevent a modification of the
2079             --  dowmain of iteration in the course of an iteration.
2080
2081             --  If the object is an expression it has been captured in a
2082             --  temporary, so examine original node.
2083
2084             if Nkind (Original_Node (Iter_Name)) = N_Selected_Component
2085               and then Is_Dependent_Component_Of_Mutable_Object
2086                          (Original_Node (Iter_Name))
2087             then
2088                Error_Msg_N
2089                  ("iterable name cannot be a discriminant-dependent "
2090                   & "component of a mutable object", N);
2091             end if;
2092
2093             if Present (Subt)
2094               and then
2095                 (Base_Type (Bas) /= Base_Type (Component_Type (Typ))
2096                   or else
2097                     not Subtypes_Statically_Match (Bas, Component_Type (Typ)))
2098             then
2099                Error_Msg_N
2100                  ("subtype indication does not match component type", Subt);
2101             end if;
2102
2103          --  Here we have a missing Range attribute
2104
2105          else
2106             Error_Msg_N
2107               ("missing Range attribute in iteration over an array", N);
2108
2109             --  In Ada 2012 mode, this may be an attempt at an iterator
2110
2111             if Ada_Version >= Ada_2012 then
2112                Error_Msg_NE
2113                  ("\if& is meant to designate an element of the array, use OF",
2114                   N, Def_Id);
2115             end if;
2116
2117             --  Prevent cascaded errors
2118
2119             Set_Ekind (Def_Id, E_Loop_Parameter);
2120             Set_Etype (Def_Id, Etype (First_Index (Typ)));
2121          end if;
2122
2123          --  Check for type error in iterator
2124
2125       elsif Typ = Any_Type then
2126          return;
2127
2128       --  Iteration over a container
2129
2130       else
2131          Set_Ekind (Def_Id, E_Loop_Parameter);
2132          Error_Msg_Ada_2012_Feature ("container iterator", Sloc (N));
2133
2134          --  OF present
2135
2136          if Of_Present (N) then
2137             if Has_Aspect (Typ, Aspect_Iterable) then
2138                declare
2139                   Elt : constant Entity_Id :=
2140                           Get_Iterable_Type_Primitive (Typ, Name_Element);
2141                begin
2142                   if No (Elt) then
2143                      Error_Msg_N
2144                        ("missing Element primitive for iteration", N);
2145                   else
2146                      Set_Etype (Def_Id, Etype (Elt));
2147                   end if;
2148                end;
2149
2150             --  For a predefined container, The type of the loop variable is
2151             --  the Iterator_Element aspect of the container type.
2152
2153             else
2154                declare
2155                   Element     : constant Entity_Id :=
2156                     Find_Value_Of_Aspect (Typ, Aspect_Iterator_Element);
2157                   Iterator    : constant Entity_Id :=
2158                     Find_Value_Of_Aspect (Typ, Aspect_Default_Iterator);
2159                   Cursor_Type : Entity_Id;
2160
2161                begin
2162                   if No (Element) then
2163                      Error_Msg_NE ("cannot iterate over&", N, Typ);
2164                      return;
2165
2166                   else
2167                      Set_Etype (Def_Id, Entity (Element));
2168                      Cursor_Type := Get_Cursor_Type (Typ);
2169                      pragma Assert (Present (Cursor_Type));
2170
2171                      --  If subtype indication was given, verify that it covers
2172                      --  the element type of the container.
2173
2174                      if Present (Subt)
2175                        and then (not Covers (Bas, Etype (Def_Id))
2176                                   or else not Subtypes_Statically_Match
2177                                                 (Bas, Etype (Def_Id)))
2178                      then
2179                         Error_Msg_N
2180                           ("subtype indication does not match element type",
2181                            Subt);
2182                      end if;
2183
2184                      --  If the container has a variable indexing aspect, the
2185                      --  element is a variable and is modifiable in the loop.
2186
2187                      if Has_Aspect (Typ, Aspect_Variable_Indexing) then
2188                         Set_Ekind (Def_Id, E_Variable);
2189                      end if;
2190
2191                      --  If the container is a constant, iterating over it
2192                      --  requires a Constant_Indexing operation.
2193
2194                      if not Is_Variable (Iter_Name)
2195                        and then not Has_Aspect (Typ, Aspect_Constant_Indexing)
2196                      then
2197                         Error_Msg_N ("iteration over constant container "
2198                           & "require constant_indexing aspect", N);
2199
2200                      --  The Iterate function may have an in_out parameter,
2201                      --  and a constant container is thus illegal.
2202
2203                      elsif Present (Iterator)
2204                        and then Ekind (Entity (Iterator)) = E_Function
2205                        and then Ekind (First_Formal (Entity (Iterator))) /=
2206                                   E_In_Parameter
2207                        and then not Is_Variable (Iter_Name)
2208                      then
2209                         Error_Msg_N
2210                           ("variable container expected", N);
2211                      end if;
2212
2213                      if Nkind (Original_Node (Iter_Name))
2214                         = N_Selected_Component
2215                        and then
2216                          Is_Dependent_Component_Of_Mutable_Object
2217                            (Original_Node (Iter_Name))
2218                      then
2219                         Error_Msg_N
2220                           ("container cannot be a discriminant-dependent "
2221                            & "component of a mutable object", N);
2222                      end if;
2223                   end if;
2224                end;
2225             end if;
2226
2227          --  IN iterator, domain is a range, or a call to Iterate function
2228
2229          else
2230             --  For an iteration of the form IN, the name must denote an
2231             --  iterator, typically the result of a call to Iterate. Give a
2232             --  useful error message when the name is a container by itself.
2233
2234             --  The type may be a formal container type, which has to have
2235             --  an Iterable aspect detailing the required primitives.
2236
2237             if Is_Entity_Name (Original_Node (Name (N)))
2238               and then not Is_Iterator (Typ)
2239             then
2240                if Has_Aspect (Typ, Aspect_Iterable) then
2241                   null;
2242
2243                elsif not Has_Aspect (Typ, Aspect_Iterator_Element) then
2244                   Error_Msg_NE
2245                     ("cannot iterate over&", Name (N), Typ);
2246                else
2247                   Error_Msg_N
2248                     ("name must be an iterator, not a container", Name (N));
2249                end if;
2250
2251                if Has_Aspect (Typ, Aspect_Iterable) then
2252                   null;
2253                else
2254                   Error_Msg_NE
2255                     ("\to iterate directly over the elements of a container, "
2256                      & "write `of &`", Name (N), Original_Node (Name (N)));
2257
2258                   --  No point in continuing analysis of iterator spec
2259
2260                   return;
2261                end if;
2262             end if;
2263
2264             --  If the name is a call (typically prefixed) to some Iterate
2265             --  function, it has been rewritten as an object declaration.
2266             --  If that object is a selected component, verify that it is not
2267             --  a component of an unconstrained mutable object.
2268
2269             if Nkind (Iter_Name) = N_Identifier then
2270                declare
2271                   Orig_Node : constant Node_Id := Original_Node (Iter_Name);
2272                   Iter_Kind : constant Node_Kind := Nkind (Orig_Node);
2273                   Obj       : Node_Id;
2274
2275                begin
2276                   if Iter_Kind = N_Selected_Component then
2277                      Obj  := Prefix (Orig_Node);
2278
2279                   elsif Iter_Kind = N_Function_Call then
2280                      Obj  := First_Actual (Orig_Node);
2281
2282                   --  If neither, the name comes from source
2283
2284                   else
2285                      Obj := Iter_Name;
2286                   end if;
2287
2288                   if Nkind (Obj) = N_Selected_Component
2289                     and then Is_Dependent_Component_Of_Mutable_Object (Obj)
2290                   then
2291                      Error_Msg_N
2292                        ("container cannot be a discriminant-dependent "
2293                         & "component of a mutable object", N);
2294                   end if;
2295                end;
2296             end if;
2297
2298             --  The result type of Iterate function is the classwide type of
2299             --  the interface parent. We need the specific Cursor type defined
2300             --  in the container package. We obtain it by name for a predefined
2301             --  container, or through the Iterable aspect for a formal one.
2302
2303             if Has_Aspect (Typ, Aspect_Iterable) then
2304                Set_Etype (Def_Id,
2305                  Get_Cursor_Type
2306                    (Parent (Find_Value_Of_Aspect (Typ, Aspect_Iterable)),
2307                     Typ));
2308
2309             else
2310                Set_Etype (Def_Id, Get_Cursor_Type (Typ));
2311             end if;
2312
2313          end if;
2314       end if;
2315    end Analyze_Iterator_Specification;
2316
2317    -------------------
2318    -- Analyze_Label --
2319    -------------------
2320
2321    --  Note: the semantic work required for analyzing labels (setting them as
2322    --  reachable) was done in a prepass through the statements in the block,
2323    --  so that forward gotos would be properly handled. See Analyze_Statements
2324    --  for further details. The only processing required here is to deal with
2325    --  optimizations that depend on an assumption of sequential control flow,
2326    --  since of course the occurrence of a label breaks this assumption.
2327
2328    procedure Analyze_Label (N : Node_Id) is
2329       pragma Warnings (Off, N);
2330    begin
2331       Kill_Current_Values;
2332    end Analyze_Label;
2333
2334    --------------------------
2335    -- Analyze_Label_Entity --
2336    --------------------------
2337
2338    procedure Analyze_Label_Entity (E : Entity_Id) is
2339    begin
2340       Set_Ekind           (E, E_Label);
2341       Set_Etype           (E, Standard_Void_Type);
2342       Set_Enclosing_Scope (E, Current_Scope);
2343       Set_Reachable       (E, True);
2344    end Analyze_Label_Entity;
2345
2346    ------------------------------------------
2347    -- Analyze_Loop_Parameter_Specification --
2348    ------------------------------------------
2349
2350    procedure Analyze_Loop_Parameter_Specification (N : Node_Id) is
2351       Loop_Nod : constant Node_Id := Parent (Parent (N));
2352
2353       procedure Check_Controlled_Array_Attribute (DS : Node_Id);
2354       --  If the bounds are given by a 'Range reference on a function call
2355       --  that returns a controlled array, introduce an explicit declaration
2356       --  to capture the bounds, so that the function result can be finalized
2357       --  in timely fashion.
2358
2359       procedure Check_Predicate_Use (T : Entity_Id);
2360       --  Diagnose Attempt to iterate through non-static predicate. Note that
2361       --  a type with inherited predicates may have both static and dynamic
2362       --  forms. In this case it is not sufficent to check the static predicate
2363       --  function only, look for a dynamic predicate aspect as well.
2364
2365       function Has_Call_Using_Secondary_Stack (N : Node_Id) return Boolean;
2366       --  N is the node for an arbitrary construct. This function searches the
2367       --  construct N to see if any expressions within it contain function
2368       --  calls that use the secondary stack, returning True if any such call
2369       --  is found, and False otherwise.
2370
2371       procedure Process_Bounds (R : Node_Id);
2372       --  If the iteration is given by a range, create temporaries and
2373       --  assignment statements block to capture the bounds and perform
2374       --  required finalization actions in case a bound includes a function
2375       --  call that uses the temporary stack. We first pre-analyze a copy of
2376       --  the range in order to determine the expected type, and analyze and
2377       --  resolve the original bounds.
2378
2379       --------------------------------------
2380       -- Check_Controlled_Array_Attribute --
2381       --------------------------------------
2382
2383       procedure Check_Controlled_Array_Attribute (DS : Node_Id) is
2384       begin
2385          if Nkind (DS) = N_Attribute_Reference
2386            and then Is_Entity_Name (Prefix (DS))
2387            and then Ekind (Entity (Prefix (DS))) = E_Function
2388            and then Is_Array_Type (Etype (Entity (Prefix (DS))))
2389            and then
2390              Is_Controlled (Component_Type (Etype (Entity (Prefix (DS)))))
2391            and then Expander_Active
2392          then
2393             declare
2394                Loc  : constant Source_Ptr := Sloc (N);
2395                Arr  : constant Entity_Id := Etype (Entity (Prefix (DS)));
2396                Indx : constant Entity_Id :=
2397                         Base_Type (Etype (First_Index (Arr)));
2398                Subt : constant Entity_Id := Make_Temporary (Loc, 'S');
2399                Decl : Node_Id;
2400
2401             begin
2402                Decl :=
2403                  Make_Subtype_Declaration (Loc,
2404                    Defining_Identifier => Subt,
2405                    Subtype_Indication  =>
2406                       Make_Subtype_Indication (Loc,
2407                         Subtype_Mark => New_Occurrence_Of (Indx, Loc),
2408                         Constraint   =>
2409                           Make_Range_Constraint (Loc, Relocate_Node (DS))));
2410                Insert_Before (Loop_Nod, Decl);
2411                Analyze (Decl);
2412
2413                Rewrite (DS,
2414                  Make_Attribute_Reference (Loc,
2415                    Prefix         => New_Occurrence_Of (Subt, Loc),
2416                    Attribute_Name => Attribute_Name (DS)));
2417
2418                Analyze (DS);
2419             end;
2420          end if;
2421       end Check_Controlled_Array_Attribute;
2422
2423       -------------------------
2424       -- Check_Predicate_Use --
2425       -------------------------
2426
2427       procedure Check_Predicate_Use (T : Entity_Id) is
2428       begin
2429          --  A predicated subtype is illegal in loops and related constructs
2430          --  if the predicate is not static, or if it is a non-static subtype
2431          --  of a statically predicated subtype.
2432
2433          if Is_Discrete_Type (T)
2434            and then Has_Predicates (T)
2435            and then (not Has_Static_Predicate (T)
2436                       or else not Is_Static_Subtype (T)
2437                       or else Has_Dynamic_Predicate_Aspect (T))
2438          then
2439             --  Seems a confusing message for the case of a static predicate
2440             --  with a non-static subtype???
2441
2442             Bad_Predicated_Subtype_Use
2443               ("cannot use subtype& with non-static predicate for loop "
2444                & "iteration", Discrete_Subtype_Definition (N),
2445                T, Suggest_Static => True);
2446
2447          elsif Inside_A_Generic and then Is_Generic_Formal (T) then
2448             Set_No_Dynamic_Predicate_On_Actual (T);
2449          end if;
2450       end Check_Predicate_Use;
2451
2452       ------------------------------------
2453       -- Has_Call_Using_Secondary_Stack --
2454       ------------------------------------
2455
2456       function Has_Call_Using_Secondary_Stack (N : Node_Id) return Boolean is
2457
2458          function Check_Call (N : Node_Id) return Traverse_Result;
2459          --  Check if N is a function call which uses the secondary stack
2460
2461          ----------------
2462          -- Check_Call --
2463          ----------------
2464
2465          function Check_Call (N : Node_Id) return Traverse_Result is
2466             Nam        : Node_Id;
2467             Subp       : Entity_Id;
2468             Return_Typ : Entity_Id;
2469
2470          begin
2471             if Nkind (N) = N_Function_Call then
2472                Nam := Name (N);
2473
2474                --  Call using access to subprogram with explicit dereference
2475
2476                if Nkind (Nam) = N_Explicit_Dereference then
2477                   Subp := Etype (Nam);
2478
2479                --  Call using a selected component notation or Ada 2005 object
2480                --  operation notation
2481
2482                elsif Nkind (Nam) = N_Selected_Component then
2483                   Subp := Entity (Selector_Name (Nam));
2484
2485                --  Common case
2486
2487                else
2488                   Subp := Entity (Nam);
2489                end if;
2490
2491                Return_Typ := Etype (Subp);
2492
2493                if Is_Composite_Type (Return_Typ)
2494                  and then not Is_Constrained (Return_Typ)
2495                then
2496                   return Abandon;
2497
2498                elsif Sec_Stack_Needed_For_Return (Subp) then
2499                   return Abandon;
2500                end if;
2501             end if;
2502
2503             --  Continue traversing the tree
2504
2505             return OK;
2506          end Check_Call;
2507
2508          function Check_Calls is new Traverse_Func (Check_Call);
2509
2510       --  Start of processing for Has_Call_Using_Secondary_Stack
2511
2512       begin
2513          return Check_Calls (N) = Abandon;
2514       end Has_Call_Using_Secondary_Stack;
2515
2516       --------------------
2517       -- Process_Bounds --
2518       --------------------
2519
2520       procedure Process_Bounds (R : Node_Id) is
2521          Loc : constant Source_Ptr := Sloc (N);
2522
2523          function One_Bound
2524            (Original_Bound : Node_Id;
2525             Analyzed_Bound : Node_Id;
2526             Typ            : Entity_Id) return Node_Id;
2527          --  Capture value of bound and return captured value
2528
2529          ---------------
2530          -- One_Bound --
2531          ---------------
2532
2533          function One_Bound
2534            (Original_Bound : Node_Id;
2535             Analyzed_Bound : Node_Id;
2536             Typ            : Entity_Id) return Node_Id
2537          is
2538             Assign : Node_Id;
2539             Decl   : Node_Id;
2540             Id     : Entity_Id;
2541
2542          begin
2543             --  If the bound is a constant or an object, no need for a separate
2544             --  declaration. If the bound is the result of previous expansion
2545             --  it is already analyzed and should not be modified. Note that
2546             --  the Bound will be resolved later, if needed, as part of the
2547             --  call to Make_Index (literal bounds may need to be resolved to
2548             --  type Integer).
2549
2550             if Analyzed (Original_Bound) then
2551                return Original_Bound;
2552
2553             elsif Nkind_In (Analyzed_Bound, N_Integer_Literal,
2554                                             N_Character_Literal)
2555               or else Is_Entity_Name (Analyzed_Bound)
2556             then
2557                Analyze_And_Resolve (Original_Bound, Typ);
2558                return Original_Bound;
2559             end if;
2560
2561             --  Normally, the best approach is simply to generate a constant
2562             --  declaration that captures the bound. However, there is a nasty
2563             --  case where this is wrong. If the bound is complex, and has a
2564             --  possible use of the secondary stack, we need to generate a
2565             --  separate assignment statement to ensure the creation of a block
2566             --  which will release the secondary stack.
2567
2568             --  We prefer the constant declaration, since it leaves us with a
2569             --  proper trace of the value, useful in optimizations that get rid
2570             --  of junk range checks.
2571
2572             if not Has_Call_Using_Secondary_Stack (Analyzed_Bound) then
2573                Analyze_And_Resolve (Original_Bound, Typ);
2574
2575                --  Ensure that the bound is valid. This check should not be
2576                --  generated when the range belongs to a quantified expression
2577                --  as the construct is still not expanded into its final form.
2578
2579                if Nkind (Parent (R)) /= N_Loop_Parameter_Specification
2580                  or else Nkind (Parent (Parent (R))) /= N_Quantified_Expression
2581                then
2582                   Ensure_Valid (Original_Bound);
2583                end if;
2584
2585                Force_Evaluation (Original_Bound);
2586                return Original_Bound;
2587             end if;
2588
2589             Id := Make_Temporary (Loc, 'R', Original_Bound);
2590
2591             --  Here we make a declaration with a separate assignment
2592             --  statement, and insert before loop header.
2593
2594             Decl :=
2595               Make_Object_Declaration (Loc,
2596                 Defining_Identifier => Id,
2597                 Object_Definition   => New_Occurrence_Of (Typ, Loc));
2598
2599             Assign :=
2600               Make_Assignment_Statement (Loc,
2601                 Name        => New_Occurrence_Of (Id, Loc),
2602                 Expression  => Relocate_Node (Original_Bound));
2603
2604             Insert_Actions (Loop_Nod, New_List (Decl, Assign));
2605
2606             --  Now that this temporary variable is initialized we decorate it
2607             --  as safe-to-reevaluate to inform to the backend that no further
2608             --  asignment will be issued and hence it can be handled as side
2609             --  effect free. Note that this decoration must be done when the
2610             --  assignment has been analyzed because otherwise it will be
2611             --  rejected (see Analyze_Assignment).
2612
2613             Set_Is_Safe_To_Reevaluate (Id);
2614
2615             Rewrite (Original_Bound, New_Occurrence_Of (Id, Loc));
2616
2617             if Nkind (Assign) = N_Assignment_Statement then
2618                return Expression (Assign);
2619             else
2620                return Original_Bound;
2621             end if;
2622          end One_Bound;
2623
2624          Hi     : constant Node_Id := High_Bound (R);
2625          Lo     : constant Node_Id := Low_Bound  (R);
2626          R_Copy : constant Node_Id := New_Copy_Tree (R);
2627          New_Hi : Node_Id;
2628          New_Lo : Node_Id;
2629          Typ    : Entity_Id;
2630
2631       --  Start of processing for Process_Bounds
2632
2633       begin
2634          Set_Parent (R_Copy, Parent (R));
2635          Preanalyze_Range (R_Copy);
2636          Typ := Etype (R_Copy);
2637
2638          --  If the type of the discrete range is Universal_Integer, then the
2639          --  bound's type must be resolved to Integer, and any object used to
2640          --  hold the bound must also have type Integer, unless the literal
2641          --  bounds are constant-folded expressions with a user-defined type.
2642
2643          if Typ = Universal_Integer then
2644             if Nkind (Lo) = N_Integer_Literal
2645               and then Present (Etype (Lo))
2646               and then Scope (Etype (Lo)) /= Standard_Standard
2647             then
2648                Typ := Etype (Lo);
2649
2650             elsif Nkind (Hi) = N_Integer_Literal
2651               and then Present (Etype (Hi))
2652               and then Scope (Etype (Hi)) /= Standard_Standard
2653             then
2654                Typ := Etype (Hi);
2655
2656             else
2657                Typ := Standard_Integer;
2658             end if;
2659          end if;
2660
2661          Set_Etype (R, Typ);
2662
2663          New_Lo := One_Bound (Lo, Low_Bound  (R_Copy), Typ);
2664          New_Hi := One_Bound (Hi, High_Bound (R_Copy), Typ);
2665
2666          --  Propagate staticness to loop range itself, in case the
2667          --  corresponding subtype is static.
2668
2669          if New_Lo /= Lo and then Is_OK_Static_Expression (New_Lo) then
2670             Rewrite (Low_Bound (R), New_Copy (New_Lo));
2671          end if;
2672
2673          if New_Hi /= Hi and then Is_OK_Static_Expression (New_Hi) then
2674             Rewrite (High_Bound (R), New_Copy (New_Hi));
2675          end if;
2676       end Process_Bounds;
2677
2678       --  Local variables
2679
2680       DS : constant Node_Id   := Discrete_Subtype_Definition (N);
2681       Id : constant Entity_Id := Defining_Identifier (N);
2682
2683       DS_Copy : Node_Id;
2684
2685    --  Start of processing for Analyze_Loop_Parameter_Specification
2686
2687    begin
2688       Enter_Name (Id);
2689
2690       --  We always consider the loop variable to be referenced, since the loop
2691       --  may be used just for counting purposes.
2692
2693       Generate_Reference (Id, N, ' ');
2694
2695       --  Check for the case of loop variable hiding a local variable (used
2696       --  later on to give a nice warning if the hidden variable is never
2697       --  assigned).
2698
2699       declare
2700          H : constant Entity_Id := Homonym (Id);
2701       begin
2702          if Present (H)
2703            and then Ekind (H) = E_Variable
2704            and then Is_Discrete_Type (Etype (H))
2705            and then Enclosing_Dynamic_Scope (H) = Enclosing_Dynamic_Scope (Id)
2706          then
2707             Set_Hiding_Loop_Variable (H, Id);
2708          end if;
2709       end;
2710
2711       --  Loop parameter specification must include subtype mark in SPARK
2712
2713       if Nkind (DS) = N_Range then
2714          Check_SPARK_05_Restriction
2715            ("loop parameter specification must include subtype mark", N);
2716       end if;
2717
2718       --  Analyze the subtype definition and create temporaries for the bounds.
2719       --  Do not evaluate the range when preanalyzing a quantified expression
2720       --  because bounds expressed as function calls with side effects will be
2721       --  incorrectly replicated.
2722
2723       if Nkind (DS) = N_Range
2724         and then Expander_Active
2725         and then Nkind (Parent (N)) /= N_Quantified_Expression
2726       then
2727          Process_Bounds (DS);
2728
2729       --  Either the expander not active or the range of iteration is a subtype
2730       --  indication, an entity, or a function call that yields an aggregate or
2731       --  a container.
2732
2733       else
2734          DS_Copy := New_Copy_Tree (DS);
2735          Set_Parent (DS_Copy, Parent (DS));
2736          Preanalyze_Range (DS_Copy);
2737
2738          --  Ada 2012: If the domain of iteration is:
2739
2740          --  a)  a function call,
2741          --  b)  an identifier that is not a type,
2742          --  c)  an attribute reference 'Old (within a postcondition),
2743          --  d)  an unchecked conversion or a qualified expression with
2744          --      the proper iterator type.
2745
2746          --  then it is an iteration over a container. It was classified as
2747          --  a loop specification by the parser, and must be rewritten now
2748          --  to activate container iteration. The last case will occur within
2749          --  an expanded inlined call, where the expansion wraps an actual in
2750          --  an unchecked conversion when needed. The expression of the
2751          --  conversion is always an object.
2752
2753          if Nkind (DS_Copy) = N_Function_Call
2754
2755            or else (Is_Entity_Name (DS_Copy)
2756                      and then not Is_Type (Entity (DS_Copy)))
2757
2758            or else (Nkind (DS_Copy) = N_Attribute_Reference
2759                      and then Nam_In (Attribute_Name (DS_Copy),
2760                                       Name_Loop_Entry, Name_Old))
2761
2762            or else Has_Aspect (Etype (DS_Copy), Aspect_Iterable)
2763
2764            or else Nkind (DS_Copy) = N_Unchecked_Type_Conversion
2765            or else (Nkind (DS_Copy) = N_Qualified_Expression
2766                      and then Is_Iterator (Etype (DS_Copy)))
2767          then
2768             --  This is an iterator specification. Rewrite it as such and
2769             --  analyze it to capture function calls that may require
2770             --  finalization actions.
2771
2772             declare
2773                I_Spec : constant Node_Id :=
2774                           Make_Iterator_Specification (Sloc (N),
2775                             Defining_Identifier => Relocate_Node (Id),
2776                             Name                => DS_Copy,
2777                             Subtype_Indication  => Empty,
2778                             Reverse_Present     => Reverse_Present (N));
2779                Scheme : constant Node_Id := Parent (N);
2780
2781             begin
2782                Set_Iterator_Specification (Scheme, I_Spec);
2783                Set_Loop_Parameter_Specification (Scheme, Empty);
2784                Analyze_Iterator_Specification (I_Spec);
2785
2786                --  In a generic context, analyze the original domain of
2787                --  iteration, for name capture.
2788
2789                if not Expander_Active then
2790                   Analyze (DS);
2791                end if;
2792
2793                --  Set kind of loop parameter, which may be used in the
2794                --  subsequent analysis of the condition in a quantified
2795                --  expression.
2796
2797                Set_Ekind (Id, E_Loop_Parameter);
2798                return;
2799             end;
2800
2801          --  Domain of iteration is not a function call, and is side-effect
2802          --  free.
2803
2804          else
2805             --  A quantified expression that appears in a pre/post condition
2806             --  is pre-analyzed several times.  If the range is given by an
2807             --  attribute reference it is rewritten as a range, and this is
2808             --  done even with expansion disabled. If the type is already set
2809             --  do not reanalyze, because a range with static bounds may be
2810             --  typed Integer by default.
2811
2812             if Nkind (Parent (N)) = N_Quantified_Expression
2813               and then Present (Etype (DS))
2814             then
2815                null;
2816             else
2817                Analyze (DS);
2818             end if;
2819          end if;
2820       end if;
2821
2822       if DS = Error then
2823          return;
2824       end if;
2825
2826       --  Some additional checks if we are iterating through a type
2827
2828       if Is_Entity_Name (DS)
2829         and then Present (Entity (DS))
2830         and then Is_Type (Entity (DS))
2831       then
2832          --  The subtype indication may denote the completion of an incomplete
2833          --  type declaration.
2834
2835          if Ekind (Entity (DS)) = E_Incomplete_Type then
2836             Set_Entity (DS, Get_Full_View (Entity (DS)));
2837             Set_Etype  (DS, Entity (DS));
2838          end if;
2839
2840          Check_Predicate_Use (Entity (DS));
2841       end if;
2842
2843       --  Error if not discrete type
2844
2845       if not Is_Discrete_Type (Etype (DS)) then
2846          Wrong_Type (DS, Any_Discrete);
2847          Set_Etype (DS, Any_Type);
2848       end if;
2849
2850       Check_Controlled_Array_Attribute (DS);
2851
2852       if Nkind (DS) = N_Subtype_Indication then
2853          Check_Predicate_Use (Entity (Subtype_Mark (DS)));
2854       end if;
2855
2856       Make_Index (DS, N, In_Iter_Schm => True);
2857       Set_Ekind (Id, E_Loop_Parameter);
2858
2859       --  A quantified expression which appears in a pre- or post-condition may
2860       --  be analyzed multiple times. The analysis of the range creates several
2861       --  itypes which reside in different scopes depending on whether the pre-
2862       --  or post-condition has been expanded. Update the type of the loop
2863       --  variable to reflect the proper itype at each stage of analysis.
2864
2865       if No (Etype (Id))
2866         or else Etype (Id) = Any_Type
2867         or else
2868           (Present (Etype (Id))
2869             and then Is_Itype (Etype (Id))
2870             and then Nkind (Parent (Loop_Nod)) = N_Expression_With_Actions
2871             and then Nkind (Original_Node (Parent (Loop_Nod))) =
2872                                                    N_Quantified_Expression)
2873       then
2874          Set_Etype (Id, Etype (DS));
2875       end if;
2876
2877       --  Treat a range as an implicit reference to the type, to inhibit
2878       --  spurious warnings.
2879
2880       Generate_Reference (Base_Type (Etype (DS)), N, ' ');
2881       Set_Is_Known_Valid (Id, True);
2882
2883       --  The loop is not a declarative part, so the loop variable must be
2884       --  frozen explicitly. Do not freeze while preanalyzing a quantified
2885       --  expression because the freeze node will not be inserted into the
2886       --  tree due to flag Is_Spec_Expression being set.
2887
2888       if Nkind (Parent (N)) /= N_Quantified_Expression then
2889          declare
2890             Flist : constant List_Id := Freeze_Entity (Id, N);
2891          begin
2892             if Is_Non_Empty_List (Flist) then
2893                Insert_Actions (N, Flist);
2894             end if;
2895          end;
2896       end if;
2897
2898       --  Case where we have a range or a subtype, get type bounds
2899
2900       if Nkind_In (DS, N_Range, N_Subtype_Indication)
2901         and then not Error_Posted (DS)
2902         and then Etype (DS) /= Any_Type
2903         and then Is_Discrete_Type (Etype (DS))
2904       then
2905          declare
2906             L : Node_Id;
2907             H : Node_Id;
2908
2909          begin
2910             if Nkind (DS) = N_Range then
2911                L := Low_Bound  (DS);
2912                H := High_Bound (DS);
2913             else
2914                L :=
2915                  Type_Low_Bound  (Underlying_Type (Etype (Subtype_Mark (DS))));
2916                H :=
2917                  Type_High_Bound (Underlying_Type (Etype (Subtype_Mark (DS))));
2918             end if;
2919
2920             --  Check for null or possibly null range and issue warning. We
2921             --  suppress such messages in generic templates and instances,
2922             --  because in practice they tend to be dubious in these cases. The
2923             --  check applies as well to rewritten array element loops where a
2924             --  null range may be detected statically.
2925
2926             if Compile_Time_Compare (L, H, Assume_Valid => True) = GT then
2927
2928                --  Suppress the warning if inside a generic template or
2929                --  instance, since in practice they tend to be dubious in these
2930                --  cases since they can result from intended parameterization.
2931
2932                if not Inside_A_Generic and then not In_Instance then
2933
2934                   --  Specialize msg if invalid values could make the loop
2935                   --  non-null after all.
2936
2937                   if Compile_Time_Compare
2938                        (L, H, Assume_Valid => False) = GT
2939                   then
2940                      --  Since we know the range of the loop is null, set the
2941                      --  appropriate flag to remove the loop entirely during
2942                      --  expansion.
2943
2944                      Set_Is_Null_Loop (Loop_Nod);
2945
2946                      if Comes_From_Source (N) then
2947                         Error_Msg_N
2948                           ("??loop range is null, loop will not execute", DS);
2949                      end if;
2950
2951                      --  Here is where the loop could execute because of
2952                      --  invalid values, so issue appropriate message and in
2953                      --  this case we do not set the Is_Null_Loop flag since
2954                      --  the loop may execute.
2955
2956                   elsif Comes_From_Source (N) then
2957                      Error_Msg_N
2958                        ("??loop range may be null, loop may not execute",
2959                         DS);
2960                      Error_Msg_N
2961                        ("??can only execute if invalid values are present",
2962                         DS);
2963                   end if;
2964                end if;
2965
2966                --  In either case, suppress warnings in the body of the loop,
2967                --  since it is likely that these warnings will be inappropriate
2968                --  if the loop never actually executes, which is likely.
2969
2970                Set_Suppress_Loop_Warnings (Loop_Nod);
2971
2972                --  The other case for a warning is a reverse loop where the
2973                --  upper bound is the integer literal zero or one, and the
2974                --  lower bound may exceed this value.
2975
2976                --  For example, we have
2977
2978                --     for J in reverse N .. 1 loop
2979
2980                --  In practice, this is very likely to be a case of reversing
2981                --  the bounds incorrectly in the range.
2982
2983             elsif Reverse_Present (N)
2984               and then Nkind (Original_Node (H)) = N_Integer_Literal
2985               and then
2986                 (Intval (Original_Node (H)) = Uint_0
2987                   or else
2988                  Intval (Original_Node (H)) = Uint_1)
2989             then
2990                --  Lower bound may in fact be known and known not to exceed
2991                --  upper bound (e.g. reverse 0 .. 1) and that's OK.
2992
2993                if Compile_Time_Known_Value (L)
2994                  and then Expr_Value (L) <= Expr_Value (H)
2995                then
2996                   null;
2997
2998                --  Otherwise warning is warranted
2999
3000                else
3001                   Error_Msg_N ("??loop range may be null", DS);
3002                   Error_Msg_N ("\??bounds may be wrong way round", DS);
3003                end if;
3004             end if;
3005
3006             --  Check if either bound is known to be outside the range of the
3007             --  loop parameter type, this is e.g. the case of a loop from
3008             --  20..X where the type is 1..19.
3009
3010             --  Such a loop is dubious since either it raises CE or it executes
3011             --  zero times, and that cannot be useful!
3012
3013             if Etype (DS) /= Any_Type
3014               and then not Error_Posted (DS)
3015               and then Nkind (DS) = N_Subtype_Indication
3016               and then Nkind (Constraint (DS)) = N_Range_Constraint
3017             then
3018                declare
3019                   LLo : constant Node_Id :=
3020                           Low_Bound  (Range_Expression (Constraint (DS)));
3021                   LHi : constant Node_Id :=
3022                           High_Bound (Range_Expression (Constraint (DS)));
3023
3024                   Bad_Bound : Node_Id := Empty;
3025                   --  Suspicious loop bound
3026
3027                begin
3028                   --  At this stage L, H are the bounds of the type, and LLo
3029                   --  Lhi are the low bound and high bound of the loop.
3030
3031                   if Compile_Time_Compare (LLo, L, Assume_Valid => True) = LT
3032                        or else
3033                      Compile_Time_Compare (LLo, H, Assume_Valid => True) = GT
3034                   then
3035                      Bad_Bound := LLo;
3036                   end if;
3037
3038                   if Compile_Time_Compare (LHi, L, Assume_Valid => True) = LT
3039                        or else
3040                      Compile_Time_Compare (LHi, H, Assume_Valid => True) = GT
3041                   then
3042                      Bad_Bound := LHi;
3043                   end if;
3044
3045                   if Present (Bad_Bound) then
3046                      Error_Msg_N
3047                        ("suspicious loop bound out of range of "
3048                         & "loop subtype??", Bad_Bound);
3049                      Error_Msg_N
3050                        ("\loop executes zero times or raises "
3051                         & "Constraint_Error??", Bad_Bound);
3052                   end if;
3053                end;
3054             end if;
3055
3056          --  This declare block is about warnings, if we get an exception while
3057          --  testing for warnings, we simply abandon the attempt silently. This
3058          --  most likely occurs as the result of a previous error, but might
3059          --  just be an obscure case we have missed. In either case, not giving
3060          --  the warning is perfectly acceptable.
3061
3062          exception
3063             when others => null;
3064          end;
3065       end if;
3066
3067       --  A loop parameter cannot be effectively volatile (SPARK RM 7.1.3(4)).
3068       --  This check is relevant only when SPARK_Mode is on as it is not a
3069       --  standard Ada legality check.
3070
3071       if SPARK_Mode = On and then Is_Effectively_Volatile (Id) then
3072          Error_Msg_N ("loop parameter cannot be volatile", Id);
3073       end if;
3074    end Analyze_Loop_Parameter_Specification;
3075
3076    ----------------------------
3077    -- Analyze_Loop_Statement --
3078    ----------------------------
3079
3080    procedure Analyze_Loop_Statement (N : Node_Id) is
3081
3082       function Is_Container_Iterator (Iter : Node_Id) return Boolean;
3083       --  Given a loop iteration scheme, determine whether it is an Ada 2012
3084       --  container iteration.
3085
3086       function Is_Wrapped_In_Block (N : Node_Id) return Boolean;
3087       --  Determine whether loop statement N has been wrapped in a block to
3088       --  capture finalization actions that may be generated for container
3089       --  iterators. Prevents infinite recursion when block is analyzed.
3090       --  Routine is a noop if loop is single statement within source block.
3091
3092       ---------------------------
3093       -- Is_Container_Iterator --
3094       ---------------------------
3095
3096       function Is_Container_Iterator (Iter : Node_Id) return Boolean is
3097       begin
3098          --  Infinite loop
3099
3100          if No (Iter) then
3101             return False;
3102
3103          --  While loop
3104
3105          elsif Present (Condition (Iter)) then
3106             return False;
3107
3108          --  for Def_Id in [reverse] Name loop
3109          --  for Def_Id [: Subtype_Indication] of [reverse] Name loop
3110
3111          elsif Present (Iterator_Specification (Iter)) then
3112             declare
3113                Nam : constant Node_Id := Name (Iterator_Specification (Iter));
3114                Nam_Copy : Node_Id;
3115
3116             begin
3117                Nam_Copy := New_Copy_Tree (Nam);
3118                Set_Parent (Nam_Copy, Parent (Nam));
3119                Preanalyze_Range (Nam_Copy);
3120
3121                --  The only two options here are iteration over a container or
3122                --  an array.
3123
3124                return not Is_Array_Type (Etype (Nam_Copy));
3125             end;
3126
3127          --  for Def_Id in [reverse] Discrete_Subtype_Definition loop
3128
3129          else
3130             declare
3131                LP : constant Node_Id := Loop_Parameter_Specification (Iter);
3132                DS : constant Node_Id := Discrete_Subtype_Definition (LP);
3133                DS_Copy : Node_Id;
3134
3135             begin
3136                DS_Copy := New_Copy_Tree (DS);
3137                Set_Parent (DS_Copy, Parent (DS));
3138                Preanalyze_Range (DS_Copy);
3139
3140                --  Check for a call to Iterate () or an expression with
3141                --  an iterator type.
3142
3143                return
3144                  (Nkind (DS_Copy) = N_Function_Call
3145                    and then Needs_Finalization (Etype (DS_Copy)))
3146                  or else Is_Iterator (Etype (DS_Copy));
3147             end;
3148          end if;
3149       end Is_Container_Iterator;
3150
3151       -------------------------
3152       -- Is_Wrapped_In_Block --
3153       -------------------------
3154
3155       function Is_Wrapped_In_Block (N : Node_Id) return Boolean is
3156          HSS  : Node_Id;
3157          Stat : Node_Id;
3158
3159       begin
3160
3161          --  Check if current scope is a block that is not a transient block.
3162
3163          if Ekind (Current_Scope) /= E_Block
3164            or else No (Block_Node (Current_Scope))
3165          then
3166             return False;
3167
3168          else
3169             HSS  :=
3170               Handled_Statement_Sequence (Parent (Block_Node (Current_Scope)));
3171
3172             --  Skip leading pragmas that may be introduced for invariant and
3173             --  predicate checks.
3174
3175             Stat := First (Statements (HSS));
3176             while Present (Stat) and then Nkind (Stat) = N_Pragma loop
3177                Stat := Next (Stat);
3178             end loop;
3179
3180             return Stat = N and then No (Next (Stat));
3181          end if;
3182       end Is_Wrapped_In_Block;
3183
3184       --  Local declarations
3185
3186       Id   : constant Node_Id := Identifier (N);
3187       Iter : constant Node_Id := Iteration_Scheme (N);
3188       Loc  : constant Source_Ptr := Sloc (N);
3189       Ent  : Entity_Id;
3190       Stmt : Node_Id;
3191
3192    --  Start of processing for Analyze_Loop_Statement
3193
3194    begin
3195       if Present (Id) then
3196
3197          --  Make name visible, e.g. for use in exit statements. Loop labels
3198          --  are always considered to be referenced.
3199
3200          Analyze (Id);
3201          Ent := Entity (Id);
3202
3203          --  Guard against serious error (typically, a scope mismatch when
3204          --  semantic analysis is requested) by creating loop entity to
3205          --  continue analysis.
3206
3207          if No (Ent) then
3208             if Total_Errors_Detected /= 0 then
3209                Ent := New_Internal_Entity (E_Loop, Current_Scope, Loc, 'L');
3210             else
3211                raise Program_Error;
3212             end if;
3213
3214          --  Verify that the loop name is hot hidden by an unrelated
3215          --  declaration in an inner scope.
3216
3217          elsif Ekind (Ent) /= E_Label and then Ekind (Ent) /= E_Loop  then
3218             Error_Msg_Sloc := Sloc (Ent);
3219             Error_Msg_N ("implicit label declaration for & is hidden#", Id);
3220
3221             if Present (Homonym (Ent))
3222               and then Ekind (Homonym (Ent)) = E_Label
3223             then
3224                Set_Entity (Id, Ent);
3225                Set_Ekind (Ent, E_Loop);
3226             end if;
3227
3228          else
3229             Generate_Reference (Ent, N, ' ');
3230             Generate_Definition (Ent);
3231
3232             --  If we found a label, mark its type. If not, ignore it, since it
3233             --  means we have a conflicting declaration, which would already
3234             --  have been diagnosed at declaration time. Set Label_Construct
3235             --  of the implicit label declaration, which is not created by the
3236             --  parser for generic units.
3237
3238             if Ekind (Ent) = E_Label then
3239                Set_Ekind (Ent, E_Loop);
3240
3241                if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
3242                   Set_Label_Construct (Parent (Ent), N);
3243                end if;
3244             end if;
3245          end if;
3246
3247       --  Case of no identifier present. Create one and attach it to the
3248       --  loop statement for use as a scope and as a reference for later
3249       --  expansions. Indicate that the label does not come from source,
3250       --  and attach it to the loop statement so it is part of the tree,
3251       --  even without a full declaration.
3252
3253       else
3254          Ent := New_Internal_Entity (E_Loop, Current_Scope, Loc, 'L');
3255          Set_Etype  (Ent, Standard_Void_Type);
3256          Set_Identifier (N, New_Occurrence_Of (Ent, Loc));
3257          Set_Parent (Ent, N);
3258          Set_Has_Created_Identifier (N);
3259       end if;
3260
3261       --  Iteration over a container in Ada 2012 involves the creation of a
3262       --  controlled iterator object. Wrap the loop in a block to ensure the
3263       --  timely finalization of the iterator and release of container locks.
3264       --  The same applies to the use of secondary stack when obtaining an
3265       --  iterator.
3266
3267       if Ada_Version >= Ada_2012
3268         and then Is_Container_Iterator (Iter)
3269         and then not Is_Wrapped_In_Block (N)
3270       then
3271          declare
3272             Block_Nod : Node_Id;
3273             Block_Id  : Entity_Id;
3274
3275          begin
3276             Block_Nod :=
3277               Make_Block_Statement (Loc,
3278                 Declarations               => New_List,
3279                 Handled_Statement_Sequence =>
3280                   Make_Handled_Sequence_Of_Statements (Loc,
3281                     Statements => New_List (Relocate_Node (N))));
3282
3283             Add_Block_Identifier (Block_Nod, Block_Id);
3284
3285             --  The expansion of iterator loops generates an iterator in order
3286             --  to traverse the elements of a container:
3287
3288             --    Iter : <iterator type> := Iterate (Container)'reference;
3289
3290             --  The iterator is controlled and returned on the secondary stack.
3291             --  The analysis of the call to Iterate establishes a transient
3292             --  scope to deal with the secondary stack management, but never
3293             --  really creates a physical block as this would kill the iterator
3294             --  too early (see Wrap_Transient_Declaration). To address this
3295             --  case, mark the generated block as needing secondary stack
3296             --  management.
3297
3298             Set_Uses_Sec_Stack (Block_Id);
3299
3300             Rewrite (N, Block_Nod);
3301             Analyze (N);
3302             return;
3303          end;
3304       end if;
3305
3306       --  Kill current values on entry to loop, since statements in the body of
3307       --  the loop may have been executed before the loop is entered. Similarly
3308       --  we kill values after the loop, since we do not know that the body of
3309       --  the loop was executed.
3310
3311       Kill_Current_Values;
3312       Push_Scope (Ent);
3313       Analyze_Iteration_Scheme (Iter);
3314
3315       --  Check for following case which merits a warning if the type E of is
3316       --  a multi-dimensional array (and no explicit subscript ranges present).
3317
3318       --      for J in E'Range
3319       --         for K in E'Range
3320
3321       if Present (Iter)
3322         and then Present (Loop_Parameter_Specification (Iter))
3323       then
3324          declare
3325             LPS : constant Node_Id := Loop_Parameter_Specification (Iter);
3326             DSD : constant Node_Id :=
3327                     Original_Node (Discrete_Subtype_Definition (LPS));
3328          begin
3329             if Nkind (DSD) = N_Attribute_Reference
3330               and then Attribute_Name (DSD) = Name_Range
3331               and then No (Expressions (DSD))
3332             then
3333                declare
3334                   Typ : constant Entity_Id := Etype (Prefix (DSD));
3335                begin
3336                   if Is_Array_Type (Typ)
3337                     and then Number_Dimensions (Typ) > 1
3338                     and then Nkind (Parent (N)) = N_Loop_Statement
3339                     and then Present (Iteration_Scheme (Parent (N)))
3340                   then
3341                      declare
3342                         OIter : constant Node_Id :=
3343                           Iteration_Scheme (Parent (N));
3344                         OLPS  : constant Node_Id :=
3345                           Loop_Parameter_Specification (OIter);
3346                         ODSD  : constant Node_Id :=
3347                           Original_Node (Discrete_Subtype_Definition (OLPS));
3348                      begin
3349                         if Nkind (ODSD) = N_Attribute_Reference
3350                           and then Attribute_Name (ODSD) = Name_Range
3351                           and then No (Expressions (ODSD))
3352                           and then Etype (Prefix (ODSD)) = Typ
3353                         then
3354                            Error_Msg_Sloc := Sloc (ODSD);
3355                            Error_Msg_N
3356                              ("inner range same as outer range#??", DSD);
3357                         end if;
3358                      end;
3359                   end if;
3360                end;
3361             end if;
3362          end;
3363       end if;
3364
3365       --  Analyze the statements of the body except in the case of an Ada 2012
3366       --  iterator with the expander active. In this case the expander will do
3367       --  a rewrite of the loop into a while loop. We will then analyze the
3368       --  loop body when we analyze this while loop.
3369
3370       --  We need to do this delay because if the container is for indefinite
3371       --  types the actual subtype of the components will only be determined
3372       --  when the cursor declaration is analyzed.
3373
3374       --  If the expander is not active then we want to analyze the loop body
3375       --  now even in the Ada 2012 iterator case, since the rewriting will not
3376       --  be done. Insert the loop variable in the current scope, if not done
3377       --  when analysing the iteration scheme.  Set its kind properly to detect
3378       --  improper uses in the loop body.
3379
3380       --  In GNATprove mode, we do one of the above depending on the kind of
3381       --  loop. If it is an iterator over an array, then we do not analyze the
3382       --  loop now. We will analyze it after it has been rewritten by the
3383       --  special SPARK expansion which is activated in GNATprove mode. We need
3384       --  to do this so that other expansions that should occur in GNATprove
3385       --  mode take into account the specificities of the rewritten loop, in
3386       --  particular the introduction of a renaming (which needs to be
3387       --  expanded).
3388
3389       --  In other cases in GNATprove mode then we want to analyze the loop
3390       --  body now, since no rewriting will occur.
3391
3392       if Present (Iter)
3393         and then Present (Iterator_Specification (Iter))
3394       then
3395          if GNATprove_Mode
3396            and then Is_Iterator_Over_Array (Iterator_Specification (Iter))
3397          then
3398             null;
3399
3400          elsif not Expander_Active then
3401             declare
3402                I_Spec : constant Node_Id   := Iterator_Specification (Iter);
3403                Id     : constant Entity_Id := Defining_Identifier (I_Spec);
3404
3405             begin
3406                if Scope (Id) /= Current_Scope then
3407                   Enter_Name (Id);
3408                end if;
3409
3410                --  In an element iterator, The loop parameter is a variable if
3411                --  the domain of iteration (container or array) is a variable.
3412
3413                if not Of_Present (I_Spec)
3414                  or else not Is_Variable (Name (I_Spec))
3415                then
3416                   Set_Ekind (Id, E_Loop_Parameter);
3417                end if;
3418             end;
3419
3420             Analyze_Statements (Statements (N));
3421          end if;
3422
3423       else
3424
3425          --  Pre-Ada2012 for-loops and while loops.
3426
3427          Analyze_Statements (Statements (N));
3428       end if;
3429
3430       --  When the iteration scheme of a loop contains attribute 'Loop_Entry,
3431       --  the loop is transformed into a conditional block. Retrieve the loop.
3432
3433       Stmt := N;
3434
3435       if Subject_To_Loop_Entry_Attributes (Stmt) then
3436          Stmt := Find_Loop_In_Conditional_Block (Stmt);
3437       end if;
3438
3439       --  Finish up processing for the loop. We kill all current values, since
3440       --  in general we don't know if the statements in the loop have been
3441       --  executed. We could do a bit better than this with a loop that we
3442       --  know will execute at least once, but it's not worth the trouble and
3443       --  the front end is not in the business of flow tracing.
3444
3445       Process_End_Label (Stmt, 'e', Ent);
3446       End_Scope;
3447       Kill_Current_Values;
3448
3449       --  Check for infinite loop. Skip check for generated code, since it
3450       --  justs waste time and makes debugging the routine called harder.
3451
3452       --  Note that we have to wait till the body of the loop is fully analyzed
3453       --  before making this call, since Check_Infinite_Loop_Warning relies on
3454       --  being able to use semantic visibility information to find references.
3455
3456       if Comes_From_Source (Stmt) then
3457          Check_Infinite_Loop_Warning (Stmt);
3458       end if;
3459
3460       --  Code after loop is unreachable if the loop has no WHILE or FOR and
3461       --  contains no EXIT statements within the body of the loop.
3462
3463       if No (Iter) and then not Has_Exit (Ent) then
3464          Check_Unreachable_Code (Stmt);
3465       end if;
3466    end Analyze_Loop_Statement;
3467
3468    ----------------------------
3469    -- Analyze_Null_Statement --
3470    ----------------------------
3471
3472    --  Note: the semantics of the null statement is implemented by a single
3473    --  null statement, too bad everything isn't as simple as this.
3474
3475    procedure Analyze_Null_Statement (N : Node_Id) is
3476       pragma Warnings (Off, N);
3477    begin
3478       null;
3479    end Analyze_Null_Statement;
3480
3481    ------------------------
3482    -- Analyze_Statements --
3483    ------------------------
3484
3485    procedure Analyze_Statements (L : List_Id) is
3486       S   : Node_Id;
3487       Lab : Entity_Id;
3488
3489    begin
3490       --  The labels declared in the statement list are reachable from
3491       --  statements in the list. We do this as a prepass so that any goto
3492       --  statement will be properly flagged if its target is not reachable.
3493       --  This is not required, but is nice behavior.
3494
3495       S := First (L);
3496       while Present (S) loop
3497          if Nkind (S) = N_Label then
3498             Analyze (Identifier (S));
3499             Lab := Entity (Identifier (S));
3500
3501             --  If we found a label mark it as reachable
3502
3503             if Ekind (Lab) = E_Label then
3504                Generate_Definition (Lab);
3505                Set_Reachable (Lab);
3506
3507                if Nkind (Parent (Lab)) = N_Implicit_Label_Declaration then
3508                   Set_Label_Construct (Parent (Lab), S);
3509                end if;
3510
3511             --  If we failed to find a label, it means the implicit declaration
3512             --  of the label was hidden.  A for-loop parameter can do this to
3513             --  a label with the same name inside the loop, since the implicit
3514             --  label declaration is in the innermost enclosing body or block
3515             --  statement.
3516
3517             else
3518                Error_Msg_Sloc := Sloc (Lab);
3519                Error_Msg_N
3520                  ("implicit label declaration for & is hidden#",
3521                   Identifier (S));
3522             end if;
3523          end if;
3524
3525          Next (S);
3526       end loop;
3527
3528       --  Perform semantic analysis on all statements
3529
3530       Conditional_Statements_Begin;
3531
3532       S := First (L);
3533       while Present (S) loop
3534          Analyze (S);
3535
3536          --  Remove dimension in all statements
3537
3538          Remove_Dimension_In_Statement (S);
3539          Next (S);
3540       end loop;
3541
3542       Conditional_Statements_End;
3543
3544       --  Make labels unreachable. Visibility is not sufficient, because labels
3545       --  in one if-branch for example are not reachable from the other branch,
3546       --  even though their declarations are in the enclosing declarative part.
3547
3548       S := First (L);
3549       while Present (S) loop
3550          if Nkind (S) = N_Label then
3551             Set_Reachable (Entity (Identifier (S)), False);
3552          end if;
3553
3554          Next (S);
3555       end loop;
3556    end Analyze_Statements;
3557
3558    ----------------------------
3559    -- Check_Unreachable_Code --
3560    ----------------------------
3561
3562    procedure Check_Unreachable_Code (N : Node_Id) is
3563       Error_Node : Node_Id;
3564       P          : Node_Id;
3565
3566    begin
3567       if Is_List_Member (N) and then Comes_From_Source (N) then
3568          declare
3569             Nxt : Node_Id;
3570
3571          begin
3572             Nxt := Original_Node (Next (N));
3573
3574             --  Skip past pragmas
3575
3576             while Nkind (Nxt) = N_Pragma loop
3577                Nxt := Original_Node (Next (Nxt));
3578             end loop;
3579
3580             --  If a label follows us, then we never have dead code, since
3581             --  someone could branch to the label, so we just ignore it, unless
3582             --  we are in formal mode where goto statements are not allowed.
3583
3584             if Nkind (Nxt) = N_Label
3585               and then not Restriction_Check_Required (SPARK_05)
3586             then
3587                return;
3588
3589             --  Otherwise see if we have a real statement following us
3590
3591             elsif Present (Nxt)
3592               and then Comes_From_Source (Nxt)
3593               and then Is_Statement (Nxt)
3594             then
3595                --  Special very annoying exception. If we have a return that
3596                --  follows a raise, then we allow it without a warning, since
3597                --  the Ada RM annoyingly requires a useless return here.
3598
3599                if Nkind (Original_Node (N)) /= N_Raise_Statement
3600                  or else Nkind (Nxt) /= N_Simple_Return_Statement
3601                then
3602                   --  The rather strange shenanigans with the warning message
3603                   --  here reflects the fact that Kill_Dead_Code is very good
3604                   --  at removing warnings in deleted code, and this is one
3605                   --  warning we would prefer NOT to have removed.
3606
3607                   Error_Node := Nxt;
3608
3609                   --  If we have unreachable code, analyze and remove the
3610                   --  unreachable code, since it is useless and we don't
3611                   --  want to generate junk warnings.
3612
3613                   --  We skip this step if we are not in code generation mode
3614                   --  or CodePeer mode.
3615
3616                   --  This is the one case where we remove dead code in the
3617                   --  semantics as opposed to the expander, and we do not want
3618                   --  to remove code if we are not in code generation mode,
3619                   --  since this messes up the ASIS trees or loses useful
3620                   --  information in the CodePeer tree.
3621
3622                   --  Note that one might react by moving the whole circuit to
3623                   --  exp_ch5, but then we lose the warning in -gnatc mode.
3624
3625                   if Operating_Mode = Generate_Code
3626                     and then not CodePeer_Mode
3627                   then
3628                      loop
3629                         Nxt := Next (N);
3630
3631                         --  Quit deleting when we have nothing more to delete
3632                         --  or if we hit a label (since someone could transfer
3633                         --  control to a label, so we should not delete it).
3634
3635                         exit when No (Nxt) or else Nkind (Nxt) = N_Label;
3636
3637                         --  Statement/declaration is to be deleted
3638
3639                         Analyze (Nxt);
3640                         Remove (Nxt);
3641                         Kill_Dead_Code (Nxt);
3642                      end loop;
3643                   end if;
3644
3645                   --  Now issue the warning (or error in formal mode)
3646
3647                   if Restriction_Check_Required (SPARK_05) then
3648                      Check_SPARK_05_Restriction
3649                        ("unreachable code is not allowed", Error_Node);
3650                   else
3651                      Error_Msg ("??unreachable code!", Sloc (Error_Node));
3652                   end if;
3653                end if;
3654
3655             --  If the unconditional transfer of control instruction is the
3656             --  last statement of a sequence, then see if our parent is one of
3657             --  the constructs for which we count unblocked exits, and if so,
3658             --  adjust the count.
3659
3660             else
3661                P := Parent (N);
3662
3663                --  Statements in THEN part or ELSE part of IF statement
3664
3665                if Nkind (P) = N_If_Statement then
3666                   null;
3667
3668                --  Statements in ELSIF part of an IF statement
3669
3670                elsif Nkind (P) = N_Elsif_Part then
3671                   P := Parent (P);
3672                   pragma Assert (Nkind (P) = N_If_Statement);
3673
3674                --  Statements in CASE statement alternative
3675
3676                elsif Nkind (P) = N_Case_Statement_Alternative then
3677                   P := Parent (P);
3678                   pragma Assert (Nkind (P) = N_Case_Statement);
3679
3680                --  Statements in body of block
3681
3682                elsif Nkind (P) = N_Handled_Sequence_Of_Statements
3683                  and then Nkind (Parent (P)) = N_Block_Statement
3684                then
3685                   --  The original loop is now placed inside a block statement
3686                   --  due to the expansion of attribute 'Loop_Entry. Return as
3687                   --  this is not a "real" block for the purposes of exit
3688                   --  counting.
3689
3690                   if Nkind (N) = N_Loop_Statement
3691                     and then Subject_To_Loop_Entry_Attributes (N)
3692                   then
3693                      return;
3694                   end if;
3695
3696                --  Statements in exception handler in a block
3697
3698                elsif Nkind (P) = N_Exception_Handler
3699                  and then Nkind (Parent (P)) = N_Handled_Sequence_Of_Statements
3700                  and then Nkind (Parent (Parent (P))) = N_Block_Statement
3701                then
3702                   null;
3703
3704                --  None of these cases, so return
3705
3706                else
3707                   return;
3708                end if;
3709
3710                --  This was one of the cases we are looking for (i.e. the
3711                --  parent construct was IF, CASE or block) so decrement count.
3712
3713                Unblocked_Exit_Count := Unblocked_Exit_Count - 1;
3714             end if;
3715          end;
3716       end if;
3717    end Check_Unreachable_Code;
3718
3719    ----------------------
3720    -- Preanalyze_Range --
3721    ----------------------
3722
3723    procedure Preanalyze_Range (R_Copy : Node_Id) is
3724       Save_Analysis : constant Boolean := Full_Analysis;
3725       Typ           : Entity_Id;
3726
3727    begin
3728       Full_Analysis := False;
3729       Expander_Mode_Save_And_Set (False);
3730
3731       Analyze (R_Copy);
3732
3733       if Nkind (R_Copy) in N_Subexpr and then Is_Overloaded (R_Copy) then
3734
3735          --  Apply preference rules for range of predefined integer types, or
3736          --  diagnose true ambiguity.
3737
3738          declare
3739             I     : Interp_Index;
3740             It    : Interp;
3741             Found : Entity_Id := Empty;
3742
3743          begin
3744             Get_First_Interp (R_Copy, I, It);
3745             while Present (It.Typ) loop
3746                if Is_Discrete_Type (It.Typ) then
3747                   if No (Found) then
3748                      Found := It.Typ;
3749                   else
3750                      if Scope (Found) = Standard_Standard then
3751                         null;
3752
3753                      elsif Scope (It.Typ) = Standard_Standard then
3754                         Found := It.Typ;
3755
3756                      else
3757                         --  Both of them are user-defined
3758
3759                         Error_Msg_N
3760                           ("ambiguous bounds in range of iteration", R_Copy);
3761                         Error_Msg_N ("\possible interpretations:", R_Copy);
3762                         Error_Msg_NE ("\\} ", R_Copy, Found);
3763                         Error_Msg_NE ("\\} ", R_Copy, It.Typ);
3764                         exit;
3765                      end if;
3766                   end if;
3767                end if;
3768
3769                Get_Next_Interp (I, It);
3770             end loop;
3771          end;
3772       end if;
3773
3774       --  Subtype mark in iteration scheme
3775
3776       if Is_Entity_Name (R_Copy) and then Is_Type (Entity (R_Copy)) then
3777          null;
3778
3779       --  Expression in range, or Ada 2012 iterator
3780
3781       elsif Nkind (R_Copy) in N_Subexpr then
3782          Resolve (R_Copy);
3783          Typ := Etype (R_Copy);
3784
3785          if Is_Discrete_Type (Typ) then
3786             null;
3787
3788          --  Check that the resulting object is an iterable container
3789
3790          elsif Has_Aspect (Typ, Aspect_Iterator_Element)
3791            or else Has_Aspect (Typ, Aspect_Constant_Indexing)
3792            or else Has_Aspect (Typ, Aspect_Variable_Indexing)
3793          then
3794             null;
3795
3796          --  The expression may yield an implicit reference to an iterable
3797          --  container. Insert explicit dereference so that proper type is
3798          --  visible in the loop.
3799
3800          elsif Has_Implicit_Dereference (Etype (R_Copy)) then
3801             declare
3802                Disc : Entity_Id;
3803
3804             begin
3805                Disc := First_Discriminant (Typ);
3806                while Present (Disc) loop
3807                   if Has_Implicit_Dereference (Disc) then
3808                      Build_Explicit_Dereference (R_Copy, Disc);
3809                      exit;
3810                   end if;
3811
3812                   Next_Discriminant (Disc);
3813                end loop;
3814             end;
3815
3816          end if;
3817       end if;
3818
3819       Expander_Mode_Restore;
3820       Full_Analysis := Save_Analysis;
3821    end Preanalyze_Range;
3822
3823 end Sem_Ch5;