1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                             S E M _ W A R N                              --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1999-2019, 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
26with Atree;    use Atree;
27with Debug;    use Debug;
28with Einfo;    use Einfo;
29with Errout;   use Errout;
30with Exp_Code; use Exp_Code;
31with Lib;      use Lib;
32with Lib.Xref; use Lib.Xref;
33with Namet;    use Namet;
34with Nlists;   use Nlists;
35with Opt;      use Opt;
36with Par_SCO;  use Par_SCO;
37with Rtsfind;  use Rtsfind;
38with Sem;      use Sem;
39with Sem_Ch8;  use Sem_Ch8;
40with Sem_Aux;  use Sem_Aux;
41with Sem_Eval; use Sem_Eval;
42with Sem_Prag; use Sem_Prag;
43with Sem_Util; use Sem_Util;
44with Sinfo;    use Sinfo;
45with Sinput;   use Sinput;
46with Snames;   use Snames;
47with Stand;    use Stand;
48with Stringt;  use Stringt;
49with Tbuild;   use Tbuild;
50with Uintp;    use Uintp;
51
52package body Sem_Warn is
53
54   --  The following table collects Id's of entities that are potentially
55   --  unreferenced. See Check_Unset_Reference for further details.
56   --  ??? Check_Unset_Reference has zero information about this table.
57
58   package Unreferenced_Entities is new Table.Table (
59     Table_Component_Type => Entity_Id,
60     Table_Index_Type     => Nat,
61     Table_Low_Bound      => 1,
62     Table_Initial        => Alloc.Unreferenced_Entities_Initial,
63     Table_Increment      => Alloc.Unreferenced_Entities_Increment,
64     Table_Name           => "Unreferenced_Entities");
65
66   --  The following table collects potential warnings for IN OUT parameters
67   --  that are referenced but not modified. These warnings are processed when
68   --  the front end calls the procedure Output_Non_Modified_In_Out_Warnings.
69   --  The reason that we defer output of these messages is that we want to
70   --  detect the case where the relevant procedure is used as a generic actual
71   --  in an instantiation, since we suppress the warnings in this case. The
72   --  flag Used_As_Generic_Actual will be set in this case, but only at the
73   --  point of usage. Similarly, we suppress the message if the address of the
74   --  procedure is taken, where the flag Address_Taken may be set later.
75
76   package In_Out_Warnings is new Table.Table (
77     Table_Component_Type => Entity_Id,
78     Table_Index_Type     => Nat,
79     Table_Low_Bound      => 1,
80     Table_Initial        => Alloc.In_Out_Warnings_Initial,
81     Table_Increment      => Alloc.In_Out_Warnings_Increment,
82     Table_Name           => "In_Out_Warnings");
83
84   --------------------------------------------------------
85   -- Handling of Warnings Off, Unmodified, Unreferenced --
86   --------------------------------------------------------
87
88   --  The functions Has_Warnings_Off, Has_Unmodified, Has_Unreferenced must
89   --  generally be used instead of Warnings_Off, Has_Pragma_Unmodified and
90   --  Has_Pragma_Unreferenced, as noted in the specs in Einfo.
91
92   --  In order to avoid losing warnings in -gnatw.w (warn on unnecessary
93   --  warnings off pragma) mode, i.e. to avoid false negatives, the code
94   --  must follow some important rules.
95
96   --  Call these functions as late as possible, after completing all other
97   --  tests, just before the warnings is given. For example, don't write:
98
99   --     if not Has_Warnings_Off (E)
100   --       and then some-other-predicate-on-E then ..
101
102   --  Instead the following is preferred
103
104   --     if some-other-predicate-on-E
105   --       and then Has_Warnings_Off (E)
106
107   --  This way if some-other-predicate is false, we avoid a false indication
108   --  that a Warnings (Off, E) pragma was useful in preventing a warning.
109
110   --  The second rule is that if both Has_Unmodified and Has_Warnings_Off, or
111   --  Has_Unreferenced and Has_Warnings_Off are called, make sure that the
112   --  call to Has_Unmodified/Has_Unreferenced comes first, this way we record
113   --  that the Warnings (Off) could have been Unreferenced or Unmodified. In
114   --  fact Has_Unmodified/Has_Unreferenced includes a test for Warnings Off,
115   --  and so a subsequent test is not needed anyway (though it is harmless).
116
117   -----------------------
118   -- Local Subprograms --
119   -----------------------
120
121   function Generic_Package_Spec_Entity (E : Entity_Id) return Boolean;
122   --  This returns true if the entity E is declared within a generic package.
123   --  The point of this is to detect variables which are not assigned within
124   --  the generic, but might be assigned outside the package for any given
125   --  instance. These are cases where we leave the warnings to be posted for
126   --  the instance, when we will know more.
127
128   function Goto_Spec_Entity (E : Entity_Id) return Entity_Id;
129   --  If E is a parameter entity for a subprogram body, then this function
130   --  returns the corresponding spec entity, if not, E is returned unchanged.
131
132   function Has_Pragma_Unmodified_Check_Spec (E : Entity_Id) return Boolean;
133   --  Tests Has_Pragma_Unmodified flag for entity E. If E is not a formal,
134   --  this is simply the setting of the flag Has_Pragma_Unmodified. If E is
135   --  a body formal, the setting of the flag in the corresponding spec is
136   --  also checked (and True returned if either flag is True).
137
138   function Has_Pragma_Unreferenced_Check_Spec (E : Entity_Id) return Boolean;
139   --  Tests Has_Pragma_Unreferenced flag for entity E. If E is not a formal,
140   --  this is simply the setting of the flag Has_Pragma_Unreferenced. If E is
141   --  a body formal, the setting of the flag in the corresponding spec is
142   --  also checked (and True returned if either flag is True).
143
144   function Is_Attribute_And_Known_Value_Comparison
145     (Op : Node_Id) return Boolean;
146   --  Determine whether operator Op denotes a comparison where the left
147   --  operand is an attribute reference and the value of the right operand is
148   --  known at compile time.
149
150   function Never_Set_In_Source_Check_Spec (E : Entity_Id) return Boolean;
151   --  Tests Never_Set_In_Source status for entity E. If E is not a formal,
152   --  this is simply the setting of the flag Never_Set_In_Source. If E is
153   --  a body formal, the setting of the flag in the corresponding spec is
154   --  also checked (and False returned if either flag is False).
155
156   function Operand_Has_Warnings_Suppressed (N : Node_Id) return Boolean;
157   --  This function traverses the expression tree represented by the node N
158   --  and determines if any sub-operand is a reference to an entity for which
159   --  the Warnings_Off flag is set. True is returned if such an entity is
160   --  encountered, and False otherwise.
161
162   function Referenced_Check_Spec (E : Entity_Id) return Boolean;
163   --  Tests Referenced status for entity E. If E is not a formal, this is
164   --  simply the setting of the flag Referenced. If E is a body formal, the
165   --  setting of the flag in the corresponding spec is also checked (and True
166   --  returned if either flag is True).
167
168   function Referenced_As_LHS_Check_Spec (E : Entity_Id) return Boolean;
169   --  Tests Referenced_As_LHS status for entity E. If E is not a formal, this
170   --  is simply the setting of the flag Referenced_As_LHS. If E is a body
171   --  formal, the setting of the flag in the corresponding spec is also
172   --  checked (and True returned if either flag is True).
173
174   function Referenced_As_Out_Parameter_Check_Spec
175     (E : Entity_Id) return Boolean;
176   --  Tests Referenced_As_Out_Parameter status for entity E. If E is not a
177   --  formal, this is simply the setting of Referenced_As_Out_Parameter. If E
178   --  is a body formal, the setting of the flag in the corresponding spec is
179   --  also checked (and True returned if either flag is True).
180
181   procedure Warn_On_Unreferenced_Entity
182     (Spec_E : Entity_Id;
183      Body_E : Entity_Id := Empty);
184   --  Output warnings for unreferenced entity E. For the case of an entry
185   --  formal, Body_E is the corresponding body entity for a particular
186   --  accept statement, and the message is posted on Body_E. In all other
187   --  cases, Body_E is ignored and must be Empty.
188
189   function Warnings_Off_Check_Spec (E : Entity_Id) return Boolean;
190   --  Returns True if Warnings_Off is set for the entity E or (in the case
191   --  where there is a Spec_Entity), Warnings_Off is set for the Spec_Entity.
192
193   --------------------------
194   -- Check_Code_Statement --
195   --------------------------
196
197   procedure Check_Code_Statement (N : Node_Id) is
198   begin
199      --  If volatile, nothing to worry about
200
201      if Is_Asm_Volatile (N) then
202         return;
203      end if;
204
205      --  Warn if no input or no output
206
207      Setup_Asm_Inputs (N);
208
209      if No (Asm_Input_Value) then
210         Error_Msg_F
211           ("??code statement with no inputs should usually be Volatile!", N);
212         return;
213      end if;
214
215      Setup_Asm_Outputs (N);
216
217      if No (Asm_Output_Variable) then
218         Error_Msg_F
219           ("??code statement with no outputs should usually be Volatile!", N);
220         return;
221      end if;
222   end Check_Code_Statement;
223
224   ---------------------------------
225   -- Check_Infinite_Loop_Warning --
226   ---------------------------------
227
228   --  The case we look for is a while loop which tests a local variable, where
229   --  there is no obvious direct or possible indirect update of the variable
230   --  within the body of the loop.
231
232   procedure Check_Infinite_Loop_Warning (Loop_Statement : Node_Id) is
233      Expression : Node_Id := Empty;
234      --  Set to WHILE or EXIT WHEN condition to be tested
235
236      Ref : Node_Id := Empty;
237      --  Reference in Expression to variable that might not be modified
238      --  in loop, indicating a possible infinite loop.
239
240      Var : Entity_Id := Empty;
241      --  Corresponding entity (entity of Ref)
242
243      Function_Call_Found : Boolean := False;
244      --  True if Find_Var found a function call in the condition
245
246      procedure Find_Var (N : Node_Id);
247      --  Inspect condition to see if it depends on a single entity reference.
248      --  If so, Ref is set to point to the reference node, and Var is set to
249      --  the referenced Entity.
250
251      function Has_Condition_Actions (Iter : Node_Id) return Boolean;
252      --  Determine whether iteration scheme Iter has meaningful condition
253      --  actions.
254
255      function Has_Indirection (T : Entity_Id) return Boolean;
256      --  If the controlling variable is an access type, or is a record type
257      --  with access components, assume that it is changed indirectly and
258      --  suppress the warning. As a concession to low-level programming, in
259      --  particular within Declib, we also suppress warnings on a record
260      --  type that contains components of type Address or Short_Address.
261
262      function Is_Suspicious_Function_Name (E : Entity_Id) return Boolean;
263      --  Given an entity name, see if the name appears to have something to
264      --  do with I/O or network stuff, and if so, return True. Used to kill
265      --  some false positives on a heuristic basis that such functions will
266      --  likely have some strange side effect dependencies. A rather strange
267      --  test, but warning messages are in the heuristics business.
268
269      function Test_Ref (N : Node_Id) return Traverse_Result;
270      --  Test for reference to variable in question. Returns Abandon if
271      --  matching reference found. Used in instantiation of No_Ref_Found.
272
273      function No_Ref_Found is new Traverse_Func (Test_Ref);
274      --  Function to traverse body of procedure. Returns Abandon if matching
275      --  reference found.
276
277      --------------
278      -- Find_Var --
279      --------------
280
281      procedure Find_Var (N : Node_Id) is
282      begin
283         --  Condition is a direct variable reference
284
285         if Is_Entity_Name (N) then
286            Ref := N;
287            Var := Entity (Ref);
288
289         --  Case of condition is a comparison with compile time known value
290
291         elsif Nkind (N) in N_Op_Compare then
292            if Compile_Time_Known_Value (Right_Opnd (N)) then
293               Find_Var (Left_Opnd (N));
294
295            elsif Compile_Time_Known_Value (Left_Opnd (N)) then
296               Find_Var (Right_Opnd (N));
297
298            --  Ignore any other comparison
299
300            else
301               return;
302            end if;
303
304         --  If condition is a negation, check its operand
305
306         elsif Nkind (N) = N_Op_Not then
307            Find_Var (Right_Opnd (N));
308
309         --  Case of condition is function call
310
311         elsif Nkind (N) = N_Function_Call then
312
313            Function_Call_Found := True;
314
315            --  Forget it if function name is not entity, who knows what
316            --  we might be calling?
317
318            if not Is_Entity_Name (Name (N)) then
319               return;
320
321            --  Forget it if function name is suspicious. A strange test
322            --  but warning generation is in the heuristics business.
323
324            elsif Is_Suspicious_Function_Name (Entity (Name (N))) then
325               return;
326
327            --  Forget it if function is marked Volatile_Function
328
329            elsif Is_Volatile_Function (Entity (Name (N))) then
330               return;
331
332            --  Forget it if warnings are suppressed on function entity
333
334            elsif Has_Warnings_Off (Entity (Name (N))) then
335               return;
336
337            --  Forget it if the parameter is not In
338
339            elsif Has_Out_Or_In_Out_Parameter (Entity (Name (N))) then
340               return;
341            end if;
342
343            --  OK, see if we have one argument
344
345            declare
346               PA : constant List_Id := Parameter_Associations (N);
347
348            begin
349               --  One argument, so check the argument
350
351               if Present (PA) and then List_Length (PA) = 1 then
352                  if Nkind (First (PA)) = N_Parameter_Association then
353                     Find_Var (Explicit_Actual_Parameter (First (PA)));
354                  else
355                     Find_Var (First (PA));
356                  end if;
357
358               --  Not one argument
359
360               else
361                  return;
362               end if;
363            end;
364
365         --  Any other kind of node is not something we warn for
366
367         else
368            return;
369         end if;
370      end Find_Var;
371
372      ---------------------------
373      -- Has_Condition_Actions --
374      ---------------------------
375
376      function Has_Condition_Actions (Iter : Node_Id) return Boolean is
377         Action : Node_Id;
378
379      begin
380         --  A call marker is not considered a meaningful action because it
381         --  acts as an annotation and has no runtime semantics.
382
383         Action := First (Condition_Actions (Iter));
384         while Present (Action) loop
385            if Nkind (Action) /= N_Call_Marker then
386               return True;
387            end if;
388
389            Next (Action);
390         end loop;
391
392         return False;
393      end Has_Condition_Actions;
394
395      ---------------------
396      -- Has_Indirection --
397      ---------------------
398
399      function Has_Indirection (T : Entity_Id) return Boolean is
400         Comp : Entity_Id;
401         Rec  : Entity_Id;
402
403      begin
404         if Is_Access_Type (T) then
405            return True;
406
407         elsif Is_Private_Type (T)
408           and then Present (Full_View (T))
409           and then Is_Access_Type (Full_View (T))
410         then
411            return True;
412
413         elsif Is_Record_Type (T) then
414            Rec := T;
415
416         elsif Is_Private_Type (T)
417           and then Present (Full_View (T))
418           and then Is_Record_Type (Full_View (T))
419         then
420            Rec := Full_View (T);
421         else
422            return False;
423         end if;
424
425         Comp := First_Component (Rec);
426         while Present (Comp) loop
427            if Is_Access_Type (Etype (Comp))
428              or else Is_Descendant_Of_Address (Etype (Comp))
429            then
430               return True;
431            end if;
432
433            Next_Component (Comp);
434         end loop;
435
436         return False;
437      end Has_Indirection;
438
439      ---------------------------------
440      -- Is_Suspicious_Function_Name --
441      ---------------------------------
442
443      function Is_Suspicious_Function_Name (E : Entity_Id) return Boolean is
444         S : Entity_Id;
445
446         function Substring_Present (S : String) return Boolean;
447         --  Returns True if name buffer has given string delimited by non-
448         --  alphabetic characters or by end of string. S is lower case.
449
450         -----------------------
451         -- Substring_Present --
452         -----------------------
453
454         function Substring_Present (S : String) return Boolean is
455            Len : constant Natural := S'Length;
456
457         begin
458            for J in 1 .. Name_Len - (Len - 1) loop
459               if Name_Buffer (J .. J + (Len - 1)) = S
460                 and then (J = 1 or else Name_Buffer (J - 1) not in 'a' .. 'z')
461                 and then
462                   (J + Len > Name_Len
463                     or else Name_Buffer (J + Len) not in 'a' .. 'z')
464               then
465                  return True;
466               end if;
467            end loop;
468
469            return False;
470         end Substring_Present;
471
472      --  Start of processing for Is_Suspicious_Function_Name
473
474      begin
475         S := E;
476         while Present (S) and then S /= Standard_Standard loop
477            Get_Name_String (Chars (S));
478
479            if Substring_Present ("io")
480              or else Substring_Present ("file")
481              or else Substring_Present ("network")
482            then
483               return True;
484            else
485               S := Scope (S);
486            end if;
487         end loop;
488
489         return False;
490      end Is_Suspicious_Function_Name;
491
492      --------------
493      -- Test_Ref --
494      --------------
495
496      function Test_Ref (N : Node_Id) return Traverse_Result is
497      begin
498         --  Waste of time to look at the expression we are testing
499
500         if N = Expression then
501            return Skip;
502
503         --  Direct reference to variable in question
504
505         elsif Is_Entity_Name (N)
506           and then Present (Entity (N))
507           and then Entity (N) = Var
508         then
509            --  If this is an lvalue, then definitely abandon, since
510            --  this could be a direct modification of the variable.
511
512            if May_Be_Lvalue (N) then
513               return Abandon;
514            end if;
515
516            --  If the condition contains a function call, we consider it may
517            --  be modified by side effects from a procedure call. Otherwise,
518            --  we consider the condition may not be modified, although that
519            --  might happen if Variable is itself a by-reference parameter,
520            --  and the procedure called modifies the global object referred to
521            --  by Variable, but we actually prefer to issue a warning in this
522            --  odd case. Note that the case where the procedure called has
523            --  visibility over Variable is treated in another case below.
524
525            if Function_Call_Found then
526               declare
527                  P : Node_Id;
528
529               begin
530                  P := N;
531                  loop
532                     P := Parent (P);
533                     exit when P = Loop_Statement;
534
535                     --  Abandon if at procedure call, or something strange is
536                     --  going on (perhaps a node with no parent that should
537                     --  have one but does not?) As always, for a warning we
538                     --  prefer to just abandon the warning than get into the
539                     --  business of complaining about the tree structure here.
540
541                     if No (P)
542                       or else Nkind (P) = N_Procedure_Call_Statement
543                     then
544                        return Abandon;
545                     end if;
546                  end loop;
547               end;
548            end if;
549
550         --  Reference to variable renaming variable in question
551
552         elsif Is_Entity_Name (N)
553           and then Present (Entity (N))
554           and then Ekind (Entity (N)) = E_Variable
555           and then Present (Renamed_Object (Entity (N)))
556           and then Is_Entity_Name (Renamed_Object (Entity (N)))
557           and then Entity (Renamed_Object (Entity (N))) = Var
558           and then May_Be_Lvalue (N)
559         then
560            return Abandon;
561
562         --  Call to subprogram
563
564         elsif Nkind (N) in N_Subprogram_Call then
565
566            --  If subprogram is within the scope of the entity we are dealing
567            --  with as the loop variable, then it could modify this parameter,
568            --  so we abandon in this case. In the case of a subprogram that is
569            --  not an entity we also abandon. The check for no entity being
570            --  present is a defense against previous errors.
571
572            if not Is_Entity_Name (Name (N))
573              or else No (Entity (Name (N)))
574              or else Scope_Within (Entity (Name (N)), Scope (Var))
575            then
576               return Abandon;
577            end if;
578
579            --  If any of the arguments are of type access to subprogram, then
580            --  we may have funny side effects, so no warning in this case.
581
582            declare
583               Actual : Node_Id;
584            begin
585               Actual := First_Actual (N);
586               while Present (Actual) loop
587                  if Is_Access_Subprogram_Type (Etype (Actual)) then
588                     return Abandon;
589                  else
590                     Next_Actual (Actual);
591                  end if;
592               end loop;
593            end;
594
595         --  Declaration of the variable in question
596
597         elsif Nkind (N) = N_Object_Declaration
598           and then Defining_Identifier (N) = Var
599         then
600            return Abandon;
601         end if;
602
603         --  All OK, continue scan
604
605         return OK;
606      end Test_Ref;
607
608   --  Start of processing for Check_Infinite_Loop_Warning
609
610   begin
611      --  Skip processing if debug flag gnatd.w is set
612
613      if Debug_Flag_Dot_W then
614         return;
615      end if;
616
617      --  Deal with Iteration scheme present
618
619      declare
620         Iter : constant Node_Id := Iteration_Scheme (Loop_Statement);
621
622      begin
623         if Present (Iter) then
624
625            --  While iteration
626
627            if Present (Condition (Iter)) then
628
629               --  Skip processing for while iteration with conditions actions,
630               --  since they make it too complicated to get the warning right.
631
632               if Has_Condition_Actions (Iter) then
633                  return;
634               end if;
635
636               --  Capture WHILE condition
637
638               Expression := Condition (Iter);
639
640            --  For Loop_Parameter_Specification, do not process, since loop
641            --  will always terminate. For Iterator_Specification, also do not
642            --  process. Either it will always terminate (e.g. "for X of
643            --  Some_Array ..."), or we can't tell if it's going to terminate
644            --  without looking at the iterator, so any warning here would be
645            --  noise.
646
647            elsif Present (Loop_Parameter_Specification (Iter))
648              or else Present (Iterator_Specification (Iter))
649            then
650               return;
651            end if;
652         end if;
653      end;
654
655      --  Check chain of EXIT statements, we only process loops that have a
656      --  single exit condition (either a single EXIT WHEN statement, or a
657      --  WHILE loop not containing any EXIT WHEN statements).
658
659      declare
660         Ident     : constant Node_Id := Identifier (Loop_Statement);
661         Exit_Stmt : Node_Id;
662
663      begin
664         --  If we don't have a proper chain set, ignore call entirely. This
665         --  happens because of previous errors.
666
667         if No (Entity (Ident))
668           or else Ekind (Entity (Ident)) /= E_Loop
669         then
670            Check_Error_Detected;
671            return;
672         end if;
673
674         --  Otherwise prepare to scan list of EXIT statements
675
676         Exit_Stmt := First_Exit_Statement (Entity (Ident));
677         while Present (Exit_Stmt) loop
678
679            --  Check for EXIT WHEN
680
681            if Present (Condition (Exit_Stmt)) then
682
683               --  Quit processing if EXIT WHEN in WHILE loop, or more than
684               --  one EXIT WHEN statement present in the loop.
685
686               if Present (Expression) then
687                  return;
688
689               --  Otherwise capture condition from EXIT WHEN statement
690
691               else
692                  Expression := Condition (Exit_Stmt);
693               end if;
694
695            --  If an unconditional exit statement is the last statement in the
696            --  loop, assume that no warning is needed, without any attempt at
697            --  checking whether the exit is reachable.
698
699            elsif Exit_Stmt = Last (Statements (Loop_Statement)) then
700               return;
701            end if;
702
703            Exit_Stmt := Next_Exit_Statement (Exit_Stmt);
704         end loop;
705      end;
706
707      --  Return if no condition to test
708
709      if No (Expression) then
710         return;
711      end if;
712
713      --  Initial conditions met, see if condition is of right form
714
715      Find_Var (Expression);
716
717      --  Nothing to do if local variable from source not found. If it's a
718      --  renaming, it is probably renaming something too complicated to deal
719      --  with here.
720
721      if No (Var)
722        or else Ekind (Var) /= E_Variable
723        or else Is_Library_Level_Entity (Var)
724        or else not Comes_From_Source (Var)
725        or else Nkind (Parent (Var)) = N_Object_Renaming_Declaration
726      then
727         return;
728
729      --  Nothing to do if there is some indirection involved (assume that the
730      --  designated variable might be modified in some way we don't see).
731      --  However, if no function call was found, then we don't care about
732      --  indirections, because the condition must be something like "while X
733      --  /= null loop", so we don't care if X.all is modified in the loop.
734
735      elsif Function_Call_Found and then Has_Indirection (Etype (Var)) then
736         return;
737
738      --  Same sort of thing for volatile variable, might be modified by
739      --  some other task or by the operating system in some way.
740
741      elsif Is_Volatile (Var) then
742         return;
743      end if;
744
745      --  Filter out case of original statement sequence starting with delay.
746      --  We assume this is a multi-tasking program and that the condition
747      --  is affected by other threads (some kind of busy wait).
748
749      declare
750         Fstm : constant Node_Id :=
751                  Original_Node (First (Statements (Loop_Statement)));
752      begin
753         if Nkind (Fstm) = N_Delay_Relative_Statement
754           or else Nkind (Fstm) = N_Delay_Until_Statement
755         then
756            return;
757         end if;
758      end;
759
760      --  We have a variable reference of the right form, now we scan the loop
761      --  body to see if it looks like it might not be modified
762
763      if No_Ref_Found (Loop_Statement) = OK then
764         Error_Msg_NE
765           ("??variable& is not modified in loop body!", Ref, Var);
766         Error_Msg_N
767           ("\??possible infinite loop!", Ref);
768      end if;
769   end Check_Infinite_Loop_Warning;
770
771   ----------------------------
772   -- Check_Low_Bound_Tested --
773   ----------------------------
774
775   procedure Check_Low_Bound_Tested (Expr : Node_Id) is
776      procedure Check_Low_Bound_Tested_For (Opnd : Node_Id);
777      --  Determine whether operand Opnd denotes attribute 'First whose prefix
778      --  is a formal parameter. If this is the case, mark the entity of the
779      --  prefix as having its low bound tested.
780
781      --------------------------------
782      -- Check_Low_Bound_Tested_For --
783      --------------------------------
784
785      procedure Check_Low_Bound_Tested_For (Opnd : Node_Id) is
786      begin
787         if Nkind (Opnd) = N_Attribute_Reference
788           and then Attribute_Name (Opnd) = Name_First
789           and then Is_Entity_Name (Prefix (Opnd))
790           and then Present (Entity (Prefix (Opnd)))
791           and then Is_Formal (Entity (Prefix (Opnd)))
792         then
793            Set_Low_Bound_Tested (Entity (Prefix (Opnd)));
794         end if;
795      end Check_Low_Bound_Tested_For;
796
797   --  Start of processing for Check_Low_Bound_Tested
798
799   begin
800      if Comes_From_Source (Expr) then
801         Check_Low_Bound_Tested_For (Left_Opnd  (Expr));
802         Check_Low_Bound_Tested_For (Right_Opnd (Expr));
803      end if;
804   end Check_Low_Bound_Tested;
805
806   ----------------------
807   -- Check_References --
808   ----------------------
809
810   procedure Check_References (E : Entity_Id; Anod : Node_Id := Empty) is
811      E1  : Entity_Id;
812      E1T : Entity_Id;
813      UR  : Node_Id;
814
815      function Body_Formal
816        (E                : Entity_Id;
817         Accept_Statement : Node_Id) return Entity_Id;
818      --  For an entry formal entity from an entry declaration, find the
819      --  corresponding body formal from the given accept statement.
820
821      function Generic_Body_Formal (E : Entity_Id) return Entity_Id;
822      --  Warnings on unused formals of subprograms are placed on the entity
823      --  in the subprogram body, which seems preferable because it suggests
824      --  a better codefix for GNAT Studio. The analysis of generic subprogram
825      --  bodies uses a different circuitry, so the choice for the proper
826      --  placement of the warning in the generic case takes place here, by
827      --  finding the body entity that corresponds to a formal in a spec.
828
829      procedure May_Need_Initialized_Actual (Ent : Entity_Id);
830      --  If an entity of a generic type has default initialization, then the
831      --  corresponding actual type should be fully initialized, or else there
832      --  will be uninitialized components in the instantiation, that might go
833      --  unreported. This routine marks the type of the uninitialized variable
834      --  appropriately to allow the compiler to emit an appropriate warning
835      --  in the instance. In a sense, the use of a type that requires full
836      --  initialization is a weak part of the generic contract.
837
838      function Missing_Subunits return Boolean;
839      --  We suppress warnings when there are missing subunits, because this
840      --  may generate too many false positives: entities in a parent may only
841      --  be referenced in one of the subunits. We make an exception for
842      --  subunits that contain no other stubs.
843
844      procedure Output_Reference_Error (M : String);
845      --  Used to output an error message. Deals with posting the error on the
846      --  body formal in the accept case.
847
848      function Publicly_Referenceable (Ent : Entity_Id) return Boolean;
849      --  This is true if the entity in question is potentially referenceable
850      --  from another unit. This is true for entities in packages that are at
851      --  the library level.
852
853      function Warnings_Off_E1 return Boolean;
854      --  Return True if Warnings_Off is set for E1, or for its Etype (E1T),
855      --  or for the base type of E1T.
856
857      -----------------
858      -- Body_Formal --
859      -----------------
860
861      function Body_Formal
862        (E                : Entity_Id;
863         Accept_Statement : Node_Id) return Entity_Id
864      is
865         Body_Param : Node_Id;
866         Body_E     : Entity_Id;
867
868      begin
869         --  Loop to find matching parameter in accept statement
870
871         Body_Param := First (Parameter_Specifications (Accept_Statement));
872         while Present (Body_Param) loop
873            Body_E := Defining_Identifier (Body_Param);
874
875            if Chars (Body_E) = Chars (E) then
876               return Body_E;
877            end if;
878
879            Next (Body_Param);
880         end loop;
881
882         --  Should never fall through, should always find a match
883
884         raise Program_Error;
885      end Body_Formal;
886
887      -------------------------
888      -- Generic_Body_Formal --
889      -------------------------
890
891      function Generic_Body_Formal (E : Entity_Id) return Entity_Id is
892         Gen_Decl : constant Node_Id   := Unit_Declaration_Node (Scope (E));
893         Gen_Body : constant Entity_Id := Corresponding_Body (Gen_Decl);
894         Form     : Entity_Id;
895
896      begin
897         if No (Gen_Body) then
898            return E;
899
900         else
901            Form := First_Entity (Gen_Body);
902            while Present (Form) loop
903               if Chars (Form) = Chars (E) then
904                  return Form;
905               end if;
906
907               Next_Entity (Form);
908            end loop;
909         end if;
910
911         --  Should never fall through, should always find a match
912
913         raise Program_Error;
914      end Generic_Body_Formal;
915
916      ---------------------------------
917      -- May_Need_Initialized_Actual --
918      ---------------------------------
919
920      procedure May_Need_Initialized_Actual (Ent : Entity_Id) is
921         T   : constant Entity_Id := Etype (Ent);
922         Par : constant Node_Id   := Parent (T);
923
924      begin
925         if not Is_Generic_Type (T) then
926            null;
927
928         elsif (Nkind (Par)) = N_Private_Extension_Declaration then
929
930            --  We only indicate the first such variable in the generic.
931
932            if No (Uninitialized_Variable (Par)) then
933               Set_Uninitialized_Variable (Par, Ent);
934            end if;
935
936         elsif (Nkind (Par)) = N_Formal_Type_Declaration
937           and then Nkind (Formal_Type_Definition (Par)) =
938                                         N_Formal_Private_Type_Definition
939         then
940            if No (Uninitialized_Variable (Formal_Type_Definition (Par))) then
941               Set_Uninitialized_Variable (Formal_Type_Definition (Par), Ent);
942            end if;
943         end if;
944      end May_Need_Initialized_Actual;
945
946      ----------------------
947      -- Missing_Subunits --
948      ----------------------
949
950      function Missing_Subunits return Boolean is
951         D : Node_Id;
952
953      begin
954         if not Unloaded_Subunits then
955
956            --  Normal compilation, all subunits are present
957
958            return False;
959
960         elsif E /= Main_Unit_Entity then
961
962            --  No warnings on a stub that is not the main unit
963
964            return True;
965
966         elsif Nkind (Unit_Declaration_Node (E)) in N_Proper_Body then
967            D := First (Declarations (Unit_Declaration_Node (E)));
968            while Present (D) loop
969
970               --  No warnings if the proper body contains nested stubs
971
972               if Nkind (D) in N_Body_Stub then
973                  return True;
974               end if;
975
976               Next (D);
977            end loop;
978
979            return False;
980
981         else
982            --  Missing stubs elsewhere
983
984            return True;
985         end if;
986      end Missing_Subunits;
987
988      ----------------------------
989      -- Output_Reference_Error --
990      ----------------------------
991
992      procedure Output_Reference_Error (M : String) is
993      begin
994         --  Never issue messages for internal names or renamings
995
996         if Is_Internal_Name (Chars (E1))
997           or else Nkind (Parent (E1)) = N_Object_Renaming_Declaration
998         then
999            return;
1000         end if;
1001
1002         --  Don't output message for IN OUT formal unless we have the warning
1003         --  flag specifically set. It is a bit odd to distinguish IN OUT
1004         --  formals from other cases. This distinction is historical in
1005         --  nature. Warnings for IN OUT formals were added fairly late.
1006
1007         if Ekind (E1) = E_In_Out_Parameter
1008           and then not Check_Unreferenced_Formals
1009         then
1010            return;
1011         end if;
1012
1013         --  Other than accept case, post error on defining identifier
1014
1015         if No (Anod) then
1016            Error_Msg_N (M, E1);
1017
1018         --  Accept case, find body formal to post the message
1019
1020         else
1021            Error_Msg_NE (M, Body_Formal (E1, Accept_Statement => Anod), E1);
1022
1023         end if;
1024      end Output_Reference_Error;
1025
1026      ----------------------------
1027      -- Publicly_Referenceable --
1028      ----------------------------
1029
1030      function Publicly_Referenceable (Ent : Entity_Id) return Boolean is
1031         P    : Node_Id;
1032         Prev : Node_Id;
1033
1034      begin
1035         --  A formal parameter is never referenceable outside the body of its
1036         --  subprogram or entry.
1037
1038         if Is_Formal (Ent) then
1039            return False;
1040         end if;
1041
1042         --  Examine parents to look for a library level package spec. But if
1043         --  we find a body or block or other similar construct along the way,
1044         --  we cannot be referenced.
1045
1046         Prev := Ent;
1047         P    := Parent (Ent);
1048         loop
1049            case Nkind (P) is
1050
1051               --  If we get to top of tree, then publicly referenceable
1052
1053               when N_Empty =>
1054                  return True;
1055
1056               --  If we reach a generic package declaration, then always
1057               --  consider this referenceable, since any instantiation will
1058               --  have access to the entities in the generic package. Note
1059               --  that the package itself may not be instantiated, but then
1060               --  we will get a warning for the package entity.
1061
1062               --  Note that generic formal parameters are themselves not
1063               --  publicly referenceable in an instance, and warnings on them
1064               --  are useful.
1065
1066               when N_Generic_Package_Declaration =>
1067                  return
1068                    not Is_List_Member (Prev)
1069                      or else List_Containing (Prev) /=
1070                                            Generic_Formal_Declarations (P);
1071
1072               --  Similarly, the generic formals of a generic subprogram are
1073               --  not accessible.
1074
1075               when N_Generic_Subprogram_Declaration =>
1076                  if Is_List_Member (Prev)
1077                    and then List_Containing (Prev) =
1078                               Generic_Formal_Declarations (P)
1079                  then
1080                     return False;
1081                  else
1082                     P := Parent (P);
1083                  end if;
1084
1085               --  If we reach a subprogram body, entity is not referenceable
1086               --  unless it is the defining entity of the body. This will
1087               --  happen, e.g. when a function is an attribute renaming that
1088               --  is rewritten as a body.
1089
1090               when N_Subprogram_Body  =>
1091                  if Ent /= Defining_Entity (P) then
1092                     return False;
1093                  else
1094                     P := Parent (P);
1095                  end if;
1096
1097               --  If we reach any other body, definitely not referenceable
1098
1099               when N_Block_Statement
1100                  | N_Entry_Body
1101                  | N_Package_Body
1102                  | N_Protected_Body
1103                  | N_Subunit
1104                  | N_Task_Body
1105               =>
1106                  return False;
1107
1108               --  For all other cases, keep looking up tree
1109
1110               when others =>
1111                  Prev := P;
1112                  P    := Parent (P);
1113            end case;
1114         end loop;
1115      end Publicly_Referenceable;
1116
1117      ---------------------
1118      -- Warnings_Off_E1 --
1119      ---------------------
1120
1121      function Warnings_Off_E1 return Boolean is
1122      begin
1123         return Has_Warnings_Off (E1T)
1124           or else Has_Warnings_Off (Base_Type (E1T))
1125           or else Warnings_Off_Check_Spec (E1);
1126      end Warnings_Off_E1;
1127
1128   --  Start of processing for Check_References
1129
1130   begin
1131      Process_Deferred_References;
1132
1133      --  No messages if warnings are suppressed, or if we have detected any
1134      --  real errors so far (this last check avoids junk messages resulting
1135      --  from errors, e.g. a subunit that is not loaded).
1136
1137      if Warning_Mode = Suppress or else Serious_Errors_Detected /= 0 then
1138         return;
1139      end if;
1140
1141      --  We also skip the messages if any subunits were not loaded (see
1142      --  comment in Sem_Ch10 to understand how this is set, and why it is
1143      --  necessary to suppress the warnings in this case).
1144
1145      if Missing_Subunits then
1146         return;
1147      end if;
1148
1149      --  Otherwise loop through entities, looking for suspicious stuff
1150
1151      E1 := First_Entity (E);
1152      while Present (E1) loop
1153         E1T := Etype (E1);
1154
1155         --  We are only interested in source entities. We also don't issue
1156         --  warnings within instances, since the proper place for such
1157         --  warnings is on the template when it is compiled, and we don't
1158         --  issue warnings for variables with names like Junk, Discard etc.
1159
1160         if Comes_From_Source (E1)
1161           and then Instantiation_Location (Sloc (E1)) = No_Location
1162         then
1163            --  We are interested in variables and out/in-out parameters, but
1164            --  we exclude protected types, too complicated to worry about.
1165
1166            if Ekind (E1) = E_Variable
1167              or else
1168                (Ekind_In (E1, E_Out_Parameter, E_In_Out_Parameter)
1169                  and then not Is_Protected_Type (Current_Scope))
1170            then
1171               --  If the formal has a class-wide type, retrieve its type
1172               --  because checks below depend on its private nature.
1173
1174               if Is_Class_Wide_Type (E1T) then
1175                  E1T := Etype (E1T);
1176               end if;
1177
1178               --  Case of an unassigned variable
1179
1180               --  First gather any Unset_Reference indication for E1. In the
1181               --  case of a parameter, it is the Spec_Entity that is relevant.
1182
1183               if Ekind (E1) = E_Out_Parameter
1184                 and then Present (Spec_Entity (E1))
1185               then
1186                  UR := Unset_Reference (Spec_Entity (E1));
1187               else
1188                  UR := Unset_Reference (E1);
1189               end if;
1190
1191               --  Special processing for access types
1192
1193               if Present (UR) and then Is_Access_Type (E1T) then
1194
1195                  --  For access types, the only time we made a UR entry was
1196                  --  for a dereference, and so we post the appropriate warning
1197                  --  here (note that the dereference may not be explicit in
1198                  --  the source, for example in the case of a dispatching call
1199                  --  with an anonymous access controlling formal, or of an
1200                  --  assignment of a pointer involving discriminant check on
1201                  --  the designated object).
1202
1203                  if not Warnings_Off_E1 then
1204                     Error_Msg_NE ("??& may be null!", UR, E1);
1205                  end if;
1206
1207                  goto Continue;
1208
1209               --  Case of variable that could be a constant. Note that we
1210               --  never signal such messages for generic package entities,
1211               --  since a given instance could have modifications outside
1212               --  the package.
1213
1214               --  Note that we used to check Address_Taken here, but we don't
1215               --  want to do that since it can be set for non-source cases,
1216               --  e.g. the Unrestricted_Access from a valid attribute, and
1217               --  the wanted effect is included in Never_Set_In_Source.
1218
1219               elsif Warn_On_Constant
1220                 and then (Ekind (E1) = E_Variable
1221                            and then Has_Initial_Value (E1))
1222                 and then Never_Set_In_Source_Check_Spec (E1)
1223                 and then not Generic_Package_Spec_Entity (E1)
1224               then
1225                  --  A special case, if this variable is volatile and not
1226                  --  imported, it is not helpful to tell the programmer
1227                  --  to mark the variable as constant, since this would be
1228                  --  illegal by virtue of RM C.6(13). Instead we suggest
1229                  --  using pragma Export (can't be Import because of the
1230                  --  initial value).
1231
1232                  if (Is_Volatile (E1) or else Has_Volatile_Components (E1))
1233                    and then not Is_Imported (E1)
1234                  then
1235                     Error_Msg_N
1236                       ("?k?& is not modified, consider pragma Export for "
1237                        & "volatile variable!", E1);
1238
1239                  --  Another special case, Exception_Occurrence, this catches
1240                  --  the case of exception choice (and a bit more too, but not
1241                  --  worth doing more investigation here).
1242
1243                  elsif Is_RTE (E1T, RE_Exception_Occurrence) then
1244                     null;
1245
1246                  --  Here we give the warning if referenced and no pragma
1247                  --  Unreferenced or Unmodified is present.
1248
1249                  else
1250                     --  Variable case
1251
1252                     if Ekind (E1) = E_Variable then
1253                        if Referenced_Check_Spec (E1)
1254                          and then not Has_Pragma_Unreferenced_Check_Spec (E1)
1255                          and then not Has_Pragma_Unmodified_Check_Spec (E1)
1256                        then
1257                           if not Warnings_Off_E1
1258                             and then not Has_Junk_Name (E1)
1259                           then
1260                              Error_Msg_N -- CODEFIX
1261                                ("?k?& is not modified, "
1262                                 & "could be declared constant!",
1263                                 E1);
1264                           end if;
1265                        end if;
1266                     end if;
1267                  end if;
1268
1269               --  Other cases of a variable or parameter never set in source
1270
1271               elsif Never_Set_In_Source_Check_Spec (E1)
1272
1273                 --  No warning if warning for this case turned off
1274
1275                 and then Warn_On_No_Value_Assigned
1276
1277                 --  No warning if address taken somewhere
1278
1279                 and then not Address_Taken (E1)
1280
1281                 --  No warning if explicit initial value
1282
1283                 and then not Has_Initial_Value (E1)
1284
1285                 --  No warning for generic package spec entities, since we
1286                 --  might set them in a child unit or something like that
1287
1288                 and then not Generic_Package_Spec_Entity (E1)
1289
1290                 --  No warning if fully initialized type, except that for
1291                 --  this purpose we do not consider access types to qualify
1292                 --  as fully initialized types (relying on an access type
1293                 --  variable being null when it is never set is a bit odd).
1294
1295                 --  Also we generate warning for an out parameter that is
1296                 --  never referenced, since again it seems odd to rely on
1297                 --  default initialization to set an out parameter value.
1298
1299                and then (Is_Access_Type (E1T)
1300                           or else Ekind (E1) = E_Out_Parameter
1301                           or else not Is_Fully_Initialized_Type (E1T))
1302               then
1303                  --  Do not output complaint about never being assigned a
1304                  --  value if a pragma Unmodified applies to the variable
1305                  --  we are examining, or if it is a parameter, if there is
1306                  --  a pragma Unreferenced for the corresponding spec, or
1307                  --  if the type is marked as having unreferenced objects.
1308                  --  The last is a little peculiar, but better too few than
1309                  --  too many warnings in this situation.
1310
1311                  if Has_Pragma_Unreferenced_Objects (E1T)
1312                    or else Has_Pragma_Unmodified_Check_Spec (E1)
1313                  then
1314                     null;
1315
1316                  --  IN OUT parameter case where parameter is referenced. We
1317                  --  separate this out, since this is the case where we delay
1318                  --  output of the warning until more information is available
1319                  --  (about use in an instantiation or address being taken).
1320
1321                  elsif Ekind (E1) = E_In_Out_Parameter
1322                    and then Referenced_Check_Spec (E1)
1323                  then
1324                     --  Suppress warning if private type, and the procedure
1325                     --  has a separate declaration in a different unit. This
1326                     --  is the case where the client of a package sees only
1327                     --  the private type, and it may be quite reasonable
1328                     --  for the logical view to be IN OUT, even if the
1329                     --  implementation ends up using access types or some
1330                     --  other method to achieve the local effect of a
1331                     --  modification. On the other hand if the spec and body
1332                     --  are in the same unit, we are in the package body and
1333                     --  there we have less excuse for a junk IN OUT parameter.
1334
1335                     if Has_Private_Declaration (E1T)
1336                       and then Present (Spec_Entity (E1))
1337                       and then not In_Same_Source_Unit (E1, Spec_Entity (E1))
1338                     then
1339                        null;
1340
1341                     --  Suppress warning for any parameter of a dispatching
1342                     --  operation, since it is quite reasonable to have an
1343                     --  operation that is overridden, and for some subclasses
1344                     --  needs the formal to be IN OUT and for others happens
1345                     --  not to assign it.
1346
1347                     elsif Is_Dispatching_Operation
1348                             (Scope (Goto_Spec_Entity (E1)))
1349                     then
1350                        null;
1351
1352                     --  Suppress warning if composite type contains any access
1353                     --  component, since the logical effect of modifying a
1354                     --  parameter may be achieved by modifying a referenced
1355                     --  object.
1356
1357                     elsif Is_Composite_Type (E1T)
1358                       and then Has_Access_Values (E1T)
1359                     then
1360                        null;
1361
1362                     --  Suppress warning on formals of an entry body. All
1363                     --  references are attached to the formal in the entry
1364                     --  declaration, which are marked Is_Entry_Formal.
1365
1366                     elsif Ekind (Scope (E1)) = E_Entry
1367                       and then not Is_Entry_Formal (E1)
1368                     then
1369                        null;
1370
1371                     --  OK, looks like warning for an IN OUT parameter that
1372                     --  could be IN makes sense, but we delay the output of
1373                     --  the warning, pending possibly finding out later on
1374                     --  that the associated subprogram is used as a generic
1375                     --  actual, or its address/access is taken. In these two
1376                     --  cases, we suppress the warning because the context may
1377                     --  force use of IN OUT, even if in this particular case
1378                     --  the formal is not modified.
1379
1380                     else
1381                        --  Suppress the warnings for a junk name
1382
1383                        if not Has_Junk_Name (E1) then
1384                           In_Out_Warnings.Append (E1);
1385                        end if;
1386                     end if;
1387
1388                  --  Other cases of formals
1389
1390                  elsif Is_Formal (E1) then
1391                     if not Is_Trivial_Subprogram (Scope (E1)) then
1392                        if Referenced_Check_Spec (E1) then
1393                           if not Has_Pragma_Unmodified_Check_Spec (E1)
1394                             and then not Warnings_Off_E1
1395                             and then not Has_Junk_Name (E1)
1396                           then
1397                              Output_Reference_Error
1398                                ("?f?formal parameter& is read but "
1399                                 & "never assigned!");
1400                           end if;
1401
1402                        elsif not Has_Pragma_Unreferenced_Check_Spec (E1)
1403                          and then not Warnings_Off_E1
1404                          and then not Has_Junk_Name (E1)
1405                        then
1406                           Output_Reference_Error
1407                             ("?f?formal parameter& is not referenced!");
1408                        end if;
1409                     end if;
1410
1411                  --  Case of variable
1412
1413                  else
1414                     if Referenced (E1) then
1415                        if not Has_Unmodified (E1)
1416                          and then not Warnings_Off_E1
1417                          and then not Has_Junk_Name (E1)
1418                        then
1419                           Output_Reference_Error
1420                             ("?v?variable& is read but never assigned!");
1421                           May_Need_Initialized_Actual (E1);
1422                        end if;
1423
1424                     elsif not Has_Unreferenced (E1)
1425                       and then not Warnings_Off_E1
1426                       and then not Has_Junk_Name (E1)
1427                     then
1428                        Output_Reference_Error -- CODEFIX
1429                          ("?v?variable& is never read and never assigned!");
1430                     end if;
1431
1432                     --  Deal with special case where this variable is hidden
1433                     --  by a loop variable.
1434
1435                     if Ekind (E1) = E_Variable
1436                       and then Present (Hiding_Loop_Variable (E1))
1437                       and then not Warnings_Off_E1
1438                     then
1439                        Error_Msg_N
1440                          ("?v?for loop implicitly declares loop variable!",
1441                           Hiding_Loop_Variable (E1));
1442
1443                        Error_Msg_Sloc := Sloc (E1);
1444                        Error_Msg_N
1445                          ("\?v?declaration hides & declared#!",
1446                           Hiding_Loop_Variable (E1));
1447                     end if;
1448                  end if;
1449
1450                  goto Continue;
1451               end if;
1452
1453               --  Check for unset reference. If type of object has
1454               --  preelaborable initialization, warning is misleading.
1455
1456               if Warn_On_No_Value_Assigned
1457                 and then Present (UR)
1458                 and then not Known_To_Have_Preelab_Init (Etype (E1))
1459               then
1460
1461                  --  For other than access type, go back to original node to
1462                  --  deal with case where original unset reference has been
1463                  --  rewritten during expansion.
1464
1465                  --  In some cases, the original node may be a type
1466                  --  conversion, a qualification or an attribute reference and
1467                  --  in this case we want the object entity inside. Same for
1468                  --  an expression with actions.
1469
1470                  UR := Original_Node (UR);
1471                  loop
1472                     if Nkind_In (UR, N_Expression_With_Actions,
1473                                      N_Qualified_Expression,
1474                                      N_Type_Conversion)
1475                     then
1476                        UR := Expression (UR);
1477
1478                     elsif Nkind (UR) = N_Attribute_Reference then
1479                        UR := Prefix (UR);
1480
1481                     else
1482                        exit;
1483                     end if;
1484                  end loop;
1485
1486                  --  Don't issue warning if appearing inside Initial_Condition
1487                  --  pragma or aspect, since that expression is not evaluated
1488                  --  at the point where it occurs in the source.
1489
1490                  if In_Pragma_Expression (UR, Name_Initial_Condition) then
1491                     goto Continue;
1492                  end if;
1493
1494                  --  Here we issue the warning, all checks completed
1495
1496                  --  If we have a return statement, this was a case of an OUT
1497                  --  parameter not being set at the time of the return. (Note:
1498                  --  it can't be N_Extended_Return_Statement, because those
1499                  --  are only for functions, and functions do not allow OUT
1500                  --  parameters.)
1501
1502                  if not Is_Trivial_Subprogram (Scope (E1)) then
1503                     if Nkind (UR) = N_Simple_Return_Statement
1504                       and then not Has_Pragma_Unmodified_Check_Spec (E1)
1505                     then
1506                        if not Warnings_Off_E1
1507                          and then not Has_Junk_Name (E1)
1508                        then
1509                           Error_Msg_NE
1510                             ("?v?OUT parameter& not set before return",
1511                              UR, E1);
1512                        end if;
1513
1514                        --  If the unset reference is a selected component
1515                        --  prefix from source, mention the component as well.
1516                        --  If the selected component comes from expansion, all
1517                        --  we know is that the entity is not fully initialized
1518                        --  at the point of the reference. Locate a random
1519                        --  uninitialized component to get a better message.
1520
1521                     elsif Nkind (Parent (UR)) = N_Selected_Component then
1522                        Error_Msg_Node_2 := Selector_Name (Parent (UR));
1523
1524                        if not Comes_From_Source (Parent (UR)) then
1525                           declare
1526                              Comp : Entity_Id;
1527
1528                           begin
1529                              Comp := First_Entity (E1T);
1530                              while Present (Comp) loop
1531                                 if Ekind (Comp) = E_Component
1532                                   and then Nkind (Parent (Comp)) =
1533                                              N_Component_Declaration
1534                                   and then No (Expression (Parent (Comp)))
1535                                 then
1536                                    Error_Msg_Node_2 := Comp;
1537                                    exit;
1538                                 end if;
1539
1540                                 Next_Entity (Comp);
1541                              end loop;
1542                           end;
1543                        end if;
1544
1545                        --  Issue proper warning. This is a case of referencing
1546                        --  a variable before it has been explicitly assigned.
1547                        --  For access types, UR was only set for dereferences,
1548                        --  so the issue is that the value may be null.
1549
1550                        if not Is_Trivial_Subprogram (Scope (E1)) then
1551                           if not Warnings_Off_E1 then
1552                              if Is_Access_Type (Etype (Parent (UR))) then
1553                                 Error_Msg_N ("??`&.&` may be null!", UR);
1554                              else
1555                                 Error_Msg_N
1556                                   ("??`&.&` may be referenced before "
1557                                    & "it has a value!", UR);
1558                              end if;
1559                           end if;
1560                        end if;
1561
1562                     --  All other cases of unset reference active
1563
1564                     elsif not Warnings_Off_E1 then
1565                        Error_Msg_N
1566                          ("??& may be referenced before it has a value!", UR);
1567                     end if;
1568                  end if;
1569
1570                  goto Continue;
1571
1572               end if;
1573            end if;
1574
1575            --  Then check for unreferenced entities. Note that we are only
1576            --  interested in entities whose Referenced flag is not set.
1577
1578            if not Referenced_Check_Spec (E1)
1579
1580              --  If Referenced_As_LHS is set, then that's still interesting
1581              --  (potential "assigned but never read" case), but not if we
1582              --  have pragma Unreferenced, which cancels this warning.
1583
1584              and then (not Referenced_As_LHS_Check_Spec (E1)
1585                         or else not Has_Unreferenced (E1))
1586
1587              --  Check that warnings on unreferenced entities are enabled
1588
1589              and then
1590                ((Check_Unreferenced and then not Is_Formal (E1))
1591
1592                  --  Case of warning on unreferenced formal
1593
1594                  or else (Check_Unreferenced_Formals and then Is_Formal (E1))
1595
1596                  --  Case of warning on unread variables modified by an
1597                  --  assignment, or an OUT parameter if it is the only one.
1598
1599                  or else (Warn_On_Modified_Unread
1600                            and then Referenced_As_LHS_Check_Spec (E1))
1601
1602                  --  Case of warning on any unread OUT parameter (note such
1603                  --  indications are only set if the appropriate warning
1604                  --  options were set, so no need to recheck here.)
1605
1606                  or else Referenced_As_Out_Parameter_Check_Spec (E1))
1607
1608              --  All other entities, including local packages that cannot be
1609              --  referenced from elsewhere, including those declared within a
1610              --  package body.
1611
1612              and then (Is_Object (E1)
1613                         or else Is_Type (E1)
1614                         or else Ekind (E1) = E_Label
1615                         or else Ekind_In (E1, E_Exception,
1616                                               E_Named_Integer,
1617                                               E_Named_Real)
1618                         or else Is_Overloadable (E1)
1619
1620                         --  Package case, if the main unit is a package spec
1621                         --  or generic package spec, then there may be a
1622                         --  corresponding body that references this package
1623                         --  in some other file. Otherwise we can be sure
1624                         --  that there is no other reference.
1625
1626                         or else
1627                           (Ekind (E1) = E_Package
1628                             and then
1629                               not Is_Package_Or_Generic_Package
1630                                     (Cunit_Entity (Current_Sem_Unit))))
1631
1632              --  Exclude instantiations, since there is no reason why every
1633              --  entity in an instantiation should be referenced.
1634
1635              and then Instantiation_Location (Sloc (E1)) = No_Location
1636
1637              --  Exclude formal parameters from bodies if the corresponding
1638              --  spec entity has been referenced in the case where there is
1639              --  a separate spec.
1640
1641              and then not (Is_Formal (E1)
1642                             and then Ekind (Scope (E1)) = E_Subprogram_Body
1643                             and then Present (Spec_Entity (E1))
1644                             and then Referenced (Spec_Entity (E1)))
1645
1646              --  Consider private type referenced if full view is referenced.
1647              --  If there is not full view, this is a generic type on which
1648              --  warnings are also useful.
1649
1650              and then
1651                not (Is_Private_Type (E1)
1652                      and then Present (Full_View (E1))
1653                      and then Referenced (Full_View (E1)))
1654
1655              --  Don't worry about full view, only about private type
1656
1657              and then not Has_Private_Declaration (E1)
1658
1659              --  Eliminate dispatching operations from consideration, we
1660              --  cannot tell if these are referenced or not in any easy
1661              --  manner (note this also catches Adjust/Finalize/Initialize).
1662
1663              and then not Is_Dispatching_Operation (E1)
1664
1665              --  Check entity that can be publicly referenced (we do not give
1666              --  messages for such entities, since there could be other
1667              --  units, not involved in this compilation, that contain
1668              --  relevant references.
1669
1670              and then not Publicly_Referenceable (E1)
1671
1672              --  Class wide types are marked as source entities, but they are
1673              --  not really source entities, and are always created, so we do
1674              --  not care if they are not referenced.
1675
1676              and then Ekind (E1) /= E_Class_Wide_Type
1677
1678              --  Objects other than parameters of task types are allowed to
1679              --  be non-referenced, since they start up tasks.
1680
1681              and then ((Ekind (E1) /= E_Variable
1682                          and then Ekind (E1) /= E_Constant
1683                          and then Ekind (E1) /= E_Component)
1684                         or else not Is_Task_Type (E1T))
1685
1686              --  For subunits, only place warnings on the main unit itself,
1687              --  since parent units are not completely compiled.
1688
1689              and then (Nkind (Unit (Cunit (Main_Unit))) /= N_Subunit
1690                         or else Get_Source_Unit (E1) = Main_Unit)
1691
1692              --  No warning on a return object, because these are often
1693              --  created with a single expression and an implicit return.
1694              --  If the object is a variable there will be a warning
1695              --  indicating that it could be declared constant.
1696
1697              and then not
1698                (Ekind (E1) = E_Constant and then Is_Return_Object (E1))
1699            then
1700               --  Suppress warnings in internal units if not in -gnatg mode
1701               --  (these would be junk warnings for an applications program,
1702               --  since they refer to problems in internal units).
1703
1704               if GNAT_Mode or else not In_Internal_Unit (E1) then
1705                  --  We do not immediately flag the error. This is because we
1706                  --  have not expanded generic bodies yet, and they may have
1707                  --  the missing reference. So instead we park the entity on a
1708                  --  list, for later processing. However for the case of an
1709                  --  accept statement we want to output messages now, since
1710                  --  we know we already have all information at hand, and we
1711                  --  also want to have separate warnings for each accept
1712                  --  statement for the same entry.
1713
1714                  if Present (Anod) then
1715                     pragma Assert (Is_Formal (E1));
1716
1717                     --  The unreferenced entity is E1, but post the warning
1718                     --  on the body entity for this accept statement.
1719
1720                     if not Warnings_Off_E1 then
1721                        Warn_On_Unreferenced_Entity
1722                          (E1, Body_Formal (E1, Accept_Statement => Anod));
1723                     end if;
1724
1725                  elsif not Warnings_Off_E1
1726                    and then not Has_Junk_Name (E1)
1727                  then
1728                     if Is_Formal (E1)
1729                       and then Nkind (Unit_Declaration_Node (Scope (E1)))
1730                         = N_Generic_Subprogram_Declaration
1731                     then
1732                        Unreferenced_Entities.Append
1733                          (Generic_Body_Formal (E1));
1734                     else
1735                        Unreferenced_Entities.Append (E1);
1736                     end if;
1737                  end if;
1738               end if;
1739
1740            --  Generic units are referenced in the generic body, but if they
1741            --  are not public and never instantiated we want to force a
1742            --  warning on them. We treat them as redundant constructs to
1743            --  minimize noise.
1744
1745            elsif Is_Generic_Subprogram (E1)
1746              and then not Is_Instantiated (E1)
1747              and then not Publicly_Referenceable (E1)
1748              and then Instantiation_Depth (Sloc (E1)) = 0
1749              and then Warn_On_Redundant_Constructs
1750            then
1751               if not Warnings_Off_E1 and then not Has_Junk_Name (E1) then
1752                  Unreferenced_Entities.Append (E1);
1753
1754                  --  Force warning on entity
1755
1756                  Set_Referenced (E1, False);
1757               end if;
1758            end if;
1759         end if;
1760
1761         --  Recurse into nested package or block. Do not recurse into a formal
1762         --  package, because the corresponding body is not analyzed.
1763
1764         <<Continue>>
1765            if (Is_Package_Or_Generic_Package (E1)
1766                 and then Nkind (Parent (E1)) = N_Package_Specification
1767                 and then
1768                   Nkind (Original_Node (Unit_Declaration_Node (E1))) /=
1769                                                N_Formal_Package_Declaration)
1770
1771              or else Ekind (E1) = E_Block
1772            then
1773               Check_References (E1);
1774            end if;
1775
1776            Next_Entity (E1);
1777      end loop;
1778   end Check_References;
1779
1780   ---------------------------
1781   -- Check_Unset_Reference --
1782   ---------------------------
1783
1784   procedure Check_Unset_Reference (N : Node_Id) is
1785      Typ : constant Entity_Id := Etype (N);
1786
1787      function Is_OK_Fully_Initialized return Boolean;
1788      --  This function returns true if the given node N is fully initialized
1789      --  so that the reference is safe as far as this routine is concerned.
1790      --  Safe generally means that the type of N is a fully initialized type.
1791      --  The one special case is that for access types, which are always fully
1792      --  initialized, we don't consider a dereference OK since it will surely
1793      --  be dereferencing a null value, which won't do.
1794
1795      function Prefix_Has_Dereference (Pref : Node_Id) return Boolean;
1796      --  Used to test indexed or selected component or slice to see if the
1797      --  evaluation of the prefix depends on a dereference, and if so, returns
1798      --  True, in which case we always check the prefix, even if we know that
1799      --  the referenced component is initialized. Pref is the prefix to test.
1800
1801      -----------------------------
1802      -- Is_OK_Fully_Initialized --
1803      -----------------------------
1804
1805      function Is_OK_Fully_Initialized return Boolean is
1806      begin
1807         if Is_Access_Type (Typ) and then Is_Dereferenced (N) then
1808            return False;
1809
1810         --  A type subject to pragma Default_Initial_Condition may be fully
1811         --  default initialized depending on inheritance and the argument of
1812         --  the pragma (SPARK RM 3.1 and SPARK RM 7.3.3).
1813
1814         elsif Has_Fully_Default_Initializing_DIC_Pragma (Typ) then
1815            return True;
1816
1817         else
1818            return Is_Fully_Initialized_Type (Typ);
1819         end if;
1820      end Is_OK_Fully_Initialized;
1821
1822      ----------------------------
1823      -- Prefix_Has_Dereference --
1824      ----------------------------
1825
1826      function Prefix_Has_Dereference (Pref : Node_Id) return Boolean is
1827      begin
1828         --  If prefix is of an access type, it certainly needs a dereference
1829
1830         if Is_Access_Type (Etype (Pref)) then
1831            return True;
1832
1833         --  If prefix is explicit dereference, that's a dereference for sure
1834
1835         elsif Nkind (Pref) = N_Explicit_Dereference then
1836            return True;
1837
1838            --  If prefix is itself a component reference or slice check prefix
1839
1840         elsif Nkind (Pref) = N_Slice
1841           or else Nkind (Pref) = N_Indexed_Component
1842           or else Nkind (Pref) = N_Selected_Component
1843         then
1844            return Prefix_Has_Dereference (Prefix (Pref));
1845
1846         --  All other cases do not involve a dereference
1847
1848         else
1849            return False;
1850         end if;
1851      end Prefix_Has_Dereference;
1852
1853   --  Start of processing for Check_Unset_Reference
1854
1855   begin
1856      --  Nothing to do if warnings suppressed
1857
1858      if Warning_Mode = Suppress then
1859         return;
1860      end if;
1861
1862      --  Nothing to do for numeric or string literal. Do this test early to
1863      --  save time in a common case (it does not matter that we do not include
1864      --  character literal here, since that will be caught later on in the
1865      --  when others branch of the case statement).
1866
1867      if Nkind (N) in N_Numeric_Or_String_Literal then
1868         return;
1869      end if;
1870
1871      --  Ignore reference unless it comes from source. Almost always if we
1872      --  have a reference from generated code, it is bogus (e.g. calls to init
1873      --  procs to set default discriminant values).
1874
1875      if not Comes_From_Source (N) then
1876         return;
1877      end if;
1878
1879      --  Otherwise see what kind of node we have. If the entity already has an
1880      --  unset reference, it is not necessarily the earliest in the text,
1881      --  because resolution of the prefix of selected components is completed
1882      --  before the resolution of the selected component itself. As a result,
1883      --  given (R /= null and then R.X > 0), the occurrences of R are examined
1884      --  in right-to-left order. If there is already an unset reference, we
1885      --  check whether N is earlier before proceeding.
1886
1887      case Nkind (N) is
1888
1889         --  For identifier or expanded name, examine the entity involved
1890
1891         when N_Expanded_Name
1892            | N_Identifier
1893         =>
1894            declare
1895               E : constant Entity_Id := Entity (N);
1896
1897            begin
1898               if Ekind_In (E, E_Variable, E_Out_Parameter)
1899                 and then Never_Set_In_Source_Check_Spec (E)
1900                 and then not Has_Initial_Value (E)
1901                 and then (No (Unset_Reference (E))
1902                            or else
1903                              Earlier_In_Extended_Unit
1904                                (Sloc (N), Sloc (Unset_Reference (E))))
1905                 and then not Has_Pragma_Unmodified_Check_Spec (E)
1906                 and then not Warnings_Off_Check_Spec (E)
1907                 and then not Has_Junk_Name (E)
1908               then
1909                  --  We may have an unset reference. The first test is whether
1910                  --  this is an access to a discriminant of a record or a
1911                  --  component with default initialization. Both of these
1912                  --  cases can be ignored, since the actual object that is
1913                  --  referenced is definitely initialized. Note that this
1914                  --  covers the case of reading discriminants of an OUT
1915                  --  parameter, which is OK even in Ada 83.
1916
1917                  --  Note that we are only interested in a direct reference to
1918                  --  a record component here. If the reference is through an
1919                  --  access type, then the access object is being referenced,
1920                  --  not the record, and still deserves an unset reference.
1921
1922                  if Nkind (Parent (N)) = N_Selected_Component
1923                    and not Is_Access_Type (Typ)
1924                  then
1925                     declare
1926                        ES : constant Entity_Id :=
1927                               Entity (Selector_Name (Parent (N)));
1928                     begin
1929                        if Ekind (ES) = E_Discriminant
1930                          or else
1931                            (Present (Declaration_Node (ES))
1932                               and then
1933                             Present (Expression (Declaration_Node (ES))))
1934                        then
1935                           return;
1936                        end if;
1937                     end;
1938                  end if;
1939
1940                  --  Exclude fully initialized types
1941
1942                  if Is_OK_Fully_Initialized then
1943                     return;
1944                  end if;
1945
1946                  --  Here we have a potential unset reference. But before we
1947                  --  get worried about it, we have to make sure that the
1948                  --  entity declaration is in the same procedure as the
1949                  --  reference, since if they are in separate procedures, then
1950                  --  we have no idea about sequential execution.
1951
1952                  --  The tests in the loop below catch all such cases, but do
1953                  --  allow the reference to appear in a loop, block, or
1954                  --  package spec that is nested within the declaring scope.
1955                  --  As always, it is possible to construct cases where the
1956                  --  warning is wrong, that is why it is a warning.
1957
1958                  Potential_Unset_Reference : declare
1959                     SR : Entity_Id;
1960                     SE : constant Entity_Id := Scope (E);
1961
1962                     function Within_Postcondition return Boolean;
1963                     --  Returns True if N is within a Postcondition, a
1964                     --  Refined_Post, an Ensures component in a Test_Case,
1965                     --  or a Contract_Cases.
1966
1967                     --------------------------
1968                     -- Within_Postcondition --
1969                     --------------------------
1970
1971                     function Within_Postcondition return Boolean is
1972                        Nod, P : Node_Id;
1973
1974                     begin
1975                        Nod := Parent (N);
1976                        while Present (Nod) loop
1977                           if Nkind (Nod) = N_Pragma
1978                             and then Nam_In (Pragma_Name_Unmapped (Nod),
1979                                              Name_Postcondition,
1980                                              Name_Refined_Post,
1981                                              Name_Contract_Cases)
1982                           then
1983                              return True;
1984
1985                           elsif Present (Parent (Nod)) then
1986                              P := Parent (Nod);
1987
1988                              if Nkind (P) = N_Pragma
1989                                and then Pragma_Name (P) =
1990                                  Name_Test_Case
1991                                and then Nod = Test_Case_Arg (P, Name_Ensures)
1992                              then
1993                                 return True;
1994                              end if;
1995                           end if;
1996
1997                           Nod := Parent (Nod);
1998                        end loop;
1999
2000                        return False;
2001                     end Within_Postcondition;
2002
2003                  --  Start of processing for Potential_Unset_Reference
2004
2005                  begin
2006                     SR := Current_Scope;
2007                     while SR /= SE loop
2008                        if SR = Standard_Standard
2009                          or else Is_Subprogram (SR)
2010                          or else Is_Concurrent_Body (SR)
2011                          or else Is_Concurrent_Type (SR)
2012                        then
2013                           return;
2014                        end if;
2015
2016                        SR := Scope (SR);
2017                     end loop;
2018
2019                     --  Case of reference has an access type. This is a
2020                     --  special case since access types are always set to null
2021                     --  so cannot be truly uninitialized, but we still want to
2022                     --  warn about cases of obvious null dereference.
2023
2024                     if Is_Access_Type (Typ) then
2025                        Access_Type_Case : declare
2026                           P : Node_Id;
2027
2028                           function Process
2029                             (N : Node_Id) return Traverse_Result;
2030                           --  Process function for instantiation of Traverse
2031                           --  below. Checks if N contains reference to E other
2032                           --  than a dereference.
2033
2034                           function Ref_In (Nod : Node_Id) return Boolean;
2035                           --  Determines whether Nod contains a reference to
2036                           --  the entity E that is not a dereference.
2037
2038                           -------------
2039                           -- Process --
2040                           -------------
2041
2042                           function Process
2043                             (N : Node_Id) return Traverse_Result
2044                           is
2045                           begin
2046                              if Is_Entity_Name (N)
2047                                and then Entity (N) = E
2048                                and then not Is_Dereferenced (N)
2049                              then
2050                                 return Abandon;
2051                              else
2052                                 return OK;
2053                              end if;
2054                           end Process;
2055
2056                           ------------
2057                           -- Ref_In --
2058                           ------------
2059
2060                           function Ref_In (Nod : Node_Id) return Boolean is
2061                              function Traverse is new Traverse_Func (Process);
2062                           begin
2063                              return Traverse (Nod) = Abandon;
2064                           end Ref_In;
2065
2066                        --  Start of processing for Access_Type_Case
2067
2068                        begin
2069                           --  Don't bother if we are inside an instance, since
2070                           --  the compilation of the generic template is where
2071                           --  the warning should be issued.
2072
2073                           if In_Instance then
2074                              return;
2075                           end if;
2076
2077                           --  Don't bother if this is not the main unit. If we
2078                           --  try to give this warning for with'ed units, we
2079                           --  get some false positives, since we do not record
2080                           --  references in other units.
2081
2082                           if not In_Extended_Main_Source_Unit (E)
2083                                or else
2084                              not In_Extended_Main_Source_Unit (N)
2085                           then
2086                              return;
2087                           end if;
2088
2089                           --  We are only interested in dereferences
2090
2091                           if not Is_Dereferenced (N) then
2092                              return;
2093                           end if;
2094
2095                           --  One more check, don't bother with references
2096                           --  that are inside conditional statements or WHILE
2097                           --  loops if the condition references the entity in
2098                           --  question. This avoids most false positives.
2099
2100                           P := Parent (N);
2101                           loop
2102                              P := Parent (P);
2103                              exit when No (P);
2104
2105                              if Nkind_In (P, N_If_Statement, N_Elsif_Part)
2106                                and then Ref_In (Condition (P))
2107                              then
2108                                 return;
2109
2110                              elsif Nkind (P) = N_Loop_Statement
2111                                and then Present (Iteration_Scheme (P))
2112                                and then
2113                                  Ref_In (Condition (Iteration_Scheme (P)))
2114                              then
2115                                 return;
2116                              end if;
2117                           end loop;
2118                        end Access_Type_Case;
2119                     end if;
2120
2121                     --  One more check, don't bother if we are within a
2122                     --  postcondition, since the expression occurs in a
2123                     --  place unrelated to the actual test.
2124
2125                     if not Within_Postcondition then
2126
2127                        --  Here we definitely have a case for giving a warning
2128                        --  for a reference to an unset value. But we don't
2129                        --  give the warning now. Instead set Unset_Reference
2130                        --  in the identifier involved. The reason for this is
2131                        --  that if we find the variable is never ever assigned
2132                        --  a value then that warning is more important and
2133                        --  there is no point in giving the reference warning.
2134
2135                        --  If this is an identifier, set the field directly
2136
2137                        if Nkind (N) = N_Identifier then
2138                           Set_Unset_Reference (E, N);
2139
2140                        --  Otherwise it is an expanded name, so set the field
2141                        --  of the actual identifier for the reference.
2142
2143                        else
2144                           Set_Unset_Reference (E, Selector_Name (N));
2145                        end if;
2146                     end if;
2147                  end Potential_Unset_Reference;
2148               end if;
2149            end;
2150
2151         --  Indexed component or slice
2152
2153         when N_Indexed_Component
2154            | N_Slice
2155         =>
2156            --  If prefix does not involve dereferencing an access type, then
2157            --  we know we are OK if the component type is fully initialized,
2158            --  since the component will have been set as part of the default
2159            --  initialization.
2160
2161            if not Prefix_Has_Dereference (Prefix (N))
2162              and then Is_OK_Fully_Initialized
2163            then
2164               return;
2165
2166            --  Look at prefix in access type case, or if the component is not
2167            --  fully initialized.
2168
2169            else
2170               Check_Unset_Reference (Prefix (N));
2171            end if;
2172
2173         --  Record component
2174
2175         when N_Selected_Component =>
2176            declare
2177               Pref : constant Node_Id   := Prefix (N);
2178               Ent  : constant Entity_Id := Entity (Selector_Name (N));
2179
2180            begin
2181               --  If prefix involves dereferencing an access type, always
2182               --  check the prefix, since the issue then is whether this
2183               --  access value is null.
2184
2185               if Prefix_Has_Dereference (Pref) then
2186                  null;
2187
2188               --  Always go to prefix if no selector entity is set. Can this
2189               --  happen in the normal case? Not clear, but it definitely can
2190               --  happen in error cases.
2191
2192               elsif No (Ent) then
2193                  null;
2194
2195               --  For a record component, check some cases where we have
2196               --  reasonable cause to consider that the component is known to
2197               --  be or probably is initialized. In this case, we don't care
2198               --  if the prefix itself was explicitly initialized.
2199
2200               --  Discriminants are always considered initialized
2201
2202               elsif Ekind (Ent) = E_Discriminant then
2203                  return;
2204
2205               --  An explicitly initialized component is certainly initialized
2206
2207               elsif Nkind (Parent (Ent)) = N_Component_Declaration
2208                 and then Present (Expression (Parent (Ent)))
2209               then
2210                  return;
2211
2212               --  A fully initialized component is initialized
2213
2214               elsif Is_OK_Fully_Initialized then
2215                  return;
2216               end if;
2217
2218               --  If none of those cases apply, check the record type prefix
2219
2220               Check_Unset_Reference (Pref);
2221            end;
2222
2223         --  For type conversions, qualifications, or expressions with actions,
2224         --  examine the expression.
2225
2226         when N_Expression_With_Actions
2227            | N_Qualified_Expression
2228            | N_Type_Conversion
2229         =>
2230            Check_Unset_Reference (Expression (N));
2231
2232         --  For explicit dereference, always check prefix, which will generate
2233         --  an unset reference (since this is a case of dereferencing null).
2234
2235         when N_Explicit_Dereference =>
2236            Check_Unset_Reference (Prefix (N));
2237
2238         --  All other cases are not cases of an unset reference
2239
2240         when others =>
2241            null;
2242      end case;
2243   end Check_Unset_Reference;
2244
2245   ------------------------
2246   -- Check_Unused_Withs --
2247   ------------------------
2248
2249   procedure Check_Unused_Withs (Spec_Unit : Unit_Number_Type := No_Unit) is
2250      Cnode : Node_Id;
2251      Item  : Node_Id;
2252      Lunit : Node_Id;
2253      Ent   : Entity_Id;
2254
2255      Munite : constant Entity_Id := Cunit_Entity (Main_Unit);
2256      --  This is needed for checking the special renaming case
2257
2258      procedure Check_One_Unit (Unit : Unit_Number_Type);
2259      --  Subsidiary procedure, performs checks for specified unit
2260
2261      --------------------
2262      -- Check_One_Unit --
2263      --------------------
2264
2265      procedure Check_One_Unit (Unit : Unit_Number_Type) is
2266         Is_Visible_Renaming : Boolean := False;
2267         Pack                : Entity_Id;
2268
2269         procedure Check_Inner_Package (Pack : Entity_Id);
2270         --  Pack is a package local to a unit in a with_clause. Both the unit
2271         --  and Pack are referenced. If none of the entities in Pack are
2272         --  referenced, then the only occurrence of Pack is in a USE clause
2273         --  or a pragma, and a warning is worthwhile as well.
2274
2275         function Check_System_Aux return Boolean;
2276         --  Before giving a warning on a with_clause for System, check whether
2277         --  a system extension is present.
2278
2279         function Find_Package_Renaming
2280           (P : Entity_Id;
2281            L : Entity_Id) return Entity_Id;
2282         --  The only reference to a context unit may be in a renaming
2283         --  declaration. If this renaming declares a visible entity, do not
2284         --  warn that the context clause could be moved to the body, because
2285         --  the renaming may be intended to re-export the unit.
2286
2287         function Has_Visible_Entities (P : Entity_Id) return Boolean;
2288         --  This function determines if a package has any visible entities.
2289         --  True is returned if there is at least one declared visible entity,
2290         --  otherwise False is returned (e.g. case of only pragmas present).
2291
2292         -------------------------
2293         -- Check_Inner_Package --
2294         -------------------------
2295
2296         procedure Check_Inner_Package (Pack : Entity_Id) is
2297            E  : Entity_Id;
2298            Un : constant Node_Id := Sinfo.Unit (Cnode);
2299
2300            function Check_Use_Clause (N : Node_Id) return Traverse_Result;
2301            --  If N is a use_clause for Pack, emit warning
2302
2303            procedure Check_Use_Clauses is new
2304              Traverse_Proc (Check_Use_Clause);
2305
2306            ----------------------
2307            -- Check_Use_Clause --
2308            ----------------------
2309
2310            function Check_Use_Clause (N : Node_Id) return Traverse_Result is
2311            begin
2312               if Nkind (N) = N_Use_Package_Clause
2313                 and then Entity (Name (N)) = Pack
2314               then
2315                  --  Suppress message if any serious errors detected that turn
2316                  --  off expansion, and thus result in false positives for
2317                  --  this warning.
2318
2319                  if Serious_Errors_Detected = 0 then
2320                     Error_Msg_Qual_Level := 1;
2321                     Error_Msg_NE -- CODEFIX
2322                       ("?u?no entities of package& are referenced!",
2323                          Name (N), Pack);
2324                     Error_Msg_Qual_Level := 0;
2325                  end if;
2326               end if;
2327
2328               return OK;
2329            end Check_Use_Clause;
2330
2331         --  Start of processing for Check_Inner_Package
2332
2333         begin
2334            E := First_Entity (Pack);
2335            while Present (E) loop
2336               if Referenced_Check_Spec (E) then
2337                  return;
2338               end if;
2339
2340               Next_Entity (E);
2341            end loop;
2342
2343            --  No entities of the package are referenced. Check whether the
2344            --  reference to the package itself is a use clause, and if so
2345            --  place a warning on it.
2346
2347            Check_Use_Clauses (Un);
2348         end Check_Inner_Package;
2349
2350         ----------------------
2351         -- Check_System_Aux --
2352         ----------------------
2353
2354         function Check_System_Aux return Boolean is
2355            Ent : Entity_Id;
2356
2357         begin
2358            if Chars (Lunit) = Name_System
2359               and then Scope (Lunit) = Standard_Standard
2360               and then Present_System_Aux
2361            then
2362               Ent := First_Entity (System_Aux_Id);
2363               while Present (Ent) loop
2364                  if Referenced_Check_Spec (Ent) then
2365                     return True;
2366                  end if;
2367
2368                  Next_Entity (Ent);
2369               end loop;
2370            end if;
2371
2372            return False;
2373         end Check_System_Aux;
2374
2375         ---------------------------
2376         -- Find_Package_Renaming --
2377         ---------------------------
2378
2379         function Find_Package_Renaming
2380           (P : Entity_Id;
2381            L : Entity_Id) return Entity_Id
2382         is
2383            E1 : Entity_Id;
2384            R  : Entity_Id;
2385
2386         begin
2387            Is_Visible_Renaming := False;
2388
2389            E1 := First_Entity (P);
2390            while Present (E1) loop
2391               if Ekind (E1) = E_Package and then Renamed_Object (E1) = L then
2392                  Is_Visible_Renaming := not Is_Hidden (E1);
2393                  return E1;
2394
2395               elsif Ekind (E1) = E_Package
2396                 and then No (Renamed_Object (E1))
2397                 and then not Is_Generic_Instance (E1)
2398               then
2399                  R := Find_Package_Renaming (E1, L);
2400
2401                  if Present (R) then
2402                     Is_Visible_Renaming := not Is_Hidden (R);
2403                     return R;
2404                  end if;
2405               end if;
2406
2407               Next_Entity (E1);
2408            end loop;
2409
2410            return Empty;
2411         end Find_Package_Renaming;
2412
2413         --------------------------
2414         -- Has_Visible_Entities --
2415         --------------------------
2416
2417         function Has_Visible_Entities (P : Entity_Id) return Boolean is
2418            E : Entity_Id;
2419
2420         begin
2421            --  If unit in context is not a package, it is a subprogram that
2422            --  is not called or a generic unit that is not instantiated
2423            --  in the current unit, and warning is appropriate.
2424
2425            if Ekind (P) /= E_Package then
2426               return True;
2427            end if;
2428
2429            --  If unit comes from a limited_with clause, look for declaration
2430            --  of shadow entities.
2431
2432            if Present (Limited_View (P)) then
2433               E := First_Entity (Limited_View (P));
2434            else
2435               E := First_Entity (P);
2436            end if;
2437
2438            while Present (E) and then E /= First_Private_Entity (P) loop
2439               if Comes_From_Source (E) or else Present (Limited_View (P)) then
2440                  return True;
2441               end if;
2442
2443               Next_Entity (E);
2444            end loop;
2445
2446            return False;
2447         end Has_Visible_Entities;
2448
2449      --  Start of processing for Check_One_Unit
2450
2451      begin
2452         Cnode := Cunit (Unit);
2453
2454         --  Only do check in units that are part of the extended main unit.
2455         --  This is actually a necessary restriction, because in the case of
2456         --  subprogram acting as its own specification, there can be with's in
2457         --  subunits that we will not see.
2458
2459         if not In_Extended_Main_Source_Unit (Cnode) then
2460            return;
2461         end if;
2462
2463         --  Loop through context items in this unit
2464
2465         Item := First (Context_Items (Cnode));
2466         while Present (Item) loop
2467            if Nkind (Item) = N_With_Clause
2468              and then not Implicit_With (Item)
2469              and then In_Extended_Main_Source_Unit (Item)
2470
2471              --  Guard for no entity present. Not clear under what conditions
2472              --  this happens, but it does occur, and since this is only a
2473              --  warning, we just suppress the warning in this case.
2474
2475              and then Nkind (Name (Item)) in N_Has_Entity
2476              and then Present (Entity (Name (Item)))
2477            then
2478               Lunit := Entity (Name (Item));
2479
2480               --  Check if this unit is referenced (skip the check if this
2481               --  is explicitly marked by a pragma Unreferenced).
2482
2483               if not Referenced (Lunit) and then not Has_Unreferenced (Lunit)
2484               then
2485                  --  Suppress warnings in internal units if not in -gnatg mode
2486                  --  (these would be junk warnings for an application program,
2487                  --  since they refer to problems in internal units).
2488
2489                  if GNAT_Mode or else not Is_Internal_Unit (Unit) then
2490                     --  Here we definitely have a non-referenced unit. If it
2491                     --  is the special call for a spec unit, then just set the
2492                     --  flag to be read later.
2493
2494                     if Unit = Spec_Unit then
2495                        Set_Unreferenced_In_Spec (Item);
2496
2497                     --  Otherwise simple unreferenced message, but skip this
2498                     --  if no visible entities, because that is most likely a
2499                     --  case where warning would be false positive (e.g. a
2500                     --  package with only a linker options pragma and nothing
2501                     --  else or a pragma elaborate with a body library task).
2502
2503                     elsif Has_Visible_Entities (Entity (Name (Item))) then
2504                        Error_Msg_N -- CODEFIX
2505                          ("?u?unit& is not referenced!", Name (Item));
2506                     end if;
2507                  end if;
2508
2509               --  If main unit is a renaming of this unit, then we consider
2510               --  the with to be OK (obviously it is needed in this case).
2511               --  This may be transitive: the unit in the with_clause may
2512               --  itself be a renaming, in which case both it and the main
2513               --  unit rename the same ultimate package.
2514
2515               elsif Present (Renamed_Entity (Munite))
2516                  and then
2517                    (Renamed_Entity (Munite) = Lunit
2518                      or else Renamed_Entity (Munite) = Renamed_Entity (Lunit))
2519               then
2520                  null;
2521
2522               --  If this unit is referenced, and it is a package, we do
2523               --  another test, to see if any of the entities in the package
2524               --  are referenced. If none of the entities are referenced, we
2525               --  still post a warning. This occurs if the only use of the
2526               --  package is in a use clause, or in a package renaming
2527               --  declaration. This check is skipped for packages that are
2528               --  renamed in a spec, since the entities in such a package are
2529               --  visible to clients via the renaming.
2530
2531               elsif Ekind (Lunit) = E_Package
2532                 and then not Renamed_In_Spec (Lunit)
2533               then
2534                  --  If Is_Instantiated is set, it means that the package is
2535                  --  implicitly instantiated (this is the case of parent
2536                  --  instance or an actual for a generic package formal), and
2537                  --  this counts as a reference.
2538
2539                  if Is_Instantiated (Lunit) then
2540                     null;
2541
2542                  --  If no entities in package, and there is a pragma
2543                  --  Elaborate_Body present, then assume that this with is
2544                  --  done for purposes of this elaboration.
2545
2546                  elsif No (First_Entity (Lunit))
2547                    and then Has_Pragma_Elaborate_Body (Lunit)
2548                  then
2549                     null;
2550
2551                  --  Otherwise see if any entities have been referenced
2552
2553                  else
2554                     if Limited_Present (Item) then
2555                        Ent := First_Entity (Limited_View (Lunit));
2556                     else
2557                        Ent := First_Entity (Lunit);
2558                     end if;
2559
2560                     loop
2561                        --  No more entities, and we did not find one that was
2562                        --  referenced. Means we have a definite case of a with
2563                        --  none of whose entities was referenced.
2564
2565                        if No (Ent) then
2566
2567                           --  If in spec, just set the flag
2568
2569                           if Unit = Spec_Unit then
2570                              Set_No_Entities_Ref_In_Spec (Item);
2571
2572                           elsif Check_System_Aux then
2573                              null;
2574
2575                           --  Else the warning may be needed
2576
2577                           else
2578                              declare
2579                                 Eitem : constant Entity_Id :=
2580                                           Entity (Name (Item));
2581
2582                              begin
2583                                 --  Warn if we unreferenced flag set and we
2584                                 --  have not had serious errors. The reason we
2585                                 --  inhibit the message if there are errors is
2586                                 --  to prevent false positives from disabling
2587                                 --  expansion.
2588
2589                                 if not Has_Unreferenced (Eitem)
2590                                   and then Serious_Errors_Detected = 0
2591                                 then
2592                                    --  Get possible package renaming
2593
2594                                    Pack :=
2595                                      Find_Package_Renaming (Munite, Lunit);
2596
2597                                    --  No warning if either the package or its
2598                                    --  renaming is used as a generic actual.
2599
2600                                    if Used_As_Generic_Actual (Eitem)
2601                                      or else
2602                                        (Present (Pack)
2603                                          and then
2604                                            Used_As_Generic_Actual (Pack))
2605                                    then
2606                                       exit;
2607                                    end if;
2608
2609                                    --  Here we give the warning
2610
2611                                    Error_Msg_N -- CODEFIX
2612                                      ("?u?no entities of & are referenced!",
2613                                       Name (Item));
2614
2615                                    --  Flag renaming of package as well. If
2616                                    --  the original package has warnings off,
2617                                    --  we suppress the warning on the renaming
2618                                    --  as well.
2619
2620                                    if Present (Pack)
2621                                      and then not Has_Warnings_Off (Lunit)
2622                                      and then not Has_Unreferenced (Pack)
2623                                    then
2624                                       Error_Msg_NE -- CODEFIX
2625                                         ("?u?no entities of& are referenced!",
2626                                          Unit_Declaration_Node (Pack), Pack);
2627                                    end if;
2628                                 end if;
2629                              end;
2630                           end if;
2631
2632                           exit;
2633
2634                        --  Case of entity being referenced. The reference may
2635                        --  come from a limited_with_clause, in which case the
2636                        --  limited view of the entity carries the flag.
2637
2638                        elsif Referenced_Check_Spec (Ent)
2639                          or else Referenced_As_LHS_Check_Spec (Ent)
2640                          or else Referenced_As_Out_Parameter_Check_Spec (Ent)
2641                          or else
2642                            (From_Limited_With (Ent)
2643                              and then Is_Incomplete_Type (Ent)
2644                              and then Present (Non_Limited_View (Ent))
2645                              and then Referenced (Non_Limited_View (Ent)))
2646                        then
2647                           --  This means that the with is indeed fine, in that
2648                           --  it is definitely needed somewhere, and we can
2649                           --  quit worrying about this one...
2650
2651                           --  Except for one little detail: if either of the
2652                           --  flags was set during spec processing, this is
2653                           --  where we complain that the with could be moved
2654                           --  from the spec. If the spec contains a visible
2655                           --  renaming of the package, inhibit warning to move
2656                           --  with_clause to body.
2657
2658                           if Ekind (Munite) = E_Package_Body then
2659                              Pack :=
2660                                Find_Package_Renaming
2661                                  (Spec_Entity (Munite), Lunit);
2662                           else
2663                              Pack := Empty;
2664                           end if;
2665
2666                           --  If a renaming is present in the spec do not warn
2667                           --  because the body or child unit may depend on it.
2668
2669                           if Present (Pack)
2670                             and then Renamed_Entity (Pack) = Lunit
2671                           then
2672                              exit;
2673
2674                           elsif Unreferenced_In_Spec (Item) then
2675                              Error_Msg_N -- CODEFIX
2676                                ("?u?unit& is not referenced in spec!",
2677                                 Name (Item));
2678
2679                           elsif No_Entities_Ref_In_Spec (Item) then
2680                              Error_Msg_N -- CODEFIX
2681                                ("?u?no entities of & are referenced in spec!",
2682                                 Name (Item));
2683
2684                           else
2685                              if Ekind (Ent) = E_Package then
2686                                 Check_Inner_Package (Ent);
2687                              end if;
2688
2689                              exit;
2690                           end if;
2691
2692                           if not Is_Visible_Renaming then
2693                              Error_Msg_N -- CODEFIX
2694                                ("\?u?with clause might be moved to body!",
2695                                 Name (Item));
2696                           end if;
2697
2698                           exit;
2699
2700                        --  Move to next entity to continue search
2701
2702                        else
2703                           Next_Entity (Ent);
2704                        end if;
2705                     end loop;
2706                  end if;
2707
2708               --  For a generic package, the only interesting kind of
2709               --  reference is an instantiation, since entities cannot be
2710               --  referenced directly.
2711
2712               elsif Is_Generic_Unit (Lunit) then
2713
2714                  --  Unit was never instantiated, set flag for case of spec
2715                  --  call, or give warning for normal call.
2716
2717                  if not Is_Instantiated (Lunit) then
2718                     if Unit = Spec_Unit then
2719                        Set_Unreferenced_In_Spec (Item);
2720                     else
2721                        Error_Msg_N -- CODEFIX
2722                          ("?u?unit& is never instantiated!", Name (Item));
2723                     end if;
2724
2725                  --  If unit was indeed instantiated, make sure that flag is
2726                  --  not set showing it was uninstantiated in the spec, and if
2727                  --  so, give warning.
2728
2729                  elsif Unreferenced_In_Spec (Item) then
2730                     Error_Msg_N
2731                       ("?u?unit& is not instantiated in spec!", Name (Item));
2732                     Error_Msg_N -- CODEFIX
2733                       ("\?u?with clause can be moved to body!", Name (Item));
2734                  end if;
2735               end if;
2736            end if;
2737
2738            Next (Item);
2739         end loop;
2740      end Check_One_Unit;
2741
2742   --  Start of processing for Check_Unused_Withs
2743
2744   begin
2745      --  Immediate return if no semantics or warning flag not set
2746
2747      if not Opt.Check_Withs or else Operating_Mode = Check_Syntax then
2748         return;
2749      end if;
2750
2751      Process_Deferred_References;
2752
2753      --  Flag any unused with clauses. For a subunit, check only the units
2754      --  in its context, not those of the parent, which may be needed by other
2755      --  subunits. We will get the full warnings when we compile the parent,
2756      --  but the following is helpful when compiling a subunit by itself.
2757
2758      if Nkind (Unit (Cunit (Main_Unit))) = N_Subunit then
2759         if Current_Sem_Unit = Main_Unit then
2760            Check_One_Unit (Main_Unit);
2761         end if;
2762
2763         return;
2764      end if;
2765
2766      --  Process specified units
2767
2768      if Spec_Unit = No_Unit then
2769
2770         --  For main call, check all units
2771
2772         for Unit in Main_Unit .. Last_Unit loop
2773            Check_One_Unit (Unit);
2774         end loop;
2775
2776      else
2777         --  For call for spec, check only the spec
2778
2779         Check_One_Unit (Spec_Unit);
2780      end if;
2781   end Check_Unused_Withs;
2782
2783   ---------------------------------
2784   -- Generic_Package_Spec_Entity --
2785   ---------------------------------
2786
2787   function Generic_Package_Spec_Entity (E : Entity_Id) return Boolean is
2788      S : Entity_Id;
2789
2790   begin
2791      if Is_Package_Body_Entity (E) then
2792         return False;
2793
2794      else
2795         S := Scope (E);
2796         loop
2797            if S = Standard_Standard then
2798               return False;
2799
2800            elsif Ekind (S) = E_Generic_Package then
2801               return True;
2802
2803            elsif Ekind (S) = E_Package then
2804               S := Scope (S);
2805
2806            else
2807               return False;
2808            end if;
2809         end loop;
2810      end if;
2811   end Generic_Package_Spec_Entity;
2812
2813   ----------------------
2814   -- Goto_Spec_Entity --
2815   ----------------------
2816
2817   function Goto_Spec_Entity (E : Entity_Id) return Entity_Id is
2818   begin
2819      if Is_Formal (E) and then Present (Spec_Entity (E)) then
2820         return Spec_Entity (E);
2821      else
2822         return E;
2823      end if;
2824   end Goto_Spec_Entity;
2825
2826   -------------------
2827   -- Has_Junk_Name --
2828   -------------------
2829
2830   function Has_Junk_Name (E : Entity_Id) return Boolean is
2831      function Match (S : String) return Boolean;
2832      --  Return true if substring S is found in Name_Buffer (1 .. Name_Len)
2833
2834      -----------
2835      -- Match --
2836      -----------
2837
2838      function Match (S : String) return Boolean is
2839         Slen1 : constant Integer := S'Length - 1;
2840
2841      begin
2842         for J in 1 .. Name_Len - S'Length + 1 loop
2843            if Name_Buffer (J .. J + Slen1) = S then
2844               return True;
2845            end if;
2846         end loop;
2847
2848         return False;
2849      end Match;
2850
2851   --  Start of processing for Has_Junk_Name
2852
2853   begin
2854      Get_Unqualified_Decoded_Name_String (Chars (E));
2855
2856      return
2857        Match ("discard") or else
2858        Match ("dummy")   or else
2859        Match ("ignore")  or else
2860        Match ("junk")    or else
2861        Match ("unused");
2862   end Has_Junk_Name;
2863
2864   --------------------------------------
2865   -- Has_Pragma_Unmodified_Check_Spec --
2866   --------------------------------------
2867
2868   function Has_Pragma_Unmodified_Check_Spec
2869     (E : Entity_Id) return Boolean
2870   is
2871   begin
2872      if Is_Formal (E) and then Present (Spec_Entity (E)) then
2873
2874         --  Note: use of OR instead of OR ELSE here is deliberate, we want
2875         --  to mess with Unmodified flags on both body and spec entities.
2876         --  Has_Unmodified has side effects!
2877
2878         return Has_Unmodified (E)
2879                  or
2880                Has_Unmodified (Spec_Entity (E));
2881
2882      else
2883         return Has_Unmodified (E);
2884      end if;
2885   end Has_Pragma_Unmodified_Check_Spec;
2886
2887   ----------------------------------------
2888   -- Has_Pragma_Unreferenced_Check_Spec --
2889   ----------------------------------------
2890
2891   function Has_Pragma_Unreferenced_Check_Spec
2892     (E : Entity_Id) return Boolean
2893   is
2894   begin
2895      if Is_Formal (E) and then Present (Spec_Entity (E)) then
2896
2897         --  Note: use of OR here instead of OR ELSE is deliberate, we want
2898         --  to mess with flags on both entities.
2899
2900         return Has_Unreferenced (E)
2901                  or
2902                Has_Unreferenced (Spec_Entity (E));
2903
2904      else
2905         return Has_Unreferenced (E);
2906      end if;
2907   end Has_Pragma_Unreferenced_Check_Spec;
2908
2909   ----------------
2910   -- Initialize --
2911   ----------------
2912
2913   procedure Initialize is
2914   begin
2915      Warnings_Off_Pragmas.Init;
2916      Unreferenced_Entities.Init;
2917      In_Out_Warnings.Init;
2918   end Initialize;
2919
2920   ---------------------------------------------
2921   -- Is_Attribute_And_Known_Value_Comparison --
2922   ---------------------------------------------
2923
2924   function Is_Attribute_And_Known_Value_Comparison
2925     (Op : Node_Id) return Boolean
2926   is
2927      Orig_Op : constant Node_Id := Original_Node (Op);
2928
2929   begin
2930      return
2931        Nkind (Orig_Op) in N_Op_Compare
2932          and then Nkind (Original_Node (Left_Opnd (Orig_Op))) =
2933                     N_Attribute_Reference
2934          and then Compile_Time_Known_Value (Right_Opnd (Orig_Op));
2935   end Is_Attribute_And_Known_Value_Comparison;
2936
2937   ------------------------------------
2938   -- Never_Set_In_Source_Check_Spec --
2939   ------------------------------------
2940
2941   function Never_Set_In_Source_Check_Spec (E : Entity_Id) return Boolean is
2942   begin
2943      if Is_Formal (E) and then Present (Spec_Entity (E)) then
2944         return Never_Set_In_Source (E)
2945                  and then
2946                Never_Set_In_Source (Spec_Entity (E));
2947      else
2948         return Never_Set_In_Source (E);
2949      end if;
2950   end Never_Set_In_Source_Check_Spec;
2951
2952   -------------------------------------
2953   -- Operand_Has_Warnings_Suppressed --
2954   -------------------------------------
2955
2956   function Operand_Has_Warnings_Suppressed (N : Node_Id) return Boolean is
2957
2958      function Check_For_Warnings (N : Node_Id) return Traverse_Result;
2959      --  Function used to check one node to see if it is or was originally
2960      --  a reference to an entity for which Warnings are off. If so, Abandon
2961      --  is returned, otherwise OK_Orig is returned to continue the traversal
2962      --  of the original expression.
2963
2964      function Traverse is new Traverse_Func (Check_For_Warnings);
2965      --  Function used to traverse tree looking for warnings
2966
2967      ------------------------
2968      -- Check_For_Warnings --
2969      ------------------------
2970
2971      function Check_For_Warnings (N : Node_Id) return Traverse_Result is
2972         R : constant Node_Id := Original_Node (N);
2973
2974      begin
2975         if Nkind (R) in N_Has_Entity
2976           and then Present (Entity (R))
2977           and then Has_Warnings_Off (Entity (R))
2978         then
2979            return Abandon;
2980         else
2981            return OK_Orig;
2982         end if;
2983      end Check_For_Warnings;
2984
2985   --  Start of processing for Operand_Has_Warnings_Suppressed
2986
2987   begin
2988      return Traverse (N) = Abandon;
2989
2990   --  If any exception occurs, then something has gone wrong, and this is
2991   --  only a minor aesthetic issue anyway, so just say we did not find what
2992   --  we are looking for, rather than blow up.
2993
2994   exception
2995      when others =>
2996         return False;
2997   end Operand_Has_Warnings_Suppressed;
2998
2999   -----------------------------------------
3000   -- Output_Non_Modified_In_Out_Warnings --
3001   -----------------------------------------
3002
3003   procedure Output_Non_Modified_In_Out_Warnings is
3004
3005      function No_Warn_On_In_Out (E : Entity_Id) return Boolean;
3006      --  Given a formal parameter entity E, determines if there is a reason to
3007      --  suppress IN OUT warnings (not modified, could be IN) for formals of
3008      --  the subprogram. We suppress these warnings if Warnings Off is set, or
3009      --  if we have seen the address of the subprogram being taken, or if the
3010      --  subprogram is used as a generic actual (in the latter cases the
3011      --  context may force use of IN OUT, even if the parameter is not
3012      --  modifies for this particular case.
3013
3014      -----------------------
3015      -- No_Warn_On_In_Out --
3016      -----------------------
3017
3018      function No_Warn_On_In_Out (E : Entity_Id) return Boolean is
3019         S  : constant Entity_Id := Scope (E);
3020         SE : constant Entity_Id := Spec_Entity (E);
3021
3022      begin
3023         --  Do not warn if address is taken, since funny business may be going
3024         --  on in treating the parameter indirectly as IN OUT.
3025
3026         if Address_Taken (S)
3027           or else (Present (SE) and then Address_Taken (Scope (SE)))
3028         then
3029            return True;
3030
3031         --  Do not warn if used as a generic actual, since the generic may be
3032         --  what is forcing the use of an "unnecessary" IN OUT.
3033
3034         elsif Used_As_Generic_Actual (S)
3035           or else (Present (SE) and then Used_As_Generic_Actual (Scope (SE)))
3036         then
3037            return True;
3038
3039         --  Else test warnings off
3040
3041         elsif Warnings_Off_Check_Spec (S) then
3042            return True;
3043
3044         --  All tests for suppressing warning failed
3045
3046         else
3047            return False;
3048         end if;
3049      end No_Warn_On_In_Out;
3050
3051   --  Start of processing for Output_Non_Modified_In_Out_Warnings
3052
3053   begin
3054      --  Loop through entities for which a warning may be needed
3055
3056      for J in In_Out_Warnings.First .. In_Out_Warnings.Last loop
3057         declare
3058            E1 : constant Entity_Id := In_Out_Warnings.Table (J);
3059
3060         begin
3061            --  Suppress warning in specific cases (see details in comments for
3062            --  No_Warn_On_In_Out), or if there is a pragma Unmodified.
3063
3064            if Has_Pragma_Unmodified_Check_Spec (E1)
3065              or else No_Warn_On_In_Out (E1)
3066            then
3067               null;
3068
3069            --  Here we generate the warning
3070
3071            else
3072               --  If -gnatwc is set then output message that we could be IN
3073
3074               if not Is_Trivial_Subprogram (Scope (E1)) then
3075                  if Warn_On_Constant then
3076                     Error_Msg_N
3077                       ("?u?formal parameter & is not modified!", E1);
3078                     Error_Msg_N
3079                       ("\?u?mode could be IN instead of `IN OUT`!", E1);
3080
3081                     --  We do not generate warnings for IN OUT parameters
3082                     --  unless we have at least -gnatwu. This is deliberately
3083                     --  inconsistent with the treatment of variables, but
3084                     --  otherwise we get too many unexpected warnings in
3085                     --  default mode.
3086
3087                  elsif Check_Unreferenced then
3088                     Error_Msg_N
3089                       ("?u?formal parameter& is read but "
3090                        & "never assigned!", E1);
3091                  end if;
3092               end if;
3093
3094               --  Kill any other warnings on this entity, since this is the
3095               --  one that should dominate any other unreferenced warning.
3096
3097               Set_Warnings_Off (E1);
3098            end if;
3099         end;
3100      end loop;
3101   end Output_Non_Modified_In_Out_Warnings;
3102
3103   ----------------------------------------
3104   -- Output_Obsolescent_Entity_Warnings --
3105   ----------------------------------------
3106
3107   procedure Output_Obsolescent_Entity_Warnings (N : Node_Id; E : Entity_Id) is
3108      P : constant Node_Id := Parent (N);
3109      S : Entity_Id;
3110
3111   begin
3112      S := Current_Scope;
3113
3114      --  Do not output message if we are the scope of standard. This means
3115      --  we have a reference from a context clause from when it is originally
3116      --  processed, and that's too early to tell whether it is an obsolescent
3117      --  unit doing the with'ing. In Sem_Ch10.Analyze_Compilation_Unit we make
3118      --  sure that we have a later call when the scope is available. This test
3119      --  also eliminates all messages for use clauses, which is fine (we do
3120      --  not want messages for use clauses, since they are always redundant
3121      --  with respect to the associated with clause).
3122
3123      if S = Standard_Standard then
3124         return;
3125      end if;
3126
3127      --  Do not output message if we are in scope of an obsolescent package
3128      --  or subprogram.
3129
3130      loop
3131         if Is_Obsolescent (S) then
3132            return;
3133         end if;
3134
3135         S := Scope (S);
3136         exit when S = Standard_Standard;
3137      end loop;
3138
3139      --  Here we will output the message
3140
3141      Error_Msg_Sloc := Sloc (E);
3142
3143      --  Case of with clause
3144
3145      if Nkind (P) = N_With_Clause then
3146         if Ekind (E) = E_Package then
3147            Error_Msg_NE
3148              ("?j?with of obsolescent package& declared#", N, E);
3149         elsif Ekind (E) = E_Procedure then
3150            Error_Msg_NE
3151              ("?j?with of obsolescent procedure& declared#", N, E);
3152         else
3153            Error_Msg_NE
3154              ("??with of obsolescent function& declared#", N, E);
3155         end if;
3156
3157      --  If we do not have a with clause, then ignore any reference to an
3158      --  obsolescent package name. We only want to give the one warning of
3159      --  withing the package, not one each time it is used to qualify.
3160
3161      elsif Ekind (E) = E_Package then
3162         return;
3163
3164      --  Procedure call statement
3165
3166      elsif Nkind (P) = N_Procedure_Call_Statement then
3167         Error_Msg_NE
3168           ("??call to obsolescent procedure& declared#", N, E);
3169
3170      --  Function call
3171
3172      elsif Nkind (P) = N_Function_Call then
3173         Error_Msg_NE
3174           ("??call to obsolescent function& declared#", N, E);
3175
3176      --  Reference to obsolescent type
3177
3178      elsif Is_Type (E) then
3179         Error_Msg_NE
3180           ("??reference to obsolescent type& declared#", N, E);
3181
3182      --  Reference to obsolescent component
3183
3184      elsif Ekind_In (E, E_Component, E_Discriminant) then
3185         Error_Msg_NE
3186           ("??reference to obsolescent component& declared#", N, E);
3187
3188      --  Reference to obsolescent variable
3189
3190      elsif Ekind (E) = E_Variable then
3191         Error_Msg_NE
3192           ("??reference to obsolescent variable& declared#", N, E);
3193
3194      --  Reference to obsolescent constant
3195
3196      elsif Ekind (E) = E_Constant or else Ekind (E) in Named_Kind then
3197         Error_Msg_NE
3198           ("??reference to obsolescent constant& declared#", N, E);
3199
3200      --  Reference to obsolescent enumeration literal
3201
3202      elsif Ekind (E) = E_Enumeration_Literal then
3203         Error_Msg_NE
3204           ("??reference to obsolescent enumeration literal& declared#", N, E);
3205
3206      --  Generic message for any other case we missed
3207
3208      else
3209         Error_Msg_NE
3210           ("??reference to obsolescent entity& declared#", N, E);
3211      end if;
3212
3213      --  Output additional warning if present
3214
3215      for J in Obsolescent_Warnings.First .. Obsolescent_Warnings.Last loop
3216         if Obsolescent_Warnings.Table (J).Ent = E then
3217            String_To_Name_Buffer (Obsolescent_Warnings.Table (J).Msg);
3218            Error_Msg_Strlen := Name_Len;
3219            Error_Msg_String (1 .. Name_Len) := Name_Buffer (1 .. Name_Len);
3220            Error_Msg_N ("\\??~", N);
3221            exit;
3222         end if;
3223      end loop;
3224   end Output_Obsolescent_Entity_Warnings;
3225
3226   ----------------------------------
3227   -- Output_Unreferenced_Messages --
3228   ----------------------------------
3229
3230   procedure Output_Unreferenced_Messages is
3231   begin
3232      for J in Unreferenced_Entities.First .. Unreferenced_Entities.Last loop
3233         Warn_On_Unreferenced_Entity (Unreferenced_Entities.Table (J));
3234      end loop;
3235   end Output_Unreferenced_Messages;
3236
3237   -----------------------------------------
3238   -- Output_Unused_Warnings_Off_Warnings --
3239   -----------------------------------------
3240
3241   procedure Output_Unused_Warnings_Off_Warnings is
3242   begin
3243      for J in Warnings_Off_Pragmas.First .. Warnings_Off_Pragmas.Last loop
3244         declare
3245            Wentry : Warnings_Off_Entry renames Warnings_Off_Pragmas.Table (J);
3246            N      : Node_Id renames Wentry.N;
3247            E      : Node_Id renames Wentry.E;
3248
3249         begin
3250            --  Turn off Warnings_Off, or we won't get the warning
3251
3252            Set_Warnings_Off (E, False);
3253
3254            --  Nothing to do if pragma was used to suppress a general warning
3255
3256            if Warnings_Off_Used (E) then
3257               null;
3258
3259            --  If pragma was used both in unmodified and unreferenced contexts
3260            --  then that's as good as the general case, no warning.
3261
3262            elsif Warnings_Off_Used_Unmodified (E)
3263                    and
3264                  Warnings_Off_Used_Unreferenced (E)
3265            then
3266               null;
3267
3268            --  Used only in context where Unmodified would have worked
3269
3270            elsif Warnings_Off_Used_Unmodified (E) then
3271               Error_Msg_NE
3272                 ("?W?could use Unmodified instead of "
3273                  & "Warnings Off for &", Pragma_Identifier (N), E);
3274
3275            --  Used only in context where Unreferenced would have worked
3276
3277            elsif Warnings_Off_Used_Unreferenced (E) then
3278               Error_Msg_NE
3279                 ("?W?could use Unreferenced instead of "
3280                  & "Warnings Off for &", Pragma_Identifier (N), E);
3281
3282            --  Not used at all
3283
3284            else
3285               Error_Msg_NE
3286                 ("?W?pragma Warnings Off for & unused, "
3287                  & "could be omitted", N, E);
3288            end if;
3289         end;
3290      end loop;
3291   end Output_Unused_Warnings_Off_Warnings;
3292
3293   ---------------------------
3294   -- Referenced_Check_Spec --
3295   ---------------------------
3296
3297   function Referenced_Check_Spec (E : Entity_Id) return Boolean is
3298   begin
3299      if Is_Formal (E) and then Present (Spec_Entity (E)) then
3300         return Referenced (E) or else Referenced (Spec_Entity (E));
3301      else
3302         return Referenced (E);
3303      end if;
3304   end Referenced_Check_Spec;
3305
3306   ----------------------------------
3307   -- Referenced_As_LHS_Check_Spec --
3308   ----------------------------------
3309
3310   function Referenced_As_LHS_Check_Spec (E : Entity_Id) return Boolean is
3311   begin
3312      if Is_Formal (E) and then Present (Spec_Entity (E)) then
3313         return Referenced_As_LHS (E)
3314           or else Referenced_As_LHS (Spec_Entity (E));
3315      else
3316         return Referenced_As_LHS (E);
3317      end if;
3318   end Referenced_As_LHS_Check_Spec;
3319
3320   --------------------------------------------
3321   -- Referenced_As_Out_Parameter_Check_Spec --
3322   --------------------------------------------
3323
3324   function Referenced_As_Out_Parameter_Check_Spec
3325     (E : Entity_Id) return Boolean
3326   is
3327   begin
3328      if Is_Formal (E) and then Present (Spec_Entity (E)) then
3329         return Referenced_As_Out_Parameter (E)
3330           or else Referenced_As_Out_Parameter (Spec_Entity (E));
3331      else
3332         return Referenced_As_Out_Parameter (E);
3333      end if;
3334   end Referenced_As_Out_Parameter_Check_Spec;
3335
3336   --------------------------------------
3337   -- Warn_On_Constant_Valid_Condition --
3338   --------------------------------------
3339
3340   procedure Warn_On_Constant_Valid_Condition (Op : Node_Id) is
3341      Left  : constant Node_Id := Left_Opnd  (Op);
3342      Right : constant Node_Id := Right_Opnd (Op);
3343
3344      True_Result  : Boolean;
3345      False_Result : Boolean;
3346
3347   begin
3348      --  Determine the potential outcome of the comparison assuming that the
3349      --  scalar operands are valid.
3350
3351      if Constant_Condition_Warnings
3352        and then Comes_From_Source (Original_Node (Op))
3353        and then Is_Scalar_Type (Etype (Left))
3354        and then Is_Scalar_Type (Etype (Right))
3355
3356        --  Do not consider instances because the check was already performed
3357        --  in the generic.
3358
3359        and then not In_Instance
3360
3361        --  Do not consider comparisons between two static expressions such as
3362        --  constants or literals because those values cannot be invalidated.
3363
3364        and then not (Is_Static_Expression (Left)
3365                       and then Is_Static_Expression (Right))
3366
3367        --  Do not consider comparison between an attribute reference and a
3368        --  compile-time known value since this is most likely a conditional
3369        --  compilation.
3370
3371        and then not Is_Attribute_And_Known_Value_Comparison (Op)
3372
3373        --  Do not consider internal files to allow for various assertions and
3374        --  safeguards within our runtime.
3375
3376        and then not In_Internal_Unit (Op)
3377      then
3378         Test_Comparison
3379           (Op           => Op,
3380            Assume_Valid => True,
3381            True_Result  => True_Result,
3382            False_Result => False_Result);
3383
3384         --  Warn on a possible evaluation to False / True in the presence of
3385         --  invalid values.
3386
3387         if True_Result then
3388            Error_Msg_N
3389              ("condition can only be False if invalid values present??", Op);
3390
3391         elsif False_Result then
3392            Error_Msg_N
3393              ("condition can only be True if invalid values present??", Op);
3394         end if;
3395      end if;
3396   end Warn_On_Constant_Valid_Condition;
3397
3398   -----------------------------
3399   -- Warn_On_Known_Condition --
3400   -----------------------------
3401
3402   procedure Warn_On_Known_Condition (C : Node_Id) is
3403      Test_Result : Boolean := False;
3404      --  Force initialization to facilitate static analysis
3405
3406      function Is_Known_Branch return Boolean;
3407      --  If the type of the condition is Boolean, the constant value of the
3408      --  condition is a boolean literal. If the type is a derived boolean
3409      --  type, the constant is wrapped in a type conversion of the derived
3410      --  literal. If the value of the condition is not a literal, no warnings
3411      --  can be produced. This function returns True if the result can be
3412      --  determined, and Test_Result is set True/False accordingly. Otherwise
3413      --  False is returned, and Test_Result is unchanged.
3414
3415      procedure Track (N : Node_Id; Loc : Node_Id);
3416      --  Adds continuation warning(s) pointing to reason (assignment or test)
3417      --  for the operand of the conditional having a known value (or at least
3418      --  enough is known about the value to issue the warning). N is the node
3419      --  which is judged to have a known value. Loc is the warning location.
3420
3421      ---------------------
3422      -- Is_Known_Branch --
3423      ---------------------
3424
3425      function Is_Known_Branch return Boolean is
3426      begin
3427         if Etype (C) = Standard_Boolean
3428           and then Is_Entity_Name (C)
3429           and then
3430             (Entity (C) = Standard_False or else Entity (C) = Standard_True)
3431         then
3432            Test_Result := Entity (C) = Standard_True;
3433            return True;
3434
3435         elsif Is_Boolean_Type (Etype (C))
3436           and then Nkind (C) = N_Unchecked_Type_Conversion
3437           and then Is_Entity_Name (Expression (C))
3438           and then Ekind (Entity (Expression (C))) = E_Enumeration_Literal
3439         then
3440            Test_Result :=
3441              Chars (Entity (Expression (C))) = Chars (Standard_True);
3442            return True;
3443
3444         else
3445            return False;
3446         end if;
3447      end Is_Known_Branch;
3448
3449      -----------
3450      -- Track --
3451      -----------
3452
3453      procedure Track (N : Node_Id; Loc : Node_Id) is
3454         Nod : constant Node_Id := Original_Node (N);
3455
3456      begin
3457         if Nkind (Nod) in N_Op_Compare then
3458            Track (Left_Opnd (Nod), Loc);
3459            Track (Right_Opnd (Nod), Loc);
3460
3461         elsif Is_Entity_Name (Nod) and then Is_Object (Entity (Nod)) then
3462            declare
3463               CV : constant Node_Id := Current_Value (Entity (Nod));
3464
3465            begin
3466               if Present (CV) then
3467                  Error_Msg_Sloc := Sloc (CV);
3468
3469                  if Nkind (CV) not in N_Subexpr then
3470                     Error_Msg_N ("\\??(see test #)", Loc);
3471
3472                  elsif Nkind (Parent (CV)) =
3473                          N_Case_Statement_Alternative
3474                  then
3475                     Error_Msg_N ("\\??(see case alternative #)", Loc);
3476
3477                  else
3478                     Error_Msg_N ("\\??(see assignment #)", Loc);
3479                  end if;
3480               end if;
3481            end;
3482         end if;
3483      end Track;
3484
3485      --  Local variables
3486
3487      Orig : constant Node_Id := Original_Node (C);
3488      P    : Node_Id;
3489
3490   --  Start of processing for Warn_On_Known_Condition
3491
3492   begin
3493      --  Adjust SCO condition if from source
3494
3495      if Generate_SCO
3496        and then Comes_From_Source (Orig)
3497        and then Is_Known_Branch
3498      then
3499         declare
3500            Atrue : Boolean;
3501
3502         begin
3503            Atrue := Test_Result;
3504
3505            if Present (Parent (C)) and then Nkind (Parent (C)) = N_Op_Not then
3506               Atrue := not Atrue;
3507            end if;
3508
3509            Set_SCO_Condition (Orig, Atrue);
3510         end;
3511      end if;
3512
3513      --  Argument replacement in an inlined body can make conditions static.
3514      --  Do not emit warnings in this case.
3515
3516      if In_Inlined_Body then
3517         return;
3518      end if;
3519
3520      if Constant_Condition_Warnings
3521        and then Is_Known_Branch
3522        and then Comes_From_Source (Orig)
3523        and then not In_Instance
3524      then
3525         --  Don't warn if comparison of result of attribute against a constant
3526         --  value, since this is likely legitimate conditional compilation.
3527
3528         if Is_Attribute_And_Known_Value_Comparison (C) then
3529            return;
3530         end if;
3531
3532         --  See if this is in a statement or a declaration
3533
3534         P := Parent (C);
3535         loop
3536            --  If tree is not attached, do not issue warning (this is very
3537            --  peculiar, and probably arises from some other error condition).
3538
3539            if No (P) then
3540               return;
3541
3542            --  If we are in a declaration, then no warning, since in practice
3543            --  conditionals in declarations are used for intended tests which
3544            --  may be known at compile time, e.g. things like
3545
3546            --    x : constant Integer := 2 + (Word'Size = 32);
3547
3548            --  And a warning is annoying in such cases
3549
3550            elsif Nkind (P) in N_Declaration
3551                    or else
3552                  Nkind (P) in N_Later_Decl_Item
3553            then
3554               return;
3555
3556            --  Don't warn in assert or check pragma, since presumably tests in
3557            --  such a context are very definitely intended, and might well be
3558            --  known at compile time. Note that we have to test the original
3559            --  node, since assert pragmas get rewritten at analysis time.
3560
3561            elsif Nkind (Original_Node (P)) = N_Pragma
3562              and then Nam_In (Pragma_Name_Unmapped (Original_Node (P)),
3563                               Name_Assert, Name_Check)
3564            then
3565               return;
3566            end if;
3567
3568            exit when Is_Statement (P);
3569            P := Parent (P);
3570         end loop;
3571
3572         --  Here we issue the warning unless some sub-operand has warnings
3573         --  set off, in which case we suppress the warning for the node. If
3574         --  the original expression is an inequality, it has been expanded
3575         --  into a negation, and the value of the original expression is the
3576         --  negation of the equality. If the expression is an entity that
3577         --  appears within a negation, it is clearer to flag the negation
3578         --  itself, and report on its constant value.
3579
3580         if not Operand_Has_Warnings_Suppressed (C) then
3581            declare
3582               True_Branch : Boolean := Test_Result;
3583               Cond        : Node_Id := C;
3584
3585            begin
3586               if Present (Parent (C))
3587                 and then Nkind (Parent (C)) = N_Op_Not
3588               then
3589                  True_Branch := not True_Branch;
3590                  Cond := Parent (C);
3591               end if;
3592
3593               --  Condition always True
3594
3595               if True_Branch then
3596                  if Is_Entity_Name (Original_Node (C))
3597                    and then Nkind (Cond) /= N_Op_Not
3598                  then
3599                     Error_Msg_NE
3600                       ("object & is always True at this point?c?",
3601                        Cond, Original_Node (C));
3602                     Track (Original_Node (C), Cond);
3603
3604                  else
3605                     Error_Msg_N ("condition is always True?c?", Cond);
3606                     Track (Cond, Cond);
3607                  end if;
3608
3609               --  Condition always False
3610
3611               else
3612                  if Is_Entity_Name (Original_Node (C))
3613                    and then Nkind (Cond) /= N_Op_Not
3614                  then
3615                     Error_Msg_NE
3616                       ("object & is always False at this point?c?",
3617                        Cond, Original_Node (C));
3618                     Track (Original_Node (C), Cond);
3619
3620                  else
3621                     Error_Msg_N ("condition is always False?c?", Cond);
3622                     Track (Cond, Cond);
3623                  end if;
3624               end if;
3625            end;
3626         end if;
3627      end if;
3628   end Warn_On_Known_Condition;
3629
3630   ---------------------------------------
3631   -- Warn_On_Modified_As_Out_Parameter --
3632   ---------------------------------------
3633
3634   function Warn_On_Modified_As_Out_Parameter (E : Entity_Id) return Boolean is
3635   begin
3636      return
3637        (Warn_On_Modified_Unread and then Is_Only_Out_Parameter (E))
3638          or else Warn_On_All_Unread_Out_Parameters;
3639   end Warn_On_Modified_As_Out_Parameter;
3640
3641   ---------------------------------
3642   -- Warn_On_Overlapping_Actuals --
3643   ---------------------------------
3644
3645   procedure Warn_On_Overlapping_Actuals (Subp : Entity_Id; N : Node_Id) is
3646      function Is_Covered_Formal (Formal : Node_Id) return Boolean;
3647      --  Return True if Formal is covered by the rule
3648
3649      function Refer_Same_Object
3650        (Act1 : Node_Id;
3651         Act2 : Node_Id) return Boolean;
3652      --  Two names are known to refer to the same object if the two names
3653      --  are known to denote the same object; or one of the names is a
3654      --  selected_component, indexed_component, or slice and its prefix is
3655      --  known to refer to the same object as the other name; or one of the
3656      --  two names statically denotes a renaming declaration whose renamed
3657      --  object_name is known to refer to the same object as the other name
3658      --  (RM 6.4.1(6.11/3))
3659
3660      -----------------------
3661      -- Is_Covered_Formal --
3662      -----------------------
3663
3664      function Is_Covered_Formal (Formal : Node_Id) return Boolean is
3665      begin
3666         return
3667           Ekind_In (Formal, E_Out_Parameter, E_In_Out_Parameter)
3668             and then (Is_Elementary_Type (Etype (Formal))
3669                        or else Is_Record_Type (Etype (Formal))
3670                        or else Is_Array_Type (Etype (Formal)));
3671      end Is_Covered_Formal;
3672
3673      -----------------------
3674      -- Refer_Same_Object --
3675      -----------------------
3676
3677      function Refer_Same_Object
3678        (Act1 : Node_Id;
3679         Act2 : Node_Id) return Boolean
3680      is
3681      begin
3682         return
3683           Denotes_Same_Object (Act1, Act2)
3684             or else Denotes_Same_Prefix (Act1, Act2);
3685      end Refer_Same_Object;
3686
3687      --  Local variables
3688
3689      Act1      : Node_Id;
3690      Act2      : Node_Id;
3691      Form1     : Entity_Id;
3692      Form2     : Entity_Id;
3693      Warn_Only : Boolean;
3694      --  GNAT warns on overlapping in-out parameters of any type, not just for
3695      --  elementary in-out parameters (as specified in RM 6.4.1 (15/3-17/3)).
3696
3697   --  Start of processing for Warn_On_Overlapping_Actuals
3698
3699   begin
3700
3701      if Ada_Version < Ada_2012 and then not Warn_On_Overlap then
3702         return;
3703      end if;
3704
3705      --  The call is illegal only if there are at least two in-out parameters
3706      --  of the same elementary type.
3707
3708      Warn_Only := True;
3709      Form1 := First_Formal (Subp);
3710      while Present (Form1) loop
3711         Form2 := Next_Formal (Form1);
3712         while Present (Form2) loop
3713            if Is_Elementary_Type (Etype (Form1))
3714              and then Is_Elementary_Type (Etype (Form2))
3715              and then Ekind (Form1) /= E_In_Parameter
3716              and then Ekind (Form2) /= E_In_Parameter
3717            then
3718               Warn_Only := False;
3719               exit;
3720            end if;
3721
3722            Next_Formal (Form2);
3723         end loop;
3724
3725         Next_Formal (Form1);
3726      end loop;
3727
3728      --  Exclude calls rewritten as enumeration literals
3729
3730      if Nkind (N) not in N_Subprogram_Call
3731        and then Nkind (N) /= N_Entry_Call_Statement
3732      then
3733         return;
3734      end if;
3735
3736      --  If a call C has two or more parameters of mode in out or out that are
3737      --  of an elementary type, then the call is legal only if for each name
3738      --  N that is passed as a parameter of mode in out or out to the call C,
3739      --  there is no other name among the other parameters of mode in out or
3740      --  out to C that is known to denote the same object (RM 6.4.1(6.15/3))
3741
3742      --  If appropriate warning switch is set, we also report warnings on
3743      --  overlapping parameters that are record types or array types.
3744
3745      Form1 := First_Formal (Subp);
3746      Act1  := First_Actual (N);
3747      while Present (Form1) and then Present (Act1) loop
3748         if Is_Covered_Formal (Form1) then
3749            Form2 := First_Formal (Subp);
3750            Act2  := First_Actual (N);
3751            while Present (Form2) and then Present (Act2) loop
3752               if Form1 /= Form2
3753                 and then Is_Covered_Formal (Form2)
3754                 and then Refer_Same_Object (Act1, Act2)
3755               then
3756                  --  Guard against previous errors
3757
3758                  if Error_Posted (N)
3759                    or else No (Etype (Act1))
3760                    or else No (Etype (Act2))
3761                  then
3762                     null;
3763
3764                  --  If the actual is a function call in prefix notation,
3765                  --  there is no real overlap.
3766
3767                  elsif Nkind (Act2) = N_Function_Call then
3768                     null;
3769
3770                  --  If type is not by-copy, assume that aliasing is intended
3771
3772                  elsif
3773                    Present (Underlying_Type (Etype (Form1)))
3774                      and then
3775                        (Is_By_Reference_Type (Underlying_Type (Etype (Form1)))
3776                          or else
3777                            Convention (Underlying_Type (Etype (Form1))) =
3778                                              Convention_Ada_Pass_By_Reference)
3779                  then
3780                     null;
3781
3782                  --  Under Ada 2012 we only report warnings on overlapping
3783                  --  arrays and record types if switch is set.
3784
3785                  elsif Ada_Version >= Ada_2012
3786                    and then not Is_Elementary_Type (Etype (Form1))
3787                    and then not Warn_On_Overlap
3788                  then
3789                     null;
3790
3791                  --  Here we may need to issue overlap message
3792
3793                  else
3794                     Error_Msg_Warn :=
3795
3796                       --  Overlap checking is an error only in Ada 2012. For
3797                       --  earlier versions of Ada, this is a warning.
3798
3799                       Ada_Version < Ada_2012
3800
3801                       --  Overlap is only illegal in Ada 2012 in the case of
3802                       --  elementary types (passed by copy). For other types,
3803                       --  we always have a warning in all Ada versions.
3804
3805                       or else not Is_Elementary_Type (Etype (Form1))
3806
3807                       --  debug flag -gnatd.E changes the error to a warning
3808                       --  even in Ada 2012 mode.
3809
3810                       or else Error_To_Warning
3811                       or else Warn_Only;
3812
3813                     declare
3814                        Act  : Node_Id;
3815                        Form : Entity_Id;
3816
3817                     begin
3818                        --  Find matching actual
3819
3820                        Act  := First_Actual (N);
3821                        Form := First_Formal (Subp);
3822                        while Act /= Act2 loop
3823                           Next_Formal (Form);
3824                           Next_Actual (Act);
3825                        end loop;
3826
3827                        if Is_Elementary_Type (Etype (Act1))
3828                          and then Ekind (Form2) = E_In_Parameter
3829                        then
3830                           null;  --  No real aliasing
3831
3832                        elsif Is_Elementary_Type (Etype (Act2))
3833                          and then Ekind (Form2) = E_In_Parameter
3834                        then
3835                           null;  --  Ditto
3836
3837                        --  If the call was written in prefix notation, and
3838                        --  thus its prefix before rewriting was a selected
3839                        --  component, count only visible actuals in the call.
3840
3841                        elsif Is_Entity_Name (First_Actual (N))
3842                          and then Nkind (Original_Node (N)) = Nkind (N)
3843                          and then Nkind (Name (Original_Node (N))) =
3844                                                         N_Selected_Component
3845                          and then
3846                            Is_Entity_Name (Prefix (Name (Original_Node (N))))
3847                          and then
3848                            Entity (Prefix (Name (Original_Node (N)))) =
3849                              Entity (First_Actual (N))
3850                        then
3851                           if Act1 = First_Actual (N) then
3852                              Error_Msg_FE
3853                                ("<<`IN OUT` prefix overlaps with "
3854                                 & "actual for&", Act1, Form);
3855
3856                           else
3857                              --  For greater clarity, give name of formal
3858
3859                              Error_Msg_Node_2 := Form;
3860                              Error_Msg_FE
3861                                ("<<writable actual for & overlaps with "
3862                                 & "actual for&", Act1, Form);
3863                           end if;
3864
3865                        else
3866                           --  For greater clarity, give name of formal
3867
3868                           Error_Msg_Node_2 := Form;
3869
3870                           --  This is one of the messages
3871
3872                           Error_Msg_FE
3873                             ("<<writable actual for & overlaps with "
3874                              & "actual for&", Act1, Form1);
3875                        end if;
3876                     end;
3877                  end if;
3878
3879                  return;
3880               end if;
3881
3882               Next_Formal (Form2);
3883               Next_Actual (Act2);
3884            end loop;
3885         end if;
3886
3887         Next_Formal (Form1);
3888         Next_Actual (Act1);
3889      end loop;
3890   end Warn_On_Overlapping_Actuals;
3891
3892   ------------------------------
3893   -- Warn_On_Suspicious_Index --
3894   ------------------------------
3895
3896   procedure Warn_On_Suspicious_Index (Name : Entity_Id; X : Node_Id) is
3897
3898      Low_Bound : Uint;
3899      --  Set to lower bound for a suspicious type
3900
3901      Ent : Entity_Id;
3902      --  Entity for array reference
3903
3904      Typ : Entity_Id;
3905      --  Array type
3906
3907      function Is_Suspicious_Type (Typ : Entity_Id) return Boolean;
3908      --  Tests to see if Typ is a type for which we may have a suspicious
3909      --  index, namely an unconstrained array type, whose lower bound is
3910      --  either zero or one. If so, True is returned, and Low_Bound is set
3911      --  to this lower bound. If not, False is returned, and Low_Bound is
3912      --  undefined on return.
3913      --
3914      --  For now, we limit this to standard string types, so any other
3915      --  unconstrained types return False. We may change our minds on this
3916      --  later on, but strings seem the most important case.
3917
3918      procedure Test_Suspicious_Index;
3919      --  Test if index is of suspicious type and if so, generate warning
3920
3921      ------------------------
3922      -- Is_Suspicious_Type --
3923      ------------------------
3924
3925      function Is_Suspicious_Type (Typ : Entity_Id) return Boolean is
3926         LB : Node_Id;
3927
3928      begin
3929         if Is_Array_Type (Typ)
3930           and then not Is_Constrained (Typ)
3931           and then Number_Dimensions (Typ) = 1
3932           and then Is_Standard_String_Type (Typ)
3933           and then not Has_Warnings_Off (Typ)
3934         then
3935            LB := Type_Low_Bound (Etype (First_Index (Typ)));
3936
3937            if Compile_Time_Known_Value (LB) then
3938               Low_Bound := Expr_Value (LB);
3939               return Low_Bound = Uint_0 or else Low_Bound = Uint_1;
3940            end if;
3941         end if;
3942
3943         return False;
3944      end Is_Suspicious_Type;
3945
3946      ---------------------------
3947      -- Test_Suspicious_Index --
3948      ---------------------------
3949
3950      procedure Test_Suspicious_Index is
3951
3952         function Length_Reference (N : Node_Id) return Boolean;
3953         --  Check if node N is of the form Name'Length
3954
3955         procedure Warn1;
3956         --  Generate first warning line
3957
3958         procedure Warn_On_Index_Below_Lower_Bound;
3959         --  Generate a warning on indexing the array with a literal value
3960         --  below the lower bound of the index type.
3961
3962         procedure Warn_On_Literal_Index;
3963         --  Generate a warning on indexing the array with a literal value
3964
3965         ----------------------
3966         -- Length_Reference --
3967         ----------------------
3968
3969         function Length_Reference (N : Node_Id) return Boolean is
3970            R : constant Node_Id := Original_Node (N);
3971         begin
3972            return
3973              Nkind (R) = N_Attribute_Reference
3974                and then Attribute_Name (R) = Name_Length
3975                and then Is_Entity_Name (Prefix (R))
3976                and then Entity (Prefix (R)) = Ent;
3977         end Length_Reference;
3978
3979         -----------
3980         -- Warn1 --
3981         -----------
3982
3983         procedure Warn1 is
3984         begin
3985            Error_Msg_Uint_1 := Low_Bound;
3986            Error_Msg_FE -- CODEFIX
3987              ("?w?index for& may assume lower bound of^", X, Ent);
3988         end Warn1;
3989
3990         -------------------------------------
3991         -- Warn_On_Index_Below_Lower_Bound --
3992         -------------------------------------
3993
3994         procedure Warn_On_Index_Below_Lower_Bound is
3995         begin
3996            if Is_Standard_String_Type (Typ) then
3997               Discard_Node
3998                 (Compile_Time_Constraint_Error
3999                   (N   => X,
4000                    Msg => "?w?string index should be positive"));
4001            else
4002               Discard_Node
4003                 (Compile_Time_Constraint_Error
4004                   (N   => X,
4005                    Msg => "?w?index out of the allowed range"));
4006            end if;
4007         end Warn_On_Index_Below_Lower_Bound;
4008
4009         ---------------------------
4010         -- Warn_On_Literal_Index --
4011         ---------------------------
4012
4013         procedure Warn_On_Literal_Index is
4014         begin
4015            Warn1;
4016
4017            --  Case where original form of subscript is an integer literal
4018
4019            if Nkind (Original_Node (X)) = N_Integer_Literal then
4020               if Intval (X) = Low_Bound then
4021                  Error_Msg_FE -- CODEFIX
4022                    ("\?w?suggested replacement: `&''First`", X, Ent);
4023               else
4024                  Error_Msg_Uint_1 := Intval (X) - Low_Bound;
4025                  Error_Msg_FE -- CODEFIX
4026                    ("\?w?suggested replacement: `&''First + ^`", X, Ent);
4027
4028               end if;
4029
4030            --  Case where original form of subscript is more complex
4031
4032            else
4033               --  Build string X'First - 1 + expression where the expression
4034               --  is the original subscript. If the expression starts with "1
4035               --  + ", then the "- 1 + 1" is elided.
4036
4037               Error_Msg_String (1 .. 13) := "'First - 1 + ";
4038               Error_Msg_Strlen := 13;
4039
4040               declare
4041                  Sref : Source_Ptr := Sloc (First_Node (Original_Node (X)));
4042                  Tref : constant Source_Buffer_Ptr :=
4043                           Source_Text (Get_Source_File_Index (Sref));
4044                  --  Tref (Sref) is used to scan the subscript
4045
4046                  Pctr : Natural;
4047                  --  Parentheses counter when scanning subscript
4048
4049               begin
4050                  --  Tref (Sref) points to start of subscript
4051
4052                  --  Elide - 1 if subscript starts with 1 +
4053
4054                  if Tref (Sref .. Sref + 2) = "1 +" then
4055                     Error_Msg_Strlen := Error_Msg_Strlen - 6;
4056                     Sref := Sref + 2;
4057
4058                  elsif Tref (Sref .. Sref + 1) = "1+" then
4059                     Error_Msg_Strlen := Error_Msg_Strlen - 6;
4060                     Sref := Sref + 1;
4061                  end if;
4062
4063                  --  Now we will copy the subscript to the string buffer
4064
4065                  Pctr := 0;
4066                  loop
4067                     --  Count parens, exit if terminating right paren. Note
4068                     --  check to ignore paren appearing as character literal.
4069
4070                     if Tref (Sref + 1) = '''
4071                          and then
4072                        Tref (Sref - 1) = '''
4073                     then
4074                        null;
4075                     else
4076                        if Tref (Sref) = '(' then
4077                           Pctr := Pctr + 1;
4078                        elsif Tref (Sref) = ')' then
4079                           exit when Pctr = 0;
4080                           Pctr := Pctr - 1;
4081                        end if;
4082                     end if;
4083
4084                     --  Done if terminating double dot (slice case)
4085
4086                     exit when Pctr = 0
4087                       and then (Tref (Sref .. Sref + 1) = ".."
4088                                   or else
4089                                 Tref (Sref .. Sref + 2) = " ..");
4090
4091                     --  Quit if we have hit EOF character, something wrong
4092
4093                     if Tref (Sref) = EOF then
4094                        return;
4095                     end if;
4096
4097                     --  String literals are too much of a pain to handle
4098
4099                     if Tref (Sref) = '"' or else Tref (Sref) = '%' then
4100                        return;
4101                     end if;
4102
4103                     --  If we have a 'Range reference, then this is a case
4104                     --  where we cannot easily give a replacement. Don't try.
4105
4106                     if Tref (Sref .. Sref + 4) = "range"
4107                       and then Tref (Sref - 1) < 'A'
4108                       and then Tref (Sref + 5) < 'A'
4109                     then
4110                        return;
4111                     end if;
4112
4113                     --  Else store next character
4114
4115                     Error_Msg_Strlen := Error_Msg_Strlen + 1;
4116                     Error_Msg_String (Error_Msg_Strlen) := Tref (Sref);
4117                     Sref := Sref + 1;
4118
4119                     --  If we get more than 40 characters then the expression
4120                     --  is too long to copy, or something has gone wrong. In
4121                     --  either case, just skip the attempt at a suggested fix.
4122
4123                     if Error_Msg_Strlen > 40 then
4124                        return;
4125                     end if;
4126                  end loop;
4127               end;
4128
4129               --  Replacement subscript is now in string buffer
4130
4131               Error_Msg_FE -- CODEFIX
4132                 ("\?w?suggested replacement: `&~`", Original_Node (X), Ent);
4133            end if;
4134         end Warn_On_Literal_Index;
4135
4136      --  Start of processing for Test_Suspicious_Index
4137
4138      begin
4139         --  Nothing to do if subscript does not come from source (we don't
4140         --  want to give garbage warnings on compiler expanded code, e.g. the
4141         --  loops generated for slice assignments. Such junk warnings would
4142         --  be placed on source constructs with no subscript in sight).
4143
4144         if not Comes_From_Source (Original_Node (X)) then
4145            return;
4146         end if;
4147
4148         --  Case where subscript is a constant integer
4149
4150         if Nkind (X) = N_Integer_Literal then
4151
4152            --  Case where subscript is lower than the lowest possible bound.
4153            --  This might be the case for example when programmers try to
4154            --  access a string at index 0, as they are used to in other
4155            --  programming languages like C.
4156
4157            if Intval (X) < Low_Bound then
4158               Warn_On_Index_Below_Lower_Bound;
4159            else
4160               Warn_On_Literal_Index;
4161            end if;
4162
4163         --  Case where subscript is of the form X'Length
4164
4165         elsif Length_Reference (X) then
4166            Warn1;
4167            Error_Msg_Node_2 := Ent;
4168            Error_Msg_FE
4169              ("\?w?suggest replacement of `&''Length` by `&''Last`",
4170               X, Ent);
4171
4172         --  Case where subscript is of the form X'Length - expression
4173
4174         elsif Nkind (X) = N_Op_Subtract
4175           and then Length_Reference (Left_Opnd (X))
4176         then
4177            Warn1;
4178            Error_Msg_Node_2 := Ent;
4179            Error_Msg_FE
4180              ("\?w?suggest replacement of `&''Length` by `&''Last`",
4181               Left_Opnd (X), Ent);
4182         end if;
4183      end Test_Suspicious_Index;
4184
4185   --  Start of processing for Warn_On_Suspicious_Index
4186
4187   begin
4188      --  Only process if warnings activated
4189
4190      if Warn_On_Assumed_Low_Bound then
4191
4192         --  Test if array is simple entity name
4193
4194         if Is_Entity_Name (Name) then
4195
4196            --  Test if array is parameter of unconstrained string type
4197
4198            Ent := Entity (Name);
4199            Typ := Etype (Ent);
4200
4201            if Is_Formal (Ent)
4202              and then Is_Suspicious_Type (Typ)
4203              and then not Low_Bound_Tested (Ent)
4204            then
4205               Test_Suspicious_Index;
4206            end if;
4207         end if;
4208      end if;
4209   end Warn_On_Suspicious_Index;
4210
4211   -------------------------------
4212   -- Warn_On_Suspicious_Update --
4213   -------------------------------
4214
4215   procedure Warn_On_Suspicious_Update (N : Node_Id) is
4216      Par : constant Node_Id := Parent (N);
4217      Arg : Node_Id;
4218
4219   begin
4220      --  Only process if warnings activated
4221
4222      if Warn_On_Suspicious_Contract then
4223         if Nkind_In (Par, N_Op_Eq, N_Op_Ne) then
4224            if N = Left_Opnd (Par) then
4225               Arg := Right_Opnd (Par);
4226            else
4227               Arg := Left_Opnd (Par);
4228            end if;
4229
4230            if Same_Object (Prefix (N), Arg) then
4231               if Nkind (Par) = N_Op_Eq then
4232                  Error_Msg_N
4233                    ("suspicious equality test with modified version of "
4234                     & "same object?T?", Par);
4235               else
4236                  Error_Msg_N
4237                    ("suspicious inequality test with modified version of "
4238                     & "same object?T?", Par);
4239               end if;
4240            end if;
4241         end if;
4242      end if;
4243   end Warn_On_Suspicious_Update;
4244
4245   --------------------------------------
4246   -- Warn_On_Unassigned_Out_Parameter --
4247   --------------------------------------
4248
4249   procedure Warn_On_Unassigned_Out_Parameter
4250     (Return_Node : Node_Id;
4251      Scope_Id    : Entity_Id)
4252   is
4253      Form  : Entity_Id;
4254      Form2 : Entity_Id;
4255
4256   begin
4257      --  Ignore if procedure or return statement does not come from source
4258
4259      if not Comes_From_Source (Scope_Id)
4260        or else not Comes_From_Source (Return_Node)
4261      then
4262         return;
4263      end if;
4264
4265      --  Loop through formals
4266
4267      Form := First_Formal (Scope_Id);
4268      while Present (Form) loop
4269
4270         --  We are only interested in OUT parameters that come from source
4271         --  and are never set in the source, and furthermore only in scalars
4272         --  since non-scalars generate too many false positives.
4273
4274         if Ekind (Form) = E_Out_Parameter
4275           and then Never_Set_In_Source_Check_Spec (Form)
4276           and then Is_Scalar_Type (Etype (Form))
4277           and then not Present (Unset_Reference (Form))
4278         then
4279            --  Before we issue the warning, an add ad hoc defence against the
4280            --  most common case of false positives with this warning which is
4281            --  the case where there is a Boolean OUT parameter that has been
4282            --  set, and whose meaning is "ignore the values of the other
4283            --  parameters". We can't of course reliably tell this case at
4284            --  compile time, but the following test kills a lot of false
4285            --  positives, without generating a significant number of false
4286            --  negatives (missed real warnings).
4287
4288            Form2 := First_Formal (Scope_Id);
4289            while Present (Form2) loop
4290               if Ekind (Form2) = E_Out_Parameter
4291                 and then Root_Type (Etype (Form2)) = Standard_Boolean
4292                 and then not Never_Set_In_Source_Check_Spec (Form2)
4293               then
4294                  return;
4295               end if;
4296
4297               Next_Formal (Form2);
4298            end loop;
4299
4300            --  Here all conditions are met, record possible unset reference
4301
4302            Set_Unset_Reference (Form, Return_Node);
4303         end if;
4304
4305         Next_Formal (Form);
4306      end loop;
4307   end Warn_On_Unassigned_Out_Parameter;
4308
4309   ---------------------------------
4310   -- Warn_On_Unreferenced_Entity --
4311   ---------------------------------
4312
4313   procedure Warn_On_Unreferenced_Entity
4314     (Spec_E : Entity_Id;
4315      Body_E : Entity_Id := Empty)
4316   is
4317      E : Entity_Id := Spec_E;
4318
4319   begin
4320      if not Referenced_Check_Spec (E)
4321        and then not Has_Pragma_Unreferenced_Check_Spec (E)
4322        and then not Warnings_Off_Check_Spec (E)
4323        and then not Has_Junk_Name (Spec_E)
4324        and then not Is_Exported (Spec_E)
4325      then
4326         case Ekind (E) is
4327            when E_Variable =>
4328
4329               --  Case of variable that is assigned but not read. We suppress
4330               --  the message if the variable is volatile, has an address
4331               --  clause, is aliased, or is a renaming, or is imported.
4332
4333               if Referenced_As_LHS_Check_Spec (E)
4334                 and then No (Address_Clause (E))
4335                 and then not Is_Volatile (E)
4336               then
4337                  if Warn_On_Modified_Unread
4338                    and then not Is_Imported (E)
4339                    and then not Is_Aliased (E)
4340                    and then No (Renamed_Object (E))
4341                  then
4342                     if not Has_Pragma_Unmodified_Check_Spec (E) then
4343                        Error_Msg_N -- CODEFIX
4344                          ("?m?variable & is assigned but never read!", E);
4345                     end if;
4346
4347                     Set_Last_Assignment (E, Empty);
4348                  end if;
4349
4350               --  Normal case of neither assigned nor read (exclude variables
4351               --  referenced as out parameters, since we already generated
4352               --  appropriate warnings at the call point in this case).
4353
4354               elsif not Referenced_As_Out_Parameter (E) then
4355
4356                  --  We suppress the message for types for which a valid
4357                  --  pragma Unreferenced_Objects has been given, otherwise
4358                  --  we go ahead and give the message.
4359
4360                  if not Has_Pragma_Unreferenced_Objects (Etype (E)) then
4361
4362                     --  Distinguish renamed case in message
4363
4364                     if Present (Renamed_Object (E))
4365                       and then Comes_From_Source (Renamed_Object (E))
4366                     then
4367                        Error_Msg_N -- CODEFIX
4368                          ("?u?renamed variable & is not referenced!", E);
4369                     else
4370                        Error_Msg_N -- CODEFIX
4371                          ("?u?variable & is not referenced!", E);
4372                     end if;
4373                  end if;
4374               end if;
4375
4376            when E_Constant =>
4377               if not Has_Pragma_Unreferenced_Objects (Etype (E)) then
4378                  if Present (Renamed_Object (E))
4379                    and then Comes_From_Source (Renamed_Object (E))
4380                  then
4381                     Error_Msg_N -- CODEFIX
4382                       ("?u?renamed constant & is not referenced!", E);
4383                  else
4384                     Error_Msg_N -- CODEFIX
4385                       ("?u?constant & is not referenced!", E);
4386                  end if;
4387               end if;
4388
4389            when E_In_Out_Parameter
4390               | E_In_Parameter
4391            =>
4392               --  Do not emit message for formals of a renaming, because they
4393               --  are never referenced explicitly.
4394
4395               if Nkind (Original_Node (Unit_Declaration_Node (Scope (E)))) /=
4396                                          N_Subprogram_Renaming_Declaration
4397               then
4398                  --  Suppress this message for an IN OUT parameter of a
4399                  --  non-scalar type, since it is normal to have only an
4400                  --  assignment in such a case.
4401
4402                  if Ekind (E) = E_In_Parameter
4403                    or else not Referenced_As_LHS_Check_Spec (E)
4404                    or else Is_Scalar_Type (Etype (E))
4405                  then
4406                     if Present (Body_E) then
4407                        E := Body_E;
4408                     end if;
4409
4410                     declare
4411                        B : constant Node_Id := Parent (Parent (Scope (E)));
4412                        S : Entity_Id := Empty;
4413                     begin
4414                        if Nkind_In (B,
4415                                     N_Expression_Function,
4416                                     N_Subprogram_Body,
4417                                     N_Subprogram_Renaming_Declaration)
4418                        then
4419                           S := Corresponding_Spec (B);
4420                        end if;
4421
4422                        --  Do not warn for dispatching operations, because
4423                        --  that causes too much noise. Also do not warn for
4424                        --  trivial subprograms.
4425
4426                        if (not Present (S)
4427                            or else not Is_Dispatching_Operation (S))
4428                          and then not Is_Trivial_Subprogram (Scope (E))
4429                        then
4430                           Error_Msg_NE -- CODEFIX
4431                             ("?u?formal parameter & is not referenced!",
4432                              E, Spec_E);
4433                        end if;
4434                     end;
4435                  end if;
4436               end if;
4437
4438            when E_Out_Parameter =>
4439               null;
4440
4441            when E_Discriminant =>
4442               Error_Msg_N ("?u?discriminant & is not referenced!", E);
4443
4444            when E_Named_Integer
4445               | E_Named_Real
4446            =>
4447               Error_Msg_N -- CODEFIX
4448                 ("?u?named number & is not referenced!", E);
4449
4450            when Formal_Object_Kind =>
4451               Error_Msg_N -- CODEFIX
4452                 ("?u?formal object & is not referenced!", E);
4453
4454            when E_Enumeration_Literal =>
4455               Error_Msg_N -- CODEFIX
4456                 ("?u?literal & is not referenced!", E);
4457
4458            when E_Function =>
4459               Error_Msg_N -- CODEFIX
4460                 ("?u?function & is not referenced!", E);
4461
4462            when E_Procedure =>
4463               Error_Msg_N -- CODEFIX
4464                 ("?u?procedure & is not referenced!", E);
4465
4466            when E_Package =>
4467               Error_Msg_N -- CODEFIX
4468                 ("?u?package & is not referenced!", E);
4469
4470            when E_Exception =>
4471               Error_Msg_N -- CODEFIX
4472                 ("?u?exception & is not referenced!", E);
4473
4474            when E_Label =>
4475               Error_Msg_N -- CODEFIX
4476                 ("?u?label & is not referenced!", E);
4477
4478            when E_Generic_Procedure =>
4479               Error_Msg_N -- CODEFIX
4480                 ("?u?generic procedure & is never instantiated!", E);
4481
4482            when E_Generic_Function =>
4483               Error_Msg_N -- CODEFIX
4484                 ("?u?generic function & is never instantiated!", E);
4485
4486            when Type_Kind =>
4487               Error_Msg_N -- CODEFIX
4488                 ("?u?type & is not referenced!", E);
4489
4490            when others =>
4491               Error_Msg_N -- CODEFIX
4492                 ("?u?& is not referenced!", E);
4493         end case;
4494
4495         --  Kill warnings on the entity on which the message has been posted
4496         --  (nothing is posted on out parameters because back end might be
4497         --  able to uncover an uninitialized path, and warn accordingly).
4498
4499         if Ekind (E) /= E_Out_Parameter then
4500            Set_Warnings_Off (E);
4501         end if;
4502      end if;
4503   end Warn_On_Unreferenced_Entity;
4504
4505   --------------------------------
4506   -- Warn_On_Useless_Assignment --
4507   --------------------------------
4508
4509   procedure Warn_On_Useless_Assignment
4510     (Ent : Entity_Id;
4511      N   : Node_Id := Empty)
4512   is
4513      P    : Node_Id;
4514      X    : Node_Id;
4515
4516      function Check_Ref (N : Node_Id) return Traverse_Result;
4517      --  Used to instantiate Traverse_Func. Returns Abandon if a reference to
4518      --  the entity in question is found.
4519
4520      function Test_No_Refs is new Traverse_Func (Check_Ref);
4521
4522      ---------------
4523      -- Check_Ref --
4524      ---------------
4525
4526      function Check_Ref (N : Node_Id) return Traverse_Result is
4527      begin
4528         --  Check reference to our identifier. We use name equality here
4529         --  because the exception handlers have not yet been analyzed. This
4530         --  is not quite right, but it really does not matter that we fail
4531         --  to output the warning in some obscure cases of name clashes.
4532
4533         if Nkind (N) = N_Identifier and then Chars (N) = Chars (Ent) then
4534            return Abandon;
4535         else
4536            return OK;
4537         end if;
4538      end Check_Ref;
4539
4540   --  Start of processing for Warn_On_Useless_Assignment
4541
4542   begin
4543      --  Check if this is a case we want to warn on, a scalar or access
4544      --  variable with the last assignment field set, with warnings enabled,
4545      --  and which is not imported or exported. We also check that it is OK
4546      --  to capture the value. We are not going to capture any value, but
4547      --  the warning message depends on the same kind of conditions.
4548
4549      --  If the assignment appears as an out-parameter in a call within an
4550      --  expression function it may be detected twice: once when expression
4551      --  itself is analyzed, and once when the constructed body is analyzed.
4552      --  We don't want to emit a spurious warning in this case.
4553
4554      if Is_Assignable (Ent)
4555        and then not Is_Return_Object (Ent)
4556        and then Present (Last_Assignment (Ent))
4557        and then Last_Assignment (Ent) /= N
4558        and then not Is_Imported (Ent)
4559        and then not Is_Exported (Ent)
4560        and then Safe_To_Capture_Value (N, Ent)
4561        and then not Has_Pragma_Unreferenced_Check_Spec (Ent)
4562        and then not Has_Junk_Name (Ent)
4563      then
4564         --  Before we issue the message, check covering exception handlers.
4565         --  Search up tree for enclosing statement sequences and handlers.
4566
4567         P := Parent (Last_Assignment (Ent));
4568         while Present (P) loop
4569
4570            --  Something is really wrong if we don't find a handled statement
4571            --  sequence, so just suppress the warning.
4572
4573            if No (P) then
4574               Set_Last_Assignment (Ent, Empty);
4575               return;
4576
4577            --  When we hit a package/subprogram body, issue warning and exit
4578
4579            elsif Nkind_In (P, N_Entry_Body,
4580                               N_Package_Body,
4581                               N_Subprogram_Body,
4582                               N_Task_Body)
4583            then
4584               --  Case of assigned value never referenced
4585
4586               if No (N) then
4587                  declare
4588                     LA : constant Node_Id := Last_Assignment (Ent);
4589
4590                  begin
4591                     --  Don't give this for OUT and IN OUT formals, since
4592                     --  clearly caller may reference the assigned value. Also
4593                     --  never give such warnings for internal variables. In
4594                     --  either case, word the warning in a conditional way,
4595                     --  because in the case of a component of a controlled
4596                     --  type, the assigned value might be referenced in the
4597                     --  Finalize operation, so we can't make a definitive
4598                     --  statement that it's never referenced.
4599
4600                     if Ekind (Ent) = E_Variable
4601                       and then not Is_Internal_Name (Chars (Ent))
4602                     then
4603                        --  Give appropriate message, distinguishing between
4604                        --  assignment statements and out parameters.
4605
4606                        if Nkind_In (Parent (LA), N_Parameter_Association,
4607                                                  N_Procedure_Call_Statement)
4608                        then
4609                           Error_Msg_NE
4610                             ("?m?& modified by call, but value might not be "
4611                              & "referenced", LA, Ent);
4612
4613                        else
4614                           Error_Msg_NE -- CODEFIX
4615                             ("?m?possibly useless assignment to&, value "
4616                              & "might not be referenced!", LA, Ent);
4617                        end if;
4618                     end if;
4619                  end;
4620
4621               --  Case of assigned value overwritten
4622
4623               else
4624                  declare
4625                     LA : constant Node_Id := Last_Assignment (Ent);
4626
4627                  begin
4628                     Error_Msg_Sloc := Sloc (N);
4629
4630                     --  Give appropriate message, distinguishing between
4631                     --  assignment statements and out parameters.
4632
4633                     if Nkind_In (Parent (LA), N_Procedure_Call_Statement,
4634                                               N_Parameter_Association)
4635                     then
4636                        Error_Msg_NE
4637                          ("?m?& modified by call, but value overwritten #!",
4638                           LA, Ent);
4639                     else
4640                        Error_Msg_NE -- CODEFIX
4641                          ("?m?useless assignment to&, value overwritten #!",
4642                           LA, Ent);
4643                     end if;
4644                  end;
4645               end if;
4646
4647               --  Clear last assignment indication and we are done
4648
4649               Set_Last_Assignment (Ent, Empty);
4650               return;
4651
4652            --  Enclosing handled sequence of statements
4653
4654            elsif Nkind (P) = N_Handled_Sequence_Of_Statements then
4655
4656               --  Check exception handlers present
4657
4658               if Present (Exception_Handlers (P)) then
4659
4660                  --  If we are not at the top level, we regard an inner
4661                  --  exception handler as a decisive indicator that we should
4662                  --  not generate the warning, since the variable in question
4663                  --  may be accessed after an exception in the outer block.
4664
4665                  if not Nkind_In (Parent (P), N_Entry_Body,
4666                                               N_Package_Body,
4667                                               N_Subprogram_Body,
4668                                               N_Task_Body)
4669                  then
4670                     Set_Last_Assignment (Ent, Empty);
4671                     return;
4672
4673                     --  Otherwise we are at the outer level. An exception
4674                     --  handler is significant only if it references the
4675                     --  variable in question, or if the entity in question
4676                     --  is an OUT or IN OUT parameter, in which case
4677                     --  the caller can reference it after the exception
4678                     --  handler completes.
4679
4680                  else
4681                     if Is_Formal (Ent) then
4682                        Set_Last_Assignment (Ent, Empty);
4683                        return;
4684
4685                     else
4686                        X := First (Exception_Handlers (P));
4687                        while Present (X) loop
4688                           if Test_No_Refs (X) = Abandon then
4689                              Set_Last_Assignment (Ent, Empty);
4690                              return;
4691                           end if;
4692
4693                           X := Next (X);
4694                        end loop;
4695                     end if;
4696                  end if;
4697               end if;
4698            end if;
4699
4700            P := Parent (P);
4701         end loop;
4702      end if;
4703   end Warn_On_Useless_Assignment;
4704
4705   ---------------------------------
4706   -- Warn_On_Useless_Assignments --
4707   ---------------------------------
4708
4709   procedure Warn_On_Useless_Assignments (E : Entity_Id) is
4710      Ent : Entity_Id;
4711
4712   begin
4713      Process_Deferred_References;
4714
4715      if Warn_On_Modified_Unread
4716        and then In_Extended_Main_Source_Unit (E)
4717      then
4718         Ent := First_Entity (E);
4719         while Present (Ent) loop
4720            Warn_On_Useless_Assignment (Ent);
4721            Next_Entity (Ent);
4722         end loop;
4723      end if;
4724   end Warn_On_Useless_Assignments;
4725
4726   -----------------------------
4727   -- Warnings_Off_Check_Spec --
4728   -----------------------------
4729
4730   function Warnings_Off_Check_Spec (E : Entity_Id) return Boolean is
4731   begin
4732      if Is_Formal (E) and then Present (Spec_Entity (E)) then
4733
4734         --  Note: use of OR here instead of OR ELSE is deliberate, we want
4735         --  to mess with flags on both entities.
4736
4737         return Has_Warnings_Off (E)
4738                  or
4739                Has_Warnings_Off (Spec_Entity (E));
4740
4741      else
4742         return Has_Warnings_Off (E);
4743      end if;
4744   end Warnings_Off_Check_Spec;
4745
4746end Sem_Warn;
4747