OSDN Git Service

2010-10-11 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_Ch8;  use Sem_Ch8;
48 with Sem_Eval; use Sem_Eval;
49 with Sem_Res;  use Sem_Res;
50 with Sem_Type; use Sem_Type;
51 with Sem_Util; use Sem_Util;
52 with Sem_Warn; use Sem_Warn;
53 with Snames;   use Snames;
54 with Stand;    use Stand;
55 with Sinfo;    use Sinfo;
56 with Targparm; use Targparm;
57 with Ttypes;   use Ttypes;
58 with Tbuild;   use Tbuild;
59 with Urealp;   use Urealp;
60
61 with GNAT.Heap_Sort_G;
62
63 package body Sem_Ch13 is
64
65    SSU : constant Pos := System_Storage_Unit;
66    --  Convenient short hand for commonly used constant
67
68    -----------------------
69    -- Local Subprograms --
70    -----------------------
71
72    procedure Alignment_Check_For_Esize_Change (Typ : Entity_Id);
73    --  This routine is called after setting the Esize of type entity Typ.
74    --  The purpose is to deal with the situation where an alignment has been
75    --  inherited from a derived type that is no longer appropriate for the
76    --  new Esize value. In this case, we reset the Alignment to unknown.
77
78    function Get_Alignment_Value (Expr : Node_Id) return Uint;
79    --  Given the expression for an alignment value, returns the corresponding
80    --  Uint value. If the value is inappropriate, then error messages are
81    --  posted as required, and a value of No_Uint is returned.
82
83    function Is_Operational_Item (N : Node_Id) return Boolean;
84    --  A specification for a stream attribute is allowed before the full
85    --  type is declared, as explained in AI-00137 and the corrigendum.
86    --  Attributes that do not specify a representation characteristic are
87    --  operational attributes.
88
89    procedure New_Stream_Subprogram
90      (N    : Node_Id;
91       Ent  : Entity_Id;
92       Subp : Entity_Id;
93       Nam  : TSS_Name_Type);
94    --  Create a subprogram renaming of a given stream attribute to the
95    --  designated subprogram and then in the tagged case, provide this as a
96    --  primitive operation, or in the non-tagged case make an appropriate TSS
97    --  entry. This is more properly an expansion activity than just semantics,
98    --  but the presence of user-defined stream functions for limited types is a
99    --  legality check, which is why this takes place here rather than in
100    --  exp_ch13, where it was previously. Nam indicates the name of the TSS
101    --  function to be generated.
102    --
103    --  To avoid elaboration anomalies with freeze nodes, for untagged types
104    --  we generate both a subprogram declaration and a subprogram renaming
105    --  declaration, so that the attribute specification is handled as a
106    --  renaming_as_body. For tagged types, the specification is one of the
107    --  primitive specs.
108
109    procedure Set_Biased
110      (E      : Entity_Id;
111       N      : Node_Id;
112       Msg    : String;
113       Biased : Boolean := True);
114    --  If Biased is True, sets Has_Biased_Representation flag for E, and
115    --  outputs a warning message at node N if Warn_On_Biased_Representation is
116    --  is True. This warning inserts the string Msg to describe the construct
117    --  causing biasing.
118
119    ----------------------------------------------
120    -- Table for Validate_Unchecked_Conversions --
121    ----------------------------------------------
122
123    --  The following table collects unchecked conversions for validation.
124    --  Entries are made by Validate_Unchecked_Conversion and then the
125    --  call to Validate_Unchecked_Conversions does the actual error
126    --  checking and posting of warnings. The reason for this delayed
127    --  processing is to take advantage of back-annotations of size and
128    --  alignment values performed by the back end.
129
130    --  Note: the reason we store a Source_Ptr value instead of a Node_Id
131    --  is that by the time Validate_Unchecked_Conversions is called, Sprint
132    --  will already have modified all Sloc values if the -gnatD option is set.
133
134    type UC_Entry is record
135       Eloc   : Source_Ptr; -- node used for posting warnings
136       Source : Entity_Id;  -- source type for unchecked conversion
137       Target : Entity_Id;  -- target type for unchecked conversion
138    end record;
139
140    package Unchecked_Conversions is new Table.Table (
141      Table_Component_Type => UC_Entry,
142      Table_Index_Type     => Int,
143      Table_Low_Bound      => 1,
144      Table_Initial        => 50,
145      Table_Increment      => 200,
146      Table_Name           => "Unchecked_Conversions");
147
148    ----------------------------------------
149    -- Table for Validate_Address_Clauses --
150    ----------------------------------------
151
152    --  If an address clause has the form
153
154    --    for X'Address use Expr
155
156    --  where Expr is of the form Y'Address or recursively is a reference
157    --  to a constant of either of these forms, and X and Y are entities of
158    --  objects, then if Y has a smaller alignment than X, that merits a
159    --  warning about possible bad alignment. The following table collects
160    --  address clauses of this kind. We put these in a table so that they
161    --  can be checked after the back end has completed annotation of the
162    --  alignments of objects, since we can catch more cases that way.
163
164    type Address_Clause_Check_Record is record
165       N : Node_Id;
166       --  The address clause
167
168       X : Entity_Id;
169       --  The entity of the object overlaying Y
170
171       Y : Entity_Id;
172       --  The entity of the object being overlaid
173
174       Off : Boolean;
175       --  Whether the address is offseted within Y
176    end record;
177
178    package Address_Clause_Checks is new Table.Table (
179      Table_Component_Type => Address_Clause_Check_Record,
180      Table_Index_Type     => Int,
181      Table_Low_Bound      => 1,
182      Table_Initial        => 20,
183      Table_Increment      => 200,
184      Table_Name           => "Address_Clause_Checks");
185
186    -----------------------------------------
187    -- Adjust_Record_For_Reverse_Bit_Order --
188    -----------------------------------------
189
190    procedure Adjust_Record_For_Reverse_Bit_Order (R : Entity_Id) is
191       Comp : Node_Id;
192       CC   : Node_Id;
193
194    begin
195       --  Processing depends on version of Ada
196
197       --  For Ada 95, we just renumber bits within a storage unit. We do the
198       --  same for Ada 83 mode, since we recognize pragma Bit_Order in Ada 83,
199       --  and are free to add this extension.
200
201       if Ada_Version < Ada_2005 then
202          Comp := First_Component_Or_Discriminant (R);
203          while Present (Comp) loop
204             CC := Component_Clause (Comp);
205
206             --  If component clause is present, then deal with the non-default
207             --  bit order case for Ada 95 mode.
208
209             --  We only do this processing for the base type, and in fact that
210             --  is important, since otherwise if there are record subtypes, we
211             --  could reverse the bits once for each subtype, which is wrong.
212
213             if Present (CC)
214               and then Ekind (R) = E_Record_Type
215             then
216                declare
217                   CFB : constant Uint    := Component_Bit_Offset (Comp);
218                   CSZ : constant Uint    := Esize (Comp);
219                   CLC : constant Node_Id := Component_Clause (Comp);
220                   Pos : constant Node_Id := Position (CLC);
221                   FB  : constant Node_Id := First_Bit (CLC);
222
223                   Storage_Unit_Offset : constant Uint :=
224                                           CFB / System_Storage_Unit;
225
226                   Start_Bit : constant Uint :=
227                                 CFB mod System_Storage_Unit;
228
229                begin
230                   --  Cases where field goes over storage unit boundary
231
232                   if Start_Bit + CSZ > System_Storage_Unit then
233
234                      --  Allow multi-byte field but generate warning
235
236                      if Start_Bit mod System_Storage_Unit = 0
237                        and then CSZ mod System_Storage_Unit = 0
238                      then
239                         Error_Msg_N
240                           ("multi-byte field specified with non-standard"
241                            & " Bit_Order?", CLC);
242
243                         if Bytes_Big_Endian then
244                            Error_Msg_N
245                              ("bytes are not reversed "
246                               & "(component is big-endian)?", CLC);
247                         else
248                            Error_Msg_N
249                              ("bytes are not reversed "
250                               & "(component is little-endian)?", CLC);
251                         end if;
252
253                         --  Do not allow non-contiguous field
254
255                      else
256                         Error_Msg_N
257                           ("attempt to specify non-contiguous field "
258                            & "not permitted", CLC);
259                         Error_Msg_N
260                           ("\caused by non-standard Bit_Order "
261                            & "specified", CLC);
262                         Error_Msg_N
263                           ("\consider possibility of using "
264                            & "Ada 2005 mode here", CLC);
265                      end if;
266
267                   --  Case where field fits in one storage unit
268
269                   else
270                      --  Give warning if suspicious component clause
271
272                      if Intval (FB) >= System_Storage_Unit
273                        and then Warn_On_Reverse_Bit_Order
274                      then
275                         Error_Msg_N
276                           ("?Bit_Order clause does not affect " &
277                            "byte ordering", Pos);
278                         Error_Msg_Uint_1 :=
279                           Intval (Pos) + Intval (FB) /
280                           System_Storage_Unit;
281                         Error_Msg_N
282                           ("?position normalized to ^ before bit " &
283                            "order interpreted", Pos);
284                      end if;
285
286                      --  Here is where we fix up the Component_Bit_Offset value
287                      --  to account for the reverse bit order. Some examples of
288                      --  what needs to be done are:
289
290                      --    First_Bit .. Last_Bit     Component_Bit_Offset
291                      --      old          new          old       new
292
293                      --     0 .. 0       7 .. 7         0         7
294                      --     0 .. 1       6 .. 7         0         6
295                      --     0 .. 2       5 .. 7         0         5
296                      --     0 .. 7       0 .. 7         0         4
297
298                      --     1 .. 1       6 .. 6         1         6
299                      --     1 .. 4       3 .. 6         1         3
300                      --     4 .. 7       0 .. 3         4         0
301
302                      --  The rule is that the first bit is is obtained by
303                      --  subtracting the old ending bit from storage_unit - 1.
304
305                      Set_Component_Bit_Offset
306                        (Comp,
307                         (Storage_Unit_Offset * System_Storage_Unit) +
308                           (System_Storage_Unit - 1) -
309                           (Start_Bit + CSZ - 1));
310
311                      Set_Normalized_First_Bit
312                        (Comp,
313                         Component_Bit_Offset (Comp) mod
314                           System_Storage_Unit);
315                   end if;
316                end;
317             end if;
318
319             Next_Component_Or_Discriminant (Comp);
320          end loop;
321
322       --  For Ada 2005, we do machine scalar processing, as fully described In
323       --  AI-133. This involves gathering all components which start at the
324       --  same byte offset and processing them together. Same approach is still
325       --  valid in later versions including Ada 2012.
326
327       else
328          declare
329             Max_Machine_Scalar_Size : constant Uint :=
330                                         UI_From_Int
331                                           (Standard_Long_Long_Integer_Size);
332             --  We use this as the maximum machine scalar size
333
334             Num_CC : Natural;
335             SSU    : constant Uint := UI_From_Int (System_Storage_Unit);
336
337          begin
338             --  This first loop through components does two things. First it
339             --  deals with the case of components with component clauses whose
340             --  length is greater than the maximum machine scalar size (either
341             --  accepting them or rejecting as needed). Second, it counts the
342             --  number of components with component clauses whose length does
343             --  not exceed this maximum for later processing.
344
345             Num_CC := 0;
346             Comp   := First_Component_Or_Discriminant (R);
347             while Present (Comp) loop
348                CC := Component_Clause (Comp);
349
350                if Present (CC) then
351                   declare
352                      Fbit : constant Uint :=
353                               Static_Integer (First_Bit (CC));
354
355                   begin
356                      --  Case of component with size > max machine scalar
357
358                      if Esize (Comp) > Max_Machine_Scalar_Size then
359
360                         --  Must begin on byte boundary
361
362                         if Fbit mod SSU /= 0 then
363                            Error_Msg_N
364                              ("illegal first bit value for "
365                               & "reverse bit order",
366                               First_Bit (CC));
367                            Error_Msg_Uint_1 := SSU;
368                            Error_Msg_Uint_2 := Max_Machine_Scalar_Size;
369
370                            Error_Msg_N
371                              ("\must be a multiple of ^ "
372                               & "if size greater than ^",
373                               First_Bit (CC));
374
375                            --  Must end on byte boundary
376
377                         elsif Esize (Comp) mod SSU /= 0 then
378                            Error_Msg_N
379                              ("illegal last bit value for "
380                               & "reverse bit order",
381                               Last_Bit (CC));
382                            Error_Msg_Uint_1 := SSU;
383                            Error_Msg_Uint_2 := Max_Machine_Scalar_Size;
384
385                            Error_Msg_N
386                              ("\must be a multiple of ^ if size "
387                               & "greater than ^",
388                               Last_Bit (CC));
389
390                            --  OK, give warning if enabled
391
392                         elsif Warn_On_Reverse_Bit_Order then
393                            Error_Msg_N
394                              ("multi-byte field specified with "
395                               & "  non-standard Bit_Order?", CC);
396
397                            if Bytes_Big_Endian then
398                               Error_Msg_N
399                                 ("\bytes are not reversed "
400                                  & "(component is big-endian)?", CC);
401                            else
402                               Error_Msg_N
403                                 ("\bytes are not reversed "
404                                  & "(component is little-endian)?", CC);
405                            end if;
406                         end if;
407
408                         --  Case where size is not greater than max machine
409                         --  scalar. For now, we just count these.
410
411                      else
412                         Num_CC := Num_CC + 1;
413                      end if;
414                   end;
415                end if;
416
417                Next_Component_Or_Discriminant (Comp);
418             end loop;
419
420             --  We need to sort the component clauses on the basis of the
421             --  Position values in the clause, so we can group clauses with
422             --  the same Position. together to determine the relevant machine
423             --  scalar size.
424
425             Sort_CC : declare
426                Comps : array (0 .. Num_CC) of Entity_Id;
427                --  Array to collect component and discriminant entities. The
428                --  data starts at index 1, the 0'th entry is for the sort
429                --  routine.
430
431                function CP_Lt (Op1, Op2 : Natural) return Boolean;
432                --  Compare routine for Sort
433
434                procedure CP_Move (From : Natural; To : Natural);
435                --  Move routine for Sort
436
437                package Sorting is new GNAT.Heap_Sort_G (CP_Move, CP_Lt);
438
439                Start : Natural;
440                Stop  : Natural;
441                --  Start and stop positions in the component list of the set of
442                --  components with the same starting position (that constitute
443                --  components in a single machine scalar).
444
445                MaxL  : Uint;
446                --  Maximum last bit value of any component in this set
447
448                MSS   : Uint;
449                --  Corresponding machine scalar size
450
451                -----------
452                -- CP_Lt --
453                -----------
454
455                function CP_Lt (Op1, Op2 : Natural) return Boolean is
456                begin
457                   return Position (Component_Clause (Comps (Op1))) <
458                     Position (Component_Clause (Comps (Op2)));
459                end CP_Lt;
460
461                -------------
462                -- CP_Move --
463                -------------
464
465                procedure CP_Move (From : Natural; To : Natural) is
466                begin
467                   Comps (To) := Comps (From);
468                end CP_Move;
469
470                --  Start of processing for Sort_CC
471
472             begin
473                --  Collect the component clauses
474
475                Num_CC := 0;
476                Comp   := First_Component_Or_Discriminant (R);
477                while Present (Comp) loop
478                   if Present (Component_Clause (Comp))
479                     and then Esize (Comp) <= Max_Machine_Scalar_Size
480                   then
481                      Num_CC := Num_CC + 1;
482                      Comps (Num_CC) := Comp;
483                   end if;
484
485                   Next_Component_Or_Discriminant (Comp);
486                end loop;
487
488                --  Sort by ascending position number
489
490                Sorting.Sort (Num_CC);
491
492                --  We now have all the components whose size does not exceed
493                --  the max machine scalar value, sorted by starting position.
494                --  In this loop we gather groups of clauses starting at the
495                --  same position, to process them in accordance with AI-133.
496
497                Stop := 0;
498                while Stop < Num_CC loop
499                   Start := Stop + 1;
500                   Stop  := Start;
501                   MaxL  :=
502                     Static_Integer
503                       (Last_Bit (Component_Clause (Comps (Start))));
504                   while Stop < Num_CC loop
505                      if Static_Integer
506                           (Position (Component_Clause (Comps (Stop + 1)))) =
507                         Static_Integer
508                           (Position (Component_Clause (Comps (Stop))))
509                      then
510                         Stop := Stop + 1;
511                         MaxL :=
512                           UI_Max
513                             (MaxL,
514                              Static_Integer
515                                (Last_Bit
516                                   (Component_Clause (Comps (Stop)))));
517                      else
518                         exit;
519                      end if;
520                   end loop;
521
522                   --  Now we have a group of component clauses from Start to
523                   --  Stop whose positions are identical, and MaxL is the
524                   --  maximum last bit value of any of these components.
525
526                   --  We need to determine the corresponding machine scalar
527                   --  size. This loop assumes that machine scalar sizes are
528                   --  even, and that each possible machine scalar has twice
529                   --  as many bits as the next smaller one.
530
531                   MSS := Max_Machine_Scalar_Size;
532                   while MSS mod 2 = 0
533                     and then (MSS / 2) >= SSU
534                     and then (MSS / 2) > MaxL
535                   loop
536                      MSS := MSS / 2;
537                   end loop;
538
539                   --  Here is where we fix up the Component_Bit_Offset value
540                   --  to account for the reverse bit order. Some examples of
541                   --  what needs to be done for the case of a machine scalar
542                   --  size of 8 are:
543
544                   --    First_Bit .. Last_Bit     Component_Bit_Offset
545                   --      old          new          old       new
546
547                   --     0 .. 0       7 .. 7         0         7
548                   --     0 .. 1       6 .. 7         0         6
549                   --     0 .. 2       5 .. 7         0         5
550                   --     0 .. 7       0 .. 7         0         4
551
552                   --     1 .. 1       6 .. 6         1         6
553                   --     1 .. 4       3 .. 6         1         3
554                   --     4 .. 7       0 .. 3         4         0
555
556                   --  The rule is that the first bit is obtained by subtracting
557                   --  the old ending bit from machine scalar size - 1.
558
559                   for C in Start .. Stop loop
560                      declare
561                         Comp : constant Entity_Id := Comps (C);
562                         CC   : constant Node_Id   :=
563                                  Component_Clause (Comp);
564                         LB   : constant Uint :=
565                                  Static_Integer (Last_Bit (CC));
566                         NFB  : constant Uint := MSS - Uint_1 - LB;
567                         NLB  : constant Uint := NFB + Esize (Comp) - 1;
568                         Pos  : constant Uint :=
569                                  Static_Integer (Position (CC));
570
571                      begin
572                         if Warn_On_Reverse_Bit_Order then
573                            Error_Msg_Uint_1 := MSS;
574                            Error_Msg_N
575                              ("info: reverse bit order in machine " &
576                               "scalar of length^?", First_Bit (CC));
577                            Error_Msg_Uint_1 := NFB;
578                            Error_Msg_Uint_2 := NLB;
579
580                            if Bytes_Big_Endian then
581                               Error_Msg_NE
582                                 ("?\info: big-endian range for "
583                                  & "component & is ^ .. ^",
584                                  First_Bit (CC), Comp);
585                            else
586                               Error_Msg_NE
587                                 ("?\info: little-endian range "
588                                  & "for component & is ^ .. ^",
589                                  First_Bit (CC), Comp);
590                            end if;
591                         end if;
592
593                         Set_Component_Bit_Offset (Comp, Pos * SSU + NFB);
594                         Set_Normalized_First_Bit (Comp, NFB mod SSU);
595                      end;
596                   end loop;
597                end loop;
598             end Sort_CC;
599          end;
600       end if;
601    end Adjust_Record_For_Reverse_Bit_Order;
602
603    --------------------------------------
604    -- Alignment_Check_For_Esize_Change --
605    --------------------------------------
606
607    procedure Alignment_Check_For_Esize_Change (Typ : Entity_Id) is
608    begin
609       --  If the alignment is known, and not set by a rep clause, and is
610       --  inconsistent with the size being set, then reset it to unknown,
611       --  we assume in this case that the size overrides the inherited
612       --  alignment, and that the alignment must be recomputed.
613
614       if Known_Alignment (Typ)
615         and then not Has_Alignment_Clause (Typ)
616         and then Esize (Typ) mod (Alignment (Typ) * SSU) /= 0
617       then
618          Init_Alignment (Typ);
619       end if;
620    end Alignment_Check_For_Esize_Change;
621
622    -----------------------------------
623    -- Analyze_Aspect_Specifications --
624    -----------------------------------
625
626    procedure Analyze_Aspect_Specifications
627      (N : Node_Id;
628       E : Entity_Id;
629       L : List_Id)
630    is
631       Aspect : Node_Id;
632       Aitem  : Node_Id;
633       Ent    : Node_Id;
634
635       Ins_Node : Node_Id := N;
636       --  Insert pragmas (other than Pre/Post) after this node
637
638       --  The general processing involves building an attribute definition
639       --  clause or a pragma node that corresponds to the access type. Then
640       --  one of two things happens:
641
642       --  If we are required to delay the evaluation of this aspect to the
643       --  freeze point, we preanalyze the relevant argument, and then attach
644       --  the corresponding pragma/attribute definition clause to the aspect
645       --  specification node, which is then placed in the Rep Item chain.
646       --  In this case we mark the entity with the Has_Delayed_Aspects flag,
647       --  and we evaluate the rep item at the freeze point.
648
649       --  If no delay is required, we just insert the pragma or attribute
650       --  after the declaration, and it will get processed by the normal
651       --  circuit. The From_Aspect_Specification flag is set on the pragma
652       --  or attribute definition node in either case to activate special
653       --  processing (e.g. not traversing the list of homonyms for inline).
654
655       Delay_Required : Boolean;
656       --  Set True if delay is required
657
658    begin
659       if L = No_List then
660          return;
661       end if;
662
663       Aspect := First (L);
664       while Present (Aspect) loop
665          declare
666             Id   : constant Node_Id   := Identifier (Aspect);
667             Expr : constant Node_Id   := Expression (Aspect);
668             Nam  : constant Name_Id   := Chars (Id);
669             A_Id : constant Aspect_Id := Get_Aspect_Id (Nam);
670             Anod : Node_Id;
671             T    : Entity_Id;
672
673          begin
674             Set_Entity (Aspect, E);
675             Ent := New_Occurrence_Of (E, Sloc (Id));
676
677             --  Check for duplicate aspect
678
679             Anod := First (L);
680             while Anod /= Aspect loop
681                if Nam = Chars (Identifier (Anod)) then
682                   Error_Msg_Name_1 := Nam;
683                   Error_Msg_Sloc := Sloc (Anod);
684                   Error_Msg_NE
685                     ("aspect% for & ignored, already given at#", Id, E);
686                   goto Continue;
687                end if;
688
689                Next (Anod);
690             end loop;
691
692             --  Processing based on specific aspect
693
694             case A_Id is
695
696                --  No_Aspect should be impossible
697
698                when No_Aspect =>
699                   raise Program_Error;
700
701                   --  Aspects taking an optional boolean argument. For all of
702                   --  these we just create a matching pragma and insert it,
703                   --  setting flag Cancel_Aspect if the expression is False.
704
705                when Aspect_Ada_2005                     |
706                     Aspect_Ada_2012                     |
707                     Aspect_Atomic                       |
708                     Aspect_Atomic_Components            |
709                     Aspect_Discard_Names                |
710                     Aspect_Favor_Top_Level              |
711                     Aspect_Inline                       |
712                     Aspect_Inline_Always                |
713                     Aspect_No_Return                    |
714                     Aspect_Pack                         |
715                     Aspect_Persistent_BSS               |
716                     Aspect_Preelaborable_Initialization |
717                     Aspect_Pure_Function                |
718                     Aspect_Shared                       |
719                     Aspect_Suppress_Debug_Info          |
720                     Aspect_Unchecked_Union              |
721                     Aspect_Universal_Aliasing           |
722                     Aspect_Unmodified                   |
723                     Aspect_Unreferenced                 |
724                     Aspect_Unreferenced_Objects         |
725                     Aspect_Volatile                     |
726                     Aspect_Volatile_Components          =>
727
728                   --  Build corresponding pragma node
729
730                   Aitem :=
731                     Make_Pragma (Sloc (Aspect),
732                       Pragma_Argument_Associations => New_List (Ent),
733                       Pragma_Identifier            =>
734                         Make_Identifier (Sloc (Id), Chars (Id)));
735
736                   --  Deal with missing expression case, delay never needed
737
738                   if No (Expr) then
739                      Delay_Required := False;
740
741                   --  Expression is present
742
743                   else
744                      Preanalyze_Spec_Expression (Expr, Standard_Boolean);
745
746                      --  If preanalysis gives a static expression, we don't
747                      --  need to delay (this will happen often in practice).
748
749                      if Is_OK_Static_Expression (Expr) then
750                         Delay_Required := False;
751
752                         if Is_False (Expr_Value (Expr)) then
753                            Set_Aspect_Cancel (Aitem);
754                         end if;
755
756                      --  If we don't get a static expression, then delay, the
757                      --  expression may turn out static by freeze time.
758
759                      else
760                         Delay_Required := True;
761                      end if;
762                   end if;
763
764                --  Aspects corresponding to attribute definition clauses with
765                --  the exception of Address which is treated specially.
766
767                when Aspect_Address        |
768                     Aspect_Alignment      |
769                     Aspect_Bit_Order      |
770                     Aspect_Component_Size |
771                     Aspect_External_Tag   |
772                     Aspect_Machine_Radix  |
773                     Aspect_Object_Size    |
774                     Aspect_Size           |
775                     Aspect_Storage_Pool   |
776                     Aspect_Storage_Size   |
777                     Aspect_Stream_Size    |
778                     Aspect_Value_Size     =>
779
780                   --  Preanalyze the expression with the appropriate type
781
782                   case A_Id is
783                      when Aspect_Address      =>
784                         T := RTE (RE_Address);
785                      when Aspect_Bit_Order    =>
786                         T := RTE (RE_Bit_Order);
787                      when Aspect_External_Tag =>
788                         T := Standard_String;
789                      when Aspect_Storage_Pool =>
790                         T := Class_Wide_Type (RTE (RE_Root_Storage_Pool));
791                      when others              =>
792                         T := Any_Integer;
793                   end case;
794
795                   Preanalyze_Spec_Expression (Expr, T);
796
797                   --  Construct the attribute definition clause
798
799                   Aitem :=
800                     Make_Attribute_Definition_Clause (Sloc (Aspect),
801                       Name       => Ent,
802                       Chars      => Chars (Id),
803                       Expression => Relocate_Node (Expr));
804
805                   --  We do not need a delay if we have a static expression
806
807                   if Is_OK_Static_Expression (Expression (Aitem)) then
808                      Delay_Required := False;
809
810                   --  Here a delay is required
811
812                   else
813                      Delay_Required := True;
814                   end if;
815
816                --  Aspects corresponding to pragmas with two arguments, where
817                --  the first argument is a local name referring to the entity,
818                --  and the second argument is the aspect definition expression.
819
820                when Aspect_Suppress   |
821                     Aspect_Unsuppress =>
822
823                   --  Construct the pragma
824
825                   Aitem :=
826                     Make_Pragma (Sloc (Aspect),
827                       Pragma_Argument_Associations => New_List (
828                         New_Occurrence_Of (E, Sloc (Expr)),
829                         Relocate_Node (Expr)),
830                       Pragma_Identifier            =>
831                       Make_Identifier (Sloc (Id), Chars (Id)));
832
833                   --  We don't have to play the delay game here, since the only
834                   --  values are check names which don't get analyzed anyway.
835
836                   Delay_Required := False;
837
838                --  Aspects corresponding to pragmas with two arguments, where
839                --  the second argument is a local name referring to the entity,
840                --  and the first argument is the aspect definition expression.
841
842                when Aspect_Warnings =>
843
844                   --  Construct the pragma
845
846                   Aitem :=
847                     Make_Pragma (Sloc (Aspect),
848                       Pragma_Argument_Associations => New_List (
849                         Relocate_Node (Expr),
850                         New_Occurrence_Of (E, Sloc (Expr))),
851                       Pragma_Identifier            =>
852                          Make_Identifier (Sloc (Id), Chars (Id)));
853
854                   --  We don't have to play the delay game here, since the only
855                   --  values are check names which don't get analyzed anyway.
856
857                   Delay_Required := False;
858
859                --  Aspect Post corresponds to pragma Postcondition with single
860                --  argument that is the expression (we never give a message
861                --  argument. This is inserted right after the declaration,
862                --  to get the required pragma placement.
863
864                when Aspect_Post =>
865
866                   --  Construct the pragma
867
868                   Aitem :=
869                     Make_Pragma (Sloc (Expr),
870                       Pragma_Argument_Associations => New_List (
871                         Relocate_Node (Expr)),
872                       Pragma_Identifier            =>
873                       Make_Identifier (Sloc (Id), Name_Postcondition));
874
875                   --  We don't have to play the delay game here. The required
876                   --  delay in this case is already implemented by the pragma.
877
878                   Delay_Required := False;
879
880                --  Aspect Pre corresponds to pragma Precondition with single
881                --  argument that is the expression (we never give a message
882                --  argument). This is inserted right after the declaration,
883                --  to get the required pragma placement.
884
885                when Aspect_Pre =>
886
887                   --  Construct the pragma
888
889                   Aitem :=
890                     Make_Pragma (Sloc (Expr),
891                       Pragma_Argument_Associations => New_List (
892                         Relocate_Node (Expr)),
893                       Pragma_Identifier            =>
894                         Make_Identifier (Sloc (Id), Name_Precondition));
895
896                   --  We don't have to play the delay game here. The required
897                   --  delay in this case is already implemented by the pragma.
898
899                   Delay_Required := False;
900
901                --  Aspects currently unimplemented
902
903                when Aspect_Invariant |
904                     Aspect_Predicate =>
905
906                   Error_Msg_N ("aspect& not implemented", Identifier (Aspect));
907                   goto Continue;
908             end case;
909
910             Set_From_Aspect_Specification (Aitem, True);
911
912             --  If a delay is required, we delay the freeze (not much point in
913             --  delaying the aspect if we don't delay the freeze!). The pragma
914             --  or clause is then attached to the aspect specification which
915             --  is placed in the rep item list.
916
917             if Delay_Required then
918                Ensure_Freeze_Node (E);
919                Set_Is_Delayed_Aspect (Aitem);
920                Set_Has_Delayed_Aspects (E);
921                Set_Aspect_Rep_Item (Aspect, Aitem);
922                Record_Rep_Item (E, Aspect);
923
924             --  If no delay required, insert the pragma/clause in the tree
925
926             else
927                --  For Pre/Post cases, insert immediately after the entity
928                --  declaration, since that is the required pragma placement.
929
930                if A_Id = Aspect_Pre or else A_Id = Aspect_Post then
931                   Insert_After (N, Aitem);
932
933                --  For all other cases, insert in sequence
934
935                else
936                   Insert_After (Ins_Node, Aitem);
937                   Ins_Node := Aitem;
938                end if;
939             end if;
940          end;
941
942          <<Continue>>
943             Next (Aspect);
944       end loop;
945    end Analyze_Aspect_Specifications;
946
947    -----------------------
948    -- Analyze_At_Clause --
949    -----------------------
950
951    --  An at clause is replaced by the corresponding Address attribute
952    --  definition clause that is the preferred approach in Ada 95.
953
954    procedure Analyze_At_Clause (N : Node_Id) is
955       CS : constant Boolean := Comes_From_Source (N);
956
957    begin
958       --  This is an obsolescent feature
959
960       Check_Restriction (No_Obsolescent_Features, N);
961
962       if Warn_On_Obsolescent_Feature then
963          Error_Msg_N
964            ("at clause is an obsolescent feature (RM J.7(2))?", N);
965          Error_Msg_N
966            ("\use address attribute definition clause instead?", N);
967       end if;
968
969       --  Rewrite as address clause
970
971       Rewrite (N,
972         Make_Attribute_Definition_Clause (Sloc (N),
973           Name  => Identifier (N),
974           Chars => Name_Address,
975           Expression => Expression (N)));
976
977       --  We preserve Comes_From_Source, since logically the clause still
978       --  comes from the source program even though it is changed in form.
979
980       Set_Comes_From_Source (N, CS);
981
982       --  Analyze rewritten clause
983
984       Analyze_Attribute_Definition_Clause (N);
985    end Analyze_At_Clause;
986
987    -----------------------------------------
988    -- Analyze_Attribute_Definition_Clause --
989    -----------------------------------------
990
991    procedure Analyze_Attribute_Definition_Clause (N : Node_Id) is
992       Loc   : constant Source_Ptr   := Sloc (N);
993       Nam   : constant Node_Id      := Name (N);
994       Attr  : constant Name_Id      := Chars (N);
995       Expr  : constant Node_Id      := Expression (N);
996       Id    : constant Attribute_Id := Get_Attribute_Id (Attr);
997       Ent   : Entity_Id;
998       U_Ent : Entity_Id;
999
1000       FOnly : Boolean := False;
1001       --  Reset to True for subtype specific attribute (Alignment, Size)
1002       --  and for stream attributes, i.e. those cases where in the call
1003       --  to Rep_Item_Too_Late, FOnly is set True so that only the freezing
1004       --  rules are checked. Note that the case of stream attributes is not
1005       --  clear from the RM, but see AI95-00137. Also, the RM seems to
1006       --  disallow Storage_Size for derived task types, but that is also
1007       --  clearly unintentional.
1008
1009       procedure Analyze_Stream_TSS_Definition (TSS_Nam : TSS_Name_Type);
1010       --  Common processing for 'Read, 'Write, 'Input and 'Output attribute
1011       --  definition clauses.
1012
1013       function Duplicate_Clause return Boolean;
1014       --  This routine checks if the aspect for U_Ent being given by attribute
1015       --  definition clause N is for an aspect that has already been specified,
1016       --  and if so gives an error message. If there is a duplicate, True is
1017       --  returned, otherwise if there is no error, False is returned.
1018
1019       -----------------------------------
1020       -- Analyze_Stream_TSS_Definition --
1021       -----------------------------------
1022
1023       procedure Analyze_Stream_TSS_Definition (TSS_Nam : TSS_Name_Type) is
1024          Subp : Entity_Id := Empty;
1025          I    : Interp_Index;
1026          It   : Interp;
1027          Pnam : Entity_Id;
1028
1029          Is_Read : constant Boolean := (TSS_Nam = TSS_Stream_Read);
1030
1031          function Has_Good_Profile (Subp : Entity_Id) return Boolean;
1032          --  Return true if the entity is a subprogram with an appropriate
1033          --  profile for the attribute being defined.
1034
1035          ----------------------
1036          -- Has_Good_Profile --
1037          ----------------------
1038
1039          function Has_Good_Profile (Subp : Entity_Id) return Boolean is
1040             F              : Entity_Id;
1041             Is_Function    : constant Boolean := (TSS_Nam = TSS_Stream_Input);
1042             Expected_Ekind : constant array (Boolean) of Entity_Kind :=
1043                                (False => E_Procedure, True => E_Function);
1044             Typ            : Entity_Id;
1045
1046          begin
1047             if Ekind (Subp) /= Expected_Ekind (Is_Function) then
1048                return False;
1049             end if;
1050
1051             F := First_Formal (Subp);
1052
1053             if No (F)
1054               or else Ekind (Etype (F)) /= E_Anonymous_Access_Type
1055               or else Designated_Type (Etype (F)) /=
1056                                Class_Wide_Type (RTE (RE_Root_Stream_Type))
1057             then
1058                return False;
1059             end if;
1060
1061             if not Is_Function then
1062                Next_Formal (F);
1063
1064                declare
1065                   Expected_Mode : constant array (Boolean) of Entity_Kind :=
1066                                     (False => E_In_Parameter,
1067                                      True  => E_Out_Parameter);
1068                begin
1069                   if Parameter_Mode (F) /= Expected_Mode (Is_Read) then
1070                      return False;
1071                   end if;
1072                end;
1073
1074                Typ := Etype (F);
1075
1076             else
1077                Typ := Etype (Subp);
1078             end if;
1079
1080             return Base_Type (Typ) = Base_Type (Ent)
1081               and then No (Next_Formal (F));
1082          end Has_Good_Profile;
1083
1084       --  Start of processing for Analyze_Stream_TSS_Definition
1085
1086       begin
1087          FOnly := True;
1088
1089          if not Is_Type (U_Ent) then
1090             Error_Msg_N ("local name must be a subtype", Nam);
1091             return;
1092          end if;
1093
1094          Pnam := TSS (Base_Type (U_Ent), TSS_Nam);
1095
1096          --  If Pnam is present, it can be either inherited from an ancestor
1097          --  type (in which case it is legal to redefine it for this type), or
1098          --  be a previous definition of the attribute for the same type (in
1099          --  which case it is illegal).
1100
1101          --  In the first case, it will have been analyzed already, and we
1102          --  can check that its profile does not match the expected profile
1103          --  for a stream attribute of U_Ent. In the second case, either Pnam
1104          --  has been analyzed (and has the expected profile), or it has not
1105          --  been analyzed yet (case of a type that has not been frozen yet
1106          --  and for which the stream attribute has been set using Set_TSS).
1107
1108          if Present (Pnam)
1109            and then (No (First_Entity (Pnam)) or else Has_Good_Profile (Pnam))
1110          then
1111             Error_Msg_Sloc := Sloc (Pnam);
1112             Error_Msg_Name_1 := Attr;
1113             Error_Msg_N ("% attribute already defined #", Nam);
1114             return;
1115          end if;
1116
1117          Analyze (Expr);
1118
1119          if Is_Entity_Name (Expr) then
1120             if not Is_Overloaded (Expr) then
1121                if Has_Good_Profile (Entity (Expr)) then
1122                   Subp := Entity (Expr);
1123                end if;
1124
1125             else
1126                Get_First_Interp (Expr, I, It);
1127                while Present (It.Nam) loop
1128                   if Has_Good_Profile (It.Nam) then
1129                      Subp := It.Nam;
1130                      exit;
1131                   end if;
1132
1133                   Get_Next_Interp (I, It);
1134                end loop;
1135             end if;
1136          end if;
1137
1138          if Present (Subp) then
1139             if Is_Abstract_Subprogram (Subp) then
1140                Error_Msg_N ("stream subprogram must not be abstract", Expr);
1141                return;
1142             end if;
1143
1144             Set_Entity (Expr, Subp);
1145             Set_Etype (Expr, Etype (Subp));
1146
1147             New_Stream_Subprogram (N, U_Ent, Subp, TSS_Nam);
1148
1149          else
1150             Error_Msg_Name_1 := Attr;
1151             Error_Msg_N ("incorrect expression for% attribute", Expr);
1152          end if;
1153       end Analyze_Stream_TSS_Definition;
1154
1155       ----------------------
1156       -- Duplicate_Clause --
1157       ----------------------
1158
1159       function Duplicate_Clause return Boolean is
1160          A : Node_Id;
1161
1162       begin
1163          --  Nothing to do if this attribute definition clause comes from
1164          --  an aspect specification, since we could not be duplicating an
1165          --  explicit clause, and we dealt with the case of duplicated aspects
1166          --  in Analyze_Aspect_Specifications.
1167
1168          if From_Aspect_Specification (N) then
1169             return False;
1170          end if;
1171
1172          --  Otherwise current clause may duplicate previous clause or a
1173          --  previously given aspect specification for the same aspect.
1174
1175          A := Get_Rep_Item_For_Entity (U_Ent, Chars (N));
1176
1177          if Present (A) then
1178             if Entity (A) = U_Ent then
1179                Error_Msg_Name_1 := Chars (N);
1180                Error_Msg_Sloc := Sloc (A);
1181                Error_Msg_NE ("aspect% for & previously specified#", N, U_Ent);
1182                return True;
1183             end if;
1184          end if;
1185
1186          return False;
1187       end Duplicate_Clause;
1188
1189    --  Start of processing for Analyze_Attribute_Definition_Clause
1190
1191    begin
1192       --  Process Ignore_Rep_Clauses option
1193
1194       if Ignore_Rep_Clauses then
1195          case Id is
1196
1197             --  The following should be ignored. They do not affect legality
1198             --  and may be target dependent. The basic idea of -gnatI is to
1199             --  ignore any rep clauses that may be target dependent but do not
1200             --  affect legality (except possibly to be rejected because they
1201             --  are incompatible with the compilation target).
1202
1203             when Attribute_Alignment      |
1204                  Attribute_Bit_Order      |
1205                  Attribute_Component_Size |
1206                  Attribute_Machine_Radix  |
1207                  Attribute_Object_Size    |
1208                  Attribute_Size           |
1209                  Attribute_Small          |
1210                  Attribute_Stream_Size    |
1211                  Attribute_Value_Size     =>
1212
1213                Rewrite (N, Make_Null_Statement (Sloc (N)));
1214                return;
1215
1216             --  The following should not be ignored, because in the first place
1217             --  they are reasonably portable, and should not cause problems in
1218             --  compiling code from another target, and also they do affect
1219             --  legality, e.g. failing to provide a stream attribute for a
1220             --  type may make a program illegal.
1221
1222             when Attribute_External_Tag   |
1223                  Attribute_Input          |
1224                  Attribute_Output         |
1225                  Attribute_Read           |
1226                  Attribute_Storage_Pool   |
1227                  Attribute_Storage_Size   |
1228                  Attribute_Write          =>
1229                null;
1230
1231             --  Other cases are errors ("attribute& cannot be set with
1232             --  definition clause"), which will be caught below.
1233
1234             when others =>
1235                null;
1236          end case;
1237       end if;
1238
1239       Analyze (Nam);
1240       Ent := Entity (Nam);
1241
1242       if Rep_Item_Too_Early (Ent, N) then
1243          return;
1244       end if;
1245
1246       --  Rep clause applies to full view of incomplete type or private type if
1247       --  we have one (if not, this is a premature use of the type). However,
1248       --  certain semantic checks need to be done on the specified entity (i.e.
1249       --  the private view), so we save it in Ent.
1250
1251       if Is_Private_Type (Ent)
1252         and then Is_Derived_Type (Ent)
1253         and then not Is_Tagged_Type (Ent)
1254         and then No (Full_View (Ent))
1255       then
1256          --  If this is a private type whose completion is a derivation from
1257          --  another private type, there is no full view, and the attribute
1258          --  belongs to the type itself, not its underlying parent.
1259
1260          U_Ent := Ent;
1261
1262       elsif Ekind (Ent) = E_Incomplete_Type then
1263
1264          --  The attribute applies to the full view, set the entity of the
1265          --  attribute definition accordingly.
1266
1267          Ent := Underlying_Type (Ent);
1268          U_Ent := Ent;
1269          Set_Entity (Nam, Ent);
1270
1271       else
1272          U_Ent := Underlying_Type (Ent);
1273       end if;
1274
1275       --  Complete other routine error checks
1276
1277       if Etype (Nam) = Any_Type then
1278          return;
1279
1280       elsif Scope (Ent) /= Current_Scope then
1281          Error_Msg_N ("entity must be declared in this scope", Nam);
1282          return;
1283
1284       elsif No (U_Ent) then
1285          U_Ent := Ent;
1286
1287       elsif Is_Type (U_Ent)
1288         and then not Is_First_Subtype (U_Ent)
1289         and then Id /= Attribute_Object_Size
1290         and then Id /= Attribute_Value_Size
1291         and then not From_At_Mod (N)
1292       then
1293          Error_Msg_N ("cannot specify attribute for subtype", Nam);
1294          return;
1295       end if;
1296
1297       Set_Entity (N, U_Ent);
1298
1299       --  Switch on particular attribute
1300
1301       case Id is
1302
1303          -------------
1304          -- Address --
1305          -------------
1306
1307          --  Address attribute definition clause
1308
1309          when Attribute_Address => Address : begin
1310
1311             --  A little error check, catch for X'Address use X'Address;
1312
1313             if Nkind (Nam) = N_Identifier
1314               and then Nkind (Expr) = N_Attribute_Reference
1315               and then Attribute_Name (Expr) = Name_Address
1316               and then Nkind (Prefix (Expr)) = N_Identifier
1317               and then Chars (Nam) = Chars (Prefix (Expr))
1318             then
1319                Error_Msg_NE
1320                  ("address for & is self-referencing", Prefix (Expr), Ent);
1321                return;
1322             end if;
1323
1324             --  Not that special case, carry on with analysis of expression
1325
1326             Analyze_And_Resolve (Expr, RTE (RE_Address));
1327
1328             --  Even when ignoring rep clauses we need to indicate that the
1329             --  entity has an address clause and thus it is legal to declare
1330             --  it imported.
1331
1332             if Ignore_Rep_Clauses then
1333                if Ekind_In (U_Ent, E_Variable, E_Constant) then
1334                   Record_Rep_Item (U_Ent, N);
1335                end if;
1336
1337                return;
1338             end if;
1339
1340             if Duplicate_Clause then
1341                null;
1342
1343             --  Case of address clause for subprogram
1344
1345             elsif Is_Subprogram (U_Ent) then
1346                if Has_Homonym (U_Ent) then
1347                   Error_Msg_N
1348                     ("address clause cannot be given " &
1349                      "for overloaded subprogram",
1350                      Nam);
1351                   return;
1352                end if;
1353
1354                --  For subprograms, all address clauses are permitted, and we
1355                --  mark the subprogram as having a deferred freeze so that Gigi
1356                --  will not elaborate it too soon.
1357
1358                --  Above needs more comments, what is too soon about???
1359
1360                Set_Has_Delayed_Freeze (U_Ent);
1361
1362             --  Case of address clause for entry
1363
1364             elsif Ekind (U_Ent) = E_Entry then
1365                if Nkind (Parent (N)) = N_Task_Body then
1366                   Error_Msg_N
1367                     ("entry address must be specified in task spec", Nam);
1368                   return;
1369                end if;
1370
1371                --  For entries, we require a constant address
1372
1373                Check_Constant_Address_Clause (Expr, U_Ent);
1374
1375                --  Special checks for task types
1376
1377                if Is_Task_Type (Scope (U_Ent))
1378                  and then Comes_From_Source (Scope (U_Ent))
1379                then
1380                   Error_Msg_N
1381                     ("?entry address declared for entry in task type", N);
1382                   Error_Msg_N
1383                     ("\?only one task can be declared of this type", N);
1384                end if;
1385
1386                --  Entry address clauses are obsolescent
1387
1388                Check_Restriction (No_Obsolescent_Features, N);
1389
1390                if Warn_On_Obsolescent_Feature then
1391                   Error_Msg_N
1392                     ("attaching interrupt to task entry is an " &
1393                      "obsolescent feature (RM J.7.1)?", N);
1394                   Error_Msg_N
1395                     ("\use interrupt procedure instead?", N);
1396                end if;
1397
1398             --  Case of an address clause for a controlled object which we
1399             --  consider to be erroneous.
1400
1401             elsif Is_Controlled (Etype (U_Ent))
1402               or else Has_Controlled_Component (Etype (U_Ent))
1403             then
1404                Error_Msg_NE
1405                  ("?controlled object& must not be overlaid", Nam, U_Ent);
1406                Error_Msg_N
1407                  ("\?Program_Error will be raised at run time", Nam);
1408                Insert_Action (Declaration_Node (U_Ent),
1409                  Make_Raise_Program_Error (Loc,
1410                    Reason => PE_Overlaid_Controlled_Object));
1411                return;
1412
1413             --  Case of address clause for a (non-controlled) object
1414
1415             elsif
1416               Ekind (U_Ent) = E_Variable
1417                 or else
1418               Ekind (U_Ent) = E_Constant
1419             then
1420                declare
1421                   Expr  : constant Node_Id := Expression (N);
1422                   O_Ent : Entity_Id;
1423                   Off   : Boolean;
1424
1425                begin
1426                   --  Exported variables cannot have an address clause, because
1427                   --  this cancels the effect of the pragma Export.
1428
1429                   if Is_Exported (U_Ent) then
1430                      Error_Msg_N
1431                        ("cannot export object with address clause", Nam);
1432                      return;
1433                   end if;
1434
1435                   Find_Overlaid_Entity (N, O_Ent, Off);
1436
1437                   --  Overlaying controlled objects is erroneous
1438
1439                   if Present (O_Ent)
1440                     and then (Has_Controlled_Component (Etype (O_Ent))
1441                                 or else Is_Controlled (Etype (O_Ent)))
1442                   then
1443                      Error_Msg_N
1444                        ("?cannot overlay with controlled object", Expr);
1445                      Error_Msg_N
1446                        ("\?Program_Error will be raised at run time", Expr);
1447                      Insert_Action (Declaration_Node (U_Ent),
1448                        Make_Raise_Program_Error (Loc,
1449                          Reason => PE_Overlaid_Controlled_Object));
1450                      return;
1451
1452                   elsif Present (O_Ent)
1453                     and then Ekind (U_Ent) = E_Constant
1454                     and then not Is_Constant_Object (O_Ent)
1455                   then
1456                      Error_Msg_N ("constant overlays a variable?", Expr);
1457
1458                   elsif Present (Renamed_Object (U_Ent)) then
1459                      Error_Msg_N
1460                        ("address clause not allowed"
1461                           & " for a renaming declaration (RM 13.1(6))", Nam);
1462                      return;
1463
1464                   --  Imported variables can have an address clause, but then
1465                   --  the import is pretty meaningless except to suppress
1466                   --  initializations, so we do not need such variables to
1467                   --  be statically allocated (and in fact it causes trouble
1468                   --  if the address clause is a local value).
1469
1470                   elsif Is_Imported (U_Ent) then
1471                      Set_Is_Statically_Allocated (U_Ent, False);
1472                   end if;
1473
1474                   --  We mark a possible modification of a variable with an
1475                   --  address clause, since it is likely aliasing is occurring.
1476
1477                   Note_Possible_Modification (Nam, Sure => False);
1478
1479                   --  Here we are checking for explicit overlap of one variable
1480                   --  by another, and if we find this then mark the overlapped
1481                   --  variable as also being volatile to prevent unwanted
1482                   --  optimizations. This is a significant pessimization so
1483                   --  avoid it when there is an offset, i.e. when the object
1484                   --  is composite; they cannot be optimized easily anyway.
1485
1486                   if Present (O_Ent)
1487                     and then Is_Object (O_Ent)
1488                     and then not Off
1489                   then
1490                      Set_Treat_As_Volatile (O_Ent);
1491                   end if;
1492
1493                   --  Legality checks on the address clause for initialized
1494                   --  objects is deferred until the freeze point, because
1495                   --  a subsequent pragma might indicate that the object is
1496                   --  imported and thus not initialized.
1497
1498                   Set_Has_Delayed_Freeze (U_Ent);
1499
1500                   --  If an initialization call has been generated for this
1501                   --  object, it needs to be deferred to after the freeze node
1502                   --  we have just now added, otherwise GIGI will see a
1503                   --  reference to the variable (as actual to the IP call)
1504                   --  before its definition.
1505
1506                   declare
1507                      Init_Call : constant Node_Id := Find_Init_Call (U_Ent, N);
1508                   begin
1509                      if Present (Init_Call) then
1510                         Remove (Init_Call);
1511                         Append_Freeze_Action (U_Ent, Init_Call);
1512                      end if;
1513                   end;
1514
1515                   if Is_Exported (U_Ent) then
1516                      Error_Msg_N
1517                        ("& cannot be exported if an address clause is given",
1518                         Nam);
1519                      Error_Msg_N
1520                        ("\define and export a variable " &
1521                         "that holds its address instead",
1522                         Nam);
1523                   end if;
1524
1525                   --  Entity has delayed freeze, so we will generate an
1526                   --  alignment check at the freeze point unless suppressed.
1527
1528                   if not Range_Checks_Suppressed (U_Ent)
1529                     and then not Alignment_Checks_Suppressed (U_Ent)
1530                   then
1531                      Set_Check_Address_Alignment (N);
1532                   end if;
1533
1534                   --  Kill the size check code, since we are not allocating
1535                   --  the variable, it is somewhere else.
1536
1537                   Kill_Size_Check_Code (U_Ent);
1538
1539                   --  If the address clause is of the form:
1540
1541                   --    for Y'Address use X'Address
1542
1543                   --  or
1544
1545                   --    Const : constant Address := X'Address;
1546                   --    ...
1547                   --    for Y'Address use Const;
1548
1549                   --  then we make an entry in the table for checking the size
1550                   --  and alignment of the overlaying variable. We defer this
1551                   --  check till after code generation to take full advantage
1552                   --  of the annotation done by the back end. This entry is
1553                   --  only made if the address clause comes from source.
1554                   --  If the entity has a generic type, the check will be
1555                   --  performed in the instance if the actual type justifies
1556                   --  it, and we do not insert the clause in the table to
1557                   --  prevent spurious warnings.
1558
1559                   if Address_Clause_Overlay_Warnings
1560                     and then Comes_From_Source (N)
1561                     and then Present (O_Ent)
1562                     and then Is_Object (O_Ent)
1563                   then
1564                      if not Is_Generic_Type (Etype (U_Ent)) then
1565                         Address_Clause_Checks.Append ((N, U_Ent, O_Ent, Off));
1566                      end if;
1567
1568                      --  If variable overlays a constant view, and we are
1569                      --  warning on overlays, then mark the variable as
1570                      --  overlaying a constant (we will give warnings later
1571                      --  if this variable is assigned).
1572
1573                      if Is_Constant_Object (O_Ent)
1574                        and then Ekind (U_Ent) = E_Variable
1575                      then
1576                         Set_Overlays_Constant (U_Ent);
1577                      end if;
1578                   end if;
1579                end;
1580
1581             --  Not a valid entity for an address clause
1582
1583             else
1584                Error_Msg_N ("address cannot be given for &", Nam);
1585             end if;
1586          end Address;
1587
1588          ---------------
1589          -- Alignment --
1590          ---------------
1591
1592          --  Alignment attribute definition clause
1593
1594          when Attribute_Alignment => Alignment : declare
1595             Align : constant Uint := Get_Alignment_Value (Expr);
1596
1597          begin
1598             FOnly := True;
1599
1600             if not Is_Type (U_Ent)
1601               and then Ekind (U_Ent) /= E_Variable
1602               and then Ekind (U_Ent) /= E_Constant
1603             then
1604                Error_Msg_N ("alignment cannot be given for &", Nam);
1605
1606             elsif Duplicate_Clause then
1607                null;
1608
1609             elsif Align /= No_Uint then
1610                Set_Has_Alignment_Clause (U_Ent);
1611                Set_Alignment            (U_Ent, Align);
1612
1613                --  For an array type, U_Ent is the first subtype. In that case,
1614                --  also set the alignment of the anonymous base type so that
1615                --  other subtypes (such as the itypes for aggregates of the
1616                --  type) also receive the expected alignment.
1617
1618                if Is_Array_Type (U_Ent) then
1619                   Set_Alignment (Base_Type (U_Ent), Align);
1620                end if;
1621             end if;
1622          end Alignment;
1623
1624          ---------------
1625          -- Bit_Order --
1626          ---------------
1627
1628          --  Bit_Order attribute definition clause
1629
1630          when Attribute_Bit_Order => Bit_Order : declare
1631          begin
1632             if not Is_Record_Type (U_Ent) then
1633                Error_Msg_N
1634                  ("Bit_Order can only be defined for record type", Nam);
1635
1636             elsif Duplicate_Clause then
1637                null;
1638
1639             else
1640                Analyze_And_Resolve (Expr, RTE (RE_Bit_Order));
1641
1642                if Etype (Expr) = Any_Type then
1643                   return;
1644
1645                elsif not Is_Static_Expression (Expr) then
1646                   Flag_Non_Static_Expr
1647                     ("Bit_Order requires static expression!", Expr);
1648
1649                else
1650                   if (Expr_Value (Expr) = 0) /= Bytes_Big_Endian then
1651                      Set_Reverse_Bit_Order (U_Ent, True);
1652                   end if;
1653                end if;
1654             end if;
1655          end Bit_Order;
1656
1657          --------------------
1658          -- Component_Size --
1659          --------------------
1660
1661          --  Component_Size attribute definition clause
1662
1663          when Attribute_Component_Size => Component_Size_Case : declare
1664             Csize    : constant Uint := Static_Integer (Expr);
1665             Ctyp     : Entity_Id;
1666             Btype    : Entity_Id;
1667             Biased   : Boolean;
1668             New_Ctyp : Entity_Id;
1669             Decl     : Node_Id;
1670
1671          begin
1672             if not Is_Array_Type (U_Ent) then
1673                Error_Msg_N ("component size requires array type", Nam);
1674                return;
1675             end if;
1676
1677             Btype := Base_Type (U_Ent);
1678             Ctyp := Component_Type (Btype);
1679
1680             if Duplicate_Clause then
1681                null;
1682
1683             elsif Rep_Item_Too_Early (Btype, N) then
1684                null;
1685
1686             elsif Csize /= No_Uint then
1687                Check_Size (Expr, Ctyp, Csize, Biased);
1688
1689                --  For the biased case, build a declaration for a subtype that
1690                --  will be used to represent the biased subtype that reflects
1691                --  the biased representation of components. We need the subtype
1692                --  to get proper conversions on referencing elements of the
1693                --  array. Note: component size clauses are ignored in VM mode.
1694
1695                if VM_Target = No_VM then
1696                   if Biased then
1697                      New_Ctyp :=
1698                        Make_Defining_Identifier (Loc,
1699                          Chars =>
1700                            New_External_Name (Chars (U_Ent), 'C', 0, 'T'));
1701
1702                      Decl :=
1703                        Make_Subtype_Declaration (Loc,
1704                          Defining_Identifier => New_Ctyp,
1705                          Subtype_Indication  =>
1706                            New_Occurrence_Of (Component_Type (Btype), Loc));
1707
1708                      Set_Parent (Decl, N);
1709                      Analyze (Decl, Suppress => All_Checks);
1710
1711                      Set_Has_Delayed_Freeze        (New_Ctyp, False);
1712                      Set_Esize                     (New_Ctyp, Csize);
1713                      Set_RM_Size                   (New_Ctyp, Csize);
1714                      Init_Alignment                (New_Ctyp);
1715                      Set_Is_Itype                  (New_Ctyp, True);
1716                      Set_Associated_Node_For_Itype (New_Ctyp, U_Ent);
1717
1718                      Set_Component_Type (Btype, New_Ctyp);
1719                      Set_Biased (New_Ctyp, N, "component size clause");
1720                   end if;
1721
1722                   Set_Component_Size (Btype, Csize);
1723
1724                --  For VM case, we ignore component size clauses
1725
1726                else
1727                   --  Give a warning unless we are in GNAT mode, in which case
1728                   --  the warning is suppressed since it is not useful.
1729
1730                   if not GNAT_Mode then
1731                      Error_Msg_N
1732                        ("?component size ignored in this configuration", N);
1733                   end if;
1734                end if;
1735
1736                --  Deal with warning on overridden size
1737
1738                if Warn_On_Overridden_Size
1739                  and then Has_Size_Clause (Ctyp)
1740                  and then RM_Size (Ctyp) /= Csize
1741                then
1742                   Error_Msg_NE
1743                     ("?component size overrides size clause for&",
1744                      N, Ctyp);
1745                end if;
1746
1747                Set_Has_Component_Size_Clause (Btype, True);
1748                Set_Has_Non_Standard_Rep (Btype, True);
1749             end if;
1750          end Component_Size_Case;
1751
1752          ------------------
1753          -- External_Tag --
1754          ------------------
1755
1756          when Attribute_External_Tag => External_Tag :
1757          begin
1758             if not Is_Tagged_Type (U_Ent) then
1759                Error_Msg_N ("should be a tagged type", Nam);
1760             end if;
1761
1762             if Duplicate_Clause then
1763                null;
1764
1765             else
1766                Analyze_And_Resolve (Expr, Standard_String);
1767
1768                if not Is_Static_Expression (Expr) then
1769                   Flag_Non_Static_Expr
1770                     ("static string required for tag name!", Nam);
1771                end if;
1772
1773                if VM_Target = No_VM then
1774                   Set_Has_External_Tag_Rep_Clause (U_Ent);
1775                else
1776                   Error_Msg_Name_1 := Attr;
1777                   Error_Msg_N
1778                     ("% attribute unsupported in this configuration", Nam);
1779                end if;
1780
1781                if not Is_Library_Level_Entity (U_Ent) then
1782                   Error_Msg_NE
1783                     ("?non-unique external tag supplied for &", N, U_Ent);
1784                   Error_Msg_N
1785                     ("?\same external tag applies to all subprogram calls", N);
1786                   Error_Msg_N
1787                     ("?\corresponding internal tag cannot be obtained", N);
1788                end if;
1789             end if;
1790          end External_Tag;
1791
1792          -----------
1793          -- Input --
1794          -----------
1795
1796          when Attribute_Input =>
1797             Analyze_Stream_TSS_Definition (TSS_Stream_Input);
1798             Set_Has_Specified_Stream_Input (Ent);
1799
1800          -------------------
1801          -- Machine_Radix --
1802          -------------------
1803
1804          --  Machine radix attribute definition clause
1805
1806          when Attribute_Machine_Radix => Machine_Radix : declare
1807             Radix : constant Uint := Static_Integer (Expr);
1808
1809          begin
1810             if not Is_Decimal_Fixed_Point_Type (U_Ent) then
1811                Error_Msg_N ("decimal fixed-point type expected for &", Nam);
1812
1813             elsif Duplicate_Clause then
1814                null;
1815
1816             elsif Radix /= No_Uint then
1817                Set_Has_Machine_Radix_Clause (U_Ent);
1818                Set_Has_Non_Standard_Rep (Base_Type (U_Ent));
1819
1820                if Radix = 2 then
1821                   null;
1822                elsif Radix = 10 then
1823                   Set_Machine_Radix_10 (U_Ent);
1824                else
1825                   Error_Msg_N ("machine radix value must be 2 or 10", Expr);
1826                end if;
1827             end if;
1828          end Machine_Radix;
1829
1830          -----------------
1831          -- Object_Size --
1832          -----------------
1833
1834          --  Object_Size attribute definition clause
1835
1836          when Attribute_Object_Size => Object_Size : declare
1837             Size : constant Uint := Static_Integer (Expr);
1838
1839             Biased : Boolean;
1840             pragma Warnings (Off, Biased);
1841
1842          begin
1843             if not Is_Type (U_Ent) then
1844                Error_Msg_N ("Object_Size cannot be given for &", Nam);
1845
1846             elsif Duplicate_Clause then
1847                null;
1848
1849             else
1850                Check_Size (Expr, U_Ent, Size, Biased);
1851
1852                if Size /= 8
1853                     and then
1854                   Size /= 16
1855                     and then
1856                   Size /= 32
1857                     and then
1858                   UI_Mod (Size, 64) /= 0
1859                then
1860                   Error_Msg_N
1861                     ("Object_Size must be 8, 16, 32, or multiple of 64",
1862                      Expr);
1863                end if;
1864
1865                Set_Esize (U_Ent, Size);
1866                Set_Has_Object_Size_Clause (U_Ent);
1867                Alignment_Check_For_Esize_Change (U_Ent);
1868             end if;
1869          end Object_Size;
1870
1871          ------------
1872          -- Output --
1873          ------------
1874
1875          when Attribute_Output =>
1876             Analyze_Stream_TSS_Definition (TSS_Stream_Output);
1877             Set_Has_Specified_Stream_Output (Ent);
1878
1879          ----------
1880          -- Read --
1881          ----------
1882
1883          when Attribute_Read =>
1884             Analyze_Stream_TSS_Definition (TSS_Stream_Read);
1885             Set_Has_Specified_Stream_Read (Ent);
1886
1887          ----------
1888          -- Size --
1889          ----------
1890
1891          --  Size attribute definition clause
1892
1893          when Attribute_Size => Size : declare
1894             Size   : constant Uint := Static_Integer (Expr);
1895             Etyp   : Entity_Id;
1896             Biased : Boolean;
1897
1898          begin
1899             FOnly := True;
1900
1901             if Duplicate_Clause then
1902                null;
1903
1904             elsif not Is_Type (U_Ent)
1905               and then Ekind (U_Ent) /= E_Variable
1906               and then Ekind (U_Ent) /= E_Constant
1907             then
1908                Error_Msg_N ("size cannot be given for &", Nam);
1909
1910             elsif Is_Array_Type (U_Ent)
1911               and then not Is_Constrained (U_Ent)
1912             then
1913                Error_Msg_N
1914                  ("size cannot be given for unconstrained array", Nam);
1915
1916             elsif Size /= No_Uint then
1917
1918                if VM_Target /= No_VM and then not GNAT_Mode then
1919
1920                   --  Size clause is not handled properly on VM targets.
1921                   --  Display a warning unless we are in GNAT mode, in which
1922                   --  case this is useless.
1923
1924                   Error_Msg_N
1925                     ("?size clauses are ignored in this configuration", N);
1926                end if;
1927
1928                if Is_Type (U_Ent) then
1929                   Etyp := U_Ent;
1930                else
1931                   Etyp := Etype (U_Ent);
1932                end if;
1933
1934                --  Check size, note that Gigi is in charge of checking that the
1935                --  size of an array or record type is OK. Also we do not check
1936                --  the size in the ordinary fixed-point case, since it is too
1937                --  early to do so (there may be subsequent small clause that
1938                --  affects the size). We can check the size if a small clause
1939                --  has already been given.
1940
1941                if not Is_Ordinary_Fixed_Point_Type (U_Ent)
1942                  or else Has_Small_Clause (U_Ent)
1943                then
1944                   Check_Size (Expr, Etyp, Size, Biased);
1945                   Set_Biased (U_Ent, N, "size clause", Biased);
1946                end if;
1947
1948                --  For types set RM_Size and Esize if possible
1949
1950                if Is_Type (U_Ent) then
1951                   Set_RM_Size (U_Ent, Size);
1952
1953                   --  For scalar types, increase Object_Size to power of 2, but
1954                   --  not less than a storage unit in any case (i.e., normally
1955                   --  this means it will be byte addressable).
1956
1957                   if Is_Scalar_Type (U_Ent) then
1958                      if Size <= System_Storage_Unit then
1959                         Init_Esize (U_Ent, System_Storage_Unit);
1960                      elsif Size <= 16 then
1961                         Init_Esize (U_Ent, 16);
1962                      elsif Size <= 32 then
1963                         Init_Esize (U_Ent, 32);
1964                      else
1965                         Set_Esize  (U_Ent, (Size + 63) / 64 * 64);
1966                      end if;
1967
1968                   --  For all other types, object size = value size. The
1969                   --  backend will adjust as needed.
1970
1971                   else
1972                      Set_Esize (U_Ent, Size);
1973                   end if;
1974
1975                   Alignment_Check_For_Esize_Change (U_Ent);
1976
1977                --  For objects, set Esize only
1978
1979                else
1980                   if Is_Elementary_Type (Etyp) then
1981                      if Size /= System_Storage_Unit
1982                           and then
1983                         Size /= System_Storage_Unit * 2
1984                           and then
1985                         Size /= System_Storage_Unit * 4
1986                            and then
1987                         Size /= System_Storage_Unit * 8
1988                      then
1989                         Error_Msg_Uint_1 := UI_From_Int (System_Storage_Unit);
1990                         Error_Msg_Uint_2 := Error_Msg_Uint_1 * 8;
1991                         Error_Msg_N
1992                           ("size for primitive object must be a power of 2"
1993                             & " in the range ^-^", N);
1994                      end if;
1995                   end if;
1996
1997                   Set_Esize (U_Ent, Size);
1998                end if;
1999
2000                Set_Has_Size_Clause (U_Ent);
2001             end if;
2002          end Size;
2003
2004          -----------
2005          -- Small --
2006          -----------
2007
2008          --  Small attribute definition clause
2009
2010          when Attribute_Small => Small : declare
2011             Implicit_Base : constant Entity_Id := Base_Type (U_Ent);
2012             Small         : Ureal;
2013
2014          begin
2015             Analyze_And_Resolve (Expr, Any_Real);
2016
2017             if Etype (Expr) = Any_Type then
2018                return;
2019
2020             elsif not Is_Static_Expression (Expr) then
2021                Flag_Non_Static_Expr
2022                  ("small requires static expression!", Expr);
2023                return;
2024
2025             else
2026                Small := Expr_Value_R (Expr);
2027
2028                if Small <= Ureal_0 then
2029                   Error_Msg_N ("small value must be greater than zero", Expr);
2030                   return;
2031                end if;
2032
2033             end if;
2034
2035             if not Is_Ordinary_Fixed_Point_Type (U_Ent) then
2036                Error_Msg_N
2037                  ("small requires an ordinary fixed point type", Nam);
2038
2039             elsif Has_Small_Clause (U_Ent) then
2040                Error_Msg_N ("small already given for &", Nam);
2041
2042             elsif Small > Delta_Value (U_Ent) then
2043                Error_Msg_N
2044                  ("small value must not be greater then delta value", Nam);
2045
2046             else
2047                Set_Small_Value (U_Ent, Small);
2048                Set_Small_Value (Implicit_Base, Small);
2049                Set_Has_Small_Clause (U_Ent);
2050                Set_Has_Small_Clause (Implicit_Base);
2051                Set_Has_Non_Standard_Rep (Implicit_Base);
2052             end if;
2053          end Small;
2054
2055          ------------------
2056          -- Storage_Pool --
2057          ------------------
2058
2059          --  Storage_Pool attribute definition clause
2060
2061          when Attribute_Storage_Pool => Storage_Pool : declare
2062             Pool : Entity_Id;
2063             T    : Entity_Id;
2064
2065          begin
2066             if Ekind (U_Ent) = E_Access_Subprogram_Type then
2067                Error_Msg_N
2068                  ("storage pool cannot be given for access-to-subprogram type",
2069                   Nam);
2070                return;
2071
2072             elsif not
2073               Ekind_In (U_Ent, E_Access_Type, E_General_Access_Type)
2074             then
2075                Error_Msg_N
2076                  ("storage pool can only be given for access types", Nam);
2077                return;
2078
2079             elsif Is_Derived_Type (U_Ent) then
2080                Error_Msg_N
2081                  ("storage pool cannot be given for a derived access type",
2082                   Nam);
2083
2084             elsif Duplicate_Clause then
2085                return;
2086
2087             elsif Present (Associated_Storage_Pool (U_Ent)) then
2088                Error_Msg_N ("storage pool already given for &", Nam);
2089                return;
2090             end if;
2091
2092             Analyze_And_Resolve
2093               (Expr, Class_Wide_Type (RTE (RE_Root_Storage_Pool)));
2094
2095             if not Denotes_Variable (Expr) then
2096                Error_Msg_N ("storage pool must be a variable", Expr);
2097                return;
2098             end if;
2099
2100             if Nkind (Expr) = N_Type_Conversion then
2101                T := Etype (Expression (Expr));
2102             else
2103                T := Etype (Expr);
2104             end if;
2105
2106             --  The Stack_Bounded_Pool is used internally for implementing
2107             --  access types with a Storage_Size. Since it only work
2108             --  properly when used on one specific type, we need to check
2109             --  that it is not hijacked improperly:
2110             --    type T is access Integer;
2111             --    for T'Storage_Size use n;
2112             --    type Q is access Float;
2113             --    for Q'Storage_Size use T'Storage_Size; -- incorrect
2114
2115             if RTE_Available (RE_Stack_Bounded_Pool)
2116               and then Base_Type (T) = RTE (RE_Stack_Bounded_Pool)
2117             then
2118                Error_Msg_N ("non-shareable internal Pool", Expr);
2119                return;
2120             end if;
2121
2122             --  If the argument is a name that is not an entity name, then
2123             --  we construct a renaming operation to define an entity of
2124             --  type storage pool.
2125
2126             if not Is_Entity_Name (Expr)
2127               and then Is_Object_Reference (Expr)
2128             then
2129                Pool := Make_Temporary (Loc, 'P', Expr);
2130
2131                declare
2132                   Rnode : constant Node_Id :=
2133                             Make_Object_Renaming_Declaration (Loc,
2134                               Defining_Identifier => Pool,
2135                               Subtype_Mark        =>
2136                                 New_Occurrence_Of (Etype (Expr), Loc),
2137                               Name                => Expr);
2138
2139                begin
2140                   Insert_Before (N, Rnode);
2141                   Analyze (Rnode);
2142                   Set_Associated_Storage_Pool (U_Ent, Pool);
2143                end;
2144
2145             elsif Is_Entity_Name (Expr) then
2146                Pool := Entity (Expr);
2147
2148                --  If pool is a renamed object, get original one. This can
2149                --  happen with an explicit renaming, and within instances.
2150
2151                while Present (Renamed_Object (Pool))
2152                  and then Is_Entity_Name (Renamed_Object (Pool))
2153                loop
2154                   Pool := Entity (Renamed_Object (Pool));
2155                end loop;
2156
2157                if Present (Renamed_Object (Pool))
2158                  and then Nkind (Renamed_Object (Pool)) = N_Type_Conversion
2159                  and then Is_Entity_Name (Expression (Renamed_Object (Pool)))
2160                then
2161                   Pool := Entity (Expression (Renamed_Object (Pool)));
2162                end if;
2163
2164                Set_Associated_Storage_Pool (U_Ent, Pool);
2165
2166             elsif Nkind (Expr) = N_Type_Conversion
2167               and then Is_Entity_Name (Expression (Expr))
2168               and then Nkind (Original_Node (Expr)) = N_Attribute_Reference
2169             then
2170                Pool := Entity (Expression (Expr));
2171                Set_Associated_Storage_Pool (U_Ent, Pool);
2172
2173             else
2174                Error_Msg_N ("incorrect reference to a Storage Pool", Expr);
2175                return;
2176             end if;
2177          end Storage_Pool;
2178
2179          ------------------
2180          -- Storage_Size --
2181          ------------------
2182
2183          --  Storage_Size attribute definition clause
2184
2185          when Attribute_Storage_Size => Storage_Size : declare
2186             Btype : constant Entity_Id := Base_Type (U_Ent);
2187             Sprag : Node_Id;
2188
2189          begin
2190             if Is_Task_Type (U_Ent) then
2191                Check_Restriction (No_Obsolescent_Features, N);
2192
2193                if Warn_On_Obsolescent_Feature then
2194                   Error_Msg_N
2195                     ("storage size clause for task is an " &
2196                      "obsolescent feature (RM J.9)?", N);
2197                   Error_Msg_N ("\use Storage_Size pragma instead?", N);
2198                end if;
2199
2200                FOnly := True;
2201             end if;
2202
2203             if not Is_Access_Type (U_Ent)
2204               and then Ekind (U_Ent) /= E_Task_Type
2205             then
2206                Error_Msg_N ("storage size cannot be given for &", Nam);
2207
2208             elsif Is_Access_Type (U_Ent) and Is_Derived_Type (U_Ent) then
2209                Error_Msg_N
2210                  ("storage size cannot be given for a derived access type",
2211                   Nam);
2212
2213             elsif Duplicate_Clause then
2214                null;
2215
2216             else
2217                Analyze_And_Resolve (Expr, Any_Integer);
2218
2219                if Is_Access_Type (U_Ent) then
2220                   if Present (Associated_Storage_Pool (U_Ent)) then
2221                      Error_Msg_N ("storage pool already given for &", Nam);
2222                      return;
2223                   end if;
2224
2225                   if Is_OK_Static_Expression (Expr)
2226                     and then Expr_Value (Expr) = 0
2227                   then
2228                      Set_No_Pool_Assigned (Btype);
2229                   end if;
2230
2231                else -- Is_Task_Type (U_Ent)
2232                   Sprag := Get_Rep_Pragma (Btype, Name_Storage_Size);
2233
2234                   if Present (Sprag) then
2235                      Error_Msg_Sloc := Sloc (Sprag);
2236                      Error_Msg_N
2237                        ("Storage_Size already specified#", Nam);
2238                      return;
2239                   end if;
2240                end if;
2241
2242                Set_Has_Storage_Size_Clause (Btype);
2243             end if;
2244          end Storage_Size;
2245
2246          -----------------
2247          -- Stream_Size --
2248          -----------------
2249
2250          when Attribute_Stream_Size => Stream_Size : declare
2251             Size : constant Uint := Static_Integer (Expr);
2252
2253          begin
2254             if Ada_Version <= Ada_95 then
2255                Check_Restriction (No_Implementation_Attributes, N);
2256             end if;
2257
2258             if Duplicate_Clause then
2259                null;
2260
2261             elsif Is_Elementary_Type (U_Ent) then
2262                if Size /= System_Storage_Unit
2263                     and then
2264                   Size /= System_Storage_Unit * 2
2265                     and then
2266                   Size /= System_Storage_Unit * 4
2267                      and then
2268                   Size /= System_Storage_Unit * 8
2269                then
2270                   Error_Msg_Uint_1 := UI_From_Int (System_Storage_Unit);
2271                   Error_Msg_N
2272                     ("stream size for elementary type must be a"
2273                        & " power of 2 and at least ^", N);
2274
2275                elsif RM_Size (U_Ent) > Size then
2276                   Error_Msg_Uint_1 := RM_Size (U_Ent);
2277                   Error_Msg_N
2278                     ("stream size for elementary type must be a"
2279                        & " power of 2 and at least ^", N);
2280                end if;
2281
2282                Set_Has_Stream_Size_Clause (U_Ent);
2283
2284             else
2285                Error_Msg_N ("Stream_Size cannot be given for &", Nam);
2286             end if;
2287          end Stream_Size;
2288
2289          ----------------
2290          -- Value_Size --
2291          ----------------
2292
2293          --  Value_Size attribute definition clause
2294
2295          when Attribute_Value_Size => Value_Size : declare
2296             Size   : constant Uint := Static_Integer (Expr);
2297             Biased : Boolean;
2298
2299          begin
2300             if not Is_Type (U_Ent) then
2301                Error_Msg_N ("Value_Size cannot be given for &", Nam);
2302
2303             elsif Duplicate_Clause then
2304                null;
2305
2306             elsif Is_Array_Type (U_Ent)
2307               and then not Is_Constrained (U_Ent)
2308             then
2309                Error_Msg_N
2310                  ("Value_Size cannot be given for unconstrained array", Nam);
2311
2312             else
2313                if Is_Elementary_Type (U_Ent) then
2314                   Check_Size (Expr, U_Ent, Size, Biased);
2315                   Set_Biased (U_Ent, N, "value size clause", Biased);
2316                end if;
2317
2318                Set_RM_Size (U_Ent, Size);
2319             end if;
2320          end Value_Size;
2321
2322          -----------
2323          -- Write --
2324          -----------
2325
2326          when Attribute_Write =>
2327             Analyze_Stream_TSS_Definition (TSS_Stream_Write);
2328             Set_Has_Specified_Stream_Write (Ent);
2329
2330          --  All other attributes cannot be set
2331
2332          when others =>
2333             Error_Msg_N
2334               ("attribute& cannot be set with definition clause", N);
2335       end case;
2336
2337       --  The test for the type being frozen must be performed after
2338       --  any expression the clause has been analyzed since the expression
2339       --  itself might cause freezing that makes the clause illegal.
2340
2341       if Rep_Item_Too_Late (U_Ent, N, FOnly) then
2342          return;
2343       end if;
2344    end Analyze_Attribute_Definition_Clause;
2345
2346    ----------------------------
2347    -- Analyze_Code_Statement --
2348    ----------------------------
2349
2350    procedure Analyze_Code_Statement (N : Node_Id) is
2351       HSS   : constant Node_Id   := Parent (N);
2352       SBody : constant Node_Id   := Parent (HSS);
2353       Subp  : constant Entity_Id := Current_Scope;
2354       Stmt  : Node_Id;
2355       Decl  : Node_Id;
2356       StmtO : Node_Id;
2357       DeclO : Node_Id;
2358
2359    begin
2360       --  Analyze and check we get right type, note that this implements the
2361       --  requirement (RM 13.8(1)) that Machine_Code be with'ed, since that
2362       --  is the only way that Asm_Insn could possibly be visible.
2363
2364       Analyze_And_Resolve (Expression (N));
2365
2366       if Etype (Expression (N)) = Any_Type then
2367          return;
2368       elsif Etype (Expression (N)) /= RTE (RE_Asm_Insn) then
2369          Error_Msg_N ("incorrect type for code statement", N);
2370          return;
2371       end if;
2372
2373       Check_Code_Statement (N);
2374
2375       --  Make sure we appear in the handled statement sequence of a
2376       --  subprogram (RM 13.8(3)).
2377
2378       if Nkind (HSS) /= N_Handled_Sequence_Of_Statements
2379         or else Nkind (SBody) /= N_Subprogram_Body
2380       then
2381          Error_Msg_N
2382            ("code statement can only appear in body of subprogram", N);
2383          return;
2384       end if;
2385
2386       --  Do remaining checks (RM 13.8(3)) if not already done
2387
2388       if not Is_Machine_Code_Subprogram (Subp) then
2389          Set_Is_Machine_Code_Subprogram (Subp);
2390
2391          --  No exception handlers allowed
2392
2393          if Present (Exception_Handlers (HSS)) then
2394             Error_Msg_N
2395               ("exception handlers not permitted in machine code subprogram",
2396                First (Exception_Handlers (HSS)));
2397          end if;
2398
2399          --  No declarations other than use clauses and pragmas (we allow
2400          --  certain internally generated declarations as well).
2401
2402          Decl := First (Declarations (SBody));
2403          while Present (Decl) loop
2404             DeclO := Original_Node (Decl);
2405             if Comes_From_Source (DeclO)
2406               and not Nkind_In (DeclO, N_Pragma,
2407                                        N_Use_Package_Clause,
2408                                        N_Use_Type_Clause,
2409                                        N_Implicit_Label_Declaration)
2410             then
2411                Error_Msg_N
2412                  ("this declaration not allowed in machine code subprogram",
2413                   DeclO);
2414             end if;
2415
2416             Next (Decl);
2417          end loop;
2418
2419          --  No statements other than code statements, pragmas, and labels.
2420          --  Again we allow certain internally generated statements.
2421
2422          Stmt := First (Statements (HSS));
2423          while Present (Stmt) loop
2424             StmtO := Original_Node (Stmt);
2425             if Comes_From_Source (StmtO)
2426               and then not Nkind_In (StmtO, N_Pragma,
2427                                             N_Label,
2428                                             N_Code_Statement)
2429             then
2430                Error_Msg_N
2431                  ("this statement is not allowed in machine code subprogram",
2432                   StmtO);
2433             end if;
2434
2435             Next (Stmt);
2436          end loop;
2437       end if;
2438    end Analyze_Code_Statement;
2439
2440    -----------------------------------------------
2441    -- Analyze_Enumeration_Representation_Clause --
2442    -----------------------------------------------
2443
2444    procedure Analyze_Enumeration_Representation_Clause (N : Node_Id) is
2445       Ident    : constant Node_Id    := Identifier (N);
2446       Aggr     : constant Node_Id    := Array_Aggregate (N);
2447       Enumtype : Entity_Id;
2448       Elit     : Entity_Id;
2449       Expr     : Node_Id;
2450       Assoc    : Node_Id;
2451       Choice   : Node_Id;
2452       Val      : Uint;
2453       Err      : Boolean := False;
2454
2455       Lo : constant Uint := Expr_Value (Type_Low_Bound (Universal_Integer));
2456       Hi : constant Uint := Expr_Value (Type_High_Bound (Universal_Integer));
2457       --  Allowed range of universal integer (= allowed range of enum lit vals)
2458
2459       Min : Uint;
2460       Max : Uint;
2461       --  Minimum and maximum values of entries
2462
2463       Max_Node : Node_Id;
2464       --  Pointer to node for literal providing max value
2465
2466    begin
2467       if Ignore_Rep_Clauses then
2468          return;
2469       end if;
2470
2471       --  First some basic error checks
2472
2473       Find_Type (Ident);
2474       Enumtype := Entity (Ident);
2475
2476       if Enumtype = Any_Type
2477         or else Rep_Item_Too_Early (Enumtype, N)
2478       then
2479          return;
2480       else
2481          Enumtype := Underlying_Type (Enumtype);
2482       end if;
2483
2484       if not Is_Enumeration_Type (Enumtype) then
2485          Error_Msg_NE
2486            ("enumeration type required, found}",
2487             Ident, First_Subtype (Enumtype));
2488          return;
2489       end if;
2490
2491       --  Ignore rep clause on generic actual type. This will already have
2492       --  been flagged on the template as an error, and this is the safest
2493       --  way to ensure we don't get a junk cascaded message in the instance.
2494
2495       if Is_Generic_Actual_Type (Enumtype) then
2496          return;
2497
2498       --  Type must be in current scope
2499
2500       elsif Scope (Enumtype) /= Current_Scope then
2501          Error_Msg_N ("type must be declared in this scope", Ident);
2502          return;
2503
2504       --  Type must be a first subtype
2505
2506       elsif not Is_First_Subtype (Enumtype) then
2507          Error_Msg_N ("cannot give enumeration rep clause for subtype", N);
2508          return;
2509
2510       --  Ignore duplicate rep clause
2511
2512       elsif Has_Enumeration_Rep_Clause (Enumtype) then
2513          Error_Msg_N ("duplicate enumeration rep clause ignored", N);
2514          return;
2515
2516       --  Don't allow rep clause for standard [wide_[wide_]]character
2517
2518       elsif Is_Standard_Character_Type (Enumtype) then
2519          Error_Msg_N ("enumeration rep clause not allowed for this type", N);
2520          return;
2521
2522       --  Check that the expression is a proper aggregate (no parentheses)
2523
2524       elsif Paren_Count (Aggr) /= 0 then
2525          Error_Msg
2526            ("extra parentheses surrounding aggregate not allowed",
2527             First_Sloc (Aggr));
2528          return;
2529
2530       --  All tests passed, so set rep clause in place
2531
2532       else
2533          Set_Has_Enumeration_Rep_Clause (Enumtype);
2534          Set_Has_Enumeration_Rep_Clause (Base_Type (Enumtype));
2535       end if;
2536
2537       --  Now we process the aggregate. Note that we don't use the normal
2538       --  aggregate code for this purpose, because we don't want any of the
2539       --  normal expansion activities, and a number of special semantic
2540       --  rules apply (including the component type being any integer type)
2541
2542       Elit := First_Literal (Enumtype);
2543
2544       --  First the positional entries if any
2545
2546       if Present (Expressions (Aggr)) then
2547          Expr := First (Expressions (Aggr));
2548          while Present (Expr) loop
2549             if No (Elit) then
2550                Error_Msg_N ("too many entries in aggregate", Expr);
2551                return;
2552             end if;
2553
2554             Val := Static_Integer (Expr);
2555
2556             --  Err signals that we found some incorrect entries processing
2557             --  the list. The final checks for completeness and ordering are
2558             --  skipped in this case.
2559
2560             if Val = No_Uint then
2561                Err := True;
2562             elsif Val < Lo or else Hi < Val then
2563                Error_Msg_N ("value outside permitted range", Expr);
2564                Err := True;
2565             end if;
2566
2567             Set_Enumeration_Rep (Elit, Val);
2568             Set_Enumeration_Rep_Expr (Elit, Expr);
2569             Next (Expr);
2570             Next (Elit);
2571          end loop;
2572       end if;
2573
2574       --  Now process the named entries if present
2575
2576       if Present (Component_Associations (Aggr)) then
2577          Assoc := First (Component_Associations (Aggr));
2578          while Present (Assoc) loop
2579             Choice := First (Choices (Assoc));
2580
2581             if Present (Next (Choice)) then
2582                Error_Msg_N
2583                  ("multiple choice not allowed here", Next (Choice));
2584                Err := True;
2585             end if;
2586
2587             if Nkind (Choice) = N_Others_Choice then
2588                Error_Msg_N ("others choice not allowed here", Choice);
2589                Err := True;
2590
2591             elsif Nkind (Choice) = N_Range then
2592                --  ??? should allow zero/one element range here
2593                Error_Msg_N ("range not allowed here", Choice);
2594                Err := True;
2595
2596             else
2597                Analyze_And_Resolve (Choice, Enumtype);
2598
2599                if Is_Entity_Name (Choice)
2600                  and then Is_Type (Entity (Choice))
2601                then
2602                   Error_Msg_N ("subtype name not allowed here", Choice);
2603                   Err := True;
2604                   --  ??? should allow static subtype with zero/one entry
2605
2606                elsif Etype (Choice) = Base_Type (Enumtype) then
2607                   if not Is_Static_Expression (Choice) then
2608                      Flag_Non_Static_Expr
2609                        ("non-static expression used for choice!", Choice);
2610                      Err := True;
2611
2612                   else
2613                      Elit := Expr_Value_E (Choice);
2614
2615                      if Present (Enumeration_Rep_Expr (Elit)) then
2616                         Error_Msg_Sloc := Sloc (Enumeration_Rep_Expr (Elit));
2617                         Error_Msg_NE
2618                           ("representation for& previously given#",
2619                            Choice, Elit);
2620                         Err := True;
2621                      end if;
2622
2623                      Set_Enumeration_Rep_Expr (Elit, Expression (Assoc));
2624
2625                      Expr := Expression (Assoc);
2626                      Val := Static_Integer (Expr);
2627
2628                      if Val = No_Uint then
2629                         Err := True;
2630
2631                      elsif Val < Lo or else Hi < Val then
2632                         Error_Msg_N ("value outside permitted range", Expr);
2633                         Err := True;
2634                      end if;
2635
2636                      Set_Enumeration_Rep (Elit, Val);
2637                   end if;
2638                end if;
2639             end if;
2640
2641             Next (Assoc);
2642          end loop;
2643       end if;
2644
2645       --  Aggregate is fully processed. Now we check that a full set of
2646       --  representations was given, and that they are in range and in order.
2647       --  These checks are only done if no other errors occurred.
2648
2649       if not Err then
2650          Min  := No_Uint;
2651          Max  := No_Uint;
2652
2653          Elit := First_Literal (Enumtype);
2654          while Present (Elit) loop
2655             if No (Enumeration_Rep_Expr (Elit)) then
2656                Error_Msg_NE ("missing representation for&!", N, Elit);
2657
2658             else
2659                Val := Enumeration_Rep (Elit);
2660
2661                if Min = No_Uint then
2662                   Min := Val;
2663                end if;
2664
2665                if Val /= No_Uint then
2666                   if Max /= No_Uint and then Val <= Max then
2667                      Error_Msg_NE
2668                        ("enumeration value for& not ordered!",
2669                         Enumeration_Rep_Expr (Elit), Elit);
2670                   end if;
2671
2672                   Max_Node := Enumeration_Rep_Expr (Elit);
2673                   Max := Val;
2674                end if;
2675
2676                --  If there is at least one literal whose representation is not
2677                --  equal to the Pos value, then note that this enumeration type
2678                --  has a non-standard representation.
2679
2680                if Val /= Enumeration_Pos (Elit) then
2681                   Set_Has_Non_Standard_Rep (Base_Type (Enumtype));
2682                end if;
2683             end if;
2684
2685             Next (Elit);
2686          end loop;
2687
2688          --  Now set proper size information
2689
2690          declare
2691             Minsize : Uint := UI_From_Int (Minimum_Size (Enumtype));
2692
2693          begin
2694             if Has_Size_Clause (Enumtype) then
2695
2696                --  All OK, if size is OK now
2697
2698                if RM_Size (Enumtype) >= Minsize then
2699                   null;
2700
2701                else
2702                   --  Try if we can get by with biasing
2703
2704                   Minsize :=
2705                     UI_From_Int (Minimum_Size (Enumtype, Biased => True));
2706
2707                   --  Error message if even biasing does not work
2708
2709                   if RM_Size (Enumtype) < Minsize then
2710                      Error_Msg_Uint_1 := RM_Size (Enumtype);
2711                      Error_Msg_Uint_2 := Max;
2712                      Error_Msg_N
2713                        ("previously given size (^) is too small "
2714                         & "for this value (^)", Max_Node);
2715
2716                   --  If biasing worked, indicate that we now have biased rep
2717
2718                   else
2719                      Set_Biased
2720                        (Enumtype, Size_Clause (Enumtype), "size clause");
2721                   end if;
2722                end if;
2723
2724             else
2725                Set_RM_Size    (Enumtype, Minsize);
2726                Set_Enum_Esize (Enumtype);
2727             end if;
2728
2729             Set_RM_Size   (Base_Type (Enumtype), RM_Size   (Enumtype));
2730             Set_Esize     (Base_Type (Enumtype), Esize     (Enumtype));
2731             Set_Alignment (Base_Type (Enumtype), Alignment (Enumtype));
2732          end;
2733       end if;
2734
2735       --  We repeat the too late test in case it froze itself!
2736
2737       if Rep_Item_Too_Late (Enumtype, N) then
2738          null;
2739       end if;
2740    end Analyze_Enumeration_Representation_Clause;
2741
2742    ----------------------------
2743    -- Analyze_Free_Statement --
2744    ----------------------------
2745
2746    procedure Analyze_Free_Statement (N : Node_Id) is
2747    begin
2748       Analyze (Expression (N));
2749    end Analyze_Free_Statement;
2750
2751    ---------------------------
2752    -- Analyze_Freeze_Entity --
2753    ---------------------------
2754
2755    procedure Analyze_Freeze_Entity (N : Node_Id) is
2756       E : constant Entity_Id := Entity (N);
2757
2758    begin
2759       --  Remember that we are processing a freezing entity. Required to
2760       --  ensure correct decoration of internal entities associated with
2761       --  interfaces (see New_Overloaded_Entity).
2762
2763       Inside_Freezing_Actions := Inside_Freezing_Actions + 1;
2764
2765       --  For tagged types covering interfaces add internal entities that link
2766       --  the primitives of the interfaces with the primitives that cover them.
2767       --  Note: These entities were originally generated only when generating
2768       --  code because their main purpose was to provide support to initialize
2769       --  the secondary dispatch tables. They are now generated also when
2770       --  compiling with no code generation to provide ASIS the relationship
2771       --  between interface primitives and tagged type primitives. They are
2772       --  also used to locate primitives covering interfaces when processing
2773       --  generics (see Derive_Subprograms).
2774
2775       if Ada_Version >= Ada_2005
2776         and then Ekind (E) = E_Record_Type
2777         and then Is_Tagged_Type (E)
2778         and then not Is_Interface (E)
2779         and then Has_Interfaces (E)
2780       then
2781          --  This would be a good common place to call the routine that checks
2782          --  overriding of interface primitives (and thus factorize calls to
2783          --  Check_Abstract_Overriding located at different contexts in the
2784          --  compiler). However, this is not possible because it causes
2785          --  spurious errors in case of late overriding.
2786
2787          Add_Internal_Interface_Entities (E);
2788       end if;
2789
2790       --  Check CPP types
2791
2792       if Ekind (E) = E_Record_Type
2793         and then Is_CPP_Class (E)
2794         and then Is_Tagged_Type (E)
2795         and then Tagged_Type_Expansion
2796         and then Expander_Active
2797       then
2798          if CPP_Num_Prims (E) = 0 then
2799
2800             --  If the CPP type has user defined components then it must import
2801             --  primitives from C++. This is required because if the C++ class
2802             --  has no primitives then the C++ compiler does not added the _tag
2803             --  component to the type.
2804
2805             pragma Assert (Chars (First_Entity (E)) = Name_uTag);
2806
2807             if First_Entity (E) /= Last_Entity (E) then
2808                Error_Msg_N
2809                  ("?'C'P'P type must import at least one primitive from C++",
2810                   E);
2811             end if;
2812          end if;
2813
2814          --  Check that all its primitives are abstract or imported from C++.
2815          --  Check also availability of the C++ constructor.
2816
2817          declare
2818             Has_Constructors : constant Boolean := Has_CPP_Constructors (E);
2819             Elmt             : Elmt_Id;
2820             Error_Reported   : Boolean := False;
2821             Prim             : Node_Id;
2822
2823          begin
2824             Elmt := First_Elmt (Primitive_Operations (E));
2825             while Present (Elmt) loop
2826                Prim := Node (Elmt);
2827
2828                if Comes_From_Source (Prim) then
2829                   if Is_Abstract_Subprogram (Prim) then
2830                      null;
2831
2832                   elsif not Is_Imported (Prim)
2833                     or else Convention (Prim) /= Convention_CPP
2834                   then
2835                      Error_Msg_N
2836                        ("?primitives of 'C'P'P types must be imported from C++"
2837                         & " or abstract", Prim);
2838
2839                   elsif not Has_Constructors
2840                      and then not Error_Reported
2841                   then
2842                      Error_Msg_Name_1 := Chars (E);
2843                      Error_Msg_N
2844                        ("?'C'P'P constructor required for type %", Prim);
2845                      Error_Reported := True;
2846                   end if;
2847                end if;
2848
2849                Next_Elmt (Elmt);
2850             end loop;
2851          end;
2852       end if;
2853
2854       Inside_Freezing_Actions := Inside_Freezing_Actions - 1;
2855    end Analyze_Freeze_Entity;
2856
2857    ------------------------------------------
2858    -- Analyze_Record_Representation_Clause --
2859    ------------------------------------------
2860
2861    --  Note: we check as much as we can here, but we can't do any checks
2862    --  based on the position values (e.g. overlap checks) until freeze time
2863    --  because especially in Ada 2005 (machine scalar mode), the processing
2864    --  for non-standard bit order can substantially change the positions.
2865    --  See procedure Check_Record_Representation_Clause (called from Freeze)
2866    --  for the remainder of this processing.
2867
2868    procedure Analyze_Record_Representation_Clause (N : Node_Id) is
2869       Ident   : constant Node_Id := Identifier (N);
2870       Biased  : Boolean;
2871       CC      : Node_Id;
2872       Comp    : Entity_Id;
2873       Fbit    : Uint;
2874       Hbit    : Uint := Uint_0;
2875       Lbit    : Uint;
2876       Ocomp   : Entity_Id;
2877       Posit   : Uint;
2878       Rectype : Entity_Id;
2879
2880       CR_Pragma : Node_Id := Empty;
2881       --  Points to N_Pragma node if Complete_Representation pragma present
2882
2883    begin
2884       if Ignore_Rep_Clauses then
2885          return;
2886       end if;
2887
2888       Find_Type (Ident);
2889       Rectype := Entity (Ident);
2890
2891       if Rectype = Any_Type
2892         or else Rep_Item_Too_Early (Rectype, N)
2893       then
2894          return;
2895       else
2896          Rectype := Underlying_Type (Rectype);
2897       end if;
2898
2899       --  First some basic error checks
2900
2901       if not Is_Record_Type (Rectype) then
2902          Error_Msg_NE
2903            ("record type required, found}", Ident, First_Subtype (Rectype));
2904          return;
2905
2906       elsif Scope (Rectype) /= Current_Scope then
2907          Error_Msg_N ("type must be declared in this scope", N);
2908          return;
2909
2910       elsif not Is_First_Subtype (Rectype) then
2911          Error_Msg_N ("cannot give record rep clause for subtype", N);
2912          return;
2913
2914       elsif Has_Record_Rep_Clause (Rectype) then
2915          Error_Msg_N ("duplicate record rep clause ignored", N);
2916          return;
2917
2918       elsif Rep_Item_Too_Late (Rectype, N) then
2919          return;
2920       end if;
2921
2922       if Present (Mod_Clause (N)) then
2923          declare
2924             Loc     : constant Source_Ptr := Sloc (N);
2925             M       : constant Node_Id := Mod_Clause (N);
2926             P       : constant List_Id := Pragmas_Before (M);
2927             AtM_Nod : Node_Id;
2928
2929             Mod_Val : Uint;
2930             pragma Warnings (Off, Mod_Val);
2931
2932          begin
2933             Check_Restriction (No_Obsolescent_Features, Mod_Clause (N));
2934
2935             if Warn_On_Obsolescent_Feature then
2936                Error_Msg_N
2937                  ("mod clause is an obsolescent feature (RM J.8)?", N);
2938                Error_Msg_N
2939                  ("\use alignment attribute definition clause instead?", N);
2940             end if;
2941
2942             if Present (P) then
2943                Analyze_List (P);
2944             end if;
2945
2946             --  In ASIS_Mode mode, expansion is disabled, but we must convert
2947             --  the Mod clause into an alignment clause anyway, so that the
2948             --  back-end can compute and back-annotate properly the size and
2949             --  alignment of types that may include this record.
2950
2951             --  This seems dubious, this destroys the source tree in a manner
2952             --  not detectable by ASIS ???
2953
2954             if Operating_Mode = Check_Semantics
2955               and then ASIS_Mode
2956             then
2957                AtM_Nod :=
2958                  Make_Attribute_Definition_Clause (Loc,
2959                    Name       => New_Reference_To (Base_Type (Rectype), Loc),
2960                    Chars      => Name_Alignment,
2961                    Expression => Relocate_Node (Expression (M)));
2962
2963                Set_From_At_Mod (AtM_Nod);
2964                Insert_After (N, AtM_Nod);
2965                Mod_Val := Get_Alignment_Value (Expression (AtM_Nod));
2966                Set_Mod_Clause (N, Empty);
2967
2968             else
2969                --  Get the alignment value to perform error checking
2970
2971                Mod_Val := Get_Alignment_Value (Expression (M));
2972             end if;
2973          end;
2974       end if;
2975
2976       --  For untagged types, clear any existing component clauses for the
2977       --  type. If the type is derived, this is what allows us to override
2978       --  a rep clause for the parent. For type extensions, the representation
2979       --  of the inherited components is inherited, so we want to keep previous
2980       --  component clauses for completeness.
2981
2982       if not Is_Tagged_Type (Rectype) then
2983          Comp := First_Component_Or_Discriminant (Rectype);
2984          while Present (Comp) loop
2985             Set_Component_Clause (Comp, Empty);
2986             Next_Component_Or_Discriminant (Comp);
2987          end loop;
2988       end if;
2989
2990       --  All done if no component clauses
2991
2992       CC := First (Component_Clauses (N));
2993
2994       if No (CC) then
2995          return;
2996       end if;
2997
2998       --  A representation like this applies to the base type
2999
3000       Set_Has_Record_Rep_Clause (Base_Type (Rectype));
3001       Set_Has_Non_Standard_Rep  (Base_Type (Rectype));
3002       Set_Has_Specified_Layout  (Base_Type (Rectype));
3003
3004       --  Process the component clauses
3005
3006       while Present (CC) loop
3007
3008          --  Pragma
3009
3010          if Nkind (CC) = N_Pragma then
3011             Analyze (CC);
3012
3013             --  The only pragma of interest is Complete_Representation
3014
3015             if Pragma_Name (CC) = Name_Complete_Representation then
3016                CR_Pragma := CC;
3017             end if;
3018
3019          --  Processing for real component clause
3020
3021          else
3022             Posit := Static_Integer (Position  (CC));
3023             Fbit  := Static_Integer (First_Bit (CC));
3024             Lbit  := Static_Integer (Last_Bit  (CC));
3025
3026             if Posit /= No_Uint
3027               and then Fbit /= No_Uint
3028               and then Lbit /= No_Uint
3029             then
3030                if Posit < 0 then
3031                   Error_Msg_N
3032                     ("position cannot be negative", Position (CC));
3033
3034                elsif Fbit < 0 then
3035                   Error_Msg_N
3036                     ("first bit cannot be negative", First_Bit (CC));
3037
3038                --  The Last_Bit specified in a component clause must not be
3039                --  less than the First_Bit minus one (RM-13.5.1(10)).
3040
3041                elsif Lbit < Fbit - 1 then
3042                   Error_Msg_N
3043                     ("last bit cannot be less than first bit minus one",
3044                      Last_Bit (CC));
3045
3046                --  Values look OK, so find the corresponding record component
3047                --  Even though the syntax allows an attribute reference for
3048                --  implementation-defined components, GNAT does not allow the
3049                --  tag to get an explicit position.
3050
3051                elsif Nkind (Component_Name (CC)) = N_Attribute_Reference then
3052                   if Attribute_Name (Component_Name (CC)) = Name_Tag then
3053                      Error_Msg_N ("position of tag cannot be specified", CC);
3054                   else
3055                      Error_Msg_N ("illegal component name", CC);
3056                   end if;
3057
3058                else
3059                   Comp := First_Entity (Rectype);
3060                   while Present (Comp) loop
3061                      exit when Chars (Comp) = Chars (Component_Name (CC));
3062                      Next_Entity (Comp);
3063                   end loop;
3064
3065                   if No (Comp) then
3066
3067                      --  Maybe component of base type that is absent from
3068                      --  statically constrained first subtype.
3069
3070                      Comp := First_Entity (Base_Type (Rectype));
3071                      while Present (Comp) loop
3072                         exit when Chars (Comp) = Chars (Component_Name (CC));
3073                         Next_Entity (Comp);
3074                      end loop;
3075                   end if;
3076
3077                   if No (Comp) then
3078                      Error_Msg_N
3079                        ("component clause is for non-existent field", CC);
3080
3081                   --  Ada 2012 (AI05-0026): Any name that denotes a
3082                   --  discriminant of an object of an unchecked union type
3083                   --  shall not occur within a record_representation_clause.
3084
3085                   --  The general restriction of using record rep clauses on
3086                   --  Unchecked_Union types has now been lifted. Since it is
3087                   --  possible to introduce a record rep clause which mentions
3088                   --  the discriminant of an Unchecked_Union in non-Ada 2012
3089                   --  code, this check is applied to all versions of the
3090                   --  language.
3091
3092                   elsif Ekind (Comp) = E_Discriminant
3093                     and then Is_Unchecked_Union (Rectype)
3094                   then
3095                      Error_Msg_N
3096                        ("cannot reference discriminant of Unchecked_Union",
3097                         Component_Name (CC));
3098
3099                   elsif Present (Component_Clause (Comp)) then
3100
3101                      --  Diagnose duplicate rep clause, or check consistency
3102                      --  if this is an inherited component. In a double fault,
3103                      --  there may be a duplicate inconsistent clause for an
3104                      --  inherited component.
3105
3106                      if Scope (Original_Record_Component (Comp)) = Rectype
3107                        or else Parent (Component_Clause (Comp)) = N
3108                      then
3109                         Error_Msg_Sloc := Sloc (Component_Clause (Comp));
3110                         Error_Msg_N ("component clause previously given#", CC);
3111
3112                      else
3113                         declare
3114                            Rep1 : constant Node_Id := Component_Clause (Comp);
3115                         begin
3116                            if Intval (Position (Rep1)) /=
3117                                                    Intval (Position (CC))
3118                              or else Intval (First_Bit (Rep1)) /=
3119                                                    Intval (First_Bit (CC))
3120                              or else Intval (Last_Bit (Rep1)) /=
3121                                                    Intval (Last_Bit (CC))
3122                            then
3123                               Error_Msg_N ("component clause inconsistent "
3124                                 & "with representation of ancestor", CC);
3125                            elsif Warn_On_Redundant_Constructs then
3126                               Error_Msg_N ("?redundant component clause "
3127                                 & "for inherited component!", CC);
3128                            end if;
3129                         end;
3130                      end if;
3131
3132                   --  Normal case where this is the first component clause we
3133                   --  have seen for this entity, so set it up properly.
3134
3135                   else
3136                      --  Make reference for field in record rep clause and set
3137                      --  appropriate entity field in the field identifier.
3138
3139                      Generate_Reference
3140                        (Comp, Component_Name (CC), Set_Ref => False);
3141                      Set_Entity (Component_Name (CC), Comp);
3142
3143                      --  Update Fbit and Lbit to the actual bit number
3144
3145                      Fbit := Fbit + UI_From_Int (SSU) * Posit;
3146                      Lbit := Lbit + UI_From_Int (SSU) * Posit;
3147
3148                      if Has_Size_Clause (Rectype)
3149                        and then Esize (Rectype) <= Lbit
3150                      then
3151                         Error_Msg_N
3152                           ("bit number out of range of specified size",
3153                            Last_Bit (CC));
3154                      else
3155                         Set_Component_Clause     (Comp, CC);
3156                         Set_Component_Bit_Offset (Comp, Fbit);
3157                         Set_Esize                (Comp, 1 + (Lbit - Fbit));
3158                         Set_Normalized_First_Bit (Comp, Fbit mod SSU);
3159                         Set_Normalized_Position  (Comp, Fbit / SSU);
3160
3161                         if Warn_On_Overridden_Size
3162                           and then Has_Size_Clause (Etype (Comp))
3163                           and then RM_Size (Etype (Comp)) /= Esize (Comp)
3164                         then
3165                            Error_Msg_NE
3166                              ("?component size overrides size clause for&",
3167                               Component_Name (CC), Etype (Comp));
3168                         end if;
3169
3170                         --  This information is also set in the corresponding
3171                         --  component of the base type, found by accessing the
3172                         --  Original_Record_Component link if it is present.
3173
3174                         Ocomp := Original_Record_Component (Comp);
3175
3176                         if Hbit < Lbit then
3177                            Hbit := Lbit;
3178                         end if;
3179
3180                         Check_Size
3181                           (Component_Name (CC),
3182                            Etype (Comp),
3183                            Esize (Comp),
3184                            Biased);
3185
3186                         Set_Biased
3187                           (Comp, First_Node (CC), "component clause", Biased);
3188
3189                         if Present (Ocomp) then
3190                            Set_Component_Clause     (Ocomp, CC);
3191                            Set_Component_Bit_Offset (Ocomp, Fbit);
3192                            Set_Normalized_First_Bit (Ocomp, Fbit mod SSU);
3193                            Set_Normalized_Position  (Ocomp, Fbit / SSU);
3194                            Set_Esize                (Ocomp, 1 + (Lbit - Fbit));
3195
3196                            Set_Normalized_Position_Max
3197                              (Ocomp, Normalized_Position (Ocomp));
3198
3199                            --  Note: we don't use Set_Biased here, because we
3200                            --  already gave a warning above if needed, and we
3201                            --  would get a duplicate for the same name here.
3202
3203                            Set_Has_Biased_Representation
3204                              (Ocomp, Has_Biased_Representation (Comp));
3205                         end if;
3206
3207                         if Esize (Comp) < 0 then
3208                            Error_Msg_N ("component size is negative", CC);
3209                         end if;
3210                      end if;
3211                   end if;
3212                end if;
3213             end if;
3214          end if;
3215
3216          Next (CC);
3217       end loop;
3218
3219       --  Check missing components if Complete_Representation pragma appeared
3220
3221       if Present (CR_Pragma) then
3222          Comp := First_Component_Or_Discriminant (Rectype);
3223          while Present (Comp) loop
3224             if No (Component_Clause (Comp)) then
3225                Error_Msg_NE
3226                  ("missing component clause for &", CR_Pragma, Comp);
3227             end if;
3228
3229             Next_Component_Or_Discriminant (Comp);
3230          end loop;
3231
3232          --  If no Complete_Representation pragma, warn if missing components
3233
3234       elsif Warn_On_Unrepped_Components then
3235          declare
3236             Num_Repped_Components   : Nat := 0;
3237             Num_Unrepped_Components : Nat := 0;
3238
3239          begin
3240             --  First count number of repped and unrepped components
3241
3242             Comp := First_Component_Or_Discriminant (Rectype);
3243             while Present (Comp) loop
3244                if Present (Component_Clause (Comp)) then
3245                   Num_Repped_Components := Num_Repped_Components + 1;
3246                else
3247                   Num_Unrepped_Components := Num_Unrepped_Components + 1;
3248                end if;
3249
3250                Next_Component_Or_Discriminant (Comp);
3251             end loop;
3252
3253             --  We are only interested in the case where there is at least one
3254             --  unrepped component, and at least half the components have rep
3255             --  clauses. We figure that if less than half have them, then the
3256             --  partial rep clause is really intentional. If the component
3257             --  type has no underlying type set at this point (as for a generic
3258             --  formal type), we don't know enough to give a warning on the
3259             --  component.
3260
3261             if Num_Unrepped_Components > 0
3262               and then Num_Unrepped_Components < Num_Repped_Components
3263             then
3264                Comp := First_Component_Or_Discriminant (Rectype);
3265                while Present (Comp) loop
3266                   if No (Component_Clause (Comp))
3267                     and then Comes_From_Source (Comp)
3268                     and then Present (Underlying_Type (Etype (Comp)))
3269                     and then (Is_Scalar_Type (Underlying_Type (Etype (Comp)))
3270                                or else Size_Known_At_Compile_Time
3271                                          (Underlying_Type (Etype (Comp))))
3272                     and then not Has_Warnings_Off (Rectype)
3273                   then
3274                      Error_Msg_Sloc := Sloc (Comp);
3275                      Error_Msg_NE
3276                        ("?no component clause given for & declared #",
3277                         N, Comp);
3278                   end if;
3279
3280                   Next_Component_Or_Discriminant (Comp);
3281                end loop;
3282             end if;
3283          end;
3284       end if;
3285    end Analyze_Record_Representation_Clause;
3286
3287    -----------------------------------
3288    -- Check_Constant_Address_Clause --
3289    -----------------------------------
3290
3291    procedure Check_Constant_Address_Clause
3292      (Expr  : Node_Id;
3293       U_Ent : Entity_Id)
3294    is
3295       procedure Check_At_Constant_Address (Nod : Node_Id);
3296       --  Checks that the given node N represents a name whose 'Address is
3297       --  constant (in the same sense as OK_Constant_Address_Clause, i.e. the
3298       --  address value is the same at the point of declaration of U_Ent and at
3299       --  the time of elaboration of the address clause.
3300
3301       procedure Check_Expr_Constants (Nod : Node_Id);
3302       --  Checks that Nod meets the requirements for a constant address clause
3303       --  in the sense of the enclosing procedure.
3304
3305       procedure Check_List_Constants (Lst : List_Id);
3306       --  Check that all elements of list Lst meet the requirements for a
3307       --  constant address clause in the sense of the enclosing procedure.
3308
3309       -------------------------------
3310       -- Check_At_Constant_Address --
3311       -------------------------------
3312
3313       procedure Check_At_Constant_Address (Nod : Node_Id) is
3314       begin
3315          if Is_Entity_Name (Nod) then
3316             if Present (Address_Clause (Entity ((Nod)))) then
3317                Error_Msg_NE
3318                  ("invalid address clause for initialized object &!",
3319                            Nod, U_Ent);
3320                Error_Msg_NE
3321                  ("address for& cannot" &
3322                     " depend on another address clause! (RM 13.1(22))!",
3323                   Nod, U_Ent);
3324
3325             elsif In_Same_Source_Unit (Entity (Nod), U_Ent)
3326               and then Sloc (U_Ent) < Sloc (Entity (Nod))
3327             then
3328                Error_Msg_NE
3329                  ("invalid address clause for initialized object &!",
3330                   Nod, U_Ent);
3331                Error_Msg_Node_2 := U_Ent;
3332                Error_Msg_NE
3333                  ("\& must be defined before & (RM 13.1(22))!",
3334                   Nod, Entity (Nod));
3335             end if;
3336
3337          elsif Nkind (Nod) = N_Selected_Component then
3338             declare
3339                T : constant Entity_Id := Etype (Prefix (Nod));
3340
3341             begin
3342                if (Is_Record_Type (T)
3343                     and then Has_Discriminants (T))
3344                  or else
3345                   (Is_Access_Type (T)
3346                      and then Is_Record_Type (Designated_Type (T))
3347                      and then Has_Discriminants (Designated_Type (T)))
3348                then
3349                   Error_Msg_NE
3350                     ("invalid address clause for initialized object &!",
3351                      Nod, U_Ent);
3352                   Error_Msg_N
3353                     ("\address cannot depend on component" &
3354                      " of discriminated record (RM 13.1(22))!",
3355                      Nod);
3356                else
3357                   Check_At_Constant_Address (Prefix (Nod));
3358                end if;
3359             end;
3360
3361          elsif Nkind (Nod) = N_Indexed_Component then
3362             Check_At_Constant_Address (Prefix (Nod));
3363             Check_List_Constants (Expressions (Nod));
3364
3365          else
3366             Check_Expr_Constants (Nod);
3367          end if;
3368       end Check_At_Constant_Address;
3369
3370       --------------------------
3371       -- Check_Expr_Constants --
3372       --------------------------
3373
3374       procedure Check_Expr_Constants (Nod : Node_Id) is
3375          Loc_U_Ent : constant Source_Ptr := Sloc (U_Ent);
3376          Ent       : Entity_Id           := Empty;
3377
3378       begin
3379          if Nkind (Nod) in N_Has_Etype
3380            and then Etype (Nod) = Any_Type
3381          then
3382             return;
3383          end if;
3384
3385          case Nkind (Nod) is
3386             when N_Empty | N_Error =>
3387                return;
3388
3389             when N_Identifier | N_Expanded_Name =>
3390                Ent := Entity (Nod);
3391
3392                --  We need to look at the original node if it is different
3393                --  from the node, since we may have rewritten things and
3394                --  substituted an identifier representing the rewrite.
3395
3396                if Original_Node (Nod) /= Nod then
3397                   Check_Expr_Constants (Original_Node (Nod));
3398
3399                   --  If the node is an object declaration without initial
3400                   --  value, some code has been expanded, and the expression
3401                   --  is not constant, even if the constituents might be
3402                   --  acceptable, as in A'Address + offset.
3403
3404                   if Ekind (Ent) = E_Variable
3405                     and then
3406                       Nkind (Declaration_Node (Ent)) = N_Object_Declaration
3407                     and then
3408                       No (Expression (Declaration_Node (Ent)))
3409                   then
3410                      Error_Msg_NE
3411                        ("invalid address clause for initialized object &!",
3412                         Nod, U_Ent);
3413
3414                   --  If entity is constant, it may be the result of expanding
3415                   --  a check. We must verify that its declaration appears
3416                   --  before the object in question, else we also reject the
3417                   --  address clause.
3418
3419                   elsif Ekind (Ent) = E_Constant
3420                     and then In_Same_Source_Unit (Ent, U_Ent)
3421                     and then Sloc (Ent) > Loc_U_Ent
3422                   then
3423                      Error_Msg_NE
3424                        ("invalid address clause for initialized object &!",
3425                         Nod, U_Ent);
3426                   end if;
3427
3428                   return;
3429                end if;
3430
3431                --  Otherwise look at the identifier and see if it is OK
3432
3433                if Ekind_In (Ent, E_Named_Integer, E_Named_Real)
3434                  or else Is_Type (Ent)
3435                then
3436                   return;
3437
3438                elsif
3439                   Ekind (Ent) = E_Constant
3440                     or else
3441                   Ekind (Ent) = E_In_Parameter
3442                then
3443                   --  This is the case where we must have Ent defined before
3444                   --  U_Ent. Clearly if they are in different units this
3445                   --  requirement is met since the unit containing Ent is
3446                   --  already processed.
3447
3448                   if not In_Same_Source_Unit (Ent, U_Ent) then
3449                      return;
3450
3451                   --  Otherwise location of Ent must be before the location
3452                   --  of U_Ent, that's what prior defined means.
3453
3454                   elsif Sloc (Ent) < Loc_U_Ent then
3455                      return;
3456
3457                   else
3458                      Error_Msg_NE
3459                        ("invalid address clause for initialized object &!",
3460                         Nod, U_Ent);
3461                      Error_Msg_Node_2 := U_Ent;
3462                      Error_Msg_NE
3463                        ("\& must be defined before & (RM 13.1(22))!",
3464                         Nod, Ent);
3465                   end if;
3466
3467                elsif Nkind (Original_Node (Nod)) = N_Function_Call then
3468                   Check_Expr_Constants (Original_Node (Nod));
3469
3470                else
3471                   Error_Msg_NE
3472                     ("invalid address clause for initialized object &!",
3473                      Nod, U_Ent);
3474
3475                   if Comes_From_Source (Ent) then
3476                      Error_Msg_NE
3477                        ("\reference to variable& not allowed"
3478                           & " (RM 13.1(22))!", Nod, Ent);
3479                   else
3480                      Error_Msg_N
3481                        ("non-static expression not allowed"
3482                           & " (RM 13.1(22))!", Nod);
3483                   end if;
3484                end if;
3485
3486             when N_Integer_Literal   =>
3487
3488                --  If this is a rewritten unchecked conversion, in a system
3489                --  where Address is an integer type, always use the base type
3490                --  for a literal value. This is user-friendly and prevents
3491                --  order-of-elaboration issues with instances of unchecked
3492                --  conversion.
3493
3494                if Nkind (Original_Node (Nod)) = N_Function_Call then
3495                   Set_Etype (Nod, Base_Type (Etype (Nod)));
3496                end if;
3497
3498             when N_Real_Literal      |
3499                  N_String_Literal    |
3500                  N_Character_Literal =>
3501                return;
3502
3503             when N_Range =>
3504                Check_Expr_Constants (Low_Bound (Nod));
3505                Check_Expr_Constants (High_Bound (Nod));
3506
3507             when N_Explicit_Dereference =>
3508                Check_Expr_Constants (Prefix (Nod));
3509
3510             when N_Indexed_Component =>
3511                Check_Expr_Constants (Prefix (Nod));
3512                Check_List_Constants (Expressions (Nod));
3513
3514             when N_Slice =>
3515                Check_Expr_Constants (Prefix (Nod));
3516                Check_Expr_Constants (Discrete_Range (Nod));
3517
3518             when N_Selected_Component =>
3519                Check_Expr_Constants (Prefix (Nod));
3520
3521             when N_Attribute_Reference =>
3522                if Attribute_Name (Nod) = Name_Address
3523                    or else
3524                   Attribute_Name (Nod) = Name_Access
3525                     or else
3526                   Attribute_Name (Nod) = Name_Unchecked_Access
3527                     or else
3528                   Attribute_Name (Nod) = Name_Unrestricted_Access
3529                then
3530                   Check_At_Constant_Address (Prefix (Nod));
3531
3532                else
3533                   Check_Expr_Constants (Prefix (Nod));
3534                   Check_List_Constants (Expressions (Nod));
3535                end if;
3536
3537             when N_Aggregate =>
3538                Check_List_Constants (Component_Associations (Nod));
3539                Check_List_Constants (Expressions (Nod));
3540
3541             when N_Component_Association =>
3542                Check_Expr_Constants (Expression (Nod));
3543
3544             when N_Extension_Aggregate =>
3545                Check_Expr_Constants (Ancestor_Part (Nod));
3546                Check_List_Constants (Component_Associations (Nod));
3547                Check_List_Constants (Expressions (Nod));
3548
3549             when N_Null =>
3550                return;
3551
3552             when N_Binary_Op | N_Short_Circuit | N_Membership_Test =>
3553                Check_Expr_Constants (Left_Opnd (Nod));
3554                Check_Expr_Constants (Right_Opnd (Nod));
3555
3556             when N_Unary_Op =>
3557                Check_Expr_Constants (Right_Opnd (Nod));
3558
3559             when N_Type_Conversion           |
3560                  N_Qualified_Expression      |
3561                  N_Allocator                 =>
3562                Check_Expr_Constants (Expression (Nod));
3563
3564             when N_Unchecked_Type_Conversion =>
3565                Check_Expr_Constants (Expression (Nod));
3566
3567                --  If this is a rewritten unchecked conversion, subtypes in
3568                --  this node are those created within the instance. To avoid
3569                --  order of elaboration issues, replace them with their base
3570                --  types. Note that address clauses can cause order of
3571                --  elaboration problems because they are elaborated by the
3572                --  back-end at the point of definition, and may mention
3573                --  entities declared in between (as long as everything is
3574                --  static). It is user-friendly to allow unchecked conversions
3575                --  in this context.
3576
3577                if Nkind (Original_Node (Nod)) = N_Function_Call then
3578                   Set_Etype (Expression (Nod),
3579                     Base_Type (Etype (Expression (Nod))));
3580                   Set_Etype (Nod, Base_Type (Etype (Nod)));
3581                end if;
3582
3583             when N_Function_Call =>
3584                if not Is_Pure (Entity (Name (Nod))) then
3585                   Error_Msg_NE
3586                     ("invalid address clause for initialized object &!",
3587                      Nod, U_Ent);
3588
3589                   Error_Msg_NE
3590                     ("\function & is not pure (RM 13.1(22))!",
3591                      Nod, Entity (Name (Nod)));
3592
3593                else
3594                   Check_List_Constants (Parameter_Associations (Nod));
3595                end if;
3596
3597             when N_Parameter_Association =>
3598                Check_Expr_Constants (Explicit_Actual_Parameter (Nod));
3599
3600             when others =>
3601                Error_Msg_NE
3602                  ("invalid address clause for initialized object &!",
3603                   Nod, U_Ent);
3604                Error_Msg_NE
3605                  ("\must be constant defined before& (RM 13.1(22))!",
3606                   Nod, U_Ent);
3607          end case;
3608       end Check_Expr_Constants;
3609
3610       --------------------------
3611       -- Check_List_Constants --
3612       --------------------------
3613
3614       procedure Check_List_Constants (Lst : List_Id) is
3615          Nod1 : Node_Id;
3616
3617       begin
3618          if Present (Lst) then
3619             Nod1 := First (Lst);
3620             while Present (Nod1) loop
3621                Check_Expr_Constants (Nod1);
3622                Next (Nod1);
3623             end loop;
3624          end if;
3625       end Check_List_Constants;
3626
3627    --  Start of processing for Check_Constant_Address_Clause
3628
3629    begin
3630       --  If rep_clauses are to be ignored, no need for legality checks. In
3631       --  particular, no need to pester user about rep clauses that violate
3632       --  the rule on constant addresses, given that these clauses will be
3633       --  removed by Freeze before they reach the back end.
3634
3635       if not Ignore_Rep_Clauses then
3636          Check_Expr_Constants (Expr);
3637       end if;
3638    end Check_Constant_Address_Clause;
3639
3640    ----------------------------------------
3641    -- Check_Record_Representation_Clause --
3642    ----------------------------------------
3643
3644    procedure Check_Record_Representation_Clause (N : Node_Id) is
3645       Loc     : constant Source_Ptr := Sloc (N);
3646       Ident   : constant Node_Id    := Identifier (N);
3647       Rectype : Entity_Id;
3648       Fent    : Entity_Id;
3649       CC      : Node_Id;
3650       Fbit    : Uint;
3651       Lbit    : Uint;
3652       Hbit    : Uint := Uint_0;
3653       Comp    : Entity_Id;
3654       Pcomp   : Entity_Id;
3655
3656       Max_Bit_So_Far : Uint;
3657       --  Records the maximum bit position so far. If all field positions
3658       --  are monotonically increasing, then we can skip the circuit for
3659       --  checking for overlap, since no overlap is possible.
3660
3661       Tagged_Parent : Entity_Id := Empty;
3662       --  This is set in the case of a derived tagged type for which we have
3663       --  Is_Fully_Repped_Tagged_Type True (indicating that all components are
3664       --  positioned by record representation clauses). In this case we must
3665       --  check for overlap between components of this tagged type, and the
3666       --  components of its parent. Tagged_Parent will point to this parent
3667       --  type. For all other cases Tagged_Parent is left set to Empty.
3668
3669       Parent_Last_Bit : Uint;
3670       --  Relevant only if Tagged_Parent is set, Parent_Last_Bit indicates the
3671       --  last bit position for any field in the parent type. We only need to
3672       --  check overlap for fields starting below this point.
3673
3674       Overlap_Check_Required : Boolean;
3675       --  Used to keep track of whether or not an overlap check is required
3676
3677       Overlap_Detected : Boolean := False;
3678       --  Set True if an overlap is detected
3679
3680       Ccount : Natural := 0;
3681       --  Number of component clauses in record rep clause
3682
3683       procedure Check_Component_Overlap (C1_Ent, C2_Ent : Entity_Id);
3684       --  Given two entities for record components or discriminants, checks
3685       --  if they have overlapping component clauses and issues errors if so.
3686
3687       procedure Find_Component;
3688       --  Finds component entity corresponding to current component clause (in
3689       --  CC), and sets Comp to the entity, and Fbit/Lbit to the zero origin
3690       --  start/stop bits for the field. If there is no matching component or
3691       --  if the matching component does not have a component clause, then
3692       --  that's an error and Comp is set to Empty, but no error message is
3693       --  issued, since the message was already given. Comp is also set to
3694       --  Empty if the current "component clause" is in fact a pragma.
3695
3696       -----------------------------
3697       -- Check_Component_Overlap --
3698       -----------------------------
3699
3700       procedure Check_Component_Overlap (C1_Ent, C2_Ent : Entity_Id) is
3701          CC1 : constant Node_Id := Component_Clause (C1_Ent);
3702          CC2 : constant Node_Id := Component_Clause (C2_Ent);
3703
3704       begin
3705          if Present (CC1) and then Present (CC2) then
3706
3707             --  Exclude odd case where we have two tag fields in the same
3708             --  record, both at location zero. This seems a bit strange, but
3709             --  it seems to happen in some circumstances, perhaps on an error.
3710
3711             if Chars (C1_Ent) = Name_uTag
3712                  and then
3713                Chars (C2_Ent) = Name_uTag
3714             then
3715                return;
3716             end if;
3717
3718             --  Here we check if the two fields overlap
3719
3720             declare
3721                S1 : constant Uint := Component_Bit_Offset (C1_Ent);
3722                S2 : constant Uint := Component_Bit_Offset (C2_Ent);
3723                E1 : constant Uint := S1 + Esize (C1_Ent);
3724                E2 : constant Uint := S2 + Esize (C2_Ent);
3725
3726             begin
3727                if E2 <= S1 or else E1 <= S2 then
3728                   null;
3729                else
3730                   Error_Msg_Node_2 := Component_Name (CC2);
3731                   Error_Msg_Sloc := Sloc (Error_Msg_Node_2);
3732                   Error_Msg_Node_1 := Component_Name (CC1);
3733                   Error_Msg_N
3734                     ("component& overlaps & #", Component_Name (CC1));
3735                   Overlap_Detected := True;
3736                end if;
3737             end;
3738          end if;
3739       end Check_Component_Overlap;
3740
3741       --------------------
3742       -- Find_Component --
3743       --------------------
3744
3745       procedure Find_Component is
3746
3747          procedure Search_Component (R : Entity_Id);
3748          --  Search components of R for a match. If found, Comp is set.
3749
3750          ----------------------
3751          -- Search_Component --
3752          ----------------------
3753
3754          procedure Search_Component (R : Entity_Id) is
3755          begin
3756             Comp := First_Component_Or_Discriminant (R);
3757             while Present (Comp) loop
3758
3759                --  Ignore error of attribute name for component name (we
3760                --  already gave an error message for this, so no need to
3761                --  complain here)
3762
3763                if Nkind (Component_Name (CC)) = N_Attribute_Reference then
3764                   null;
3765                else
3766                   exit when Chars (Comp) = Chars (Component_Name (CC));
3767                end if;
3768
3769                Next_Component_Or_Discriminant (Comp);
3770             end loop;
3771          end Search_Component;
3772
3773       --  Start of processing for Find_Component
3774
3775       begin
3776          --  Return with Comp set to Empty if we have a pragma
3777
3778          if Nkind (CC) = N_Pragma then
3779             Comp := Empty;
3780             return;
3781          end if;
3782
3783          --  Search current record for matching component
3784
3785          Search_Component (Rectype);
3786
3787          --  If not found, maybe component of base type that is absent from
3788          --  statically constrained first subtype.
3789
3790          if No (Comp) then
3791             Search_Component (Base_Type (Rectype));
3792          end if;
3793
3794          --  If no component, or the component does not reference the component
3795          --  clause in question, then there was some previous error for which
3796          --  we already gave a message, so just return with Comp Empty.
3797
3798          if No (Comp)
3799            or else Component_Clause (Comp) /= CC
3800          then
3801             Comp := Empty;
3802
3803          --  Normal case where we have a component clause
3804
3805          else
3806             Fbit := Component_Bit_Offset (Comp);
3807             Lbit := Fbit + Esize (Comp) - 1;
3808          end if;
3809       end Find_Component;
3810
3811    --  Start of processing for Check_Record_Representation_Clause
3812
3813    begin
3814       Find_Type (Ident);
3815       Rectype := Entity (Ident);
3816
3817       if Rectype = Any_Type then
3818          return;
3819       else
3820          Rectype := Underlying_Type (Rectype);
3821       end if;
3822
3823       --  See if we have a fully repped derived tagged type
3824
3825       declare
3826          PS : constant Entity_Id := Parent_Subtype (Rectype);
3827
3828       begin
3829          if Present (PS) and then Is_Fully_Repped_Tagged_Type (PS) then
3830             Tagged_Parent := PS;
3831
3832             --  Find maximum bit of any component of the parent type
3833
3834             Parent_Last_Bit := UI_From_Int (System_Address_Size - 1);
3835             Pcomp := First_Entity (Tagged_Parent);
3836             while Present (Pcomp) loop
3837                if Ekind_In (Pcomp, E_Discriminant, E_Component) then
3838                   if Component_Bit_Offset (Pcomp) /= No_Uint
3839                     and then Known_Static_Esize (Pcomp)
3840                   then
3841                      Parent_Last_Bit :=
3842                        UI_Max
3843                          (Parent_Last_Bit,
3844                           Component_Bit_Offset (Pcomp) + Esize (Pcomp) - 1);
3845                   end if;
3846
3847                   Next_Entity (Pcomp);
3848                end if;
3849             end loop;
3850          end if;
3851       end;
3852
3853       --  All done if no component clauses
3854
3855       CC := First (Component_Clauses (N));
3856
3857       if No (CC) then
3858          return;
3859       end if;
3860
3861       --  If a tag is present, then create a component clause that places it
3862       --  at the start of the record (otherwise gigi may place it after other
3863       --  fields that have rep clauses).
3864
3865       Fent := First_Entity (Rectype);
3866
3867       if Nkind (Fent) = N_Defining_Identifier
3868         and then Chars (Fent) = Name_uTag
3869       then
3870          Set_Component_Bit_Offset    (Fent, Uint_0);
3871          Set_Normalized_Position     (Fent, Uint_0);
3872          Set_Normalized_First_Bit    (Fent, Uint_0);
3873          Set_Normalized_Position_Max (Fent, Uint_0);
3874          Init_Esize                  (Fent, System_Address_Size);
3875
3876          Set_Component_Clause (Fent,
3877            Make_Component_Clause (Loc,
3878              Component_Name =>
3879                Make_Identifier (Loc,
3880                  Chars => Name_uTag),
3881
3882              Position  =>
3883                Make_Integer_Literal (Loc,
3884                  Intval => Uint_0),
3885
3886              First_Bit =>
3887                Make_Integer_Literal (Loc,
3888                  Intval => Uint_0),
3889
3890              Last_Bit  =>
3891                Make_Integer_Literal (Loc,
3892                  UI_From_Int (System_Address_Size))));
3893
3894          Ccount := Ccount + 1;
3895       end if;
3896
3897       Max_Bit_So_Far := Uint_Minus_1;
3898       Overlap_Check_Required := False;
3899
3900       --  Process the component clauses
3901
3902       while Present (CC) loop
3903          Find_Component;
3904
3905          if Present (Comp) then
3906             Ccount := Ccount + 1;
3907
3908             --  We need a full overlap check if record positions non-monotonic
3909
3910             if Fbit <= Max_Bit_So_Far then
3911                Overlap_Check_Required := True;
3912             end if;
3913
3914             Max_Bit_So_Far := Lbit;
3915
3916             --  Check bit position out of range of specified size
3917
3918             if Has_Size_Clause (Rectype)
3919               and then Esize (Rectype) <= Lbit
3920             then
3921                Error_Msg_N
3922                  ("bit number out of range of specified size",
3923                   Last_Bit (CC));
3924
3925                --  Check for overlap with tag field
3926
3927             else
3928                if Is_Tagged_Type (Rectype)
3929                  and then Fbit < System_Address_Size
3930                then
3931                   Error_Msg_NE
3932                     ("component overlaps tag field of&",
3933                      Component_Name (CC), Rectype);
3934                   Overlap_Detected := True;
3935                end if;
3936
3937                if Hbit < Lbit then
3938                   Hbit := Lbit;
3939                end if;
3940             end if;
3941
3942             --  Check parent overlap if component might overlap parent field
3943
3944             if Present (Tagged_Parent)
3945               and then Fbit <= Parent_Last_Bit
3946             then
3947                Pcomp := First_Component_Or_Discriminant (Tagged_Parent);
3948                while Present (Pcomp) loop
3949                   if not Is_Tag (Pcomp)
3950                     and then Chars (Pcomp) /= Name_uParent
3951                   then
3952                      Check_Component_Overlap (Comp, Pcomp);
3953                   end if;
3954
3955                   Next_Component_Or_Discriminant (Pcomp);
3956                end loop;
3957             end if;
3958          end if;
3959
3960          Next (CC);
3961       end loop;
3962
3963       --  Now that we have processed all the component clauses, check for
3964       --  overlap. We have to leave this till last, since the components can
3965       --  appear in any arbitrary order in the representation clause.
3966
3967       --  We do not need this check if all specified ranges were monotonic,
3968       --  as recorded by Overlap_Check_Required being False at this stage.
3969
3970       --  This first section checks if there are any overlapping entries at
3971       --  all. It does this by sorting all entries and then seeing if there are
3972       --  any overlaps. If there are none, then that is decisive, but if there
3973       --  are overlaps, they may still be OK (they may result from fields in
3974       --  different variants).
3975
3976       if Overlap_Check_Required then
3977          Overlap_Check1 : declare
3978
3979             OC_Fbit : array (0 .. Ccount) of Uint;
3980             --  First-bit values for component clauses, the value is the offset
3981             --  of the first bit of the field from start of record. The zero
3982             --  entry is for use in sorting.
3983
3984             OC_Lbit : array (0 .. Ccount) of Uint;
3985             --  Last-bit values for component clauses, the value is the offset
3986             --  of the last bit of the field from start of record. The zero
3987             --  entry is for use in sorting.
3988
3989             OC_Count : Natural := 0;
3990             --  Count of entries in OC_Fbit and OC_Lbit
3991
3992             function OC_Lt (Op1, Op2 : Natural) return Boolean;
3993             --  Compare routine for Sort
3994
3995             procedure OC_Move (From : Natural; To : Natural);
3996             --  Move routine for Sort
3997
3998             package Sorting is new GNAT.Heap_Sort_G (OC_Move, OC_Lt);
3999
4000             -----------
4001             -- OC_Lt --
4002             -----------
4003
4004             function OC_Lt (Op1, Op2 : Natural) return Boolean is
4005             begin
4006                return OC_Fbit (Op1) < OC_Fbit (Op2);
4007             end OC_Lt;
4008
4009             -------------
4010             -- OC_Move --
4011             -------------
4012
4013             procedure OC_Move (From : Natural; To : Natural) is
4014             begin
4015                OC_Fbit (To) := OC_Fbit (From);
4016                OC_Lbit (To) := OC_Lbit (From);
4017             end OC_Move;
4018
4019             --  Start of processing for Overlap_Check
4020
4021          begin
4022             CC := First (Component_Clauses (N));
4023             while Present (CC) loop
4024
4025                --  Exclude component clause already marked in error
4026
4027                if not Error_Posted (CC) then
4028                   Find_Component;
4029
4030                   if Present (Comp) then
4031                      OC_Count := OC_Count + 1;
4032                      OC_Fbit (OC_Count) := Fbit;
4033                      OC_Lbit (OC_Count) := Lbit;
4034                   end if;
4035                end if;
4036
4037                Next (CC);
4038             end loop;
4039
4040             Sorting.Sort (OC_Count);
4041
4042             Overlap_Check_Required := False;
4043             for J in 1 .. OC_Count - 1 loop
4044                if OC_Lbit (J) >= OC_Fbit (J + 1) then
4045                   Overlap_Check_Required := True;
4046                   exit;
4047                end if;
4048             end loop;
4049          end Overlap_Check1;
4050       end if;
4051
4052       --  If Overlap_Check_Required is still True, then we have to do the full
4053       --  scale overlap check, since we have at least two fields that do
4054       --  overlap, and we need to know if that is OK since they are in
4055       --  different variant, or whether we have a definite problem.
4056
4057       if Overlap_Check_Required then
4058          Overlap_Check2 : declare
4059             C1_Ent, C2_Ent : Entity_Id;
4060             --  Entities of components being checked for overlap
4061
4062             Clist : Node_Id;
4063             --  Component_List node whose Component_Items are being checked
4064
4065             Citem : Node_Id;
4066             --  Component declaration for component being checked
4067
4068          begin
4069             C1_Ent := First_Entity (Base_Type (Rectype));
4070
4071             --  Loop through all components in record. For each component check
4072             --  for overlap with any of the preceding elements on the component
4073             --  list containing the component and also, if the component is in
4074             --  a variant, check against components outside the case structure.
4075             --  This latter test is repeated recursively up the variant tree.
4076
4077             Main_Component_Loop : while Present (C1_Ent) loop
4078                if not Ekind_In (C1_Ent, E_Component, E_Discriminant) then
4079                   goto Continue_Main_Component_Loop;
4080                end if;
4081
4082                --  Skip overlap check if entity has no declaration node. This
4083                --  happens with discriminants in constrained derived types.
4084                --  Possibly we are missing some checks as a result, but that
4085                --  does not seem terribly serious.
4086
4087                if No (Declaration_Node (C1_Ent)) then
4088                   goto Continue_Main_Component_Loop;
4089                end if;
4090
4091                Clist := Parent (List_Containing (Declaration_Node (C1_Ent)));
4092
4093                --  Loop through component lists that need checking. Check the
4094                --  current component list and all lists in variants above us.
4095
4096                Component_List_Loop : loop
4097
4098                   --  If derived type definition, go to full declaration
4099                   --  If at outer level, check discriminants if there are any.
4100
4101                   if Nkind (Clist) = N_Derived_Type_Definition then
4102                      Clist := Parent (Clist);
4103                   end if;
4104
4105                   --  Outer level of record definition, check discriminants
4106
4107                   if Nkind_In (Clist, N_Full_Type_Declaration,
4108                                N_Private_Type_Declaration)
4109                   then
4110                      if Has_Discriminants (Defining_Identifier (Clist)) then
4111                         C2_Ent :=
4112                           First_Discriminant (Defining_Identifier (Clist));
4113                         while Present (C2_Ent) loop
4114                            exit when C1_Ent = C2_Ent;
4115                            Check_Component_Overlap (C1_Ent, C2_Ent);
4116                            Next_Discriminant (C2_Ent);
4117                         end loop;
4118                      end if;
4119
4120                      --  Record extension case
4121
4122                   elsif Nkind (Clist) = N_Derived_Type_Definition then
4123                      Clist := Empty;
4124
4125                      --  Otherwise check one component list
4126
4127                   else
4128                      Citem := First (Component_Items (Clist));
4129                      while Present (Citem) loop
4130                         if Nkind (Citem) = N_Component_Declaration then
4131                            C2_Ent := Defining_Identifier (Citem);
4132                            exit when C1_Ent = C2_Ent;
4133                            Check_Component_Overlap (C1_Ent, C2_Ent);
4134                         end if;
4135
4136                         Next (Citem);
4137                      end loop;
4138                   end if;
4139
4140                   --  Check for variants above us (the parent of the Clist can
4141                   --  be a variant, in which case its parent is a variant part,
4142                   --  and the parent of the variant part is a component list
4143                   --  whose components must all be checked against the current
4144                   --  component for overlap).
4145
4146                   if Nkind (Parent (Clist)) = N_Variant then
4147                      Clist := Parent (Parent (Parent (Clist)));
4148
4149                      --  Check for possible discriminant part in record, this
4150                      --  is treated essentially as another level in the
4151                      --  recursion. For this case the parent of the component
4152                      --  list is the record definition, and its parent is the
4153                      --  full type declaration containing the discriminant
4154                      --  specifications.
4155
4156                   elsif Nkind (Parent (Clist)) = N_Record_Definition then
4157                      Clist := Parent (Parent ((Clist)));
4158
4159                      --  If neither of these two cases, we are at the top of
4160                      --  the tree.
4161
4162                   else
4163                      exit Component_List_Loop;
4164                   end if;
4165                end loop Component_List_Loop;
4166
4167                <<Continue_Main_Component_Loop>>
4168                Next_Entity (C1_Ent);
4169
4170             end loop Main_Component_Loop;
4171          end Overlap_Check2;
4172       end if;
4173
4174       --  The following circuit deals with warning on record holes (gaps). We
4175       --  skip this check if overlap was detected, since it makes sense for the
4176       --  programmer to fix this illegality before worrying about warnings.
4177
4178       if not Overlap_Detected and Warn_On_Record_Holes then
4179          Record_Hole_Check : declare
4180             Decl : constant Node_Id := Declaration_Node (Base_Type (Rectype));
4181             --  Full declaration of record type
4182
4183             procedure Check_Component_List
4184               (CL   : Node_Id;
4185                Sbit : Uint;
4186                DS   : List_Id);
4187             --  Check component list CL for holes. The starting bit should be
4188             --  Sbit. which is zero for the main record component list and set
4189             --  appropriately for recursive calls for variants. DS is set to
4190             --  a list of discriminant specifications to be included in the
4191             --  consideration of components. It is No_List if none to consider.
4192
4193             --------------------------
4194             -- Check_Component_List --
4195             --------------------------
4196
4197             procedure Check_Component_List
4198               (CL   : Node_Id;
4199                Sbit : Uint;
4200                DS   : List_Id)
4201             is
4202                Compl : Integer;
4203
4204             begin
4205                Compl := Integer (List_Length (Component_Items (CL)));
4206
4207                if DS /= No_List then
4208                   Compl := Compl + Integer (List_Length (DS));
4209                end if;
4210
4211                declare
4212                   Comps : array (Natural range 0 .. Compl) of Entity_Id;
4213                   --  Gather components (zero entry is for sort routine)
4214
4215                   Ncomps : Natural := 0;
4216                   --  Number of entries stored in Comps (starting at Comps (1))
4217
4218                   Citem : Node_Id;
4219                   --  One component item or discriminant specification
4220
4221                   Nbit  : Uint;
4222                   --  Starting bit for next component
4223
4224                   CEnt  : Entity_Id;
4225                   --  Component entity
4226
4227                   Variant : Node_Id;
4228                   --  One variant
4229
4230                   function Lt (Op1, Op2 : Natural) return Boolean;
4231                   --  Compare routine for Sort
4232
4233                   procedure Move (From : Natural; To : Natural);
4234                   --  Move routine for Sort
4235
4236                   package Sorting is new GNAT.Heap_Sort_G (Move, Lt);
4237
4238                   --------
4239                   -- Lt --
4240                   --------
4241
4242                   function Lt (Op1, Op2 : Natural) return Boolean is
4243                   begin
4244                      return Component_Bit_Offset (Comps (Op1))
4245                        <
4246                        Component_Bit_Offset (Comps (Op2));
4247                   end Lt;
4248
4249                   ----------
4250                   -- Move --
4251                   ----------
4252
4253                   procedure Move (From : Natural; To : Natural) is
4254                   begin
4255                      Comps (To) := Comps (From);
4256                   end Move;
4257
4258                begin
4259                   --  Gather discriminants into Comp
4260
4261                   if DS /= No_List then
4262                      Citem := First (DS);
4263                      while Present (Citem) loop
4264                         if Nkind (Citem) = N_Discriminant_Specification then
4265                            declare
4266                               Ent : constant Entity_Id :=
4267                                       Defining_Identifier (Citem);
4268                            begin
4269                               if Ekind (Ent) = E_Discriminant then
4270                                  Ncomps := Ncomps + 1;
4271                                  Comps (Ncomps) := Ent;
4272                               end if;
4273                            end;
4274                         end if;
4275
4276                         Next (Citem);
4277                      end loop;
4278                   end if;
4279
4280                   --  Gather component entities into Comp
4281
4282                   Citem := First (Component_Items (CL));
4283                   while Present (Citem) loop
4284                      if Nkind (Citem) = N_Component_Declaration then
4285                         Ncomps := Ncomps + 1;
4286                         Comps (Ncomps) := Defining_Identifier (Citem);
4287                      end if;
4288
4289                      Next (Citem);
4290                   end loop;
4291
4292                   --  Now sort the component entities based on the first bit.
4293                   --  Note we already know there are no overlapping components.
4294
4295                   Sorting.Sort (Ncomps);
4296
4297                   --  Loop through entries checking for holes
4298
4299                   Nbit := Sbit;
4300                   for J in 1 .. Ncomps loop
4301                      CEnt := Comps (J);
4302                      Error_Msg_Uint_1 := Component_Bit_Offset (CEnt) - Nbit;
4303
4304                      if Error_Msg_Uint_1 > 0 then
4305                         Error_Msg_NE
4306                           ("?^-bit gap before component&",
4307                            Component_Name (Component_Clause (CEnt)), CEnt);
4308                      end if;
4309
4310                      Nbit := Component_Bit_Offset (CEnt) + Esize (CEnt);
4311                   end loop;
4312
4313                   --  Process variant parts recursively if present
4314
4315                   if Present (Variant_Part (CL)) then
4316                      Variant := First (Variants (Variant_Part (CL)));
4317                      while Present (Variant) loop
4318                         Check_Component_List
4319                           (Component_List (Variant), Nbit, No_List);
4320                         Next (Variant);
4321                      end loop;
4322                   end if;
4323                end;
4324             end Check_Component_List;
4325
4326          --  Start of processing for Record_Hole_Check
4327
4328          begin
4329             declare
4330                Sbit : Uint;
4331
4332             begin
4333                if Is_Tagged_Type (Rectype) then
4334                   Sbit := UI_From_Int (System_Address_Size);
4335                else
4336                   Sbit := Uint_0;
4337                end if;
4338
4339                if Nkind (Decl) = N_Full_Type_Declaration
4340                  and then Nkind (Type_Definition (Decl)) = N_Record_Definition
4341                then
4342                   Check_Component_List
4343                     (Component_List (Type_Definition (Decl)),
4344                      Sbit,
4345                      Discriminant_Specifications (Decl));
4346                end if;
4347             end;
4348          end Record_Hole_Check;
4349       end if;
4350
4351       --  For records that have component clauses for all components, and whose
4352       --  size is less than or equal to 32, we need to know the size in the
4353       --  front end to activate possible packed array processing where the
4354       --  component type is a record.
4355
4356       --  At this stage Hbit + 1 represents the first unused bit from all the
4357       --  component clauses processed, so if the component clauses are
4358       --  complete, then this is the length of the record.
4359
4360       --  For records longer than System.Storage_Unit, and for those where not
4361       --  all components have component clauses, the back end determines the
4362       --  length (it may for example be appropriate to round up the size
4363       --  to some convenient boundary, based on alignment considerations, etc).
4364
4365       if Unknown_RM_Size (Rectype) and then Hbit + 1 <= 32 then
4366
4367          --  Nothing to do if at least one component has no component clause
4368
4369          Comp := First_Component_Or_Discriminant (Rectype);
4370          while Present (Comp) loop
4371             exit when No (Component_Clause (Comp));
4372             Next_Component_Or_Discriminant (Comp);
4373          end loop;
4374
4375          --  If we fall out of loop, all components have component clauses
4376          --  and so we can set the size to the maximum value.
4377
4378          if No (Comp) then
4379             Set_RM_Size (Rectype, Hbit + 1);
4380          end if;
4381       end if;
4382    end Check_Record_Representation_Clause;
4383
4384    ----------------
4385    -- Check_Size --
4386    ----------------
4387
4388    procedure Check_Size
4389      (N      : Node_Id;
4390       T      : Entity_Id;
4391       Siz    : Uint;
4392       Biased : out Boolean)
4393    is
4394       UT : constant Entity_Id := Underlying_Type (T);
4395       M  : Uint;
4396
4397    begin
4398       Biased := False;
4399
4400       --  Dismiss cases for generic types or types with previous errors
4401
4402       if No (UT)
4403         or else UT = Any_Type
4404         or else Is_Generic_Type (UT)
4405         or else Is_Generic_Type (Root_Type (UT))
4406       then
4407          return;
4408
4409       --  Check case of bit packed array
4410
4411       elsif Is_Array_Type (UT)
4412         and then Known_Static_Component_Size (UT)
4413         and then Is_Bit_Packed_Array (UT)
4414       then
4415          declare
4416             Asiz : Uint;
4417             Indx : Node_Id;
4418             Ityp : Entity_Id;
4419
4420          begin
4421             Asiz := Component_Size (UT);
4422             Indx := First_Index (UT);
4423             loop
4424                Ityp := Etype (Indx);
4425
4426                --  If non-static bound, then we are not in the business of
4427                --  trying to check the length, and indeed an error will be
4428                --  issued elsewhere, since sizes of non-static array types
4429                --  cannot be set implicitly or explicitly.
4430
4431                if not Is_Static_Subtype (Ityp) then
4432                   return;
4433                end if;
4434
4435                --  Otherwise accumulate next dimension
4436
4437                Asiz := Asiz * (Expr_Value (Type_High_Bound (Ityp)) -
4438                                Expr_Value (Type_Low_Bound  (Ityp)) +
4439                                Uint_1);
4440
4441                Next_Index (Indx);
4442                exit when No (Indx);
4443             end loop;
4444
4445             if Asiz <= Siz then
4446                return;
4447             else
4448                Error_Msg_Uint_1 := Asiz;
4449                Error_Msg_NE
4450                  ("size for& too small, minimum allowed is ^", N, T);
4451                Set_Esize   (T, Asiz);
4452                Set_RM_Size (T, Asiz);
4453             end if;
4454          end;
4455
4456       --  All other composite types are ignored
4457
4458       elsif Is_Composite_Type (UT) then
4459          return;
4460
4461       --  For fixed-point types, don't check minimum if type is not frozen,
4462       --  since we don't know all the characteristics of the type that can
4463       --  affect the size (e.g. a specified small) till freeze time.
4464
4465       elsif Is_Fixed_Point_Type (UT)
4466         and then not Is_Frozen (UT)
4467       then
4468          null;
4469
4470       --  Cases for which a minimum check is required
4471
4472       else
4473          --  Ignore if specified size is correct for the type
4474
4475          if Known_Esize (UT) and then Siz = Esize (UT) then
4476             return;
4477          end if;
4478
4479          --  Otherwise get minimum size
4480
4481          M := UI_From_Int (Minimum_Size (UT));
4482
4483          if Siz < M then
4484
4485             --  Size is less than minimum size, but one possibility remains
4486             --  that we can manage with the new size if we bias the type.
4487
4488             M := UI_From_Int (Minimum_Size (UT, Biased => True));
4489
4490             if Siz < M then
4491                Error_Msg_Uint_1 := M;
4492                Error_Msg_NE
4493                  ("size for& too small, minimum allowed is ^", N, T);
4494                Set_Esize (T, M);
4495                Set_RM_Size (T, M);
4496             else
4497                Biased := True;
4498             end if;
4499          end if;
4500       end if;
4501    end Check_Size;
4502
4503    -------------------------
4504    -- Get_Alignment_Value --
4505    -------------------------
4506
4507    function Get_Alignment_Value (Expr : Node_Id) return Uint is
4508       Align : constant Uint := Static_Integer (Expr);
4509
4510    begin
4511       if Align = No_Uint then
4512          return No_Uint;
4513
4514       elsif Align <= 0 then
4515          Error_Msg_N ("alignment value must be positive", Expr);
4516          return No_Uint;
4517
4518       else
4519          for J in Int range 0 .. 64 loop
4520             declare
4521                M : constant Uint := Uint_2 ** J;
4522
4523             begin
4524                exit when M = Align;
4525
4526                if M > Align then
4527                   Error_Msg_N
4528                     ("alignment value must be power of 2", Expr);
4529                   return No_Uint;
4530                end if;
4531             end;
4532          end loop;
4533
4534          return Align;
4535       end if;
4536    end Get_Alignment_Value;
4537
4538    ----------------
4539    -- Initialize --
4540    ----------------
4541
4542    procedure Initialize is
4543    begin
4544       Address_Clause_Checks.Init;
4545       Independence_Checks.Init;
4546       Unchecked_Conversions.Init;
4547    end Initialize;
4548
4549    -------------------------
4550    -- Is_Operational_Item --
4551    -------------------------
4552
4553    function Is_Operational_Item (N : Node_Id) return Boolean is
4554    begin
4555       if Nkind (N) /= N_Attribute_Definition_Clause then
4556          return False;
4557       else
4558          declare
4559             Id    : constant Attribute_Id := Get_Attribute_Id (Chars (N));
4560          begin
4561             return   Id = Attribute_Input
4562               or else Id = Attribute_Output
4563               or else Id = Attribute_Read
4564               or else Id = Attribute_Write
4565               or else Id = Attribute_External_Tag;
4566          end;
4567       end if;
4568    end Is_Operational_Item;
4569
4570    ------------------
4571    -- Minimum_Size --
4572    ------------------
4573
4574    function Minimum_Size
4575      (T      : Entity_Id;
4576       Biased : Boolean := False) return Nat
4577    is
4578       Lo     : Uint    := No_Uint;
4579       Hi     : Uint    := No_Uint;
4580       LoR    : Ureal   := No_Ureal;
4581       HiR    : Ureal   := No_Ureal;
4582       LoSet  : Boolean := False;
4583       HiSet  : Boolean := False;
4584       B      : Uint;
4585       S      : Nat;
4586       Ancest : Entity_Id;
4587       R_Typ  : constant Entity_Id := Root_Type (T);
4588
4589    begin
4590       --  If bad type, return 0
4591
4592       if T = Any_Type then
4593          return 0;
4594
4595       --  For generic types, just return zero. There cannot be any legitimate
4596       --  need to know such a size, but this routine may be called with a
4597       --  generic type as part of normal processing.
4598
4599       elsif Is_Generic_Type (R_Typ)
4600         or else R_Typ = Any_Type
4601       then
4602          return 0;
4603
4604          --  Access types. Normally an access type cannot have a size smaller
4605          --  than the size of System.Address. The exception is on VMS, where
4606          --  we have short and long addresses, and it is possible for an access
4607          --  type to have a short address size (and thus be less than the size
4608          --  of System.Address itself). We simply skip the check for VMS, and
4609          --  leave it to the back end to do the check.
4610
4611       elsif Is_Access_Type (T) then
4612          if OpenVMS_On_Target then
4613             return 0;
4614          else
4615             return System_Address_Size;
4616          end if;
4617
4618       --  Floating-point types
4619
4620       elsif Is_Floating_Point_Type (T) then
4621          return UI_To_Int (Esize (R_Typ));
4622
4623       --  Discrete types
4624
4625       elsif Is_Discrete_Type (T) then
4626
4627          --  The following loop is looking for the nearest compile time known
4628          --  bounds following the ancestor subtype chain. The idea is to find
4629          --  the most restrictive known bounds information.
4630
4631          Ancest := T;
4632          loop
4633             if Ancest = Any_Type or else Etype (Ancest) = Any_Type then
4634                return 0;
4635             end if;
4636
4637             if not LoSet then
4638                if Compile_Time_Known_Value (Type_Low_Bound (Ancest)) then
4639                   Lo := Expr_Rep_Value (Type_Low_Bound (Ancest));
4640                   LoSet := True;
4641                   exit when HiSet;
4642                end if;
4643             end if;
4644
4645             if not HiSet then
4646                if Compile_Time_Known_Value (Type_High_Bound (Ancest)) then
4647                   Hi := Expr_Rep_Value (Type_High_Bound (Ancest));
4648                   HiSet := True;
4649                   exit when LoSet;
4650                end if;
4651             end if;
4652
4653             Ancest := Ancestor_Subtype (Ancest);
4654
4655             if No (Ancest) then
4656                Ancest := Base_Type (T);
4657
4658                if Is_Generic_Type (Ancest) then
4659                   return 0;
4660                end if;
4661             end if;
4662          end loop;
4663
4664       --  Fixed-point types. We can't simply use Expr_Value to get the
4665       --  Corresponding_Integer_Value values of the bounds, since these do not
4666       --  get set till the type is frozen, and this routine can be called
4667       --  before the type is frozen. Similarly the test for bounds being static
4668       --  needs to include the case where we have unanalyzed real literals for
4669       --  the same reason.
4670
4671       elsif Is_Fixed_Point_Type (T) then
4672
4673          --  The following loop is looking for the nearest compile time known
4674          --  bounds following the ancestor subtype chain. The idea is to find
4675          --  the most restrictive known bounds information.
4676
4677          Ancest := T;
4678          loop
4679             if Ancest = Any_Type or else Etype (Ancest) = Any_Type then
4680                return 0;
4681             end if;
4682
4683             --  Note: In the following two tests for LoSet and HiSet, it may
4684             --  seem redundant to test for N_Real_Literal here since normally
4685             --  one would assume that the test for the value being known at
4686             --  compile time includes this case. However, there is a glitch.
4687             --  If the real literal comes from folding a non-static expression,
4688             --  then we don't consider any non- static expression to be known
4689             --  at compile time if we are in configurable run time mode (needed
4690             --  in some cases to give a clearer definition of what is and what
4691             --  is not accepted). So the test is indeed needed. Without it, we
4692             --  would set neither Lo_Set nor Hi_Set and get an infinite loop.
4693
4694             if not LoSet then
4695                if Nkind (Type_Low_Bound (Ancest)) = N_Real_Literal
4696                  or else Compile_Time_Known_Value (Type_Low_Bound (Ancest))
4697                then
4698                   LoR := Expr_Value_R (Type_Low_Bound (Ancest));
4699                   LoSet := True;
4700                   exit when HiSet;
4701                end if;
4702             end if;
4703
4704             if not HiSet then
4705                if Nkind (Type_High_Bound (Ancest)) = N_Real_Literal
4706                  or else Compile_Time_Known_Value (Type_High_Bound (Ancest))
4707                then
4708                   HiR := Expr_Value_R (Type_High_Bound (Ancest));
4709                   HiSet := True;
4710                   exit when LoSet;
4711                end if;
4712             end if;
4713
4714             Ancest := Ancestor_Subtype (Ancest);
4715
4716             if No (Ancest) then
4717                Ancest := Base_Type (T);
4718
4719                if Is_Generic_Type (Ancest) then
4720                   return 0;
4721                end if;
4722             end if;
4723          end loop;
4724
4725          Lo := UR_To_Uint (LoR / Small_Value (T));
4726          Hi := UR_To_Uint (HiR / Small_Value (T));
4727
4728       --  No other types allowed
4729
4730       else
4731          raise Program_Error;
4732       end if;
4733
4734       --  Fall through with Hi and Lo set. Deal with biased case
4735
4736       if (Biased
4737            and then not Is_Fixed_Point_Type (T)
4738            and then not (Is_Enumeration_Type (T)
4739                           and then Has_Non_Standard_Rep (T)))
4740         or else Has_Biased_Representation (T)
4741       then
4742          Hi := Hi - Lo;
4743          Lo := Uint_0;
4744       end if;
4745
4746       --  Signed case. Note that we consider types like range 1 .. -1 to be
4747       --  signed for the purpose of computing the size, since the bounds have
4748       --  to be accommodated in the base type.
4749
4750       if Lo < 0 or else Hi < 0 then
4751          S := 1;
4752          B := Uint_1;
4753
4754          --  S = size, B = 2 ** (size - 1) (can accommodate -B .. +(B - 1))
4755          --  Note that we accommodate the case where the bounds cross. This
4756          --  can happen either because of the way the bounds are declared
4757          --  or because of the algorithm in Freeze_Fixed_Point_Type.
4758
4759          while Lo < -B
4760            or else Hi < -B
4761            or else Lo >= B
4762            or else Hi >= B
4763          loop
4764             B := Uint_2 ** S;
4765             S := S + 1;
4766          end loop;
4767
4768       --  Unsigned case
4769
4770       else
4771          --  If both bounds are positive, make sure that both are represen-
4772          --  table in the case where the bounds are crossed. This can happen
4773          --  either because of the way the bounds are declared, or because of
4774          --  the algorithm in Freeze_Fixed_Point_Type.
4775
4776          if Lo > Hi then
4777             Hi := Lo;
4778          end if;
4779
4780          --  S = size, (can accommodate 0 .. (2**size - 1))
4781
4782          S := 0;
4783          while Hi >= Uint_2 ** S loop
4784             S := S + 1;
4785          end loop;
4786       end if;
4787
4788       return S;
4789    end Minimum_Size;
4790
4791    ---------------------------
4792    -- New_Stream_Subprogram --
4793    ---------------------------
4794
4795    procedure New_Stream_Subprogram
4796      (N     : Node_Id;
4797       Ent   : Entity_Id;
4798       Subp  : Entity_Id;
4799       Nam   : TSS_Name_Type)
4800    is
4801       Loc       : constant Source_Ptr := Sloc (N);
4802       Sname     : constant Name_Id    := Make_TSS_Name (Base_Type (Ent), Nam);
4803       Subp_Id   : Entity_Id;
4804       Subp_Decl : Node_Id;
4805       F         : Entity_Id;
4806       Etyp      : Entity_Id;
4807
4808       Defer_Declaration : constant Boolean :=
4809                             Is_Tagged_Type (Ent) or else Is_Private_Type (Ent);
4810       --  For a tagged type, there is a declaration for each stream attribute
4811       --  at the freeze point, and we must generate only a completion of this
4812       --  declaration. We do the same for private types, because the full view
4813       --  might be tagged. Otherwise we generate a declaration at the point of
4814       --  the attribute definition clause.
4815
4816       function Build_Spec return Node_Id;
4817       --  Used for declaration and renaming declaration, so that this is
4818       --  treated as a renaming_as_body.
4819
4820       ----------------
4821       -- Build_Spec --
4822       ----------------
4823
4824       function Build_Spec return Node_Id is
4825          Out_P   : constant Boolean := (Nam = TSS_Stream_Read);
4826          Formals : List_Id;
4827          Spec    : Node_Id;
4828          T_Ref   : constant Node_Id := New_Reference_To (Etyp, Loc);
4829
4830       begin
4831          Subp_Id := Make_Defining_Identifier (Loc, Sname);
4832
4833          --  S : access Root_Stream_Type'Class
4834
4835          Formals := New_List (
4836                       Make_Parameter_Specification (Loc,
4837                         Defining_Identifier =>
4838                           Make_Defining_Identifier (Loc, Name_S),
4839                         Parameter_Type =>
4840                           Make_Access_Definition (Loc,
4841                             Subtype_Mark =>
4842                               New_Reference_To (
4843                                 Designated_Type (Etype (F)), Loc))));
4844
4845          if Nam = TSS_Stream_Input then
4846             Spec := Make_Function_Specification (Loc,
4847                       Defining_Unit_Name       => Subp_Id,
4848                       Parameter_Specifications => Formals,
4849                       Result_Definition        => T_Ref);
4850          else
4851             --  V : [out] T
4852
4853             Append_To (Formals,
4854               Make_Parameter_Specification (Loc,
4855                 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
4856                 Out_Present         => Out_P,
4857                 Parameter_Type      => T_Ref));
4858
4859             Spec :=
4860               Make_Procedure_Specification (Loc,
4861                 Defining_Unit_Name       => Subp_Id,
4862                 Parameter_Specifications => Formals);
4863          end if;
4864
4865          return Spec;
4866       end Build_Spec;
4867
4868    --  Start of processing for New_Stream_Subprogram
4869
4870    begin
4871       F := First_Formal (Subp);
4872
4873       if Ekind (Subp) = E_Procedure then
4874          Etyp := Etype (Next_Formal (F));
4875       else
4876          Etyp := Etype (Subp);
4877       end if;
4878
4879       --  Prepare subprogram declaration and insert it as an action on the
4880       --  clause node. The visibility for this entity is used to test for
4881       --  visibility of the attribute definition clause (in the sense of
4882       --  8.3(23) as amended by AI-195).
4883
4884       if not Defer_Declaration then
4885          Subp_Decl :=
4886            Make_Subprogram_Declaration (Loc,
4887              Specification => Build_Spec);
4888
4889       --  For a tagged type, there is always a visible declaration for each
4890       --  stream TSS (it is a predefined primitive operation), and the
4891       --  completion of this declaration occurs at the freeze point, which is
4892       --  not always visible at places where the attribute definition clause is
4893       --  visible. So, we create a dummy entity here for the purpose of
4894       --  tracking the visibility of the attribute definition clause itself.
4895
4896       else
4897          Subp_Id :=
4898            Make_Defining_Identifier (Loc,
4899              Chars => New_External_Name (Sname, 'V'));
4900          Subp_Decl :=
4901            Make_Object_Declaration (Loc,
4902              Defining_Identifier => Subp_Id,
4903              Object_Definition   => New_Occurrence_Of (Standard_Boolean, Loc));
4904       end if;
4905
4906       Insert_Action (N, Subp_Decl);
4907       Set_Entity (N, Subp_Id);
4908
4909       Subp_Decl :=
4910         Make_Subprogram_Renaming_Declaration (Loc,
4911           Specification => Build_Spec,
4912           Name => New_Reference_To (Subp, Loc));
4913
4914       if Defer_Declaration then
4915          Set_TSS (Base_Type (Ent), Subp_Id);
4916       else
4917          Insert_Action (N, Subp_Decl);
4918          Copy_TSS (Subp_Id, Base_Type (Ent));
4919       end if;
4920    end New_Stream_Subprogram;
4921
4922    ------------------------
4923    -- Rep_Item_Too_Early --
4924    ------------------------
4925
4926    function Rep_Item_Too_Early (T : Entity_Id; N : Node_Id) return Boolean is
4927    begin
4928       --  Cannot apply non-operational rep items to generic types
4929
4930       if Is_Operational_Item (N) then
4931          return False;
4932
4933       elsif Is_Type (T)
4934         and then Is_Generic_Type (Root_Type (T))
4935       then
4936          Error_Msg_N ("representation item not allowed for generic type", N);
4937          return True;
4938       end if;
4939
4940       --  Otherwise check for incomplete type
4941
4942       if Is_Incomplete_Or_Private_Type (T)
4943         and then No (Underlying_Type (T))
4944       then
4945          Error_Msg_N
4946            ("representation item must be after full type declaration", N);
4947          return True;
4948
4949       --  If the type has incomplete components, a representation clause is
4950       --  illegal but stream attributes and Convention pragmas are correct.
4951
4952       elsif Has_Private_Component (T) then
4953          if Nkind (N) = N_Pragma then
4954             return False;
4955          else
4956             Error_Msg_N
4957               ("representation item must appear after type is fully defined",
4958                 N);
4959             return True;
4960          end if;
4961       else
4962          return False;
4963       end if;
4964    end Rep_Item_Too_Early;
4965
4966    -----------------------
4967    -- Rep_Item_Too_Late --
4968    -----------------------
4969
4970    function Rep_Item_Too_Late
4971      (T     : Entity_Id;
4972       N     : Node_Id;
4973       FOnly : Boolean := False) return Boolean
4974    is
4975       S           : Entity_Id;
4976       Parent_Type : Entity_Id;
4977
4978       procedure Too_Late;
4979       --  Output the too late message. Note that this is not considered a
4980       --  serious error, since the effect is simply that we ignore the
4981       --  representation clause in this case.
4982
4983       --------------
4984       -- Too_Late --
4985       --------------
4986
4987       procedure Too_Late is
4988       begin
4989          Error_Msg_N ("|representation item appears too late!", N);
4990       end Too_Late;
4991
4992    --  Start of processing for Rep_Item_Too_Late
4993
4994    begin
4995       --  First make sure entity is not frozen (RM 13.1(9)). Exclude imported
4996       --  types, which may be frozen if they appear in a representation clause
4997       --  for a local type.
4998
4999       if Is_Frozen (T)
5000         and then not From_With_Type (T)
5001       then
5002          Too_Late;
5003          S := First_Subtype (T);
5004
5005          if Present (Freeze_Node (S)) then
5006             Error_Msg_NE
5007               ("?no more representation items for }", Freeze_Node (S), S);
5008          end if;
5009
5010          return True;
5011
5012       --  Check for case of non-tagged derived type whose parent either has
5013       --  primitive operations, or is a by reference type (RM 13.1(10)).
5014
5015       elsif Is_Type (T)
5016         and then not FOnly
5017         and then Is_Derived_Type (T)
5018         and then not Is_Tagged_Type (T)
5019       then
5020          Parent_Type := Etype (Base_Type (T));
5021
5022          if Has_Primitive_Operations (Parent_Type) then
5023             Too_Late;
5024             Error_Msg_NE
5025               ("primitive operations already defined for&!", N, Parent_Type);
5026             return True;
5027
5028          elsif Is_By_Reference_Type (Parent_Type) then
5029             Too_Late;
5030             Error_Msg_NE
5031               ("parent type & is a by reference type!", N, Parent_Type);
5032             return True;
5033          end if;
5034       end if;
5035
5036       --  No error, link item into head of chain of rep items for the entity,
5037       --  but avoid chaining if we have an overloadable entity, and the pragma
5038       --  is one that can apply to multiple overloaded entities.
5039
5040       if Is_Overloadable (T)
5041         and then Nkind (N) = N_Pragma
5042       then
5043          declare
5044             Pname : constant Name_Id := Pragma_Name (N);
5045          begin
5046             if Pname = Name_Convention or else
5047                Pname = Name_Import     or else
5048                Pname = Name_Export     or else
5049                Pname = Name_External   or else
5050                Pname = Name_Interface
5051             then
5052                return False;
5053             end if;
5054          end;
5055       end if;
5056
5057       Record_Rep_Item (T, N);
5058       return False;
5059    end Rep_Item_Too_Late;
5060
5061    -------------------------
5062    -- Same_Representation --
5063    -------------------------
5064
5065    function Same_Representation (Typ1, Typ2 : Entity_Id) return Boolean is
5066       T1 : constant Entity_Id := Underlying_Type (Typ1);
5067       T2 : constant Entity_Id := Underlying_Type (Typ2);
5068
5069    begin
5070       --  A quick check, if base types are the same, then we definitely have
5071       --  the same representation, because the subtype specific representation
5072       --  attributes (Size and Alignment) do not affect representation from
5073       --  the point of view of this test.
5074
5075       if Base_Type (T1) = Base_Type (T2) then
5076          return True;
5077
5078       elsif Is_Private_Type (Base_Type (T2))
5079         and then Base_Type (T1) = Full_View (Base_Type (T2))
5080       then
5081          return True;
5082       end if;
5083
5084       --  Tagged types never have differing representations
5085
5086       if Is_Tagged_Type (T1) then
5087          return True;
5088       end if;
5089
5090       --  Representations are definitely different if conventions differ
5091
5092       if Convention (T1) /= Convention (T2) then
5093          return False;
5094       end if;
5095
5096       --  Representations are different if component alignments differ
5097
5098       if (Is_Record_Type (T1) or else Is_Array_Type (T1))
5099         and then
5100          (Is_Record_Type (T2) or else Is_Array_Type (T2))
5101         and then Component_Alignment (T1) /= Component_Alignment (T2)
5102       then
5103          return False;
5104       end if;
5105
5106       --  For arrays, the only real issue is component size. If we know the
5107       --  component size for both arrays, and it is the same, then that's
5108       --  good enough to know we don't have a change of representation.
5109
5110       if Is_Array_Type (T1) then
5111          if Known_Component_Size (T1)
5112            and then Known_Component_Size (T2)
5113            and then Component_Size (T1) = Component_Size (T2)
5114          then
5115             return True;
5116          end if;
5117       end if;
5118
5119       --  Types definitely have same representation if neither has non-standard
5120       --  representation since default representations are always consistent.
5121       --  If only one has non-standard representation, and the other does not,
5122       --  then we consider that they do not have the same representation. They
5123       --  might, but there is no way of telling early enough.
5124
5125       if Has_Non_Standard_Rep (T1) then
5126          if not Has_Non_Standard_Rep (T2) then
5127             return False;
5128          end if;
5129       else
5130          return not Has_Non_Standard_Rep (T2);
5131       end if;
5132
5133       --  Here the two types both have non-standard representation, and we need
5134       --  to determine if they have the same non-standard representation.
5135
5136       --  For arrays, we simply need to test if the component sizes are the
5137       --  same. Pragma Pack is reflected in modified component sizes, so this
5138       --  check also deals with pragma Pack.
5139
5140       if Is_Array_Type (T1) then
5141          return Component_Size (T1) = Component_Size (T2);
5142
5143       --  Tagged types always have the same representation, because it is not
5144       --  possible to specify different representations for common fields.
5145
5146       elsif Is_Tagged_Type (T1) then
5147          return True;
5148
5149       --  Case of record types
5150
5151       elsif Is_Record_Type (T1) then
5152
5153          --  Packed status must conform
5154
5155          if Is_Packed (T1) /= Is_Packed (T2) then
5156             return False;
5157
5158          --  Otherwise we must check components. Typ2 maybe a constrained
5159          --  subtype with fewer components, so we compare the components
5160          --  of the base types.
5161
5162          else
5163             Record_Case : declare
5164                CD1, CD2 : Entity_Id;
5165
5166                function Same_Rep return Boolean;
5167                --  CD1 and CD2 are either components or discriminants. This
5168                --  function tests whether the two have the same representation
5169
5170                --------------
5171                -- Same_Rep --
5172                --------------
5173
5174                function Same_Rep return Boolean is
5175                begin
5176                   if No (Component_Clause (CD1)) then
5177                      return No (Component_Clause (CD2));
5178
5179                   else
5180                      return
5181                         Present (Component_Clause (CD2))
5182                           and then
5183                         Component_Bit_Offset (CD1) = Component_Bit_Offset (CD2)
5184                           and then
5185                         Esize (CD1) = Esize (CD2);
5186                   end if;
5187                end Same_Rep;
5188
5189             --  Start of processing for Record_Case
5190
5191             begin
5192                if Has_Discriminants (T1) then
5193                   CD1 := First_Discriminant (T1);
5194                   CD2 := First_Discriminant (T2);
5195
5196                   --  The number of discriminants may be different if the
5197                   --  derived type has fewer (constrained by values). The
5198                   --  invisible discriminants retain the representation of
5199                   --  the original, so the discrepancy does not per se
5200                   --  indicate a different representation.
5201
5202                   while Present (CD1)
5203                     and then Present (CD2)
5204                   loop
5205                      if not Same_Rep then
5206                         return False;
5207                      else
5208                         Next_Discriminant (CD1);
5209                         Next_Discriminant (CD2);
5210                      end if;
5211                   end loop;
5212                end if;
5213
5214                CD1 := First_Component (Underlying_Type (Base_Type (T1)));
5215                CD2 := First_Component (Underlying_Type (Base_Type (T2)));
5216
5217                while Present (CD1) loop
5218                   if not Same_Rep then
5219                      return False;
5220                   else
5221                      Next_Component (CD1);
5222                      Next_Component (CD2);
5223                   end if;
5224                end loop;
5225
5226                return True;
5227             end Record_Case;
5228          end if;
5229
5230       --  For enumeration types, we must check each literal to see if the
5231       --  representation is the same. Note that we do not permit enumeration
5232       --  representation clauses for Character and Wide_Character, so these
5233       --  cases were already dealt with.
5234
5235       elsif Is_Enumeration_Type (T1) then
5236          Enumeration_Case : declare
5237             L1, L2 : Entity_Id;
5238
5239          begin
5240             L1 := First_Literal (T1);
5241             L2 := First_Literal (T2);
5242
5243             while Present (L1) loop
5244                if Enumeration_Rep (L1) /= Enumeration_Rep (L2) then
5245                   return False;
5246                else
5247                   Next_Literal (L1);
5248                   Next_Literal (L2);
5249                end if;
5250             end loop;
5251
5252             return True;
5253
5254          end Enumeration_Case;
5255
5256       --  Any other types have the same representation for these purposes
5257
5258       else
5259          return True;
5260       end if;
5261    end Same_Representation;
5262
5263    ----------------
5264    -- Set_Biased --
5265    ----------------
5266
5267    procedure Set_Biased
5268      (E      : Entity_Id;
5269       N      : Node_Id;
5270       Msg    : String;
5271       Biased : Boolean := True)
5272    is
5273    begin
5274       if Biased then
5275          Set_Has_Biased_Representation (E);
5276
5277          if Warn_On_Biased_Representation then
5278             Error_Msg_NE
5279               ("?" & Msg & " forces biased representation for&", N, E);
5280          end if;
5281       end if;
5282    end Set_Biased;
5283
5284    --------------------
5285    -- Set_Enum_Esize --
5286    --------------------
5287
5288    procedure Set_Enum_Esize (T : Entity_Id) is
5289       Lo : Uint;
5290       Hi : Uint;
5291       Sz : Nat;
5292
5293    begin
5294       Init_Alignment (T);
5295
5296       --  Find the minimum standard size (8,16,32,64) that fits
5297
5298       Lo := Enumeration_Rep (Entity (Type_Low_Bound (T)));
5299       Hi := Enumeration_Rep (Entity (Type_High_Bound (T)));
5300
5301       if Lo < 0 then
5302          if Lo >= -Uint_2**07 and then Hi < Uint_2**07 then
5303             Sz := Standard_Character_Size;  -- May be > 8 on some targets
5304
5305          elsif Lo >= -Uint_2**15 and then Hi < Uint_2**15 then
5306             Sz := 16;
5307
5308          elsif Lo >= -Uint_2**31 and then Hi < Uint_2**31 then
5309             Sz := 32;
5310
5311          else pragma Assert (Lo >= -Uint_2**63 and then Hi < Uint_2**63);
5312             Sz := 64;
5313          end if;
5314
5315       else
5316          if Hi < Uint_2**08 then
5317             Sz := Standard_Character_Size;  -- May be > 8 on some targets
5318
5319          elsif Hi < Uint_2**16 then
5320             Sz := 16;
5321
5322          elsif Hi < Uint_2**32 then
5323             Sz := 32;
5324
5325          else pragma Assert (Hi < Uint_2**63);
5326             Sz := 64;
5327          end if;
5328       end if;
5329
5330       --  That minimum is the proper size unless we have a foreign convention
5331       --  and the size required is 32 or less, in which case we bump the size
5332       --  up to 32. This is required for C and C++ and seems reasonable for
5333       --  all other foreign conventions.
5334
5335       if Has_Foreign_Convention (T)
5336         and then Esize (T) < Standard_Integer_Size
5337       then
5338          Init_Esize (T, Standard_Integer_Size);
5339       else
5340          Init_Esize (T, Sz);
5341       end if;
5342    end Set_Enum_Esize;
5343
5344    ------------------------------
5345    -- Validate_Address_Clauses --
5346    ------------------------------
5347
5348    procedure Validate_Address_Clauses is
5349    begin
5350       for J in Address_Clause_Checks.First .. Address_Clause_Checks.Last loop
5351          declare
5352             ACCR : Address_Clause_Check_Record
5353                      renames Address_Clause_Checks.Table (J);
5354
5355             Expr : Node_Id;
5356
5357             X_Alignment : Uint;
5358             Y_Alignment : Uint;
5359
5360             X_Size : Uint;
5361             Y_Size : Uint;
5362
5363          begin
5364             --  Skip processing of this entry if warning already posted
5365
5366             if not Address_Warning_Posted (ACCR.N) then
5367
5368                Expr := Original_Node (Expression (ACCR.N));
5369
5370                --  Get alignments
5371
5372                X_Alignment := Alignment (ACCR.X);
5373                Y_Alignment := Alignment (ACCR.Y);
5374
5375                --  Similarly obtain sizes
5376
5377                X_Size := Esize (ACCR.X);
5378                Y_Size := Esize (ACCR.Y);
5379
5380                --  Check for large object overlaying smaller one
5381
5382                if Y_Size > Uint_0
5383                  and then X_Size > Uint_0
5384                  and then X_Size > Y_Size
5385                then
5386                   Error_Msg_NE
5387                     ("?& overlays smaller object", ACCR.N, ACCR.X);
5388                   Error_Msg_N
5389                     ("\?program execution may be erroneous", ACCR.N);
5390                   Error_Msg_Uint_1 := X_Size;
5391                   Error_Msg_NE
5392                     ("\?size of & is ^", ACCR.N, ACCR.X);
5393                   Error_Msg_Uint_1 := Y_Size;
5394                   Error_Msg_NE
5395                     ("\?size of & is ^", ACCR.N, ACCR.Y);
5396
5397                --  Check for inadequate alignment, both of the base object
5398                --  and of the offset, if any.
5399
5400                --  Note: we do not check the alignment if we gave a size
5401                --  warning, since it would likely be redundant.
5402
5403                elsif Y_Alignment /= Uint_0
5404                  and then (Y_Alignment < X_Alignment
5405                              or else (ACCR.Off
5406                                         and then
5407                                           Nkind (Expr) = N_Attribute_Reference
5408                                         and then
5409                                           Attribute_Name (Expr) = Name_Address
5410                                         and then
5411                                           Has_Compatible_Alignment
5412                                             (ACCR.X, Prefix (Expr))
5413                                              /= Known_Compatible))
5414                then
5415                   Error_Msg_NE
5416                     ("?specified address for& may be inconsistent "
5417                        & "with alignment",
5418                      ACCR.N, ACCR.X);
5419                   Error_Msg_N
5420                     ("\?program execution may be erroneous (RM 13.3(27))",
5421                      ACCR.N);
5422                   Error_Msg_Uint_1 := X_Alignment;
5423                   Error_Msg_NE
5424                     ("\?alignment of & is ^",
5425                      ACCR.N, ACCR.X);
5426                   Error_Msg_Uint_1 := Y_Alignment;
5427                   Error_Msg_NE
5428                     ("\?alignment of & is ^",
5429                      ACCR.N, ACCR.Y);
5430                   if Y_Alignment >= X_Alignment then
5431                      Error_Msg_N
5432                       ("\?but offset is not multiple of alignment",
5433                        ACCR.N);
5434                   end if;
5435                end if;
5436             end if;
5437          end;
5438       end loop;
5439    end Validate_Address_Clauses;
5440
5441    ---------------------------
5442    -- Validate_Independence --
5443    ---------------------------
5444
5445    procedure Validate_Independence is
5446       SU   : constant Uint := UI_From_Int (System_Storage_Unit);
5447       N    : Node_Id;
5448       E    : Entity_Id;
5449       IC   : Boolean;
5450       Comp : Entity_Id;
5451       Addr : Node_Id;
5452       P    : Node_Id;
5453
5454       procedure Check_Array_Type (Atyp : Entity_Id);
5455       --  Checks if the array type Atyp has independent components, and
5456       --  if not, outputs an appropriate set of error messages.
5457
5458       procedure No_Independence;
5459       --  Output message that independence cannot be guaranteed
5460
5461       function OK_Component (C : Entity_Id) return Boolean;
5462       --  Checks one component to see if it is independently accessible, and
5463       --  if so yields True, otherwise yields False if independent access
5464       --  cannot be guaranteed. This is a conservative routine, it only
5465       --  returns True if it knows for sure, it returns False if it knows
5466       --  there is a problem, or it cannot be sure there is no problem.
5467
5468       procedure Reason_Bad_Component (C : Entity_Id);
5469       --  Outputs continuation message if a reason can be determined for
5470       --  the component C being bad.
5471
5472       ----------------------
5473       -- Check_Array_Type --
5474       ----------------------
5475
5476       procedure Check_Array_Type (Atyp : Entity_Id) is
5477          Ctyp : constant Entity_Id := Component_Type (Atyp);
5478
5479       begin
5480          --  OK if no alignment clause, no pack, and no component size
5481
5482          if not Has_Component_Size_Clause (Atyp)
5483            and then not Has_Alignment_Clause (Atyp)
5484            and then not Is_Packed (Atyp)
5485          then
5486             return;
5487          end if;
5488
5489          --  Check actual component size
5490
5491          if not Known_Component_Size (Atyp)
5492            or else not (Addressable (Component_Size (Atyp))
5493                           and then Component_Size (Atyp) < 64)
5494            or else Component_Size (Atyp) mod Esize (Ctyp) /= 0
5495          then
5496             No_Independence;
5497
5498             --  Bad component size, check reason
5499
5500             if Has_Component_Size_Clause (Atyp) then
5501                P :=
5502                  Get_Attribute_Definition_Clause
5503                    (Atyp, Attribute_Component_Size);
5504
5505                if Present (P) then
5506                   Error_Msg_Sloc := Sloc (P);
5507                   Error_Msg_N ("\because of Component_Size clause#", N);
5508                   return;
5509                end if;
5510             end if;
5511
5512             if Is_Packed (Atyp) then
5513                P := Get_Rep_Pragma (Atyp, Name_Pack);
5514
5515                if Present (P) then
5516                   Error_Msg_Sloc := Sloc (P);
5517                   Error_Msg_N ("\because of pragma Pack#", N);
5518                   return;
5519                end if;
5520             end if;
5521
5522             --  No reason found, just return
5523
5524             return;
5525          end if;
5526
5527          --  Array type is OK independence-wise
5528
5529          return;
5530       end Check_Array_Type;
5531
5532       ---------------------
5533       -- No_Independence --
5534       ---------------------
5535
5536       procedure No_Independence is
5537       begin
5538          if Pragma_Name (N) = Name_Independent then
5539             Error_Msg_NE
5540               ("independence cannot be guaranteed for&", N, E);
5541          else
5542             Error_Msg_NE
5543               ("independent components cannot be guaranteed for&", N, E);
5544          end if;
5545       end No_Independence;
5546
5547       ------------------
5548       -- OK_Component --
5549       ------------------
5550
5551       function OK_Component (C : Entity_Id) return Boolean is
5552          Rec  : constant Entity_Id := Scope (C);
5553          Ctyp : constant Entity_Id := Etype (C);
5554
5555       begin
5556          --  OK if no component clause, no Pack, and no alignment clause
5557
5558          if No (Component_Clause (C))
5559            and then not Is_Packed (Rec)
5560            and then not Has_Alignment_Clause (Rec)
5561          then
5562             return True;
5563          end if;
5564
5565          --  Here we look at the actual component layout. A component is
5566          --  addressable if its size is a multiple of the Esize of the
5567          --  component type, and its starting position in the record has
5568          --  appropriate alignment, and the record itself has appropriate
5569          --  alignment to guarantee the component alignment.
5570
5571          --  Make sure sizes are static, always assume the worst for any
5572          --  cases where we cannot check static values.
5573
5574          if not (Known_Static_Esize (C)
5575                   and then Known_Static_Esize (Ctyp))
5576          then
5577             return False;
5578          end if;
5579
5580          --  Size of component must be addressable or greater than 64 bits
5581          --  and a multiple of bytes.
5582
5583          if not Addressable (Esize (C))
5584            and then Esize (C) < Uint_64
5585          then
5586             return False;
5587          end if;
5588
5589          --  Check size is proper multiple
5590
5591          if Esize (C) mod Esize (Ctyp) /= 0 then
5592             return False;
5593          end if;
5594
5595          --  Check alignment of component is OK
5596
5597          if not Known_Component_Bit_Offset (C)
5598            or else Component_Bit_Offset (C) < Uint_0
5599            or else Component_Bit_Offset (C) mod Esize (Ctyp) /= 0
5600          then
5601             return False;
5602          end if;
5603
5604          --  Check alignment of record type is OK
5605
5606          if not Known_Alignment (Rec)
5607            or else (Alignment (Rec) * SU) mod Esize (Ctyp) /= 0
5608          then
5609             return False;
5610          end if;
5611
5612          --  All tests passed, component is addressable
5613
5614          return True;
5615       end OK_Component;
5616
5617       --------------------------
5618       -- Reason_Bad_Component --
5619       --------------------------
5620
5621       procedure Reason_Bad_Component (C : Entity_Id) is
5622          Rec  : constant Entity_Id := Scope (C);
5623          Ctyp : constant Entity_Id := Etype (C);
5624
5625       begin
5626          --  If component clause present assume that's the problem
5627
5628          if Present (Component_Clause (C)) then
5629             Error_Msg_Sloc := Sloc (Component_Clause (C));
5630             Error_Msg_N ("\because of Component_Clause#", N);
5631             return;
5632          end if;
5633
5634          --  If pragma Pack clause present, assume that's the problem
5635
5636          if Is_Packed (Rec) then
5637             P := Get_Rep_Pragma (Rec, Name_Pack);
5638
5639             if Present (P) then
5640                Error_Msg_Sloc := Sloc (P);
5641                Error_Msg_N ("\because of pragma Pack#", N);
5642                return;
5643             end if;
5644          end if;
5645
5646          --  See if record has bad alignment clause
5647
5648          if Has_Alignment_Clause (Rec)
5649            and then Known_Alignment (Rec)
5650            and then (Alignment (Rec) * SU) mod Esize (Ctyp) /= 0
5651          then
5652             P := Get_Attribute_Definition_Clause (Rec, Attribute_Alignment);
5653
5654             if Present (P) then
5655                Error_Msg_Sloc := Sloc (P);
5656                Error_Msg_N ("\because of Alignment clause#", N);
5657             end if;
5658          end if;
5659
5660          --  Couldn't find a reason, so return without a message
5661
5662          return;
5663       end Reason_Bad_Component;
5664
5665    --  Start of processing for Validate_Independence
5666
5667    begin
5668       for J in Independence_Checks.First .. Independence_Checks.Last loop
5669          N  := Independence_Checks.Table (J).N;
5670          E  := Independence_Checks.Table (J).E;
5671          IC := Pragma_Name (N) = Name_Independent_Components;
5672
5673          --  Deal with component case
5674
5675          if Ekind (E) = E_Discriminant or else Ekind (E) = E_Component then
5676             if not OK_Component (E) then
5677                No_Independence;
5678                Reason_Bad_Component (E);
5679                goto Continue;
5680             end if;
5681          end if;
5682
5683          --  Deal with record with Independent_Components
5684
5685          if IC and then Is_Record_Type (E) then
5686             Comp := First_Component_Or_Discriminant (E);
5687             while Present (Comp) loop
5688                if not OK_Component (Comp) then
5689                   No_Independence;
5690                   Reason_Bad_Component (Comp);
5691                   goto Continue;
5692                end if;
5693
5694                Next_Component_Or_Discriminant (Comp);
5695             end loop;
5696          end if;
5697
5698          --  Deal with address clause case
5699
5700          if Is_Object (E) then
5701             Addr := Address_Clause (E);
5702
5703             if Present (Addr) then
5704                No_Independence;
5705                Error_Msg_Sloc := Sloc (Addr);
5706                Error_Msg_N ("\because of Address clause#", N);
5707                goto Continue;
5708             end if;
5709          end if;
5710
5711          --  Deal with independent components for array type
5712
5713          if IC and then Is_Array_Type (E) then
5714             Check_Array_Type (E);
5715          end if;
5716
5717          --  Deal with independent components for array object
5718
5719          if IC and then Is_Object (E) and then Is_Array_Type (Etype (E)) then
5720             Check_Array_Type (Etype (E));
5721          end if;
5722
5723       <<Continue>> null;
5724       end loop;
5725    end Validate_Independence;
5726
5727    -----------------------------------
5728    -- Validate_Unchecked_Conversion --
5729    -----------------------------------
5730
5731    procedure Validate_Unchecked_Conversion
5732      (N        : Node_Id;
5733       Act_Unit : Entity_Id)
5734    is
5735       Source : Entity_Id;
5736       Target : Entity_Id;
5737       Vnode  : Node_Id;
5738
5739    begin
5740       --  Obtain source and target types. Note that we call Ancestor_Subtype
5741       --  here because the processing for generic instantiation always makes
5742       --  subtypes, and we want the original frozen actual types.
5743
5744       --  If we are dealing with private types, then do the check on their
5745       --  fully declared counterparts if the full declarations have been
5746       --  encountered (they don't have to be visible, but they must exist!)
5747
5748       Source := Ancestor_Subtype (Etype (First_Formal (Act_Unit)));
5749
5750       if Is_Private_Type (Source)
5751         and then Present (Underlying_Type (Source))
5752       then
5753          Source := Underlying_Type (Source);
5754       end if;
5755
5756       Target := Ancestor_Subtype (Etype (Act_Unit));
5757
5758       --  If either type is generic, the instantiation happens within a generic
5759       --  unit, and there is nothing to check. The proper check
5760       --  will happen when the enclosing generic is instantiated.
5761
5762       if Is_Generic_Type (Source) or else Is_Generic_Type (Target) then
5763          return;
5764       end if;
5765
5766       if Is_Private_Type (Target)
5767         and then Present (Underlying_Type (Target))
5768       then
5769          Target := Underlying_Type (Target);
5770       end if;
5771
5772       --  Source may be unconstrained array, but not target
5773
5774       if Is_Array_Type (Target)
5775         and then not Is_Constrained (Target)
5776       then
5777          Error_Msg_N
5778            ("unchecked conversion to unconstrained array not allowed", N);
5779          return;
5780       end if;
5781
5782       --  Warn if conversion between two different convention pointers
5783
5784       if Is_Access_Type (Target)
5785         and then Is_Access_Type (Source)
5786         and then Convention (Target) /= Convention (Source)
5787         and then Warn_On_Unchecked_Conversion
5788       then
5789          --  Give warnings for subprogram pointers only on most targets. The
5790          --  exception is VMS, where data pointers can have different lengths
5791          --  depending on the pointer convention.
5792
5793          if Is_Access_Subprogram_Type (Target)
5794            or else Is_Access_Subprogram_Type (Source)
5795            or else OpenVMS_On_Target
5796          then
5797             Error_Msg_N
5798               ("?conversion between pointers with different conventions!", N);
5799          end if;
5800       end if;
5801
5802       --  Warn if one of the operands is Ada.Calendar.Time. Do not emit a
5803       --  warning when compiling GNAT-related sources.
5804
5805       if Warn_On_Unchecked_Conversion
5806         and then not In_Predefined_Unit (N)
5807         and then RTU_Loaded (Ada_Calendar)
5808         and then
5809           (Chars (Source) = Name_Time
5810              or else
5811            Chars (Target) = Name_Time)
5812       then
5813          --  If Ada.Calendar is loaded and the name of one of the operands is
5814          --  Time, there is a good chance that this is Ada.Calendar.Time.
5815
5816          declare
5817             Calendar_Time : constant Entity_Id :=
5818                               Full_View (RTE (RO_CA_Time));
5819          begin
5820             pragma Assert (Present (Calendar_Time));
5821
5822             if Source = Calendar_Time
5823               or else Target = Calendar_Time
5824             then
5825                Error_Msg_N
5826                  ("?representation of 'Time values may change between " &
5827                   "'G'N'A'T versions", N);
5828             end if;
5829          end;
5830       end if;
5831
5832       --  Make entry in unchecked conversion table for later processing by
5833       --  Validate_Unchecked_Conversions, which will check sizes and alignments
5834       --  (using values set by the back-end where possible). This is only done
5835       --  if the appropriate warning is active.
5836
5837       if Warn_On_Unchecked_Conversion then
5838          Unchecked_Conversions.Append
5839            (New_Val => UC_Entry'
5840               (Eloc   => Sloc (N),
5841                Source => Source,
5842                Target => Target));
5843
5844          --  If both sizes are known statically now, then back end annotation
5845          --  is not required to do a proper check but if either size is not
5846          --  known statically, then we need the annotation.
5847
5848          if Known_Static_RM_Size (Source)
5849            and then Known_Static_RM_Size (Target)
5850          then
5851             null;
5852          else
5853             Back_Annotate_Rep_Info := True;
5854          end if;
5855       end if;
5856
5857       --  If unchecked conversion to access type, and access type is declared
5858       --  in the same unit as the unchecked conversion, then set the
5859       --  No_Strict_Aliasing flag (no strict aliasing is implicit in this
5860       --  situation).
5861
5862       if Is_Access_Type (Target) and then
5863         In_Same_Source_Unit (Target, N)
5864       then
5865          Set_No_Strict_Aliasing (Implementation_Base_Type (Target));
5866       end if;
5867
5868       --  Generate N_Validate_Unchecked_Conversion node for back end in
5869       --  case the back end needs to perform special validation checks.
5870
5871       --  Shouldn't this be in Exp_Ch13, since the check only gets done
5872       --  if we have full expansion and the back end is called ???
5873
5874       Vnode :=
5875         Make_Validate_Unchecked_Conversion (Sloc (N));
5876       Set_Source_Type (Vnode, Source);
5877       Set_Target_Type (Vnode, Target);
5878
5879       --  If the unchecked conversion node is in a list, just insert before it.
5880       --  If not we have some strange case, not worth bothering about.
5881
5882       if Is_List_Member (N) then
5883          Insert_After (N, Vnode);
5884       end if;
5885    end Validate_Unchecked_Conversion;
5886
5887    ------------------------------------
5888    -- Validate_Unchecked_Conversions --
5889    ------------------------------------
5890
5891    procedure Validate_Unchecked_Conversions is
5892    begin
5893       for N in Unchecked_Conversions.First .. Unchecked_Conversions.Last loop
5894          declare
5895             T : UC_Entry renames Unchecked_Conversions.Table (N);
5896
5897             Eloc   : constant Source_Ptr := T.Eloc;
5898             Source : constant Entity_Id  := T.Source;
5899             Target : constant Entity_Id  := T.Target;
5900
5901             Source_Siz    : Uint;
5902             Target_Siz    : Uint;
5903
5904          begin
5905             --  This validation check, which warns if we have unequal sizes for
5906             --  unchecked conversion, and thus potentially implementation
5907             --  dependent semantics, is one of the few occasions on which we
5908             --  use the official RM size instead of Esize. See description in
5909             --  Einfo "Handling of Type'Size Values" for details.
5910
5911             if Serious_Errors_Detected = 0
5912               and then Known_Static_RM_Size (Source)
5913               and then Known_Static_RM_Size (Target)
5914
5915               --  Don't do the check if warnings off for either type, note the
5916               --  deliberate use of OR here instead of OR ELSE to get the flag
5917               --  Warnings_Off_Used set for both types if appropriate.
5918
5919               and then not (Has_Warnings_Off (Source)
5920                               or
5921                             Has_Warnings_Off (Target))
5922             then
5923                Source_Siz := RM_Size (Source);
5924                Target_Siz := RM_Size (Target);
5925
5926                if Source_Siz /= Target_Siz then
5927                   Error_Msg
5928                     ("?types for unchecked conversion have different sizes!",
5929                      Eloc);
5930
5931                   if All_Errors_Mode then
5932                      Error_Msg_Name_1 := Chars (Source);
5933                      Error_Msg_Uint_1 := Source_Siz;
5934                      Error_Msg_Name_2 := Chars (Target);
5935                      Error_Msg_Uint_2 := Target_Siz;
5936                      Error_Msg ("\size of % is ^, size of % is ^?", Eloc);
5937
5938                      Error_Msg_Uint_1 := UI_Abs (Source_Siz - Target_Siz);
5939
5940                      if Is_Discrete_Type (Source)
5941                        and then Is_Discrete_Type (Target)
5942                      then
5943                         if Source_Siz > Target_Siz then
5944                            Error_Msg
5945                              ("\?^ high order bits of source will be ignored!",
5946                               Eloc);
5947
5948                         elsif Is_Unsigned_Type (Source) then
5949                            Error_Msg
5950                              ("\?source will be extended with ^ high order " &
5951                               "zero bits?!", Eloc);
5952
5953                         else
5954                            Error_Msg
5955                              ("\?source will be extended with ^ high order " &
5956                               "sign bits!",
5957                               Eloc);
5958                         end if;
5959
5960                      elsif Source_Siz < Target_Siz then
5961                         if Is_Discrete_Type (Target) then
5962                            if Bytes_Big_Endian then
5963                               Error_Msg
5964                                 ("\?target value will include ^ undefined " &
5965                                  "low order bits!",
5966                                  Eloc);
5967                            else
5968                               Error_Msg
5969                                 ("\?target value will include ^ undefined " &
5970                                  "high order bits!",
5971                                  Eloc);
5972                            end if;
5973
5974                         else
5975                            Error_Msg
5976                              ("\?^ trailing bits of target value will be " &
5977                               "undefined!", Eloc);
5978                         end if;
5979
5980                      else pragma Assert (Source_Siz > Target_Siz);
5981                         Error_Msg
5982                           ("\?^ trailing bits of source will be ignored!",
5983                            Eloc);
5984                      end if;
5985                   end if;
5986                end if;
5987             end if;
5988
5989             --  If both types are access types, we need to check the alignment.
5990             --  If the alignment of both is specified, we can do it here.
5991
5992             if Serious_Errors_Detected = 0
5993               and then Ekind (Source) in Access_Kind
5994               and then Ekind (Target) in Access_Kind
5995               and then Target_Strict_Alignment
5996               and then Present (Designated_Type (Source))
5997               and then Present (Designated_Type (Target))
5998             then
5999                declare
6000                   D_Source : constant Entity_Id := Designated_Type (Source);
6001                   D_Target : constant Entity_Id := Designated_Type (Target);
6002
6003                begin
6004                   if Known_Alignment (D_Source)
6005                     and then Known_Alignment (D_Target)
6006                   then
6007                      declare
6008                         Source_Align : constant Uint := Alignment (D_Source);
6009                         Target_Align : constant Uint := Alignment (D_Target);
6010
6011                      begin
6012                         if Source_Align < Target_Align
6013                           and then not Is_Tagged_Type (D_Source)
6014
6015                           --  Suppress warning if warnings suppressed on either
6016                           --  type or either designated type. Note the use of
6017                           --  OR here instead of OR ELSE. That is intentional,
6018                           --  we would like to set flag Warnings_Off_Used in
6019                           --  all types for which warnings are suppressed.
6020
6021                           and then not (Has_Warnings_Off (D_Source)
6022                                           or
6023                                         Has_Warnings_Off (D_Target)
6024                                           or
6025                                         Has_Warnings_Off (Source)
6026                                           or
6027                                         Has_Warnings_Off (Target))
6028                         then
6029                            Error_Msg_Uint_1 := Target_Align;
6030                            Error_Msg_Uint_2 := Source_Align;
6031                            Error_Msg_Node_1 := D_Target;
6032                            Error_Msg_Node_2 := D_Source;
6033                            Error_Msg
6034                              ("?alignment of & (^) is stricter than " &
6035                               "alignment of & (^)!", Eloc);
6036                            Error_Msg
6037                              ("\?resulting access value may have invalid " &
6038                               "alignment!", Eloc);
6039                         end if;
6040                      end;
6041                   end if;
6042                end;
6043             end if;
6044          end;
6045       end loop;
6046    end Validate_Unchecked_Conversions;
6047
6048 end Sem_Ch13;