OSDN Git Service

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