OSDN Git Service

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