OSDN Git Service

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