OSDN Git Service

2007-08-14 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_attr.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ A T T R                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2007, 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 2,  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 COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Exp_Atag; use Exp_Atag;
32 with Exp_Ch2;  use Exp_Ch2;
33 with Exp_Ch9;  use Exp_Ch9;
34 with Exp_Imgv; use Exp_Imgv;
35 with Exp_Pakd; use Exp_Pakd;
36 with Exp_Strm; use Exp_Strm;
37 with Exp_Tss;  use Exp_Tss;
38 with Exp_Util; use Exp_Util;
39 with Exp_VFpt; use Exp_VFpt;
40 with Gnatvsn;  use Gnatvsn;
41 with Lib;      use Lib;
42 with Namet;    use Namet;
43 with Nmake;    use Nmake;
44 with Nlists;   use Nlists;
45 with Opt;      use Opt;
46 with Restrict; use Restrict;
47 with Rident;   use Rident;
48 with Rtsfind;  use Rtsfind;
49 with Sem;      use Sem;
50 with Sem_Ch7;  use Sem_Ch7;
51 with Sem_Ch8;  use Sem_Ch8;
52 with Sem_Eval; use Sem_Eval;
53 with Sem_Res;  use Sem_Res;
54 with Sem_Util; use Sem_Util;
55 with Sinfo;    use Sinfo;
56 with Snames;   use Snames;
57 with Stand;    use Stand;
58 with Stringt;  use Stringt;
59 with Targparm; use Targparm;
60 with Tbuild;   use Tbuild;
61 with Ttypes;   use Ttypes;
62 with Uintp;    use Uintp;
63 with Uname;    use Uname;
64 with Validsw;  use Validsw;
65
66 package body Exp_Attr is
67
68    -----------------------
69    -- Local Subprograms --
70    -----------------------
71
72    procedure Compile_Stream_Body_In_Scope
73      (N     : Node_Id;
74       Decl  : Node_Id;
75       Arr   : Entity_Id;
76       Check : Boolean);
77    --  The body for a stream subprogram may be generated outside of the scope
78    --  of the type. If the type is fully private, it may depend on the full
79    --  view of other types (e.g. indices) that are currently private as well.
80    --  We install the declarations of the package in which the type is declared
81    --  before compiling the body in what is its proper environment. The Check
82    --  parameter indicates if checks are to be suppressed for the stream body.
83    --  We suppress checks for array/record reads, since the rule is that these
84    --  are like assignments, out of range values due to uninitialized storage,
85    --  or other invalid values do NOT cause a Constraint_Error to be raised.
86
87    procedure Expand_Access_To_Protected_Op
88      (N    : Node_Id;
89       Pref : Node_Id;
90       Typ  : Entity_Id);
91
92    --  An attribute reference to a protected subprogram is transformed into
93    --  a pair of pointers: one to the object, and one to the operations.
94    --  This expansion is performed for 'Access and for 'Unrestricted_Access.
95
96    procedure Expand_Fpt_Attribute
97      (N    : Node_Id;
98       Pkg  : RE_Id;
99       Nam  : Name_Id;
100       Args : List_Id);
101    --  This procedure expands a call to a floating-point attribute function.
102    --  N is the attribute reference node, and Args is a list of arguments to
103    --  be passed to the function call. Pkg identifies the package containing
104    --  the appropriate instantiation of System.Fat_Gen. Float arguments in Args
105    --  have already been converted to the floating-point type for which Pkg was
106    --  instantiated. The Nam argument is the relevant attribute processing
107    --  routine to be called. This is the same as the attribute name, except in
108    --  the Unaligned_Valid case.
109
110    procedure Expand_Fpt_Attribute_R (N : Node_Id);
111    --  This procedure expands a call to a floating-point attribute function
112    --  that takes a single floating-point argument. The function to be called
113    --  is always the same as the attribute name.
114
115    procedure Expand_Fpt_Attribute_RI (N : Node_Id);
116    --  This procedure expands a call to a floating-point attribute function
117    --  that takes one floating-point argument and one integer argument. The
118    --  function to be called is always the same as the attribute name.
119
120    procedure Expand_Fpt_Attribute_RR (N : Node_Id);
121    --  This procedure expands a call to a floating-point attribute function
122    --  that takes two floating-point arguments. The function to be called
123    --  is always the same as the attribute name.
124
125    procedure Expand_Pred_Succ (N : Node_Id);
126    --  Handles expansion of Pred or Succ attributes for case of non-real
127    --  operand with overflow checking required.
128
129    function Get_Index_Subtype (N : Node_Id) return Entity_Id;
130    --  Used for Last, Last, and Length, when the prefix is an array type,
131    --  Obtains the corresponding index subtype.
132
133    procedure Find_Fat_Info
134      (T        : Entity_Id;
135       Fat_Type : out Entity_Id;
136       Fat_Pkg  : out RE_Id);
137    --  Given a floating-point type T, identifies the package containing the
138    --  attributes for this type (returned in Fat_Pkg), and the corresponding
139    --  type for which this package was instantiated from Fat_Gen. Error if T
140    --  is not a floating-point type.
141
142    function Find_Stream_Subprogram
143      (Typ : Entity_Id;
144       Nam : TSS_Name_Type) return Entity_Id;
145    --  Returns the stream-oriented subprogram attribute for Typ. For tagged
146    --  types, the corresponding primitive operation is looked up, else the
147    --  appropriate TSS from the type itself, or from its closest ancestor
148    --  defining it, is returned. In both cases, inheritance of representation
149    --  aspects is thus taken into account.
150
151    function Get_Stream_Convert_Pragma (T : Entity_Id) return Node_Id;
152    --  Given a type, find a corresponding stream convert pragma that applies to
153    --  the implementation base type of this type (Typ). If found, return the
154    --  pragma node, otherwise return Empty if no pragma is found.
155
156    function Is_Constrained_Packed_Array (Typ : Entity_Id) return Boolean;
157    --  Utility for array attributes, returns true on packed constrained
158    --  arrays, and on access to same.
159
160    function Is_Inline_Floating_Point_Attribute (N : Node_Id) return Boolean;
161    --  Returns true iff the given node refers to an attribute call that
162    --  can be expanded directly by the back end and does not need front end
163    --  expansion. Typically used for rounding and truncation attributes that
164    --  appear directly inside a conversion to integer.
165
166    ----------------------------------
167    -- Compile_Stream_Body_In_Scope --
168    ----------------------------------
169
170    procedure Compile_Stream_Body_In_Scope
171      (N     : Node_Id;
172       Decl  : Node_Id;
173       Arr   : Entity_Id;
174       Check : Boolean)
175    is
176       Installed : Boolean := False;
177       Scop      : constant Entity_Id := Scope (Arr);
178       Curr      : constant Entity_Id := Current_Scope;
179
180    begin
181       if Is_Hidden (Arr)
182         and then not In_Open_Scopes (Scop)
183         and then Ekind (Scop) = E_Package
184       then
185          Push_Scope (Scop);
186          Install_Visible_Declarations (Scop);
187          Install_Private_Declarations (Scop);
188          Installed := True;
189
190          --  The entities in the package are now visible, but the generated
191          --  stream entity must appear in the current scope (usually an
192          --  enclosing stream function) so that itypes all have their proper
193          --  scopes.
194
195          Push_Scope (Curr);
196       end if;
197
198       if Check then
199          Insert_Action (N, Decl);
200       else
201          Insert_Action (N, Decl, Suppress => All_Checks);
202       end if;
203
204       if Installed then
205
206          --  Remove extra copy of current scope, and package itself
207
208          Pop_Scope;
209          End_Package_Scope (Scop);
210       end if;
211    end Compile_Stream_Body_In_Scope;
212
213    -----------------------------------
214    -- Expand_Access_To_Protected_Op --
215    -----------------------------------
216
217    procedure Expand_Access_To_Protected_Op
218      (N    : Node_Id;
219       Pref : Node_Id;
220       Typ  : Entity_Id)
221    is
222       --  The value of the attribute_reference is a record containing two
223       --  fields: an access to the protected object, and an access to the
224       --  subprogram itself. The prefix is a selected component.
225
226       Loc     : constant Source_Ptr := Sloc (N);
227       Agg     : Node_Id;
228       Btyp    : constant Entity_Id := Base_Type (Typ);
229       Sub     : Entity_Id;
230       E_T     : constant Entity_Id := Equivalent_Type (Btyp);
231       Acc     : constant Entity_Id :=
232                   Etype (Next_Component (First_Component (E_T)));
233       Obj_Ref : Node_Id;
234       Curr    : Entity_Id;
235
236       function May_Be_External_Call return Boolean;
237       --  If the 'Access is to a local operation, but appears in a context
238       --  where it may lead to a call from outside the object, we must treat
239       --  this as an external call. Clearly we cannot tell without full
240       --  flow analysis, and a subsequent call that uses this 'Access may
241       --  lead to a bounded error (trying to seize locks twice, e.g.). For
242       --  now we treat 'Access as a potential external call if it is an actual
243       --  in a call to an outside subprogram.
244
245       --------------------------
246       -- May_Be_External_Call --
247       --------------------------
248
249       function May_Be_External_Call return Boolean is
250          Subp : Entity_Id;
251       begin
252          if (Nkind (Parent (N)) = N_Procedure_Call_Statement
253               or else Nkind (Parent (N)) = N_Function_Call)
254             and then Is_Entity_Name (Name (Parent (N)))
255          then
256             Subp := Entity (Name (Parent (N)));
257             return not In_Open_Scopes (Scope (Subp));
258          else
259             return False;
260          end if;
261       end May_Be_External_Call;
262
263    --  Start of processing for Expand_Access_To_Protected_Op
264
265    begin
266       --  Within the body of the protected type, the prefix
267       --  designates a local operation, and the object is the first
268       --  parameter of the corresponding protected body of the
269       --  current enclosing operation.
270
271       if Is_Entity_Name (Pref) then
272          pragma Assert (In_Open_Scopes (Scope (Entity (Pref))));
273
274          if May_Be_External_Call then
275             Sub :=
276               New_Occurrence_Of
277                 (External_Subprogram (Entity (Pref)), Loc);
278          else
279             Sub :=
280               New_Occurrence_Of
281                 (Protected_Body_Subprogram (Entity (Pref)), Loc);
282          end if;
283
284          Curr := Current_Scope;
285          while Scope (Curr) /= Scope (Entity (Pref)) loop
286             Curr := Scope (Curr);
287          end loop;
288
289          --  In case of protected entries the first formal of its Protected_
290          --  Body_Subprogram is the address of the object.
291
292          if Ekind (Curr) = E_Entry then
293             Obj_Ref :=
294                New_Occurrence_Of
295                  (First_Formal
296                    (Protected_Body_Subprogram (Curr)), Loc);
297
298          --  In case of protected subprograms the first formal of its
299          --  Protected_Body_Subprogram is the object and we get its address.
300
301          else
302             Obj_Ref :=
303               Make_Attribute_Reference (Loc,
304                 Prefix =>
305                    New_Occurrence_Of
306                      (First_Formal
307                         (Protected_Body_Subprogram (Curr)), Loc),
308                 Attribute_Name => Name_Address);
309          end if;
310
311       --  Case where the prefix is not an entity name. Find the
312       --  version of the protected operation to be called from
313       --  outside the protected object.
314
315       else
316          Sub :=
317            New_Occurrence_Of
318              (External_Subprogram
319                (Entity (Selector_Name (Pref))), Loc);
320
321          Obj_Ref :=
322            Make_Attribute_Reference (Loc,
323              Prefix => Relocate_Node (Prefix (Pref)),
324                Attribute_Name => Name_Address);
325       end if;
326
327       Agg :=
328         Make_Aggregate (Loc,
329           Expressions =>
330             New_List (
331               Obj_Ref,
332               Unchecked_Convert_To (Acc,
333                 Make_Attribute_Reference (Loc,
334                   Prefix => Sub,
335                   Attribute_Name => Name_Address))));
336
337       Rewrite (N, Agg);
338
339       Analyze_And_Resolve (N, E_T);
340
341       --  For subsequent analysis,  the node must retain its type.
342       --  The backend will replace it with the equivalent type where
343       --  needed.
344
345       Set_Etype (N, Typ);
346    end Expand_Access_To_Protected_Op;
347
348    --------------------------
349    -- Expand_Fpt_Attribute --
350    --------------------------
351
352    procedure Expand_Fpt_Attribute
353      (N    : Node_Id;
354       Pkg  : RE_Id;
355       Nam  : Name_Id;
356       Args : List_Id)
357    is
358       Loc : constant Source_Ptr := Sloc (N);
359       Typ : constant Entity_Id  := Etype (N);
360       Fnm : Node_Id;
361
362    begin
363       --  The function name is the selected component Attr_xxx.yyy where
364       --  Attr_xxx is the package name, and yyy is the argument Nam.
365
366       --  Note: it would be more usual to have separate RE entries for each
367       --  of the entities in the Fat packages, but first they have identical
368       --  names (so we would have to have lots of renaming declarations to
369       --  meet the normal RE rule of separate names for all runtime entities),
370       --  and second there would be an awful lot of them!
371
372       Fnm :=
373         Make_Selected_Component (Loc,
374           Prefix        => New_Reference_To (RTE (Pkg), Loc),
375           Selector_Name => Make_Identifier (Loc, Nam));
376
377       --  The generated call is given the provided set of parameters, and then
378       --  wrapped in a conversion which converts the result to the target type
379       --  We use the base type as the target because a range check may be
380       --  required.
381
382       Rewrite (N,
383         Unchecked_Convert_To (Base_Type (Etype (N)),
384           Make_Function_Call (Loc,
385             Name                   => Fnm,
386             Parameter_Associations => Args)));
387
388       Analyze_And_Resolve (N, Typ);
389    end Expand_Fpt_Attribute;
390
391    ----------------------------
392    -- Expand_Fpt_Attribute_R --
393    ----------------------------
394
395    --  The single argument is converted to its root type to call the
396    --  appropriate runtime function, with the actual call being built
397    --  by Expand_Fpt_Attribute
398
399    procedure Expand_Fpt_Attribute_R (N : Node_Id) is
400       E1  : constant Node_Id    := First (Expressions (N));
401       Ftp : Entity_Id;
402       Pkg : RE_Id;
403    begin
404       Find_Fat_Info (Etype (E1), Ftp, Pkg);
405       Expand_Fpt_Attribute
406         (N, Pkg, Attribute_Name (N),
407          New_List (Unchecked_Convert_To (Ftp, Relocate_Node (E1))));
408    end Expand_Fpt_Attribute_R;
409
410    -----------------------------
411    -- Expand_Fpt_Attribute_RI --
412    -----------------------------
413
414    --  The first argument is converted to its root type and the second
415    --  argument is converted to standard long long integer to call the
416    --  appropriate runtime function, with the actual call being built
417    --  by Expand_Fpt_Attribute
418
419    procedure Expand_Fpt_Attribute_RI (N : Node_Id) is
420       E1  : constant Node_Id   := First (Expressions (N));
421       Ftp : Entity_Id;
422       Pkg : RE_Id;
423       E2  : constant Node_Id   := Next (E1);
424    begin
425       Find_Fat_Info (Etype (E1), Ftp, Pkg);
426       Expand_Fpt_Attribute
427         (N, Pkg, Attribute_Name (N),
428          New_List (
429            Unchecked_Convert_To (Ftp, Relocate_Node (E1)),
430            Unchecked_Convert_To (Standard_Integer, Relocate_Node (E2))));
431    end Expand_Fpt_Attribute_RI;
432
433    -----------------------------
434    -- Expand_Fpt_Attribute_RR --
435    -----------------------------
436
437    --  The two arguments are converted to their root types to call the
438    --  appropriate runtime function, with the actual call being built
439    --  by Expand_Fpt_Attribute
440
441    procedure Expand_Fpt_Attribute_RR (N : Node_Id) is
442       E1  : constant Node_Id   := First (Expressions (N));
443       Ftp : Entity_Id;
444       Pkg : RE_Id;
445       E2  : constant Node_Id   := Next (E1);
446    begin
447       Find_Fat_Info (Etype (E1), Ftp, Pkg);
448       Expand_Fpt_Attribute
449         (N, Pkg, Attribute_Name (N),
450          New_List (
451            Unchecked_Convert_To (Ftp, Relocate_Node (E1)),
452            Unchecked_Convert_To (Ftp, Relocate_Node (E2))));
453    end Expand_Fpt_Attribute_RR;
454
455    ----------------------------------
456    -- Expand_N_Attribute_Reference --
457    ----------------------------------
458
459    procedure Expand_N_Attribute_Reference (N : Node_Id) is
460       Loc   : constant Source_Ptr   := Sloc (N);
461       Typ   : constant Entity_Id    := Etype (N);
462       Btyp  : constant Entity_Id    := Base_Type (Typ);
463       Pref  : constant Node_Id      := Prefix (N);
464       Exprs : constant List_Id      := Expressions (N);
465       Id    : constant Attribute_Id := Get_Attribute_Id (Attribute_Name (N));
466
467       procedure Rewrite_Stream_Proc_Call (Pname : Entity_Id);
468       --  Rewrites a stream attribute for Read, Write or Output with the
469       --  procedure call. Pname is the entity for the procedure to call.
470
471       ------------------------------
472       -- Rewrite_Stream_Proc_Call --
473       ------------------------------
474
475       procedure Rewrite_Stream_Proc_Call (Pname : Entity_Id) is
476          Item       : constant Node_Id   := Next (First (Exprs));
477          Formal     : constant Entity_Id := Next_Formal (First_Formal (Pname));
478          Formal_Typ : constant Entity_Id := Etype (Formal);
479          Is_Written : constant Boolean   := (Ekind (Formal) /= E_In_Parameter);
480
481       begin
482          --  The expansion depends on Item, the second actual, which is
483          --  the object being streamed in or out.
484
485          --  If the item is a component of a packed array type, and
486          --  a conversion is needed on exit, we introduce a temporary to
487          --  hold the value, because otherwise the packed reference will
488          --  not be properly expanded.
489
490          if Nkind (Item) = N_Indexed_Component
491            and then Is_Packed (Base_Type (Etype (Prefix (Item))))
492            and then Base_Type (Etype (Item)) /= Base_Type (Formal_Typ)
493            and then Is_Written
494          then
495             declare
496                Temp : constant Entity_Id :=
497                         Make_Defining_Identifier
498                           (Loc, New_Internal_Name ('V'));
499                Decl : Node_Id;
500                Assn : Node_Id;
501
502             begin
503                Decl :=
504                  Make_Object_Declaration (Loc,
505                    Defining_Identifier => Temp,
506                    Object_Definition    =>
507                      New_Occurrence_Of (Formal_Typ, Loc));
508                Set_Etype (Temp, Formal_Typ);
509
510                Assn :=
511                  Make_Assignment_Statement (Loc,
512                    Name => New_Copy_Tree (Item),
513                    Expression =>
514                      Unchecked_Convert_To
515                        (Etype (Item), New_Occurrence_Of (Temp, Loc)));
516
517                Rewrite (Item, New_Occurrence_Of (Temp, Loc));
518                Insert_Actions (N,
519                  New_List (
520                    Decl,
521                    Make_Procedure_Call_Statement (Loc,
522                      Name => New_Occurrence_Of (Pname, Loc),
523                      Parameter_Associations => Exprs),
524                    Assn));
525
526                Rewrite (N, Make_Null_Statement (Loc));
527                return;
528             end;
529          end if;
530
531          --  For the class-wide dispatching cases, and for cases in which
532          --  the base type of the second argument matches the base type of
533          --  the corresponding formal parameter (that is to say the stream
534          --  operation is not inherited), we are all set, and can use the
535          --  argument unchanged.
536
537          --  For all other cases we do an unchecked conversion of the second
538          --  parameter to the type of the formal of the procedure we are
539          --  calling. This deals with the private type cases, and with going
540          --  to the root type as required in elementary type case.
541
542          if not Is_Class_Wide_Type (Entity (Pref))
543            and then not Is_Class_Wide_Type (Etype (Item))
544            and then Base_Type (Etype (Item)) /= Base_Type (Formal_Typ)
545          then
546             Rewrite (Item,
547               Unchecked_Convert_To (Formal_Typ, Relocate_Node (Item)));
548
549             --  For untagged derived types set Assignment_OK, to prevent
550             --  copies from being created when the unchecked conversion
551             --  is expanded (which would happen in Remove_Side_Effects
552             --  if Expand_N_Unchecked_Conversion were allowed to call
553             --  Force_Evaluation). The copy could violate Ada semantics
554             --  in cases such as an actual that is an out parameter.
555             --  Note that this approach is also used in exp_ch7 for calls
556             --  to controlled type operations to prevent problems with
557             --  actuals wrapped in unchecked conversions.
558
559             if Is_Untagged_Derivation (Etype (Expression (Item))) then
560                Set_Assignment_OK (Item);
561             end if;
562          end if;
563
564          --  And now rewrite the call
565
566          Rewrite (N,
567            Make_Procedure_Call_Statement (Loc,
568              Name => New_Occurrence_Of (Pname, Loc),
569              Parameter_Associations => Exprs));
570
571          Analyze (N);
572       end Rewrite_Stream_Proc_Call;
573
574    --  Start of processing for Expand_N_Attribute_Reference
575
576    begin
577       --  Do required validity checking, if enabled. Do not apply check to
578       --  output parameters of an Asm instruction, since the value of this
579       --  is not set till after the attribute has been elaborated.
580
581       if Validity_Checks_On and then Validity_Check_Operands
582         and then Id /= Attribute_Asm_Output
583       then
584          declare
585             Expr : Node_Id;
586          begin
587             Expr := First (Expressions (N));
588             while Present (Expr) loop
589                Ensure_Valid (Expr);
590                Next (Expr);
591             end loop;
592          end;
593       end if;
594
595       --  Remaining processing depends on specific attribute
596
597       case Id is
598
599       ------------
600       -- Access --
601       ------------
602
603       when Attribute_Access              |
604            Attribute_Unchecked_Access    |
605            Attribute_Unrestricted_Access =>
606
607          if Is_Access_Protected_Subprogram_Type (Btyp) then
608             Expand_Access_To_Protected_Op (N, Pref, Typ);
609
610          --  If the prefix is a type name, this is a reference to the current
611          --  instance of the type, within its initialization procedure.
612
613          elsif Is_Entity_Name (Pref)
614            and then Is_Type (Entity (Pref))
615          then
616             declare
617                Par    : Node_Id;
618                Formal : Entity_Id;
619
620             begin
621                --  If the current instance name denotes a task type, then the
622                --  access attribute is rewritten to be the name of the "_task"
623                --  parameter associated with the task type's task procedure.
624                --  An unchecked conversion is applied to ensure a type match in
625                --  cases of expander-generated calls (e.g., init procs).
626
627                if Is_Task_Type (Entity (Pref)) then
628                   Formal :=
629                     First_Entity (Get_Task_Body_Procedure (Entity (Pref)));
630                   while Present (Formal) loop
631                      exit when Chars (Formal) = Name_uTask;
632                      Next_Entity (Formal);
633                   end loop;
634
635                   pragma Assert (Present (Formal));
636
637                   Rewrite (N,
638                     Unchecked_Convert_To
639                       (Typ, New_Occurrence_Of (Formal, Loc)));
640                   Set_Etype (N, Typ);
641
642                   return;
643
644                --  The expression must appear in a default expression, (which
645                --  in the initialization procedure is the right-hand side of an
646                --  assignment), and not in a discriminant constraint.
647
648                else
649                   Par := Parent (N);
650                   while Present (Par) loop
651                      exit when Nkind (Par) = N_Assignment_Statement;
652
653                      if Nkind (Par) = N_Component_Declaration then
654                         return;
655                      end if;
656
657                      Par := Parent (Par);
658                   end loop;
659
660                   if Present (Par) then
661                      Rewrite (N,
662                        Make_Attribute_Reference (Loc,
663                          Prefix => Make_Identifier (Loc, Name_uInit),
664                          Attribute_Name  => Attribute_Name (N)));
665
666                      Analyze_And_Resolve (N, Typ);
667                   end if;
668
669                   return;
670                end if;
671             end;
672
673          --  The following handles cases involving interfaces and when the
674          --  prefix of an access attribute is an explicit dereference. In the
675          --  case where the access attribute is specifically Attribute_Access,
676          --  we only do this when the context type is E_General_Access_Type,
677          --  and not for anonymous access types. It seems that this code should
678          --  be used for anonymous contexts as well, but that causes various
679          --  regressions, such as on prefix-notation calls to dispatching
680          --  operations and back-end errors on access type conversions. ???
681
682          elsif Id /= Attribute_Access
683            or else Ekind (Btyp) = E_General_Access_Type
684          then
685             declare
686                Ref_Object : constant Node_Id := Get_Referenced_Object (Pref);
687                Parm_Ent   : Entity_Id;
688                Conversion : Node_Id;
689
690             begin
691                --  If the prefix of an Access attribute is a dereference of an
692                --  access parameter (or a renaming of such a dereference) and
693                --  the context is a general access type (but not an anonymous
694                --  access type), then rewrite the attribute as a conversion of
695                --  the access parameter to the context access type. This will
696                --  result in an accessibility check being performed, if needed.
697
698                --    (X.all'Access => Acc_Type (X))
699
700                --  Note: Limit the expansion of an attribute applied to a
701                --  dereference of an access parameter so that it's only done
702                --  for 'Access. This fixes a problem with 'Unrestricted_Access
703                --  that leads to errors in the case where the attribute
704                --  type is access-to-variable and the access parameter is
705                --  access-to-constant. The conversion is only done to get
706                --  accessibility checks, so it makes sense to limit it to
707                --  'Access (and consistent with existing comment).
708
709                if Nkind (Ref_Object) = N_Explicit_Dereference
710                  and then Is_Entity_Name (Prefix (Ref_Object))
711                  and then Id = Attribute_Access
712                then
713                   Parm_Ent := Entity (Prefix (Ref_Object));
714
715                   if Ekind (Parm_Ent) in Formal_Kind
716                     and then Ekind (Etype (Parm_Ent)) = E_Anonymous_Access_Type
717                     and then Present (Extra_Accessibility (Parm_Ent))
718                   then
719                      Conversion :=
720                        Convert_To (Typ, New_Copy_Tree (Prefix (Ref_Object)));
721
722                      Rewrite (N, Conversion);
723                      Analyze_And_Resolve (N, Typ);
724
725                      return;
726                   end if;
727                end if;
728
729                --  Ada 2005 (AI-251): If the designated type is an interface,
730                --  then rewrite the referenced object as a conversion, to force
731                --  the displacement of the pointer to the secondary dispatch
732                --  table.
733
734                if Is_Interface (Directly_Designated_Type (Btyp)) then
735
736                   --  When the object is an explicit dereference, just convert
737                   --  the dereference's prefix.
738
739                   if Nkind (Ref_Object) = N_Explicit_Dereference then
740                      Conversion :=
741                        Convert_To (Typ, New_Copy_Tree (Prefix (Ref_Object)));
742
743                   --  It seems rather bizarre that we generate a conversion of
744                   --  a tagged object to an access type, since such conversions
745                   --  are not normally permitted, but Expand_N_Type_Conversion
746                   --  (actually Expand_Interface_Conversion) is designed to
747                   --  handle them in the interface case. Do we really want to
748                   --  create such odd conversions???
749
750                   else
751                      Conversion :=
752                        Convert_To (Typ, New_Copy_Tree (Ref_Object));
753                   end if;
754
755                   Rewrite (N, Conversion);
756                   Analyze_And_Resolve (N, Typ);
757                end if;
758             end;
759          end if;
760
761       --------------
762       -- Adjacent --
763       --------------
764
765       --  Transforms 'Adjacent into a call to the floating-point attribute
766       --  function Adjacent in Fat_xxx (where xxx is the root type)
767
768       when Attribute_Adjacent =>
769          Expand_Fpt_Attribute_RR (N);
770
771       -------------
772       -- Address --
773       -------------
774
775       when Attribute_Address => Address : declare
776          Task_Proc : Entity_Id;
777
778       begin
779          --  If the prefix is a task or a task type, the useful address is that
780          --  of the procedure for the task body, i.e. the actual program unit.
781          --  We replace the original entity with that of the procedure.
782
783          if Is_Entity_Name (Pref)
784            and then Is_Task_Type (Entity (Pref))
785          then
786             Task_Proc := Next_Entity (Root_Type (Etype (Pref)));
787
788             while Present (Task_Proc) loop
789                exit when Ekind (Task_Proc) = E_Procedure
790                  and then Etype (First_Formal (Task_Proc)) =
791                                   Corresponding_Record_Type (Etype (Pref));
792                Next_Entity (Task_Proc);
793             end loop;
794
795             if Present (Task_Proc) then
796                Set_Entity (Pref, Task_Proc);
797                Set_Etype  (Pref, Etype (Task_Proc));
798             end if;
799
800          --  Similarly, the address of a protected operation is the address
801          --  of the corresponding protected body, regardless of the protected
802          --  object from which it is selected.
803
804          elsif Nkind (Pref) = N_Selected_Component
805            and then Is_Subprogram (Entity (Selector_Name (Pref)))
806            and then Is_Protected_Type (Scope (Entity (Selector_Name (Pref))))
807          then
808             Rewrite (Pref,
809               New_Occurrence_Of (
810                 External_Subprogram (Entity (Selector_Name (Pref))), Loc));
811
812          elsif Nkind (Pref) = N_Explicit_Dereference
813            and then Ekind (Etype (Pref)) = E_Subprogram_Type
814            and then Convention (Etype (Pref)) = Convention_Protected
815          then
816             --  The prefix is be a dereference of an access_to_protected_
817             --  subprogram. The desired address is the second component of
818             --  the record that represents the access.
819
820             declare
821                Addr : constant Entity_Id := Etype (N);
822                Ptr  : constant Node_Id   := Prefix (Pref);
823                T    : constant Entity_Id :=
824                         Equivalent_Type (Base_Type (Etype (Ptr)));
825
826             begin
827                Rewrite (N,
828                  Unchecked_Convert_To (Addr,
829                    Make_Selected_Component (Loc,
830                      Prefix => Unchecked_Convert_To (T, Ptr),
831                      Selector_Name => New_Occurrence_Of (
832                        Next_Entity (First_Entity (T)), Loc))));
833
834                Analyze_And_Resolve (N, Addr);
835             end;
836
837          --  Ada 2005 (AI-251): Class-wide interface objects are always
838          --  "displaced" to reference the tag associated with the interface
839          --  type. In order to obtain the real address of such objects we
840          --  generate a call to a run-time subprogram that returns the base
841          --  address of the object.
842
843          elsif Is_Class_Wide_Type (Etype (Pref))
844            and then Is_Interface (Etype (Pref))
845            and then not (Nkind (Pref) in N_Has_Entity
846                           and then Is_Subprogram (Entity (Pref)))
847          then
848             Rewrite (N,
849               Make_Function_Call (Loc,
850                 Name => New_Reference_To (RTE (RE_Base_Address), Loc),
851                 Parameter_Associations => New_List (
852                   Relocate_Node (N))));
853             Analyze (N);
854             return;
855          end if;
856
857          --  Deal with packed array reference, other cases are handled by gigi
858
859          if Involves_Packed_Array_Reference (Pref) then
860             Expand_Packed_Address_Reference (N);
861          end if;
862       end Address;
863
864       ---------------
865       -- Alignment --
866       ---------------
867
868       when Attribute_Alignment => Alignment : declare
869          Ptyp     : constant Entity_Id := Etype (Pref);
870          New_Node : Node_Id;
871
872       begin
873          --  For class-wide types, X'Class'Alignment is transformed into a
874          --  direct reference to the Alignment of the class type, so that the
875          --  back end does not have to deal with the X'Class'Alignment
876          --  reference.
877
878          if Is_Entity_Name (Pref)
879            and then Is_Class_Wide_Type (Entity (Pref))
880          then
881             Rewrite (Prefix (N), New_Occurrence_Of (Entity (Pref), Loc));
882             return;
883
884          --  For x'Alignment applied to an object of a class wide type,
885          --  transform X'Alignment into a call to the predefined primitive
886          --  operation _Alignment applied to X.
887
888          elsif Is_Class_Wide_Type (Ptyp) then
889
890             --  No need to do anything else compiling under restriction
891             --  No_Dispatching_Calls. During the semantic analysis we
892             --  already notified such violation.
893
894             if Restriction_Active (No_Dispatching_Calls) then
895                return;
896             end if;
897
898             New_Node :=
899               Make_Function_Call (Loc,
900                 Name => New_Reference_To
901                   (Find_Prim_Op (Ptyp, Name_uAlignment), Loc),
902                 Parameter_Associations => New_List (Pref));
903
904             if Typ /= Standard_Integer then
905
906                --  The context is a specific integer type with which the
907                --  original attribute was compatible. The function has a
908                --  specific type as well, so to preserve the compatibility
909                --  we must convert explicitly.
910
911                New_Node := Convert_To (Typ, New_Node);
912             end if;
913
914             Rewrite (N, New_Node);
915             Analyze_And_Resolve (N, Typ);
916             return;
917
918          --  For all other cases, we just have to deal with the case of
919          --  the fact that the result can be universal.
920
921          else
922             Apply_Universal_Integer_Attribute_Checks (N);
923          end if;
924       end Alignment;
925
926       ---------------
927       -- AST_Entry --
928       ---------------
929
930       when Attribute_AST_Entry => AST_Entry : declare
931          Ttyp : Entity_Id;
932          T_Id : Node_Id;
933          Eent : Entity_Id;
934
935          Entry_Ref : Node_Id;
936          --  The reference to the entry or entry family
937
938          Index : Node_Id;
939          --  The index expression for an entry family reference, or
940          --  the Empty if Entry_Ref references a simple entry.
941
942       begin
943          if Nkind (Pref) = N_Indexed_Component then
944             Entry_Ref := Prefix (Pref);
945             Index := First (Expressions (Pref));
946          else
947             Entry_Ref := Pref;
948             Index := Empty;
949          end if;
950
951          --  Get expression for Task_Id and the entry entity
952
953          if Nkind (Entry_Ref) = N_Selected_Component then
954             T_Id :=
955               Make_Attribute_Reference (Loc,
956                 Attribute_Name => Name_Identity,
957                 Prefix         => Prefix (Entry_Ref));
958
959             Ttyp := Etype (Prefix (Entry_Ref));
960             Eent := Entity (Selector_Name (Entry_Ref));
961
962          else
963             T_Id :=
964               Make_Function_Call (Loc,
965                 Name => New_Occurrence_Of (RTE (RE_Current_Task), Loc));
966
967             Eent  := Entity (Entry_Ref);
968
969             --  We have to find the enclosing task to get the task type
970             --  There must be one, since we already validated this earlier
971
972             Ttyp := Current_Scope;
973             while not Is_Task_Type (Ttyp) loop
974                Ttyp := Scope (Ttyp);
975             end loop;
976          end if;
977
978          --  Now rewrite the attribute with a call to Create_AST_Handler
979
980          Rewrite (N,
981            Make_Function_Call (Loc,
982              Name => New_Occurrence_Of (RTE (RE_Create_AST_Handler), Loc),
983              Parameter_Associations => New_List (
984                T_Id,
985                Entry_Index_Expression (Loc, Eent, Index, Ttyp))));
986
987          Analyze_And_Resolve (N, RTE (RE_AST_Handler));
988       end AST_Entry;
989
990       ------------------
991       -- Bit_Position --
992       ------------------
993
994       --  We compute this if a component clause was present, otherwise
995       --  we leave the computation up to Gigi, since we don't know what
996       --  layout will be chosen.
997
998       --  Note that the attribute can apply to a naked record component
999       --  in generated code (i.e. the prefix is an identifier that
1000       --  references the component or discriminant entity).
1001
1002       when Attribute_Bit_Position => Bit_Position :
1003       declare
1004          CE : Entity_Id;
1005
1006       begin
1007          if Nkind (Pref) = N_Identifier then
1008             CE := Entity (Pref);
1009          else
1010             CE := Entity (Selector_Name (Pref));
1011          end if;
1012
1013          if Known_Static_Component_Bit_Offset (CE) then
1014             Rewrite (N,
1015               Make_Integer_Literal (Loc,
1016                 Intval => Component_Bit_Offset (CE)));
1017             Analyze_And_Resolve (N, Typ);
1018
1019          else
1020             Apply_Universal_Integer_Attribute_Checks (N);
1021          end if;
1022       end Bit_Position;
1023
1024       ------------------
1025       -- Body_Version --
1026       ------------------
1027
1028       --  A reference to P'Body_Version or P'Version is expanded to
1029
1030       --     Vnn : Unsigned;
1031       --     pragma Import (C, Vnn, "uuuuT";
1032       --     ...
1033       --     Get_Version_String (Vnn)
1034
1035       --  where uuuu is the unit name (dots replaced by double underscore)
1036       --  and T is B for the cases of Body_Version, or Version applied to a
1037       --  subprogram acting as its own spec, and S for Version applied to a
1038       --  subprogram spec or package. This sequence of code references the
1039       --  the unsigned constant created in the main program by the binder.
1040
1041       --  A special exception occurs for Standard, where the string
1042       --  returned is a copy of the library string in gnatvsn.ads.
1043
1044       when Attribute_Body_Version | Attribute_Version => Version : declare
1045          E    : constant Entity_Id :=
1046                   Make_Defining_Identifier (Loc, New_Internal_Name ('V'));
1047          Pent : Entity_Id;
1048          S    : String_Id;
1049
1050       begin
1051          --  If not library unit, get to containing library unit
1052
1053          Pent := Entity (Pref);
1054          while Pent /= Standard_Standard
1055            and then Scope (Pent) /= Standard_Standard
1056            and then not Is_Child_Unit (Pent)
1057          loop
1058             Pent := Scope (Pent);
1059          end loop;
1060
1061          --  Special case Standard and Standard.ASCII
1062
1063          if Pent = Standard_Standard or else Pent = Standard_ASCII then
1064             Rewrite (N,
1065               Make_String_Literal (Loc,
1066                 Strval => Verbose_Library_Version));
1067
1068          --  All other cases
1069
1070          else
1071             --  Build required string constant
1072
1073             Get_Name_String (Get_Unit_Name (Pent));
1074
1075             Start_String;
1076             for J in 1 .. Name_Len - 2 loop
1077                if Name_Buffer (J) = '.' then
1078                   Store_String_Chars ("__");
1079                else
1080                   Store_String_Char (Get_Char_Code (Name_Buffer (J)));
1081                end if;
1082             end loop;
1083
1084             --  Case of subprogram acting as its own spec, always use body
1085
1086             if Nkind (Declaration_Node (Pent)) in N_Subprogram_Specification
1087               and then Nkind (Parent (Declaration_Node (Pent))) =
1088                                                           N_Subprogram_Body
1089               and then Acts_As_Spec (Parent (Declaration_Node (Pent)))
1090             then
1091                Store_String_Chars ("B");
1092
1093             --  Case of no body present, always use spec
1094
1095             elsif not Unit_Requires_Body (Pent) then
1096                Store_String_Chars ("S");
1097
1098             --  Otherwise use B for Body_Version, S for spec
1099
1100             elsif Id = Attribute_Body_Version then
1101                Store_String_Chars ("B");
1102             else
1103                Store_String_Chars ("S");
1104             end if;
1105
1106             S := End_String;
1107             Lib.Version_Referenced (S);
1108
1109             --  Insert the object declaration
1110
1111             Insert_Actions (N, New_List (
1112               Make_Object_Declaration (Loc,
1113                 Defining_Identifier => E,
1114                 Object_Definition   =>
1115                   New_Occurrence_Of (RTE (RE_Unsigned), Loc))));
1116
1117             --  Set entity as imported with correct external name
1118
1119             Set_Is_Imported (E);
1120             Set_Interface_Name (E, Make_String_Literal (Loc, S));
1121
1122             --  Set entity as internal to ensure proper Sprint output of its
1123             --  implicit importation.
1124
1125             Set_Is_Internal (E);
1126
1127             --  And now rewrite original reference
1128
1129             Rewrite (N,
1130               Make_Function_Call (Loc,
1131                 Name => New_Reference_To (RTE (RE_Get_Version_String), Loc),
1132                 Parameter_Associations => New_List (
1133                   New_Occurrence_Of (E, Loc))));
1134          end if;
1135
1136          Analyze_And_Resolve (N, RTE (RE_Version_String));
1137       end Version;
1138
1139       -------------
1140       -- Ceiling --
1141       -------------
1142
1143       --  Transforms 'Ceiling into a call to the floating-point attribute
1144       --  function Ceiling in Fat_xxx (where xxx is the root type)
1145
1146       when Attribute_Ceiling =>
1147          Expand_Fpt_Attribute_R (N);
1148
1149       --------------
1150       -- Callable --
1151       --------------
1152
1153       --  Transforms 'Callable attribute into a call to the Callable function
1154
1155       when Attribute_Callable => Callable :
1156       begin
1157          --  We have an object of a task interface class-wide type as a prefix
1158          --  to Callable. Generate:
1159
1160          --    callable (Task_Id (Pref._disp_get_task_id));
1161
1162          if Ada_Version >= Ada_05
1163            and then Ekind (Etype (Pref)) = E_Class_Wide_Type
1164            and then Is_Interface (Etype (Pref))
1165            and then Is_Task_Interface (Etype (Pref))
1166          then
1167             Rewrite (N,
1168               Make_Function_Call (Loc,
1169                 Name =>
1170                   New_Reference_To (RTE (RE_Callable), Loc),
1171                 Parameter_Associations => New_List (
1172                   Make_Unchecked_Type_Conversion (Loc,
1173                     Subtype_Mark =>
1174                       New_Reference_To (RTE (RO_ST_Task_Id), Loc),
1175                     Expression =>
1176                       Make_Selected_Component (Loc,
1177                         Prefix =>
1178                           New_Copy_Tree (Pref),
1179                         Selector_Name =>
1180                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id))))));
1181
1182          else
1183             Rewrite (N,
1184               Build_Call_With_Task (Pref, RTE (RE_Callable)));
1185          end if;
1186
1187          Analyze_And_Resolve (N, Standard_Boolean);
1188       end Callable;
1189
1190       ------------
1191       -- Caller --
1192       ------------
1193
1194       --  Transforms 'Caller attribute into a call to either the
1195       --  Task_Entry_Caller or the Protected_Entry_Caller function.
1196
1197       when Attribute_Caller => Caller : declare
1198          Id_Kind    : constant Entity_Id := RTE (RO_AT_Task_Id);
1199          Ent        : constant Entity_Id := Entity (Pref);
1200          Conctype   : constant Entity_Id := Scope (Ent);
1201          Nest_Depth : Integer := 0;
1202          Name       : Node_Id;
1203          S          : Entity_Id;
1204
1205       begin
1206          --  Protected case
1207
1208          if Is_Protected_Type (Conctype) then
1209             if Abort_Allowed
1210               or else Restriction_Active (No_Entry_Queue) = False
1211               or else Number_Entries (Conctype) > 1
1212             then
1213                Name :=
1214                  New_Reference_To
1215                    (RTE (RE_Protected_Entry_Caller), Loc);
1216             else
1217                Name :=
1218                  New_Reference_To
1219                    (RTE (RE_Protected_Single_Entry_Caller), Loc);
1220             end if;
1221
1222             Rewrite (N,
1223               Unchecked_Convert_To (Id_Kind,
1224                 Make_Function_Call (Loc,
1225                   Name => Name,
1226                   Parameter_Associations => New_List
1227                     (New_Reference_To (
1228                       Object_Ref
1229                         (Corresponding_Body (Parent (Conctype))), Loc)))));
1230
1231          --  Task case
1232
1233          else
1234             --  Determine the nesting depth of the E'Caller attribute, that
1235             --  is, how many accept statements are nested within the accept
1236             --  statement for E at the point of E'Caller. The runtime uses
1237             --  this depth to find the specified entry call.
1238
1239             for J in reverse 0 .. Scope_Stack.Last loop
1240                S := Scope_Stack.Table (J).Entity;
1241
1242                --  We should not reach the scope of the entry, as it should
1243                --  already have been checked in Sem_Attr that this attribute
1244                --  reference is within a matching accept statement.
1245
1246                pragma Assert (S /= Conctype);
1247
1248                if S = Ent then
1249                   exit;
1250
1251                elsif Is_Entry (S) then
1252                   Nest_Depth := Nest_Depth + 1;
1253                end if;
1254             end loop;
1255
1256             Rewrite (N,
1257               Unchecked_Convert_To (Id_Kind,
1258                 Make_Function_Call (Loc,
1259                   Name => New_Reference_To (
1260                     RTE (RE_Task_Entry_Caller), Loc),
1261                   Parameter_Associations => New_List (
1262                     Make_Integer_Literal (Loc,
1263                       Intval => Int (Nest_Depth))))));
1264          end if;
1265
1266          Analyze_And_Resolve (N, Id_Kind);
1267       end Caller;
1268
1269       -------------
1270       -- Compose --
1271       -------------
1272
1273       --  Transforms 'Compose into a call to the floating-point attribute
1274       --  function Compose in Fat_xxx (where xxx is the root type)
1275
1276       --  Note: we strictly should have special code here to deal with the
1277       --  case of absurdly negative arguments (less than Integer'First)
1278       --  which will return a (signed) zero value, but it hardly seems
1279       --  worth the effort. Absurdly large positive arguments will raise
1280       --  constraint error which is fine.
1281
1282       when Attribute_Compose =>
1283          Expand_Fpt_Attribute_RI (N);
1284
1285       -----------------
1286       -- Constrained --
1287       -----------------
1288
1289       when Attribute_Constrained => Constrained : declare
1290          Formal_Ent : constant Entity_Id := Param_Entity (Pref);
1291          Typ        : constant Entity_Id := Etype (Pref);
1292
1293          function Is_Constrained_Aliased_View (Obj : Node_Id) return Boolean;
1294          --  Ada 2005 (AI-363): Returns True if the object name Obj denotes a
1295          --  view of an aliased object whose subtype is constrained.
1296
1297          ---------------------------------
1298          -- Is_Constrained_Aliased_View --
1299          ---------------------------------
1300
1301          function Is_Constrained_Aliased_View (Obj : Node_Id) return Boolean is
1302             E : Entity_Id;
1303
1304          begin
1305             if Is_Entity_Name (Obj) then
1306                E := Entity (Obj);
1307
1308                if Present (Renamed_Object (E)) then
1309                   return Is_Constrained_Aliased_View (Renamed_Object (E));
1310
1311                else
1312                   return Is_Aliased (E) and then Is_Constrained (Etype (E));
1313                end if;
1314
1315             else
1316                return Is_Aliased_View (Obj)
1317                         and then
1318                       (Is_Constrained (Etype (Obj))
1319                          or else (Nkind (Obj) = N_Explicit_Dereference
1320                                     and then
1321                                       not Has_Constrained_Partial_View
1322                                             (Base_Type (Etype (Obj)))));
1323             end if;
1324          end Is_Constrained_Aliased_View;
1325
1326       --  Start of processing for Constrained
1327
1328       begin
1329          --  Reference to a parameter where the value is passed as an extra
1330          --  actual, corresponding to the extra formal referenced by the
1331          --  Extra_Constrained field of the corresponding formal. If this
1332          --  is an entry in-parameter, it is replaced by a constant renaming
1333          --  for which Extra_Constrained is never created.
1334
1335          if Present (Formal_Ent)
1336            and then Ekind (Formal_Ent) /= E_Constant
1337            and then Present (Extra_Constrained (Formal_Ent))
1338          then
1339             Rewrite (N,
1340               New_Occurrence_Of
1341                 (Extra_Constrained (Formal_Ent), Sloc (N)));
1342
1343          --  For variables with a Extra_Constrained field, we use the
1344          --  corresponding entity.
1345
1346          elsif Nkind (Pref) = N_Identifier
1347            and then Ekind (Entity (Pref)) = E_Variable
1348            and then Present (Extra_Constrained (Entity (Pref)))
1349          then
1350             Rewrite (N,
1351               New_Occurrence_Of
1352                 (Extra_Constrained (Entity (Pref)), Sloc (N)));
1353
1354          --  For all other entity names, we can tell at compile time
1355
1356          elsif Is_Entity_Name (Pref) then
1357             declare
1358                Ent : constant Entity_Id   := Entity (Pref);
1359                Res : Boolean;
1360
1361             begin
1362                --  (RM J.4) obsolescent cases
1363
1364                if Is_Type (Ent) then
1365
1366                   --  Private type
1367
1368                   if Is_Private_Type (Ent) then
1369                      Res := not Has_Discriminants (Ent)
1370                               or else Is_Constrained (Ent);
1371
1372                   --  It not a private type, must be a generic actual type
1373                   --  that corresponded to a private type. We know that this
1374                   --  correspondence holds, since otherwise the reference
1375                   --  within the generic template would have been illegal.
1376
1377                   else
1378                      if Is_Composite_Type (Underlying_Type (Ent)) then
1379                         Res := Is_Constrained (Ent);
1380                      else
1381                         Res := True;
1382                      end if;
1383                   end if;
1384
1385                --  If the prefix is not a variable or is aliased, then
1386                --  definitely true; if it's a formal parameter without
1387                --  an associated extra formal, then treat it as constrained.
1388
1389                --  Ada 2005 (AI-363): An aliased prefix must be known to be
1390                --  constrained in order to set the attribute to True.
1391
1392                elsif not Is_Variable (Pref)
1393                  or else Present (Formal_Ent)
1394                  or else (Ada_Version < Ada_05
1395                             and then Is_Aliased_View (Pref))
1396                  or else (Ada_Version >= Ada_05
1397                             and then Is_Constrained_Aliased_View (Pref))
1398                then
1399                   Res := True;
1400
1401                --  Variable case, just look at type to see if it is
1402                --  constrained. Note that the one case where this is
1403                --  not accurate (the procedure formal case), has been
1404                --  handled above.
1405
1406                --  We use the Underlying_Type here (and below) in case the
1407                --  type is private without discriminants, but the full type
1408                --  has discriminants. This case is illegal, but we generate it
1409                --  internally for passing to the Extra_Constrained parameter.
1410
1411                else
1412                   Res := Is_Constrained (Underlying_Type (Etype (Ent)));
1413                end if;
1414
1415                Rewrite (N,
1416                  New_Reference_To (Boolean_Literals (Res), Loc));
1417             end;
1418
1419          --  Prefix is not an entity name. These are also cases where
1420          --  we can always tell at compile time by looking at the form
1421          --  and type of the prefix. If an explicit dereference of an
1422          --  object with constrained partial view, this is unconstrained
1423          --  (Ada 2005 AI-363).
1424
1425          else
1426             Rewrite (N,
1427               New_Reference_To (
1428                 Boolean_Literals (
1429                   not Is_Variable (Pref)
1430                     or else
1431                      (Nkind (Pref) = N_Explicit_Dereference
1432                         and then
1433                           not Has_Constrained_Partial_View (Base_Type (Typ)))
1434                     or else Is_Constrained (Underlying_Type (Typ))),
1435                 Loc));
1436          end if;
1437
1438          Analyze_And_Resolve (N, Standard_Boolean);
1439       end Constrained;
1440
1441       ---------------
1442       -- Copy_Sign --
1443       ---------------
1444
1445       --  Transforms 'Copy_Sign into a call to the floating-point attribute
1446       --  function Copy_Sign in Fat_xxx (where xxx is the root type)
1447
1448       when Attribute_Copy_Sign =>
1449          Expand_Fpt_Attribute_RR (N);
1450
1451       -----------
1452       -- Count --
1453       -----------
1454
1455       --  Transforms 'Count attribute into a call to the Count function
1456
1457       when Attribute_Count => Count :
1458       declare
1459          Entnam  : Node_Id;
1460          Index   : Node_Id;
1461          Name    : Node_Id;
1462          Call    : Node_Id;
1463          Conctyp : Entity_Id;
1464
1465       begin
1466          --  If the prefix is a member of an entry family, retrieve both
1467          --  entry name and index. For a simple entry there is no index.
1468
1469          if Nkind (Pref) = N_Indexed_Component then
1470             Entnam := Prefix (Pref);
1471             Index := First (Expressions (Pref));
1472          else
1473             Entnam := Pref;
1474             Index := Empty;
1475          end if;
1476
1477          --  Find the concurrent type in which this attribute is referenced
1478          --  (there had better be one).
1479
1480          Conctyp := Current_Scope;
1481          while not Is_Concurrent_Type (Conctyp) loop
1482             Conctyp := Scope (Conctyp);
1483          end loop;
1484
1485          --  Protected case
1486
1487          if Is_Protected_Type (Conctyp) then
1488
1489             if Abort_Allowed
1490               or else Restriction_Active (No_Entry_Queue) = False
1491               or else Number_Entries (Conctyp) > 1
1492             then
1493                Name := New_Reference_To (RTE (RE_Protected_Count), Loc);
1494
1495                Call :=
1496                  Make_Function_Call (Loc,
1497                    Name => Name,
1498                    Parameter_Associations => New_List (
1499                      New_Reference_To (
1500                        Object_Ref (
1501                          Corresponding_Body (Parent (Conctyp))), Loc),
1502                      Entry_Index_Expression (
1503                        Loc, Entity (Entnam), Index, Scope (Entity (Entnam)))));
1504             else
1505                Name := New_Reference_To (RTE (RE_Protected_Count_Entry), Loc);
1506
1507                Call := Make_Function_Call (Loc,
1508                    Name => Name,
1509                    Parameter_Associations => New_List (
1510                      New_Reference_To (
1511                        Object_Ref (
1512                          Corresponding_Body (Parent (Conctyp))), Loc)));
1513             end if;
1514
1515          --  Task case
1516
1517          else
1518             Call :=
1519               Make_Function_Call (Loc,
1520                 Name => New_Reference_To (RTE (RE_Task_Count), Loc),
1521                 Parameter_Associations => New_List (
1522                   Entry_Index_Expression
1523                     (Loc, Entity (Entnam), Index, Scope (Entity (Entnam)))));
1524          end if;
1525
1526          --  The call returns type Natural but the context is universal integer
1527          --  so any integer type is allowed. The attribute was already resolved
1528          --  so its Etype is the required result type. If the base type of the
1529          --  context type is other than Standard.Integer we put in a conversion
1530          --  to the required type. This can be a normal typed conversion since
1531          --  both input and output types of the conversion are integer types
1532
1533          if Base_Type (Typ) /= Base_Type (Standard_Integer) then
1534             Rewrite (N, Convert_To (Typ, Call));
1535          else
1536             Rewrite (N, Call);
1537          end if;
1538
1539          Analyze_And_Resolve (N, Typ);
1540       end Count;
1541
1542       ---------------
1543       -- Elab_Body --
1544       ---------------
1545
1546       --  This processing is shared by Elab_Spec
1547
1548       --  What we do is to insert the following declarations
1549
1550       --     procedure tnn;
1551       --     pragma Import (C, enn, "name___elabb/s");
1552
1553       --  and then the Elab_Body/Spec attribute is replaced by a reference
1554       --  to this defining identifier.
1555
1556       when Attribute_Elab_Body |
1557            Attribute_Elab_Spec =>
1558
1559          Elab_Body : declare
1560             Ent  : constant Entity_Id :=
1561                      Make_Defining_Identifier (Loc,
1562                        New_Internal_Name ('E'));
1563             Str  : String_Id;
1564             Lang : Node_Id;
1565
1566             procedure Make_Elab_String (Nod : Node_Id);
1567             --  Given Nod, an identifier, or a selected component, put the
1568             --  image into the current string literal, with double underline
1569             --  between components.
1570
1571             ----------------------
1572             -- Make_Elab_String --
1573             ----------------------
1574
1575             procedure Make_Elab_String (Nod : Node_Id) is
1576             begin
1577                if Nkind (Nod) = N_Selected_Component then
1578                   Make_Elab_String (Prefix (Nod));
1579
1580                   case VM_Target is
1581                      when JVM_Target =>
1582                         Store_String_Char ('$');
1583                      when CLI_Target =>
1584                         Store_String_Char ('.');
1585                      when No_VM =>
1586                         Store_String_Char ('_');
1587                         Store_String_Char ('_');
1588                   end case;
1589
1590                   Get_Name_String (Chars (Selector_Name (Nod)));
1591
1592                else
1593                   pragma Assert (Nkind (Nod) = N_Identifier);
1594                   Get_Name_String (Chars (Nod));
1595                end if;
1596
1597                Store_String_Chars (Name_Buffer (1 .. Name_Len));
1598             end Make_Elab_String;
1599
1600          --  Start of processing for Elab_Body/Elab_Spec
1601
1602          begin
1603             --  First we need to prepare the string literal for the name of
1604             --  the elaboration routine to be referenced.
1605
1606             Start_String;
1607             Make_Elab_String (Pref);
1608
1609             if VM_Target = No_VM then
1610                Store_String_Chars ("___elab");
1611                Lang := Make_Identifier (Loc, Name_C);
1612             else
1613                Store_String_Chars ("._elab");
1614                Lang := Make_Identifier (Loc, Name_Ada);
1615             end if;
1616
1617             if Id = Attribute_Elab_Body then
1618                Store_String_Char ('b');
1619             else
1620                Store_String_Char ('s');
1621             end if;
1622
1623             Str := End_String;
1624
1625             Insert_Actions (N, New_List (
1626               Make_Subprogram_Declaration (Loc,
1627                 Specification =>
1628                   Make_Procedure_Specification (Loc,
1629                     Defining_Unit_Name => Ent)),
1630
1631               Make_Pragma (Loc,
1632                 Chars => Name_Import,
1633                 Pragma_Argument_Associations => New_List (
1634                   Make_Pragma_Argument_Association (Loc,
1635                     Expression => Lang),
1636
1637                   Make_Pragma_Argument_Association (Loc,
1638                     Expression =>
1639                       Make_Identifier (Loc, Chars (Ent))),
1640
1641                   Make_Pragma_Argument_Association (Loc,
1642                     Expression =>
1643                       Make_String_Literal (Loc, Str))))));
1644
1645             Set_Entity (N, Ent);
1646             Rewrite (N, New_Occurrence_Of (Ent, Loc));
1647          end Elab_Body;
1648
1649       ----------------
1650       -- Elaborated --
1651       ----------------
1652
1653       --  Elaborated is always True for preelaborated units, predefined
1654       --  units, pure units and units which have Elaborate_Body pragmas.
1655       --  These units have no elaboration entity.
1656
1657       --  Note: The Elaborated attribute is never passed through to Gigi
1658
1659       when Attribute_Elaborated => Elaborated : declare
1660          Ent : constant Entity_Id := Entity (Pref);
1661
1662       begin
1663          if Present (Elaboration_Entity (Ent)) then
1664             Rewrite (N,
1665               New_Occurrence_Of (Elaboration_Entity (Ent), Loc));
1666          else
1667             Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
1668          end if;
1669       end Elaborated;
1670
1671       --------------
1672       -- Enum_Rep --
1673       --------------
1674
1675       when Attribute_Enum_Rep => Enum_Rep :
1676       begin
1677          --  X'Enum_Rep (Y) expands to
1678
1679          --    target-type (Y)
1680
1681          --  This is simply a direct conversion from the enumeration type
1682          --  to the target integer type, which is treated by Gigi as a normal
1683          --  integer conversion, treating the enumeration type as an integer,
1684          --  which is exactly what we want! We set Conversion_OK to make sure
1685          --  that the analyzer does not complain about what otherwise might
1686          --  be an illegal conversion.
1687
1688          if Is_Non_Empty_List (Exprs) then
1689             Rewrite (N,
1690               OK_Convert_To (Typ, Relocate_Node (First (Exprs))));
1691
1692          --  X'Enum_Rep where X is an enumeration literal is replaced by
1693          --  the literal value.
1694
1695          elsif Ekind (Entity (Pref)) = E_Enumeration_Literal then
1696             Rewrite (N,
1697               Make_Integer_Literal (Loc, Enumeration_Rep (Entity (Pref))));
1698
1699          --  If this is a renaming of a literal, recover the representation
1700          --  of the original.
1701
1702          elsif Ekind (Entity (Pref)) = E_Constant
1703            and then Present (Renamed_Object (Entity (Pref)))
1704            and then
1705              Ekind (Entity (Renamed_Object (Entity (Pref))))
1706                = E_Enumeration_Literal
1707          then
1708             Rewrite (N,
1709               Make_Integer_Literal (Loc,
1710                 Enumeration_Rep (Entity (Renamed_Object (Entity (Pref))))));
1711
1712          --  X'Enum_Rep where X is an object does a direct unchecked conversion
1713          --  of the object value, as described for the type case above.
1714
1715          else
1716             Rewrite (N,
1717               OK_Convert_To (Typ, Relocate_Node (Pref)));
1718          end if;
1719
1720          Set_Etype (N, Typ);
1721          Analyze_And_Resolve (N, Typ);
1722
1723       end Enum_Rep;
1724
1725       --------------
1726       -- Exponent --
1727       --------------
1728
1729       --  Transforms 'Exponent into a call to the floating-point attribute
1730       --  function Exponent in Fat_xxx (where xxx is the root type)
1731
1732       when Attribute_Exponent =>
1733          Expand_Fpt_Attribute_R (N);
1734
1735       ------------------
1736       -- External_Tag --
1737       ------------------
1738
1739       --  transforme X'External_Tag into Ada.Tags.External_Tag (X'tag)
1740
1741       when Attribute_External_Tag => External_Tag :
1742       begin
1743          Rewrite (N,
1744            Make_Function_Call (Loc,
1745              Name => New_Reference_To (RTE (RE_External_Tag), Loc),
1746              Parameter_Associations => New_List (
1747                Make_Attribute_Reference (Loc,
1748                  Attribute_Name => Name_Tag,
1749                  Prefix => Prefix (N)))));
1750
1751          Analyze_And_Resolve (N, Standard_String);
1752       end External_Tag;
1753
1754       -----------
1755       -- First --
1756       -----------
1757
1758       when Attribute_First => declare
1759          Ptyp : constant Entity_Id := Etype (Pref);
1760
1761       begin
1762          --  If the prefix type is a constrained packed array type which
1763          --  already has a Packed_Array_Type representation defined, then
1764          --  replace this attribute with a direct reference to 'First of the
1765          --  appropriate index subtype (since otherwise Gigi will try to give
1766          --  us the value of 'First for this implementation type).
1767
1768          if Is_Constrained_Packed_Array (Ptyp) then
1769             Rewrite (N,
1770               Make_Attribute_Reference (Loc,
1771                 Attribute_Name => Name_First,
1772                 Prefix => New_Reference_To (Get_Index_Subtype (N), Loc)));
1773             Analyze_And_Resolve (N, Typ);
1774
1775          elsif Is_Access_Type (Ptyp) then
1776             Apply_Access_Check (N);
1777          end if;
1778       end;
1779
1780       ---------------
1781       -- First_Bit --
1782       ---------------
1783
1784       --  We compute this if a component clause was present, otherwise
1785       --  we leave the computation up to Gigi, since we don't know what
1786       --  layout will be chosen.
1787
1788       when Attribute_First_Bit => First_Bit :
1789       declare
1790          CE : constant Entity_Id := Entity (Selector_Name (Pref));
1791
1792       begin
1793          if Known_Static_Component_Bit_Offset (CE) then
1794             Rewrite (N,
1795               Make_Integer_Literal (Loc,
1796                 Component_Bit_Offset (CE) mod System_Storage_Unit));
1797
1798             Analyze_And_Resolve (N, Typ);
1799
1800          else
1801             Apply_Universal_Integer_Attribute_Checks (N);
1802          end if;
1803       end First_Bit;
1804
1805       -----------------
1806       -- Fixed_Value --
1807       -----------------
1808
1809       --  We transform:
1810
1811       --     fixtype'Fixed_Value (integer-value)
1812
1813       --  into
1814
1815       --     fixtype(integer-value)
1816
1817       --  we do all the required analysis of the conversion here, because
1818       --  we do not want this to go through the fixed-point conversion
1819       --  circuits. Note that gigi always treats fixed-point as equivalent
1820       --  to the corresponding integer type anyway.
1821
1822       when Attribute_Fixed_Value => Fixed_Value :
1823       begin
1824          Rewrite (N,
1825            Make_Type_Conversion (Loc,
1826              Subtype_Mark => New_Occurrence_Of (Entity (Pref), Loc),
1827              Expression   => Relocate_Node (First (Exprs))));
1828          Set_Etype (N, Entity (Pref));
1829          Set_Analyzed (N);
1830
1831       --  Note: it might appear that a properly analyzed unchecked conversion
1832       --  would be just fine here, but that's not the case, since the full
1833       --  range checks performed by the following call are critical!
1834
1835          Apply_Type_Conversion_Checks (N);
1836       end Fixed_Value;
1837
1838       -----------
1839       -- Floor --
1840       -----------
1841
1842       --  Transforms 'Floor into a call to the floating-point attribute
1843       --  function Floor in Fat_xxx (where xxx is the root type)
1844
1845       when Attribute_Floor =>
1846          Expand_Fpt_Attribute_R (N);
1847
1848       ----------
1849       -- Fore --
1850       ----------
1851
1852       --  For the fixed-point type Typ:
1853
1854       --    Typ'Fore
1855
1856       --  expands into
1857
1858       --    Result_Type (System.Fore (Universal_Real (Type'First)),
1859       --                              Universal_Real (Type'Last))
1860
1861       --  Note that we know that the type is a non-static subtype, or Fore
1862       --  would have itself been computed dynamically in Eval_Attribute.
1863
1864       when Attribute_Fore => Fore :
1865       declare
1866          Ptyp : constant Entity_Id := Etype (Pref);
1867
1868       begin
1869          Rewrite (N,
1870            Convert_To (Typ,
1871              Make_Function_Call (Loc,
1872                Name => New_Reference_To (RTE (RE_Fore), Loc),
1873
1874                Parameter_Associations => New_List (
1875                  Convert_To (Universal_Real,
1876                    Make_Attribute_Reference (Loc,
1877                      Prefix => New_Reference_To (Ptyp, Loc),
1878                      Attribute_Name => Name_First)),
1879
1880                  Convert_To (Universal_Real,
1881                    Make_Attribute_Reference (Loc,
1882                      Prefix => New_Reference_To (Ptyp, Loc),
1883                      Attribute_Name => Name_Last))))));
1884
1885          Analyze_And_Resolve (N, Typ);
1886       end Fore;
1887
1888       --------------
1889       -- Fraction --
1890       --------------
1891
1892       --  Transforms 'Fraction into a call to the floating-point attribute
1893       --  function Fraction in Fat_xxx (where xxx is the root type)
1894
1895       when Attribute_Fraction =>
1896          Expand_Fpt_Attribute_R (N);
1897
1898       --------------
1899       -- Identity --
1900       --------------
1901
1902       --  For an exception returns a reference to the exception data:
1903       --      Exception_Id!(Prefix'Reference)
1904
1905       --  For a task it returns a reference to the _task_id component of
1906       --  corresponding record:
1907
1908       --    taskV!(Prefix)._Task_Id, converted to the type Task_Id defined
1909
1910       --  in Ada.Task_Identification
1911
1912       when Attribute_Identity => Identity : declare
1913          Id_Kind : Entity_Id;
1914
1915       begin
1916          if Etype (Pref) = Standard_Exception_Type then
1917             Id_Kind := RTE (RE_Exception_Id);
1918
1919             if Present (Renamed_Object (Entity (Pref))) then
1920                Set_Entity (Pref, Renamed_Object (Entity (Pref)));
1921             end if;
1922
1923             Rewrite (N,
1924               Unchecked_Convert_To (Id_Kind, Make_Reference (Loc, Pref)));
1925          else
1926             Id_Kind := RTE (RO_AT_Task_Id);
1927
1928             Rewrite (N,
1929               Unchecked_Convert_To (Id_Kind, Concurrent_Ref (Pref)));
1930          end if;
1931
1932          Analyze_And_Resolve (N, Id_Kind);
1933       end Identity;
1934
1935       -----------
1936       -- Image --
1937       -----------
1938
1939       --  Image attribute is handled in separate unit Exp_Imgv
1940
1941       when Attribute_Image =>
1942          Exp_Imgv.Expand_Image_Attribute (N);
1943
1944       ---------
1945       -- Img --
1946       ---------
1947
1948       --  X'Img is expanded to typ'Image (X), where typ is the type of X
1949
1950       when Attribute_Img => Img :
1951       begin
1952          Rewrite (N,
1953            Make_Attribute_Reference (Loc,
1954              Prefix => New_Reference_To (Etype (Pref), Loc),
1955              Attribute_Name => Name_Image,
1956              Expressions => New_List (Relocate_Node (Pref))));
1957
1958          Analyze_And_Resolve (N, Standard_String);
1959       end Img;
1960
1961       -----------
1962       -- Input --
1963       -----------
1964
1965       when Attribute_Input => Input : declare
1966          P_Type : constant Entity_Id := Entity (Pref);
1967          B_Type : constant Entity_Id := Base_Type (P_Type);
1968          U_Type : constant Entity_Id := Underlying_Type (P_Type);
1969          Strm   : constant Node_Id   := First (Exprs);
1970          Fname  : Entity_Id;
1971          Decl   : Node_Id;
1972          Call   : Node_Id;
1973          Prag   : Node_Id;
1974          Arg2   : Node_Id;
1975          Rfunc  : Node_Id;
1976
1977          Cntrl  : Node_Id := Empty;
1978          --  Value for controlling argument in call. Always Empty except in
1979          --  the dispatching (class-wide type) case, where it is a reference
1980          --  to the dummy object initialized to the right internal tag.
1981
1982          procedure Freeze_Stream_Subprogram (F : Entity_Id);
1983          --  The expansion of the attribute reference may generate a call to
1984          --  a user-defined stream subprogram that is frozen by the call. This
1985          --  can lead to access-before-elaboration problem if the reference
1986          --  appears in an object declaration and the subprogram body has not
1987          --  been seen. The freezing of the subprogram requires special code
1988          --  because it appears in an expanded context where expressions do
1989          --  not freeze their constituents.
1990
1991          ------------------------------
1992          -- Freeze_Stream_Subprogram --
1993          ------------------------------
1994
1995          procedure Freeze_Stream_Subprogram (F : Entity_Id) is
1996             Decl : constant Node_Id := Unit_Declaration_Node (F);
1997             Bod  : Node_Id;
1998
1999          begin
2000             --  If this is user-defined subprogram, the corresponding
2001             --  stream function appears as a renaming-as-body, and the
2002             --  user subprogram must be retrieved by tree traversal.
2003
2004             if Present (Decl)
2005               and then Nkind (Decl) = N_Subprogram_Declaration
2006               and then Present (Corresponding_Body (Decl))
2007             then
2008                Bod := Corresponding_Body (Decl);
2009
2010                if Nkind (Unit_Declaration_Node (Bod)) =
2011                  N_Subprogram_Renaming_Declaration
2012                then
2013                   Set_Is_Frozen (Entity (Name (Unit_Declaration_Node (Bod))));
2014                end if;
2015             end if;
2016          end Freeze_Stream_Subprogram;
2017
2018       --  Start of processing for Input
2019
2020       begin
2021          --  If no underlying type, we have an error that will be diagnosed
2022          --  elsewhere, so here we just completely ignore the expansion.
2023
2024          if No (U_Type) then
2025             return;
2026          end if;
2027
2028          --  If there is a TSS for Input, just call it
2029
2030          Fname := Find_Stream_Subprogram (P_Type, TSS_Stream_Input);
2031
2032          if Present (Fname) then
2033             null;
2034
2035          else
2036             --  If there is a Stream_Convert pragma, use it, we rewrite
2037
2038             --     sourcetyp'Input (stream)
2039
2040             --  as
2041
2042             --     sourcetyp (streamread (strmtyp'Input (stream)));
2043
2044             --  where stmrearead is the given Read function that converts
2045             --  an argument of type strmtyp to type sourcetyp or a type
2046             --  from which it is derived. The extra conversion is required
2047             --  for the derived case.
2048
2049             Prag := Get_Stream_Convert_Pragma (P_Type);
2050
2051             if Present (Prag) then
2052                Arg2  := Next (First (Pragma_Argument_Associations (Prag)));
2053                Rfunc := Entity (Expression (Arg2));
2054
2055                Rewrite (N,
2056                  Convert_To (B_Type,
2057                    Make_Function_Call (Loc,
2058                      Name => New_Occurrence_Of (Rfunc, Loc),
2059                      Parameter_Associations => New_List (
2060                        Make_Attribute_Reference (Loc,
2061                          Prefix =>
2062                            New_Occurrence_Of
2063                              (Etype (First_Formal (Rfunc)), Loc),
2064                          Attribute_Name => Name_Input,
2065                          Expressions => Exprs)))));
2066
2067                Analyze_And_Resolve (N, B_Type);
2068                return;
2069
2070             --  Elementary types
2071
2072             elsif Is_Elementary_Type (U_Type) then
2073
2074                --  A special case arises if we have a defined _Read routine,
2075                --  since in this case we are required to call this routine.
2076
2077                if Present (TSS (Base_Type (U_Type), TSS_Stream_Read)) then
2078                   Build_Record_Or_Elementary_Input_Function
2079                     (Loc, U_Type, Decl, Fname);
2080                   Insert_Action (N, Decl);
2081
2082                --  For normal cases, we call the I_xxx routine directly
2083
2084                else
2085                   Rewrite (N, Build_Elementary_Input_Call (N));
2086                   Analyze_And_Resolve (N, P_Type);
2087                   return;
2088                end if;
2089
2090             --  Array type case
2091
2092             elsif Is_Array_Type (U_Type) then
2093                Build_Array_Input_Function (Loc, U_Type, Decl, Fname);
2094                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
2095
2096             --  Dispatching case with class-wide type
2097
2098             elsif Is_Class_Wide_Type (P_Type) then
2099
2100                --  No need to do anything else compiling under restriction
2101                --  No_Dispatching_Calls. During the semantic analysis we
2102                --  already notified such violation.
2103
2104                if Restriction_Active (No_Dispatching_Calls) then
2105                   return;
2106                end if;
2107
2108                declare
2109                   Rtyp : constant Entity_Id := Root_Type (P_Type);
2110                   Dnn  : Entity_Id;
2111                   Decl : Node_Id;
2112
2113                begin
2114                   --  Read the internal tag (RM 13.13.2(34)) and use it to
2115                   --  initialize a dummy tag object:
2116
2117                   --    Dnn : Ada.Tags.Tag
2118                   --           := Descendant_Tag (String'Input (Strm), P_Type);
2119
2120                   --  This dummy object is used only to provide a controlling
2121                   --  argument for the eventual _Input call. Descendant_Tag is
2122                   --  called rather than Internal_Tag to ensure that we have a
2123                   --  tag for a type that is descended from the prefix type and
2124                   --  declared at the same accessibility level (the exception
2125                   --  Tag_Error will be raised otherwise). The level check is
2126                   --  required for Ada 2005 because tagged types can be
2127                   --  extended in nested scopes (AI-344).
2128
2129                   Dnn :=
2130                     Make_Defining_Identifier (Loc,
2131                       Chars => New_Internal_Name ('D'));
2132
2133                   Decl :=
2134                     Make_Object_Declaration (Loc,
2135                       Defining_Identifier => Dnn,
2136                       Object_Definition =>
2137                         New_Occurrence_Of (RTE (RE_Tag), Loc),
2138                       Expression =>
2139                         Make_Function_Call (Loc,
2140                           Name =>
2141                             New_Occurrence_Of (RTE (RE_Descendant_Tag), Loc),
2142                           Parameter_Associations => New_List (
2143                             Make_Attribute_Reference (Loc,
2144                               Prefix =>
2145                                 New_Occurrence_Of (Standard_String, Loc),
2146                               Attribute_Name => Name_Input,
2147                               Expressions => New_List (
2148                                 Relocate_Node
2149                                   (Duplicate_Subexpr (Strm)))),
2150                             Make_Attribute_Reference (Loc,
2151                               Prefix => New_Reference_To (P_Type, Loc),
2152                               Attribute_Name => Name_Tag))));
2153
2154                   Insert_Action (N, Decl);
2155
2156                   --  Now we need to get the entity for the call, and construct
2157                   --  a function call node, where we preset a reference to Dnn
2158                   --  as the controlling argument (doing an unchecked convert
2159                   --  to the class-wide tagged type to make it look like a real
2160                   --  tagged object).
2161
2162                   Fname := Find_Prim_Op (Rtyp, TSS_Stream_Input);
2163                   Cntrl := Unchecked_Convert_To (P_Type,
2164                              New_Occurrence_Of (Dnn, Loc));
2165                   Set_Etype (Cntrl, P_Type);
2166                   Set_Parent (Cntrl, N);
2167                end;
2168
2169             --  For tagged types, use the primitive Input function
2170
2171             elsif Is_Tagged_Type (U_Type) then
2172                Fname := Find_Prim_Op (U_Type, TSS_Stream_Input);
2173
2174             --  All other record type cases, including protected records. The
2175             --  latter only arise for expander generated code for handling
2176             --  shared passive partition access.
2177
2178             else
2179                pragma Assert
2180                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
2181
2182                --  Ada 2005 (AI-216): Program_Error is raised when executing
2183                --  the default implementation of the Input attribute of an
2184                --  unchecked union type if the type lacks default discriminant
2185                --  values.
2186
2187                if Is_Unchecked_Union (Base_Type (U_Type))
2188                  and then No (Discriminant_Constraint (U_Type))
2189                then
2190                   Insert_Action (N,
2191                     Make_Raise_Program_Error (Loc,
2192                       Reason => PE_Unchecked_Union_Restriction));
2193
2194                   return;
2195                end if;
2196
2197                Build_Record_Or_Elementary_Input_Function
2198                  (Loc, Base_Type (U_Type), Decl, Fname);
2199                Insert_Action (N, Decl);
2200
2201                if Nkind (Parent (N)) = N_Object_Declaration
2202                  and then Is_Record_Type (U_Type)
2203                then
2204                   --  The stream function may contain calls to user-defined
2205                   --  Read procedures for individual components.
2206
2207                   declare
2208                      Comp : Entity_Id;
2209                      Func : Entity_Id;
2210
2211                   begin
2212                      Comp := First_Component (U_Type);
2213                      while Present (Comp) loop
2214                         Func :=
2215                           Find_Stream_Subprogram
2216                             (Etype (Comp), TSS_Stream_Read);
2217
2218                         if Present (Func) then
2219                            Freeze_Stream_Subprogram (Func);
2220                         end if;
2221
2222                         Next_Component (Comp);
2223                      end loop;
2224                   end;
2225                end if;
2226             end if;
2227          end if;
2228
2229          --  If we fall through, Fname is the function to be called. The result
2230          --  is obtained by calling the appropriate function, then converting
2231          --  the result. The conversion does a subtype check.
2232
2233          Call :=
2234            Make_Function_Call (Loc,
2235              Name => New_Occurrence_Of (Fname, Loc),
2236              Parameter_Associations => New_List (
2237                 Relocate_Node (Strm)));
2238
2239          Set_Controlling_Argument (Call, Cntrl);
2240          Rewrite (N, Unchecked_Convert_To (P_Type, Call));
2241          Analyze_And_Resolve (N, P_Type);
2242
2243          if Nkind (Parent (N)) = N_Object_Declaration then
2244             Freeze_Stream_Subprogram (Fname);
2245          end if;
2246       end Input;
2247
2248       -------------------
2249       -- Integer_Value --
2250       -------------------
2251
2252       --  We transform
2253
2254       --    inttype'Fixed_Value (fixed-value)
2255
2256       --  into
2257
2258       --    inttype(integer-value))
2259
2260       --  we do all the required analysis of the conversion here, because
2261       --  we do not want this to go through the fixed-point conversion
2262       --  circuits. Note that gigi always treats fixed-point as equivalent
2263       --  to the corresponding integer type anyway.
2264
2265       when Attribute_Integer_Value => Integer_Value :
2266       begin
2267          Rewrite (N,
2268            Make_Type_Conversion (Loc,
2269              Subtype_Mark => New_Occurrence_Of (Entity (Pref), Loc),
2270              Expression   => Relocate_Node (First (Exprs))));
2271          Set_Etype (N, Entity (Pref));
2272          Set_Analyzed (N);
2273
2274       --  Note: it might appear that a properly analyzed unchecked conversion
2275       --  would be just fine here, but that's not the case, since the full
2276       --  range checks performed by the following call are critical!
2277
2278          Apply_Type_Conversion_Checks (N);
2279       end Integer_Value;
2280
2281       ----------
2282       -- Last --
2283       ----------
2284
2285       when Attribute_Last => declare
2286          Ptyp : constant Entity_Id := Etype (Pref);
2287
2288       begin
2289          --  If the prefix type is a constrained packed array type which
2290          --  already has a Packed_Array_Type representation defined, then
2291          --  replace this attribute with a direct reference to 'Last of the
2292          --  appropriate index subtype (since otherwise Gigi will try to give
2293          --  us the value of 'Last for this implementation type).
2294
2295          if Is_Constrained_Packed_Array (Ptyp) then
2296             Rewrite (N,
2297               Make_Attribute_Reference (Loc,
2298                 Attribute_Name => Name_Last,
2299                 Prefix => New_Reference_To (Get_Index_Subtype (N), Loc)));
2300             Analyze_And_Resolve (N, Typ);
2301
2302          elsif Is_Access_Type (Ptyp) then
2303             Apply_Access_Check (N);
2304          end if;
2305       end;
2306
2307       --------------
2308       -- Last_Bit --
2309       --------------
2310
2311       --  We compute this if a component clause was present, otherwise
2312       --  we leave the computation up to Gigi, since we don't know what
2313       --  layout will be chosen.
2314
2315       when Attribute_Last_Bit => Last_Bit :
2316       declare
2317          CE : constant Entity_Id := Entity (Selector_Name (Pref));
2318
2319       begin
2320          if Known_Static_Component_Bit_Offset (CE)
2321            and then Known_Static_Esize (CE)
2322          then
2323             Rewrite (N,
2324               Make_Integer_Literal (Loc,
2325                Intval => (Component_Bit_Offset (CE) mod System_Storage_Unit)
2326                                 + Esize (CE) - 1));
2327
2328             Analyze_And_Resolve (N, Typ);
2329
2330          else
2331             Apply_Universal_Integer_Attribute_Checks (N);
2332          end if;
2333       end Last_Bit;
2334
2335       ------------------
2336       -- Leading_Part --
2337       ------------------
2338
2339       --  Transforms 'Leading_Part into a call to the floating-point attribute
2340       --  function Leading_Part in Fat_xxx (where xxx is the root type)
2341
2342       --  Note: strictly, we should have special case code to deal with
2343       --  absurdly large positive arguments (greater than Integer'Last), which
2344       --  result in returning the first argument unchanged, but it hardly seems
2345       --  worth the effort. We raise constraint error for absurdly negative
2346       --  arguments which is fine.
2347
2348       when Attribute_Leading_Part =>
2349          Expand_Fpt_Attribute_RI (N);
2350
2351       ------------
2352       -- Length --
2353       ------------
2354
2355       when Attribute_Length => declare
2356          Ptyp : constant Entity_Id := Etype (Pref);
2357          Ityp : Entity_Id;
2358          Xnum : Uint;
2359
2360       begin
2361          --  Processing for packed array types
2362
2363          if Is_Array_Type (Ptyp) and then Is_Packed (Ptyp) then
2364             Ityp := Get_Index_Subtype (N);
2365
2366             --  If the index type, Ityp, is an enumeration type with
2367             --  holes, then we calculate X'Length explicitly using
2368
2369             --     Typ'Max
2370             --       (0, Ityp'Pos (X'Last  (N)) -
2371             --           Ityp'Pos (X'First (N)) + 1);
2372
2373             --  Since the bounds in the template are the representation
2374             --  values and gigi would get the wrong value.
2375
2376             if Is_Enumeration_Type (Ityp)
2377               and then Present (Enum_Pos_To_Rep (Base_Type (Ityp)))
2378             then
2379                if No (Exprs) then
2380                   Xnum := Uint_1;
2381                else
2382                   Xnum := Expr_Value (First (Expressions (N)));
2383                end if;
2384
2385                Rewrite (N,
2386                  Make_Attribute_Reference (Loc,
2387                    Prefix         => New_Occurrence_Of (Typ, Loc),
2388                    Attribute_Name => Name_Max,
2389                    Expressions    => New_List
2390                      (Make_Integer_Literal (Loc, 0),
2391
2392                       Make_Op_Add (Loc,
2393                         Left_Opnd =>
2394                           Make_Op_Subtract (Loc,
2395                             Left_Opnd =>
2396                               Make_Attribute_Reference (Loc,
2397                                 Prefix => New_Occurrence_Of (Ityp, Loc),
2398                                 Attribute_Name => Name_Pos,
2399
2400                                 Expressions => New_List (
2401                                   Make_Attribute_Reference (Loc,
2402                                     Prefix => Duplicate_Subexpr (Pref),
2403                                    Attribute_Name => Name_Last,
2404                                     Expressions => New_List (
2405                                       Make_Integer_Literal (Loc, Xnum))))),
2406
2407                             Right_Opnd =>
2408                               Make_Attribute_Reference (Loc,
2409                                 Prefix => New_Occurrence_Of (Ityp, Loc),
2410                                 Attribute_Name => Name_Pos,
2411
2412                                 Expressions => New_List (
2413                                   Make_Attribute_Reference (Loc,
2414                                     Prefix =>
2415                                       Duplicate_Subexpr_No_Checks (Pref),
2416                                    Attribute_Name => Name_First,
2417                                     Expressions => New_List (
2418                                       Make_Integer_Literal (Loc, Xnum)))))),
2419
2420                         Right_Opnd => Make_Integer_Literal (Loc, 1)))));
2421
2422                Analyze_And_Resolve (N, Typ, Suppress => All_Checks);
2423                return;
2424
2425             --  If the prefix type is a constrained packed array type which
2426             --  already has a Packed_Array_Type representation defined, then
2427             --  replace this attribute with a direct reference to 'Range_Length
2428             --  of the appropriate index subtype (since otherwise Gigi will try
2429             --  to give us the value of 'Length for this implementation type).
2430
2431             elsif Is_Constrained (Ptyp) then
2432                Rewrite (N,
2433                  Make_Attribute_Reference (Loc,
2434                    Attribute_Name => Name_Range_Length,
2435                    Prefix => New_Reference_To (Ityp, Loc)));
2436                Analyze_And_Resolve (N, Typ);
2437             end if;
2438
2439          --  If we have a packed array that is not bit packed, which was
2440
2441          --  Access type case
2442
2443          elsif Is_Access_Type (Ptyp) then
2444             Apply_Access_Check (N);
2445
2446             --  If the designated type is a packed array type, then we
2447             --  convert the reference to:
2448
2449             --    typ'Max (0, 1 +
2450             --                xtyp'Pos (Pref'Last (Expr)) -
2451             --                xtyp'Pos (Pref'First (Expr)));
2452
2453             --  This is a bit complex, but it is the easiest thing to do
2454             --  that works in all cases including enum types with holes
2455             --  xtyp here is the appropriate index type.
2456
2457             declare
2458                Dtyp : constant Entity_Id := Designated_Type (Ptyp);
2459                Xtyp : Entity_Id;
2460
2461             begin
2462                if Is_Array_Type (Dtyp) and then Is_Packed (Dtyp) then
2463                   Xtyp := Get_Index_Subtype (N);
2464
2465                   Rewrite (N,
2466                     Make_Attribute_Reference (Loc,
2467                       Prefix         => New_Occurrence_Of (Typ, Loc),
2468                       Attribute_Name => Name_Max,
2469                       Expressions    => New_List (
2470                         Make_Integer_Literal (Loc, 0),
2471
2472                         Make_Op_Add (Loc,
2473                           Make_Integer_Literal (Loc, 1),
2474                           Make_Op_Subtract (Loc,
2475                             Left_Opnd =>
2476                               Make_Attribute_Reference (Loc,
2477                                 Prefix => New_Occurrence_Of (Xtyp, Loc),
2478                                 Attribute_Name => Name_Pos,
2479                                 Expressions    => New_List (
2480                                   Make_Attribute_Reference (Loc,
2481                                     Prefix => Duplicate_Subexpr (Pref),
2482                                     Attribute_Name => Name_Last,
2483                                     Expressions =>
2484                                       New_Copy_List (Exprs)))),
2485
2486                             Right_Opnd =>
2487                               Make_Attribute_Reference (Loc,
2488                                 Prefix => New_Occurrence_Of (Xtyp, Loc),
2489                                 Attribute_Name => Name_Pos,
2490                                 Expressions    => New_List (
2491                                   Make_Attribute_Reference (Loc,
2492                                     Prefix =>
2493                                       Duplicate_Subexpr_No_Checks (Pref),
2494                                     Attribute_Name => Name_First,
2495                                     Expressions =>
2496                                       New_Copy_List (Exprs)))))))));
2497
2498                   Analyze_And_Resolve (N, Typ);
2499                end if;
2500             end;
2501
2502          --  Otherwise leave it to gigi
2503
2504          else
2505             Apply_Universal_Integer_Attribute_Checks (N);
2506          end if;
2507       end;
2508
2509       -------------
2510       -- Machine --
2511       -------------
2512
2513       --  Transforms 'Machine into a call to the floating-point attribute
2514       --  function Machine in Fat_xxx (where xxx is the root type)
2515
2516       when Attribute_Machine =>
2517          Expand_Fpt_Attribute_R (N);
2518
2519       ----------------------
2520       -- Machine_Rounding --
2521       ----------------------
2522
2523       --  Transforms 'Machine_Rounding into a call to the floating-point
2524       --  attribute function Machine_Rounding in Fat_xxx (where xxx is the root
2525       --  type). Expansion is avoided for cases the back end can handle
2526       --  directly.
2527
2528       when Attribute_Machine_Rounding =>
2529          if not Is_Inline_Floating_Point_Attribute (N) then
2530             Expand_Fpt_Attribute_R (N);
2531          end if;
2532
2533       ------------------
2534       -- Machine_Size --
2535       ------------------
2536
2537       --  Machine_Size is equivalent to Object_Size, so transform it into
2538       --  Object_Size and that way Gigi never sees Machine_Size.
2539
2540       when Attribute_Machine_Size =>
2541          Rewrite (N,
2542            Make_Attribute_Reference (Loc,
2543              Prefix => Prefix (N),
2544              Attribute_Name => Name_Object_Size));
2545
2546          Analyze_And_Resolve (N, Typ);
2547
2548       --------------
2549       -- Mantissa --
2550       --------------
2551
2552       --  The only case that can get this far is the dynamic case of the old
2553       --  Ada 83 Mantissa attribute for the fixed-point case. For this case, we
2554       --  expand:
2555
2556       --    typ'Mantissa
2557
2558       --  into
2559
2560       --    ityp (System.Mantissa.Mantissa_Value
2561       --           (Integer'Integer_Value (typ'First),
2562       --            Integer'Integer_Value (typ'Last)));
2563
2564       when Attribute_Mantissa => Mantissa : declare
2565          Ptyp : constant Entity_Id := Etype (Pref);
2566
2567       begin
2568          Rewrite (N,
2569            Convert_To (Typ,
2570              Make_Function_Call (Loc,
2571                Name => New_Occurrence_Of (RTE (RE_Mantissa_Value), Loc),
2572
2573                Parameter_Associations => New_List (
2574
2575                  Make_Attribute_Reference (Loc,
2576                    Prefix => New_Occurrence_Of (Standard_Integer, Loc),
2577                    Attribute_Name => Name_Integer_Value,
2578                    Expressions => New_List (
2579
2580                      Make_Attribute_Reference (Loc,
2581                        Prefix => New_Occurrence_Of (Ptyp, Loc),
2582                        Attribute_Name => Name_First))),
2583
2584                  Make_Attribute_Reference (Loc,
2585                    Prefix => New_Occurrence_Of (Standard_Integer, Loc),
2586                    Attribute_Name => Name_Integer_Value,
2587                    Expressions => New_List (
2588
2589                      Make_Attribute_Reference (Loc,
2590                        Prefix => New_Occurrence_Of (Ptyp, Loc),
2591                        Attribute_Name => Name_Last)))))));
2592
2593          Analyze_And_Resolve (N, Typ);
2594       end Mantissa;
2595
2596       --------------------
2597       -- Mechanism_Code --
2598       --------------------
2599
2600       when Attribute_Mechanism_Code =>
2601
2602          --  We must replace the prefix in the renamed case
2603
2604          if Is_Entity_Name (Pref)
2605            and then Present (Alias (Entity (Pref)))
2606          then
2607             Set_Renamed_Subprogram (Pref, Alias (Entity (Pref)));
2608          end if;
2609
2610       ---------
2611       -- Mod --
2612       ---------
2613
2614       when Attribute_Mod => Mod_Case : declare
2615          Arg  : constant Node_Id := Relocate_Node (First (Exprs));
2616          Hi   : constant Node_Id := Type_High_Bound (Etype (Arg));
2617          Modv : constant Uint    := Modulus (Btyp);
2618
2619       begin
2620
2621          --  This is not so simple. The issue is what type to use for the
2622          --  computation of the modular value.
2623
2624          --  The easy case is when the modulus value is within the bounds
2625          --  of the signed integer type of the argument. In this case we can
2626          --  just do the computation in that signed integer type, and then
2627          --  do an ordinary conversion to the target type.
2628
2629          if Modv <= Expr_Value (Hi) then
2630             Rewrite (N,
2631               Convert_To (Btyp,
2632                 Make_Op_Mod (Loc,
2633                   Left_Opnd  => Arg,
2634                   Right_Opnd => Make_Integer_Literal (Loc, Modv))));
2635
2636          --  Here we know that the modulus is larger than type'Last of the
2637          --  integer type. There are two cases to consider:
2638
2639          --    a) The integer value is non-negative. In this case, it is
2640          --    returned as the result (since it is less than the modulus).
2641
2642          --    b) The integer value is negative. In this case, we know that the
2643          --    result is modulus + value, where the value might be as small as
2644          --    -modulus. The trouble is what type do we use to do the subtract.
2645          --    No type will do, since modulus can be as big as 2**64, and no
2646          --    integer type accomodates this value. Let's do bit of algebra
2647
2648          --         modulus + value
2649          --      =  modulus - (-value)
2650          --      =  (modulus - 1) - (-value - 1)
2651
2652          --    Now modulus - 1 is certainly in range of the modular type.
2653          --    -value is in the range 1 .. modulus, so -value -1 is in the
2654          --    range 0 .. modulus-1 which is in range of the modular type.
2655          --    Furthermore, (-value - 1) can be expressed as -(value + 1)
2656          --    which we can compute using the integer base type.
2657
2658          --  Once this is done we analyze the conditional expression without
2659          --  range checks, because we know everything is in range, and we
2660          --  want to prevent spurious warnings on either branch.
2661
2662          else
2663             Rewrite (N,
2664               Make_Conditional_Expression (Loc,
2665                 Expressions => New_List (
2666                   Make_Op_Ge (Loc,
2667                     Left_Opnd  => Duplicate_Subexpr (Arg),
2668                     Right_Opnd => Make_Integer_Literal (Loc, 0)),
2669
2670                   Convert_To (Btyp,
2671                     Duplicate_Subexpr_No_Checks (Arg)),
2672
2673                   Make_Op_Subtract (Loc,
2674                     Left_Opnd =>
2675                       Make_Integer_Literal (Loc,
2676                         Intval => Modv - 1),
2677                     Right_Opnd =>
2678                       Convert_To (Btyp,
2679                         Make_Op_Minus (Loc,
2680                           Right_Opnd =>
2681                             Make_Op_Add (Loc,
2682                               Left_Opnd  => Duplicate_Subexpr_No_Checks (Arg),
2683                               Right_Opnd =>
2684                                 Make_Integer_Literal (Loc,
2685                                   Intval => 1))))))));
2686
2687          end if;
2688
2689          Analyze_And_Resolve (N, Btyp, Suppress => All_Checks);
2690       end Mod_Case;
2691
2692       -----------
2693       -- Model --
2694       -----------
2695
2696       --  Transforms 'Model into a call to the floating-point attribute
2697       --  function Model in Fat_xxx (where xxx is the root type)
2698
2699       when Attribute_Model =>
2700          Expand_Fpt_Attribute_R (N);
2701
2702       -----------------
2703       -- Object_Size --
2704       -----------------
2705
2706       --  The processing for Object_Size shares the processing for Size
2707
2708       ------------
2709       -- Output --
2710       ------------
2711
2712       when Attribute_Output => Output : declare
2713          P_Type : constant Entity_Id := Entity (Pref);
2714          U_Type : constant Entity_Id := Underlying_Type (P_Type);
2715          Pname  : Entity_Id;
2716          Decl   : Node_Id;
2717          Prag   : Node_Id;
2718          Arg3   : Node_Id;
2719          Wfunc  : Node_Id;
2720
2721       begin
2722          --  If no underlying type, we have an error that will be diagnosed
2723          --  elsewhere, so here we just completely ignore the expansion.
2724
2725          if No (U_Type) then
2726             return;
2727          end if;
2728
2729          --  If TSS for Output is present, just call it
2730
2731          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Output);
2732
2733          if Present (Pname) then
2734             null;
2735
2736          else
2737             --  If there is a Stream_Convert pragma, use it, we rewrite
2738
2739             --     sourcetyp'Output (stream, Item)
2740
2741             --  as
2742
2743             --     strmtyp'Output (Stream, strmwrite (acttyp (Item)));
2744
2745             --  where strmwrite is the given Write function that converts an
2746             --  argument of type sourcetyp or a type acctyp, from which it is
2747             --  derived to type strmtyp. The conversion to acttyp is required
2748             --  for the derived case.
2749
2750             Prag := Get_Stream_Convert_Pragma (P_Type);
2751
2752             if Present (Prag) then
2753                Arg3 :=
2754                  Next (Next (First (Pragma_Argument_Associations (Prag))));
2755                Wfunc := Entity (Expression (Arg3));
2756
2757                Rewrite (N,
2758                  Make_Attribute_Reference (Loc,
2759                    Prefix => New_Occurrence_Of (Etype (Wfunc), Loc),
2760                    Attribute_Name => Name_Output,
2761                    Expressions => New_List (
2762                    Relocate_Node (First (Exprs)),
2763                      Make_Function_Call (Loc,
2764                        Name => New_Occurrence_Of (Wfunc, Loc),
2765                        Parameter_Associations => New_List (
2766                          OK_Convert_To (Etype (First_Formal (Wfunc)),
2767                            Relocate_Node (Next (First (Exprs)))))))));
2768
2769                Analyze (N);
2770                return;
2771
2772             --  For elementary types, we call the W_xxx routine directly.
2773             --  Note that the effect of Write and Output is identical for
2774             --  the case of an elementary type, since there are no
2775             --  discriminants or bounds.
2776
2777             elsif Is_Elementary_Type (U_Type) then
2778
2779                --  A special case arises if we have a defined _Write routine,
2780                --  since in this case we are required to call this routine.
2781
2782                if Present (TSS (Base_Type (U_Type), TSS_Stream_Write)) then
2783                   Build_Record_Or_Elementary_Output_Procedure
2784                     (Loc, U_Type, Decl, Pname);
2785                   Insert_Action (N, Decl);
2786
2787                --  For normal cases, we call the W_xxx routine directly
2788
2789                else
2790                   Rewrite (N, Build_Elementary_Write_Call (N));
2791                   Analyze (N);
2792                   return;
2793                end if;
2794
2795             --  Array type case
2796
2797             elsif Is_Array_Type (U_Type) then
2798                Build_Array_Output_Procedure (Loc, U_Type, Decl, Pname);
2799                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
2800
2801             --  Class-wide case, first output external tag, then dispatch
2802             --  to the appropriate primitive Output function (RM 13.13.2(31)).
2803
2804             elsif Is_Class_Wide_Type (P_Type) then
2805
2806                --  No need to do anything else compiling under restriction
2807                --  No_Dispatching_Calls. During the semantic analysis we
2808                --  already notified such violation.
2809
2810                if Restriction_Active (No_Dispatching_Calls) then
2811                   return;
2812                end if;
2813
2814                Tag_Write : declare
2815                   Strm : constant Node_Id := First (Exprs);
2816                   Item : constant Node_Id := Next (Strm);
2817
2818                begin
2819                   --  Ada 2005 (AI-344): Check that the accessibility level
2820                   --  of the type of the output object is not deeper than
2821                   --  that of the attribute's prefix type.
2822
2823                   --  if Get_Access_Level (Item'Tag)
2824                   --       /= Get_Access_Level (P_Type'Tag)
2825                   --  then
2826                   --     raise Tag_Error;
2827                   --  end if;
2828
2829                   --  String'Output (Strm, External_Tag (Item'Tag));
2830
2831                   --  We cannot figure out a practical way to implement this
2832                   --  accessibility check on virtual machines, so we omit it.
2833
2834                   if Ada_Version >= Ada_05
2835                     and then VM_Target = No_VM
2836                   then
2837                      Insert_Action (N,
2838                        Make_Implicit_If_Statement (N,
2839                          Condition =>
2840                            Make_Op_Ne (Loc,
2841                              Left_Opnd  =>
2842                                Build_Get_Access_Level (Loc,
2843                                  Make_Attribute_Reference (Loc,
2844                                    Prefix         =>
2845                                      Relocate_Node (
2846                                        Duplicate_Subexpr (Item,
2847                                          Name_Req => True)),
2848                                    Attribute_Name => Name_Tag)),
2849
2850                              Right_Opnd =>
2851                                Make_Integer_Literal (Loc,
2852                                  Type_Access_Level (P_Type))),
2853
2854                          Then_Statements =>
2855                            New_List (Make_Raise_Statement (Loc,
2856                                        New_Occurrence_Of (
2857                                          RTE (RE_Tag_Error), Loc)))));
2858                   end if;
2859
2860                   Insert_Action (N,
2861                     Make_Attribute_Reference (Loc,
2862                       Prefix => New_Occurrence_Of (Standard_String, Loc),
2863                       Attribute_Name => Name_Output,
2864                       Expressions => New_List (
2865                         Relocate_Node (Duplicate_Subexpr (Strm)),
2866                         Make_Function_Call (Loc,
2867                           Name =>
2868                             New_Occurrence_Of (RTE (RE_External_Tag), Loc),
2869                           Parameter_Associations => New_List (
2870                            Make_Attribute_Reference (Loc,
2871                              Prefix =>
2872                                Relocate_Node
2873                                  (Duplicate_Subexpr (Item, Name_Req => True)),
2874                              Attribute_Name => Name_Tag))))));
2875                end Tag_Write;
2876
2877                Pname := Find_Prim_Op (U_Type, TSS_Stream_Output);
2878
2879             --  Tagged type case, use the primitive Output function
2880
2881             elsif Is_Tagged_Type (U_Type) then
2882                Pname := Find_Prim_Op (U_Type, TSS_Stream_Output);
2883
2884             --  All other record type cases, including protected records.
2885             --  The latter only arise for expander generated code for
2886             --  handling shared passive partition access.
2887
2888             else
2889                pragma Assert
2890                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
2891
2892                --  Ada 2005 (AI-216): Program_Error is raised when executing
2893                --  the default implementation of the Output attribute of an
2894                --  unchecked union type if the type lacks default discriminant
2895                --  values.
2896
2897                if Is_Unchecked_Union (Base_Type (U_Type))
2898                  and then No (Discriminant_Constraint (U_Type))
2899                then
2900                   Insert_Action (N,
2901                     Make_Raise_Program_Error (Loc,
2902                       Reason => PE_Unchecked_Union_Restriction));
2903
2904                   return;
2905                end if;
2906
2907                Build_Record_Or_Elementary_Output_Procedure
2908                  (Loc, Base_Type (U_Type), Decl, Pname);
2909                Insert_Action (N, Decl);
2910             end if;
2911          end if;
2912
2913          --  If we fall through, Pname is the name of the procedure to call
2914
2915          Rewrite_Stream_Proc_Call (Pname);
2916       end Output;
2917
2918       ---------
2919       -- Pos --
2920       ---------
2921
2922       --  For enumeration types with a standard representation, Pos is
2923       --  handled by Gigi.
2924
2925       --  For enumeration types, with a non-standard representation we
2926       --  generate a call to the _Rep_To_Pos function created when the
2927       --  type was frozen. The call has the form
2928
2929       --    _rep_to_pos (expr, flag)
2930
2931       --  The parameter flag is True if range checks are enabled, causing
2932       --  Program_Error to be raised if the expression has an invalid
2933       --  representation, and False if range checks are suppressed.
2934
2935       --  For integer types, Pos is equivalent to a simple integer
2936       --  conversion and we rewrite it as such
2937
2938       when Attribute_Pos => Pos :
2939       declare
2940          Etyp : Entity_Id := Base_Type (Entity (Pref));
2941
2942       begin
2943          --  Deal with zero/non-zero boolean values
2944
2945          if Is_Boolean_Type (Etyp) then
2946             Adjust_Condition (First (Exprs));
2947             Etyp := Standard_Boolean;
2948             Set_Prefix (N, New_Occurrence_Of (Standard_Boolean, Loc));
2949          end if;
2950
2951          --  Case of enumeration type
2952
2953          if Is_Enumeration_Type (Etyp) then
2954
2955             --  Non-standard enumeration type (generate call)
2956
2957             if Present (Enum_Pos_To_Rep (Etyp)) then
2958                Append_To (Exprs, Rep_To_Pos_Flag (Etyp, Loc));
2959                Rewrite (N,
2960                  Convert_To (Typ,
2961                    Make_Function_Call (Loc,
2962                      Name =>
2963                        New_Reference_To (TSS (Etyp, TSS_Rep_To_Pos), Loc),
2964                      Parameter_Associations => Exprs)));
2965
2966                Analyze_And_Resolve (N, Typ);
2967
2968             --  Standard enumeration type (do universal integer check)
2969
2970             else
2971                Apply_Universal_Integer_Attribute_Checks (N);
2972             end if;
2973
2974          --  Deal with integer types (replace by conversion)
2975
2976          elsif Is_Integer_Type (Etyp) then
2977             Rewrite (N, Convert_To (Typ, First (Exprs)));
2978             Analyze_And_Resolve (N, Typ);
2979          end if;
2980
2981       end Pos;
2982
2983       --------------
2984       -- Position --
2985       --------------
2986
2987       --  We compute this if a component clause was present, otherwise
2988       --  we leave the computation up to Gigi, since we don't know what
2989       --  layout will be chosen.
2990
2991       when Attribute_Position => Position :
2992       declare
2993          CE : constant Entity_Id := Entity (Selector_Name (Pref));
2994
2995       begin
2996          if Present (Component_Clause (CE)) then
2997             Rewrite (N,
2998               Make_Integer_Literal (Loc,
2999                 Intval => Component_Bit_Offset (CE) / System_Storage_Unit));
3000             Analyze_And_Resolve (N, Typ);
3001
3002          else
3003             Apply_Universal_Integer_Attribute_Checks (N);
3004          end if;
3005       end Position;
3006
3007       ----------
3008       -- Pred --
3009       ----------
3010
3011       --  1. Deal with enumeration types with holes
3012       --  2. For floating-point, generate call to attribute function
3013       --  3. For other cases, deal with constraint checking
3014
3015       when Attribute_Pred => Pred :
3016       declare
3017          Ptyp : constant Entity_Id := Base_Type (Etype (Pref));
3018
3019       begin
3020          --  For enumeration types with non-standard representations, we
3021          --  expand typ'Pred (x) into
3022
3023          --    Pos_To_Rep (Rep_To_Pos (x) - 1)
3024
3025          --    If the representation is contiguous, we compute instead
3026          --    Lit1 + Rep_to_Pos (x -1), to catch invalid representations.
3027
3028          if Is_Enumeration_Type (Ptyp)
3029            and then Present (Enum_Pos_To_Rep (Ptyp))
3030          then
3031             if Has_Contiguous_Rep (Ptyp) then
3032                Rewrite (N,
3033                   Unchecked_Convert_To (Ptyp,
3034                      Make_Op_Add (Loc,
3035                         Left_Opnd  =>
3036                          Make_Integer_Literal (Loc,
3037                            Enumeration_Rep (First_Literal (Ptyp))),
3038                         Right_Opnd =>
3039                           Make_Function_Call (Loc,
3040                             Name =>
3041                               New_Reference_To
3042                                (TSS (Ptyp, TSS_Rep_To_Pos), Loc),
3043
3044                             Parameter_Associations =>
3045                               New_List (
3046                                 Unchecked_Convert_To (Ptyp,
3047                                   Make_Op_Subtract (Loc,
3048                                     Left_Opnd =>
3049                                      Unchecked_Convert_To (Standard_Integer,
3050                                        Relocate_Node (First (Exprs))),
3051                                     Right_Opnd =>
3052                                       Make_Integer_Literal (Loc, 1))),
3053                                 Rep_To_Pos_Flag (Ptyp, Loc))))));
3054
3055             else
3056                --  Add Boolean parameter True, to request program errror if
3057                --  we have a bad representation on our hands. If checks are
3058                --  suppressed, then add False instead
3059
3060                Append_To (Exprs, Rep_To_Pos_Flag (Ptyp, Loc));
3061                Rewrite (N,
3062                  Make_Indexed_Component (Loc,
3063                    Prefix => New_Reference_To (Enum_Pos_To_Rep (Ptyp), Loc),
3064                    Expressions => New_List (
3065                      Make_Op_Subtract (Loc,
3066                     Left_Opnd =>
3067                       Make_Function_Call (Loc,
3068                         Name =>
3069                           New_Reference_To (TSS (Ptyp, TSS_Rep_To_Pos), Loc),
3070                           Parameter_Associations => Exprs),
3071                     Right_Opnd => Make_Integer_Literal (Loc, 1)))));
3072             end if;
3073
3074             Analyze_And_Resolve (N, Typ);
3075
3076          --  For floating-point, we transform 'Pred into a call to the Pred
3077          --  floating-point attribute function in Fat_xxx (xxx is root type)
3078
3079          elsif Is_Floating_Point_Type (Ptyp) then
3080             Expand_Fpt_Attribute_R (N);
3081             Analyze_And_Resolve (N, Typ);
3082
3083          --  For modular types, nothing to do (no overflow, since wraps)
3084
3085          elsif Is_Modular_Integer_Type (Ptyp) then
3086             null;
3087
3088          --  For other types, if range checking is enabled, we must generate
3089          --  a check if overflow checking is enabled.
3090
3091          elsif not Overflow_Checks_Suppressed (Ptyp) then
3092             Expand_Pred_Succ (N);
3093          end if;
3094       end Pred;
3095
3096       --------------
3097       -- Priority --
3098       --------------
3099
3100       --  Ada 2005 (AI-327): Dynamic ceiling priorities
3101
3102       --  We rewrite X'Priority as the following run-time call:
3103
3104       --     Get_Ceiling (X._Object)
3105
3106       --  Note that although X'Priority is notionally an object, it is quite
3107       --  deliberately not defined as an aliased object in the RM. This means
3108       --  that it works fine to rewrite it as a call, without having to worry
3109       --  about complications that would other arise from X'Priority'Access,
3110       --  which is illegal, because of the lack of aliasing.
3111
3112       when Attribute_Priority =>
3113          declare
3114             Call           : Node_Id;
3115             Conctyp        : Entity_Id;
3116             Object_Parm    : Node_Id;
3117             Subprg         : Entity_Id;
3118             RT_Subprg_Name : Node_Id;
3119
3120          begin
3121             --  Look for the enclosing concurrent type
3122
3123             Conctyp := Current_Scope;
3124             while not Is_Concurrent_Type (Conctyp) loop
3125                Conctyp := Scope (Conctyp);
3126             end loop;
3127
3128             pragma Assert (Is_Protected_Type (Conctyp));
3129
3130             --  Generate the actual of the call
3131
3132             Subprg := Current_Scope;
3133             while not Present (Protected_Body_Subprogram (Subprg)) loop
3134                Subprg := Scope (Subprg);
3135             end loop;
3136
3137             Object_Parm :=
3138               Make_Attribute_Reference (Loc,
3139                  Prefix =>
3140                    Make_Selected_Component (Loc,
3141                      Prefix => New_Reference_To
3142                                  (First_Entity
3143                                    (Protected_Body_Subprogram (Subprg)), Loc),
3144                    Selector_Name =>
3145                        Make_Identifier (Loc, Name_uObject)),
3146                  Attribute_Name => Name_Unchecked_Access);
3147
3148             --  Select the appropriate run-time subprogram
3149
3150             if Number_Entries (Conctyp) = 0 then
3151                RT_Subprg_Name :=
3152                  New_Reference_To (RTE (RE_Get_Ceiling), Loc);
3153             else
3154                RT_Subprg_Name :=
3155                  New_Reference_To (RTE (RO_PE_Get_Ceiling), Loc);
3156             end if;
3157
3158             Call :=
3159               Make_Function_Call (Loc,
3160                 Name => RT_Subprg_Name,
3161                 Parameter_Associations => New_List (Object_Parm));
3162
3163             Rewrite (N, Call);
3164             Analyze_And_Resolve (N, Typ);
3165          end;
3166
3167       ------------------
3168       -- Range_Length --
3169       ------------------
3170
3171       when Attribute_Range_Length => Range_Length : declare
3172          P_Type : constant Entity_Id := Etype (Pref);
3173
3174       begin
3175          --  The only special processing required is for the case where
3176          --  Range_Length is applied to an enumeration type with holes.
3177          --  In this case we transform
3178
3179          --     X'Range_Length
3180
3181          --  to
3182
3183          --     X'Pos (X'Last) - X'Pos (X'First) + 1
3184
3185          --  So that the result reflects the proper Pos values instead
3186          --  of the underlying representations.
3187
3188          if Is_Enumeration_Type (P_Type)
3189            and then Has_Non_Standard_Rep (P_Type)
3190          then
3191             Rewrite (N,
3192               Make_Op_Add (Loc,
3193                 Left_Opnd =>
3194                   Make_Op_Subtract (Loc,
3195                     Left_Opnd =>
3196                       Make_Attribute_Reference (Loc,
3197                         Attribute_Name => Name_Pos,
3198                         Prefix => New_Occurrence_Of (P_Type, Loc),
3199                         Expressions => New_List (
3200                           Make_Attribute_Reference (Loc,
3201                             Attribute_Name => Name_Last,
3202                             Prefix => New_Occurrence_Of (P_Type, Loc)))),
3203
3204                     Right_Opnd =>
3205                       Make_Attribute_Reference (Loc,
3206                         Attribute_Name => Name_Pos,
3207                         Prefix => New_Occurrence_Of (P_Type, Loc),
3208                         Expressions => New_List (
3209                           Make_Attribute_Reference (Loc,
3210                             Attribute_Name => Name_First,
3211                             Prefix => New_Occurrence_Of (P_Type, Loc))))),
3212
3213                 Right_Opnd =>
3214                   Make_Integer_Literal (Loc, 1)));
3215
3216             Analyze_And_Resolve (N, Typ);
3217
3218          --  For all other cases, attribute is handled by Gigi, but we need
3219          --  to deal with the case of the range check on a universal integer.
3220
3221          else
3222             Apply_Universal_Integer_Attribute_Checks (N);
3223          end if;
3224       end Range_Length;
3225
3226       ----------
3227       -- Read --
3228       ----------
3229
3230       when Attribute_Read => Read : declare
3231          P_Type : constant Entity_Id := Entity (Pref);
3232          B_Type : constant Entity_Id := Base_Type (P_Type);
3233          U_Type : constant Entity_Id := Underlying_Type (P_Type);
3234          Pname  : Entity_Id;
3235          Decl   : Node_Id;
3236          Prag   : Node_Id;
3237          Arg2   : Node_Id;
3238          Rfunc  : Node_Id;
3239          Lhs    : Node_Id;
3240          Rhs    : Node_Id;
3241
3242       begin
3243          --  If no underlying type, we have an error that will be diagnosed
3244          --  elsewhere, so here we just completely ignore the expansion.
3245
3246          if No (U_Type) then
3247             return;
3248          end if;
3249
3250          --  The simple case, if there is a TSS for Read, just call it
3251
3252          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Read);
3253
3254          if Present (Pname) then
3255             null;
3256
3257          else
3258             --  If there is a Stream_Convert pragma, use it, we rewrite
3259
3260             --     sourcetyp'Read (stream, Item)
3261
3262             --  as
3263
3264             --     Item := sourcetyp (strmread (strmtyp'Input (Stream)));
3265
3266             --  where strmread is the given Read function that converts an
3267             --  argument of type strmtyp to type sourcetyp or a type from which
3268             --  it is derived. The conversion to sourcetyp is required in the
3269             --  latter case.
3270
3271             --  A special case arises if Item is a type conversion in which
3272             --  case, we have to expand to:
3273
3274             --     Itemx := typex (strmread (strmtyp'Input (Stream)));
3275
3276             --  where Itemx is the expression of the type conversion (i.e.
3277             --  the actual object), and typex is the type of Itemx.
3278
3279             Prag := Get_Stream_Convert_Pragma (P_Type);
3280
3281             if Present (Prag) then
3282                Arg2  := Next (First (Pragma_Argument_Associations (Prag)));
3283                Rfunc := Entity (Expression (Arg2));
3284                Lhs := Relocate_Node (Next (First (Exprs)));
3285                Rhs :=
3286                  OK_Convert_To (B_Type,
3287                    Make_Function_Call (Loc,
3288                      Name => New_Occurrence_Of (Rfunc, Loc),
3289                      Parameter_Associations => New_List (
3290                        Make_Attribute_Reference (Loc,
3291                          Prefix =>
3292                            New_Occurrence_Of
3293                              (Etype (First_Formal (Rfunc)), Loc),
3294                          Attribute_Name => Name_Input,
3295                          Expressions => New_List (
3296                            Relocate_Node (First (Exprs)))))));
3297
3298                if Nkind (Lhs) = N_Type_Conversion then
3299                   Lhs := Expression (Lhs);
3300                   Rhs := Convert_To (Etype (Lhs), Rhs);
3301                end if;
3302
3303                Rewrite (N,
3304                  Make_Assignment_Statement (Loc,
3305                    Name       => Lhs,
3306                    Expression => Rhs));
3307                Set_Assignment_OK (Lhs);
3308                Analyze (N);
3309                return;
3310
3311             --  For elementary types, we call the I_xxx routine using the first
3312             --  parameter and then assign the result into the second parameter.
3313             --  We set Assignment_OK to deal with the conversion case.
3314
3315             elsif Is_Elementary_Type (U_Type) then
3316                declare
3317                   Lhs : Node_Id;
3318                   Rhs : Node_Id;
3319
3320                begin
3321                   Lhs := Relocate_Node (Next (First (Exprs)));
3322                   Rhs := Build_Elementary_Input_Call (N);
3323
3324                   if Nkind (Lhs) = N_Type_Conversion then
3325                      Lhs := Expression (Lhs);
3326                      Rhs := Convert_To (Etype (Lhs), Rhs);
3327                   end if;
3328
3329                   Set_Assignment_OK (Lhs);
3330
3331                   Rewrite (N,
3332                     Make_Assignment_Statement (Loc,
3333                       Name => Lhs,
3334                       Expression => Rhs));
3335
3336                   Analyze (N);
3337                   return;
3338                end;
3339
3340             --  Array type case
3341
3342             elsif Is_Array_Type (U_Type) then
3343                Build_Array_Read_Procedure (N, U_Type, Decl, Pname);
3344                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
3345
3346             --  Tagged type case, use the primitive Read function. Note that
3347             --  this will dispatch in the class-wide case which is what we want
3348
3349             elsif Is_Tagged_Type (U_Type) then
3350                Pname := Find_Prim_Op (U_Type, TSS_Stream_Read);
3351
3352             --  All other record type cases, including protected records. The
3353             --  latter only arise for expander generated code for handling
3354             --  shared passive partition access.
3355
3356             else
3357                pragma Assert
3358                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
3359
3360                --  Ada 2005 (AI-216): Program_Error is raised when executing
3361                --  the default implementation of the Read attribute of an
3362                --  Unchecked_Union type.
3363
3364                if Is_Unchecked_Union (Base_Type (U_Type)) then
3365                   Insert_Action (N,
3366                     Make_Raise_Program_Error (Loc,
3367                       Reason => PE_Unchecked_Union_Restriction));
3368                end if;
3369
3370                if Has_Discriminants (U_Type)
3371                  and then Present
3372                    (Discriminant_Default_Value (First_Discriminant (U_Type)))
3373                then
3374                   Build_Mutable_Record_Read_Procedure
3375                     (Loc, Base_Type (U_Type), Decl, Pname);
3376                else
3377                   Build_Record_Read_Procedure
3378                     (Loc, Base_Type (U_Type), Decl, Pname);
3379                end if;
3380
3381                --  Suppress checks, uninitialized or otherwise invalid
3382                --  data does not cause constraint errors to be raised for
3383                --  a complete record read.
3384
3385                Insert_Action (N, Decl, All_Checks);
3386             end if;
3387          end if;
3388
3389          Rewrite_Stream_Proc_Call (Pname);
3390       end Read;
3391
3392       ---------------
3393       -- Remainder --
3394       ---------------
3395
3396       --  Transforms 'Remainder into a call to the floating-point attribute
3397       --  function Remainder in Fat_xxx (where xxx is the root type)
3398
3399       when Attribute_Remainder =>
3400          Expand_Fpt_Attribute_RR (N);
3401
3402       -----------
3403       -- Round --
3404       -----------
3405
3406       --  The handling of the Round attribute is quite delicate. The processing
3407       --  in Sem_Attr introduced a conversion to universal real, reflecting the
3408       --  semantics of Round, but we do not want anything to do with universal
3409       --  real at runtime, since this corresponds to using floating-point
3410       --  arithmetic.
3411
3412       --  What we have now is that the Etype of the Round attribute correctly
3413       --  indicates the final result type. The operand of the Round is the
3414       --  conversion to universal real, described above, and the operand of
3415       --  this conversion is the actual operand of Round, which may be the
3416       --  special case of a fixed point multiplication or division (Etype =
3417       --  universal fixed)
3418
3419       --  The exapander will expand first the operand of the conversion, then
3420       --  the conversion, and finally the round attribute itself, since we
3421       --  always work inside out. But we cannot simply process naively in this
3422       --  order. In the semantic world where universal fixed and real really
3423       --  exist and have infinite precision, there is no problem, but in the
3424       --  implementation world, where universal real is a floating-point type,
3425       --  we would get the wrong result.
3426
3427       --  So the approach is as follows. First, when expanding a multiply or
3428       --  divide whose type is universal fixed, we do nothing at all, instead
3429       --  deferring the operation till later.
3430
3431       --  The actual processing is done in Expand_N_Type_Conversion which
3432       --  handles the special case of Round by looking at its parent to see if
3433       --  it is a Round attribute, and if it is, handling the conversion (or
3434       --  its fixed multiply/divide child) in an appropriate manner.
3435
3436       --  This means that by the time we get to expanding the Round attribute
3437       --  itself, the Round is nothing more than a type conversion (and will
3438       --  often be a null type conversion), so we just replace it with the
3439       --  appropriate conversion operation.
3440
3441       when Attribute_Round =>
3442          Rewrite (N,
3443            Convert_To (Etype (N), Relocate_Node (First (Exprs))));
3444          Analyze_And_Resolve (N);
3445
3446       --------------
3447       -- Rounding --
3448       --------------
3449
3450       --  Transforms 'Rounding into a call to the floating-point attribute
3451       --  function Rounding in Fat_xxx (where xxx is the root type)
3452
3453       when Attribute_Rounding =>
3454          Expand_Fpt_Attribute_R (N);
3455
3456       -------------
3457       -- Scaling --
3458       -------------
3459
3460       --  Transforms 'Scaling into a call to the floating-point attribute
3461       --  function Scaling in Fat_xxx (where xxx is the root type)
3462
3463       when Attribute_Scaling =>
3464          Expand_Fpt_Attribute_RI (N);
3465
3466       ----------
3467       -- Size --
3468       ----------
3469
3470       when Attribute_Size        |
3471            Attribute_Object_Size |
3472            Attribute_Value_Size  |
3473            Attribute_VADS_Size   => Size :
3474
3475       declare
3476          Ptyp     : constant Entity_Id := Etype (Pref);
3477          Siz      : Uint;
3478          New_Node : Node_Id;
3479
3480       begin
3481          --  Processing for VADS_Size case. Note that this processing removes
3482          --  all traces of VADS_Size from the tree, and completes all required
3483          --  processing for VADS_Size by translating the attribute reference
3484          --  to an appropriate Size or Object_Size reference.
3485
3486          if Id = Attribute_VADS_Size
3487            or else (Use_VADS_Size and then Id = Attribute_Size)
3488          then
3489             --  If the size is specified, then we simply use the specified
3490             --  size. This applies to both types and objects. The size of an
3491             --  object can be specified in the following ways:
3492
3493             --    An explicit size object is given for an object
3494             --    A component size is specified for an indexed component
3495             --    A component clause is specified for a selected component
3496             --    The object is a component of a packed composite object
3497
3498             --  If the size is specified, then VADS_Size of an object
3499
3500             if (Is_Entity_Name (Pref)
3501                  and then Present (Size_Clause (Entity (Pref))))
3502               or else
3503                 (Nkind (Pref) = N_Component_Clause
3504                   and then (Present (Component_Clause
3505                                      (Entity (Selector_Name (Pref))))
3506                              or else Is_Packed (Etype (Prefix (Pref)))))
3507               or else
3508                 (Nkind (Pref) = N_Indexed_Component
3509                   and then (Component_Size (Etype (Prefix (Pref))) /= 0
3510                              or else Is_Packed (Etype (Prefix (Pref)))))
3511             then
3512                Set_Attribute_Name (N, Name_Size);
3513
3514             --  Otherwise if we have an object rather than a type, then the
3515             --  VADS_Size attribute applies to the type of the object, rather
3516             --  than the object itself. This is one of the respects in which
3517             --  VADS_Size differs from Size.
3518
3519             else
3520                if (not Is_Entity_Name (Pref)
3521                     or else not Is_Type (Entity (Pref)))
3522                  and then (Is_Scalar_Type (Etype (Pref))
3523                             or else Is_Constrained (Etype (Pref)))
3524                then
3525                   Rewrite (Pref, New_Occurrence_Of (Etype (Pref), Loc));
3526                end if;
3527
3528                --  For a scalar type for which no size was explicitly given,
3529                --  VADS_Size means Object_Size. This is the other respect in
3530                --  which VADS_Size differs from Size.
3531
3532                if Is_Scalar_Type (Etype (Pref))
3533                  and then No (Size_Clause (Etype (Pref)))
3534                then
3535                   Set_Attribute_Name (N, Name_Object_Size);
3536
3537                --  In all other cases, Size and VADS_Size are the sane
3538
3539                else
3540                   Set_Attribute_Name (N, Name_Size);
3541                end if;
3542             end if;
3543          end if;
3544
3545          --  For class-wide types,  X'Class'Size is transformed into a
3546          --  direct reference to the Size of the class type, so that gigi
3547          --  does not have to deal with the X'Class'Size reference.
3548
3549          if Is_Entity_Name (Pref)
3550            and then Is_Class_Wide_Type (Entity (Pref))
3551          then
3552             Rewrite (Prefix (N), New_Occurrence_Of (Entity (Pref), Loc));
3553             return;
3554
3555          --  For X'Size applied to an object of a class-wide type, transform
3556          --  X'Size into a call to the primitive operation _Size applied to X.
3557
3558          elsif Is_Class_Wide_Type (Ptyp) then
3559
3560             --  No need to do anything else compiling under restriction
3561             --  No_Dispatching_Calls. During the semantic analysis we
3562             --  already notified such violation.
3563
3564             if Restriction_Active (No_Dispatching_Calls) then
3565                return;
3566             end if;
3567
3568             New_Node :=
3569               Make_Function_Call (Loc,
3570                 Name => New_Reference_To
3571                   (Find_Prim_Op (Ptyp, Name_uSize), Loc),
3572                 Parameter_Associations => New_List (Pref));
3573
3574             if Typ /= Standard_Long_Long_Integer then
3575
3576                --  The context is a specific integer type with which the
3577                --  original attribute was compatible. The function has a
3578                --  specific type as well, so to preserve the compatibility
3579                --  we must convert explicitly.
3580
3581                New_Node := Convert_To (Typ, New_Node);
3582             end if;
3583
3584             Rewrite (N, New_Node);
3585             Analyze_And_Resolve (N, Typ);
3586                return;
3587
3588          --  Case of known RM_Size of a type
3589
3590          elsif (Id = Attribute_Size or else Id = Attribute_Value_Size)
3591            and then Is_Entity_Name (Pref)
3592            and then Is_Type (Entity (Pref))
3593            and then Known_Static_RM_Size (Entity (Pref))
3594          then
3595             Siz := RM_Size (Entity (Pref));
3596
3597          --  Case of known Esize of a type
3598
3599          elsif Id = Attribute_Object_Size
3600            and then Is_Entity_Name (Pref)
3601            and then Is_Type (Entity (Pref))
3602            and then Known_Static_Esize (Entity (Pref))
3603          then
3604             Siz := Esize (Entity (Pref));
3605
3606          --  Case of known size of object
3607
3608          elsif Id = Attribute_Size
3609            and then Is_Entity_Name (Pref)
3610            and then Is_Object (Entity (Pref))
3611            and then Known_Esize (Entity (Pref))
3612            and then Known_Static_Esize (Entity (Pref))
3613          then
3614             Siz := Esize (Entity (Pref));
3615
3616          --  For an array component, we can do Size in the front end
3617          --  if the component_size of the array is set.
3618
3619          elsif Nkind (Pref) = N_Indexed_Component then
3620             Siz := Component_Size (Etype (Prefix (Pref)));
3621
3622          --  For a record component, we can do Size in the front end if there
3623          --  is a component clause, or if the record is packed and the
3624          --  component's size is known at compile time.
3625
3626          elsif Nkind (Pref) = N_Selected_Component then
3627             declare
3628                Rec  : constant Entity_Id := Etype (Prefix (Pref));
3629                Comp : constant Entity_Id := Entity (Selector_Name (Pref));
3630
3631             begin
3632                if Present (Component_Clause (Comp)) then
3633                   Siz := Esize (Comp);
3634
3635                elsif Is_Packed (Rec) then
3636                   Siz := RM_Size (Ptyp);
3637
3638                else
3639                   Apply_Universal_Integer_Attribute_Checks (N);
3640                   return;
3641                end if;
3642             end;
3643
3644          --  All other cases are handled by Gigi
3645
3646          else
3647             Apply_Universal_Integer_Attribute_Checks (N);
3648
3649             --  If Size is applied to a formal parameter that is of a packed
3650             --  array subtype, then apply Size to the actual subtype.
3651
3652             if Is_Entity_Name (Pref)
3653               and then Is_Formal (Entity (Pref))
3654               and then Is_Array_Type (Etype (Pref))
3655               and then Is_Packed (Etype (Pref))
3656             then
3657                Rewrite (N,
3658                  Make_Attribute_Reference (Loc,
3659                    Prefix =>
3660                      New_Occurrence_Of (Get_Actual_Subtype (Pref), Loc),
3661                    Attribute_Name => Name_Size));
3662                Analyze_And_Resolve (N, Typ);
3663             end if;
3664
3665             --  If Size applies to a dereference of an access to unconstrained
3666             --  packed array, GIGI needs to see its unconstrained nominal type,
3667             --  but also a hint to the actual constrained type.
3668
3669             if Nkind (Pref) = N_Explicit_Dereference
3670               and then Is_Array_Type (Etype (Pref))
3671               and then not Is_Constrained (Etype (Pref))
3672               and then Is_Packed (Etype (Pref))
3673             then
3674                Set_Actual_Designated_Subtype (Pref,
3675                  Get_Actual_Subtype (Pref));
3676             end if;
3677
3678             return;
3679          end if;
3680
3681          --  Common processing for record and array component case
3682
3683          if Siz /= No_Uint and then Siz /= 0 then
3684             Rewrite (N, Make_Integer_Literal (Loc, Siz));
3685
3686             Analyze_And_Resolve (N, Typ);
3687
3688             --  The result is not a static expression
3689
3690             Set_Is_Static_Expression (N, False);
3691          end if;
3692       end Size;
3693
3694       ------------------
3695       -- Storage_Pool --
3696       ------------------
3697
3698       when Attribute_Storage_Pool =>
3699          Rewrite (N,
3700            Make_Type_Conversion (Loc,
3701              Subtype_Mark => New_Reference_To (Etype (N), Loc),
3702              Expression   => New_Reference_To (Entity (N), Loc)));
3703          Analyze_And_Resolve (N, Typ);
3704
3705       ------------------
3706       -- Storage_Size --
3707       ------------------
3708
3709       when Attribute_Storage_Size => Storage_Size :
3710       declare
3711          Ptyp : constant Entity_Id := Etype (Pref);
3712
3713       begin
3714          --  Access type case, always go to the root type
3715
3716          --  The case of access types results in a value of zero for the case
3717          --  where no storage size attribute clause has been given. If a
3718          --  storage size has been given, then the attribute is converted
3719          --  to a reference to the variable used to hold this value.
3720
3721          if Is_Access_Type (Ptyp) then
3722             if Present (Storage_Size_Variable (Root_Type (Ptyp))) then
3723                Rewrite (N,
3724                  Make_Attribute_Reference (Loc,
3725                    Prefix => New_Reference_To (Typ, Loc),
3726                    Attribute_Name => Name_Max,
3727                    Expressions => New_List (
3728                      Make_Integer_Literal (Loc, 0),
3729                      Convert_To (Typ,
3730                        New_Reference_To
3731                          (Storage_Size_Variable (Root_Type (Ptyp)), Loc)))));
3732
3733             elsif Present (Associated_Storage_Pool (Root_Type (Ptyp))) then
3734                Rewrite (N,
3735                  OK_Convert_To (Typ,
3736                    Make_Function_Call (Loc,
3737                      Name =>
3738                        New_Reference_To
3739                          (Find_Prim_Op
3740                            (Etype (Associated_Storage_Pool (Root_Type (Ptyp))),
3741                             Attribute_Name (N)),
3742                           Loc),
3743
3744                      Parameter_Associations => New_List (
3745                        New_Reference_To
3746                          (Associated_Storage_Pool (Root_Type (Ptyp)), Loc)))));
3747
3748             else
3749                Rewrite (N, Make_Integer_Literal (Loc, 0));
3750             end if;
3751
3752             Analyze_And_Resolve (N, Typ);
3753
3754          --  For tasks, we retrieve the size directly from the TCB. The
3755          --  size may depend on a discriminant of the type, and therefore
3756          --  can be a per-object expression, so type-level information is
3757          --  not sufficient in general. There are four cases to consider:
3758
3759          --  a) If the attribute appears within a task body, the designated
3760          --    TCB is obtained by a call to Self.
3761
3762          --  b) If the prefix of the attribute is the name of a task object,
3763          --  the designated TCB is the one stored in the corresponding record.
3764
3765          --  c) If the prefix is a task type, the size is obtained from the
3766          --  size variable created for each task type
3767
3768          --  d) If no storage_size was specified for the type , there is no
3769          --  size variable, and the value is a system-specific default.
3770
3771          else
3772             if In_Open_Scopes (Ptyp) then
3773
3774                --  Storage_Size (Self)
3775
3776                Rewrite (N,
3777                  Convert_To (Typ,
3778                    Make_Function_Call (Loc,
3779                      Name =>
3780                        New_Occurrence_Of (RTE (RE_Storage_Size), Loc),
3781                      Parameter_Associations =>
3782                        New_List (
3783                          Make_Function_Call (Loc,
3784                            Name =>
3785                              New_Reference_To (RTE (RE_Self), Loc))))));
3786
3787             elsif not Is_Entity_Name (Pref)
3788               or else not Is_Type (Entity (Pref))
3789             then
3790                --  Storage_Size (Rec (Obj).Size)
3791
3792                Rewrite (N,
3793                  Convert_To (Typ,
3794                    Make_Function_Call (Loc,
3795                      Name =>
3796                        New_Occurrence_Of (RTE (RE_Storage_Size), Loc),
3797                        Parameter_Associations =>
3798                           New_List (
3799                             Make_Selected_Component (Loc,
3800                               Prefix =>
3801                                 Unchecked_Convert_To (
3802                                   Corresponding_Record_Type (Ptyp),
3803                                     New_Copy_Tree (Pref)),
3804                               Selector_Name =>
3805                                  Make_Identifier (Loc, Name_uTask_Id))))));
3806
3807             elsif Present (Storage_Size_Variable (Ptyp)) then
3808
3809                --  Static storage size pragma given for type: retrieve value
3810                --  from its allocated storage variable.
3811
3812                Rewrite (N,
3813                  Convert_To (Typ,
3814                    Make_Function_Call (Loc,
3815                      Name => New_Occurrence_Of (
3816                        RTE (RE_Adjust_Storage_Size), Loc),
3817                      Parameter_Associations =>
3818                        New_List (
3819                          New_Reference_To (
3820                            Storage_Size_Variable (Ptyp), Loc)))));
3821             else
3822                --  Get system default
3823
3824                Rewrite (N,
3825                  Convert_To (Typ,
3826                    Make_Function_Call (Loc,
3827                      Name =>
3828                        New_Occurrence_Of (
3829                         RTE (RE_Default_Stack_Size), Loc))));
3830             end if;
3831
3832             Analyze_And_Resolve (N, Typ);
3833          end if;
3834       end Storage_Size;
3835
3836       -----------------
3837       -- Stream_Size --
3838       -----------------
3839
3840       when Attribute_Stream_Size => Stream_Size : declare
3841          Ptyp : constant Entity_Id := Etype (Pref);
3842          Size : Int;
3843
3844       begin
3845          --  If we have a Stream_Size clause for this type use it, otherwise
3846          --  the Stream_Size if the size of the type.
3847
3848          if Has_Stream_Size_Clause (Ptyp) then
3849             Size :=
3850               UI_To_Int
3851                 (Static_Integer (Expression (Stream_Size_Clause (Ptyp))));
3852          else
3853             Size := UI_To_Int (Esize (Ptyp));
3854          end if;
3855
3856          Rewrite (N, Make_Integer_Literal (Loc, Intval => Size));
3857          Analyze_And_Resolve (N, Typ);
3858       end Stream_Size;
3859
3860       ----------
3861       -- Succ --
3862       ----------
3863
3864       --  1. Deal with enumeration types with holes
3865       --  2. For floating-point, generate call to attribute function
3866       --  3. For other cases, deal with constraint checking
3867
3868       when Attribute_Succ => Succ :
3869       declare
3870          Ptyp : constant Entity_Id := Base_Type (Etype (Pref));
3871
3872       begin
3873          --  For enumeration types with non-standard representations, we
3874          --  expand typ'Succ (x) into
3875
3876          --    Pos_To_Rep (Rep_To_Pos (x) + 1)
3877
3878          --    If the representation is contiguous, we compute instead
3879          --    Lit1 + Rep_to_Pos (x+1), to catch invalid representations.
3880
3881          if Is_Enumeration_Type (Ptyp)
3882            and then Present (Enum_Pos_To_Rep (Ptyp))
3883          then
3884             if Has_Contiguous_Rep (Ptyp) then
3885                Rewrite (N,
3886                   Unchecked_Convert_To (Ptyp,
3887                      Make_Op_Add (Loc,
3888                         Left_Opnd  =>
3889                          Make_Integer_Literal (Loc,
3890                            Enumeration_Rep (First_Literal (Ptyp))),
3891                         Right_Opnd =>
3892                           Make_Function_Call (Loc,
3893                             Name =>
3894                               New_Reference_To
3895                                (TSS (Ptyp, TSS_Rep_To_Pos), Loc),
3896
3897                             Parameter_Associations =>
3898                               New_List (
3899                                 Unchecked_Convert_To (Ptyp,
3900                                   Make_Op_Add (Loc,
3901                                   Left_Opnd =>
3902                                     Unchecked_Convert_To (Standard_Integer,
3903                                       Relocate_Node (First (Exprs))),
3904                                   Right_Opnd =>
3905                                     Make_Integer_Literal (Loc, 1))),
3906                                 Rep_To_Pos_Flag (Ptyp, Loc))))));
3907             else
3908                --  Add Boolean parameter True, to request program errror if
3909                --  we have a bad representation on our hands. Add False if
3910                --  checks are suppressed.
3911
3912                Append_To (Exprs, Rep_To_Pos_Flag (Ptyp, Loc));
3913                Rewrite (N,
3914                  Make_Indexed_Component (Loc,
3915                    Prefix => New_Reference_To (Enum_Pos_To_Rep (Ptyp), Loc),
3916                    Expressions => New_List (
3917                      Make_Op_Add (Loc,
3918                        Left_Opnd =>
3919                          Make_Function_Call (Loc,
3920                            Name =>
3921                              New_Reference_To
3922                                (TSS (Ptyp, TSS_Rep_To_Pos), Loc),
3923                            Parameter_Associations => Exprs),
3924                        Right_Opnd => Make_Integer_Literal (Loc, 1)))));
3925             end if;
3926
3927             Analyze_And_Resolve (N, Typ);
3928
3929          --  For floating-point, we transform 'Succ into a call to the Succ
3930          --  floating-point attribute function in Fat_xxx (xxx is root type)
3931
3932          elsif Is_Floating_Point_Type (Ptyp) then
3933             Expand_Fpt_Attribute_R (N);
3934             Analyze_And_Resolve (N, Typ);
3935
3936          --  For modular types, nothing to do (no overflow, since wraps)
3937
3938          elsif Is_Modular_Integer_Type (Ptyp) then
3939             null;
3940
3941          --  For other types, if range checking is enabled, we must generate
3942          --  a check if overflow checking is enabled.
3943
3944          elsif not Overflow_Checks_Suppressed (Ptyp) then
3945             Expand_Pred_Succ (N);
3946          end if;
3947       end Succ;
3948
3949       ---------
3950       -- Tag --
3951       ---------
3952
3953       --  Transforms X'Tag into a direct reference to the tag of X
3954
3955       when Attribute_Tag => Tag :
3956       declare
3957          Ttyp           : Entity_Id;
3958          Prefix_Is_Type : Boolean;
3959
3960       begin
3961          if Is_Entity_Name (Pref) and then Is_Type (Entity (Pref)) then
3962             Ttyp := Entity (Pref);
3963             Prefix_Is_Type := True;
3964          else
3965             Ttyp := Etype (Pref);
3966             Prefix_Is_Type := False;
3967          end if;
3968
3969          if Is_Class_Wide_Type (Ttyp) then
3970             Ttyp := Root_Type (Ttyp);
3971          end if;
3972
3973          Ttyp := Underlying_Type (Ttyp);
3974
3975          if Prefix_Is_Type then
3976
3977             --  For VMs we leave the type attribute unexpanded because
3978             --  there's not a dispatching table to reference.
3979
3980             if VM_Target = No_VM then
3981                Rewrite (N,
3982                  Unchecked_Convert_To (RTE (RE_Tag),
3983                    New_Reference_To
3984                      (Node (First_Elmt (Access_Disp_Table (Ttyp))), Loc)));
3985                Analyze_And_Resolve (N, RTE (RE_Tag));
3986             end if;
3987
3988          --  (Ada 2005 (AI-251): The use of 'Tag in the sources always
3989          --  references the primary tag of the actual object. If 'Tag is
3990          --  applied to class-wide interface objects we generate code that
3991          --  displaces "this" to reference the base of the object.
3992
3993          elsif Comes_From_Source (N)
3994             and then Is_Class_Wide_Type (Etype (Prefix (N)))
3995             and then Is_Interface (Etype (Prefix (N)))
3996          then
3997             --  Generate:
3998             --    (To_Tag_Ptr (Prefix'Address)).all
3999
4000             --  Note that Prefix'Address is recursively expanded into a call
4001             --  to Base_Address (Obj.Tag)
4002
4003             Rewrite (N,
4004               Make_Explicit_Dereference (Loc,
4005                 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
4006                   Make_Attribute_Reference (Loc,
4007                     Prefix => Relocate_Node (Pref),
4008                     Attribute_Name => Name_Address))));
4009             Analyze_And_Resolve (N, RTE (RE_Tag));
4010
4011          else
4012             Rewrite (N,
4013               Make_Selected_Component (Loc,
4014                 Prefix => Relocate_Node (Pref),
4015                 Selector_Name =>
4016                   New_Reference_To (First_Tag_Component (Ttyp), Loc)));
4017             Analyze_And_Resolve (N, RTE (RE_Tag));
4018          end if;
4019       end Tag;
4020
4021       ----------------
4022       -- Terminated --
4023       ----------------
4024
4025       --  Transforms 'Terminated attribute into a call to Terminated function
4026
4027       when Attribute_Terminated => Terminated :
4028       begin
4029          --  The prefix of Terminated is of a task interface class-wide type.
4030          --  Generate:
4031
4032          --    terminated (Task_Id (Pref._disp_get_task_id));
4033
4034          if Ada_Version >= Ada_05
4035            and then Ekind (Etype (Pref)) = E_Class_Wide_Type
4036            and then Is_Interface (Etype (Pref))
4037            and then Is_Task_Interface (Etype (Pref))
4038          then
4039             Rewrite (N,
4040               Make_Function_Call (Loc,
4041                 Name =>
4042                   New_Reference_To (RTE (RE_Terminated), Loc),
4043                 Parameter_Associations => New_List (
4044                   Make_Unchecked_Type_Conversion (Loc,
4045                     Subtype_Mark =>
4046                       New_Reference_To (RTE (RO_ST_Task_Id), Loc),
4047                     Expression =>
4048                       Make_Selected_Component (Loc,
4049                         Prefix =>
4050                           New_Copy_Tree (Pref),
4051                         Selector_Name =>
4052                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id))))));
4053
4054          elsif Restricted_Profile then
4055             Rewrite (N,
4056               Build_Call_With_Task (Pref, RTE (RE_Restricted_Terminated)));
4057
4058          else
4059             Rewrite (N,
4060               Build_Call_With_Task (Pref, RTE (RE_Terminated)));
4061          end if;
4062
4063          Analyze_And_Resolve (N, Standard_Boolean);
4064       end Terminated;
4065
4066       ----------------
4067       -- To_Address --
4068       ----------------
4069
4070       --  Transforms System'To_Address (X) into unchecked conversion
4071       --  from (integral) type of X to type address.
4072
4073       when Attribute_To_Address =>
4074          Rewrite (N,
4075            Unchecked_Convert_To (RTE (RE_Address),
4076              Relocate_Node (First (Exprs))));
4077          Analyze_And_Resolve (N, RTE (RE_Address));
4078
4079       ----------------
4080       -- Truncation --
4081       ----------------
4082
4083       --  Transforms 'Truncation into a call to the floating-point attribute
4084       --  function Truncation in Fat_xxx (where xxx is the root type).
4085       --  Expansion is avoided for cases the back end can handle directly.
4086
4087       when Attribute_Truncation =>
4088          if not Is_Inline_Floating_Point_Attribute (N) then
4089             Expand_Fpt_Attribute_R (N);
4090          end if;
4091
4092       -----------------------
4093       -- Unbiased_Rounding --
4094       -----------------------
4095
4096       --  Transforms 'Unbiased_Rounding into a call to the floating-point
4097       --  attribute function Unbiased_Rounding in Fat_xxx (where xxx is the
4098       --  root type). Expansion is avoided for cases the back end can handle
4099       --  directly.
4100
4101       when Attribute_Unbiased_Rounding =>
4102          if not Is_Inline_Floating_Point_Attribute (N) then
4103             Expand_Fpt_Attribute_R (N);
4104          end if;
4105
4106       -----------------
4107       -- UET_Address --
4108       -----------------
4109
4110       when Attribute_UET_Address => UET_Address : declare
4111          Ent : constant Entity_Id :=
4112                  Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
4113
4114       begin
4115          Insert_Action (N,
4116            Make_Object_Declaration (Loc,
4117              Defining_Identifier => Ent,
4118              Aliased_Present     => True,
4119              Object_Definition   =>
4120                New_Occurrence_Of (RTE (RE_Address), Loc)));
4121
4122          --  Construct name __gnat_xxx__SDP, where xxx is the unit name
4123          --  in normal external form.
4124
4125          Get_External_Unit_Name_String (Get_Unit_Name (Pref));
4126          Name_Buffer (1 + 7 .. Name_Len + 7) := Name_Buffer (1 .. Name_Len);
4127          Name_Len := Name_Len + 7;
4128          Name_Buffer (1 .. 7) := "__gnat_";
4129          Name_Buffer (Name_Len + 1 .. Name_Len + 5) := "__SDP";
4130          Name_Len := Name_Len + 5;
4131
4132          Set_Is_Imported (Ent);
4133          Set_Interface_Name (Ent,
4134            Make_String_Literal (Loc,
4135              Strval => String_From_Name_Buffer));
4136
4137          --  Set entity as internal to ensure proper Sprint output of its
4138          --  implicit importation.
4139
4140          Set_Is_Internal (Ent);
4141
4142          Rewrite (N,
4143            Make_Attribute_Reference (Loc,
4144              Prefix => New_Occurrence_Of (Ent, Loc),
4145              Attribute_Name => Name_Address));
4146
4147          Analyze_And_Resolve (N, Typ);
4148       end UET_Address;
4149
4150       ---------------
4151       -- VADS_Size --
4152       ---------------
4153
4154       --  The processing for VADS_Size is shared with Size
4155
4156       ---------
4157       -- Val --
4158       ---------
4159
4160       --  For enumeration types with a standard representation, and for all
4161       --  other types, Val is handled by Gigi. For enumeration types with
4162       --  a non-standard representation we use the _Pos_To_Rep array that
4163       --  was created when the type was frozen.
4164
4165       when Attribute_Val => Val :
4166       declare
4167          Etyp : constant Entity_Id := Base_Type (Entity (Pref));
4168
4169       begin
4170          if Is_Enumeration_Type (Etyp)
4171            and then Present (Enum_Pos_To_Rep (Etyp))
4172          then
4173             if Has_Contiguous_Rep (Etyp) then
4174                declare
4175                   Rep_Node : constant Node_Id :=
4176                     Unchecked_Convert_To (Etyp,
4177                        Make_Op_Add (Loc,
4178                          Left_Opnd =>
4179                             Make_Integer_Literal (Loc,
4180                               Enumeration_Rep (First_Literal (Etyp))),
4181                          Right_Opnd =>
4182                           (Convert_To (Standard_Integer,
4183                              Relocate_Node (First (Exprs))))));
4184
4185                begin
4186                   Rewrite (N,
4187                      Unchecked_Convert_To (Etyp,
4188                          Make_Op_Add (Loc,
4189                            Left_Opnd =>
4190                              Make_Integer_Literal (Loc,
4191                                Enumeration_Rep (First_Literal (Etyp))),
4192                            Right_Opnd =>
4193                              Make_Function_Call (Loc,
4194                                Name =>
4195                                  New_Reference_To
4196                                    (TSS (Etyp, TSS_Rep_To_Pos), Loc),
4197                                Parameter_Associations => New_List (
4198                                  Rep_Node,
4199                                  Rep_To_Pos_Flag (Etyp, Loc))))));
4200                end;
4201
4202             else
4203                Rewrite (N,
4204                  Make_Indexed_Component (Loc,
4205                    Prefix => New_Reference_To (Enum_Pos_To_Rep (Etyp), Loc),
4206                    Expressions => New_List (
4207                      Convert_To (Standard_Integer,
4208                        Relocate_Node (First (Exprs))))));
4209             end if;
4210
4211             Analyze_And_Resolve (N, Typ);
4212          end if;
4213       end Val;
4214
4215       -----------
4216       -- Valid --
4217       -----------
4218
4219       --  The code for valid is dependent on the particular types involved.
4220       --  See separate sections below for the generated code in each case.
4221
4222       when Attribute_Valid => Valid :
4223       declare
4224          Ptyp : constant Entity_Id  := Etype (Pref);
4225          Btyp : Entity_Id           := Base_Type (Ptyp);
4226          Tst  : Node_Id;
4227
4228          Save_Validity_Checks_On : constant Boolean := Validity_Checks_On;
4229          --  Save the validity checking mode. We always turn off validity
4230          --  checking during process of 'Valid since this is one place
4231          --  where we do not want the implicit validity checks to intefere
4232          --  with the explicit validity check that the programmer is doing.
4233
4234          function Make_Range_Test return Node_Id;
4235          --  Build the code for a range test of the form
4236          --    Btyp!(Pref) >= Btyp!(Ptyp'First)
4237          --      and then
4238          --    Btyp!(Pref) <= Btyp!(Ptyp'Last)
4239
4240          ---------------------
4241          -- Make_Range_Test --
4242          ---------------------
4243
4244          function Make_Range_Test return Node_Id is
4245          begin
4246             return
4247               Make_And_Then (Loc,
4248                 Left_Opnd =>
4249                   Make_Op_Ge (Loc,
4250                     Left_Opnd =>
4251                       Unchecked_Convert_To (Btyp, Duplicate_Subexpr (Pref)),
4252
4253                     Right_Opnd =>
4254                       Unchecked_Convert_To (Btyp,
4255                         Make_Attribute_Reference (Loc,
4256                           Prefix => New_Occurrence_Of (Ptyp, Loc),
4257                           Attribute_Name => Name_First))),
4258
4259                 Right_Opnd =>
4260                   Make_Op_Le (Loc,
4261                     Left_Opnd =>
4262                       Unchecked_Convert_To (Btyp,
4263                         Duplicate_Subexpr_No_Checks (Pref)),
4264
4265                     Right_Opnd =>
4266                       Unchecked_Convert_To (Btyp,
4267                         Make_Attribute_Reference (Loc,
4268                           Prefix => New_Occurrence_Of (Ptyp, Loc),
4269                           Attribute_Name => Name_Last))));
4270          end Make_Range_Test;
4271
4272       --  Start of processing for Attribute_Valid
4273
4274       begin
4275          --  Turn off validity checks. We do not want any implicit validity
4276          --  checks to intefere with the explicit check from the attribute
4277
4278          Validity_Checks_On := False;
4279
4280          --  Floating-point case. This case is handled by the Valid attribute
4281          --  code in the floating-point attribute run-time library.
4282
4283          if Is_Floating_Point_Type (Ptyp) then
4284             declare
4285                Pkg : RE_Id;
4286                Ftp : Entity_Id;
4287
4288             begin
4289                --  For vax fpt types, call appropriate routine in special vax
4290                --  floating point unit. We do not have to worry about loads in
4291                --  this case, since these types have no signalling NaN's.
4292
4293                if Vax_Float (Btyp) then
4294                   Expand_Vax_Valid (N);
4295
4296                --  The AAMP back end handles Valid for floating-point types
4297
4298                elsif Is_AAMP_Float (Btyp) then
4299                   Analyze_And_Resolve (Pref, Ptyp);
4300                   Set_Etype (N, Standard_Boolean);
4301                   Set_Analyzed (N);
4302
4303                --  Non VAX float case
4304
4305                else
4306                   Find_Fat_Info (Etype (Pref), Ftp, Pkg);
4307
4308                   --  If the floating-point object might be unaligned, we need
4309                   --  to call the special routine Unaligned_Valid, which makes
4310                   --  the needed copy, being careful not to load the value into
4311                   --  any floating-point register. The argument in this case is
4312                   --  obj'Address (see Unaligned_Valid routine in Fat_Gen).
4313
4314                   if Is_Possibly_Unaligned_Object (Pref) then
4315                      Expand_Fpt_Attribute
4316                        (N, Pkg, Name_Unaligned_Valid,
4317                         New_List (
4318                           Make_Attribute_Reference (Loc,
4319                             Prefix => Relocate_Node (Pref),
4320                             Attribute_Name => Name_Address)));
4321
4322                   --  In the normal case where we are sure the object is
4323                   --  aligned, we generate a call to Valid, and the argument in
4324                   --  this case is obj'Unrestricted_Access (after converting
4325                   --  obj to the right floating-point type).
4326
4327                   else
4328                      Expand_Fpt_Attribute
4329                        (N, Pkg, Name_Valid,
4330                         New_List (
4331                           Make_Attribute_Reference (Loc,
4332                             Prefix => Unchecked_Convert_To (Ftp, Pref),
4333                             Attribute_Name => Name_Unrestricted_Access)));
4334                   end if;
4335                end if;
4336
4337                --  One more task, we still need a range check. Required
4338                --  only if we have a constraint, since the Valid routine
4339                --  catches infinities properly (infinities are never valid).
4340
4341                --  The way we do the range check is simply to create the
4342                --  expression: Valid (N) and then Base_Type(Pref) in Typ.
4343
4344                if not Subtypes_Statically_Match (Ptyp, Btyp) then
4345                   Rewrite (N,
4346                     Make_And_Then (Loc,
4347                       Left_Opnd  => Relocate_Node (N),
4348                       Right_Opnd =>
4349                         Make_In (Loc,
4350                           Left_Opnd => Convert_To (Btyp, Pref),
4351                           Right_Opnd => New_Occurrence_Of (Ptyp, Loc))));
4352                end if;
4353             end;
4354
4355          --  Enumeration type with holes
4356
4357          --  For enumeration types with holes, the Pos value constructed by
4358          --  the Enum_Rep_To_Pos function built in Exp_Ch3 called with a
4359          --  second argument of False returns minus one for an invalid value,
4360          --  and the non-negative pos value for a valid value, so the
4361          --  expansion of X'Valid is simply:
4362
4363          --     type(X)'Pos (X) >= 0
4364
4365          --  We can't quite generate it that way because of the requirement
4366          --  for the non-standard second argument of False in the resulting
4367          --  rep_to_pos call, so we have to explicitly create:
4368
4369          --     _rep_to_pos (X, False) >= 0
4370
4371          --  If we have an enumeration subtype, we also check that the
4372          --  value is in range:
4373
4374          --    _rep_to_pos (X, False) >= 0
4375          --      and then
4376          --       (X >= type(X)'First and then type(X)'Last <= X)
4377
4378          elsif Is_Enumeration_Type (Ptyp)
4379            and then Present (Enum_Pos_To_Rep (Base_Type (Ptyp)))
4380          then
4381             Tst :=
4382               Make_Op_Ge (Loc,
4383                 Left_Opnd =>
4384                   Make_Function_Call (Loc,
4385                     Name =>
4386                       New_Reference_To
4387                         (TSS (Base_Type (Ptyp), TSS_Rep_To_Pos), Loc),
4388                     Parameter_Associations => New_List (
4389                       Pref,
4390                       New_Occurrence_Of (Standard_False, Loc))),
4391                 Right_Opnd => Make_Integer_Literal (Loc, 0));
4392
4393             if Ptyp /= Btyp
4394               and then
4395                 (Type_Low_Bound (Ptyp) /= Type_Low_Bound (Btyp)
4396                   or else
4397                  Type_High_Bound (Ptyp) /= Type_High_Bound (Btyp))
4398             then
4399                --  The call to Make_Range_Test will create declarations
4400                --  that need a proper insertion point, but Pref is now
4401                --  attached to a node with no ancestor. Attach to tree
4402                --  even if it is to be rewritten below.
4403
4404                Set_Parent (Tst, Parent (N));
4405
4406                Tst :=
4407                  Make_And_Then (Loc,
4408                    Left_Opnd  => Make_Range_Test,
4409                    Right_Opnd => Tst);
4410             end if;
4411
4412             Rewrite (N, Tst);
4413
4414          --  Fortran convention booleans
4415
4416          --  For the very special case of Fortran convention booleans, the
4417          --  value is always valid, since it is an integer with the semantics
4418          --  that non-zero is true, and any value is permissible.
4419
4420          elsif Is_Boolean_Type (Ptyp)
4421            and then Convention (Ptyp) = Convention_Fortran
4422          then
4423             Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
4424
4425          --  For biased representations, we will be doing an unchecked
4426          --  conversion without unbiasing the result. That means that the range
4427          --  test has to take this into account, and the proper form of the
4428          --  test is:
4429
4430          --    Btyp!(Pref) < Btyp!(Ptyp'Range_Length)
4431
4432          elsif Has_Biased_Representation (Ptyp) then
4433             Btyp := RTE (RE_Unsigned_32);
4434             Rewrite (N,
4435               Make_Op_Lt (Loc,
4436                 Left_Opnd =>
4437                   Unchecked_Convert_To (Btyp, Duplicate_Subexpr (Pref)),
4438                 Right_Opnd =>
4439                   Unchecked_Convert_To (Btyp,
4440                     Make_Attribute_Reference (Loc,
4441                       Prefix => New_Occurrence_Of (Ptyp, Loc),
4442                       Attribute_Name => Name_Range_Length))));
4443
4444          --  For all other scalar types, what we want logically is a
4445          --  range test:
4446
4447          --     X in type(X)'First .. type(X)'Last
4448
4449          --  But that's precisely what won't work because of possible
4450          --  unwanted optimization (and indeed the basic motivation for
4451          --  the Valid attribute is exactly that this test does not work!)
4452          --  What will work is:
4453
4454          --     Btyp!(X) >= Btyp!(type(X)'First)
4455          --       and then
4456          --     Btyp!(X) <= Btyp!(type(X)'Last)
4457
4458          --  where Btyp is an integer type large enough to cover the full
4459          --  range of possible stored values (i.e. it is chosen on the basis
4460          --  of the size of the type, not the range of the values). We write
4461          --  this as two tests, rather than a range check, so that static
4462          --  evaluation will easily remove either or both of the checks if
4463          --  they can be -statically determined to be true (this happens
4464          --  when the type of X is static and the range extends to the full
4465          --  range of stored values).
4466
4467          --  Unsigned types. Note: it is safe to consider only whether the
4468          --  subtype is unsigned, since we will in that case be doing all
4469          --  unsigned comparisons based on the subtype range. Since we use the
4470          --  actual subtype object size, this is appropriate.
4471
4472          --  For example, if we have
4473
4474          --    subtype x is integer range 1 .. 200;
4475          --    for x'Object_Size use 8;
4476
4477          --  Now the base type is signed, but objects of this type are bits
4478          --  unsigned, and doing an unsigned test of the range 1 to 200 is
4479          --  correct, even though a value greater than 127 looks signed to a
4480          --  signed comparison.
4481
4482          elsif Is_Unsigned_Type (Ptyp) then
4483             if Esize (Ptyp) <= 32 then
4484                Btyp := RTE (RE_Unsigned_32);
4485             else
4486                Btyp := RTE (RE_Unsigned_64);
4487             end if;
4488
4489             Rewrite (N, Make_Range_Test);
4490
4491          --  Signed types
4492
4493          else
4494             if Esize (Ptyp) <= Esize (Standard_Integer) then
4495                Btyp := Standard_Integer;
4496             else
4497                Btyp := Universal_Integer;
4498             end if;
4499
4500             Rewrite (N, Make_Range_Test);
4501          end if;
4502
4503          Analyze_And_Resolve (N, Standard_Boolean);
4504          Validity_Checks_On := Save_Validity_Checks_On;
4505       end Valid;
4506
4507       -----------
4508       -- Value --
4509       -----------
4510
4511       --  Value attribute is handled in separate unti Exp_Imgv
4512
4513       when Attribute_Value =>
4514          Exp_Imgv.Expand_Value_Attribute (N);
4515
4516       -----------------
4517       -- Value_Size --
4518       -----------------
4519
4520       --  The processing for Value_Size shares the processing for Size
4521
4522       -------------
4523       -- Version --
4524       -------------
4525
4526       --  The processing for Version shares the processing for Body_Version
4527
4528       ----------------
4529       -- Wide_Image --
4530       ----------------
4531
4532       --  We expand typ'Wide_Image (X) into
4533
4534       --    String_To_Wide_String
4535       --      (typ'Image (X), Wide_Character_Encoding_Method)
4536
4537       --  This works in all cases because String_To_Wide_String converts any
4538       --  wide character escape sequences resulting from the Image call to the
4539       --  proper Wide_Character equivalent
4540
4541       --  not quite right for typ = Wide_Character ???
4542
4543       when Attribute_Wide_Image => Wide_Image :
4544       begin
4545          Rewrite (N,
4546            Make_Function_Call (Loc,
4547              Name => New_Reference_To (RTE (RE_String_To_Wide_String), Loc),
4548              Parameter_Associations => New_List (
4549                Make_Attribute_Reference (Loc,
4550                  Prefix         => Pref,
4551                  Attribute_Name => Name_Image,
4552                  Expressions    => Exprs),
4553
4554                Make_Integer_Literal (Loc,
4555                  Intval => Int (Wide_Character_Encoding_Method)))));
4556
4557          Analyze_And_Resolve (N, Standard_Wide_String);
4558       end Wide_Image;
4559
4560       ---------------------
4561       -- Wide_Wide_Image --
4562       ---------------------
4563
4564       --  We expand typ'Wide_Wide_Image (X) into
4565
4566       --    String_To_Wide_Wide_String
4567       --      (typ'Image (X), Wide_Character_Encoding_Method)
4568
4569       --  This works in all cases because String_To_Wide_Wide_String converts
4570       --  any wide character escape sequences resulting from the Image call to
4571       --  the proper Wide_Character equivalent
4572
4573       --  not quite right for typ = Wide_Wide_Character ???
4574
4575       when Attribute_Wide_Wide_Image => Wide_Wide_Image :
4576       begin
4577          Rewrite (N,
4578            Make_Function_Call (Loc,
4579              Name => New_Reference_To
4580                (RTE (RE_String_To_Wide_Wide_String), Loc),
4581              Parameter_Associations => New_List (
4582                Make_Attribute_Reference (Loc,
4583                  Prefix         => Pref,
4584                  Attribute_Name => Name_Image,
4585                  Expressions    => Exprs),
4586
4587                Make_Integer_Literal (Loc,
4588                  Intval => Int (Wide_Character_Encoding_Method)))));
4589
4590          Analyze_And_Resolve (N, Standard_Wide_Wide_String);
4591       end Wide_Wide_Image;
4592
4593       ----------------
4594       -- Wide_Value --
4595       ----------------
4596
4597       --  We expand typ'Wide_Value (X) into
4598
4599       --    typ'Value
4600       --      (Wide_String_To_String (X, Wide_Character_Encoding_Method))
4601
4602       --  Wide_String_To_String is a runtime function that converts its wide
4603       --  string argument to String, converting any non-translatable characters
4604       --  into appropriate escape sequences. This preserves the required
4605       --  semantics of Wide_Value in all cases, and results in a very simple
4606       --  implementation approach.
4607
4608       --  Note: for this approach to be fully standard compliant for the cases
4609       --  where typ is Wide_Character and Wide_Wide_Character, the encoding
4610       --  method must cover the entire character range (e.g. UTF-8). But that
4611       --  is a reasonable requirement when dealing with encoded character
4612       --  sequences. Presumably if one of the restrictive encoding mechanisms
4613       --  is in use such as Shift-JIS, then characters that cannot be
4614       --  represented using this encoding will not appear in any case.
4615
4616       when Attribute_Wide_Value => Wide_Value :
4617       begin
4618          Rewrite (N,
4619            Make_Attribute_Reference (Loc,
4620              Prefix         => Pref,
4621              Attribute_Name => Name_Value,
4622
4623              Expressions    => New_List (
4624                Make_Function_Call (Loc,
4625                  Name =>
4626                    New_Reference_To (RTE (RE_Wide_String_To_String), Loc),
4627
4628                  Parameter_Associations => New_List (
4629                    Relocate_Node (First (Exprs)),
4630                    Make_Integer_Literal (Loc,
4631                      Intval => Int (Wide_Character_Encoding_Method)))))));
4632
4633          Analyze_And_Resolve (N, Typ);
4634       end Wide_Value;
4635
4636       ---------------------
4637       -- Wide_Wide_Value --
4638       ---------------------
4639
4640       --  We expand typ'Wide_Value_Value (X) into
4641
4642       --    typ'Value
4643       --      (Wide_Wide_String_To_String (X, Wide_Character_Encoding_Method))
4644
4645       --  Wide_Wide_String_To_String is a runtime function that converts its
4646       --  wide string argument to String, converting any non-translatable
4647       --  characters into appropriate escape sequences. This preserves the
4648       --  required semantics of Wide_Wide_Value in all cases, and results in a
4649       --  very simple implementation approach.
4650
4651       --  It's not quite right where typ = Wide_Wide_Character, because the
4652       --  encoding method may not cover the whole character type ???
4653
4654       when Attribute_Wide_Wide_Value => Wide_Wide_Value :
4655       begin
4656          Rewrite (N,
4657            Make_Attribute_Reference (Loc,
4658              Prefix         => Pref,
4659              Attribute_Name => Name_Value,
4660
4661              Expressions    => New_List (
4662                Make_Function_Call (Loc,
4663                  Name =>
4664                    New_Reference_To (RTE (RE_Wide_Wide_String_To_String), Loc),
4665
4666                  Parameter_Associations => New_List (
4667                    Relocate_Node (First (Exprs)),
4668                    Make_Integer_Literal (Loc,
4669                      Intval => Int (Wide_Character_Encoding_Method)))))));
4670
4671          Analyze_And_Resolve (N, Typ);
4672       end Wide_Wide_Value;
4673
4674       ---------------------
4675       -- Wide_Wide_Width --
4676       ---------------------
4677
4678       --  Wide_Wide_Width attribute is handled in separate unit Exp_Imgv
4679
4680       when Attribute_Wide_Wide_Width =>
4681          Exp_Imgv.Expand_Width_Attribute (N, Wide_Wide);
4682
4683       ----------------
4684       -- Wide_Width --
4685       ----------------
4686
4687       --  Wide_Width attribute is handled in separate unit Exp_Imgv
4688
4689       when Attribute_Wide_Width =>
4690          Exp_Imgv.Expand_Width_Attribute (N, Wide);
4691
4692       -----------
4693       -- Width --
4694       -----------
4695
4696       --  Width attribute is handled in separate unit Exp_Imgv
4697
4698       when Attribute_Width =>
4699          Exp_Imgv.Expand_Width_Attribute (N, Normal);
4700
4701       -----------
4702       -- Write --
4703       -----------
4704
4705       when Attribute_Write => Write : declare
4706          P_Type : constant Entity_Id := Entity (Pref);
4707          U_Type : constant Entity_Id := Underlying_Type (P_Type);
4708          Pname  : Entity_Id;
4709          Decl   : Node_Id;
4710          Prag   : Node_Id;
4711          Arg3   : Node_Id;
4712          Wfunc  : Node_Id;
4713
4714       begin
4715          --  If no underlying type, we have an error that will be diagnosed
4716          --  elsewhere, so here we just completely ignore the expansion.
4717
4718          if No (U_Type) then
4719             return;
4720          end if;
4721
4722          --  The simple case, if there is a TSS for Write, just call it
4723
4724          Pname := Find_Stream_Subprogram (P_Type, TSS_Stream_Write);
4725
4726          if Present (Pname) then
4727             null;
4728
4729          else
4730             --  If there is a Stream_Convert pragma, use it, we rewrite
4731
4732             --     sourcetyp'Output (stream, Item)
4733
4734             --  as
4735
4736             --     strmtyp'Output (Stream, strmwrite (acttyp (Item)));
4737
4738             --  where strmwrite is the given Write function that converts an
4739             --  argument of type sourcetyp or a type acctyp, from which it is
4740             --  derived to type strmtyp. The conversion to acttyp is required
4741             --  for the derived case.
4742
4743             Prag := Get_Stream_Convert_Pragma (P_Type);
4744
4745             if Present (Prag) then
4746                Arg3 :=
4747                  Next (Next (First (Pragma_Argument_Associations (Prag))));
4748                Wfunc := Entity (Expression (Arg3));
4749
4750                Rewrite (N,
4751                  Make_Attribute_Reference (Loc,
4752                    Prefix => New_Occurrence_Of (Etype (Wfunc), Loc),
4753                    Attribute_Name => Name_Output,
4754                    Expressions => New_List (
4755                      Relocate_Node (First (Exprs)),
4756                      Make_Function_Call (Loc,
4757                        Name => New_Occurrence_Of (Wfunc, Loc),
4758                        Parameter_Associations => New_List (
4759                          OK_Convert_To (Etype (First_Formal (Wfunc)),
4760                            Relocate_Node (Next (First (Exprs)))))))));
4761
4762                Analyze (N);
4763                return;
4764
4765             --  For elementary types, we call the W_xxx routine directly
4766
4767             elsif Is_Elementary_Type (U_Type) then
4768                Rewrite (N, Build_Elementary_Write_Call (N));
4769                Analyze (N);
4770                return;
4771
4772             --  Array type case
4773
4774             elsif Is_Array_Type (U_Type) then
4775                Build_Array_Write_Procedure (N, U_Type, Decl, Pname);
4776                Compile_Stream_Body_In_Scope (N, Decl, U_Type, Check => False);
4777
4778             --  Tagged type case, use the primitive Write function. Note that
4779             --  this will dispatch in the class-wide case which is what we want
4780
4781             elsif Is_Tagged_Type (U_Type) then
4782                Pname := Find_Prim_Op (U_Type, TSS_Stream_Write);
4783
4784             --  All other record type cases, including protected records.
4785             --  The latter only arise for expander generated code for
4786             --  handling shared passive partition access.
4787
4788             else
4789                pragma Assert
4790                  (Is_Record_Type (U_Type) or else Is_Protected_Type (U_Type));
4791
4792                --  Ada 2005 (AI-216): Program_Error is raised when executing
4793                --  the default implementation of the Write attribute of an
4794                --  Unchecked_Union type. However, if the 'Write reference is
4795                --  within the generated Output stream procedure, Write outputs
4796                --  the components, and the default values of the discriminant
4797                --  are streamed by the Output procedure itself.
4798
4799                if Is_Unchecked_Union (Base_Type (U_Type))
4800                  and not Is_TSS (Current_Scope, TSS_Stream_Output)
4801                then
4802                   Insert_Action (N,
4803                     Make_Raise_Program_Error (Loc,
4804                       Reason => PE_Unchecked_Union_Restriction));
4805                end if;
4806
4807                if Has_Discriminants (U_Type)
4808                  and then Present
4809                    (Discriminant_Default_Value (First_Discriminant (U_Type)))
4810                then
4811                   Build_Mutable_Record_Write_Procedure
4812                     (Loc, Base_Type (U_Type), Decl, Pname);
4813                else
4814                   Build_Record_Write_Procedure
4815                     (Loc, Base_Type (U_Type), Decl, Pname);
4816                end if;
4817
4818                Insert_Action (N, Decl);
4819             end if;
4820          end if;
4821
4822          --  If we fall through, Pname is the procedure to be called
4823
4824          Rewrite_Stream_Proc_Call (Pname);
4825       end Write;
4826
4827       --  Component_Size is handled by Gigi, unless the component size is known
4828       --  at compile time, which is always true in the packed array case. It is
4829       --  important that the packed array case is handled in the front end (see
4830       --  Eval_Attribute) since Gigi would otherwise get confused by the
4831       --  equivalent packed array type.
4832
4833       when Attribute_Component_Size =>
4834          null;
4835
4836       --  The following attributes are handled by the back end (except that
4837       --  static cases have already been evaluated during semantic processing,
4838       --  but in any case the back end should not count on this). The one bit
4839       --  of special processing required is that these attributes typically
4840       --  generate conditionals in the code, so we need to check the relevant
4841       --  restriction.
4842
4843       when Attribute_Max                          |
4844            Attribute_Min                          =>
4845          Check_Restriction (No_Implicit_Conditionals, N);
4846
4847       --  The following attributes are handled by the back end (except that
4848       --  static cases have already been evaluated during semantic processing,
4849       --  but in any case the back end should not count on this).
4850
4851       --  Gigi also handles the non-class-wide cases of Size
4852
4853       when Attribute_Bit_Order                    |
4854            Attribute_Code_Address                 |
4855            Attribute_Definite                     |
4856            Attribute_Null_Parameter               |
4857            Attribute_Passed_By_Reference          |
4858            Attribute_Pool_Address                 =>
4859          null;
4860
4861       --  The following attributes are also handled by Gigi, but return a
4862       --  universal integer result, so may need a conversion for checking
4863       --  that the result is in range.
4864
4865       when Attribute_Aft                          |
4866            Attribute_Bit                          |
4867            Attribute_Max_Size_In_Storage_Elements
4868       =>
4869          Apply_Universal_Integer_Attribute_Checks (N);
4870
4871       --  The following attributes should not appear at this stage, since they
4872       --  have already been handled by the analyzer (and properly rewritten
4873       --  with corresponding values or entities to represent the right values)
4874
4875       when Attribute_Abort_Signal                 |
4876            Attribute_Address_Size                 |
4877            Attribute_Base                         |
4878            Attribute_Class                        |
4879            Attribute_Default_Bit_Order            |
4880            Attribute_Delta                        |
4881            Attribute_Denorm                       |
4882            Attribute_Digits                       |
4883            Attribute_Emax                         |
4884            Attribute_Enabled                      |
4885            Attribute_Epsilon                      |
4886            Attribute_Has_Access_Values            |
4887            Attribute_Has_Discriminants            |
4888            Attribute_Large                        |
4889            Attribute_Machine_Emax                 |
4890            Attribute_Machine_Emin                 |
4891            Attribute_Machine_Mantissa             |
4892            Attribute_Machine_Overflows            |
4893            Attribute_Machine_Radix                |
4894            Attribute_Machine_Rounds               |
4895            Attribute_Maximum_Alignment            |
4896            Attribute_Model_Emin                   |
4897            Attribute_Model_Epsilon                |
4898            Attribute_Model_Mantissa               |
4899            Attribute_Model_Small                  |
4900            Attribute_Modulus                      |
4901            Attribute_Partition_ID                 |
4902            Attribute_Range                        |
4903            Attribute_Safe_Emax                    |
4904            Attribute_Safe_First                   |
4905            Attribute_Safe_Large                   |
4906            Attribute_Safe_Last                    |
4907            Attribute_Safe_Small                   |
4908            Attribute_Scale                        |
4909            Attribute_Signed_Zeros                 |
4910            Attribute_Small                        |
4911            Attribute_Storage_Unit                 |
4912            Attribute_Stub_Type                    |
4913            Attribute_Target_Name                  |
4914            Attribute_Type_Class                   |
4915            Attribute_Unconstrained_Array          |
4916            Attribute_Universal_Literal_String     |
4917            Attribute_Wchar_T_Size                 |
4918            Attribute_Word_Size                    =>
4919
4920          raise Program_Error;
4921
4922       --  The Asm_Input and Asm_Output attributes are not expanded at this
4923       --  stage, but will be eliminated in the expansion of the Asm call,
4924       --  see Exp_Intr for details. So Gigi will never see these either.
4925
4926       when Attribute_Asm_Input                    |
4927            Attribute_Asm_Output                   =>
4928
4929          null;
4930
4931       end case;
4932
4933    exception
4934       when RE_Not_Available =>
4935          return;
4936    end Expand_N_Attribute_Reference;
4937
4938    ----------------------
4939    -- Expand_Pred_Succ --
4940    ----------------------
4941
4942    --  For typ'Pred (exp), we generate the check
4943
4944    --    [constraint_error when exp = typ'Base'First]
4945
4946    --  Similarly, for typ'Succ (exp), we generate the check
4947
4948    --    [constraint_error when exp = typ'Base'Last]
4949
4950    --  These checks are not generated for modular types, since the proper
4951    --  semantics for Succ and Pred on modular types is to wrap, not raise CE.
4952
4953    procedure Expand_Pred_Succ (N : Node_Id) is
4954       Loc  : constant Source_Ptr := Sloc (N);
4955       Cnam : Name_Id;
4956
4957    begin
4958       if Attribute_Name (N) = Name_Pred then
4959          Cnam := Name_First;
4960       else
4961          Cnam := Name_Last;
4962       end if;
4963
4964       Insert_Action (N,
4965         Make_Raise_Constraint_Error (Loc,
4966           Condition =>
4967             Make_Op_Eq (Loc,
4968               Left_Opnd =>
4969                 Duplicate_Subexpr_Move_Checks (First (Expressions (N))),
4970               Right_Opnd =>
4971                 Make_Attribute_Reference (Loc,
4972                   Prefix =>
4973                     New_Reference_To (Base_Type (Etype (Prefix (N))), Loc),
4974                   Attribute_Name => Cnam)),
4975           Reason => CE_Overflow_Check_Failed));
4976    end Expand_Pred_Succ;
4977
4978    -------------------
4979    -- Find_Fat_Info --
4980    -------------------
4981
4982    procedure Find_Fat_Info
4983      (T        : Entity_Id;
4984       Fat_Type : out Entity_Id;
4985       Fat_Pkg  : out RE_Id)
4986    is
4987       Btyp : constant Entity_Id := Base_Type (T);
4988       Rtyp : constant Entity_Id := Root_Type (T);
4989       Digs : constant Nat       := UI_To_Int (Digits_Value (Btyp));
4990
4991    begin
4992       --  If the base type is VAX float, then get appropriate VAX float type
4993
4994       if Vax_Float (Btyp) then
4995          case Digs is
4996             when 6 =>
4997                Fat_Type := RTE (RE_Fat_VAX_F);
4998                Fat_Pkg  := RE_Attr_VAX_F_Float;
4999
5000             when 9 =>
5001                Fat_Type := RTE (RE_Fat_VAX_D);
5002                Fat_Pkg  := RE_Attr_VAX_D_Float;
5003
5004             when 15 =>
5005                Fat_Type := RTE (RE_Fat_VAX_G);
5006                Fat_Pkg  := RE_Attr_VAX_G_Float;
5007
5008             when others =>
5009                raise Program_Error;
5010          end case;
5011
5012       --  If root type is VAX float, this is the case where the library has
5013       --  been recompiled in VAX float mode, and we have an IEEE float type.
5014       --  This is when we use the special IEEE Fat packages.
5015
5016       elsif Vax_Float (Rtyp) then
5017          case Digs is
5018             when 6 =>
5019                Fat_Type := RTE (RE_Fat_IEEE_Short);
5020                Fat_Pkg  := RE_Attr_IEEE_Short;
5021
5022             when 15 =>
5023                Fat_Type := RTE (RE_Fat_IEEE_Long);
5024                Fat_Pkg  := RE_Attr_IEEE_Long;
5025
5026             when others =>
5027                raise Program_Error;
5028          end case;
5029
5030       --  If neither the base type nor the root type is VAX_Float then VAX
5031       --  float is out of the picture, and we can just use the root type.
5032
5033       else
5034          Fat_Type := Rtyp;
5035
5036          if Fat_Type = Standard_Short_Float then
5037             Fat_Pkg := RE_Attr_Short_Float;
5038
5039          elsif Fat_Type = Standard_Float then
5040             Fat_Pkg := RE_Attr_Float;
5041
5042          elsif Fat_Type = Standard_Long_Float then
5043             Fat_Pkg := RE_Attr_Long_Float;
5044
5045          elsif Fat_Type = Standard_Long_Long_Float then
5046             Fat_Pkg := RE_Attr_Long_Long_Float;
5047
5048          --  Universal real (which is its own root type) is treated as being
5049          --  equivalent to Standard.Long_Long_Float, since it is defined to
5050          --  have the same precision as the longest Float type.
5051
5052          elsif Fat_Type = Universal_Real then
5053             Fat_Type := Standard_Long_Long_Float;
5054             Fat_Pkg := RE_Attr_Long_Long_Float;
5055
5056          else
5057             raise Program_Error;
5058          end if;
5059       end if;
5060    end Find_Fat_Info;
5061
5062    ----------------------------
5063    -- Find_Stream_Subprogram --
5064    ----------------------------
5065
5066    function Find_Stream_Subprogram
5067      (Typ : Entity_Id;
5068       Nam : TSS_Name_Type) return Entity_Id
5069    is
5070       Ent : constant Entity_Id := TSS (Typ, Nam);
5071    begin
5072       if Present (Ent) then
5073          return Ent;
5074       end if;
5075
5076       if Is_Tagged_Type (Typ)
5077         and then Is_Derived_Type (Typ)
5078       then
5079          return Find_Prim_Op (Typ, Nam);
5080       else
5081          return Find_Inherited_TSS (Typ, Nam);
5082       end if;
5083    end Find_Stream_Subprogram;
5084
5085    -----------------------
5086    -- Get_Index_Subtype --
5087    -----------------------
5088
5089    function Get_Index_Subtype (N : Node_Id) return Node_Id is
5090       P_Type : Entity_Id := Etype (Prefix (N));
5091       Indx   : Node_Id;
5092       J      : Int;
5093
5094    begin
5095       if Is_Access_Type (P_Type) then
5096          P_Type := Designated_Type (P_Type);
5097       end if;
5098
5099       if No (Expressions (N)) then
5100          J := 1;
5101       else
5102          J := UI_To_Int (Expr_Value (First (Expressions (N))));
5103       end if;
5104
5105       Indx := First_Index (P_Type);
5106       while J > 1 loop
5107          Next_Index (Indx);
5108          J := J - 1;
5109       end loop;
5110
5111       return Etype (Indx);
5112    end Get_Index_Subtype;
5113
5114    -------------------------------
5115    -- Get_Stream_Convert_Pragma --
5116    -------------------------------
5117
5118    function Get_Stream_Convert_Pragma (T : Entity_Id) return Node_Id is
5119       Typ : Entity_Id;
5120       N   : Node_Id;
5121
5122    begin
5123       --  Note: we cannot use Get_Rep_Pragma here because of the peculiarity
5124       --  that a stream convert pragma for a tagged type is not inherited from
5125       --  its parent. Probably what is wrong here is that it is basically
5126       --  incorrect to consider a stream convert pragma to be a representation
5127       --  pragma at all ???
5128
5129       N := First_Rep_Item (Implementation_Base_Type (T));
5130       while Present (N) loop
5131          if Nkind (N) = N_Pragma and then Chars (N) = Name_Stream_Convert then
5132
5133             --  For tagged types this pragma is not inherited, so we
5134             --  must verify that it is defined for the given type and
5135             --  not an ancestor.
5136
5137             Typ :=
5138               Entity (Expression (First (Pragma_Argument_Associations (N))));
5139
5140             if not Is_Tagged_Type (T)
5141               or else T = Typ
5142               or else (Is_Private_Type (Typ) and then T = Full_View (Typ))
5143             then
5144                return N;
5145             end if;
5146          end if;
5147
5148          Next_Rep_Item (N);
5149       end loop;
5150
5151       return Empty;
5152    end Get_Stream_Convert_Pragma;
5153
5154    ---------------------------------
5155    -- Is_Constrained_Packed_Array --
5156    ---------------------------------
5157
5158    function Is_Constrained_Packed_Array (Typ : Entity_Id) return Boolean is
5159       Arr : Entity_Id := Typ;
5160
5161    begin
5162       if Is_Access_Type (Arr) then
5163          Arr := Designated_Type (Arr);
5164       end if;
5165
5166       return Is_Array_Type (Arr)
5167         and then Is_Constrained (Arr)
5168         and then Present (Packed_Array_Type (Arr));
5169    end Is_Constrained_Packed_Array;
5170
5171    ----------------------------------------
5172    -- Is_Inline_Floating_Point_Attribute --
5173    ----------------------------------------
5174
5175    function Is_Inline_Floating_Point_Attribute (N : Node_Id) return Boolean is
5176       Id : constant Attribute_Id := Get_Attribute_Id (Attribute_Name (N));
5177
5178    begin
5179       if Nkind (Parent (N)) /= N_Type_Conversion
5180         or else not Is_Integer_Type (Etype (Parent (N)))
5181       then
5182          return False;
5183       end if;
5184
5185       --  Should also support 'Machine_Rounding and 'Unbiased_Rounding, but
5186       --  required back end support has not been implemented yet ???
5187
5188       return Id = Attribute_Truncation;
5189    end Is_Inline_Floating_Point_Attribute;
5190
5191 end Exp_Attr;