OSDN Git Service

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