OSDN Git Service

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