OSDN Git Service

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