OSDN Git Service

2011-08-02 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch13.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             S E M _ C H 1 3                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Exp_Disp; use Exp_Disp;
33 with Exp_Tss;  use Exp_Tss;
34 with Exp_Util; use Exp_Util;
35 with Lib;      use Lib;
36 with Lib.Xref; use Lib.Xref;
37 with Namet;    use Namet;
38 with Nlists;   use Nlists;
39 with Nmake;    use Nmake;
40 with Opt;      use Opt;
41 with Restrict; use Restrict;
42 with Rident;   use Rident;
43 with Rtsfind;  use Rtsfind;
44 with Sem;      use Sem;
45 with Sem_Aux;  use Sem_Aux;
46 with Sem_Ch3;  use Sem_Ch3;
47 with Sem_Ch6;  use Sem_Ch6;
48 with Sem_Ch8;  use Sem_Ch8;
49 with Sem_Eval; use Sem_Eval;
50 with Sem_Res;  use Sem_Res;
51 with Sem_Type; use Sem_Type;
52 with Sem_Util; use Sem_Util;
53 with Sem_Warn; use Sem_Warn;
54 with Sinput;   use Sinput;
55 with Snames;   use Snames;
56 with Stand;    use Stand;
57 with Sinfo;    use Sinfo;
58 with Stringt;  use Stringt;
59 with Targparm; use Targparm;
60 with Ttypes;   use Ttypes;
61 with Tbuild;   use Tbuild;
62 with Urealp;   use Urealp;
63 with Warnsw;   use Warnsw;
64
65 with GNAT.Heap_Sort_G;
66
67 package body Sem_Ch13 is
68
69    SSU : constant Pos := System_Storage_Unit;
70    --  Convenient short hand for commonly used constant
71
72    -----------------------
73    -- Local Subprograms --
74    -----------------------
75
76    procedure Alignment_Check_For_Esize_Change (Typ : Entity_Id);
77    --  This routine is called after setting the Esize of type entity Typ.
78    --  The purpose is to deal with the situation where an alignment has been
79    --  inherited from a derived type that is no longer appropriate for the
80    --  new Esize value. In this case, we reset the Alignment to unknown.
81
82    procedure Build_Predicate_Function (Typ : Entity_Id; N : Node_Id);
83    --  If Typ has predicates (indicated by Has_Predicates being set for Typ,
84    --  then either there are pragma Invariant entries on the rep chain for the
85    --  type (note that Predicate aspects are converted to pragma Predicate), or
86    --  there are inherited aspects from a parent type, or ancestor subtypes.
87    --  This procedure builds the spec and body for the Predicate function that
88    --  tests these predicates. N is the freeze node for the type. The spec of
89    --  the function is inserted before the freeze node, and the body of the
90    --  function is inserted after the freeze node.
91
92    procedure Build_Static_Predicate
93      (Typ  : Entity_Id;
94       Expr : Node_Id;
95       Nam  : Name_Id);
96    --  Given a predicated type Typ, where Typ is a discrete static subtype,
97    --  whose predicate expression is Expr, tests if Expr is a static predicate,
98    --  and if so, builds the predicate range list. Nam is the name of the one
99    --  argument to the predicate function. Occurrences of the type name in the
100    --  predicate expression have been replaced by identifier references to this
101    --  name, which is unique, so any identifier with Chars matching Nam must be
102    --  a reference to the type. If the predicate is non-static, this procedure
103    --  returns doing nothing. If the predicate is static, then the predicate
104    --  list is stored in Static_Predicate (Typ), and the Expr is rewritten as
105    --  a canonicalized membership operation.
106
107    function Get_Alignment_Value (Expr : Node_Id) return Uint;
108    --  Given the expression for an alignment value, returns the corresponding
109    --  Uint value. If the value is inappropriate, then error messages are
110    --  posted as required, and a value of No_Uint is returned.
111
112    function Is_Operational_Item (N : Node_Id) return Boolean;
113    --  A specification for a stream attribute is allowed before the full type
114    --  is declared, as explained in AI-00137 and the corrigendum. Attributes
115    --  that do not specify a representation characteristic are operational
116    --  attributes.
117
118    procedure New_Stream_Subprogram
119      (N    : Node_Id;
120       Ent  : Entity_Id;
121       Subp : Entity_Id;
122       Nam  : TSS_Name_Type);
123    --  Create a subprogram renaming of a given stream attribute to the
124    --  designated subprogram and then in the tagged case, provide this as a
125    --  primitive operation, or in the non-tagged case make an appropriate TSS
126    --  entry. This is more properly an expansion activity than just semantics,
127    --  but the presence of user-defined stream functions for limited types is a
128    --  legality check, which is why this takes place here rather than in
129    --  exp_ch13, where it was previously. Nam indicates the name of the TSS
130    --  function to be generated.
131    --
132    --  To avoid elaboration anomalies with freeze nodes, for untagged types
133    --  we generate both a subprogram declaration and a subprogram renaming
134    --  declaration, so that the attribute specification is handled as a
135    --  renaming_as_body. For tagged types, the specification is one of the
136    --  primitive specs.
137
138    generic
139       with procedure Replace_Type_Reference (N : Node_Id);
140    procedure Replace_Type_References_Generic (N : Node_Id; TName : Name_Id);
141    --  This is used to scan an expression for a predicate or invariant aspect
142    --  replacing occurrences of the name TName (the name of the subtype to
143    --  which the aspect applies) with appropriate references to the parameter
144    --  of the predicate function or invariant procedure. The procedure passed
145    --  as a generic parameter does the actual replacement of node N, which is
146    --  either a simple direct reference to TName, or a selected component that
147    --  represents an appropriately qualified occurrence of TName.
148
149    procedure Set_Biased
150      (E      : Entity_Id;
151       N      : Node_Id;
152       Msg    : String;
153       Biased : Boolean := True);
154    --  If Biased is True, sets Has_Biased_Representation flag for E, and
155    --  outputs a warning message at node N if Warn_On_Biased_Representation is
156    --  is True. This warning inserts the string Msg to describe the construct
157    --  causing biasing.
158
159    ----------------------------------------------
160    -- Table for Validate_Unchecked_Conversions --
161    ----------------------------------------------
162
163    --  The following table collects unchecked conversions for validation.
164    --  Entries are made by Validate_Unchecked_Conversion and then the
165    --  call to Validate_Unchecked_Conversions does the actual error
166    --  checking and posting of warnings. The reason for this delayed
167    --  processing is to take advantage of back-annotations of size and
168    --  alignment values performed by the back end.
169
170    --  Note: the reason we store a Source_Ptr value instead of a Node_Id
171    --  is that by the time Validate_Unchecked_Conversions is called, Sprint
172    --  will already have modified all Sloc values if the -gnatD option is set.
173
174    type UC_Entry is record
175       Eloc   : Source_Ptr; -- node used for posting warnings
176       Source : Entity_Id;  -- source type for unchecked conversion
177       Target : Entity_Id;  -- target type for unchecked conversion
178    end record;
179
180    package Unchecked_Conversions is new Table.Table (
181      Table_Component_Type => UC_Entry,
182      Table_Index_Type     => Int,
183      Table_Low_Bound      => 1,
184      Table_Initial        => 50,
185      Table_Increment      => 200,
186      Table_Name           => "Unchecked_Conversions");
187
188    ----------------------------------------
189    -- Table for Validate_Address_Clauses --
190    ----------------------------------------
191
192    --  If an address clause has the form
193
194    --    for X'Address use Expr
195
196    --  where Expr is of the form Y'Address or recursively is a reference
197    --  to a constant of either of these forms, and X and Y are entities of
198    --  objects, then if Y has a smaller alignment than X, that merits a
199    --  warning about possible bad alignment. The following table collects
200    --  address clauses of this kind. We put these in a table so that they
201    --  can be checked after the back end has completed annotation of the
202    --  alignments of objects, since we can catch more cases that way.
203
204    type Address_Clause_Check_Record is record
205       N : Node_Id;
206       --  The address clause
207
208       X : Entity_Id;
209       --  The entity of the object overlaying Y
210
211       Y : Entity_Id;
212       --  The entity of the object being overlaid
213
214       Off : Boolean;
215       --  Whether the address is offset within Y
216    end record;
217
218    package Address_Clause_Checks is new Table.Table (
219      Table_Component_Type => Address_Clause_Check_Record,
220      Table_Index_Type     => Int,
221      Table_Low_Bound      => 1,
222      Table_Initial        => 20,
223      Table_Increment      => 200,
224      Table_Name           => "Address_Clause_Checks");
225
226    -----------------------------------------
227    -- Adjust_Record_For_Reverse_Bit_Order --
228    -----------------------------------------
229
230    procedure Adjust_Record_For_Reverse_Bit_Order (R : Entity_Id) is
231       Comp : Node_Id;
232       CC   : Node_Id;
233
234    begin
235       --  Processing depends on version of Ada
236
237       --  For Ada 95, we just renumber bits within a storage unit. We do the
238       --  same for Ada 83 mode, since we recognize pragma Bit_Order in Ada 83,
239       --  and are free to add this extension.
240
241       if Ada_Version < Ada_2005 then
242          Comp := First_Component_Or_Discriminant (R);
243          while Present (Comp) loop
244             CC := Component_Clause (Comp);
245
246             --  If component clause is present, then deal with the non-default
247             --  bit order case for Ada 95 mode.
248
249             --  We only do this processing for the base type, and in fact that
250             --  is important, since otherwise if there are record subtypes, we
251             --  could reverse the bits once for each subtype, which is wrong.
252
253             if Present (CC)
254               and then Ekind (R) = E_Record_Type
255             then
256                declare
257                   CFB : constant Uint    := Component_Bit_Offset (Comp);
258                   CSZ : constant Uint    := Esize (Comp);
259                   CLC : constant Node_Id := Component_Clause (Comp);
260                   Pos : constant Node_Id := Position (CLC);
261                   FB  : constant Node_Id := First_Bit (CLC);
262
263                   Storage_Unit_Offset : constant Uint :=
264                                           CFB / System_Storage_Unit;
265
266                   Start_Bit : constant Uint :=
267                                 CFB mod System_Storage_Unit;
268
269                begin
270                   --  Cases where field goes over storage unit boundary
271
272                   if Start_Bit + CSZ > System_Storage_Unit then
273
274                      --  Allow multi-byte field but generate warning
275
276                      if Start_Bit mod System_Storage_Unit = 0
277                        and then CSZ mod System_Storage_Unit = 0
278                      then
279                         Error_Msg_N
280                           ("multi-byte field specified with non-standard"
281                            & " Bit_Order?", CLC);
282
283                         if Bytes_Big_Endian then
284                            Error_Msg_N
285                              ("bytes are not reversed "
286                               & "(component is big-endian)?", CLC);
287                         else
288                            Error_Msg_N
289                              ("bytes are not reversed "
290                               & "(component is little-endian)?", CLC);
291                         end if;
292
293                         --  Do not allow non-contiguous field
294
295                      else
296                         Error_Msg_N
297                           ("attempt to specify non-contiguous field "
298                            & "not permitted", CLC);
299                         Error_Msg_N
300                           ("\caused by non-standard Bit_Order "
301                            & "specified", CLC);
302                         Error_Msg_N
303                           ("\consider possibility of using "
304                            & "Ada 2005 mode here", CLC);
305                      end if;
306
307                   --  Case where field fits in one storage unit
308
309                   else
310                      --  Give warning if suspicious component clause
311
312                      if Intval (FB) >= System_Storage_Unit
313                        and then Warn_On_Reverse_Bit_Order
314                      then
315                         Error_Msg_N
316                           ("?Bit_Order clause does not affect " &
317                            "byte ordering", Pos);
318                         Error_Msg_Uint_1 :=
319                           Intval (Pos) + Intval (FB) /
320                           System_Storage_Unit;
321                         Error_Msg_N
322                           ("?position normalized to ^ before bit " &
323                            "order interpreted", Pos);
324                      end if;
325
326                      --  Here is where we fix up the Component_Bit_Offset value
327                      --  to account for the reverse bit order. Some examples of
328                      --  what needs to be done are:
329
330                      --    First_Bit .. Last_Bit     Component_Bit_Offset
331                      --      old          new          old       new
332
333                      --     0 .. 0       7 .. 7         0         7
334                      --     0 .. 1       6 .. 7         0         6
335                      --     0 .. 2       5 .. 7         0         5
336                      --     0 .. 7       0 .. 7         0         4
337
338                      --     1 .. 1       6 .. 6         1         6
339                      --     1 .. 4       3 .. 6         1         3
340                      --     4 .. 7       0 .. 3         4         0
341
342                      --  The rule is that the first bit is is obtained by
343                      --  subtracting the old ending bit from storage_unit - 1.
344
345                      Set_Component_Bit_Offset
346                        (Comp,
347                         (Storage_Unit_Offset * System_Storage_Unit) +
348                           (System_Storage_Unit - 1) -
349                           (Start_Bit + CSZ - 1));
350
351                      Set_Normalized_First_Bit
352                        (Comp,
353                         Component_Bit_Offset (Comp) mod
354                           System_Storage_Unit);
355                   end if;
356                end;
357             end if;
358
359             Next_Component_Or_Discriminant (Comp);
360          end loop;
361
362       --  For Ada 2005, we do machine scalar processing, as fully described In
363       --  AI-133. This involves gathering all components which start at the
364       --  same byte offset and processing them together. Same approach is still
365       --  valid in later versions including Ada 2012.
366
367       else
368          declare
369             Max_Machine_Scalar_Size : constant Uint :=
370                                         UI_From_Int
371                                           (Standard_Long_Long_Integer_Size);
372             --  We use this as the maximum machine scalar size
373
374             Num_CC : Natural;
375             SSU    : constant Uint := UI_From_Int (System_Storage_Unit);
376
377          begin
378             --  This first loop through components does two things. First it
379             --  deals with the case of components with component clauses whose
380             --  length is greater than the maximum machine scalar size (either
381             --  accepting them or rejecting as needed). Second, it counts the
382             --  number of components with component clauses whose length does
383             --  not exceed this maximum for later processing.
384
385             Num_CC := 0;
386             Comp   := First_Component_Or_Discriminant (R);
387             while Present (Comp) loop
388                CC := Component_Clause (Comp);
389
390                if Present (CC) then
391                   declare
392                      Fbit : constant Uint :=
393                               Static_Integer (First_Bit (CC));
394                      Lbit : constant Uint :=
395                               Static_Integer (Last_Bit (CC));
396
397                   begin
398                      --  Case of component with last bit >= max machine scalar
399
400                      if Lbit >= Max_Machine_Scalar_Size then
401
402                         --  This is allowed only if first bit is zero, and
403                         --  last bit + 1 is a multiple of storage unit size.
404
405                         if Fbit = 0 and then (Lbit + 1) mod SSU = 0 then
406
407                            --  This is the case to give a warning if enabled
408
409                            if Warn_On_Reverse_Bit_Order then
410                               Error_Msg_N
411                                 ("multi-byte field specified with "
412                                  & "  non-standard Bit_Order?", CC);
413
414                               if Bytes_Big_Endian then
415                                  Error_Msg_N
416                                    ("\bytes are not reversed "
417                                     & "(component is big-endian)?", CC);
418                               else
419                                  Error_Msg_N
420                                    ("\bytes are not reversed "
421                                     & "(component is little-endian)?", CC);
422                               end if;
423                            end if;
424
425                         --  Give error message for RM 13.4.1(10) violation
426
427                         else
428                            Error_Msg_FE
429                              ("machine scalar rules not followed for&",
430                               First_Bit (CC), Comp);
431
432                            Error_Msg_Uint_1 := Lbit;
433                            Error_Msg_Uint_2 := Max_Machine_Scalar_Size;
434                            Error_Msg_F
435                              ("\last bit (^) exceeds maximum machine "
436                               & "scalar size (^)",
437                               First_Bit (CC));
438
439                            if (Lbit + 1) mod SSU /= 0 then
440                               Error_Msg_Uint_1 := SSU;
441                               Error_Msg_F
442                                 ("\and is not a multiple of Storage_Unit (^) "
443                                  & "('R'M 13.4.1(10))",
444                                  First_Bit (CC));
445
446                            else
447                               Error_Msg_Uint_1 := Fbit;
448                               Error_Msg_F
449                                 ("\and first bit (^) is non-zero "
450                                  & "('R'M 13.4.1(10))",
451                                  First_Bit (CC));
452                            end if;
453                         end if;
454
455                      --  OK case of machine scalar related component clause,
456                      --  For now, just count them.
457
458                      else
459                         Num_CC := Num_CC + 1;
460                      end if;
461                   end;
462                end if;
463
464                Next_Component_Or_Discriminant (Comp);
465             end loop;
466
467             --  We need to sort the component clauses on the basis of the
468             --  Position values in the clause, so we can group clauses with
469             --  the same Position. together to determine the relevant machine
470             --  scalar size.
471
472             Sort_CC : declare
473                Comps : array (0 .. Num_CC) of Entity_Id;
474                --  Array to collect component and discriminant entities. The
475                --  data starts at index 1, the 0'th entry is for the sort
476                --  routine.
477
478                function CP_Lt (Op1, Op2 : Natural) return Boolean;
479                --  Compare routine for Sort
480
481                procedure CP_Move (From : Natural; To : Natural);
482                --  Move routine for Sort
483
484                package Sorting is new GNAT.Heap_Sort_G (CP_Move, CP_Lt);
485
486                Start : Natural;
487                Stop  : Natural;
488                --  Start and stop positions in the component list of the set of
489                --  components with the same starting position (that constitute
490                --  components in a single machine scalar).
491
492                MaxL  : Uint;
493                --  Maximum last bit value of any component in this set
494
495                MSS   : Uint;
496                --  Corresponding machine scalar size
497
498                -----------
499                -- CP_Lt --
500                -----------
501
502                function CP_Lt (Op1, Op2 : Natural) return Boolean is
503                begin
504                   return Position (Component_Clause (Comps (Op1))) <
505                     Position (Component_Clause (Comps (Op2)));
506                end CP_Lt;
507
508                -------------
509                -- CP_Move --
510                -------------
511
512                procedure CP_Move (From : Natural; To : Natural) is
513                begin
514                   Comps (To) := Comps (From);
515                end CP_Move;
516
517                --  Start of processing for Sort_CC
518
519             begin
520                --  Collect the machine scalar relevant component clauses
521
522                Num_CC := 0;
523                Comp   := First_Component_Or_Discriminant (R);
524                while Present (Comp) loop
525                   declare
526                      CC   : constant Node_Id := Component_Clause (Comp);
527
528                   begin
529                      --  Collect only component clauses whose last bit is less
530                      --  than machine scalar size. Any component clause whose
531                      --  last bit exceeds this value does not take part in
532                      --  machine scalar layout considerations. The test for
533                      --  Error_Posted makes sure we exclude component clauses
534                      --  for which we already posted an error.
535
536                      if Present (CC)
537                        and then not Error_Posted (Last_Bit (CC))
538                        and then Static_Integer (Last_Bit (CC)) <
539                                                     Max_Machine_Scalar_Size
540                      then
541                         Num_CC := Num_CC + 1;
542                         Comps (Num_CC) := Comp;
543                      end if;
544                   end;
545
546                   Next_Component_Or_Discriminant (Comp);
547                end loop;
548
549                --  Sort by ascending position number
550
551                Sorting.Sort (Num_CC);
552
553                --  We now have all the components whose size does not exceed
554                --  the max machine scalar value, sorted by starting position.
555                --  In this loop we gather groups of clauses starting at the
556                --  same position, to process them in accordance with AI-133.
557
558                Stop := 0;
559                while Stop < Num_CC loop
560                   Start := Stop + 1;
561                   Stop  := Start;
562                   MaxL  :=
563                     Static_Integer
564                       (Last_Bit (Component_Clause (Comps (Start))));
565                   while Stop < Num_CC loop
566                      if Static_Integer
567                           (Position (Component_Clause (Comps (Stop + 1)))) =
568                         Static_Integer
569                           (Position (Component_Clause (Comps (Stop))))
570                      then
571                         Stop := Stop + 1;
572                         MaxL :=
573                           UI_Max
574                             (MaxL,
575                              Static_Integer
576                                (Last_Bit
577                                   (Component_Clause (Comps (Stop)))));
578                      else
579                         exit;
580                      end if;
581                   end loop;
582
583                   --  Now we have a group of component clauses from Start to
584                   --  Stop whose positions are identical, and MaxL is the
585                   --  maximum last bit value of any of these components.
586
587                   --  We need to determine the corresponding machine scalar
588                   --  size. This loop assumes that machine scalar sizes are
589                   --  even, and that each possible machine scalar has twice
590                   --  as many bits as the next smaller one.
591
592                   MSS := Max_Machine_Scalar_Size;
593                   while MSS mod 2 = 0
594                     and then (MSS / 2) >= SSU
595                     and then (MSS / 2) > MaxL
596                   loop
597                      MSS := MSS / 2;
598                   end loop;
599
600                   --  Here is where we fix up the Component_Bit_Offset value
601                   --  to account for the reverse bit order. Some examples of
602                   --  what needs to be done for the case of a machine scalar
603                   --  size of 8 are:
604
605                   --    First_Bit .. Last_Bit     Component_Bit_Offset
606                   --      old          new          old       new
607
608                   --     0 .. 0       7 .. 7         0         7
609                   --     0 .. 1       6 .. 7         0         6
610                   --     0 .. 2       5 .. 7         0         5
611                   --     0 .. 7       0 .. 7         0         4
612
613                   --     1 .. 1       6 .. 6         1         6
614                   --     1 .. 4       3 .. 6         1         3
615                   --     4 .. 7       0 .. 3         4         0
616
617                   --  The rule is that the first bit is obtained by subtracting
618                   --  the old ending bit from machine scalar size - 1.
619
620                   for C in Start .. Stop loop
621                      declare
622                         Comp : constant Entity_Id := Comps (C);
623                         CC   : constant Node_Id   :=
624                                  Component_Clause (Comp);
625                         LB   : constant Uint :=
626                                  Static_Integer (Last_Bit (CC));
627                         NFB  : constant Uint := MSS - Uint_1 - LB;
628                         NLB  : constant Uint := NFB + Esize (Comp) - 1;
629                         Pos  : constant Uint :=
630                                  Static_Integer (Position (CC));
631
632                      begin
633                         if Warn_On_Reverse_Bit_Order then
634                            Error_Msg_Uint_1 := MSS;
635                            Error_Msg_N
636                              ("info: reverse bit order in machine " &
637                               "scalar of length^?", First_Bit (CC));
638                            Error_Msg_Uint_1 := NFB;
639                            Error_Msg_Uint_2 := NLB;
640
641                            if Bytes_Big_Endian then
642                               Error_Msg_NE
643                                 ("?\info: big-endian range for "
644                                  & "component & is ^ .. ^",
645                                  First_Bit (CC), Comp);
646                            else
647                               Error_Msg_NE
648                                 ("?\info: little-endian range "
649                                  & "for component & is ^ .. ^",
650                                  First_Bit (CC), Comp);
651                            end if;
652                         end if;
653
654                         Set_Component_Bit_Offset (Comp, Pos * SSU + NFB);
655                         Set_Normalized_First_Bit (Comp, NFB mod SSU);
656                      end;
657                   end loop;
658                end loop;
659             end Sort_CC;
660          end;
661       end if;
662    end Adjust_Record_For_Reverse_Bit_Order;
663
664    --------------------------------------
665    -- Alignment_Check_For_Esize_Change --
666    --------------------------------------
667
668    procedure Alignment_Check_For_Esize_Change (Typ : Entity_Id) is
669    begin
670       --  If the alignment is known, and not set by a rep clause, and is
671       --  inconsistent with the size being set, then reset it to unknown,
672       --  we assume in this case that the size overrides the inherited
673       --  alignment, and that the alignment must be recomputed.
674
675       if Known_Alignment (Typ)
676         and then not Has_Alignment_Clause (Typ)
677         and then Esize (Typ) mod (Alignment (Typ) * SSU) /= 0
678       then
679          Init_Alignment (Typ);
680       end if;
681    end Alignment_Check_For_Esize_Change;
682
683    -----------------------------------
684    -- Analyze_Aspect_Specifications --
685    -----------------------------------
686
687    procedure Analyze_Aspect_Specifications (N : Node_Id; E : Entity_Id) is
688       Aspect : Node_Id;
689       Aitem  : Node_Id;
690       Ent    : Node_Id;
691
692       L : constant List_Id := Aspect_Specifications (N);
693
694       Ins_Node : Node_Id := N;
695       --  Insert pragmas (except Pre/Post/Invariant/Predicate) after this node
696
697       --  The general processing involves building an attribute definition
698       --  clause or a pragma node that corresponds to the access type. Then
699       --  one of two things happens:
700
701       --  If we are required to delay the evaluation of this aspect to the
702       --  freeze point, we attach the corresponding pragma/attribute definition
703       --  clause to the aspect specification node, which is then placed in the
704       --  Rep Item chain. In this case we mark the entity by setting the flag
705       --  Has_Delayed_Aspects and we evaluate the rep item at the freeze point.
706
707       --  If no delay is required, we just insert the pragma or attribute
708       --  after the declaration, and it will get processed by the normal
709       --  circuit. The From_Aspect_Specification flag is set on the pragma
710       --  or attribute definition node in either case to activate special
711       --  processing (e.g. not traversing the list of homonyms for inline).
712
713       Delay_Required : Boolean;
714       --  Set True if delay is required
715
716    begin
717       pragma Assert (Present (L));
718
719       --  Loop through aspects
720
721       Aspect := First (L);
722       Aspect_Loop : while Present (Aspect) loop
723          declare
724             Loc  : constant Source_Ptr := Sloc (Aspect);
725             Id   : constant Node_Id    := Identifier (Aspect);
726             Expr : constant Node_Id    := Expression (Aspect);
727             Nam  : constant Name_Id    := Chars (Id);
728             A_Id : constant Aspect_Id  := Get_Aspect_Id (Nam);
729             Anod : Node_Id;
730
731             Eloc : Source_Ptr := Sloc (Expr);
732             --  Source location of expression, modified when we split PPC's
733
734             procedure Check_False_Aspect_For_Derived_Type;
735             --  This procedure checks for the case of a false aspect for a
736             --  derived type, which improperly tries to cancel an aspect
737             --  inherited from the parent;
738
739             -----------------------------------------
740             -- Check_False_Aspect_For_Derived_Type --
741             -----------------------------------------
742
743             procedure Check_False_Aspect_For_Derived_Type is
744             begin
745                --  We are only checking derived types
746
747                if not Is_Derived_Type (E) then
748                   return;
749                end if;
750
751                case A_Id is
752                   when Aspect_Atomic | Aspect_Shared =>
753                      if not Is_Atomic (E) then
754                         return;
755                      end if;
756
757                   when Aspect_Atomic_Components =>
758                      if not Has_Atomic_Components (E) then
759                         return;
760                      end if;
761
762                   when Aspect_Discard_Names =>
763                      if not Discard_Names (E) then
764                         return;
765                      end if;
766
767                   when Aspect_Pack =>
768                      if not Is_Packed (E) then
769                         return;
770                      end if;
771
772                   when Aspect_Unchecked_Union =>
773                      if not Is_Unchecked_Union (E) then
774                         return;
775                      end if;
776
777                   when Aspect_Volatile =>
778                      if not Is_Volatile (E) then
779                         return;
780                      end if;
781
782                   when Aspect_Volatile_Components =>
783                      if not Has_Volatile_Components (E) then
784                         return;
785                      end if;
786
787                   when others =>
788                      return;
789                end case;
790
791                --  Fall through means we are canceling an inherited aspect
792
793                Error_Msg_Name_1 := Nam;
794                Error_Msg_NE
795                  ("derived type& inherits aspect%, cannot cancel", Expr, E);
796             end Check_False_Aspect_For_Derived_Type;
797
798          --  Start of processing for Aspect_Loop
799
800          begin
801             --  Skip aspect if already analyzed (not clear if this is needed)
802
803             if Analyzed (Aspect) then
804                goto Continue;
805             end if;
806
807             Set_Analyzed (Aspect);
808             Set_Entity (Aspect, E);
809             Ent := New_Occurrence_Of (E, Sloc (Id));
810
811             --  Check for duplicate aspect. Note that the Comes_From_Source
812             --  test allows duplicate Pre/Post's that we generate internally
813             --  to escape being flagged here.
814
815             Anod := First (L);
816             while Anod /= Aspect loop
817                if Same_Aspect (A_Id, Get_Aspect_Id (Chars (Identifier (Anod))))
818                  and then Comes_From_Source (Aspect)
819                then
820                   Error_Msg_Name_1 := Nam;
821                   Error_Msg_Sloc := Sloc (Anod);
822
823                   --  Case of same aspect specified twice
824
825                   if Class_Present (Anod) = Class_Present (Aspect) then
826                      if not Class_Present (Anod) then
827                         Error_Msg_NE
828                           ("aspect% for & previously given#",
829                            Id, E);
830                      else
831                         Error_Msg_NE
832                           ("aspect `%''Class` for & previously given#",
833                            Id, E);
834                      end if;
835
836                   --  Case of Pre and Pre'Class both specified
837
838                   elsif Nam = Name_Pre then
839                      if Class_Present (Aspect) then
840                         Error_Msg_NE
841                           ("aspect `Pre''Class` for & is not allowed here",
842                            Id, E);
843                         Error_Msg_NE
844                           ("\since aspect `Pre` previously given#",
845                            Id, E);
846
847                      else
848                         Error_Msg_NE
849                           ("aspect `Pre` for & is not allowed here",
850                            Id, E);
851                         Error_Msg_NE
852                           ("\since aspect `Pre''Class` previously given#",
853                            Id, E);
854                      end if;
855                   end if;
856
857                   goto Continue;
858                end if;
859
860                Next (Anod);
861             end loop;
862
863             --  Copy expression for later processing by the procedures
864             --  Check_Aspect_At_[Freeze_Point | End_Of_Declarations]
865
866             Set_Entity (Id, New_Copy_Tree (Expr));
867
868             --  Processing based on specific aspect
869
870             case A_Id is
871
872                --  No_Aspect should be impossible
873
874                when No_Aspect =>
875                   raise Program_Error;
876
877                --  Aspects taking an optional boolean argument. For all of
878                --  these we just create a matching pragma and insert it, if
879                --  the expression is missing or set to True. If the expression
880                --  is False, we can ignore the aspect with the exception that
881                --  in the case of a derived type, we must check for an illegal
882                --  attempt to cancel an inherited aspect.
883
884                when Boolean_Aspects =>
885                   Set_Is_Boolean_Aspect (Aspect);
886
887                   if Present (Expr)
888                     and then Is_False (Static_Boolean (Expr))
889                   then
890                      Check_False_Aspect_For_Derived_Type;
891                      goto Continue;
892                   end if;
893
894                   --  If True, build corresponding pragma node
895
896                   Aitem :=
897                     Make_Pragma (Loc,
898                       Pragma_Argument_Associations => New_List (Ent),
899                       Pragma_Identifier            =>
900                         Make_Identifier (Sloc (Id), Chars (Id)));
901
902                   --  Never need to delay for boolean aspects
903
904                   Delay_Required := False;
905
906                --  Library unit aspects. These are boolean aspects, but we
907                --  have to do special things with the insertion, since the
908                --  pragma belongs inside the declarations of a package.
909
910                when Library_Unit_Aspects =>
911                   if Present (Expr)
912                     and then Is_False (Static_Boolean (Expr))
913                   then
914                      goto Continue;
915                   end if;
916
917                   --  Build corresponding pragma node
918
919                   Aitem :=
920                     Make_Pragma (Loc,
921                       Pragma_Argument_Associations => New_List (Ent),
922                       Pragma_Identifier            =>
923                         Make_Identifier (Sloc (Id), Chars (Id)));
924
925                   --  This requires special handling in the case of a package
926                   --  declaration, the pragma needs to be inserted in the list
927                   --  of declarations for the associated package. There is no
928                   --  issue of visibility delay for these aspects.
929
930                   if Nkind (N) = N_Package_Declaration then
931                      if Nkind (Parent (N)) /= N_Compilation_Unit then
932                         Error_Msg_N
933                           ("incorrect context for library unit aspect&", Id);
934                      else
935                         Prepend
936                           (Aitem, Visible_Declarations (Specification (N)));
937                      end if;
938
939                      goto Continue;
940                   end if;
941
942                   --  If not package declaration, no delay is required
943
944                   Delay_Required := False;
945
946                --  Aspects corresponding to attribute definition clauses
947
948                when Aspect_Address        |
949                     Aspect_Alignment      |
950                     Aspect_Bit_Order      |
951                     Aspect_Component_Size |
952                     Aspect_External_Tag   |
953                     Aspect_Input          |
954                     Aspect_Machine_Radix  |
955                     Aspect_Object_Size    |
956                     Aspect_Output         |
957                     Aspect_Read           |
958                     Aspect_Size           |
959                     Aspect_Storage_Pool   |
960                     Aspect_Storage_Size   |
961                     Aspect_Stream_Size    |
962                     Aspect_Value_Size     |
963                     Aspect_Write          =>
964
965                   --  Construct the attribute definition clause
966
967                   Aitem :=
968                     Make_Attribute_Definition_Clause (Loc,
969                       Name       => Ent,
970                       Chars      => Chars (Id),
971                       Expression => Relocate_Node (Expr));
972
973                   --  A delay is required except in the common case where
974                   --  the expression is a literal, in which case it is fine
975                   --  to take care of it right away.
976
977                   if Nkind_In (Expr, N_Integer_Literal, N_String_Literal) then
978                      Delay_Required := False;
979                   else
980                      Delay_Required := True;
981                      Set_Is_Delayed_Aspect (Aspect);
982                   end if;
983
984                --  Aspects corresponding to pragmas with two arguments, where
985                --  the first argument is a local name referring to the entity,
986                --  and the second argument is the aspect definition expression
987                --  which is an expression that does not get analyzed.
988
989                when Aspect_Suppress   |
990                     Aspect_Unsuppress =>
991
992                   --  Construct the pragma
993
994                   Aitem :=
995                     Make_Pragma (Loc,
996                       Pragma_Argument_Associations => New_List (
997                         New_Occurrence_Of (E, Loc),
998                         Relocate_Node (Expr)),
999                       Pragma_Identifier            =>
1000                         Make_Identifier (Sloc (Id), Chars (Id)));
1001
1002                   --  We don't have to play the delay game here, since the only
1003                   --  values are check names which don't get analyzed anyway.
1004
1005                   Delay_Required := False;
1006
1007                --  Aspects corresponding to pragmas with two arguments, where
1008                --  the second argument is a local name referring to the entity,
1009                --  and the first argument is the aspect definition expression.
1010
1011                when Aspect_Warnings =>
1012
1013                   --  Construct the pragma
1014
1015                   Aitem :=
1016                     Make_Pragma (Loc,
1017                       Pragma_Argument_Associations => New_List (
1018                         Relocate_Node (Expr),
1019                         New_Occurrence_Of (E, Loc)),
1020                       Pragma_Identifier            =>
1021                         Make_Identifier (Sloc (Id), Chars (Id)),
1022                       Class_Present                => Class_Present (Aspect));
1023
1024                   --  We don't have to play the delay game here, since the only
1025                   --  values are ON/OFF which don't get analyzed anyway.
1026
1027                   Delay_Required := False;
1028
1029                --  Default_Value and Default_Component_Value aspects. These
1030                --  are specially handled because they have no corresponding
1031                --  pragmas or attributes.
1032
1033                when Aspect_Default_Value | Aspect_Default_Component_Value =>
1034                   Error_Msg_Name_1 := Chars (Id);
1035
1036                   if not Is_Type (E) then
1037                      Error_Msg_N ("aspect% can only apply to a type", Id);
1038                      goto Continue;
1039
1040                   elsif not Is_First_Subtype (E) then
1041                      Error_Msg_N ("aspect% cannot apply to subtype", Id);
1042                      goto Continue;
1043
1044                   elsif A_Id = Aspect_Default_Value
1045                     and then not Is_Scalar_Type (E)
1046                   then
1047                      Error_Msg_N
1048                        ("aspect% can only be applied to scalar type", Id);
1049                      goto Continue;
1050
1051                   elsif A_Id = Aspect_Default_Component_Value then
1052                      if not Is_Array_Type (E) then
1053                         Error_Msg_N
1054                           ("aspect% can only be applied to array type", Id);
1055                         goto Continue;
1056                      elsif not Is_Scalar_Type (Component_Type (E)) then
1057                         Error_Msg_N
1058                           ("aspect% requires scalar components", Id);
1059                         goto Continue;
1060                      end if;
1061                   end if;
1062
1063                   Aitem := Empty;
1064                   Delay_Required := True;
1065                   Set_Is_Delayed_Aspect (Aspect);
1066                   Set_Has_Default_Aspect (Base_Type (Entity (Ent)));
1067
1068                --  Aspects Pre/Post generate Precondition/Postcondition pragmas
1069                --  with a first argument that is the expression, and a second
1070                --  argument that is an informative message if the test fails.
1071                --  This is inserted right after the declaration, to get the
1072                --  required pragma placement. The processing for the pragmas
1073                --  takes care of the required delay.
1074
1075                when Pre_Post_Aspects => declare
1076                   Pname : Name_Id;
1077
1078                begin
1079                   if A_Id = Aspect_Pre or else A_Id = Aspect_Precondition then
1080                      Pname := Name_Precondition;
1081                   else
1082                      Pname := Name_Postcondition;
1083                   end if;
1084
1085                   --  If the expressions is of the form A and then B, then
1086                   --  we generate separate Pre/Post aspects for the separate
1087                   --  clauses. Since we allow multiple pragmas, there is no
1088                   --  problem in allowing multiple Pre/Post aspects internally.
1089
1090                   --  We do not do this for Pre'Class, since we have to put
1091                   --  these conditions together in a complex OR expression
1092
1093                   if Pname = Name_Postcondition
1094                     or else not Class_Present (Aspect)
1095                   then
1096                      while Nkind (Expr) = N_And_Then loop
1097                         Insert_After (Aspect,
1098                           Make_Aspect_Specification (Sloc (Right_Opnd (Expr)),
1099                             Identifier    => Identifier (Aspect),
1100                             Expression    => Relocate_Node (Right_Opnd (Expr)),
1101                             Class_Present => Class_Present (Aspect),
1102                             Split_PPC     => True));
1103                         Rewrite (Expr, Relocate_Node (Left_Opnd (Expr)));
1104                         Eloc := Sloc (Expr);
1105                      end loop;
1106                   end if;
1107
1108                   --  Build the precondition/postcondition pragma
1109
1110                   Aitem :=
1111                     Make_Pragma (Loc,
1112                       Pragma_Identifier            =>
1113                         Make_Identifier (Sloc (Id), Pname),
1114                       Class_Present                => Class_Present (Aspect),
1115                       Split_PPC                    => Split_PPC (Aspect),
1116                       Pragma_Argument_Associations => New_List (
1117                         Make_Pragma_Argument_Association (Eloc,
1118                           Chars      => Name_Check,
1119                           Expression => Relocate_Node (Expr))));
1120
1121                   --  Add message unless exception messages are suppressed
1122
1123                   if not Opt.Exception_Locations_Suppressed then
1124                      Append_To (Pragma_Argument_Associations (Aitem),
1125                        Make_Pragma_Argument_Association (Eloc,
1126                          Chars     => Name_Message,
1127                          Expression =>
1128                            Make_String_Literal (Eloc,
1129                              Strval => "failed "
1130                                        & Get_Name_String (Pname)
1131                                        & " from "
1132                                        & Build_Location_String (Eloc))));
1133                   end if;
1134
1135                   Set_From_Aspect_Specification (Aitem, True);
1136                   Set_Is_Delayed_Aspect (Aspect);
1137
1138                   --  For Pre/Post cases, insert immediately after the entity
1139                   --  declaration, since that is the required pragma placement.
1140                   --  Note that for these aspects, we do not have to worry
1141                   --  about delay issues, since the pragmas themselves deal
1142                   --  with delay of visibility for the expression analysis.
1143
1144                   --  If the entity is a library-level subprogram, the pre/
1145                   --  postconditions must be treated as late pragmas.
1146
1147                   if Nkind (Parent (N)) = N_Compilation_Unit then
1148                      Add_Global_Declaration (Aitem);
1149                   else
1150                      Insert_After (N, Aitem);
1151                   end if;
1152
1153                   goto Continue;
1154                end;
1155
1156                --  Invariant aspects generate a corresponding pragma with a
1157                --  first argument that is the entity, a second argument that is
1158                --  the expression and a third argument that is an appropriate
1159                --  message. This is inserted right after the declaration, to
1160                --  get the required pragma placement. The pragma processing
1161                --  takes care of the required delay.
1162
1163                when Aspect_Invariant      |
1164                     Aspect_Type_Invariant =>
1165
1166                   --  Construct the pragma
1167
1168                   Aitem :=
1169                     Make_Pragma (Loc,
1170                       Pragma_Argument_Associations =>
1171                         New_List (Ent, Relocate_Node (Expr)),
1172                       Class_Present                => Class_Present (Aspect),
1173                       Pragma_Identifier            =>
1174                         Make_Identifier (Sloc (Id), Name_Invariant));
1175
1176                   --  Add message unless exception messages are suppressed
1177
1178                   if not Opt.Exception_Locations_Suppressed then
1179                      Append_To (Pragma_Argument_Associations (Aitem),
1180                        Make_Pragma_Argument_Association (Eloc,
1181                          Chars      => Name_Message,
1182                          Expression =>
1183                            Make_String_Literal (Eloc,
1184                              Strval => "failed invariant from "
1185                                        & Build_Location_String (Eloc))));
1186                   end if;
1187
1188                   Set_From_Aspect_Specification (Aitem, True);
1189                   Set_Is_Delayed_Aspect (Aspect);
1190
1191                   --  For Invariant case, insert immediately after the entity
1192                   --  declaration. We do not have to worry about delay issues
1193                   --  since the pragma processing takes care of this.
1194
1195                   Insert_After (N, Aitem);
1196                   goto Continue;
1197
1198                --  Predicate aspects generate a corresponding pragma with a
1199                --  first argument that is the entity, and the second argument
1200                --  is the expression.
1201
1202                when Aspect_Dynamic_Predicate |
1203                     Aspect_Predicate         |
1204                     Aspect_Static_Predicate  =>
1205
1206                   --  Construct the pragma (always a pragma Predicate, with
1207                   --  flags recording whether
1208
1209                   Aitem :=
1210                     Make_Pragma (Loc,
1211                       Pragma_Argument_Associations =>
1212                         New_List (Ent, Relocate_Node (Expr)),
1213                       Class_Present                => Class_Present (Aspect),
1214                       Pragma_Identifier            =>
1215                         Make_Identifier (Sloc (Id), Name_Predicate));
1216
1217                   Set_From_Aspect_Specification (Aitem, True);
1218
1219                   --  Set special flags for dynamic/static cases
1220
1221                   if A_Id = Aspect_Dynamic_Predicate then
1222                      Set_From_Dynamic_Predicate (Aitem);
1223                   elsif A_Id = Aspect_Static_Predicate then
1224                      Set_From_Static_Predicate (Aitem);
1225                   end if;
1226
1227                   --  Make sure we have a freeze node (it might otherwise be
1228                   --  missing in cases like subtype X is Y, and we would not
1229                   --  have a place to build the predicate function).
1230
1231                   Set_Has_Predicates (E);
1232                   Ensure_Freeze_Node (E);
1233                   Set_Is_Delayed_Aspect (Aspect);
1234                   Delay_Required := True;
1235             end case;
1236
1237             --  If a delay is required, we delay the freeze (not much point in
1238             --  delaying the aspect if we don't delay the freeze!). The pragma
1239             --  or attribute clause if there is one is then attached to the
1240             --  aspect specification which is placed in the rep item list.
1241
1242             if Delay_Required then
1243                if Present (Aitem) then
1244                   Set_From_Aspect_Specification (Aitem, True);
1245                   Set_Is_Delayed_Aspect (Aitem);
1246                   Set_Aspect_Rep_Item (Aspect, Aitem);
1247                end if;
1248
1249                Ensure_Freeze_Node (E);
1250                Set_Has_Delayed_Aspects (E);
1251                Record_Rep_Item (E, Aspect);
1252
1253             --  If no delay required, insert the pragma/clause in the tree
1254
1255             else
1256                Set_From_Aspect_Specification (Aitem, True);
1257
1258                --  If this is a compilation unit, we will put the pragma in
1259                --  the Pragmas_After list of the N_Compilation_Unit_Aux node.
1260
1261                if Nkind (Parent (Ins_Node)) = N_Compilation_Unit then
1262                   declare
1263                      Aux : constant Node_Id :=
1264                              Aux_Decls_Node (Parent (Ins_Node));
1265
1266                   begin
1267                      pragma Assert (Nkind (Aux) = N_Compilation_Unit_Aux);
1268
1269                      if No (Pragmas_After (Aux)) then
1270                         Set_Pragmas_After (Aux, Empty_List);
1271                      end if;
1272
1273                      --  For Pre_Post put at start of list, otherwise at end
1274
1275                      if A_Id in Pre_Post_Aspects then
1276                         Prepend (Aitem, Pragmas_After (Aux));
1277                      else
1278                         Append (Aitem, Pragmas_After (Aux));
1279                      end if;
1280                   end;
1281
1282                --  Here if not compilation unit case
1283
1284                else
1285                   --  For Pre/Post cases, insert immediately after the entity
1286                   --  declaration, since that is the required pragma placement.
1287
1288                   if A_Id in Pre_Post_Aspects then
1289                      Insert_After (N, Aitem);
1290
1291                   --  For all other cases, insert in sequence
1292
1293                   else
1294                      Insert_After (Ins_Node, Aitem);
1295                      Ins_Node := Aitem;
1296                   end if;
1297                end if;
1298             end if;
1299          end;
1300
1301       <<Continue>>
1302          Next (Aspect);
1303       end loop Aspect_Loop;
1304    end Analyze_Aspect_Specifications;
1305
1306    -----------------------
1307    -- Analyze_At_Clause --
1308    -----------------------
1309
1310    --  An at clause is replaced by the corresponding Address attribute
1311    --  definition clause that is the preferred approach in Ada 95.
1312
1313    procedure Analyze_At_Clause (N : Node_Id) is
1314       CS : constant Boolean := Comes_From_Source (N);
1315
1316    begin
1317       --  This is an obsolescent feature
1318
1319       Check_Restriction (No_Obsolescent_Features, N);
1320
1321       if Warn_On_Obsolescent_Feature then
1322          Error_Msg_N
1323            ("at clause is an obsolescent feature (RM J.7(2))?", N);
1324          Error_Msg_N
1325            ("\use address attribute definition clause instead?", N);
1326       end if;
1327
1328       --  Rewrite as address clause
1329
1330       Rewrite (N,
1331         Make_Attribute_Definition_Clause (Sloc (N),
1332           Name  => Identifier (N),
1333           Chars => Name_Address,
1334           Expression => Expression (N)));
1335
1336       --  We preserve Comes_From_Source, since logically the clause still
1337       --  comes from the source program even though it is changed in form.
1338
1339       Set_Comes_From_Source (N, CS);
1340
1341       --  Analyze rewritten clause
1342
1343       Analyze_Attribute_Definition_Clause (N);
1344    end Analyze_At_Clause;
1345
1346    -----------------------------------------
1347    -- Analyze_Attribute_Definition_Clause --
1348    -----------------------------------------
1349
1350    procedure Analyze_Attribute_Definition_Clause (N : Node_Id) is
1351       Loc   : constant Source_Ptr   := Sloc (N);
1352       Nam   : constant Node_Id      := Name (N);
1353       Attr  : constant Name_Id      := Chars (N);
1354       Expr  : constant Node_Id      := Expression (N);
1355       Id    : constant Attribute_Id := Get_Attribute_Id (Attr);
1356
1357       Ent : Entity_Id;
1358       --  The entity of Nam after it is analyzed. In the case of an incomplete
1359       --  type, this is the underlying type.
1360
1361       U_Ent : Entity_Id;
1362       --  The underlying entity to which the attribute applies. Generally this
1363       --  is the Underlying_Type of Ent, except in the case where the clause
1364       --  applies to full view of incomplete type or private type in which case
1365       --  U_Ent is just a copy of Ent.
1366
1367       FOnly : Boolean := False;
1368       --  Reset to True for subtype specific attribute (Alignment, Size)
1369       --  and for stream attributes, i.e. those cases where in the call
1370       --  to Rep_Item_Too_Late, FOnly is set True so that only the freezing
1371       --  rules are checked. Note that the case of stream attributes is not
1372       --  clear from the RM, but see AI95-00137. Also, the RM seems to
1373       --  disallow Storage_Size for derived task types, but that is also
1374       --  clearly unintentional.
1375
1376       procedure Analyze_Stream_TSS_Definition (TSS_Nam : TSS_Name_Type);
1377       --  Common processing for 'Read, 'Write, 'Input and 'Output attribute
1378       --  definition clauses.
1379
1380       function Duplicate_Clause return Boolean;
1381       --  This routine checks if the aspect for U_Ent being given by attribute
1382       --  definition clause N is for an aspect that has already been specified,
1383       --  and if so gives an error message. If there is a duplicate, True is
1384       --  returned, otherwise if there is no error, False is returned.
1385
1386       -----------------------------------
1387       -- Analyze_Stream_TSS_Definition --
1388       -----------------------------------
1389
1390       procedure Analyze_Stream_TSS_Definition (TSS_Nam : TSS_Name_Type) is
1391          Subp : Entity_Id := Empty;
1392          I    : Interp_Index;
1393          It   : Interp;
1394          Pnam : Entity_Id;
1395
1396          Is_Read : constant Boolean := (TSS_Nam = TSS_Stream_Read);
1397          --  True for Read attribute, false for other attributes
1398
1399          function Has_Good_Profile (Subp : Entity_Id) return Boolean;
1400          --  Return true if the entity is a subprogram with an appropriate
1401          --  profile for the attribute being defined.
1402
1403          ----------------------
1404          -- Has_Good_Profile --
1405          ----------------------
1406
1407          function Has_Good_Profile (Subp : Entity_Id) return Boolean is
1408             F              : Entity_Id;
1409             Is_Function    : constant Boolean := (TSS_Nam = TSS_Stream_Input);
1410             Expected_Ekind : constant array (Boolean) of Entity_Kind :=
1411                                (False => E_Procedure, True => E_Function);
1412             Typ            : Entity_Id;
1413
1414          begin
1415             if Ekind (Subp) /= Expected_Ekind (Is_Function) then
1416                return False;
1417             end if;
1418
1419             F := First_Formal (Subp);
1420
1421             if No (F)
1422               or else Ekind (Etype (F)) /= E_Anonymous_Access_Type
1423               or else Designated_Type (Etype (F)) /=
1424                                Class_Wide_Type (RTE (RE_Root_Stream_Type))
1425             then
1426                return False;
1427             end if;
1428
1429             if not Is_Function then
1430                Next_Formal (F);
1431
1432                declare
1433                   Expected_Mode : constant array (Boolean) of Entity_Kind :=
1434                                     (False => E_In_Parameter,
1435                                      True  => E_Out_Parameter);
1436                begin
1437                   if Parameter_Mode (F) /= Expected_Mode (Is_Read) then
1438                      return False;
1439                   end if;
1440                end;
1441
1442                Typ := Etype (F);
1443
1444             else
1445                Typ := Etype (Subp);
1446             end if;
1447
1448             return Base_Type (Typ) = Base_Type (Ent)
1449               and then No (Next_Formal (F));
1450          end Has_Good_Profile;
1451
1452       --  Start of processing for Analyze_Stream_TSS_Definition
1453
1454       begin
1455          FOnly := True;
1456
1457          if not Is_Type (U_Ent) then
1458             Error_Msg_N ("local name must be a subtype", Nam);
1459             return;
1460          end if;
1461
1462          Pnam := TSS (Base_Type (U_Ent), TSS_Nam);
1463
1464          --  If Pnam is present, it can be either inherited from an ancestor
1465          --  type (in which case it is legal to redefine it for this type), or
1466          --  be a previous definition of the attribute for the same type (in
1467          --  which case it is illegal).
1468
1469          --  In the first case, it will have been analyzed already, and we
1470          --  can check that its profile does not match the expected profile
1471          --  for a stream attribute of U_Ent. In the second case, either Pnam
1472          --  has been analyzed (and has the expected profile), or it has not
1473          --  been analyzed yet (case of a type that has not been frozen yet
1474          --  and for which the stream attribute has been set using Set_TSS).
1475
1476          if Present (Pnam)
1477            and then (No (First_Entity (Pnam)) or else Has_Good_Profile (Pnam))
1478          then
1479             Error_Msg_Sloc := Sloc (Pnam);
1480             Error_Msg_Name_1 := Attr;
1481             Error_Msg_N ("% attribute already defined #", Nam);
1482             return;
1483          end if;
1484
1485          Analyze (Expr);
1486
1487          if Is_Entity_Name (Expr) then
1488             if not Is_Overloaded (Expr) then
1489                if Has_Good_Profile (Entity (Expr)) then
1490                   Subp := Entity (Expr);
1491                end if;
1492
1493             else
1494                Get_First_Interp (Expr, I, It);
1495                while Present (It.Nam) loop
1496                   if Has_Good_Profile (It.Nam) then
1497                      Subp := It.Nam;
1498                      exit;
1499                   end if;
1500
1501                   Get_Next_Interp (I, It);
1502                end loop;
1503             end if;
1504          end if;
1505
1506          if Present (Subp) then
1507             if Is_Abstract_Subprogram (Subp) then
1508                Error_Msg_N ("stream subprogram must not be abstract", Expr);
1509                return;
1510             end if;
1511
1512             Set_Entity (Expr, Subp);
1513             Set_Etype (Expr, Etype (Subp));
1514
1515             New_Stream_Subprogram (N, U_Ent, Subp, TSS_Nam);
1516
1517          else
1518             Error_Msg_Name_1 := Attr;
1519             Error_Msg_N ("incorrect expression for% attribute", Expr);
1520          end if;
1521       end Analyze_Stream_TSS_Definition;
1522
1523       ----------------------
1524       -- Duplicate_Clause --
1525       ----------------------
1526
1527       function Duplicate_Clause return Boolean is
1528          A : Node_Id;
1529
1530       begin
1531          --  Nothing to do if this attribute definition clause comes from
1532          --  an aspect specification, since we could not be duplicating an
1533          --  explicit clause, and we dealt with the case of duplicated aspects
1534          --  in Analyze_Aspect_Specifications.
1535
1536          if From_Aspect_Specification (N) then
1537             return False;
1538          end if;
1539
1540          --  Otherwise current clause may duplicate previous clause or a
1541          --  previously given aspect specification for the same aspect.
1542
1543          A := Get_Rep_Item_For_Entity (U_Ent, Chars (N));
1544
1545          if Present (A) then
1546             if Entity (A) = U_Ent then
1547                Error_Msg_Name_1 := Chars (N);
1548                Error_Msg_Sloc := Sloc (A);
1549                Error_Msg_NE ("aspect% for & previously given#", N, U_Ent);
1550                return True;
1551             end if;
1552          end if;
1553
1554          return False;
1555       end Duplicate_Clause;
1556
1557    --  Start of processing for Analyze_Attribute_Definition_Clause
1558
1559    begin
1560       --  The following code is a defense against recursion. Not clear that
1561       --  this can happen legitimately, but perhaps some error situations
1562       --  can cause it, and we did see this recursion during testing.
1563
1564       if Analyzed (N) then
1565          return;
1566       else
1567          Set_Analyzed (N, True);
1568       end if;
1569
1570       --  Process Ignore_Rep_Clauses option
1571
1572       if Ignore_Rep_Clauses then
1573          case Id is
1574
1575             --  The following should be ignored. They do not affect legality
1576             --  and may be target dependent. The basic idea of -gnatI is to
1577             --  ignore any rep clauses that may be target dependent but do not
1578             --  affect legality (except possibly to be rejected because they
1579             --  are incompatible with the compilation target).
1580
1581             when Attribute_Alignment      |
1582                  Attribute_Bit_Order      |
1583                  Attribute_Component_Size |
1584                  Attribute_Machine_Radix  |
1585                  Attribute_Object_Size    |
1586                  Attribute_Size           |
1587                  Attribute_Small          |
1588                  Attribute_Stream_Size    |
1589                  Attribute_Value_Size     =>
1590
1591                Rewrite (N, Make_Null_Statement (Sloc (N)));
1592                return;
1593
1594             --  The following should not be ignored, because in the first place
1595             --  they are reasonably portable, and should not cause problems in
1596             --  compiling code from another target, and also they do affect
1597             --  legality, e.g. failing to provide a stream attribute for a
1598             --  type may make a program illegal.
1599
1600             when Attribute_External_Tag            |
1601                  Attribute_Input                   |
1602                  Attribute_Output                  |
1603                  Attribute_Read                    |
1604                  Attribute_Storage_Pool            |
1605                  Attribute_Storage_Size            |
1606                  Attribute_Write                   =>
1607                null;
1608
1609             --  Other cases are errors ("attribute& cannot be set with
1610             --  definition clause"), which will be caught below.
1611
1612             when others =>
1613                null;
1614          end case;
1615       end if;
1616
1617       Analyze (Nam);
1618       Ent := Entity (Nam);
1619
1620       if Rep_Item_Too_Early (Ent, N) then
1621          return;
1622       end if;
1623
1624       --  Rep clause applies to full view of incomplete type or private type if
1625       --  we have one (if not, this is a premature use of the type). However,
1626       --  certain semantic checks need to be done on the specified entity (i.e.
1627       --  the private view), so we save it in Ent.
1628
1629       if Is_Private_Type (Ent)
1630         and then Is_Derived_Type (Ent)
1631         and then not Is_Tagged_Type (Ent)
1632         and then No (Full_View (Ent))
1633       then
1634          --  If this is a private type whose completion is a derivation from
1635          --  another private type, there is no full view, and the attribute
1636          --  belongs to the type itself, not its underlying parent.
1637
1638          U_Ent := Ent;
1639
1640       elsif Ekind (Ent) = E_Incomplete_Type then
1641
1642          --  The attribute applies to the full view, set the entity of the
1643          --  attribute definition accordingly.
1644
1645          Ent := Underlying_Type (Ent);
1646          U_Ent := Ent;
1647          Set_Entity (Nam, Ent);
1648
1649       else
1650          U_Ent := Underlying_Type (Ent);
1651       end if;
1652
1653       --  Complete other routine error checks
1654
1655       if Etype (Nam) = Any_Type then
1656          return;
1657
1658       elsif Scope (Ent) /= Current_Scope then
1659          Error_Msg_N ("entity must be declared in this scope", Nam);
1660          return;
1661
1662       elsif No (U_Ent) then
1663          U_Ent := Ent;
1664
1665       elsif Is_Type (U_Ent)
1666         and then not Is_First_Subtype (U_Ent)
1667         and then Id /= Attribute_Object_Size
1668         and then Id /= Attribute_Value_Size
1669         and then not From_At_Mod (N)
1670       then
1671          Error_Msg_N ("cannot specify attribute for subtype", Nam);
1672          return;
1673       end if;
1674
1675       Set_Entity (N, U_Ent);
1676
1677       --  Switch on particular attribute
1678
1679       case Id is
1680
1681          -------------
1682          -- Address --
1683          -------------
1684
1685          --  Address attribute definition clause
1686
1687          when Attribute_Address => Address : begin
1688
1689             --  A little error check, catch for X'Address use X'Address;
1690
1691             if Nkind (Nam) = N_Identifier
1692               and then Nkind (Expr) = N_Attribute_Reference
1693               and then Attribute_Name (Expr) = Name_Address
1694               and then Nkind (Prefix (Expr)) = N_Identifier
1695               and then Chars (Nam) = Chars (Prefix (Expr))
1696             then
1697                Error_Msg_NE
1698                  ("address for & is self-referencing", Prefix (Expr), Ent);
1699                return;
1700             end if;
1701
1702             --  Not that special case, carry on with analysis of expression
1703
1704             Analyze_And_Resolve (Expr, RTE (RE_Address));
1705
1706             --  Even when ignoring rep clauses we need to indicate that the
1707             --  entity has an address clause and thus it is legal to declare
1708             --  it imported.
1709
1710             if Ignore_Rep_Clauses then
1711                if Ekind_In (U_Ent, E_Variable, E_Constant) then
1712                   Record_Rep_Item (U_Ent, N);
1713                end if;
1714
1715                return;
1716             end if;
1717
1718             if Duplicate_Clause then
1719                null;
1720
1721             --  Case of address clause for subprogram
1722
1723             elsif Is_Subprogram (U_Ent) then
1724                if Has_Homonym (U_Ent) then
1725                   Error_Msg_N
1726                     ("address clause cannot be given " &
1727                      "for overloaded subprogram",
1728                      Nam);
1729                   return;
1730                end if;
1731
1732                --  For subprograms, all address clauses are permitted, and we
1733                --  mark the subprogram as having a deferred freeze so that Gigi
1734                --  will not elaborate it too soon.
1735
1736                --  Above needs more comments, what is too soon about???
1737
1738                Set_Has_Delayed_Freeze (U_Ent);
1739
1740             --  Case of address clause for entry
1741
1742             elsif Ekind (U_Ent) = E_Entry then
1743                if Nkind (Parent (N)) = N_Task_Body then
1744                   Error_Msg_N
1745                     ("entry address must be specified in task spec", Nam);
1746                   return;
1747                end if;
1748
1749                --  For entries, we require a constant address
1750
1751                Check_Constant_Address_Clause (Expr, U_Ent);
1752
1753                --  Special checks for task types
1754
1755                if Is_Task_Type (Scope (U_Ent))
1756                  and then Comes_From_Source (Scope (U_Ent))
1757                then
1758                   Error_Msg_N
1759                     ("?entry address declared for entry in task type", N);
1760                   Error_Msg_N
1761                     ("\?only one task can be declared of this type", N);
1762                end if;
1763
1764                --  Entry address clauses are obsolescent
1765
1766                Check_Restriction (No_Obsolescent_Features, N);
1767
1768                if Warn_On_Obsolescent_Feature then
1769                   Error_Msg_N
1770                     ("attaching interrupt to task entry is an " &
1771                      "obsolescent feature (RM J.7.1)?", N);
1772                   Error_Msg_N
1773                     ("\use interrupt procedure instead?", N);
1774                end if;
1775
1776             --  Case of an address clause for a controlled object which we
1777             --  consider to be erroneous.
1778
1779             elsif Is_Controlled (Etype (U_Ent))
1780               or else Has_Controlled_Component (Etype (U_Ent))
1781             then
1782                Error_Msg_NE
1783                  ("?controlled object& must not be overlaid", Nam, U_Ent);
1784                Error_Msg_N
1785                  ("\?Program_Error will be raised at run time", Nam);
1786                Insert_Action (Declaration_Node (U_Ent),
1787                  Make_Raise_Program_Error (Loc,
1788                    Reason => PE_Overlaid_Controlled_Object));
1789                return;
1790
1791             --  Case of address clause for a (non-controlled) object
1792
1793             elsif
1794               Ekind (U_Ent) = E_Variable
1795                 or else
1796               Ekind (U_Ent) = E_Constant
1797             then
1798                declare
1799                   Expr  : constant Node_Id := Expression (N);
1800                   O_Ent : Entity_Id;
1801                   Off   : Boolean;
1802
1803                begin
1804                   --  Exported variables cannot have an address clause, because
1805                   --  this cancels the effect of the pragma Export.
1806
1807                   if Is_Exported (U_Ent) then
1808                      Error_Msg_N
1809                        ("cannot export object with address clause", Nam);
1810                      return;
1811                   end if;
1812
1813                   Find_Overlaid_Entity (N, O_Ent, Off);
1814
1815                   --  Overlaying controlled objects is erroneous
1816
1817                   if Present (O_Ent)
1818                     and then (Has_Controlled_Component (Etype (O_Ent))
1819                                 or else Is_Controlled (Etype (O_Ent)))
1820                   then
1821                      Error_Msg_N
1822                        ("?cannot overlay with controlled object", Expr);
1823                      Error_Msg_N
1824                        ("\?Program_Error will be raised at run time", Expr);
1825                      Insert_Action (Declaration_Node (U_Ent),
1826                        Make_Raise_Program_Error (Loc,
1827                          Reason => PE_Overlaid_Controlled_Object));
1828                      return;
1829
1830                   elsif Present (O_Ent)
1831                     and then Ekind (U_Ent) = E_Constant
1832                     and then not Is_Constant_Object (O_Ent)
1833                   then
1834                      Error_Msg_N ("constant overlays a variable?", Expr);
1835
1836                   elsif Present (Renamed_Object (U_Ent)) then
1837                      Error_Msg_N
1838                        ("address clause not allowed"
1839                           & " for a renaming declaration (RM 13.1(6))", Nam);
1840                      return;
1841
1842                   --  Imported variables can have an address clause, but then
1843                   --  the import is pretty meaningless except to suppress
1844                   --  initializations, so we do not need such variables to
1845                   --  be statically allocated (and in fact it causes trouble
1846                   --  if the address clause is a local value).
1847
1848                   elsif Is_Imported (U_Ent) then
1849                      Set_Is_Statically_Allocated (U_Ent, False);
1850                   end if;
1851
1852                   --  We mark a possible modification of a variable with an
1853                   --  address clause, since it is likely aliasing is occurring.
1854
1855                   Note_Possible_Modification (Nam, Sure => False);
1856
1857                   --  Here we are checking for explicit overlap of one variable
1858                   --  by another, and if we find this then mark the overlapped
1859                   --  variable as also being volatile to prevent unwanted
1860                   --  optimizations. This is a significant pessimization so
1861                   --  avoid it when there is an offset, i.e. when the object
1862                   --  is composite; they cannot be optimized easily anyway.
1863
1864                   if Present (O_Ent)
1865                     and then Is_Object (O_Ent)
1866                     and then not Off
1867                   then
1868                      Set_Treat_As_Volatile (O_Ent);
1869                   end if;
1870
1871                   --  Legality checks on the address clause for initialized
1872                   --  objects is deferred until the freeze point, because
1873                   --  a subsequent pragma might indicate that the object is
1874                   --  imported and thus not initialized.
1875
1876                   Set_Has_Delayed_Freeze (U_Ent);
1877
1878                   --  If an initialization call has been generated for this
1879                   --  object, it needs to be deferred to after the freeze node
1880                   --  we have just now added, otherwise GIGI will see a
1881                   --  reference to the variable (as actual to the IP call)
1882                   --  before its definition.
1883
1884                   declare
1885                      Init_Call : constant Node_Id := Find_Init_Call (U_Ent, N);
1886                   begin
1887                      if Present (Init_Call) then
1888                         Remove (Init_Call);
1889                         Append_Freeze_Action (U_Ent, Init_Call);
1890                      end if;
1891                   end;
1892
1893                   if Is_Exported (U_Ent) then
1894                      Error_Msg_N
1895                        ("& cannot be exported if an address clause is given",
1896                         Nam);
1897                      Error_Msg_N
1898                        ("\define and export a variable " &
1899                         "that holds its address instead",
1900                         Nam);
1901                   end if;
1902
1903                   --  Entity has delayed freeze, so we will generate an
1904                   --  alignment check at the freeze point unless suppressed.
1905
1906                   if not Range_Checks_Suppressed (U_Ent)
1907                     and then not Alignment_Checks_Suppressed (U_Ent)
1908                   then
1909                      Set_Check_Address_Alignment (N);
1910                   end if;
1911
1912                   --  Kill the size check code, since we are not allocating
1913                   --  the variable, it is somewhere else.
1914
1915                   Kill_Size_Check_Code (U_Ent);
1916
1917                   --  If the address clause is of the form:
1918
1919                   --    for Y'Address use X'Address
1920
1921                   --  or
1922
1923                   --    Const : constant Address := X'Address;
1924                   --    ...
1925                   --    for Y'Address use Const;
1926
1927                   --  then we make an entry in the table for checking the size
1928                   --  and alignment of the overlaying variable. We defer this
1929                   --  check till after code generation to take full advantage
1930                   --  of the annotation done by the back end. This entry is
1931                   --  only made if the address clause comes from source.
1932
1933                   --  If the entity has a generic type, the check will be
1934                   --  performed in the instance if the actual type justifies
1935                   --  it, and we do not insert the clause in the table to
1936                   --  prevent spurious warnings.
1937
1938                   if Address_Clause_Overlay_Warnings
1939                     and then Comes_From_Source (N)
1940                     and then Present (O_Ent)
1941                     and then Is_Object (O_Ent)
1942                   then
1943                      if not Is_Generic_Type (Etype (U_Ent)) then
1944                         Address_Clause_Checks.Append ((N, U_Ent, O_Ent, Off));
1945                      end if;
1946
1947                      --  If variable overlays a constant view, and we are
1948                      --  warning on overlays, then mark the variable as
1949                      --  overlaying a constant (we will give warnings later
1950                      --  if this variable is assigned).
1951
1952                      if Is_Constant_Object (O_Ent)
1953                        and then Ekind (U_Ent) = E_Variable
1954                      then
1955                         Set_Overlays_Constant (U_Ent);
1956                      end if;
1957                   end if;
1958                end;
1959
1960             --  Not a valid entity for an address clause
1961
1962             else
1963                Error_Msg_N ("address cannot be given for &", Nam);
1964             end if;
1965          end Address;
1966
1967          ---------------
1968          -- Alignment --
1969          ---------------
1970
1971          --  Alignment attribute definition clause
1972
1973          when Attribute_Alignment => Alignment : declare
1974             Align : constant Uint := Get_Alignment_Value (Expr);
1975
1976          begin
1977             FOnly := True;
1978
1979             if not Is_Type (U_Ent)
1980               and then Ekind (U_Ent) /= E_Variable
1981               and then Ekind (U_Ent) /= E_Constant
1982             then
1983                Error_Msg_N ("alignment cannot be given for &", Nam);
1984
1985             elsif Duplicate_Clause then
1986                null;
1987
1988             elsif Align /= No_Uint then
1989                Set_Has_Alignment_Clause (U_Ent);
1990                Set_Alignment            (U_Ent, Align);
1991
1992                --  For an array type, U_Ent is the first subtype. In that case,
1993                --  also set the alignment of the anonymous base type so that
1994                --  other subtypes (such as the itypes for aggregates of the
1995                --  type) also receive the expected alignment.
1996
1997                if Is_Array_Type (U_Ent) then
1998                   Set_Alignment (Base_Type (U_Ent), Align);
1999                end if;
2000             end if;
2001          end Alignment;
2002
2003          ---------------
2004          -- Bit_Order --
2005          ---------------
2006
2007          --  Bit_Order attribute definition clause
2008
2009          when Attribute_Bit_Order => Bit_Order : declare
2010          begin
2011             if not Is_Record_Type (U_Ent) then
2012                Error_Msg_N
2013                  ("Bit_Order can only be defined for record type", Nam);
2014
2015             elsif Duplicate_Clause then
2016                null;
2017
2018             else
2019                Analyze_And_Resolve (Expr, RTE (RE_Bit_Order));
2020
2021                if Etype (Expr) = Any_Type then
2022                   return;
2023
2024                elsif not Is_Static_Expression (Expr) then
2025                   Flag_Non_Static_Expr
2026                     ("Bit_Order requires static expression!", Expr);
2027
2028                else
2029                   if (Expr_Value (Expr) = 0) /= Bytes_Big_Endian then
2030                      Set_Reverse_Bit_Order (U_Ent, True);
2031                   end if;
2032                end if;
2033             end if;
2034          end Bit_Order;
2035
2036          --------------------
2037          -- Component_Size --
2038          --------------------
2039
2040          --  Component_Size attribute definition clause
2041
2042          when Attribute_Component_Size => Component_Size_Case : declare
2043             Csize    : constant Uint := Static_Integer (Expr);
2044             Ctyp     : Entity_Id;
2045             Btype    : Entity_Id;
2046             Biased   : Boolean;
2047             New_Ctyp : Entity_Id;
2048             Decl     : Node_Id;
2049
2050          begin
2051             if not Is_Array_Type (U_Ent) then
2052                Error_Msg_N ("component size requires array type", Nam);
2053                return;
2054             end if;
2055
2056             Btype := Base_Type (U_Ent);
2057             Ctyp := Component_Type (Btype);
2058
2059             if Duplicate_Clause then
2060                null;
2061
2062             elsif Rep_Item_Too_Early (Btype, N) then
2063                null;
2064
2065             elsif Csize /= No_Uint then
2066                Check_Size (Expr, Ctyp, Csize, Biased);
2067
2068                --  For the biased case, build a declaration for a subtype that
2069                --  will be used to represent the biased subtype that reflects
2070                --  the biased representation of components. We need the subtype
2071                --  to get proper conversions on referencing elements of the
2072                --  array. Note: component size clauses are ignored in VM mode.
2073
2074                if VM_Target = No_VM then
2075                   if Biased then
2076                      New_Ctyp :=
2077                        Make_Defining_Identifier (Loc,
2078                          Chars =>
2079                            New_External_Name (Chars (U_Ent), 'C', 0, 'T'));
2080
2081                      Decl :=
2082                        Make_Subtype_Declaration (Loc,
2083                          Defining_Identifier => New_Ctyp,
2084                          Subtype_Indication  =>
2085                            New_Occurrence_Of (Component_Type (Btype), Loc));
2086
2087                      Set_Parent (Decl, N);
2088                      Analyze (Decl, Suppress => All_Checks);
2089
2090                      Set_Has_Delayed_Freeze        (New_Ctyp, False);
2091                      Set_Esize                     (New_Ctyp, Csize);
2092                      Set_RM_Size                   (New_Ctyp, Csize);
2093                      Init_Alignment                (New_Ctyp);
2094                      Set_Is_Itype                  (New_Ctyp, True);
2095                      Set_Associated_Node_For_Itype (New_Ctyp, U_Ent);
2096
2097                      Set_Component_Type (Btype, New_Ctyp);
2098                      Set_Biased (New_Ctyp, N, "component size clause");
2099                   end if;
2100
2101                   Set_Component_Size (Btype, Csize);
2102
2103                --  For VM case, we ignore component size clauses
2104
2105                else
2106                   --  Give a warning unless we are in GNAT mode, in which case
2107                   --  the warning is suppressed since it is not useful.
2108
2109                   if not GNAT_Mode then
2110                      Error_Msg_N
2111                        ("?component size ignored in this configuration", N);
2112                   end if;
2113                end if;
2114
2115                --  Deal with warning on overridden size
2116
2117                if Warn_On_Overridden_Size
2118                  and then Has_Size_Clause (Ctyp)
2119                  and then RM_Size (Ctyp) /= Csize
2120                then
2121                   Error_Msg_NE
2122                     ("?component size overrides size clause for&",
2123                      N, Ctyp);
2124                end if;
2125
2126                Set_Has_Component_Size_Clause (Btype, True);
2127                Set_Has_Non_Standard_Rep (Btype, True);
2128             end if;
2129          end Component_Size_Case;
2130
2131          ------------------
2132          -- External_Tag --
2133          ------------------
2134
2135          when Attribute_External_Tag => External_Tag :
2136          begin
2137             if not Is_Tagged_Type (U_Ent) then
2138                Error_Msg_N ("should be a tagged type", Nam);
2139             end if;
2140
2141             if Duplicate_Clause then
2142                null;
2143
2144             else
2145                Analyze_And_Resolve (Expr, Standard_String);
2146
2147                if not Is_Static_Expression (Expr) then
2148                   Flag_Non_Static_Expr
2149                     ("static string required for tag name!", Nam);
2150                end if;
2151
2152                if VM_Target = No_VM then
2153                   Set_Has_External_Tag_Rep_Clause (U_Ent);
2154                else
2155                   Error_Msg_Name_1 := Attr;
2156                   Error_Msg_N
2157                     ("% attribute unsupported in this configuration", Nam);
2158                end if;
2159
2160                if not Is_Library_Level_Entity (U_Ent) then
2161                   Error_Msg_NE
2162                     ("?non-unique external tag supplied for &", N, U_Ent);
2163                   Error_Msg_N
2164                     ("?\same external tag applies to all subprogram calls", N);
2165                   Error_Msg_N
2166                     ("?\corresponding internal tag cannot be obtained", N);
2167                end if;
2168             end if;
2169          end External_Tag;
2170
2171          -----------
2172          -- Input --
2173          -----------
2174
2175          when Attribute_Input =>
2176             Analyze_Stream_TSS_Definition (TSS_Stream_Input);
2177             Set_Has_Specified_Stream_Input (Ent);
2178
2179          -------------------
2180          -- Machine_Radix --
2181          -------------------
2182
2183          --  Machine radix attribute definition clause
2184
2185          when Attribute_Machine_Radix => Machine_Radix : declare
2186             Radix : constant Uint := Static_Integer (Expr);
2187
2188          begin
2189             if not Is_Decimal_Fixed_Point_Type (U_Ent) then
2190                Error_Msg_N ("decimal fixed-point type expected for &", Nam);
2191
2192             elsif Duplicate_Clause then
2193                null;
2194
2195             elsif Radix /= No_Uint then
2196                Set_Has_Machine_Radix_Clause (U_Ent);
2197                Set_Has_Non_Standard_Rep (Base_Type (U_Ent));
2198
2199                if Radix = 2 then
2200                   null;
2201                elsif Radix = 10 then
2202                   Set_Machine_Radix_10 (U_Ent);
2203                else
2204                   Error_Msg_N ("machine radix value must be 2 or 10", Expr);
2205                end if;
2206             end if;
2207          end Machine_Radix;
2208
2209          -----------------
2210          -- Object_Size --
2211          -----------------
2212
2213          --  Object_Size attribute definition clause
2214
2215          when Attribute_Object_Size => Object_Size : declare
2216             Size : constant Uint := Static_Integer (Expr);
2217
2218             Biased : Boolean;
2219             pragma Warnings (Off, Biased);
2220
2221          begin
2222             if not Is_Type (U_Ent) then
2223                Error_Msg_N ("Object_Size cannot be given for &", Nam);
2224
2225             elsif Duplicate_Clause then
2226                null;
2227
2228             else
2229                Check_Size (Expr, U_Ent, Size, Biased);
2230
2231                if Size /= 8
2232                     and then
2233                   Size /= 16
2234                     and then
2235                   Size /= 32
2236                     and then
2237                   UI_Mod (Size, 64) /= 0
2238                then
2239                   Error_Msg_N
2240                     ("Object_Size must be 8, 16, 32, or multiple of 64",
2241                      Expr);
2242                end if;
2243
2244                Set_Esize (U_Ent, Size);
2245                Set_Has_Object_Size_Clause (U_Ent);
2246                Alignment_Check_For_Esize_Change (U_Ent);
2247             end if;
2248          end Object_Size;
2249
2250          ------------
2251          -- Output --
2252          ------------
2253
2254          when Attribute_Output =>
2255             Analyze_Stream_TSS_Definition (TSS_Stream_Output);
2256             Set_Has_Specified_Stream_Output (Ent);
2257
2258          ----------
2259          -- Read --
2260          ----------
2261
2262          when Attribute_Read =>
2263             Analyze_Stream_TSS_Definition (TSS_Stream_Read);
2264             Set_Has_Specified_Stream_Read (Ent);
2265
2266          ----------
2267          -- Size --
2268          ----------
2269
2270          --  Size attribute definition clause
2271
2272          when Attribute_Size => Size : declare
2273             Size   : constant Uint := Static_Integer (Expr);
2274             Etyp   : Entity_Id;
2275             Biased : Boolean;
2276
2277          begin
2278             FOnly := True;
2279
2280             if Duplicate_Clause then
2281                null;
2282
2283             elsif not Is_Type (U_Ent)
2284               and then Ekind (U_Ent) /= E_Variable
2285               and then Ekind (U_Ent) /= E_Constant
2286             then
2287                Error_Msg_N ("size cannot be given for &", Nam);
2288
2289             elsif Is_Array_Type (U_Ent)
2290               and then not Is_Constrained (U_Ent)
2291             then
2292                Error_Msg_N
2293                  ("size cannot be given for unconstrained array", Nam);
2294
2295             elsif Size /= No_Uint then
2296                if VM_Target /= No_VM and then not GNAT_Mode then
2297
2298                   --  Size clause is not handled properly on VM targets.
2299                   --  Display a warning unless we are in GNAT mode, in which
2300                   --  case this is useless.
2301
2302                   Error_Msg_N
2303                     ("?size clauses are ignored in this configuration", N);
2304                end if;
2305
2306                if Is_Type (U_Ent) then
2307                   Etyp := U_Ent;
2308                else
2309                   Etyp := Etype (U_Ent);
2310                end if;
2311
2312                --  Check size, note that Gigi is in charge of checking that the
2313                --  size of an array or record type is OK. Also we do not check
2314                --  the size in the ordinary fixed-point case, since it is too
2315                --  early to do so (there may be subsequent small clause that
2316                --  affects the size). We can check the size if a small clause
2317                --  has already been given.
2318
2319                if not Is_Ordinary_Fixed_Point_Type (U_Ent)
2320                  or else Has_Small_Clause (U_Ent)
2321                then
2322                   Check_Size (Expr, Etyp, Size, Biased);
2323                   Set_Biased (U_Ent, N, "size clause", Biased);
2324                end if;
2325
2326                --  For types set RM_Size and Esize if possible
2327
2328                if Is_Type (U_Ent) then
2329                   Set_RM_Size (U_Ent, Size);
2330
2331                   --  For scalar types, increase Object_Size to power of 2, but
2332                   --  not less than a storage unit in any case (i.e., normally
2333                   --  this means it will be byte addressable).
2334
2335                   if Is_Scalar_Type (U_Ent) then
2336                      if Size <= System_Storage_Unit then
2337                         Init_Esize (U_Ent, System_Storage_Unit);
2338                      elsif Size <= 16 then
2339                         Init_Esize (U_Ent, 16);
2340                      elsif Size <= 32 then
2341                         Init_Esize (U_Ent, 32);
2342                      else
2343                         Set_Esize  (U_Ent, (Size + 63) / 64 * 64);
2344                      end if;
2345
2346                   --  For all other types, object size = value size. The
2347                   --  backend will adjust as needed.
2348
2349                   else
2350                      Set_Esize (U_Ent, Size);
2351                   end if;
2352
2353                   Alignment_Check_For_Esize_Change (U_Ent);
2354
2355                --  For objects, set Esize only
2356
2357                else
2358                   if Is_Elementary_Type (Etyp) then
2359                      if Size /= System_Storage_Unit
2360                           and then
2361                         Size /= System_Storage_Unit * 2
2362                           and then
2363                         Size /= System_Storage_Unit * 4
2364                            and then
2365                         Size /= System_Storage_Unit * 8
2366                      then
2367                         Error_Msg_Uint_1 := UI_From_Int (System_Storage_Unit);
2368                         Error_Msg_Uint_2 := Error_Msg_Uint_1 * 8;
2369                         Error_Msg_N
2370                           ("size for primitive object must be a power of 2"
2371                             & " in the range ^-^", N);
2372                      end if;
2373                   end if;
2374
2375                   Set_Esize (U_Ent, Size);
2376                end if;
2377
2378                Set_Has_Size_Clause (U_Ent);
2379             end if;
2380          end Size;
2381
2382          -----------
2383          -- Small --
2384          -----------
2385
2386          --  Small attribute definition clause
2387
2388          when Attribute_Small => Small : declare
2389             Implicit_Base : constant Entity_Id := Base_Type (U_Ent);
2390             Small         : Ureal;
2391
2392          begin
2393             Analyze_And_Resolve (Expr, Any_Real);
2394
2395             if Etype (Expr) = Any_Type then
2396                return;
2397
2398             elsif not Is_Static_Expression (Expr) then
2399                Flag_Non_Static_Expr
2400                  ("small requires static expression!", Expr);
2401                return;
2402
2403             else
2404                Small := Expr_Value_R (Expr);
2405
2406                if Small <= Ureal_0 then
2407                   Error_Msg_N ("small value must be greater than zero", Expr);
2408                   return;
2409                end if;
2410
2411             end if;
2412
2413             if not Is_Ordinary_Fixed_Point_Type (U_Ent) then
2414                Error_Msg_N
2415                  ("small requires an ordinary fixed point type", Nam);
2416
2417             elsif Has_Small_Clause (U_Ent) then
2418                Error_Msg_N ("small already given for &", Nam);
2419
2420             elsif Small > Delta_Value (U_Ent) then
2421                Error_Msg_N
2422                  ("small value must not be greater then delta value", Nam);
2423
2424             else
2425                Set_Small_Value (U_Ent, Small);
2426                Set_Small_Value (Implicit_Base, Small);
2427                Set_Has_Small_Clause (U_Ent);
2428                Set_Has_Small_Clause (Implicit_Base);
2429                Set_Has_Non_Standard_Rep (Implicit_Base);
2430             end if;
2431          end Small;
2432
2433          ------------------
2434          -- Storage_Pool --
2435          ------------------
2436
2437          --  Storage_Pool attribute definition clause
2438
2439          when Attribute_Storage_Pool => Storage_Pool : declare
2440             Pool : Entity_Id;
2441             T    : Entity_Id;
2442
2443          begin
2444             if Ekind (U_Ent) = E_Access_Subprogram_Type then
2445                Error_Msg_N
2446                  ("storage pool cannot be given for access-to-subprogram type",
2447                   Nam);
2448                return;
2449
2450             elsif not
2451               Ekind_In (U_Ent, E_Access_Type, E_General_Access_Type)
2452             then
2453                Error_Msg_N
2454                  ("storage pool can only be given for access types", Nam);
2455                return;
2456
2457             elsif Is_Derived_Type (U_Ent) then
2458                Error_Msg_N
2459                  ("storage pool cannot be given for a derived access type",
2460                   Nam);
2461
2462             elsif Duplicate_Clause then
2463                return;
2464
2465             elsif Present (Associated_Storage_Pool (U_Ent)) then
2466                Error_Msg_N ("storage pool already given for &", Nam);
2467                return;
2468             end if;
2469
2470             Analyze_And_Resolve
2471               (Expr, Class_Wide_Type (RTE (RE_Root_Storage_Pool)));
2472
2473             if not Denotes_Variable (Expr) then
2474                Error_Msg_N ("storage pool must be a variable", Expr);
2475                return;
2476             end if;
2477
2478             if Nkind (Expr) = N_Type_Conversion then
2479                T := Etype (Expression (Expr));
2480             else
2481                T := Etype (Expr);
2482             end if;
2483
2484             --  The Stack_Bounded_Pool is used internally for implementing
2485             --  access types with a Storage_Size. Since it only work properly
2486             --  when used on one specific type, we need to check that it is not
2487             --  hijacked improperly:
2488
2489             --    type T is access Integer;
2490             --    for T'Storage_Size use n;
2491             --    type Q is access Float;
2492             --    for Q'Storage_Size use T'Storage_Size; -- incorrect
2493
2494             if RTE_Available (RE_Stack_Bounded_Pool)
2495               and then Base_Type (T) = RTE (RE_Stack_Bounded_Pool)
2496             then
2497                Error_Msg_N ("non-shareable internal Pool", Expr);
2498                return;
2499             end if;
2500
2501             --  If the argument is a name that is not an entity name, then
2502             --  we construct a renaming operation to define an entity of
2503             --  type storage pool.
2504
2505             if not Is_Entity_Name (Expr)
2506               and then Is_Object_Reference (Expr)
2507             then
2508                Pool := Make_Temporary (Loc, 'P', Expr);
2509
2510                declare
2511                   Rnode : constant Node_Id :=
2512                             Make_Object_Renaming_Declaration (Loc,
2513                               Defining_Identifier => Pool,
2514                               Subtype_Mark        =>
2515                                 New_Occurrence_Of (Etype (Expr), Loc),
2516                               Name                => Expr);
2517
2518                begin
2519                   Insert_Before (N, Rnode);
2520                   Analyze (Rnode);
2521                   Set_Associated_Storage_Pool (U_Ent, Pool);
2522                end;
2523
2524             elsif Is_Entity_Name (Expr) then
2525                Pool := Entity (Expr);
2526
2527                --  If pool is a renamed object, get original one. This can
2528                --  happen with an explicit renaming, and within instances.
2529
2530                while Present (Renamed_Object (Pool))
2531                  and then Is_Entity_Name (Renamed_Object (Pool))
2532                loop
2533                   Pool := Entity (Renamed_Object (Pool));
2534                end loop;
2535
2536                if Present (Renamed_Object (Pool))
2537                  and then Nkind (Renamed_Object (Pool)) = N_Type_Conversion
2538                  and then Is_Entity_Name (Expression (Renamed_Object (Pool)))
2539                then
2540                   Pool := Entity (Expression (Renamed_Object (Pool)));
2541                end if;
2542
2543                Set_Associated_Storage_Pool (U_Ent, Pool);
2544
2545             elsif Nkind (Expr) = N_Type_Conversion
2546               and then Is_Entity_Name (Expression (Expr))
2547               and then Nkind (Original_Node (Expr)) = N_Attribute_Reference
2548             then
2549                Pool := Entity (Expression (Expr));
2550                Set_Associated_Storage_Pool (U_Ent, Pool);
2551
2552             else
2553                Error_Msg_N ("incorrect reference to a Storage Pool", Expr);
2554                return;
2555             end if;
2556          end Storage_Pool;
2557
2558          ------------------
2559          -- Storage_Size --
2560          ------------------
2561
2562          --  Storage_Size attribute definition clause
2563
2564          when Attribute_Storage_Size => Storage_Size : declare
2565             Btype : constant Entity_Id := Base_Type (U_Ent);
2566             Sprag : Node_Id;
2567
2568          begin
2569             if Is_Task_Type (U_Ent) then
2570                Check_Restriction (No_Obsolescent_Features, N);
2571
2572                if Warn_On_Obsolescent_Feature then
2573                   Error_Msg_N
2574                     ("storage size clause for task is an " &
2575                      "obsolescent feature (RM J.9)?", N);
2576                   Error_Msg_N ("\use Storage_Size pragma instead?", N);
2577                end if;
2578
2579                FOnly := True;
2580             end if;
2581
2582             if not Is_Access_Type (U_Ent)
2583               and then Ekind (U_Ent) /= E_Task_Type
2584             then
2585                Error_Msg_N ("storage size cannot be given for &", Nam);
2586
2587             elsif Is_Access_Type (U_Ent) and Is_Derived_Type (U_Ent) then
2588                Error_Msg_N
2589                  ("storage size cannot be given for a derived access type",
2590                   Nam);
2591
2592             elsif Duplicate_Clause then
2593                null;
2594
2595             else
2596                Analyze_And_Resolve (Expr, Any_Integer);
2597
2598                if Is_Access_Type (U_Ent) then
2599                   if Present (Associated_Storage_Pool (U_Ent)) then
2600                      Error_Msg_N ("storage pool already given for &", Nam);
2601                      return;
2602                   end if;
2603
2604                   if Is_OK_Static_Expression (Expr)
2605                     and then Expr_Value (Expr) = 0
2606                   then
2607                      Set_No_Pool_Assigned (Btype);
2608                   end if;
2609
2610                else -- Is_Task_Type (U_Ent)
2611                   Sprag := Get_Rep_Pragma (Btype, Name_Storage_Size);
2612
2613                   if Present (Sprag) then
2614                      Error_Msg_Sloc := Sloc (Sprag);
2615                      Error_Msg_N
2616                        ("Storage_Size already specified#", Nam);
2617                      return;
2618                   end if;
2619                end if;
2620
2621                Set_Has_Storage_Size_Clause (Btype);
2622             end if;
2623          end Storage_Size;
2624
2625          -----------------
2626          -- Stream_Size --
2627          -----------------
2628
2629          when Attribute_Stream_Size => Stream_Size : declare
2630             Size : constant Uint := Static_Integer (Expr);
2631
2632          begin
2633             if Ada_Version <= Ada_95 then
2634                Check_Restriction (No_Implementation_Attributes, N);
2635             end if;
2636
2637             if Duplicate_Clause then
2638                null;
2639
2640             elsif Is_Elementary_Type (U_Ent) then
2641                if Size /= System_Storage_Unit
2642                     and then
2643                   Size /= System_Storage_Unit * 2
2644                     and then
2645                   Size /= System_Storage_Unit * 4
2646                      and then
2647                   Size /= System_Storage_Unit * 8
2648                then
2649                   Error_Msg_Uint_1 := UI_From_Int (System_Storage_Unit);
2650                   Error_Msg_N
2651                     ("stream size for elementary type must be a"
2652                        & " power of 2 and at least ^", N);
2653
2654                elsif RM_Size (U_Ent) > Size then
2655                   Error_Msg_Uint_1 := RM_Size (U_Ent);
2656                   Error_Msg_N
2657                     ("stream size for elementary type must be a"
2658                        & " power of 2 and at least ^", N);
2659                end if;
2660
2661                Set_Has_Stream_Size_Clause (U_Ent);
2662
2663             else
2664                Error_Msg_N ("Stream_Size cannot be given for &", Nam);
2665             end if;
2666          end Stream_Size;
2667
2668          ----------------
2669          -- Value_Size --
2670          ----------------
2671
2672          --  Value_Size attribute definition clause
2673
2674          when Attribute_Value_Size => Value_Size : declare
2675             Size   : constant Uint := Static_Integer (Expr);
2676             Biased : Boolean;
2677
2678          begin
2679             if not Is_Type (U_Ent) then
2680                Error_Msg_N ("Value_Size cannot be given for &", Nam);
2681
2682             elsif Duplicate_Clause then
2683                null;
2684
2685             elsif Is_Array_Type (U_Ent)
2686               and then not Is_Constrained (U_Ent)
2687             then
2688                Error_Msg_N
2689                  ("Value_Size cannot be given for unconstrained array", Nam);
2690
2691             else
2692                if Is_Elementary_Type (U_Ent) then
2693                   Check_Size (Expr, U_Ent, Size, Biased);
2694                   Set_Biased (U_Ent, N, "value size clause", Biased);
2695                end if;
2696
2697                Set_RM_Size (U_Ent, Size);
2698             end if;
2699          end Value_Size;
2700
2701          -----------
2702          -- Write --
2703          -----------
2704
2705          when Attribute_Write =>
2706             Analyze_Stream_TSS_Definition (TSS_Stream_Write);
2707             Set_Has_Specified_Stream_Write (Ent);
2708
2709          --  All other attributes cannot be set
2710
2711          when others =>
2712             Error_Msg_N
2713               ("attribute& cannot be set with definition clause", N);
2714       end case;
2715
2716       --  The test for the type being frozen must be performed after any
2717       --  expression the clause has been analyzed since the expression itself
2718       --  might cause freezing that makes the clause illegal.
2719
2720       if Rep_Item_Too_Late (U_Ent, N, FOnly) then
2721          return;
2722       end if;
2723    end Analyze_Attribute_Definition_Clause;
2724
2725    ----------------------------
2726    -- Analyze_Code_Statement --
2727    ----------------------------
2728
2729    procedure Analyze_Code_Statement (N : Node_Id) is
2730       HSS   : constant Node_Id   := Parent (N);
2731       SBody : constant Node_Id   := Parent (HSS);
2732       Subp  : constant Entity_Id := Current_Scope;
2733       Stmt  : Node_Id;
2734       Decl  : Node_Id;
2735       StmtO : Node_Id;
2736       DeclO : Node_Id;
2737
2738    begin
2739       --  Analyze and check we get right type, note that this implements the
2740       --  requirement (RM 13.8(1)) that Machine_Code be with'ed, since that
2741       --  is the only way that Asm_Insn could possibly be visible.
2742
2743       Analyze_And_Resolve (Expression (N));
2744
2745       if Etype (Expression (N)) = Any_Type then
2746          return;
2747       elsif Etype (Expression (N)) /= RTE (RE_Asm_Insn) then
2748          Error_Msg_N ("incorrect type for code statement", N);
2749          return;
2750       end if;
2751
2752       Check_Code_Statement (N);
2753
2754       --  Make sure we appear in the handled statement sequence of a
2755       --  subprogram (RM 13.8(3)).
2756
2757       if Nkind (HSS) /= N_Handled_Sequence_Of_Statements
2758         or else Nkind (SBody) /= N_Subprogram_Body
2759       then
2760          Error_Msg_N
2761            ("code statement can only appear in body of subprogram", N);
2762          return;
2763       end if;
2764
2765       --  Do remaining checks (RM 13.8(3)) if not already done
2766
2767       if not Is_Machine_Code_Subprogram (Subp) then
2768          Set_Is_Machine_Code_Subprogram (Subp);
2769
2770          --  No exception handlers allowed
2771
2772          if Present (Exception_Handlers (HSS)) then
2773             Error_Msg_N
2774               ("exception handlers not permitted in machine code subprogram",
2775                First (Exception_Handlers (HSS)));
2776          end if;
2777
2778          --  No declarations other than use clauses and pragmas (we allow
2779          --  certain internally generated declarations as well).
2780
2781          Decl := First (Declarations (SBody));
2782          while Present (Decl) loop
2783             DeclO := Original_Node (Decl);
2784             if Comes_From_Source (DeclO)
2785               and not Nkind_In (DeclO, N_Pragma,
2786                                        N_Use_Package_Clause,
2787                                        N_Use_Type_Clause,
2788                                        N_Implicit_Label_Declaration)
2789             then
2790                Error_Msg_N
2791                  ("this declaration not allowed in machine code subprogram",
2792                   DeclO);
2793             end if;
2794
2795             Next (Decl);
2796          end loop;
2797
2798          --  No statements other than code statements, pragmas, and labels.
2799          --  Again we allow certain internally generated statements.
2800
2801          Stmt := First (Statements (HSS));
2802          while Present (Stmt) loop
2803             StmtO := Original_Node (Stmt);
2804             if Comes_From_Source (StmtO)
2805               and then not Nkind_In (StmtO, N_Pragma,
2806                                             N_Label,
2807                                             N_Code_Statement)
2808             then
2809                Error_Msg_N
2810                  ("this statement is not allowed in machine code subprogram",
2811                   StmtO);
2812             end if;
2813
2814             Next (Stmt);
2815          end loop;
2816       end if;
2817    end Analyze_Code_Statement;
2818
2819    -----------------------------------------------
2820    -- Analyze_Enumeration_Representation_Clause --
2821    -----------------------------------------------
2822
2823    procedure Analyze_Enumeration_Representation_Clause (N : Node_Id) is
2824       Ident    : constant Node_Id    := Identifier (N);
2825       Aggr     : constant Node_Id    := Array_Aggregate (N);
2826       Enumtype : Entity_Id;
2827       Elit     : Entity_Id;
2828       Expr     : Node_Id;
2829       Assoc    : Node_Id;
2830       Choice   : Node_Id;
2831       Val      : Uint;
2832       Err      : Boolean := False;
2833
2834       Lo : constant Uint := Expr_Value (Type_Low_Bound (Universal_Integer));
2835       Hi : constant Uint := Expr_Value (Type_High_Bound (Universal_Integer));
2836       --  Allowed range of universal integer (= allowed range of enum lit vals)
2837
2838       Min : Uint;
2839       Max : Uint;
2840       --  Minimum and maximum values of entries
2841
2842       Max_Node : Node_Id;
2843       --  Pointer to node for literal providing max value
2844
2845    begin
2846       if Ignore_Rep_Clauses then
2847          return;
2848       end if;
2849
2850       --  First some basic error checks
2851
2852       Find_Type (Ident);
2853       Enumtype := Entity (Ident);
2854
2855       if Enumtype = Any_Type
2856         or else Rep_Item_Too_Early (Enumtype, N)
2857       then
2858          return;
2859       else
2860          Enumtype := Underlying_Type (Enumtype);
2861       end if;
2862
2863       if not Is_Enumeration_Type (Enumtype) then
2864          Error_Msg_NE
2865            ("enumeration type required, found}",
2866             Ident, First_Subtype (Enumtype));
2867          return;
2868       end if;
2869
2870       --  Ignore rep clause on generic actual type. This will already have
2871       --  been flagged on the template as an error, and this is the safest
2872       --  way to ensure we don't get a junk cascaded message in the instance.
2873
2874       if Is_Generic_Actual_Type (Enumtype) then
2875          return;
2876
2877       --  Type must be in current scope
2878
2879       elsif Scope (Enumtype) /= Current_Scope then
2880          Error_Msg_N ("type must be declared in this scope", Ident);
2881          return;
2882
2883       --  Type must be a first subtype
2884
2885       elsif not Is_First_Subtype (Enumtype) then
2886          Error_Msg_N ("cannot give enumeration rep clause for subtype", N);
2887          return;
2888
2889       --  Ignore duplicate rep clause
2890
2891       elsif Has_Enumeration_Rep_Clause (Enumtype) then
2892          Error_Msg_N ("duplicate enumeration rep clause ignored", N);
2893          return;
2894
2895       --  Don't allow rep clause for standard [wide_[wide_]]character
2896
2897       elsif Is_Standard_Character_Type (Enumtype) then
2898          Error_Msg_N ("enumeration rep clause not allowed for this type", N);
2899          return;
2900
2901       --  Check that the expression is a proper aggregate (no parentheses)
2902
2903       elsif Paren_Count (Aggr) /= 0 then
2904          Error_Msg
2905            ("extra parentheses surrounding aggregate not allowed",
2906             First_Sloc (Aggr));
2907          return;
2908
2909       --  All tests passed, so set rep clause in place
2910
2911       else
2912          Set_Has_Enumeration_Rep_Clause (Enumtype);
2913          Set_Has_Enumeration_Rep_Clause (Base_Type (Enumtype));
2914       end if;
2915
2916       --  Now we process the aggregate. Note that we don't use the normal
2917       --  aggregate code for this purpose, because we don't want any of the
2918       --  normal expansion activities, and a number of special semantic
2919       --  rules apply (including the component type being any integer type)
2920
2921       Elit := First_Literal (Enumtype);
2922
2923       --  First the positional entries if any
2924
2925       if Present (Expressions (Aggr)) then
2926          Expr := First (Expressions (Aggr));
2927          while Present (Expr) loop
2928             if No (Elit) then
2929                Error_Msg_N ("too many entries in aggregate", Expr);
2930                return;
2931             end if;
2932
2933             Val := Static_Integer (Expr);
2934
2935             --  Err signals that we found some incorrect entries processing
2936             --  the list. The final checks for completeness and ordering are
2937             --  skipped in this case.
2938
2939             if Val = No_Uint then
2940                Err := True;
2941             elsif Val < Lo or else Hi < Val then
2942                Error_Msg_N ("value outside permitted range", Expr);
2943                Err := True;
2944             end if;
2945
2946             Set_Enumeration_Rep (Elit, Val);
2947             Set_Enumeration_Rep_Expr (Elit, Expr);
2948             Next (Expr);
2949             Next (Elit);
2950          end loop;
2951       end if;
2952
2953       --  Now process the named entries if present
2954
2955       if Present (Component_Associations (Aggr)) then
2956          Assoc := First (Component_Associations (Aggr));
2957          while Present (Assoc) loop
2958             Choice := First (Choices (Assoc));
2959
2960             if Present (Next (Choice)) then
2961                Error_Msg_N
2962                  ("multiple choice not allowed here", Next (Choice));
2963                Err := True;
2964             end if;
2965
2966             if Nkind (Choice) = N_Others_Choice then
2967                Error_Msg_N ("others choice not allowed here", Choice);
2968                Err := True;
2969
2970             elsif Nkind (Choice) = N_Range then
2971                --  ??? should allow zero/one element range here
2972                Error_Msg_N ("range not allowed here", Choice);
2973                Err := True;
2974
2975             else
2976                Analyze_And_Resolve (Choice, Enumtype);
2977
2978                if Is_Entity_Name (Choice)
2979                  and then Is_Type (Entity (Choice))
2980                then
2981                   Error_Msg_N ("subtype name not allowed here", Choice);
2982                   Err := True;
2983                   --  ??? should allow static subtype with zero/one entry
2984
2985                elsif Etype (Choice) = Base_Type (Enumtype) then
2986                   if not Is_Static_Expression (Choice) then
2987                      Flag_Non_Static_Expr
2988                        ("non-static expression used for choice!", Choice);
2989                      Err := True;
2990
2991                   else
2992                      Elit := Expr_Value_E (Choice);
2993
2994                      if Present (Enumeration_Rep_Expr (Elit)) then
2995                         Error_Msg_Sloc := Sloc (Enumeration_Rep_Expr (Elit));
2996                         Error_Msg_NE
2997                           ("representation for& previously given#",
2998                            Choice, Elit);
2999                         Err := True;
3000                      end if;
3001
3002                      Set_Enumeration_Rep_Expr (Elit, Expression (Assoc));
3003
3004                      Expr := Expression (Assoc);
3005                      Val := Static_Integer (Expr);
3006
3007                      if Val = No_Uint then
3008                         Err := True;
3009
3010                      elsif Val < Lo or else Hi < Val then
3011                         Error_Msg_N ("value outside permitted range", Expr);
3012                         Err := True;
3013                      end if;
3014
3015                      Set_Enumeration_Rep (Elit, Val);
3016                   end if;
3017                end if;
3018             end if;
3019
3020             Next (Assoc);
3021          end loop;
3022       end if;
3023
3024       --  Aggregate is fully processed. Now we check that a full set of
3025       --  representations was given, and that they are in range and in order.
3026       --  These checks are only done if no other errors occurred.
3027
3028       if not Err then
3029          Min  := No_Uint;
3030          Max  := No_Uint;
3031
3032          Elit := First_Literal (Enumtype);
3033          while Present (Elit) loop
3034             if No (Enumeration_Rep_Expr (Elit)) then
3035                Error_Msg_NE ("missing representation for&!", N, Elit);
3036
3037             else
3038                Val := Enumeration_Rep (Elit);
3039
3040                if Min = No_Uint then
3041                   Min := Val;
3042                end if;
3043
3044                if Val /= No_Uint then
3045                   if Max /= No_Uint and then Val <= Max then
3046                      Error_Msg_NE
3047                        ("enumeration value for& not ordered!",
3048                         Enumeration_Rep_Expr (Elit), Elit);
3049                   end if;
3050
3051                   Max_Node := Enumeration_Rep_Expr (Elit);
3052                   Max := Val;
3053                end if;
3054
3055                --  If there is at least one literal whose representation is not
3056                --  equal to the Pos value, then note that this enumeration type
3057                --  has a non-standard representation.
3058
3059                if Val /= Enumeration_Pos (Elit) then
3060                   Set_Has_Non_Standard_Rep (Base_Type (Enumtype));
3061                end if;
3062             end if;
3063
3064             Next (Elit);
3065          end loop;
3066
3067          --  Now set proper size information
3068
3069          declare
3070             Minsize : Uint := UI_From_Int (Minimum_Size (Enumtype));
3071
3072          begin
3073             if Has_Size_Clause (Enumtype) then
3074
3075                --  All OK, if size is OK now
3076
3077                if RM_Size (Enumtype) >= Minsize then
3078                   null;
3079
3080                else
3081                   --  Try if we can get by with biasing
3082
3083                   Minsize :=
3084                     UI_From_Int (Minimum_Size (Enumtype, Biased => True));
3085
3086                   --  Error message if even biasing does not work
3087
3088                   if RM_Size (Enumtype) < Minsize then
3089                      Error_Msg_Uint_1 := RM_Size (Enumtype);
3090                      Error_Msg_Uint_2 := Max;
3091                      Error_Msg_N
3092                        ("previously given size (^) is too small "
3093                         & "for this value (^)", Max_Node);
3094
3095                   --  If biasing worked, indicate that we now have biased rep
3096
3097                   else
3098                      Set_Biased
3099                        (Enumtype, Size_Clause (Enumtype), "size clause");
3100                   end if;
3101                end if;
3102
3103             else
3104                Set_RM_Size    (Enumtype, Minsize);
3105                Set_Enum_Esize (Enumtype);
3106             end if;
3107
3108             Set_RM_Size   (Base_Type (Enumtype), RM_Size   (Enumtype));
3109             Set_Esize     (Base_Type (Enumtype), Esize     (Enumtype));
3110             Set_Alignment (Base_Type (Enumtype), Alignment (Enumtype));
3111          end;
3112       end if;
3113
3114       --  We repeat the too late test in case it froze itself!
3115
3116       if Rep_Item_Too_Late (Enumtype, N) then
3117          null;
3118       end if;
3119    end Analyze_Enumeration_Representation_Clause;
3120
3121    ----------------------------
3122    -- Analyze_Free_Statement --
3123    ----------------------------
3124
3125    procedure Analyze_Free_Statement (N : Node_Id) is
3126    begin
3127       Analyze (Expression (N));
3128    end Analyze_Free_Statement;
3129
3130    ---------------------------
3131    -- Analyze_Freeze_Entity --
3132    ---------------------------
3133
3134    procedure Analyze_Freeze_Entity (N : Node_Id) is
3135       E : constant Entity_Id := Entity (N);
3136
3137    begin
3138       --  Remember that we are processing a freezing entity. Required to
3139       --  ensure correct decoration of internal entities associated with
3140       --  interfaces (see New_Overloaded_Entity).
3141
3142       Inside_Freezing_Actions := Inside_Freezing_Actions + 1;
3143
3144       --  For tagged types covering interfaces add internal entities that link
3145       --  the primitives of the interfaces with the primitives that cover them.
3146       --  Note: These entities were originally generated only when generating
3147       --  code because their main purpose was to provide support to initialize
3148       --  the secondary dispatch tables. They are now generated also when
3149       --  compiling with no code generation to provide ASIS the relationship
3150       --  between interface primitives and tagged type primitives. They are
3151       --  also used to locate primitives covering interfaces when processing
3152       --  generics (see Derive_Subprograms).
3153
3154       if Ada_Version >= Ada_2005
3155         and then Ekind (E) = E_Record_Type
3156         and then Is_Tagged_Type (E)
3157         and then not Is_Interface (E)
3158         and then Has_Interfaces (E)
3159       then
3160          --  This would be a good common place to call the routine that checks
3161          --  overriding of interface primitives (and thus factorize calls to
3162          --  Check_Abstract_Overriding located at different contexts in the
3163          --  compiler). However, this is not possible because it causes
3164          --  spurious errors in case of late overriding.
3165
3166          Add_Internal_Interface_Entities (E);
3167       end if;
3168
3169       --  Check CPP types
3170
3171       if Ekind (E) = E_Record_Type
3172         and then Is_CPP_Class (E)
3173         and then Is_Tagged_Type (E)
3174         and then Tagged_Type_Expansion
3175         and then Expander_Active
3176       then
3177          if CPP_Num_Prims (E) = 0 then
3178
3179             --  If the CPP type has user defined components then it must import
3180             --  primitives from C++. This is required because if the C++ class
3181             --  has no primitives then the C++ compiler does not added the _tag
3182             --  component to the type.
3183
3184             pragma Assert (Chars (First_Entity (E)) = Name_uTag);
3185
3186             if First_Entity (E) /= Last_Entity (E) then
3187                Error_Msg_N
3188                  ("?'C'P'P type must import at least one primitive from C++",
3189                   E);
3190             end if;
3191          end if;
3192
3193          --  Check that all its primitives are abstract or imported from C++.
3194          --  Check also availability of the C++ constructor.
3195
3196          declare
3197             Has_Constructors : constant Boolean := Has_CPP_Constructors (E);
3198             Elmt             : Elmt_Id;
3199             Error_Reported   : Boolean := False;
3200             Prim             : Node_Id;
3201
3202          begin
3203             Elmt := First_Elmt (Primitive_Operations (E));
3204             while Present (Elmt) loop
3205                Prim := Node (Elmt);
3206
3207                if Comes_From_Source (Prim) then
3208                   if Is_Abstract_Subprogram (Prim) then
3209                      null;
3210
3211                   elsif not Is_Imported (Prim)
3212                     or else Convention (Prim) /= Convention_CPP
3213                   then
3214                      Error_Msg_N
3215                        ("?primitives of 'C'P'P types must be imported from C++"
3216                         & " or abstract", Prim);
3217
3218                   elsif not Has_Constructors
3219                      and then not Error_Reported
3220                   then
3221                      Error_Msg_Name_1 := Chars (E);
3222                      Error_Msg_N
3223                        ("?'C'P'P constructor required for type %", Prim);
3224                      Error_Reported := True;
3225                   end if;
3226                end if;
3227
3228                Next_Elmt (Elmt);
3229             end loop;
3230          end;
3231       end if;
3232
3233       Inside_Freezing_Actions := Inside_Freezing_Actions - 1;
3234
3235       --  If we have a type with predicates, build predicate function
3236
3237       if Is_Type (E) and then Has_Predicates (E) then
3238          Build_Predicate_Function (E, N);
3239       end if;
3240
3241       --  If type has delayed aspects, this is where we do the preanalysis at
3242       --  the freeze point, as part of the consistent visibility check. Note
3243       --  that this must be done after calling Build_Predicate_Function or
3244       --  Build_Invariant_Procedure since these subprograms fix occurrences of
3245       --  the subtype name in the saved expression so that they will not cause
3246       --  trouble in the preanalysis.
3247
3248       if Has_Delayed_Aspects (E) then
3249          declare
3250             Ritem : Node_Id;
3251
3252          begin
3253             --  Look for aspect specification entries for this entity
3254
3255             Ritem := First_Rep_Item (E);
3256             while Present (Ritem) loop
3257                if Nkind (Ritem) = N_Aspect_Specification
3258                  and then Entity (Ritem) = E
3259                  and then Is_Delayed_Aspect (Ritem)
3260                then
3261                   Check_Aspect_At_Freeze_Point (Ritem);
3262                end if;
3263
3264                Next_Rep_Item (Ritem);
3265             end loop;
3266          end;
3267       end if;
3268    end Analyze_Freeze_Entity;
3269
3270    ------------------------------------------
3271    -- Analyze_Record_Representation_Clause --
3272    ------------------------------------------
3273
3274    --  Note: we check as much as we can here, but we can't do any checks
3275    --  based on the position values (e.g. overlap checks) until freeze time
3276    --  because especially in Ada 2005 (machine scalar mode), the processing
3277    --  for non-standard bit order can substantially change the positions.
3278    --  See procedure Check_Record_Representation_Clause (called from Freeze)
3279    --  for the remainder of this processing.
3280
3281    procedure Analyze_Record_Representation_Clause (N : Node_Id) is
3282       Ident   : constant Node_Id := Identifier (N);
3283       Biased  : Boolean;
3284       CC      : Node_Id;
3285       Comp    : Entity_Id;
3286       Fbit    : Uint;
3287       Hbit    : Uint := Uint_0;
3288       Lbit    : Uint;
3289       Ocomp   : Entity_Id;
3290       Posit   : Uint;
3291       Rectype : Entity_Id;
3292
3293       CR_Pragma : Node_Id := Empty;
3294       --  Points to N_Pragma node if Complete_Representation pragma present
3295
3296    begin
3297       if Ignore_Rep_Clauses then
3298          return;
3299       end if;
3300
3301       Find_Type (Ident);
3302       Rectype := Entity (Ident);
3303
3304       if Rectype = Any_Type
3305         or else Rep_Item_Too_Early (Rectype, N)
3306       then
3307          return;
3308       else
3309          Rectype := Underlying_Type (Rectype);
3310       end if;
3311
3312       --  First some basic error checks
3313
3314       if not Is_Record_Type (Rectype) then
3315          Error_Msg_NE
3316            ("record type required, found}", Ident, First_Subtype (Rectype));
3317          return;
3318
3319       elsif Scope (Rectype) /= Current_Scope then
3320          Error_Msg_N ("type must be declared in this scope", N);
3321          return;
3322
3323       elsif not Is_First_Subtype (Rectype) then
3324          Error_Msg_N ("cannot give record rep clause for subtype", N);
3325          return;
3326
3327       elsif Has_Record_Rep_Clause (Rectype) then
3328          Error_Msg_N ("duplicate record rep clause ignored", N);
3329          return;
3330
3331       elsif Rep_Item_Too_Late (Rectype, N) then
3332          return;
3333       end if;
3334
3335       if Present (Mod_Clause (N)) then
3336          declare
3337             Loc     : constant Source_Ptr := Sloc (N);
3338             M       : constant Node_Id := Mod_Clause (N);
3339             P       : constant List_Id := Pragmas_Before (M);
3340             AtM_Nod : Node_Id;
3341
3342             Mod_Val : Uint;
3343             pragma Warnings (Off, Mod_Val);
3344
3345          begin
3346             Check_Restriction (No_Obsolescent_Features, Mod_Clause (N));
3347
3348             if Warn_On_Obsolescent_Feature then
3349                Error_Msg_N
3350                  ("mod clause is an obsolescent feature (RM J.8)?", N);
3351                Error_Msg_N
3352                  ("\use alignment attribute definition clause instead?", N);
3353             end if;
3354
3355             if Present (P) then
3356                Analyze_List (P);
3357             end if;
3358
3359             --  In ASIS_Mode mode, expansion is disabled, but we must convert
3360             --  the Mod clause into an alignment clause anyway, so that the
3361             --  back-end can compute and back-annotate properly the size and
3362             --  alignment of types that may include this record.
3363
3364             --  This seems dubious, this destroys the source tree in a manner
3365             --  not detectable by ASIS ???
3366
3367             if Operating_Mode = Check_Semantics
3368               and then ASIS_Mode
3369             then
3370                AtM_Nod :=
3371                  Make_Attribute_Definition_Clause (Loc,
3372                    Name       => New_Reference_To (Base_Type (Rectype), Loc),
3373                    Chars      => Name_Alignment,
3374                    Expression => Relocate_Node (Expression (M)));
3375
3376                Set_From_At_Mod (AtM_Nod);
3377                Insert_After (N, AtM_Nod);
3378                Mod_Val := Get_Alignment_Value (Expression (AtM_Nod));
3379                Set_Mod_Clause (N, Empty);
3380
3381             else
3382                --  Get the alignment value to perform error checking
3383
3384                Mod_Val := Get_Alignment_Value (Expression (M));
3385             end if;
3386          end;
3387       end if;
3388
3389       --  For untagged types, clear any existing component clauses for the
3390       --  type. If the type is derived, this is what allows us to override
3391       --  a rep clause for the parent. For type extensions, the representation
3392       --  of the inherited components is inherited, so we want to keep previous
3393       --  component clauses for completeness.
3394
3395       if not Is_Tagged_Type (Rectype) then
3396          Comp := First_Component_Or_Discriminant (Rectype);
3397          while Present (Comp) loop
3398             Set_Component_Clause (Comp, Empty);
3399             Next_Component_Or_Discriminant (Comp);
3400          end loop;
3401       end if;
3402
3403       --  All done if no component clauses
3404
3405       CC := First (Component_Clauses (N));
3406
3407       if No (CC) then
3408          return;
3409       end if;
3410
3411       --  A representation like this applies to the base type
3412
3413       Set_Has_Record_Rep_Clause (Base_Type (Rectype));
3414       Set_Has_Non_Standard_Rep  (Base_Type (Rectype));
3415       Set_Has_Specified_Layout  (Base_Type (Rectype));
3416
3417       --  Process the component clauses
3418
3419       while Present (CC) loop
3420
3421          --  Pragma
3422
3423          if Nkind (CC) = N_Pragma then
3424             Analyze (CC);
3425
3426             --  The only pragma of interest is Complete_Representation
3427
3428             if Pragma_Name (CC) = Name_Complete_Representation then
3429                CR_Pragma := CC;
3430             end if;
3431
3432          --  Processing for real component clause
3433
3434          else
3435             Posit := Static_Integer (Position  (CC));
3436             Fbit  := Static_Integer (First_Bit (CC));
3437             Lbit  := Static_Integer (Last_Bit  (CC));
3438
3439             if Posit /= No_Uint
3440               and then Fbit /= No_Uint
3441               and then Lbit /= No_Uint
3442             then
3443                if Posit < 0 then
3444                   Error_Msg_N
3445                     ("position cannot be negative", Position (CC));
3446
3447                elsif Fbit < 0 then
3448                   Error_Msg_N
3449                     ("first bit cannot be negative", First_Bit (CC));
3450
3451                --  The Last_Bit specified in a component clause must not be
3452                --  less than the First_Bit minus one (RM-13.5.1(10)).
3453
3454                elsif Lbit < Fbit - 1 then
3455                   Error_Msg_N
3456                     ("last bit cannot be less than first bit minus one",
3457                      Last_Bit (CC));
3458
3459                --  Values look OK, so find the corresponding record component
3460                --  Even though the syntax allows an attribute reference for
3461                --  implementation-defined components, GNAT does not allow the
3462                --  tag to get an explicit position.
3463
3464                elsif Nkind (Component_Name (CC)) = N_Attribute_Reference then
3465                   if Attribute_Name (Component_Name (CC)) = Name_Tag then
3466                      Error_Msg_N ("position of tag cannot be specified", CC);
3467                   else
3468                      Error_Msg_N ("illegal component name", CC);
3469                   end if;
3470
3471                else
3472                   Comp := First_Entity (Rectype);
3473                   while Present (Comp) loop
3474                      exit when Chars (Comp) = Chars (Component_Name (CC));
3475                      Next_Entity (Comp);
3476                   end loop;
3477
3478                   if No (Comp) then
3479
3480                      --  Maybe component of base type that is absent from
3481                      --  statically constrained first subtype.
3482
3483                      Comp := First_Entity (Base_Type (Rectype));
3484                      while Present (Comp) loop
3485                         exit when Chars (Comp) = Chars (Component_Name (CC));
3486                         Next_Entity (Comp);
3487                      end loop;
3488                   end if;
3489
3490                   if No (Comp) then
3491                      Error_Msg_N
3492                        ("component clause is for non-existent field", CC);
3493
3494                   --  Ada 2012 (AI05-0026): Any name that denotes a
3495                   --  discriminant of an object of an unchecked union type
3496                   --  shall not occur within a record_representation_clause.
3497
3498                   --  The general restriction of using record rep clauses on
3499                   --  Unchecked_Union types has now been lifted. Since it is
3500                   --  possible to introduce a record rep clause which mentions
3501                   --  the discriminant of an Unchecked_Union in non-Ada 2012
3502                   --  code, this check is applied to all versions of the
3503                   --  language.
3504
3505                   elsif Ekind (Comp) = E_Discriminant
3506                     and then Is_Unchecked_Union (Rectype)
3507                   then
3508                      Error_Msg_N
3509                        ("cannot reference discriminant of Unchecked_Union",
3510                         Component_Name (CC));
3511
3512                   elsif Present (Component_Clause (Comp)) then
3513
3514                      --  Diagnose duplicate rep clause, or check consistency
3515                      --  if this is an inherited component. In a double fault,
3516                      --  there may be a duplicate inconsistent clause for an
3517                      --  inherited component.
3518
3519                      if Scope (Original_Record_Component (Comp)) = Rectype
3520                        or else Parent (Component_Clause (Comp)) = N
3521                      then
3522                         Error_Msg_Sloc := Sloc (Component_Clause (Comp));
3523                         Error_Msg_N ("component clause previously given#", CC);
3524
3525                      else
3526                         declare
3527                            Rep1 : constant Node_Id := Component_Clause (Comp);
3528                         begin
3529                            if Intval (Position (Rep1)) /=
3530                                                    Intval (Position (CC))
3531                              or else Intval (First_Bit (Rep1)) /=
3532                                                    Intval (First_Bit (CC))
3533                              or else Intval (Last_Bit (Rep1)) /=
3534                                                    Intval (Last_Bit (CC))
3535                            then
3536                               Error_Msg_N ("component clause inconsistent "
3537                                 & "with representation of ancestor", CC);
3538                            elsif Warn_On_Redundant_Constructs then
3539                               Error_Msg_N ("?redundant component clause "
3540                                 & "for inherited component!", CC);
3541                            end if;
3542                         end;
3543                      end if;
3544
3545                   --  Normal case where this is the first component clause we
3546                   --  have seen for this entity, so set it up properly.
3547
3548                   else
3549                      --  Make reference for field in record rep clause and set
3550                      --  appropriate entity field in the field identifier.
3551
3552                      Generate_Reference
3553                        (Comp, Component_Name (CC), Set_Ref => False);
3554                      Set_Entity (Component_Name (CC), Comp);
3555
3556                      --  Update Fbit and Lbit to the actual bit number
3557
3558                      Fbit := Fbit + UI_From_Int (SSU) * Posit;
3559                      Lbit := Lbit + UI_From_Int (SSU) * Posit;
3560
3561                      if Has_Size_Clause (Rectype)
3562                        and then Esize (Rectype) <= Lbit
3563                      then
3564                         Error_Msg_N
3565                           ("bit number out of range of specified size",
3566                            Last_Bit (CC));
3567                      else
3568                         Set_Component_Clause     (Comp, CC);
3569                         Set_Component_Bit_Offset (Comp, Fbit);
3570                         Set_Esize                (Comp, 1 + (Lbit - Fbit));
3571                         Set_Normalized_First_Bit (Comp, Fbit mod SSU);
3572                         Set_Normalized_Position  (Comp, Fbit / SSU);
3573
3574                         if Warn_On_Overridden_Size
3575                           and then Has_Size_Clause (Etype (Comp))
3576                           and then RM_Size (Etype (Comp)) /= Esize (Comp)
3577                         then
3578                            Error_Msg_NE
3579                              ("?component size overrides size clause for&",
3580                               Component_Name (CC), Etype (Comp));
3581                         end if;
3582
3583                         --  This information is also set in the corresponding
3584                         --  component of the base type, found by accessing the
3585                         --  Original_Record_Component link if it is present.
3586
3587                         Ocomp := Original_Record_Component (Comp);
3588
3589                         if Hbit < Lbit then
3590                            Hbit := Lbit;
3591                         end if;
3592
3593                         Check_Size
3594                           (Component_Name (CC),
3595                            Etype (Comp),
3596                            Esize (Comp),
3597                            Biased);
3598
3599                         Set_Biased
3600                           (Comp, First_Node (CC), "component clause", Biased);
3601
3602                         if Present (Ocomp) then
3603                            Set_Component_Clause     (Ocomp, CC);
3604                            Set_Component_Bit_Offset (Ocomp, Fbit);
3605                            Set_Normalized_First_Bit (Ocomp, Fbit mod SSU);
3606                            Set_Normalized_Position  (Ocomp, Fbit / SSU);
3607                            Set_Esize                (Ocomp, 1 + (Lbit - Fbit));
3608
3609                            Set_Normalized_Position_Max
3610                              (Ocomp, Normalized_Position (Ocomp));
3611
3612                            --  Note: we don't use Set_Biased here, because we
3613                            --  already gave a warning above if needed, and we
3614                            --  would get a duplicate for the same name here.
3615
3616                            Set_Has_Biased_Representation
3617                              (Ocomp, Has_Biased_Representation (Comp));
3618                         end if;
3619
3620                         if Esize (Comp) < 0 then
3621                            Error_Msg_N ("component size is negative", CC);
3622                         end if;
3623                      end if;
3624                   end if;
3625                end if;
3626             end if;
3627          end if;
3628
3629          Next (CC);
3630       end loop;
3631
3632       --  Check missing components if Complete_Representation pragma appeared
3633
3634       if Present (CR_Pragma) then
3635          Comp := First_Component_Or_Discriminant (Rectype);
3636          while Present (Comp) loop
3637             if No (Component_Clause (Comp)) then
3638                Error_Msg_NE
3639                  ("missing component clause for &", CR_Pragma, Comp);
3640             end if;
3641
3642             Next_Component_Or_Discriminant (Comp);
3643          end loop;
3644
3645          --  If no Complete_Representation pragma, warn if missing components
3646
3647       elsif Warn_On_Unrepped_Components then
3648          declare
3649             Num_Repped_Components   : Nat := 0;
3650             Num_Unrepped_Components : Nat := 0;
3651
3652          begin
3653             --  First count number of repped and unrepped components
3654
3655             Comp := First_Component_Or_Discriminant (Rectype);
3656             while Present (Comp) loop
3657                if Present (Component_Clause (Comp)) then
3658                   Num_Repped_Components := Num_Repped_Components + 1;
3659                else
3660                   Num_Unrepped_Components := Num_Unrepped_Components + 1;
3661                end if;
3662
3663                Next_Component_Or_Discriminant (Comp);
3664             end loop;
3665
3666             --  We are only interested in the case where there is at least one
3667             --  unrepped component, and at least half the components have rep
3668             --  clauses. We figure that if less than half have them, then the
3669             --  partial rep clause is really intentional. If the component
3670             --  type has no underlying type set at this point (as for a generic
3671             --  formal type), we don't know enough to give a warning on the
3672             --  component.
3673
3674             if Num_Unrepped_Components > 0
3675               and then Num_Unrepped_Components < Num_Repped_Components
3676             then
3677                Comp := First_Component_Or_Discriminant (Rectype);
3678                while Present (Comp) loop
3679                   if No (Component_Clause (Comp))
3680                     and then Comes_From_Source (Comp)
3681                     and then Present (Underlying_Type (Etype (Comp)))
3682                     and then (Is_Scalar_Type (Underlying_Type (Etype (Comp)))
3683                                or else Size_Known_At_Compile_Time
3684                                          (Underlying_Type (Etype (Comp))))
3685                     and then not Has_Warnings_Off (Rectype)
3686                   then
3687                      Error_Msg_Sloc := Sloc (Comp);
3688                      Error_Msg_NE
3689                        ("?no component clause given for & declared #",
3690                         N, Comp);
3691                   end if;
3692
3693                   Next_Component_Or_Discriminant (Comp);
3694                end loop;
3695             end if;
3696          end;
3697       end if;
3698    end Analyze_Record_Representation_Clause;
3699
3700    -------------------------------
3701    -- Build_Invariant_Procedure --
3702    -------------------------------
3703
3704    --  The procedure that is constructed here has the form
3705
3706    --  procedure typInvariant (Ixxx : typ) is
3707    --  begin
3708    --     pragma Check (Invariant, exp, "failed invariant from xxx");
3709    --     pragma Check (Invariant, exp, "failed invariant from xxx");
3710    --     ...
3711    --     pragma Check (Invariant, exp, "failed inherited invariant from xxx");
3712    --     ...
3713    --  end typInvariant;
3714
3715    procedure Build_Invariant_Procedure (Typ : Entity_Id; N : Node_Id) is
3716       Loc   : constant Source_Ptr := Sloc (Typ);
3717       Stmts : List_Id;
3718       Spec  : Node_Id;
3719       SId   : Entity_Id;
3720       PDecl : Node_Id;
3721       PBody : Node_Id;
3722
3723       Visible_Decls : constant List_Id := Visible_Declarations (N);
3724       Private_Decls : constant List_Id := Private_Declarations (N);
3725
3726       procedure Add_Invariants (T : Entity_Id; Inherit : Boolean);
3727       --  Appends statements to Stmts for any invariants in the rep item chain
3728       --  of the given type. If Inherit is False, then we only process entries
3729       --  on the chain for the type Typ. If Inherit is True, then we ignore any
3730       --  Invariant aspects, but we process all Invariant'Class aspects, adding
3731       --  "inherited" to the exception message and generating an informational
3732       --  message about the inheritance of an invariant.
3733
3734       Object_Name : constant Name_Id := New_Internal_Name ('I');
3735       --  Name for argument of invariant procedure
3736
3737       Object_Entity : constant Node_Id :=
3738                         Make_Defining_Identifier (Loc, Object_Name);
3739       --  The procedure declaration entity for the argument
3740
3741       --------------------
3742       -- Add_Invariants --
3743       --------------------
3744
3745       procedure Add_Invariants (T : Entity_Id; Inherit : Boolean) is
3746          Ritem : Node_Id;
3747          Arg1  : Node_Id;
3748          Arg2  : Node_Id;
3749          Arg3  : Node_Id;
3750          Exp   : Node_Id;
3751          Loc   : Source_Ptr;
3752          Assoc : List_Id;
3753          Str   : String_Id;
3754
3755          procedure Replace_Type_Reference (N : Node_Id);
3756          --  Replace a single occurrence N of the subtype name with a reference
3757          --  to the formal of the predicate function. N can be an identifier
3758          --  referencing the subtype, or a selected component, representing an
3759          --  appropriately qualified occurrence of the subtype name.
3760
3761          procedure Replace_Type_References is
3762            new Replace_Type_References_Generic (Replace_Type_Reference);
3763          --  Traverse an expression replacing all occurrences of the subtype
3764          --  name with appropriate references to the object that is the formal
3765          --  parameter of the predicate function. Note that we must ensure
3766          --  that the type and entity information is properly set in the
3767          --  replacement node, since we will do a Preanalyze call of this
3768          --  expression without proper visibility of the procedure argument.
3769
3770          ----------------------------
3771          -- Replace_Type_Reference --
3772          ----------------------------
3773
3774          procedure Replace_Type_Reference (N : Node_Id) is
3775          begin
3776             --  Invariant'Class, replace with T'Class (obj)
3777
3778             if Class_Present (Ritem) then
3779                Rewrite (N,
3780                  Make_Type_Conversion (Loc,
3781                    Subtype_Mark =>
3782                      Make_Attribute_Reference (Loc,
3783                        Prefix         => New_Occurrence_Of (T, Loc),
3784                        Attribute_Name => Name_Class),
3785                    Expression   => Make_Identifier (Loc, Object_Name)));
3786
3787                Set_Entity (Expression (N), Object_Entity);
3788                Set_Etype  (Expression (N), Typ);
3789
3790             --  Invariant, replace with obj
3791
3792             else
3793                Rewrite (N, Make_Identifier (Loc, Object_Name));
3794                Set_Entity (N, Object_Entity);
3795                Set_Etype  (N, Typ);
3796             end if;
3797          end Replace_Type_Reference;
3798
3799       --  Start of processing for Add_Invariants
3800
3801       begin
3802          Ritem := First_Rep_Item (T);
3803          while Present (Ritem) loop
3804             if Nkind (Ritem) = N_Pragma
3805               and then Pragma_Name (Ritem) = Name_Invariant
3806             then
3807                Arg1 := First (Pragma_Argument_Associations (Ritem));
3808                Arg2 := Next (Arg1);
3809                Arg3 := Next (Arg2);
3810
3811                Arg1 := Get_Pragma_Arg (Arg1);
3812                Arg2 := Get_Pragma_Arg (Arg2);
3813
3814                --  For Inherit case, ignore Invariant, process only Class case
3815
3816                if Inherit then
3817                   if not Class_Present (Ritem) then
3818                      goto Continue;
3819                   end if;
3820
3821                --  For Inherit false, process only item for right type
3822
3823                else
3824                   if Entity (Arg1) /= Typ then
3825                      goto Continue;
3826                   end if;
3827                end if;
3828
3829                if No (Stmts) then
3830                   Stmts := Empty_List;
3831                end if;
3832
3833                Exp := New_Copy_Tree (Arg2);
3834                Loc := Sloc (Exp);
3835
3836                --  We need to replace any occurrences of the name of the type
3837                --  with references to the object, converted to type'Class in
3838                --  the case of Invariant'Class aspects.
3839
3840                Replace_Type_References (Exp, Chars (T));
3841
3842                --  If this invariant comes from an aspect, find the aspect
3843                --  specification, and replace the saved expression because
3844                --  we need the subtype references replaced for the calls to
3845                --  Preanalyze_Spec_Expressin in Check_Aspect_At_Freeze_Point
3846                --  and Check_Aspect_At_End_Of_Declarations.
3847
3848                if From_Aspect_Specification (Ritem) then
3849                   declare
3850                      Aitem : Node_Id;
3851
3852                   begin
3853                      --  Loop to find corresponding aspect, note that this
3854                      --  must be present given the pragma is marked delayed.
3855
3856                      Aitem := Next_Rep_Item (Ritem);
3857                      while Present (Aitem) loop
3858                         if Nkind (Aitem) = N_Aspect_Specification
3859                           and then Aspect_Rep_Item (Aitem) = Ritem
3860                         then
3861                            Set_Entity
3862                              (Identifier (Aitem), New_Copy_Tree (Exp));
3863                            exit;
3864                         end if;
3865
3866                         Aitem := Next_Rep_Item (Aitem);
3867                      end loop;
3868                   end;
3869                end if;
3870
3871                --  Now we need to preanalyze the expression to properly capture
3872                --  the visibility in the visible part. The expression will not
3873                --  be analyzed for real until the body is analyzed, but that is
3874                --  at the end of the private part and has the wrong visibility.
3875
3876                Set_Parent (Exp, N);
3877                Preanalyze_Spec_Expression (Exp, Standard_Boolean);
3878
3879                --  Build first two arguments for Check pragma
3880
3881                Assoc := New_List (
3882                  Make_Pragma_Argument_Association (Loc,
3883                    Expression => Make_Identifier (Loc, Name_Invariant)),
3884                  Make_Pragma_Argument_Association (Loc, Expression => Exp));
3885
3886                --  Add message if present in Invariant pragma
3887
3888                if Present (Arg3) then
3889                   Str := Strval (Get_Pragma_Arg (Arg3));
3890
3891                   --  If inherited case, and message starts "failed invariant",
3892                   --  change it to be "failed inherited invariant".
3893
3894                   if Inherit then
3895                      String_To_Name_Buffer (Str);
3896
3897                      if Name_Buffer (1 .. 16) = "failed invariant" then
3898                         Insert_Str_In_Name_Buffer ("inherited ", 8);
3899                         Str := String_From_Name_Buffer;
3900                      end if;
3901                   end if;
3902
3903                   Append_To (Assoc,
3904                     Make_Pragma_Argument_Association (Loc,
3905                       Expression => Make_String_Literal (Loc, Str)));
3906                end if;
3907
3908                --  Add Check pragma to list of statements
3909
3910                Append_To (Stmts,
3911                  Make_Pragma (Loc,
3912                    Pragma_Identifier            =>
3913                      Make_Identifier (Loc, Name_Check),
3914                    Pragma_Argument_Associations => Assoc));
3915
3916                --  If Inherited case and option enabled, output info msg. Note
3917                --  that we know this is a case of Invariant'Class.
3918
3919                if Inherit and Opt.List_Inherited_Aspects then
3920                   Error_Msg_Sloc := Sloc (Ritem);
3921                   Error_Msg_N
3922                     ("?info: & inherits `Invariant''Class` aspect from #",
3923                      Typ);
3924                end if;
3925             end if;
3926
3927          <<Continue>>
3928             Next_Rep_Item (Ritem);
3929          end loop;
3930       end Add_Invariants;
3931
3932    --  Start of processing for Build_Invariant_Procedure
3933
3934    begin
3935       Stmts := No_List;
3936       PDecl := Empty;
3937       PBody := Empty;
3938       Set_Etype (Object_Entity, Typ);
3939
3940       --  Add invariants for the current type
3941
3942       Add_Invariants (Typ, Inherit => False);
3943
3944       --  Add invariants for parent types
3945
3946       declare
3947          Current_Typ : Entity_Id;
3948          Parent_Typ  : Entity_Id;
3949
3950       begin
3951          Current_Typ := Typ;
3952          loop
3953             Parent_Typ := Etype (Current_Typ);
3954
3955             if Is_Private_Type (Parent_Typ)
3956               and then Present (Full_View (Base_Type (Parent_Typ)))
3957             then
3958                Parent_Typ := Full_View (Base_Type (Parent_Typ));
3959             end if;
3960
3961             exit when Parent_Typ = Current_Typ;
3962
3963             Current_Typ := Parent_Typ;
3964             Add_Invariants (Current_Typ, Inherit => True);
3965          end loop;
3966       end;
3967
3968       --  Build the procedure if we generated at least one Check pragma
3969
3970       if Stmts /= No_List then
3971
3972          --  Build procedure declaration
3973
3974          SId :=
3975            Make_Defining_Identifier (Loc,
3976              Chars => New_External_Name (Chars (Typ), "Invariant"));
3977          Set_Has_Invariants (SId);
3978          Set_Invariant_Procedure (Typ, SId);
3979
3980          Spec :=
3981            Make_Procedure_Specification (Loc,
3982              Defining_Unit_Name       => SId,
3983              Parameter_Specifications => New_List (
3984                Make_Parameter_Specification (Loc,
3985                  Defining_Identifier => Object_Entity,
3986                  Parameter_Type      => New_Occurrence_Of (Typ, Loc))));
3987
3988          PDecl := Make_Subprogram_Declaration (Loc, Specification => Spec);
3989
3990          --  Build procedure body
3991
3992          SId :=
3993            Make_Defining_Identifier (Loc,
3994              Chars => New_External_Name (Chars (Typ), "Invariant"));
3995
3996          Spec :=
3997            Make_Procedure_Specification (Loc,
3998              Defining_Unit_Name       => SId,
3999              Parameter_Specifications => New_List (
4000                Make_Parameter_Specification (Loc,
4001                  Defining_Identifier =>
4002                    Make_Defining_Identifier (Loc, Object_Name),
4003                  Parameter_Type => New_Occurrence_Of (Typ, Loc))));
4004
4005          PBody :=
4006            Make_Subprogram_Body (Loc,
4007              Specification              => Spec,
4008              Declarations               => Empty_List,
4009              Handled_Statement_Sequence =>
4010                Make_Handled_Sequence_Of_Statements (Loc,
4011                  Statements => Stmts));
4012
4013          --  Insert procedure declaration and spec at the appropriate points.
4014          --  Skip this if there are no private declarations (that's an error
4015          --  that will be diagnosed elsewhere, and there is no point in having
4016          --  an invariant procedure set if the full declaration is missing).
4017
4018          if Present (Private_Decls) then
4019
4020             --  The spec goes at the end of visible declarations, but they have
4021             --  already been analyzed, so we need to explicitly do the analyze.
4022
4023             Append_To (Visible_Decls, PDecl);
4024             Analyze (PDecl);
4025
4026             --  The body goes at the end of the private declarations, which we
4027             --  have not analyzed yet, so we do not need to perform an explicit
4028             --  analyze call. We skip this if there are no private declarations
4029             --  (this is an error that will be caught elsewhere);
4030
4031             Append_To (Private_Decls, PBody);
4032          end if;
4033       end if;
4034    end Build_Invariant_Procedure;
4035
4036    ------------------------------
4037    -- Build_Predicate_Function --
4038    ------------------------------
4039
4040    --  The procedure that is constructed here has the form
4041
4042    --  function typPredicate (Ixxx : typ) return Boolean is
4043    --  begin
4044    --     return
4045    --        exp1 and then exp2 and then ...
4046    --        and then typ1Predicate (typ1 (Ixxx))
4047    --        and then typ2Predicate (typ2 (Ixxx))
4048    --        and then ...;
4049    --  end typPredicate;
4050
4051    --  Here exp1, and exp2 are expressions from Predicate pragmas. Note that
4052    --  this is the point at which these expressions get analyzed, providing the
4053    --  required delay, and typ1, typ2, are entities from which predicates are
4054    --  inherited. Note that we do NOT generate Check pragmas, that's because we
4055    --  use this function even if checks are off, e.g. for membership tests.
4056
4057    procedure Build_Predicate_Function (Typ : Entity_Id; N : Node_Id) is
4058       Loc  : constant Source_Ptr := Sloc (Typ);
4059       Spec : Node_Id;
4060       SId  : Entity_Id;
4061       FDecl : Node_Id;
4062       FBody : Node_Id;
4063
4064       Expr : Node_Id;
4065       --  This is the expression for the return statement in the function. It
4066       --  is build by connecting the component predicates with AND THEN.
4067
4068       procedure Add_Call (T : Entity_Id);
4069       --  Includes a call to the predicate function for type T in Expr if T
4070       --  has predicates and Predicate_Function (T) is non-empty.
4071
4072       procedure Add_Predicates;
4073       --  Appends expressions for any Predicate pragmas in the rep item chain
4074       --  Typ to Expr. Note that we look only at items for this exact entity.
4075       --  Inheritance of predicates for the parent type is done by calling the
4076       --  Predicate_Function of the parent type, using Add_Call above.
4077
4078       Object_Name : constant Name_Id := New_Internal_Name ('I');
4079       --  Name for argument of Predicate procedure
4080
4081       Object_Entity : constant Entity_Id :=
4082                         Make_Defining_Identifier (Loc, Object_Name);
4083       --  The entity for the spec entity for the argument
4084
4085       Dynamic_Predicate_Present : Boolean := False;
4086       --  Set True if a dynamic predicate is present, results in the entire
4087       --  predicate being considered dynamic even if it looks static
4088
4089       Static_Predicate_Present : Node_Id := Empty;
4090       --  Set to N_Pragma node for a static predicate if one is encountered.
4091
4092       --------------
4093       -- Add_Call --
4094       --------------
4095
4096       procedure Add_Call (T : Entity_Id) is
4097          Exp : Node_Id;
4098
4099       begin
4100          if Present (T) and then Present (Predicate_Function (T)) then
4101             Set_Has_Predicates (Typ);
4102
4103             --  Build the call to the predicate function of T
4104
4105             Exp :=
4106               Make_Predicate_Call
4107                 (T, Convert_To (T, Make_Identifier (Loc, Object_Name)));
4108
4109             --  Add call to evolving expression, using AND THEN if needed
4110
4111             if No (Expr) then
4112                Expr := Exp;
4113             else
4114                Expr :=
4115                  Make_And_Then (Loc,
4116                    Left_Opnd  => Relocate_Node (Expr),
4117                    Right_Opnd => Exp);
4118             end if;
4119
4120             --  Output info message on inheritance if required. Note we do not
4121             --  give this information for generic actual types, since it is
4122             --  unwelcome noise in that case in instantiations. We also
4123             --  generally suppress the message in instantiations, and also
4124             --  if it involves internal names.
4125
4126             if Opt.List_Inherited_Aspects
4127               and then not Is_Generic_Actual_Type (Typ)
4128               and then Instantiation_Depth (Sloc (Typ)) = 0
4129               and then not Is_Internal_Name (Chars (T))
4130               and then not Is_Internal_Name (Chars (Typ))
4131             then
4132                Error_Msg_Sloc := Sloc (Predicate_Function (T));
4133                Error_Msg_Node_2 := T;
4134                Error_Msg_N ("?info: & inherits predicate from & #", Typ);
4135             end if;
4136          end if;
4137       end Add_Call;
4138
4139       --------------------
4140       -- Add_Predicates --
4141       --------------------
4142
4143       procedure Add_Predicates is
4144          Ritem : Node_Id;
4145          Arg1  : Node_Id;
4146          Arg2  : Node_Id;
4147
4148          procedure Replace_Type_Reference (N : Node_Id);
4149          --  Replace a single occurrence N of the subtype name with a reference
4150          --  to the formal of the predicate function. N can be an identifier
4151          --  referencing the subtype, or a selected component, representing an
4152          --  appropriately qualified occurrence of the subtype name.
4153
4154          procedure Replace_Type_References is
4155            new Replace_Type_References_Generic (Replace_Type_Reference);
4156          --  Traverse an expression changing every occurrence of an identifier
4157          --  whose name matches the name of the subtype with a reference to
4158          --  the formal parameter of the predicate function.
4159
4160          ----------------------------
4161          -- Replace_Type_Reference --
4162          ----------------------------
4163
4164          procedure Replace_Type_Reference (N : Node_Id) is
4165          begin
4166             Rewrite (N, Make_Identifier (Loc, Object_Name));
4167             Set_Entity (N, Object_Entity);
4168             Set_Etype (N, Typ);
4169          end Replace_Type_Reference;
4170
4171       --  Start of processing for Add_Predicates
4172
4173       begin
4174          Ritem := First_Rep_Item (Typ);
4175          while Present (Ritem) loop
4176             if Nkind (Ritem) = N_Pragma
4177               and then Pragma_Name (Ritem) = Name_Predicate
4178             then
4179                if From_Dynamic_Predicate (Ritem) then
4180                   Dynamic_Predicate_Present := True;
4181                elsif From_Static_Predicate (Ritem) then
4182                   Static_Predicate_Present := Ritem;
4183                end if;
4184
4185                --  Acquire arguments
4186
4187                Arg1 := First (Pragma_Argument_Associations (Ritem));
4188                Arg2 := Next (Arg1);
4189
4190                Arg1 := Get_Pragma_Arg (Arg1);
4191                Arg2 := Get_Pragma_Arg (Arg2);
4192
4193                --  See if this predicate pragma is for the current type
4194
4195                if Entity (Arg1) = Typ then
4196
4197                   --  We have a match, this entry is for our subtype
4198
4199                   --  We need to replace any occurrences of the name of the
4200                   --  type with references to the object.
4201
4202                   Replace_Type_References (Arg2, Chars (Typ));
4203
4204                   --  If this predicate comes from an aspect, find the aspect
4205                   --  specification, and replace the saved expression because
4206                   --  we need the subtype references replaced for the calls to
4207                   --  Preanalyze_Spec_Expressin in Check_Aspect_At_Freeze_Point
4208                   --  and Check_Aspect_At_End_Of_Declarations.
4209
4210                   if From_Aspect_Specification (Ritem) then
4211                      declare
4212                         Aitem : Node_Id;
4213
4214                      begin
4215                         --  Loop to find corresponding aspect, note that this
4216                         --  must be present given the pragma is marked delayed.
4217
4218                         Aitem := Next_Rep_Item (Ritem);
4219                         loop
4220                            if Nkind (Aitem) = N_Aspect_Specification
4221                              and then Aspect_Rep_Item (Aitem) = Ritem
4222                            then
4223                               Set_Entity
4224                                 (Identifier (Aitem), New_Copy_Tree (Arg2));
4225                               exit;
4226                            end if;
4227
4228                            Aitem := Next_Rep_Item (Aitem);
4229                         end loop;
4230                      end;
4231                   end if;
4232
4233                   --  Now we can add the expression
4234
4235                   if No (Expr) then
4236                      Expr := Relocate_Node (Arg2);
4237
4238                   --  There already was a predicate, so add to it
4239
4240                   else
4241                      Expr :=
4242                        Make_And_Then (Loc,
4243                          Left_Opnd  => Relocate_Node (Expr),
4244                          Right_Opnd => Relocate_Node (Arg2));
4245                   end if;
4246                end if;
4247             end if;
4248
4249             Next_Rep_Item (Ritem);
4250          end loop;
4251       end Add_Predicates;
4252
4253    --  Start of processing for Build_Predicate_Function
4254
4255    begin
4256       --  Initialize for construction of statement list
4257
4258       Expr := Empty;
4259
4260       --  Return if already built or if type does not have predicates
4261
4262       if not Has_Predicates (Typ)
4263         or else Present (Predicate_Function (Typ))
4264       then
4265          return;
4266       end if;
4267
4268       --  Add Predicates for the current type
4269
4270       Add_Predicates;
4271
4272       --  Add predicates for ancestor if present
4273
4274       declare
4275          Atyp : constant Entity_Id := Nearest_Ancestor (Typ);
4276       begin
4277          if Present (Atyp) then
4278             Add_Call (Atyp);
4279          end if;
4280       end;
4281
4282       --  If we have predicates, build the function
4283
4284       if Present (Expr) then
4285
4286          --  Build function declaration
4287
4288          pragma Assert (Has_Predicates (Typ));
4289          SId :=
4290            Make_Defining_Identifier (Loc,
4291              Chars => New_External_Name (Chars (Typ), "Predicate"));
4292          Set_Has_Predicates (SId);
4293          Set_Predicate_Function (Typ, SId);
4294
4295          Spec :=
4296            Make_Function_Specification (Loc,
4297              Defining_Unit_Name       => SId,
4298              Parameter_Specifications => New_List (
4299                Make_Parameter_Specification (Loc,
4300                  Defining_Identifier => Object_Entity,
4301                  Parameter_Type      => New_Occurrence_Of (Typ, Loc))),
4302              Result_Definition        =>
4303                New_Occurrence_Of (Standard_Boolean, Loc));
4304
4305          FDecl := Make_Subprogram_Declaration (Loc, Specification => Spec);
4306
4307          --  Build function body
4308
4309          SId :=
4310            Make_Defining_Identifier (Loc,
4311              Chars => New_External_Name (Chars (Typ), "Predicate"));
4312
4313          Spec :=
4314            Make_Function_Specification (Loc,
4315              Defining_Unit_Name       => SId,
4316              Parameter_Specifications => New_List (
4317                Make_Parameter_Specification (Loc,
4318                  Defining_Identifier =>
4319                    Make_Defining_Identifier (Loc, Object_Name),
4320                  Parameter_Type =>
4321                    New_Occurrence_Of (Typ, Loc))),
4322              Result_Definition        =>
4323                New_Occurrence_Of (Standard_Boolean, Loc));
4324
4325          FBody :=
4326            Make_Subprogram_Body (Loc,
4327              Specification              => Spec,
4328              Declarations               => Empty_List,
4329              Handled_Statement_Sequence =>
4330                Make_Handled_Sequence_Of_Statements (Loc,
4331                  Statements => New_List (
4332                    Make_Simple_Return_Statement (Loc,
4333                      Expression => Expr))));
4334
4335          --  Insert declaration before freeze node and body after
4336
4337          Insert_Before_And_Analyze (N, FDecl);
4338          Insert_After_And_Analyze  (N, FBody);
4339
4340          --  Deal with static predicate case
4341
4342          if Ekind_In (Typ, E_Enumeration_Subtype,
4343                            E_Modular_Integer_Subtype,
4344                            E_Signed_Integer_Subtype)
4345            and then Is_Static_Subtype (Typ)
4346            and then not Dynamic_Predicate_Present
4347          then
4348             Build_Static_Predicate (Typ, Expr, Object_Name);
4349
4350             if Present (Static_Predicate_Present)
4351               and No (Static_Predicate (Typ))
4352             then
4353                Error_Msg_F
4354                  ("expression does not have required form for "
4355                   & "static predicate",
4356                   Next (First (Pragma_Argument_Associations
4357                                 (Static_Predicate_Present))));
4358             end if;
4359          end if;
4360       end if;
4361    end Build_Predicate_Function;
4362
4363    ----------------------------
4364    -- Build_Static_Predicate --
4365    ----------------------------
4366
4367    procedure Build_Static_Predicate
4368      (Typ  : Entity_Id;
4369       Expr : Node_Id;
4370       Nam  : Name_Id)
4371    is
4372       Loc : constant Source_Ptr := Sloc (Expr);
4373
4374       Non_Static : exception;
4375       --  Raised if something non-static is found
4376
4377       Btyp : constant Entity_Id := Base_Type (Typ);
4378
4379       BLo : constant Uint := Expr_Value (Type_Low_Bound  (Btyp));
4380       BHi : constant Uint := Expr_Value (Type_High_Bound (Btyp));
4381       --  Low bound and high bound value of base type of Typ
4382
4383       TLo : constant Uint := Expr_Value (Type_Low_Bound  (Typ));
4384       THi : constant Uint := Expr_Value (Type_High_Bound (Typ));
4385       --  Low bound and high bound values of static subtype Typ
4386
4387       type REnt is record
4388          Lo, Hi : Uint;
4389       end record;
4390       --  One entry in a Rlist value, a single REnt (range entry) value
4391       --  denotes one range from Lo to Hi. To represent a single value
4392       --  range Lo = Hi = value.
4393
4394       type RList is array (Nat range <>) of REnt;
4395       --  A list of ranges. The ranges are sorted in increasing order,
4396       --  and are disjoint (there is a gap of at least one value between
4397       --  each range in the table). A value is in the set of ranges in
4398       --  Rlist if it lies within one of these ranges
4399
4400       False_Range : constant RList :=
4401                       RList'(1 .. 0 => REnt'(No_Uint, No_Uint));
4402       --  An empty set of ranges represents a range list that can never be
4403       --  satisfied, since there are no ranges in which the value could lie,
4404       --  so it does not lie in any of them. False_Range is a canonical value
4405       --  for this empty set, but general processing should test for an Rlist
4406       --  with length zero (see Is_False predicate), since other null ranges
4407       --  may appear which must be treated as False.
4408
4409       True_Range : constant RList := RList'(1 => REnt'(BLo, BHi));
4410       --  Range representing True, value must be in the base range
4411
4412       function "and" (Left, Right : RList) return RList;
4413       --  And's together two range lists, returning a range list. This is
4414       --  a set intersection operation.
4415
4416       function "or" (Left, Right : RList) return RList;
4417       --  Or's together two range lists, returning a range list. This is a
4418       --  set union operation.
4419
4420       function "not" (Right : RList) return RList;
4421       --  Returns complement of a given range list, i.e. a range list
4422       --  representing all the values in TLo .. THi that are not in the
4423       --  input operand Right.
4424
4425       function Build_Val (V : Uint) return Node_Id;
4426       --  Return an analyzed N_Identifier node referencing this value, suitable
4427       --  for use as an entry in the Static_Predicate list. This node is typed
4428       --  with the base type.
4429
4430       function Build_Range (Lo, Hi : Uint) return Node_Id;
4431       --  Return an analyzed N_Range node referencing this range, suitable
4432       --  for use as an entry in the Static_Predicate list. This node is typed
4433       --  with the base type.
4434
4435       function Get_RList (Exp : Node_Id) return RList;
4436       --  This is a recursive routine that converts the given expression into
4437       --  a list of ranges, suitable for use in building the static predicate.
4438
4439       function Is_False (R : RList) return Boolean;
4440       pragma Inline (Is_False);
4441       --  Returns True if the given range list is empty, and thus represents
4442       --  a False list of ranges that can never be satisfied.
4443
4444       function Is_True (R : RList) return Boolean;
4445       --  Returns True if R trivially represents the True predicate by having
4446       --  a single range from BLo to BHi.
4447
4448       function Is_Type_Ref (N : Node_Id) return Boolean;
4449       pragma Inline (Is_Type_Ref);
4450       --  Returns if True if N is a reference to the type for the predicate in
4451       --  the expression (i.e. if it is an identifier whose Chars field matches
4452       --  the Nam given in the call).
4453
4454       function Lo_Val (N : Node_Id) return Uint;
4455       --  Given static expression or static range from a Static_Predicate list,
4456       --  gets expression value or low bound of range.
4457
4458       function Hi_Val (N : Node_Id) return Uint;
4459       --  Given static expression or static range from a Static_Predicate list,
4460       --  gets expression value of high bound of range.
4461
4462       function Membership_Entry (N : Node_Id) return RList;
4463       --  Given a single membership entry (range, value, or subtype), returns
4464       --  the corresponding range list. Raises Static_Error if not static.
4465
4466       function Membership_Entries (N : Node_Id) return RList;
4467       --  Given an element on an alternatives list of a membership operation,
4468       --  returns the range list corresponding to this entry and all following
4469       --  entries (i.e. returns the "or" of this list of values).
4470
4471       function Stat_Pred (Typ : Entity_Id) return RList;
4472       --  Given a type, if it has a static predicate, then return the predicate
4473       --  as a range list, otherwise raise Non_Static.
4474
4475       -----------
4476       -- "and" --
4477       -----------
4478
4479       function "and" (Left, Right : RList) return RList is
4480          FEnt : REnt;
4481          --  First range of result
4482
4483          SLeft : Nat := Left'First;
4484          --  Start of rest of left entries
4485
4486          SRight : Nat := Right'First;
4487          --  Start of rest of right entries
4488
4489       begin
4490          --  If either range is True, return the other
4491
4492          if Is_True (Left) then
4493             return Right;
4494          elsif Is_True (Right) then
4495             return Left;
4496          end if;
4497
4498          --  If either range is False, return False
4499
4500          if Is_False (Left) or else Is_False (Right) then
4501             return False_Range;
4502          end if;
4503
4504          --  Loop to remove entries at start that are disjoint, and thus
4505          --  just get discarded from the result entirely.
4506
4507          loop
4508             --  If no operands left in either operand, result is false
4509
4510             if SLeft > Left'Last or else SRight > Right'Last then
4511                return False_Range;
4512
4513             --  Discard first left operand entry if disjoint with right
4514
4515             elsif Left (SLeft).Hi < Right (SRight).Lo then
4516                SLeft := SLeft + 1;
4517
4518             --  Discard first right operand entry if disjoint with left
4519
4520             elsif Right (SRight).Hi < Left (SLeft).Lo then
4521                SRight := SRight + 1;
4522
4523             --  Otherwise we have an overlapping entry
4524
4525             else
4526                exit;
4527             end if;
4528          end loop;
4529
4530          --  Now we have two non-null operands, and first entries overlap.
4531          --  The first entry in the result will be the overlapping part of
4532          --  these two entries.
4533
4534          FEnt := REnt'(Lo => UI_Max (Left (SLeft).Lo, Right (SRight).Lo),
4535                        Hi => UI_Min (Left (SLeft).Hi, Right (SRight).Hi));
4536
4537          --  Now we can remove the entry that ended at a lower value, since
4538          --  its contribution is entirely contained in Fent.
4539
4540          if Left (SLeft).Hi <= Right (SRight).Hi then
4541             SLeft := SLeft + 1;
4542          else
4543             SRight := SRight + 1;
4544          end if;
4545
4546          --  Compute result by concatenating this first entry with the "and"
4547          --  of the remaining parts of the left and right operands. Note that
4548          --  if either of these is empty, "and" will yield empty, so that we
4549          --  will end up with just Fent, which is what we want in that case.
4550
4551          return
4552            FEnt & (Left (SLeft .. Left'Last) and Right (SRight .. Right'Last));
4553       end "and";
4554
4555       -----------
4556       -- "not" --
4557       -----------
4558
4559       function "not" (Right : RList) return RList is
4560       begin
4561          --  Return True if False range
4562
4563          if Is_False (Right) then
4564             return True_Range;
4565          end if;
4566
4567          --  Return False if True range
4568
4569          if Is_True (Right) then
4570             return False_Range;
4571          end if;
4572
4573          --  Here if not trivial case
4574
4575          declare
4576             Result : RList (1 .. Right'Length + 1);
4577             --  May need one more entry for gap at beginning and end
4578
4579             Count : Nat := 0;
4580             --  Number of entries stored in Result
4581
4582          begin
4583             --  Gap at start
4584
4585             if Right (Right'First).Lo > TLo then
4586                Count := Count + 1;
4587                Result (Count) := REnt'(TLo, Right (Right'First).Lo - 1);
4588             end if;
4589
4590             --  Gaps between ranges
4591
4592             for J in Right'First .. Right'Last - 1 loop
4593                Count := Count + 1;
4594                Result (Count) :=
4595                  REnt'(Right (J).Hi + 1, Right (J + 1).Lo - 1);
4596             end loop;
4597
4598             --  Gap at end
4599
4600             if Right (Right'Last).Hi < THi then
4601                Count := Count + 1;
4602                Result (Count) := REnt'(Right (Right'Last).Hi + 1, THi);
4603             end if;
4604
4605             return Result (1 .. Count);
4606          end;
4607       end "not";
4608
4609       ----------
4610       -- "or" --
4611       ----------
4612
4613       function "or" (Left, Right : RList) return RList is
4614          FEnt : REnt;
4615          --  First range of result
4616
4617          SLeft : Nat := Left'First;
4618          --  Start of rest of left entries
4619
4620          SRight : Nat := Right'First;
4621          --  Start of rest of right entries
4622
4623       begin
4624          --  If either range is True, return True
4625
4626          if Is_True (Left) or else Is_True (Right) then
4627             return True_Range;
4628          end if;
4629
4630          --  If either range is False (empty), return the other
4631
4632          if Is_False (Left) then
4633             return Right;
4634          elsif Is_False (Right) then
4635             return Left;
4636          end if;
4637
4638          --  Initialize result first entry from left or right operand
4639          --  depending on which starts with the lower range.
4640
4641          if Left (SLeft).Lo < Right (SRight).Lo then
4642             FEnt := Left (SLeft);
4643             SLeft := SLeft + 1;
4644          else
4645             FEnt := Right (SRight);
4646             SRight := SRight + 1;
4647          end if;
4648
4649          --  This loop eats ranges from left and right operands that
4650          --  are contiguous with the first range we are gathering.
4651
4652          loop
4653             --  Eat first entry in left operand if contiguous or
4654             --  overlapped by gathered first operand of result.
4655
4656             if SLeft <= Left'Last
4657               and then Left (SLeft).Lo <= FEnt.Hi + 1
4658             then
4659                FEnt.Hi := UI_Max (FEnt.Hi, Left (SLeft).Hi);
4660                SLeft := SLeft + 1;
4661
4662                --  Eat first entry in right operand if contiguous or
4663                --  overlapped by gathered right operand of result.
4664
4665             elsif SRight <= Right'Last
4666               and then Right (SRight).Lo <= FEnt.Hi + 1
4667             then
4668                FEnt.Hi := UI_Max (FEnt.Hi, Right (SRight).Hi);
4669                SRight := SRight + 1;
4670
4671                --  All done if no more entries to eat!
4672
4673             else
4674                exit;
4675             end if;
4676          end loop;
4677
4678          --  Obtain result as the first entry we just computed, concatenated
4679          --  to the "or" of the remaining results (if one operand is empty,
4680          --  this will just concatenate with the other
4681
4682          return
4683            FEnt & (Left (SLeft .. Left'Last) or Right (SRight .. Right'Last));
4684       end "or";
4685
4686       -----------------
4687       -- Build_Range --
4688       -----------------
4689
4690       function Build_Range (Lo, Hi : Uint) return Node_Id is
4691          Result : Node_Id;
4692       begin
4693          if Lo = Hi then
4694             return Build_Val (Hi);
4695          else
4696             Result :=
4697               Make_Range (Loc,
4698                 Low_Bound  => Build_Val (Lo),
4699                 High_Bound => Build_Val (Hi));
4700             Set_Etype (Result, Btyp);
4701             Set_Analyzed (Result);
4702             return Result;
4703          end if;
4704       end Build_Range;
4705
4706       ---------------
4707       -- Build_Val --
4708       ---------------
4709
4710       function Build_Val (V : Uint) return Node_Id is
4711          Result : Node_Id;
4712
4713       begin
4714          if Is_Enumeration_Type (Typ) then
4715             Result := Get_Enum_Lit_From_Pos (Typ, V, Loc);
4716          else
4717             Result := Make_Integer_Literal (Loc, V);
4718          end if;
4719
4720          Set_Etype (Result, Btyp);
4721          Set_Is_Static_Expression (Result);
4722          Set_Analyzed (Result);
4723          return Result;
4724       end Build_Val;
4725
4726       ---------------
4727       -- Get_RList --
4728       ---------------
4729
4730       function Get_RList (Exp : Node_Id) return RList is
4731          Op  : Node_Kind;
4732          Val : Uint;
4733
4734       begin
4735          --  Static expression can only be true or false
4736
4737          if Is_OK_Static_Expression (Exp) then
4738
4739             --  For False
4740
4741             if Expr_Value (Exp) = 0 then
4742                return False_Range;
4743             else
4744                return True_Range;
4745             end if;
4746          end if;
4747
4748          --  Otherwise test node type
4749
4750          Op := Nkind (Exp);
4751
4752          case Op is
4753
4754             --  And
4755
4756             when N_Op_And | N_And_Then =>
4757                return Get_RList (Left_Opnd (Exp))
4758                         and
4759                       Get_RList (Right_Opnd (Exp));
4760
4761             --  Or
4762
4763             when N_Op_Or | N_Or_Else =>
4764                return Get_RList (Left_Opnd (Exp))
4765                         or
4766                       Get_RList (Right_Opnd (Exp));
4767
4768             --  Not
4769
4770             when N_Op_Not =>
4771                return not Get_RList (Right_Opnd (Exp));
4772
4773             --  Comparisons of type with static value
4774
4775             when N_Op_Compare =>
4776                --  Type is left operand
4777
4778                if Is_Type_Ref (Left_Opnd (Exp))
4779                  and then Is_OK_Static_Expression (Right_Opnd (Exp))
4780                then
4781                   Val := Expr_Value (Right_Opnd (Exp));
4782
4783                   --  Typ is right operand
4784
4785                elsif Is_Type_Ref (Right_Opnd (Exp))
4786                  and then Is_OK_Static_Expression (Left_Opnd (Exp))
4787                then
4788                   Val := Expr_Value (Left_Opnd (Exp));
4789
4790                   --  Invert sense of comparison
4791
4792                   case Op is
4793                      when N_Op_Gt => Op := N_Op_Lt;
4794                      when N_Op_Lt => Op := N_Op_Gt;
4795                      when N_Op_Ge => Op := N_Op_Le;
4796                      when N_Op_Le => Op := N_Op_Ge;
4797                      when others  => null;
4798                   end case;
4799
4800                   --  Other cases are non-static
4801
4802                else
4803                   raise Non_Static;
4804                end if;
4805
4806                --  Construct range according to comparison operation
4807
4808                case Op is
4809                   when N_Op_Eq =>
4810                      return RList'(1 => REnt'(Val, Val));
4811
4812                   when N_Op_Ge =>
4813                      return RList'(1 => REnt'(Val, BHi));
4814
4815                   when N_Op_Gt =>
4816                      return RList'(1 => REnt'(Val + 1, BHi));
4817
4818                   when N_Op_Le =>
4819                      return RList'(1 => REnt'(BLo, Val));
4820
4821                   when N_Op_Lt =>
4822                      return RList'(1 => REnt'(BLo, Val - 1));
4823
4824                   when N_Op_Ne =>
4825                      return RList'(REnt'(BLo, Val - 1),
4826                                    REnt'(Val + 1, BHi));
4827
4828                   when others  =>
4829                      raise Program_Error;
4830                end case;
4831
4832             --  Membership (IN)
4833
4834             when N_In =>
4835                if not Is_Type_Ref (Left_Opnd (Exp)) then
4836                   raise Non_Static;
4837                end if;
4838
4839                if Present (Right_Opnd (Exp)) then
4840                   return Membership_Entry (Right_Opnd (Exp));
4841                else
4842                   return Membership_Entries (First (Alternatives (Exp)));
4843                end if;
4844
4845             --  Negative membership (NOT IN)
4846
4847             when N_Not_In =>
4848                if not Is_Type_Ref (Left_Opnd (Exp)) then
4849                   raise Non_Static;
4850                end if;
4851
4852                if Present (Right_Opnd (Exp)) then
4853                   return not Membership_Entry (Right_Opnd (Exp));
4854                else
4855                   return not Membership_Entries (First (Alternatives (Exp)));
4856                end if;
4857
4858             --  Function call, may be call to static predicate
4859
4860             when N_Function_Call =>
4861                if Is_Entity_Name (Name (Exp)) then
4862                   declare
4863                      Ent : constant Entity_Id := Entity (Name (Exp));
4864                   begin
4865                      if Has_Predicates (Ent) then
4866                         return Stat_Pred (Etype (First_Formal (Ent)));
4867                      end if;
4868                   end;
4869                end if;
4870
4871                --  Other function call cases are non-static
4872
4873                raise Non_Static;
4874
4875             --  Qualified expression, dig out the expression
4876
4877             when N_Qualified_Expression =>
4878                return Get_RList (Expression (Exp));
4879
4880             --  Xor operator
4881
4882             when N_Op_Xor =>
4883                return (Get_RList (Left_Opnd (Exp))
4884                         and not Get_RList (Right_Opnd (Exp)))
4885                  or   (Get_RList (Right_Opnd (Exp))
4886                         and not Get_RList (Left_Opnd (Exp)));
4887
4888             --  Any other node type is non-static
4889
4890             when others =>
4891                raise Non_Static;
4892          end case;
4893       end Get_RList;
4894
4895       ------------
4896       -- Hi_Val --
4897       ------------
4898
4899       function Hi_Val (N : Node_Id) return Uint is
4900       begin
4901          if Is_Static_Expression (N) then
4902             return Expr_Value (N);
4903          else
4904             pragma Assert (Nkind (N) = N_Range);
4905             return Expr_Value (High_Bound (N));
4906          end if;
4907       end Hi_Val;
4908
4909       --------------
4910       -- Is_False --
4911       --------------
4912
4913       function Is_False (R : RList) return Boolean is
4914       begin
4915          return R'Length = 0;
4916       end Is_False;
4917
4918       -------------
4919       -- Is_True --
4920       -------------
4921
4922       function Is_True (R : RList) return Boolean is
4923       begin
4924          return R'Length = 1
4925            and then R (R'First).Lo = BLo
4926            and then R (R'First).Hi = BHi;
4927       end Is_True;
4928
4929       -----------------
4930       -- Is_Type_Ref --
4931       -----------------
4932
4933       function Is_Type_Ref (N : Node_Id) return Boolean is
4934       begin
4935          return Nkind (N) = N_Identifier and then Chars (N) = Nam;
4936       end Is_Type_Ref;
4937
4938       ------------
4939       -- Lo_Val --
4940       ------------
4941
4942       function Lo_Val (N : Node_Id) return Uint is
4943       begin
4944          if Is_Static_Expression (N) then
4945             return Expr_Value (N);
4946          else
4947             pragma Assert (Nkind (N) = N_Range);
4948             return Expr_Value (Low_Bound (N));
4949          end if;
4950       end Lo_Val;
4951
4952       ------------------------
4953       -- Membership_Entries --
4954       ------------------------
4955
4956       function Membership_Entries (N : Node_Id) return RList is
4957       begin
4958          if No (Next (N)) then
4959             return Membership_Entry (N);
4960          else
4961             return Membership_Entry (N) or Membership_Entries (Next (N));
4962          end if;
4963       end Membership_Entries;
4964
4965       ----------------------
4966       -- Membership_Entry --
4967       ----------------------
4968
4969       function Membership_Entry (N : Node_Id) return RList is
4970          Val : Uint;
4971          SLo : Uint;
4972          SHi : Uint;
4973
4974       begin
4975          --  Range case
4976
4977          if Nkind (N) = N_Range then
4978             if not Is_Static_Expression (Low_Bound (N))
4979                  or else
4980                not Is_Static_Expression (High_Bound (N))
4981             then
4982                raise Non_Static;
4983             else
4984                SLo := Expr_Value (Low_Bound  (N));
4985                SHi := Expr_Value (High_Bound (N));
4986                return RList'(1 => REnt'(SLo, SHi));
4987             end if;
4988
4989          --  Static expression case
4990
4991          elsif Is_Static_Expression (N) then
4992             Val := Expr_Value (N);
4993             return RList'(1 => REnt'(Val, Val));
4994
4995          --  Identifier (other than static expression) case
4996
4997          else pragma Assert (Nkind (N) = N_Identifier);
4998
4999             --  Type case
5000
5001             if Is_Type (Entity (N)) then
5002
5003                --  If type has predicates, process them
5004
5005                if Has_Predicates (Entity (N)) then
5006                   return Stat_Pred (Entity (N));
5007
5008                --  For static subtype without predicates, get range
5009
5010                elsif Is_Static_Subtype (Entity (N)) then
5011                   SLo := Expr_Value (Type_Low_Bound  (Entity (N)));
5012                   SHi := Expr_Value (Type_High_Bound (Entity (N)));
5013                   return RList'(1 => REnt'(SLo, SHi));
5014
5015                --  Any other type makes us non-static
5016
5017                else
5018                   raise Non_Static;
5019                end if;
5020
5021             --  Any other kind of identifier in predicate (e.g. a non-static
5022             --  expression value) means this is not a static predicate.
5023
5024             else
5025                raise Non_Static;
5026             end if;
5027          end if;
5028       end Membership_Entry;
5029
5030       ---------------
5031       -- Stat_Pred --
5032       ---------------
5033
5034       function Stat_Pred (Typ : Entity_Id) return RList is
5035       begin
5036          --  Not static if type does not have static predicates
5037
5038          if not Has_Predicates (Typ)
5039            or else No (Static_Predicate (Typ))
5040          then
5041             raise Non_Static;
5042          end if;
5043
5044          --  Otherwise we convert the predicate list to a range list
5045
5046          declare
5047             Result : RList (1 .. List_Length (Static_Predicate (Typ)));
5048             P      : Node_Id;
5049
5050          begin
5051             P := First (Static_Predicate (Typ));
5052             for J in Result'Range loop
5053                Result (J) := REnt'(Lo_Val (P), Hi_Val (P));
5054                Next (P);
5055             end loop;
5056
5057             return Result;
5058          end;
5059       end Stat_Pred;
5060
5061    --  Start of processing for Build_Static_Predicate
5062
5063    begin
5064       --  Now analyze the expression to see if it is a static predicate
5065
5066       declare
5067          Ranges : constant RList := Get_RList (Expr);
5068          --  Range list from expression if it is static
5069
5070          Plist : List_Id;
5071
5072       begin
5073          --  Convert range list into a form for the static predicate. In the
5074          --  Ranges array, we just have raw ranges, these must be converted
5075          --  to properly typed and analyzed static expressions or range nodes.
5076
5077          --  Note: here we limit ranges to the ranges of the subtype, so that
5078          --  a predicate is always false for values outside the subtype. That
5079          --  seems fine, such values are invalid anyway, and considering them
5080          --  to fail the predicate seems allowed and friendly, and furthermore
5081          --  simplifies processing for case statements and loops.
5082
5083          Plist := New_List;
5084
5085          for J in Ranges'Range loop
5086             declare
5087                Lo : Uint := Ranges (J).Lo;
5088                Hi : Uint := Ranges (J).Hi;
5089
5090             begin
5091                --  Ignore completely out of range entry
5092
5093                if Hi < TLo or else Lo > THi then
5094                   null;
5095
5096                   --  Otherwise process entry
5097
5098                else
5099                   --  Adjust out of range value to subtype range
5100
5101                   if Lo < TLo then
5102                      Lo := TLo;
5103                   end if;
5104
5105                   if Hi > THi then
5106                      Hi := THi;
5107                   end if;
5108
5109                   --  Convert range into required form
5110
5111                   if Lo = Hi then
5112                      Append_To (Plist, Build_Val (Lo));
5113                   else
5114                      Append_To (Plist, Build_Range (Lo, Hi));
5115                   end if;
5116                end if;
5117             end;
5118          end loop;
5119
5120          --  Processing was successful and all entries were static, so now we
5121          --  can store the result as the predicate list.
5122
5123          Set_Static_Predicate (Typ, Plist);
5124
5125          --  The processing for static predicates put the expression into
5126          --  canonical form as a series of ranges. It also eliminated
5127          --  duplicates and collapsed and combined ranges. We might as well
5128          --  replace the alternatives list of the right operand of the
5129          --  membership test with the static predicate list, which will
5130          --  usually be more efficient.
5131
5132          declare
5133             New_Alts : constant List_Id := New_List;
5134             Old_Node : Node_Id;
5135             New_Node : Node_Id;
5136
5137          begin
5138             Old_Node := First (Plist);
5139             while Present (Old_Node) loop
5140                New_Node := New_Copy (Old_Node);
5141
5142                if Nkind (New_Node) = N_Range then
5143                   Set_Low_Bound  (New_Node, New_Copy (Low_Bound  (Old_Node)));
5144                   Set_High_Bound (New_Node, New_Copy (High_Bound (Old_Node)));
5145                end if;
5146
5147                Append_To (New_Alts, New_Node);
5148                Next (Old_Node);
5149             end loop;
5150
5151             --  If empty list, replace by False
5152
5153             if Is_Empty_List (New_Alts) then
5154                Rewrite (Expr, New_Occurrence_Of (Standard_False, Loc));
5155
5156             --  Else replace by set membership test
5157
5158             else
5159                Rewrite (Expr,
5160                  Make_In (Loc,
5161                    Left_Opnd    => Make_Identifier (Loc, Nam),
5162                    Right_Opnd   => Empty,
5163                    Alternatives => New_Alts));
5164
5165                --  Resolve new expression in function context
5166
5167                Install_Formals (Predicate_Function (Typ));
5168                Push_Scope (Predicate_Function (Typ));
5169                Analyze_And_Resolve (Expr, Standard_Boolean);
5170                Pop_Scope;
5171             end if;
5172          end;
5173       end;
5174
5175    --  If non-static, return doing nothing
5176
5177    exception
5178       when Non_Static =>
5179          return;
5180    end Build_Static_Predicate;
5181
5182    -----------------------------------------
5183    -- Check_Aspect_At_End_Of_Declarations --
5184    -----------------------------------------
5185
5186    procedure Check_Aspect_At_End_Of_Declarations (ASN : Node_Id) is
5187       Ent   : constant Entity_Id := Entity     (ASN);
5188       Ident : constant Node_Id   := Identifier (ASN);
5189
5190       Freeze_Expr : constant Node_Id := Expression (ASN);
5191       --  Preanalyzed expression from call to Check_Aspect_At_Freeze_Point
5192
5193       End_Decl_Expr : constant Node_Id := Entity (Ident);
5194       --  Expression to be analyzed at end of declarations
5195
5196       T : constant Entity_Id := Etype (Freeze_Expr);
5197       --  Type required for preanalyze call
5198
5199       A_Id : constant Aspect_Id := Get_Aspect_Id (Chars (Ident));
5200
5201       Err : Boolean;
5202       --  Set False if error
5203
5204       --  On entry to this procedure, Entity (Ident) contains a copy of the
5205       --  original expression from the aspect, saved for this purpose, and
5206       --  but Expression (Ident) is a preanalyzed copy of the expression,
5207       --  preanalyzed just after the freeze point.
5208
5209    begin
5210       --  Case of stream attributes, just have to compare entities
5211
5212       if A_Id = Aspect_Input  or else
5213          A_Id = Aspect_Output or else
5214          A_Id = Aspect_Read   or else
5215          A_Id = Aspect_Write
5216       then
5217          Analyze (End_Decl_Expr);
5218          Err := Entity (End_Decl_Expr) /= Entity (Freeze_Expr);
5219
5220       --  All other cases
5221
5222       else
5223          Preanalyze_Spec_Expression (End_Decl_Expr, T);
5224          Err := not Fully_Conformant_Expressions (End_Decl_Expr, Freeze_Expr);
5225       end if;
5226
5227       --  Output error message if error
5228
5229       if Err then
5230          Error_Msg_NE
5231            ("visibility of aspect for& changes after freeze point",
5232             ASN, Ent);
5233          Error_Msg_NE
5234            ("?info: & is frozen here, aspects evaluated at this point",
5235             Freeze_Node (Ent), Ent);
5236       end if;
5237    end Check_Aspect_At_End_Of_Declarations;
5238
5239    ----------------------------------
5240    -- Check_Aspect_At_Freeze_Point --
5241    ----------------------------------
5242
5243    procedure Check_Aspect_At_Freeze_Point (ASN : Node_Id) is
5244       Ident : constant Node_Id := Identifier (ASN);
5245       --  Identifier (use Entity field to save expression)
5246
5247       T : Entity_Id;
5248       --  Type required for preanalyze call
5249
5250       A_Id : constant Aspect_Id := Get_Aspect_Id (Chars (Ident));
5251
5252    begin
5253       --  On entry to this procedure, Entity (Ident) contains a copy of the
5254       --  original expression from the aspect, saved for this purpose.
5255
5256       --  On exit from this procedure Entity (Ident) is unchanged, still
5257       --  containing that copy, but Expression (Ident) is a preanalyzed copy
5258       --  of the expression, preanalyzed just after the freeze point.
5259
5260       --  Make a copy of the expression to be preanalyed
5261
5262       Set_Expression (ASN, New_Copy_Tree (Entity (Ident)));
5263
5264       --  Find type for preanalyze call
5265
5266       case A_Id is
5267
5268          --  No_Aspect should be impossible
5269
5270          when No_Aspect =>
5271             raise Program_Error;
5272
5273          --  Library unit aspects should be impossible (never delayed)
5274
5275          when Library_Unit_Aspects =>
5276             raise Program_Error;
5277
5278          --  Aspects taking an optional boolean argument. Should be impossible
5279          --  since these are never delayed.
5280
5281          when Boolean_Aspects =>
5282             raise Program_Error;
5283
5284          --  Default_Value is resolved with the type entity in question
5285
5286          when Aspect_Default_Value =>
5287             T := Entity (ASN);
5288
5289          --  Default_Component_Value is resolved with the component type
5290
5291          when Aspect_Default_Component_Value =>
5292             T := Component_Type (Entity (ASN));
5293
5294          --  Aspects corresponding to attribute definition clauses
5295
5296          when Aspect_Address =>
5297             T := RTE (RE_Address);
5298
5299          when Aspect_Bit_Order =>
5300             T := RTE (RE_Bit_Order);
5301
5302          when Aspect_External_Tag =>
5303             T := Standard_String;
5304
5305          when Aspect_Storage_Pool =>
5306             T := Class_Wide_Type (RTE (RE_Root_Storage_Pool));
5307
5308          when
5309               Aspect_Alignment      |
5310               Aspect_Component_Size |
5311               Aspect_Machine_Radix  |
5312               Aspect_Object_Size    |
5313               Aspect_Size           |
5314               Aspect_Storage_Size   |
5315               Aspect_Stream_Size    |
5316               Aspect_Value_Size     =>
5317             T := Any_Integer;
5318
5319          --  Stream attribute. Special case, the expression is just an entity
5320          --  that does not need any resolution, so just analyze.
5321
5322          when Aspect_Input  |
5323               Aspect_Output |
5324               Aspect_Read   |
5325               Aspect_Write  =>
5326             Analyze (Expression (ASN));
5327             return;
5328
5329          --  Suppress/Unsupress/Warnings should never be delayed
5330
5331          when Aspect_Suppress   |
5332               Aspect_Unsuppress |
5333               Aspect_Warnings   =>
5334             raise Program_Error;
5335
5336          --  Pre/Post/Invariant/Predicate take boolean expressions
5337
5338          when Aspect_Dynamic_Predicate |
5339               Aspect_Invariant         |
5340               Aspect_Pre               |
5341               Aspect_Precondition      |
5342               Aspect_Post              |
5343               Aspect_Postcondition     |
5344               Aspect_Predicate         |
5345               Aspect_Static_Predicate  |
5346               Aspect_Type_Invariant    =>
5347             T := Standard_Boolean;
5348       end case;
5349
5350       --  Do the preanalyze call
5351
5352       Preanalyze_Spec_Expression (Expression (ASN), T);
5353    end Check_Aspect_At_Freeze_Point;
5354
5355    -----------------------------------
5356    -- Check_Constant_Address_Clause --
5357    -----------------------------------
5358
5359    procedure Check_Constant_Address_Clause
5360      (Expr  : Node_Id;
5361       U_Ent : Entity_Id)
5362    is
5363       procedure Check_At_Constant_Address (Nod : Node_Id);
5364       --  Checks that the given node N represents a name whose 'Address is
5365       --  constant (in the same sense as OK_Constant_Address_Clause, i.e. the
5366       --  address value is the same at the point of declaration of U_Ent and at
5367       --  the time of elaboration of the address clause.
5368
5369       procedure Check_Expr_Constants (Nod : Node_Id);
5370       --  Checks that Nod meets the requirements for a constant address clause
5371       --  in the sense of the enclosing procedure.
5372
5373       procedure Check_List_Constants (Lst : List_Id);
5374       --  Check that all elements of list Lst meet the requirements for a
5375       --  constant address clause in the sense of the enclosing procedure.
5376
5377       -------------------------------
5378       -- Check_At_Constant_Address --
5379       -------------------------------
5380
5381       procedure Check_At_Constant_Address (Nod : Node_Id) is
5382       begin
5383          if Is_Entity_Name (Nod) then
5384             if Present (Address_Clause (Entity ((Nod)))) then
5385                Error_Msg_NE
5386                  ("invalid address clause for initialized object &!",
5387                            Nod, U_Ent);
5388                Error_Msg_NE
5389                  ("address for& cannot" &
5390                     " depend on another address clause! (RM 13.1(22))!",
5391                   Nod, U_Ent);
5392
5393             elsif In_Same_Source_Unit (Entity (Nod), U_Ent)
5394               and then Sloc (U_Ent) < Sloc (Entity (Nod))
5395             then
5396                Error_Msg_NE
5397                  ("invalid address clause for initialized object &!",
5398                   Nod, U_Ent);
5399                Error_Msg_Node_2 := U_Ent;
5400                Error_Msg_NE
5401                  ("\& must be defined before & (RM 13.1(22))!",
5402                   Nod, Entity (Nod));
5403             end if;
5404
5405          elsif Nkind (Nod) = N_Selected_Component then
5406             declare
5407                T : constant Entity_Id := Etype (Prefix (Nod));
5408
5409             begin
5410                if (Is_Record_Type (T)
5411                     and then Has_Discriminants (T))
5412                  or else
5413                   (Is_Access_Type (T)
5414                      and then Is_Record_Type (Designated_Type (T))
5415                      and then Has_Discriminants (Designated_Type (T)))
5416                then
5417                   Error_Msg_NE
5418                     ("invalid address clause for initialized object &!",
5419                      Nod, U_Ent);
5420                   Error_Msg_N
5421                     ("\address cannot depend on component" &
5422                      " of discriminated record (RM 13.1(22))!",
5423                      Nod);
5424                else
5425                   Check_At_Constant_Address (Prefix (Nod));
5426                end if;
5427             end;
5428
5429          elsif Nkind (Nod) = N_Indexed_Component then
5430             Check_At_Constant_Address (Prefix (Nod));
5431             Check_List_Constants (Expressions (Nod));
5432
5433          else
5434             Check_Expr_Constants (Nod);
5435          end if;
5436       end Check_At_Constant_Address;
5437
5438       --------------------------
5439       -- Check_Expr_Constants --
5440       --------------------------
5441
5442       procedure Check_Expr_Constants (Nod : Node_Id) is
5443          Loc_U_Ent : constant Source_Ptr := Sloc (U_Ent);
5444          Ent       : Entity_Id           := Empty;
5445
5446       begin
5447          if Nkind (Nod) in N_Has_Etype
5448            and then Etype (Nod) = Any_Type
5449          then
5450             return;
5451          end if;
5452
5453          case Nkind (Nod) is
5454             when N_Empty | N_Error =>
5455                return;
5456
5457             when N_Identifier | N_Expanded_Name =>
5458                Ent := Entity (Nod);
5459
5460                --  We need to look at the original node if it is different
5461                --  from the node, since we may have rewritten things and
5462                --  substituted an identifier representing the rewrite.
5463
5464                if Original_Node (Nod) /= Nod then
5465                   Check_Expr_Constants (Original_Node (Nod));
5466
5467                   --  If the node is an object declaration without initial
5468                   --  value, some code has been expanded, and the expression
5469                   --  is not constant, even if the constituents might be
5470                   --  acceptable, as in A'Address + offset.
5471
5472                   if Ekind (Ent) = E_Variable
5473                     and then
5474                       Nkind (Declaration_Node (Ent)) = N_Object_Declaration
5475                     and then
5476                       No (Expression (Declaration_Node (Ent)))
5477                   then
5478                      Error_Msg_NE
5479                        ("invalid address clause for initialized object &!",
5480                         Nod, U_Ent);
5481
5482                   --  If entity is constant, it may be the result of expanding
5483                   --  a check. We must verify that its declaration appears
5484                   --  before the object in question, else we also reject the
5485                   --  address clause.
5486
5487                   elsif Ekind (Ent) = E_Constant
5488                     and then In_Same_Source_Unit (Ent, U_Ent)
5489                     and then Sloc (Ent) > Loc_U_Ent
5490                   then
5491                      Error_Msg_NE
5492                        ("invalid address clause for initialized object &!",
5493                         Nod, U_Ent);
5494                   end if;
5495
5496                   return;
5497                end if;
5498
5499                --  Otherwise look at the identifier and see if it is OK
5500
5501                if Ekind_In (Ent, E_Named_Integer, E_Named_Real)
5502                  or else Is_Type (Ent)
5503                then
5504                   return;
5505
5506                elsif
5507                   Ekind (Ent) = E_Constant
5508                     or else
5509                   Ekind (Ent) = E_In_Parameter
5510                then
5511                   --  This is the case where we must have Ent defined before
5512                   --  U_Ent. Clearly if they are in different units this
5513                   --  requirement is met since the unit containing Ent is
5514                   --  already processed.
5515
5516                   if not In_Same_Source_Unit (Ent, U_Ent) then
5517                      return;
5518
5519                   --  Otherwise location of Ent must be before the location
5520                   --  of U_Ent, that's what prior defined means.
5521
5522                   elsif Sloc (Ent) < Loc_U_Ent then
5523                      return;
5524
5525                   else
5526                      Error_Msg_NE
5527                        ("invalid address clause for initialized object &!",
5528                         Nod, U_Ent);
5529                      Error_Msg_Node_2 := U_Ent;
5530                      Error_Msg_NE
5531                        ("\& must be defined before & (RM 13.1(22))!",
5532                         Nod, Ent);
5533                   end if;
5534
5535                elsif Nkind (Original_Node (Nod)) = N_Function_Call then
5536                   Check_Expr_Constants (Original_Node (Nod));
5537
5538                else
5539                   Error_Msg_NE
5540                     ("invalid address clause for initialized object &!",
5541                      Nod, U_Ent);
5542
5543                   if Comes_From_Source (Ent) then
5544                      Error_Msg_NE
5545                        ("\reference to variable& not allowed"
5546                           & " (RM 13.1(22))!", Nod, Ent);
5547                   else
5548                      Error_Msg_N
5549                        ("non-static expression not allowed"
5550                           & " (RM 13.1(22))!", Nod);
5551                   end if;
5552                end if;
5553
5554             when N_Integer_Literal   =>
5555
5556                --  If this is a rewritten unchecked conversion, in a system
5557                --  where Address is an integer type, always use the base type
5558                --  for a literal value. This is user-friendly and prevents
5559                --  order-of-elaboration issues with instances of unchecked
5560                --  conversion.
5561
5562                if Nkind (Original_Node (Nod)) = N_Function_Call then
5563                   Set_Etype (Nod, Base_Type (Etype (Nod)));
5564                end if;
5565
5566             when N_Real_Literal      |
5567                  N_String_Literal    |
5568                  N_Character_Literal =>
5569                return;
5570
5571             when N_Range =>
5572                Check_Expr_Constants (Low_Bound (Nod));
5573                Check_Expr_Constants (High_Bound (Nod));
5574
5575             when N_Explicit_Dereference =>
5576                Check_Expr_Constants (Prefix (Nod));
5577
5578             when N_Indexed_Component =>
5579                Check_Expr_Constants (Prefix (Nod));
5580                Check_List_Constants (Expressions (Nod));
5581
5582             when N_Slice =>
5583                Check_Expr_Constants (Prefix (Nod));
5584                Check_Expr_Constants (Discrete_Range (Nod));
5585
5586             when N_Selected_Component =>
5587                Check_Expr_Constants (Prefix (Nod));
5588
5589             when N_Attribute_Reference =>
5590                if Attribute_Name (Nod) = Name_Address
5591                    or else
5592                   Attribute_Name (Nod) = Name_Access
5593                     or else
5594                   Attribute_Name (Nod) = Name_Unchecked_Access
5595                     or else
5596                   Attribute_Name (Nod) = Name_Unrestricted_Access
5597                then
5598                   Check_At_Constant_Address (Prefix (Nod));
5599
5600                else
5601                   Check_Expr_Constants (Prefix (Nod));
5602                   Check_List_Constants (Expressions (Nod));
5603                end if;
5604
5605             when N_Aggregate =>
5606                Check_List_Constants (Component_Associations (Nod));
5607                Check_List_Constants (Expressions (Nod));
5608
5609             when N_Component_Association =>
5610                Check_Expr_Constants (Expression (Nod));
5611
5612             when N_Extension_Aggregate =>
5613                Check_Expr_Constants (Ancestor_Part (Nod));
5614                Check_List_Constants (Component_Associations (Nod));
5615                Check_List_Constants (Expressions (Nod));
5616
5617             when N_Null =>
5618                return;
5619
5620             when N_Binary_Op | N_Short_Circuit | N_Membership_Test =>
5621                Check_Expr_Constants (Left_Opnd (Nod));
5622                Check_Expr_Constants (Right_Opnd (Nod));
5623
5624             when N_Unary_Op =>
5625                Check_Expr_Constants (Right_Opnd (Nod));
5626
5627             when N_Type_Conversion           |
5628                  N_Qualified_Expression      |
5629                  N_Allocator                 =>
5630                Check_Expr_Constants (Expression (Nod));
5631
5632             when N_Unchecked_Type_Conversion =>
5633                Check_Expr_Constants (Expression (Nod));
5634
5635                --  If this is a rewritten unchecked conversion, subtypes in
5636                --  this node are those created within the instance. To avoid
5637                --  order of elaboration issues, replace them with their base
5638                --  types. Note that address clauses can cause order of
5639                --  elaboration problems because they are elaborated by the
5640                --  back-end at the point of definition, and may mention
5641                --  entities declared in between (as long as everything is
5642                --  static). It is user-friendly to allow unchecked conversions
5643                --  in this context.
5644
5645                if Nkind (Original_Node (Nod)) = N_Function_Call then
5646                   Set_Etype (Expression (Nod),
5647                     Base_Type (Etype (Expression (Nod))));
5648                   Set_Etype (Nod, Base_Type (Etype (Nod)));
5649                end if;
5650
5651             when N_Function_Call =>
5652                if not Is_Pure (Entity (Name (Nod))) then
5653                   Error_Msg_NE
5654                     ("invalid address clause for initialized object &!",
5655                      Nod, U_Ent);
5656
5657                   Error_Msg_NE
5658                     ("\function & is not pure (RM 13.1(22))!",
5659                      Nod, Entity (Name (Nod)));
5660
5661                else
5662                   Check_List_Constants (Parameter_Associations (Nod));
5663                end if;
5664
5665             when N_Parameter_Association =>
5666                Check_Expr_Constants (Explicit_Actual_Parameter (Nod));
5667
5668             when others =>
5669                Error_Msg_NE
5670                  ("invalid address clause for initialized object &!",
5671                   Nod, U_Ent);
5672                Error_Msg_NE
5673                  ("\must be constant defined before& (RM 13.1(22))!",
5674                   Nod, U_Ent);
5675          end case;
5676       end Check_Expr_Constants;
5677
5678       --------------------------
5679       -- Check_List_Constants --
5680       --------------------------
5681
5682       procedure Check_List_Constants (Lst : List_Id) is
5683          Nod1 : Node_Id;
5684
5685       begin
5686          if Present (Lst) then
5687             Nod1 := First (Lst);
5688             while Present (Nod1) loop
5689                Check_Expr_Constants (Nod1);
5690                Next (Nod1);
5691             end loop;
5692          end if;
5693       end Check_List_Constants;
5694
5695    --  Start of processing for Check_Constant_Address_Clause
5696
5697    begin
5698       --  If rep_clauses are to be ignored, no need for legality checks. In
5699       --  particular, no need to pester user about rep clauses that violate
5700       --  the rule on constant addresses, given that these clauses will be
5701       --  removed by Freeze before they reach the back end.
5702
5703       if not Ignore_Rep_Clauses then
5704          Check_Expr_Constants (Expr);
5705       end if;
5706    end Check_Constant_Address_Clause;
5707
5708    ----------------------------------------
5709    -- Check_Record_Representation_Clause --
5710    ----------------------------------------
5711
5712    procedure Check_Record_Representation_Clause (N : Node_Id) is
5713       Loc     : constant Source_Ptr := Sloc (N);
5714       Ident   : constant Node_Id    := Identifier (N);
5715       Rectype : Entity_Id;
5716       Fent    : Entity_Id;
5717       CC      : Node_Id;
5718       Fbit    : Uint;
5719       Lbit    : Uint;
5720       Hbit    : Uint := Uint_0;
5721       Comp    : Entity_Id;
5722       Pcomp   : Entity_Id;
5723
5724       Max_Bit_So_Far : Uint;
5725       --  Records the maximum bit position so far. If all field positions
5726       --  are monotonically increasing, then we can skip the circuit for
5727       --  checking for overlap, since no overlap is possible.
5728
5729       Tagged_Parent : Entity_Id := Empty;
5730       --  This is set in the case of a derived tagged type for which we have
5731       --  Is_Fully_Repped_Tagged_Type True (indicating that all components are
5732       --  positioned by record representation clauses). In this case we must
5733       --  check for overlap between components of this tagged type, and the
5734       --  components of its parent. Tagged_Parent will point to this parent
5735       --  type. For all other cases Tagged_Parent is left set to Empty.
5736
5737       Parent_Last_Bit : Uint;
5738       --  Relevant only if Tagged_Parent is set, Parent_Last_Bit indicates the
5739       --  last bit position for any field in the parent type. We only need to
5740       --  check overlap for fields starting below this point.
5741
5742       Overlap_Check_Required : Boolean;
5743       --  Used to keep track of whether or not an overlap check is required
5744
5745       Overlap_Detected : Boolean := False;
5746       --  Set True if an overlap is detected
5747
5748       Ccount : Natural := 0;
5749       --  Number of component clauses in record rep clause
5750
5751       procedure Check_Component_Overlap (C1_Ent, C2_Ent : Entity_Id);
5752       --  Given two entities for record components or discriminants, checks
5753       --  if they have overlapping component clauses and issues errors if so.
5754
5755       procedure Find_Component;
5756       --  Finds component entity corresponding to current component clause (in
5757       --  CC), and sets Comp to the entity, and Fbit/Lbit to the zero origin
5758       --  start/stop bits for the field. If there is no matching component or
5759       --  if the matching component does not have a component clause, then
5760       --  that's an error and Comp is set to Empty, but no error message is
5761       --  issued, since the message was already given. Comp is also set to
5762       --  Empty if the current "component clause" is in fact a pragma.
5763
5764       -----------------------------
5765       -- Check_Component_Overlap --
5766       -----------------------------
5767
5768       procedure Check_Component_Overlap (C1_Ent, C2_Ent : Entity_Id) is
5769          CC1 : constant Node_Id := Component_Clause (C1_Ent);
5770          CC2 : constant Node_Id := Component_Clause (C2_Ent);
5771
5772       begin
5773          if Present (CC1) and then Present (CC2) then
5774
5775             --  Exclude odd case where we have two tag fields in the same
5776             --  record, both at location zero. This seems a bit strange, but
5777             --  it seems to happen in some circumstances, perhaps on an error.
5778
5779             if Chars (C1_Ent) = Name_uTag
5780                  and then
5781                Chars (C2_Ent) = Name_uTag
5782             then
5783                return;
5784             end if;
5785
5786             --  Here we check if the two fields overlap
5787
5788             declare
5789                S1 : constant Uint := Component_Bit_Offset (C1_Ent);
5790                S2 : constant Uint := Component_Bit_Offset (C2_Ent);
5791                E1 : constant Uint := S1 + Esize (C1_Ent);
5792                E2 : constant Uint := S2 + Esize (C2_Ent);
5793
5794             begin
5795                if E2 <= S1 or else E1 <= S2 then
5796                   null;
5797                else
5798                   Error_Msg_Node_2 := Component_Name (CC2);
5799                   Error_Msg_Sloc := Sloc (Error_Msg_Node_2);
5800                   Error_Msg_Node_1 := Component_Name (CC1);
5801                   Error_Msg_N
5802                     ("component& overlaps & #", Component_Name (CC1));
5803                   Overlap_Detected := True;
5804                end if;
5805             end;
5806          end if;
5807       end Check_Component_Overlap;
5808
5809       --------------------
5810       -- Find_Component --
5811       --------------------
5812
5813       procedure Find_Component is
5814
5815          procedure Search_Component (R : Entity_Id);
5816          --  Search components of R for a match. If found, Comp is set.
5817
5818          ----------------------
5819          -- Search_Component --
5820          ----------------------
5821
5822          procedure Search_Component (R : Entity_Id) is
5823          begin
5824             Comp := First_Component_Or_Discriminant (R);
5825             while Present (Comp) loop
5826
5827                --  Ignore error of attribute name for component name (we
5828                --  already gave an error message for this, so no need to
5829                --  complain here)
5830
5831                if Nkind (Component_Name (CC)) = N_Attribute_Reference then
5832                   null;
5833                else
5834                   exit when Chars (Comp) = Chars (Component_Name (CC));
5835                end if;
5836
5837                Next_Component_Or_Discriminant (Comp);
5838             end loop;
5839          end Search_Component;
5840
5841       --  Start of processing for Find_Component
5842
5843       begin
5844          --  Return with Comp set to Empty if we have a pragma
5845
5846          if Nkind (CC) = N_Pragma then
5847             Comp := Empty;
5848             return;
5849          end if;
5850
5851          --  Search current record for matching component
5852
5853          Search_Component (Rectype);
5854
5855          --  If not found, maybe component of base type that is absent from
5856          --  statically constrained first subtype.
5857
5858          if No (Comp) then
5859             Search_Component (Base_Type (Rectype));
5860          end if;
5861
5862          --  If no component, or the component does not reference the component
5863          --  clause in question, then there was some previous error for which
5864          --  we already gave a message, so just return with Comp Empty.
5865
5866          if No (Comp)
5867            or else Component_Clause (Comp) /= CC
5868          then
5869             Comp := Empty;
5870
5871          --  Normal case where we have a component clause
5872
5873          else
5874             Fbit := Component_Bit_Offset (Comp);
5875             Lbit := Fbit + Esize (Comp) - 1;
5876          end if;
5877       end Find_Component;
5878
5879    --  Start of processing for Check_Record_Representation_Clause
5880
5881    begin
5882       Find_Type (Ident);
5883       Rectype := Entity (Ident);
5884
5885       if Rectype = Any_Type then
5886          return;
5887       else
5888          Rectype := Underlying_Type (Rectype);
5889       end if;
5890
5891       --  See if we have a fully repped derived tagged type
5892
5893       declare
5894          PS : constant Entity_Id := Parent_Subtype (Rectype);
5895
5896       begin
5897          if Present (PS) and then Is_Fully_Repped_Tagged_Type (PS) then
5898             Tagged_Parent := PS;
5899
5900             --  Find maximum bit of any component of the parent type
5901
5902             Parent_Last_Bit := UI_From_Int (System_Address_Size - 1);
5903             Pcomp := First_Entity (Tagged_Parent);
5904             while Present (Pcomp) loop
5905                if Ekind_In (Pcomp, E_Discriminant, E_Component) then
5906                   if Component_Bit_Offset (Pcomp) /= No_Uint
5907                     and then Known_Static_Esize (Pcomp)
5908                   then
5909                      Parent_Last_Bit :=
5910                        UI_Max
5911                          (Parent_Last_Bit,
5912                           Component_Bit_Offset (Pcomp) + Esize (Pcomp) - 1);
5913                   end if;
5914
5915                   Next_Entity (Pcomp);
5916                end if;
5917             end loop;
5918          end if;
5919       end;
5920
5921       --  All done if no component clauses
5922
5923       CC := First (Component_Clauses (N));
5924
5925       if No (CC) then
5926          return;
5927       end if;
5928
5929       --  If a tag is present, then create a component clause that places it
5930       --  at the start of the record (otherwise gigi may place it after other
5931       --  fields that have rep clauses).
5932
5933       Fent := First_Entity (Rectype);
5934
5935       if Nkind (Fent) = N_Defining_Identifier
5936         and then Chars (Fent) = Name_uTag
5937       then
5938          Set_Component_Bit_Offset    (Fent, Uint_0);
5939          Set_Normalized_Position     (Fent, Uint_0);
5940          Set_Normalized_First_Bit    (Fent, Uint_0);
5941          Set_Normalized_Position_Max (Fent, Uint_0);
5942          Init_Esize                  (Fent, System_Address_Size);
5943
5944          Set_Component_Clause (Fent,
5945            Make_Component_Clause (Loc,
5946              Component_Name => Make_Identifier (Loc, Name_uTag),
5947
5948              Position  => Make_Integer_Literal (Loc, Uint_0),
5949              First_Bit => Make_Integer_Literal (Loc, Uint_0),
5950              Last_Bit  =>
5951                Make_Integer_Literal (Loc,
5952                  UI_From_Int (System_Address_Size))));
5953
5954          Ccount := Ccount + 1;
5955       end if;
5956
5957       Max_Bit_So_Far := Uint_Minus_1;
5958       Overlap_Check_Required := False;
5959
5960       --  Process the component clauses
5961
5962       while Present (CC) loop
5963          Find_Component;
5964
5965          if Present (Comp) then
5966             Ccount := Ccount + 1;
5967
5968             --  We need a full overlap check if record positions non-monotonic
5969
5970             if Fbit <= Max_Bit_So_Far then
5971                Overlap_Check_Required := True;
5972             end if;
5973
5974             Max_Bit_So_Far := Lbit;
5975
5976             --  Check bit position out of range of specified size
5977
5978             if Has_Size_Clause (Rectype)
5979               and then Esize (Rectype) <= Lbit
5980             then
5981                Error_Msg_N
5982                  ("bit number out of range of specified size",
5983                   Last_Bit (CC));
5984
5985                --  Check for overlap with tag field
5986
5987             else
5988                if Is_Tagged_Type (Rectype)
5989                  and then Fbit < System_Address_Size
5990                then
5991                   Error_Msg_NE
5992                     ("component overlaps tag field of&",
5993                      Component_Name (CC), Rectype);
5994                   Overlap_Detected := True;
5995                end if;
5996
5997                if Hbit < Lbit then
5998                   Hbit := Lbit;
5999                end if;
6000             end if;
6001
6002             --  Check parent overlap if component might overlap parent field
6003
6004             if Present (Tagged_Parent)
6005               and then Fbit <= Parent_Last_Bit
6006             then
6007                Pcomp := First_Component_Or_Discriminant (Tagged_Parent);
6008                while Present (Pcomp) loop
6009                   if not Is_Tag (Pcomp)
6010                     and then Chars (Pcomp) /= Name_uParent
6011                   then
6012                      Check_Component_Overlap (Comp, Pcomp);
6013                   end if;
6014
6015                   Next_Component_Or_Discriminant (Pcomp);
6016                end loop;
6017             end if;
6018          end if;
6019
6020          Next (CC);
6021       end loop;
6022
6023       --  Now that we have processed all the component clauses, check for
6024       --  overlap. We have to leave this till last, since the components can
6025       --  appear in any arbitrary order in the representation clause.
6026
6027       --  We do not need this check if all specified ranges were monotonic,
6028       --  as recorded by Overlap_Check_Required being False at this stage.
6029
6030       --  This first section checks if there are any overlapping entries at
6031       --  all. It does this by sorting all entries and then seeing if there are
6032       --  any overlaps. If there are none, then that is decisive, but if there
6033       --  are overlaps, they may still be OK (they may result from fields in
6034       --  different variants).
6035
6036       if Overlap_Check_Required then
6037          Overlap_Check1 : declare
6038
6039             OC_Fbit : array (0 .. Ccount) of Uint;
6040             --  First-bit values for component clauses, the value is the offset
6041             --  of the first bit of the field from start of record. The zero
6042             --  entry is for use in sorting.
6043
6044             OC_Lbit : array (0 .. Ccount) of Uint;
6045             --  Last-bit values for component clauses, the value is the offset
6046             --  of the last bit of the field from start of record. The zero
6047             --  entry is for use in sorting.
6048
6049             OC_Count : Natural := 0;
6050             --  Count of entries in OC_Fbit and OC_Lbit
6051
6052             function OC_Lt (Op1, Op2 : Natural) return Boolean;
6053             --  Compare routine for Sort
6054
6055             procedure OC_Move (From : Natural; To : Natural);
6056             --  Move routine for Sort
6057
6058             package Sorting is new GNAT.Heap_Sort_G (OC_Move, OC_Lt);
6059
6060             -----------
6061             -- OC_Lt --
6062             -----------
6063
6064             function OC_Lt (Op1, Op2 : Natural) return Boolean is
6065             begin
6066                return OC_Fbit (Op1) < OC_Fbit (Op2);
6067             end OC_Lt;
6068
6069             -------------
6070             -- OC_Move --
6071             -------------
6072
6073             procedure OC_Move (From : Natural; To : Natural) is
6074             begin
6075                OC_Fbit (To) := OC_Fbit (From);
6076                OC_Lbit (To) := OC_Lbit (From);
6077             end OC_Move;
6078
6079             --  Start of processing for Overlap_Check
6080
6081          begin
6082             CC := First (Component_Clauses (N));
6083             while Present (CC) loop
6084
6085                --  Exclude component clause already marked in error
6086
6087                if not Error_Posted (CC) then
6088                   Find_Component;
6089
6090                   if Present (Comp) then
6091                      OC_Count := OC_Count + 1;
6092                      OC_Fbit (OC_Count) := Fbit;
6093                      OC_Lbit (OC_Count) := Lbit;
6094                   end if;
6095                end if;
6096
6097                Next (CC);
6098             end loop;
6099
6100             Sorting.Sort (OC_Count);
6101
6102             Overlap_Check_Required := False;
6103             for J in 1 .. OC_Count - 1 loop
6104                if OC_Lbit (J) >= OC_Fbit (J + 1) then
6105                   Overlap_Check_Required := True;
6106                   exit;
6107                end if;
6108             end loop;
6109          end Overlap_Check1;
6110       end if;
6111
6112       --  If Overlap_Check_Required is still True, then we have to do the full
6113       --  scale overlap check, since we have at least two fields that do
6114       --  overlap, and we need to know if that is OK since they are in
6115       --  different variant, or whether we have a definite problem.
6116
6117       if Overlap_Check_Required then
6118          Overlap_Check2 : declare
6119             C1_Ent, C2_Ent : Entity_Id;
6120             --  Entities of components being checked for overlap
6121
6122             Clist : Node_Id;
6123             --  Component_List node whose Component_Items are being checked
6124
6125             Citem : Node_Id;
6126             --  Component declaration for component being checked
6127
6128          begin
6129             C1_Ent := First_Entity (Base_Type (Rectype));
6130
6131             --  Loop through all components in record. For each component check
6132             --  for overlap with any of the preceding elements on the component
6133             --  list containing the component and also, if the component is in
6134             --  a variant, check against components outside the case structure.
6135             --  This latter test is repeated recursively up the variant tree.
6136
6137             Main_Component_Loop : while Present (C1_Ent) loop
6138                if not Ekind_In (C1_Ent, E_Component, E_Discriminant) then
6139                   goto Continue_Main_Component_Loop;
6140                end if;
6141
6142                --  Skip overlap check if entity has no declaration node. This
6143                --  happens with discriminants in constrained derived types.
6144                --  Possibly we are missing some checks as a result, but that
6145                --  does not seem terribly serious.
6146
6147                if No (Declaration_Node (C1_Ent)) then
6148                   goto Continue_Main_Component_Loop;
6149                end if;
6150
6151                Clist := Parent (List_Containing (Declaration_Node (C1_Ent)));
6152
6153                --  Loop through component lists that need checking. Check the
6154                --  current component list and all lists in variants above us.
6155
6156                Component_List_Loop : loop
6157
6158                   --  If derived type definition, go to full declaration
6159                   --  If at outer level, check discriminants if there are any.
6160
6161                   if Nkind (Clist) = N_Derived_Type_Definition then
6162                      Clist := Parent (Clist);
6163                   end if;
6164
6165                   --  Outer level of record definition, check discriminants
6166
6167                   if Nkind_In (Clist, N_Full_Type_Declaration,
6168                                N_Private_Type_Declaration)
6169                   then
6170                      if Has_Discriminants (Defining_Identifier (Clist)) then
6171                         C2_Ent :=
6172                           First_Discriminant (Defining_Identifier (Clist));
6173                         while Present (C2_Ent) loop
6174                            exit when C1_Ent = C2_Ent;
6175                            Check_Component_Overlap (C1_Ent, C2_Ent);
6176                            Next_Discriminant (C2_Ent);
6177                         end loop;
6178                      end if;
6179
6180                      --  Record extension case
6181
6182                   elsif Nkind (Clist) = N_Derived_Type_Definition then
6183                      Clist := Empty;
6184
6185                      --  Otherwise check one component list
6186
6187                   else
6188                      Citem := First (Component_Items (Clist));
6189                      while Present (Citem) loop
6190                         if Nkind (Citem) = N_Component_Declaration then
6191                            C2_Ent := Defining_Identifier (Citem);
6192                            exit when C1_Ent = C2_Ent;
6193                            Check_Component_Overlap (C1_Ent, C2_Ent);
6194                         end if;
6195
6196                         Next (Citem);
6197                      end loop;
6198                   end if;
6199
6200                   --  Check for variants above us (the parent of the Clist can
6201                   --  be a variant, in which case its parent is a variant part,
6202                   --  and the parent of the variant part is a component list
6203                   --  whose components must all be checked against the current
6204                   --  component for overlap).
6205
6206                   if Nkind (Parent (Clist)) = N_Variant then
6207                      Clist := Parent (Parent (Parent (Clist)));
6208
6209                      --  Check for possible discriminant part in record, this
6210                      --  is treated essentially as another level in the
6211                      --  recursion. For this case the parent of the component
6212                      --  list is the record definition, and its parent is the
6213                      --  full type declaration containing the discriminant
6214                      --  specifications.
6215
6216                   elsif Nkind (Parent (Clist)) = N_Record_Definition then
6217                      Clist := Parent (Parent ((Clist)));
6218
6219                      --  If neither of these two cases, we are at the top of
6220                      --  the tree.
6221
6222                   else
6223                      exit Component_List_Loop;
6224                   end if;
6225                end loop Component_List_Loop;
6226
6227                <<Continue_Main_Component_Loop>>
6228                Next_Entity (C1_Ent);
6229
6230             end loop Main_Component_Loop;
6231          end Overlap_Check2;
6232       end if;
6233
6234       --  The following circuit deals with warning on record holes (gaps). We
6235       --  skip this check if overlap was detected, since it makes sense for the
6236       --  programmer to fix this illegality before worrying about warnings.
6237
6238       if not Overlap_Detected and Warn_On_Record_Holes then
6239          Record_Hole_Check : declare
6240             Decl : constant Node_Id := Declaration_Node (Base_Type (Rectype));
6241             --  Full declaration of record type
6242
6243             procedure Check_Component_List
6244               (CL   : Node_Id;
6245                Sbit : Uint;
6246                DS   : List_Id);
6247             --  Check component list CL for holes. The starting bit should be
6248             --  Sbit. which is zero for the main record component list and set
6249             --  appropriately for recursive calls for variants. DS is set to
6250             --  a list of discriminant specifications to be included in the
6251             --  consideration of components. It is No_List if none to consider.
6252
6253             --------------------------
6254             -- Check_Component_List --
6255             --------------------------
6256
6257             procedure Check_Component_List
6258               (CL   : Node_Id;
6259                Sbit : Uint;
6260                DS   : List_Id)
6261             is
6262                Compl : Integer;
6263
6264             begin
6265                Compl := Integer (List_Length (Component_Items (CL)));
6266
6267                if DS /= No_List then
6268                   Compl := Compl + Integer (List_Length (DS));
6269                end if;
6270
6271                declare
6272                   Comps : array (Natural range 0 .. Compl) of Entity_Id;
6273                   --  Gather components (zero entry is for sort routine)
6274
6275                   Ncomps : Natural := 0;
6276                   --  Number of entries stored in Comps (starting at Comps (1))
6277
6278                   Citem : Node_Id;
6279                   --  One component item or discriminant specification
6280
6281                   Nbit  : Uint;
6282                   --  Starting bit for next component
6283
6284                   CEnt  : Entity_Id;
6285                   --  Component entity
6286
6287                   Variant : Node_Id;
6288                   --  One variant
6289
6290                   function Lt (Op1, Op2 : Natural) return Boolean;
6291                   --  Compare routine for Sort
6292
6293                   procedure Move (From : Natural; To : Natural);
6294                   --  Move routine for Sort
6295
6296                   package Sorting is new GNAT.Heap_Sort_G (Move, Lt);
6297
6298                   --------
6299                   -- Lt --
6300                   --------
6301
6302                   function Lt (Op1, Op2 : Natural) return Boolean is
6303                   begin
6304                      return Component_Bit_Offset (Comps (Op1))
6305                        <
6306                        Component_Bit_Offset (Comps (Op2));
6307                   end Lt;
6308
6309                   ----------
6310                   -- Move --
6311                   ----------
6312
6313                   procedure Move (From : Natural; To : Natural) is
6314                   begin
6315                      Comps (To) := Comps (From);
6316                   end Move;
6317
6318                begin
6319                   --  Gather discriminants into Comp
6320
6321                   if DS /= No_List then
6322                      Citem := First (DS);
6323                      while Present (Citem) loop
6324                         if Nkind (Citem) = N_Discriminant_Specification then
6325                            declare
6326                               Ent : constant Entity_Id :=
6327                                       Defining_Identifier (Citem);
6328                            begin
6329                               if Ekind (Ent) = E_Discriminant then
6330                                  Ncomps := Ncomps + 1;
6331                                  Comps (Ncomps) := Ent;
6332                               end if;
6333                            end;
6334                         end if;
6335
6336                         Next (Citem);
6337                      end loop;
6338                   end if;
6339
6340                   --  Gather component entities into Comp
6341
6342                   Citem := First (Component_Items (CL));
6343                   while Present (Citem) loop
6344                      if Nkind (Citem) = N_Component_Declaration then
6345                         Ncomps := Ncomps + 1;
6346                         Comps (Ncomps) := Defining_Identifier (Citem);
6347                      end if;
6348
6349                      Next (Citem);
6350                   end loop;
6351
6352                   --  Now sort the component entities based on the first bit.
6353                   --  Note we already know there are no overlapping components.
6354
6355                   Sorting.Sort (Ncomps);
6356
6357                   --  Loop through entries checking for holes
6358
6359                   Nbit := Sbit;
6360                   for J in 1 .. Ncomps loop
6361                      CEnt := Comps (J);
6362                      Error_Msg_Uint_1 := Component_Bit_Offset (CEnt) - Nbit;
6363
6364                      if Error_Msg_Uint_1 > 0 then
6365                         Error_Msg_NE
6366                           ("?^-bit gap before component&",
6367                            Component_Name (Component_Clause (CEnt)), CEnt);
6368                      end if;
6369
6370                      Nbit := Component_Bit_Offset (CEnt) + Esize (CEnt);
6371                   end loop;
6372
6373                   --  Process variant parts recursively if present
6374
6375                   if Present (Variant_Part (CL)) then
6376                      Variant := First (Variants (Variant_Part (CL)));
6377                      while Present (Variant) loop
6378                         Check_Component_List
6379                           (Component_List (Variant), Nbit, No_List);
6380                         Next (Variant);
6381                      end loop;
6382                   end if;
6383                end;
6384             end Check_Component_List;
6385
6386          --  Start of processing for Record_Hole_Check
6387
6388          begin
6389             declare
6390                Sbit : Uint;
6391
6392             begin
6393                if Is_Tagged_Type (Rectype) then
6394                   Sbit := UI_From_Int (System_Address_Size);
6395                else
6396                   Sbit := Uint_0;
6397                end if;
6398
6399                if Nkind (Decl) = N_Full_Type_Declaration
6400                  and then Nkind (Type_Definition (Decl)) = N_Record_Definition
6401                then
6402                   Check_Component_List
6403                     (Component_List (Type_Definition (Decl)),
6404                      Sbit,
6405                      Discriminant_Specifications (Decl));
6406                end if;
6407             end;
6408          end Record_Hole_Check;
6409       end if;
6410
6411       --  For records that have component clauses for all components, and whose
6412       --  size is less than or equal to 32, we need to know the size in the
6413       --  front end to activate possible packed array processing where the
6414       --  component type is a record.
6415
6416       --  At this stage Hbit + 1 represents the first unused bit from all the
6417       --  component clauses processed, so if the component clauses are
6418       --  complete, then this is the length of the record.
6419
6420       --  For records longer than System.Storage_Unit, and for those where not
6421       --  all components have component clauses, the back end determines the
6422       --  length (it may for example be appropriate to round up the size
6423       --  to some convenient boundary, based on alignment considerations, etc).
6424
6425       if Unknown_RM_Size (Rectype) and then Hbit + 1 <= 32 then
6426
6427          --  Nothing to do if at least one component has no component clause
6428
6429          Comp := First_Component_Or_Discriminant (Rectype);
6430          while Present (Comp) loop
6431             exit when No (Component_Clause (Comp));
6432             Next_Component_Or_Discriminant (Comp);
6433          end loop;
6434
6435          --  If we fall out of loop, all components have component clauses
6436          --  and so we can set the size to the maximum value.
6437
6438          if No (Comp) then
6439             Set_RM_Size (Rectype, Hbit + 1);
6440          end if;
6441       end if;
6442    end Check_Record_Representation_Clause;
6443
6444    ----------------
6445    -- Check_Size --
6446    ----------------
6447
6448    procedure Check_Size
6449      (N      : Node_Id;
6450       T      : Entity_Id;
6451       Siz    : Uint;
6452       Biased : out Boolean)
6453    is
6454       UT : constant Entity_Id := Underlying_Type (T);
6455       M  : Uint;
6456
6457    begin
6458       Biased := False;
6459
6460       --  Dismiss cases for generic types or types with previous errors
6461
6462       if No (UT)
6463         or else UT = Any_Type
6464         or else Is_Generic_Type (UT)
6465         or else Is_Generic_Type (Root_Type (UT))
6466       then
6467          return;
6468
6469       --  Check case of bit packed array
6470
6471       elsif Is_Array_Type (UT)
6472         and then Known_Static_Component_Size (UT)
6473         and then Is_Bit_Packed_Array (UT)
6474       then
6475          declare
6476             Asiz : Uint;
6477             Indx : Node_Id;
6478             Ityp : Entity_Id;
6479
6480          begin
6481             Asiz := Component_Size (UT);
6482             Indx := First_Index (UT);
6483             loop
6484                Ityp := Etype (Indx);
6485
6486                --  If non-static bound, then we are not in the business of
6487                --  trying to check the length, and indeed an error will be
6488                --  issued elsewhere, since sizes of non-static array types
6489                --  cannot be set implicitly or explicitly.
6490
6491                if not Is_Static_Subtype (Ityp) then
6492                   return;
6493                end if;
6494
6495                --  Otherwise accumulate next dimension
6496
6497                Asiz := Asiz * (Expr_Value (Type_High_Bound (Ityp)) -
6498                                Expr_Value (Type_Low_Bound  (Ityp)) +
6499                                Uint_1);
6500
6501                Next_Index (Indx);
6502                exit when No (Indx);
6503             end loop;
6504
6505             if Asiz <= Siz then
6506                return;
6507             else
6508                Error_Msg_Uint_1 := Asiz;
6509                Error_Msg_NE
6510                  ("size for& too small, minimum allowed is ^", N, T);
6511                Set_Esize   (T, Asiz);
6512                Set_RM_Size (T, Asiz);
6513             end if;
6514          end;
6515
6516       --  All other composite types are ignored
6517
6518       elsif Is_Composite_Type (UT) then
6519          return;
6520
6521       --  For fixed-point types, don't check minimum if type is not frozen,
6522       --  since we don't know all the characteristics of the type that can
6523       --  affect the size (e.g. a specified small) till freeze time.
6524
6525       elsif Is_Fixed_Point_Type (UT)
6526         and then not Is_Frozen (UT)
6527       then
6528          null;
6529
6530       --  Cases for which a minimum check is required
6531
6532       else
6533          --  Ignore if specified size is correct for the type
6534
6535          if Known_Esize (UT) and then Siz = Esize (UT) then
6536             return;
6537          end if;
6538
6539          --  Otherwise get minimum size
6540
6541          M := UI_From_Int (Minimum_Size (UT));
6542
6543          if Siz < M then
6544
6545             --  Size is less than minimum size, but one possibility remains
6546             --  that we can manage with the new size if we bias the type.
6547
6548             M := UI_From_Int (Minimum_Size (UT, Biased => True));
6549
6550             if Siz < M then
6551                Error_Msg_Uint_1 := M;
6552                Error_Msg_NE
6553                  ("size for& too small, minimum allowed is ^", N, T);
6554                Set_Esize (T, M);
6555                Set_RM_Size (T, M);
6556             else
6557                Biased := True;
6558             end if;
6559          end if;
6560       end if;
6561    end Check_Size;
6562
6563    -------------------------
6564    -- Get_Alignment_Value --
6565    -------------------------
6566
6567    function Get_Alignment_Value (Expr : Node_Id) return Uint is
6568       Align : constant Uint := Static_Integer (Expr);
6569
6570    begin
6571       if Align = No_Uint then
6572          return No_Uint;
6573
6574       elsif Align <= 0 then
6575          Error_Msg_N ("alignment value must be positive", Expr);
6576          return No_Uint;
6577
6578       else
6579          for J in Int range 0 .. 64 loop
6580             declare
6581                M : constant Uint := Uint_2 ** J;
6582
6583             begin
6584                exit when M = Align;
6585
6586                if M > Align then
6587                   Error_Msg_N
6588                     ("alignment value must be power of 2", Expr);
6589                   return No_Uint;
6590                end if;
6591             end;
6592          end loop;
6593
6594          return Align;
6595       end if;
6596    end Get_Alignment_Value;
6597
6598    ----------------
6599    -- Initialize --
6600    ----------------
6601
6602    procedure Initialize is
6603    begin
6604       Address_Clause_Checks.Init;
6605       Independence_Checks.Init;
6606       Unchecked_Conversions.Init;
6607    end Initialize;
6608
6609    -------------------------
6610    -- Is_Operational_Item --
6611    -------------------------
6612
6613    function Is_Operational_Item (N : Node_Id) return Boolean is
6614    begin
6615       if Nkind (N) /= N_Attribute_Definition_Clause then
6616          return False;
6617       else
6618          declare
6619             Id    : constant Attribute_Id := Get_Attribute_Id (Chars (N));
6620          begin
6621             return   Id = Attribute_Input
6622               or else Id = Attribute_Output
6623               or else Id = Attribute_Read
6624               or else Id = Attribute_Write
6625               or else Id = Attribute_External_Tag;
6626          end;
6627       end if;
6628    end Is_Operational_Item;
6629
6630    ------------------
6631    -- Minimum_Size --
6632    ------------------
6633
6634    function Minimum_Size
6635      (T      : Entity_Id;
6636       Biased : Boolean := False) return Nat
6637    is
6638       Lo     : Uint    := No_Uint;
6639       Hi     : Uint    := No_Uint;
6640       LoR    : Ureal   := No_Ureal;
6641       HiR    : Ureal   := No_Ureal;
6642       LoSet  : Boolean := False;
6643       HiSet  : Boolean := False;
6644       B      : Uint;
6645       S      : Nat;
6646       Ancest : Entity_Id;
6647       R_Typ  : constant Entity_Id := Root_Type (T);
6648
6649    begin
6650       --  If bad type, return 0
6651
6652       if T = Any_Type then
6653          return 0;
6654
6655       --  For generic types, just return zero. There cannot be any legitimate
6656       --  need to know such a size, but this routine may be called with a
6657       --  generic type as part of normal processing.
6658
6659       elsif Is_Generic_Type (R_Typ)
6660         or else R_Typ = Any_Type
6661       then
6662          return 0;
6663
6664          --  Access types. Normally an access type cannot have a size smaller
6665          --  than the size of System.Address. The exception is on VMS, where
6666          --  we have short and long addresses, and it is possible for an access
6667          --  type to have a short address size (and thus be less than the size
6668          --  of System.Address itself). We simply skip the check for VMS, and
6669          --  leave it to the back end to do the check.
6670
6671       elsif Is_Access_Type (T) then
6672          if OpenVMS_On_Target then
6673             return 0;
6674          else
6675             return System_Address_Size;
6676          end if;
6677
6678       --  Floating-point types
6679
6680       elsif Is_Floating_Point_Type (T) then
6681          return UI_To_Int (Esize (R_Typ));
6682
6683       --  Discrete types
6684
6685       elsif Is_Discrete_Type (T) then
6686
6687          --  The following loop is looking for the nearest compile time known
6688          --  bounds following the ancestor subtype chain. The idea is to find
6689          --  the most restrictive known bounds information.
6690
6691          Ancest := T;
6692          loop
6693             if Ancest = Any_Type or else Etype (Ancest) = Any_Type then
6694                return 0;
6695             end if;
6696
6697             if not LoSet then
6698                if Compile_Time_Known_Value (Type_Low_Bound (Ancest)) then
6699                   Lo := Expr_Rep_Value (Type_Low_Bound (Ancest));
6700                   LoSet := True;
6701                   exit when HiSet;
6702                end if;
6703             end if;
6704
6705             if not HiSet then
6706                if Compile_Time_Known_Value (Type_High_Bound (Ancest)) then
6707                   Hi := Expr_Rep_Value (Type_High_Bound (Ancest));
6708                   HiSet := True;
6709                   exit when LoSet;
6710                end if;
6711             end if;
6712
6713             Ancest := Ancestor_Subtype (Ancest);
6714
6715             if No (Ancest) then
6716                Ancest := Base_Type (T);
6717
6718                if Is_Generic_Type (Ancest) then
6719                   return 0;
6720                end if;
6721             end if;
6722          end loop;
6723
6724       --  Fixed-point types. We can't simply use Expr_Value to get the
6725       --  Corresponding_Integer_Value values of the bounds, since these do not
6726       --  get set till the type is frozen, and this routine can be called
6727       --  before the type is frozen. Similarly the test for bounds being static
6728       --  needs to include the case where we have unanalyzed real literals for
6729       --  the same reason.
6730
6731       elsif Is_Fixed_Point_Type (T) then
6732
6733          --  The following loop is looking for the nearest compile time known
6734          --  bounds following the ancestor subtype chain. The idea is to find
6735          --  the most restrictive known bounds information.
6736
6737          Ancest := T;
6738          loop
6739             if Ancest = Any_Type or else Etype (Ancest) = Any_Type then
6740                return 0;
6741             end if;
6742
6743             --  Note: In the following two tests for LoSet and HiSet, it may
6744             --  seem redundant to test for N_Real_Literal here since normally
6745             --  one would assume that the test for the value being known at
6746             --  compile time includes this case. However, there is a glitch.
6747             --  If the real literal comes from folding a non-static expression,
6748             --  then we don't consider any non- static expression to be known
6749             --  at compile time if we are in configurable run time mode (needed
6750             --  in some cases to give a clearer definition of what is and what
6751             --  is not accepted). So the test is indeed needed. Without it, we
6752             --  would set neither Lo_Set nor Hi_Set and get an infinite loop.
6753
6754             if not LoSet then
6755                if Nkind (Type_Low_Bound (Ancest)) = N_Real_Literal
6756                  or else Compile_Time_Known_Value (Type_Low_Bound (Ancest))
6757                then
6758                   LoR := Expr_Value_R (Type_Low_Bound (Ancest));
6759                   LoSet := True;
6760                   exit when HiSet;
6761                end if;
6762             end if;
6763
6764             if not HiSet then
6765                if Nkind (Type_High_Bound (Ancest)) = N_Real_Literal
6766                  or else Compile_Time_Known_Value (Type_High_Bound (Ancest))
6767                then
6768                   HiR := Expr_Value_R (Type_High_Bound (Ancest));
6769                   HiSet := True;
6770                   exit when LoSet;
6771                end if;
6772             end if;
6773
6774             Ancest := Ancestor_Subtype (Ancest);
6775
6776             if No (Ancest) then
6777                Ancest := Base_Type (T);
6778
6779                if Is_Generic_Type (Ancest) then
6780                   return 0;
6781                end if;
6782             end if;
6783          end loop;
6784
6785          Lo := UR_To_Uint (LoR / Small_Value (T));
6786          Hi := UR_To_Uint (HiR / Small_Value (T));
6787
6788       --  No other types allowed
6789
6790       else
6791          raise Program_Error;
6792       end if;
6793
6794       --  Fall through with Hi and Lo set. Deal with biased case
6795
6796       if (Biased
6797            and then not Is_Fixed_Point_Type (T)
6798            and then not (Is_Enumeration_Type (T)
6799                           and then Has_Non_Standard_Rep (T)))
6800         or else Has_Biased_Representation (T)
6801       then
6802          Hi := Hi - Lo;
6803          Lo := Uint_0;
6804       end if;
6805
6806       --  Signed case. Note that we consider types like range 1 .. -1 to be
6807       --  signed for the purpose of computing the size, since the bounds have
6808       --  to be accommodated in the base type.
6809
6810       if Lo < 0 or else Hi < 0 then
6811          S := 1;
6812          B := Uint_1;
6813
6814          --  S = size, B = 2 ** (size - 1) (can accommodate -B .. +(B - 1))
6815          --  Note that we accommodate the case where the bounds cross. This
6816          --  can happen either because of the way the bounds are declared
6817          --  or because of the algorithm in Freeze_Fixed_Point_Type.
6818
6819          while Lo < -B
6820            or else Hi < -B
6821            or else Lo >= B
6822            or else Hi >= B
6823          loop
6824             B := Uint_2 ** S;
6825             S := S + 1;
6826          end loop;
6827
6828       --  Unsigned case
6829
6830       else
6831          --  If both bounds are positive, make sure that both are represen-
6832          --  table in the case where the bounds are crossed. This can happen
6833          --  either because of the way the bounds are declared, or because of
6834          --  the algorithm in Freeze_Fixed_Point_Type.
6835
6836          if Lo > Hi then
6837             Hi := Lo;
6838          end if;
6839
6840          --  S = size, (can accommodate 0 .. (2**size - 1))
6841
6842          S := 0;
6843          while Hi >= Uint_2 ** S loop
6844             S := S + 1;
6845          end loop;
6846       end if;
6847
6848       return S;
6849    end Minimum_Size;
6850
6851    ---------------------------
6852    -- New_Stream_Subprogram --
6853    ---------------------------
6854
6855    procedure New_Stream_Subprogram
6856      (N     : Node_Id;
6857       Ent   : Entity_Id;
6858       Subp  : Entity_Id;
6859       Nam   : TSS_Name_Type)
6860    is
6861       Loc       : constant Source_Ptr := Sloc (N);
6862       Sname     : constant Name_Id    := Make_TSS_Name (Base_Type (Ent), Nam);
6863       Subp_Id   : Entity_Id;
6864       Subp_Decl : Node_Id;
6865       F         : Entity_Id;
6866       Etyp      : Entity_Id;
6867
6868       Defer_Declaration : constant Boolean :=
6869                             Is_Tagged_Type (Ent) or else Is_Private_Type (Ent);
6870       --  For a tagged type, there is a declaration for each stream attribute
6871       --  at the freeze point, and we must generate only a completion of this
6872       --  declaration. We do the same for private types, because the full view
6873       --  might be tagged. Otherwise we generate a declaration at the point of
6874       --  the attribute definition clause.
6875
6876       function Build_Spec return Node_Id;
6877       --  Used for declaration and renaming declaration, so that this is
6878       --  treated as a renaming_as_body.
6879
6880       ----------------
6881       -- Build_Spec --
6882       ----------------
6883
6884       function Build_Spec return Node_Id is
6885          Out_P   : constant Boolean := (Nam = TSS_Stream_Read);
6886          Formals : List_Id;
6887          Spec    : Node_Id;
6888          T_Ref   : constant Node_Id := New_Reference_To (Etyp, Loc);
6889
6890       begin
6891          Subp_Id := Make_Defining_Identifier (Loc, Sname);
6892
6893          --  S : access Root_Stream_Type'Class
6894
6895          Formals := New_List (
6896                       Make_Parameter_Specification (Loc,
6897                         Defining_Identifier =>
6898                           Make_Defining_Identifier (Loc, Name_S),
6899                         Parameter_Type =>
6900                           Make_Access_Definition (Loc,
6901                             Subtype_Mark =>
6902                               New_Reference_To (
6903                                 Designated_Type (Etype (F)), Loc))));
6904
6905          if Nam = TSS_Stream_Input then
6906             Spec := Make_Function_Specification (Loc,
6907                       Defining_Unit_Name       => Subp_Id,
6908                       Parameter_Specifications => Formals,
6909                       Result_Definition        => T_Ref);
6910          else
6911             --  V : [out] T
6912
6913             Append_To (Formals,
6914               Make_Parameter_Specification (Loc,
6915                 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
6916                 Out_Present         => Out_P,
6917                 Parameter_Type      => T_Ref));
6918
6919             Spec :=
6920               Make_Procedure_Specification (Loc,
6921                 Defining_Unit_Name       => Subp_Id,
6922                 Parameter_Specifications => Formals);
6923          end if;
6924
6925          return Spec;
6926       end Build_Spec;
6927
6928    --  Start of processing for New_Stream_Subprogram
6929
6930    begin
6931       F := First_Formal (Subp);
6932
6933       if Ekind (Subp) = E_Procedure then
6934          Etyp := Etype (Next_Formal (F));
6935       else
6936          Etyp := Etype (Subp);
6937       end if;
6938
6939       --  Prepare subprogram declaration and insert it as an action on the
6940       --  clause node. The visibility for this entity is used to test for
6941       --  visibility of the attribute definition clause (in the sense of
6942       --  8.3(23) as amended by AI-195).
6943
6944       if not Defer_Declaration then
6945          Subp_Decl :=
6946            Make_Subprogram_Declaration (Loc,
6947              Specification => Build_Spec);
6948
6949       --  For a tagged type, there is always a visible declaration for each
6950       --  stream TSS (it is a predefined primitive operation), and the
6951       --  completion of this declaration occurs at the freeze point, which is
6952       --  not always visible at places where the attribute definition clause is
6953       --  visible. So, we create a dummy entity here for the purpose of
6954       --  tracking the visibility of the attribute definition clause itself.
6955
6956       else
6957          Subp_Id :=
6958            Make_Defining_Identifier (Loc, New_External_Name (Sname, 'V'));
6959          Subp_Decl :=
6960            Make_Object_Declaration (Loc,
6961              Defining_Identifier => Subp_Id,
6962              Object_Definition   => New_Occurrence_Of (Standard_Boolean, Loc));
6963       end if;
6964
6965       Insert_Action (N, Subp_Decl);
6966       Set_Entity (N, Subp_Id);
6967
6968       Subp_Decl :=
6969         Make_Subprogram_Renaming_Declaration (Loc,
6970           Specification => Build_Spec,
6971           Name => New_Reference_To (Subp, Loc));
6972
6973       if Defer_Declaration then
6974          Set_TSS (Base_Type (Ent), Subp_Id);
6975       else
6976          Insert_Action (N, Subp_Decl);
6977          Copy_TSS (Subp_Id, Base_Type (Ent));
6978       end if;
6979    end New_Stream_Subprogram;
6980
6981    ------------------------
6982    -- Rep_Item_Too_Early --
6983    ------------------------
6984
6985    function Rep_Item_Too_Early (T : Entity_Id; N : Node_Id) return Boolean is
6986    begin
6987       --  Cannot apply non-operational rep items to generic types
6988
6989       if Is_Operational_Item (N) then
6990          return False;
6991
6992       elsif Is_Type (T)
6993         and then Is_Generic_Type (Root_Type (T))
6994       then
6995          Error_Msg_N ("representation item not allowed for generic type", N);
6996          return True;
6997       end if;
6998
6999       --  Otherwise check for incomplete type
7000
7001       if Is_Incomplete_Or_Private_Type (T)
7002         and then No (Underlying_Type (T))
7003         and then
7004           (Nkind (N) /= N_Pragma
7005             or else Get_Pragma_Id (N) /= Pragma_Import)
7006       then
7007          Error_Msg_N
7008            ("representation item must be after full type declaration", N);
7009          return True;
7010
7011       --  If the type has incomplete components, a representation clause is
7012       --  illegal but stream attributes and Convention pragmas are correct.
7013
7014       elsif Has_Private_Component (T) then
7015          if Nkind (N) = N_Pragma then
7016             return False;
7017          else
7018             Error_Msg_N
7019               ("representation item must appear after type is fully defined",
7020                 N);
7021             return True;
7022          end if;
7023       else
7024          return False;
7025       end if;
7026    end Rep_Item_Too_Early;
7027
7028    -----------------------
7029    -- Rep_Item_Too_Late --
7030    -----------------------
7031
7032    function Rep_Item_Too_Late
7033      (T     : Entity_Id;
7034       N     : Node_Id;
7035       FOnly : Boolean := False) return Boolean
7036    is
7037       S           : Entity_Id;
7038       Parent_Type : Entity_Id;
7039
7040       procedure Too_Late;
7041       --  Output the too late message. Note that this is not considered a
7042       --  serious error, since the effect is simply that we ignore the
7043       --  representation clause in this case.
7044
7045       --------------
7046       -- Too_Late --
7047       --------------
7048
7049       procedure Too_Late is
7050       begin
7051          Error_Msg_N ("|representation item appears too late!", N);
7052       end Too_Late;
7053
7054    --  Start of processing for Rep_Item_Too_Late
7055
7056    begin
7057       --  First make sure entity is not frozen (RM 13.1(9)). Exclude imported
7058       --  types, which may be frozen if they appear in a representation clause
7059       --  for a local type.
7060
7061       if Is_Frozen (T)
7062         and then not From_With_Type (T)
7063       then
7064          Too_Late;
7065          S := First_Subtype (T);
7066
7067          if Present (Freeze_Node (S)) then
7068             Error_Msg_NE
7069               ("?no more representation items for }", Freeze_Node (S), S);
7070          end if;
7071
7072          return True;
7073
7074       --  Check for case of non-tagged derived type whose parent either has
7075       --  primitive operations, or is a by reference type (RM 13.1(10)).
7076
7077       elsif Is_Type (T)
7078         and then not FOnly
7079         and then Is_Derived_Type (T)
7080         and then not Is_Tagged_Type (T)
7081       then
7082          Parent_Type := Etype (Base_Type (T));
7083
7084          if Has_Primitive_Operations (Parent_Type) then
7085             Too_Late;
7086             Error_Msg_NE
7087               ("primitive operations already defined for&!", N, Parent_Type);
7088             return True;
7089
7090          elsif Is_By_Reference_Type (Parent_Type) then
7091             Too_Late;
7092             Error_Msg_NE
7093               ("parent type & is a by reference type!", N, Parent_Type);
7094             return True;
7095          end if;
7096       end if;
7097
7098       --  No error, link item into head of chain of rep items for the entity,
7099       --  but avoid chaining if we have an overloadable entity, and the pragma
7100       --  is one that can apply to multiple overloaded entities.
7101
7102       if Is_Overloadable (T)
7103         and then Nkind (N) = N_Pragma
7104       then
7105          declare
7106             Pname : constant Name_Id := Pragma_Name (N);
7107          begin
7108             if Pname = Name_Convention or else
7109                Pname = Name_Import     or else
7110                Pname = Name_Export     or else
7111                Pname = Name_External   or else
7112                Pname = Name_Interface
7113             then
7114                return False;
7115             end if;
7116          end;
7117       end if;
7118
7119       Record_Rep_Item (T, N);
7120       return False;
7121    end Rep_Item_Too_Late;
7122
7123    -------------------------------------
7124    -- Replace_Type_References_Generic --
7125    -------------------------------------
7126
7127    procedure Replace_Type_References_Generic (N : Node_Id; TName : Name_Id) is
7128
7129       function Replace_Node (N : Node_Id) return Traverse_Result;
7130       --  Processes a single node in the traversal procedure below, checking
7131       --  if node N should be replaced, and if so, doing the replacement.
7132
7133       procedure Replace_Type_Refs is new Traverse_Proc (Replace_Node);
7134       --  This instantiation provides the body of Replace_Type_References
7135
7136       ------------------
7137       -- Replace_Node --
7138       ------------------
7139
7140       function Replace_Node (N : Node_Id) return Traverse_Result is
7141          S : Entity_Id;
7142          P : Node_Id;
7143
7144       begin
7145          --  Case of identifier
7146
7147          if Nkind (N) = N_Identifier then
7148
7149             --  If not the type name, all done with this node
7150
7151             if Chars (N) /= TName then
7152                return Skip;
7153
7154             --  Otherwise do the replacement and we are done with this node
7155
7156             else
7157                Replace_Type_Reference (N);
7158                return Skip;
7159             end if;
7160
7161          --  Case of selected component (which is what a qualification
7162          --  looks like in the unanalyzed tree, which is what we have.
7163
7164          elsif Nkind (N) = N_Selected_Component then
7165
7166             --  If selector name is not our type, keeping going (we might
7167             --  still have an occurrence of the type in the prefix).
7168
7169             if Nkind (Selector_Name (N)) /= N_Identifier
7170               or else Chars (Selector_Name (N)) /= TName
7171             then
7172                return OK;
7173
7174             --  Selector name is our type, check qualification
7175
7176             else
7177                --  Loop through scopes and prefixes, doing comparison
7178
7179                S := Current_Scope;
7180                P := Prefix (N);
7181                loop
7182                   --  Continue if no more scopes or scope with no name
7183
7184                   if No (S) or else Nkind (S) not in N_Has_Chars then
7185                      return OK;
7186                   end if;
7187
7188                   --  Do replace if prefix is an identifier matching the
7189                   --  scope that we are currently looking at.
7190
7191                   if Nkind (P) = N_Identifier
7192                     and then Chars (P) = Chars (S)
7193                   then
7194                      Replace_Type_Reference (N);
7195                      return Skip;
7196                   end if;
7197
7198                   --  Go check scope above us if prefix is itself of the
7199                   --  form of a selected component, whose selector matches
7200                   --  the scope we are currently looking at.
7201
7202                   if Nkind (P) = N_Selected_Component
7203                     and then Nkind (Selector_Name (P)) = N_Identifier
7204                     and then Chars (Selector_Name (P)) = Chars (S)
7205                   then
7206                      S := Scope (S);
7207                      P := Prefix (P);
7208
7209                   --  For anything else, we don't have a match, so keep on
7210                   --  going, there are still some weird cases where we may
7211                   --  still have a replacement within the prefix.
7212
7213                   else
7214                      return OK;
7215                   end if;
7216                end loop;
7217             end if;
7218
7219             --  Continue for any other node kind
7220
7221          else
7222             return OK;
7223          end if;
7224       end Replace_Node;
7225
7226    begin
7227       Replace_Type_Refs (N);
7228    end Replace_Type_References_Generic;
7229
7230    -------------------------
7231    -- Same_Representation --
7232    -------------------------
7233
7234    function Same_Representation (Typ1, Typ2 : Entity_Id) return Boolean is
7235       T1 : constant Entity_Id := Underlying_Type (Typ1);
7236       T2 : constant Entity_Id := Underlying_Type (Typ2);
7237
7238    begin
7239       --  A quick check, if base types are the same, then we definitely have
7240       --  the same representation, because the subtype specific representation
7241       --  attributes (Size and Alignment) do not affect representation from
7242       --  the point of view of this test.
7243
7244       if Base_Type (T1) = Base_Type (T2) then
7245          return True;
7246
7247       elsif Is_Private_Type (Base_Type (T2))
7248         and then Base_Type (T1) = Full_View (Base_Type (T2))
7249       then
7250          return True;
7251       end if;
7252
7253       --  Tagged types never have differing representations
7254
7255       if Is_Tagged_Type (T1) then
7256          return True;
7257       end if;
7258
7259       --  Representations are definitely different if conventions differ
7260
7261       if Convention (T1) /= Convention (T2) then
7262          return False;
7263       end if;
7264
7265       --  Representations are different if component alignments differ
7266
7267       if (Is_Record_Type (T1) or else Is_Array_Type (T1))
7268         and then
7269          (Is_Record_Type (T2) or else Is_Array_Type (T2))
7270         and then Component_Alignment (T1) /= Component_Alignment (T2)
7271       then
7272          return False;
7273       end if;
7274
7275       --  For arrays, the only real issue is component size. If we know the
7276       --  component size for both arrays, and it is the same, then that's
7277       --  good enough to know we don't have a change of representation.
7278
7279       if Is_Array_Type (T1) then
7280          if Known_Component_Size (T1)
7281            and then Known_Component_Size (T2)
7282            and then Component_Size (T1) = Component_Size (T2)
7283          then
7284             return True;
7285          end if;
7286       end if;
7287
7288       --  Types definitely have same representation if neither has non-standard
7289       --  representation since default representations are always consistent.
7290       --  If only one has non-standard representation, and the other does not,
7291       --  then we consider that they do not have the same representation. They
7292       --  might, but there is no way of telling early enough.
7293
7294       if Has_Non_Standard_Rep (T1) then
7295          if not Has_Non_Standard_Rep (T2) then
7296             return False;
7297          end if;
7298       else
7299          return not Has_Non_Standard_Rep (T2);
7300       end if;
7301
7302       --  Here the two types both have non-standard representation, and we need
7303       --  to determine if they have the same non-standard representation.
7304
7305       --  For arrays, we simply need to test if the component sizes are the
7306       --  same. Pragma Pack is reflected in modified component sizes, so this
7307       --  check also deals with pragma Pack.
7308
7309       if Is_Array_Type (T1) then
7310          return Component_Size (T1) = Component_Size (T2);
7311
7312       --  Tagged types always have the same representation, because it is not
7313       --  possible to specify different representations for common fields.
7314
7315       elsif Is_Tagged_Type (T1) then
7316          return True;
7317
7318       --  Case of record types
7319
7320       elsif Is_Record_Type (T1) then
7321
7322          --  Packed status must conform
7323
7324          if Is_Packed (T1) /= Is_Packed (T2) then
7325             return False;
7326
7327          --  Otherwise we must check components. Typ2 maybe a constrained
7328          --  subtype with fewer components, so we compare the components
7329          --  of the base types.
7330
7331          else
7332             Record_Case : declare
7333                CD1, CD2 : Entity_Id;
7334
7335                function Same_Rep return Boolean;
7336                --  CD1 and CD2 are either components or discriminants. This
7337                --  function tests whether the two have the same representation
7338
7339                --------------
7340                -- Same_Rep --
7341                --------------
7342
7343                function Same_Rep return Boolean is
7344                begin
7345                   if No (Component_Clause (CD1)) then
7346                      return No (Component_Clause (CD2));
7347
7348                   else
7349                      return
7350                         Present (Component_Clause (CD2))
7351                           and then
7352                         Component_Bit_Offset (CD1) = Component_Bit_Offset (CD2)
7353                           and then
7354                         Esize (CD1) = Esize (CD2);
7355                   end if;
7356                end Same_Rep;
7357
7358             --  Start of processing for Record_Case
7359
7360             begin
7361                if Has_Discriminants (T1) then
7362                   CD1 := First_Discriminant (T1);
7363                   CD2 := First_Discriminant (T2);
7364
7365                   --  The number of discriminants may be different if the
7366                   --  derived type has fewer (constrained by values). The
7367                   --  invisible discriminants retain the representation of
7368                   --  the original, so the discrepancy does not per se
7369                   --  indicate a different representation.
7370
7371                   while Present (CD1)
7372                     and then Present (CD2)
7373                   loop
7374                      if not Same_Rep then
7375                         return False;
7376                      else
7377                         Next_Discriminant (CD1);
7378                         Next_Discriminant (CD2);
7379                      end if;
7380                   end loop;
7381                end if;
7382
7383                CD1 := First_Component (Underlying_Type (Base_Type (T1)));
7384                CD2 := First_Component (Underlying_Type (Base_Type (T2)));
7385
7386                while Present (CD1) loop
7387                   if not Same_Rep then
7388                      return False;
7389                   else
7390                      Next_Component (CD1);
7391                      Next_Component (CD2);
7392                   end if;
7393                end loop;
7394
7395                return True;
7396             end Record_Case;
7397          end if;
7398
7399       --  For enumeration types, we must check each literal to see if the
7400       --  representation is the same. Note that we do not permit enumeration
7401       --  representation clauses for Character and Wide_Character, so these
7402       --  cases were already dealt with.
7403
7404       elsif Is_Enumeration_Type (T1) then
7405          Enumeration_Case : declare
7406             L1, L2 : Entity_Id;
7407
7408          begin
7409             L1 := First_Literal (T1);
7410             L2 := First_Literal (T2);
7411
7412             while Present (L1) loop
7413                if Enumeration_Rep (L1) /= Enumeration_Rep (L2) then
7414                   return False;
7415                else
7416                   Next_Literal (L1);
7417                   Next_Literal (L2);
7418                end if;
7419             end loop;
7420
7421             return True;
7422
7423          end Enumeration_Case;
7424
7425       --  Any other types have the same representation for these purposes
7426
7427       else
7428          return True;
7429       end if;
7430    end Same_Representation;
7431
7432    ----------------
7433    -- Set_Biased --
7434    ----------------
7435
7436    procedure Set_Biased
7437      (E      : Entity_Id;
7438       N      : Node_Id;
7439       Msg    : String;
7440       Biased : Boolean := True)
7441    is
7442    begin
7443       if Biased then
7444          Set_Has_Biased_Representation (E);
7445
7446          if Warn_On_Biased_Representation then
7447             Error_Msg_NE
7448               ("?" & Msg & " forces biased representation for&", N, E);
7449          end if;
7450       end if;
7451    end Set_Biased;
7452
7453    --------------------
7454    -- Set_Enum_Esize --
7455    --------------------
7456
7457    procedure Set_Enum_Esize (T : Entity_Id) is
7458       Lo : Uint;
7459       Hi : Uint;
7460       Sz : Nat;
7461
7462    begin
7463       Init_Alignment (T);
7464
7465       --  Find the minimum standard size (8,16,32,64) that fits
7466
7467       Lo := Enumeration_Rep (Entity (Type_Low_Bound (T)));
7468       Hi := Enumeration_Rep (Entity (Type_High_Bound (T)));
7469
7470       if Lo < 0 then
7471          if Lo >= -Uint_2**07 and then Hi < Uint_2**07 then
7472             Sz := Standard_Character_Size;  -- May be > 8 on some targets
7473
7474          elsif Lo >= -Uint_2**15 and then Hi < Uint_2**15 then
7475             Sz := 16;
7476
7477          elsif Lo >= -Uint_2**31 and then Hi < Uint_2**31 then
7478             Sz := 32;
7479
7480          else pragma Assert (Lo >= -Uint_2**63 and then Hi < Uint_2**63);
7481             Sz := 64;
7482          end if;
7483
7484       else
7485          if Hi < Uint_2**08 then
7486             Sz := Standard_Character_Size;  -- May be > 8 on some targets
7487
7488          elsif Hi < Uint_2**16 then
7489             Sz := 16;
7490
7491          elsif Hi < Uint_2**32 then
7492             Sz := 32;
7493
7494          else pragma Assert (Hi < Uint_2**63);
7495             Sz := 64;
7496          end if;
7497       end if;
7498
7499       --  That minimum is the proper size unless we have a foreign convention
7500       --  and the size required is 32 or less, in which case we bump the size
7501       --  up to 32. This is required for C and C++ and seems reasonable for
7502       --  all other foreign conventions.
7503
7504       if Has_Foreign_Convention (T)
7505         and then Esize (T) < Standard_Integer_Size
7506       then
7507          Init_Esize (T, Standard_Integer_Size);
7508       else
7509          Init_Esize (T, Sz);
7510       end if;
7511    end Set_Enum_Esize;
7512
7513    ------------------------------
7514    -- Validate_Address_Clauses --
7515    ------------------------------
7516
7517    procedure Validate_Address_Clauses is
7518    begin
7519       for J in Address_Clause_Checks.First .. Address_Clause_Checks.Last loop
7520          declare
7521             ACCR : Address_Clause_Check_Record
7522                      renames Address_Clause_Checks.Table (J);
7523
7524             Expr : Node_Id;
7525
7526             X_Alignment : Uint;
7527             Y_Alignment : Uint;
7528
7529             X_Size : Uint;
7530             Y_Size : Uint;
7531
7532          begin
7533             --  Skip processing of this entry if warning already posted
7534
7535             if not Address_Warning_Posted (ACCR.N) then
7536
7537                Expr := Original_Node (Expression (ACCR.N));
7538
7539                --  Get alignments
7540
7541                X_Alignment := Alignment (ACCR.X);
7542                Y_Alignment := Alignment (ACCR.Y);
7543
7544                --  Similarly obtain sizes
7545
7546                X_Size := Esize (ACCR.X);
7547                Y_Size := Esize (ACCR.Y);
7548
7549                --  Check for large object overlaying smaller one
7550
7551                if Y_Size > Uint_0
7552                  and then X_Size > Uint_0
7553                  and then X_Size > Y_Size
7554                then
7555                   Error_Msg_NE
7556                     ("?& overlays smaller object", ACCR.N, ACCR.X);
7557                   Error_Msg_N
7558                     ("\?program execution may be erroneous", ACCR.N);
7559                   Error_Msg_Uint_1 := X_Size;
7560                   Error_Msg_NE
7561                     ("\?size of & is ^", ACCR.N, ACCR.X);
7562                   Error_Msg_Uint_1 := Y_Size;
7563                   Error_Msg_NE
7564                     ("\?size of & is ^", ACCR.N, ACCR.Y);
7565
7566                --  Check for inadequate alignment, both of the base object
7567                --  and of the offset, if any.
7568
7569                --  Note: we do not check the alignment if we gave a size
7570                --  warning, since it would likely be redundant.
7571
7572                elsif Y_Alignment /= Uint_0
7573                  and then (Y_Alignment < X_Alignment
7574                              or else (ACCR.Off
7575                                         and then
7576                                           Nkind (Expr) = N_Attribute_Reference
7577                                         and then
7578                                           Attribute_Name (Expr) = Name_Address
7579                                         and then
7580                                           Has_Compatible_Alignment
7581                                             (ACCR.X, Prefix (Expr))
7582                                              /= Known_Compatible))
7583                then
7584                   Error_Msg_NE
7585                     ("?specified address for& may be inconsistent "
7586                        & "with alignment",
7587                      ACCR.N, ACCR.X);
7588                   Error_Msg_N
7589                     ("\?program execution may be erroneous (RM 13.3(27))",
7590                      ACCR.N);
7591                   Error_Msg_Uint_1 := X_Alignment;
7592                   Error_Msg_NE
7593                     ("\?alignment of & is ^",
7594                      ACCR.N, ACCR.X);
7595                   Error_Msg_Uint_1 := Y_Alignment;
7596                   Error_Msg_NE
7597                     ("\?alignment of & is ^",
7598                      ACCR.N, ACCR.Y);
7599                   if Y_Alignment >= X_Alignment then
7600                      Error_Msg_N
7601                       ("\?but offset is not multiple of alignment",
7602                        ACCR.N);
7603                   end if;
7604                end if;
7605             end if;
7606          end;
7607       end loop;
7608    end Validate_Address_Clauses;
7609
7610    ---------------------------
7611    -- Validate_Independence --
7612    ---------------------------
7613
7614    procedure Validate_Independence is
7615       SU   : constant Uint := UI_From_Int (System_Storage_Unit);
7616       N    : Node_Id;
7617       E    : Entity_Id;
7618       IC   : Boolean;
7619       Comp : Entity_Id;
7620       Addr : Node_Id;
7621       P    : Node_Id;
7622
7623       procedure Check_Array_Type (Atyp : Entity_Id);
7624       --  Checks if the array type Atyp has independent components, and
7625       --  if not, outputs an appropriate set of error messages.
7626
7627       procedure No_Independence;
7628       --  Output message that independence cannot be guaranteed
7629
7630       function OK_Component (C : Entity_Id) return Boolean;
7631       --  Checks one component to see if it is independently accessible, and
7632       --  if so yields True, otherwise yields False if independent access
7633       --  cannot be guaranteed. This is a conservative routine, it only
7634       --  returns True if it knows for sure, it returns False if it knows
7635       --  there is a problem, or it cannot be sure there is no problem.
7636
7637       procedure Reason_Bad_Component (C : Entity_Id);
7638       --  Outputs continuation message if a reason can be determined for
7639       --  the component C being bad.
7640
7641       ----------------------
7642       -- Check_Array_Type --
7643       ----------------------
7644
7645       procedure Check_Array_Type (Atyp : Entity_Id) is
7646          Ctyp : constant Entity_Id := Component_Type (Atyp);
7647
7648       begin
7649          --  OK if no alignment clause, no pack, and no component size
7650
7651          if not Has_Component_Size_Clause (Atyp)
7652            and then not Has_Alignment_Clause (Atyp)
7653            and then not Is_Packed (Atyp)
7654          then
7655             return;
7656          end if;
7657
7658          --  Check actual component size
7659
7660          if not Known_Component_Size (Atyp)
7661            or else not (Addressable (Component_Size (Atyp))
7662                           and then Component_Size (Atyp) < 64)
7663            or else Component_Size (Atyp) mod Esize (Ctyp) /= 0
7664          then
7665             No_Independence;
7666
7667             --  Bad component size, check reason
7668
7669             if Has_Component_Size_Clause (Atyp) then
7670                P :=
7671                  Get_Attribute_Definition_Clause
7672                    (Atyp, Attribute_Component_Size);
7673
7674                if Present (P) then
7675                   Error_Msg_Sloc := Sloc (P);
7676                   Error_Msg_N ("\because of Component_Size clause#", N);
7677                   return;
7678                end if;
7679             end if;
7680
7681             if Is_Packed (Atyp) then
7682                P := Get_Rep_Pragma (Atyp, Name_Pack);
7683
7684                if Present (P) then
7685                   Error_Msg_Sloc := Sloc (P);
7686                   Error_Msg_N ("\because of pragma Pack#", N);
7687                   return;
7688                end if;
7689             end if;
7690
7691             --  No reason found, just return
7692
7693             return;
7694          end if;
7695
7696          --  Array type is OK independence-wise
7697
7698          return;
7699       end Check_Array_Type;
7700
7701       ---------------------
7702       -- No_Independence --
7703       ---------------------
7704
7705       procedure No_Independence is
7706       begin
7707          if Pragma_Name (N) = Name_Independent then
7708             Error_Msg_NE
7709               ("independence cannot be guaranteed for&", N, E);
7710          else
7711             Error_Msg_NE
7712               ("independent components cannot be guaranteed for&", N, E);
7713          end if;
7714       end No_Independence;
7715
7716       ------------------
7717       -- OK_Component --
7718       ------------------
7719
7720       function OK_Component (C : Entity_Id) return Boolean is
7721          Rec  : constant Entity_Id := Scope (C);
7722          Ctyp : constant Entity_Id := Etype (C);
7723
7724       begin
7725          --  OK if no component clause, no Pack, and no alignment clause
7726
7727          if No (Component_Clause (C))
7728            and then not Is_Packed (Rec)
7729            and then not Has_Alignment_Clause (Rec)
7730          then
7731             return True;
7732          end if;
7733
7734          --  Here we look at the actual component layout. A component is
7735          --  addressable if its size is a multiple of the Esize of the
7736          --  component type, and its starting position in the record has
7737          --  appropriate alignment, and the record itself has appropriate
7738          --  alignment to guarantee the component alignment.
7739
7740          --  Make sure sizes are static, always assume the worst for any
7741          --  cases where we cannot check static values.
7742
7743          if not (Known_Static_Esize (C)
7744                   and then Known_Static_Esize (Ctyp))
7745          then
7746             return False;
7747          end if;
7748
7749          --  Size of component must be addressable or greater than 64 bits
7750          --  and a multiple of bytes.
7751
7752          if not Addressable (Esize (C))
7753            and then Esize (C) < Uint_64
7754          then
7755             return False;
7756          end if;
7757
7758          --  Check size is proper multiple
7759
7760          if Esize (C) mod Esize (Ctyp) /= 0 then
7761             return False;
7762          end if;
7763
7764          --  Check alignment of component is OK
7765
7766          if not Known_Component_Bit_Offset (C)
7767            or else Component_Bit_Offset (C) < Uint_0
7768            or else Component_Bit_Offset (C) mod Esize (Ctyp) /= 0
7769          then
7770             return False;
7771          end if;
7772
7773          --  Check alignment of record type is OK
7774
7775          if not Known_Alignment (Rec)
7776            or else (Alignment (Rec) * SU) mod Esize (Ctyp) /= 0
7777          then
7778             return False;
7779          end if;
7780
7781          --  All tests passed, component is addressable
7782
7783          return True;
7784       end OK_Component;
7785
7786       --------------------------
7787       -- Reason_Bad_Component --
7788       --------------------------
7789
7790       procedure Reason_Bad_Component (C : Entity_Id) is
7791          Rec  : constant Entity_Id := Scope (C);
7792          Ctyp : constant Entity_Id := Etype (C);
7793
7794       begin
7795          --  If component clause present assume that's the problem
7796
7797          if Present (Component_Clause (C)) then
7798             Error_Msg_Sloc := Sloc (Component_Clause (C));
7799             Error_Msg_N ("\because of Component_Clause#", N);
7800             return;
7801          end if;
7802
7803          --  If pragma Pack clause present, assume that's the problem
7804
7805          if Is_Packed (Rec) then
7806             P := Get_Rep_Pragma (Rec, Name_Pack);
7807
7808             if Present (P) then
7809                Error_Msg_Sloc := Sloc (P);
7810                Error_Msg_N ("\because of pragma Pack#", N);
7811                return;
7812             end if;
7813          end if;
7814
7815          --  See if record has bad alignment clause
7816
7817          if Has_Alignment_Clause (Rec)
7818            and then Known_Alignment (Rec)
7819            and then (Alignment (Rec) * SU) mod Esize (Ctyp) /= 0
7820          then
7821             P := Get_Attribute_Definition_Clause (Rec, Attribute_Alignment);
7822
7823             if Present (P) then
7824                Error_Msg_Sloc := Sloc (P);
7825                Error_Msg_N ("\because of Alignment clause#", N);
7826             end if;
7827          end if;
7828
7829          --  Couldn't find a reason, so return without a message
7830
7831          return;
7832       end Reason_Bad_Component;
7833
7834    --  Start of processing for Validate_Independence
7835
7836    begin
7837       for J in Independence_Checks.First .. Independence_Checks.Last loop
7838          N  := Independence_Checks.Table (J).N;
7839          E  := Independence_Checks.Table (J).E;
7840          IC := Pragma_Name (N) = Name_Independent_Components;
7841
7842          --  Deal with component case
7843
7844          if Ekind (E) = E_Discriminant or else Ekind (E) = E_Component then
7845             if not OK_Component (E) then
7846                No_Independence;
7847                Reason_Bad_Component (E);
7848                goto Continue;
7849             end if;
7850          end if;
7851
7852          --  Deal with record with Independent_Components
7853
7854          if IC and then Is_Record_Type (E) then
7855             Comp := First_Component_Or_Discriminant (E);
7856             while Present (Comp) loop
7857                if not OK_Component (Comp) then
7858                   No_Independence;
7859                   Reason_Bad_Component (Comp);
7860                   goto Continue;
7861                end if;
7862
7863                Next_Component_Or_Discriminant (Comp);
7864             end loop;
7865          end if;
7866
7867          --  Deal with address clause case
7868
7869          if Is_Object (E) then
7870             Addr := Address_Clause (E);
7871
7872             if Present (Addr) then
7873                No_Independence;
7874                Error_Msg_Sloc := Sloc (Addr);
7875                Error_Msg_N ("\because of Address clause#", N);
7876                goto Continue;
7877             end if;
7878          end if;
7879
7880          --  Deal with independent components for array type
7881
7882          if IC and then Is_Array_Type (E) then
7883             Check_Array_Type (E);
7884          end if;
7885
7886          --  Deal with independent components for array object
7887
7888          if IC and then Is_Object (E) and then Is_Array_Type (Etype (E)) then
7889             Check_Array_Type (Etype (E));
7890          end if;
7891
7892       <<Continue>> null;
7893       end loop;
7894    end Validate_Independence;
7895
7896    -----------------------------------
7897    -- Validate_Unchecked_Conversion --
7898    -----------------------------------
7899
7900    procedure Validate_Unchecked_Conversion
7901      (N        : Node_Id;
7902       Act_Unit : Entity_Id)
7903    is
7904       Source : Entity_Id;
7905       Target : Entity_Id;
7906       Vnode  : Node_Id;
7907
7908    begin
7909       --  Obtain source and target types. Note that we call Ancestor_Subtype
7910       --  here because the processing for generic instantiation always makes
7911       --  subtypes, and we want the original frozen actual types.
7912
7913       --  If we are dealing with private types, then do the check on their
7914       --  fully declared counterparts if the full declarations have been
7915       --  encountered (they don't have to be visible, but they must exist!)
7916
7917       Source := Ancestor_Subtype (Etype (First_Formal (Act_Unit)));
7918
7919       if Is_Private_Type (Source)
7920         and then Present (Underlying_Type (Source))
7921       then
7922          Source := Underlying_Type (Source);
7923       end if;
7924
7925       Target := Ancestor_Subtype (Etype (Act_Unit));
7926
7927       --  If either type is generic, the instantiation happens within a generic
7928       --  unit, and there is nothing to check. The proper check
7929       --  will happen when the enclosing generic is instantiated.
7930
7931       if Is_Generic_Type (Source) or else Is_Generic_Type (Target) then
7932          return;
7933       end if;
7934
7935       if Is_Private_Type (Target)
7936         and then Present (Underlying_Type (Target))
7937       then
7938          Target := Underlying_Type (Target);
7939       end if;
7940
7941       --  Source may be unconstrained array, but not target
7942
7943       if Is_Array_Type (Target)
7944         and then not Is_Constrained (Target)
7945       then
7946          Error_Msg_N
7947            ("unchecked conversion to unconstrained array not allowed", N);
7948          return;
7949       end if;
7950
7951       --  Warn if conversion between two different convention pointers
7952
7953       if Is_Access_Type (Target)
7954         and then Is_Access_Type (Source)
7955         and then Convention (Target) /= Convention (Source)
7956         and then Warn_On_Unchecked_Conversion
7957       then
7958          --  Give warnings for subprogram pointers only on most targets. The
7959          --  exception is VMS, where data pointers can have different lengths
7960          --  depending on the pointer convention.
7961
7962          if Is_Access_Subprogram_Type (Target)
7963            or else Is_Access_Subprogram_Type (Source)
7964            or else OpenVMS_On_Target
7965          then
7966             Error_Msg_N
7967               ("?conversion between pointers with different conventions!", N);
7968          end if;
7969       end if;
7970
7971       --  Warn if one of the operands is Ada.Calendar.Time. Do not emit a
7972       --  warning when compiling GNAT-related sources.
7973
7974       if Warn_On_Unchecked_Conversion
7975         and then not In_Predefined_Unit (N)
7976         and then RTU_Loaded (Ada_Calendar)
7977         and then
7978           (Chars (Source) = Name_Time
7979              or else
7980            Chars (Target) = Name_Time)
7981       then
7982          --  If Ada.Calendar is loaded and the name of one of the operands is
7983          --  Time, there is a good chance that this is Ada.Calendar.Time.
7984
7985          declare
7986             Calendar_Time : constant Entity_Id :=
7987                               Full_View (RTE (RO_CA_Time));
7988          begin
7989             pragma Assert (Present (Calendar_Time));
7990
7991             if Source = Calendar_Time
7992               or else Target = Calendar_Time
7993             then
7994                Error_Msg_N
7995                  ("?representation of 'Time values may change between " &
7996                   "'G'N'A'T versions", N);
7997             end if;
7998          end;
7999       end if;
8000
8001       --  Make entry in unchecked conversion table for later processing by
8002       --  Validate_Unchecked_Conversions, which will check sizes and alignments
8003       --  (using values set by the back-end where possible). This is only done
8004       --  if the appropriate warning is active.
8005
8006       if Warn_On_Unchecked_Conversion then
8007          Unchecked_Conversions.Append
8008            (New_Val => UC_Entry'
8009               (Eloc   => Sloc (N),
8010                Source => Source,
8011                Target => Target));
8012
8013          --  If both sizes are known statically now, then back end annotation
8014          --  is not required to do a proper check but if either size is not
8015          --  known statically, then we need the annotation.
8016
8017          if Known_Static_RM_Size (Source)
8018            and then Known_Static_RM_Size (Target)
8019          then
8020             null;
8021          else
8022             Back_Annotate_Rep_Info := True;
8023          end if;
8024       end if;
8025
8026       --  If unchecked conversion to access type, and access type is declared
8027       --  in the same unit as the unchecked conversion, then set the
8028       --  No_Strict_Aliasing flag (no strict aliasing is implicit in this
8029       --  situation).
8030
8031       if Is_Access_Type (Target) and then
8032         In_Same_Source_Unit (Target, N)
8033       then
8034          Set_No_Strict_Aliasing (Implementation_Base_Type (Target));
8035       end if;
8036
8037       --  Generate N_Validate_Unchecked_Conversion node for back end in
8038       --  case the back end needs to perform special validation checks.
8039
8040       --  Shouldn't this be in Exp_Ch13, since the check only gets done
8041       --  if we have full expansion and the back end is called ???
8042
8043       Vnode :=
8044         Make_Validate_Unchecked_Conversion (Sloc (N));
8045       Set_Source_Type (Vnode, Source);
8046       Set_Target_Type (Vnode, Target);
8047
8048       --  If the unchecked conversion node is in a list, just insert before it.
8049       --  If not we have some strange case, not worth bothering about.
8050
8051       if Is_List_Member (N) then
8052          Insert_After (N, Vnode);
8053       end if;
8054    end Validate_Unchecked_Conversion;
8055
8056    ------------------------------------
8057    -- Validate_Unchecked_Conversions --
8058    ------------------------------------
8059
8060    procedure Validate_Unchecked_Conversions is
8061    begin
8062       for N in Unchecked_Conversions.First .. Unchecked_Conversions.Last loop
8063          declare
8064             T : UC_Entry renames Unchecked_Conversions.Table (N);
8065
8066             Eloc   : constant Source_Ptr := T.Eloc;
8067             Source : constant Entity_Id  := T.Source;
8068             Target : constant Entity_Id  := T.Target;
8069
8070             Source_Siz    : Uint;
8071             Target_Siz    : Uint;
8072
8073          begin
8074             --  This validation check, which warns if we have unequal sizes for
8075             --  unchecked conversion, and thus potentially implementation
8076             --  dependent semantics, is one of the few occasions on which we
8077             --  use the official RM size instead of Esize. See description in
8078             --  Einfo "Handling of Type'Size Values" for details.
8079
8080             if Serious_Errors_Detected = 0
8081               and then Known_Static_RM_Size (Source)
8082               and then Known_Static_RM_Size (Target)
8083
8084               --  Don't do the check if warnings off for either type, note the
8085               --  deliberate use of OR here instead of OR ELSE to get the flag
8086               --  Warnings_Off_Used set for both types if appropriate.
8087
8088               and then not (Has_Warnings_Off (Source)
8089                               or
8090                             Has_Warnings_Off (Target))
8091             then
8092                Source_Siz := RM_Size (Source);
8093                Target_Siz := RM_Size (Target);
8094
8095                if Source_Siz /= Target_Siz then
8096                   Error_Msg
8097                     ("?types for unchecked conversion have different sizes!",
8098                      Eloc);
8099
8100                   if All_Errors_Mode then
8101                      Error_Msg_Name_1 := Chars (Source);
8102                      Error_Msg_Uint_1 := Source_Siz;
8103                      Error_Msg_Name_2 := Chars (Target);
8104                      Error_Msg_Uint_2 := Target_Siz;
8105                      Error_Msg ("\size of % is ^, size of % is ^?", Eloc);
8106
8107                      Error_Msg_Uint_1 := UI_Abs (Source_Siz - Target_Siz);
8108
8109                      if Is_Discrete_Type (Source)
8110                        and then Is_Discrete_Type (Target)
8111                      then
8112                         if Source_Siz > Target_Siz then
8113                            Error_Msg
8114                              ("\?^ high order bits of source will be ignored!",
8115                               Eloc);
8116
8117                         elsif Is_Unsigned_Type (Source) then
8118                            Error_Msg
8119                              ("\?source will be extended with ^ high order " &
8120                               "zero bits?!", Eloc);
8121
8122                         else
8123                            Error_Msg
8124                              ("\?source will be extended with ^ high order " &
8125                               "sign bits!",
8126                               Eloc);
8127                         end if;
8128
8129                      elsif Source_Siz < Target_Siz then
8130                         if Is_Discrete_Type (Target) then
8131                            if Bytes_Big_Endian then
8132                               Error_Msg
8133                                 ("\?target value will include ^ undefined " &
8134                                  "low order bits!",
8135                                  Eloc);
8136                            else
8137                               Error_Msg
8138                                 ("\?target value will include ^ undefined " &
8139                                  "high order bits!",
8140                                  Eloc);
8141                            end if;
8142
8143                         else
8144                            Error_Msg
8145                              ("\?^ trailing bits of target value will be " &
8146                               "undefined!", Eloc);
8147                         end if;
8148
8149                      else pragma Assert (Source_Siz > Target_Siz);
8150                         Error_Msg
8151                           ("\?^ trailing bits of source will be ignored!",
8152                            Eloc);
8153                      end if;
8154                   end if;
8155                end if;
8156             end if;
8157
8158             --  If both types are access types, we need to check the alignment.
8159             --  If the alignment of both is specified, we can do it here.
8160
8161             if Serious_Errors_Detected = 0
8162               and then Ekind (Source) in Access_Kind
8163               and then Ekind (Target) in Access_Kind
8164               and then Target_Strict_Alignment
8165               and then Present (Designated_Type (Source))
8166               and then Present (Designated_Type (Target))
8167             then
8168                declare
8169                   D_Source : constant Entity_Id := Designated_Type (Source);
8170                   D_Target : constant Entity_Id := Designated_Type (Target);
8171
8172                begin
8173                   if Known_Alignment (D_Source)
8174                     and then Known_Alignment (D_Target)
8175                   then
8176                      declare
8177                         Source_Align : constant Uint := Alignment (D_Source);
8178                         Target_Align : constant Uint := Alignment (D_Target);
8179
8180                      begin
8181                         if Source_Align < Target_Align
8182                           and then not Is_Tagged_Type (D_Source)
8183
8184                           --  Suppress warning if warnings suppressed on either
8185                           --  type or either designated type. Note the use of
8186                           --  OR here instead of OR ELSE. That is intentional,
8187                           --  we would like to set flag Warnings_Off_Used in
8188                           --  all types for which warnings are suppressed.
8189
8190                           and then not (Has_Warnings_Off (D_Source)
8191                                           or
8192                                         Has_Warnings_Off (D_Target)
8193                                           or
8194                                         Has_Warnings_Off (Source)
8195                                           or
8196                                         Has_Warnings_Off (Target))
8197                         then
8198                            Error_Msg_Uint_1 := Target_Align;
8199                            Error_Msg_Uint_2 := Source_Align;
8200                            Error_Msg_Node_1 := D_Target;
8201                            Error_Msg_Node_2 := D_Source;
8202                            Error_Msg
8203                              ("?alignment of & (^) is stricter than " &
8204                               "alignment of & (^)!", Eloc);
8205                            Error_Msg
8206                              ("\?resulting access value may have invalid " &
8207                               "alignment!", Eloc);
8208                         end if;
8209                      end;
8210                   end if;
8211                end;
8212             end if;
8213          end;
8214       end loop;
8215    end Validate_Unchecked_Conversions;
8216
8217 end Sem_Ch13;