OSDN Git Service

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