OSDN Git Service

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