OSDN Git Service

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