OSDN Git Service

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